• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 
17 #pragma once
18 
19 #include <stdint.h>
20 #include <stdlib.h>
21 
22 // Set TRACE_CHECKSUMHELPER to 1 to debug creation/destruction of GLprotocol
23 // instances.
24 #define TRACE_CHECKSUMHELPER 0
25 
26 #if TRACE_CHECKSUMHELPER
27 #define LOG_CHECKSUMHELPER(x...) fprintf(stderr, x)
28 #else
29 #define LOG_CHECKSUMHELPER(x...)
30 #endif
31 
32 namespace android { namespace base { class Stream; } }
33 
34 // ChecksumCalculator adds checksum as an array of bytes to GL pipe communication, which
35 // size depends on the protocol version. Each pipe should use one ChecksumCalculator.
36 // It can:
37 //      (1) take a list of buffers one by one and compute their checksum string,
38 //          in this case the checksum should be as the data in those buffers are
39 //          concatenated;
40 //      (2) compute the checksum of the buffer list, then either write them into
41 //          a buffer provided by user, or compare it against a checksum provided
42 //          by user
43 //      (3) support different checksum version in future.
44 //
45 // For backward compatibility, checksum version 0 behaves the same as there is
46 // no checksum (i.e., checksumByteSize returns 0, validate always returns true,
47 // addBuffer and writeCheckSum does nothing).
48 //
49 // Notice that to detect package lost, ChecksumCalculator also keeps track of how
50 // many times it generates/validates checksums, and might use it as part of the
51 // checksum.
52 //
53 // To evaluate checksums from a list of data buffers buf1, buf2... Please call
54 // addBuffer(buf1, buf1len), addBuffer(buf2, buf2len) ... in order.
55 // Then if the checksum needs to be encoded into a buffer, one needs to allocate
56 // a checksum buffer with size checksumByteSize(), and call
57 // writeChecksum(checksumBuffer) to write the checksum to the buffer.
58 // If the checksum needs to be validated against an existing one, one needs to
59 // call validate(existChecksum, existChecksumLen).
60 //
61 // The checksum generator and validator must be set to the same version, and
62 // the validator must check ALL checksums in the order they are generated,
63 // otherwise the validation function will return false.
64 //
65 // It is allowed to change the checksum version between calculating two
66 // checksums. This is designed for backward compatibility reason.
67 //
68 // Example 1, encoding and decoding:
69 //
70 // bool testChecksum(void* buf, size_t bufLen) {
71 //     // encoding message
72 //     ChecksumCalculator encoder;
73 //     encoder.setVersion(1);
74 //     encoder.addBuffer(buf, bufLen);
75 //     std::vector<unsigned char> message(bufLen + encoder.checksumByteSize());
76 //     memcpy(&message[0], buf, bufLen);
77 //     encoder.writeChecksum(&message[0] + bufLen, encoder.checksumByteSize());
78 //
79 //     // decoding message
80 //     ChecksumCalculator decoder;
81 //     decoder.setVersion(1);
82 //     decoder.addBuffer(&message[0], bufLen);
83 //     return decoder.validate(&message[0] + bufLen, decoder.checksumByteSize());
84 // }
85 // The return value is true.
86 //
87 // Example 2, decoding will fail if the order of messages is wrong:
88 //
89 // bool testChecksumOrder(void* buf1, size_t bufLen1,
90 //                        void* buf2, size_t bufLen2) {
91 //     // encoding messages
92 //     ChecksumCalculator encoder;
93 //     encoder.setVersion(1);
94 //
95 //     std::vector<unsigned char> message1(bufLen1 + encoder.checksumByteSize());
96 //     std::vector<unsigned char> message2(bufLen2 + encoder.checksumByteSize());
97 //
98 //     encoder.addBuffer(buf1, bufLen1);
99 //     std::vector<unsigned char> message1(bufLen1 + encoder.checksumByteSize());
100 //     memcpy(&message1[0], buf1, bufLen1);
101 //     encoder.writeChecksum(&message1[0] + bufLen1, encoder.checksumByteSize());
102 //
103 //     encoder.addBuffer(buf2, bufLen2);
104 //     std::vector<unsigned char> message2(bufLen2 + encoder.checksumByteSize());
105 //     memcpy(&message2[0], buf2, bufLen2);
106 //     encoder.writeChecksum(&message2[0] + bufLen2, encoder.checksumByteSize());
107 //
108 //     // decoding messages
109 //     ChecksumCalculator decoder;
110 //     decoder.setVersion(1);
111 //     decoder.addBuffer(&message2[0], bufLen2);
112 //     // returns false because the decoding order is not consistent with
113 //     // encoding order
114 //     if (!decoder.validate(&message2[0]+bufLen2, decoder.checksumByteSize())) {
115 //         return false;
116 //     }
117 //
118 //     decoder.addBuffer(&message1[0], bufLen1);
119 //     if (!decoder.validate(&message1[0]+bufLen1, decoder.checksumByteSize())) {
120 //         return false;
121 //     }
122 //
123 //     return false;
124 // }
125 
126 class ChecksumCalculator {
127 public:
128     static constexpr size_t kMaxChecksumLength = 8;
129 
130     // Get and set current checksum version
getVersion()131     uint32_t getVersion() const { return m_version; }
132     // Call setVersion to set a checksum version. It should be called before
133     // addBuffer(), writeChecksum() and validate(). And it should be called
134     // exact once per rendering thread if both host and guest support checksum.
135     // It won't be called if either host or guest does not support checksum.
136     bool setVersion(uint32_t version);
137 
138     // Maximum supported checksum version
139     static uint32_t getMaxVersion();
140     // A version string that looks like "ANDROID_EMU_CHECKSUM_HELPER_v1"
141     // Used multiple times when the guest queries the maximum supported version
142     // from the host.
143     // The library owns the returned pointer. The returned pointer will be
144     // deconstructed when unloading library.
145     static const char* getMaxVersionStr();
146     static const char* getMaxVersionStrPrefix();
147 
148     // Size of checksum in the current version
checksumByteSize()149     size_t checksumByteSize() const { return m_checksumSize; }
150 
151     // Update the current checksum value from the data
152     // at |buf| of |bufLen| bytes. Once all buffers
153     // have been added, call writeChecksum() to store
154     // the final checksum value and reset its state.
155     void addBuffer(const void* buf, size_t bufLen);
156     // Write the checksum from the list of buffers to outputChecksum
157     // Will reset the list of buffers by calling resetChecksum.
158     // Return false if the buffer is not long enough
159     // Please query buffer size from checksumByteSize()
160     bool writeChecksum(void* outputChecksum, size_t outputChecksumLen);
161     // Restore the states for computing checksums.
162     // Automatically called at the end of writeChecksum and validate.
163     // Can also be used to abandon the current checksum being calculated.
164     // Notes: it doesn't update the internal read / write counter
165     void resetChecksum();
166 
167     // Calculate the checksum from the list of buffers and
168     // compare it with the checksum encoded in expectedChecksum
169     // Will reset the list of buffers by calling resetChecksum.
170     bool validate(const void* expectedChecksum, size_t expectedChecksumLen);
171 
172     // Snapshot support.
173     void save(android::base::Stream* stream);
174     void load(android::base::Stream* stream);
175 
176 private:
177     static constexpr size_t kVersion1ChecksumSize = 8;  // 2 x uint32_t
178 
179     static_assert(kVersion1ChecksumSize <= kMaxChecksumLength,
180                   "Invalid ChecksumCalculator::kMaxChecksumLength value");
181 
checksumByteSize(uint32_t version)182     static constexpr size_t checksumByteSize(uint32_t version) {
183         return version == 1 ? kVersion1ChecksumSize : 0;
184     }
185 
186     uint32_t m_version = 0;
187     uint32_t m_checksumSize = checksumByteSize(0);
188     // A temporary state used to compute the total length of a list of buffers,
189     // if addBuffer is called.
190     uint32_t m_numRead = 0;
191     uint32_t m_numWrite = 0;
192     // m_isEncodingChecksum is true when between addBuffer and writeChecksum
193     bool m_isEncodingChecksum = false;
194 
195     // Compute a 32bit checksum
196     // Used in protocol v1
197     uint32_t computeV1Checksum() const;
198     // The buffer used in protocol version 1 to compute checksum.
199     uint32_t m_v1BufferTotalLength = 0;
200 };
201