Merge "Remove getPrimaryPhysicalDisplayId"
diff --git a/cmds/atrace/atrace.rc b/cmds/atrace/atrace.rc
index 891b1c6..2e0c95a 100644
--- a/cmds/atrace/atrace.rc
+++ b/cmds/atrace/atrace.rc
@@ -300,6 +300,12 @@
chmod 0666 /sys/kernel/debug/tracing/events/kmem/rss_stat/trigger
chmod 0666 /sys/kernel/tracing/events/kmem/rss_stat/trigger
+on late-init && property:ro.boot.fastboot.boottrace=enabled
+ setprop debug.atrace.tags.enableflags 802922
+ setprop persist.traced.enable 0
+ write /sys/kernel/debug/tracing/tracing_on 1
+ write /sys/kernel/tracing/tracing_on 1
+
# Only create the tracing instance if persist.mm_events.enabled
# Attempting to remove the tracing instance after it has been created
# will likely fail with EBUSY as it would be in use by traced_probes.
@@ -395,3 +401,10 @@
service boottrace /system/bin/atrace --async_start -f /data/misc/boottrace/categories
disabled
oneshot
+
+on property:sys.boot_completed=1 && property:ro.boot.fastboot.boottrace=enabled
+ setprop debug.atrace.tags.enableflags 0
+ setprop persist.traced.enable 1
+ write /sys/kernel/debug/tracing/tracing_on 0
+ write /sys/kernel/tracing/tracing_on 0
+
diff --git a/cmds/servicemanager/main.cpp b/cmds/servicemanager/main.cpp
index 1d458b7..a831d1b 100644
--- a/cmds/servicemanager/main.cpp
+++ b/cmds/servicemanager/main.cpp
@@ -15,6 +15,7 @@
*/
#include <android-base/logging.h>
+#include <android-base/properties.h>
#include <binder/IPCThreadState.h>
#include <binder/ProcessState.h>
#include <binder/Status.h>
@@ -26,15 +27,14 @@
#include "ServiceManager.h"
using ::android::Access;
-using ::android::sp;
+using ::android::IPCThreadState;
using ::android::Looper;
using ::android::LooperCallback;
using ::android::ProcessState;
-using ::android::IPCThreadState;
-using ::android::ProcessState;
using ::android::ServiceManager;
-using ::android::os::IServiceManager;
using ::android::sp;
+using ::android::base::SetProperty;
+using ::android::os::IServiceManager;
class BinderCallback : public LooperCallback {
public:
@@ -140,6 +140,12 @@
BinderCallback::setupTo(looper);
ClientCallbackCallback::setupTo(looper, manager);
+#ifndef VENDORSERVICEMANAGER
+ if (!SetProperty("servicemanager.ready", "true")) {
+ LOG(ERROR) << "Failed to set servicemanager ready property";
+ }
+#endif
+
while(true) {
looper->pollAll(-1);
}
diff --git a/cmds/servicemanager/servicemanager.microdroid.rc b/cmds/servicemanager/servicemanager.microdroid.rc
index e01f132..c516043 100644
--- a/cmds/servicemanager/servicemanager.microdroid.rc
+++ b/cmds/servicemanager/servicemanager.microdroid.rc
@@ -3,6 +3,7 @@
user system
group system readproc
critical
+ onrestart setprop servicemanager.ready false
onrestart restart apexd
task_profiles ServiceCapacityLow
shutdown critical
diff --git a/cmds/servicemanager/servicemanager.rc b/cmds/servicemanager/servicemanager.rc
index e5d689f..6b35265 100644
--- a/cmds/servicemanager/servicemanager.rc
+++ b/cmds/servicemanager/servicemanager.rc
@@ -3,6 +3,7 @@
user system
group system readproc
critical
+ onrestart setprop servicemanager.ready false
onrestart restart apexd
onrestart restart audioserver
onrestart restart gatekeeperd
diff --git a/cmds/servicemanager/servicemanager.recovery.rc b/cmds/servicemanager/servicemanager.recovery.rc
index 067faf9..b927c01 100644
--- a/cmds/servicemanager/servicemanager.recovery.rc
+++ b/cmds/servicemanager/servicemanager.recovery.rc
@@ -1,4 +1,5 @@
service servicemanager /system/bin/servicemanager
disabled
group system readproc
+ onrestart setprop servicemanager.ready false
seclabel u:r:servicemanager:s0
diff --git a/headers/media_plugin/media/openmax/OMX_VideoExt.h b/headers/media_plugin/media/openmax/OMX_VideoExt.h
index e65b224..4746bc3 100644
--- a/headers/media_plugin/media/openmax/OMX_VideoExt.h
+++ b/headers/media_plugin/media/openmax/OMX_VideoExt.h
@@ -318,6 +318,9 @@
OMX_VIDEO_DolbyVisionLevelUhd30 = 0x40,
OMX_VIDEO_DolbyVisionLevelUhd48 = 0x80,
OMX_VIDEO_DolbyVisionLevelUhd60 = 0x100,
+ OMX_VIDEO_DolbyVisionLevelUhd120 = 0x200,
+ OMX_VIDEO_DolbyVisionLevel8k30 = 0x400,
+ OMX_VIDEO_DolbyVisionLevel8k60 = 0x800,
OMX_VIDEO_DolbyVisionLevelmax = 0x7FFFFFFF
} OMX_VIDEO_DOLBYVISIONLEVELTYPE;
diff --git a/include/android/input.h b/include/android/input.h
index 38b27bc..8cd9e95 100644
--- a/include/android/input.h
+++ b/include/android/input.h
@@ -54,7 +54,14 @@
#include <stdint.h>
#include <sys/types.h>
#include <android/keycodes.h>
+
+// This file is included by modules that have host support but android/looper.h is not supported
+// on host. __REMOVED_IN needs to be defined in order for android/looper.h to be compiled.
+#ifndef __BIONIC__
+#define __REMOVED_IN(x) __attribute__((deprecated))
+#endif
#include <android/looper.h>
+
#include <jni.h>
#if !defined(__INTRODUCED_IN)
diff --git a/include/android/looper.h b/include/android/looper.h
index 718f703..4fe142a 100644
--- a/include/android/looper.h
+++ b/include/android/looper.h
@@ -201,8 +201,11 @@
* Like ALooper_pollOnce(), but performs all pending callbacks until all
* 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.
*/
-int ALooper_pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData);
+int ALooper_pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData) __REMOVED_IN(1);
/**
* Wakes the poll asynchronously.
diff --git a/include/android/sensor.h b/include/android/sensor.h
index eef69f4..105f952 100644
--- a/include/android/sensor.h
+++ b/include/android/sensor.h
@@ -45,6 +45,11 @@
* - DO NOT CHANGE THE LAYOUT OR SIZE OF STRUCTURES
*/
+// This file is included by modules that have host support but android/looper.h is not supported
+// on host. __REMOVED_IN needs to be defined in order for android/looper.h to be compiled.
+#ifndef __BIONIC__
+#define __REMOVED_IN(x) __attribute__((deprecated))
+#endif
#include <android/looper.h>
#include <stdbool.h>
diff --git a/include/audiomanager/AudioManager.h b/include/audiomanager/AudioManager.h
index caf13a0..6794fbf 100644
--- a/include/audiomanager/AudioManager.h
+++ b/include/audiomanager/AudioManager.h
@@ -39,8 +39,51 @@
PLAYER_STATE_STOPPED = 4,
PLAYER_UPDATE_DEVICE_ID = 5,
PLAYER_UPDATE_PORT_ID = 6,
+ PLAYER_UPDATE_MUTED = 7,
} player_state_t;
+static constexpr char
+ kExtraPlayerEventMuteKey[] = "android.media.extra.PLAYER_EVENT_MUTE";
+enum {
+ PLAYER_MUTE_MASTER = (1 << 0),
+ PLAYER_MUTE_STREAM_VOLUME = (1 << 1),
+ PLAYER_MUTE_STREAM_MUTED = (1 << 2),
+ PLAYER_MUTE_PLAYBACK_RESTRICTED = (1 << 3),
+ PLAYER_MUTE_CLIENT_VOLUME = (1 << 4),
+ PLAYER_MUTE_VOLUME_SHAPER = (1 << 5),
+};
+
+struct mute_state_t {
+ /** Flag used when the master volume is causing the mute state. */
+ bool muteFromMasterMute = false;
+ /** Flag used when the stream volume is causing the mute state. */
+ bool muteFromStreamVolume = false;
+ /** Flag used when the stream muted is causing the mute state. */
+ bool muteFromStreamMuted = false;
+ /** Flag used when playback is restricted by AppOps manager with OP_PLAY_AUDIO. */
+ bool muteFromPlaybackRestricted = false;
+ /** Flag used when audio track was muted by client volume. */
+ bool muteFromClientVolume = false;
+ /** Flag used when volume is muted by volume shaper. */
+ bool muteFromVolumeShaper = false;
+
+ explicit operator int() const
+ {
+ int result = muteFromMasterMute * PLAYER_MUTE_MASTER;
+ result |= muteFromStreamVolume * PLAYER_MUTE_STREAM_VOLUME;
+ result |= muteFromStreamMuted * PLAYER_MUTE_STREAM_MUTED;
+ result |= muteFromPlaybackRestricted * PLAYER_MUTE_PLAYBACK_RESTRICTED;
+ result |= muteFromClientVolume * PLAYER_MUTE_CLIENT_VOLUME;
+ result |= muteFromVolumeShaper * PLAYER_MUTE_VOLUME_SHAPER;
+ return result;
+ }
+
+ bool operator==(const mute_state_t& other) const
+ {
+ return static_cast<int>(*this) == static_cast<int>(other);
+ }
+};
+
// must be kept in sync with definitions in AudioManager.java
#define RECORD_RIID_INVALID -1
diff --git a/include/audiomanager/IAudioManager.h b/include/audiomanager/IAudioManager.h
index 3d531fe..769670e 100644
--- a/include/audiomanager/IAudioManager.h
+++ b/include/audiomanager/IAudioManager.h
@@ -20,6 +20,7 @@
#include <audiomanager/AudioManager.h>
#include <utils/Errors.h>
#include <binder/IInterface.h>
+#include <binder/PersistableBundle.h>
#include <hardware/power.h>
#include <system/audio.h>
@@ -41,6 +42,7 @@
RECORDER_EVENT = IBinder::FIRST_CALL_TRANSACTION + 5,
RELEASE_RECORDER = IBinder::FIRST_CALL_TRANSACTION + 6,
PLAYER_SESSION_ID = IBinder::FIRST_CALL_TRANSACTION + 7,
+ PORT_EVENT = IBinder::FIRST_CALL_TRANSACTION + 8,
};
DECLARE_META_INTERFACE(AudioManager)
@@ -59,6 +61,8 @@
/*oneway*/ virtual status_t recorderEvent(audio_unique_id_t riid, recorder_state_t event) = 0;
/*oneway*/ virtual status_t releaseRecorder(audio_unique_id_t riid) = 0;
/*oneway*/ virtual status_t playerSessionId(audio_unique_id_t piid, audio_session_t sessionId) = 0;
+ /*oneway*/ virtual status_t portEvent(audio_port_handle_t portId, player_state_t event,
+ const std::unique_ptr<os::PersistableBundle>& extras) = 0;
};
// ----------------------------------------------------------------------------
diff --git a/include/input/Input.h b/include/input/Input.h
index e0c9de4..a3c9f33 100644
--- a/include/input/Input.h
+++ b/include/input/Input.h
@@ -297,6 +297,8 @@
*/
const char* motionClassificationToString(MotionClassification classification);
+const char* motionToolTypeToString(int32_t toolType);
+
/**
* Portion of FrameMetrics timeline of interest to input code.
*/
diff --git a/include/input/KeyCharacterMap.h b/include/input/KeyCharacterMap.h
index f6f8939..1c9a5ea 100644
--- a/include/input/KeyCharacterMap.h
+++ b/include/input/KeyCharacterMap.h
@@ -18,6 +18,7 @@
#define _LIBINPUT_KEY_CHARACTER_MAP_H
#include <stdint.h>
+#include <list>
#ifdef __linux__
#include <binder/IBinder.h>
@@ -152,29 +153,22 @@
private:
struct Behavior {
- Behavior();
- Behavior(const Behavior& other);
-
- /* The next behavior in the list, or NULL if none. */
- Behavior* next;
-
/* The meta key modifiers for this behavior. */
- int32_t metaState;
+ int32_t metaState = 0;
/* The character to insert. */
- char16_t character;
+ char16_t character = 0;
/* The fallback keycode if the key is not handled. */
- int32_t fallbackKeyCode;
+ int32_t fallbackKeyCode = 0;
/* The replacement keycode if the key has to be replaced outright. */
- int32_t replacementKeyCode;
+ int32_t replacementKeyCode = 0;
};
struct Key {
Key();
Key(const Key& other);
- ~Key();
/* The single character label printed on the key, or 0 if none. */
char16_t label;
@@ -184,7 +178,7 @@
/* The list of key behaviors sorted from most specific to least specific
* meta key binding. */
- Behavior* firstBehavior;
+ std::list<Behavior> behaviors;
};
class Parser {
@@ -240,8 +234,7 @@
KeyCharacterMap(const std::string& filename);
bool getKey(int32_t keyCode, const Key** outKey) const;
- bool getKeyBehavior(int32_t keyCode, int32_t metaState,
- const Key** outKey, const Behavior** outBehavior) const;
+ const Behavior* getKeyBehavior(int32_t keyCode, int32_t metaState) const;
static bool matchesMetaState(int32_t eventMetaState, int32_t behaviorMetaState);
bool findKey(char16_t ch, int32_t* outKeyCode, int32_t* outMetaState) const;
diff --git a/libs/binder/Binder.cpp b/libs/binder/Binder.cpp
index 532bacb..b5ea60f 100644
--- a/libs/binder/Binder.cpp
+++ b/libs/binder/Binder.cpp
@@ -610,8 +610,24 @@
BBinder::~BBinder()
{
- if (!wasParceled() && getExtension()) {
- ALOGW("Binder %p destroyed with extension attached before being parceled.", this);
+ if (!wasParceled()) {
+ if (getExtension()) {
+ ALOGW("Binder %p destroyed with extension attached before being parceled.", this);
+ }
+ if (isRequestingSid()) {
+ ALOGW("Binder %p destroyed when requesting SID before being parceled.", this);
+ }
+ if (isInheritRt()) {
+ ALOGW("Binder %p destroyed after setInheritRt before being parceled.", this);
+ }
+#ifdef __linux__
+ if (getMinSchedulerPolicy() != SCHED_NORMAL) {
+ ALOGW("Binder %p destroyed after setMinSchedulerPolicy before being parceled.", this);
+ }
+ if (getMinSchedulerPriority() != 0) {
+ ALOGW("Binder %p destroyed after setMinSchedulerPolicy before being parceled.", this);
+ }
+#endif // __linux__
}
Extras* e = mExtras.load(std::memory_order_relaxed);
diff --git a/libs/binder/IServiceManager.cpp b/libs/binder/IServiceManager.cpp
index fd47783..c0a8d74 100644
--- a/libs/binder/IServiceManager.cpp
+++ b/libs/binder/IServiceManager.cpp
@@ -21,6 +21,7 @@
#include <inttypes.h>
#include <unistd.h>
+#include <android-base/properties.h>
#include <android/os/BnServiceCallback.h>
#include <android/os/IServiceManager.h>
#include <binder/IPCThreadState.h>
@@ -140,6 +141,16 @@
sp<IServiceManager> defaultServiceManager()
{
std::call_once(gSmOnce, []() {
+#if defined(__BIONIC__) && !defined(__ANDROID_VNDK__)
+ /* wait for service manager */ {
+ using std::literals::chrono_literals::operator""s;
+ using android::base::WaitForProperty;
+ while (!WaitForProperty("servicemanager.ready", "true", 1s)) {
+ ALOGE("Waited for servicemanager.ready for a second, waiting another...");
+ }
+ }
+#endif
+
sp<AidlServiceManager> sm = nullptr;
while (sm == nullptr) {
sm = interface_cast<AidlServiceManager>(ProcessState::self()->getContextObject(nullptr));
diff --git a/libs/binder/RpcSession.cpp b/libs/binder/RpcSession.cpp
index e6dbd79..d347262 100644
--- a/libs/binder/RpcSession.cpp
+++ b/libs/binder/RpcSession.cpp
@@ -36,6 +36,7 @@
#include <utils/Compat.h>
#include <utils/String8.h>
+#include "BuildFlags.h"
#include "FdTrigger.h"
#include "OS.h"
#include "RpcSocketAddress.h"
@@ -78,10 +79,8 @@
void RpcSession::setMaxIncomingThreads(size_t threads) {
RpcMutexLockGuard _l(mMutex);
- LOG_ALWAYS_FATAL_IF(!mConnections.mOutgoing.empty() || !mConnections.mIncoming.empty(),
- "Must set max incoming threads before setting up connections, but has %zu "
- "client(s) and %zu server(s)",
- mConnections.mOutgoing.size(), mConnections.mIncoming.size());
+ LOG_ALWAYS_FATAL_IF(mStartedSetup,
+ "Must set max incoming threads before setting up connections");
mMaxIncomingThreads = threads;
}
@@ -92,10 +91,8 @@
void RpcSession::setMaxOutgoingThreads(size_t threads) {
RpcMutexLockGuard _l(mMutex);
- LOG_ALWAYS_FATAL_IF(!mConnections.mOutgoing.empty() || !mConnections.mIncoming.empty(),
- "Must set max outgoing threads before setting up connections, but has %zu "
- "client(s) and %zu server(s)",
- mConnections.mOutgoing.size(), mConnections.mIncoming.size());
+ LOG_ALWAYS_FATAL_IF(mStartedSetup,
+ "Must set max outgoing threads before setting up connections");
mMaxOutgoingThreads = threads;
}
@@ -104,7 +101,7 @@
return mMaxOutgoingThreads;
}
-bool RpcSession::setProtocolVersion(uint32_t version) {
+bool RpcSession::setProtocolVersionInternal(uint32_t version, bool checkStarted) {
if (version >= RPC_WIRE_PROTOCOL_VERSION_NEXT &&
version != RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL) {
ALOGE("Cannot start RPC session with version %u which is unknown (current protocol version "
@@ -114,6 +111,8 @@
}
RpcMutexLockGuard _l(mMutex);
+ LOG_ALWAYS_FATAL_IF(checkStarted && mStartedSetup,
+ "Must set protocol version before setting up connections");
if (mProtocolVersion && version > *mProtocolVersion) {
ALOGE("Cannot upgrade explicitly capped protocol version %u to newer version %u",
*mProtocolVersion, version);
@@ -124,12 +123,19 @@
return true;
}
+bool RpcSession::setProtocolVersion(uint32_t version) {
+ return setProtocolVersionInternal(version, true);
+}
+
std::optional<uint32_t> RpcSession::getProtocolVersion() {
RpcMutexLockGuard _l(mMutex);
return mProtocolVersion;
}
void RpcSession::setFileDescriptorTransportMode(FileDescriptorTransportMode mode) {
+ RpcMutexLockGuard _l(mMutex);
+ LOG_ALWAYS_FATAL_IF(mStartedSetup,
+ "Must set file descriptor transport mode before setting up connections");
mFileDescriptorTransportMode = mode;
}
@@ -445,9 +451,16 @@
bool incoming)>& connectAndInit) {
{
RpcMutexLockGuard _l(mMutex);
- LOG_ALWAYS_FATAL_IF(mConnections.mOutgoing.size() != 0,
- "Must only setup session once, but already has %zu clients",
- mConnections.mOutgoing.size());
+ LOG_ALWAYS_FATAL_IF(mStartedSetup, "Must only setup session once");
+ mStartedSetup = true;
+
+ if constexpr (!kEnableRpcThreads) {
+ LOG_ALWAYS_FATAL_IF(mMaxIncomingThreads > 0,
+ "Incoming threads are not supported on single-threaded libbinder");
+ // mMaxIncomingThreads should not change from here to its use below,
+ // since we set mStartedSetup==true and setMaxIncomingThreads checks
+ // for that
+ }
}
if (auto status = initShutdownTrigger(); status != OK) return status;
@@ -488,7 +501,7 @@
sp<RpcSession>::fromExisting(this), &version);
status != OK)
return status;
- if (!setProtocolVersion(version)) return BAD_VALUE;
+ if (!setProtocolVersionInternal(version, false)) return BAD_VALUE;
}
// TODO(b/189955605): we should add additional sessions dynamically
@@ -506,11 +519,7 @@
return status;
}
-#ifdef BINDER_RPC_SINGLE_THREADED
- constexpr size_t outgoingThreads = 1;
-#else // BINDER_RPC_SINGLE_THREADED
size_t outgoingThreads = std::min(numThreadsAvailable, mMaxOutgoingThreads);
-#endif // BINDER_RPC_SINGLE_THREADED
ALOGI_IF(outgoingThreads != numThreadsAvailable,
"Server hints client to start %zu outgoing threads, but client will only start %zu "
"because it is preconfigured to start at most %zu outgoing threads.",
diff --git a/libs/binder/include/binder/RpcSession.h b/libs/binder/include/binder/RpcSession.h
index 9d94e00..428e272 100644
--- a/libs/binder/include/binder/RpcSession.h
+++ b/libs/binder/include/binder/RpcSession.h
@@ -207,6 +207,10 @@
friend RpcState;
explicit RpcSession(std::unique_ptr<RpcTransportCtx> ctx);
+ // internal version of setProtocolVersion that
+ // optionally skips the mStartedSetup check
+ [[nodiscard]] bool setProtocolVersionInternal(uint32_t version, bool checkStarted);
+
// for 'target', see RpcState::sendDecStrongToTarget
[[nodiscard]] status_t sendDecStrongToTarget(uint64_t address, size_t target);
@@ -344,6 +348,7 @@
RpcMutex mMutex; // for all below
+ bool mStartedSetup = false;
size_t mMaxIncomingThreads = 0;
size_t mMaxOutgoingThreads = kDefaultMaxOutgoingThreads;
std::optional<uint32_t> mProtocolVersion;
diff --git a/libs/binder/ndk/ibinder.cpp b/libs/binder/ndk/ibinder.cpp
index b21a7e9..9778ec0 100644
--- a/libs/binder/ndk/ibinder.cpp
+++ b/libs/binder/ndk/ibinder.cpp
@@ -64,6 +64,9 @@
wp<ABpBinder> binder;
};
void clean(const void* id, void* obj, void* cookie) {
+ // be weary of leaks!
+ // LOG(INFO) << "Deleting an ABpBinder";
+
CHECK(id == kId) << id << " " << obj << " " << cookie;
delete static_cast<Value*>(obj);
@@ -239,26 +242,11 @@
}
ABpBinder::ABpBinder(const ::android::sp<::android::IBinder>& binder)
- : AIBinder(nullptr /*clazz*/), BpRefBase(binder) {
+ : AIBinder(nullptr /*clazz*/), mRemote(binder) {
CHECK(binder != nullptr);
}
ABpBinder::~ABpBinder() {}
-void ABpBinder::onLastStrongRef(const void* id) {
- // Since ABpBinder is OBJECT_LIFETIME_WEAK, we must remove this weak reference in order for
- // the ABpBinder to be deleted. Even though we have no more references on the ABpBinder
- // (BpRefBase), the remote object may still exist (for instance, if we
- // receive it from another process, before the ABpBinder is attached).
-
- ABpBinderTag::Value* value =
- static_cast<ABpBinderTag::Value*>(remote()->findObject(ABpBinderTag::kId));
- CHECK_NE(nullptr, value) << "ABpBinder must always be attached";
-
- remote()->withLock([&]() { value->binder = nullptr; });
-
- BpRefBase::onLastStrongRef(id);
-}
-
sp<AIBinder> ABpBinder::lookupOrCreateFromBinder(const ::android::sp<::android::IBinder>& binder) {
if (binder == nullptr) {
return nullptr;
diff --git a/libs/binder/ndk/ibinder_internal.h b/libs/binder/ndk/ibinder_internal.h
index 730e51b..d7098e8 100644
--- a/libs/binder/ndk/ibinder_internal.h
+++ b/libs/binder/ndk/ibinder_internal.h
@@ -91,7 +91,7 @@
// This binder object may be remote or local (even though it is 'Bp'). The implication if it is
// local is that it is an IBinder object created outside of the domain of libbinder_ndk.
-struct ABpBinder : public AIBinder, public ::android::BpRefBase {
+struct ABpBinder : public AIBinder {
// Looks up to see if this object has or is an existing ABBinder or ABpBinder object, otherwise
// it creates an ABpBinder object.
static ::android::sp<AIBinder> lookupOrCreateFromBinder(
@@ -99,14 +99,13 @@
virtual ~ABpBinder();
- void onLastStrongRef(const void* id) override;
-
- ::android::sp<::android::IBinder> getBinder() override { return remote(); }
+ ::android::sp<::android::IBinder> getBinder() override { return mRemote; }
ABpBinder* asABpBinder() override { return this; }
private:
friend android::sp<ABpBinder>;
explicit ABpBinder(const ::android::sp<::android::IBinder>& binder);
+ ::android::sp<::android::IBinder> mRemote;
};
struct AIBinder_Class {
diff --git a/libs/binder/rust/Android.bp b/libs/binder/rust/Android.bp
index 355b3b4..c0d4487 100644
--- a/libs/binder/rust/Android.bp
+++ b/libs/binder/rust/Android.bp
@@ -15,9 +15,10 @@
"libutils",
],
rustlibs: [
- "liblibc",
"libbinder_ndk_sys",
"libdowncast_rs",
+ "liblazy_static",
+ "liblibc",
],
host_supported: true,
vendor_available: true,
@@ -148,6 +149,7 @@
name: "libbinder_rpc_unstable_bindgen",
wrapper_src: ":libbinder_rpc_unstable_header",
crate_name: "binder_rpc_unstable_bindgen",
+ visibility: ["//packages/modules/Virtualization:__subpackages__"],
source_stem: "bindings",
shared_libs: [
"libutils",
@@ -170,9 +172,10 @@
"libbinder_ndk",
],
rustlibs: [
- "liblibc",
"libbinder_ndk_sys",
"libdowncast_rs",
+ "liblazy_static",
+ "liblibc",
],
}
diff --git a/libs/binder/rust/src/error.rs b/libs/binder/rust/src/error.rs
index 2598ebc..f6b09ed 100644
--- a/libs/binder/rust/src/error.rs
+++ b/libs/binder/rust/src/error.rs
@@ -18,7 +18,7 @@
use crate::sys;
use std::error;
-use std::ffi::CStr;
+use std::ffi::{CStr, CString};
use std::fmt::{Debug, Display, Formatter, Result as FmtResult};
use std::result;
@@ -104,6 +104,10 @@
// A thread-local `AStatus` would not be valid.
unsafe impl Send for Status {}
+fn to_cstring<T: AsRef<str>>(message: T) -> Option<CString> {
+ CString::new(message.as_ref()).ok()
+}
+
impl Status {
/// Create a status object representing a successful transaction.
pub fn ok() -> Self {
@@ -146,6 +150,11 @@
Self(ptr)
}
+ /// Creates a status object from a service specific error.
+ pub fn new_service_specific_error_str<T: AsRef<str>>(err: i32, message: Option<T>) -> Status {
+ Self::new_service_specific_error(err, message.and_then(to_cstring).as_deref())
+ }
+
/// Create a status object from an exception code
pub fn new_exception(exception: ExceptionCode, message: Option<&CStr>) -> Status {
if let Some(message) = message {
@@ -158,6 +167,14 @@
}
}
+ /// Creates a status object from an exception code and message.
+ pub fn new_exception_str<T: AsRef<str>>(
+ exception: ExceptionCode,
+ message: Option<T>,
+ ) -> Status {
+ Self::new_exception(exception, message.and_then(to_cstring).as_deref())
+ }
+
/// Create a status object from a raw `AStatus` pointer.
///
/// # Safety
@@ -371,3 +388,41 @@
self.0
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn make_service_specific_error() {
+ let status = Status::new_service_specific_error_str(-42, Some("message"));
+
+ assert!(!status.is_ok());
+ assert_eq!(status.exception_code(), ExceptionCode::SERVICE_SPECIFIC);
+ assert_eq!(status.service_specific_error(), -42);
+ assert_eq!(
+ status.get_description(),
+ "Status(-8, EX_SERVICE_SPECIFIC): '-42: message'".to_string()
+ );
+ }
+
+ #[test]
+ fn make_exception() {
+ let status = Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some("message"));
+
+ assert!(!status.is_ok());
+ assert_eq!(status.exception_code(), ExceptionCode::ILLEGAL_STATE);
+ assert_eq!(status.service_specific_error(), 0);
+ assert_eq!(status.get_description(), "Status(-5, EX_ILLEGAL_STATE): 'message'".to_string());
+ }
+
+ #[test]
+ fn make_exception_null() {
+ let status = Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some("one\0two"));
+
+ assert!(!status.is_ok());
+ assert_eq!(status.exception_code(), ExceptionCode::ILLEGAL_STATE);
+ assert_eq!(status.service_specific_error(), 0);
+ assert_eq!(status.get_description(), "Status(-5, EX_ILLEGAL_STATE): ''".to_string());
+ }
+}
diff --git a/libs/binder/rust/src/lib.rs b/libs/binder/rust/src/lib.rs
index 67872a9..195d9ac 100644
--- a/libs/binder/rust/src/lib.rs
+++ b/libs/binder/rust/src/lib.rs
@@ -111,6 +111,7 @@
pub use error::{ExceptionCode, Status, StatusCode};
pub use native::{
add_service, force_lazy_services_persist, is_handling_transaction, register_lazy_service,
+ LazyServiceGuard,
};
pub use parcel::{ParcelFileDescriptor, Parcelable, ParcelableHolder};
pub use proxy::{
diff --git a/libs/binder/rust/src/native.rs b/libs/binder/rust/src/native.rs
index 9e2cef1..3a6dadd 100644
--- a/libs/binder/rust/src/native.rs
+++ b/libs/binder/rust/src/native.rs
@@ -22,6 +22,7 @@
use crate::proxy::SpIBinder;
use crate::sys;
+use lazy_static::lazy_static;
use std::convert::TryFrom;
use std::ffi::{c_void, CStr, CString};
use std::fs::File;
@@ -30,6 +31,7 @@
use std::os::raw::c_char;
use std::os::unix::io::FromRawFd;
use std::slice;
+use std::sync::Mutex;
/// Rust wrapper around Binder remotable objects.
///
@@ -487,6 +489,8 @@
/// If persist is true then shut down will be blocked until this function is called again with
/// persist false. If this is to be the initial state, call this function before calling
/// register_lazy_service.
+///
+/// Consider using [`LazyServiceGuard`] rather than calling this directly.
pub fn force_lazy_services_persist(persist: bool) {
unsafe {
// Safety: No borrowing or transfer of ownership occurs here.
@@ -494,6 +498,59 @@
}
}
+/// An RAII object to ensure a process which registers lazy services is not killed. During the
+/// lifetime of any of these objects the service manager will not not kill the process even if none
+/// of its lazy services are in use.
+#[must_use]
+#[derive(Debug)]
+pub struct LazyServiceGuard {
+ // Prevent construction outside this module.
+ _private: (),
+}
+
+lazy_static! {
+ // Count of how many LazyServiceGuard objects are in existence.
+ static ref GUARD_COUNT: Mutex<u64> = Mutex::new(0);
+}
+
+impl LazyServiceGuard {
+ /// Create a new LazyServiceGuard to prevent the service manager prematurely killing this
+ /// process.
+ pub fn new() -> Self {
+ let mut count = GUARD_COUNT.lock().unwrap();
+ *count += 1;
+ if *count == 1 {
+ // It's important that we make this call with the mutex held, to make sure
+ // that multiple calls (e.g. if the count goes 1 -> 0 -> 1) are correctly
+ // sequenced. (That also means we can't just use an AtomicU64.)
+ force_lazy_services_persist(true);
+ }
+ Self { _private: () }
+ }
+}
+
+impl Drop for LazyServiceGuard {
+ fn drop(&mut self) {
+ let mut count = GUARD_COUNT.lock().unwrap();
+ *count -= 1;
+ if *count == 0 {
+ force_lazy_services_persist(false);
+ }
+ }
+}
+
+impl Clone for LazyServiceGuard {
+ fn clone(&self) -> Self {
+ Self::new()
+ }
+}
+
+impl Default for LazyServiceGuard {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
/// Tests often create a base BBinder instance; so allowing the unit
/// type to be remotable translates nicely to Binder::new(()).
impl Remotable for () {
diff --git a/libs/binder/tests/binderThroughputTest.cpp b/libs/binder/tests/binderThroughputTest.cpp
index 3b1faa8..cfaf2a9 100644
--- a/libs/binder/tests/binderThroughputTest.cpp
+++ b/libs/binder/tests/binderThroughputTest.cpp
@@ -249,12 +249,13 @@
pid_t pid = fork();
if (pid) {
/* parent */
- return move(get<0>(pipe_pair));
+ return std::move(get<0>(pipe_pair));
} else {
/* child */
- worker_fx(num, worker_count, iterations, payload_size, cs_pair, move(get<1>(pipe_pair)));
+ worker_fx(num, worker_count, iterations, payload_size, cs_pair,
+ std::move(get<1>(pipe_pair)));
/* never get here */
- return move(get<0>(pipe_pair));
+ return std::move(get<0>(pipe_pair));
}
}
diff --git a/libs/binder/tests/schd-dbg.cpp b/libs/binder/tests/schd-dbg.cpp
index 56d958c..0035e4e 100644
--- a/libs/binder/tests/schd-dbg.cpp
+++ b/libs/binder/tests/schd-dbg.cpp
@@ -398,14 +398,13 @@
pid_t pid = fork();
if (pid) {
// parent
- return move(get<0>(pipe_pair));
+ return std::move(get<0>(pipe_pair));
} else {
// child
thread_dump(is_client(num) ? "client" : "server");
- worker_fx(num, no_process, iterations, payload_size,
- move(get<1>(pipe_pair)));
+ worker_fx(num, no_process, iterations, payload_size, std::move(get<1>(pipe_pair)));
// never get here
- return move(get<0>(pipe_pair));
+ return std::move(get<0>(pipe_pair));
}
}
diff --git a/libs/binder/trusty/RpcTransportTipcTrusty.cpp b/libs/binder/trusty/RpcTransportTipcTrusty.cpp
index e0d80fb..dc27eb9 100644
--- a/libs/binder/trusty/RpcTransportTipcTrusty.cpp
+++ b/libs/binder/trusty/RpcTransportTipcTrusty.cpp
@@ -64,7 +64,7 @@
.num_handles = 0, // TODO: add ancillaryFds
.handles = nullptr,
};
- int rc = send_msg(mSocket.get(), &msg);
+ ssize_t rc = send_msg(mSocket.get(), &msg);
if (rc == ERR_NOT_ENOUGH_BUFFER) {
// Peer is blocked, wait until it unblocks.
// TODO: when tipc supports a send-unblocked handler,
@@ -89,7 +89,7 @@
return statusFromTrusty(rc);
}
LOG_ALWAYS_FATAL_IF(static_cast<size_t>(rc) != size,
- "Sent the wrong number of bytes %d!=%zu", rc, size);
+ "Sent the wrong number of bytes %zd!=%zu", rc, size);
return OK;
}
@@ -129,7 +129,7 @@
.num_handles = 0, // TODO: support ancillaryFds
.handles = nullptr,
};
- int rc = read_msg(mSocket.get(), mMessageInfo.id, mMessageOffset, &msg);
+ ssize_t rc = read_msg(mSocket.get(), mMessageInfo.id, mMessageOffset, &msg);
if (rc < 0) {
return statusFromTrusty(rc);
}
diff --git a/libs/binder/trusty/rules.mk b/libs/binder/trusty/rules.mk
index cd81a09..83475f5 100644
--- a/libs/binder/trusty/rules.mk
+++ b/libs/binder/trusty/rules.mk
@@ -69,6 +69,11 @@
$(LIBUTILS_DIR)/include \
$(FMTLIB_DIR)/include \
+# The android/binder_to_string.h header is shared between libbinder and
+# libbinder_ndk and included by auto-generated AIDL C++ files
+MODULE_EXPORT_INCLUDES += \
+ $(LIBBINDER_DIR)/ndk/include_cpp \
+
MODULE_EXPORT_COMPILEFLAGS += \
-DBINDER_NO_KERNEL_IPC \
-DBINDER_RPC_SINGLE_THREADED \
diff --git a/libs/cputimeinstate/fuzz/cputimeinstate_fuzzer/Android.bp b/libs/cputimeinstate/fuzz/cputimeinstate_fuzzer/Android.bp
new file mode 100644
index 0000000..2399acd
--- /dev/null
+++ b/libs/cputimeinstate/fuzz/cputimeinstate_fuzzer/Android.bp
@@ -0,0 +1,41 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2022 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.
+ *
+ *****************************************************************************
+ */
+package {
+ // See: http://go/android-license-faq
+ // A large-scale-change added 'default_applicable_licenses' to import
+ // all of the 'license_kinds' from "frameworks_native_license"
+ // to get the below license kinds:
+ // SPDX-license-identifier-Apache-2.0
+ default_applicable_licenses: ["frameworks_native_license"],
+}
+
+cc_fuzz {
+ name: "cputimeinstate_fuzzer",
+ srcs: [
+ "cputimeinstate_fuzzer.cpp",
+ ],
+ static_libs: [
+ "libtimeinstate",
+ ],
+ shared_libs: [
+ "libbpf_bcc",
+ "libbase",
+ "libbpf_minimal",
+ ],
+}
diff --git a/libs/cputimeinstate/fuzz/cputimeinstate_fuzzer/cputimeinstate_fuzzer.cpp b/libs/cputimeinstate/fuzz/cputimeinstate_fuzzer/cputimeinstate_fuzzer.cpp
new file mode 100644
index 0000000..f835997
--- /dev/null
+++ b/libs/cputimeinstate/fuzz/cputimeinstate_fuzzer/cputimeinstate_fuzzer.cpp
@@ -0,0 +1,56 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2022 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 <fuzzer/FuzzedDataProvider.h>
+#include <android-base/unique_fd.h>
+#include <cputimeinstate.h>
+
+using namespace android::bpf;
+
+static const uint16_t MAX_VEC_SIZE = 500;
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+ FuzzedDataProvider fdp(data, size);
+
+ uint32_t uid = fdp.ConsumeIntegral<uint32_t>();
+ uint64_t lastUpdate = fdp.ConsumeIntegral<uint64_t>();
+ uint16_t aggregationKey = fdp.ConsumeIntegral<uint16_t>();
+ pid_t pid = fdp.ConsumeIntegral<pid_t>();
+ std::vector<uint16_t> aggregationKeys;
+ uint16_t aggregationKeysSize = fdp.ConsumeIntegralInRange<size_t>(0, MAX_VEC_SIZE);
+ for (uint16_t i = 0; i < aggregationKeysSize; i++) {
+ aggregationKeys.push_back(fdp.ConsumeIntegral<uint16_t>());
+ }
+
+ // To randomize the API calls
+ while (fdp.remaining_bytes() > 0) {
+ auto func = fdp.PickValueInArray<const std::function<void()>>({
+ [&]() { getUidCpuFreqTimes(uid); },
+ [&]() { getUidsUpdatedCpuFreqTimes(&lastUpdate); },
+ [&]() { getUidConcurrentTimes(uid);},
+ [&]() { getUidsUpdatedConcurrentTimes(&lastUpdate); },
+ [&]() { startAggregatingTaskCpuTimes(pid, aggregationKey); },
+ [&]() { getAggregatedTaskCpuFreqTimes(pid, aggregationKeys); },
+ });
+
+ func();
+ }
+
+ return 0;
+}
diff --git a/libs/gui/SurfaceComposerClient.cpp b/libs/gui/SurfaceComposerClient.cpp
index ad9130b..c793523 100644
--- a/libs/gui/SurfaceComposerClient.cpp
+++ b/libs/gui/SurfaceComposerClient.cpp
@@ -2167,6 +2167,16 @@
return nullptr;
}
+sp<SurfaceControl> SurfaceComposerClient::mirrorDisplay(DisplayId displayId) {
+ gui::MirrorSurfaceResult result;
+ const binder::Status status = mClient->mirrorDisplay(displayId.value, &result);
+ const status_t err = statusTFromBinderStatus(status);
+ if (err == NO_ERROR) {
+ return new SurfaceControl(this, result.handle, result.layerId);
+ }
+ return nullptr;
+}
+
status_t SurfaceComposerClient::clearLayerFrameStats(const sp<IBinder>& token) const {
if (mStatus != NO_ERROR) {
return mStatus;
diff --git a/libs/gui/aidl/android/gui/ISurfaceComposerClient.aidl b/libs/gui/aidl/android/gui/ISurfaceComposerClient.aidl
index 71933aa..b8ee4d7 100644
--- a/libs/gui/aidl/android/gui/ISurfaceComposerClient.aidl
+++ b/libs/gui/aidl/android/gui/ISurfaceComposerClient.aidl
@@ -59,4 +59,6 @@
FrameStats getLayerFrameStats(IBinder handle);
MirrorSurfaceResult mirrorSurface(IBinder mirrorFromHandle);
+
+ MirrorSurfaceResult mirrorDisplay(long displayId);
}
diff --git a/libs/gui/fuzzer/Android.bp b/libs/gui/fuzzer/Android.bp
index a41fd57..cdc9376 100644
--- a/libs/gui/fuzzer/Android.bp
+++ b/libs/gui/fuzzer/Android.bp
@@ -95,3 +95,43 @@
"libgui_fuzzer_defaults",
],
}
+
+cc_fuzz {
+ name: "libgui_parcelable_fuzzer",
+ srcs: [
+ "libgui_parcelable_fuzzer.cpp",
+ ],
+ defaults: [
+ "libgui_fuzzer_defaults",
+ ],
+}
+
+cc_fuzz {
+ name: "libgui_bufferQueue_fuzzer",
+ srcs: [
+ "libgui_bufferQueue_fuzzer.cpp",
+ ],
+ defaults: [
+ "libgui_fuzzer_defaults",
+ ],
+}
+
+cc_fuzz {
+ name: "libgui_consumer_fuzzer",
+ srcs: [
+ "libgui_consumer_fuzzer.cpp",
+ ],
+ defaults: [
+ "libgui_fuzzer_defaults",
+ ],
+}
+
+cc_fuzz {
+ name: "libgui_displayEvent_fuzzer",
+ srcs: [
+ "libgui_displayEvent_fuzzer.cpp",
+ ],
+ defaults: [
+ "libgui_fuzzer_defaults",
+ ],
+}
diff --git a/libs/gui/fuzzer/README.md b/libs/gui/fuzzer/README.md
index 73206a1..96e27c9 100644
--- a/libs/gui/fuzzer/README.md
+++ b/libs/gui/fuzzer/README.md
@@ -3,6 +3,10 @@
## Table of contents
+ [libgui_surfaceComposer_fuzzer](#SurfaceComposer)
+ [libgui_surfaceComposerClient_fuzzer](#SurfaceComposerClient)
++ [libgui_parcelable_fuzzer](#Libgui_Parcelable)
++ [libgui_bufferQueue_fuzzer](#BufferQueue)
++ [libgui_consumer_fuzzer](#Libgui_Consumer)
++ [libgui_displayEvent_fuzzer](#LibGui_DisplayEvent)
# <a name="libgui_surfaceComposer_fuzzer"></a> Fuzzer for SurfaceComposer
@@ -99,3 +103,117 @@
$ adb sync data
$ adb shell /data/fuzz/arm64/libgui_surfaceComposerClient_fuzzer/libgui_surfaceComposerClient_fuzzer
```
+
+# <a name="libgui_parcelable_fuzzer"></a> Fuzzer for Libgui_Parcelable
+
+Libgui_Parcelable supports the following parameters:
+1. LayerMetadataKey (parameter name:`key`)
+2. Dataspace (parameter name:`mDataspace`)
+
+| Parameter| Valid Values| Configured Value|
+|------------- |-------------| ----- |
+|`key`| 0.`view::LayerMetadataKey::METADATA_OWNER_UID`, 1.`view::LayerMetadataKey::METADATA_WINDOW_TYPE`, 2.`view::LayerMetadataKey::METADATA_TASK_ID`, 3.`view::LayerMetadataKey::METADATA_MOUSE_CURSOR`, 4.`view::LayerMetadataKey::METADATA_ACCESSIBILITY_ID`, 5.`view::LayerMetadataKey::METADATA_OWNER_PID`, 6.`view::LayerMetadataKey::METADATA_DEQUEUE_TIME`, 7.`view::LayerMetadataKey::METADATA_GAME_MODE`, |Value obtained from FuzzedDataProvider|
+|`mDataSpace`| 0.`ui::Dataspace::UNKNOWN`, 1.`ui::Dataspace::ARBITRARY`, 2.`ui::Dataspace::STANDARD_SHIFT`, 3.`ui::Dataspace::STANDARD_MASK`, 4.`ui::Dataspace::STANDARD_UNSPECIFIED`, 5.`ui::Dataspace::STANDARD_BT709`, 6.`ui::Dataspace::STANDARD_BT601_625`, 7.`ui::Dataspace::STANDARD_BT601_625_UNADJUSTED`, 8.`ui::Dataspace::STANDARD_BT601_525`, 9.`ui::Dataspace::STANDARD_BT601_525_UNADJUSTED`, 10.`ui::Dataspace::STANDARD_BT2020`, 11.`ui::Dataspace::STANDARD_BT2020_CONSTANT_LUMINANCE`, 12.`ui::Dataspace::STANDARD_BT470M`, 13.`ui::Dataspace::STANDARD_FILM`, 14.`ui::Dataspace::STANDARD_DCI_P3`, 15.`ui::Dataspace::STANDARD_ADOBE_RGB`, 16.`ui::Dataspace::TRANSFER_SHIFT`, 17.`ui::Dataspace::TRANSFER_MASK`, 18.`ui::Dataspace::TRANSFER_UNSPECIFIED`, 19.`ui::Dataspace::TRANSFER_LINEAR`, 20.`ui::Dataspace::TRANSFER_SRGB`, 21.`ui::Dataspace::TRANSFER_SMPTE_170M`, 22.`ui::Dataspace::TRANSFER_GAMMA2_2`, 23.`ui::Dataspace::TRANSFER_GAMMA2_6`, 24.`ui::Dataspace::TRANSFER_GAMMA2_8`, 25.`ui::Dataspace::TRANSFER_ST2084`, 26.`ui::Dataspace::TRANSFER_HLG`, 27.`ui::Dataspace::RANGE_SHIFT`, 28.`ui::Dataspace::RANGE_MASK`, 29.`ui::Dataspace::RANGE_UNSPECIFIED`, 30.`ui::Dataspace::RANGE_FULL`, 31.`ui::Dataspace::RANGE_LIMITED`, 32.`ui::Dataspace::RANGE_EXTENDED`, 33.`ui::Dataspace::SRGB_LINEAR`, 34.`ui::Dataspace::V0_SRGB_LINEAR`, 35.`ui::Dataspace::V0_SCRGB_LINEAR`, 36.`ui::Dataspace::SRGB`, 37.`ui::Dataspace::V0_SRGB`, 38.`ui::Dataspace::V0_SCRGB`, 39.`ui::Dataspace::JFIF`, 40.`ui::Dataspace::V0_JFIF`, 41.`ui::Dataspace::BT601_625`, 42.`ui::Dataspace::V0_BT601_625`, 43.`ui::Dataspace::BT601_525`, 44.`ui::Dataspace::V0_BT601_525`, 45.`ui::Dataspace::BT709`, 46.`ui::Dataspace::V0_BT709`, 47.`ui::Dataspace::DCI_P3_LINEAR`, 48.`ui::Dataspace::DCI_P3`, 49.`ui::Dataspace::DISPLAY_P3_LINEAR`, 50.`ui::Dataspace::DISPLAY_P3`, 51.`ui::Dataspace::ADOBE_RGB`, 52.`ui::Dataspace::BT2020_LINEAR`, 53.`ui::Dataspace::BT2020`, 54.`ui::Dataspace::BT2020_PQ`, 55.`ui::Dataspace::DEPTH`, 56.`ui::Dataspace::SENSOR`, 57.`ui::Dataspace::BT2020_ITU`, 58.`ui::Dataspace::BT2020_ITU_PQ`, 59.`ui::Dataspace::BT2020_ITU_HLG`, 60.`ui::Dataspace::BT2020_HLG`, 61.`ui::Dataspace::DISPLAY_BT2020`, 62.`ui::Dataspace::DYNAMIC_DEPTH`, 63.`ui::Dataspace::JPEG_APP_SEGMENTS`, 64.`ui::Dataspace::HEIF`, |Value obtained from FuzzedDataProvider|
+
+#### Steps to run
+1. Build the fuzzer
+```
+ $ mm -j$(nproc) libgui_fuzzer
+```
+2. Run on device
+```
+ $ adb sync data
+ $ adb shell /data/fuzz/arm64/libgui_fuzzer/libgui_fuzzer
+```
+
+# <a name="libgui_bufferQueue_fuzzer"></a> Fuzzer for BufferQueue
+
+BufferQueue supports the following parameters:
+1. SurfaceWidth (parameter name:`width`)
+2. SurfaceHeight (parameter name:`height`)
+3. TransactionStateFlags (parameter name:`flags`)
+4. TransformHint (parameter name:`outTransformHint`)
+5. SurfacePixelFormat (parameter name:`format`)
+6. LayerId (parameter name:`layerId`)
+7. BufferId (parameter name:`bufferId`)
+8. FrameNumber (parameter name:`frameNumber`)
+9. FrameRate (parameter name:`frameRate`)
+10. Compatability (parameter name:`compatability`)
+11. LatchTime (parameter name:`latchTime`)
+12. AcquireTime (parameter name:`acquireTime`)
+13. RefreshTime (parameter name:`refreshTime`)
+14. DequeueTime (parameter name:`dequeueTime`)
+15. Slot (parameter name:`slot`)
+16. MaxBuffers (parameter name:`maxBuffers`)
+17. GenerationNumber (parameter name:`generationNumber`)
+18. Api (parameter name:`api`)
+19. Usage (parameter name:`usage`)
+20. MaxFrameNumber (parameter name:`maxFrameNumber`)
+21. BufferCount (parameter name:`bufferCount`)
+22. MaxAcquredBufferCount (parameter name:`maxAcquredBufferCount`)
+23. Status (parameter name:`status`)
+24. ApiConnection (parameter name:`apiConnection`)
+25. Dataspace (parameter name:`dataspace`)
+
+| Parameter| Valid Values| Configured Value|
+|------------- |-------------| ----- |
+|`status`| 0.`OK`, 1.`NO_MEMORY`, 2.`NO_INIT`, 3.`BAD_VALUE`, 4.`DEAD_OBJECT`, 5.`INVALID_OPERATION`, 6.`TIMED_OUT`, 7.`WOULD_BLOCK`, 8.`UNKNOWN_ERROR`, 9.`ALREADY_EXISTS`, |Value obtained from FuzzedDataProvider|
+|`apiConnection`| 0.`BufferQueueCore::CURRENTLY_CONNECTED_API`, 1.`BufferQueueCore::NO_CONNECTED_API`, 2.`NATIVE_WINDOW_API_EGL`, 3.`NATIVE_WINDOW_API_CPU`, 4.`NATIVE_WINDOW_API_MEDIA`, 5.`NATIVE_WINDOW_API_CAMERA`, |Value obtained from FuzzedDataProvider|
+|`dataspace`| 0.`ui::Dataspace::UNKNOWN`, 1.`ui::Dataspace::ARBITRARY`, 2.`ui::Dataspace::STANDARD_SHIFT`, 3.`ui::Dataspace::STANDARD_MASK`, 4.`ui::Dataspace::STANDARD_UNSPECIFIED`, 5.`ui::Dataspace::STANDARD_BT709`, 6.`ui::Dataspace::STANDARD_BT601_625`, 7.`ui::Dataspace::STANDARD_BT601_625_UNADJUSTED`, 8.`ui::Dataspace::STANDARD_BT601_525`, 9.`ui::Dataspace::STANDARD_BT601_525_UNADJUSTED`, 10.`ui::Dataspace::STANDARD_BT2020`, 11.`ui::Dataspace::STANDARD_BT2020_CONSTANT_LUMINANCE`, 12.`ui::Dataspace::STANDARD_BT470M`, 13.`ui::Dataspace::STANDARD_FILM`, 14.`ui::Dataspace::STANDARD_DCI_P3`, 15.`ui::Dataspace::STANDARD_ADOBE_RGB`, 16.`ui::Dataspace::TRANSFER_SHIFT`, 17.`ui::Dataspace::TRANSFER_MASK`, 18.`ui::Dataspace::TRANSFER_UNSPECIFIED`, 19.`ui::Dataspace::TRANSFER_LINEAR`, 20.`ui::Dataspace::TRANSFER_SRGB`, 21.`ui::Dataspace::TRANSFER_SMPTE_170M`, 22.`ui::Dataspace::TRANSFER_GAMMA2_2`, 23.`ui::Dataspace::TRANSFER_GAMMA2_6`, 24.`ui::Dataspace::TRANSFER_GAMMA2_8`, 25.`ui::Dataspace::TRANSFER_ST2084`, 26.`ui::Dataspace::TRANSFER_HLG`, 27.`ui::Dataspace::RANGE_SHIFT`, 28.`ui::Dataspace::RANGE_MASK`, 29.`ui::Dataspace::RANGE_UNSPECIFIED`, 30.`ui::Dataspace::RANGE_FULL`, 31.`ui::Dataspace::RANGE_LIMITED`, 32.`ui::Dataspace::RANGE_EXTENDED`, 33.`ui::Dataspace::SRGB_LINEAR`, 34.`ui::Dataspace::V0_SRGB_LINEAR`, 35.`ui::Dataspace::V0_SCRGB_LINEAR`, 36.`ui::Dataspace::SRGB`, 37.`ui::Dataspace::V0_SRGB`, 38.`ui::Dataspace::V0_SCRGB`, 39.`ui::Dataspace::JFIF`, 40.`ui::Dataspace::V0_JFIF`, 41.`ui::Dataspace::BT601_625`, 42.`ui::Dataspace::V0_BT601_625`, 43.`ui::Dataspace::BT601_525`, 44.`ui::Dataspace::V0_BT601_525`, 45.`ui::Dataspace::BT709`, 46.`ui::Dataspace::V0_BT709`, 47.`ui::Dataspace::DCI_P3_LINEAR`, 48.`ui::Dataspace::DCI_P3`, 49.`ui::Dataspace::DISPLAY_P3_LINEAR`, 50.`ui::Dataspace::DISPLAY_P3`, 51.`ui::Dataspace::ADOBE_RGB`, 52.`ui::Dataspace::BT2020_LINEAR`, 53.`ui::Dataspace::BT2020`, 54.`ui::Dataspace::BT2020_PQ`, 55.`ui::Dataspace::DEPTH`, 56.`ui::Dataspace::SENSOR`, 57.`ui::Dataspace::BT2020_ITU`, 58.`ui::Dataspace::BT2020_ITU_PQ`, 59.`ui::Dataspace::BT2020_ITU_HLG`, 60.`ui::Dataspace::BT2020_HLG`, 61.`ui::Dataspace::DISPLAY_BT2020`, 62.`ui::Dataspace::DYNAMIC_DEPTH`, 63.`ui::Dataspace::JPEG_APP_SEGMENTS`, 64.`ui::Dataspace::HEIF`, |Value obtained from FuzzedDataProvider|
+
+#### Steps to run
+1. Build the fuzzer
+```
+ $ mm -j$(nproc) libgui_bufferQueue_fuzzer
+```
+2. To run on device
+```
+ $ adb sync data
+ $ adb shell /data/fuzz/arm64/libgui_bufferQueue_fuzzer/libgui_bufferQueue_fuzzer
+```
+
+# <a name="libgui_consumer_fuzzer"></a> Fuzzer for Libgui_Consumer
+
+Libgui_Consumer supports the following parameters:
+1. GraphicWidth (parameter name:`graphicWidth`)
+2. GraphicHeight (parameter name:`graphicHeight`)
+4. TransformHint (parameter name:`outTransformHint`)
+5. GraphicPixelFormat (parameter name:`format`)
+6. Usage (parameter name:`usage`)
+
+#### Steps to run
+1. Build the fuzzer
+```
+ $ mm -j$(nproc) libgui_consumer_fuzzer
+```
+2. Run on device
+```
+ $ adb sync data
+ $ adb shell /data/fuzz/arm64/libgui_consumer_fuzzer/libgui_consumer_fuzzer
+```
+
+# <a name="libgui_displayEvent_fuzzer"></a> Fuzzer for LibGui_DisplayEvent
+
+LibGui_DisplayEvent supports the following parameters:
+1. DisplayEventType (parameter name:`type`)
+2. Events (parameter name:`events`)
+3. VsyncSource (parameter name:`vsyncSource`)
+4. EventRegistrationFlags (parameter name:`flags`)
+
+| Parameter| Valid Values| Configured Value|
+|------------- |-------------| ----- |
+|`vsyncSource`| 0.`ISurfaceComposer::eVsyncSourceApp`, 1.`ISurfaceComposer::eVsyncSourceSurfaceFlinger`, |Value obtained from FuzzedDataProvider|
+|`flags`| 0.`ISurfaceComposer::EventRegistration::modeChanged`, 1.`ISurfaceComposer::EventRegistration::frameRateOverride`, |Value obtained from FuzzedDataProvider|
+|`type`| 0.`DisplayEventReceiver::DISPLAY_EVENT_NULL`, 1.`DisplayEventReceiver::DISPLAY_EVENT_VSYNC`, 2.`DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG`, 3.`DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE`, 4.`DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE`, 5.`DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH`, |Value obtained from FuzzedDataProvider|
+|`events`| 0.`Looper::EVENT_INPUT`, 1.`Looper::EVENT_OUTPUT`, 2.`Looper::EVENT_ERROR`, 3.`Looper::EVENT_HANGUP`, 4.`Looper::EVENT_INVALID`, |Value obtained from FuzzedDataProvider|
+
+#### Steps to run
+1. Build the fuzzer
+```
+ $ mm -j$(nproc) libgui_displayEvent_fuzzer
+```
+2. Run on device
+```
+ $ adb sync data
+ $ adb shell /data/fuzz/arm64/libgui_displayEvent_fuzzer/libgui_displayEvent_fuzzer
+```
diff --git a/libs/gui/fuzzer/libgui_bufferQueue_fuzzer.cpp b/libs/gui/fuzzer/libgui_bufferQueue_fuzzer.cpp
new file mode 100644
index 0000000..c97770b
--- /dev/null
+++ b/libs/gui/fuzzer/libgui_bufferQueue_fuzzer.cpp
@@ -0,0 +1,388 @@
+/*
+ * Copyright 2022 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 <gui/BufferQueueConsumer.h>
+#include <gui/BufferQueueCore.h>
+#include <gui/BufferQueueProducer.h>
+#include <gui/bufferqueue/2.0/types.h>
+#include <system/window.h>
+
+#include <libgui_fuzzer_utils.h>
+
+using namespace android;
+using namespace hardware::graphics::bufferqueue;
+using namespace V1_0::utils;
+using namespace V2_0::utils;
+
+constexpr int32_t kMaxBytes = 256;
+
+constexpr int32_t kError[] = {
+ OK, NO_MEMORY, NO_INIT, BAD_VALUE, DEAD_OBJECT, INVALID_OPERATION,
+ TIMED_OUT, WOULD_BLOCK, UNKNOWN_ERROR, ALREADY_EXISTS,
+};
+
+constexpr int32_t kAPIConnection[] = {
+ BufferQueueCore::CURRENTLY_CONNECTED_API,
+ BufferQueueCore::NO_CONNECTED_API,
+ NATIVE_WINDOW_API_EGL,
+ NATIVE_WINDOW_API_CPU,
+ NATIVE_WINDOW_API_MEDIA,
+ NATIVE_WINDOW_API_CAMERA,
+};
+
+class BufferQueueFuzzer {
+public:
+ BufferQueueFuzzer(const uint8_t* data, size_t size) : mFdp(data, size){};
+ void process();
+
+private:
+ void invokeTypes();
+ void invokeH2BGraphicBufferV1();
+ void invokeH2BGraphicBufferV2();
+ void invokeBufferQueueConsumer();
+ void invokeBufferQueueProducer();
+ void invokeBlastBufferQueue();
+ void invokeQuery(sp<BufferQueueProducer>);
+ void invokeQuery(sp<V1_0::utils::H2BGraphicBufferProducer>);
+ void invokeQuery(sp<V2_0::utils::H2BGraphicBufferProducer>);
+ void invokeAcquireBuffer(sp<BufferQueueConsumer>);
+ void invokeOccupancyTracker(sp<BufferQueueConsumer>);
+ sp<SurfaceControl> makeSurfaceControl();
+ sp<BLASTBufferQueue> makeBLASTBufferQueue(sp<SurfaceControl>);
+
+ FuzzedDataProvider mFdp;
+};
+
+class ManageResourceHandle {
+public:
+ ManageResourceHandle(FuzzedDataProvider* fdp) {
+ mNativeHandle = native_handle_create(0 /*numFds*/, 1 /*numInts*/);
+ mShouldOwn = fdp->ConsumeBool();
+ mStream = NativeHandle::create(mNativeHandle, mShouldOwn);
+ }
+ ~ManageResourceHandle() {
+ if (!mShouldOwn) {
+ native_handle_close(mNativeHandle);
+ native_handle_delete(mNativeHandle);
+ }
+ }
+ sp<NativeHandle> getStream() { return mStream; }
+
+private:
+ bool mShouldOwn;
+ sp<NativeHandle> mStream;
+ native_handle_t* mNativeHandle;
+};
+
+sp<SurfaceControl> BufferQueueFuzzer::makeSurfaceControl() {
+ sp<IBinder> handle;
+ const sp<FakeBnSurfaceComposerClient> testClient(new FakeBnSurfaceComposerClient());
+ sp<SurfaceComposerClient> client = new SurfaceComposerClient(testClient);
+ sp<BnGraphicBufferProducer> producer;
+ return sp<SurfaceControl>::make(client, handle, mFdp.ConsumeIntegral<int32_t>(),
+ mFdp.ConsumeIntegral<uint32_t>(),
+ mFdp.ConsumeIntegral<uint32_t>(),
+ mFdp.ConsumeIntegral<int32_t>(),
+ mFdp.ConsumeIntegral<uint32_t>(),
+ mFdp.ConsumeIntegral<uint32_t>());
+}
+
+sp<BLASTBufferQueue> BufferQueueFuzzer::makeBLASTBufferQueue(sp<SurfaceControl> surface) {
+ return sp<BLASTBufferQueue>::make(mFdp.ConsumeRandomLengthString(kMaxBytes), surface,
+ mFdp.ConsumeIntegral<uint32_t>(),
+ mFdp.ConsumeIntegral<uint32_t>(),
+ mFdp.ConsumeIntegral<int32_t>());
+}
+
+void BufferQueueFuzzer::invokeBlastBufferQueue() {
+ sp<SurfaceControl> surface = makeSurfaceControl();
+ sp<BLASTBufferQueue> queue = makeBLASTBufferQueue(surface);
+
+ BufferItem item;
+ queue->onFrameAvailable(item);
+ queue->onFrameReplaced(item);
+ uint64_t bufferId = mFdp.ConsumeIntegral<uint64_t>();
+ queue->onFrameDequeued(bufferId);
+ queue->onFrameCancelled(bufferId);
+
+ SurfaceComposerClient::Transaction next;
+ uint64_t frameNumber = mFdp.ConsumeIntegral<uint64_t>();
+ queue->mergeWithNextTransaction(&next, frameNumber);
+ queue->applyPendingTransactions(frameNumber);
+
+ queue->update(surface, mFdp.ConsumeIntegral<uint32_t>(), mFdp.ConsumeIntegral<uint32_t>(),
+ mFdp.ConsumeIntegral<int32_t>());
+ queue->setFrameRate(mFdp.ConsumeFloatingPoint<float>(), mFdp.ConsumeIntegral<int8_t>(),
+ mFdp.ConsumeBool() /*shouldBeSeamless*/);
+ FrameTimelineInfo info;
+ queue->setFrameTimelineInfo(info);
+
+ ManageResourceHandle handle(&mFdp);
+ queue->setSidebandStream(handle.getStream());
+
+ queue->getLastTransformHint();
+ queue->getLastAcquiredFrameNum();
+
+ CompositorTiming compTiming;
+ sp<Fence> previousFence = new Fence(memfd_create("pfd", MFD_ALLOW_SEALING));
+ sp<Fence> gpuFence = new Fence(memfd_create("gfd", MFD_ALLOW_SEALING));
+ FrameEventHistoryStats frameStats(frameNumber, gpuFence, compTiming,
+ mFdp.ConsumeIntegral<int64_t>(),
+ mFdp.ConsumeIntegral<int64_t>());
+ std::vector<SurfaceControlStats> stats;
+ sp<Fence> presentFence = new Fence(memfd_create("fd", MFD_ALLOW_SEALING));
+ SurfaceControlStats controlStats(surface, mFdp.ConsumeIntegral<int64_t>(),
+ mFdp.ConsumeIntegral<int64_t>(), presentFence, previousFence,
+ mFdp.ConsumeIntegral<uint32_t>(), frameStats);
+ stats.push_back(controlStats);
+}
+
+void BufferQueueFuzzer::invokeQuery(sp<BufferQueueProducer> producer) {
+ int32_t value;
+ producer->query(mFdp.ConsumeIntegral<int32_t>(), &value);
+}
+
+void BufferQueueFuzzer::invokeQuery(sp<V1_0::utils::H2BGraphicBufferProducer> producer) {
+ int32_t value;
+ producer->query(mFdp.ConsumeIntegral<int32_t>(), &value);
+}
+
+void BufferQueueFuzzer::invokeQuery(sp<V2_0::utils::H2BGraphicBufferProducer> producer) {
+ int32_t value;
+ producer->query(mFdp.ConsumeIntegral<int32_t>(), &value);
+}
+
+void BufferQueueFuzzer::invokeBufferQueueProducer() {
+ sp<BufferQueueCore> core(new BufferQueueCore());
+ sp<BufferQueueProducer> producer(new BufferQueueProducer(core));
+ const sp<android::IProducerListener> listener;
+ android::IGraphicBufferProducer::QueueBufferOutput output;
+ uint32_t api = mFdp.ConsumeIntegral<uint32_t>();
+ producer->connect(listener, api, mFdp.ConsumeBool() /*producerControlledByApp*/, &output);
+
+ sp<GraphicBuffer> buffer;
+ int32_t slot = mFdp.ConsumeIntegral<int32_t>();
+ uint32_t maxBuffers = mFdp.ConsumeIntegral<uint32_t>();
+ producer->requestBuffer(slot, &buffer);
+ producer->setMaxDequeuedBufferCount(maxBuffers);
+ producer->setAsyncMode(mFdp.ConsumeBool() /*async*/);
+
+ android::IGraphicBufferProducer::QueueBufferInput input;
+ producer->attachBuffer(&slot, buffer);
+ producer->queueBuffer(slot, input, &output);
+
+ int32_t format = mFdp.ConsumeIntegral<int32_t>();
+ uint32_t width = mFdp.ConsumeIntegral<uint32_t>();
+ uint32_t height = mFdp.ConsumeIntegral<uint32_t>();
+ uint64_t usage = mFdp.ConsumeIntegral<uint64_t>();
+ uint64_t outBufferAge;
+ FrameEventHistoryDelta outTimestamps;
+ sp<android::Fence> fence;
+ producer->dequeueBuffer(&slot, &fence, width, height, format, usage, &outBufferAge,
+ &outTimestamps);
+ producer->detachBuffer(slot);
+ producer->detachNextBuffer(&buffer, &fence);
+ producer->cancelBuffer(slot, fence);
+
+ invokeQuery(producer);
+
+ ManageResourceHandle handle(&mFdp);
+ producer->setSidebandStream(handle.getStream());
+
+ producer->allocateBuffers(width, height, format, usage);
+ producer->allowAllocation(mFdp.ConsumeBool() /*allow*/);
+ producer->setSharedBufferMode(mFdp.ConsumeBool() /*sharedBufferMode*/);
+ producer->setAutoRefresh(mFdp.ConsumeBool() /*autoRefresh*/);
+ producer->setLegacyBufferDrop(mFdp.ConsumeBool() /*drop*/);
+ producer->setAutoPrerotation(mFdp.ConsumeBool() /*autoPrerotation*/);
+
+ producer->setGenerationNumber(mFdp.ConsumeIntegral<uint32_t>());
+ producer->setDequeueTimeout(mFdp.ConsumeIntegral<uint32_t>());
+ producer->disconnect(api);
+}
+
+void BufferQueueFuzzer::invokeAcquireBuffer(sp<BufferQueueConsumer> consumer) {
+ BufferItem item;
+ consumer->acquireBuffer(&item, mFdp.ConsumeIntegral<uint32_t>(),
+ mFdp.ConsumeIntegral<uint64_t>());
+}
+
+void BufferQueueFuzzer::invokeOccupancyTracker(sp<BufferQueueConsumer> consumer) {
+ String8 outResult;
+ String8 prefix((mFdp.ConsumeRandomLengthString(kMaxBytes)).c_str());
+ consumer->dumpState(prefix, &outResult);
+
+ std::vector<OccupancyTracker::Segment> outHistory;
+ consumer->getOccupancyHistory(mFdp.ConsumeBool() /*forceFlush*/, &outHistory);
+}
+
+void BufferQueueFuzzer::invokeBufferQueueConsumer() {
+ sp<BufferQueueCore> core(new BufferQueueCore());
+ sp<BufferQueueConsumer> consumer(new BufferQueueConsumer(core));
+ sp<android::IConsumerListener> listener;
+ consumer->consumerConnect(listener, mFdp.ConsumeBool() /*controlledByApp*/);
+ invokeAcquireBuffer(consumer);
+
+ int32_t slot = mFdp.ConsumeIntegral<int32_t>();
+ sp<GraphicBuffer> buffer =
+ new GraphicBuffer(mFdp.ConsumeIntegral<uint32_t>(), mFdp.ConsumeIntegral<uint32_t>(),
+ mFdp.ConsumeIntegral<int32_t>(), mFdp.ConsumeIntegral<uint32_t>(),
+ mFdp.ConsumeIntegral<uint64_t>());
+ consumer->attachBuffer(&slot, buffer);
+ consumer->detachBuffer(slot);
+
+ consumer->setDefaultBufferSize(mFdp.ConsumeIntegral<uint32_t>(),
+ mFdp.ConsumeIntegral<uint32_t>());
+ consumer->setMaxBufferCount(mFdp.ConsumeIntegral<int32_t>());
+ consumer->setMaxAcquiredBufferCount(mFdp.ConsumeIntegral<int32_t>());
+
+ String8 name((mFdp.ConsumeRandomLengthString(kMaxBytes)).c_str());
+ consumer->setConsumerName(name);
+ consumer->setDefaultBufferFormat(mFdp.ConsumeIntegral<int32_t>());
+ android_dataspace dataspace =
+ static_cast<android_dataspace>(mFdp.PickValueInArray(kDataspaces));
+ consumer->setDefaultBufferDataSpace(dataspace);
+
+ consumer->setTransformHint(mFdp.ConsumeIntegral<uint32_t>());
+ consumer->setConsumerUsageBits(mFdp.ConsumeIntegral<uint64_t>());
+ consumer->setConsumerIsProtected(mFdp.ConsumeBool() /*isProtected*/);
+ invokeOccupancyTracker(consumer);
+
+ sp<Fence> releaseFence = new Fence(memfd_create("fd", MFD_ALLOW_SEALING));
+ consumer->releaseBuffer(mFdp.ConsumeIntegral<int32_t>(), mFdp.ConsumeIntegral<uint64_t>(),
+ EGL_NO_DISPLAY, EGL_NO_SYNC_KHR, releaseFence);
+ consumer->consumerDisconnect();
+}
+
+void BufferQueueFuzzer::invokeTypes() {
+ HStatus hStatus;
+ int32_t status = mFdp.PickValueInArray(kError);
+ bool bufferNeedsReallocation = mFdp.ConsumeBool();
+ bool releaseAllBuffers = mFdp.ConsumeBool();
+ b2h(status, &hStatus, &bufferNeedsReallocation, &releaseAllBuffers);
+ h2b(hStatus, &status);
+
+ HConnectionType type;
+ int32_t apiConnection = mFdp.PickValueInArray(kAPIConnection);
+ b2h(apiConnection, &type);
+ h2b(type, &apiConnection);
+}
+
+void BufferQueueFuzzer::invokeH2BGraphicBufferV1() {
+ sp<V1_0::utils::H2BGraphicBufferProducer> producer(
+ new V1_0::utils::H2BGraphicBufferProducer(new FakeGraphicBufferProducerV1()));
+ const sp<android::IProducerListener> listener;
+ android::IGraphicBufferProducer::QueueBufferOutput output;
+ uint32_t api = mFdp.ConsumeIntegral<uint32_t>();
+ producer->connect(listener, api, mFdp.ConsumeBool() /*producerControlledByApp*/, &output);
+
+ sp<GraphicBuffer> buffer;
+ int32_t slot = mFdp.ConsumeIntegral<int32_t>();
+ producer->requestBuffer(slot, &buffer);
+ producer->setMaxDequeuedBufferCount(mFdp.ConsumeIntegral<int32_t>());
+ producer->setAsyncMode(mFdp.ConsumeBool());
+
+ android::IGraphicBufferProducer::QueueBufferInput input;
+ input.fence = new Fence(memfd_create("ffd", MFD_ALLOW_SEALING));
+ producer->attachBuffer(&slot, buffer);
+ producer->queueBuffer(slot, input, &output);
+
+ int32_t format = mFdp.ConsumeIntegral<int32_t>();
+ uint32_t width = mFdp.ConsumeIntegral<uint32_t>();
+ uint32_t height = mFdp.ConsumeIntegral<uint32_t>();
+ uint64_t usage = mFdp.ConsumeIntegral<uint64_t>();
+ uint64_t outBufferAge;
+ FrameEventHistoryDelta outTimestamps;
+ sp<android::Fence> fence;
+ producer->dequeueBuffer(&slot, &fence, width, height, format, usage, &outBufferAge,
+ &outTimestamps);
+ producer->detachBuffer(slot);
+ producer->cancelBuffer(slot, fence);
+
+ invokeQuery(producer);
+
+ ManageResourceHandle handle(&mFdp);
+ producer->setSidebandStream(handle.getStream());
+
+ producer->allocateBuffers(width, height, format, usage);
+ producer->allowAllocation(mFdp.ConsumeBool() /*allow*/);
+ producer->setSharedBufferMode(mFdp.ConsumeBool() /*sharedBufferMode*/);
+ producer->setAutoRefresh(mFdp.ConsumeBool() /*autoRefresh*/);
+
+ producer->setGenerationNumber(mFdp.ConsumeIntegral<uint32_t>());
+ producer->setDequeueTimeout(mFdp.ConsumeIntegral<uint32_t>());
+ producer->disconnect(api);
+}
+
+void BufferQueueFuzzer::invokeH2BGraphicBufferV2() {
+ sp<V2_0::utils::H2BGraphicBufferProducer> producer(
+ new V2_0::utils::H2BGraphicBufferProducer(new FakeGraphicBufferProducerV2()));
+ const sp<android::IProducerListener> listener;
+ android::IGraphicBufferProducer::QueueBufferOutput output;
+ uint32_t api = mFdp.ConsumeIntegral<uint32_t>();
+ producer->connect(listener, api, mFdp.ConsumeBool() /*producerControlledByApp*/, &output);
+
+ sp<GraphicBuffer> buffer;
+ int32_t slot = mFdp.ConsumeIntegral<int32_t>();
+ producer->requestBuffer(slot, &buffer);
+ producer->setMaxDequeuedBufferCount(mFdp.ConsumeIntegral<uint32_t>());
+ producer->setAsyncMode(mFdp.ConsumeBool());
+
+ android::IGraphicBufferProducer::QueueBufferInput input;
+ input.fence = new Fence(memfd_create("ffd", MFD_ALLOW_SEALING));
+ producer->attachBuffer(&slot, buffer);
+ producer->queueBuffer(slot, input, &output);
+
+ int32_t format = mFdp.ConsumeIntegral<int32_t>();
+ uint32_t width = mFdp.ConsumeIntegral<uint32_t>();
+ uint32_t height = mFdp.ConsumeIntegral<uint32_t>();
+ uint64_t usage = mFdp.ConsumeIntegral<uint64_t>();
+ uint64_t outBufferAge;
+ FrameEventHistoryDelta outTimestamps;
+ sp<android::Fence> fence;
+ producer->dequeueBuffer(&slot, &fence, width, height, format, usage, &outBufferAge,
+ &outTimestamps);
+ producer->detachBuffer(slot);
+ producer->cancelBuffer(slot, fence);
+
+ invokeQuery(producer);
+
+ ManageResourceHandle handle(&mFdp);
+ producer->setSidebandStream(handle.getStream());
+
+ producer->allocateBuffers(width, height, format, usage);
+ producer->allowAllocation(mFdp.ConsumeBool() /*allow*/);
+ producer->setSharedBufferMode(mFdp.ConsumeBool() /*sharedBufferMode*/);
+ producer->setAutoRefresh(mFdp.ConsumeBool() /*autoRefresh*/);
+
+ producer->setGenerationNumber(mFdp.ConsumeIntegral<uint32_t>());
+ producer->setDequeueTimeout(mFdp.ConsumeIntegral<uint32_t>());
+ producer->disconnect(api);
+}
+
+void BufferQueueFuzzer::process() {
+ invokeBlastBufferQueue();
+ invokeH2BGraphicBufferV1();
+ invokeH2BGraphicBufferV2();
+ invokeTypes();
+ invokeBufferQueueConsumer();
+ invokeBufferQueueProducer();
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+ BufferQueueFuzzer bufferQueueFuzzer(data, size);
+ bufferQueueFuzzer.process();
+ return 0;
+}
diff --git a/libs/gui/fuzzer/libgui_consumer_fuzzer.cpp b/libs/gui/fuzzer/libgui_consumer_fuzzer.cpp
new file mode 100644
index 0000000..24a046d
--- /dev/null
+++ b/libs/gui/fuzzer/libgui_consumer_fuzzer.cpp
@@ -0,0 +1,82 @@
+/*
+ * Copyright 2022 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 <gui/BufferQueueConsumer.h>
+#include <gui/BufferQueueCore.h>
+#include <gui/BufferQueueProducer.h>
+#include <gui/GLConsumer.h>
+#include <libgui_fuzzer_utils.h>
+
+using namespace android;
+
+constexpr int32_t kMinBuffer = 0;
+constexpr int32_t kMaxBuffer = 100000;
+
+class ConsumerFuzzer {
+public:
+ ConsumerFuzzer(const uint8_t* data, size_t size) : mFdp(data, size){};
+ void process();
+
+private:
+ FuzzedDataProvider mFdp;
+};
+
+void ConsumerFuzzer::process() {
+ sp<BufferQueueCore> core(new BufferQueueCore());
+ sp<IGraphicBufferConsumer> consumer(new BufferQueueConsumer(core));
+
+ uint64_t maxBuffers = mFdp.ConsumeIntegralInRange<uint64_t>(kMinBuffer, kMaxBuffer);
+ sp<CpuConsumer> cpu(
+ new CpuConsumer(consumer, maxBuffers, mFdp.ConsumeBool() /*controlledByApp*/));
+ CpuConsumer::LockedBuffer lockBuffer;
+ cpu->lockNextBuffer(&lockBuffer);
+ cpu->unlockBuffer(lockBuffer);
+ cpu->abandon();
+
+ uint32_t tex = mFdp.ConsumeIntegral<uint32_t>();
+ sp<GLConsumer> glComsumer(new GLConsumer(consumer, tex, GLConsumer::TEXTURE_EXTERNAL,
+ mFdp.ConsumeBool() /*useFenceSync*/,
+ mFdp.ConsumeBool() /*isControlledByApp*/));
+ sp<Fence> releaseFence = new Fence(memfd_create("rfd", MFD_ALLOW_SEALING));
+ glComsumer->setReleaseFence(releaseFence);
+ glComsumer->updateTexImage();
+ glComsumer->releaseTexImage();
+
+ sp<GraphicBuffer> buffer =
+ new GraphicBuffer(mFdp.ConsumeIntegral<uint32_t>(), mFdp.ConsumeIntegral<uint32_t>(),
+ mFdp.ConsumeIntegral<int32_t>(), mFdp.ConsumeIntegral<uint32_t>(),
+ mFdp.ConsumeIntegral<uint64_t>());
+ float mtx[16];
+ glComsumer->getTransformMatrix(mtx);
+ glComsumer->computeTransformMatrix(mtx, buffer, getRect(&mFdp),
+ mFdp.ConsumeIntegral<uint32_t>(),
+ mFdp.ConsumeBool() /*filtering*/);
+ glComsumer->scaleDownCrop(getRect(&mFdp), mFdp.ConsumeIntegral<uint32_t>(),
+ mFdp.ConsumeIntegral<uint32_t>());
+
+ glComsumer->setDefaultBufferSize(mFdp.ConsumeIntegral<uint32_t>(),
+ mFdp.ConsumeIntegral<uint32_t>());
+ glComsumer->setFilteringEnabled(mFdp.ConsumeBool() /*enabled*/);
+
+ glComsumer->setConsumerUsageBits(mFdp.ConsumeIntegral<uint64_t>());
+ glComsumer->attachToContext(tex);
+ glComsumer->abandon();
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+ ConsumerFuzzer consumerFuzzer(data, size);
+ consumerFuzzer.process();
+ return 0;
+}
diff --git a/libs/gui/fuzzer/libgui_displayEvent_fuzzer.cpp b/libs/gui/fuzzer/libgui_displayEvent_fuzzer.cpp
new file mode 100644
index 0000000..6d5ae49
--- /dev/null
+++ b/libs/gui/fuzzer/libgui_displayEvent_fuzzer.cpp
@@ -0,0 +1,104 @@
+/*
+ * Copyright 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <android/gui/ISurfaceComposer.h>
+
+#include <libgui_fuzzer_utils.h>
+
+using namespace android;
+
+constexpr gui::ISurfaceComposer::VsyncSource kVsyncSource[] = {
+ gui::ISurfaceComposer::VsyncSource::eVsyncSourceApp,
+ gui::ISurfaceComposer::VsyncSource::eVsyncSourceSurfaceFlinger,
+};
+
+constexpr gui::ISurfaceComposer::EventRegistration kEventRegistration[] = {
+ gui::ISurfaceComposer::EventRegistration::modeChanged,
+ gui::ISurfaceComposer::EventRegistration::frameRateOverride,
+};
+
+constexpr uint32_t kDisplayEvent[] = {
+ DisplayEventReceiver::DISPLAY_EVENT_NULL,
+ DisplayEventReceiver::DISPLAY_EVENT_VSYNC,
+ DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG,
+ DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE,
+ DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE,
+ DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH,
+};
+
+constexpr int32_t kEvents[] = {
+ Looper::EVENT_INPUT, Looper::EVENT_OUTPUT, Looper::EVENT_ERROR,
+ Looper::EVENT_HANGUP, Looper::EVENT_INVALID,
+};
+
+DisplayEventReceiver::Event buildDisplayEvent(FuzzedDataProvider* fdp, uint32_t type,
+ DisplayEventReceiver::Event event) {
+ switch (type) {
+ case DisplayEventReceiver::DISPLAY_EVENT_VSYNC: {
+ event.vsync.count = fdp->ConsumeIntegral<uint32_t>();
+ event.vsync.vsyncData.frameInterval = fdp->ConsumeIntegral<uint64_t>();
+ event.vsync.vsyncData.preferredFrameTimelineIndex = fdp->ConsumeIntegral<uint32_t>();
+ for (size_t idx = 0; idx < gui::VsyncEventData::kFrameTimelinesLength; ++idx) {
+ event.vsync.vsyncData.frameTimelines[idx].vsyncId = fdp->ConsumeIntegral<int64_t>();
+ event.vsync.vsyncData.frameTimelines[idx].deadlineTimestamp =
+ fdp->ConsumeIntegral<uint64_t>();
+ event.vsync.vsyncData.frameTimelines[idx].expectedPresentationTime =
+ fdp->ConsumeIntegral<uint64_t>();
+ }
+ break;
+
+ }
+ case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG: {
+ event.hotplug = DisplayEventReceiver::Event::Hotplug{fdp->ConsumeBool() /*connected*/};
+ break;
+ }
+ case DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE: {
+ event.modeChange =
+ DisplayEventReceiver::Event::ModeChange{fdp->ConsumeIntegral<int32_t>(),
+ fdp->ConsumeIntegral<int64_t>()};
+ break;
+ }
+ case DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE:
+ case DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH: {
+ event.frameRateOverride =
+ DisplayEventReceiver::Event::FrameRateOverride{fdp->ConsumeIntegral<uint32_t>(),
+ fdp->ConsumeFloatingPoint<
+ float>()};
+ break;
+ }
+ }
+ return event;
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+ FuzzedDataProvider fdp(data, size);
+ sp<Looper> looper;
+ sp<FakeDisplayEventDispatcher> dispatcher(
+ new FakeDisplayEventDispatcher(looper, fdp.PickValueInArray(kVsyncSource),
+ fdp.PickValueInArray(kEventRegistration)));
+
+ dispatcher->initialize();
+ DisplayEventReceiver::Event event;
+ uint32_t type = fdp.PickValueInArray(kDisplayEvent);
+ PhysicalDisplayId displayId;
+ event.header =
+ DisplayEventReceiver::Event::Header{type, displayId, fdp.ConsumeIntegral<int64_t>()};
+ event = buildDisplayEvent(&fdp, type, event);
+
+ dispatcher->injectEvent(event);
+ dispatcher->handleEvent(0, fdp.PickValueInArray(kEvents), nullptr);
+ return 0;
+}
diff --git a/libs/gui/fuzzer/libgui_fuzzer_utils.h b/libs/gui/fuzzer/libgui_fuzzer_utils.h
index d17ce4a..d51f685 100644
--- a/libs/gui/fuzzer/libgui_fuzzer_utils.h
+++ b/libs/gui/fuzzer/libgui_fuzzer_utils.h
@@ -173,6 +173,9 @@
MOCK_METHOD(binder::Status, mirrorSurface,
(const sp<IBinder>& mirrorFromHandle, gui::MirrorSurfaceResult* outResult),
(override));
+
+ MOCK_METHOD(binder::Status, mirrorDisplay,
+ (int64_t displayId, gui::MirrorSurfaceResult* outResult), (override));
};
class FakeDisplayEventDispatcher : public DisplayEventDispatcher {
diff --git a/libs/gui/fuzzer/libgui_parcelable_fuzzer.cpp b/libs/gui/fuzzer/libgui_parcelable_fuzzer.cpp
new file mode 100644
index 0000000..9f0f6ca
--- /dev/null
+++ b/libs/gui/fuzzer/libgui_parcelable_fuzzer.cpp
@@ -0,0 +1,175 @@
+/*
+ * Copyright 2022 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 <gui/BufferQueueConsumer.h>
+#include <gui/BufferQueueCore.h>
+#include <gui/BufferQueueProducer.h>
+#include <gui/LayerMetadata.h>
+#include <gui/OccupancyTracker.h>
+#include <gui/StreamSplitter.h>
+#include <gui/Surface.h>
+#include <gui/SurfaceControl.h>
+#include <gui/view/Surface.h>
+#include <libgui_fuzzer_utils.h>
+#include "android/view/LayerMetadataKey.h"
+
+using namespace android;
+
+constexpr int32_t kMaxBytes = 256;
+constexpr int32_t kMatrixSize = 4;
+constexpr int32_t kLayerMetadataKeyCount = 8;
+
+constexpr uint32_t kMetadataKey[] = {
+ (uint32_t)view::LayerMetadataKey::METADATA_OWNER_UID,
+ (uint32_t)view::LayerMetadataKey::METADATA_WINDOW_TYPE,
+ (uint32_t)view::LayerMetadataKey::METADATA_TASK_ID,
+ (uint32_t)view::LayerMetadataKey::METADATA_MOUSE_CURSOR,
+ (uint32_t)view::LayerMetadataKey::METADATA_ACCESSIBILITY_ID,
+ (uint32_t)view::LayerMetadataKey::METADATA_OWNER_PID,
+ (uint32_t)view::LayerMetadataKey::METADATA_DEQUEUE_TIME,
+ (uint32_t)view::LayerMetadataKey::METADATA_GAME_MODE,
+};
+
+class ParcelableFuzzer {
+public:
+ ParcelableFuzzer(const uint8_t* data, size_t size) : mFdp(data, size){};
+ void process();
+
+private:
+ void invokeStreamSplitter();
+ void invokeOccupancyTracker();
+ void invokeLayerDebugInfo();
+ void invokeLayerMetadata();
+ void invokeViewSurface();
+
+ FuzzedDataProvider mFdp;
+};
+
+void ParcelableFuzzer::invokeViewSurface() {
+ view::Surface surface;
+ surface.name = String16((mFdp.ConsumeRandomLengthString(kMaxBytes)).c_str());
+ Parcel parcel;
+ surface.writeToParcel(&parcel);
+ parcel.setDataPosition(0);
+ surface.readFromParcel(&parcel);
+ bool nameAlreadyWritten = mFdp.ConsumeBool();
+ surface.writeToParcel(&parcel, nameAlreadyWritten);
+ parcel.setDataPosition(0);
+ surface.readFromParcel(&parcel, mFdp.ConsumeBool());
+}
+
+void ParcelableFuzzer::invokeLayerMetadata() {
+ std::unordered_map<uint32_t, std::vector<uint8_t>> map;
+ for (size_t idx = 0; idx < kLayerMetadataKeyCount; ++idx) {
+ std::vector<uint8_t> data;
+ for (size_t idx1 = 0; idx1 < mFdp.ConsumeIntegral<uint32_t>(); ++idx1) {
+ data.push_back(mFdp.ConsumeIntegral<uint8_t>());
+ }
+ map[kMetadataKey[idx]] = data;
+ }
+ LayerMetadata metadata(map);
+ uint32_t key = mFdp.PickValueInArray(kMetadataKey);
+ metadata.setInt32(key, mFdp.ConsumeIntegral<int32_t>());
+ metadata.itemToString(key, (mFdp.ConsumeRandomLengthString(kMaxBytes)).c_str());
+
+ Parcel parcel;
+ metadata.writeToParcel(&parcel);
+ parcel.setDataPosition(0);
+ metadata.readFromParcel(&parcel);
+}
+
+void ParcelableFuzzer::invokeLayerDebugInfo() {
+ gui::LayerDebugInfo info;
+ info.mName = mFdp.ConsumeRandomLengthString(kMaxBytes);
+ info.mParentName = mFdp.ConsumeRandomLengthString(kMaxBytes);
+ info.mType = mFdp.ConsumeRandomLengthString(kMaxBytes);
+ info.mLayerStack = mFdp.ConsumeIntegral<uint32_t>();
+ info.mX = mFdp.ConsumeFloatingPoint<float>();
+ info.mY = mFdp.ConsumeFloatingPoint<float>();
+ info.mZ = mFdp.ConsumeIntegral<uint32_t>();
+ info.mWidth = mFdp.ConsumeIntegral<int32_t>();
+ info.mHeight = mFdp.ConsumeIntegral<int32_t>();
+ info.mActiveBufferWidth = mFdp.ConsumeIntegral<int32_t>();
+ info.mActiveBufferHeight = mFdp.ConsumeIntegral<int32_t>();
+ info.mActiveBufferStride = mFdp.ConsumeIntegral<int32_t>();
+ info.mActiveBufferFormat = mFdp.ConsumeIntegral<int32_t>();
+ info.mNumQueuedFrames = mFdp.ConsumeIntegral<int32_t>();
+
+ info.mFlags = mFdp.ConsumeIntegral<uint32_t>();
+ info.mPixelFormat = mFdp.ConsumeIntegral<int32_t>();
+ info.mTransparentRegion = Region(getRect(&mFdp));
+ info.mVisibleRegion = Region(getRect(&mFdp));
+ info.mSurfaceDamageRegion = Region(getRect(&mFdp));
+ info.mCrop = getRect(&mFdp);
+ info.mDataSpace = static_cast<android_dataspace>(mFdp.PickValueInArray(kDataspaces));
+ info.mColor = half4(mFdp.ConsumeFloatingPoint<float>(), mFdp.ConsumeFloatingPoint<float>(),
+ mFdp.ConsumeFloatingPoint<float>(), mFdp.ConsumeFloatingPoint<float>());
+ for (size_t idx = 0; idx < kMatrixSize; ++idx) {
+ info.mMatrix[idx / 2][idx % 2] = mFdp.ConsumeFloatingPoint<float>();
+ }
+ info.mIsOpaque = mFdp.ConsumeBool();
+ info.mContentDirty = mFdp.ConsumeBool();
+ info.mStretchEffect.width = mFdp.ConsumeFloatingPoint<float>();
+ info.mStretchEffect.height = mFdp.ConsumeFloatingPoint<float>();
+ info.mStretchEffect.vectorX = mFdp.ConsumeFloatingPoint<float>();
+ info.mStretchEffect.vectorY = mFdp.ConsumeFloatingPoint<float>();
+ info.mStretchEffect.maxAmountX = mFdp.ConsumeFloatingPoint<float>();
+ info.mStretchEffect.maxAmountY = mFdp.ConsumeFloatingPoint<float>();
+ info.mStretchEffect.mappedChildBounds =
+ FloatRect(mFdp.ConsumeFloatingPoint<float>(), mFdp.ConsumeFloatingPoint<float>(),
+ mFdp.ConsumeFloatingPoint<float>(), mFdp.ConsumeFloatingPoint<float>());
+
+ Parcel parcel;
+ info.writeToParcel(&parcel);
+ parcel.setDataPosition(0);
+ info.readFromParcel(&parcel);
+}
+
+void ParcelableFuzzer::invokeOccupancyTracker() {
+ nsecs_t totalTime = mFdp.ConsumeIntegral<uint32_t>();
+ size_t numFrames = mFdp.ConsumeIntegral<size_t>();
+ float occupancyAverage = mFdp.ConsumeFloatingPoint<float>();
+ OccupancyTracker::Segment segment(totalTime, numFrames, occupancyAverage,
+ mFdp.ConsumeBool() /*usedThirdBuffer*/);
+ Parcel parcel;
+ segment.writeToParcel(&parcel);
+ parcel.setDataPosition(0);
+ segment.readFromParcel(&parcel);
+}
+
+void ParcelableFuzzer::invokeStreamSplitter() {
+ sp<IGraphicBufferProducer> producer;
+ sp<IGraphicBufferConsumer> consumer;
+ BufferQueue::createBufferQueue(&producer, &consumer);
+ sp<StreamSplitter> splitter;
+ StreamSplitter::createSplitter(consumer, &splitter);
+ splitter->addOutput(producer);
+ std::string name = mFdp.ConsumeRandomLengthString(kMaxBytes);
+ splitter->setName(String8(name.c_str()));
+}
+
+void ParcelableFuzzer::process() {
+ invokeStreamSplitter();
+ invokeOccupancyTracker();
+ invokeLayerDebugInfo();
+ invokeLayerMetadata();
+ invokeViewSurface();
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+ ParcelableFuzzer libGuiFuzzer(data, size);
+ libGuiFuzzer.process();
+ return 0;
+}
diff --git a/libs/gui/include/gui/BLASTBufferQueue.h b/libs/gui/include/gui/BLASTBufferQueue.h
index 2ed5260..95df811 100644
--- a/libs/gui/include/gui/BLASTBufferQueue.h
+++ b/libs/gui/include/gui/BLASTBufferQueue.h
@@ -233,7 +233,7 @@
// Queues up transactions using this token in SurfaceFlinger. This prevents queued up
// transactions from other parts of the client from blocking this transaction.
- const sp<IBinder> mApplyToken GUARDED_BY(mMutex) = new BBinder();
+ const sp<IBinder> mApplyToken GUARDED_BY(mMutex) = sp<BBinder>::make();
// Guards access to mDequeueTimestamps since we cannot hold to mMutex in onFrameDequeued or
// we will deadlock.
diff --git a/libs/gui/include/gui/LayerState.h b/libs/gui/include/gui/LayerState.h
index f3701e8..759fcc6 100644
--- a/libs/gui/include/gui/LayerState.h
+++ b/libs/gui/include/gui/LayerState.h
@@ -250,7 +250,7 @@
mat4 colorTransform;
std::vector<BlurRegion> blurRegions;
- sp<gui::WindowInfoHandle> windowInfoHandle = new gui::WindowInfoHandle();
+ sp<gui::WindowInfoHandle> windowInfoHandle = sp<gui::WindowInfoHandle>::make();
LayerMetadata metadata;
diff --git a/libs/gui/include/gui/SurfaceComposerClient.h b/libs/gui/include/gui/SurfaceComposerClient.h
index 27a44a4..20c38d8 100644
--- a/libs/gui/include/gui/SurfaceComposerClient.h
+++ b/libs/gui/include/gui/SurfaceComposerClient.h
@@ -341,6 +341,8 @@
// B B'
sp<SurfaceControl> mirrorSurface(SurfaceControl* mirrorFromSurface);
+ sp<SurfaceControl> mirrorDisplay(DisplayId displayId);
+
//! Create a virtual display
static sp<IBinder> createDisplay(const String8& displayName, bool secure);
diff --git a/libs/input/Input.cpp b/libs/input/Input.cpp
index 375b684..155cb04 100644
--- a/libs/input/Input.cpp
+++ b/libs/input/Input.cpp
@@ -90,6 +90,25 @@
}
}
+const char* motionToolTypeToString(int32_t toolType) {
+ switch (toolType) {
+ case AMOTION_EVENT_TOOL_TYPE_UNKNOWN:
+ return "UNKNOWN";
+ case AMOTION_EVENT_TOOL_TYPE_FINGER:
+ return "FINGER";
+ case AMOTION_EVENT_TOOL_TYPE_STYLUS:
+ return "STYLUS";
+ case AMOTION_EVENT_TOOL_TYPE_MOUSE:
+ return "MOUSE";
+ case AMOTION_EVENT_TOOL_TYPE_ERASER:
+ return "ERASER";
+ case AMOTION_EVENT_TOOL_TYPE_PALM:
+ return "PALM";
+ default:
+ return "INVALID";
+ }
+}
+
// --- IdGenerator ---
IdGenerator::IdGenerator(Source source) : mSource(source) {}
diff --git a/libs/input/KeyCharacterMap.cpp b/libs/input/KeyCharacterMap.cpp
index 2039fa6..422e6e0 100644
--- a/libs/input/KeyCharacterMap.cpp
+++ b/libs/input/KeyCharacterMap.cpp
@@ -304,9 +304,8 @@
char16_t KeyCharacterMap::getCharacter(int32_t keyCode, int32_t metaState) const {
char16_t result = 0;
- const Key* key;
- const Behavior* behavior;
- if (getKeyBehavior(keyCode, metaState, &key, &behavior)) {
+ const Behavior* behavior = getKeyBehavior(keyCode, metaState);
+ if (behavior != nullptr) {
result = behavior->character;
}
#if DEBUG_MAPPING
@@ -321,9 +320,8 @@
outFallbackAction->metaState = 0;
bool result = false;
- const Key* key;
- const Behavior* behavior;
- if (getKeyBehavior(keyCode, metaState, &key, &behavior)) {
+ const Behavior* behavior = getKeyBehavior(keyCode, metaState);
+ if (behavior != nullptr) {
if (behavior->fallbackKeyCode) {
outFallbackAction->keyCode = behavior->fallbackKeyCode;
outFallbackAction->metaState = metaState & ~behavior->metaState;
@@ -347,12 +345,12 @@
// Try to find the most general behavior that maps to this character.
// For example, the base key behavior will usually be last in the list.
// However, if we find a perfect meta state match for one behavior then use that one.
- for (const Behavior* behavior = key->firstBehavior; behavior; behavior = behavior->next) {
- if (behavior->character) {
+ for (const Behavior& behavior : key->behaviors) {
+ if (behavior.character) {
for (size_t i = 0; i < numChars; i++) {
- if (behavior->character == chars[i]) {
- result = behavior->character;
- if ((behavior->metaState & metaState) == behavior->metaState) {
+ if (behavior.character == chars[i]) {
+ result = behavior.character;
+ if ((behavior.metaState & metaState) == behavior.metaState) {
goto ExactMatch;
}
break;
@@ -438,9 +436,8 @@
*outKeyCode = keyCode;
*outMetaState = metaState;
- const Key* key;
- const Behavior* behavior;
- if (getKeyBehavior(keyCode, metaState, &key, &behavior)) {
+ const Behavior* behavior = getKeyBehavior(keyCode, metaState);
+ if (behavior != nullptr) {
if (behavior->replacementKeyCode) {
*outKeyCode = behavior->replacementKeyCode;
int32_t newMetaState = metaState & ~behavior->metaState;
@@ -484,21 +481,17 @@
return false;
}
-bool KeyCharacterMap::getKeyBehavior(int32_t keyCode, int32_t metaState,
- const Key** outKey, const Behavior** outBehavior) const {
+const KeyCharacterMap::Behavior* KeyCharacterMap::getKeyBehavior(int32_t keyCode,
+ int32_t metaState) const {
const Key* key;
if (getKey(keyCode, &key)) {
- const Behavior* behavior = key->firstBehavior;
- while (behavior) {
- if (matchesMetaState(metaState, behavior->metaState)) {
- *outKey = key;
- *outBehavior = behavior;
- return true;
+ for (const Behavior& behavior : key->behaviors) {
+ if (matchesMetaState(metaState, behavior.metaState)) {
+ return &behavior;
}
- behavior = behavior->next;
}
}
- return false;
+ return nullptr;
}
bool KeyCharacterMap::matchesMetaState(int32_t eventMetaState, int32_t behaviorMetaState) {
@@ -543,12 +536,12 @@
// Try to find the most general behavior that maps to this character.
// For example, the base key behavior will usually be last in the list.
const Behavior* found = nullptr;
- for (const Behavior* behavior = key->firstBehavior; behavior; behavior = behavior->next) {
- if (behavior->character == ch) {
- found = behavior;
+ for (const Behavior& behavior : key->behaviors) {
+ if (behavior.character == ch) {
+ found = &behavior;
}
}
- if (found) {
+ if (found != nullptr) {
*outKeyCode = mKeys.keyAt(i);
*outMetaState = found->metaState;
return true;
@@ -706,7 +699,6 @@
key->number = number;
map->mKeys.add(keyCode, key);
- Behavior* lastBehavior = nullptr;
while (parcel->readInt32()) {
int32_t metaState = parcel->readInt32();
char16_t character = parcel->readInt32();
@@ -716,17 +708,12 @@
return nullptr;
}
- Behavior* behavior = new Behavior();
- behavior->metaState = metaState;
- behavior->character = character;
- behavior->fallbackKeyCode = fallbackKeyCode;
- behavior->replacementKeyCode = replacementKeyCode;
- if (lastBehavior) {
- lastBehavior->next = behavior;
- } else {
- key->firstBehavior = behavior;
- }
- lastBehavior = behavior;
+ key->behaviors.push_back({
+ .metaState = metaState,
+ .character = character,
+ .fallbackKeyCode = fallbackKeyCode,
+ .replacementKeyCode = replacementKeyCode,
+ });
}
if (parcel->errorCheck()) {
@@ -777,13 +764,12 @@
parcel->writeInt32(keyCode);
parcel->writeInt32(key->label);
parcel->writeInt32(key->number);
- for (const Behavior* behavior = key->firstBehavior; behavior != nullptr;
- behavior = behavior->next) {
+ for (const Behavior& behavior : key->behaviors) {
parcel->writeInt32(1);
- parcel->writeInt32(behavior->metaState);
- parcel->writeInt32(behavior->character);
- parcel->writeInt32(behavior->fallbackKeyCode);
- parcel->writeInt32(behavior->replacementKeyCode);
+ parcel->writeInt32(behavior.metaState);
+ parcel->writeInt32(behavior.character);
+ parcel->writeInt32(behavior.fallbackKeyCode);
+ parcel->writeInt32(behavior.replacementKeyCode);
}
parcel->writeInt32(0);
}
@@ -804,38 +790,10 @@
// --- KeyCharacterMap::Key ---
-KeyCharacterMap::Key::Key() :
- label(0), number(0), firstBehavior(nullptr) {
-}
+KeyCharacterMap::Key::Key() : label(0), number(0) {}
-KeyCharacterMap::Key::Key(const Key& other) :
- label(other.label), number(other.number),
- firstBehavior(other.firstBehavior ? new Behavior(*other.firstBehavior) : nullptr) {
-}
-
-KeyCharacterMap::Key::~Key() {
- Behavior* behavior = firstBehavior;
- while (behavior) {
- Behavior* next = behavior->next;
- delete behavior;
- behavior = next;
- }
-}
-
-
-// --- KeyCharacterMap::Behavior ---
-
-KeyCharacterMap::Behavior::Behavior() :
- next(nullptr), metaState(0), character(0), fallbackKeyCode(0), replacementKeyCode(0) {
-}
-
-KeyCharacterMap::Behavior::Behavior(const Behavior& other) :
- next(other.next ? new Behavior(*other.next) : nullptr),
- metaState(other.metaState), character(other.character),
- fallbackKeyCode(other.fallbackKeyCode),
- replacementKeyCode(other.replacementKeyCode) {
-}
-
+KeyCharacterMap::Key::Key(const Key& other)
+ : label(other.label), number(other.number), behaviors(other.behaviors) {}
// --- KeyCharacterMap::Parser ---
@@ -1213,23 +1171,21 @@
#endif
break;
case PROPERTY_META: {
- for (Behavior* b = key->firstBehavior; b; b = b->next) {
- if (b->metaState == property.metaState) {
+ for (const Behavior& b : key->behaviors) {
+ if (b.metaState == property.metaState) {
ALOGE("%s: Duplicate key behavior for modifier.",
mTokenizer->getLocation().string());
return BAD_VALUE;
}
}
- Behavior* newBehavior = new Behavior(behavior);
- newBehavior->metaState = property.metaState;
- newBehavior->next = key->firstBehavior;
- key->firstBehavior = newBehavior;
-#if DEBUG_PARSER
- ALOGD("Parsed key meta: keyCode=%d, meta=0x%x, char=%d, fallback=%d replace=%d.",
- mKeyCode,
- newBehavior->metaState, newBehavior->character,
- newBehavior->fallbackKeyCode, newBehavior->replacementKeyCode);
-#endif
+ Behavior newBehavior = behavior;
+ newBehavior.metaState = property.metaState;
+ key->behaviors.push_front(newBehavior);
+ ALOGD_IF(DEBUG_PARSER,
+ "Parsed key meta: keyCode=%d, meta=0x%x, char=%d, fallback=%d replace=%d.",
+ mKeyCode, key->behaviors.front().metaState, key->behaviors.front().character,
+ key->behaviors.front().fallbackKeyCode,
+ key->behaviors.front().replacementKeyCode);
break;
}
}
@@ -1242,8 +1198,8 @@
if (!key->number) {
char16_t digit = 0;
char16_t symbol = 0;
- for (Behavior* b = key->firstBehavior; b; b = b->next) {
- char16_t ch = b->character;
+ for (const Behavior& b : key->behaviors) {
+ char16_t ch = b.character;
if (ch) {
if (ch >= '0' && ch <= '9') {
digit = ch;
diff --git a/libs/renderengine/benchmark/RenderEngineBench.cpp b/libs/renderengine/benchmark/RenderEngineBench.cpp
index ead97cf..7bcfff5 100644
--- a/libs/renderengine/benchmark/RenderEngineBench.cpp
+++ b/libs/renderengine/benchmark/RenderEngineBench.cpp
@@ -117,11 +117,12 @@
uint64_t extraUsageFlags = 0,
std::string name = "output") {
return std::make_shared<
- impl::ExternalTexture>(new GraphicBuffer(width, height, HAL_PIXEL_FORMAT_RGBA_8888, 1,
- GRALLOC_USAGE_HW_RENDER |
- GRALLOC_USAGE_HW_TEXTURE |
- extraUsageFlags,
- std::move(name)),
+ impl::ExternalTexture>(sp<GraphicBuffer>::make(width, height,
+ HAL_PIXEL_FORMAT_RGBA_8888, 1u,
+ GRALLOC_USAGE_HW_RENDER |
+ GRALLOC_USAGE_HW_TEXTURE |
+ extraUsageFlags,
+ std::move(name)),
re,
impl::ExternalTexture::Usage::READABLE |
impl::ExternalTexture::Usage::WRITEABLE);
diff --git a/libs/renderengine/gl/GLESRenderEngine.cpp b/libs/renderengine/gl/GLESRenderEngine.cpp
index 6dc01b9..9a5ff54 100644
--- a/libs/renderengine/gl/GLESRenderEngine.cpp
+++ b/libs/renderengine/gl/GLESRenderEngine.cpp
@@ -454,8 +454,9 @@
mImageManager->initThread();
mDrawingBuffer = createFramebuffer();
sp<GraphicBuffer> buf =
- new GraphicBuffer(1, 1, PIXEL_FORMAT_RGBA_8888, 1,
- GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE, "placeholder");
+ sp<GraphicBuffer>::make(1, 1, PIXEL_FORMAT_RGBA_8888, 1,
+ GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE,
+ "placeholder");
const status_t err = buf->initCheck();
if (err != OK) {
diff --git a/libs/renderengine/skia/Cache.cpp b/libs/renderengine/skia/Cache.cpp
index c39f0a9..f6b9183 100644
--- a/libs/renderengine/skia/Cache.cpp
+++ b/libs/renderengine/skia/Cache.cpp
@@ -364,8 +364,8 @@
const int64_t usage = GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
sp<GraphicBuffer> dstBuffer =
- new GraphicBuffer(displayRect.width(), displayRect.height(), PIXEL_FORMAT_RGBA_8888,
- 1, usage, "primeShaderCache_dst");
+ sp<GraphicBuffer>::make(displayRect.width(), displayRect.height(),
+ PIXEL_FORMAT_RGBA_8888, 1, usage, "primeShaderCache_dst");
const auto dstTexture =
std::make_shared<impl::ExternalTexture>(dstBuffer, *renderengine,
@@ -375,8 +375,8 @@
// something, but the details are not important. Make use of the shadow layer drawing step
// to populate it.
sp<GraphicBuffer> srcBuffer =
- new GraphicBuffer(displayRect.width(), displayRect.height(), PIXEL_FORMAT_RGBA_8888,
- 1, usage, "drawImageLayer_src");
+ sp<GraphicBuffer>::make(displayRect.width(), displayRect.height(),
+ PIXEL_FORMAT_RGBA_8888, 1, usage, "drawImageLayer_src");
const auto srcTexture = std::make_shared<
impl::ExternalTexture>(srcBuffer, *renderengine,
@@ -398,8 +398,9 @@
// GRALLOC_USAGE_HW_TEXTURE should be the same as AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE.
const int64_t usageExternal = GRALLOC_USAGE_HW_TEXTURE;
sp<GraphicBuffer> externalBuffer =
- new GraphicBuffer(displayRect.width(), displayRect.height(), PIXEL_FORMAT_RGBA_8888,
- 1, usageExternal, "primeShaderCache_external");
+ sp<GraphicBuffer>::make(displayRect.width(), displayRect.height(),
+ PIXEL_FORMAT_RGBA_8888, 1, usageExternal,
+ "primeShaderCache_external");
const auto externalTexture =
std::make_shared<impl::ExternalTexture>(externalBuffer, *renderengine,
impl::ExternalTexture::Usage::READABLE);
@@ -409,8 +410,9 @@
// Another external texture with a different pixel format triggers useIsOpaqueWorkaround.
// It doesn't have to be f16, but it can't be the usual 8888.
sp<GraphicBuffer> f16ExternalBuffer =
- new GraphicBuffer(displayRect.width(), displayRect.height(), PIXEL_FORMAT_RGBA_FP16,
- 1, usageExternal, "primeShaderCache_external_f16");
+ sp<GraphicBuffer>::make(displayRect.width(), displayRect.height(),
+ PIXEL_FORMAT_RGBA_FP16, 1, usageExternal,
+ "primeShaderCache_external_f16");
// The F16 texture may not be usable on all devices, so check first that it was created.
status_t error = f16ExternalBuffer->initCheck();
if (!error) {
diff --git a/libs/renderengine/tests/RenderEngineTest.cpp b/libs/renderengine/tests/RenderEngineTest.cpp
index f289730..d23063c 100644
--- a/libs/renderengine/tests/RenderEngineTest.cpp
+++ b/libs/renderengine/tests/RenderEngineTest.cpp
@@ -232,14 +232,14 @@
std::shared_ptr<renderengine::ExternalTexture> allocateDefaultBuffer() {
return std::make_shared<
renderengine::impl::
- ExternalTexture>(new GraphicBuffer(DEFAULT_DISPLAY_WIDTH,
- DEFAULT_DISPLAY_HEIGHT,
- HAL_PIXEL_FORMAT_RGBA_8888, 1,
- GRALLOC_USAGE_SW_READ_OFTEN |
- GRALLOC_USAGE_SW_WRITE_OFTEN |
- GRALLOC_USAGE_HW_RENDER |
- GRALLOC_USAGE_HW_TEXTURE,
- "output"),
+ ExternalTexture>(sp<GraphicBuffer>::
+ make(DEFAULT_DISPLAY_WIDTH, DEFAULT_DISPLAY_HEIGHT,
+ HAL_PIXEL_FORMAT_RGBA_8888, 1,
+ GRALLOC_USAGE_SW_READ_OFTEN |
+ GRALLOC_USAGE_SW_WRITE_OFTEN |
+ GRALLOC_USAGE_HW_RENDER |
+ GRALLOC_USAGE_HW_TEXTURE,
+ "output"),
*mRE,
renderengine::impl::ExternalTexture::Usage::READABLE |
renderengine::impl::ExternalTexture::Usage::
@@ -251,12 +251,12 @@
uint32_t height) {
return std::make_shared<
renderengine::impl::
- ExternalTexture>(new GraphicBuffer(width, height,
- HAL_PIXEL_FORMAT_RGBA_8888, 1,
- GRALLOC_USAGE_SW_READ_OFTEN |
- GRALLOC_USAGE_SW_WRITE_OFTEN |
- GRALLOC_USAGE_HW_TEXTURE,
- "input"),
+ ExternalTexture>(sp<GraphicBuffer>::
+ make(width, height, HAL_PIXEL_FORMAT_RGBA_8888, 1,
+ GRALLOC_USAGE_SW_READ_OFTEN |
+ GRALLOC_USAGE_SW_WRITE_OFTEN |
+ GRALLOC_USAGE_HW_TEXTURE,
+ "input"),
*mRE,
renderengine::impl::ExternalTexture::Usage::READABLE |
renderengine::impl::ExternalTexture::Usage::
@@ -285,10 +285,12 @@
}
std::shared_ptr<renderengine::ExternalTexture> allocateR8Buffer(int width, int height) {
- auto buffer = new GraphicBuffer(width, height, android::PIXEL_FORMAT_R_8, 1,
- GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
- GRALLOC_USAGE_HW_TEXTURE,
- "r8");
+ const auto kUsageFlags =
+ static_cast<uint64_t>(GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
+ GRALLOC_USAGE_HW_TEXTURE);
+ auto buffer =
+ sp<GraphicBuffer>::make(static_cast<uint32_t>(width), static_cast<uint32_t>(height),
+ android::PIXEL_FORMAT_R_8, 1u, kUsageFlags, "r8");
if (buffer->initCheck() != 0) {
// Devices are not required to support R8.
return nullptr;
@@ -1496,13 +1498,13 @@
auto buf = std::make_shared<
renderengine::impl::
- ExternalTexture>(new GraphicBuffer(kGreyLevels, 1, HAL_PIXEL_FORMAT_RGBA_8888,
- 1,
- GRALLOC_USAGE_SW_READ_OFTEN |
- GRALLOC_USAGE_SW_WRITE_OFTEN |
- GRALLOC_USAGE_HW_RENDER |
- GRALLOC_USAGE_HW_TEXTURE,
- "input"),
+ ExternalTexture>(sp<GraphicBuffer>::make(kGreyLevels, 1,
+ HAL_PIXEL_FORMAT_RGBA_8888, 1,
+ GRALLOC_USAGE_SW_READ_OFTEN |
+ GRALLOC_USAGE_SW_WRITE_OFTEN |
+ GRALLOC_USAGE_HW_RENDER |
+ GRALLOC_USAGE_HW_TEXTURE,
+ "input"),
*mRE,
renderengine::impl::ExternalTexture::Usage::READABLE |
renderengine::impl::ExternalTexture::Usage::WRITEABLE);
@@ -1529,13 +1531,13 @@
mBuffer = std::make_shared<
renderengine::impl::
- ExternalTexture>(new GraphicBuffer(kGreyLevels, 1, HAL_PIXEL_FORMAT_RGBA_8888,
- 1,
- GRALLOC_USAGE_SW_READ_OFTEN |
- GRALLOC_USAGE_SW_WRITE_OFTEN |
- GRALLOC_USAGE_HW_RENDER |
- GRALLOC_USAGE_HW_TEXTURE,
- "output"),
+ ExternalTexture>(sp<GraphicBuffer>::make(kGreyLevels, 1,
+ HAL_PIXEL_FORMAT_RGBA_8888, 1,
+ GRALLOC_USAGE_SW_READ_OFTEN |
+ GRALLOC_USAGE_SW_WRITE_OFTEN |
+ GRALLOC_USAGE_HW_RENDER |
+ GRALLOC_USAGE_HW_TEXTURE,
+ "output"),
*mRE,
renderengine::impl::ExternalTexture::Usage::READABLE |
renderengine::impl::ExternalTexture::Usage::WRITEABLE);
diff --git a/libs/renderengine/tests/RenderEngineThreadedTest.cpp b/libs/renderengine/tests/RenderEngineThreadedTest.cpp
index 9685189..909ded3 100644
--- a/libs/renderengine/tests/RenderEngineThreadedTest.cpp
+++ b/libs/renderengine/tests/RenderEngineThreadedTest.cpp
@@ -176,7 +176,7 @@
std::vector<renderengine::LayerSettings> layers;
std::shared_ptr<renderengine::ExternalTexture> buffer = std::make_shared<
renderengine::impl::
- ExternalTexture>(new GraphicBuffer(), *mRenderEngine,
+ ExternalTexture>(sp<GraphicBuffer>::make(), *mRenderEngine,
renderengine::impl::ExternalTexture::Usage::READABLE |
renderengine::impl::ExternalTexture::Usage::WRITEABLE);
diff --git a/libs/sensor/fuzz/bittube_fuzzer/Android.bp b/libs/sensor/fuzz/bittube_fuzzer/Android.bp
new file mode 100644
index 0000000..7af22cc
--- /dev/null
+++ b/libs/sensor/fuzz/bittube_fuzzer/Android.bp
@@ -0,0 +1,51 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2022 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.
+ *
+ *****************************************************************************
+ */
+package {
+ // See: http://go/android-license-faq
+ // A large-scale-change added 'default_applicable_licenses' to import
+ // all of the 'license_kinds' from "frameworks_native_license"
+ // to get the below license kinds:
+ // SPDX-license-identifier-Apache-2.0
+ default_applicable_licenses: ["frameworks_native_license"],
+}
+
+cc_fuzz {
+ name: "bittube_fuzzer",
+ srcs: [
+ "bittube_fuzzer.cpp",
+ ],
+ static_libs: [
+ ],
+ shared_libs: [
+ "libsensor",
+ "libbinder",
+ "libcutils",
+ "libutils",
+ "liblog",
+ "libhardware",
+ "libpermission",
+ ],
+ export_shared_lib_headers: [
+ "libbinder",
+ "libpermission",
+ "libhardware",
+ ],
+ header_libs: [
+ ],
+}
diff --git a/libs/sensor/fuzz/bittube_fuzzer/bittube_fuzzer.cpp b/libs/sensor/fuzz/bittube_fuzzer/bittube_fuzzer.cpp
new file mode 100644
index 0000000..6f10a67
--- /dev/null
+++ b/libs/sensor/fuzz/bittube_fuzzer/bittube_fuzzer.cpp
@@ -0,0 +1,37 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2022 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 <fuzzer/FuzzedDataProvider.h>
+
+#include <sensor/BitTube.h>
+#include <binder/Parcel.h>
+using namespace android;
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+ FuzzedDataProvider fdp(data, size);
+ BitTube bittube(size);
+ Parcel parcel[5];
+ bittube.writeToParcel(parcel);
+ sp<BitTube> tube(new BitTube(size));
+ bittube.sendObjects<uint8_t>(tube, data, size);
+ uint8_t recvData[size];
+ for (int i = 0; i < size; i++) recvData[i] = fdp.ConsumeIntegral<uint8_t>();
+ bittube.recvObjects<uint8_t>(tube, recvData, size);
+
+ return 0;
+}
diff --git a/services/audiomanager/IAudioManager.cpp b/services/audiomanager/IAudioManager.cpp
index 700074a..3ef5049 100644
--- a/services/audiomanager/IAudioManager.cpp
+++ b/services/audiomanager/IAudioManager.cpp
@@ -141,6 +141,17 @@
data.writeInt32((int32_t) sessionId);
return remote()->transact(PLAYER_SESSION_ID, data, &reply, IBinder::FLAG_ONEWAY);
}
+
+ virtual status_t portEvent(audio_port_handle_t portId, player_state_t event,
+ const std::unique_ptr<os::PersistableBundle>& extras) {
+ Parcel data, reply;
+ data.writeInterfaceToken(IAudioManager::getInterfaceDescriptor());
+ data.writeInt32((int32_t) portId);
+ data.writeInt32((int32_t) event);
+ // TODO: replace PersistableBundle with own struct
+ data.writeNullableParcelable(extras);
+ return remote()->transact(PORT_EVENT, data, &reply, IBinder::FLAG_ONEWAY);
+ }
};
IMPLEMENT_META_INTERFACE(AudioManager, "android.media.IAudioService");
diff --git a/services/inputflinger/Android.bp b/services/inputflinger/Android.bp
index 554514d..29a0e4f 100644
--- a/services/inputflinger/Android.bp
+++ b/services/inputflinger/Android.bp
@@ -38,6 +38,7 @@
"-Wshadow",
"-Wshadow-field-in-constructor-modified",
"-Wshadow-uncaptured-local",
+ "-DANDROID_UTILS_REF_BASE_DISABLE_IMPLICIT_CONSTRUCTION",
],
sanitize: {
misc_undefined: ["bounds"],
@@ -56,7 +57,7 @@
filegroup {
name: "libinputflinger_sources",
srcs: [
- "InputClassifier.cpp",
+ "InputProcessor.cpp",
"InputCommonConverter.cpp",
"PreferStylusOverTouchBlocker.cpp",
"UnwantedInteractionBlocker.cpp",
@@ -189,6 +190,7 @@
"libinputservice_test",
"Bug-115739809",
"StructLayout_test",
+ "inputflinger_latencytracker_fuzzer",
// Java/Kotlin targets
"CtsWindowManagerDeviceTestCases",
diff --git a/services/inputflinger/InputListener.cpp b/services/inputflinger/InputListener.cpp
index 2a3924b..dce327e 100644
--- a/services/inputflinger/InputListener.cpp
+++ b/services/inputflinger/InputListener.cpp
@@ -196,9 +196,20 @@
}
coords += StringPrintf("{%" PRIu32 ": ", i);
coords +=
- StringPrintf("id=%" PRIu32 " x=%.1f y=%.1f, pressure=%.1f", pointerProperties[i].id,
+ StringPrintf("id=%" PRIu32 " x=%.1f y=%.1f pressure=%.1f", pointerProperties[i].id,
pointerCoords[i].getX(), pointerCoords[i].getY(),
pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
+ const int32_t toolType = pointerProperties[i].toolType;
+ if (toolType != AMOTION_EVENT_TOOL_TYPE_FINGER) {
+ coords += StringPrintf(" toolType=%s", motionToolTypeToString(toolType));
+ }
+ const float major = pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR);
+ const float minor = pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR);
+ const float orientation = pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION);
+ if (major != 0 || minor != 0) {
+ coords += StringPrintf(" major=%.1f minor=%.1f orientation=%.1f", major, minor,
+ orientation);
+ }
coords += "}";
}
return StringPrintf("NotifyMotionArgs(id=%" PRId32 ", eventTime=%" PRId64 ", deviceId=%" PRId32
diff --git a/services/inputflinger/InputManager.cpp b/services/inputflinger/InputManager.cpp
index 9767cd9..9182503 100644
--- a/services/inputflinger/InputManager.cpp
+++ b/services/inputflinger/InputManager.cpp
@@ -55,14 +55,14 @@
/**
* The event flow is via the "InputListener" interface, as follows:
- * InputReader -> UnwantedInteractionBlocker -> InputClassifier -> InputDispatcher
+ * InputReader -> UnwantedInteractionBlocker -> InputProcessor -> InputDispatcher
*/
InputManager::InputManager(
const sp<InputReaderPolicyInterface>& readerPolicy,
const sp<InputDispatcherPolicyInterface>& dispatcherPolicy) {
mDispatcher = createInputDispatcher(dispatcherPolicy);
- mClassifier = std::make_unique<InputClassifier>(*mDispatcher);
- mBlocker = std::make_unique<UnwantedInteractionBlocker>(*mClassifier);
+ mProcessor = std::make_unique<InputProcessor>(*mDispatcher);
+ mBlocker = std::make_unique<UnwantedInteractionBlocker>(*mProcessor);
mReader = createInputReader(readerPolicy, *mBlocker);
}
@@ -110,12 +110,12 @@
return *mReader;
}
-UnwantedInteractionBlockerInterface& InputManager::getUnwantedInteractionBlocker() {
+UnwantedInteractionBlockerInterface& InputManager::getBlocker() {
return *mBlocker;
}
-InputClassifierInterface& InputManager::getClassifier() {
- return *mClassifier;
+InputProcessorInterface& InputManager::getProcessor() {
+ return *mProcessor;
}
InputDispatcherInterface& InputManager::getDispatcher() {
@@ -125,7 +125,7 @@
void InputManager::monitor() {
mReader->monitor();
mBlocker->monitor();
- mClassifier->monitor();
+ mProcessor->monitor();
mDispatcher->monitor();
}
diff --git a/services/inputflinger/InputManager.h b/services/inputflinger/InputManager.h
index 8aad35b..b40ab7f 100644
--- a/services/inputflinger/InputManager.h
+++ b/services/inputflinger/InputManager.h
@@ -21,7 +21,7 @@
* Native input manager.
*/
-#include "InputClassifier.h"
+#include "InputProcessor.h"
#include "InputReaderBase.h"
#include "include/UnwantedInteractionBlockerInterface.h"
@@ -52,10 +52,11 @@
* this could be a palm on the screen. This stage would alter the event stream to remove either
* partially (some of the pointers) or fully (all touches) the unwanted interaction. The events
* are processed on the InputReader thread, without any additional queue. The events are then
- * posted to the queue managed by the InputClassifier.
- * 3. The InputClassifier class starts a thread to communicate with the device-specific
- * classifiers. It then waits on the queue of events from UnwantedInteractionBlocker, applies
- * a classification to them, and queues them for the InputDispatcher.
+ * posted to the queue managed by the InputProcessor.
+ * 3. The InputProcessor class starts a thread to communicate with the device-specific
+ * IInputProcessor HAL. It then waits on the queue of events from UnwantedInteractionBlocker,
+ * processes the events (for example, applies a classification to the events), and queues them
+ * for the InputDispatcher.
* 4. The InputDispatcher class starts a thread that waits for new events on the
* previous queue and asynchronously dispatches them to applications.
*
@@ -83,10 +84,10 @@
virtual InputReaderInterface& getReader() = 0;
/* Gets the unwanted interaction blocker. */
- virtual UnwantedInteractionBlockerInterface& getUnwantedInteractionBlocker() = 0;
+ virtual UnwantedInteractionBlockerInterface& getBlocker() = 0;
- /* Gets the input classifier */
- virtual InputClassifierInterface& getClassifier() = 0;
+ /* Gets the input processor */
+ virtual InputProcessorInterface& getProcessor() = 0;
/* Gets the input dispatcher. */
virtual InputDispatcherInterface& getDispatcher() = 0;
@@ -108,8 +109,8 @@
status_t stop() override;
InputReaderInterface& getReader() override;
- UnwantedInteractionBlockerInterface& getUnwantedInteractionBlocker() override;
- InputClassifierInterface& getClassifier() override;
+ UnwantedInteractionBlockerInterface& getBlocker() override;
+ InputProcessorInterface& getProcessor() override;
InputDispatcherInterface& getDispatcher() override;
void monitor() override;
@@ -123,7 +124,7 @@
std::unique_ptr<UnwantedInteractionBlockerInterface> mBlocker;
- std::unique_ptr<InputClassifierInterface> mClassifier;
+ std::unique_ptr<InputProcessorInterface> mProcessor;
std::unique_ptr<InputDispatcherInterface> mDispatcher;
};
diff --git a/services/inputflinger/InputClassifier.cpp b/services/inputflinger/InputProcessor.cpp
similarity index 85%
rename from services/inputflinger/InputClassifier.cpp
rename to services/inputflinger/InputProcessor.cpp
index 21695c3..0749441 100644
--- a/services/inputflinger/InputClassifier.cpp
+++ b/services/inputflinger/InputProcessor.cpp
@@ -14,9 +14,9 @@
* limitations under the License.
*/
-#define LOG_TAG "InputClassifier"
+#define LOG_TAG "InputProcessor"
-#include "InputClassifier.h"
+#include "InputProcessor.h"
#include "InputCommonConverter.h"
#include <android-base/stringprintf.h>
@@ -27,7 +27,7 @@
#include <algorithm>
#include <cmath>
#if defined(__linux__)
- #include <pthread.h>
+#include <pthread.h>
#endif
#include <unordered_set>
@@ -44,10 +44,10 @@
namespace android {
-//Max number of elements to store in mEvents.
+// Max number of elements to store in mEvents.
static constexpr size_t MAX_EVENTS = 5;
-template<class K, class V>
+template <class K, class V>
static V getValueForKey(const std::unordered_map<K, V>& map, K key, V defaultValue) {
auto it = map.find(key);
if (it == map.end()) {
@@ -123,15 +123,15 @@
// --- ClassifierEvent ---
-ClassifierEvent::ClassifierEvent(std::unique_ptr<NotifyMotionArgs> args) :
- type(ClassifierEventType::MOTION), args(std::move(args)) { };
-ClassifierEvent::ClassifierEvent(std::unique_ptr<NotifyDeviceResetArgs> args) :
- type(ClassifierEventType::DEVICE_RESET), args(std::move(args)) { };
-ClassifierEvent::ClassifierEvent(ClassifierEventType type, std::unique_ptr<NotifyArgs> args) :
- type(type), args(std::move(args)) { };
+ClassifierEvent::ClassifierEvent(std::unique_ptr<NotifyMotionArgs> args)
+ : type(ClassifierEventType::MOTION), args(std::move(args)){};
+ClassifierEvent::ClassifierEvent(std::unique_ptr<NotifyDeviceResetArgs> args)
+ : type(ClassifierEventType::DEVICE_RESET), args(std::move(args)){};
+ClassifierEvent::ClassifierEvent(ClassifierEventType type, std::unique_ptr<NotifyArgs> args)
+ : type(type), args(std::move(args)){};
-ClassifierEvent::ClassifierEvent(ClassifierEvent&& other) :
- type(other.type), args(std::move(other.args)) { };
+ClassifierEvent::ClassifierEvent(ClassifierEvent&& other)
+ : type(other.type), args(std::move(other.args)){};
ClassifierEvent& ClassifierEvent::operator=(ClassifierEvent&& other) {
type = other.type;
@@ -180,7 +180,7 @@
mHalThread = std::thread(&MotionClassifier::processEvents, this);
#if defined(__linux__)
// Set the thread name for debugging
- pthread_setname_np(mHalThread.native_handle(), "InputClassifier");
+ pthread_setname_np(mHalThread.native_handle(), "InputProcessor");
#endif
}
@@ -198,7 +198,7 @@
/**
* Obtain the classification from the HAL for a given MotionEvent.
- * Should only be called from the InputClassifier thread (mHalThread).
+ * Should only be called from the InputProcessor thread (mHalThread).
* Should not be called from the thread that notifyMotion runs on.
*
* There is no way to provide a timeout for a HAL call. So if the HAL takes too long
@@ -239,8 +239,8 @@
}
}
if (!halResponseOk) {
- ALOGE("Error communicating with InputClassifier HAL. "
- "Exiting MotionClassifier HAL thread");
+ ALOGE("Error communicating with InputProcessor HAL. "
+ "Exiting MotionClassifier HAL thread");
clearClassifications();
return;
}
@@ -262,14 +262,14 @@
}
void MotionClassifier::updateClassification(int32_t deviceId, nsecs_t eventTime,
- MotionClassification classification) {
+ MotionClassification classification) {
std::scoped_lock lock(mLock);
const nsecs_t lastDownTime = getValueForKey(mLastDownTimes, deviceId, static_cast<nsecs_t>(0));
if (eventTime < lastDownTime) {
// HAL just finished processing an event that belonged to an earlier gesture,
// but new gesture is already in progress. Drop this classification.
ALOGW("Received late classification. Late by at least %" PRId64 " ms.",
- nanoseconds_to_milliseconds(lastDownTime - eventTime));
+ nanoseconds_to_milliseconds(lastDownTime - eventTime));
return;
}
mClassifications[deviceId] = classification;
@@ -319,14 +319,14 @@
/**
* Per-device reset. Clear the outstanding events that are going to be sent to HAL.
- * Request InputClassifier thread to call resetDevice for this particular device.
+ * Request InputProcessor thread to call resetDevice for this particular device.
*/
void MotionClassifier::reset(const NotifyDeviceResetArgs& args) {
int32_t deviceId = args.deviceId;
// Clear the pending events right away, to avoid unnecessary work done by the HAL.
mEvents.erase([deviceId](const ClassifierEvent& event) {
- std::optional<int32_t> eventDeviceId = event.getDeviceId();
- return eventDeviceId && (*eventDeviceId == deviceId);
+ std::optional<int32_t> eventDeviceId = event.getDeviceId();
+ return eventDeviceId && (*eventDeviceId == deviceId);
});
enqueueEvent(std::make_unique<NotifyDeviceResetArgs>(args));
}
@@ -334,23 +334,22 @@
void MotionClassifier::dump(std::string& dump) {
std::scoped_lock lock(mLock);
dump += StringPrintf(INDENT2 "mService connected: %s\n", mService ? "true" : "false");
- dump += StringPrintf(INDENT2 "mEvents: %zu element(s) (max=%zu)\n",
- mEvents.size(), MAX_EVENTS);
+ dump += StringPrintf(INDENT2 "mEvents: %zu element(s) (max=%zu)\n", mEvents.size(), MAX_EVENTS);
dump += INDENT2 "mClassifications, mLastDownTimes:\n";
dump += INDENT3 "Device Id\tClassification\tLast down time";
// Combine mClassifications and mLastDownTimes into a single table.
// Create a superset of device ids.
std::unordered_set<int32_t> deviceIds;
std::for_each(mClassifications.begin(), mClassifications.end(),
- [&deviceIds](auto pair){ deviceIds.insert(pair.first); });
+ [&deviceIds](auto pair) { deviceIds.insert(pair.first); });
std::for_each(mLastDownTimes.begin(), mLastDownTimes.end(),
- [&deviceIds](auto pair){ deviceIds.insert(pair.first); });
- for(int32_t deviceId : deviceIds) {
+ [&deviceIds](auto pair) { deviceIds.insert(pair.first); });
+ for (int32_t deviceId : deviceIds) {
const MotionClassification classification =
getValueForKey(mClassifications, deviceId, MotionClassification::NONE);
const nsecs_t downTime = getValueForKey(mLastDownTimes, deviceId, static_cast<nsecs_t>(0));
- dump += StringPrintf("\n" INDENT4 "%" PRId32 "\t%s\t%" PRId64,
- deviceId, motionClassificationToString(classification), downTime);
+ dump += StringPrintf("\n" INDENT4 "%" PRId32 "\t%s\t%" PRId64, deviceId,
+ motionClassificationToString(classification), downTime);
}
}
@@ -366,20 +365,20 @@
}
}
-// --- InputClassifier ---
+// --- InputProcessor ---
-InputClassifier::InputClassifier(InputListenerInterface& listener) : mQueuedListener(listener) {}
+InputProcessor::InputProcessor(InputListenerInterface& listener) : mQueuedListener(listener) {}
-void InputClassifier::onBinderDied(void* cookie) {
- InputClassifier* classifier = static_cast<InputClassifier*>(cookie);
- if (classifier == nullptr) {
+void InputProcessor::onBinderDied(void* cookie) {
+ InputProcessor* processor = static_cast<InputProcessor*>(cookie);
+ if (processor == nullptr) {
LOG_ALWAYS_FATAL("Cookie is not valid");
return;
}
- classifier->setMotionClassifierEnabled(false);
+ processor->setMotionClassifierEnabled(false);
}
-void InputClassifier::setMotionClassifierEnabled(bool enabled) {
+void InputProcessor::setMotionClassifierEnabled(bool enabled) {
std::scoped_lock lock(mLock);
if (enabled) {
ALOGI("Enabling motion classifier");
@@ -392,7 +391,7 @@
* and we can't continue because 'mInitializeMotionClassifier' will block in its
* destructor.
*/
- LOG_ALWAYS_FATAL("The thread to load IInputClassifier is stuck!");
+ LOG_ALWAYS_FATAL("The thread to load IInputProcessor is stuck!");
}
}
mInitializeMotionClassifier = std::async(std::launch::async, [this] {
@@ -416,19 +415,19 @@
}
}
-void InputClassifier::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
+void InputProcessor::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
// pass through
mQueuedListener.notifyConfigurationChanged(args);
mQueuedListener.flush();
}
-void InputClassifier::notifyKey(const NotifyKeyArgs* args) {
+void InputProcessor::notifyKey(const NotifyKeyArgs* args) {
// pass through
mQueuedListener.notifyKey(args);
mQueuedListener.flush();
}
-void InputClassifier::notifyMotion(const NotifyMotionArgs* args) {
+void InputProcessor::notifyMotion(const NotifyMotionArgs* args) {
{ // acquire lock
std::scoped_lock lock(mLock);
// MotionClassifier is only used for touch events, for now
@@ -444,25 +443,25 @@
mQueuedListener.flush();
}
-void InputClassifier::notifySensor(const NotifySensorArgs* args) {
+void InputProcessor::notifySensor(const NotifySensorArgs* args) {
// pass through
mQueuedListener.notifySensor(args);
mQueuedListener.flush();
}
-void InputClassifier::notifyVibratorState(const NotifyVibratorStateArgs* args) {
+void InputProcessor::notifyVibratorState(const NotifyVibratorStateArgs* args) {
// pass through
mQueuedListener.notifyVibratorState(args);
mQueuedListener.flush();
}
-void InputClassifier::notifySwitch(const NotifySwitchArgs* args) {
+void InputProcessor::notifySwitch(const NotifySwitchArgs* args) {
// pass through
mQueuedListener.notifySwitch(args);
mQueuedListener.flush();
}
-void InputClassifier::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
+void InputProcessor::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
{ // acquire lock
std::scoped_lock lock(mLock);
if (mMotionClassifier) {
@@ -475,13 +474,13 @@
mQueuedListener.flush();
}
-void InputClassifier::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
+void InputProcessor::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
// pass through
mQueuedListener.notifyPointerCaptureChanged(args);
mQueuedListener.flush();
}
-void InputClassifier::setMotionClassifierLocked(
+void InputProcessor::setMotionClassifierLocked(
std::unique_ptr<MotionClassifierInterface> motionClassifier) REQUIRES(mLock) {
if (motionClassifier == nullptr) {
// Destroy the ScopedDeathRecipient object, which will cause it to unlinkToDeath.
@@ -491,9 +490,9 @@
mMotionClassifier = std::move(motionClassifier);
}
-void InputClassifier::dump(std::string& dump) {
+void InputProcessor::dump(std::string& dump) {
std::scoped_lock lock(mLock);
- dump += "Input Classifier State:\n";
+ dump += "Input Processor State:\n";
dump += INDENT1 "Motion Classifier:\n";
if (mMotionClassifier) {
mMotionClassifier->dump(dump);
@@ -503,12 +502,11 @@
dump += "\n";
}
-void InputClassifier::monitor() {
+void InputProcessor::monitor() {
std::scoped_lock lock(mLock);
if (mMotionClassifier) mMotionClassifier->monitor();
}
-InputClassifier::~InputClassifier() {
-}
+InputProcessor::~InputProcessor() {}
} // namespace android
diff --git a/services/inputflinger/InputClassifier.h b/services/inputflinger/InputProcessor.h
similarity index 90%
rename from services/inputflinger/InputClassifier.h
rename to services/inputflinger/InputProcessor.h
index 9b31a3c..261e012 100644
--- a/services/inputflinger/InputClassifier.h
+++ b/services/inputflinger/InputProcessor.h
@@ -61,8 +61,8 @@
*/
class MotionClassifierInterface {
public:
- MotionClassifierInterface() { }
- virtual ~MotionClassifierInterface() { }
+ MotionClassifierInterface() {}
+ virtual ~MotionClassifierInterface() {}
/**
* Based on the motion event described by NotifyMotionArgs,
* provide a MotionClassification for the current gesture.
@@ -92,7 +92,7 @@
* Base interface for an InputListener stage.
* Provides classification to events.
*/
-class InputClassifierInterface : public InputListenerInterface {
+class InputProcessorInterface : public InputListenerInterface {
public:
virtual void setMotionClassifierEnabled(bool enabled) = 0;
/**
@@ -104,8 +104,8 @@
/** Called by the heartbeat to ensure that the classifier has not deadlocked. */
virtual void monitor() = 0;
- InputClassifierInterface() { }
- virtual ~InputClassifierInterface() { }
+ InputProcessorInterface() {}
+ virtual ~InputProcessorInterface() {}
};
// --- Implementations ---
@@ -124,10 +124,10 @@
};
/**
- * Implementation of MotionClassifierInterface that calls the InputClassifier HAL
+ * Implementation of MotionClassifierInterface that calls the InputProcessor HAL
* in order to determine the classification for the current gesture.
*
- * The InputClassifier HAL may keep track of the entire gesture in order to determine
+ * The InputProcessor HAL may keep track of the entire gesture in order to determine
* the classification, and may be hardware-specific. It may use the data in
* NotifyMotionArgs::videoFrames field to drive the classification decisions.
* The HAL is called from a separate thread.
@@ -174,20 +174,20 @@
*/
void enqueueEvent(ClassifierEvent&& event);
/**
- * Thread that will communicate with InputClassifier HAL.
- * This should be the only thread that communicates with InputClassifier HAL,
+ * Thread that will communicate with InputProcessor HAL.
+ * This should be the only thread that communicates with InputProcessor HAL,
* because this thread is allowed to block on the HAL calls.
*/
std::thread mHalThread;
/**
- * Process events and call the InputClassifier HAL
+ * Process events and call the InputProcessor HAL
*/
void processEvents();
/**
* Access to the InputProcessor HAL. May be null if init() hasn't completed yet.
* When init() successfully completes, mService is guaranteed to remain non-null and to not
* change its value until MotionClassifier is destroyed.
- * This variable is *not* guarded by mLock in the InputClassifier thread, because
+ * This variable is *not* guarded by mLock in the InputProcessor thread, because
* that thread knows exactly when this variable is initialized.
* When accessed in any other thread, mService is checked for nullness with a lock.
*/
@@ -197,8 +197,8 @@
* Per-device input classifications. Should only be accessed using the
* getClassification / setClassification methods.
*/
- std::unordered_map<int32_t /*deviceId*/, MotionClassification>
- mClassifications GUARDED_BY(mLock);
+ std::unordered_map<int32_t /*deviceId*/, MotionClassification> mClassifications
+ GUARDED_BY(mLock);
/**
* Set the current classification for a given device.
*/
@@ -208,7 +208,7 @@
*/
MotionClassification getClassification(int32_t deviceId);
void updateClassification(int32_t deviceId, nsecs_t eventTime,
- MotionClassification classification);
+ MotionClassification classification);
/**
* Clear all current classifications
*/
@@ -217,7 +217,7 @@
* Per-device times when the last ACTION_DOWN was received.
* Used to reject late classifications that do not belong to the current gesture.
*
- * Accessed indirectly by both InputClassifier thread and the thread that receives notifyMotion.
+ * Accessed indirectly by both InputProcessor thread and the thread that receives notifyMotion.
*/
std::unordered_map<int32_t /*deviceId*/, nsecs_t /*downTime*/> mLastDownTimes GUARDED_BY(mLock);
@@ -226,7 +226,7 @@
void clearDeviceState(int32_t deviceId);
/**
- * Exit the InputClassifier HAL thread.
+ * Exit the InputProcessor HAL thread.
* Useful for tests to ensure proper cleanup.
*/
void requestExit();
@@ -237,14 +237,14 @@
};
/**
- * Implementation of the InputClassifierInterface.
+ * Implementation of the InputProcessorInterface.
* Represents a separate stage of input processing. All of the input events go through this stage.
* Acts as a passthrough for all input events except for motion events.
* The events of motion type are sent to MotionClassifier.
*/
-class InputClassifier : public InputClassifierInterface {
+class InputProcessor : public InputProcessorInterface {
public:
- explicit InputClassifier(InputListenerInterface& listener);
+ explicit InputProcessor(InputListenerInterface& listener);
void notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) override;
void notifyKey(const NotifyKeyArgs* args) override;
@@ -258,7 +258,7 @@
void dump(std::string& dump) override;
void monitor() override;
- ~InputClassifier();
+ ~InputProcessor();
// Called from InputManager
void setMotionClassifierEnabled(bool enabled) override;
diff --git a/services/inputflinger/InputThread.cpp b/services/inputflinger/InputThread.cpp
index b87f7a1..e2e64f9 100644
--- a/services/inputflinger/InputThread.cpp
+++ b/services/inputflinger/InputThread.cpp
@@ -41,7 +41,7 @@
InputThread::InputThread(std::string name, std::function<void()> loop, std::function<void()> wake)
: mName(name), mThreadWake(wake) {
- mThread = new InputThreadImpl(loop);
+ mThread = sp<InputThreadImpl>::make(loop);
mThread->run(mName.c_str(), ANDROID_PRIORITY_URGENT_DISPLAY);
}
diff --git a/services/inputflinger/UnwantedInteractionBlocker.cpp b/services/inputflinger/UnwantedInteractionBlocker.cpp
index a8e495f..4e0f0c3 100644
--- a/services/inputflinger/UnwantedInteractionBlocker.cpp
+++ b/services/inputflinger/UnwantedInteractionBlocker.cpp
@@ -39,6 +39,30 @@
namespace android {
+/**
+ * Log detailed debug messages about each inbound motion event notification to the blocker.
+ * Enable this via "adb shell setprop log.tag.UnwantedInteractionBlockerInboundMotion DEBUG"
+ * (requires restart)
+ */
+const bool DEBUG_INBOUND_MOTION =
+ __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "InboundMotion", ANDROID_LOG_INFO);
+
+/**
+ * Log detailed debug messages about each outbound motion event processed by the blocker.
+ * Enable this via "adb shell setprop log.tag.UnwantedInteractionBlockerOutboundMotion DEBUG"
+ * (requires restart)
+ */
+const bool DEBUG_OUTBOUND_MOTION =
+ __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "OutboundMotion", ANDROID_LOG_INFO);
+
+/**
+ * Log the data sent to the model and received back from the model.
+ * Enable this via "adb shell setprop log.tag.UnwantedInteractionBlockerModel DEBUG"
+ * (requires restart)
+ */
+const bool DEBUG_MODEL =
+ __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Model", ANDROID_LOG_INFO);
+
// Category (=namespace) name for the input settings that are applied at boot time
static const char* INPUT_NATIVE_BOOT = "input_native_boot";
/**
@@ -58,8 +82,7 @@
}
static ::base::TimeTicks toChromeTimestamp(nsecs_t eventTime) {
- return ::base::TimeTicks::UnixEpoch() +
- ::base::Milliseconds(static_cast<float>(ns2ms(eventTime)));
+ return ::base::TimeTicks::UnixEpoch() + ::base::TimeDelta::FromNanosecondsD(eventTime);
}
/**
@@ -69,8 +92,8 @@
static bool isPalmRejectionEnabled() {
std::string value = toLower(
server_configurable_flags::GetServerConfigurableFlag(INPUT_NATIVE_BOOT,
- PALM_REJECTION_ENABLED, "false"));
- if (value == "true" || value == "1") {
+ PALM_REJECTION_ENABLED, "0"));
+ if (value == "1") {
return true;
}
return false;
@@ -310,6 +333,7 @@
}
void UnwantedInteractionBlocker::notifyMotion(const NotifyMotionArgs* args) {
+ ALOGD_IF(DEBUG_INBOUND_MOTION, "%s: %s", __func__, args->dump().c_str());
{ // acquire lock
std::scoped_lock lock(mLock);
const std::vector<NotifyMotionArgs> processedArgs =
@@ -323,17 +347,22 @@
mQueuedListener.flush();
}
+void UnwantedInteractionBlocker::enqueueOutboundMotionLocked(const NotifyMotionArgs& args) {
+ ALOGD_IF(DEBUG_OUTBOUND_MOTION, "%s: %s", __func__, args.dump().c_str());
+ mQueuedListener.notifyMotion(&args);
+}
+
void UnwantedInteractionBlocker::notifyMotionLocked(const NotifyMotionArgs* args) {
auto it = mPalmRejectors.find(args->deviceId);
const bool sendToPalmRejector = it != mPalmRejectors.end() && isFromTouchscreen(args->source);
if (!sendToPalmRejector) {
- mQueuedListener.notifyMotion(args);
+ enqueueOutboundMotionLocked(*args);
return;
}
std::vector<NotifyMotionArgs> processedArgs = it->second.processMotion(*args);
for (const NotifyMotionArgs& loopArgs : processedArgs) {
- mQueuedListener.notifyMotion(&loopArgs);
+ enqueueOutboundMotionLocked(loopArgs);
}
}
@@ -617,8 +646,18 @@
getTouches(args, mDeviceInfo, oldSlotState, mSlotState);
::base::TimeTicks chromeTimestamp = toChromeTimestamp(args.eventTime);
+ if (DEBUG_MODEL) {
+ std::stringstream touchesStream;
+ for (const ::ui::InProgressTouchEvdev& touch : touches) {
+ touchesStream << touch.tracking_id << " : " << touch << "\n";
+ }
+ ALOGD("Filter: touches = %s", touchesStream.str().c_str());
+ }
mPalmDetectionFilter->Filter(touches, chromeTimestamp, &slotsToHold, &slotsToSuppress);
+ ALOGD_IF(DEBUG_MODEL, "Response: slotsToHold = %s, slotsToSuppress = %s",
+ slotsToHold.to_string().c_str(), slotsToSuppress.to_string().c_str());
+
// Now that we know which slots should be suppressed, let's convert those to pointer id's.
std::set<int32_t> oldSuppressedIds;
std::swap(oldSuppressedIds, mSuppressedPointerIds);
diff --git a/services/inputflinger/UnwantedInteractionBlocker.h b/services/inputflinger/UnwantedInteractionBlocker.h
index a433764..8ff9658 100644
--- a/services/inputflinger/UnwantedInteractionBlocker.h
+++ b/services/inputflinger/UnwantedInteractionBlocker.h
@@ -101,6 +101,9 @@
std::map<int32_t /*deviceId*/, PalmRejector> mPalmRejectors GUARDED_BY(mLock);
// TODO(b/210159205): delete this when simultaneous stylus and touch is supported
void notifyMotionLocked(const NotifyMotionArgs* args) REQUIRES(mLock);
+
+ // Call this function for outbound events so that they can be logged when logging is enabled.
+ void enqueueOutboundMotionLocked(const NotifyMotionArgs& args) REQUIRES(mLock);
};
class SlotState {
diff --git a/services/inputflinger/benchmarks/InputDispatcher_benchmarks.cpp b/services/inputflinger/benchmarks/InputDispatcher_benchmarks.cpp
index c9ea068..12eeea6 100644
--- a/services/inputflinger/benchmarks/InputDispatcher_benchmarks.cpp
+++ b/services/inputflinger/benchmarks/InputDispatcher_benchmarks.cpp
@@ -260,14 +260,15 @@
static void benchmarkNotifyMotion(benchmark::State& state) {
// Create dispatcher
- sp<FakeInputDispatcherPolicy> fakePolicy = new FakeInputDispatcherPolicy();
+ sp<FakeInputDispatcherPolicy> fakePolicy = sp<FakeInputDispatcherPolicy>::make();
InputDispatcher dispatcher(fakePolicy);
dispatcher.setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
dispatcher.start();
// Create a window that will receive motion events
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
- sp<FakeWindowHandle> window = new FakeWindowHandle(application, dispatcher, "Fake Window");
+ sp<FakeWindowHandle> window =
+ sp<FakeWindowHandle>::make(application, dispatcher, "Fake Window");
dispatcher.setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
@@ -294,14 +295,15 @@
static void benchmarkInjectMotion(benchmark::State& state) {
// Create dispatcher
- sp<FakeInputDispatcherPolicy> fakePolicy = new FakeInputDispatcherPolicy();
+ sp<FakeInputDispatcherPolicy> fakePolicy = sp<FakeInputDispatcherPolicy>::make();
InputDispatcher dispatcher(fakePolicy);
dispatcher.setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
dispatcher.start();
// Create a window that will receive motion events
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
- sp<FakeWindowHandle> window = new FakeWindowHandle(application, dispatcher, "Fake Window");
+ sp<FakeWindowHandle> window =
+ sp<FakeWindowHandle>::make(application, dispatcher, "Fake Window");
dispatcher.setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
@@ -327,14 +329,15 @@
static void benchmarkOnWindowInfosChanged(benchmark::State& state) {
// Create dispatcher
- sp<FakeInputDispatcherPolicy> fakePolicy = new FakeInputDispatcherPolicy();
+ sp<FakeInputDispatcherPolicy> fakePolicy = sp<FakeInputDispatcherPolicy>::make();
InputDispatcher dispatcher(fakePolicy);
dispatcher.setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
dispatcher.start();
// Create a window
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
- sp<FakeWindowHandle> window = new FakeWindowHandle(application, dispatcher, "Fake Window");
+ sp<FakeWindowHandle> window =
+ sp<FakeWindowHandle>::make(application, dispatcher, "Fake Window");
std::vector<gui::WindowInfo> windowInfos{*window->getInfo()};
gui::DisplayInfo info;
diff --git a/services/inputflinger/dispatcher/InputDispatcher.cpp b/services/inputflinger/dispatcher/InputDispatcher.cpp
index 79e9d4b..ff63967 100644
--- a/services/inputflinger/dispatcher/InputDispatcher.cpp
+++ b/services/inputflinger/dispatcher/InputDispatcher.cpp
@@ -555,10 +555,10 @@
mLatencyAggregator(),
mLatencyTracker(&mLatencyAggregator),
kPerDisplayTouchModeEnabled(mPolicy->isPerDisplayTouchModeEnabled()) {
- mLooper = new Looper(false);
+ mLooper = sp<Looper>::make(false);
mReporter = createInputReporter();
- mWindowInfoListener = new DispatcherWindowListener(*this);
+ mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
mKeyRepeatState.lastKeyEntry = nullptr;
@@ -5510,7 +5510,7 @@
const sp<IBinder>& token = serverChannel->getConnectionToken();
int fd = serverChannel->getFd();
sp<Connection> connection =
- new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
+ sp<Connection>::make(std::move(serverChannel), false /*monitor*/, mIdGenerator);
if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
ALOGE("Created a new connection, but the token %p is already known", token.get());
@@ -5520,7 +5520,8 @@
std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
this, std::placeholders::_1, token);
- mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
+ mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
+ nullptr);
} // release lock
// Wake the looper because some connections have changed.
@@ -5546,7 +5547,8 @@
<< " without a specified display.";
}
- sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
+ sp<Connection> connection =
+ sp<Connection>::make(serverChannel, true /*monitor*/, mIdGenerator);
const sp<IBinder>& token = serverChannel->getConnectionToken();
const int fd = serverChannel->getFd();
@@ -5559,7 +5561,8 @@
mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
- mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
+ mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
+ nullptr);
}
// Wake the looper because some connections have changed.
@@ -6367,7 +6370,7 @@
std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
for (const auto& info : windowInfos) {
handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
- handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
+ handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
}
{ // acquire lock
diff --git a/services/inputflinger/reader/EventHub.cpp b/services/inputflinger/reader/EventHub.cpp
index a17d2c0..bfa44ac 100644
--- a/services/inputflinger/reader/EventHub.cpp
+++ b/services/inputflinger/reader/EventHub.cpp
@@ -1310,7 +1310,8 @@
if (!identifier.uniqueId.empty()) {
rawDescriptor += "uniqueId:";
rawDescriptor += identifier.uniqueId;
- } else if (identifier.nonce != 0) {
+ }
+ if (identifier.nonce != 0) {
rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
}
@@ -1338,16 +1339,20 @@
// of Android. In practice we sometimes get devices that cannot be uniquely
// identified. In this case we enforce uniqueness between connected devices.
// Ideally, we also want the descriptor to be short and relatively opaque.
+ // Note that we explicitly do not use the path or location for external devices
+ // as their path or location will change as they are plugged/unplugged or moved
+ // to different ports. We do fallback to using name and location in the case of
+ // internal devices which are detected by the vendor and product being 0 in
+ // generateDescriptor. If two identical descriptors are detected we will fallback
+ // to using a 'nonce' and incrementing it until the new descriptor no longer has
+ // a match with any existing descriptors.
identifier.nonce = 0;
std::string rawDescriptor = generateDescriptor(identifier);
- if (identifier.uniqueId.empty()) {
- // If it didn't have a unique id check for conflicts and enforce
- // uniqueness if necessary.
- while (getDeviceByDescriptorLocked(identifier.descriptor) != nullptr) {
- identifier.nonce++;
- rawDescriptor = generateDescriptor(identifier);
- }
+ // Enforce that the generated descriptor is unique.
+ while (hasDeviceWithDescriptorLocked(identifier.descriptor)) {
+ identifier.nonce++;
+ rawDescriptor = generateDescriptor(identifier);
}
ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
identifier.descriptor.c_str());
@@ -1422,13 +1427,22 @@
return vibrators;
}
-EventHub::Device* EventHub::getDeviceByDescriptorLocked(const std::string& descriptor) const {
- for (const auto& [id, device] : mDevices) {
+/**
+ * Checks both mDevices and mOpeningDevices for a device with the descriptor passed.
+ */
+bool EventHub::hasDeviceWithDescriptorLocked(const std::string& descriptor) const {
+ for (const auto& device : mOpeningDevices) {
if (descriptor == device->identifier.descriptor) {
- return device.get();
+ return true;
}
}
- return nullptr;
+
+ for (const auto& [id, device] : mDevices) {
+ if (descriptor == device->identifier.descriptor) {
+ return true;
+ }
+ }
+ return false;
}
EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
diff --git a/services/inputflinger/reader/InputReader.cpp b/services/inputflinger/reader/InputReader.cpp
index 79901f0..11a2dbe 100644
--- a/services/inputflinger/reader/InputReader.cpp
+++ b/services/inputflinger/reader/InputReader.cpp
@@ -38,6 +38,26 @@
namespace android {
+/**
+ * Determines if the identifiers passed are a sub-devices. Sub-devices are physical devices
+ * that expose multiple input device paths such a keyboard that also has a touchpad input.
+ * These are separate devices with unique descriptors in EventHub, but InputReader should
+ * create a single InputDevice for them.
+ * Sub-devices are detected by the following criteria:
+ * 1. The vendor, product, bus, version, and unique id match
+ * 2. The location matches. The location is used to distinguish a single device with multiple
+ * inputs versus the same device plugged into multiple ports.
+ */
+
+static bool isSubDevice(const InputDeviceIdentifier& identifier1,
+ const InputDeviceIdentifier& identifier2) {
+ return (identifier1.vendor == identifier2.vendor &&
+ identifier1.product == identifier2.product && identifier1.bus == identifier2.bus &&
+ identifier1.version == identifier2.version &&
+ identifier1.uniqueId == identifier2.uniqueId &&
+ identifier1.location == identifier2.location);
+}
+
// --- InputReader ---
InputReader::InputReader(std::shared_ptr<EventHubInterface> eventHub,
@@ -270,8 +290,9 @@
std::shared_ptr<InputDevice> InputReader::createDeviceLocked(
int32_t eventHubId, const InputDeviceIdentifier& identifier) {
auto deviceIt = std::find_if(mDevices.begin(), mDevices.end(), [identifier](auto& devicePair) {
- return devicePair.second->getDescriptor().size() && identifier.descriptor.size() &&
- devicePair.second->getDescriptor() == identifier.descriptor;
+ const InputDeviceIdentifier identifier2 =
+ devicePair.second->getDeviceInfo().getIdentifier();
+ return isSubDevice(identifier, identifier2);
});
std::shared_ptr<InputDevice> device;
diff --git a/services/inputflinger/reader/include/EventHub.h b/services/inputflinger/reader/include/EventHub.h
index 79188aa..4733ecb 100644
--- a/services/inputflinger/reader/include/EventHub.h
+++ b/services/inputflinger/reader/include/EventHub.h
@@ -652,7 +652,6 @@
base::Result<void> readNotifyLocked() REQUIRES(mLock);
void handleNotifyEventLocked(const inotify_event&) REQUIRES(mLock);
- Device* getDeviceByDescriptorLocked(const std::string& descriptor) const REQUIRES(mLock);
Device* getDeviceLocked(int32_t deviceId) const REQUIRES(mLock);
Device* getDeviceByPathLocked(const std::string& devicePath) const REQUIRES(mLock);
/**
@@ -662,6 +661,9 @@
Device* getDeviceByFdLocked(int fd) const REQUIRES(mLock);
int32_t getNextControllerNumberLocked(const std::string& name) REQUIRES(mLock);
+
+ bool hasDeviceWithDescriptorLocked(const std::string& descriptor) const REQUIRES(mLock);
+
void releaseControllerNumberLocked(int32_t num) REQUIRES(mLock);
void reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
ftl::Flags<InputDeviceClass> classes) REQUIRES(mLock);
diff --git a/services/inputflinger/reader/mapper/TouchInputMapper.cpp b/services/inputflinger/reader/mapper/TouchInputMapper.cpp
index ba019f6..c069248 100644
--- a/services/inputflinger/reader/mapper/TouchInputMapper.cpp
+++ b/services/inputflinger/reader/mapper/TouchInputMapper.cpp
@@ -1031,8 +1031,9 @@
: getInverseRotation(mViewport.orientation);
// For orientation-aware devices that work in the un-rotated coordinate space, the
// viewport update should be skipped if it is only a change in the orientation.
- skipViewportUpdate = mParameters.orientationAware && mDisplayWidth == oldDisplayWidth &&
- mDisplayHeight == oldDisplayHeight && viewportOrientationChanged;
+ skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
+ mDisplayWidth == oldDisplayWidth && mDisplayHeight == oldDisplayHeight &&
+ viewportOrientationChanged;
// Apply the input device orientation for the device.
mInputDeviceOrientation =
@@ -1047,8 +1048,6 @@
mDisplayHeight = rawHeight;
mInputDeviceOrientation = DISPLAY_ORIENTATION_0;
}
- // If displayId changed, do not skip viewport update.
- skipViewportUpdate &= !viewportDisplayIdChanged;
}
// If moving between pointer modes, need to reset some state.
diff --git a/services/inputflinger/reporter/InputReporter.cpp b/services/inputflinger/reporter/InputReporter.cpp
index b591d3f..6f1eef6 100644
--- a/services/inputflinger/reporter/InputReporter.cpp
+++ b/services/inputflinger/reporter/InputReporter.cpp
@@ -35,7 +35,7 @@
}
sp<InputReporterInterface> createInputReporter() {
- return new InputReporter();
+ return sp<InputReporter>::make();
}
} // namespace android
diff --git a/services/inputflinger/tests/Android.bp b/services/inputflinger/tests/Android.bp
index 76a7c19..6da2145 100644
--- a/services/inputflinger/tests/Android.bp
+++ b/services/inputflinger/tests/Android.bp
@@ -41,8 +41,8 @@
"EventHub_test.cpp",
"FocusResolver_test.cpp",
"IInputFlingerQuery.aidl",
- "InputClassifier_test.cpp",
- "InputClassifierConverter_test.cpp",
+ "InputProcessor_test.cpp",
+ "InputProcessorConverter_test.cpp",
"InputDispatcher_test.cpp",
"InputReader_test.cpp",
"InputFlingerService_test.cpp",
diff --git a/services/inputflinger/tests/AnrTracker_test.cpp b/services/inputflinger/tests/AnrTracker_test.cpp
index b561da1..f8be48a 100644
--- a/services/inputflinger/tests/AnrTracker_test.cpp
+++ b/services/inputflinger/tests/AnrTracker_test.cpp
@@ -40,8 +40,8 @@
TEST(AnrTrackerTest, MultipleEntries_RemoveToken) {
AnrTracker tracker;
- sp<IBinder> token1 = new BBinder();
- sp<IBinder> token2 = new BBinder();
+ sp<IBinder> token1 = sp<BBinder>::make();
+ sp<IBinder> token2 = sp<BBinder>::make();
tracker.insert(1, token1);
tracker.insert(2, token2);
@@ -90,8 +90,8 @@
TEST(AnrTrackerTest, MultipleTokens_MaintainsOrder) {
AnrTracker tracker;
- sp<IBinder> token1 = new BBinder();
- sp<IBinder> token2 = new BBinder();
+ sp<IBinder> token1 = sp<BBinder>::make();
+ sp<IBinder> token2 = sp<BBinder>::make();
tracker.insert(2, token1);
tracker.insert(5, token2);
@@ -104,8 +104,8 @@
TEST(AnrTrackerTest, MultipleTokens_IdenticalTimes) {
AnrTracker tracker;
- sp<IBinder> token1 = new BBinder();
- sp<IBinder> token2 = new BBinder();
+ sp<IBinder> token1 = sp<BBinder>::make();
+ sp<IBinder> token2 = sp<BBinder>::make();
tracker.insert(2, token1);
tracker.insert(2, token2);
@@ -119,8 +119,8 @@
TEST(AnrTrackerTest, MultipleTokens_IdenticalTimesRemove) {
AnrTracker tracker;
- sp<IBinder> token1 = new BBinder();
- sp<IBinder> token2 = new BBinder();
+ sp<IBinder> token1 = sp<BBinder>::make();
+ sp<IBinder> token2 = sp<BBinder>::make();
tracker.insert(2, token1);
tracker.insert(2, token2);
@@ -152,12 +152,12 @@
ASSERT_EQ(nullptr, tracker.firstToken());
// Remove with non-matching token
- tracker.erase(1, new BBinder());
+ tracker.erase(1, sp<BBinder>::make());
ASSERT_EQ(1, tracker.firstTimeout());
ASSERT_EQ(nullptr, tracker.firstToken());
// Remove with both non-matching
- tracker.erase(2, new BBinder());
+ tracker.erase(2, sp<BBinder>::make());
ASSERT_EQ(1, tracker.firstTimeout());
ASSERT_EQ(nullptr, tracker.firstToken());
}
diff --git a/services/inputflinger/tests/EventHub_test.cpp b/services/inputflinger/tests/EventHub_test.cpp
index ef68a84..6ef6e44 100644
--- a/services/inputflinger/tests/EventHub_test.cpp
+++ b/services/inputflinger/tests/EventHub_test.cpp
@@ -180,6 +180,20 @@
}
/**
+ * Ensure that two identical devices get assigned unique descriptors from EventHub.
+ */
+TEST_F(EventHubTest, DevicesWithMatchingUniqueIdsAreUnique) {
+ std::unique_ptr<UinputHomeKey> keyboard2 = createUinputDevice<UinputHomeKey>();
+ int32_t deviceId2;
+ ASSERT_NO_FATAL_FAILURE(deviceId2 = waitForDeviceCreation());
+
+ ASSERT_NE(mEventHub->getDeviceIdentifier(mDeviceId).descriptor,
+ mEventHub->getDeviceIdentifier(deviceId2).descriptor);
+ keyboard2.reset();
+ waitForDeviceClose(deviceId2);
+}
+
+/**
* Ensure that input_events are generated with monotonic clock.
* That means input_event should receive a timestamp that is in the future of the time
* before the event was sent.
diff --git a/services/inputflinger/tests/FocusResolver_test.cpp b/services/inputflinger/tests/FocusResolver_test.cpp
index 91be4a3..5d5cf9c 100644
--- a/services/inputflinger/tests/FocusResolver_test.cpp
+++ b/services/inputflinger/tests/FocusResolver_test.cpp
@@ -50,16 +50,16 @@
};
TEST(FocusResolverTest, SetFocusedWindow) {
- sp<IBinder> focusableWindowToken = new BBinder();
- sp<IBinder> invisibleWindowToken = new BBinder();
- sp<IBinder> unfocusableWindowToken = new BBinder();
+ sp<IBinder> focusableWindowToken = sp<BBinder>::make();
+ sp<IBinder> invisibleWindowToken = sp<BBinder>::make();
+ sp<IBinder> unfocusableWindowToken = sp<BBinder>::make();
std::vector<sp<WindowInfoHandle>> windows;
- windows.push_back(new FakeWindowHandle("Focusable", focusableWindowToken, true /* focusable */,
- true /* visible */));
- windows.push_back(new FakeWindowHandle("Invisible", invisibleWindowToken, true /* focusable */,
- false /* visible */));
- windows.push_back(new FakeWindowHandle("unfocusable", unfocusableWindowToken,
- false /* focusable */, true /* visible */));
+ windows.push_back(sp<FakeWindowHandle>::make("Focusable", focusableWindowToken,
+ true /* focusable */, true /* visible */));
+ windows.push_back(sp<FakeWindowHandle>::make("Invisible", invisibleWindowToken,
+ true /* focusable */, false /* visible */));
+ windows.push_back(sp<FakeWindowHandle>::make("unfocusable", unfocusableWindowToken,
+ false /* focusable */, true /* visible */));
// focusable window can get focused
FocusRequest request;
@@ -85,10 +85,10 @@
}
TEST(FocusResolverTest, RemoveFocusFromFocusedWindow) {
- sp<IBinder> focusableWindowToken = new BBinder();
+ sp<IBinder> focusableWindowToken = sp<BBinder>::make();
std::vector<sp<WindowInfoHandle>> windows;
- windows.push_back(new FakeWindowHandle("Focusable", focusableWindowToken, true /* focusable */,
- true /* visible */));
+ windows.push_back(sp<FakeWindowHandle>::make("Focusable", focusableWindowToken,
+ true /* focusable */, true /* visible */));
FocusRequest request;
request.displayId = 42;
@@ -109,24 +109,24 @@
}
TEST(FocusResolverTest, SetFocusedMirroredWindow) {
- sp<IBinder> focusableWindowToken = new BBinder();
- sp<IBinder> invisibleWindowToken = new BBinder();
- sp<IBinder> unfocusableWindowToken = new BBinder();
+ sp<IBinder> focusableWindowToken = sp<BBinder>::make();
+ sp<IBinder> invisibleWindowToken = sp<BBinder>::make();
+ sp<IBinder> unfocusableWindowToken = sp<BBinder>::make();
std::vector<sp<WindowInfoHandle>> windows;
- windows.push_back(new FakeWindowHandle("Mirror1", focusableWindowToken, true /* focusable */,
- true /* visible */));
- windows.push_back(new FakeWindowHandle("Mirror1", focusableWindowToken, true /* focusable */,
- true /* visible */));
+ windows.push_back(sp<FakeWindowHandle>::make("Mirror1", focusableWindowToken,
+ true /* focusable */, true /* visible */));
+ windows.push_back(sp<FakeWindowHandle>::make("Mirror1", focusableWindowToken,
+ true /* focusable */, true /* visible */));
- windows.push_back(new FakeWindowHandle("Mirror2Visible", invisibleWindowToken,
- true /* focusable */, true /* visible */));
- windows.push_back(new FakeWindowHandle("Mirror2Invisible", invisibleWindowToken,
- true /* focusable */, false /* visible */));
+ windows.push_back(sp<FakeWindowHandle>::make("Mirror2Visible", invisibleWindowToken,
+ true /* focusable */, true /* visible */));
+ windows.push_back(sp<FakeWindowHandle>::make("Mirror2Invisible", invisibleWindowToken,
+ true /* focusable */, false /* visible */));
- windows.push_back(new FakeWindowHandle("Mirror3Focusable", unfocusableWindowToken,
- true /* focusable */, true /* visible */));
- windows.push_back(new FakeWindowHandle("Mirror3Unfocusable", unfocusableWindowToken,
- false /* focusable */, true /* visible */));
+ windows.push_back(sp<FakeWindowHandle>::make("Mirror3Focusable", unfocusableWindowToken,
+ true /* focusable */, true /* visible */));
+ windows.push_back(sp<FakeWindowHandle>::make("Mirror3Unfocusable", unfocusableWindowToken,
+ false /* focusable */, true /* visible */));
// mirrored window can get focused
FocusRequest request;
@@ -149,10 +149,11 @@
}
TEST(FocusResolverTest, SetInputWindows) {
- sp<IBinder> focusableWindowToken = new BBinder();
+ sp<IBinder> focusableWindowToken = sp<BBinder>::make();
std::vector<sp<WindowInfoHandle>> windows;
- sp<FakeWindowHandle> window = new FakeWindowHandle("Focusable", focusableWindowToken,
- true /* focusable */, true /* visible */);
+ sp<FakeWindowHandle> window =
+ sp<FakeWindowHandle>::make("Focusable", focusableWindowToken, true /* focusable */,
+ true /* visible */);
windows.push_back(window);
// focusable window can get focused
@@ -171,12 +172,12 @@
}
TEST(FocusResolverTest, FocusRequestsCanBePending) {
- sp<IBinder> invisibleWindowToken = new BBinder();
+ sp<IBinder> invisibleWindowToken = sp<BBinder>::make();
std::vector<sp<WindowInfoHandle>> windows;
sp<FakeWindowHandle> invisibleWindow =
- new FakeWindowHandle("Invisible", invisibleWindowToken, true /* focusable */,
- false /* visible */);
+ sp<FakeWindowHandle>::make("Invisible", invisibleWindowToken, true /* focusable */,
+ false /* visible */);
windows.push_back(invisibleWindow);
// invisible window cannot get focused
@@ -195,11 +196,12 @@
}
TEST(FocusResolverTest, FocusRequestsArePersistent) {
- sp<IBinder> windowToken = new BBinder();
+ sp<IBinder> windowToken = sp<BBinder>::make();
std::vector<sp<WindowInfoHandle>> windows;
- sp<FakeWindowHandle> window = new FakeWindowHandle("Test Window", windowToken,
- false /* focusable */, true /* visible */);
+ sp<FakeWindowHandle> window =
+ sp<FakeWindowHandle>::make("Test Window", windowToken, false /* focusable */,
+ true /* visible */);
windows.push_back(window);
// non-focusable window cannot get focused
@@ -236,17 +238,17 @@
}
TEST(FocusResolverTest, ConditionalFocusRequestsAreNotPersistent) {
- sp<IBinder> hostWindowToken = new BBinder();
+ sp<IBinder> hostWindowToken = sp<BBinder>::make();
std::vector<sp<WindowInfoHandle>> windows;
sp<FakeWindowHandle> hostWindow =
- new FakeWindowHandle("Host Window", hostWindowToken, true /* focusable */,
- true /* visible */);
+ sp<FakeWindowHandle>::make("Host Window", hostWindowToken, true /* focusable */,
+ true /* visible */);
windows.push_back(hostWindow);
- sp<IBinder> embeddedWindowToken = new BBinder();
+ sp<IBinder> embeddedWindowToken = sp<BBinder>::make();
sp<FakeWindowHandle> embeddedWindow =
- new FakeWindowHandle("Embedded Window", embeddedWindowToken, true /* focusable */,
- true /* visible */);
+ sp<FakeWindowHandle>::make("Embedded Window", embeddedWindowToken, true /* focusable */,
+ true /* visible */);
windows.push_back(embeddedWindow);
FocusRequest request;
@@ -287,11 +289,12 @@
ASSERT_FALSE(changes);
}
TEST(FocusResolverTest, FocusRequestsAreClearedWhenWindowIsRemoved) {
- sp<IBinder> windowToken = new BBinder();
+ sp<IBinder> windowToken = sp<BBinder>::make();
std::vector<sp<WindowInfoHandle>> windows;
- sp<FakeWindowHandle> window = new FakeWindowHandle("Test Window", windowToken,
- true /* focusable */, true /* visible */);
+ sp<FakeWindowHandle> window =
+ sp<FakeWindowHandle>::make("Test Window", windowToken, true /* focusable */,
+ true /* visible */);
windows.push_back(window);
FocusRequest request;
diff --git a/services/inputflinger/tests/InputDispatcher_test.cpp b/services/inputflinger/tests/InputDispatcher_test.cpp
index 7f21dea..7ee6950 100644
--- a/services/inputflinger/tests/InputDispatcher_test.cpp
+++ b/services/inputflinger/tests/InputDispatcher_test.cpp
@@ -515,7 +515,7 @@
std::unique_ptr<InputDispatcher> mDispatcher;
void SetUp() override {
- mFakePolicy = new FakeInputDispatcherPolicy();
+ mFakePolicy = sp<FakeInputDispatcherPolicy>::make();
mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy, STALE_EVENT_TIMEOUT);
mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
// Start InputDispatcher thread
@@ -752,7 +752,7 @@
public:
FakeApplicationHandle() {
mInfo.name = "Fake Application";
- mInfo.token = new BBinder();
+ mInfo.token = sp<BBinder>::make();
mInfo.dispatchingTimeoutMillis =
std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
}
@@ -1028,8 +1028,8 @@
const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
sp<FakeWindowHandle> handle =
- new FakeWindowHandle(inputApplicationHandle, dispatcher, mInfo.name + "(Mirror)",
- displayId, mInfo.token);
+ sp<FakeWindowHandle>::make(inputApplicationHandle, dispatcher,
+ mInfo.name + "(Mirror)", displayId, mInfo.token);
return handle;
}
@@ -1563,8 +1563,8 @@
TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "Window that breaks its input channel",
- ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher,
+ "Window that breaks its input channel", ADISPLAY_ID_DEFAULT);
mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
@@ -1575,8 +1575,8 @@
TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
- sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
+ "Fake Window", ADISPLAY_ID_DEFAULT);
mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
@@ -1589,8 +1589,8 @@
TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
- sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
+ "Fake Window", ADISPLAY_ID_DEFAULT);
mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
// Inject a MotionEvent to an unknown display.
@@ -1609,8 +1609,8 @@
*/
TEST_F(InputDispatcherTest, SetInputWindowOnceWithSingleTouchWindow) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
- sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
+ "Fake Window", ADISPLAY_ID_DEFAULT);
window->setFrame(Rect(0, 0, 100, 100));
mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
@@ -1628,8 +1628,8 @@
*/
TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
- sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
+ "Fake Window", ADISPLAY_ID_DEFAULT);
window->setFrame(Rect(0, 0, 100, 100));
mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
@@ -1647,9 +1647,9 @@
TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
sp<FakeWindowHandle> windowTop =
- new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
sp<FakeWindowHandle> windowSecond =
- new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
@@ -1671,10 +1671,10 @@
TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
sp<FakeWindowHandle> foregroundWindow =
- new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
foregroundWindow->setDupTouchToWallpaper(true);
sp<FakeWindowHandle> wallpaperWindow =
- new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
wallpaperWindow->setIsWallpaper(true);
constexpr int expectedWallpaperFlags =
AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
@@ -1715,10 +1715,10 @@
TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
sp<FakeWindowHandle> foregroundWindow =
- new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
foregroundWindow->setDupTouchToWallpaper(true);
sp<FakeWindowHandle> wallpaperWindow =
- new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
wallpaperWindow->setIsWallpaper(true);
constexpr int expectedWallpaperFlags =
AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
@@ -1759,11 +1759,11 @@
TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
window->setDupTouchToWallpaper(true);
sp<FakeWindowHandle> wallpaperWindow =
- new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
wallpaperWindow->setIsWallpaper(true);
constexpr int expectedWallpaperFlags =
AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
@@ -1814,17 +1814,17 @@
TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
sp<FakeWindowHandle> leftWindow =
- new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
leftWindow->setFrame(Rect(0, 0, 200, 200));
leftWindow->setDupTouchToWallpaper(true);
sp<FakeWindowHandle> rightWindow =
- new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
rightWindow->setFrame(Rect(200, 0, 400, 200));
rightWindow->setDupTouchToWallpaper(true);
sp<FakeWindowHandle> wallpaperWindow =
- new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
wallpaperWindow->setIsWallpaper(true);
constexpr int expectedWallpaperFlags =
@@ -1901,7 +1901,7 @@
TEST_F(InputDispatcherTest, SplitWorksWhenEmptyAreaIsTouched) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "Window", DISPLAY_ID);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Window", DISPLAY_ID);
mDispatcher->setInputWindows({{DISPLAY_ID, {window}}});
NotifyMotionArgs args;
@@ -1925,11 +1925,11 @@
TEST_F(InputDispatcherTest, SplitWorksWhenNonTouchableWindowIsTouched) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
sp<FakeWindowHandle> window1 =
- new FakeWindowHandle(application, mDispatcher, "Window1", DISPLAY_ID);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Window1", DISPLAY_ID);
window1->setTouchableRegion(Region{{0, 0, 100, 100}});
window1->setTouchable(false);
sp<FakeWindowHandle> window2 =
- new FakeWindowHandle(application, mDispatcher, "Window2", DISPLAY_ID);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Window2", DISPLAY_ID);
window2->setTouchableRegion(Region{{100, 0, 200, 100}});
mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
@@ -1955,10 +1955,10 @@
TEST_F(InputDispatcherTest, SplitTouchesSendCorrectActionDownTime) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
sp<FakeWindowHandle> window1 =
- new FakeWindowHandle(application, mDispatcher, "Window1", DISPLAY_ID);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Window1", DISPLAY_ID);
window1->setTouchableRegion(Region{{0, 0, 100, 100}});
sp<FakeWindowHandle> window2 =
- new FakeWindowHandle(application, mDispatcher, "Window2", DISPLAY_ID);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Window2", DISPLAY_ID);
window2->setTouchableRegion(Region{{100, 0, 200, 100}});
mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
@@ -2022,10 +2022,10 @@
TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
sp<FakeWindowHandle> windowLeft =
- new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
windowLeft->setFrame(Rect(0, 0, 600, 800));
sp<FakeWindowHandle> windowRight =
- new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
windowRight->setFrame(Rect(600, 0, 1200, 800));
mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
@@ -2131,7 +2131,7 @@
TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
window->setFrame(Rect(0, 0, 1200, 800));
mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
@@ -2212,10 +2212,10 @@
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
sp<FakeWindowHandle> windowLeft =
- new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
windowLeft->setFrame(Rect(0, 0, 600, 800));
sp<FakeWindowHandle> windowRight =
- new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
windowRight->setFrame(Rect(600, 0, 1200, 800));
mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
@@ -2233,8 +2233,8 @@
TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
- sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
+ "Fake Window", ADISPLAY_ID_DEFAULT);
window->setFocusable(true);
mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
@@ -2258,8 +2258,8 @@
TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
- sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
+ "Fake Window", ADISPLAY_ID_DEFAULT);
mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
@@ -2281,8 +2281,8 @@
TEST_F(InputDispatcherTest, InterceptKeyByPolicy) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
- sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
+ "Fake Window", ADISPLAY_ID_DEFAULT);
window->setFocusable(true);
mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
@@ -2303,8 +2303,8 @@
TEST_F(InputDispatcherTest, InterceptKeyIfKeyUp) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
- sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
+ "Fake Window", ADISPLAY_ID_DEFAULT);
window->setFocusable(true);
mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
@@ -2331,15 +2331,17 @@
TEST_F(InputDispatcherTest, ActionOutsideSentOnlyWhenAWindowIsTouched) {
// There are three windows that do not overlap. `window` wants to WATCH_OUTSIDE_TOUCH.
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
- sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
+ "First Window", ADISPLAY_ID_DEFAULT);
window->setWatchOutsideTouch(true);
window->setFrame(Rect{0, 0, 100, 100});
sp<FakeWindowHandle> secondWindow =
- new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
+ ADISPLAY_ID_DEFAULT);
secondWindow->setFrame(Rect{100, 100, 200, 200});
sp<FakeWindowHandle> thirdWindow =
- new FakeWindowHandle(application, mDispatcher, "Third Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Third Window",
+ ADISPLAY_ID_DEFAULT);
thirdWindow->setFrame(Rect{200, 200, 300, 300});
mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, secondWindow, thirdWindow}}});
@@ -2372,8 +2374,8 @@
TEST_F(InputDispatcherTest, OnWindowInfosChanged_RemoveAllWindowsOnDisplay) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
- sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
+ "Fake Window", ADISPLAY_ID_DEFAULT);
window->setFocusable(true);
mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
@@ -2441,13 +2443,14 @@
// Add two windows to the display. Their frames are represented in the display space.
sp<FakeWindowHandle> firstWindow =
- new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
+ ADISPLAY_ID_DEFAULT);
firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
addWindow(firstWindow);
sp<FakeWindowHandle> secondWindow =
- new FakeWindowHandle(application, mDispatcher, "Second Window",
- ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
+ ADISPLAY_ID_DEFAULT);
secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
addWindow(secondWindow);
return {std::move(firstWindow), std::move(secondWindow)};
@@ -2548,9 +2551,11 @@
// Create a couple of windows
sp<FakeWindowHandle> firstWindow =
- new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
+ ADISPLAY_ID_DEFAULT);
sp<FakeWindowHandle> secondWindow =
- new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
+ ADISPLAY_ID_DEFAULT);
// Add the windows to the dispatcher
mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
@@ -2599,13 +2604,13 @@
// Create a couple of windows + a spy window
sp<FakeWindowHandle> spyWindow =
- new FakeWindowHandle(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
spyWindow->setTrustedOverlay(true);
spyWindow->setSpy(true);
sp<FakeWindowHandle> firstWindow =
- new FakeWindowHandle(application, mDispatcher, "First", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "First", ADISPLAY_ID_DEFAULT);
sp<FakeWindowHandle> secondWindow =
- new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
// Add the windows to the dispatcher
mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, firstWindow, secondWindow}}});
@@ -2646,10 +2651,12 @@
// Create a couple of windows
sp<FakeWindowHandle> firstWindow =
- new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
+ ADISPLAY_ID_DEFAULT);
firstWindow->setPreventSplitting(true);
sp<FakeWindowHandle> secondWindow =
- new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
+ ADISPLAY_ID_DEFAULT);
secondWindow->setPreventSplitting(true);
// Add the windows to the dispatcher
@@ -2721,11 +2728,13 @@
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
sp<FakeWindowHandle> firstWindow =
- new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
+ ADISPLAY_ID_DEFAULT);
firstWindow->setFrame(Rect(0, 0, 600, 400));
sp<FakeWindowHandle> secondWindow =
- new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
+ ADISPLAY_ID_DEFAULT);
secondWindow->setFrame(Rect(0, 400, 600, 800));
// Add the windows to the dispatcher
@@ -2785,11 +2794,13 @@
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
sp<FakeWindowHandle> firstWindow =
- new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
+ ADISPLAY_ID_DEFAULT);
firstWindow->setFrame(Rect(0, 0, 600, 400));
sp<FakeWindowHandle> secondWindow =
- new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
+ ADISPLAY_ID_DEFAULT);
secondWindow->setFrame(Rect(0, 400, 600, 800));
// Add the windows to the dispatcher
@@ -2850,10 +2861,10 @@
TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
sp<FakeWindowHandle> firstWindowInPrimary =
- new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
sp<FakeWindowHandle> secondWindowInPrimary =
- new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
sp<FakeWindowHandle> mirrorWindowInPrimary =
@@ -2909,10 +2920,10 @@
TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
sp<FakeWindowHandle> firstWindowInPrimary =
- new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
sp<FakeWindowHandle> secondWindowInPrimary =
- new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
sp<FakeWindowHandle> mirrorWindowInPrimary =
@@ -2964,8 +2975,8 @@
TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
- sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
+ "Fake Window", ADISPLAY_ID_DEFAULT);
window->setFocusable(true);
mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
@@ -2982,8 +2993,8 @@
TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
- sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
+ "Fake Window", ADISPLAY_ID_DEFAULT);
mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
@@ -2997,8 +3008,8 @@
// If a window is touchable, but does not have focus, it should receive motion events, but not keys
TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
- sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
+ "Fake Window", ADISPLAY_ID_DEFAULT);
mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
@@ -3020,11 +3031,13 @@
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
sp<FakeWindowHandle> firstWindow =
- new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
+ ADISPLAY_ID_DEFAULT);
firstWindow->setFrame(Rect(0, 0, 600, 400));
sp<FakeWindowHandle> secondWindow =
- new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
+ ADISPLAY_ID_DEFAULT);
secondWindow->setFrame(Rect(0, 400, 600, 800));
// Add the windows to the dispatcher
@@ -3075,7 +3088,7 @@
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
@@ -3165,7 +3178,7 @@
TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
@@ -3205,8 +3218,8 @@
TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
- sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
+ "Fake Window", ADISPLAY_ID_DEFAULT);
mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
@@ -3222,8 +3235,8 @@
FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
- sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
+ "Fake Window", ADISPLAY_ID_DEFAULT);
mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
@@ -3247,8 +3260,8 @@
TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
- sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
+ "Fake Window", ADISPLAY_ID_DEFAULT);
mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
window->setWindowOffset(20, 40);
window->setWindowTransform(0, 1, -1, 0);
@@ -3276,8 +3289,8 @@
TEST_F(InputDispatcherTest, TestMoveEvent) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
- sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
+ "Fake Window", ADISPLAY_ID_DEFAULT);
mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
@@ -3307,8 +3320,8 @@
*/
TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
- sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
+ "Test window", ADISPLAY_ID_DEFAULT);
const WindowInfo& windowInfo = *window->getInfo();
// Set focused application.
@@ -3353,8 +3366,8 @@
TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
- sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
+ "Test window", ADISPLAY_ID_DEFAULT);
mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
window->setFocusable(true);
@@ -3392,8 +3405,8 @@
TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
- sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
+ "Test window", ADISPLAY_ID_DEFAULT);
mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
@@ -3497,9 +3510,9 @@
TEST_F(InputDispatcherTest, SetFocusedWindow) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
sp<FakeWindowHandle> windowTop =
- new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
sp<FakeWindowHandle> windowSecond =
- new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
// Top window is also focusable but is not granted focus.
@@ -3520,7 +3533,7 @@
TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
window->setFocusable(true);
@@ -3540,7 +3553,7 @@
TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
window->setFocusable(false);
mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
@@ -3558,9 +3571,9 @@
TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
sp<FakeWindowHandle> windowTop =
- new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
sp<FakeWindowHandle> windowSecond =
- new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
windowTop->setFocusable(true);
@@ -3583,9 +3596,9 @@
TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
sp<FakeWindowHandle> windowTop =
- new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
sp<FakeWindowHandle> windowSecond =
- new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
windowTop->setFocusable(true);
@@ -3604,10 +3617,10 @@
TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
sp<FakeWindowHandle> previousFocusedWindow =
- new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
- ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "previousFocusedWindow",
+ ADISPLAY_ID_DEFAULT);
mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
window->setFocusable(true);
@@ -3642,7 +3655,7 @@
TEST_F(InputDispatcherTest, DisplayRemoved) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
// window is granted focus.
@@ -3687,7 +3700,7 @@
mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
sp<FakeWindowHandle> slipperyExitWindow =
- new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
slipperyExitWindow->setSlippery(true);
// Make sure this one overlaps the bottom window
slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
@@ -3696,7 +3709,7 @@
slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
sp<FakeWindowHandle> slipperyEnterWindow =
- new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
mDispatcher->setInputWindows(
@@ -3730,7 +3743,7 @@
sp<FakeWindowHandle> mWindow;
virtual void SetUp() override {
- mFakePolicy = new FakeInputDispatcherPolicy();
+ mFakePolicy = sp<FakeInputDispatcherPolicy>::make();
mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
@@ -3741,7 +3754,7 @@
void setUpWindow() {
mApp = std::make_shared<FakeApplicationHandle>();
- mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
+ mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
mWindow->setFocusable(true);
mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
@@ -3878,7 +3891,7 @@
application1 = std::make_shared<FakeApplicationHandle>();
windowInPrimary =
- new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
// Set focus window for primary display, but focused display would be second one.
mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
@@ -3889,7 +3902,7 @@
application2 = std::make_shared<FakeApplicationHandle>();
windowInSecondary =
- new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
+ sp<FakeWindowHandle>::make(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
// Set focus to second display window.
// Set focus display to second one.
mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
@@ -4018,7 +4031,7 @@
TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
sp<FakeWindowHandle> secondWindowInPrimary =
- new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
secondWindowInPrimary->setFocusable(true);
mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
setFocusedWindow(secondWindowInPrimary);
@@ -4187,8 +4200,8 @@
std::shared_ptr<InputApplicationHandle> application =
std::make_shared<FakeApplicationHandle>();
- mWindow =
- new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
+ mWindow = sp<FakeWindowHandle>::make(application, mDispatcher, "Test Window",
+ ADISPLAY_ID_DEFAULT);
mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
mWindow->setFocusable(true);
@@ -4292,11 +4305,11 @@
std::shared_ptr<FakeApplicationHandle> application =
std::make_shared<FakeApplicationHandle>();
mUnfocusedWindow =
- new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
mFocusedWindow =
- new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
// Set focused application.
@@ -4402,12 +4415,12 @@
std::shared_ptr<FakeApplicationHandle> application =
std::make_shared<FakeApplicationHandle>();
- mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
- ADISPLAY_ID_DEFAULT);
+ mWindow1 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 1",
+ ADISPLAY_ID_DEFAULT);
mWindow1->setFrame(Rect(0, 0, 100, 100));
- mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
- ADISPLAY_ID_DEFAULT, mWindow1->getToken());
+ mWindow2 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 2",
+ ADISPLAY_ID_DEFAULT, mWindow1->getToken());
mWindow2->setFrame(Rect(100, 100, 200, 200));
mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
@@ -4589,8 +4602,8 @@
mApplication = std::make_shared<FakeApplicationHandle>();
mApplication->setDispatchingTimeout(20ms);
- mWindow =
- new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
+ mWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "TestWindow",
+ ADISPLAY_ID_DEFAULT);
mWindow->setFrame(Rect(0, 0, 30, 30));
mWindow->setDispatchingTimeout(30ms);
mWindow->setFocusable(true);
@@ -4624,7 +4637,7 @@
sp<FakeWindowHandle> addSpyWindow() {
sp<FakeWindowHandle> spy =
- new FakeWindowHandle(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
spy->setTrustedOverlay(true);
spy->setFocusable(false);
spy->setSpy(true);
@@ -5070,14 +5083,14 @@
mApplication = std::make_shared<FakeApplicationHandle>();
mApplication->setDispatchingTimeout(10ms);
- mUnfocusedWindow =
- new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
+ mUnfocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Unfocused",
+ ADISPLAY_ID_DEFAULT);
mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
// Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
mUnfocusedWindow->setWatchOutsideTouch(true);
- mFocusedWindow =
- new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
+ mFocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Focused",
+ ADISPLAY_ID_DEFAULT);
mFocusedWindow->setDispatchingTimeout(30ms);
mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
@@ -5444,16 +5457,17 @@
InputDispatcherTest::SetUp();
mApplication = std::make_shared<FakeApplicationHandle>();
- mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
- "Window without input channel", ADISPLAY_ID_DEFAULT,
- std::make_optional<sp<IBinder>>(nullptr) /*token*/);
+ mNoInputWindow =
+ sp<FakeWindowHandle>::make(mApplication, mDispatcher,
+ "Window without input channel", ADISPLAY_ID_DEFAULT,
+ std::make_optional<sp<IBinder>>(nullptr) /*token*/);
mNoInputWindow->setNoInputChannel(true);
mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
// It's perfectly valid for this window to not have an associated input channel
- mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
- ADISPLAY_ID_DEFAULT);
+ mBottomWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Bottom window",
+ ADISPLAY_ID_DEFAULT);
mBottomWindow->setFrame(Rect(0, 0, 100, 100));
mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
@@ -5486,9 +5500,9 @@
*/
TEST_F(InputDispatcherMultiWindowOcclusionTests,
NoInputChannelFeature_DropsTouchesWithValidChannel) {
- mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
- "Window with input channel and NO_INPUT_CHANNEL",
- ADISPLAY_ID_DEFAULT);
+ mNoInputWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher,
+ "Window with input channel and NO_INPUT_CHANNEL",
+ ADISPLAY_ID_DEFAULT);
mNoInputWindow->setNoInputChannel(true);
mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
@@ -5514,9 +5528,9 @@
virtual void SetUp() override {
InputDispatcherTest::SetUp();
mApp = std::make_shared<FakeApplicationHandle>();
- mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
- mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
- mWindow->getToken());
+ mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
+ mMirror = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindowMirror",
+ ADISPLAY_ID_DEFAULT, mWindow->getToken());
mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
mWindow->setFocusable(true);
mMirror->setFocusable(true);
@@ -5658,9 +5672,10 @@
void SetUp() override {
InputDispatcherTest::SetUp();
mApp = std::make_shared<FakeApplicationHandle>();
- mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
+ mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
mWindow->setFocusable(true);
- mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
+ mSecondWindow =
+ sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
mSecondWindow->setFocusable(true);
mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
@@ -5841,7 +5856,7 @@
sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
sp<FakeWindowHandle> window =
- new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
// Generate an arbitrary PID based on the UID
window->setOwnerInfo(1777 + (uid % 10000), uid);
return window;
@@ -6208,13 +6223,15 @@
void SetUp() override {
InputDispatcherTest::SetUp();
mApp = std::make_shared<FakeApplicationHandle>();
- mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
+ mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
mWindow->setFrame(Rect(0, 0, 100, 100));
- mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
+ mSecondWindow =
+ sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
mSecondWindow->setFrame(Rect(100, 0, 200, 100));
- mSpyWindow = new FakeWindowHandle(mApp, mDispatcher, "SpyWindow", ADISPLAY_ID_DEFAULT);
+ mSpyWindow =
+ sp<FakeWindowHandle>::make(mApp, mDispatcher, "SpyWindow", ADISPLAY_ID_DEFAULT);
mSpyWindow->setSpy(true);
mSpyWindow->setTrustedOverlay(true);
mSpyWindow->setFrame(Rect(0, 0, 200, 100));
@@ -6274,7 +6291,8 @@
}
// The drag window covers the entire display
- mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
+ mDragWindow =
+ sp<FakeWindowHandle>::make(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
mDragWindow->setTouchableRegion(Region{{0, 0, 0, 0}});
mDispatcher->setInputWindows(
{{ADISPLAY_ID_DEFAULT, {mDragWindow, mSpyWindow, mWindow, mSecondWindow}}});
@@ -6559,7 +6577,7 @@
// Update window of second display.
sp<FakeWindowHandle> windowInSecondary =
- new FakeWindowHandle(mApp, mDispatcher, "D_2", SECOND_DISPLAY_ID);
+ sp<FakeWindowHandle>::make(mApp, mDispatcher, "D_2", SECOND_DISPLAY_ID);
mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
// Let second display has a touch state.
@@ -6659,8 +6677,8 @@
TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
- sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
+ "Test window", ADISPLAY_ID_DEFAULT);
window->setDropInput(true);
mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
window->setFocusable(true);
@@ -6698,14 +6716,14 @@
std::shared_ptr<FakeApplicationHandle> obscuringApplication =
std::make_shared<FakeApplicationHandle>();
sp<FakeWindowHandle> obscuringWindow =
- new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
- ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
+ ADISPLAY_ID_DEFAULT);
obscuringWindow->setFrame(Rect(0, 0, 50, 50));
obscuringWindow->setOwnerInfo(111, 111);
obscuringWindow->setTouchable(false);
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
- sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
+ "Test window", ADISPLAY_ID_DEFAULT);
window->setDropInputIfObscured(true);
window->setOwnerInfo(222, 222);
mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
@@ -6744,14 +6762,14 @@
std::shared_ptr<FakeApplicationHandle> obscuringApplication =
std::make_shared<FakeApplicationHandle>();
sp<FakeWindowHandle> obscuringWindow =
- new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
- ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
+ ADISPLAY_ID_DEFAULT);
obscuringWindow->setFrame(Rect(0, 0, 50, 50));
obscuringWindow->setOwnerInfo(111, 111);
obscuringWindow->setTouchable(false);
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
- sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
+ "Test window", ADISPLAY_ID_DEFAULT);
window->setDropInputIfObscured(true);
window->setOwnerInfo(222, 222);
mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
@@ -6795,10 +6813,11 @@
InputDispatcherTest::SetUp();
mApp = std::make_shared<FakeApplicationHandle>();
- mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
+ mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
mWindow->setFocusable(true);
setFocusedWindow(mWindow);
- mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
+ mSecondWindow =
+ sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
mSecondWindow->setFocusable(true);
mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
@@ -6881,8 +6900,8 @@
std::make_shared<FakeApplicationHandle>();
std::string name = "Fake Spy ";
name += std::to_string(mSpyCount++);
- sp<FakeWindowHandle> spy =
- new FakeWindowHandle(application, mDispatcher, name.c_str(), ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle> spy = sp<FakeWindowHandle>::make(application, mDispatcher,
+ name.c_str(), ADISPLAY_ID_DEFAULT);
spy->setSpy(true);
spy->setTrustedOverlay(true);
return spy;
@@ -6892,7 +6911,8 @@
std::shared_ptr<FakeApplicationHandle> application =
std::make_shared<FakeApplicationHandle>();
sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window",
+ ADISPLAY_ID_DEFAULT);
window->setFocusable(true);
return window;
}
@@ -7470,8 +7490,8 @@
std::shared_ptr<FakeApplicationHandle> overlayApplication =
std::make_shared<FakeApplicationHandle>();
sp<FakeWindowHandle> overlay =
- new FakeWindowHandle(overlayApplication, mDispatcher, "Stylus interceptor window",
- ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(overlayApplication, mDispatcher,
+ "Stylus interceptor window", ADISPLAY_ID_DEFAULT);
overlay->setFocusable(false);
overlay->setOwnerInfo(111, 111);
overlay->setTouchable(false);
@@ -7481,8 +7501,8 @@
std::shared_ptr<FakeApplicationHandle> application =
std::make_shared<FakeApplicationHandle>();
sp<FakeWindowHandle> window =
- new FakeWindowHandle(application, mDispatcher, "Application window",
- ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Application window",
+ ADISPLAY_ID_DEFAULT);
window->setFocusable(true);
window->setOwnerInfo(222, 222);
@@ -7622,8 +7642,9 @@
sp<FakeWindowHandle> createWindow() const {
std::shared_ptr<FakeApplicationHandle> overlayApplication =
std::make_shared<FakeApplicationHandle>();
- sp<FakeWindowHandle> window = new FakeWindowHandle(overlayApplication, mDispatcher,
- "Owned Window", ADISPLAY_ID_DEFAULT);
+ sp<FakeWindowHandle> window =
+ sp<FakeWindowHandle>::make(overlayApplication, mDispatcher, "Owned Window",
+ ADISPLAY_ID_DEFAULT);
window->setOwnerInfo(mPid, mUid);
return window;
}
diff --git a/services/inputflinger/tests/InputFlingerService_test.cpp b/services/inputflinger/tests/InputFlingerService_test.cpp
index 454e531..22ae894 100644
--- a/services/inputflinger/tests/InputFlingerService_test.cpp
+++ b/services/inputflinger/tests/InputFlingerService_test.cpp
@@ -223,8 +223,10 @@
if (forkPid == 0) {
// Server process
- android::sp<android::TestInputManager> manager = new android::TestInputManager();
- android::sp<android::TestInputQuery> query = new android::TestInputQuery(manager);
+ android::sp<android::TestInputManager> manager =
+ android::sp<android::TestInputManager>::make();
+ android::sp<android::TestInputQuery> query =
+ android::sp<android::TestInputQuery>::make(manager);
android::defaultServiceManager()->addService(android::kTestServiceName, manager,
false /*allowIsolated*/);
diff --git a/services/inputflinger/tests/InputClassifierConverter_test.cpp b/services/inputflinger/tests/InputProcessorConverter_test.cpp
similarity index 93%
rename from services/inputflinger/tests/InputClassifierConverter_test.cpp
rename to services/inputflinger/tests/InputProcessorConverter_test.cpp
index 81ef9b9..040c8da 100644
--- a/services/inputflinger/tests/InputClassifierConverter_test.cpp
+++ b/services/inputflinger/tests/InputProcessorConverter_test.cpp
@@ -24,7 +24,7 @@
namespace android {
-// --- InputClassifierConverterTest ---
+// --- InputProcessorConverterTest ---
static NotifyMotionArgs generateBasicMotionArgs() {
// Create a basic motion event for testing
@@ -52,7 +52,7 @@
static float getMotionEventAxis(common::PointerCoords coords, common::Axis axis) {
uint32_t index = BitSet64::getIndexOfBit(static_cast<uint64_t>(coords.bits),
- static_cast<uint64_t>(axis));
+ static_cast<uint64_t>(axis));
return coords.values[index];
}
@@ -60,7 +60,7 @@
* Check that coordinates get converted properly from the framework's PointerCoords
* to the hidl PointerCoords in input::common.
*/
-TEST(InputClassifierConverterTest, PointerCoordsAxes) {
+TEST(InputProcessorConverterTest, PointerCoordsAxes) {
const NotifyMotionArgs motionArgs = generateBasicMotionArgs();
ASSERT_EQ(1, motionArgs.pointerCoords[0].getX());
ASSERT_EQ(2, motionArgs.pointerCoords[0].getY());
@@ -76,7 +76,7 @@
ASSERT_EQ(getMotionEventAxis(motionEvent.pointerCoords[0], common::Axis::SIZE),
motionArgs.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_SIZE));
ASSERT_EQ(BitSet64::count(motionArgs.pointerCoords[0].bits),
- BitSet64::count(motionEvent.pointerCoords[0].bits));
+ BitSet64::count(motionEvent.pointerCoords[0].bits));
}
} // namespace android
diff --git a/services/inputflinger/tests/InputClassifier_test.cpp b/services/inputflinger/tests/InputProcessor_test.cpp
similarity index 75%
rename from services/inputflinger/tests/InputClassifier_test.cpp
rename to services/inputflinger/tests/InputProcessor_test.cpp
index 3a77127..380001c 100644
--- a/services/inputflinger/tests/InputClassifier_test.cpp
+++ b/services/inputflinger/tests/InputProcessor_test.cpp
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-#include "../InputClassifier.h"
+#include "../InputProcessor.h"
#include <gtest/gtest.h>
#include <gui/constants.h>
@@ -31,7 +31,7 @@
namespace android {
-// --- InputClassifierTest ---
+// --- InputProcessorTest ---
static NotifyMotionArgs generateBasicMotionArgs() {
// Create a basic motion event for testing
@@ -56,105 +56,104 @@
return motionArgs;
}
-class InputClassifierTest : public testing::Test {
+class InputProcessorTest : public testing::Test {
protected:
TestInputListener mTestListener;
- std::unique_ptr<InputClassifierInterface> mClassifier;
+ std::unique_ptr<InputProcessorInterface> mProcessor;
- void SetUp() override { mClassifier = std::make_unique<InputClassifier>(mTestListener); }
+ void SetUp() override { mProcessor = std::make_unique<InputProcessor>(mTestListener); }
};
/**
- * Create a basic configuration change and send it to input classifier.
+ * Create a basic configuration change and send it to input processor.
* Expect that the event is received by the next input stage, unmodified.
*/
-TEST_F(InputClassifierTest, SendToNextStage_NotifyConfigurationChangedArgs) {
- // Create a basic configuration change and send to classifier
- NotifyConfigurationChangedArgs args(1/*sequenceNum*/, 2/*eventTime*/);
+TEST_F(InputProcessorTest, SendToNextStage_NotifyConfigurationChangedArgs) {
+ // Create a basic configuration change and send to processor
+ NotifyConfigurationChangedArgs args(1 /*sequenceNum*/, 2 /*eventTime*/);
- mClassifier->notifyConfigurationChanged(&args);
+ mProcessor->notifyConfigurationChanged(&args);
NotifyConfigurationChangedArgs outArgs;
ASSERT_NO_FATAL_FAILURE(mTestListener.assertNotifyConfigurationChangedWasCalled(&outArgs));
ASSERT_EQ(args, outArgs);
}
-TEST_F(InputClassifierTest, SendToNextStage_NotifyKeyArgs) {
- // Create a basic key event and send to classifier
+TEST_F(InputProcessorTest, SendToNextStage_NotifyKeyArgs) {
+ // Create a basic key event and send to processor
NotifyKeyArgs args(1 /*sequenceNum*/, 2 /*eventTime*/, 21 /*readTime*/, 3 /*deviceId*/,
AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_DEFAULT, 0 /*policyFlags*/,
AKEY_EVENT_ACTION_DOWN, 4 /*flags*/, AKEYCODE_HOME, 5 /*scanCode*/,
AMETA_NONE, 6 /*downTime*/);
- mClassifier->notifyKey(&args);
+ mProcessor->notifyKey(&args);
NotifyKeyArgs outArgs;
ASSERT_NO_FATAL_FAILURE(mTestListener.assertNotifyKeyWasCalled(&outArgs));
ASSERT_EQ(args, outArgs);
}
-
/**
- * Create a basic motion event and send it to input classifier.
+ * Create a basic motion event and send it to input processor.
* Expect that the event is received by the next input stage, unmodified.
*/
-TEST_F(InputClassifierTest, SendToNextStage_NotifyMotionArgs) {
+TEST_F(InputProcessorTest, SendToNextStage_NotifyMotionArgs) {
NotifyMotionArgs motionArgs = generateBasicMotionArgs();
- mClassifier->notifyMotion(&motionArgs);
+ mProcessor->notifyMotion(&motionArgs);
NotifyMotionArgs args;
ASSERT_NO_FATAL_FAILURE(mTestListener.assertNotifyMotionWasCalled(&args));
ASSERT_EQ(motionArgs, args);
}
/**
- * Create a basic switch event and send it to input classifier.
+ * Create a basic switch event and send it to input processor.
* Expect that the event is received by the next input stage, unmodified.
*/
-TEST_F(InputClassifierTest, SendToNextStage_NotifySwitchArgs) {
- NotifySwitchArgs args(1/*sequenceNum*/, 2/*eventTime*/, 3/*policyFlags*/, 4/*switchValues*/,
- 5/*switchMask*/);
+TEST_F(InputProcessorTest, SendToNextStage_NotifySwitchArgs) {
+ NotifySwitchArgs args(1 /*sequenceNum*/, 2 /*eventTime*/, 3 /*policyFlags*/, 4 /*switchValues*/,
+ 5 /*switchMask*/);
- mClassifier->notifySwitch(&args);
+ mProcessor->notifySwitch(&args);
NotifySwitchArgs outArgs;
ASSERT_NO_FATAL_FAILURE(mTestListener.assertNotifySwitchWasCalled(&outArgs));
ASSERT_EQ(args, outArgs);
}
/**
- * Create a basic device reset event and send it to input classifier.
+ * Create a basic device reset event and send it to input processor.
* Expect that the event is received by the next input stage, unmodified.
*/
-TEST_F(InputClassifierTest, SendToNextStage_NotifyDeviceResetArgs) {
- NotifyDeviceResetArgs args(1/*sequenceNum*/, 2/*eventTime*/, 3/*deviceId*/);
+TEST_F(InputProcessorTest, SendToNextStage_NotifyDeviceResetArgs) {
+ NotifyDeviceResetArgs args(1 /*sequenceNum*/, 2 /*eventTime*/, 3 /*deviceId*/);
- mClassifier->notifyDeviceReset(&args);
+ mProcessor->notifyDeviceReset(&args);
NotifyDeviceResetArgs outArgs;
ASSERT_NO_FATAL_FAILURE(mTestListener.assertNotifyDeviceResetWasCalled(&outArgs));
ASSERT_EQ(args, outArgs);
}
-TEST_F(InputClassifierTest, SetMotionClassifier_Enabled) {
- mClassifier->setMotionClassifierEnabled(true);
+TEST_F(InputProcessorTest, SetMotionClassifier_Enabled) {
+ mProcessor->setMotionClassifierEnabled(true);
}
-TEST_F(InputClassifierTest, SetMotionClassifier_Disabled) {
- mClassifier->setMotionClassifierEnabled(false);
+TEST_F(InputProcessorTest, SetMotionClassifier_Disabled) {
+ mProcessor->setMotionClassifierEnabled(false);
}
/**
* Try to break it by calling setMotionClassifierEnabled multiple times.
*/
-TEST_F(InputClassifierTest, SetMotionClassifier_Multiple) {
- mClassifier->setMotionClassifierEnabled(true);
- mClassifier->setMotionClassifierEnabled(true);
- mClassifier->setMotionClassifierEnabled(true);
- mClassifier->setMotionClassifierEnabled(false);
- mClassifier->setMotionClassifierEnabled(false);
- mClassifier->setMotionClassifierEnabled(true);
- mClassifier->setMotionClassifierEnabled(true);
- mClassifier->setMotionClassifierEnabled(true);
+TEST_F(InputProcessorTest, SetMotionClassifier_Multiple) {
+ mProcessor->setMotionClassifierEnabled(true);
+ mProcessor->setMotionClassifierEnabled(true);
+ mProcessor->setMotionClassifierEnabled(true);
+ mProcessor->setMotionClassifierEnabled(false);
+ mProcessor->setMotionClassifierEnabled(false);
+ mProcessor->setMotionClassifierEnabled(true);
+ mProcessor->setMotionClassifierEnabled(true);
+ mProcessor->setMotionClassifierEnabled(true);
}
/**
- * A minimal implementation of IInputClassifier.
+ * A minimal implementation of IInputProcessor.
*/
class TestHal : public aidl::android::hardware::input::processor::BnInputProcessor {
::ndk::ScopedAStatus classify(
@@ -212,7 +211,7 @@
NotifyMotionArgs motionArgs = generateBasicMotionArgs();
std::vector<int16_t> videoData = {1, 2, 3, 4};
- timeval timestamp = { 1, 1};
+ timeval timestamp = {1, 1};
TouchVideoFrame frame(2, 2, std::move(videoData), timestamp);
motionArgs.videoFrames = {frame};
@@ -228,11 +227,11 @@
NotifyMotionArgs motionArgs = generateBasicMotionArgs();
std::vector<int16_t> videoData1 = {1, 2, 3, 4};
- timeval timestamp1 = { 1, 1};
+ timeval timestamp1 = {1, 1};
TouchVideoFrame frame1(2, 2, std::move(videoData1), timestamp1);
std::vector<int16_t> videoData2 = {6, 6, 6, 6};
- timeval timestamp2 = { 1, 2};
+ timeval timestamp2 = {1, 2};
TouchVideoFrame frame2(2, 2, std::move(videoData2), timestamp2);
motionArgs.videoFrames = {frame1, frame2};
@@ -253,7 +252,7 @@
* Make sure MotionClassifier does not crash when a device is reset.
*/
TEST_F(MotionClassifierTest, DeviceReset_DoesNotCrash) {
- NotifyDeviceResetArgs args(1/*sequenceNum*/, 2/*eventTime*/, 3/*deviceId*/);
+ NotifyDeviceResetArgs args(1 /*sequenceNum*/, 2 /*eventTime*/, 3 /*deviceId*/);
ASSERT_NO_FATAL_FAILURE(mMotionClassifier->reset(args));
}
diff --git a/services/inputflinger/tests/InputReader_test.cpp b/services/inputflinger/tests/InputReader_test.cpp
index dcd8521..e80a956 100644
--- a/services/inputflinger/tests/InputReader_test.cpp
+++ b/services/inputflinger/tests/InputReader_test.cpp
@@ -1332,7 +1332,7 @@
protected:
sp<FakeInputReaderPolicy> mFakePolicy;
- void SetUp() override { mFakePolicy = new FakeInputReaderPolicy(); }
+ void SetUp() override { mFakePolicy = sp<FakeInputReaderPolicy>::make(); }
void TearDown() override { mFakePolicy.clear(); }
};
@@ -1570,7 +1570,7 @@
void SetUp() override {
mFakeEventHub = std::make_unique<FakeEventHub>();
- mFakePolicy = new FakeInputReaderPolicy();
+ mFakePolicy = sp<FakeInputReaderPolicy>::make();
mFakeListener = std::make_unique<TestInputListener>();
mReader = std::make_unique<InstrumentedInputReader>(mFakeEventHub, mFakePolicy,
@@ -2254,7 +2254,7 @@
std::shared_ptr<FakePointerController> mFakePointerController;
void SetUp() override {
- mFakePolicy = new FakeInputReaderPolicy();
+ mFakePolicy = sp<FakeInputReaderPolicy>::make();
mFakePointerController = std::make_shared<FakePointerController>();
mFakePolicy->setPointerController(mFakePointerController);
mTestListener = std::make_unique<TestInputListener>(2000ms /*eventHappenedTimeout*/,
@@ -2653,7 +2653,7 @@
void SetUp() override {
mFakeEventHub = std::make_unique<FakeEventHub>();
- mFakePolicy = new FakeInputReaderPolicy();
+ mFakePolicy = sp<FakeInputReaderPolicy>::make();
mFakeListener = std::make_unique<TestInputListener>();
mReader = std::make_unique<InstrumentedInputReader>(mFakeEventHub, mFakePolicy,
*mFakeListener);
@@ -2940,7 +2940,7 @@
virtual void SetUp(ftl::Flags<InputDeviceClass> classes) {
mFakeEventHub = std::make_unique<FakeEventHub>();
- mFakePolicy = new FakeInputReaderPolicy();
+ mFakePolicy = sp<FakeInputReaderPolicy>::make();
mFakeListener = std::make_unique<TestInputListener>();
mReader = std::make_unique<InstrumentedInputReader>(mFakeEventHub, mFakePolicy,
*mFakeListener);
@@ -6706,9 +6706,7 @@
NotifyMotionArgs motionArgs;
// Down.
- int32_t x = 100;
- int32_t y = 200;
- processDown(mapper, x, y);
+ processDown(mapper, 100, 200);
processSync(mapper);
// We should receive a down event
@@ -9835,7 +9833,7 @@
virtual void SetUp(ftl::Flags<InputDeviceClass> classes) {
mFakeEventHub = std::make_unique<FakeEventHub>();
- mFakePolicy = new FakeInputReaderPolicy();
+ mFakePolicy = sp<FakeInputReaderPolicy>::make();
mFakeListener = std::make_unique<TestInputListener>();
mReader = std::make_unique<InstrumentedInputReader>(mFakeEventHub, mFakePolicy,
*mFakeListener);
diff --git a/services/inputflinger/tests/LatencyTracker_test.cpp b/services/inputflinger/tests/LatencyTracker_test.cpp
index 89c0741..1f4b248 100644
--- a/services/inputflinger/tests/LatencyTracker_test.cpp
+++ b/services/inputflinger/tests/LatencyTracker_test.cpp
@@ -44,7 +44,7 @@
graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 9;
graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 10;
expectedCT.setGraphicsTimeline(std::move(graphicsTimeline));
- t.connectionTimelines.emplace(new BBinder(), std::move(expectedCT));
+ t.connectionTimelines.emplace(sp<BBinder>::make(), std::move(expectedCT));
return t;
}
@@ -56,8 +56,8 @@
sp<IBinder> connection2;
void SetUp() override {
- connection1 = new BBinder();
- connection2 = new BBinder();
+ connection1 = sp<BBinder>::make();
+ connection2 = sp<BBinder>::make();
mTracker = std::make_unique<LatencyTracker>(this);
}
diff --git a/services/inputflinger/tests/UnwantedInteractionBlocker_test.cpp b/services/inputflinger/tests/UnwantedInteractionBlocker_test.cpp
index 8af3871..f2a3964 100644
--- a/services/inputflinger/tests/UnwantedInteractionBlocker_test.cpp
+++ b/services/inputflinger/tests/UnwantedInteractionBlocker_test.cpp
@@ -405,11 +405,11 @@
};
/**
- * Create a basic configuration change and send it to input classifier.
+ * Create a basic configuration change and send it to input processor.
* Expect that the event is received by the next input stage, unmodified.
*/
TEST_F(UnwantedInteractionBlockerTest, ConfigurationChangedIsPassedToNextListener) {
- // Create a basic configuration change and send to classifier
+ // Create a basic configuration change and send to blocker
NotifyConfigurationChangedArgs args(1 /*sequenceNum*/, 2 /*eventTime*/);
mBlocker->notifyConfigurationChanged(&args);
@@ -423,7 +423,7 @@
* to next stage unmodified.
*/
TEST_F(UnwantedInteractionBlockerTest, KeyIsPassedToNextListener) {
- // Create a basic key event and send to classifier
+ // Create a basic key event and send to blocker
NotifyKeyArgs args(1 /*sequenceNum*/, 2 /*eventTime*/, 21 /*readTime*/, 3 /*deviceId*/,
AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_DEFAULT, 0 /*policyFlags*/,
AKEY_EVENT_ACTION_DOWN, 4 /*flags*/, AKEYCODE_HOME, 5 /*scanCode*/,
diff --git a/services/inputflinger/tests/fuzzers/LatencyTrackerFuzzer.cpp b/services/inputflinger/tests/fuzzers/LatencyTrackerFuzzer.cpp
index 4f066ad..72780fb 100644
--- a/services/inputflinger/tests/fuzzers/LatencyTrackerFuzzer.cpp
+++ b/services/inputflinger/tests/fuzzers/LatencyTrackerFuzzer.cpp
@@ -42,7 +42,7 @@
if (useExistingToken) {
return tokens[fdp.ConsumeIntegralInRange<size_t>(0ul, tokens.size() - 1)];
}
- return new BBinder();
+ return sp<BBinder>::make();
}
extern "C" int LLVMFuzzerTestOneInput(uint8_t* data, size_t size) {
@@ -54,7 +54,7 @@
// Make some pre-defined tokens to ensure that some timelines are complete.
std::array<sp<IBinder> /*token*/, 10> predefinedTokens;
for (size_t i = 0; i < predefinedTokens.size(); i++) {
- predefinedTokens[i] = new BBinder();
+ predefinedTokens[i] = sp<BBinder>::make();
}
// Randomly invoke LatencyTracker api's until randomness is exhausted.
diff --git a/services/surfaceflinger/Android.bp b/services/surfaceflinger/Android.bp
index a8ba15f..76429ff 100644
--- a/services/surfaceflinger/Android.bp
+++ b/services/surfaceflinger/Android.bp
@@ -18,6 +18,7 @@
"-Wunused",
"-Wunreachable-code",
"-Wconversion",
+ "-DANDROID_UTILS_REF_BASE_DISABLE_IMPLICIT_CONSTRUCTION",
],
}
@@ -145,7 +146,6 @@
"ClientCache.cpp",
"Client.cpp",
"EffectLayer.cpp",
- "ContainerLayer.cpp",
"DisplayDevice.cpp",
"DisplayHardware/AidlComposerHal.cpp",
"DisplayHardware/HidlComposerHal.cpp",
diff --git a/services/surfaceflinger/BufferStateLayer.cpp b/services/surfaceflinger/BufferStateLayer.cpp
index 5656e05..51a5445 100644
--- a/services/surfaceflinger/BufferStateLayer.cpp
+++ b/services/surfaceflinger/BufferStateLayer.cpp
@@ -134,7 +134,7 @@
: Layer(args),
mTextureName(args.textureName),
mCompositionState{mFlinger->getCompositionEngine().createLayerFECompositionState()},
- mHwcSlotGenerator(new HwcSlotGenerator()) {
+ mHwcSlotGenerator(sp<HwcSlotGenerator>::make()) {
ALOGV("Creating Layer %s", getDebugName());
mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
@@ -812,7 +812,7 @@
args.textureName = mTextureName;
sp<BufferStateLayer> layer = mFlinger->getFactory().createBufferStateLayer(args);
layer->mHwcSlotGenerator = mHwcSlotGenerator;
- layer->setInitialValuesForClone(this);
+ layer->setInitialValuesForClone(sp<Layer>::fromExisting(this));
return layer;
}
@@ -1573,7 +1573,8 @@
void BufferStateLayer::setInitialValuesForClone(const sp<Layer>& clonedFrom) {
Layer::setInitialValuesForClone(clonedFrom);
- sp<BufferStateLayer> bufferClonedFrom = static_cast<BufferStateLayer*>(clonedFrom.get());
+ sp<BufferStateLayer> bufferClonedFrom =
+ sp<BufferStateLayer>::fromExisting(static_cast<BufferStateLayer*>(clonedFrom.get()));
mPremultipliedAlpha = bufferClonedFrom->mPremultipliedAlpha;
mPotentialCursor = bufferClonedFrom->mPotentialCursor;
mProtectedByApp = bufferClonedFrom->mProtectedByApp;
@@ -1586,7 +1587,8 @@
return;
}
- sp<BufferStateLayer> clonedFrom = static_cast<BufferStateLayer*>(getClonedFrom().get());
+ sp<BufferStateLayer> clonedFrom = sp<BufferStateLayer>::fromExisting(
+ static_cast<BufferStateLayer*>(getClonedFrom().get()));
mBufferInfo = clonedFrom->mBufferInfo;
mSidebandStream = clonedFrom->mSidebandStream;
surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
diff --git a/services/surfaceflinger/Client.cpp b/services/surfaceflinger/Client.cpp
index b27055d..3685bb4 100644
--- a/services/surfaceflinger/Client.cpp
+++ b/services/surfaceflinger/Client.cpp
@@ -83,8 +83,8 @@
sp<IBinder> handle;
int32_t layerId;
uint32_t transformHint;
- LayerCreationArgs args(mFlinger.get(), this, name.c_str(), static_cast<uint32_t>(flags),
- std::move(metadata));
+ LayerCreationArgs args(mFlinger.get(), sp<Client>::fromExisting(this), name.c_str(),
+ static_cast<uint32_t>(flags), std::move(metadata));
const status_t status =
mFlinger->createLayer(args, &handle, parent, &layerId, nullptr, &transformHint);
if (status == NO_ERROR) {
@@ -137,7 +137,8 @@
gui::MirrorSurfaceResult* outResult) {
sp<IBinder> handle;
int32_t layerId;
- LayerCreationArgs args(mFlinger.get(), this, "MirrorRoot", 0 /* flags */, gui::LayerMetadata());
+ LayerCreationArgs args(mFlinger.get(), sp<Client>::fromExisting(this), "MirrorRoot",
+ 0 /* flags */, gui::LayerMetadata());
status_t status = mFlinger->mirrorLayer(args, mirrorFromHandle, &handle, &layerId);
if (status == NO_ERROR) {
outResult->handle = handle;
@@ -146,5 +147,20 @@
return binderStatusFromStatusT(status);
}
+binder::Status Client::mirrorDisplay(int64_t displayId, gui::MirrorSurfaceResult* outResult) {
+ sp<IBinder> handle;
+ int32_t layerId;
+ LayerCreationArgs args(mFlinger.get(), sp<Client>::fromExisting(this),
+ "MirrorRoot-" + std::to_string(displayId), 0 /* flags */,
+ gui::LayerMetadata());
+ std::optional<DisplayId> id = DisplayId::fromValue(static_cast<uint64_t>(displayId));
+ status_t status = mFlinger->mirrorDisplay(*id, args, &handle, &layerId);
+ if (status == NO_ERROR) {
+ outResult->handle = handle;
+ outResult->layerId = layerId;
+ }
+ return binderStatusFromStatusT(status);
+}
+
// ---------------------------------------------------------------------------
}; // namespace android
diff --git a/services/surfaceflinger/Client.h b/services/surfaceflinger/Client.h
index 4720d5c..4e59dfd 100644
--- a/services/surfaceflinger/Client.h
+++ b/services/surfaceflinger/Client.h
@@ -59,6 +59,8 @@
binder::Status mirrorSurface(const sp<IBinder>& mirrorFromHandle,
gui::MirrorSurfaceResult* outResult) override;
+ binder::Status mirrorDisplay(int64_t displayId, gui::MirrorSurfaceResult* outResult) override;
+
// constant
sp<SurfaceFlinger> mFlinger;
diff --git a/services/surfaceflinger/ClientCache.cpp b/services/surfaceflinger/ClientCache.cpp
index 3c7b9d9..cf932a8 100644
--- a/services/surfaceflinger/ClientCache.cpp
+++ b/services/surfaceflinger/ClientCache.cpp
@@ -30,7 +30,7 @@
ANDROID_SINGLETON_STATIC_INSTANCE(ClientCache);
-ClientCache::ClientCache() : mDeathRecipient(new CacheDeathRecipient) {}
+ClientCache::ClientCache() : mDeathRecipient(sp<CacheDeathRecipient>::make()) {}
bool ClientCache::getBuffer(const client_cache_t& cacheId,
ClientCacheBuffer** outClientCacheBuffer) {
diff --git a/services/surfaceflinger/CompositionEngine/src/Display.cpp b/services/surfaceflinger/CompositionEngine/src/Display.cpp
index ea856e4..09adaed 100644
--- a/services/surfaceflinger/CompositionEngine/src/Display.cpp
+++ b/services/surfaceflinger/CompositionEngine/src/Display.cpp
@@ -196,7 +196,7 @@
});
if (hasQueuedFrames) {
- releasedLayers.emplace_back(layerFE);
+ releasedLayers.emplace_back(wp<LayerFE>::fromExisting(layerFE));
}
}
diff --git a/services/surfaceflinger/CompositionEngine/src/Output.cpp b/services/surfaceflinger/CompositionEngine/src/Output.cpp
index aea6798..a98aed2 100644
--- a/services/surfaceflinger/CompositionEngine/src/Output.cpp
+++ b/services/surfaceflinger/CompositionEngine/src/Output.cpp
@@ -1160,7 +1160,8 @@
if (isPowerHintSessionEnabled()) {
// get fence end time to know when gpu is complete in display
- setHintSessionGpuFence(std::make_unique<FenceTime>(new Fence(dup(optReadyFence->get()))));
+ setHintSessionGpuFence(
+ std::make_unique<FenceTime>(sp<Fence>::make(dup(optReadyFence->get()))));
}
// swap buffers (presentation)
mRenderSurface->queueBuffer(std::move(*optReadyFence));
@@ -1288,7 +1289,8 @@
ATRACE_NAME("ClientCompositionCacheHit");
outputCompositionState.reusedClientComposition = true;
setExpensiveRenderingExpected(false);
- return base::unique_fd();
+ // b/239944175 pass the fence associated with the buffer.
+ return base::unique_fd(std::move(fd));
}
ATRACE_NAME("ClientCompositionCacheMiss");
mClientCompositionRequestCache->add(tex->getBuffer()->getId(), clientCompositionDisplay,
diff --git a/services/surfaceflinger/CompositionEngine/tests/DisplayTest.cpp b/services/surfaceflinger/CompositionEngine/tests/DisplayTest.cpp
index 344fea3..51ca213 100644
--- a/services/surfaceflinger/CompositionEngine/tests/DisplayTest.cpp
+++ b/services/surfaceflinger/CompositionEngine/tests/DisplayTest.cpp
@@ -194,7 +194,7 @@
StrictMock<Hwc2::mock::PowerAdvisor> mPowerAdvisor;
StrictMock<renderengine::mock::RenderEngine> mRenderEngine;
StrictMock<mock::CompositionEngine> mCompositionEngine;
- sp<mock::NativeWindow> mNativeWindow = new StrictMock<mock::NativeWindow>();
+ sp<mock::NativeWindow> mNativeWindow = sp<StrictMock<mock::NativeWindow>>::make();
};
struct PartialMockDisplayTestCommon : public DisplayTestCommon {
@@ -524,7 +524,7 @@
auto args = getDisplayCreationArgsForGpuVirtualDisplay();
std::shared_ptr<impl::Display> gpuDisplay = impl::createDisplay(mCompositionEngine, args);
- sp<mock::LayerFE> layerXLayerFE = new StrictMock<mock::LayerFE>();
+ sp<mock::LayerFE> layerXLayerFE = sp<StrictMock<mock::LayerFE>>::make();
{
Output::ReleasedLayers releasedLayers;
@@ -542,7 +542,7 @@
}
TEST_F(DisplaySetReleasedLayersTest, doesNothingIfNoLayersWithQueuedFrames) {
- sp<mock::LayerFE> layerXLayerFE = new StrictMock<mock::LayerFE>();
+ sp<mock::LayerFE> layerXLayerFE = sp<StrictMock<mock::LayerFE>>::make();
{
Output::ReleasedLayers releasedLayers;
@@ -558,7 +558,7 @@
}
TEST_F(DisplaySetReleasedLayersTest, setReleasedLayers) {
- sp<mock::LayerFE> unknownLayer = new StrictMock<mock::LayerFE>();
+ sp<mock::LayerFE> unknownLayer = sp<StrictMock<mock::LayerFE>>::make();
CompositionRefreshArgs refreshArgs;
refreshArgs.layersWithQueuedFrames.push_back(mLayer1.layerFE);
@@ -897,9 +897,9 @@
}
TEST_F(DisplayPresentAndGetFrameFencesTest, returnsPresentAndLayerFences) {
- sp<Fence> presentFence = new Fence();
- sp<Fence> layer1Fence = new Fence();
- sp<Fence> layer2Fence = new Fence();
+ sp<Fence> presentFence = sp<Fence>::make();
+ sp<Fence> layer1Fence = sp<Fence>::make();
+ sp<Fence> layer2Fence = sp<Fence>::make();
EXPECT_CALL(mHwComposer, presentAndGetReleaseFences(HalDisplayId(DEFAULT_DISPLAY_ID), _, _))
.Times(1);
@@ -1018,8 +1018,8 @@
NiceMock<android::mock::HWComposer> mHwComposer;
NiceMock<Hwc2::mock::PowerAdvisor> mPowerAdvisor;
NiceMock<mock::CompositionEngine> mCompositionEngine;
- sp<mock::NativeWindow> mNativeWindow = new NiceMock<mock::NativeWindow>();
- sp<mock::DisplaySurface> mDisplaySurface = new NiceMock<mock::DisplaySurface>();
+ sp<mock::NativeWindow> mNativeWindow = sp<NiceMock<mock::NativeWindow>>::make();
+ sp<mock::DisplaySurface> mDisplaySurface = sp<NiceMock<mock::DisplaySurface>>::make();
std::shared_ptr<Display> mDisplay;
impl::RenderSurface* mRenderSurface;
diff --git a/services/surfaceflinger/CompositionEngine/tests/HwcBufferCacheTest.cpp b/services/surfaceflinger/CompositionEngine/tests/HwcBufferCacheTest.cpp
index 00eafb1..7197780 100644
--- a/services/surfaceflinger/CompositionEngine/tests/HwcBufferCacheTest.cpp
+++ b/services/surfaceflinger/CompositionEngine/tests/HwcBufferCacheTest.cpp
@@ -66,8 +66,10 @@
}
impl::HwcBufferCache mCache;
- sp<GraphicBuffer> mBuffer1{new GraphicBuffer(1, 1, HAL_PIXEL_FORMAT_RGBA_8888, 1, 0)};
- sp<GraphicBuffer> mBuffer2{new GraphicBuffer(1, 1, HAL_PIXEL_FORMAT_RGBA_8888, 1, 0)};
+ sp<GraphicBuffer> mBuffer1 =
+ sp<GraphicBuffer>::make(1u, 1u, HAL_PIXEL_FORMAT_RGBA_8888, 1u, 0u);
+ sp<GraphicBuffer> mBuffer2 =
+ sp<GraphicBuffer>::make(1u, 1u, HAL_PIXEL_FORMAT_RGBA_8888, 1u, 0u);
};
TEST_F(HwcBufferCacheTest, cacheWorksForSlotZero) {
diff --git a/services/surfaceflinger/CompositionEngine/tests/OutputLayerTest.cpp b/services/surfaceflinger/CompositionEngine/tests/OutputLayerTest.cpp
index 5290bd9..0f7dce8 100644
--- a/services/surfaceflinger/CompositionEngine/tests/OutputLayerTest.cpp
+++ b/services/surfaceflinger/CompositionEngine/tests/OutputLayerTest.cpp
@@ -955,11 +955,11 @@
reinterpret_cast<native_handle_t*>(1031);
const sp<GraphicBuffer> OutputLayerWriteStateToHWCTest::kBuffer;
const sp<GraphicBuffer> OutputLayerWriteStateToHWCTest::kOverrideBuffer =
- new GraphicBuffer(4, 5, PIXEL_FORMAT_RGBA_8888,
- AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN |
- AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN);
+ sp<GraphicBuffer>::make(4, 5, PIXEL_FORMAT_RGBA_8888,
+ AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN |
+ AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN);
const sp<Fence> OutputLayerWriteStateToHWCTest::kFence;
-const sp<Fence> OutputLayerWriteStateToHWCTest::kOverrideFence = new Fence();
+const sp<Fence> OutputLayerWriteStateToHWCTest::kOverrideFence = sp<Fence>::make();
const std::string OutputLayerWriteStateToHWCTest::kLayerGenericMetadata1Key =
"com.example.metadata.1";
const std::vector<uint8_t> OutputLayerWriteStateToHWCTest::kLayerGenericMetadata1Value{{1, 2, 3}};
diff --git a/services/surfaceflinger/CompositionEngine/tests/OutputTest.cpp b/services/surfaceflinger/CompositionEngine/tests/OutputTest.cpp
index cf12890..657084a 100644
--- a/services/surfaceflinger/CompositionEngine/tests/OutputTest.cpp
+++ b/services/surfaceflinger/CompositionEngine/tests/OutputTest.cpp
@@ -293,7 +293,7 @@
InjectedLayer layer;
layer.outputLayerState.overrideInfo.buffer = std::make_shared<
renderengine::impl::
- ExternalTexture>(new GraphicBuffer(), renderEngine,
+ ExternalTexture>(sp<GraphicBuffer>::make(), renderEngine,
renderengine::impl::ExternalTexture::Usage::READABLE |
renderengine::impl::ExternalTexture::Usage::WRITEABLE);
injectOutputLayer(layer);
@@ -1017,7 +1017,7 @@
std::shared_ptr<renderengine::ExternalTexture> buffer = std::make_shared<
renderengine::impl::
- ExternalTexture>(new GraphicBuffer(), renderEngine,
+ ExternalTexture>(sp<GraphicBuffer>::make(), renderEngine,
renderengine::impl::ExternalTexture::Usage::READABLE |
renderengine::impl::ExternalTexture::Usage::WRITEABLE);
layer1.outputLayerState.overrideInfo.buffer = buffer;
@@ -3449,7 +3449,7 @@
StrictMock<OutputPartialMock> mOutput;
std::shared_ptr<renderengine::ExternalTexture> mOutputBuffer = std::make_shared<
renderengine::impl::
- ExternalTexture>(new GraphicBuffer(), mRenderEngine,
+ ExternalTexture>(sp<GraphicBuffer>::make(), mRenderEngine,
renderengine::impl::ExternalTexture::Usage::READABLE |
renderengine::impl::ExternalTexture::Usage::WRITEABLE);
@@ -3687,7 +3687,7 @@
const auto otherOutputBuffer = std::make_shared<
renderengine::impl::
- ExternalTexture>(new GraphicBuffer(), mRenderEngine,
+ ExternalTexture>(sp<GraphicBuffer>::make(), mRenderEngine,
renderengine::impl::ExternalTexture::Usage::READABLE |
renderengine::impl::ExternalTexture::Usage::WRITEABLE);
EXPECT_CALL(*mRenderSurface, dequeueBuffer(_))
diff --git a/services/surfaceflinger/CompositionEngine/tests/RenderSurfaceTest.cpp b/services/surfaceflinger/CompositionEngine/tests/RenderSurfaceTest.cpp
index e5f9ebf..8c793b0 100644
--- a/services/surfaceflinger/CompositionEngine/tests/RenderSurfaceTest.cpp
+++ b/services/surfaceflinger/CompositionEngine/tests/RenderSurfaceTest.cpp
@@ -61,8 +61,8 @@
StrictMock<renderengine::mock::RenderEngine> mRenderEngine;
StrictMock<mock::CompositionEngine> mCompositionEngine;
StrictMock<mock::Display> mDisplay;
- sp<mock::NativeWindow> mNativeWindow = new StrictMock<mock::NativeWindow>();
- sp<mock::DisplaySurface> mDisplaySurface = new StrictMock<mock::DisplaySurface>();
+ sp<mock::NativeWindow> mNativeWindow = sp<StrictMock<mock::NativeWindow>>::make();
+ sp<mock::DisplaySurface> mDisplaySurface = sp<StrictMock<mock::DisplaySurface>>::make();
impl::RenderSurface mSurface{mCompositionEngine, mDisplay,
RenderSurfaceCreationArgsBuilder()
.setDisplayWidth(DEFAULT_DISPLAY_WIDTH)
@@ -109,7 +109,7 @@
*/
TEST_F(RenderSurfaceTest, getClientTargetAcquireFenceForwardsCall) {
- sp<Fence> fence = new Fence();
+ sp<Fence> fence = sp<Fence>::make();
EXPECT_CALL(*mDisplaySurface, getClientTargetAcquireFence()).WillOnce(ReturnRef(fence));
@@ -234,7 +234,7 @@
*/
TEST_F(RenderSurfaceTest, dequeueBufferObtainsABuffer) {
- sp<GraphicBuffer> buffer = new GraphicBuffer();
+ sp<GraphicBuffer> buffer = sp<GraphicBuffer>::make();
EXPECT_CALL(*mNativeWindow, dequeueBuffer(_, _))
.WillOnce(
@@ -253,7 +253,7 @@
TEST_F(RenderSurfaceTest, queueBufferHandlesNoClientComposition) {
const auto buffer = std::make_shared<
renderengine::impl::
- ExternalTexture>(new GraphicBuffer(), mRenderEngine,
+ ExternalTexture>(sp<GraphicBuffer>::make(), mRenderEngine,
renderengine::impl::ExternalTexture::Usage::READABLE |
renderengine::impl::ExternalTexture::Usage::WRITEABLE);
mSurface.mutableTextureForTest() = buffer;
@@ -271,8 +271,9 @@
}
TEST_F(RenderSurfaceTest, queueBufferHandlesClientComposition) {
- const auto buffer = std::make_shared<renderengine::impl::ExternalTexture>(new GraphicBuffer(),
- mRenderEngine, false);
+ const auto buffer =
+ std::make_shared<renderengine::impl::ExternalTexture>(sp<GraphicBuffer>::make(),
+ mRenderEngine, false);
mSurface.mutableTextureForTest() = buffer;
impl::OutputCompositionState state;
@@ -290,8 +291,9 @@
}
TEST_F(RenderSurfaceTest, queueBufferHandlesFlipClientTargetRequest) {
- const auto buffer = std::make_shared<renderengine::impl::ExternalTexture>(new GraphicBuffer(),
- mRenderEngine, false);
+ const auto buffer =
+ std::make_shared<renderengine::impl::ExternalTexture>(sp<GraphicBuffer>::make(),
+ mRenderEngine, false);
mSurface.mutableTextureForTest() = buffer;
impl::OutputCompositionState state;
@@ -309,7 +311,7 @@
}
TEST_F(RenderSurfaceTest, queueBufferHandlesFlipClientTargetRequestWithNoBufferYetDequeued) {
- sp<GraphicBuffer> buffer = new GraphicBuffer();
+ sp<GraphicBuffer> buffer = sp<GraphicBuffer>::make();
impl::OutputCompositionState state;
state.usesClientComposition = false;
@@ -329,8 +331,9 @@
}
TEST_F(RenderSurfaceTest, queueBufferHandlesNativeWindowQueueBufferFailureOnVirtualDisplay) {
- const auto buffer = std::make_shared<renderengine::impl::ExternalTexture>(new GraphicBuffer(),
- mRenderEngine, false);
+ const auto buffer =
+ std::make_shared<renderengine::impl::ExternalTexture>(sp<GraphicBuffer>::make(),
+ mRenderEngine, false);
mSurface.mutableTextureForTest() = buffer;
impl::OutputCompositionState state;
diff --git a/services/surfaceflinger/CompositionEngine/tests/planner/FlattenerTest.cpp b/services/surfaceflinger/CompositionEngine/tests/planner/FlattenerTest.cpp
index 50e3a28..200278c 100644
--- a/services/surfaceflinger/CompositionEngine/tests/planner/FlattenerTest.cpp
+++ b/services/surfaceflinger/CompositionEngine/tests/planner/FlattenerTest.cpp
@@ -108,11 +108,12 @@
testLayer->outputLayerCompositionState.visibleRegion =
Region(Rect(pos + 1, pos + 1, pos + 2, pos + 2));
+ const auto kUsageFlags =
+ static_cast<uint64_t>(GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
+ GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE);
testLayer->layerFECompositionState.buffer =
- new GraphicBuffer(100, 100, HAL_PIXEL_FORMAT_RGBA_8888, 1,
- GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
- GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE,
- "output");
+ sp<GraphicBuffer>::make(100u, 100u, HAL_PIXEL_FORMAT_RGBA_8888, 1u, kUsageFlags,
+ "output");
testLayer->layerFE = sp<mock::LayerFE>::make();
diff --git a/services/surfaceflinger/CompositionEngine/tests/planner/LayerStateTest.cpp b/services/surfaceflinger/CompositionEngine/tests/planner/LayerStateTest.cpp
index 5c6e8da..47b6820 100644
--- a/services/surfaceflinger/CompositionEngine/tests/planner/LayerStateTest.cpp
+++ b/services/surfaceflinger/CompositionEngine/tests/planner/LayerStateTest.cpp
@@ -112,6 +112,9 @@
sp<mock::LayerFE> mLayerFE = sp<mock::LayerFE>::make();
mock::OutputLayer mOutputLayer;
std::unique_ptr<LayerState> mLayerState;
+
+ static constexpr auto kUsageFlags = static_cast<uint32_t>(
+ AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN | AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN);
};
TEST_F(LayerStateTest, getOutputLayer) {
@@ -346,7 +349,7 @@
TEST_F(LayerStateTest, updateBuffer) {
OutputLayerCompositionState outputLayerCompositionState;
LayerFECompositionState layerFECompositionState;
- layerFECompositionState.buffer = new GraphicBuffer();
+ layerFECompositionState.buffer = sp<GraphicBuffer>::make();
setupMocksForLayer(mOutputLayer, *mLayerFE, outputLayerCompositionState,
layerFECompositionState);
mLayerState = std::make_unique<LayerState>(&mOutputLayer);
@@ -354,7 +357,7 @@
mock::OutputLayer newOutputLayer;
sp<mock::LayerFE> newLayerFE = sp<mock::LayerFE>::make();
LayerFECompositionState layerFECompositionStateTwo;
- layerFECompositionStateTwo.buffer = new GraphicBuffer();
+ layerFECompositionStateTwo.buffer = sp<GraphicBuffer>::make();
setupMocksForLayer(newOutputLayer, *newLayerFE, outputLayerCompositionState,
layerFECompositionStateTwo);
ftl::Flags<LayerStateField> updates = mLayerState->update(&newOutputLayer);
@@ -364,7 +367,7 @@
TEST_F(LayerStateTest, updateBufferSingleBufferedLegacy) {
OutputLayerCompositionState outputLayerCompositionState;
LayerFECompositionState layerFECompositionState;
- layerFECompositionState.buffer = new GraphicBuffer();
+ layerFECompositionState.buffer = sp<GraphicBuffer>::make();
setupMocksForLayer(mOutputLayer, *mLayerFE, outputLayerCompositionState,
layerFECompositionState);
mLayerState = std::make_unique<LayerState>(&mOutputLayer);
@@ -372,7 +375,7 @@
mock::OutputLayer newOutputLayer;
sp<mock::LayerFE> newLayerFE = sp<mock::LayerFE>::make();
LayerFECompositionState layerFECompositionStateTwo;
- layerFECompositionStateTwo.buffer = new GraphicBuffer();
+ layerFECompositionStateTwo.buffer = sp<GraphicBuffer>::make();
setupMocksForLayer(newOutputLayer, *newLayerFE, outputLayerCompositionState,
layerFECompositionStateTwo);
@@ -388,7 +391,7 @@
TEST_F(LayerStateTest, updateBufferSingleBufferedUsage) {
OutputLayerCompositionState outputLayerCompositionState;
LayerFECompositionState layerFECompositionState;
- layerFECompositionState.buffer = new GraphicBuffer();
+ layerFECompositionState.buffer = sp<GraphicBuffer>::make();
setupMocksForLayer(mOutputLayer, *mLayerFE, outputLayerCompositionState,
layerFECompositionState);
mLayerState = std::make_unique<LayerState>(&mOutputLayer);
@@ -396,7 +399,7 @@
mock::OutputLayer newOutputLayer;
sp<mock::LayerFE> newLayerFE = sp<mock::LayerFE>::make();
LayerFECompositionState layerFECompositionStateTwo;
- layerFECompositionStateTwo.buffer = new GraphicBuffer();
+ layerFECompositionStateTwo.buffer = sp<GraphicBuffer>::make();
layerFECompositionStateTwo.buffer->usage = static_cast<uint64_t>(BufferUsage::FRONT_BUFFER);
setupMocksForLayer(newOutputLayer, *newLayerFE, outputLayerCompositionState,
layerFECompositionStateTwo);
@@ -412,14 +415,14 @@
TEST_F(LayerStateTest, compareBuffer) {
OutputLayerCompositionState outputLayerCompositionState;
LayerFECompositionState layerFECompositionState;
- layerFECompositionState.buffer = new GraphicBuffer();
+ layerFECompositionState.buffer = sp<GraphicBuffer>::make();
setupMocksForLayer(mOutputLayer, *mLayerFE, outputLayerCompositionState,
layerFECompositionState);
mLayerState = std::make_unique<LayerState>(&mOutputLayer);
mock::OutputLayer newOutputLayer;
sp<mock::LayerFE> newLayerFE = sp<mock::LayerFE>::make();
LayerFECompositionState layerFECompositionStateTwo;
- layerFECompositionStateTwo.buffer = new GraphicBuffer();
+ layerFECompositionStateTwo.buffer = sp<GraphicBuffer>::make();
setupMocksForLayer(newOutputLayer, *newLayerFE, outputLayerCompositionState,
layerFECompositionStateTwo);
auto otherLayerState = std::make_unique<LayerState>(&newOutputLayer);
@@ -720,10 +723,7 @@
OutputLayerCompositionState outputLayerCompositionState;
LayerFECompositionState layerFECompositionState;
layerFECompositionState.buffer =
- new GraphicBuffer(1, 1, PIXEL_FORMAT_RGBA_8888,
- AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN |
- AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN,
- "buffer1");
+ sp<GraphicBuffer>::make(1u, 1u, PIXEL_FORMAT_RGBA_8888, kUsageFlags, "buffer1");
setupMocksForLayer(mOutputLayer, *mLayerFE, outputLayerCompositionState,
layerFECompositionState);
mLayerState = std::make_unique<LayerState>(&mOutputLayer);
@@ -732,10 +732,7 @@
sp<mock::LayerFE> newLayerFE = sp<mock::LayerFE>::make();
LayerFECompositionState layerFECompositionStateTwo;
layerFECompositionStateTwo.buffer =
- new GraphicBuffer(1, 1, PIXEL_FORMAT_RGBX_8888,
- AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN |
- AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN,
- "buffer2");
+ sp<GraphicBuffer>::make(1u, 1u, PIXEL_FORMAT_RGBX_8888, kUsageFlags, "buffer2");
setupMocksForLayer(newOutputLayer, *newLayerFE, outputLayerCompositionState,
layerFECompositionStateTwo);
ftl::Flags<LayerStateField> updates = mLayerState->update(&newOutputLayer);
@@ -748,10 +745,7 @@
OutputLayerCompositionState outputLayerCompositionState;
LayerFECompositionState layerFECompositionState;
layerFECompositionState.buffer =
- new GraphicBuffer(1, 1, PIXEL_FORMAT_RGBA_8888,
- AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN |
- AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN,
- "buffer1");
+ sp<GraphicBuffer>::make(1u, 1u, PIXEL_FORMAT_RGBA_8888, kUsageFlags, "buffer1");
setupMocksForLayer(mOutputLayer, *mLayerFE, outputLayerCompositionState,
layerFECompositionState);
mLayerState = std::make_unique<LayerState>(&mOutputLayer);
@@ -759,10 +753,7 @@
sp<mock::LayerFE> newLayerFE = sp<mock::LayerFE>::make();
LayerFECompositionState layerFECompositionStateTwo;
layerFECompositionStateTwo.buffer =
- new GraphicBuffer(1, 1, PIXEL_FORMAT_RGBX_8888,
- AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN |
- AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN,
- "buffer2");
+ sp<GraphicBuffer>::make(1u, 1u, PIXEL_FORMAT_RGBX_8888, kUsageFlags, "buffer2");
setupMocksForLayer(newOutputLayer, *newLayerFE, outputLayerCompositionState,
layerFECompositionStateTwo);
auto otherLayerState = std::make_unique<LayerState>(&newOutputLayer);
@@ -1069,7 +1060,7 @@
TEST_F(LayerStateTest, getNonBufferHash_filtersOutBuffers) {
OutputLayerCompositionState outputLayerCompositionState;
LayerFECompositionState layerFECompositionState;
- layerFECompositionState.buffer = new GraphicBuffer();
+ layerFECompositionState.buffer = sp<GraphicBuffer>::make();
setupMocksForLayer(mOutputLayer, *mLayerFE, outputLayerCompositionState,
layerFECompositionState);
mLayerState = std::make_unique<LayerState>(&mOutputLayer);
@@ -1077,7 +1068,7 @@
mock::OutputLayer newOutputLayer;
sp<mock::LayerFE> newLayerFE = sp<mock::LayerFE>::make();
LayerFECompositionState layerFECompositionStateTwo;
- layerFECompositionStateTwo.buffer = new GraphicBuffer();
+ layerFECompositionStateTwo.buffer = sp<GraphicBuffer>::make();
setupMocksForLayer(newOutputLayer, *newLayerFE, outputLayerCompositionState,
layerFECompositionStateTwo);
auto otherLayerState = std::make_unique<LayerState>(&newOutputLayer);
diff --git a/services/surfaceflinger/CompositionEngine/tests/planner/PredictorTest.cpp b/services/surfaceflinger/CompositionEngine/tests/planner/PredictorTest.cpp
index 68c72e0..35d0ffb 100644
--- a/services/surfaceflinger/CompositionEngine/tests/planner/PredictorTest.cpp
+++ b/services/surfaceflinger/CompositionEngine/tests/planner/PredictorTest.cpp
@@ -228,7 +228,7 @@
}
TEST_F(LayerStackTest, getApproximateMatch_exactMatchesSameBuffer) {
- sp<GraphicBuffer> buffer = new GraphicBuffer();
+ sp<GraphicBuffer> buffer = sp<GraphicBuffer>::make();
mock::OutputLayer outputLayerOne;
sp<mock::LayerFE> layerFEOne = sp<mock::LayerFE>::make();
OutputLayerCompositionState outputLayerCompositionStateOne;
@@ -268,7 +268,7 @@
.dataspace = ui::Dataspace::SRGB,
};
LayerFECompositionState layerFECompositionStateOne;
- layerFECompositionStateOne.buffer = new GraphicBuffer();
+ layerFECompositionStateOne.buffer = sp<GraphicBuffer>::make();
layerFECompositionStateOne.alpha = sAlphaOne;
layerFECompositionStateOne.colorTransformIsIdentity = true;
setupMocksForLayer(outputLayerOne, *layerFEOne, outputLayerCompositionStateOne,
@@ -285,7 +285,7 @@
.dataspace = ui::Dataspace::DISPLAY_P3,
};
LayerFECompositionState layerFECompositionStateTwo;
- layerFECompositionStateTwo.buffer = new GraphicBuffer();
+ layerFECompositionStateTwo.buffer = sp<GraphicBuffer>::make();
layerFECompositionStateTwo.alpha = sAlphaTwo;
layerFECompositionStateTwo.colorTransformIsIdentity = false;
layerFECompositionStateTwo.colorTransform = sMat4One;
@@ -310,7 +310,7 @@
.sourceCrop = sFloatRectOne,
};
LayerFECompositionState layerFECompositionStateOne;
- layerFECompositionStateOne.buffer = new GraphicBuffer();
+ layerFECompositionStateOne.buffer = sp<GraphicBuffer>::make();
setupMocksForLayer(outputLayerOne, *layerFEOne, outputLayerCompositionStateOne,
layerFECompositionStateOne);
LayerState layerStateOne(&outputLayerOne);
@@ -321,7 +321,7 @@
.sourceCrop = sFloatRectTwo,
};
LayerFECompositionState layerFECompositionStateTwo;
- layerFECompositionStateTwo.buffer = new GraphicBuffer();
+ layerFECompositionStateTwo.buffer = sp<GraphicBuffer>::make();
setupMocksForLayer(outputLayerTwo, *layerFETwo, outputLayerCompositionStateTwo,
layerFECompositionStateTwo);
LayerState layerStateTwo(&outputLayerTwo);
diff --git a/services/surfaceflinger/ContainerLayer.cpp b/services/surfaceflinger/ContainerLayer.cpp
deleted file mode 100644
index 3ccc229..0000000
--- a/services/surfaceflinger/ContainerLayer.cpp
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-// TODO(b/129481165): remove the #pragma below and fix conversion issues
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wconversion"
-
-// #define LOG_NDEBUG 0
-#undef LOG_TAG
-#define LOG_TAG "ContainerLayer"
-
-#include "ContainerLayer.h"
-
-namespace android {
-
-ContainerLayer::ContainerLayer(const LayerCreationArgs& args) : Layer(args) {}
-
-ContainerLayer::~ContainerLayer() = default;
-
-bool ContainerLayer::isVisible() const {
- return false;
-}
-
-sp<Layer> ContainerLayer::createClone() {
- sp<ContainerLayer> layer = mFlinger->getFactory().createContainerLayer(
- LayerCreationArgs(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata()));
- layer->setInitialValuesForClone(this);
- return layer;
-}
-
-} // namespace android
-
-// TODO(b/129481165): remove the #pragma below and fix conversion issues
-#pragma clang diagnostic pop // ignored "-Wconversion"
diff --git a/services/surfaceflinger/ContainerLayer.h b/services/surfaceflinger/ContainerLayer.h
deleted file mode 100644
index 9b7bab1..0000000
--- a/services/surfaceflinger/ContainerLayer.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#pragma once
-
-#include <sys/types.h>
-
-#include <cstdint>
-
-#include "Layer.h"
-
-namespace android {
-
-class ContainerLayer : public Layer {
-public:
- explicit ContainerLayer(const LayerCreationArgs&);
- ~ContainerLayer() override;
-
- const char* getType() const override { return "ContainerLayer"; }
- bool isVisible() const override;
-
- bool isCreatedFromMainThread() const override { return true; }
-
-protected:
- bool canDrawShadows() const override { return false; }
- sp<Layer> createClone() override;
-};
-
-} // namespace android
diff --git a/services/surfaceflinger/DisplayDevice.cpp b/services/surfaceflinger/DisplayDevice.cpp
index 8680900..bff301e 100644
--- a/services/surfaceflinger/DisplayDevice.cpp
+++ b/services/surfaceflinger/DisplayDevice.cpp
@@ -136,10 +136,6 @@
mDeviceProductInfo = std::move(info);
}
-uint32_t DisplayDevice::getPageFlipCount() const {
- return mCompositionDisplay->getRenderSurface()->getPageFlipCount();
-}
-
auto DisplayDevice::getInputInfo() const -> InputInfo {
gui::DisplayInfo info;
info.displayId = getLayerStack().id;
diff --git a/services/surfaceflinger/DisplayDevice.h b/services/surfaceflinger/DisplayDevice.h
index 2161436..10fc095 100644
--- a/services/surfaceflinger/DisplayDevice.h
+++ b/services/surfaceflinger/DisplayDevice.h
@@ -259,7 +259,6 @@
/* ------------------------------------------------------------------------
* Debugging
*/
- uint32_t getPageFlipCount() const;
std::string getDebugName() const;
void dump(std::string& result) const;
diff --git a/services/surfaceflinger/DisplayHardware/HWC2.cpp b/services/surfaceflinger/DisplayHardware/HWC2.cpp
index c52e96d..16d3984 100644
--- a/services/surfaceflinger/DisplayHardware/HWC2.cpp
+++ b/services/surfaceflinger/DisplayHardware/HWC2.cpp
@@ -369,7 +369,7 @@
for (uint32_t element = 0; element < numElements; ++element) {
auto layer = getLayerById(layerIds[element]);
if (layer) {
- sp<Fence> fence(new Fence(fenceFds[element]));
+ sp<Fence> fence(sp<Fence>::make(fenceFds[element]));
releaseFences.emplace(layer.get(), fence);
} else {
ALOGE("getReleaseFences: invalid layer %" PRIu64
@@ -394,7 +394,7 @@
return error;
}
- *outPresentFence = new Fence(presentFenceFd);
+ *outPresentFence = sp<Fence>::make(presentFenceFd);
return Error::NONE;
}
@@ -532,7 +532,7 @@
}
if (*state == 1) {
- *outPresentFence = new Fence(presentFenceFd);
+ *outPresentFence = sp<Fence>::make(presentFenceFd);
}
if (*state == 0) {
diff --git a/services/surfaceflinger/EffectLayer.cpp b/services/surfaceflinger/EffectLayer.cpp
index e8c590e..d8bbc30 100644
--- a/services/surfaceflinger/EffectLayer.cpp
+++ b/services/surfaceflinger/EffectLayer.cpp
@@ -74,7 +74,7 @@
}
bool EffectLayer::isVisible() const {
- return !isHiddenByPolicy() && (getAlpha() > 0.0_hf || hasBlur()) && hasSomethingToDraw();
+ return hasSomethingToDraw() && !isHiddenByPolicy() && (getAlpha() > 0.0_hf || hasBlur());
}
bool EffectLayer::setColor(const half3& color) {
@@ -144,7 +144,7 @@
sp<Layer> EffectLayer::createClone() {
sp<EffectLayer> layer = mFlinger->getFactory().createEffectLayer(
LayerCreationArgs(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata()));
- layer->setInitialValuesForClone(this);
+ layer->setInitialValuesForClone(sp<Layer>::fromExisting(this));
return layer;
}
diff --git a/services/surfaceflinger/FpsReporter.cpp b/services/surfaceflinger/FpsReporter.cpp
index c89c9ff..155cf4d 100644
--- a/services/surfaceflinger/FpsReporter.cpp
+++ b/services/surfaceflinger/FpsReporter.cpp
@@ -63,7 +63,8 @@
for (TrackedListener& listener : localListeners) {
if (listener.taskId == taskId) {
seenTasks.insert(taskId);
- listenersAndLayersToReport.push_back({listener, sp<Layer>(layer)});
+ listenersAndLayersToReport.push_back(
+ {listener, sp<Layer>::fromExisting(layer)});
break;
}
}
@@ -90,7 +91,7 @@
void FpsReporter::addListener(const sp<gui::IFpsListener>& listener, int32_t taskId) {
sp<IBinder> asBinder = IInterface::asBinder(listener);
- asBinder->linkToDeath(this);
+ asBinder->linkToDeath(sp<DeathRecipient>::fromExisting(this));
std::lock_guard lock(mMutex);
mListeners.emplace(wp<IBinder>(asBinder), TrackedListener{listener, taskId});
}
diff --git a/services/surfaceflinger/HdrLayerInfoReporter.cpp b/services/surfaceflinger/HdrLayerInfoReporter.cpp
index c06e300..c88554e 100644
--- a/services/surfaceflinger/HdrLayerInfoReporter.cpp
+++ b/services/surfaceflinger/HdrLayerInfoReporter.cpp
@@ -51,7 +51,7 @@
void HdrLayerInfoReporter::addListener(const sp<gui::IHdrLayerInfoListener>& listener) {
sp<IBinder> asBinder = IInterface::asBinder(listener);
- asBinder->linkToDeath(this);
+ asBinder->linkToDeath(sp<DeathRecipient>::fromExisting(this));
std::lock_guard lock(mMutex);
mListeners.emplace(wp<IBinder>(asBinder), TrackedListener{listener, HdrLayerInfo{}});
}
diff --git a/services/surfaceflinger/HwcSlotGenerator.cpp b/services/surfaceflinger/HwcSlotGenerator.cpp
index b7e9607..939c35b 100644
--- a/services/surfaceflinger/HwcSlotGenerator.cpp
+++ b/services/surfaceflinger/HwcSlotGenerator.cpp
@@ -56,7 +56,8 @@
return BufferQueue::INVALID_BUFFER_SLOT;
}
- ClientCache::getInstance().registerErasedRecipient(clientCacheId, wp<ErasedRecipient>(this));
+ ClientCache::getInstance().registerErasedRecipient(clientCacheId,
+ wp<ErasedRecipient>::fromExisting(this));
int hwcCacheSlot = getFreeHwcCacheSlot();
mCachedBuffers[clientCacheId] = {hwcCacheSlot, mCounter++};
@@ -85,7 +86,8 @@
}
eraseBufferLocked(minClientCacheId);
- ClientCache::getInstance().unregisterErasedRecipient(minClientCacheId, this);
+ ClientCache::getInstance().unregisterErasedRecipient(minClientCacheId,
+ wp<ErasedRecipient>::fromExisting(this));
}
void HwcSlotGenerator::eraseBufferLocked(const client_cache_t& clientCacheId) REQUIRES(mMutex) {
diff --git a/services/surfaceflinger/Layer.cpp b/services/surfaceflinger/Layer.cpp
index 0091f03..5e1a858 100644
--- a/services/surfaceflinger/Layer.cpp
+++ b/services/surfaceflinger/Layer.cpp
@@ -94,7 +94,7 @@
Layer::Layer(const LayerCreationArgs& args)
: sequence(args.sequence.value_or(sSequence++)),
- mFlinger(args.flinger),
+ mFlinger(sp<SurfaceFlinger>::fromExisting(args.flinger)),
mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)),
mClientRef(args.client),
mWindowType(static_cast<WindowInfo::Type>(
@@ -228,7 +228,7 @@
}
if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
- strongRelative->removeZOrderRelative(this);
+ strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
mFlinger->setTransactionFlags(eTraversalNeeded);
setZOrderRelativeOf(nullptr);
}
@@ -240,13 +240,13 @@
mFlinger->mScheduler->deregisterLayer(this);
}
- mFlinger->markLayerPendingRemovalLocked(this);
+ mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
}
sp<Layer> Layer::getRootLayer() {
sp<Layer> parent = getParent();
if (parent == nullptr) {
- return this;
+ return sp<Layer>::fromExisting(this);
}
return parent->getRootLayer();
}
@@ -289,7 +289,7 @@
return nullptr;
}
mGetHandleCalled = true;
- return new Handle(mFlinger, this);
+ return sp<Handle>::make(mFlinger, sp<Layer>::fromExisting(this));
}
// ---------------------------------------------------------------------------
@@ -521,8 +521,9 @@
}
sp<compositionengine::LayerFE> Layer::asLayerFE() const {
- return const_cast<compositionengine::LayerFE*>(
+ compositionengine::LayerFE* layerFE = const_cast<compositionengine::LayerFE*>(
static_cast<const compositionengine::LayerFE*>(this));
+ return sp<compositionengine::LayerFE>::fromExisting(layerFE);
}
sp<compositionengine::LayerFE> Layer::getCompositionEngineLayerFE() const {
@@ -813,7 +814,7 @@
if (mDrawingState.zOrderRelativeOf != nullptr) {
sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
if (strongRelative != nullptr) {
- strongRelative->removeZOrderRelative(this);
+ strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
}
setZOrderRelativeOf(nullptr);
}
@@ -871,10 +872,10 @@
auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
if (oldZOrderRelativeOf != nullptr) {
- oldZOrderRelativeOf->removeZOrderRelative(this);
+ oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
}
setZOrderRelativeOf(relative);
- relative->addZOrderRelative(this);
+ relative->addZOrderRelative(wp<Layer>::fromExisting(this));
setTransactionFlags(eTransactionNeeded);
@@ -1241,7 +1242,7 @@
void Layer::updateTreeHasFrameRateVote() {
const auto root = [&]() -> sp<Layer> {
- sp<Layer> layer = this;
+ sp<Layer> layer = sp<Layer>::fromExisting(this);
while (auto parent = layer->getParent()) {
layer = parent;
}
@@ -1614,7 +1615,7 @@
setTransactionFlags(eTransactionNeeded);
mCurrentChildren.add(layer);
- layer->setParent(this);
+ layer->setParent(sp<Layer>::fromExisting(this));
layer->setGameModeForTree(mGameMode);
updateTreeHasFrameRateVote();
}
@@ -1659,11 +1660,11 @@
sp<Layer> parent = getParent();
if (parent != nullptr) {
- parent->removeChild(this);
+ parent->removeChild(sp<Layer>::fromExisting(this));
}
if (newParentHandle != nullptr) {
- newParent->addChild(this);
+ newParent->addChild(sp<Layer>::fromExisting(this));
if (!newParent->isRemovedFromCurrentState()) {
addToCurrentState();
} else {
@@ -1945,8 +1946,11 @@
}
int32_t Layer::getBackgroundBlurRadius() const {
- const auto& p = mDrawingParent.promote();
+ if (getDrawingState().backgroundBlurRadius == 0) {
+ return 0;
+ }
+ const auto& p = mDrawingParent.promote();
half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
return parentAlpha * getDrawingState().backgroundBlurRadius;
}
@@ -2061,7 +2065,7 @@
zOrderRelativeOf->mName.c_str());
ALOGE("Severing rel Z loop, potentially dangerous");
mDrawingState.isRelativeOf = false;
- zOrderRelativeOf->removeZOrderRelative(this);
+ zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
}
}
}
@@ -2339,7 +2343,7 @@
}
void Layer::fillTouchOcclusionMode(WindowInfo& info) {
- sp<Layer> p = this;
+ sp<Layer> p = sp<Layer>::fromExisting(this);
while (p != nullptr && !p->hasInputInfo()) {
p = p->mDrawingParent.promote();
}
@@ -2491,7 +2495,7 @@
sp<Layer> Layer::getClonedRoot() {
if (mClonedChild != nullptr) {
- return this;
+ return sp<Layer>::fromExisting(this);
}
if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
return nullptr;
@@ -2545,7 +2549,7 @@
}
mClonedChild->updateClonedDrawingState(clonedLayersMap);
- mClonedChild->updateClonedChildren(this, clonedLayersMap);
+ mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
mClonedChild->updateClonedRelatives(clonedLayersMap);
}
@@ -2556,7 +2560,7 @@
if (isClonedFromAlive()) {
sp<Layer> clonedFrom = getClonedFrom();
cloneDrawingState(clonedFrom.get());
- clonedLayersMap.emplace(clonedFrom, this);
+ clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
}
// The clone layer may have children in drawingState since they may have been created and
@@ -2600,7 +2604,7 @@
if (clonedLayersMap.count(cropLayer) == 0) {
// Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
// self as crop layer to avoid going outside bounds.
- mDrawingState.touchableRegionCrop = this;
+ mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
} else {
const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
mDrawingState.touchableRegionCrop = clonedCropLayer;
@@ -2612,7 +2616,7 @@
}
void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
- mDrawingState.zOrderRelativeOf = nullptr;
+ mDrawingState.zOrderRelativeOf = wp<Layer>();
mDrawingState.zOrderRelatives.clear();
if (!isClonedFromAlive()) {
@@ -2648,7 +2652,7 @@
void Layer::addChildToDrawing(const sp<Layer>& layer) {
mDrawingChildren.add(layer);
- layer->mDrawingParent = this;
+ layer->mDrawingParent = sp<Layer>::fromExisting(this);
}
Layer::FrameRateCompatibility Layer::FrameRate::convertCompatibility(int8_t compatibility) {
@@ -2710,7 +2714,7 @@
}
// We can safely cast this binder since its local and we verified its interface descriptor.
- sp<Handle> handle = static_cast<Handle*>(handleBinder.get());
+ sp<Handle> handle = sp<Handle>::cast(handleBinder);
return handle->owner;
}
diff --git a/services/surfaceflinger/LayerRenderArea.cpp b/services/surfaceflinger/LayerRenderArea.cpp
index 896f254..e17b01f 100644
--- a/services/surfaceflinger/LayerRenderArea.cpp
+++ b/services/surfaceflinger/LayerRenderArea.cpp
@@ -17,8 +17,8 @@
#include <ui/GraphicTypes.h>
#include <ui/Transform.h>
-#include "ContainerLayer.h"
#include "DisplayDevice.h"
+#include "EffectLayer.h"
#include "Layer.h"
#include "LayerRenderArea.h"
#include "SurfaceFlinger.h"
@@ -110,8 +110,9 @@
// layer which has no properties set and which does not draw.
// We hold the statelock as the reparent-for-drawing operation modifies the
// hierarchy and there could be readers on Binder threads, like dump.
- sp<ContainerLayer> screenshotParentLayer = mFlinger.getFactory().createContainerLayer(
- {&mFlinger, nullptr, "Screenshot Parent"s, 0, LayerMetadata()});
+ sp<EffectLayer> screenshotParentLayer = mFlinger.getFactory().createEffectLayer(
+ {&mFlinger, nullptr, "Screenshot Parent"s, ISurfaceComposerClient::eNoColorFill,
+ LayerMetadata()});
{
Mutex::Autolock _l(mFlinger.mStateLock);
reparentForDrawing(mLayer, screenshotParentLayer, sourceCrop);
diff --git a/services/surfaceflinger/NativeWindowSurface.cpp b/services/surfaceflinger/NativeWindowSurface.cpp
index 3fff928..a6a3eec 100644
--- a/services/surfaceflinger/NativeWindowSurface.cpp
+++ b/services/surfaceflinger/NativeWindowSurface.cpp
@@ -30,7 +30,7 @@
class NativeWindowSurface final : public surfaceflinger::NativeWindowSurface {
public:
explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
- : mSurface(new Surface(producer, /* controlledByApp */ false)) {}
+ : mSurface(sp<Surface>::make(producer, /* controlledByApp */ false)) {}
~NativeWindowSurface() override = default;
diff --git a/services/surfaceflinger/RefreshRateOverlay.cpp b/services/surfaceflinger/RefreshRateOverlay.cpp
index a9180d4..9b19afb 100644
--- a/services/surfaceflinger/RefreshRateOverlay.cpp
+++ b/services/surfaceflinger/RefreshRateOverlay.cpp
@@ -152,13 +152,13 @@
}
}();
- sp<GraphicBuffer> buffer =
- new GraphicBuffer(static_cast<uint32_t>(bufferWidth),
- static_cast<uint32_t>(bufferHeight), HAL_PIXEL_FORMAT_RGBA_8888,
- 1,
- GRALLOC_USAGE_SW_WRITE_RARELY | GRALLOC_USAGE_HW_COMPOSER |
- GRALLOC_USAGE_HW_TEXTURE,
- "RefreshRateOverlayBuffer");
+ const auto kUsageFlags =
+ static_cast<uint64_t>(GRALLOC_USAGE_SW_WRITE_RARELY | GRALLOC_USAGE_HW_COMPOSER |
+ GRALLOC_USAGE_HW_TEXTURE);
+ sp<GraphicBuffer> buffer = sp<GraphicBuffer>::make(static_cast<uint32_t>(bufferWidth),
+ static_cast<uint32_t>(bufferHeight),
+ HAL_PIXEL_FORMAT_RGBA_8888, 1u,
+ kUsageFlags, "RefreshRateOverlayBuffer");
const status_t bufferStatus = buffer->initCheck();
LOG_ALWAYS_FATAL_IF(bufferStatus != OK, "RefreshRateOverlay: Buffer failed to allocate: %d",
diff --git a/services/surfaceflinger/RegionSamplingThread.cpp b/services/surfaceflinger/RegionSamplingThread.cpp
index 2487dbd..5705255 100644
--- a/services/surfaceflinger/RegionSamplingThread.cpp
+++ b/services/surfaceflinger/RegionSamplingThread.cpp
@@ -132,7 +132,7 @@
void RegionSamplingThread::addListener(const Rect& samplingArea, const wp<Layer>& stopLayer,
const sp<IRegionSamplingListener>& listener) {
sp<IBinder> asBinder = IInterface::asBinder(listener);
- asBinder->linkToDeath(this);
+ asBinder->linkToDeath(sp<DeathRecipient>::fromExisting(this));
std::lock_guard lock(mSamplingMutex);
mDescriptors.emplace(wp<IBinder>(asBinder), Descriptor{samplingArea, stopLayer, listener});
}
@@ -344,8 +344,8 @@
const uint32_t usage =
GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
sp<GraphicBuffer> graphicBuffer =
- new GraphicBuffer(sampledBounds.getWidth(), sampledBounds.getHeight(),
- PIXEL_FORMAT_RGBA_8888, 1, usage, "RegionSamplingThread");
+ sp<GraphicBuffer>::make(sampledBounds.getWidth(), sampledBounds.getHeight(),
+ PIXEL_FORMAT_RGBA_8888, 1, usage, "RegionSamplingThread");
const status_t bufferStatus = graphicBuffer->initCheck();
LOG_ALWAYS_FATAL_IF(bufferStatus != OK, "captureSample: Buffer failed to allocate: %d",
bufferStatus);
diff --git a/services/surfaceflinger/Scheduler/EventThread.cpp b/services/surfaceflinger/Scheduler/EventThread.cpp
index d152ab2..d3f53c1 100644
--- a/services/surfaceflinger/Scheduler/EventThread.cpp
+++ b/services/surfaceflinger/Scheduler/EventThread.cpp
@@ -173,7 +173,7 @@
void EventThreadConnection::onFirstRef() {
// NOTE: mEventThread doesn't hold a strong reference on us
- mEventThread->registerDisplayEventConnection(this);
+ mEventThread->registerDisplayEventConnection(sp<EventThreadConnection>::fromExisting(this));
}
binder::Status EventThreadConnection::stealReceiveChannel(gui::BitTube* outChannel) {
@@ -188,20 +188,22 @@
}
binder::Status EventThreadConnection::setVsyncRate(int rate) {
- mEventThread->setVsyncRate(static_cast<uint32_t>(rate), this);
+ mEventThread->setVsyncRate(static_cast<uint32_t>(rate),
+ sp<EventThreadConnection>::fromExisting(this));
return binder::Status::ok();
}
binder::Status EventThreadConnection::requestNextVsync() {
ATRACE_CALL();
- mEventThread->requestNextVsync(this);
+ mEventThread->requestNextVsync(sp<EventThreadConnection>::fromExisting(this));
return binder::Status::ok();
}
binder::Status EventThreadConnection::getLatestVsyncEventData(
ParcelableVsyncEventData* outVsyncEventData) {
ATRACE_CALL();
- outVsyncEventData->vsync = mEventThread->getLatestVsyncEventData(this);
+ outVsyncEventData->vsync =
+ mEventThread->getLatestVsyncEventData(sp<EventThreadConnection>::fromExisting(this));
return binder::Status::ok();
}
@@ -289,9 +291,9 @@
sp<EventThreadConnection> EventThread::createEventConnection(
ResyncCallback resyncCallback, EventRegistrationFlags eventRegistration) const {
- return new EventThreadConnection(const_cast<EventThread*>(this),
- IPCThreadState::self()->getCallingUid(),
- std::move(resyncCallback), eventRegistration);
+ return sp<EventThreadConnection>::make(const_cast<EventThread*>(this),
+ IPCThreadState::self()->getCallingUid(),
+ std::move(resyncCallback), eventRegistration);
}
status_t EventThread::registerDisplayEventConnection(const sp<EventThreadConnection>& connection) {
diff --git a/services/surfaceflinger/Scheduler/MessageQueue.cpp b/services/surfaceflinger/Scheduler/MessageQueue.cpp
index f2af85e..e90e387 100644
--- a/services/surfaceflinger/Scheduler/MessageQueue.cpp
+++ b/services/surfaceflinger/Scheduler/MessageQueue.cpp
@@ -34,7 +34,7 @@
if (!mFramePending.exchange(true)) {
mVsyncId = vsyncId;
mExpectedVsyncTime = expectedVsyncTime;
- mQueue.mLooper->sendMessage(this, Message());
+ mQueue.mLooper->sendMessage(sp<MessageHandler>::fromExisting(this), Message());
}
}
diff --git a/services/surfaceflinger/Scheduler/MessageQueue.h b/services/surfaceflinger/Scheduler/MessageQueue.h
index 4082e26..9dde82b 100644
--- a/services/surfaceflinger/Scheduler/MessageQueue.h
+++ b/services/surfaceflinger/Scheduler/MessageQueue.h
@@ -25,6 +25,7 @@
#include <android/gui/IDisplayEventConnection.h>
#include <private/gui/BitTube.h>
#include <utils/Looper.h>
+#include <utils/StrongPointer.h>
#include <utils/Timers.h>
#include "EventThread.h"
@@ -47,6 +48,9 @@
template <typename G>
friend auto makeTask(G&&);
+ template <typename... Args>
+ friend sp<Task<F>> sp<Task<F>>::make(Args&&... args);
+
explicit Task(F&& f) : mTask(std::move(f)) {}
void handleMessage(const Message&) override { mTask(); }
@@ -57,7 +61,7 @@
template <typename F>
inline auto makeTask(F&& f) {
- sp<Task<F>> task = new Task<F>(std::move(f));
+ sp<Task<F>> task = sp<Task<F>>::make(std::forward<F>(f));
return std::make_pair(task, task->mTask.get_future());
}
diff --git a/services/surfaceflinger/Scheduler/VsyncModulator.cpp b/services/surfaceflinger/Scheduler/VsyncModulator.cpp
index be57b2a..138d8d6 100644
--- a/services/surfaceflinger/Scheduler/VsyncModulator.cpp
+++ b/services/surfaceflinger/Scheduler/VsyncModulator.cpp
@@ -53,14 +53,14 @@
case Schedule::EarlyStart:
if (token) {
mEarlyWakeupRequests.emplace(token);
- token->linkToDeath(this);
+ token->linkToDeath(sp<DeathRecipient>::fromExisting(this));
} else {
ALOGW("%s: EarlyStart requested without a valid token", __func__);
}
break;
case Schedule::EarlyEnd: {
if (token && mEarlyWakeupRequests.erase(token) > 0) {
- token->unlinkToDeath(this);
+ token->unlinkToDeath(sp<DeathRecipient>::fromExisting(this));
} else {
ALOGW("%s: Unexpected EarlyEnd", __func__);
}
diff --git a/services/surfaceflinger/Scheduler/include/scheduler/Time.h b/services/surfaceflinger/Scheduler/include/scheduler/Time.h
index 2b3ad2d..487709b 100644
--- a/services/surfaceflinger/Scheduler/include/scheduler/Time.h
+++ b/services/surfaceflinger/Scheduler/include/scheduler/Time.h
@@ -32,6 +32,7 @@
struct Duration;
struct TimePoint : scheduler::SchedulerClock::time_point {
+ constexpr TimePoint() = default;
explicit constexpr TimePoint(const Duration&);
// Implicit conversion from std::chrono counterpart.
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index 24aed17..de12d62 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -108,7 +108,6 @@
#include "BufferStateLayer.h"
#include "Client.h"
#include "Colorizer.h"
-#include "ContainerLayer.h"
#include "DisplayDevice.h"
#include "DisplayHardware/ComposerHal.h"
#include "DisplayHardware/FramebufferSurface.h"
@@ -335,7 +334,7 @@
mFrameTimeline(mFactory.createFrameTimeline(mTimeStats, mPid)),
mCompositionEngine(mFactory.createCompositionEngine()),
mHwcServiceName(base::GetProperty("debug.sf.hwc_service_name"s, "default"s)),
- mTunnelModeEnabledReporter(new TunnelModeEnabledReporter()),
+ mTunnelModeEnabledReporter(sp<TunnelModeEnabledReporter>::make()),
mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)),
mPowerAdvisor(std::make_unique<Hwc2::impl::PowerAdvisor>(*this)),
@@ -478,7 +477,8 @@
mBootFinished = false;
// Sever the link to inputflinger since it's gone as well.
- static_cast<void>(mScheduler->schedule([=] { mInputFlinger = nullptr; }));
+ static_cast<void>(mScheduler->schedule(
+ [this] { mInputFlinger.clear(); }));
// restore initial conditions (default device unblank, etc)
initializeDisplays();
@@ -506,7 +506,7 @@
virtual ~DisplayToken() {
// no more references, this display must be terminated
Mutex::Autolock _l(flinger->mStateLock);
- flinger->mCurrentState.displays.removeItem(this);
+ flinger->mCurrentState.displays.removeItem(wp<IBinder>::fromExisting(this));
flinger->setTransactionFlags(eDisplayTransactionNeeded);
}
public:
@@ -515,7 +515,7 @@
}
};
- sp<BBinder> token = new DisplayToken(this);
+ sp<BBinder> token = sp<DisplayToken>::make(sp<SurfaceFlinger>::fromExisting(this));
Mutex::Autolock _l(mStateLock);
// Display ID is assigned when virtual display is allocated by HWC.
@@ -657,7 +657,7 @@
const String16 name("window");
mWindowManager = defaultServiceManager()->getService(name);
if (mWindowManager != 0) {
- mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
+ mWindowManager->linkToDeath(sp<IBinder::DeathRecipient>::fromExisting(this));
}
// stop boot animation
@@ -2059,13 +2059,15 @@
}
// Save this once per commit + composite to ensure consistency
- mPowerHintSessionEnabled = mPowerAdvisor->usePowerHintSession();
+ // TODO (b/240619471): consider removing active display check once AOD is fixed
+ const auto activeDisplay =
+ FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(mActiveDisplayToken));
+ mPowerHintSessionEnabled = mPowerAdvisor->usePowerHintSession() && activeDisplay &&
+ activeDisplay->getPowerMode() == hal::PowerMode::ON;
if (mPowerHintSessionEnabled) {
- nsecs_t vsyncPeriod;
- {
- Mutex::Autolock lock(mStateLock);
- vsyncPeriod = getVsyncPeriodFromHWC();
- }
+ const auto& display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked()).get();
+ // get stable vsync period from display mode
+ const nsecs_t vsyncPeriod = display->getActiveMode()->getVsyncPeriod();
mPowerAdvisor->setCommitStart(frameTime);
mPowerAdvisor->setExpectedPresentTime(mExpectedPresentTime);
const nsecs_t idealSfWorkDuration =
@@ -2096,6 +2098,7 @@
bool needsTraversal = false;
if (clearTransactionFlags(eTransactionFlushNeeded)) {
+ needsTraversal |= commitMirrorDisplays(vsyncId);
needsTraversal |= commitCreatedLayers(vsyncId);
needsTraversal |= flushTransactionQueues(vsyncId);
}
@@ -2242,7 +2245,6 @@
scheduleComposite(FrameHint::kNone);
}
- postFrame();
postComposition();
const bool prevFrameHadClientComposition = mHadClientComposition;
@@ -2358,7 +2360,7 @@
void SurfaceFlinger::postComposition() {
ATRACE_CALL();
- ALOGV("postComposition");
+ ALOGV(__func__);
const auto* display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked()).get();
@@ -2373,18 +2375,19 @@
}
mPreviousPresentFences[1] = mPreviousPresentFences[0];
- mPreviousPresentFences[0].fence =
- display ? getHwComposer().getPresentFence(display->getPhysicalId()) : Fence::NO_FENCE;
- mPreviousPresentFences[0].fenceTime =
- std::make_shared<FenceTime>(mPreviousPresentFences[0].fence);
- nsecs_t now = systemTime();
+ auto presentFence =
+ display ? getHwComposer().getPresentFence(display->getPhysicalId()) : Fence::NO_FENCE;
+
+ auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
+ mPreviousPresentFences[0] = {presentFence, presentFenceTime};
+
+ const TimePoint presentTime = scheduler::SchedulerClock::now();
// Set presentation information before calling Layer::releasePendingBuffer, such that jank
// information from previous' frame classification is already available when sending jank info
// to clients, so they get jank classification as early as possible.
- mFrameTimeline->setSfPresent(/* sfPresentTime */ now, mPreviousPresentFences[0].fenceTime,
- glCompositionDoneFenceTime);
+ mFrameTimeline->setSfPresent(presentTime.ns(), presentFenceTime, glCompositionDoneFenceTime);
// We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
// be sampled a little later than when we started doing work for this frame,
@@ -2392,11 +2395,10 @@
const TimePoint compositeTime =
TimePoint::fromNs(mCompositionEngine->getLastFrameRefreshTimestamp());
const Duration presentLatency =
- mPresentLatencyTracker.trackPendingFrame(compositeTime,
- mPreviousPresentFences[0].fenceTime);
+ mPresentLatencyTracker.trackPendingFrame(compositeTime, presentFenceTime);
const auto& schedule = mScheduler->getVsyncSchedule();
- const TimePoint vsyncDeadline = schedule.vsyncDeadlineAfter(TimePoint::fromNs(now));
+ const TimePoint vsyncDeadline = schedule.vsyncDeadlineAfter(presentTime);
const Period vsyncPeriod = schedule.period();
const nsecs_t vsyncPhase = mVsyncConfiguration->getCurrentConfigs().late.sfOffset;
@@ -2404,9 +2406,9 @@
presentLatency.ns());
for (const auto& layer: mLayersWithQueuedFrames) {
- layer->onPostComposition(display, glCompositionDoneFenceTime,
- mPreviousPresentFences[0].fenceTime, compositorTiming);
- layer->releasePendingBuffer(/*dequeueReadyTime*/ now);
+ layer->onPostComposition(display, glCompositionDoneFenceTime, presentFenceTime,
+ compositorTiming);
+ layer->releasePendingBuffer(presentTime.ns());
}
std::vector<std::pair<std::shared_ptr<compositionengine::Display>, sp<HdrLayerInfoReporter>>>
@@ -2463,13 +2465,16 @@
mSomeDataspaceChanged = false;
mVisibleRegionsWereDirtyThisFrame = false;
- mTransactionCallbackInvoker.addPresentFence(mPreviousPresentFences[0].fence);
+ mTransactionCallbackInvoker.addPresentFence(std::move(presentFence));
mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
mTransactionCallbackInvoker.clearCompletedTransactions();
+ mTimeStats->incrementTotalFrames();
+ mTimeStats->setPresentFenceGlobal(presentFenceTime);
+
if (display && display->isInternal() && display->getPowerMode() == hal::PowerMode::ON &&
- mPreviousPresentFences[0].fenceTime->isValid()) {
- mScheduler->addPresentFence(mPreviousPresentFences[0].fenceTime);
+ presentFenceTime->isValid()) {
+ mScheduler->addPresentFence(std::move(presentFenceTime));
}
const bool isDisplayConnected =
@@ -2481,9 +2486,6 @@
}
}
- mTimeStats->incrementTotalFrames();
- mTimeStats->setPresentFenceGlobal(mPreviousPresentFences[0].fenceTime);
-
const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
@@ -2493,20 +2495,19 @@
return;
}
- nsecs_t currentTime = systemTime();
if (mHasPoweredOff) {
mHasPoweredOff = false;
} else {
- nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
- const size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncPeriod.ns());
+ const Duration elapsedTime = presentTime - getBE().mLastPresentTime;
+ const size_t numPeriods = static_cast<size_t>(elapsedTime.ns() / vsyncPeriod.ns());
if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
- getBE().mFrameBuckets[numPeriods] += elapsedTime;
+ getBE().mFrameBuckets[numPeriods] += elapsedTime.ns();
} else {
- getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
+ getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime.ns();
}
- getBE().mTotalTime += elapsedTime;
+ getBE().mTotalTime += elapsedTime.ns();
}
- getBE().mLastSwapTime = currentTime;
+ getBE().mLastPresentTime = presentTime;
// Cleanup any outstanding resources due to rendering a prior frame.
getRenderEngine().cleanupPostRender();
@@ -2534,6 +2535,8 @@
// getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
}
+
+ logFrameStats(presentTime);
}
FloatRect SurfaceFlinger::getMaxDisplayBounds() {
@@ -2566,16 +2569,6 @@
}
}
-void SurfaceFlinger::postFrame() {
- const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
- if (display && getHwComposer().isConnected(display->getPhysicalId())) {
- uint32_t flipCount = display->getPageFlipCount();
- if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
- logFrameStats();
- }
- }
-}
-
void SurfaceFlinger::commitTransactions() {
ATRACE_CALL();
@@ -2694,7 +2687,7 @@
state.isSecure = true; // All physical displays are currently considered secure.
state.displayName = std::move(info->name);
- sp<IBinder> token = new BBinder();
+ sp<IBinder> token = sp<BBinder>::make();
mCurrentState.displays.add(token, state);
mPhysicalDisplayTokens.try_emplace(displayId, std::move(token));
mInterceptor->saveDisplayCreation(state);
@@ -2740,7 +2733,8 @@
const DisplayDeviceState& state,
const sp<compositionengine::DisplaySurface>& displaySurface,
const sp<IGraphicBufferProducer>& producer) {
- DisplayDeviceCreationArgs creationArgs(this, getHwComposer(), displayToken, compositionDisplay);
+ DisplayDeviceCreationArgs creationArgs(sp<SurfaceFlinger>::fromExisting(this), getHwComposer(),
+ displayToken, compositionDisplay);
creationArgs.sequenceId = state.sequenceId;
creationArgs.isSecure = state.isSecure;
creationArgs.displaySurface = displaySurface;
@@ -3139,11 +3133,11 @@
mVisibleRegionsDirty = true;
mUpdateInputInfo = true;
mDrawingState.traverseInZOrder([&](Layer* layer) {
- if (mLayersPendingRemoval.indexOf(layer) >= 0) {
+ if (mLayersPendingRemoval.indexOf(sp<Layer>::fromExisting(layer)) >= 0) {
// this layer is not visible anymore
Region visibleReg;
visibleReg.set(layer->getScreenBounds());
- invalidateLayerStack(layer, visibleReg);
+ invalidateLayerStack(sp<Layer>::fromExisting(layer), visibleReg);
}
});
}
@@ -3378,8 +3372,9 @@
*mFrameTimeline->getTokenManager(), configs.late.sfWorkDuration);
mRegionSamplingThread =
- new RegionSamplingThread(*this, RegionSamplingThread::EnvironmentTimingTunables());
- mFpsReporter = new FpsReporter(*mFrameTimeline, *this);
+ sp<RegionSamplingThread>::make(*this,
+ RegionSamplingThread::EnvironmentTimingTunables());
+ mFpsReporter = sp<FpsReporter>::make(*mFrameTimeline, *this);
// Dispatch a mode change request for the primary display on scheduler
// initialization, so that the EventThreads always contain a reference to a
// prior configuration.
@@ -3501,7 +3496,7 @@
if (layer->hasReadyFrame()) {
frameQueued = true;
- mLayersWithQueuedFrames.emplace(layer);
+ mLayersWithQueuedFrames.emplace(sp<Layer>::fromExisting(layer));
} else {
layer->useEmptyDamage();
}
@@ -3614,39 +3609,21 @@
}
}
-bool SurfaceFlinger::stopTransactionProcessing(
- const std::unordered_set<sp<IBinder>, SpHash<IBinder>>&
- applyTokensWithUnsignaledTransactions) const {
- if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
- // if we are in LatchUnsignaledConfig::AutoSingleLayer
- // then we should have only one applyToken for processing.
- // so we can stop further transactions on this applyToken.
- return !applyTokensWithUnsignaledTransactions.empty();
- }
-
- return false;
-}
-
-int SurfaceFlinger::flushUnsignaledPendingTransactionQueues(
- std::vector<TransactionState>& transactions,
- std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
- std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions) {
- return flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
- applyTokensWithUnsignaledTransactions,
- /*tryApplyUnsignaled*/ true);
-}
-
int SurfaceFlinger::flushPendingTransactionQueues(
std::vector<TransactionState>& transactions,
std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
- std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions,
bool tryApplyUnsignaled) {
+ std::unordered_set<sp<IBinder>, SpHash<IBinder>> applyTokensWithUnsignaledTransactions;
int transactionsPendingBarrier = 0;
auto it = mPendingTransactionQueues.begin();
while (it != mPendingTransactionQueues.end()) {
auto& [applyToken, transactionQueue] = *it;
while (!transactionQueue.empty()) {
- if (stopTransactionProcessing(applyTokensWithUnsignaledTransactions)) {
+ // if we are in LatchUnsignaledConfig::AutoSingleLayer
+ // then we should have only one applyToken for processing.
+ // so we can stop further transactions on this applyToken.
+ if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer &&
+ !applyTokensWithUnsignaledTransactions.empty()) {
ATRACE_NAME("stopTransactionProcessing");
break;
}
@@ -3694,7 +3671,6 @@
if (transactionQueue.empty()) {
it = mPendingTransactionQueues.erase(it);
- mTransactionQueueCV.broadcast();
} else {
it = std::next(it, 1);
}
@@ -3709,68 +3685,16 @@
std::vector<TransactionState> transactions;
// Layer handles that have transactions with buffers that are ready to be applied.
std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>> bufferLayersReadyToPresent;
- std::unordered_set<sp<IBinder>, SpHash<IBinder>> applyTokensWithUnsignaledTransactions;
{
Mutex::Autolock _l(mStateLock);
{
- int lastTransactionsPendingBarrier = 0;
- int transactionsPendingBarrier = 0;
- // First collect transactions from the pending transaction queues.
- // We are not allowing unsignaled buffers here as we want to
- // collect all the transactions from applyTokens that are ready first.
- transactionsPendingBarrier =
- flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
- applyTokensWithUnsignaledTransactions, /*tryApplyUnsignaled*/ false);
-
- // Second, collect transactions from the transaction queue.
- // Here as well we are not allowing unsignaled buffers for the same
- // reason as above.
while (!mLocklessTransactionQueue.isEmpty()) {
auto maybeTransaction = mLocklessTransactionQueue.pop();
if (!maybeTransaction.has_value()) {
break;
}
auto transaction = maybeTransaction.value();
- const bool pendingTransactions =
- mPendingTransactionQueues.find(transaction.applyToken) !=
- mPendingTransactionQueues.end();
- const auto ready = [&]() REQUIRES(mStateLock) {
- if (pendingTransactions) {
- ATRACE_NAME("pendingTransactions");
- return TransactionReadiness::NotReady;
- }
-
- return transactionIsReadyToBeApplied(transaction, transaction.frameTimelineInfo,
- transaction.isAutoTimestamp,
- transaction.desiredPresentTime,
- transaction.originUid, transaction.states,
- bufferLayersReadyToPresent,
- transactions.size(),
- /*tryApplyUnsignaled*/ false);
- }();
- ATRACE_INT("TransactionReadiness", static_cast<int>(ready));
- if (ready != TransactionReadiness::Ready) {
- if (ready == TransactionReadiness::NotReadyBarrier) {
- transactionsPendingBarrier++;
- }
- mPendingTransactionQueues[transaction.applyToken].push(std::move(transaction));
- } else {
- transaction.traverseStatesWithBuffers([&](const layer_state_t& state) {
- const bool frameNumberChanged = state.bufferData->flags.test(
- BufferData::BufferDataChange::frameNumberChanged);
- if (frameNumberChanged) {
- bufferLayersReadyToPresent[state.surface] = state.bufferData->frameNumber;
- } else {
- // Barrier function only used for BBQ which always includes a frame number.
- // This value only used for barrier logic.
- bufferLayersReadyToPresent[state.surface] =
- std::numeric_limits<uint64_t>::max();
- }
- });
- transactions.emplace_back(std::move(transaction));
- mPendingTransactionCount--;
- ATRACE_INT("TransactionQueue", mPendingTransactionCount.load());
- }
+ mPendingTransactionQueues[transaction.applyToken].push(std::move(transaction));
}
// Transactions with a buffer pending on a barrier may be on a different applyToken
@@ -3783,20 +3707,21 @@
// loop through flushPendingTransactionQueues until we perform an iteration
// where the number of transactionsPendingBarrier doesn't change. This way
// we can continue to resolve dependency chains of barriers as far as possible.
- while (lastTransactionsPendingBarrier != transactionsPendingBarrier) {
+ int lastTransactionsPendingBarrier = 0;
+ int transactionsPendingBarrier = 0;
+ do {
lastTransactionsPendingBarrier = transactionsPendingBarrier;
transactionsPendingBarrier =
- flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
- applyTokensWithUnsignaledTransactions,
- /*tryApplyUnsignaled*/ false);
- }
+ flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
+ /*tryApplyUnsignaled*/ false);
+ } while (lastTransactionsPendingBarrier != transactionsPendingBarrier);
// We collected all transactions that could apply without latching unsignaled buffers.
// If we are allowing latch unsignaled of some form, now it's the time to go over the
// transactions that were not applied and try to apply them unsignaled.
if (enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
- flushUnsignaledPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
- applyTokensWithUnsignaledTransactions);
+ flushPendingTransactionQueues(transactions, bufferLayersReadyToPresent,
+ /*tryApplyUnsignaled*/ true);
}
return applyTransactions(transactions, vsyncId);
@@ -3970,7 +3895,7 @@
if (fenceUnsignaled && !allowLatchUnsignaled) {
if (!transaction.sentFenceTimeoutWarning &&
- queueProcessTime - transaction.queueTime > std::chrono::nanoseconds(4s).count()) {
+ queueProcessTime - transaction.postTime > std::chrono::nanoseconds(4s).count()) {
transaction.sentFenceTimeoutWarning = true;
auto listener = s.bufferData->releaseBufferListener;
if (listener) {
@@ -3997,7 +3922,6 @@
}
void SurfaceFlinger::queueTransaction(TransactionState& state) {
- state.queueTime = systemTime();
// Generate a CountDownLatch pending state if this is a synchronous transaction.
if (state.flags & eSynchronous) {
state.transactionCommittedSignal =
@@ -4283,7 +4207,7 @@
if (layer == nullptr) {
for (auto& [listener, callbackIds] : s.listeners) {
mTransactionCallbackInvoker.registerUnpresentedCallbackHandle(
- new CallbackHandle(listener, callbackIds, s.surface));
+ sp<CallbackHandle>::make(listener, callbackIds, s.surface));
}
return 0;
}
@@ -4537,7 +4461,8 @@
std::vector<sp<CallbackHandle>> callbackHandles;
if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!filteredListeners.empty())) {
for (auto& [listener, callbackIds] : filteredListeners) {
- callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
+ callbackHandles.emplace_back(
+ sp<CallbackHandle>::make(listener, callbackIds, s.surface));
}
}
@@ -4578,7 +4503,9 @@
if (!mirrorFrom) {
return NAME_NOT_FOUND;
}
- status_t result = createContainerLayer(args, outHandle, &mirrorLayer);
+ LayerCreationArgs mirrorArgs = args;
+ mirrorArgs.flags |= ISurfaceComposerClient::eNoColorFill;
+ status_t result = createEffectLayer(mirrorArgs, outHandle, &mirrorLayer);
if (result != NO_ERROR) {
return result;
}
@@ -4595,6 +4522,55 @@
false /* addToRoot */, nullptr /* outTransformHint */);
}
+status_t SurfaceFlinger::mirrorDisplay(DisplayId displayId, const LayerCreationArgs& args,
+ sp<IBinder>* outHandle, int32_t* outLayerId) {
+ IPCThreadState* ipc = IPCThreadState::self();
+ const int uid = ipc->getCallingUid();
+ if (uid != AID_ROOT && uid != AID_GRAPHICS && uid != AID_SYSTEM && uid != AID_SHELL) {
+ ALOGE("Permission denied when trying to mirror display");
+ return PERMISSION_DENIED;
+ }
+
+ ui::LayerStack layerStack;
+ sp<Layer> rootMirrorLayer;
+ status_t result = 0;
+
+ {
+ Mutex::Autolock lock(mStateLock);
+
+ const auto display = getDisplayDeviceLocked(displayId);
+ if (!display) {
+ return NAME_NOT_FOUND;
+ }
+
+ layerStack = display->getLayerStack();
+ LayerCreationArgs mirrorArgs = args;
+ mirrorArgs.flags |= ISurfaceComposerClient::eNoColorFill;
+ result = createEffectLayer(mirrorArgs, outHandle, &rootMirrorLayer);
+ *outLayerId = rootMirrorLayer->sequence;
+ result |= addClientLayer(args.client, *outHandle, rootMirrorLayer /* layer */,
+ nullptr /* parent */, true /* addToRoot */,
+ nullptr /* outTransformHint */);
+ }
+
+ if (result != NO_ERROR) {
+ return result;
+ }
+
+ if (mTransactionTracing) {
+ mTransactionTracing->onLayerAdded((*outHandle)->localBinder(), *outLayerId, args.name,
+ args.flags, -1 /* parentId */);
+ }
+
+ {
+ std::scoped_lock<std::mutex> lock(mMirrorDisplayLock);
+ mMirrorDisplays.emplace_back(layerStack, *outHandle, args.client);
+ }
+
+ setTransactionFlags(eTransactionFlushNeeded);
+ return NO_ERROR;
+}
+
status_t SurfaceFlinger::createLayer(LayerCreationArgs& args, sp<IBinder>* outHandle,
const sp<IBinder>& parentHandle, int32_t* outLayerId,
const sp<Layer>& parentLayer, uint32_t* outTransformHint) {
@@ -4617,12 +4593,12 @@
pendingBufferCounter);
}
} break;
+ case ISurfaceComposerClient::eFXSurfaceContainer:
+ args.flags |= ISurfaceComposerClient::eNoColorFill;
+ FMT_FALLTHROUGH;
case ISurfaceComposerClient::eFXSurfaceEffect:
result = createEffectLayer(args, outHandle, &layer);
break;
- case ISurfaceComposerClient::eFXSurfaceContainer:
- result = createContainerLayer(args, outHandle, &layer);
- break;
default:
result = BAD_VALUE;
break;
@@ -4678,13 +4654,6 @@
return NO_ERROR;
}
-status_t SurfaceFlinger::createContainerLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
- sp<Layer>* outLayer) {
- *outLayer = getFactory().createContainerLayer(args);
- *handle = (*outLayer)->getHandle();
- return NO_ERROR;
-}
-
void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
mLayersPendingRemoval.add(layer);
mLayersRemoved = true;
@@ -4975,7 +4944,14 @@
mFrameTimeline->parseArgs(args, result);
}
-void SurfaceFlinger::logFrameStats() {
+void SurfaceFlinger::logFrameStats(TimePoint now) {
+ using namespace std::chrono_literals;
+
+ static TimePoint sTimestamp = now;
+ if (now - sTimestamp < 30min) return;
+ sTimestamp = now;
+
+ ATRACE_CALL();
mDrawingState.traverse([&](Layer* layer) { layer->logFrameStats(); });
}
@@ -5579,15 +5555,8 @@
reply->writeInt32(0);
reply->writeInt32(mDebugDisableHWC);
return NO_ERROR;
- case 1013: {
- const auto display = getDefaultDisplayDevice();
- if (!display) {
- return NAME_NOT_FOUND;
- }
-
- reply->writeInt32(display->getPageFlipCount());
- return NO_ERROR;
- }
+ case 1013: // Unused.
+ return NAME_NOT_FOUND;
case 1014: {
Mutex::Autolock _l(mStateLock);
// daltonize
@@ -6406,7 +6375,7 @@
return;
}
- sp<Layer> p = layer;
+ auto p = sp<Layer>::fromExisting(layer);
while (p != nullptr) {
if (excludeLayers.count(p) != 0) {
return;
@@ -7125,6 +7094,45 @@
return buffer;
}
+bool SurfaceFlinger::commitMirrorDisplays(int64_t vsyncId) {
+ std::vector<MirrorDisplayState> mirrorDisplays;
+ {
+ std::scoped_lock<std::mutex> lock(mMirrorDisplayLock);
+ mirrorDisplays = std::move(mMirrorDisplays);
+ mMirrorDisplays.clear();
+ if (mirrorDisplays.size() == 0) {
+ return false;
+ }
+ }
+
+ sp<IBinder> unused;
+ for (const auto& mirrorDisplay : mirrorDisplays) {
+ // Set mirror layer's default layer stack to -1 so it doesn't end up rendered on a display
+ // accidentally.
+ sp<Layer> rootMirrorLayer = Layer::fromHandle(mirrorDisplay.rootHandle).promote();
+ rootMirrorLayer->setLayerStack(ui::LayerStack::fromValue(-1));
+ for (const auto& layer : mDrawingState.layersSortedByZ) {
+ if (layer->getLayerStack() != mirrorDisplay.layerStack ||
+ layer->isInternalDisplayOverlay()) {
+ continue;
+ }
+
+ LayerCreationArgs mirrorArgs(this, mirrorDisplay.client, "MirrorLayerParent",
+ ISurfaceComposerClient::eNoColorFill,
+ gui::LayerMetadata());
+ sp<Layer> childMirror;
+ createEffectLayer(mirrorArgs, &unused, &childMirror);
+ childMirror->setClonedChild(layer->createClone());
+ if (mTransactionTracing) {
+ mTransactionTracing->onLayerAddedToDrawingState(childMirror->getSequence(),
+ vsyncId);
+ }
+ childMirror->reparent(mirrorDisplay.rootHandle);
+ }
+ }
+ return true;
+}
+
bool SurfaceFlinger::commitCreatedLayers(int64_t vsyncId) {
std::vector<LayerCreatedState> createdLayers;
{
@@ -7183,7 +7191,7 @@
}
binder::Status SurfaceComposerAIDL::createConnection(sp<gui::ISurfaceComposerClient>* outClient) {
- const sp<Client> client = new Client(mFlinger);
+ const sp<Client> client = sp<Client>::make(mFlinger);
if (client->initCheck() == NO_ERROR) {
*outClient = client;
return binder::Status::ok();
diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h
index 39277aa..361fa2e 100644
--- a/services/surfaceflinger/SurfaceFlinger.h
+++ b/services/surfaceflinger/SurfaceFlinger.h
@@ -56,6 +56,7 @@
#include <compositionengine/OutputColorSetting.h>
#include <scheduler/Fps.h>
#include <scheduler/PresentLatencyTracker.h>
+#include <scheduler/Time.h>
#include "ClientCache.h"
#include "DisplayDevice.h"
@@ -96,12 +97,12 @@
#include <utility>
#include <aidl/android/hardware/graphics/common/DisplayDecorationSupport.h>
+#include "Client.h"
using namespace android::surfaceflinger;
namespace android {
-class Client;
class EventThread;
class FlagManager;
class FpsReporter;
@@ -174,7 +175,7 @@
static const size_t NUM_BUCKETS = 8; // < 1-7, 7+
nsecs_t mFrameBuckets[NUM_BUCKETS] = {};
nsecs_t mTotalTime = 0;
- std::atomic<nsecs_t> mLastSwapTime = 0;
+ TimePoint mLastPresentTime;
};
class SurfaceFlinger : public BnSurfaceComposer,
@@ -197,29 +198,6 @@
static char const* getServiceName() ANDROID_API { return "SurfaceFlinger"; }
- // This is the phase offset in nanoseconds of the software vsync event
- // relative to the vsync event reported by HWComposer. The software vsync
- // event is when SurfaceFlinger and Choreographer-based applications run each
- // frame.
- //
- // This phase offset allows adjustment of the minimum latency from application
- // wake-up time (by Choreographer) to the time at which the resulting window
- // image is displayed. This value may be either positive (after the HW vsync)
- // or negative (before the HW vsync). Setting it to 0 will result in a lower
- // latency bound of two vsync periods because the app and SurfaceFlinger
- // will run just after the HW vsync. Setting it to a positive number will
- // result in the minimum latency being:
- //
- // (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
- //
- // Note that reducing this latency makes it more likely for the applications
- // to not have their window content image ready in time. When this happens
- // the latency will end up being an additional vsync period, and animations
- // will hiccup. Therefore, this latency should be tuned somewhat
- // conservatively (or at least with awareness of the trade-off being made).
- static int64_t vsyncPhaseOffsetNs;
- static int64_t sfVsyncPhaseOffsetNs;
-
// If fences from sync Framework are supported.
static bool hasSyncFramework;
@@ -386,10 +364,6 @@
using DumpArgs = Vector<String16>;
using Dumper = std::function<void(const DumpArgs&, bool asProto, std::string&)>;
- // This value is specified in number of frames. Log frame stats at most
- // every half hour.
- enum { LOG_FRAME_STATS_PERIOD = 30*60*60 };
-
class State {
public:
explicit State(LayerVector::StateSet set) : stateSet(set), layersSortedByZ(set) {}
@@ -753,15 +727,8 @@
int flushPendingTransactionQueues(
std::vector<TransactionState>& transactions,
std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
- std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions,
bool tryApplyUnsignaled) REQUIRES(mStateLock);
- int flushUnsignaledPendingTransactionQueues(
- std::vector<TransactionState>& transactions,
- std::unordered_map<sp<IBinder>, uint64_t, SpHash<IBinder>>& bufferLayersReadyToPresent,
- std::unordered_set<sp<IBinder>, SpHash<IBinder>>& applyTokensWithUnsignaledTransactions)
- REQUIRES(mStateLock);
-
uint32_t setClientStateLocked(const FrameTimelineInfo&, ComposerState&,
int64_t desiredPresentTime, bool isAutoTimestamp,
int64_t postTime, uint32_t permissions) REQUIRES(mStateLock);
@@ -793,8 +760,6 @@
static LatchUnsignaledConfig getLatchUnsignaledConfig();
bool shouldLatchUnsignaled(const sp<Layer>& layer, const layer_state_t&, size_t numStates,
size_t totalTXapplied) const;
- bool stopTransactionProcessing(const std::unordered_set<sp<IBinder>, SpHash<IBinder>>&
- applyTokensWithUnsignaledTransactions) const;
bool applyTransactions(std::vector<TransactionState>& transactions, int64_t vsyncId)
REQUIRES(mStateLock);
uint32_t setDisplayStateLocked(const DisplayState& s) REQUIRES(mStateLock);
@@ -815,12 +780,12 @@
status_t createEffectLayer(const LayerCreationArgs& args, sp<IBinder>* outHandle,
sp<Layer>* outLayer);
- status_t createContainerLayer(const LayerCreationArgs& args, sp<IBinder>* outHandle,
- sp<Layer>* outLayer);
-
status_t mirrorLayer(const LayerCreationArgs& args, const sp<IBinder>& mirrorFromHandle,
sp<IBinder>* outHandle, int32_t* outLayerId);
+ status_t mirrorDisplay(DisplayId displayId, const LayerCreationArgs& args,
+ sp<IBinder>* outHandle, int32_t* outLayerId);
+
// called when all clients have released all their references to
// this layer meaning it is entirely safe to destroy all
// resources associated to this layer.
@@ -946,7 +911,6 @@
* Compositing
*/
void postComposition() REQUIRES(kMainThreadContext);
- void postFrame() REQUIRES(kMainThreadContext);
/*
* Display management
@@ -1046,7 +1010,7 @@
void clearStatsLocked(const DumpArgs& args, std::string& result);
void dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const;
void dumpFrameTimeline(const DumpArgs& args, std::string& result) const;
- void logFrameStats() REQUIRES(kMainThreadContext);
+ void logFrameStats(TimePoint now) REQUIRES(kMainThreadContext);
void dumpVSync(std::string& result) const REQUIRES(mStateLock);
void dumpStaticScreenStats(std::string& result) const;
@@ -1244,7 +1208,6 @@
uint32_t mTexturePoolSize = 0;
std::vector<uint32_t> mTexturePool;
- Condition mTransactionQueueCV;
std::unordered_map<sp<IBinder>, std::queue<TransactionState>, IListenerHash>
mPendingTransactionQueues;
LocklessQueue<TransactionState> mLocklessTransactionQueue;
@@ -1374,6 +1337,19 @@
void handleLayerCreatedLocked(const LayerCreatedState& state, int64_t vsyncId)
REQUIRES(mStateLock);
+ mutable std::mutex mMirrorDisplayLock;
+ struct MirrorDisplayState {
+ MirrorDisplayState(ui::LayerStack layerStack, sp<IBinder>& rootHandle,
+ const sp<Client>& client)
+ : layerStack(layerStack), rootHandle(rootHandle), client(client) {}
+
+ ui::LayerStack layerStack;
+ sp<IBinder> rootHandle;
+ const sp<Client> client;
+ };
+ std::vector<MirrorDisplayState> mMirrorDisplays GUARDED_BY(mMirrorDisplayLock);
+ bool commitMirrorDisplays(int64_t vsyncId);
+
std::atomic<ui::Transform::RotationFlags> mActiveDisplayTransformHint;
bool isRefreshRateOverlayEnabled() const REQUIRES(mStateLock) {
diff --git a/services/surfaceflinger/SurfaceFlingerDefaultFactory.cpp b/services/surfaceflinger/SurfaceFlingerDefaultFactory.cpp
index 2399a39..5c96f35 100644
--- a/services/surfaceflinger/SurfaceFlingerDefaultFactory.cpp
+++ b/services/surfaceflinger/SurfaceFlingerDefaultFactory.cpp
@@ -23,7 +23,6 @@
#include <ui/GraphicBuffer.h>
#include "BufferStateLayer.h"
-#include "ContainerLayer.h"
#include "DisplayDevice.h"
#include "EffectLayer.h"
#include "FrameTracer/FrameTracer.h"
@@ -57,22 +56,22 @@
}
sp<SurfaceInterceptor> DefaultFactory::createSurfaceInterceptor() {
- return new android::impl::SurfaceInterceptor();
+ return sp<android::impl::SurfaceInterceptor>::make();
}
sp<StartPropertySetThread> DefaultFactory::createStartPropertySetThread(
bool timestampPropertyValue) {
- return new StartPropertySetThread(timestampPropertyValue);
+ return sp<StartPropertySetThread>::make(timestampPropertyValue);
}
sp<DisplayDevice> DefaultFactory::createDisplayDevice(DisplayDeviceCreationArgs& creationArgs) {
- return new DisplayDevice(creationArgs);
+ return sp<DisplayDevice>::make(creationArgs);
}
sp<GraphicBuffer> DefaultFactory::createGraphicBuffer(uint32_t width, uint32_t height,
PixelFormat format, uint32_t layerCount,
uint64_t usage, std::string requestorName) {
- return new GraphicBuffer(width, height, format, layerCount, usage, requestorName);
+ return sp<GraphicBuffer>::make(width, height, format, layerCount, usage, requestorName);
}
void DefaultFactory::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
@@ -90,16 +89,12 @@
return compositionengine::impl::createCompositionEngine();
}
-sp<ContainerLayer> DefaultFactory::createContainerLayer(const LayerCreationArgs& args) {
- return new ContainerLayer(args);
-}
-
sp<BufferStateLayer> DefaultFactory::createBufferStateLayer(const LayerCreationArgs& args) {
- return new BufferStateLayer(args);
+ return sp<BufferStateLayer>::make(args);
}
sp<EffectLayer> DefaultFactory::createEffectLayer(const LayerCreationArgs& args) {
- return new EffectLayer(args);
+ return sp<EffectLayer>::make(args);
}
std::unique_ptr<FrameTracer> DefaultFactory::createFrameTracer() {
diff --git a/services/surfaceflinger/SurfaceFlingerDefaultFactory.h b/services/surfaceflinger/SurfaceFlingerDefaultFactory.h
index 4000e09..8d00379 100644
--- a/services/surfaceflinger/SurfaceFlingerDefaultFactory.h
+++ b/services/surfaceflinger/SurfaceFlingerDefaultFactory.h
@@ -43,7 +43,6 @@
std::unique_ptr<compositionengine::CompositionEngine> createCompositionEngine() override;
sp<BufferStateLayer> createBufferStateLayer(const LayerCreationArgs& args) override;
sp<EffectLayer> createEffectLayer(const LayerCreationArgs& args) override;
- sp<ContainerLayer> createContainerLayer(const LayerCreationArgs& args) override;
std::unique_ptr<FrameTracer> createFrameTracer() override;
std::unique_ptr<frametimeline::FrameTimeline> createFrameTimeline(
std::shared_ptr<TimeStats> timeStats, pid_t surfaceFlingerPid) override;
diff --git a/services/surfaceflinger/SurfaceFlingerFactory.cpp b/services/surfaceflinger/SurfaceFlingerFactory.cpp
index 3997b04..7bd6cf6 100644
--- a/services/surfaceflinger/SurfaceFlingerFactory.cpp
+++ b/services/surfaceflinger/SurfaceFlingerFactory.cpp
@@ -26,7 +26,7 @@
sp<SurfaceFlinger> createSurfaceFlinger() {
static DefaultFactory factory;
- return new SurfaceFlinger(factory);
+ return sp<SurfaceFlinger>::make(factory);
}
} // namespace android::surfaceflinger
diff --git a/services/surfaceflinger/SurfaceFlingerFactory.h b/services/surfaceflinger/SurfaceFlingerFactory.h
index 77a75c4..291838f 100644
--- a/services/surfaceflinger/SurfaceFlingerFactory.h
+++ b/services/surfaceflinger/SurfaceFlingerFactory.h
@@ -32,7 +32,6 @@
class BufferLayerConsumer;
class BufferStateLayer;
-class ContainerLayer;
class DisplayDevice;
class EffectLayer;
class FrameTracer;
@@ -93,7 +92,6 @@
virtual sp<BufferStateLayer> createBufferStateLayer(const LayerCreationArgs& args) = 0;
virtual sp<EffectLayer> createEffectLayer(const LayerCreationArgs& args) = 0;
- virtual sp<ContainerLayer> createContainerLayer(const LayerCreationArgs& args) = 0;
virtual std::unique_ptr<FrameTracer> createFrameTracer() = 0;
virtual std::unique_ptr<frametimeline::FrameTimeline> createFrameTimeline(
std::shared_ptr<TimeStats> timeStats, pid_t surfaceFlingerPid) = 0;
diff --git a/services/surfaceflinger/SurfaceInterceptor.cpp b/services/surfaceflinger/SurfaceInterceptor.cpp
index 0782fef..66691c2 100644
--- a/services/surfaceflinger/SurfaceInterceptor.cpp
+++ b/services/surfaceflinger/SurfaceInterceptor.cpp
@@ -46,7 +46,7 @@
std::scoped_lock lock(mListenersMutex);
- asBinder->linkToDeath(this);
+ asBinder->linkToDeath(sp<DeathRecipient>::fromExisting(this));
listener->onToggled(mEnabled); // notifies of current state
@@ -115,8 +115,9 @@
ATRACE_CALL();
for (const auto& l : layers) {
l->traverseInZOrder(LayerVector::StateSet::Drawing, [this](Layer* layer) {
- addSurfaceCreationLocked(createTraceIncrementLocked(), layer);
- addInitialSurfaceStateLocked(createTraceIncrementLocked(), layer);
+ addSurfaceCreationLocked(createTraceIncrementLocked(), sp<Layer>::fromExisting(layer));
+ addInitialSurfaceStateLocked(createTraceIncrementLocked(),
+ sp<Layer>::fromExisting(layer));
});
}
}
diff --git a/services/surfaceflinger/Tracing/TransactionProtoParser.cpp b/services/surfaceflinger/Tracing/TransactionProtoParser.cpp
index 65918f6..77dec6f 100644
--- a/services/surfaceflinger/Tracing/TransactionProtoParser.cpp
+++ b/services/surfaceflinger/Tracing/TransactionProtoParser.cpp
@@ -457,9 +457,9 @@
layer.parentSurfaceControlForChild = nullptr;
} else {
layer.parentSurfaceControlForChild =
- new SurfaceControl(SurfaceComposerClient::getDefault(),
- mMapper->getLayerHandle(static_cast<int32_t>(layerId)),
- static_cast<int32_t>(layerId));
+ sp<SurfaceControl>::make(SurfaceComposerClient::getDefault(),
+ mMapper->getLayerHandle(static_cast<int32_t>(layerId)),
+ static_cast<int32_t>(layerId));
}
}
if (proto.what() & layer_state_t::eRelativeLayerChanged) {
@@ -468,9 +468,9 @@
layer.relativeLayerSurfaceControl = nullptr;
} else {
layer.relativeLayerSurfaceControl =
- new SurfaceControl(SurfaceComposerClient::getDefault(),
- mMapper->getLayerHandle(static_cast<int32_t>(layerId)),
- static_cast<int32_t>(layerId));
+ sp<SurfaceControl>::make(SurfaceComposerClient::getDefault(),
+ mMapper->getLayerHandle(static_cast<int32_t>(layerId)),
+ static_cast<int32_t>(layerId));
}
layer.z = proto.z();
}
@@ -502,7 +502,7 @@
inputInfo.touchableRegionCropHandle =
mMapper->getLayerHandle(static_cast<int32_t>(layerId));
} else {
- inputInfo.touchableRegionCropHandle = nullptr;
+ inputInfo.touchableRegionCropHandle = wp<IBinder>();
}
layer.windowInfoHandle = sp<gui::WindowInfoHandle>::make(inputInfo);
diff --git a/services/surfaceflinger/Tracing/tools/LayerTraceGenerator.cpp b/services/surfaceflinger/Tracing/tools/LayerTraceGenerator.cpp
index c4b1b0f..ca642fb 100644
--- a/services/surfaceflinger/Tracing/tools/LayerTraceGenerator.cpp
+++ b/services/surfaceflinger/Tracing/tools/LayerTraceGenerator.cpp
@@ -48,23 +48,23 @@
}
sp<SurfaceInterceptor> createSurfaceInterceptor() override {
- return new android::impl::SurfaceInterceptor();
+ return sp<android::impl::SurfaceInterceptor>::make();
}
sp<StartPropertySetThread> createStartPropertySetThread(
bool /* timestampPropertyValue */) override {
- return nullptr;
+ return sp<StartPropertySetThread>();
}
sp<DisplayDevice> createDisplayDevice(DisplayDeviceCreationArgs& /* creationArgs */) override {
- return nullptr;
+ return sp<DisplayDevice>();
}
sp<GraphicBuffer> createGraphicBuffer(uint32_t /* width */, uint32_t /* height */,
PixelFormat /* format */, uint32_t /* layerCount */,
uint64_t /* usage */,
std::string /* requestorName */) override {
- return nullptr;
+ return sp<GraphicBuffer>();
}
void createBufferQueue(sp<IGraphicBufferProducer>* /* outProducer */,
@@ -80,16 +80,12 @@
return compositionengine::impl::createCompositionEngine();
}
- sp<ContainerLayer> createContainerLayer(const LayerCreationArgs& args) {
- return sp<ContainerLayer>::make(args);
- }
-
sp<BufferStateLayer> createBufferStateLayer(const LayerCreationArgs& args) {
- return new BufferStateLayer(args);
+ return sp<BufferStateLayer>::make(args);
}
sp<EffectLayer> createEffectLayer(const LayerCreationArgs& args) {
- return new EffectLayer(args);
+ return sp<EffectLayer>::make(args);
}
std::unique_ptr<FrameTracer> createFrameTracer() override {
@@ -178,7 +174,7 @@
}
Factory mFactory;
- sp<MockSurfaceFlinger> flinger = new MockSurfaceFlinger(mFactory);
+ sp<MockSurfaceFlinger> flinger = sp<MockSurfaceFlinger>::make(mFactory);
TestableSurfaceFlinger mFlinger(flinger);
mFlinger.setupRenderEngine(
std::make_unique<testing::NiceMock<renderengine::mock::RenderEngine>>());
diff --git a/services/surfaceflinger/TransactionCallbackInvoker.cpp b/services/surfaceflinger/TransactionCallbackInvoker.cpp
index d2c2e29..e5de759 100644
--- a/services/surfaceflinger/TransactionCallbackInvoker.cpp
+++ b/services/surfaceflinger/TransactionCallbackInvoker.cpp
@@ -178,8 +178,8 @@
return NO_ERROR;
}
-void TransactionCallbackInvoker::addPresentFence(const sp<Fence>& presentFence) {
- mPresentFence = presentFence;
+void TransactionCallbackInvoker::addPresentFence(sp<Fence> presentFence) {
+ mPresentFence = std::move(presentFence);
}
void TransactionCallbackInvoker::sendCallbacks(bool onCommitOnly) {
diff --git a/services/surfaceflinger/TransactionCallbackInvoker.h b/services/surfaceflinger/TransactionCallbackInvoker.h
index 81d79f0..59abe33 100644
--- a/services/surfaceflinger/TransactionCallbackInvoker.h
+++ b/services/surfaceflinger/TransactionCallbackInvoker.h
@@ -70,7 +70,7 @@
status_t registerUnpresentedCallbackHandle(const sp<CallbackHandle>& handle);
void addEmptyTransaction(const ListenerCallbacks& listenerCallbacks);
- void addPresentFence(const sp<Fence>& presentFence);
+ void addPresentFence(sp<Fence>);
void sendCallbacks(bool onCommitOnly);
void clearCompletedTransactions() {
diff --git a/services/surfaceflinger/TransactionState.h b/services/surfaceflinger/TransactionState.h
index bbfeac1..61f0fa6 100644
--- a/services/surfaceflinger/TransactionState.h
+++ b/services/surfaceflinger/TransactionState.h
@@ -98,7 +98,6 @@
int originUid;
uint64_t id;
std::shared_ptr<CountDownLatch> transactionCommittedSignal;
- int64_t queueTime = 0;
bool sentFenceTimeoutWarning = false;
};
diff --git a/services/surfaceflinger/TunnelModeEnabledReporter.cpp b/services/surfaceflinger/TunnelModeEnabledReporter.cpp
index 4497caf..bc9b870 100644
--- a/services/surfaceflinger/TunnelModeEnabledReporter.cpp
+++ b/services/surfaceflinger/TunnelModeEnabledReporter.cpp
@@ -59,7 +59,7 @@
void TunnelModeEnabledReporter::addListener(const sp<gui::ITunnelModeEnabledListener>& listener) {
sp<IBinder> asBinder = IInterface::asBinder(listener);
- asBinder->linkToDeath(this);
+ asBinder->linkToDeath(sp<DeathRecipient>::fromExisting(this));
bool tunnelModeEnabled = false;
{
std::scoped_lock lock(mMutex);
diff --git a/services/surfaceflinger/WindowInfosListenerInvoker.cpp b/services/surfaceflinger/WindowInfosListenerInvoker.cpp
index 4a8f157..a1313e3 100644
--- a/services/surfaceflinger/WindowInfosListenerInvoker.cpp
+++ b/services/surfaceflinger/WindowInfosListenerInvoker.cpp
@@ -62,7 +62,7 @@
void WindowInfosListenerInvoker::addWindowInfosListener(sp<IWindowInfosListener> listener) {
sp<IBinder> asBinder = IInterface::asBinder(listener);
- asBinder->linkToDeath(this);
+ asBinder->linkToDeath(sp<DeathRecipient>::fromExisting(this));
std::scoped_lock lock(mListenersMutex);
mWindowInfosListeners.try_emplace(asBinder, std::move(listener));
@@ -73,7 +73,7 @@
sp<IBinder> asBinder = IInterface::asBinder(listener);
std::scoped_lock lock(mListenersMutex);
- asBinder->unlinkToDeath(this);
+ asBinder->unlinkToDeath(sp<DeathRecipient>::fromExisting(this));
mWindowInfosListeners.erase(asBinder);
}
diff --git a/services/surfaceflinger/fuzzer/surfaceflinger_displayhardware_fuzzer.cpp b/services/surfaceflinger/fuzzer/surfaceflinger_displayhardware_fuzzer.cpp
index a605a2f..fae9165 100644
--- a/services/surfaceflinger/fuzzer/surfaceflinger_displayhardware_fuzzer.cpp
+++ b/services/surfaceflinger/fuzzer/surfaceflinger_displayhardware_fuzzer.cpp
@@ -116,7 +116,8 @@
class DisplayHardwareFuzzer {
public:
DisplayHardwareFuzzer(const uint8_t* data, size_t size) : mFdp(data, size) {
- mPhysicalDisplayId = SurfaceComposerClient::getInternalDisplayId().value();
+ mPhysicalDisplayId = SurfaceComposerClient::getInternalDisplayId().value_or(
+ PhysicalDisplayId::fromPort(mFdp.ConsumeIntegral<uint8_t>()));
};
void process();
@@ -480,8 +481,8 @@
BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
sp<FramebufferSurface> surface =
- new FramebufferSurface(mHwc, mPhysicalDisplayId, bqConsumer, getFuzzedSize() /*size*/,
- getFuzzedSize() /*maxSize*/);
+ sp<FramebufferSurface>::make(mHwc, mPhysicalDisplayId, bqConsumer,
+ getFuzzedSize() /*size*/, getFuzzedSize() /*maxSize*/);
surface->beginFrame(mFdp.ConsumeBool());
surface->prepareFrame(mFdp.PickValueInArray(kCompositionTypes));
@@ -497,15 +498,15 @@
DisplayIdGenerator<HalVirtualDisplayId> mGenerator;
VirtualDisplayId VirtualDisplayId = mGenerator.generateId().value();
- sp<SurfaceComposerClient> mClient = new SurfaceComposerClient();
+ sp<SurfaceComposerClient> mClient = sp<SurfaceComposerClient>::make();
sp<SurfaceControl> mSurfaceControl =
mClient->createSurface(String8("TestSurface"), 100, 100, PIXEL_FORMAT_RGBA_8888,
ISurfaceComposerClient::eFXSurfaceBufferState,
/*parent*/ nullptr);
- sp<BLASTBufferQueue> mBlastBufferQueueAdapter =
- new BLASTBufferQueue("TestBLASTBufferQueue", mSurfaceControl, 100, 100,
- PIXEL_FORMAT_RGBA_8888);
+ auto mBlastBufferQueueAdapter =
+ sp<BLASTBufferQueue>::make("TestBLASTBufferQueue", mSurfaceControl, 100, 100,
+ PIXEL_FORMAT_RGBA_8888);
sp<IGraphicBufferProducer> sink = mBlastBufferQueueAdapter->getIGraphicBufferProducer();
sp<IGraphicBufferProducer> bqProducer = mBlastBufferQueueAdapter->getIGraphicBufferProducer();
@@ -513,9 +514,9 @@
BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
BufferQueue::createBufferQueue(&sink, &bqConsumer);
- sp<VirtualDisplaySurface> surface =
- new VirtualDisplaySurface(mHwc, VirtualDisplayId, sink, bqProducer, bqConsumer,
- mFdp.ConsumeRandomLengthString().c_str() /*name*/);
+ auto surface =
+ sp<VirtualDisplaySurface>::make(mHwc, VirtualDisplayId, sink, bqProducer, bqConsumer,
+ mFdp.ConsumeRandomLengthString().c_str() /*name*/);
surface->beginFrame(mFdp.ConsumeBool());
surface->prepareFrame(mFdp.PickValueInArray(kCompositionTypes));
@@ -565,7 +566,7 @@
mHwc.getLayerReleaseFence(halDisplayID, layer);
- mHwc.setOutputBuffer(halVirtualDisplayId, sp<Fence>::make().get(), sp<GraphicBuffer>::make());
+ mHwc.setOutputBuffer(halVirtualDisplayId, sp<Fence>::make(), sp<GraphicBuffer>::make());
mHwc.clearReleaseFences(halDisplayID);
diff --git a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzer.cpp b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzer.cpp
index 8e60247..cf4cd80 100644
--- a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzer.cpp
+++ b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzer.cpp
@@ -103,7 +103,7 @@
class SurfaceFlingerFuzzer {
public:
SurfaceFlingerFuzzer(const uint8_t *data, size_t size) : mFdp(data, size) {
- mFlinger = mTestableFlinger.flinger();
+ mFlinger = sp<SurfaceFlinger>::fromExisting(mTestableFlinger.flinger());
};
void process(const uint8_t *data, size_t size);
diff --git a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h
index ed57e18..86b7a7a 100644
--- a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h
+++ b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h
@@ -31,7 +31,6 @@
#include <ui/DynamicDisplayInfo.h>
#include "BufferStateLayer.h"
-#include "ContainerLayer.h"
#include "DisplayDevice.h"
#include "DisplayHardware/ComposerHal.h"
#include "EffectLayer.h"
@@ -306,21 +305,21 @@
}
sp<SurfaceInterceptor> createSurfaceInterceptor() override {
- return new android::impl::SurfaceInterceptor();
+ return sp<android::impl::SurfaceInterceptor>::make();
}
sp<StartPropertySetThread> createStartPropertySetThread(bool timestampPropertyValue) override {
- return new StartPropertySetThread(timestampPropertyValue);
+ return sp<StartPropertySetThread>::make(timestampPropertyValue);
}
sp<DisplayDevice> createDisplayDevice(DisplayDeviceCreationArgs &creationArgs) override {
- return new DisplayDevice(creationArgs);
+ return sp<DisplayDevice>::make(creationArgs);
}
sp<GraphicBuffer> createGraphicBuffer(uint32_t width, uint32_t height, PixelFormat format,
uint32_t layerCount, uint64_t usage,
std::string requestorName) override {
- return new GraphicBuffer(width, height, format, layerCount, usage, requestorName);
+ return sp<GraphicBuffer>::make(width, height, format, layerCount, usage, requestorName);
}
void createBufferQueue(sp<IGraphicBufferProducer> *outProducer,
@@ -348,11 +347,7 @@
}
sp<EffectLayer> createEffectLayer(const LayerCreationArgs &args) override {
- return new EffectLayer(args);
- }
-
- sp<ContainerLayer> createContainerLayer(const LayerCreationArgs &args) override {
- return new ContainerLayer(args);
+ return sp<EffectLayer>::make(args);
}
std::unique_ptr<FrameTracer> createFrameTracer() override {
@@ -430,7 +425,8 @@
mFlinger->clearStatsLocked(dumpArgs, result);
mFlinger->dumpTimeStats(dumpArgs, fdp->ConsumeBool(), result);
- FTL_FAKE_GUARD(kMainThreadContext, mFlinger->logFrameStats());
+ FTL_FAKE_GUARD(kMainThreadContext,
+ mFlinger->logFrameStats(TimePoint::fromNs(fdp->ConsumeIntegral<nsecs_t>())));
result = fdp->ConsumeRandomLengthString().c_str();
mFlinger->dumpFrameTimeline(dumpArgs, result);
@@ -525,7 +521,7 @@
sp<IBinder> fuzzBoot(FuzzedDataProvider *fdp) {
mFlinger->callingThreadHasUnscopedSurfaceFlingerAccess(fdp->ConsumeBool());
- const sp<Client> client = new Client(mFlinger);
+ const sp<Client> client = sp<Client>::make(mFlinger);
DisplayIdGenerator<HalVirtualDisplayId> kGenerator;
HalVirtualDisplayId halVirtualDisplayId = kGenerator.generateId().value();
@@ -534,7 +530,9 @@
ui::PixelFormat pixelFormat{};
mFlinger->getHwComposer().allocateVirtualDisplay(halVirtualDisplayId, uiSize, &pixelFormat);
- PhysicalDisplayId physicalDisplayId = SurfaceComposerClient::getInternalDisplayId().value();
+ PhysicalDisplayId physicalDisplayId =
+ SurfaceComposerClient::getInternalDisplayId().value_or(
+ PhysicalDisplayId::fromPort(fdp->ConsumeIntegral<uint8_t>()));
mFlinger->getHwComposer().allocatePhysicalDisplay(kHwDisplayId, physicalDisplayId);
sp<IBinder> display =
@@ -615,7 +613,6 @@
mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mFdp.ConsumeIntegral<uid_t>());
FTL_FAKE_GUARD(kMainThreadContext, mFlinger->postComposition());
- FTL_FAKE_GUARD(kMainThreadContext, mFlinger->postFrame());
mFlinger->calculateExpectedPresentTime({});
@@ -781,7 +778,8 @@
void triggerOnFrameRateOverridesChanged() override {}
surfaceflinger::test::Factory mFactory;
- sp<SurfaceFlinger> mFlinger = new SurfaceFlinger(mFactory, SurfaceFlinger::SkipInitialization);
+ sp<SurfaceFlinger> mFlinger =
+ sp<SurfaceFlinger>::make(mFactory, SurfaceFlinger::SkipInitialization);
scheduler::TestableScheduler *mScheduler = nullptr;
std::shared_ptr<scheduler::RefreshRateConfigs> mRefreshRateConfigs;
};
diff --git a/services/surfaceflinger/fuzzer/surfaceflinger_layer_fuzzer.cpp b/services/surfaceflinger/fuzzer/surfaceflinger_layer_fuzzer.cpp
index ed94e76..aeccc52 100644
--- a/services/surfaceflinger/fuzzer/surfaceflinger_layer_fuzzer.cpp
+++ b/services/surfaceflinger/fuzzer/surfaceflinger_layer_fuzzer.cpp
@@ -77,7 +77,7 @@
void LayerFuzzer::invokeEffectLayer() {
TestableSurfaceFlinger flinger;
- sp<Client> client = sp<Client>::make(flinger.flinger());
+ sp<Client> client = sp<Client>::make(sp<SurfaceFlinger>::fromExisting(flinger.flinger()));
const LayerCreationArgs layerCreationArgs = createLayerCreationArgs(&flinger, client);
sp<EffectLayer> effectLayer = sp<EffectLayer>::make(layerCreationArgs);
@@ -109,7 +109,7 @@
void LayerFuzzer::invokeBufferStateLayer() {
TestableSurfaceFlinger flinger;
- sp<Client> client = sp<Client>::make(flinger.flinger());
+ sp<Client> client = sp<Client>::make(sp<SurfaceFlinger>::fromExisting(flinger.flinger()));
sp<BufferStateLayer> layer =
sp<BufferStateLayer>::make(createLayerCreationArgs(&flinger, client));
sp<Fence> fence = sp<Fence>::make();
diff --git a/services/surfaceflinger/fuzzer/surfaceflinger_scheduler_fuzzer.cpp b/services/surfaceflinger/fuzzer/surfaceflinger_scheduler_fuzzer.cpp
index 95219b5..f507ef0 100644
--- a/services/surfaceflinger/fuzzer/surfaceflinger_scheduler_fuzzer.cpp
+++ b/services/surfaceflinger/fuzzer/surfaceflinger_scheduler_fuzzer.cpp
@@ -96,8 +96,8 @@
thread->onHotplugReceived(getPhysicalDisplayId(), mFdp.ConsumeBool());
sp<EventThreadConnection> connection =
- new EventThreadConnection(thread.get(), mFdp.ConsumeIntegral<uint16_t>(), nullptr,
- {} /*eventRegistration*/);
+ sp<EventThreadConnection>::make(thread.get(), mFdp.ConsumeIntegral<uint16_t>(),
+ nullptr);
thread->requestNextVsync(connection);
thread->setVsyncRate(mFdp.ConsumeIntegral<uint32_t>() /*rate*/, connection);
@@ -227,8 +227,8 @@
nsecs_t time2 = time1;
uint8_t historySize = mFdp.ConsumeIntegral<uint8_t>();
- sp<FuzzImplLayer> layer1 = new FuzzImplLayer(flinger.flinger());
- sp<FuzzImplLayer> layer2 = new FuzzImplLayer(flinger.flinger());
+ sp<FuzzImplLayer> layer1 = sp<FuzzImplLayer>::make(flinger.flinger());
+ sp<FuzzImplLayer> layer2 = sp<FuzzImplLayer>::make(flinger.flinger());
for (int i = 0; i < historySize; ++i) {
historyV1.record(layer1.get(), time1, time1,
@@ -263,7 +263,7 @@
reactor.addHwVsyncTimestamp(0, std::nullopt, &periodFlushed);
reactor.addHwVsyncTimestamp(mFdp.ConsumeIntegral<nsecs_t>() /*newPeriod*/, std::nullopt,
&periodFlushed);
- sp<Fence> fence = new Fence(memfd_create("fd", MFD_ALLOW_SEALING));
+ sp<Fence> fence = sp<Fence>::make(memfd_create("fd", MFD_ALLOW_SEALING));
std::shared_ptr<FenceTime> ft = std::make_shared<FenceTime>(fence);
vSyncTracker->addVsyncTimestamp(mFdp.ConsumeIntegral<nsecs_t>());
FenceTime::Snapshot snap(mFdp.ConsumeIntegral<nsecs_t>());
@@ -322,7 +322,7 @@
LayerCreationArgs args(flinger.flinger(), client,
mFdp.ConsumeRandomLengthString(kRandomStringLength) /*name*/,
mFdp.ConsumeIntegral<uint16_t>() /*layerFlags*/, LayerMetadata());
- sp<Layer> layer = new BufferStateLayer(args);
+ sp<Layer> layer = sp<BufferStateLayer>::make(args);
layer->setFrameRateSelectionPriority(mFdp.ConsumeIntegral<int16_t>());
}
diff --git a/services/surfaceflinger/main_surfaceflinger.cpp b/services/surfaceflinger/main_surfaceflinger.cpp
index ec18054..fedd71e 100644
--- a/services/surfaceflinger/main_surfaceflinger.cpp
+++ b/services/surfaceflinger/main_surfaceflinger.cpp
@@ -67,7 +67,7 @@
using android::frameworks::displayservice::V1_0::implementation::DisplayService;
using android::frameworks::displayservice::V1_0::IDisplayService;
- sp<IDisplayService> displayservice = new DisplayService();
+ sp<IDisplayService> displayservice = sp<DisplayService>::make();
status_t err = displayservice->registerAsService();
// b/141930622
@@ -153,7 +153,7 @@
IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL | IServiceManager::DUMP_FLAG_PROTO);
// publish gui::ISurfaceComposer, the new AIDL interface
- sp<SurfaceComposerAIDL> composerAIDL = new SurfaceComposerAIDL(flinger);
+ sp<SurfaceComposerAIDL> composerAIDL = sp<SurfaceComposerAIDL>::make(flinger);
sm->addService(String16("SurfaceFlingerAIDL"), composerAIDL, false,
IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL | IServiceManager::DUMP_FLAG_PROTO);
diff --git a/services/surfaceflinger/tests/BufferGenerator.cpp b/services/surfaceflinger/tests/BufferGenerator.cpp
index 47a150d..d74bd55 100644
--- a/services/surfaceflinger/tests/BufferGenerator.cpp
+++ b/services/surfaceflinger/tests/BufferGenerator.cpp
@@ -70,12 +70,13 @@
consumer->setDefaultBufferSize(width, height);
consumer->setDefaultBufferFormat(format);
- mBufferItemConsumer = new BufferItemConsumer(consumer, GraphicBuffer::USAGE_HW_TEXTURE);
+ mBufferItemConsumer =
+ sp<BufferItemConsumer>::make(consumer, GraphicBuffer::USAGE_HW_TEXTURE);
- mListener = new BufferListener(consumer, callback);
+ mListener = sp<BufferListener>::make(consumer, callback);
mBufferItemConsumer->setFrameAvailableListener(mListener);
- mSurface = new Surface(producer, true);
+ mSurface = sp<Surface>::make(producer, true);
}
/* Used by Egl manager. The surface is never displayed. */
@@ -364,7 +365,7 @@
*outBuffer = mGraphicBuffer;
}
if (outFence) {
- *outFence = new Fence(mFence);
+ *outFence = sp<Fence>::make(mFence);
} else {
close(mFence);
}
diff --git a/services/surfaceflinger/tests/Credentials_test.cpp b/services/surfaceflinger/tests/Credentials_test.cpp
index 8a443b8..353b813 100644
--- a/services/surfaceflinger/tests/Credentials_test.cpp
+++ b/services/surfaceflinger/tests/Credentials_test.cpp
@@ -77,7 +77,7 @@
sp<SurfaceControl> mVirtualSurfaceControl;
void initClient() {
- mComposerClient = new SurfaceComposerClient;
+ mComposerClient = sp<SurfaceComposerClient>::make();
ASSERT_EQ(NO_ERROR, mComposerClient->initCheck());
}
@@ -169,7 +169,7 @@
// Anyone else can init the client.
setBinUID();
- mComposerClient = new SurfaceComposerClient;
+ mComposerClient = sp<SurfaceComposerClient>::make();
ASSERT_NO_FATAL_FAILURE(initClient());
}
diff --git a/services/surfaceflinger/tests/IPC_test.cpp b/services/surfaceflinger/tests/IPC_test.cpp
index ce94dab..c63d251 100644
--- a/services/surfaceflinger/tests/IPC_test.cpp
+++ b/services/surfaceflinger/tests/IPC_test.cpp
@@ -136,7 +136,7 @@
}
status_t initClient() override {
- mClient = new SurfaceComposerClient;
+ mClient = sp<SurfaceComposerClient>::make();
auto err = mClient->initCheck();
return err;
}
@@ -221,7 +221,7 @@
ProcessState::self()->startThreadPool();
}
void SetUp() {
- mClient = new SurfaceComposerClient;
+ mClient = sp<SurfaceComposerClient>::make();
ASSERT_EQ(NO_ERROR, mClient->initCheck());
mPrimaryDisplay = mClient->getInternalDisplayToken();
diff --git a/services/surfaceflinger/tests/InvalidHandles_test.cpp b/services/surfaceflinger/tests/InvalidHandles_test.cpp
index 023133f..741b6f7 100644
--- a/services/surfaceflinger/tests/InvalidHandles_test.cpp
+++ b/services/surfaceflinger/tests/InvalidHandles_test.cpp
@@ -42,13 +42,13 @@
sp<SurfaceComposerClient> mScc;
sp<SurfaceControl> mNotSc;
void SetUp() override {
- mScc = new SurfaceComposerClient;
+ mScc = sp<SurfaceComposerClient>::make();
ASSERT_EQ(NO_ERROR, mScc->initCheck());
mNotSc = makeNotSurfaceControl();
}
sp<SurfaceControl> makeNotSurfaceControl() {
- return new SurfaceControl(mScc, new NotALayer(), 1);
+ return sp<SurfaceControl>::make(mScc, sp<NotALayer>::make(), 1);
}
};
diff --git a/services/surfaceflinger/tests/LayerBorder_test.cpp b/services/surfaceflinger/tests/LayerBorder_test.cpp
index f80c705..0d55ec1 100644
--- a/services/surfaceflinger/tests/LayerBorder_test.cpp
+++ b/services/surfaceflinger/tests/LayerBorder_test.cpp
@@ -228,10 +228,11 @@
mContainerLayer->getHandle());
sp<GraphicBuffer> buffer =
- new GraphicBuffer(400, 400, PIXEL_FORMAT_RGBA_8888, 1,
- BufferUsage::CPU_READ_OFTEN | BufferUsage::CPU_WRITE_OFTEN |
- BufferUsage::COMPOSER_OVERLAY | BufferUsage::GPU_TEXTURE,
- "test");
+ sp<GraphicBuffer>::make(400u, 400u, PIXEL_FORMAT_RGBA_8888, 1u,
+ BufferUsage::CPU_READ_OFTEN | BufferUsage::CPU_WRITE_OFTEN |
+ BufferUsage::COMPOSER_OVERLAY |
+ BufferUsage::GPU_TEXTURE,
+ "test");
TransactionUtils::fillGraphicBufferColor(buffer, Rect(0, 0, 200, 200), Color::GREEN);
TransactionUtils::fillGraphicBufferColor(buffer, Rect(200, 200, 400, 400), Color::BLUE);
diff --git a/services/surfaceflinger/tests/LayerCallback_test.cpp b/services/surfaceflinger/tests/LayerCallback_test.cpp
index c8df0a0..1460fe1 100644
--- a/services/surfaceflinger/tests/LayerCallback_test.cpp
+++ b/services/surfaceflinger/tests/LayerCallback_test.cpp
@@ -442,8 +442,8 @@
}
TEST_F(LayerCallbackTest, Merge_DifferentClients) {
- sp<SurfaceComposerClient> client1(new SurfaceComposerClient),
- client2(new SurfaceComposerClient);
+ sp<SurfaceComposerClient> client1(sp<SurfaceComposerClient>::make()),
+ client2(sp<SurfaceComposerClient>::make());
ASSERT_EQ(NO_ERROR, client1->initCheck()) << "failed to create SurfaceComposerClient";
ASSERT_EQ(NO_ERROR, client2->initCheck()) << "failed to create SurfaceComposerClient";
@@ -620,8 +620,8 @@
}
TEST_F(LayerCallbackTest, MultipleTransactions_Merge_DifferentClients) {
- sp<SurfaceComposerClient> client1(new SurfaceComposerClient),
- client2(new SurfaceComposerClient);
+ sp<SurfaceComposerClient> client1(sp<SurfaceComposerClient>::make()),
+ client2(sp<SurfaceComposerClient>::make());
ASSERT_EQ(NO_ERROR, client1->initCheck()) << "failed to create SurfaceComposerClient";
ASSERT_EQ(NO_ERROR, client2->initCheck()) << "failed to create SurfaceComposerClient";
@@ -669,8 +669,8 @@
}
TEST_F(LayerCallbackTest, MultipleTransactions_Merge_DifferentClients_NoStateChange) {
- sp<SurfaceComposerClient> client1(new SurfaceComposerClient),
- client2(new SurfaceComposerClient);
+ sp<SurfaceComposerClient> client1(sp<SurfaceComposerClient>::make()),
+ client2(sp<SurfaceComposerClient>::make());
ASSERT_EQ(NO_ERROR, client1->initCheck()) << "failed to create SurfaceComposerClient";
ASSERT_EQ(NO_ERROR, client2->initCheck()) << "failed to create SurfaceComposerClient";
@@ -730,8 +730,8 @@
}
TEST_F(LayerCallbackTest, MultipleTransactions_Merge_DifferentClients_SameStateChange) {
- sp<SurfaceComposerClient> client1(new SurfaceComposerClient),
- client2(new SurfaceComposerClient);
+ sp<SurfaceComposerClient> client1(sp<SurfaceComposerClient>::make()),
+ client2(sp<SurfaceComposerClient>::make());
ASSERT_EQ(NO_ERROR, client1->initCheck()) << "failed to create SurfaceComposerClient";
ASSERT_EQ(NO_ERROR, client2->initCheck()) << "failed to create SurfaceComposerClient";
diff --git a/services/surfaceflinger/tests/LayerRenderTypeTransaction_test.cpp b/services/surfaceflinger/tests/LayerRenderTypeTransaction_test.cpp
index 0e2bc3d..bbe7ae8 100644
--- a/services/surfaceflinger/tests/LayerRenderTypeTransaction_test.cpp
+++ b/services/surfaceflinger/tests/LayerRenderTypeTransaction_test.cpp
@@ -328,7 +328,7 @@
layer = createLayer("test", 32, 32, ISurfaceComposerClient::eFXSurfaceBufferState));
sp<GraphicBuffer> buffer =
- new GraphicBuffer(32, 32, PIXEL_FORMAT_RGBA_8888, 1, kUsageFlags, "test");
+ sp<GraphicBuffer>::make(32u, 32u, PIXEL_FORMAT_RGBA_8888, 1u, kUsageFlags, "test");
ASSERT_NO_FATAL_FAILURE(
TransactionUtils::fillGraphicBufferColor(buffer, top, Color::TRANSPARENT));
@@ -352,7 +352,7 @@
shot->expectColor(bottom, Color::BLACK);
}
- buffer = new GraphicBuffer(32, 32, PIXEL_FORMAT_RGBA_8888, 1, kUsageFlags, "test");
+ buffer = sp<GraphicBuffer>::make(32u, 32u, PIXEL_FORMAT_RGBA_8888, 1u, kUsageFlags, "test");
ASSERT_NO_FATAL_FAILURE(TransactionUtils::fillGraphicBufferColor(buffer, top, Color::RED));
ASSERT_NO_FATAL_FAILURE(
@@ -894,7 +894,7 @@
ASSERT_NO_FATAL_FAILURE(
layer = createLayer("test", 32, 64, ISurfaceComposerClient::eFXSurfaceBufferState));
sp<GraphicBuffer> buffer =
- new GraphicBuffer(32, 64, PIXEL_FORMAT_RGBA_8888, 1, kUsageFlags, "test");
+ sp<GraphicBuffer>::make(32, 64, PIXEL_FORMAT_RGBA_8888, 1, kUsageFlags, "test");
TransactionUtils::fillGraphicBufferColor(buffer, Rect(0, 0, 32, 16), Color::BLUE);
TransactionUtils::fillGraphicBufferColor(buffer, Rect(0, 16, 32, 64), Color::RED);
@@ -1197,7 +1197,7 @@
size_t idx = 0;
for (auto& buffer : buffers) {
- buffer = new GraphicBuffer(32, 32, PIXEL_FORMAT_RGBA_8888, 1, kUsageFlags, "test");
+ buffer = sp<GraphicBuffer>::make(32u, 32u, PIXEL_FORMAT_RGBA_8888, 1u, kUsageFlags, "test");
Color color = colors[idx % colors.size()];
TransactionUtils::fillGraphicBufferColor(buffer, Rect(0, 0, 32, 32), color);
idx++;
@@ -1230,7 +1230,7 @@
size_t idx = 0;
for (auto& buffer : buffers) {
- buffer = new GraphicBuffer(32, 32, PIXEL_FORMAT_RGBA_8888, 1, kUsageFlags, "test");
+ buffer = sp<GraphicBuffer>::make(32u, 32u, PIXEL_FORMAT_RGBA_8888, 1u, kUsageFlags, "test");
Color color = colors[idx % colors.size()];
TransactionUtils::fillGraphicBufferColor(buffer, Rect(0, 0, 32, 32), color);
idx++;
@@ -1263,7 +1263,7 @@
size_t idx = 0;
for (auto& buffer : buffers) {
- buffer = new GraphicBuffer(32, 32, PIXEL_FORMAT_RGBA_8888, 1, kUsageFlags, "test");
+ buffer = sp<GraphicBuffer>::make(32u, 32u, PIXEL_FORMAT_RGBA_8888, 1u, kUsageFlags, "test");
Color color = colors[idx % colors.size()];
TransactionUtils::fillGraphicBufferColor(buffer, Rect(0, 0, 32, 32), color);
idx++;
@@ -1344,7 +1344,7 @@
layer = createLayer("test", 32, 32, ISurfaceComposerClient::eFXSurfaceBufferState));
sp<GraphicBuffer> buffer =
- new GraphicBuffer(32, 32, PIXEL_FORMAT_RGBA_8888, 1, kUsageFlags, "test");
+ sp<GraphicBuffer>::make(32u, 32u, PIXEL_FORMAT_RGBA_8888, 1u, kUsageFlags, "test");
TransactionUtils::fillGraphicBufferColor(buffer, Rect(0, 0, 32, 32), Color::RED);
sp<Fence> fence;
@@ -1370,7 +1370,7 @@
layer = createLayer("test", 32, 32, ISurfaceComposerClient::eFXSurfaceBufferState));
sp<GraphicBuffer> buffer =
- new GraphicBuffer(32, 32, PIXEL_FORMAT_RGBA_8888, 1, kUsageFlags, "test");
+ sp<GraphicBuffer>::make(32u, 32u, PIXEL_FORMAT_RGBA_8888, 1u, kUsageFlags, "test");
TransactionUtils::fillGraphicBufferColor(buffer, Rect(0, 0, 32, 32), Color::RED);
sp<Fence> fence = Fence::NO_FENCE;
@@ -1388,7 +1388,7 @@
layer = createLayer("test", 32, 32, ISurfaceComposerClient::eFXSurfaceBufferState));
sp<GraphicBuffer> buffer =
- new GraphicBuffer(32, 32, PIXEL_FORMAT_RGBA_8888, 1, kUsageFlags, "test");
+ sp<GraphicBuffer>::make(32u, 32u, PIXEL_FORMAT_RGBA_8888, 1u, kUsageFlags, "test");
TransactionUtils::fillGraphicBufferColor(buffer, Rect(0, 0, 32, 32), Color::RED);
Transaction().setBuffer(layer, buffer).setDataspace(layer, ui::Dataspace::UNKNOWN).apply();
@@ -1404,7 +1404,7 @@
layer = createLayer("test", 32, 32, ISurfaceComposerClient::eFXSurfaceBufferState));
sp<GraphicBuffer> buffer =
- new GraphicBuffer(32, 32, PIXEL_FORMAT_RGBA_8888, 1, kUsageFlags, "test");
+ sp<GraphicBuffer>::make(32u, 32u, PIXEL_FORMAT_RGBA_8888, 1u, kUsageFlags, "test");
TransactionUtils::fillGraphicBufferColor(buffer, Rect(0, 0, 32, 32), Color::RED);
HdrMetadata hdrMetadata;
@@ -1422,7 +1422,7 @@
layer = createLayer("test", 32, 32, ISurfaceComposerClient::eFXSurfaceBufferState));
sp<GraphicBuffer> buffer =
- new GraphicBuffer(32, 32, PIXEL_FORMAT_RGBA_8888, 1, kUsageFlags, "test");
+ sp<GraphicBuffer>::make(32u, 32u, PIXEL_FORMAT_RGBA_8888, 1u, kUsageFlags, "test");
TransactionUtils::fillGraphicBufferColor(buffer, Rect(0, 0, 32, 32), Color::RED);
Region region;
@@ -1440,7 +1440,7 @@
layer = createLayer("test", 32, 32, ISurfaceComposerClient::eFXSurfaceBufferState));
sp<GraphicBuffer> buffer =
- new GraphicBuffer(32, 32, PIXEL_FORMAT_RGBA_8888, 1, kUsageFlags, "test");
+ sp<GraphicBuffer>::make(32u, 32u, PIXEL_FORMAT_RGBA_8888, 1u, kUsageFlags, "test");
TransactionUtils::fillGraphicBufferColor(buffer, Rect(0, 0, 32, 32), Color::RED);
Transaction().setBuffer(layer, buffer).setApi(layer, NATIVE_WINDOW_API_CPU).apply();
diff --git a/services/surfaceflinger/tests/LayerState_test.cpp b/services/surfaceflinger/tests/LayerState_test.cpp
index 094b0ff..fbbf322 100644
--- a/services/surfaceflinger/tests/LayerState_test.cpp
+++ b/services/surfaceflinger/tests/LayerState_test.cpp
@@ -35,7 +35,7 @@
args.frameScaleX = 2;
args.frameScaleY = 4;
args.captureSecureLayers = true;
- args.displayToken = new BBinder();
+ args.displayToken = sp<BBinder>::make();
args.width = 10;
args.height = 20;
args.useIdentityTransform = true;
@@ -67,8 +67,8 @@
args.frameScaleX = 2;
args.frameScaleY = 4;
args.captureSecureLayers = true;
- args.layerHandle = new BBinder();
- args.excludeHandles = {new BBinder(), new BBinder()};
+ args.layerHandle = sp<BBinder>::make();
+ args.excludeHandles = {sp<BBinder>::make(), sp<BBinder>::make()};
args.childrenOnly = false;
args.grayscale = true;
@@ -92,8 +92,8 @@
TEST(LayerStateTest, ParcellingScreenCaptureResults) {
ScreenCaptureResults results;
- results.buffer = new GraphicBuffer(100, 200, PIXEL_FORMAT_RGBA_8888, 1, 0);
- results.fence = new Fence(dup(fileno(tmpfile())));
+ results.buffer = sp<GraphicBuffer>::make(100u, 200u, PIXEL_FORMAT_RGBA_8888, 1u, 0u);
+ results.fence = sp<Fence>::make(dup(fileno(tmpfile())));
results.capturedSecureLayers = true;
results.capturedDataspace = ui::Dataspace::DISPLAY_P3;
results.result = BAD_VALUE;
diff --git a/services/surfaceflinger/tests/LayerTransactionTest.h b/services/surfaceflinger/tests/LayerTransactionTest.h
index b46db65..4b91605 100644
--- a/services/surfaceflinger/tests/LayerTransactionTest.h
+++ b/services/surfaceflinger/tests/LayerTransactionTest.h
@@ -41,7 +41,7 @@
class LayerTransactionTest : public ::testing::Test {
protected:
void SetUp() override {
- mClient = new SurfaceComposerClient;
+ mClient = sp<SurfaceComposerClient>::make();
ASSERT_EQ(NO_ERROR, mClient->initCheck()) << "failed to create SurfaceComposerClient";
ASSERT_NO_FATAL_FAILURE(SetUpDisplay());
@@ -140,10 +140,13 @@
virtual void fillBufferStateLayerColor(const sp<SurfaceControl>& layer, const Color& color,
int32_t bufferWidth, int32_t bufferHeight) {
sp<GraphicBuffer> buffer =
- new GraphicBuffer(bufferWidth, bufferHeight, PIXEL_FORMAT_RGBA_8888, 1,
- BufferUsage::CPU_READ_OFTEN | BufferUsage::CPU_WRITE_OFTEN |
- BufferUsage::COMPOSER_OVERLAY | BufferUsage::GPU_TEXTURE,
- "test");
+ sp<GraphicBuffer>::make(static_cast<uint32_t>(bufferWidth),
+ static_cast<uint32_t>(bufferHeight), PIXEL_FORMAT_RGBA_8888,
+ 1u,
+ BufferUsage::CPU_READ_OFTEN | BufferUsage::CPU_WRITE_OFTEN |
+ BufferUsage::COMPOSER_OVERLAY |
+ BufferUsage::GPU_TEXTURE,
+ "test");
TransactionUtils::fillGraphicBufferColor(buffer, Rect(0, 0, bufferWidth, bufferHeight),
color);
Transaction().setBuffer(layer, buffer).apply();
@@ -209,10 +212,13 @@
const Color& topRight, const Color& bottomLeft,
const Color& bottomRight) {
sp<GraphicBuffer> buffer =
- new GraphicBuffer(bufferWidth, bufferHeight, PIXEL_FORMAT_RGBA_8888, 1,
- BufferUsage::CPU_READ_OFTEN | BufferUsage::CPU_WRITE_OFTEN |
- BufferUsage::COMPOSER_OVERLAY | BufferUsage::GPU_TEXTURE,
- "test");
+ sp<GraphicBuffer>::make(static_cast<uint32_t>(bufferWidth),
+ static_cast<uint32_t>(bufferHeight), PIXEL_FORMAT_RGBA_8888,
+ 1u,
+ BufferUsage::CPU_READ_OFTEN | BufferUsage::CPU_WRITE_OFTEN |
+ BufferUsage::COMPOSER_OVERLAY |
+ BufferUsage::GPU_TEXTURE,
+ "test");
ASSERT_TRUE(bufferWidth % 2 == 0 && bufferHeight % 2 == 0);
diff --git a/services/surfaceflinger/tests/LayerTransaction_test.cpp b/services/surfaceflinger/tests/LayerTransaction_test.cpp
index ef992d6..513fdc3 100644
--- a/services/surfaceflinger/tests/LayerTransaction_test.cpp
+++ b/services/surfaceflinger/tests/LayerTransaction_test.cpp
@@ -80,7 +80,7 @@
sp<SurfaceControl> layer;
ASSERT_NO_FATAL_FAILURE(layer = createLayer("test", width, height));
const auto producer = layer->getIGraphicBufferProducer();
- const sp<IProducerListener> stubListener(new StubProducerListener);
+ const sp<IProducerListener> stubListener(sp<StubProducerListener>::make());
IGraphicBufferProducer::QueueBufferOutput queueBufferOutput;
ASSERT_EQ(OK, producer->connect(stubListener, NATIVE_WINDOW_API_CPU, true, &queueBufferOutput));
diff --git a/services/surfaceflinger/tests/LayerTypeAndRenderTypeTransaction_test.cpp b/services/surfaceflinger/tests/LayerTypeAndRenderTypeTransaction_test.cpp
index 9cb617a..f247c9f 100644
--- a/services/surfaceflinger/tests/LayerTypeAndRenderTypeTransaction_test.cpp
+++ b/services/surfaceflinger/tests/LayerTypeAndRenderTypeTransaction_test.cpp
@@ -799,7 +799,7 @@
sp<Surface> surface = layer->getSurface();
sp<GraphicBuffer> buffer =
- new GraphicBuffer(width, height, PIXEL_FORMAT_RGBX_8888, 1, kUsageFlags, "test");
+ sp<GraphicBuffer>::make(width, height, PIXEL_FORMAT_RGBX_8888, 1, kUsageFlags, "test");
ASSERT_NO_FATAL_FAILURE(
TransactionUtils::fillGraphicBufferColor(buffer, crop, Color::TRANSPARENT));
@@ -815,7 +815,7 @@
shot->expectColor(crop, Color::BLACK);
}
- buffer = new GraphicBuffer(width, height, PIXEL_FORMAT_RGBA_8888, 1, kUsageFlags, "test");
+ buffer = sp<GraphicBuffer>::make(width, height, PIXEL_FORMAT_RGBA_8888, 1, kUsageFlags, "test");
ASSERT_NO_FATAL_FAILURE(
TransactionUtils::fillGraphicBufferColor(buffer, crop, Color::TRANSPARENT));
diff --git a/services/surfaceflinger/tests/ReleaseBufferCallback_test.cpp b/services/surfaceflinger/tests/ReleaseBufferCallback_test.cpp
index a6d7f58..16076ea 100644
--- a/services/surfaceflinger/tests/ReleaseBufferCallback_test.cpp
+++ b/services/surfaceflinger/tests/ReleaseBufferCallback_test.cpp
@@ -110,10 +110,10 @@
}
static sp<GraphicBuffer> getBuffer() {
- return new GraphicBuffer(32, 32, PIXEL_FORMAT_RGBA_8888, 1,
- BufferUsage::CPU_READ_OFTEN | BufferUsage::CPU_WRITE_OFTEN |
- BufferUsage::COMPOSER_OVERLAY,
- "test");
+ return sp<GraphicBuffer>::make(32u, 32u, PIXEL_FORMAT_RGBA_8888, 1u,
+ BufferUsage::CPU_READ_OFTEN | BufferUsage::CPU_WRITE_OFTEN |
+ BufferUsage::COMPOSER_OVERLAY,
+ "test");
}
static uint64_t generateFrameNumber() {
static uint64_t sFrameNumber = 0;
@@ -332,8 +332,10 @@
}
TEST_F(ReleaseBufferCallbackTest, DISABLED_Merge_Different_Processes) {
- sp<TransactionCompletedListener> firstCompletedListener = new TransactionCompletedListener();
- sp<TransactionCompletedListener> secondCompletedListener = new TransactionCompletedListener();
+ sp<TransactionCompletedListener> firstCompletedListener =
+ sp<TransactionCompletedListener>::make();
+ sp<TransactionCompletedListener> secondCompletedListener =
+ sp<TransactionCompletedListener>::make();
CallbackHelper callback1, callback2;
@@ -433,8 +435,10 @@
}
TEST_F(ReleaseBufferCallbackTest, DISABLED_MergeBuffers_Different_Processes) {
- sp<TransactionCompletedListener> firstCompletedListener = new TransactionCompletedListener();
- sp<TransactionCompletedListener> secondCompletedListener = new TransactionCompletedListener();
+ sp<TransactionCompletedListener> firstCompletedListener =
+ sp<TransactionCompletedListener>::make();
+ sp<TransactionCompletedListener> secondCompletedListener =
+ sp<TransactionCompletedListener>::make();
TransactionCompletedListener::setInstance(firstCompletedListener);
diff --git a/services/surfaceflinger/tests/ScreenCapture_test.cpp b/services/surfaceflinger/tests/ScreenCapture_test.cpp
index 6a7d8b8..d78c8a9 100644
--- a/services/surfaceflinger/tests/ScreenCapture_test.cpp
+++ b/services/surfaceflinger/tests/ScreenCapture_test.cpp
@@ -519,7 +519,7 @@
TEST_F(ScreenCaptureTest, CaptureInvalidLayer) {
LayerCaptureArgs args;
- args.layerHandle = new BBinder();
+ args.layerHandle = sp<BBinder>::make();
ScreenCaptureResults captureResults;
// Layer was deleted so captureLayers should fail with NAME_NOT_FOUND
diff --git a/services/surfaceflinger/tests/Stress_test.cpp b/services/surfaceflinger/tests/Stress_test.cpp
index e9b6ba0..03201f7 100644
--- a/services/surfaceflinger/tests/Stress_test.cpp
+++ b/services/surfaceflinger/tests/Stress_test.cpp
@@ -32,7 +32,7 @@
TEST(SurfaceFlingerStress, create_and_destroy) {
auto do_stress = []() {
- sp<SurfaceComposerClient> client = new SurfaceComposerClient;
+ sp<SurfaceComposerClient> client = sp<SurfaceComposerClient>::make();
ASSERT_EQ(NO_ERROR, client->initCheck());
for (int j = 0; j < 1000; j++) {
auto surf = client->createSurface(String8("t"), 100, 100,
diff --git a/services/surfaceflinger/tests/SurfaceInterceptor_test.cpp b/services/surfaceflinger/tests/SurfaceInterceptor_test.cpp
index 28e8b8c..8dcd013 100644
--- a/services/surfaceflinger/tests/SurfaceInterceptor_test.cpp
+++ b/services/surfaceflinger/tests/SurfaceInterceptor_test.cpp
@@ -138,7 +138,7 @@
// Allow SurfaceInterceptor write to /data
system("setenforce 0");
- mComposerClient = new SurfaceComposerClient;
+ mComposerClient = sp<SurfaceComposerClient>::make();
ASSERT_EQ(NO_ERROR, mComposerClient->initCheck());
}
diff --git a/services/surfaceflinger/tests/TransactionTestHarnesses.h b/services/surfaceflinger/tests/TransactionTestHarnesses.h
index 8ce63bc..ad03ed3 100644
--- a/services/surfaceflinger/tests/TransactionTestHarnesses.h
+++ b/services/surfaceflinger/tests/TransactionTestHarnesses.h
@@ -53,11 +53,11 @@
consumer->setConsumerName(String8("Virtual disp consumer"));
consumer->setDefaultBufferSize(resolution.getWidth(), resolution.getHeight());
- itemConsumer = new BufferItemConsumer(consumer,
- // Sample usage bits from screenrecord
- GRALLOC_USAGE_HW_VIDEO_ENCODER |
- GRALLOC_USAGE_SW_READ_OFTEN);
- sp<BufferListener> listener = new BufferListener(this);
+ itemConsumer = sp<BufferItemConsumer>::make(consumer,
+ // Sample usage bits from screenrecord
+ GRALLOC_USAGE_HW_VIDEO_ENCODER |
+ GRALLOC_USAGE_SW_READ_OFTEN);
+ sp<BufferListener> listener = sp<BufferListener>::make(this);
itemConsumer->setFrameAvailableListener(listener);
vDisplay = SurfaceComposerClient::createDisplay(String8("VirtualDisplay"),
diff --git a/services/surfaceflinger/tests/VirtualDisplay_test.cpp b/services/surfaceflinger/tests/VirtualDisplay_test.cpp
index 18e0806..f31f582 100644
--- a/services/surfaceflinger/tests/VirtualDisplay_test.cpp
+++ b/services/surfaceflinger/tests/VirtualDisplay_test.cpp
@@ -33,7 +33,7 @@
consumer->setConsumerName(String8("Virtual disp consumer"));
consumer->setDefaultBufferSize(100, 100);
- mGLConsumer = new GLConsumer(consumer, GLConsumer::TEXTURE_EXTERNAL, true, false);
+ mGLConsumer = sp<GLConsumer>::make(consumer, GLConsumer::TEXTURE_EXTERNAL, true, false);
}
sp<IGraphicBufferProducer> mProducer;
@@ -55,7 +55,7 @@
// add another sync since we are deferring the display destruction
t.apply(true);
- sp<Surface> surface = new Surface(mProducer);
+ sp<Surface> surface = sp<Surface>::make(mProducer);
sp<ANativeWindow> window(surface);
ASSERT_EQ(NO_ERROR, native_window_api_connect(window.get(), NATIVE_WINDOW_API_EGL));
diff --git a/services/surfaceflinger/tests/WindowInfosListener_test.cpp b/services/surfaceflinger/tests/WindowInfosListener_test.cpp
index bb52245..53c3c39 100644
--- a/services/surfaceflinger/tests/WindowInfosListener_test.cpp
+++ b/services/surfaceflinger/tests/WindowInfosListener_test.cpp
@@ -29,8 +29,8 @@
protected:
void SetUp() override {
seteuid(AID_SYSTEM);
- mClient = new SurfaceComposerClient;
- mWindowInfosListener = new SyncWindowInfosListener();
+ mClient = sp<SurfaceComposerClient>::make();
+ mWindowInfosListener = sp<SyncWindowInfosListener>::make();
mClient->addWindowInfosListener(mWindowInfosListener);
}
@@ -77,7 +77,7 @@
TEST_F(WindowInfosListenerTest, WindowInfoAddedAndRemoved) {
std::string name = "Test Layer";
- sp<IBinder> token = new BBinder();
+ sp<IBinder> token = sp<BBinder>::make();
WindowInfo windowInfo;
windowInfo.name = name;
windowInfo.token = token;
@@ -105,7 +105,7 @@
TEST_F(WindowInfosListenerTest, WindowInfoChanged) {
std::string name = "Test Layer";
- sp<IBinder> token = new BBinder();
+ sp<IBinder> token = sp<BBinder>::make();
WindowInfo windowInfo;
windowInfo.name = name;
windowInfo.token = token;
diff --git a/services/surfaceflinger/tests/fakehwc/FakeComposerClient.cpp b/services/surfaceflinger/tests/fakehwc/FakeComposerClient.cpp
index f824fdf..a5cca35 100644
--- a/services/surfaceflinger/tests/fakehwc/FakeComposerClient.cpp
+++ b/services/surfaceflinger/tests/fakehwc/FakeComposerClient.cpp
@@ -896,7 +896,7 @@
void FakeComposerClient::onSurfaceFlingerStart() {
mSurfaceComposer = nullptr;
do {
- mSurfaceComposer = new android::SurfaceComposerClient;
+ mSurfaceComposer = android::sp<android::SurfaceComposerClient>::make();
android::status_t initResult = mSurfaceComposer->initCheck();
if (initResult != android::NO_ERROR) {
ALOGD("Init result: %d", initResult);
diff --git a/services/surfaceflinger/tests/fakehwc/SFFakeHwc_test.cpp b/services/surfaceflinger/tests/fakehwc/SFFakeHwc_test.cpp
index 00845d7..1d3401a 100644
--- a/services/surfaceflinger/tests/fakehwc/SFFakeHwc_test.cpp
+++ b/services/surfaceflinger/tests/fakehwc/SFFakeHwc_test.cpp
@@ -220,8 +220,8 @@
mFakeComposerClient = new FakeComposerClient();
mFakeComposerClient->setMockHal(mMockComposer.get());
- sp<V2_4::hal::ComposerClient> client = new V2_4::hal::ComposerClient(mFakeComposerClient);
- mFakeService = new FakeComposerService(client);
+ auto client = sp<V2_4::hal::ComposerClient>::make(mFakeComposerClient);
+ mFakeService = sp<FakeComposerService>::make(client);
ASSERT_EQ(android::OK, mFakeService->registerAsService("mock"));
android::hardware::ProcessState::self()->startThreadPool();
@@ -242,13 +242,13 @@
// Fake composer wants to enable VSync injection
mFakeComposerClient->onSurfaceFlingerStart();
- mComposerClient = new SurfaceComposerClient;
+ mComposerClient = sp<SurfaceComposerClient>::make();
ASSERT_EQ(NO_ERROR, mComposerClient->initCheck());
mReceiver.reset(
new DisplayEventReceiver(gui::ISurfaceComposer::VsyncSource::eVsyncSourceApp,
gui::ISurfaceComposer::EventRegistration::modeChanged));
- mLooper = new Looper(false);
+ mLooper = sp<Looper>::make(false);
mLooper->addFd(mReceiver->getFd(), 0, ALOOPER_EVENT_INPUT, processDisplayEvents, this);
}
@@ -1143,8 +1143,8 @@
// TODO: See TODO comment at DisplayTest::SetUp for background on
// the lifetime of the FakeComposerClient.
sFakeComposer = new FakeComposerClient;
- sp<V2_4::hal::ComposerClient> client = new V2_4::hal::ComposerClient(sFakeComposer);
- sp<V2_1::IComposer> fakeService = new FakeComposerService(client);
+ auto client = sp<V2_4::hal::ComposerClient>::make(sFakeComposer);
+ sp<V2_1::IComposer> fakeService = sp<FakeComposerService>::make(client);
(void)fakeService->registerAsService("mock");
android::hardware::ProcessState::self()->startThreadPool();
@@ -1167,7 +1167,7 @@
void SetUp() override {
ALOGI("TransactionTest::SetUp");
- mComposerClient = new SurfaceComposerClient;
+ mComposerClient = sp<SurfaceComposerClient>::make();
ASSERT_EQ(NO_ERROR, mComposerClient->initCheck());
ALOGI("TransactionTest::SetUp - display");
diff --git a/services/surfaceflinger/tests/unittests/AidlPowerHalWrapperTest.cpp b/services/surfaceflinger/tests/unittests/AidlPowerHalWrapperTest.cpp
index 53de4a6..69d30c4 100644
--- a/services/surfaceflinger/tests/unittests/AidlPowerHalWrapperTest.cpp
+++ b/services/surfaceflinger/tests/unittests/AidlPowerHalWrapperTest.cpp
@@ -57,8 +57,8 @@
};
void AidlPowerHalWrapperTest::SetUp() {
- mMockHal = new NiceMock<MockIPower>();
- mMockSession = new NiceMock<MockIPowerHintSession>();
+ mMockHal = sp<NiceMock<MockIPower>>::make();
+ mMockSession = sp<NiceMock<MockIPowerHintSession>>::make();
ON_CALL(*mMockHal.get(), getHintSessionPreferredRate(_)).WillByDefault(Return(Status::ok()));
mWrapper = std::make_unique<AidlPowerHalWrapper>(mMockHal);
mWrapper->setAllowedActualDeviation(std::chrono::nanoseconds{10ms}.count());
diff --git a/services/surfaceflinger/tests/unittests/CachingTest.cpp b/services/surfaceflinger/tests/unittests/CachingTest.cpp
index 7f203ce..9082a22 100644
--- a/services/surfaceflinger/tests/unittests/CachingTest.cpp
+++ b/services/surfaceflinger/tests/unittests/CachingTest.cpp
@@ -27,13 +27,16 @@
class SlotGenerationTest : public testing::Test {
protected:
sp<HwcSlotGenerator> mHwcSlotGenerator = sp<HwcSlotGenerator>::make();
- sp<GraphicBuffer> mBuffer1{new GraphicBuffer(1, 1, HAL_PIXEL_FORMAT_RGBA_8888, 1, 0)};
- sp<GraphicBuffer> mBuffer2{new GraphicBuffer(1, 1, HAL_PIXEL_FORMAT_RGBA_8888, 1, 0)};
- sp<GraphicBuffer> mBuffer3{new GraphicBuffer(10, 10, HAL_PIXEL_FORMAT_RGBA_8888, 1, 0)};
+ sp<GraphicBuffer> mBuffer1 =
+ sp<GraphicBuffer>::make(1u, 1u, HAL_PIXEL_FORMAT_RGBA_8888, 1u, 0u);
+ sp<GraphicBuffer> mBuffer2 =
+ sp<GraphicBuffer>::make(1u, 1u, HAL_PIXEL_FORMAT_RGBA_8888, 1u, 0u);
+ sp<GraphicBuffer> mBuffer3 =
+ sp<GraphicBuffer>::make(10u, 10u, HAL_PIXEL_FORMAT_RGBA_8888, 1u, 0u);
};
TEST_F(SlotGenerationTest, getHwcCacheSlot_Invalid) {
- sp<IBinder> binder = new BBinder();
+ sp<IBinder> binder = sp<BBinder>::make();
// test getting invalid client_cache_id
client_cache_t id;
int slot = mHwcSlotGenerator->getHwcCacheSlot(id);
@@ -41,7 +44,7 @@
}
TEST_F(SlotGenerationTest, getHwcCacheSlot_Basic) {
- sp<IBinder> binder = new BBinder();
+ sp<IBinder> binder = sp<BBinder>::make();
client_cache_t id;
id.token = binder;
id.id = 0;
@@ -62,7 +65,7 @@
}
TEST_F(SlotGenerationTest, getHwcCacheSlot_Reuse) {
- sp<IBinder> binder = new BBinder();
+ sp<IBinder> binder = sp<BBinder>::make();
std::vector<client_cache_t> ids;
uint32_t cacheId = 0;
// fill up cache
diff --git a/services/surfaceflinger/tests/unittests/CompositionTest.cpp b/services/surfaceflinger/tests/unittests/CompositionTest.cpp
index 9c16e4c..2571e3a 100644
--- a/services/surfaceflinger/tests/unittests/CompositionTest.cpp
+++ b/services/surfaceflinger/tests/unittests/CompositionTest.cpp
@@ -37,7 +37,6 @@
#include <system/window.h>
#include <utils/String8.h>
-#include "ContainerLayer.h"
#include "DisplayRenderArea.h"
#include "EffectLayer.h"
#include "Layer.h"
@@ -130,13 +129,15 @@
EXPECT_CALL(*eventThread, registerDisplayEventConnection(_));
EXPECT_CALL(*eventThread, createEventConnection(_, _))
- .WillOnce(Return(new EventThreadConnection(eventThread.get(), /*callingUid=*/0,
- ResyncCallback())));
+ .WillOnce(Return(sp<EventThreadConnection>::make(eventThread.get(),
+ mock::EventThread::kCallingUid,
+ ResyncCallback())));
EXPECT_CALL(*sfEventThread, registerDisplayEventConnection(_));
EXPECT_CALL(*sfEventThread, createEventConnection(_, _))
- .WillOnce(Return(new EventThreadConnection(sfEventThread.get(), /*callingUid=*/0,
- ResyncCallback())));
+ .WillOnce(Return(sp<EventThreadConnection>::make(sfEventThread.get(),
+ mock::EventThread::kCallingUid,
+ ResyncCallback())));
auto vsyncController = std::make_unique<mock::VsyncController>();
auto vsyncTracker = std::make_unique<mock::VSyncTracker>();
@@ -178,11 +179,11 @@
sp<DisplayDevice> mDisplay;
sp<DisplayDevice> mExternalDisplay;
sp<compositionengine::mock::DisplaySurface> mDisplaySurface =
- new compositionengine::mock::DisplaySurface();
- mock::NativeWindow* mNativeWindow = new mock::NativeWindow();
+ sp<compositionengine::mock::DisplaySurface>::make();
+ sp<mock::NativeWindow> mNativeWindow = sp<mock::NativeWindow>::make();
std::vector<sp<Layer>> mAuxiliaryLayers;
- sp<GraphicBuffer> mBuffer = new GraphicBuffer();
+ sp<GraphicBuffer> mBuffer = sp<GraphicBuffer>::make();
ANativeWindowBuffer* mNativeWindowBuffer = mBuffer->getNativeBuffer();
Hwc2::mock::Composer* mComposer = nullptr;
@@ -316,7 +317,7 @@
.setSecure(Derived::IS_SECURE)
.setPowerMode(Derived::INIT_POWER_MODE)
.inject();
- Mock::VerifyAndClear(test->mNativeWindow);
+ Mock::VerifyAndClear(test->mNativeWindow.get());
test->mDisplay->setLayerStack(LAYER_STACK);
}
@@ -868,7 +869,7 @@
static FlingerLayerType createLayer(CompositionTest* test) {
FlingerLayerType layer = Base::template createLayerWithFactory<EffectLayer>(test, [test]() {
- return new EffectLayer(
+ return sp<EffectLayer>::make(
LayerCreationArgs(test->mFlinger.flinger(), sp<Client>(), "test-layer",
LayerProperties::LAYER_FLAGS, LayerMetadata()));
});
@@ -910,7 +911,7 @@
LayerCreationArgs args(test->mFlinger.flinger(), sp<Client>(), "test-layer",
LayerProperties::LAYER_FLAGS, LayerMetadata());
args.textureName = test->mFlinger.mutableTexturePool().back();
- return new BufferStateLayer(args);
+ return sp<BufferStateLayer>::make(args);
});
LayerProperties::setupLayerState(test, layer);
@@ -952,12 +953,12 @@
template <typename LayerProperties>
struct ContainerLayerVariant : public BaseLayerVariant<LayerProperties> {
using Base = BaseLayerVariant<LayerProperties>;
- using FlingerLayerType = sp<ContainerLayer>;
+ using FlingerLayerType = sp<EffectLayer>;
static FlingerLayerType createLayer(CompositionTest* test) {
LayerCreationArgs args(test->mFlinger.flinger(), sp<Client>(), "test-container-layer",
LayerProperties::LAYER_FLAGS, LayerMetadata());
- FlingerLayerType layer = new ContainerLayer(args);
+ FlingerLayerType layer = sp<EffectLayer>::make(args);
Base::template initLayerDrawingStateAndComputeBounds(test, layer);
return layer;
}
diff --git a/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp b/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp
index f04221c..044c112 100644
--- a/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp
+++ b/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp
@@ -66,13 +66,15 @@
void DisplayTransactionTest::injectMockScheduler() {
EXPECT_CALL(*mEventThread, registerDisplayEventConnection(_));
EXPECT_CALL(*mEventThread, createEventConnection(_, _))
- .WillOnce(Return(
- new EventThreadConnection(mEventThread, /*callingUid=*/0, ResyncCallback())));
+ .WillOnce(Return(sp<EventThreadConnection>::make(mEventThread,
+ mock::EventThread::kCallingUid,
+ ResyncCallback())));
EXPECT_CALL(*mSFEventThread, registerDisplayEventConnection(_));
EXPECT_CALL(*mSFEventThread, createEventConnection(_, _))
- .WillOnce(Return(
- new EventThreadConnection(mSFEventThread, /*callingUid=*/0, ResyncCallback())));
+ .WillOnce(Return(sp<EventThreadConnection>::make(mSFEventThread,
+ mock::EventThread::kCallingUid,
+ ResyncCallback())));
mFlinger.setupScheduler(std::unique_ptr<scheduler::VsyncController>(mVsyncController),
std::unique_ptr<scheduler::VSyncTracker>(mVSyncTracker),
@@ -100,8 +102,8 @@
// This setup is only expected once per test.
ASSERT_TRUE(mConsumer == nullptr && mProducer == nullptr);
- mConsumer = new mock::GraphicBufferConsumer();
- mProducer = new mock::GraphicBufferProducer();
+ mConsumer = sp<mock::GraphicBufferConsumer>::make();
+ mProducer = sp<mock::GraphicBufferProducer>::make();
mFlinger.setCreateBufferQueueFunction([this](auto outProducer, auto outConsumer, bool) {
*outProducer = mProducer;
diff --git a/services/surfaceflinger/tests/unittests/DisplayTransactionTestHelpers.h b/services/surfaceflinger/tests/unittests/DisplayTransactionTestHelpers.h
index f5235ce..0c071d4 100644
--- a/services/surfaceflinger/tests/unittests/DisplayTransactionTestHelpers.h
+++ b/services/surfaceflinger/tests/unittests/DisplayTransactionTestHelpers.h
@@ -111,8 +111,8 @@
// Test instances
TestableSurfaceFlinger mFlinger;
- sp<mock::NativeWindow> mNativeWindow = new mock::NativeWindow();
- sp<GraphicBuffer> mBuffer = new GraphicBuffer();
+ sp<mock::NativeWindow> mNativeWindow = sp<mock::NativeWindow>::make();
+ sp<GraphicBuffer> mBuffer = sp<GraphicBuffer>::make();
Hwc2::mock::PowerAdvisor mPowerAdvisor;
// These mocks are created by the test, but are destroyed by SurfaceFlinger
@@ -120,7 +120,7 @@
// to keep a reference to them for use in setting up call expectations.
renderengine::mock::RenderEngine* mRenderEngine = new renderengine::mock::RenderEngine();
Hwc2::mock::Composer* mComposer = nullptr;
- sp<mock::SurfaceInterceptor> mSurfaceInterceptor = new mock::SurfaceInterceptor;
+ sp<mock::SurfaceInterceptor> mSurfaceInterceptor = sp<mock::SurfaceInterceptor>::make();
mock::VsyncController* mVsyncController = new mock::VsyncController;
mock::VSyncTracker* mVSyncTracker = new mock::VSyncTracker;
diff --git a/services/surfaceflinger/tests/unittests/EventThreadTest.cpp b/services/surfaceflinger/tests/unittests/EventThreadTest.cpp
index 7ee04b0..978afc5 100644
--- a/services/surfaceflinger/tests/unittests/EventThreadTest.cpp
+++ b/services/surfaceflinger/tests/unittests/EventThreadTest.cpp
@@ -193,8 +193,9 @@
ConnectionEventRecorder& recorder, EventRegistrationFlags eventRegistration,
uid_t ownerUid) {
sp<MockEventThreadConnection> connection =
- new MockEventThreadConnection(mThread.get(), ownerUid,
- mResyncCallRecorder.getInvocable(), eventRegistration);
+ sp<MockEventThreadConnection>::make(mThread.get(), ownerUid,
+ mResyncCallRecorder.getInvocable(),
+ eventRegistration);
EXPECT_CALL(*connection, postEvent(_)).WillRepeatedly(Invoke(recorder.getInvocable()));
return connection;
}
diff --git a/services/surfaceflinger/tests/unittests/FpsReporterTest.cpp b/services/surfaceflinger/tests/unittests/FpsReporterTest.cpp
index 3a9b805..0b4e196 100644
--- a/services/surfaceflinger/tests/unittests/FpsReporterTest.cpp
+++ b/services/surfaceflinger/tests/unittests/FpsReporterTest.cpp
@@ -95,8 +95,8 @@
sp<TestableFpsListener> mFpsListener;
fake::FakeClock* mClock = new fake::FakeClock();
- sp<FpsReporter> mFpsReporter =
- new FpsReporter(mFrameTimeline, *(mFlinger.flinger()), std::unique_ptr<Clock>(mClock));
+ sp<FpsReporter> mFpsReporter = sp<FpsReporter>::make(mFrameTimeline, *(mFlinger.flinger()),
+ std::unique_ptr<Clock>(mClock));
};
FpsReporterTest::FpsReporterTest() {
@@ -107,7 +107,7 @@
setupScheduler();
mFlinger.setupComposer(std::make_unique<Hwc2::mock::Composer>());
- mFpsListener = new TestableFpsListener();
+ mFpsListener = sp<TestableFpsListener>::make();
}
FpsReporterTest::~FpsReporterTest() {
@@ -119,7 +119,7 @@
sp<BufferStateLayer> FpsReporterTest::createBufferStateLayer(LayerMetadata metadata = {}) {
sp<Client> client;
LayerCreationArgs args(mFlinger.flinger(), client, "buffer-state-layer", LAYER_FLAGS, metadata);
- return new BufferStateLayer(args);
+ return sp<BufferStateLayer>::make(args);
}
void FpsReporterTest::setupScheduler() {
@@ -128,13 +128,15 @@
EXPECT_CALL(*eventThread, registerDisplayEventConnection(_));
EXPECT_CALL(*eventThread, createEventConnection(_, _))
- .WillOnce(Return(new EventThreadConnection(eventThread.get(), /*callingUid=*/0,
- ResyncCallback())));
+ .WillOnce(Return(sp<EventThreadConnection>::make(eventThread.get(),
+ mock::EventThread::kCallingUid,
+ ResyncCallback())));
EXPECT_CALL(*sfEventThread, registerDisplayEventConnection(_));
EXPECT_CALL(*sfEventThread, createEventConnection(_, _))
- .WillOnce(Return(new EventThreadConnection(sfEventThread.get(), /*callingUid=*/0,
- ResyncCallback())));
+ .WillOnce(Return(sp<EventThreadConnection>::make(sfEventThread.get(),
+ mock::EventThread::kCallingUid,
+ ResyncCallback())));
auto vsyncController = std::make_unique<mock::VsyncController>();
auto vsyncTracker = std::make_unique<mock::VSyncTracker>();
diff --git a/services/surfaceflinger/tests/unittests/GameModeTest.cpp b/services/surfaceflinger/tests/unittests/GameModeTest.cpp
index b79909a..cd857c3 100644
--- a/services/surfaceflinger/tests/unittests/GameModeTest.cpp
+++ b/services/surfaceflinger/tests/unittests/GameModeTest.cpp
@@ -57,7 +57,7 @@
sp<Client> client;
LayerCreationArgs args(mFlinger.flinger(), client, "buffer-state-layer", 0,
LayerMetadata());
- return new BufferStateLayer(args);
+ return sp<BufferStateLayer>::make(args);
}
void setupScheduler() {
@@ -66,13 +66,15 @@
EXPECT_CALL(*eventThread, registerDisplayEventConnection(_));
EXPECT_CALL(*eventThread, createEventConnection(_, _))
- .WillOnce(Return(new EventThreadConnection(eventThread.get(), /*callingUid=*/0,
- ResyncCallback())));
+ .WillOnce(Return(sp<EventThreadConnection>::make(eventThread.get(),
+ mock::EventThread::kCallingUid,
+ ResyncCallback())));
EXPECT_CALL(*sfEventThread, registerDisplayEventConnection(_));
EXPECT_CALL(*sfEventThread, createEventConnection(_, _))
- .WillOnce(Return(new EventThreadConnection(sfEventThread.get(), /*callingUid=*/0,
- ResyncCallback())));
+ .WillOnce(Return(sp<EventThreadConnection>::make(sfEventThread.get(),
+ mock::EventThread::kCallingUid,
+ ResyncCallback())));
auto vsyncController = std::make_unique<mock::VsyncController>();
auto vsyncTracker = std::make_unique<mock::VSyncTracker>();
diff --git a/services/surfaceflinger/tests/unittests/LayerTestUtils.cpp b/services/surfaceflinger/tests/unittests/LayerTestUtils.cpp
index 5a2c147..b7a8a93 100644
--- a/services/surfaceflinger/tests/unittests/LayerTestUtils.cpp
+++ b/services/surfaceflinger/tests/unittests/LayerTestUtils.cpp
@@ -29,13 +29,13 @@
sp<Client> client;
LayerCreationArgs args(flinger.flinger(), client, "buffer-state-layer", LAYER_FLAGS,
LayerMetadata());
- return new BufferStateLayer(args);
+ return sp<BufferStateLayer>::make(args);
}
sp<Layer> EffectLayerFactory::createLayer(TestableSurfaceFlinger& flinger) {
sp<Client> client;
LayerCreationArgs args(flinger.flinger(), client, "color-layer", LAYER_FLAGS, LayerMetadata());
- return new EffectLayer(args);
+ return sp<EffectLayer>::make(args);
}
std::string PrintToStringParamName(
@@ -53,13 +53,15 @@
EXPECT_CALL(*eventThread, registerDisplayEventConnection(_));
EXPECT_CALL(*eventThread, createEventConnection(_, _))
- .WillOnce(Return(new EventThreadConnection(eventThread.get(), /*callingUid=*/0,
- ResyncCallback())));
+ .WillOnce(Return(sp<EventThreadConnection>::make(eventThread.get(),
+ mock::EventThread::kCallingUid,
+ ResyncCallback())));
EXPECT_CALL(*sfEventThread, registerDisplayEventConnection(_));
EXPECT_CALL(*sfEventThread, createEventConnection(_, _))
- .WillOnce(Return(new EventThreadConnection(sfEventThread.get(), /*callingUid=*/0,
- ResyncCallback())));
+ .WillOnce(Return(sp<EventThreadConnection>::make(sfEventThread.get(),
+ mock::EventThread::kCallingUid,
+ ResyncCallback())));
auto vsyncController = std::make_unique<mock::VsyncController>();
auto vsyncTracker = std::make_unique<mock::VSyncTracker>();
diff --git a/services/surfaceflinger/tests/unittests/RefreshRateSelectionTest.cpp b/services/surfaceflinger/tests/unittests/RefreshRateSelectionTest.cpp
index 1e6e336..6752a39 100644
--- a/services/surfaceflinger/tests/unittests/RefreshRateSelectionTest.cpp
+++ b/services/surfaceflinger/tests/unittests/RefreshRateSelectionTest.cpp
@@ -93,17 +93,17 @@
sp<Client> client;
LayerCreationArgs args(mFlinger.flinger(), client, "buffer-queue-layer", LAYER_FLAGS,
LayerMetadata());
- return new BufferStateLayer(args);
+ return sp<BufferStateLayer>::make(args);
}
sp<EffectLayer> RefreshRateSelectionTest::createEffectLayer() {
sp<Client> client;
LayerCreationArgs args(mFlinger.flinger(), client, "color-layer", LAYER_FLAGS, LayerMetadata());
- return new EffectLayer(args);
+ return sp<EffectLayer>::make(args);
}
void RefreshRateSelectionTest::setParent(Layer* child, Layer* parent) {
- child->setParent(parent);
+ child->setParent(sp<Layer>::fromExisting(parent));
}
void RefreshRateSelectionTest::commitTransaction(Layer* layer) {
@@ -117,13 +117,15 @@
EXPECT_CALL(*eventThread, registerDisplayEventConnection(_));
EXPECT_CALL(*eventThread, createEventConnection(_, _))
- .WillOnce(Return(new EventThreadConnection(eventThread.get(), /*callingUid=*/0,
- ResyncCallback())));
+ .WillOnce(Return(sp<EventThreadConnection>::make(eventThread.get(),
+ mock::EventThread::kCallingUid,
+ ResyncCallback())));
EXPECT_CALL(*sfEventThread, registerDisplayEventConnection(_));
EXPECT_CALL(*sfEventThread, createEventConnection(_, _))
- .WillOnce(Return(new EventThreadConnection(sfEventThread.get(), /*callingUid=*/0,
- ResyncCallback())));
+ .WillOnce(Return(sp<EventThreadConnection>::make(sfEventThread.get(),
+ mock::EventThread::kCallingUid,
+ ResyncCallback())));
auto vsyncController = std::make_unique<mock::VsyncController>();
auto vsyncTracker = std::make_unique<mock::VSyncTracker>();
diff --git a/services/surfaceflinger/tests/unittests/SchedulerTest.cpp b/services/surfaceflinger/tests/unittests/SchedulerTest.cpp
index 93c809e..53e49eb 100644
--- a/services/surfaceflinger/tests/unittests/SchedulerTest.cpp
+++ b/services/surfaceflinger/tests/unittests/SchedulerTest.cpp
@@ -48,7 +48,8 @@
class MockEventThreadConnection : public android::EventThreadConnection {
public:
explicit MockEventThreadConnection(EventThread* eventThread)
- : EventThreadConnection(eventThread, /*callingUid=*/0, ResyncCallback()) {}
+ : EventThreadConnection(eventThread, /*callingUid*/ static_cast<uid_t>(0),
+ ResyncCallback()) {}
~MockEventThreadConnection() = default;
MOCK_METHOD1(stealReceiveChannel, binder::Status(gui::BitTube* outChannel));
@@ -79,7 +80,7 @@
mEventThread = eventThread.get();
EXPECT_CALL(*mEventThread, registerDisplayEventConnection(_)).WillOnce(Return(0));
- mEventThreadConnection = new MockEventThreadConnection(mEventThread);
+ mEventThreadConnection = sp<MockEventThreadConnection>::make(mEventThread);
// createConnection call to scheduler makes a createEventConnection call to EventThread. Make
// sure that call gets executed and returns an EventThread::Connection object.
diff --git a/services/surfaceflinger/tests/unittests/SetFrameRateTest.cpp b/services/surfaceflinger/tests/unittests/SetFrameRateTest.cpp
index b9a5f36..6ee8174 100644
--- a/services/surfaceflinger/tests/unittests/SetFrameRateTest.cpp
+++ b/services/surfaceflinger/tests/unittests/SetFrameRateTest.cpp
@@ -78,11 +78,11 @@
}
void SetFrameRateTest::addChild(sp<Layer> layer, sp<Layer> child) {
- layer.get()->addChild(child.get());
+ layer->addChild(child);
}
void SetFrameRateTest::removeChild(sp<Layer> layer, sp<Layer> child) {
- layer.get()->removeChild(child.get());
+ layer->removeChild(child);
}
void SetFrameRateTest::commitTransaction() {
diff --git a/services/surfaceflinger/tests/unittests/SurfaceFlinger_DestroyDisplayTest.cpp b/services/surfaceflinger/tests/unittests/SurfaceFlinger_DestroyDisplayTest.cpp
index c7e61c9..40ef949 100644
--- a/services/surfaceflinger/tests/unittests/SurfaceFlinger_DestroyDisplayTest.cpp
+++ b/services/surfaceflinger/tests/unittests/SurfaceFlinger_DestroyDisplayTest.cpp
@@ -65,7 +65,7 @@
// --------------------------------------------------------------------
// Preconditions
- sp<BBinder> displayToken = new BBinder();
+ sp<BBinder> displayToken = sp<BBinder>::make();
// --------------------------------------------------------------------
// Invocation
diff --git a/services/surfaceflinger/tests/unittests/SurfaceFlinger_DisplayModeSwitching.cpp b/services/surfaceflinger/tests/unittests/SurfaceFlinger_DisplayModeSwitching.cpp
index 5872a47..b607b88 100644
--- a/services/surfaceflinger/tests/unittests/SurfaceFlinger_DisplayModeSwitching.cpp
+++ b/services/surfaceflinger/tests/unittests/SurfaceFlinger_DisplayModeSwitching.cpp
@@ -87,13 +87,15 @@
EXPECT_CALL(*eventThread, registerDisplayEventConnection(_));
EXPECT_CALL(*eventThread, createEventConnection(_, _))
- .WillOnce(Return(new EventThreadConnection(eventThread.get(), /*callingUid=*/0,
- ResyncCallback())));
+ .WillOnce(Return(sp<EventThreadConnection>::make(eventThread.get(),
+ mock::EventThread::kCallingUid,
+ ResyncCallback())));
EXPECT_CALL(*sfEventThread, registerDisplayEventConnection(_));
EXPECT_CALL(*sfEventThread, createEventConnection(_, _))
- .WillOnce(Return(new EventThreadConnection(sfEventThread.get(), /*callingUid=*/0,
- ResyncCallback())));
+ .WillOnce(Return(sp<EventThreadConnection>::make(sfEventThread.get(),
+ mock::EventThread::kCallingUid,
+ ResyncCallback())));
auto vsyncController = std::make_unique<mock::VsyncController>();
auto vsyncTracker = std::make_unique<mock::VSyncTracker>();
diff --git a/services/surfaceflinger/tests/unittests/SurfaceFlinger_DisplayTransactionCommitTest.cpp b/services/surfaceflinger/tests/unittests/SurfaceFlinger_DisplayTransactionCommitTest.cpp
index 9ac2907..bc9e801 100644
--- a/services/surfaceflinger/tests/unittests/SurfaceFlinger_DisplayTransactionCommitTest.cpp
+++ b/services/surfaceflinger/tests/unittests/SurfaceFlinger_DisplayTransactionCommitTest.cpp
@@ -408,12 +408,12 @@
// A virtual display was added to the current state, and it has a
// surface(producer)
- sp<BBinder> displayToken = new BBinder();
+ sp<BBinder> displayToken = sp<BBinder>::make();
DisplayDeviceState state;
state.isSecure = static_cast<bool>(Case::Display::SECURE);
- sp<mock::GraphicBufferProducer> surface{new mock::GraphicBufferProducer()};
+ sp<mock::GraphicBufferProducer> surface{sp<mock::GraphicBufferProducer>::make()};
state.surface = surface;
mFlinger.mutableCurrentState().displays.add(displayToken, state);
@@ -479,7 +479,7 @@
// A virtual display was added to the current state, but it does not have a
// surface.
- sp<BBinder> displayToken = new BBinder();
+ sp<BBinder> displayToken = sp<BBinder>::make();
DisplayDeviceState state;
state.isSecure = static_cast<bool>(Case::Display::SECURE);
@@ -656,9 +656,11 @@
// Preconditions
// A display is set up
- auto nativeWindow = new mock::NativeWindow();
- auto displaySurface = new compositionengine::mock::DisplaySurface();
- sp<GraphicBuffer> buf = new GraphicBuffer();
+ auto nativeWindow = sp<mock::NativeWindow>::make();
+ auto displaySurface = sp<compositionengine::mock::DisplaySurface>::make();
+ sp<GraphicBuffer> buf =
+
+ sp<GraphicBuffer>::make();
auto display = Case::Display::makeFakeExistingDisplayInjector(this);
display.setNativeWindow(nativeWindow);
display.setDisplaySurface(displaySurface);
@@ -701,9 +703,9 @@
// Preconditions
// A display is set up
- auto nativeWindow = new mock::NativeWindow();
- auto displaySurface = new compositionengine::mock::DisplaySurface();
- sp<GraphicBuffer> buf = new GraphicBuffer();
+ auto nativeWindow = sp<mock::NativeWindow>::make();
+ auto displaySurface = sp<compositionengine::mock::DisplaySurface>::make();
+ sp<GraphicBuffer> buf = sp<GraphicBuffer>::make();
auto display = Case::Display::makeFakeExistingDisplayInjector(this);
display.setNativeWindow(nativeWindow);
display.setDisplaySurface(displaySurface);
@@ -750,9 +752,9 @@
// Preconditions
// A display is set up
- auto nativeWindow = new mock::NativeWindow();
- auto displaySurface = new compositionengine::mock::DisplaySurface();
- sp<GraphicBuffer> buf = new GraphicBuffer();
+ auto nativeWindow = sp<mock::NativeWindow>::make();
+ auto displaySurface = sp<compositionengine::mock::DisplaySurface>::make();
+ sp<GraphicBuffer> buf = sp<GraphicBuffer>::make();
auto display = Case::Display::makeFakeExistingDisplayInjector(this);
display.setNativeWindow(nativeWindow);
display.setDisplaySurface(displaySurface);
diff --git a/services/surfaceflinger/tests/unittests/SurfaceFlinger_GetDisplayNativePrimariesTest.cpp b/services/surfaceflinger/tests/unittests/SurfaceFlinger_GetDisplayNativePrimariesTest.cpp
index 0171f1b..5951c98 100644
--- a/services/surfaceflinger/tests/unittests/SurfaceFlinger_GetDisplayNativePrimariesTest.cpp
+++ b/services/surfaceflinger/tests/unittests/SurfaceFlinger_GetDisplayNativePrimariesTest.cpp
@@ -95,7 +95,7 @@
}
TEST_F(GetDisplayNativePrimaries, notInternalDisplayToken) {
- sp<BBinder> notInternalDisplayToken = new BBinder();
+ sp<BBinder> notInternalDisplayToken = sp<BBinder>::make();
ui::DisplayPrimaries primaries;
populateDummyDisplayNativePrimaries(primaries);
diff --git a/services/surfaceflinger/tests/unittests/SurfaceFlinger_PowerHintTest.cpp b/services/surfaceflinger/tests/unittests/SurfaceFlinger_PowerHintTest.cpp
index c2d87f2..18e0a1c 100644
--- a/services/surfaceflinger/tests/unittests/SurfaceFlinger_PowerHintTest.cpp
+++ b/services/surfaceflinger/tests/unittests/SurfaceFlinger_PowerHintTest.cpp
@@ -60,8 +60,8 @@
renderengine::mock::RenderEngine* mRenderEngine = new renderengine::mock::RenderEngine();
sp<DisplayDevice> mDisplay;
sp<compositionengine::mock::DisplaySurface> mDisplaySurface =
- new compositionengine::mock::DisplaySurface();
- mock::NativeWindow* mNativeWindow = new mock::NativeWindow();
+ sp<compositionengine::mock::DisplaySurface>::make();
+ sp<mock::NativeWindow> mNativeWindow = sp<mock::NativeWindow>::make();
mock::TimeStats* mTimeStats = new mock::TimeStats();
Hwc2::mock::PowerAdvisor* mPowerAdvisor = nullptr;
Hwc2::mock::Composer* mComposer = nullptr;
@@ -97,6 +97,7 @@
.setNativeWindow(mNativeWindow)
.setPowerMode(hal::PowerMode::ON)
.inject();
+ mFlinger.mutableActiveDisplayToken() = mDisplay->getDisplayToken();
}
void SurfaceFlingerPowerHintTest::setupScheduler() {
@@ -105,13 +106,15 @@
EXPECT_CALL(*eventThread, registerDisplayEventConnection(_));
EXPECT_CALL(*eventThread, createEventConnection(_, _))
- .WillOnce(Return(new EventThreadConnection(eventThread.get(), /*callingUid=*/0,
- ResyncCallback())));
+ .WillOnce(Return(sp<EventThreadConnection>::make(eventThread.get(),
+ mock::EventThread::kCallingUid,
+ ResyncCallback())));
EXPECT_CALL(*sfEventThread, registerDisplayEventConnection(_));
EXPECT_CALL(*sfEventThread, createEventConnection(_, _))
- .WillOnce(Return(new EventThreadConnection(sfEventThread.get(), /*callingUid=*/0,
- ResyncCallback())));
+ .WillOnce(Return(sp<EventThreadConnection>::make(sfEventThread.get(),
+ mock::EventThread::kCallingUid,
+ ResyncCallback())));
auto vsyncController = std::make_unique<mock::VsyncController>();
auto vsyncTracker = std::make_unique<mock::VSyncTracker>();
@@ -148,5 +151,28 @@
mFlinger.commitAndComposite(now, kVsyncId, now + mockVsyncPeriod.count());
}
+TEST_F(SurfaceFlingerPowerHintTest, inactiveOnDisplayDoze) {
+ ON_CALL(*mPowerAdvisor, usePowerHintSession()).WillByDefault(Return(true));
+
+ mDisplay->setPowerMode(hal::PowerMode::DOZE);
+
+ const std::chrono::nanoseconds mockVsyncPeriod = 15ms;
+ EXPECT_CALL(*mPowerAdvisor, setTargetWorkDuration(_)).Times(0);
+
+ const nsecs_t now = systemTime();
+ const std::chrono::nanoseconds mockHwcRunTime = 20ms;
+ EXPECT_CALL(*mDisplaySurface,
+ prepareFrame(compositionengine::DisplaySurface::CompositionType::Hwc))
+ .Times(1);
+ EXPECT_CALL(*mComposer, presentOrValidateDisplay(HWC_DISPLAY, _, _, _, _, _))
+ .WillOnce([mockHwcRunTime] {
+ std::this_thread::sleep_for(mockHwcRunTime);
+ return hardware::graphics::composer::V2_1::Error::NONE;
+ });
+ EXPECT_CALL(*mPowerAdvisor, sendActualWorkDuration()).Times(0);
+ static constexpr bool kVsyncId = 123; // arbitrary
+ mFlinger.commitAndComposite(now, kVsyncId, now + mockVsyncPeriod.count());
+}
+
} // namespace
} // namespace android
diff --git a/services/surfaceflinger/tests/unittests/SurfaceFlinger_SetDisplayStateTest.cpp b/services/surfaceflinger/tests/unittests/SurfaceFlinger_SetDisplayStateTest.cpp
index 7d9e22b..9c7f55b 100644
--- a/services/surfaceflinger/tests/unittests/SurfaceFlinger_SetDisplayStateTest.cpp
+++ b/services/surfaceflinger/tests/unittests/SurfaceFlinger_SetDisplayStateTest.cpp
@@ -34,7 +34,7 @@
// Preconditions
// We have an unknown display token not associated with a known display
- sp<BBinder> displayToken = new BBinder();
+ sp<BBinder> displayToken = sp<BBinder>::make();
// The requested display state references the unknown display.
DisplayState state;
@@ -95,7 +95,7 @@
display.inject();
// There is a surface that can be set.
- sp<mock::GraphicBufferProducer> surface = new mock::GraphicBufferProducer();
+ sp<mock::GraphicBufferProducer> surface = sp<mock::GraphicBufferProducer>::make();
// The current display state has the surface set
display.mutableCurrentDisplayState().surface = surface;
@@ -132,7 +132,7 @@
display.inject();
// There is a surface that can be set.
- sp<mock::GraphicBufferProducer> surface = new mock::GraphicBufferProducer();
+ sp<mock::GraphicBufferProducer> surface = sp<mock::GraphicBufferProducer>::make();
// The current display state does not have a surface
display.mutableCurrentDisplayState().surface = nullptr;
diff --git a/services/surfaceflinger/tests/unittests/SurfaceFlinger_SetupNewDisplayDeviceInternalTest.cpp b/services/surfaceflinger/tests/unittests/SurfaceFlinger_SetupNewDisplayDeviceInternalTest.cpp
index a0e078b..6aeb3fe 100644
--- a/services/surfaceflinger/tests/unittests/SurfaceFlinger_SetupNewDisplayDeviceInternalTest.cpp
+++ b/services/surfaceflinger/tests/unittests/SurfaceFlinger_SetupNewDisplayDeviceInternalTest.cpp
@@ -197,10 +197,10 @@
template <typename Case>
void SetupNewDisplayDeviceInternalTest::setupNewDisplayDeviceInternalTest() {
- const sp<BBinder> displayToken = new BBinder();
+ const sp<BBinder> displayToken = sp<BBinder>::make();
const sp<compositionengine::mock::DisplaySurface> displaySurface =
- new compositionengine::mock::DisplaySurface();
- const sp<mock::GraphicBufferProducer> producer = new mock::GraphicBufferProducer();
+ sp<compositionengine::mock::DisplaySurface>::make();
+ const auto producer = sp<mock::GraphicBufferProducer>::make();
// --------------------------------------------------------------------
// Preconditions
diff --git a/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h b/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h
index 77cefa6..66eb186 100644
--- a/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h
+++ b/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h
@@ -30,7 +30,6 @@
#include <gui/ScreenCaptureResults.h>
#include "BufferStateLayer.h"
-#include "ContainerLayer.h"
#include "DisplayDevice.h"
#include "EffectLayer.h"
#include "FakeVsyncConfiguration.h"
@@ -84,21 +83,21 @@
}
sp<SurfaceInterceptor> createSurfaceInterceptor() override {
- return new android::impl::SurfaceInterceptor();
+ return sp<android::impl::SurfaceInterceptor>::make();
}
sp<StartPropertySetThread> createStartPropertySetThread(bool timestampPropertyValue) override {
- return new StartPropertySetThread(timestampPropertyValue);
+ return sp<StartPropertySetThread>::make(timestampPropertyValue);
}
sp<DisplayDevice> createDisplayDevice(DisplayDeviceCreationArgs& creationArgs) override {
- return new DisplayDevice(creationArgs);
+ return sp<DisplayDevice>::make(creationArgs);
}
sp<GraphicBuffer> createGraphicBuffer(uint32_t width, uint32_t height, PixelFormat format,
uint32_t layerCount, uint64_t usage,
std::string requestorName) override {
- return new GraphicBuffer(width, height, format, layerCount, usage, requestorName);
+ return sp<GraphicBuffer>::make(width, height, format, layerCount, usage, requestorName);
}
void createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
@@ -127,10 +126,6 @@
sp<EffectLayer> createEffectLayer(const LayerCreationArgs&) override { return nullptr; }
- sp<ContainerLayer> createContainerLayer(const LayerCreationArgs&) override {
- return nullptr;
- }
-
std::unique_ptr<FrameTracer> createFrameTracer() override {
return std::make_unique<mock::FrameTracer>();
}
@@ -720,8 +715,8 @@
std::optional<ui::DisplayConnectionType> connectionType,
std::optional<hal::HWDisplayId> hwcDisplayId, bool isPrimary)
: mFlinger(flinger),
- mCreationArgs(flinger.mFlinger.get(), flinger.mFlinger->getHwComposer(),
- mDisplayToken, display),
+ mCreationArgs(flinger.mFlinger, flinger.mFlinger->getHwComposer(), mDisplayToken,
+ display),
mHwcDisplayId(hwcDisplayId) {
mCreationArgs.connectionType = connectionType;
mCreationArgs.isPrimary = isPrimary;
@@ -869,7 +864,7 @@
private:
TestableSurfaceFlinger& mFlinger;
- sp<BBinder> mDisplayToken = new BBinder();
+ sp<BBinder> mDisplayToken = sp<BBinder>::make();
DisplayDeviceCreationArgs mCreationArgs;
const std::optional<hal::HWDisplayId> mHwcDisplayId;
};
diff --git a/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp b/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp
index b2da34e..efb9e0c 100644
--- a/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp
+++ b/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp
@@ -60,13 +60,15 @@
EXPECT_CALL(*eventThread, registerDisplayEventConnection(_));
EXPECT_CALL(*eventThread, createEventConnection(_, _))
- .WillOnce(Return(new EventThreadConnection(eventThread.get(), /*callingUid=*/0,
- ResyncCallback())));
+ .WillOnce(Return(sp<EventThreadConnection>::make(eventThread.get(),
+ mock::EventThread::kCallingUid,
+ ResyncCallback())));
EXPECT_CALL(*sfEventThread, registerDisplayEventConnection(_));
EXPECT_CALL(*sfEventThread, createEventConnection(_, _))
- .WillOnce(Return(new EventThreadConnection(sfEventThread.get(), /*callingUid=*/0,
- ResyncCallback())));
+ .WillOnce(Return(sp<EventThreadConnection>::make(sfEventThread.get(),
+ mock::EventThread::kCallingUid,
+ ResyncCallback())));
EXPECT_CALL(*mVSyncTracker, nextAnticipatedVSyncTimeFrom(_)).WillRepeatedly(Return(0));
EXPECT_CALL(*mVSyncTracker, currentPeriod())
diff --git a/services/surfaceflinger/tests/unittests/TransactionFrameTracerTest.cpp b/services/surfaceflinger/tests/unittests/TransactionFrameTracerTest.cpp
index 28bf8bf..cd64325 100644
--- a/services/surfaceflinger/tests/unittests/TransactionFrameTracerTest.cpp
+++ b/services/surfaceflinger/tests/unittests/TransactionFrameTracerTest.cpp
@@ -60,7 +60,7 @@
sp<Client> client;
LayerCreationArgs args(mFlinger.flinger(), client, "buffer-state-layer", 0,
LayerMetadata());
- return new BufferStateLayer(args);
+ return sp<BufferStateLayer>::make(args);
}
void commitTransaction(Layer* layer) {
@@ -74,13 +74,15 @@
EXPECT_CALL(*eventThread, registerDisplayEventConnection(_));
EXPECT_CALL(*eventThread, createEventConnection(_, _))
- .WillOnce(Return(new EventThreadConnection(eventThread.get(), /*callingUid=*/0,
- ResyncCallback())));
+ .WillOnce(Return(sp<EventThreadConnection>::make(eventThread.get(),
+ mock::EventThread::kCallingUid,
+ ResyncCallback())));
EXPECT_CALL(*sfEventThread, registerDisplayEventConnection(_));
EXPECT_CALL(*sfEventThread, createEventConnection(_, _))
- .WillOnce(Return(new EventThreadConnection(sfEventThread.get(), /*callingUid=*/0,
- ResyncCallback())));
+ .WillOnce(Return(sp<EventThreadConnection>::make(sfEventThread.get(),
+ mock::EventThread::kCallingUid,
+ ResyncCallback())));
auto vsyncController = std::make_unique<mock::VsyncController>();
auto vsyncTracker = std::make_unique<mock::VSyncTracker>();
@@ -101,7 +103,7 @@
void BLASTTransactionSendsFrameTracerEvents() {
sp<BufferStateLayer> layer = createBufferStateLayer();
- sp<Fence> fence(new Fence());
+ sp<Fence> fence(sp<Fence>::make());
int32_t layerId = layer->getSequence();
uint64_t bufferId = 42;
uint64_t frameNumber = 5;
diff --git a/services/surfaceflinger/tests/unittests/TransactionProtoParserTest.cpp b/services/surfaceflinger/tests/unittests/TransactionProtoParserTest.cpp
index 669fa3a..1f011be 100644
--- a/services/surfaceflinger/tests/unittests/TransactionProtoParserTest.cpp
+++ b/services/surfaceflinger/tests/unittests/TransactionProtoParserTest.cpp
@@ -27,8 +27,8 @@
namespace android {
TEST(TransactionProtoParserTest, parse) {
- const sp<IBinder> layerHandle = new BBinder();
- const sp<IBinder> displayHandle = new BBinder();
+ const sp<IBinder> layerHandle = sp<BBinder>::make();
+ const sp<IBinder> displayHandle = sp<BBinder>::make();
TransactionState t1;
t1.originPid = 1;
t1.originUid = 2;
@@ -49,7 +49,7 @@
ComposerState s;
if (i == 1) {
layer.parentSurfaceControlForChild =
- new SurfaceControl(SurfaceComposerClient::getDefault(), layerHandle, 42);
+ sp<SurfaceControl>::make(SurfaceComposerClient::getDefault(), layerHandle, 42);
}
s.state = layer;
t1.states.add(s);
diff --git a/services/surfaceflinger/tests/unittests/TransactionSurfaceFrameTest.cpp b/services/surfaceflinger/tests/unittests/TransactionSurfaceFrameTest.cpp
index e943644..d5823c3 100644
--- a/services/surfaceflinger/tests/unittests/TransactionSurfaceFrameTest.cpp
+++ b/services/surfaceflinger/tests/unittests/TransactionSurfaceFrameTest.cpp
@@ -60,7 +60,7 @@
sp<Client> client;
LayerCreationArgs args(mFlinger.flinger(), client, "buffer-state-layer", 0,
LayerMetadata());
- return new BufferStateLayer(args);
+ return sp<BufferStateLayer>::make(args);
}
void commitTransaction(Layer* layer) {
@@ -74,13 +74,15 @@
EXPECT_CALL(*eventThread, registerDisplayEventConnection(_));
EXPECT_CALL(*eventThread, createEventConnection(_, _))
- .WillOnce(Return(new EventThreadConnection(eventThread.get(), /*callingUid=*/0,
- ResyncCallback())));
+ .WillOnce(Return(sp<EventThreadConnection>::make(eventThread.get(),
+ mock::EventThread::kCallingUid,
+ ResyncCallback())));
EXPECT_CALL(*sfEventThread, registerDisplayEventConnection(_));
EXPECT_CALL(*sfEventThread, createEventConnection(_, _))
- .WillOnce(Return(new EventThreadConnection(sfEventThread.get(), /*callingUid=*/0,
- ResyncCallback())));
+ .WillOnce(Return(sp<EventThreadConnection>::make(sfEventThread.get(),
+ mock::EventThread::kCallingUid,
+ ResyncCallback())));
auto vsyncController = std::make_unique<mock::VsyncController>();
auto vsyncTracker = std::make_unique<mock::VSyncTracker>();
@@ -115,7 +117,7 @@
void PresentedSurfaceFrameForBufferTransaction() {
sp<BufferStateLayer> layer = createBufferStateLayer();
- sp<Fence> fence(new Fence());
+ sp<Fence> fence(sp<Fence>::make());
auto acquireFence = fenceFactory.createFenceTimeForTest(fence);
BufferData bufferData;
bufferData.acquireFence = fence;
@@ -150,7 +152,7 @@
void DroppedSurfaceFrameForBufferTransaction() {
sp<BufferStateLayer> layer = createBufferStateLayer();
- sp<Fence> fence1(new Fence());
+ sp<Fence> fence1(sp<Fence>::make());
auto acquireFence1 = fenceFactory.createFenceTimeForTest(fence1);
BufferData bufferData;
bufferData.acquireFence = fence1;
@@ -170,7 +172,7 @@
ASSERT_NE(nullptr, layer->mDrawingState.bufferSurfaceFrameTX);
const auto droppedSurfaceFrame = layer->mDrawingState.bufferSurfaceFrameTX;
- sp<Fence> fence2(new Fence());
+ sp<Fence> fence2(sp<Fence>::make());
auto acquireFence2 = fenceFactory.createFenceTimeForTest(fence2);
nsecs_t start = systemTime();
bufferData.acquireFence = fence2;
@@ -216,7 +218,7 @@
EXPECT_EQ(1u, layer->mDrawingState.bufferlessSurfaceFramesTX.size());
ASSERT_EQ(nullptr, layer->mDrawingState.bufferSurfaceFrameTX);
- sp<Fence> fence(new Fence());
+ sp<Fence> fence(sp<Fence>::make());
auto acquireFence = fenceFactory.createFenceTimeForTest(fence);
BufferData bufferData;
bufferData.acquireFence = fence;
@@ -248,7 +250,7 @@
void BufferlessSurfaceFrameNotCreatedIfBufferSufaceFrameExists() {
sp<BufferStateLayer> layer = createBufferStateLayer();
- sp<Fence> fence(new Fence());
+ sp<Fence> fence(sp<Fence>::make());
auto acquireFence = fenceFactory.createFenceTimeForTest(fence);
BufferData bufferData;
bufferData.acquireFence = fence;
@@ -291,7 +293,7 @@
ASSERT_EQ(nullptr, layer->mDrawingState.bufferSurfaceFrameTX);
const auto bufferlessSurfaceFrame2 = layer->mDrawingState.bufferlessSurfaceFramesTX[4];
- sp<Fence> fence(new Fence());
+ sp<Fence> fence(sp<Fence>::make());
auto acquireFence = fenceFactory.createFenceTimeForTest(fence);
BufferData bufferData;
bufferData.acquireFence = fence;
@@ -336,7 +338,7 @@
void PendingSurfaceFramesRemovedAfterClassification() {
sp<BufferStateLayer> layer = createBufferStateLayer();
- sp<Fence> fence1(new Fence());
+ sp<Fence> fence1(sp<Fence>::make());
auto acquireFence1 = fenceFactory.createFenceTimeForTest(fence1);
BufferData bufferData;
bufferData.acquireFence = fence1;
@@ -355,7 +357,7 @@
ASSERT_NE(nullptr, layer->mDrawingState.bufferSurfaceFrameTX);
const auto droppedSurfaceFrame = layer->mDrawingState.bufferSurfaceFrameTX;
- sp<Fence> fence2(new Fence());
+ sp<Fence> fence2(sp<Fence>::make());
auto acquireFence2 = fenceFactory.createFenceTimeForTest(fence2);
bufferData.acquireFence = fence2;
bufferData.frameNumber = 1;
@@ -388,7 +390,7 @@
void BufferSurfaceFrame_ReplaceValidTokenBufferWithInvalidTokenBuffer() {
sp<BufferStateLayer> layer = createBufferStateLayer();
- sp<Fence> fence1(new Fence());
+ sp<Fence> fence1(sp<Fence>::make());
auto acquireFence1 = fenceFactory.createFenceTimeForTest(fence1);
BufferData bufferData;
bufferData.acquireFence = fence1;
@@ -408,7 +410,7 @@
ASSERT_NE(nullptr, layer->mDrawingState.bufferSurfaceFrameTX);
const auto droppedSurfaceFrame1 = layer->mDrawingState.bufferSurfaceFrameTX;
- sp<Fence> fence2(new Fence());
+ sp<Fence> fence2(sp<Fence>::make());
auto acquireFence2 = fenceFactory.createFenceTimeForTest(fence2);
auto dropStartTime1 = systemTime();
bufferData.acquireFence = fence2;
@@ -429,7 +431,7 @@
ASSERT_NE(nullptr, layer->mDrawingState.bufferSurfaceFrameTX);
const auto droppedSurfaceFrame2 = layer->mDrawingState.bufferSurfaceFrameTX;
- sp<Fence> fence3(new Fence());
+ sp<Fence> fence3(sp<Fence>::make());
auto acquireFence3 = fenceFactory.createFenceTimeForTest(fence3);
auto dropStartTime2 = systemTime();
bufferData.acquireFence = fence3;
@@ -479,7 +481,7 @@
uint32_t surfaceFramesPendingClassification = 0;
std::vector<std::shared_ptr<frametimeline::SurfaceFrame>> bufferlessSurfaceFrames;
for (int i = 0; i < 10; i += 2) {
- sp<Fence> fence(new Fence());
+ sp<Fence> fence(sp<Fence>::make());
BufferData bufferData;
bufferData.acquireFence = fence;
bufferData.frameNumber = 1;
diff --git a/services/surfaceflinger/tests/unittests/TransactionTracingTest.cpp b/services/surfaceflinger/tests/unittests/TransactionTracingTest.cpp
index 8ec918d..2dbcfbd 100644
--- a/services/surfaceflinger/tests/unittests/TransactionTracingTest.cpp
+++ b/services/surfaceflinger/tests/unittests/TransactionTracingTest.cpp
@@ -101,10 +101,10 @@
void SetUp() override {
// add layers
mTracing.setBufferSize(SMALL_BUFFER_SIZE);
- const sp<IBinder> fakeLayerHandle = new BBinder();
+ const sp<IBinder> fakeLayerHandle = sp<BBinder>::make();
mTracing.onLayerAdded(fakeLayerHandle->localBinder(), mParentLayerId, "parent",
123 /* flags */, -1 /* parentId */);
- const sp<IBinder> fakeChildLayerHandle = new BBinder();
+ const sp<IBinder> fakeChildLayerHandle = sp<BBinder>::make();
mTracing.onLayerAdded(fakeChildLayerHandle->localBinder(), mChildLayerId, "child",
456 /* flags */, mParentLayerId);
@@ -234,10 +234,10 @@
void SetUp() override {
// add layers
mTracing.setBufferSize(SMALL_BUFFER_SIZE);
- const sp<IBinder> fakeLayerHandle = new BBinder();
+ const sp<IBinder> fakeLayerHandle = sp<BBinder>::make();
mTracing.onLayerAdded(fakeLayerHandle->localBinder(), mLayerId, "Test Layer",
123 /* flags */, -1 /* parentId */);
- const sp<IBinder> fakeMirrorLayerHandle = new BBinder();
+ const sp<IBinder> fakeMirrorLayerHandle = sp<BBinder>::make();
mTracing.onMirrorLayerAdded(fakeMirrorLayerHandle->localBinder(), mMirrorLayerId, "Mirror",
mLayerId);
mTracing.onLayerAddedToDrawingState(mLayerId, mVsyncId);
diff --git a/services/surfaceflinger/tests/unittests/TunnelModeEnabledReporterTest.cpp b/services/surfaceflinger/tests/unittests/TunnelModeEnabledReporterTest.cpp
index 15fea9c..45ebb85 100644
--- a/services/surfaceflinger/tests/unittests/TunnelModeEnabledReporterTest.cpp
+++ b/services/surfaceflinger/tests/unittests/TunnelModeEnabledReporterTest.cpp
@@ -99,7 +99,7 @@
LayerMetadata metadata = {}) {
sp<Client> client;
LayerCreationArgs args(mFlinger.flinger(), client, "buffer-state-layer", LAYER_FLAGS, metadata);
- return new BufferStateLayer(args);
+ return sp<BufferStateLayer>::make(args);
}
void TunnelModeEnabledReporterTest::setupScheduler() {
@@ -108,13 +108,15 @@
EXPECT_CALL(*eventThread, registerDisplayEventConnection(_));
EXPECT_CALL(*eventThread, createEventConnection(_, _))
- .WillOnce(Return(new EventThreadConnection(eventThread.get(), /*callingUid=*/0,
- ResyncCallback())));
+ .WillOnce(Return(sp<EventThreadConnection>::make(eventThread.get(),
+ mock::EventThread::kCallingUid,
+ ResyncCallback())));
EXPECT_CALL(*sfEventThread, registerDisplayEventConnection(_));
EXPECT_CALL(*sfEventThread, createEventConnection(_, _))
- .WillOnce(Return(new EventThreadConnection(sfEventThread.get(), /*callingUid=*/0,
- ResyncCallback())));
+ .WillOnce(Return(sp<EventThreadConnection>::make(sfEventThread.get(),
+ mock::EventThread::kCallingUid,
+ ResyncCallback())));
auto vsyncController = std::make_unique<mock::VsyncController>();
auto vsyncTracker = std::make_unique<mock::VSyncTracker>();
diff --git a/services/surfaceflinger/tests/unittests/VSyncReactorTest.cpp b/services/surfaceflinger/tests/unittests/VSyncReactorTest.cpp
index 30a3f9a..a35ff96 100644
--- a/services/surfaceflinger/tests/unittests/VSyncReactorTest.cpp
+++ b/services/surfaceflinger/tests/unittests/VSyncReactorTest.cpp
@@ -77,12 +77,12 @@
};
std::shared_ptr<android::FenceTime> generateInvalidFence() {
- sp<Fence> fence = new Fence();
+ sp<Fence> fence = sp<Fence>::make();
return std::make_shared<android::FenceTime>(fence);
}
std::shared_ptr<android::FenceTime> generatePendingFence() {
- sp<Fence> fence = new Fence(dup(fileno(tmpfile())));
+ sp<Fence> fence = sp<Fence>::make(dup(fileno(tmpfile())));
return std::make_shared<android::FenceTime>(fence);
}
@@ -92,7 +92,7 @@
}
std::shared_ptr<android::FenceTime> generateSignalledFenceWithTime(nsecs_t time) {
- sp<Fence> fence = new Fence(dup(fileno(tmpfile())));
+ sp<Fence> fence = sp<Fence>::make(dup(fileno(tmpfile())));
std::shared_ptr<android::FenceTime> ft = std::make_shared<android::FenceTime>(fence);
signalFenceWithTime(ft, time);
return ft;
diff --git a/services/surfaceflinger/tests/unittests/mock/MockEventThread.h b/services/surfaceflinger/tests/unittests/mock/MockEventThread.h
index d30dc42..ded6806 100644
--- a/services/surfaceflinger/tests/unittests/mock/MockEventThread.h
+++ b/services/surfaceflinger/tests/unittests/mock/MockEventThread.h
@@ -24,6 +24,8 @@
class EventThread : public android::EventThread {
public:
+ static constexpr auto kCallingUid = static_cast<uid_t>(0);
+
EventThread();
~EventThread() override;
diff --git a/services/surfaceflinger/tests/utils/ScreenshotUtils.h b/services/surfaceflinger/tests/utils/ScreenshotUtils.h
index 6ada549..cb7040a 100644
--- a/services/surfaceflinger/tests/utils/ScreenshotUtils.h
+++ b/services/surfaceflinger/tests/utils/ScreenshotUtils.h
@@ -39,7 +39,7 @@
SurfaceComposerClient::Transaction().apply(true);
captureArgs.dataspace = ui::Dataspace::V0_SRGB;
- const sp<SyncScreenCaptureListener> captureListener = new SyncScreenCaptureListener();
+ const sp<SyncScreenCaptureListener> captureListener = sp<SyncScreenCaptureListener>::make();
binder::Status status = sf->captureDisplay(captureArgs, captureListener);
status_t err = statusTFromBinderStatus(status);
if (err != NO_ERROR) {
@@ -73,7 +73,7 @@
SurfaceComposerClient::Transaction().apply(true);
captureArgs.dataspace = ui::Dataspace::V0_SRGB;
- const sp<SyncScreenCaptureListener> captureListener = new SyncScreenCaptureListener();
+ const sp<SyncScreenCaptureListener> captureListener = sp<SyncScreenCaptureListener>::make();
binder::Status status = sf->captureLayers(captureArgs, captureListener);
status_t err = statusTFromBinderStatus(status);
if (err != NO_ERROR) {
diff --git a/services/surfaceflinger/tests/vsync/vsync.cpp b/services/surfaceflinger/tests/vsync/vsync.cpp
index 667dfb9..8b4a6be 100644
--- a/services/surfaceflinger/tests/vsync/vsync.cpp
+++ b/services/surfaceflinger/tests/vsync/vsync.cpp
@@ -18,7 +18,13 @@
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wconversion"
+// This file is included by modules that have host support but android/looper.h is not supported
+// on host. __REMOVED_IN needs to be defined in order for android/looper.h to be compiled.
+#ifndef __BIONIC__
+#define __REMOVED_IN(x) __attribute__((deprecated))
+#endif
#include <android/looper.h>
+
#include <gui/DisplayEventReceiver.h>
#include <utils/Looper.h>
@@ -55,8 +61,7 @@
{
DisplayEventReceiver myDisplayEvent;
-
- sp<Looper> loop = new Looper(false);
+ sp<Looper> loop = sp<Looper>::make(false);
loop->addFd(myDisplayEvent.getFd(), 0, ALOOPER_EVENT_INPUT, receiver,
&myDisplayEvent);