Checksum for GL pipe communication

This is the guest side implementation for cl go/oag/c/207292.

It initializes checksum whenever a renderControl is created. Each
HostConnection owns a checksum structure.

The list contains mostly auto-generated code by emugen.

Change-Id: I5f7bb9ec8a0cea82f3687f8a15839081651fd841
diff --git a/shared/OpenglCodecCommon/Android.mk b/shared/OpenglCodecCommon/Android.mk
index 1c0aca5..e91eb6c 100644
--- a/shared/OpenglCodecCommon/Android.mk
+++ b/shared/OpenglCodecCommon/Android.mk
@@ -5,6 +5,7 @@
 
 commonSources := \
         GLClientState.cpp \
+        ChecksumCalculator.cpp \
         GLSharedGroup.cpp \
         glUtils.cpp \
         SocketStream.cpp \
diff --git a/shared/OpenglCodecCommon/ChecksumCalculator.cpp b/shared/OpenglCodecCommon/ChecksumCalculator.cpp
new file mode 100644
index 0000000..6dc0316
--- /dev/null
+++ b/shared/OpenglCodecCommon/ChecksumCalculator.cpp
@@ -0,0 +1,150 @@
+/*
+* Copyright (C) 2016 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 "ChecksumCalculator.h"
+
+#include <string>
+#include <vector>
+#include <string.h>
+
+// Checklist when implementing new protocol:
+// 1. update CHECKSUMHELPER_MAX_VERSION
+// 2. update maxChecksumSize()
+// 3. update checksumByteSize()
+// 4. update addBuffer, writeChecksum, resetChecksum, validate
+
+// change CHECKSUMHELPER_MAX_VERSION when you want to update the protocol version
+#define CHECKSUMHELPER_MAX_VERSION 1
+
+// checksum buffer size
+// Please add a new checksum buffer size when implementing a new protocol,
+// as well as modifying the maxChecksumSize function.
+static const size_t kV1ChecksumSize = 8;
+
+static constexpr size_t maxChecksumSize() {
+    return 0 > kV1ChecksumSize ? 0 : kV1ChecksumSize;
+}
+
+static const size_t kMaxChecksumSize = maxChecksumSize();
+
+// utility macros to create checksum string at compilation time
+#define CHECKSUMHELPER_VERSION_STR_PREFIX "ANDROID_EMU_CHECKSUM_HELPER_v"
+#define CHECKSUMHELPER_MACRO_TO_STR(x) #x
+#define CHECKSUMHELPER_MACRO_VAL_TO_STR(x) CHECKSUMHELPER_MACRO_TO_STR(x)
+
+static const uint32_t kMaxVersion = CHECKSUMHELPER_MAX_VERSION;
+static const char* kMaxVersionStrPrefix = CHECKSUMHELPER_VERSION_STR_PREFIX;
+static const char* kMaxVersionStr = CHECKSUMHELPER_VERSION_STR_PREFIX CHECKSUMHELPER_MACRO_VAL_TO_STR(CHECKSUMHELPER_MAX_VERSION);
+
+#undef CHECKSUMHELPER_MAX_VERSION
+#undef CHECKSUMHELPER_VERSION_STR_PREFIX
+#undef CHECKSUMHELPER_MACRO_TO_STR
+#undef CHECKSUMHELPER_MACRO_VAL_TO_STR
+
+uint32_t ChecksumCalculator::getMaxVersion() {return kMaxVersion;}
+const char* ChecksumCalculator::getMaxVersionStr() {return kMaxVersionStr;}
+const char* ChecksumCalculator::getMaxVersionStrPrefix() {return kMaxVersionStrPrefix;}
+
+bool ChecksumCalculator::setVersion(uint32_t version) {
+    if (version > kMaxVersion) {  // unsupported version
+        LOG_CHECKSUMHELPER("%s: ChecksumCalculator Set Unsupported version Version %d\n",
+                __FUNCTION__, m_version);
+        return false;
+    }
+    if (m_isEncodingChecksum) { // setVersion is called in the middle of encoding checksums
+        LOG_CHECKSUMHELPER("%s: called between addBuffer and writeChecksum\n",
+                __FUNCTION__);
+        return false;
+    }
+    m_version = version;
+    LOG_CHECKSUMHELPER("%s: ChecksumCalculator Set Version %d\n", __FUNCTION__,
+                m_version);
+    return true;
+}
+
+size_t ChecksumCalculator::checksumByteSize() const {
+    switch (m_version) {
+        case 0:
+            return 0;
+        case 1:
+            return sizeof(uint32_t) + sizeof(m_numWrite);
+        default:
+            return 0;
+    }
+}
+
+void ChecksumCalculator::addBuffer(const void* buf, size_t packetLen) {
+    m_isEncodingChecksum = true;
+    switch (m_version) {
+        case 1:
+            m_v1BufferTotalLength += packetLen;
+            break;
+    }
+}
+
+bool ChecksumCalculator::writeChecksum(void* outputChecksum, size_t outputChecksumLen) {
+    if (outputChecksumLen < checksumByteSize()) return false;
+    char *checksumPtr = (char *)outputChecksum;
+    switch (m_version) {
+        case 1: { // protocol v1 is to reverse the packetLen and write it at the end
+            uint32_t val = computeV1Checksum(NULL, m_v1BufferTotalLength);
+            memcpy(checksumPtr, &val, sizeof(val));
+            memcpy(checksumPtr+sizeof(val), &m_numWrite, sizeof(m_numWrite));
+            break;
+        }
+    }
+    resetChecksum();
+    m_isEncodingChecksum = false;
+    m_numWrite++;
+    return true;
+}
+
+void ChecksumCalculator::resetChecksum() {
+    switch (m_version) {
+        case 1:
+            m_v1BufferTotalLength = 0;
+            break;
+    }
+    m_isEncodingChecksum = false;
+}
+
+bool ChecksumCalculator::validate(const void* buf, size_t bufLen, const void* expectedChecksum) {
+    // buffers for computing the checksum
+    unsigned char sChecksumBuffer[kMaxChecksumSize];
+
+    size_t checksumSize = checksumByteSize();
+    switch (m_version) {
+        case 1: {
+            uint32_t val = computeV1Checksum(buf, bufLen);
+            memcpy(sChecksumBuffer, &val, sizeof(val));
+            memcpy(sChecksumBuffer+sizeof(val), &m_numRead, sizeof(m_numRead));
+            break;
+        }
+    }
+    bool isValid = !memcmp(sChecksumBuffer, expectedChecksum, checksumSize);
+    m_numRead++;
+    return isValid;
+}
+
+uint32_t ChecksumCalculator::computeV1Checksum(const void* buf, size_t bufLen) {
+    uint32_t revLen = bufLen;
+    revLen = (revLen & 0xffff0000) >> 16 | (revLen & 0x0000ffff) << 16;
+    revLen = (revLen & 0xff00ff00) >> 8 | (revLen & 0x00ff00ff) << 8;
+    revLen = (revLen & 0xf0f0f0f0) >> 4 | (revLen & 0x0f0f0f0f) << 4;
+    revLen = (revLen & 0xcccccccc) >> 2 | (revLen & 0x33333333) << 2;
+    revLen = (revLen & 0xaaaaaaaa) >> 1 | (revLen & 0x55555555) << 1;
+    return revLen;
+}
diff --git a/shared/OpenglCodecCommon/ChecksumCalculator.h b/shared/OpenglCodecCommon/ChecksumCalculator.h
new file mode 100644
index 0000000..7884a8d
--- /dev/null
+++ b/shared/OpenglCodecCommon/ChecksumCalculator.h
@@ -0,0 +1,170 @@
+/*
+* Copyright (C) 2016 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 <stdint.h>
+#include <stdlib.h>
+
+// Set TRACE_CHECKSUMHELPER to 1 to debug creation/destruction of GLprotocol
+// instances.
+#define TRACE_CHECKSUMHELPER 0
+
+#if TRACE_CHECKSUMHELPER
+#define LOG_CHECKSUMHELPER(x...) fprintf(stderr, x)
+#else
+#define LOG_CHECKSUMHELPER(x...)
+#endif
+
+// ChecksumCalculator adds checksum as an array of bytes to GL pipe communication, which
+// size depends on the protocol version. Each pipe should use one ChecksumCalculator.
+// It can:
+//      (1) take a list of buffers one by one and compute their checksum string,
+//          in this case the checksum should be as the data in those buffers are
+//          concatenated;
+//      (2) take a buffer and a checksum string, tell if they match;
+//      (3) support different checksum version in future.
+//
+// For backward compatibility, checksum version 0 behaves the same as there is
+// no checksum (i.e., checksumByteSize returns 0, validate always returns true,
+// addBuffer and writeCheckSum does nothing).
+//
+// Notice that to detect package lost, ChecksumCalculator also keeps track of how
+// many times it generates/validates checksums, and might use it as part of the
+// checksum.
+//
+// To evaluate checksums from a list of data buffers buf1, buf2... Please call
+// addBuffer(buf1, buf1len), addBuffer(buf2, buf2len) ... in order.
+// Then allocate a checksum buffer with size checksumByteSize(), and call
+// writeChecksum(checksumBuffer) to write the checksum to the buffer.
+//
+// To calculate if a data buffer match its checksum, please call
+// validate(buf, bufLen, checksumBuffer)
+//
+// The checksum generator and validator must be set to the same version, and
+// the validator must check ALL checksums in the order they are generated,
+// otherwise the validation function will return false.
+//
+// It is allowed to change the checksum version between calculating two
+// checksums. This is designed for backward compatibility reason.
+//
+// Example 1, encoding and decoding:
+//
+// bool testChecksum(void* buf, size_t bufLen) {
+//     // encoding message
+//     ChecksumCalculator encoder;
+//     encoder.setVersion(1);
+//     encoder.addBuffer(buf, bufLen);
+//     std::vector<unsigned char> message(bufLen + checksumByteSize());
+//     memcpy(&message[0], buf, bufLen);
+//     encoder.writeChecksum(&message[0] + bufLen, checksumByteSize());
+//
+//     // decoding message
+//     ChecksumCalculator decoder;
+//     decoder.setVersion(1);
+//     return decoder.validate(&message[0], bufLen, &message[0] + bufLen);
+// }
+// The return value is true.
+//
+// Example 2, decoding will fail if the order of messages is wrong:
+//
+// bool testChecksumOrder(void* buf1, size_t bufLen1,
+//                        void* buf2, size_t bufLen2) {
+//     // encoding messages
+//     ChecksumCalculator encoder;
+//     encoder.setVersion(1);
+//
+//     std::vector<unsigned char> message1(bufLen1 + checksumByteSize());
+//     std::vector<unsigned char> message2(bufLen2 + checksumByteSize());
+//
+//     encoder.addBuffer(buf1, bufLen1);
+//     std::vector<unsigned char> message1(bufLen1 + checksumByteSize());
+//     memcpy(&message1[0], buf1, bufLen1);
+//     encoder.writeChecksum(&message1[0] + bufLen1, checksumByteSize());
+//
+//     encoder.addBuffer(buf2, bufLen2);
+//     std::vector<unsigned char> message2(bufLen2 + checksumByteSize());
+//     memcpy(&message2[0], buf2, bufLen2);
+//     encoder.writeChecksum(&message2[0] + bufLen2, checksumByteSize());
+//
+//     // decoding messages
+//     ChecksumCalculator decoder;
+//     decoder.setVersion(1);
+//     // returns false because the decoding order is not consistent with
+//     // encoding order
+//     if (decoder.validate(&message2[0], bufLen2, &message2[0] + bufLen2) &&
+//          decoder.validate(&message1[0], bufLen1, &message1[0] + bufLen1) ) {
+//          return true;
+//     }
+//     return false;
+// }
+
+class ChecksumCalculator {
+public:
+    // Get and set current checksum version
+    uint32_t getVersion() const { return m_version; }
+    // Call setVersion to set a checksum version. It should be called before
+    // addBuffer(), writeChecksum() and validate(). And it should be called
+    // exact once per rendering thread if both host and guest support checksum.
+    // It won't be called if either host or guest does not support checksum.
+    bool setVersion(uint32_t version);
+
+    // Maximum supported checksum version
+    static uint32_t getMaxVersion();
+    // A version string that looks like "ANDROID_EMU_CHECKSUM_HELPER_v1"
+    // Used multiple times when the guest queries the maximum supported version
+    // from the host.
+    // The library owns the returned pointer. The returned pointer will be
+    // deconstructed when unloading library.
+    static const char* getMaxVersionStr();
+    static const char* getMaxVersionStrPrefix();
+
+    // Size of checksum in the current version
+    size_t checksumByteSize() const;
+
+    // Update the current checksum value from the data
+    // at |buf| of |bufLen| bytes. Once all buffers
+    // have been added, call writeChecksum() to store
+    // the final checksum value and reset its state.
+    void addBuffer(const void* buf, size_t bufLen);
+    // Write the checksum from the list of buffers to outputChecksum
+    // Return false if the buffer is not long enough
+    // Please query buffer size from checksumByteSize()
+    bool writeChecksum(void* outputChecksum, size_t outputChecksumLen);
+    // Restore the states for computing checksums.
+    // Automatically called at the end of writeChecksum.
+    // Can also be used to abandon the current checksum being calculated.
+    // Notes: it doesn't update the internal read / write counter
+    void resetChecksum();
+
+    // Calculate the checksum of a packet (with size specified by packetLen),
+    // and compare it with the checksum encoded in expectedChecksum
+    bool validate(const void* buf, size_t bufLen, const void* expectedChecksum);
+protected:
+    uint32_t m_version = 0;
+    // A temporary state used to compute the total length of a list of buffers,
+    // if addBuffer is called.
+    uint32_t m_numRead = 0;
+    uint32_t m_numWrite = 0;
+    // m_isEncodingChecksum is true when between addBuffer and writeChecksum
+    bool m_isEncodingChecksum = false;
+private:
+    // Compute a 32bit checksum
+    // Used in protocol v1
+    static uint32_t computeV1Checksum(const void* buf, size_t bufLen);
+    // The buffer used in protocol version 1 to compute checksum.
+    uint32_t m_v1BufferTotalLength = 0;
+};