Fuzz InputDispatcher

Initial version of a fuzzer for InputDispatcher.

The goal is to reproduce crashes that are triggered by the fatal logs,
mainly around:
1) mismatching downtime / eventTimes
2) unexpected hover events

Currently, the fuzzer runs without hitting those targets.
However, it hits an ODR due to rect so currently it has to run without
checking for ODRs.

It also currently hits an out of memory issue after a short run, finding
a problem in
AStatsManager_setPullAtomCallback packages/modules/StatsD/lib/libstatspull/stats_pull_atom_callback.cpp:397:46

Bug: 281806933
Test: FUZZER=inputflinger_input_dispatcher_fuzzer; m $FUZZER && ASAN_OPTIONS=detect_odr_violation=0 $ANDROID_HOST_OUT/fuzz/x86_64/$FUZZER/$FUZZER
Test: atest inputflinger_benchmarks
Change-Id: I465ea11520fc9cc21886646c0ecf20dc529b2698
diff --git a/services/inputflinger/tests/fuzzers/Android.bp b/services/inputflinger/tests/fuzzers/Android.bp
index 9313a89..8a4f6f0 100644
--- a/services/inputflinger/tests/fuzzers/Android.bp
+++ b/services/inputflinger/tests/fuzzers/Android.bp
@@ -167,3 +167,17 @@
         "LatencyTrackerFuzzer.cpp",
     ],
 }
+
+cc_fuzz {
+    name: "inputflinger_input_dispatcher_fuzzer",
+    defaults: [
+        "inputflinger_fuzz_defaults",
+        "libinputdispatcher_defaults",
+    ],
+    shared_libs: [
+        "libinputreporter",
+    ],
+    srcs: [
+        "InputDispatcherFuzzer.cpp",
+    ],
+}
diff --git a/services/inputflinger/tests/fuzzers/FuzzedInputStream.h b/services/inputflinger/tests/fuzzers/FuzzedInputStream.h
new file mode 100644
index 0000000..885820f
--- /dev/null
+++ b/services/inputflinger/tests/fuzzers/FuzzedInputStream.h
@@ -0,0 +1,204 @@
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <fuzzer/FuzzedDataProvider.h>
+
+namespace android {
+
+namespace {
+static constexpr int32_t MAX_RANDOM_POINTERS = 4;
+static constexpr int32_t MAX_RANDOM_DEVICES = 4;
+} // namespace
+
+int getFuzzedMotionAction(FuzzedDataProvider& fdp) {
+    int actionMasked = fdp.PickValueInArray<int>({
+            AMOTION_EVENT_ACTION_DOWN, AMOTION_EVENT_ACTION_UP, AMOTION_EVENT_ACTION_MOVE,
+            AMOTION_EVENT_ACTION_HOVER_ENTER, AMOTION_EVENT_ACTION_HOVER_MOVE,
+            AMOTION_EVENT_ACTION_HOVER_EXIT, AMOTION_EVENT_ACTION_CANCEL,
+            // do not inject AMOTION_EVENT_ACTION_OUTSIDE,
+            AMOTION_EVENT_ACTION_SCROLL, AMOTION_EVENT_ACTION_POINTER_DOWN,
+            AMOTION_EVENT_ACTION_POINTER_UP,
+            // do not send buttons until verifier supports them
+            // AMOTION_EVENT_ACTION_BUTTON_PRESS,
+            // AMOTION_EVENT_ACTION_BUTTON_RELEASE,
+    });
+    switch (actionMasked) {
+        case AMOTION_EVENT_ACTION_POINTER_DOWN:
+        case AMOTION_EVENT_ACTION_POINTER_UP: {
+            const int32_t index = fdp.ConsumeIntegralInRange(0, MAX_RANDOM_POINTERS - 1);
+            const int32_t action =
+                    actionMasked | (index << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
+            return action;
+        }
+        default:
+            return actionMasked;
+    }
+}
+
+/**
+ * For now, focus on the 3 main sources.
+ */
+int getFuzzedSource(FuzzedDataProvider& fdp) {
+    return fdp.PickValueInArray<int>({
+            // AINPUT_SOURCE_UNKNOWN,
+            // AINPUT_SOURCE_KEYBOARD,
+            // AINPUT_SOURCE_DPAD,
+            // AINPUT_SOURCE_GAMEPAD,
+            AINPUT_SOURCE_TOUCHSCREEN, AINPUT_SOURCE_MOUSE, AINPUT_SOURCE_STYLUS,
+            // AINPUT_SOURCE_BLUETOOTH_STYLUS,
+            // AINPUT_SOURCE_TRACKBALL,
+            // AINPUT_SOURCE_MOUSE_RELATIVE,
+            // AINPUT_SOURCE_TOUCHPAD,
+            // AINPUT_SOURCE_TOUCH_NAVIGATION,
+            // AINPUT_SOURCE_JOYSTICK,
+            // AINPUT_SOURCE_HDMI,
+            // AINPUT_SOURCE_SENSOR,
+            // AINPUT_SOURCE_ROTARY_ENCODER,
+            // AINPUT_SOURCE_ANY,
+    });
+}
+
+int getFuzzedButtonState(FuzzedDataProvider& fdp) {
+    return fdp.PickValueInArray<int>({
+            0,
+            // AMOTION_EVENT_BUTTON_PRIMARY,
+            // AMOTION_EVENT_BUTTON_SECONDARY,
+            // AMOTION_EVENT_BUTTON_TERTIARY,
+            // AMOTION_EVENT_BUTTON_BACK,
+            // AMOTION_EVENT_BUTTON_FORWARD,
+            // AMOTION_EVENT_BUTTON_STYLUS_PRIMARY,
+            // AMOTION_EVENT_BUTTON_STYLUS_SECONDARY,
+    });
+}
+
+int32_t getFuzzedFlags(FuzzedDataProvider& fdp, int32_t action) {
+    constexpr std::array<int32_t, 4> FLAGS{
+            AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED,
+            AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED,
+            AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT,
+            AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE,
+    };
+
+    int32_t flags = 0;
+    for (size_t i = 0; i < fdp.ConsumeIntegralInRange(size_t(0), FLAGS.size()); i++) {
+        flags |= fdp.PickValueInArray<int32_t>(FLAGS);
+    }
+    if (action == AMOTION_EVENT_ACTION_CANCEL) {
+        flags |= AMOTION_EVENT_FLAG_CANCELED;
+    }
+    if (MotionEvent::getActionMasked(action) == AMOTION_EVENT_ACTION_POINTER_UP) {
+        if (fdp.ConsumeBool()) {
+            flags |= AMOTION_EVENT_FLAG_CANCELED;
+        }
+    }
+    return flags;
+}
+
+int32_t getFuzzedPointerCount(FuzzedDataProvider& fdp, int32_t action) {
+    switch (MotionEvent::getActionMasked(action)) {
+        case AMOTION_EVENT_ACTION_DOWN:
+        case AMOTION_EVENT_ACTION_UP: {
+            return 1;
+        }
+        case AMOTION_EVENT_ACTION_OUTSIDE:
+        case AMOTION_EVENT_ACTION_CANCEL:
+        case AMOTION_EVENT_ACTION_MOVE:
+            return fdp.ConsumeIntegralInRange<int32_t>(1, MAX_RANDOM_POINTERS);
+        case AMOTION_EVENT_ACTION_HOVER_ENTER:
+        case AMOTION_EVENT_ACTION_HOVER_MOVE:
+        case AMOTION_EVENT_ACTION_HOVER_EXIT:
+            return 1;
+        case AMOTION_EVENT_ACTION_SCROLL:
+            return 1;
+        case AMOTION_EVENT_ACTION_POINTER_DOWN:
+        case AMOTION_EVENT_ACTION_POINTER_UP: {
+            const uint8_t actionIndex = MotionEvent::getActionIndex(action);
+            const int32_t count =
+                    std::max(actionIndex + 1,
+                             fdp.ConsumeIntegralInRange<int32_t>(1, MAX_RANDOM_POINTERS));
+            // Need to have at least 2 pointers
+            return std::max(2, count);
+        }
+        case AMOTION_EVENT_ACTION_BUTTON_PRESS:
+        case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
+            return 1;
+        }
+    }
+    return 1;
+}
+
+ToolType getToolType(int32_t source) {
+    switch (source) {
+        case AINPUT_SOURCE_TOUCHSCREEN:
+            return ToolType::FINGER;
+        case AINPUT_SOURCE_MOUSE:
+            return ToolType::MOUSE;
+        case AINPUT_SOURCE_STYLUS:
+            return ToolType::STYLUS;
+    }
+    return ToolType::UNKNOWN;
+}
+
+inline nsecs_t now() {
+    return systemTime(SYSTEM_TIME_MONOTONIC);
+}
+
+NotifyMotionArgs generateFuzzedMotionArgs(IdGenerator& idGenerator, FuzzedDataProvider& fdp,
+                                          int32_t maxDisplays) {
+    // Create a basic motion event for testing
+    const int32_t source = getFuzzedSource(fdp);
+    const ToolType toolType = getToolType(source);
+    const int32_t action = getFuzzedMotionAction(fdp);
+    const int32_t pointerCount = getFuzzedPointerCount(fdp, action);
+    std::vector<PointerProperties> pointerProperties;
+    std::vector<PointerCoords> pointerCoords;
+    for (int i = 0; i < pointerCount; i++) {
+        PointerProperties properties{};
+        properties.id = i;
+        properties.toolType = toolType;
+        pointerProperties.push_back(properties);
+
+        PointerCoords coords{};
+        coords.setAxisValue(AMOTION_EVENT_AXIS_X, fdp.ConsumeIntegralInRange<int>(-1000, 1000));
+        coords.setAxisValue(AMOTION_EVENT_AXIS_Y, fdp.ConsumeIntegralInRange<int>(-1000, 1000));
+        coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1);
+        pointerCoords.push_back(coords);
+    }
+
+    const int32_t displayId = fdp.ConsumeIntegralInRange<int32_t>(0, maxDisplays - 1);
+    const int32_t deviceId = fdp.ConsumeIntegralInRange<int32_t>(0, MAX_RANDOM_DEVICES - 1);
+
+    // Current time +- 5 seconds
+    const nsecs_t currentTime = now();
+    const nsecs_t downTime =
+            fdp.ConsumeIntegralInRange<nsecs_t>(currentTime - 5E9, currentTime + 5E9);
+    const nsecs_t readTime = downTime;
+    const nsecs_t eventTime = fdp.ConsumeIntegralInRange<nsecs_t>(downTime, downTime + 1E9);
+
+    const float cursorX = fdp.ConsumeIntegralInRange<int>(-10000, 10000);
+    const float cursorY = fdp.ConsumeIntegralInRange<int>(-10000, 10000);
+    return NotifyMotionArgs(idGenerator.nextId(), eventTime, readTime, deviceId, source, displayId,
+                            POLICY_FLAG_PASS_TO_USER, action,
+                            /*actionButton=*/fdp.ConsumeIntegral<int32_t>(),
+                            getFuzzedFlags(fdp, action), AMETA_NONE, getFuzzedButtonState(fdp),
+                            MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount,
+                            pointerProperties.data(), pointerCoords.data(),
+                            /*xPrecision=*/0,
+                            /*yPrecision=*/0, cursorX, cursorY, downTime,
+                            /*videoFrames=*/{});
+}
+
+} // namespace android
diff --git a/services/inputflinger/tests/fuzzers/InputClassifierFuzzer.cpp b/services/inputflinger/tests/fuzzers/InputClassifierFuzzer.cpp
index 3b3ed9b..deb811d 100644
--- a/services/inputflinger/tests/fuzzers/InputClassifierFuzzer.cpp
+++ b/services/inputflinger/tests/fuzzers/InputClassifierFuzzer.cpp
@@ -16,44 +16,16 @@
 
 #include <MapperHelpers.h>
 #include <fuzzer/FuzzedDataProvider.h>
+#include "FuzzedInputStream.h"
 #include "InputCommonConverter.h"
 #include "InputProcessor.h"
 
 namespace android {
 
-static constexpr int32_t MAX_AXES = 64;
+namespace {
 
-// Used by two fuzz operations and a bit lengthy, so pulled out into a function.
-NotifyMotionArgs generateFuzzedMotionArgs(FuzzedDataProvider &fdp) {
-    // Create a basic motion event for testing
-    PointerProperties properties;
-    properties.id = 0;
-    properties.toolType = getFuzzedToolType(fdp);
-    PointerCoords coords;
-    coords.clear();
-    for (int32_t i = 0; i < fdp.ConsumeIntegralInRange<int32_t>(0, MAX_AXES); i++) {
-        coords.setAxisValue(fdp.ConsumeIntegral<int32_t>(), fdp.ConsumeFloatingPoint<float>());
-    }
+constexpr int32_t MAX_RANDOM_DISPLAYS = 4;
 
-    const nsecs_t downTime = 2;
-    const nsecs_t readTime = downTime + fdp.ConsumeIntegralInRange<nsecs_t>(0, 1E8);
-    NotifyMotionArgs motionArgs(/*sequenceNum=*/fdp.ConsumeIntegral<uint32_t>(),
-                                /*eventTime=*/downTime, readTime,
-                                /*deviceId=*/fdp.ConsumeIntegral<int32_t>(), AINPUT_SOURCE_ANY,
-                                ADISPLAY_ID_DEFAULT,
-                                /*policyFlags=*/fdp.ConsumeIntegral<uint32_t>(),
-                                AMOTION_EVENT_ACTION_DOWN,
-                                /*actionButton=*/fdp.ConsumeIntegral<int32_t>(),
-                                /*flags=*/fdp.ConsumeIntegral<int32_t>(), AMETA_NONE,
-                                /*buttonState=*/fdp.ConsumeIntegral<int32_t>(),
-                                MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
-                                /*pointerCount=*/1, &properties, &coords,
-                                /*xPrecision=*/fdp.ConsumeFloatingPoint<float>(),
-                                /*yPrecision=*/fdp.ConsumeFloatingPoint<float>(),
-                                AMOTION_EVENT_INVALID_CURSOR_POSITION,
-                                AMOTION_EVENT_INVALID_CURSOR_POSITION, downTime,
-                                /*videoFrames=*/{});
-    return motionArgs;
 }
 
 extern "C" int LLVMFuzzerTestOneInput(uint8_t *data, size_t size) {
@@ -62,6 +34,7 @@
     std::unique_ptr<FuzzInputListener> mFuzzListener = std::make_unique<FuzzInputListener>();
     std::unique_ptr<InputProcessorInterface> mClassifier =
             std::make_unique<InputProcessor>(*mFuzzListener);
+    IdGenerator idGenerator(IdGenerator::Source::OTHER);
 
     while (fdp.remaining_bytes() > 0) {
         fdp.PickValueInArray<std::function<void()>>({
@@ -90,7 +63,8 @@
                 },
                 [&]() -> void {
                     // SendToNextStage_NotifyMotionArgs
-                    mClassifier->notifyMotion(generateFuzzedMotionArgs(fdp));
+                    mClassifier->notifyMotion(
+                            generateFuzzedMotionArgs(idGenerator, fdp, MAX_RANDOM_DISPLAYS));
                 },
                 [&]() -> void {
                     // SendToNextStage_NotifySwitchArgs
@@ -108,7 +82,8 @@
                 },
                 [&]() -> void {
                     // InputClassifierConverterTest
-                    const NotifyMotionArgs motionArgs = generateFuzzedMotionArgs(fdp);
+                    const NotifyMotionArgs motionArgs =
+                            generateFuzzedMotionArgs(idGenerator, fdp, MAX_RANDOM_DISPLAYS);
                     aidl::android::hardware::input::common::MotionEvent motionEvent =
                             notifyMotionArgsToHalMotionEvent(motionArgs);
                 },
diff --git a/services/inputflinger/tests/fuzzers/InputDispatcherFuzzer.cpp b/services/inputflinger/tests/fuzzers/InputDispatcherFuzzer.cpp
new file mode 100644
index 0000000..214649c
--- /dev/null
+++ b/services/inputflinger/tests/fuzzers/InputDispatcherFuzzer.cpp
@@ -0,0 +1,175 @@
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <android-base/stringprintf.h>
+#include <fuzzer/FuzzedDataProvider.h>
+#include "../FakeApplicationHandle.h"
+#include "../FakeInputDispatcherPolicy.h"
+#include "../FakeWindowHandle.h"
+#include "FuzzedInputStream.h"
+#include "dispatcher/InputDispatcher.h"
+#include "input/InputVerifier.h"
+
+namespace android {
+
+using android::base::Result;
+using android::gui::WindowInfo;
+
+namespace inputdispatcher {
+
+namespace {
+
+static constexpr int32_t MAX_RANDOM_DISPLAYS = 4;
+static constexpr int32_t MAX_RANDOM_WINDOWS = 4;
+
+/**
+ * Provide a valid motion stream, to make the fuzzer more effective.
+ */
+class NotifyStreamProvider {
+public:
+    NotifyStreamProvider(FuzzedDataProvider& fdp)
+          : mFdp(fdp), mIdGenerator(IdGenerator::Source::OTHER), mVerifier("Fuzz verifier") {}
+
+    std::optional<NotifyMotionArgs> nextMotion() {
+        NotifyMotionArgs args = generateFuzzedMotionArgs(mIdGenerator, mFdp, MAX_RANDOM_DISPLAYS);
+        const Result<void> result =
+                mVerifier.processMovement(args.deviceId, args.source, args.action,
+                                          args.getPointerCount(), args.pointerProperties.data(),
+                                          args.pointerCoords.data(), args.flags);
+        if (result.ok()) {
+            return args;
+        }
+        return {};
+    }
+
+private:
+    FuzzedDataProvider& mFdp;
+
+    IdGenerator mIdGenerator;
+
+    InputVerifier mVerifier;
+};
+
+} // namespace
+
+sp<FakeWindowHandle> generateFuzzedWindow(FuzzedDataProvider& fdp, InputDispatcher& dispatcher,
+                                          int32_t displayId) {
+    static size_t windowNumber = 0;
+    std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
+    std::string windowName = android::base::StringPrintf("Win") + std::to_string(windowNumber++);
+    sp<FakeWindowHandle> window =
+            sp<FakeWindowHandle>::make(application, dispatcher, "Fake", displayId);
+
+    const int32_t left = fdp.ConsumeIntegralInRange<int32_t>(0, 100);
+    const int32_t top = fdp.ConsumeIntegralInRange<int32_t>(0, 100);
+    const int32_t width = fdp.ConsumeIntegralInRange<int32_t>(0, 100);
+    const int32_t height = fdp.ConsumeIntegralInRange<int32_t>(0, 100);
+
+    window->setFrame(Rect(left, top, left + width, top + height));
+    window->setSlippery(fdp.ConsumeBool());
+    window->setDupTouchToWallpaper(fdp.ConsumeBool());
+    window->setTrustedOverlay(fdp.ConsumeBool());
+    return window;
+}
+
+void randomizeWindows(
+        std::unordered_map<int32_t, std::vector<sp<FakeWindowHandle>>>& windowsPerDisplay,
+        FuzzedDataProvider& fdp, InputDispatcher& dispatcher) {
+    const int32_t displayId = fdp.ConsumeIntegralInRange<int32_t>(0, MAX_RANDOM_DISPLAYS - 1);
+    std::vector<sp<FakeWindowHandle>>& windows = windowsPerDisplay[displayId];
+
+    fdp.PickValueInArray<std::function<void()>>({
+            // Add a new window
+            [&]() -> void {
+                if (windows.size() < MAX_RANDOM_WINDOWS) {
+                    windows.push_back(generateFuzzedWindow(fdp, dispatcher, displayId));
+                }
+            },
+            // Remove a window
+            [&]() -> void {
+                if (windows.empty()) {
+                    return;
+                }
+                const int32_t erasedPosition =
+                        fdp.ConsumeIntegralInRange<int32_t>(0, windows.size() - 1);
+
+                windows.erase(windows.begin() + erasedPosition);
+                if (windows.empty()) {
+                    windowsPerDisplay.erase(displayId);
+                }
+            },
+            // Could also clone a window, change flags, reposition, etc...
+    })();
+}
+
+extern "C" int LLVMFuzzerTestOneInput(uint8_t* data, size_t size) {
+    FuzzedDataProvider fdp(data, size);
+    NotifyStreamProvider streamProvider(fdp);
+
+    FakeInputDispatcherPolicy fakePolicy;
+    InputDispatcher dispatcher(fakePolicy);
+    dispatcher.setInputDispatchMode(/*enabled=*/true, /*frozen=*/false);
+    // Start InputDispatcher thread
+    dispatcher.start();
+
+    std::unordered_map<int32_t, std::vector<sp<FakeWindowHandle>>> windowsPerDisplay;
+
+    // Randomly invoke InputDispatcher api's until randomness is exhausted.
+    while (fdp.remaining_bytes() > 0) {
+        fdp.PickValueInArray<std::function<void()>>({
+                [&]() -> void {
+                    std::optional<NotifyMotionArgs> motion = streamProvider.nextMotion();
+                    if (motion) {
+                        dispatcher.notifyMotion(*motion);
+                    }
+                },
+                [&]() -> void {
+                    // Scramble the windows we currently have
+                    randomizeWindows(/*byref*/ windowsPerDisplay, fdp, dispatcher);
+
+                    std::vector<WindowInfo> windowInfos;
+                    for (const auto& [displayId, windows] : windowsPerDisplay) {
+                        for (const sp<FakeWindowHandle>& window : windows) {
+                            windowInfos.emplace_back(*window->getInfo());
+                        }
+                    }
+
+                    dispatcher.onWindowInfosChanged(
+                            {windowInfos, {}, /*vsyncId=*/0, /*timestamp=*/0});
+                },
+                // Consume on all the windows
+                [&]() -> void {
+                    for (const auto& [_, windows] : windowsPerDisplay) {
+                        for (const sp<FakeWindowHandle>& window : windows) {
+                            // To speed up the fuzzing, don't wait for consumption. If there's an
+                            // event pending, this can be consumed on the next call instead.
+                            // We also don't care about whether consumption succeeds here, or what
+                            // kind of event is returned.
+                            window->consume(0ms);
+                        }
+                    }
+                },
+        })();
+    }
+
+    dispatcher.stop();
+
+    return 0;
+}
+
+} // namespace inputdispatcher
+
+} // namespace android
\ No newline at end of file