• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2017 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 #define DEBUG false  // STOPSHIP if true
18 #include "logd/LogEvent.h"
19 
20 #include "stats_log_util.h"
21 #include "statslog.h"
22 
23 #include <binder/IPCThreadState.h>
24 #include <private/android_filesystem_config.h>
25 
26 namespace android {
27 namespace os {
28 namespace statsd {
29 
30 // for TrainInfo experiment id serialization
31 const int FIELD_ID_EXPERIMENT_ID = 1;
32 
33 using namespace android::util;
34 using android::util::ProtoOutputStream;
35 using std::string;
36 using std::vector;
37 
LogEvent(log_msg & msg)38 LogEvent::LogEvent(log_msg& msg) {
39     mContext =
40             create_android_log_parser(msg.msg() + sizeof(uint32_t), msg.len() - sizeof(uint32_t));
41     mLogdTimestampNs = msg.entry_v1.sec * NS_PER_SEC + msg.entry_v1.nsec;
42     mLogUid = msg.entry_v4.uid;
43     init(mContext);
44     if (mContext) {
45         // android_log_destroy will set mContext to NULL
46         android_log_destroy(&mContext);
47     }
48 }
49 
LogEvent(const LogEvent & event)50 LogEvent::LogEvent(const LogEvent& event) {
51     mTagId = event.mTagId;
52     mLogUid = event.mLogUid;
53     mElapsedTimestampNs = event.mElapsedTimestampNs;
54     mLogdTimestampNs = event.mLogdTimestampNs;
55     mValues = event.mValues;
56 }
57 
LogEvent(const StatsLogEventWrapper & statsLogEventWrapper,int workChainIndex)58 LogEvent::LogEvent(const StatsLogEventWrapper& statsLogEventWrapper, int workChainIndex) {
59     mTagId = statsLogEventWrapper.getTagId();
60     mLogdTimestampNs = statsLogEventWrapper.getWallClockTimeNs();
61     mElapsedTimestampNs = statsLogEventWrapper.getElapsedRealTimeNs();
62     mLogUid = 0;
63     int workChainPosOffset = 0;
64     if (workChainIndex != -1) {
65         const WorkChain& wc = statsLogEventWrapper.getWorkChains()[workChainIndex];
66         // chains are at field 1, level 2
67         int depth = 2;
68         for (int i = 0; i < (int)wc.uids.size(); i++) {
69             int pos[] = {1, i + 1, 1};
70             mValues.push_back(FieldValue(Field(mTagId, pos, depth), Value(wc.uids[i])));
71             pos[2]++;
72             mValues.push_back(FieldValue(Field(mTagId, pos, depth), Value(wc.tags[i])));
73             mValues.back().mField.decorateLastPos(2);
74         }
75         mValues.back().mField.decorateLastPos(1);
76         workChainPosOffset = 1;
77     }
78     for (int i = 0; i < (int)statsLogEventWrapper.getElements().size(); i++) {
79         Field field(statsLogEventWrapper.getTagId(), getSimpleField(i + 1 + workChainPosOffset));
80         switch (statsLogEventWrapper.getElements()[i].type) {
81             case android::os::StatsLogValue::STATS_LOG_VALUE_TYPE::INT:
82                 mValues.push_back(
83                         FieldValue(field, Value(statsLogEventWrapper.getElements()[i].int_value)));
84                 break;
85             case android::os::StatsLogValue::STATS_LOG_VALUE_TYPE::LONG:
86                 mValues.push_back(
87                         FieldValue(field, Value(statsLogEventWrapper.getElements()[i].long_value)));
88                 break;
89             case android::os::StatsLogValue::STATS_LOG_VALUE_TYPE::FLOAT:
90                 mValues.push_back(FieldValue(
91                         field, Value(statsLogEventWrapper.getElements()[i].float_value)));
92                 break;
93             case android::os::StatsLogValue::STATS_LOG_VALUE_TYPE::DOUBLE:
94                 mValues.push_back(FieldValue(
95                         field, Value(statsLogEventWrapper.getElements()[i].double_value)));
96                 break;
97             case android::os::StatsLogValue::STATS_LOG_VALUE_TYPE::STRING:
98                 mValues.push_back(
99                         FieldValue(field, Value(statsLogEventWrapper.getElements()[i].str_value)));
100                 break;
101             case android::os::StatsLogValue::STATS_LOG_VALUE_TYPE::STORAGE:
102                 mValues.push_back(FieldValue(
103                         field, Value(statsLogEventWrapper.getElements()[i].storage_value)));
104                 break;
105             default:
106                 break;
107         }
108     }
109 }
110 
createLogEvents(const StatsLogEventWrapper & statsLogEventWrapper,std::vector<std::shared_ptr<LogEvent>> & logEvents)111 void LogEvent::createLogEvents(const StatsLogEventWrapper& statsLogEventWrapper,
112                                std::vector<std::shared_ptr<LogEvent>>& logEvents) {
113     if (statsLogEventWrapper.getWorkChains().size() == 0) {
114         logEvents.push_back(std::make_shared<LogEvent>(statsLogEventWrapper, -1));
115     } else {
116         for (size_t i = 0; i < statsLogEventWrapper.getWorkChains().size(); i++) {
117             logEvents.push_back(std::make_shared<LogEvent>(statsLogEventWrapper, i));
118         }
119     }
120 }
121 
LogEvent(int32_t tagId,int64_t wallClockTimestampNs,int64_t elapsedTimestampNs)122 LogEvent::LogEvent(int32_t tagId, int64_t wallClockTimestampNs, int64_t elapsedTimestampNs) {
123     mLogdTimestampNs = wallClockTimestampNs;
124     mElapsedTimestampNs = elapsedTimestampNs;
125     mTagId = tagId;
126     mLogUid = 0;
127     mContext = create_android_logger(1937006964); // the event tag shared by all stats logs
128     if (mContext) {
129         android_log_write_int64(mContext, elapsedTimestampNs);
130         android_log_write_int32(mContext, tagId);
131     }
132 }
133 
LogEvent(int32_t tagId,int64_t wallClockTimestampNs,int64_t elapsedTimestampNs,int32_t uid,const std::map<int32_t,int32_t> & int_map,const std::map<int32_t,int64_t> & long_map,const std::map<int32_t,std::string> & string_map,const std::map<int32_t,float> & float_map)134 LogEvent::LogEvent(int32_t tagId, int64_t wallClockTimestampNs, int64_t elapsedTimestampNs,
135                    int32_t uid,
136                    const std::map<int32_t, int32_t>& int_map,
137                    const std::map<int32_t, int64_t>& long_map,
138                    const std::map<int32_t, std::string>& string_map,
139                    const std::map<int32_t, float>& float_map) {
140     mLogdTimestampNs = wallClockTimestampNs;
141     mElapsedTimestampNs = elapsedTimestampNs;
142     mTagId = android::util::KEY_VALUE_PAIRS_ATOM;
143     mLogUid = uid;
144 
145     int pos[] = {1, 1, 1};
146 
147     mValues.push_back(FieldValue(Field(mTagId, pos, 0 /* depth */), Value(uid)));
148     pos[0]++;
149     for (const auto&itr : int_map) {
150         pos[2] = 1;
151         mValues.push_back(FieldValue(Field(mTagId, pos, 2 /* depth */), Value(itr.first)));
152         pos[2] = 2;
153         mValues.push_back(FieldValue(Field(mTagId, pos, 2 /* depth */), Value(itr.second)));
154         mValues.back().mField.decorateLastPos(2);
155         pos[1]++;
156     }
157 
158     for (const auto&itr : long_map) {
159         pos[2] = 1;
160         mValues.push_back(FieldValue(Field(mTagId, pos, 2 /* depth */), Value(itr.first)));
161         pos[2] = 3;
162         mValues.push_back(FieldValue(Field(mTagId, pos, 2 /* depth */), Value(itr.second)));
163         mValues.back().mField.decorateLastPos(2);
164         pos[1]++;
165     }
166 
167     for (const auto&itr : string_map) {
168         pos[2] = 1;
169         mValues.push_back(FieldValue(Field(mTagId, pos, 2 /* depth */), Value(itr.first)));
170         pos[2] = 4;
171         mValues.push_back(FieldValue(Field(mTagId, pos, 2 /* depth */), Value(itr.second)));
172         mValues.back().mField.decorateLastPos(2);
173         pos[1]++;
174     }
175 
176     for (const auto&itr : float_map) {
177         pos[2] = 1;
178         mValues.push_back(FieldValue(Field(mTagId, pos, 2 /* depth */), Value(itr.first)));
179         pos[2] = 5;
180         mValues.push_back(FieldValue(Field(mTagId, pos, 2 /* depth */), Value(itr.second)));
181         mValues.back().mField.decorateLastPos(2);
182         pos[1]++;
183     }
184     if (!mValues.empty()) {
185         mValues.back().mField.decorateLastPos(1);
186         mValues.at(mValues.size() - 2).mField.decorateLastPos(1);
187     }
188 }
189 
LogEvent(const string & trainName,int64_t trainVersionCode,bool requiresStaging,bool rollbackEnabled,bool requiresLowLatencyMonitor,int32_t state,const std::vector<uint8_t> & experimentIds,int32_t userId)190 LogEvent::LogEvent(const string& trainName, int64_t trainVersionCode, bool requiresStaging,
191                    bool rollbackEnabled, bool requiresLowLatencyMonitor, int32_t state,
192                    const std::vector<uint8_t>& experimentIds, int32_t userId) {
193     mLogdTimestampNs = getWallClockNs();
194     mElapsedTimestampNs = getElapsedRealtimeNs();
195     mTagId = android::util::BINARY_PUSH_STATE_CHANGED;
196     mLogUid = android::IPCThreadState::self()->getCallingUid();
197 
198     mValues.push_back(FieldValue(Field(mTagId, getSimpleField(1)), Value(trainName)));
199     mValues.push_back(FieldValue(Field(mTagId, getSimpleField(2)), Value(trainVersionCode)));
200     mValues.push_back(FieldValue(Field(mTagId, getSimpleField(3)), Value((int)requiresStaging)));
201     mValues.push_back(FieldValue(Field(mTagId, getSimpleField(4)), Value((int)rollbackEnabled)));
202     mValues.push_back(
203             FieldValue(Field(mTagId, getSimpleField(5)), Value((int)requiresLowLatencyMonitor)));
204     mValues.push_back(FieldValue(Field(mTagId, getSimpleField(6)), Value(state)));
205     mValues.push_back(FieldValue(Field(mTagId, getSimpleField(7)), Value(experimentIds)));
206     mValues.push_back(FieldValue(Field(mTagId, getSimpleField(8)), Value(userId)));
207 }
208 
LogEvent(int64_t wallClockTimestampNs,int64_t elapsedTimestampNs,const VendorAtom & vendorAtom)209 LogEvent::LogEvent(int64_t wallClockTimestampNs, int64_t elapsedTimestampNs,
210                    const VendorAtom& vendorAtom) {
211     mLogdTimestampNs = wallClockTimestampNs;
212     mElapsedTimestampNs = elapsedTimestampNs;
213     mTagId = vendorAtom.atomId;
214     mLogUid = AID_STATSD;
215 
216     mValues.push_back(
217             FieldValue(Field(mTagId, getSimpleField(1)), Value(vendorAtom.reverseDomainName)));
218     for (int i = 0; i < (int)vendorAtom.values.size(); i++) {
219         switch (vendorAtom.values[i].getDiscriminator()) {
220             case VendorAtom::Value::hidl_discriminator::intValue:
221                 mValues.push_back(FieldValue(Field(mTagId, getSimpleField(i + 2)),
222                                              Value(vendorAtom.values[i].intValue())));
223                 break;
224             case VendorAtom::Value::hidl_discriminator::longValue:
225                 mValues.push_back(FieldValue(Field(mTagId, getSimpleField(i + 2)),
226                                              Value(vendorAtom.values[i].longValue())));
227                 break;
228             case VendorAtom::Value::hidl_discriminator::floatValue:
229                 mValues.push_back(FieldValue(Field(mTagId, getSimpleField(i + 2)),
230                                              Value(vendorAtom.values[i].floatValue())));
231                 break;
232             case VendorAtom::Value::hidl_discriminator::stringValue:
233                 mValues.push_back(FieldValue(Field(mTagId, getSimpleField(i + 2)),
234                                              Value(vendorAtom.values[i].stringValue())));
235                 break;
236         }
237     }
238 }
239 
LogEvent(int64_t wallClockTimestampNs,int64_t elapsedTimestampNs,const InstallTrainInfo & trainInfo)240 LogEvent::LogEvent(int64_t wallClockTimestampNs, int64_t elapsedTimestampNs,
241                    const InstallTrainInfo& trainInfo) {
242     mLogdTimestampNs = wallClockTimestampNs;
243     mElapsedTimestampNs = elapsedTimestampNs;
244     mTagId = android::util::TRAIN_INFO;
245 
246     mValues.push_back(
247             FieldValue(Field(mTagId, getSimpleField(1)), Value(trainInfo.trainVersionCode)));
248     std::vector<uint8_t> experimentIdsProto;
249     writeExperimentIdsToProto(trainInfo.experimentIds, &experimentIdsProto);
250     mValues.push_back(FieldValue(Field(mTagId, getSimpleField(2)), Value(experimentIdsProto)));
251     mValues.push_back(FieldValue(Field(mTagId, getSimpleField(3)), Value(trainInfo.trainName)));
252     mValues.push_back(FieldValue(Field(mTagId, getSimpleField(4)), Value(trainInfo.status)));
253 }
254 
LogEvent(int32_t tagId,int64_t timestampNs)255 LogEvent::LogEvent(int32_t tagId, int64_t timestampNs) : LogEvent(tagId, timestampNs, timestampNs) {
256 }
257 
LogEvent(int32_t tagId,int64_t timestampNs,int32_t uid)258 LogEvent::LogEvent(int32_t tagId, int64_t timestampNs, int32_t uid) {
259     mLogdTimestampNs = timestampNs;
260     mTagId = tagId;
261     mLogUid = uid;
262     mContext = create_android_logger(1937006964); // the event tag shared by all stats logs
263     if (mContext) {
264         android_log_write_int64(mContext, timestampNs);
265         android_log_write_int32(mContext, tagId);
266     }
267 }
268 
init()269 void LogEvent::init() {
270     if (mContext) {
271         const char* buffer;
272         size_t len = android_log_write_list_buffer(mContext, &buffer);
273         // turns to reader mode
274         android_log_context contextForRead = create_android_log_parser(buffer, len);
275         if (contextForRead) {
276             init(contextForRead);
277             // destroy the context to save memory.
278             // android_log_destroy will set mContext to NULL
279             android_log_destroy(&contextForRead);
280         }
281         android_log_destroy(&mContext);
282     }
283 }
284 
~LogEvent()285 LogEvent::~LogEvent() {
286     if (mContext) {
287         // This is for the case when LogEvent is created using the test interface
288         // but init() isn't called.
289         android_log_destroy(&mContext);
290     }
291 }
292 
write(int32_t value)293 bool LogEvent::write(int32_t value) {
294     if (mContext) {
295         return android_log_write_int32(mContext, value) >= 0;
296     }
297     return false;
298 }
299 
write(uint32_t value)300 bool LogEvent::write(uint32_t value) {
301     if (mContext) {
302         return android_log_write_int32(mContext, value) >= 0;
303     }
304     return false;
305 }
306 
write(int64_t value)307 bool LogEvent::write(int64_t value) {
308     if (mContext) {
309         return android_log_write_int64(mContext, value) >= 0;
310     }
311     return false;
312 }
313 
write(uint64_t value)314 bool LogEvent::write(uint64_t value) {
315     if (mContext) {
316         return android_log_write_int64(mContext, value) >= 0;
317     }
318     return false;
319 }
320 
write(const string & value)321 bool LogEvent::write(const string& value) {
322     if (mContext) {
323         return android_log_write_string8_len(mContext, value.c_str(), value.length()) >= 0;
324     }
325     return false;
326 }
327 
write(float value)328 bool LogEvent::write(float value) {
329     if (mContext) {
330         return android_log_write_float32(mContext, value) >= 0;
331     }
332     return false;
333 }
334 
writeKeyValuePairs(int32_t uid,const std::map<int32_t,int32_t> & int_map,const std::map<int32_t,int64_t> & long_map,const std::map<int32_t,std::string> & string_map,const std::map<int32_t,float> & float_map)335 bool LogEvent::writeKeyValuePairs(int32_t uid,
336                                   const std::map<int32_t, int32_t>& int_map,
337                                   const std::map<int32_t, int64_t>& long_map,
338                                   const std::map<int32_t, std::string>& string_map,
339                                   const std::map<int32_t, float>& float_map) {
340     if (mContext) {
341          if (android_log_write_list_begin(mContext) < 0) {
342             return false;
343          }
344          write(uid);
345          for (const auto& itr : int_map) {
346              if (android_log_write_list_begin(mContext) < 0) {
347                 return false;
348              }
349              write(itr.first);
350              write(itr.second);
351              if (android_log_write_list_end(mContext) < 0) {
352                 return false;
353              }
354          }
355 
356          for (const auto& itr : long_map) {
357              if (android_log_write_list_begin(mContext) < 0) {
358                 return false;
359              }
360              write(itr.first);
361              write(itr.second);
362              if (android_log_write_list_end(mContext) < 0) {
363                 return false;
364              }
365          }
366 
367          for (const auto& itr : string_map) {
368              if (android_log_write_list_begin(mContext) < 0) {
369                 return false;
370              }
371              write(itr.first);
372              write(itr.second.c_str());
373              if (android_log_write_list_end(mContext) < 0) {
374                 return false;
375              }
376          }
377 
378          for (const auto& itr : float_map) {
379              if (android_log_write_list_begin(mContext) < 0) {
380                 return false;
381              }
382              write(itr.first);
383              write(itr.second);
384              if (android_log_write_list_end(mContext) < 0) {
385                 return false;
386              }
387          }
388 
389          if (android_log_write_list_end(mContext) < 0) {
390             return false;
391          }
392          return true;
393     }
394     return false;
395 }
396 
write(const std::vector<AttributionNodeInternal> & nodes)397 bool LogEvent::write(const std::vector<AttributionNodeInternal>& nodes) {
398     if (mContext) {
399          if (android_log_write_list_begin(mContext) < 0) {
400             return false;
401          }
402          for (size_t i = 0; i < nodes.size(); ++i) {
403              if (!write(nodes[i])) {
404                 return false;
405              }
406          }
407          if (android_log_write_list_end(mContext) < 0) {
408             return false;
409          }
410          return true;
411     }
412     return false;
413 }
414 
write(const AttributionNodeInternal & node)415 bool LogEvent::write(const AttributionNodeInternal& node) {
416     if (mContext) {
417          if (android_log_write_list_begin(mContext) < 0) {
418             return false;
419          }
420          if (android_log_write_int32(mContext, node.uid()) < 0) {
421             return false;
422          }
423          if (android_log_write_string8(mContext, node.tag().c_str()) < 0) {
424             return false;
425          }
426          if (android_log_write_list_end(mContext) < 0) {
427             return false;
428          }
429          return true;
430     }
431     return false;
432 }
433 
434 /**
435  * The elements of each log event are stored as a vector of android_log_list_elements.
436  * The goal is to do as little preprocessing as possible, because we read a tiny fraction
437  * of the elements that are written to the log.
438  *
439  * The idea here is to read through the log items once, we get as much information we need for
440  * matching as possible. Because this log will be matched against lots of matchers.
441  */
init(android_log_context context)442 void LogEvent::init(android_log_context context) {
443     android_log_list_element elem;
444     int i = 0;
445     int depth = -1;
446     int pos[] = {1, 1, 1};
447     bool isKeyValuePairAtom = false;
448     do {
449         elem = android_log_read_next(context);
450         switch ((int)elem.type) {
451             case EVENT_TYPE_INT:
452                 // elem at [0] is EVENT_TYPE_LIST, [1] is the timestamp, [2] is tag id.
453                 if (i == 2) {
454                     mTagId = elem.data.int32;
455                     isKeyValuePairAtom = (mTagId == android::util::KEY_VALUE_PAIRS_ATOM);
456                 } else {
457                     if (depth < 0 || depth > 2) {
458                         return;
459                     }
460 
461                     mValues.push_back(
462                             FieldValue(Field(mTagId, pos, depth), Value((int32_t)elem.data.int32)));
463 
464                     pos[depth]++;
465                 }
466                 break;
467             case EVENT_TYPE_FLOAT: {
468                 if (depth < 0 || depth > 2) {
469                     ALOGE("Depth > 2. Not supported!");
470                     return;
471                 }
472 
473                 // Handles the oneof field in KeyValuePair atom.
474                 if (isKeyValuePairAtom && depth == 2) {
475                     pos[depth] = 5;
476                 }
477 
478                 mValues.push_back(FieldValue(Field(mTagId, pos, depth), Value(elem.data.float32)));
479 
480                 pos[depth]++;
481 
482             } break;
483             case EVENT_TYPE_STRING: {
484                 if (depth < 0 || depth > 2) {
485                     ALOGE("Depth > 2. Not supported!");
486                     return;
487                 }
488 
489                 // Handles the oneof field in KeyValuePair atom.
490                 if (isKeyValuePairAtom && depth == 2) {
491                     pos[depth] = 4;
492                 }
493                 mValues.push_back(FieldValue(Field(mTagId, pos, depth),
494                                              Value(string(elem.data.string, elem.len))));
495 
496                 pos[depth]++;
497 
498             } break;
499             case EVENT_TYPE_LONG: {
500                 if (i == 1) {
501                     mElapsedTimestampNs = elem.data.int64;
502                 } else {
503                     if (depth < 0 || depth > 2) {
504                         ALOGE("Depth > 2. Not supported!");
505                         return;
506                     }
507                     // Handles the oneof field in KeyValuePair atom.
508                     if (isKeyValuePairAtom && depth == 2) {
509                         pos[depth] = 3;
510                     }
511                     mValues.push_back(
512                             FieldValue(Field(mTagId, pos, depth), Value((int64_t)elem.data.int64)));
513 
514                     pos[depth]++;
515                 }
516             } break;
517             case EVENT_TYPE_LIST:
518                 depth++;
519                 if (depth > 2) {
520                     ALOGE("Depth > 2. Not supported!");
521                     return;
522                 }
523                 pos[depth] = 1;
524 
525                 break;
526             case EVENT_TYPE_LIST_STOP: {
527                 int prevDepth = depth;
528                 depth--;
529                 if (depth >= 0 && depth < 2) {
530                     // Now go back to decorate the previous items that are last at prevDepth.
531                     // So that we can later easily match them with Position=Last matchers.
532                     pos[prevDepth]--;
533                     int path = getEncodedField(pos, prevDepth, false);
534                     for (auto it = mValues.rbegin(); it != mValues.rend(); ++it) {
535                         if (it->mField.getDepth() >= prevDepth &&
536                             it->mField.getPath(prevDepth) == path) {
537                             it->mField.decorateLastPos(prevDepth);
538                         } else {
539                             // Safe to break, because the items are in DFS order.
540                             break;
541                         }
542                     }
543                     pos[depth]++;
544                 }
545                 break;
546             }
547             case EVENT_TYPE_UNKNOWN:
548                 break;
549             default:
550                 break;
551         }
552         i++;
553     } while ((elem.type != EVENT_TYPE_UNKNOWN) && !elem.complete);
554     if (isKeyValuePairAtom && mValues.size() > 0) {
555         mValues[0] = FieldValue(Field(android::util::KEY_VALUE_PAIRS_ATOM, getSimpleField(1)),
556                                 Value((int32_t)mLogUid));
557     }
558 }
559 
GetLong(size_t key,status_t * err) const560 int64_t LogEvent::GetLong(size_t key, status_t* err) const {
561     // TODO(b/110561208): encapsulate the magical operations in Field struct as static functions
562     int field = getSimpleField(key);
563     for (const auto& value : mValues) {
564         if (value.mField.getField() == field) {
565             if (value.mValue.getType() == LONG) {
566                 return value.mValue.long_value;
567             } else if (value.mValue.getType() == INT) {
568                 return value.mValue.int_value;
569             } else {
570                 *err = BAD_TYPE;
571                 return 0;
572             }
573         }
574         if ((size_t)value.mField.getPosAtDepth(0) > key) {
575             break;
576         }
577     }
578 
579     *err = BAD_INDEX;
580     return 0;
581 }
582 
GetInt(size_t key,status_t * err) const583 int LogEvent::GetInt(size_t key, status_t* err) const {
584     int field = getSimpleField(key);
585     for (const auto& value : mValues) {
586         if (value.mField.getField() == field) {
587             if (value.mValue.getType() == INT) {
588                 return value.mValue.int_value;
589             } else {
590                 *err = BAD_TYPE;
591                 return 0;
592             }
593         }
594         if ((size_t)value.mField.getPosAtDepth(0) > key) {
595             break;
596         }
597     }
598 
599     *err = BAD_INDEX;
600     return 0;
601 }
602 
GetString(size_t key,status_t * err) const603 const char* LogEvent::GetString(size_t key, status_t* err) const {
604     int field = getSimpleField(key);
605     for (const auto& value : mValues) {
606         if (value.mField.getField() == field) {
607             if (value.mValue.getType() == STRING) {
608                 return value.mValue.str_value.c_str();
609             } else {
610                 *err = BAD_TYPE;
611                 return 0;
612             }
613         }
614         if ((size_t)value.mField.getPosAtDepth(0) > key) {
615             break;
616         }
617     }
618 
619     *err = BAD_INDEX;
620     return NULL;
621 }
622 
GetBool(size_t key,status_t * err) const623 bool LogEvent::GetBool(size_t key, status_t* err) const {
624     int field = getSimpleField(key);
625     for (const auto& value : mValues) {
626         if (value.mField.getField() == field) {
627             if (value.mValue.getType() == INT) {
628                 return value.mValue.int_value != 0;
629             } else if (value.mValue.getType() == LONG) {
630                 return value.mValue.long_value != 0;
631             } else {
632                 *err = BAD_TYPE;
633                 return false;
634             }
635         }
636         if ((size_t)value.mField.getPosAtDepth(0) > key) {
637             break;
638         }
639     }
640 
641     *err = BAD_INDEX;
642     return false;
643 }
644 
GetFloat(size_t key,status_t * err) const645 float LogEvent::GetFloat(size_t key, status_t* err) const {
646     int field = getSimpleField(key);
647     for (const auto& value : mValues) {
648         if (value.mField.getField() == field) {
649             if (value.mValue.getType() == FLOAT) {
650                 return value.mValue.float_value;
651             } else {
652                 *err = BAD_TYPE;
653                 return 0.0;
654             }
655         }
656         if ((size_t)value.mField.getPosAtDepth(0) > key) {
657             break;
658         }
659     }
660 
661     *err = BAD_INDEX;
662     return 0.0;
663 }
664 
ToString() const665 string LogEvent::ToString() const {
666     string result;
667     result += StringPrintf("{ uid(%d) %lld %lld (%d)", mLogUid, (long long)mLogdTimestampNs,
668                            (long long)mElapsedTimestampNs, mTagId);
669     for (const auto& value : mValues) {
670         result +=
671                 StringPrintf("%#x", value.mField.getField()) + "->" + value.mValue.toString() + " ";
672     }
673     result += " }";
674     return result;
675 }
676 
ToProto(ProtoOutputStream & protoOutput) const677 void LogEvent::ToProto(ProtoOutputStream& protoOutput) const {
678     writeFieldValueTreeToStream(mTagId, getValues(), &protoOutput);
679 }
680 
writeExperimentIdsToProto(const std::vector<int64_t> & experimentIds,std::vector<uint8_t> * protoOut)681 void writeExperimentIdsToProto(const std::vector<int64_t>& experimentIds,
682                                std::vector<uint8_t>* protoOut) {
683     ProtoOutputStream proto;
684     for (const auto& expId : experimentIds) {
685         proto.write(FIELD_TYPE_INT64 | FIELD_COUNT_REPEATED | FIELD_ID_EXPERIMENT_ID,
686                     (long long)expId);
687     }
688 
689     protoOut->resize(proto.size());
690     size_t pos = 0;
691     sp<ProtoReader> reader = proto.data();
692     while (reader->readBuffer() != NULL) {
693         size_t toRead = reader->currentToRead();
694         std::memcpy(protoOut->data() + pos, reader->readBuffer(), toRead);
695         pos += toRead;
696         reader->move(toRead);
697     }
698 }
699 
700 }  // namespace statsd
701 }  // namespace os
702 }  // namespace android
703