1 /*
2 * Copyright (C) 2019 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 #include "include/stats_event.h"
18
19 #include <stdlib.h>
20 #include <string.h>
21
22 #include "stats_buffer_writer.h"
23 #include "utils.h"
24
25 #define LOGGER_ENTRY_MAX_PAYLOAD 4068
26 // Max payload size is 4 bytes less as 4 bytes are reserved for stats_eventTag.
27 // See android_util_Stats_Log.cpp
28 #define MAX_PUSH_EVENT_PAYLOAD (LOGGER_ENTRY_MAX_PAYLOAD - 4)
29
30 #define MAX_PULL_EVENT_PAYLOAD (50 * 1024) // 50 KB
31
32 /* POSITIONS */
33 #define POS_NUM_ELEMENTS 1
34 #define POS_TIMESTAMP (POS_NUM_ELEMENTS + sizeof(uint8_t))
35 #define POS_ATOM_ID (POS_TIMESTAMP + sizeof(uint8_t) + sizeof(uint64_t))
36
37 /* LIMITS */
38 #define MAX_ANNOTATION_COUNT 15
39 #define MAX_BYTE_VALUE 127 // parsing side requires that lengths fit in 7 bits
40
41 /* ERRORS */
42 #define ERROR_NO_TIMESTAMP 0x1
43 #define ERROR_NO_ATOM_ID 0x2
44 #define ERROR_OVERFLOW 0x4
45 #define ERROR_ATTRIBUTION_CHAIN_TOO_LONG 0x8
46 #define ERROR_TOO_MANY_KEY_VALUE_PAIRS 0x10
47 #define ERROR_ANNOTATION_DOES_NOT_FOLLOW_FIELD 0x20
48 #define ERROR_INVALID_ANNOTATION_ID 0x40
49 #define ERROR_ANNOTATION_ID_TOO_LARGE 0x80
50 #define ERROR_TOO_MANY_ANNOTATIONS 0x100
51 #define ERROR_TOO_MANY_FIELDS 0x200
52 #define ERROR_INVALID_VALUE_TYPE 0x400
53 #define ERROR_STRING_NOT_NULL_TERMINATED 0x800
54 #define ERROR_ATOM_ID_INVALID_POSITION 0x2000
55 #define ERROR_LIST_TOO_LONG 0x4000
56
57 /* TYPE IDS */
58 #define INT32_TYPE 0x00
59 #define INT64_TYPE 0x01
60 #define STRING_TYPE 0x02
61 #define LIST_TYPE 0x03
62 #define FLOAT_TYPE 0x04
63 #define BOOL_TYPE 0x05
64 #define BYTE_ARRAY_TYPE 0x06
65 #define OBJECT_TYPE 0x07
66 #define KEY_VALUE_PAIRS_TYPE 0x08
67 #define ATTRIBUTION_CHAIN_TYPE 0x09
68 #define ERROR_TYPE 0x0F
69
70 // The AStatsEvent struct holds the serialized encoding of an event
71 // within a buf. Also includes other required fields.
72 struct AStatsEvent {
73 uint8_t* buf;
74 // Location of last field within the buf. Here, field denotes either a
75 // metadata field (e.g. timestamp) or an atom field.
76 size_t lastFieldPos;
77 // Number of valid bytes within the buffer.
78 size_t numBytesWritten;
79 uint32_t numElements;
80 uint32_t atomId;
81 uint32_t errors;
82 bool built;
83 size_t bufSize;
84 };
85
AStatsEvent_obtain()86 AStatsEvent* AStatsEvent_obtain() {
87 AStatsEvent* event = malloc(sizeof(AStatsEvent));
88 event->lastFieldPos = 0;
89 event->numBytesWritten = 2; // reserve first 2 bytes for root event type and number of elements
90 event->numElements = 0;
91 event->atomId = 0;
92 event->errors = 0;
93 event->built = false;
94 event->bufSize = MAX_PUSH_EVENT_PAYLOAD;
95 event->buf = (uint8_t*)calloc(event->bufSize, 1);
96
97 event->buf[0] = OBJECT_TYPE;
98 AStatsEvent_writeInt64(event, get_elapsed_realtime_ns()); // write the timestamp
99
100 return event;
101 }
102
AStatsEvent_release(AStatsEvent * event)103 void AStatsEvent_release(AStatsEvent* event) {
104 free(event->buf);
105 free(event);
106 }
107
AStatsEvent_setAtomId(AStatsEvent * event,uint32_t atomId)108 void AStatsEvent_setAtomId(AStatsEvent* event, uint32_t atomId) {
109 if (event->atomId != 0) return;
110 if (event->numElements != 1) {
111 event->errors |= ERROR_ATOM_ID_INVALID_POSITION;
112 return;
113 }
114
115 event->atomId = atomId;
116 AStatsEvent_writeInt32(event, atomId);
117 }
118
119 // Overwrites the timestamp populated in AStatsEvent_obtain with a custom
120 // timestamp. Should only be called from test code.
AStatsEvent_overwriteTimestamp(AStatsEvent * event,uint64_t timestampNs)121 void AStatsEvent_overwriteTimestamp(AStatsEvent* event, uint64_t timestampNs) {
122 memcpy(&event->buf[POS_TIMESTAMP + sizeof(uint8_t)], ×tampNs, sizeof(timestampNs));
123 // Do not increment numElements because we already accounted for the timestamp
124 // within AStatsEvent_obtain.
125 }
126
127 // Side-effect: modifies event->errors if the buffer would overflow
overflows(AStatsEvent * event,size_t size)128 static bool overflows(AStatsEvent* event, size_t size) {
129 const size_t totalBytesNeeded = event->numBytesWritten + size;
130 if (totalBytesNeeded > MAX_PULL_EVENT_PAYLOAD) {
131 event->errors |= ERROR_OVERFLOW;
132 return true;
133 }
134
135 // Expand buffer if needed.
136 if (event->bufSize < MAX_PULL_EVENT_PAYLOAD && totalBytesNeeded > event->bufSize) {
137 do {
138 event->bufSize *= 2;
139 } while (event->bufSize <= totalBytesNeeded);
140
141 if (event->bufSize > MAX_PULL_EVENT_PAYLOAD) {
142 event->bufSize = MAX_PULL_EVENT_PAYLOAD;
143 }
144
145 event->buf = (uint8_t*)realloc(event->buf, event->bufSize);
146 }
147 return false;
148 }
149
150 // Side-effect: all append functions increment event->numBytesWritten if there is
151 // sufficient space within the buffer to place the value
append_byte(AStatsEvent * event,uint8_t value)152 static void append_byte(AStatsEvent* event, uint8_t value) {
153 if (!overflows(event, sizeof(value))) {
154 event->buf[event->numBytesWritten] = value;
155 event->numBytesWritten += sizeof(value);
156 }
157 }
158
append_bool(AStatsEvent * event,bool value)159 static void append_bool(AStatsEvent* event, bool value) {
160 append_byte(event, (uint8_t)value);
161 }
162
append_int32(AStatsEvent * event,int32_t value)163 static void append_int32(AStatsEvent* event, int32_t value) {
164 if (!overflows(event, sizeof(value))) {
165 memcpy(&event->buf[event->numBytesWritten], &value, sizeof(value));
166 event->numBytesWritten += sizeof(value);
167 }
168 }
169
append_int64(AStatsEvent * event,int64_t value)170 static void append_int64(AStatsEvent* event, int64_t value) {
171 if (!overflows(event, sizeof(value))) {
172 memcpy(&event->buf[event->numBytesWritten], &value, sizeof(value));
173 event->numBytesWritten += sizeof(value);
174 }
175 }
176
append_float(AStatsEvent * event,float value)177 static void append_float(AStatsEvent* event, float value) {
178 if (!overflows(event, sizeof(value))) {
179 memcpy(&event->buf[event->numBytesWritten], &value, sizeof(value));
180 event->numBytesWritten += sizeof(float);
181 }
182 }
183
append_byte_array(AStatsEvent * event,const uint8_t * buf,size_t size)184 static void append_byte_array(AStatsEvent* event, const uint8_t* buf, size_t size) {
185 if (!overflows(event, size)) {
186 memcpy(&event->buf[event->numBytesWritten], buf, size);
187 event->numBytesWritten += size;
188 }
189 }
190
191 // Side-effect: modifies event->errors if buf is not properly null-terminated
append_string(AStatsEvent * event,const char * buf)192 static void append_string(AStatsEvent* event, const char* buf) {
193 size_t size = strnlen(buf, MAX_PULL_EVENT_PAYLOAD);
194 if (size == MAX_PULL_EVENT_PAYLOAD) {
195 event->errors |= ERROR_STRING_NOT_NULL_TERMINATED;
196 return;
197 }
198
199 append_int32(event, size);
200 append_byte_array(event, (uint8_t*)buf, size);
201 }
202
start_field(AStatsEvent * event,uint8_t typeId)203 static void start_field(AStatsEvent* event, uint8_t typeId) {
204 event->lastFieldPos = event->numBytesWritten;
205 append_byte(event, typeId);
206 event->numElements++;
207 }
208
AStatsEvent_writeInt32(AStatsEvent * event,int32_t value)209 void AStatsEvent_writeInt32(AStatsEvent* event, int32_t value) {
210 start_field(event, INT32_TYPE);
211 append_int32(event, value);
212 }
213
AStatsEvent_writeInt64(AStatsEvent * event,int64_t value)214 void AStatsEvent_writeInt64(AStatsEvent* event, int64_t value) {
215 start_field(event, INT64_TYPE);
216 append_int64(event, value);
217 }
218
AStatsEvent_writeFloat(AStatsEvent * event,float value)219 void AStatsEvent_writeFloat(AStatsEvent* event, float value) {
220 start_field(event, FLOAT_TYPE);
221 append_float(event, value);
222 }
223
AStatsEvent_writeBool(AStatsEvent * event,bool value)224 void AStatsEvent_writeBool(AStatsEvent* event, bool value) {
225 start_field(event, BOOL_TYPE);
226 append_bool(event, value);
227 }
228
AStatsEvent_writeByteArray(AStatsEvent * event,const uint8_t * buf,size_t numBytes)229 void AStatsEvent_writeByteArray(AStatsEvent* event, const uint8_t* buf, size_t numBytes) {
230 start_field(event, BYTE_ARRAY_TYPE);
231 if (buf == NULL) {
232 numBytes = 0;
233 }
234 append_int32(event, numBytes);
235 if (numBytes > 0) {
236 append_byte_array(event, buf, numBytes);
237 }
238 }
239
240 // Value is assumed to be encoded using UTF8
AStatsEvent_writeString(AStatsEvent * event,const char * value)241 void AStatsEvent_writeString(AStatsEvent* event, const char* value) {
242 start_field(event, STRING_TYPE);
243 append_string(event, value == NULL ? "" : value);
244 }
245
246 // Tags are assumed to be encoded using UTF8
AStatsEvent_writeAttributionChain(AStatsEvent * event,const uint32_t * uids,const char * const * tags,uint8_t numNodes)247 void AStatsEvent_writeAttributionChain(AStatsEvent* event, const uint32_t* uids,
248 const char* const* tags, uint8_t numNodes) {
249 if (numNodes > MAX_BYTE_VALUE) {
250 event->errors |= ERROR_ATTRIBUTION_CHAIN_TOO_LONG;
251 return;
252 }
253
254 start_field(event, ATTRIBUTION_CHAIN_TYPE);
255 append_byte(event, numNodes);
256
257 for (uint8_t i = 0; i < numNodes; i++) {
258 append_int32(event, uids[i]);
259 append_string(event, tags[i] == NULL ? "" : tags[i]);
260 }
261 }
262
writeArrayMetadata(AStatsEvent * event,size_t numElements,uint8_t elementTypeId)263 static bool writeArrayMetadata(AStatsEvent* event, size_t numElements, uint8_t elementTypeId) {
264 if (numElements > MAX_BYTE_VALUE) {
265 event->errors |= ERROR_LIST_TOO_LONG;
266 return false;
267 }
268
269 start_field(event, LIST_TYPE);
270 append_byte(event, numElements);
271 append_byte(event, elementTypeId);
272 return true;
273 }
274
AStatsEvent_writeInt32Array(AStatsEvent * event,const int32_t * elements,size_t numElements)275 void AStatsEvent_writeInt32Array(AStatsEvent* event, const int32_t* elements, size_t numElements) {
276 if (!writeArrayMetadata(event, numElements, INT32_TYPE)) {
277 return;
278 }
279
280 for (size_t i = 0; i < numElements; i++) {
281 append_int32(event, elements[i]);
282 }
283 }
284
AStatsEvent_writeInt64Array(AStatsEvent * event,const int64_t * elements,size_t numElements)285 void AStatsEvent_writeInt64Array(AStatsEvent* event, const int64_t* elements, size_t numElements) {
286 if (!writeArrayMetadata(event, numElements, INT64_TYPE)) {
287 return;
288 }
289
290 for (size_t i = 0; i < numElements; i++) {
291 append_int64(event, elements[i]);
292 }
293 }
294
AStatsEvent_writeFloatArray(AStatsEvent * event,const float * elements,size_t numElements)295 void AStatsEvent_writeFloatArray(AStatsEvent* event, const float* elements, size_t numElements) {
296 if (!writeArrayMetadata(event, numElements, FLOAT_TYPE)) {
297 return;
298 }
299
300 for (size_t i = 0; i < numElements; i++) {
301 append_float(event, elements[i]);
302 }
303 }
304
AStatsEvent_writeBoolArray(AStatsEvent * event,const bool * elements,size_t numElements)305 void AStatsEvent_writeBoolArray(AStatsEvent* event, const bool* elements, size_t numElements) {
306 if (!writeArrayMetadata(event, numElements, BOOL_TYPE)) {
307 return;
308 }
309
310 for (size_t i = 0; i < numElements; i++) {
311 append_bool(event, elements[i]);
312 }
313 }
314
AStatsEvent_writeStringArray(AStatsEvent * event,const char * const * elements,size_t numElements)315 void AStatsEvent_writeStringArray(AStatsEvent* event, const char* const* elements,
316 size_t numElements) {
317 if (!writeArrayMetadata(event, numElements, STRING_TYPE)) {
318 return;
319 }
320
321 for (size_t i = 0; i < numElements; i++) {
322 append_string(event, elements[i] == NULL ? "" : elements[i]);
323 }
324 }
325
326 // Side-effect: modifies event->errors if field has too many annotations
increment_annotation_count(AStatsEvent * event)327 static void increment_annotation_count(AStatsEvent* event) {
328 if (event->lastFieldPos >= event->bufSize) {
329 return;
330 }
331 uint8_t fieldType = event->buf[event->lastFieldPos] & 0x0F;
332 uint32_t oldAnnotationCount = (event->buf[event->lastFieldPos] & 0xF0) >> 4;
333 uint32_t newAnnotationCount = oldAnnotationCount + 1;
334
335 if (newAnnotationCount > MAX_ANNOTATION_COUNT) {
336 event->errors |= ERROR_TOO_MANY_ANNOTATIONS;
337 return;
338 }
339
340 event->buf[event->lastFieldPos] = (((uint8_t)newAnnotationCount << 4) & 0xF0) | fieldType;
341 }
342
AStatsEvent_addBoolAnnotation(AStatsEvent * event,uint8_t annotationId,bool value)343 void AStatsEvent_addBoolAnnotation(AStatsEvent* event, uint8_t annotationId, bool value) {
344 if (event->numElements < 2) {
345 event->errors |= ERROR_ANNOTATION_DOES_NOT_FOLLOW_FIELD;
346 return;
347 } else if (annotationId > MAX_BYTE_VALUE) {
348 event->errors |= ERROR_ANNOTATION_ID_TOO_LARGE;
349 return;
350 }
351
352 append_byte(event, annotationId);
353 append_byte(event, BOOL_TYPE);
354 append_bool(event, value);
355 increment_annotation_count(event);
356 }
357
AStatsEvent_addInt32Annotation(AStatsEvent * event,uint8_t annotationId,int32_t value)358 void AStatsEvent_addInt32Annotation(AStatsEvent* event, uint8_t annotationId, int32_t value) {
359 if (event->numElements < 2) {
360 event->errors |= ERROR_ANNOTATION_DOES_NOT_FOLLOW_FIELD;
361 return;
362 } else if (annotationId > MAX_BYTE_VALUE) {
363 event->errors |= ERROR_ANNOTATION_ID_TOO_LARGE;
364 return;
365 }
366
367 append_byte(event, annotationId);
368 append_byte(event, INT32_TYPE);
369 append_int32(event, value);
370 increment_annotation_count(event);
371 }
372
AStatsEvent_getAtomId(AStatsEvent * event)373 uint32_t AStatsEvent_getAtomId(AStatsEvent* event) {
374 return event->atomId;
375 }
376
AStatsEvent_getBuffer(AStatsEvent * event,size_t * size)377 uint8_t* AStatsEvent_getBuffer(AStatsEvent* event, size_t* size) {
378 if (size) *size = event->numBytesWritten;
379 return event->buf;
380 }
381
AStatsEvent_getErrors(AStatsEvent * event)382 uint32_t AStatsEvent_getErrors(AStatsEvent* event) {
383 return event->errors;
384 }
385
build_internal(AStatsEvent * event,const bool push)386 static void build_internal(AStatsEvent* event, const bool push) {
387 if (event->numElements > MAX_BYTE_VALUE) event->errors |= ERROR_TOO_MANY_FIELDS;
388 if (0 == event->atomId) event->errors |= ERROR_NO_ATOM_ID;
389 if (push && event->numBytesWritten > MAX_PUSH_EVENT_PAYLOAD) event->errors |= ERROR_OVERFLOW;
390
391 // If there are errors, rewrite buffer.
392 if (event->errors) {
393 // Discard everything after the atom id (including atom-level
394 // annotations). This leaves only two elements (timestamp and atom id).
395 event->numElements = 2;
396 // Reset number of atom-level annotations to 0.
397 event->buf[POS_ATOM_ID] = INT32_TYPE;
398 // Now, write errors to the buffer immediately after the atom id.
399 event->numBytesWritten = POS_ATOM_ID + sizeof(uint8_t) + sizeof(uint32_t);
400 start_field(event, ERROR_TYPE);
401 append_int32(event, event->errors);
402 }
403
404 event->buf[POS_NUM_ELEMENTS] = event->numElements;
405 }
406
AStatsEvent_build(AStatsEvent * event)407 void AStatsEvent_build(AStatsEvent* event) {
408 if (event->built) return;
409
410 build_internal(event, false /* push */);
411
412 event->built = true;
413 }
414
AStatsEvent_write(AStatsEvent * event)415 int AStatsEvent_write(AStatsEvent* event) {
416 build_internal(event, true /* push */);
417 return write_buffer_to_statsd(event->buf, event->numBytesWritten, event->atomId);
418 }
419