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