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