Merge "Vulkan: remove redundant function definitions in null_driver"
diff --git a/cmds/dumpstate/dumpstate.cpp b/cmds/dumpstate/dumpstate.cpp
index 369c3de..e1181a6 100644
--- a/cmds/dumpstate/dumpstate.cpp
+++ b/cmds/dumpstate/dumpstate.cpp
@@ -253,7 +253,7 @@
         MYLOGE("Failed to retrieve module metadata package name: %s", status.toString8().c_str());
         return 0L;
     }
-    MYLOGD("Module metadata package name: %s", package_name.c_str());
+    MYLOGD("Module metadata package name: %s\n", package_name.c_str());
     int64_t version_code;
     status = package_service->getVersionCodeForPackage(android::String16(package_name.c_str()),
                                                        &version_code);
@@ -876,6 +876,17 @@
         CommandOptions::WithTimeoutInMs(timeout_ms).Build());
 }
 
+static void DoSystemLogcat(time_t since) {
+    char since_str[80];
+    strftime(since_str, sizeof(since_str), "%Y-%m-%d %H:%M:%S.000", localtime(&since));
+
+    unsigned long timeout_ms = logcat_timeout({"main", "system", "crash"});
+    RunCommand("SYSTEM LOG",
+               {"logcat", "-v", "threadtime", "-v", "printable", "-v", "uid", "-d", "*:v", "-T",
+                since_str},
+               CommandOptions::WithTimeoutInMs(timeout_ms).Build());
+}
+
 static void DoLogcat() {
     unsigned long timeout_ms;
     // DumpFile("EVENT LOG TAGS", "/etc/event-log-tags");
@@ -1365,8 +1376,6 @@
         ds.TakeScreenshot();
     }
 
-    DoLogcat();
-
     AddAnrTraceFiles();
 
     // NOTE: tombstones are always added as separate entries in the zip archive
@@ -1523,6 +1532,12 @@
     // keep the system stats as close to its initial state as possible.
     RUN_SLOW_FUNCTION_WITH_CONSENT_CHECK(RunDumpsysCritical);
 
+    // Capture first logcat early on; useful to take a snapshot before dumpstate logs take over the
+    // buffer.
+    DoLogcat();
+    // Capture timestamp after first logcat to use in next logcat
+    time_t logcat_ts = time(nullptr);
+
     /* collect stack traces from Dalvik and native processes (needs root) */
     RUN_SLOW_FUNCTION_WITH_CONSENT_CHECK(ds.DumpTraces, &dump_traces_path);
 
@@ -1569,7 +1584,10 @@
     }
 
     RETURN_IF_USER_DENIED_CONSENT();
-    return dumpstate();
+    Dumpstate::RunStatus status = dumpstate();
+    // Capture logcat since the last time we did it.
+    DoSystemLogcat(logcat_ts);
+    return status;
 }
 
 // This method collects common dumpsys for telephony and wifi
diff --git a/libs/binder/fuzzer/main.cpp b/libs/binder/fuzzer/main.cpp
index 369aa34..929e2c3 100644
--- a/libs/binder/fuzzer/main.cpp
+++ b/libs/binder/fuzzer/main.cpp
@@ -36,22 +36,40 @@
 
     for (size_t i = 0; i < instructions.size() - 1; i += 2) {
         uint8_t a = instructions[i];
+        uint8_t readIdx = a % reads.size();
+
         uint8_t b = instructions[i + 1];
 
-        FUZZ_LOG() << "size: " << p.dataSize() << " avail: " << p.dataAvail()
-                   << " pos: " << p.dataPosition() << " cap: " << p.dataCapacity();
+        FUZZ_LOG() << "Instruction: " << (i / 2) + 1 << "/" << instructions.size() / 2
+                   << " cmd: " << static_cast<size_t>(a) << " (" << static_cast<size_t>(readIdx)
+                   << ") arg: " << static_cast<size_t>(b) << " size: " << p.dataSize()
+                   << " avail: " << p.dataAvail() << " pos: " << p.dataPosition()
+                   << " cap: " << p.dataCapacity();
 
-        reads[a % reads.size()](p, b);
+        reads[readIdx](p, b);
     }
 }
 
 void fuzz(uint8_t options, const std::vector<uint8_t>& input, const std::vector<uint8_t>& instructions) {
-    (void) options;
+    uint8_t parcelType = options & 0x3;
 
-    // although they will do completely different things, might as well fuzz both
-    doFuzz<::android::hardware::Parcel>(HWBINDER_PARCEL_READ_FUNCTIONS, input, instructions);
-    doFuzz<::android::Parcel>(BINDER_PARCEL_READ_FUNCTIONS, input, instructions);
-    doFuzz<NdkParcelAdapter>(BINDER_NDK_PARCEL_READ_FUNCTIONS, input, instructions);
+    switch (parcelType) {
+        case 0x0:
+            doFuzz<::android::hardware::Parcel>(HWBINDER_PARCEL_READ_FUNCTIONS, input,
+                                                instructions);
+            break;
+        case 0x1:
+            doFuzz<::android::Parcel>(BINDER_PARCEL_READ_FUNCTIONS, input, instructions);
+            break;
+        case 0x2:
+            doFuzz<NdkParcelAdapter>(BINDER_NDK_PARCEL_READ_FUNCTIONS, input, instructions);
+            break;
+        case 0x3:
+            /*reserved for future use*/
+            break;
+        default:
+            LOG_ALWAYS_FATAL("unknown parcel type %d", static_cast<int>(parcelType));
+    }
 }
 
 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
diff --git a/libs/binder/fuzzer/util.cpp b/libs/binder/fuzzer/util.cpp
index b1213e9..479f406 100644
--- a/libs/binder/fuzzer/util.cpp
+++ b/libs/binder/fuzzer/util.cpp
@@ -24,13 +24,17 @@
 std::string hexString(const void* bytes, size_t len) {
     if (bytes == nullptr) return "<null>";
 
-    std::ostringstream s;
-    s << std::hex << std::setfill('0');
+    const uint8_t* bytes8 = static_cast<const uint8_t*>(bytes);
+    char chars[] = "0123456789abcdef";
+    std::string result;
+    result.resize(len * 2);
+
     for (size_t i = 0; i < len; i++) {
-        s << std::setw(2) << static_cast<int>(
-            static_cast<const uint8_t*>(bytes)[i]);
+        result[2 * i] = chars[bytes8[i] >> 4];
+        result[2 * i + 1] = chars[bytes8[i] & 0xf];
     }
-    return s.str();
+
+    return result;
 }
 std::string hexString(const std::vector<uint8_t>& bytes) {
     return hexString(bytes.data(), bytes.size());
diff --git a/libs/binder/fuzzer/util.h b/libs/binder/fuzzer/util.h
index 416c3a7..a28cd1e 100644
--- a/libs/binder/fuzzer/util.h
+++ b/libs/binder/fuzzer/util.h
@@ -23,27 +23,34 @@
 #error "Must define FUZZ_LOG_TAG"
 #endif
 
-#define ENABLE_LOG_FUZZ 1
-#define FUZZ_LOG() FuzzLog(FUZZ_LOG_TAG, ENABLE_LOG_FUZZ).log()
+// for local debugging
+#define ENABLE_LOG_FUZZ 0
 
+#define FUZZ_LOG() FuzzLog(FUZZ_LOG_TAG).log()
+
+#if ENABLE_LOG_FUZZ == 1
 class FuzzLog {
 public:
-    FuzzLog(const std::string& tag, bool log) : mTag(tag), mLog(log) {}
-    ~FuzzLog() {
-        if (mLog) {
-            std::cout << mTag << ": " << mOs.str() << std::endl;
-        }
-    }
+    FuzzLog(const char* tag) : mTag(tag) {}
+    ~FuzzLog() { std::cout << mTag << ": " << mOs.str() << std::endl; }
 
-    std::stringstream& log() {
-        return mOs;
-    }
+    std::stringstream& log() { return mOs; }
 
 private:
-    std::string mTag;
-    bool mLog;
+    const char* mTag = nullptr;
     std::stringstream mOs;
 };
+#else
+class FuzzLog {
+public:
+    FuzzLog(const char* /*tag*/) {}
+    template <typename T>
+    FuzzLog& operator<<(const T& /*t*/) {
+        return *this;
+    }
+    FuzzLog& log() { return *this; }
+};
+#endif
 
 std::string hexString(const void* bytes, size_t len);
 std::string hexString(const std::vector<uint8_t>& bytes);
diff --git a/libs/graphicsenv/GraphicsEnv.cpp b/libs/graphicsenv/GraphicsEnv.cpp
index 30f5f73..2859111 100644
--- a/libs/graphicsenv/GraphicsEnv.cpp
+++ b/libs/graphicsenv/GraphicsEnv.cpp
@@ -307,6 +307,13 @@
     }
 }
 
+bool GraphicsEnv::setInjectLayersPrSetDumpable() {
+    if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
+        return false;
+    }
+    return true;
+}
+
 void* GraphicsEnv::loadLibrary(std::string name) {
     const android_dlextinfo dlextinfo = {
             .flags = ANDROID_DLEXT_USE_NAMESPACE,
diff --git a/libs/graphicsenv/include/graphicsenv/GraphicsEnv.h b/libs/graphicsenv/include/graphicsenv/GraphicsEnv.h
index a47f468..83448d4 100644
--- a/libs/graphicsenv/include/graphicsenv/GraphicsEnv.h
+++ b/libs/graphicsenv/include/graphicsenv/GraphicsEnv.h
@@ -68,6 +68,14 @@
     void setDriverLoaded(GpuStatsInfo::Api api, bool isDriverLoaded, int64_t driverLoadingTime);
 
     /*
+     * Api for Vk/GL layer injection.  Presently, drivers enable certain
+     * profiling features when prctl(PR_GET_DUMPABLE) returns true.
+     * Calling this when layer injection metadata is present allows the driver
+     * to enable profiling even when in a non-debuggable app
+     */
+    bool setInjectLayersPrSetDumpable();
+
+    /*
      * Apis for ANGLE
      */
     // Check if the requested app should use ANGLE.
diff --git a/libs/gui/Android.bp b/libs/gui/Android.bp
index da51675..e6d442d 100644
--- a/libs/gui/Android.bp
+++ b/libs/gui/Android.bp
@@ -35,6 +35,7 @@
         ":libgui_bufferqueue_sources",
 
         "BitTube.cpp",
+        "BLASTBufferQueue.cpp",
         "BufferHubConsumer.cpp",
         "BufferHubProducer.cpp",
         "BufferItemConsumer.cpp",
diff --git a/libs/gui/BLASTBufferQueue.cpp b/libs/gui/BLASTBufferQueue.cpp
new file mode 100644
index 0000000..3a369cd
--- /dev/null
+++ b/libs/gui/BLASTBufferQueue.cpp
@@ -0,0 +1,126 @@
+/*
+ * Copyright (C) 2019 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/BLASTBufferQueue.h>
+#include <gui/BufferItemConsumer.h>
+
+#include <chrono>
+
+using namespace std::chrono_literals;
+
+namespace android {
+
+BLASTBufferQueue::BLASTBufferQueue(const sp<SurfaceControl>& surface, int width, int height)
+      : mSurfaceControl(surface), mWidth(width), mHeight(height) {
+    BufferQueue::createBufferQueue(&mProducer, &mConsumer);
+    mBufferItemConsumer =
+            new BufferItemConsumer(mConsumer, AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER, 1, true);
+    mBufferItemConsumer->setName(String8("BLAST Consumer"));
+    mBufferItemConsumer->setFrameAvailableListener(this);
+    mBufferItemConsumer->setBufferFreedListener(this);
+    mBufferItemConsumer->setDefaultBufferSize(mWidth, mHeight);
+    mBufferItemConsumer->setDefaultBufferFormat(PIXEL_FORMAT_RGBA_8888);
+}
+
+void BLASTBufferQueue::update(const sp<SurfaceControl>& surface, int width, int height) {
+    std::unique_lock _lock{mMutex};
+    mSurfaceControl = surface;
+    mWidth = width;
+    mHeight = height;
+    mBufferItemConsumer->setDefaultBufferSize(mWidth, mHeight);
+}
+
+static void transactionCallbackThunk(void* context, nsecs_t latchTime,
+                                     const sp<Fence>& presentFence,
+                                     const std::vector<SurfaceControlStats>& stats) {
+    if (context == nullptr) {
+        return;
+    }
+    BLASTBufferQueue* bq = static_cast<BLASTBufferQueue*>(context);
+    bq->transactionCallback(latchTime, presentFence, stats);
+}
+
+void BLASTBufferQueue::transactionCallback(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
+                                           const std::vector<SurfaceControlStats>& stats) {
+    std::unique_lock _lock{mMutex};
+
+    if (stats.size() > 0 && mNextCallbackBufferItem.mGraphicBuffer != nullptr) {
+        mBufferItemConsumer->releaseBuffer(mNextCallbackBufferItem,
+                                           stats[0].previousReleaseFence
+                                                   ? stats[0].previousReleaseFence
+                                                   : Fence::NO_FENCE);
+        mNextCallbackBufferItem = BufferItem();
+    }
+    mDequeueWaitCV.notify_one();
+    decStrong((void*)transactionCallbackThunk);
+}
+
+void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
+    std::unique_lock _lock{mMutex};
+
+    SurfaceComposerClient::Transaction localTransaction;
+    bool applyTransaction = true;
+    SurfaceComposerClient::Transaction* t = &localTransaction;
+    if (mNextTransaction != nullptr) {
+        t = mNextTransaction;
+        mNextTransaction = nullptr;
+        applyTransaction = false;
+    }
+
+    int status = OK;
+    mNextCallbackBufferItem = mLastSubmittedBufferItem;
+
+    mLastSubmittedBufferItem = BufferItem();
+    status = mBufferItemConsumer->acquireBuffer(&mLastSubmittedBufferItem, -1, false);
+    if (status != OK) {
+        ALOGE("Failed to acquire?");
+    }
+
+    auto buffer = mLastSubmittedBufferItem.mGraphicBuffer;
+
+    if (buffer == nullptr) {
+        ALOGE("Null buffer");
+        return;
+    }
+
+
+    // Ensure BLASTBufferQueue stays alive until we receive the transaction complete callback.
+    incStrong((void*)transactionCallbackThunk);
+
+    t->setBuffer(mSurfaceControl, buffer);
+    t->setAcquireFence(mSurfaceControl,
+                       item.mFence ? new Fence(item.mFence->dup()) : Fence::NO_FENCE);
+    t->addTransactionCompletedCallback(transactionCallbackThunk, static_cast<void*>(this));
+
+    t->setFrame(mSurfaceControl, {0, 0, (int32_t)buffer->getWidth(), (int32_t)buffer->getHeight()});
+    t->setCrop(mSurfaceControl, {0, 0, (int32_t)buffer->getWidth(), (int32_t)buffer->getHeight()});
+
+    if (applyTransaction) {
+        ALOGE("Apply transaction");
+        t->apply();
+
+        if (mNextCallbackBufferItem.mGraphicBuffer != nullptr) {
+            mDequeueWaitCV.wait_for(_lock, 5000ms);
+        }
+    }
+}
+
+void BLASTBufferQueue::setNextTransaction(SurfaceComposerClient::Transaction* t) {
+    std::unique_lock _lock{mMutex};
+    mNextTransaction = t;
+}
+
+} // namespace android
diff --git a/libs/gui/include/gui/BLASTBufferQueue.h b/libs/gui/include/gui/BLASTBufferQueue.h
new file mode 100644
index 0000000..139c3f9
--- /dev/null
+++ b/libs/gui/include/gui/BLASTBufferQueue.h
@@ -0,0 +1,92 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#ifndef ANDROID_GUI_BLAST_BUFFER_QUEUE_H
+#define ANDROID_GUI_BLAST_BUFFER_QUEUE_H
+
+#include <gui/IGraphicBufferProducer.h>
+#include <gui/BufferItemConsumer.h>
+#include <gui/BufferItem.h>
+#include <gui/SurfaceComposerClient.h>
+
+#include <utils/Condition.h>
+#include <utils/Mutex.h>
+#include <utils/RefBase.h>
+
+#include <system/window.h>
+
+namespace android {
+
+class BufferItemConsumer;
+
+class BLASTBufferQueue
+    : public ConsumerBase::FrameAvailableListener, public BufferItemConsumer::BufferFreedListener
+{
+public:
+    BLASTBufferQueue(const sp<SurfaceControl>& surface, int width, int height);
+    sp<IGraphicBufferProducer> getIGraphicBufferProducer() const {
+        return mProducer;
+    }
+
+    void onBufferFreed(const wp<GraphicBuffer>&/* graphicBuffer*/) override { /* TODO */ }
+    void onFrameReplaced(const BufferItem& item) override {onFrameAvailable(item);}
+    void onFrameAvailable(const BufferItem& item) override;
+
+    void transactionCallback(nsecs_t latchTime, const sp<Fence>& presentFence,
+            const std::vector<SurfaceControlStats>& stats);
+    void setNextTransaction(SurfaceComposerClient::Transaction *t);
+
+    void update(const sp<SurfaceControl>& surface, int width, int height);
+    
+
+    virtual ~BLASTBufferQueue() = default;
+
+private:
+    // can't be copied
+    BLASTBufferQueue& operator = (const BLASTBufferQueue& rhs);
+    BLASTBufferQueue(const BLASTBufferQueue& rhs);
+
+    sp<SurfaceControl> mSurfaceControl;
+    
+    mutable std::mutex mMutex;
+
+    static const int MAX_BUFFERS = 2;
+    struct BufferInfo {
+        sp<GraphicBuffer> buffer;
+        int fence;
+    };
+    
+    int mDequeuedBuffers = 0;
+
+    int mWidth;
+    int mHeight;
+
+    BufferItem mLastSubmittedBufferItem;
+    BufferItem mNextCallbackBufferItem;
+    sp<Fence> mLastFence;
+
+    std::condition_variable mDequeueWaitCV;
+
+    sp<IGraphicBufferConsumer> mConsumer;
+    sp<IGraphicBufferProducer> mProducer;
+    sp<BufferItemConsumer> mBufferItemConsumer;
+
+    SurfaceComposerClient::Transaction* mNextTransaction = nullptr;
+};
+
+} // namespace android
+
+#endif  // ANDROID_GUI_SURFACE_H
diff --git a/opengl/tests/gl_perf/fill_common.cpp b/opengl/tests/gl_perf/fill_common.cpp
index fefedc0..613f1c6 100644
--- a/opengl/tests/gl_perf/fill_common.cpp
+++ b/opengl/tests/gl_perf/fill_common.cpp
@@ -191,10 +191,10 @@
 static void randUniform(int pgm, const char *var) {
     GLint loc = glGetUniformLocation(pgm, var);
     if (loc >= 0) {
-        float x = ((float)rand()) / RAND_MAX;
-        float y = ((float)rand()) / RAND_MAX;
-        float z = ((float)rand()) / RAND_MAX;
-        float w = ((float)rand()) / RAND_MAX;
+        float x = ((float)rand()) / (float)RAND_MAX;
+        float y = ((float)rand()) / (float)RAND_MAX;
+        float z = ((float)rand()) / (float)RAND_MAX;
+        float w = ((float)rand()) / (float)RAND_MAX;
         glUniform4f(loc, x, y, z, w);
     }
 }
diff --git a/services/inputflinger/dispatcher/TouchState.cpp b/services/inputflinger/dispatcher/TouchState.cpp
index 18848a0..2baceba 100644
--- a/services/inputflinger/dispatcher/TouchState.cpp
+++ b/services/inputflinger/dispatcher/TouchState.cpp
@@ -93,15 +93,6 @@
                            std::end(newMonitors));
 }
 
-void TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
-    for (size_t i = 0; i < windows.size(); i++) {
-        if (windows[i].windowHandle == windowHandle) {
-            windows.erase(windows.begin() + i);
-            return;
-        }
-    }
-}
-
 void TouchState::removeWindowByToken(const sp<IBinder>& token) {
     for (size_t i = 0; i < windows.size(); i++) {
         if (windows[i].windowHandle->getToken() == token) {
diff --git a/services/inputflinger/dispatcher/TouchState.h b/services/inputflinger/dispatcher/TouchState.h
index 3e0e0eb..623c6a8 100644
--- a/services/inputflinger/dispatcher/TouchState.h
+++ b/services/inputflinger/dispatcher/TouchState.h
@@ -49,7 +49,6 @@
                            BitSet32 pointerIds);
     void addPortalWindow(const sp<android::InputWindowHandle>& windowHandle);
     void addGestureMonitors(const std::vector<TouchedMonitor>& monitors);
-    void removeWindow(const sp<android::InputWindowHandle>& windowHandle);
     void removeWindowByToken(const sp<IBinder>& token);
     void filterNonAsIsTouchWindows();
     void filterNonMonitors();