Merge "Fix wallpaper placement + performance improvement"
diff --git a/Android.bp b/Android.bp
index 114ca2c..2dc1cc3 100644
--- a/Android.bp
+++ b/Android.bp
@@ -34,6 +34,11 @@
         include_dirs: ["external/protobuf/src"],
     },
 
+    cflags: [
+        "-Wall",
+        "-Werror",
+        "-Wno-unused-parameter",
+    ],
     target: {
         host: {
             proto: {
diff --git a/Android.mk b/Android.mk
index 4a57020..b5efd47 100644
--- a/Android.mk
+++ b/Android.mk
@@ -587,6 +587,17 @@
 	lowpan/java/android/net/lowpan/ILowpanManagerListener.aidl \
 	lowpan/java/android/net/lowpan/ILowpanManager.aidl
 
+# StatsLog generated functions
+statslog_src_dir := $(call intermediates-dir-for,JAVA_LIBRARIES,framework,,COMMON)/statslog
+gen := $(statslog_src_dir)/android/util/StatsLog.java
+$(gen): PRIVATE_PATH := $(LOCAL_PATH)
+$(gen): PRIVATE_CUSTOM_TOOL = $(HOST_OUT_EXECUTABLES)/stats-log-api-gen --java $@
+$(gen): $(HOST_OUT_EXECUTABLES)/stats-log-api-gen
+	$(transform-generated-source)
+LOCAL_GENERATED_SOURCES += $(gen)
+statslog_src_dir:=
+gen:=
+
 # FRAMEWORKS_BASE_JAVA_SRC_DIRS comes from build/core/pathmap.mk
 LOCAL_AIDL_INCLUDES += \
       $(FRAMEWORKS_BASE_JAVA_SRC_DIRS) \
diff --git a/cmds/am/Android.bp b/cmds/am/Android.bp
index 7eb4edf..bb16df1 100644
--- a/cmds/am/Android.bp
+++ b/cmds/am/Android.bp
@@ -4,6 +4,7 @@
 cc_library_host_static {
     name: "libinstrumentation",
     srcs: ["**/*.proto"],
+    cflags: ["-Wall", "-Werror"],
     proto: {
         type: "full",
         export_proto_headers: true,
diff --git a/cmds/incidentd/src/Privacy.cpp b/cmds/incidentd/src/Privacy.cpp
index e7969e7..140b12c 100644
--- a/cmds/incidentd/src/Privacy.cpp
+++ b/cmds/incidentd/src/Privacy.cpp
@@ -30,6 +30,9 @@
 bool
 Privacy::IsMessageType() const { return type == TYPE_MESSAGE; }
 
+uint64_t
+Privacy::EncodedFieldId() const { return (uint64_t)type << 32 | field_id; }
+
 bool
 Privacy::IsStringType() const { return type == TYPE_STRING; }
 
diff --git a/cmds/incidentd/src/Privacy.h b/cmds/incidentd/src/Privacy.h
index 7f1977e..f514f19 100644
--- a/cmds/incidentd/src/Privacy.h
+++ b/cmds/incidentd/src/Privacy.h
@@ -40,6 +40,8 @@
     bool IsMessageType() const;
     bool IsStringType() const;
     bool HasChildren() const;
+    uint64_t EncodedFieldId() const;
+
     const Privacy* lookup(uint32_t fieldId) const;
 };
 
diff --git a/cmds/incidentd/src/PrivacyBuffer.cpp b/cmds/incidentd/src/PrivacyBuffer.cpp
index 37f6ed7..a095afc 100644
--- a/cmds/incidentd/src/PrivacyBuffer.cpp
+++ b/cmds/incidentd/src/PrivacyBuffer.cpp
@@ -28,37 +28,41 @@
  * Write the field to buf based on the wire type, iterator will point to next field.
  * If skip is set to true, no data will be written to buf. Return number of bytes written.
  */
-static size_t
-write_field_or_skip(EncodedBuffer::iterator* iter, EncodedBuffer* buf, uint8_t wireType, bool skip)
+void
+PrivacyBuffer::writeFieldOrSkip(uint32_t fieldTag, bool skip)
 {
-    EncodedBuffer::Pointer snapshot = iter->rp()->copy();
+    uint8_t wireType = read_wire_type(fieldTag);
     size_t bytesToWrite = 0;
-    uint64_t varint = 0;
+    uint32_t varint = 0;
+
     switch (wireType) {
         case WIRE_TYPE_VARINT:
-            varint = iter->readRawVarint();
-            if(!skip) return buf->writeRawVarint64(varint);
-            break;
+            varint = mData.readRawVarint();
+            if (!skip) {
+                mProto.writeRawVarint(fieldTag);
+                mProto.writeRawVarint(varint);
+            }
+            return;
         case WIRE_TYPE_FIXED64:
+            if (!skip) mProto.writeRawVarint(fieldTag);
             bytesToWrite = 8;
             break;
         case WIRE_TYPE_LENGTH_DELIMITED:
-            bytesToWrite = iter->readRawVarint();
-            if(!skip) buf->writeRawVarint32(bytesToWrite);
+            bytesToWrite = mData.readRawVarint();
+            if(!skip) mProto.writeLengthDelimitedHeader(read_field_id(fieldTag), bytesToWrite);
             break;
         case WIRE_TYPE_FIXED32:
+            if (!skip) mProto.writeRawVarint(fieldTag);
             bytesToWrite = 4;
             break;
     }
     if (skip) {
-        iter->rp()->move(bytesToWrite);
+        mData.rp()->move(bytesToWrite);
     } else {
         for (size_t i=0; i<bytesToWrite; i++) {
-            *buf->writeBuffer() = iter->next();
-            buf->wp()->move();
+            mProto.writeRawByte(mData.next());
         }
     }
-    return skip ? 0 : iter->rp()->pos() - snapshot.pos();
 }
 
 /**
@@ -68,46 +72,27 @@
  * The iterator must point to the head of a protobuf formatted field for successful operation.
  * After exit with NO_ERROR, iterator points to the next protobuf field's head.
  */
-static status_t
-stripField(EncodedBuffer::iterator* iter, EncodedBuffer* buf, const Privacy* parentPolicy, const PrivacySpec& spec)
+status_t
+PrivacyBuffer::stripField(const Privacy* parentPolicy, const PrivacySpec& spec)
 {
-    if (!iter->hasNext() || parentPolicy == NULL) return BAD_VALUE;
-    uint32_t varint = iter->readRawVarint();
-    uint8_t wireType = read_wire_type(varint);
-    uint32_t fieldId = read_field_id(varint);
-    const Privacy* policy = parentPolicy->lookup(fieldId);
+    if (!mData.hasNext() || parentPolicy == NULL) return BAD_VALUE;
+    uint32_t fieldTag = mData.readRawVarint();
+    const Privacy* policy = parentPolicy->lookup(read_field_id(fieldTag));
+
     if (policy == NULL || !policy->IsMessageType() || !policy->HasChildren()) {
         bool skip = !spec.CheckPremission(policy);
-        size_t amt = buf->size();
-        if (!skip) amt += buf->writeHeader(fieldId, wireType);
-        amt += write_field_or_skip(iter, buf, wireType, skip); // point to head of next field
-        return buf->size() != amt ? BAD_VALUE : NO_ERROR;
+        // iterator will point to head of next field
+        writeFieldOrSkip(fieldTag, skip);
+        return NO_ERROR;
     }
     // current field is message type and its sub-fields have extra privacy policies
-    deque<EncodedBuffer*> q;
-    uint32_t msgSize = iter->readRawVarint();
-    size_t finalSize = 0;
-    EncodedBuffer::Pointer start = iter->rp()->copy();
-    while (iter->rp()->pos() - start.pos() != msgSize) {
-        EncodedBuffer* v = new EncodedBuffer();
-        status_t err = stripField(iter, v, policy, spec);
+    uint32_t msgSize = mData.readRawVarint();
+    EncodedBuffer::Pointer start = mData.rp()->copy();
+    while (mData.rp()->pos() - start.pos() != msgSize) {
+        long long token = mProto.start(policy->EncodedFieldId());
+        status_t err = stripField(policy, spec);
         if (err != NO_ERROR) return err;
-        if (v->size() == 0) continue;
-        q.push_back(v);
-        finalSize += v->size();
-    }
-
-    buf->writeHeader(fieldId, wireType);
-    buf->writeRawVarint32(finalSize);
-    while (!q.empty()) {
-        EncodedBuffer* subField = q.front();
-        EncodedBuffer::iterator it = subField->begin();
-        while (it.hasNext()) {
-            *buf->writeBuffer() = it.next();
-            buf->wp()->move();
-        }
-        q.pop_front();
-        delete subField;
+        mProto.end(token);
     }
     return NO_ERROR;
 }
@@ -116,7 +101,7 @@
 PrivacyBuffer::PrivacyBuffer(const Privacy* policy, EncodedBuffer::iterator& data)
         :mPolicy(policy),
          mData(data),
-         mBuffer(0),
+         mProto(),
          mSize(0)
 {
 }
@@ -134,11 +119,11 @@
         return NO_ERROR;
     }
     while (mData.hasNext()) {
-        status_t err = stripField(&mData, &mBuffer, mPolicy, spec);
+        status_t err = stripField(mPolicy, spec);
         if (err != NO_ERROR) return err;
     }
     if (mData.bytesRead() != mData.size()) return BAD_VALUE;
-    mSize = mBuffer.size();
+    mSize = mProto.size();
     mData.rp()->rewind(); // rewind the read pointer back to beginning after the strip.
     return NO_ERROR;
 }
@@ -147,7 +132,7 @@
 PrivacyBuffer::clear()
 {
     mSize = 0;
-    mBuffer.wp()->rewind();
+    mProto = ProtoOutputStream();
 }
 
 size_t
@@ -157,7 +142,7 @@
 PrivacyBuffer::flush(int fd)
 {
     status_t err = NO_ERROR;
-    EncodedBuffer::iterator iter = size() == mData.size() ? mData : mBuffer.begin();
+    EncodedBuffer::iterator iter = size() == mData.size() ? mData : mProto.data();
     while (iter.readBuffer() != NULL) {
         err = write_all(fd, iter.readBuffer(), iter.currentToRead());
         iter.rp()->move(iter.currentToRead());
diff --git a/cmds/incidentd/src/PrivacyBuffer.h b/cmds/incidentd/src/PrivacyBuffer.h
index 720b38e..c9ca9a7 100644
--- a/cmds/incidentd/src/PrivacyBuffer.h
+++ b/cmds/incidentd/src/PrivacyBuffer.h
@@ -20,6 +20,7 @@
 #include "Privacy.h"
 
 #include <android/util/EncodedBuffer.h>
+#include <android/util/ProtoOutputStream.h>
 #include <stdint.h>
 #include <utils/Errors.h>
 
@@ -60,8 +61,11 @@
     const Privacy* mPolicy;
     EncodedBuffer::iterator& mData;
 
-    EncodedBuffer mBuffer;
+    ProtoOutputStream mProto;
     size_t mSize;
+
+    status_t stripField(const Privacy* parentPolicy, const PrivacySpec& spec);
+    void writeFieldOrSkip(uint32_t fieldTag, bool skip);
 };
 
 #endif // PRIVACY_BUFFER_H
\ No newline at end of file
diff --git a/cmds/statsd/Android.bp b/cmds/statsd/Android.bp
new file mode 100644
index 0000000..5586057
--- /dev/null
+++ b/cmds/statsd/Android.bp
@@ -0,0 +1,37 @@
+//
+// Copyright (C) 2015 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+// ==========================================================
+// Build the library for use on the host
+// ==========================================================
+cc_library_host_shared {
+    name: "libstats_proto_host",
+    srcs: [
+        "src/stats_events.proto",
+        "src/stats_log.proto",
+        "src/statsd_config.proto",
+    ],
+
+    shared_libs: [
+        "libplatformprotos",
+    ],
+
+    proto: {
+        type: "full",
+        export_proto_headers: true,
+    },
+}
+
diff --git a/cmds/statsd/Android.mk b/cmds/statsd/Android.mk
index 4c95007..d9c37ef 100644
--- a/cmds/statsd/Android.mk
+++ b/cmds/statsd/Android.mk
@@ -14,22 +14,51 @@
 
 LOCAL_PATH:= $(call my-dir)
 
-# ================
-# proto static lib
-# ================
-include $(CLEAR_VARS)
 
-LOCAL_MODULE := statsd_proto
-LOCAL_MODULE_TAGS := optional
+statsd_common_src := \
+    ../../core/java/android/os/IStatsCompanionService.aidl \
+    ../../core/java/android/os/IStatsManager.aidl \
+    src/stats_log.proto \
+    src/statsd_config.proto \
+    src/stats_events.proto \
+    src/condition/CombinationConditionTracker.cpp \
+    src/condition/condition_util.cpp \
+    src/condition/SimpleConditionTracker.cpp \
+    src/matchers/CombinationLogMatchingTracker.cpp \
+    src/matchers/matcher_util.cpp \
+    src/matchers/SimpleLogMatchingTracker.cpp \
+    src/metrics/CountAnomalyTracker.cpp \
+    src/metrics/CountMetricProducer.cpp \
+    src/metrics/MetricsManager.cpp \
+    src/metrics/metrics_manager_util.cpp \
+    src/AnomalyMonitor.cpp \
+    src/DropboxReader.cpp \
+    src/DropboxWriter.cpp \
+    src/KernelWakelockPuller.cpp \
+    src/LogEntryPrinter.cpp \
+    src/LogReader.cpp \
+    src/StatsLogProcessor.cpp \
+    src/StatsPullerManager.cpp \
+    src/StatsService.cpp \
+    src/stats_util.cpp \
+    src/UidMap.cpp
 
-LOCAL_SRC_FILES := $(call all-proto-files-under, src)
+statsd_common_c_includes := \
+    $(LOCAL_PATH)/src
 
-LOCAL_PROTOC_FLAGS :=
-LOCAL_PROTOC_OPTIMIZE_TYPE := lite-static
+statsd_common_aidl_includes := \
+    $(LOCAL_PATH)/../../core/java
 
-include $(BUILD_STATIC_LIBRARY)
-
-STATSD_PROTO_INCLUDES := $(local-generated-sources-dir)/src/$(LOCAL_PATH)
+statsd_common_shared_libraries := \
+    libbase \
+    libbinder \
+    libcutils \
+    libincident \
+    liblog \
+    libselinux \
+    libutils \
+    libservices \
+    libandroidfw
 
 # =========
 # statsd
@@ -40,9 +69,8 @@
 LOCAL_MODULE := statsd
 
 LOCAL_SRC_FILES := \
-    ../../core/java/android/os/IStatsCompanionService.aidl \
-    ../../core/java/android/os/IStatsManager.aidl \
-    $(call all-cpp-files-under,src) \
+    $(statsd_common_src) \
+    src/main.cpp
 
 LOCAL_CFLAGS += \
     -Wall \
@@ -60,24 +88,12 @@
     LOCAL_CFLAGS += \
             -Os
 endif
+LOCAL_PROTOC_OPTIMIZE_TYPE := lite-static
 
-LOCAL_AIDL_INCLUDES := $(LOCAL_PATH)/../../core/java
-LOCAL_C_INCLUDES += $(LOCAL_PATH)/src \
-	STATSD_PROTO_INCLUDES
+LOCAL_AIDL_INCLUDES := $(statsd_common_c_includes)
+LOCAL_C_INCLUDES += $(statsd_common_c_includes)
 
-LOCAL_STATIC_LIBRARIES := statsd_proto
-
-LOCAL_SHARED_LIBRARIES := \
-        libbase \
-        libbinder \
-        libcutils \
-        libincident \
-        liblog \
-        libselinux \
-        libutils \
-        libservices \
-        libandroidfw \
-        libprotobuf-cpp-lite \
+LOCAL_SHARED_LIBRARIES := $(statsd_common_shared_libraries)
 
 LOCAL_MODULE_CLASS := EXECUTABLES
 
@@ -85,6 +101,7 @@
 
 include $(BUILD_EXECUTABLE)
 
+
 # ==============
 # statsd_test
 # ==============
@@ -95,8 +112,8 @@
 LOCAL_COMPATIBILITY_SUITE := device-tests
 LOCAL_MODULE_TAGS := tests
 
-LOCAL_C_INCLUDES += $(LOCAL_PATH)/src \
-	STATSD_PROTO_INCLUDES
+LOCAL_AIDL_INCLUDES := $(statsd_common_c_includes)
+LOCAL_C_INCLUDES += $(statsd_common_c_includes)
 
 LOCAL_CFLAGS += \
     -Wall \
@@ -107,38 +124,25 @@
     -Wno-unused-parameter
 
 LOCAL_SRC_FILES := \
-    src/stats_log.proto \
-    src/statsd_config.proto \
-    ../../core/java/android/os/IStatsCompanionService.aidl \
-    ../../core/java/android/os/IStatsManager.aidl \
-    src/StatsService.cpp \
-    src/AnomalyMonitor.cpp \
-    src/stats_util.cpp \
-    src/LogEntryPrinter.cpp \
-    src/LogReader.cpp \
-    src/matchers/matcher_util.cpp \
-    src/condition/SimpleConditionTracker.cpp \
-    src/condition/CombinationConditionTracker.cpp \
-    src/matchers/SimpleLogMatchingTracker.cpp \
-    src/matchers/CombinationLogMatchingTracker.cpp \
-    src/metrics/metrics_manager_util.cpp \
-    src/metrics/CountMetricProducer.cpp \
-    src/metrics/CountAnomalyTracker.cpp \
-    src/condition/condition_util.cpp \
-    src/UidMap.cpp \
-    $(call all-cpp-files-under, tests) \
+    $(statsd_common_src) \
+    tests/indexed_priority_queue_test.cpp \
+    tests/LogReader_test.cpp \
+    tests/MetricsManager_test.cpp \
+    tests/UidMap_test.cpp \
+    tests/LogEntryMatcher_test.cpp \
+    tests/AnomalyMonitor_test.cpp \
+    tests/ConditionTracker_test.cpp
 
 LOCAL_STATIC_LIBRARIES := \
-    libgmock \
-    statsd_proto \
+    libgmock
 
-LOCAL_SHARED_LIBRARIES := \
-    libbase \
-    libbinder \
-    libcutils \
-    liblog \
-    libselinux \
-    libutils \
-    libprotobuf-cpp-lite \
+LOCAL_SHARED_LIBRARIES := $(statsd_common_shared_libraries)
+
+LOCAL_PROTOC_OPTIMIZE_TYPE := lite
+
+statsd_common_src:=
+statsd_common_aidl_includes:=
+statsd_common_c_includes:=
 
 include $(BUILD_NATIVE_TEST)
+
diff --git a/cmds/statsd/src/LogEntryPrinter.cpp b/cmds/statsd/src/LogEntryPrinter.cpp
index 63465b0..3b6f679 100644
--- a/cmds/statsd/src/LogEntryPrinter.cpp
+++ b/cmds/statsd/src/LogEntryPrinter.cpp
@@ -20,6 +20,11 @@
 #include <log/logprint.h>
 #include <utils/Errors.h>
 
+#include "matchers/matcher_util.h"
+
+#define PRINT_WITH_LIBLOG 0
+#define PRINT_WITH_LOG_EVENT_WRAPPER 1
+
 using namespace android;
 
 namespace android {
@@ -44,16 +49,24 @@
 }
 
 void LogEntryPrinter::OnLogEvent(const log_msg& msg) {
-    status_t err;
-    AndroidLogEntry entry;
-    char buf[1024];
+    if (PRINT_WITH_LIBLOG) {
+        status_t err;
+        AndroidLogEntry entry;
+        char buf[1024];
 
-    err = android_log_processBinaryLogBuffer(&(const_cast<log_msg*>(&msg)->entry_v1), &entry,
-                                             m_tags, buf, sizeof(buf));
-    if (err == NO_ERROR) {
-        android_log_printLogLine(m_format, m_out, &entry);
-    } else {
-        printf("log entry: %s\n", buf);
+        err = android_log_processBinaryLogBuffer(&(const_cast<log_msg*>(&msg)->entry_v1), &entry,
+                                                 m_tags, buf, sizeof(buf));
+        if (err == NO_ERROR) {
+            android_log_printLogLine(m_format, m_out, &entry);
+        } else {
+            printf("log entry: %s\n", buf);
+            fflush(stdout);
+        }
+    }
+
+    if (PRINT_WITH_LOG_EVENT_WRAPPER) {
+        LogEventWrapper event = parseLogEvent(msg);
+        printf("event: %s\n", event.toString().c_str());
         fflush(stdout);
     }
 }
diff --git a/cmds/statsd/src/matchers/matcher_util.cpp b/cmds/statsd/src/matchers/matcher_util.cpp
index 557c032..3308f3a 100644
--- a/cmds/statsd/src/matchers/matcher_util.cpp
+++ b/cmds/statsd/src/matchers/matcher_util.cpp
@@ -26,8 +26,11 @@
 #include "frameworks/base/cmds/statsd/src/statsd_config.pb.h"
 #include "stats_util.h"
 
+#include <sstream>
+
 using std::set;
 using std::string;
+using std::ostringstream;
 using std::unordered_map;
 using std::vector;
 
@@ -35,6 +38,42 @@
 namespace os {
 namespace statsd {
 
+string LogEventWrapper::toString() const {
+    std::ostringstream result;
+    result << "{ " << timestamp_ns << " (" << tagId << ")";
+    for (int index = 1; ; index++) {
+        auto intVal = intMap.find(index);
+        auto strVal = strMap.find(index);
+        auto boolVal = boolMap.find(index);
+        auto floatVal = floatMap.find(index);
+        if (intVal != intMap.end()) {
+            result << " ";
+            result << std::to_string(index);
+            result << "->";
+            result << std::to_string(intVal->second);
+        } else if (strVal != strMap.end()) {
+            result << " ";
+            result << std::to_string(index);
+            result << "->";
+            result << strVal->second;
+        } else if (boolVal != boolMap.end()) {
+            result << " ";
+            result << std::to_string(index);
+            result << "->";
+            result << std::to_string(boolVal->second);
+        } else if (floatVal != floatMap.end()) {
+            result << " ";
+            result << std::to_string(index);
+            result << "->";
+            result << std::to_string(floatVal->second);
+        } else {
+            break;
+        }
+    }
+    result << " }";
+    return result.str();
+}
+
 LogEventWrapper parseLogEvent(log_msg msg) {
     LogEventWrapper wrapper;
     wrapper.timestamp_ns = msg.entry_v1.sec * NS_PER_SEC + msg.entry_v1.nsec;
@@ -48,38 +87,32 @@
 
     if (context) {
         memset(&elem, 0, sizeof(elem));
-        size_t index = 0;
-        int32_t key = -1;
+        // TODO: The log is actually structured inside one list.  This is convenient
+        // because we'll be able to use it to put the attribution (WorkSource) block first
+        // without doing our own tagging scheme.  Until that change is in, just drop the
+        // list-related log elements and the order we get there is our index-keyed data
+        // structure.
+        int32_t key = 1;
         do {
             elem = android_log_read_next(context);
             switch ((int)elem.type) {
                 case EVENT_TYPE_INT:
-                    if (index % 2 == 0) {
-                        key = elem.data.int32;
-                    } else {
-                        wrapper.intMap[key] = elem.data.int32;
-                    }
-                    index++;
+                    wrapper.intMap[key] = elem.data.int32;
+                    key++;
                     break;
                 case EVENT_TYPE_FLOAT:
-                    if (index % 2 == 1) {
-                        wrapper.floatMap[key] = elem.data.float32;
-                    }
-                    index++;
+                    wrapper.floatMap[key] = elem.data.float32;
+                    key++;
                     break;
                 case EVENT_TYPE_STRING:
-                    if (index % 2 == 1) {
-                        // without explicit calling string() constructor, there will be an
-                        // additional 0 in the end of the string.
-                        wrapper.strMap[key] = string(elem.data.string);
-                    }
-                    index++;
+                    // without explicit calling string() constructor, there will be an
+                    // additional 0 in the end of the string.
+                    wrapper.strMap[key] = string(elem.data.string);
+                    key++;
                     break;
                 case EVENT_TYPE_LONG:
-                    if (index % 2 == 1) {
-                        wrapper.intMap[key] = elem.data.int64;
-                    }
-                    index++;
+                    wrapper.intMap[key] = elem.data.int64;
+                    key++;
                     break;
                 case EVENT_TYPE_LIST:
                     break;
@@ -91,10 +124,6 @@
                     elem.complete = true;
                     break;
             }
-
-            if (elem.complete) {
-                break;
-            }
         } while ((elem.type != EVENT_TYPE_UNKNOWN) && !elem.complete);
 
         android_log_destroy(&context);
diff --git a/cmds/statsd/src/matchers/matcher_util.h b/cmds/statsd/src/matchers/matcher_util.h
index 6d8e762..ac17bbe 100644
--- a/cmds/statsd/src/matchers/matcher_util.h
+++ b/cmds/statsd/src/matchers/matcher_util.h
@@ -20,6 +20,7 @@
 #include <log/log_read.h>
 #include <log/logprint.h>
 #include <set>
+#include <string>
 #include <unordered_map>
 #include <vector>
 #include "frameworks/base/cmds/statsd/src/stats_log.pb.h"
@@ -36,6 +37,8 @@
     std::unordered_map<int, std::string> strMap;
     std::unordered_map<int, bool> boolMap;
     std::unordered_map<int, float> floatMap;
+
+    std::string toString() const;
 } LogEventWrapper;
 
 enum MatchingState {
diff --git a/cmds/statsd/src/stats_events.proto b/cmds/statsd/src/stats_events.proto
index 1e17895..cd00ba8 100644
--- a/cmds/statsd/src/stats_events.proto
+++ b/cmds/statsd/src/stats_events.proto
@@ -15,49 +15,116 @@
  */
 
 syntax = "proto2";
-option optimize_for = LITE_RUNTIME;
 
+// TODO: Not the right package and class name
 package android.os.statsd;
-
 option java_package = "com.android.os";
 option java_outer_classname = "StatsEventProto";
 
+/**
+ * The master event class. This message defines all of the available
+ * raw stats log events from the Android system, also known as "atoms."
+ *
+ * This field contains a single oneof with all of the available messages.
+ * The stats-log-api-gen tool runs as part of the Android build and
+ * generates the android.util.StatsLog class, which contains the constants
+ * and methods that Android uses to log.
+ *
+ * This StatsEvent class is not actually built into the Android system.
+ * Instead, statsd on Android constructs these messages synthetically,
+ * in the format defined here and in stats_log.proto.
+ */
 message StatsEvent {
-  oneof event {
-    // Screen state change.
-    ScreenStateChange screen_state_change = 2;
-    // Process state change.
-    ProcessStateChange process_state_change = 1112;
-  }
+    oneof event {
+        ScreenStateChanged screen_state_changed = 1;
+        ProcessStateChanged process_state_changed = 2;
+        WakeLockChanged wakelock_changed = 3;
+    }
 }
 
-// Logs changes in screen state. This event is logged in
-// frameworks/base/services/core/java/com/android/server/am/BatteryStatsService.java
-message ScreenStateChange {
-  // Screen state enums follow the values defined in below file.
-  // frameworks/base/core/java/android/view/Display.java
-  enum State {
-    STATE_UNKNOWN = 0;
-    STATE_OFF = 1;
-    STATE_ON = 2;
-    STATE_DOZE = 3;
-    STATE_DOZE_SUSPEND = 4;
-    STATE_VR = 5;
-  }
-  // New screen state.
-  optional State display_state = 1;
+/**
+ * A WorkSource represents the chained attribution of applications that
+ * resulted in a particular bit of work being done.
+ */
+message WorkSource {
+    // TODO
 }
 
-// Logs changes in process state. This event is logged in
-// frameworks/base/services/core/java/com/android/server/am/BatteryStatsService.java
-message ProcessStateChange {
-  // Type of process event.
-  enum State {
-    START = 1;
-    CRASH = 2;
-  }
-  optional State state = 1;
+/*
+ * *****************************************************************************
+ * Below are all of the individual atoms that are logged by Android via statsd
+ * and Westworld.
+ *
+ * RULES:
+ *   - The field ids for each atom must start at 1, and count upwards by 1.
+ *     Skipping field ids is not allowed.
+ *   - These form an API, so renaming, renumbering or removing fields is
+ *     not allowed between android releases.  (This is not currently enforced,
+ *     but there will be a tool to enforce this restriction).
+ *   - The types must be built-in protocol buffer types, namely, no sub-messages
+ *     are allowed (yet).  The bytes type is also not allowed.
+ *   - The CamelCase name of the message type should match the
+ *     underscore_separated name as defined in StatsEvent.
+ *   - If an atom represents work that can be attributed to an app, there can
+ *     be exactly one WorkSource field. It must be field number 1.
+ *   - A field that is a uid should be a string field, tagged with the [xxx]
+ *     annotation. The generated code on android will be represented by UIDs,
+ *     and those UIDs will be translated in xxx to those strings.
+ *
+ * CONVENTIONS:
+ *   - Events are past tense. e.g. ScreenStateChanged, not ScreenStateChange
+ *   - If there is a UID, it goes first. Think in an object-oriented fashion.
+ * *****************************************************************************
+ */
 
-  // UID associated with the package.
-  optional int32 uid = 2;
+/**
+ * Logs when the screen state changes.
+ *
+ * Logged from:
+ *   frameworks/base/services/core/java/com/android/server/am/BatteryStatsService.java
+ */
+message ScreenStateChanged {
+    // TODO: Use the real screen state.
+    enum State {
+        STATE_UNKNOWN = 0;
+        STATE_OFF = 1;
+        STATE_ON = 2;
+        STATE_DOZE = 3;
+        STATE_DOZE_SUSPEND = 4;
+        STATE_VR = 5;
+    }
+    // New screen state.
+    optional State display_state = 1;
 }
+
+/**
+ * Logs that the state of a process state, as per the activity manager has changed.
+ *
+ * Logged from:
+ *   frameworks/base/services/core/java/com/android/server/am/BatteryStatsService.java
+ */
+message ProcessStateChanged {
+    // TODO: Use the real (mapped) process states.
+    optional int32 uid = 1; // TODO: should be a string tagged w/ uid annotation
+
+    // The state.
+    optional int32 state = 2;
+}
+
+/**
+ * Logs that the state of a wakelock has changed.
+ *
+ * Logged from:
+ *   TODO
+ */
+message WakeLockChanged {
+    // TODO: Add attribution instead of uid.
+    optional int32 uid = 1;
+
+    // The wakelock tag (Called tag in the Java API, sometimes name elsewhere).
+    optional string tag = 2;
+
+    // TODO: Use a constant instead of boolean?
+    optional bool state = 3;
+}
+
diff --git a/core/java/android/util/StatsLog.java b/core/java/android/util/StatsLog.java
deleted file mode 100644
index 0be1a8c..0000000
--- a/core/java/android/util/StatsLog.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.util;
-
-/**
- * Logging access for platform metrics.
- *
- * <p>This is <b>not</b> the main "logcat" debugging log ({@link android.util.Log})!
- * These diagnostic stats are for system integrators, not application authors.
- *
- * <p>Stats use integer tag codes.
- * They carry a payload of one or more int, long, or String values.
- * @hide
- */
-public class StatsLog {
-    /** @hide */ public StatsLog() {}
-
-    private static final String TAG = "StatsLog";
-
-    // We assume that the native methods deal with any concurrency issues.
-
-    /**
-     * Records an stats log message.
-     * @param tag The stats type tag code
-     * @param value A value to log
-     * @return The number of bytes written
-     */
-    public static native int writeInt(int tag, int value);
-
-    /**
-     * Records an stats log message.
-     * @param tag The stats type tag code
-     * @param value A value to log
-     * @return The number of bytes written
-     */
-    public static native int writeLong(int tag, long value);
-
-    /**
-     * Records an stats log message.
-     * @param tag The stats type tag code
-     * @param value A value to log
-     * @return The number of bytes written
-     */
-    public static native int writeFloat(int tag, float value);
-
-    /**
-     * Records an stats log message.
-     * @param tag The stats type tag code
-     * @param str A value to log
-     * @return The number of bytes written
-     */
-    public static native int writeString(int tag, String str);
-
-    /**
-     * Records an stats log message.
-     * @param tag The stats type tag code
-     * @param list A list of values to log. All values should
-     * be of type int, long, float or String.
-     * @return The number of bytes written
-     */
-    public static native int writeArray(int tag, Object... list);
-}
diff --git a/core/java/android/util/StatsLogKey.java b/core/java/android/util/StatsLogKey.java
deleted file mode 100644
index 9ad0a23..0000000
--- a/core/java/android/util/StatsLogKey.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-// THIS FILE IS AUTO-GENERATED.
-// DO NOT MODIFY.
-
-package android.util;
-
-/** @hide */
-public class StatsLogKey {
-    private StatsLogKey() {}
-
-    /** Constants for android.os.statsd.ScreenStateChange. */
-
-    /** display_state */
-    public static final int SCREEN_STATE_CHANGE__DISPLAY_STATE = 1;
-
-    /** Constants for android.os.statsd.ProcessStateChange. */
-
-    /** state */
-    public static final int PROCESS_STATE_CHANGE__STATE = 1;
-
-    /** uid */
-    public static final int PROCESS_STATE_CHANGE__UID = 2;
-
-    /** package_name */
-    public static final int PROCESS_STATE_CHANGE__PACKAGE_NAME = 1002;
-
-    /** package_version */
-    public static final int PROCESS_STATE_CHANGE__PACKAGE_VERSION = 3;
-
-    /** package_version_string */
-    public static final int PROCESS_STATE_CHANGE__PACKAGE_VERSION_STRING = 4;
-
-}
diff --git a/core/java/android/util/StatsLogTag.java b/core/java/android/util/StatsLogTag.java
deleted file mode 100644
index 5e5a828..0000000
--- a/core/java/android/util/StatsLogTag.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-// THIS FILE IS AUTO-GENERATED.
-// DO NOT MODIFY.
-
-package android.util;
-
-/** @hide */
-public class StatsLogTag {
-    private StatsLogTag() {}
-
-    /** android.os.statsd.ScreenStateChange. */
-    public static final int SCREEN_STATE_CHANGE = 2;
-
-    /** android.os.statsd.ProcessStateChange. */
-    public static final int PROCESS_STATE_CHANGE = 1112;
-
-}
diff --git a/core/java/android/util/StatsLogValue.java b/core/java/android/util/StatsLogValue.java
deleted file mode 100644
index 05b9d93..0000000
--- a/core/java/android/util/StatsLogValue.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-// THIS FILE IS AUTO-GENERATED.
-// DO NOT MODIFY.
-
-package android.util;
-
-/** @hide */
-public class StatsLogValue {
-    private StatsLogValue() {}
-
-    /** Constants for android.os.statsd.ScreenStateChange. */
-
-    /** display_state: STATE_UNKNOWN */
-    public static final int SCREEN_STATE_CHANGE__DISPLAY_STATE__STATE_UNKNOWN = 0;
-
-    /** display_state: STATE_OFF */
-    public static final int SCREEN_STATE_CHANGE__DISPLAY_STATE__STATE_OFF = 1;
-
-    /** display_state: STATE_ON */
-    public static final int SCREEN_STATE_CHANGE__DISPLAY_STATE__STATE_ON = 2;
-
-    /** display_state: STATE_DOZE */
-    public static final int SCREEN_STATE_CHANGE__DISPLAY_STATE__STATE_DOZE = 3;
-
-    /** display_state: STATE_DOZE_SUSPEND */
-    public static final int SCREEN_STATE_CHANGE__DISPLAY_STATE__STATE_DOZE_SUSPEND = 4;
-
-    /** display_state: STATE_VR */
-    public static final int SCREEN_STATE_CHANGE__DISPLAY_STATE__STATE_VR = 5;
-
-    /** Constants for android.os.statsd.ProcessStateChange. */
-
-    /** state: START */
-    public static final int PROCESS_STATE_CHANGE__STATE__START = 1;
-
-    /** state: CRASH */
-    public static final int PROCESS_STATE_CHANGE__STATE__CRASH = 2;
-
-}
diff --git a/core/java/com/android/internal/os/BatteryStatsImpl.java b/core/java/com/android/internal/os/BatteryStatsImpl.java
index dd07ddb..5c310b1 100644
--- a/core/java/com/android/internal/os/BatteryStatsImpl.java
+++ b/core/java/com/android/internal/os/BatteryStatsImpl.java
@@ -119,7 +119,7 @@
     private static final int MAGIC = 0xBA757475; // 'BATSTATS'
 
     // Current on-disk Parcel version
-    private static final int VERSION = 167 + (USE_OLD_HISTORY ? 1000 : 0);
+    private static final int VERSION = 168 + (USE_OLD_HISTORY ? 1000 : 0);
 
     // Maximum number of items we will record in the history.
     private static final int MAX_HISTORY_ITEMS;
@@ -13118,7 +13118,7 @@
                 }
             }
         } else {
-            // TODO: There should be two 0's printed here, not just one.
+            out.writeInt(0);
             out.writeInt(0);
         }
 
diff --git a/core/jni/Android.bp b/core/jni/Android.bp
index 256b920..928626b 100644
--- a/core/jni/Android.bp
+++ b/core/jni/Android.bp
@@ -1,3 +1,13 @@
+
+genrule {
+    name: "android_util_StatsLog.cpp",
+    tools: ["stats-log-api-gen"],
+    cmd: "$(location stats-log-api-gen) --jni $(genDir)/android_util_StatsLog.cpp",
+    out: [
+        "android_util_StatsLog.cpp",
+    ],
+}
+
 cc_library_shared {
     name: "libandroid_runtime",
 
@@ -104,7 +114,6 @@
         "android_nio_utils.cpp",
         "android_util_AssetManager.cpp",
         "android_util_Binder.cpp",
-	"android_util_StatsLog.cpp",
         "android_util_EventLog.cpp",
         "android_util_MemoryIntArray.cpp",
         "android_util_Log.cpp",
@@ -271,11 +280,13 @@
         "libhwbinder",
         "libvintf",
         "libnativewindow",
-
         "libhwui",
         "libdl",
+        "libstatslog",
     ],
 
+    generated_sources: ["android_util_StatsLog.cpp"],
+
     local_include_dirs: ["android/graphics"],
     export_include_dirs: [
         ".",
diff --git a/core/jni/AndroidRuntime.cpp b/core/jni/AndroidRuntime.cpp
index e312478..da6d5aa 100644
--- a/core/jni/AndroidRuntime.cpp
+++ b/core/jni/AndroidRuntime.cpp
@@ -612,6 +612,8 @@
     char gctypeOptsBuf[sizeof("-Xgc:")-1 + PROPERTY_VALUE_MAX];
     char backgroundgcOptsBuf[sizeof("-XX:BackgroundGC=")-1 + PROPERTY_VALUE_MAX];
     char heaptargetutilizationOptsBuf[sizeof("-XX:HeapTargetUtilization=")-1 + PROPERTY_VALUE_MAX];
+    char foregroundHeapGrowthMultiplierOptsBuf[
+            sizeof("-XX:ForegroundHeapGrowthMultiplier=")-1 + PROPERTY_VALUE_MAX];
     char cachePruneBuf[sizeof("-Xzygote-max-boot-retry=")-1 + PROPERTY_VALUE_MAX];
     char dex2oatXmsImageFlagsBuf[sizeof("-Xms")-1 + PROPERTY_VALUE_MAX];
     char dex2oatXmxImageFlagsBuf[sizeof("-Xmx")-1 + PROPERTY_VALUE_MAX];
@@ -715,6 +717,11 @@
                        heaptargetutilizationOptsBuf,
                        "-XX:HeapTargetUtilization=");
 
+    /* Foreground heap growth multiplier option */
+    parseRuntimeOption("dalvik.vm.foreground-heap-growth-multiplier",
+                       foregroundHeapGrowthMultiplierOptsBuf,
+                       "-XX:ForegroundHeapGrowthMultiplier=");
+
     /*
      * JIT related options.
      */
@@ -1317,10 +1324,10 @@
     REG_JNI(register_com_android_internal_os_ZygoteInit_nativeZygoteInit),
     REG_JNI(register_android_os_SystemClock),
     REG_JNI(register_android_util_EventLog),
-    REG_JNI(register_android_util_StatsLog),
     REG_JNI(register_android_util_Log),
     REG_JNI(register_android_util_MemoryIntArray),
     REG_JNI(register_android_util_PathParser),
+    REG_JNI(register_android_util_StatsLog),
     REG_JNI(register_android_app_admin_SecurityLog),
     REG_JNI(register_android_content_AssetManager),
     REG_JNI(register_android_content_StringBlock),
diff --git a/core/jni/android/graphics/Bitmap.cpp b/core/jni/android/graphics/Bitmap.cpp
index 635eed3..5498a93 100755
--- a/core/jni/android/graphics/Bitmap.cpp
+++ b/core/jni/android/graphics/Bitmap.cpp
@@ -682,6 +682,8 @@
 
     sk_sp<Bitmap> nativeBitmap = Bitmap::allocateHeapBitmap(&bitmap);
     if (!nativeBitmap) {
+        ALOGE("OOM allocating Bitmap with dimensions %i x %i", width, height);
+        doThrowOOME(env);
         return NULL;
     }
 
diff --git a/core/jni/android_util_StatsLog.cpp b/core/jni/android_util_StatsLog.cpp
deleted file mode 100644
index c992365..0000000
--- a/core/jni/android_util_StatsLog.cpp
+++ /dev/null
@@ -1,201 +0,0 @@
-/*
- * Copyright (C) 2007-2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <fcntl.h>
-#include <log/log_event_list.h>
-
-#include <log/log.h>
-
-#include <nativehelper/JNIHelp.h>
-#include "core_jni_helpers.h"
-#include "jni.h"
-
-#define UNUSED  __attribute__((__unused__))
-
-namespace android {
-
-static jclass gCollectionClass;
-static jmethodID gCollectionAddID;
-
-static jclass gIntegerClass;
-static jfieldID gIntegerValueID;
-
-static jclass gLongClass;
-static jfieldID gLongValueID;
-
-static jclass gFloatClass;
-static jfieldID gFloatValueID;
-
-static jclass gStringClass;
-
-/*
- * In class android.util.StatsLog:
- *  static native int writeInt(int tag, int value)
- */
-static jint android_util_StatsLog_write_Integer(JNIEnv* env UNUSED,
-                                                     jobject clazz UNUSED,
-                                                     jint tag, jint value)
-{
-    android_log_event_list ctx(tag);
-    ctx << (int32_t)value;
-    return ctx.write(LOG_ID_STATS);
-}
-
-/*
- * In class android.util.StatsLog:
- *  static native int writeLong(long tag, long value)
- */
-static jint android_util_StatsLog_write_Long(JNIEnv* env UNUSED,
-                                                  jobject clazz UNUSED,
-                                                  jint tag, jlong value)
-{
-    android_log_event_list ctx(tag);
-    ctx << (int64_t)value;
-    return ctx.write(LOG_ID_STATS);
-}
-
-/*
- * In class android.util.StatsLog:
- *  static native int writeFloat(long tag, float value)
- */
-static jint android_util_StatsLog_write_Float(JNIEnv* env UNUSED,
-                                                  jobject clazz UNUSED,
-                                                  jint tag, jfloat value)
-{
-    android_log_event_list ctx(tag);
-    ctx << (float)value;
-    return ctx.write(LOG_ID_STATS);
-}
-
-/*
- * In class android.util.StatsLog:
- *  static native int writeString(int tag, String value)
- */
-static jint android_util_StatsLog_write_String(JNIEnv* env,
-                                                    jobject clazz UNUSED,
-                                                    jint tag, jstring value) {
-    android_log_event_list ctx(tag);
-    // Don't throw NPE -- I feel like it's sort of mean for a logging function
-    // to be all crashy if you pass in NULL -- but make the NULL value explicit.
-    if (value != NULL) {
-        const char *str = env->GetStringUTFChars(value, NULL);
-        ctx << str;
-        env->ReleaseStringUTFChars(value, str);
-    } else {
-        ctx << "NULL";
-    }
-    return ctx.write(LOG_ID_STATS);
-}
-
-/*
- * In class android.util.StatsLog:
- *  static native int writeArray(long tag, Object... value)
- */
-static jint android_util_StatsLog_write_Array(JNIEnv* env, jobject clazz,
-                                                   jint tag, jobjectArray value) {
-    android_log_event_list ctx(tag);
-
-    if (value == NULL) {
-        ctx << "[NULL]";
-        return ctx.write(LOG_ID_STATS);
-    }
-
-    jsize copied = 0, num = env->GetArrayLength(value);
-    for (; copied < num && copied < 255; ++copied) {
-        if (ctx.status()) break;
-        jobject item = env->GetObjectArrayElement(value, copied);
-        if (item == NULL) {
-            ctx << "NULL";
-        } else if (env->IsInstanceOf(item, gStringClass)) {
-            const char *str = env->GetStringUTFChars((jstring) item, NULL);
-            ctx << str;
-            env->ReleaseStringUTFChars((jstring) item, str);
-        } else if (env->IsInstanceOf(item, gIntegerClass)) {
-            ctx << (int32_t)env->GetIntField(item, gIntegerValueID);
-        } else if (env->IsInstanceOf(item, gLongClass)) {
-            ctx << (int64_t)env->GetLongField(item, gLongValueID);
-        } else if (env->IsInstanceOf(item, gFloatClass)) {
-            ctx << (float)env->GetFloatField(item, gFloatValueID);
-        } else {
-            jniThrowException(env,
-                    "java/lang/IllegalArgumentException",
-                    "Invalid payload item type");
-            return -1;
-        }
-        env->DeleteLocalRef(item);
-    }
-    return ctx.write(LOG_ID_STATS);
-}
-
-/*
- * JNI registration.
- */
-static const JNINativeMethod gRegisterMethods[] = {
-    /* name, signature, funcPtr */
-    { "writeInt", "(II)I", (void*) android_util_StatsLog_write_Integer },
-    { "writeLong", "(IJ)I", (void*) android_util_StatsLog_write_Long },
-    { "writeFloat", "(IF)I", (void*) android_util_StatsLog_write_Float },
-    { "writeString",
-      "(ILjava/lang/String;)I",
-      (void*) android_util_StatsLog_write_String
-    },
-    { "writeArray",
-      "(I[Ljava/lang/Object;)I",
-      (void*) android_util_StatsLog_write_Array
-    },
-};
-
-static struct { const char *name; jclass *clazz; } gClasses[] = {
-    { "java/lang/Integer", &gIntegerClass },
-    { "java/lang/Long", &gLongClass },
-    { "java/lang/Float", &gFloatClass },
-    { "java/lang/String", &gStringClass },
-    { "java/util/Collection", &gCollectionClass },
-};
-
-static struct { jclass *c; const char *name, *ft; jfieldID *id; } gFields[] = {
-    { &gIntegerClass, "value", "I", &gIntegerValueID },
-    { &gLongClass, "value", "J", &gLongValueID },
-    { &gFloatClass, "value", "F", &gFloatValueID },
-};
-
-static struct { jclass *c; const char *name, *mt; jmethodID *id; } gMethods[] = {
-    { &gCollectionClass, "add", "(Ljava/lang/Object;)Z", &gCollectionAddID },
-};
-
-int register_android_util_StatsLog(JNIEnv* env) {
-    for (int i = 0; i < NELEM(gClasses); ++i) {
-        jclass clazz = FindClassOrDie(env, gClasses[i].name);
-        *gClasses[i].clazz = MakeGlobalRefOrDie(env, clazz);
-    }
-
-    for (int i = 0; i < NELEM(gFields); ++i) {
-        *gFields[i].id = GetFieldIDOrDie(env,
-                *gFields[i].c, gFields[i].name, gFields[i].ft);
-    }
-
-    for (int i = 0; i < NELEM(gMethods); ++i) {
-        *gMethods[i].id = GetMethodIDOrDie(env,
-                *gMethods[i].c, gMethods[i].name, gMethods[i].mt);
-    }
-
-    return RegisterMethodsOrDie(
-            env,
-            "android/util/StatsLog",
-            gRegisterMethods, NELEM(gRegisterMethods));
-}
-
-}; // namespace android
diff --git a/core/proto/android/app/notification_channel.proto b/core/proto/android/app/notification_channel.proto
index bbc1956..0388547 100644
--- a/core/proto/android/app/notification_channel.proto
+++ b/core/proto/android/app/notification_channel.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 option java_package = "android.app";
 option java_multiple_files = true;
 
@@ -27,28 +26,28 @@
  * An android.app.NotificationChannel object.
  */
 message NotificationChannelProto {
-    string id = 1;
-    string name = 2;
-    string description = 3;
-    int32 importance = 4;
-    bool can_bypass_dnd = 5;
+    optional string id = 1;
+    optional string name = 2;
+    optional string description = 3;
+    optional int32 importance = 4;
+    optional bool can_bypass_dnd = 5;
     // Default is VISIBILITY_NO_OVERRIDE (-1000).
-    int32 lockscreen_visibility = 6;
-    string sound = 7;
-    bool use_lights = 8;
+    optional int32 lockscreen_visibility = 6;
+    optional string sound = 7;
+    optional bool use_lights = 8;
     // Default is 0.
-    int32 light_color = 9;
+    optional int32 light_color = 9;
     repeated int64 vibration = 10;
     // Bitwise representation of fields that have been changed by the user,
     // preventing the app from making changes to these fields.
-    int32 user_locked_fields = 11;
-    bool is_vibration_enabled = 12;
+    optional int32 user_locked_fields = 11;
+    optional bool is_vibration_enabled = 12;
     // Default is true.
-    bool show_badge = 13;
+    optional bool show_badge = 13;
     // Default is false.
-    bool is_deleted = 14;
-    string group = 15;
-    android.media.AudioAttributesProto audio_attributes = 16;
+    optional bool is_deleted = 14;
+    optional string group = 15;
+    optional android.media.AudioAttributesProto audio_attributes = 16;
     // If this is a blockable system notification channel.
-    bool is_blockable_system = 17;
+    optional bool is_blockable_system = 17;
 }
diff --git a/core/proto/android/app/notification_channel_group.proto b/core/proto/android/app/notification_channel_group.proto
index 9cb456f..89a540f 100644
--- a/core/proto/android/app/notification_channel_group.proto
+++ b/core/proto/android/app/notification_channel_group.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 option java_package = "android.app";
 option java_multiple_files = true;
 
@@ -27,9 +26,9 @@
  * An android.app.NotificationChannelGroup object.
  */
 message NotificationChannelGroupProto {
-    string id = 1;
-    string name = 2;
-    string description = 3;
-    bool is_blocked = 4;
+    optional string id = 1;
+    optional string name = 2;
+    optional string description = 3;
+    optional bool is_blocked = 4;
     repeated android.app.NotificationChannelProto channels = 5;
 }
diff --git a/core/proto/android/app/notificationmanager.proto b/core/proto/android/app/notificationmanager.proto
index 4dfd0cf..7d774ae 100644
--- a/core/proto/android/app/notificationmanager.proto
+++ b/core/proto/android/app/notificationmanager.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 option java_package = "android.app";
 option java_multiple_files = true;
 
@@ -48,8 +47,8 @@
         // Only starred contacts are prioritized.
         STARRED = 2;
     }
-    Sender priority_call_sender = 2;
-    Sender priority_message_sender = 3;
+    optional Sender priority_call_sender = 2;
+    optional Sender priority_message_sender = 3;
 
     enum SuppressedVisualEffect {
         SVE_UNKNOWN = 0;
diff --git a/core/proto/android/app/window_configuration.proto b/core/proto/android/app/window_configuration.proto
index 03910df..4d748e8 100644
--- a/core/proto/android/app/window_configuration.proto
+++ b/core/proto/android/app/window_configuration.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 option java_package = "android.app";
 option java_multiple_files = true;
 
@@ -25,7 +24,7 @@
 
 /** Proto representation for WindowConfiguration.java class. */
 message WindowConfigurationProto {
-  .android.graphics.RectProto app_bounds = 1;
-  int32 windowing_mode = 2;
-  int32 activity_type = 3;
+  optional .android.graphics.RectProto app_bounds = 1;
+  optional int32 windowing_mode = 2;
+  optional int32 activity_type = 3;
 }
diff --git a/core/proto/android/content/component_name.proto b/core/proto/android/content/component_name.proto
index 90f6ffb..fc0c8c5 100644
--- a/core/proto/android/content/component_name.proto
+++ b/core/proto/android/content/component_name.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 option java_package = "android.content";
 option java_multiple_files = true;
 
@@ -25,7 +24,7 @@
  * An android.content.ComponentName object.
  */
 message ComponentNameProto {
-    string package_name = 1;
-    string class_name = 2;
+    optional string package_name = 1;
+    optional string class_name = 2;
 }
 
diff --git a/core/proto/android/content/configuration.proto b/core/proto/android/content/configuration.proto
index 804e0b4..111b27f 100644
--- a/core/proto/android/content/configuration.proto
+++ b/core/proto/android/content/configuration.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 option java_package = "android.content";
 option java_multiple_files = true;
 
@@ -28,22 +27,22 @@
  * An android resource configuration.
  */
 message ConfigurationProto {
-  float font_scale = 1;
-  uint32 mcc = 2;
-  uint32 mnc = 3;
+  optional float font_scale = 1;
+  optional uint32 mcc = 2;
+  optional uint32 mnc = 3;
   repeated LocaleProto locales = 4;
-  uint32 screen_layout = 5;
-  uint32 touchscreen = 6;
-  uint32 keyboard_hidden = 7;
-  uint32 hard_keyboard_hidden = 8;
-  uint32 navigation = 9;
-  uint32 navigation_hidden = 10;
-  uint32 orientation = 11;
-  uint32 ui_mode = 12;
-  uint32 screen_width_dp = 13;
-  uint32 screen_height_dp = 14;
-  uint32 smallest_screen_width_dp = 15;
-  uint32 density_dpi = 16;
-  .android.app.WindowConfigurationProto window_configuration = 17;
+  optional uint32 screen_layout = 5;
+  optional uint32 touchscreen = 6;
+  optional uint32 keyboard_hidden = 7;
+  optional uint32 hard_keyboard_hidden = 8;
+  optional uint32 navigation = 9;
+  optional uint32 navigation_hidden = 10;
+  optional uint32 orientation = 11;
+  optional uint32 ui_mode = 12;
+  optional uint32 screen_width_dp = 13;
+  optional uint32 screen_height_dp = 14;
+  optional uint32 smallest_screen_width_dp = 15;
+  optional uint32 density_dpi = 16;
+  optional .android.app.WindowConfigurationProto window_configuration = 17;
 }
 
diff --git a/core/proto/android/content/intent.proto b/core/proto/android/content/intent.proto
index f2927a7..4f49744 100644
--- a/core/proto/android/content/intent.proto
+++ b/core/proto/android/content/intent.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 option java_package = "android.content";
 option java_multiple_files = true;
 
@@ -25,18 +24,18 @@
 
 // Next Tag: 13
 message IntentProto {
-    string action = 1;
+    optional string action = 1;
     repeated string categories = 2;
-    string data = 3;
-    string type = 4;
-    string flag = 5;
-    string package = 6;
-    string component = 7;
-    string source_bounds = 8;
-    string clip_data = 9;
-    string extras = 10;
-    int32 content_user_hint = 11;
-    string selector = 12;
+    optional string data = 3;
+    optional string type = 4;
+    optional string flag = 5;
+    optional string package = 6;
+    optional string component = 7;
+    optional string source_bounds = 8;
+    optional string clip_data = 9;
+    optional string extras = 10;
+    optional int32 content_user_hint = 11;
+    optional string selector = 12;
 }
 
 // Next Tag: 11
@@ -48,13 +47,13 @@
     repeated AuthorityEntryProto data_authorities = 5;
     repeated android.os.PatternMatcherProto data_paths = 6;
     repeated string data_types = 7;
-    int32 priority = 8;
-    bool has_partial_types = 9;
-    bool get_auto_verify = 10;
+    optional int32 priority = 8;
+    optional bool has_partial_types = 9;
+    optional bool get_auto_verify = 10;
 }
 
 message AuthorityEntryProto {
-    string host = 1;
-    bool wild = 2;
-    int32 port = 3;
+    optional string host = 1;
+    optional bool wild = 2;
+    optional int32 port = 3;
 }
diff --git a/core/proto/android/content/locale.proto b/core/proto/android/content/locale.proto
index 961b10b..f0de31c 100644
--- a/core/proto/android/content/locale.proto
+++ b/core/proto/android/content/locale.proto
@@ -14,16 +14,15 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 option java_package = "android.content";
 option java_multiple_files = true;
 
 package android.content;
 
 message LocaleProto {
-  string language = 1;
-  string country = 2;
-  string variant = 3;
+  optional string language = 1;
+  optional string country = 2;
+  optional string variant = 3;
 }
 
diff --git a/core/proto/android/graphics/rect.proto b/core/proto/android/graphics/rect.proto
index a65d331..562ffce 100644
--- a/core/proto/android/graphics/rect.proto
+++ b/core/proto/android/graphics/rect.proto
@@ -14,16 +14,15 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 package android.graphics;
 
 option java_multiple_files = true;
 
 message RectProto {
-  int32 left = 1;
-  int32 top = 2;
-  int32 right = 3;
-  int32 bottom = 4;
+  optional int32 left = 1;
+  optional int32 top = 2;
+  optional int32 right = 3;
+  optional int32 bottom = 4;
 }
 
diff --git a/core/proto/android/media/audioattributes.proto b/core/proto/android/media/audioattributes.proto
index 3aa2792..860d608 100644
--- a/core/proto/android/media/audioattributes.proto
+++ b/core/proto/android/media/audioattributes.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 option java_package = "android.media";
 option java_multiple_files = true;
 
@@ -25,10 +24,10 @@
  * An android.media.AudioAttributes object.
  */
 message AudioAttributesProto {
-    Usage usage = 1;
-    ContentType content_type = 2;
+    optional Usage usage = 1;
+    optional ContentType content_type = 2;
     // Bit representation of set flags.
-    int32 flags = 3;
+    optional int32 flags = 3;
     repeated string tags = 4;
 }
 
diff --git a/core/proto/android/os/batterystats.proto b/core/proto/android/os/batterystats.proto
index 8d85038..38879c0 100644
--- a/core/proto/android/os/batterystats.proto
+++ b/core/proto/android/os/batterystats.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 option java_multiple_files = true;
 
 package android.os;
@@ -23,13 +22,13 @@
 import "frameworks/base/core/proto/android/telephony/signalstrength.proto";
 
 message BatteryStatsProto {
-  int32 report_version = 1;
-  int64 parcel_version = 2;
-  string start_platform_version = 3;
-  string end_platform_version = 4;
-  BatteryHistoryProto history = 5;
+  optional int32 report_version = 1;
+  optional int64 parcel_version = 2;
+  optional string start_platform_version = 3;
+  optional string end_platform_version = 4;
+  optional BatteryHistoryProto history = 5;
   repeated UidProto uids = 6;
-  SystemProto system = 7;
+  optional SystemProto system = 7;
 }
 
 message BatteryHistoryProto {
@@ -37,21 +36,21 @@
 
 message ControllerActivityProto {
   // Time (milliseconds) spent in the idle state.
-  int64 idle_duration_ms = 1;
+  optional int64 idle_duration_ms = 1;
   // Time (milliseconds) spent in the receive state.
-  int64 rx_duration_ms = 2;
+  optional int64 rx_duration_ms = 2;
   // Total power (mAh) consumed by the controller in all states. The value may
   // always be 0 if the device doesn't support power calculations.
-  int64 power_mah = 3;
+  optional int64 power_mah = 3;
 
   // Represents a transmit level, where each level may draw a different amount
   // of power. The levels themselves are controller-specific (and may possibly
   // be device specific...yet to be confirmed).
   message TxLevel {
     // Transmit level. Higher levels draw more power.
-    int32 level = 1;
+    optional int32 level = 1;
     // Time spent in this specific transmit level state.
-    int64 duration_ms = 2;
+    optional int64 duration_ms = 2;
   }
   repeated TxLevel tx = 4;
 }
@@ -62,65 +61,65 @@
     // In case of device time manually reset by users:
     //   start_clock_time_ms keeps the same value in the current collection
     //   period and changes for later collection periods.
-    int64 start_clock_time_ms = 1;
+    optional int64 start_clock_time_ms = 1;
     // #times the device has been started since start_clock_time_millis.
-    int64 start_count = 2;
+    optional int64 start_count = 2;
     // Total realtime duration (= SINCE_UNPLUGGED battery_realtime_millis.)
-    int64 total_realtime_ms = 3;
-    int64 total_uptime_ms = 4;
+    optional int64 total_realtime_ms = 3;
+    optional int64 total_uptime_ms = 4;
     // Realtime duration on battery.
-    int64 battery_realtime_ms = 5;
+    optional int64 battery_realtime_ms = 5;
     // Uptime duration (i.e., not suspend).
     // Uptime is anytime the CPUs were on. The radio and Wifi chip
     // can be running while the CPUs are off.
-    int64 battery_uptime_ms = 6;
+    optional int64 battery_uptime_ms = 6;
     // Total realtime duration measured with screen off or dozing.
-    int64 screen_off_realtime_ms = 7;
+    optional int64 screen_off_realtime_ms = 7;
     // Total uptime duration measured with screen off or dozing.
-    int64 screen_off_uptime_ms = 8;
+    optional int64 screen_off_uptime_ms = 8;
     // Total time the screen was dozing while the device was running on battery.
     // For historical reasons, screen_doze_duration_msec is a subset of
     // screen_off_realtime_msec.
-    int64 screen_doze_duration_ms = 9;
+    optional int64 screen_doze_duration_ms = 9;
     // The estimated real battery capacity, which may be less than the declared
     // battery capacity (for example, because of battery aging). This field is
     // less reliable than min(max)_learned_battery_capacity_uah, use those two
     // fields whenever possible.
-    int64 estimated_battery_capacity_mah = 10;
+    optional int64 estimated_battery_capacity_mah = 10;
     // The minimum learned battery capacity in uAh.
-    int64 min_learned_battery_capacity_uah = 11;
+    optional int64 min_learned_battery_capacity_uah = 11;
     // The maximum learned battery capacity in uAh.
-    int64 max_learned_battery_capacity_uah = 12;
+    optional int64 max_learned_battery_capacity_uah = 12;
   };
-  Battery battery = 1;
+  optional Battery battery = 1;
 
   message BatteryDischarge {
     // Discharged battery percentage points since the stats were last reset
     // after charging (lower bound approximation).
-    int32 lower_bound_since_charge = 1;
+    optional int32 lower_bound_since_charge = 1;
     // Upper bound approximation.
-    int32 upper_bound_since_charge = 2;
+    optional int32 upper_bound_since_charge = 2;
     // Discharged points while screen is on.
-    int32 screen_on_since_charge = 3;
+    optional int32 screen_on_since_charge = 3;
     // Discharged points while screen is off.
-    int32 screen_off_since_charge = 4;
+    optional int32 screen_off_since_charge = 4;
     // Discharged points while screen was dozing. For historical reasons,
     // screen_doze_since_charge is a subset of screen_off_since_charge.
-    int32 screen_doze_since_charge = 5;
+    optional int32 screen_doze_since_charge = 5;
     // Total amount of battery discharged in mAh. This will only be non-zero for
     // devices that report battery discharge via a coulomb counter.
-    int64 total_mah = 6;
+    optional int64 total_mah = 6;
     // Total amount of battery discharged while the screen was off in mAh.
     // This will only be non-zero for devices that report battery discharge
     // via a coulomb counter.
-    int64 total_mah_screen_off = 7;
+    optional int64 total_mah_screen_off = 7;
     // Total amount of battery discharged while the screen was dozing in mAh.
     // This will only be non-zero for devices that report battery discharge
     // via a coulomb counter. For historical reasons, total_mah_screen_doze is
     // a subset of total_mah_screen_off.
-    int64 total_mah_screen_doze = 8;
+    optional int64 total_mah_screen_doze = 8;
   };
-  BatteryDischarge battery_discharge = 2;
+  optional BatteryDischarge battery_discharge = 2;
 
   oneof time_remaining {
     // Approximation for how much time remains until the battery is fully
@@ -138,9 +137,9 @@
   // for the entire duration should be marked MIXED.
   message BatteryLevelStep {
     // How long the battery was at the current level.
-    int64 duration_ms = 1;
+    optional int64 duration_ms = 1;
     // Battery level
-    int32 level = 2;
+    optional int32 level = 2;
 
     // State of the display. A special enum is used rather than
     // DisplayProto.State because a MIXED value needs to be in the enum, and
@@ -156,7 +155,7 @@
     }
     // The state of the display for the entire battery level step. MIXED is used
     // if there were multiple states for this step.
-    DisplayState display_state = 3;
+    optional DisplayState display_state = 3;
 
     // Indicates status in power save mode.
     enum PowerSaveMode {
@@ -166,7 +165,7 @@
     }
     // Battery Saver mode for the entire battery level step. MIXED is used
     // if there were multiple states for this step.
-    PowerSaveMode power_save_mode = 4;
+    optional PowerSaveMode power_save_mode = 4;
 
     // Indicates status in idle mode.
     enum IdleMode {
@@ -176,7 +175,7 @@
     }
     // Doze mode for the entire battery level step. MIXED is used if there were
     // multiple states for this step.
-    IdleMode idle_mode = 5;
+    optional IdleMode idle_mode = 5;
   };
   // Battery level steps when the device was charging.
   repeated BatteryLevelStep charge_step = 5;
@@ -206,109 +205,109 @@
       HSPAP = 15;
       OTHER = 16;
     };
-    Name name = 1;
-    TimerProto total = 2;
+    optional Name name = 1;
+    optional TimerProto total = 2;
   };
   repeated DataConnection data_connection = 8;
 
-  ControllerActivityProto global_bluetooth_controller = 9;
-  ControllerActivityProto global_modem_controller = 10;
-  ControllerActivityProto global_wifi_controller = 11;
+  optional ControllerActivityProto global_bluetooth_controller = 9;
+  optional ControllerActivityProto global_modem_controller = 10;
+  optional ControllerActivityProto global_wifi_controller = 11;
 
   message GlobalNetwork {
     // Total Bytes received on mobile connections.
-    int64 mobile_bytes_rx = 1;
+    optional int64 mobile_bytes_rx = 1;
     // Total Bytes transmitted on mobile connections.
-    int64 mobile_bytes_tx = 2;
+    optional int64 mobile_bytes_tx = 2;
     // Total Bytes received on wifi connections.
-    int64 wifi_bytes_rx = 3;
+    optional int64 wifi_bytes_rx = 3;
     // Total Bytes transmitted on wifi connections.
-    int64 wifi_bytes_tx = 4;
+    optional int64 wifi_bytes_tx = 4;
     // Total Packets received on mobile connections.
-    int64 mobile_packets_rx = 5;
+    optional int64 mobile_packets_rx = 5;
     // Total Packets transmitted on mobile connections.
-    int64 mobile_packets_tx = 6;
+    optional int64 mobile_packets_tx = 6;
     // Total Packets received on wifi connections.
-    int64 wifi_packets_rx = 7;
+    optional int64 wifi_packets_rx = 7;
     // Total Packets transmitted on wifi connections.
-    int64 wifi_packets_tx = 8;
+    optional int64 wifi_packets_tx = 8;
     // Total Bytes received on bluetooth connections.
-    int64 bt_bytes_rx = 9;
+    optional int64 bt_bytes_rx = 9;
     // Total Bytes transmitted on bluetooth connections.
-    int64 bt_bytes_tx = 10;
+    optional int64 bt_bytes_tx = 10;
   };
-  GlobalNetwork global_network = 12;
+  optional GlobalNetwork global_network = 12;
 
   message GlobalWifi {
     // The amount of time that wifi has been on while the device was running on
     // battery.
-    int64 on_duration_ms = 1;
+    optional int64 on_duration_ms = 1;
     // The amount of time that wifi has been on and the driver has been in the
     // running state while the device was running on battery.
-    int64 running_duration_ms = 2;
+    optional int64 running_duration_ms = 2;
   }
-  GlobalWifi global_wifi = 13;
+  optional GlobalWifi global_wifi = 13;
 
   // Kernel wakelock metrics are only recorded when the device is unplugged
   // *and* the screen is off.
   message KernelWakelock {
-    string name = 1;
+    optional string name = 1;
     // Kernel wakelock stats aren't apportioned across all kernel wakelocks (as
     // app wakelocks stats are).
-    TimerProto total = 2;
+    optional TimerProto total = 2;
     // The kernel doesn't have the data to enable printing out current and max
     // durations.
   };
   repeated KernelWakelock kernel_wakelock = 14;
 
   message Misc {
-    int64 screen_on_duration_ms = 1;
-    int64 phone_on_duration_ms = 2;
-    int64 full_wakelock_total_duration_ms = 3;
+    optional int64 screen_on_duration_ms = 1;
+    optional int64 phone_on_duration_ms = 2;
+    optional int64 full_wakelock_total_duration_ms = 3;
     // The total elapsed time that a partial wakelock was held. This duration
     // does not double count wakelocks held at the same time.
-    int64 partial_wakelock_total_duration_ms = 4;
-    int64 mobile_radio_active_duration_ms = 5;
+    optional int64 partial_wakelock_total_duration_ms = 4;
+    optional int64 mobile_radio_active_duration_ms = 5;
     // The time that is the difference between the mobile radio time we saw
     // based on the elapsed timestamp when going down vs. the given time stamp
     // from the radio.
-    int64 mobile_radio_active_adjusted_time_ms = 6;
-    int32 mobile_radio_active_count = 7;
+    optional int64 mobile_radio_active_adjusted_time_ms = 6;
+    optional int32 mobile_radio_active_count = 7;
     // The amount of time that the mobile network has been active (in a high
     // power state) but not being able to blame on an app.
-    int32 mobile_radio_active_unknown_duration_ms = 8;
+    optional int32 mobile_radio_active_unknown_duration_ms = 8;
     // Total amount of time the device was in the interactive state.
-    int64 interactive_duration_ms = 9;
-    int64 battery_saver_mode_enabled_duration_ms = 10;
-    int32 num_connectivity_changes = 11;
+    optional int64 interactive_duration_ms = 9;
+    optional int64 battery_saver_mode_enabled_duration_ms = 10;
+    optional int32 num_connectivity_changes = 11;
     // Amount of time the device was in deep Doze.
-    int64 deep_doze_enabled_duration_ms = 12;
+    optional int64 deep_doze_enabled_duration_ms = 12;
     // How many times the device went into deep Doze mode.
-    int32 deep_doze_count = 13;
+    optional int32 deep_doze_count = 13;
     // Amount of time the device was idling in deep Doze. Idling time
     // encompasses "doze" time and the maintenance windows that allow apps to
     // operate.
-    int64 deep_doze_idling_duration_ms = 14;
+    optional int64 deep_doze_idling_duration_ms = 14;
     // How many times the device idling for deep Doze mode.
-    int32 deep_doze_idling_count = 15;
-    int64 longest_deep_doze_duration_ms = 16;
+    optional int32 deep_doze_idling_count = 15;
+    optional int64 longest_deep_doze_duration_ms = 16;
     // Amount of time the device was in Doze Light.
-    int64 light_doze_enabled_duration_ms = 17;
+    optional int64 light_doze_enabled_duration_ms = 17;
     // How many times the device went into Doze Light mode.
-    int32 light_doze_count = 18;
+    optional int32 light_doze_count = 18;
     // Amount of time the device was idling in Doze Light. Idling time
     // encompasses "doze" time and the maintenance windows that allow apps to
     // operate.
-    int64 light_doze_idling_duration_ms = 19;
+    optional int64 light_doze_idling_duration_ms = 19;
     // How many times the device idling for Doze Light mode.
-    int32 light_doze_idling_count = 20;
-    int64 longest_light_doze_duration_ms = 21;
+    optional int32 light_doze_idling_count = 20;
+    optional int64 longest_light_doze_duration_ms = 21;
   }
-  Misc misc = 15;
+  optional Misc misc = 15;
 
   message PhoneSignalStrength {
-    android.telephony.SignalStrengthProto.StrengthName name = 1;
-    TimerProto total = 2;
+    optional android.telephony.SignalStrengthProto.StrengthName name = 1;
+    optional TimerProto total = 2;
   };
   repeated PhoneSignalStrength phone_signal_strength = 16;
 
@@ -328,40 +327,40 @@
       CAMERA = 11;
       MEMORY = 12;
     };
-    Sipper name = 1;
+    optional Sipper name = 1;
     // UID, only valid for the USER sipper.
-    int32 uid = 2;
+    optional int32 uid = 2;
     // Estimated power use in mAh.
-    double computed_power_mah = 3;
+    optional double computed_power_mah = 3;
     // Starting in Oreo, Battery Settings has two modes to display the battery
     // info. The first is "app usage list". In this mode, items with should_hide
     // enabled are hidden.
-    bool should_hide = 4;
+    optional bool should_hide = 4;
     // Smeared power from screen usage. Screen usage power is split and smeared
     // among apps, based on activity time.
-    double screen_power_mah = 5;
+    optional double screen_power_mah = 5;
     // Smeared power using proportional method. Power usage from hidden sippers
     // is smeared to all apps proportionally (except for screen usage).
-    double proportional_smear_mah = 6;
+    optional double proportional_smear_mah = 6;
   };
   repeated PowerUseItem power_use_item = 17;
 
   message PowerUseSummary {
-    double battery_capacity_mah = 1;
-    double computed_power_mah = 2;
+    optional double battery_capacity_mah = 1;
+    optional double computed_power_mah = 2;
     // Lower bound of actual power drained.
-    double min_drained_power_mah = 3;
+    optional double min_drained_power_mah = 3;
     // Upper bound of actual power drained.
-    double max_drained_power_mah = 4;
+    optional double max_drained_power_mah = 4;
   };
-  PowerUseSummary power_use_summary = 18;
+  optional PowerUseSummary power_use_summary = 18;
 
   message ResourcePowerManager {
-    string name = 1;
-    TimerProto total = 2;
-    TimerProto screen_off = 3;
+    optional string name = 1;
+    optional TimerProto total = 2;
+    optional TimerProto screen_off = 3;
   }
-  ResourcePowerManager resource_power_manager = 19;
+  optional ResourcePowerManager resource_power_manager = 19;
 
   message ScreenBrightness {
     enum Name {
@@ -371,17 +370,17 @@
       LIGHT = 3;
       BRIGHT = 4;
     };
-    Name name = 1;
-    TimerProto total = 2;
+    optional Name name = 1;
+    optional TimerProto total = 2;
   };
   repeated ScreenBrightness screen_brightness = 20;
 
   // Duration and number of times trying to acquire a signal
-  TimerProto signal_scanning = 21;
+  optional TimerProto signal_scanning = 21;
 
   message WakeupReason {
-    string name = 1;
-    TimerProto total = 2;
+    optional string name = 1;
+    optional TimerProto total = 2;
   };
   repeated WakeupReason wakeup_reason = 22;
 
@@ -393,8 +392,8 @@
       GOOD = 3;
       GREAT = 4;
     };
-    Name name = 1;
-    TimerProto total = 2;
+    optional Name name = 1;
+    optional TimerProto total = 2;
   };
   repeated WifiSignalStrength wifi_signal_strength = 23;
 
@@ -409,8 +408,8 @@
       ON_CONNECTED_STA_P2P = 6;
       SOFT_AP = 7;
     };
-    Name name = 1;
-    TimerProto total = 2;
+    optional Name name = 1;
+    optional TimerProto total = 2;
   };
   repeated WifiState wifi_state = 24;
 
@@ -430,19 +429,19 @@
       DORMANT = 11;
       UNINITIALIZED = 12;
     };
-    Name name = 1;
-    TimerProto total = 2;
+    optional Name name = 1;
+    optional TimerProto total = 2;
   };
   repeated WifiSupplicantState wifi_supplicant_state = 25;
 }
 
 message TimerProto {
-  int64 duration_ms = 1;
-  int64 count = 2;
+  optional int64 duration_ms = 1;
+  optional int64 count = 2;
 }
 
 message UidProto {
   // Combination of app ID and user ID.
-  int32 uid = 1;
+  optional int32 uid = 1;
   repeated string package_names = 2;
 }
diff --git a/core/proto/android/os/incident.proto b/core/proto/android/os/incident.proto
index 884d740..c9d7b49 100644
--- a/core/proto/android/os/incident.proto
+++ b/core/proto/android/os/incident.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 option java_multiple_files = true;
 option java_outer_classname = "IncidentProtoMetadata";
 
@@ -52,74 +51,74 @@
     //SystemProperties system_properties = 1000;
 
     // Linux services
-    Procrank procrank = 2000 [
+    optional Procrank procrank = 2000 [
         (section).type = SECTION_COMMAND,
         (section).args = "/system/xbin/procrank"
     ];
 
-    PageTypeInfo page_type_info = 2001 [
+    optional PageTypeInfo page_type_info = 2001 [
         (section).type = SECTION_FILE,
         (section).args = "/proc/pagetypeinfo"
     ];
 
-    KernelWakeSources kernel_wake_sources = 2002 [
+    optional KernelWakeSources kernel_wake_sources = 2002 [
         (section).type = SECTION_FILE,
         (section).args = "/d/wakeup_sources"
     ];
 
 
     // System Services
-    android.service.fingerprint.FingerprintServiceDumpProto fingerprint = 3000 [
+    optional android.service.fingerprint.FingerprintServiceDumpProto fingerprint = 3000 [
         (section).type = SECTION_DUMPSYS,
         (section).args = "fingerprint --proto --incident"
     ];
 
-    android.service.NetworkStatsServiceDumpProto netstats = 3001 [
+    optional android.service.NetworkStatsServiceDumpProto netstats = 3001 [
         (section).type = SECTION_DUMPSYS,
         (section).args = "netstats --proto"
     ];
 
-    android.providers.settings.SettingsServiceDumpProto settings = 3002;
-    android.service.appwidget.AppWidgetServiceDumpProto appwidget = 3003;
-    android.service.notification.NotificationServiceDumpProto notification = 3004 [
+    optional android.providers.settings.SettingsServiceDumpProto settings = 3002;
+    optional android.service.appwidget.AppWidgetServiceDumpProto appwidget = 3003;
+    optional android.service.notification.NotificationServiceDumpProto notification = 3004 [
         (section).type = SECTION_DUMPSYS,
         (section).args = "notification --proto"
     ];
 
-    android.service.batterystats.BatteryStatsServiceDumpProto batterystats = 3005 [
+    optional android.service.batterystats.BatteryStatsServiceDumpProto batterystats = 3005 [
         (section).type = SECTION_DUMPSYS,
         (section).args = "batterystats --proto"
     ];
 
-    android.service.battery.BatteryServiceDumpProto battery = 3006 [
+    optional android.service.battery.BatteryServiceDumpProto battery = 3006 [
         (section).type = SECTION_DUMPSYS,
         (section).args = "battery --proto"
     ];
 
-    android.service.diskstats.DiskStatsServiceDumpProto diskstats = 3007 [
+    optional android.service.diskstats.DiskStatsServiceDumpProto diskstats = 3007 [
         (section).type = SECTION_DUMPSYS,
         (section).args = "diskstats --proto"
     ];
 
-    android.service.pm.PackageServiceDumpProto package = 3008;
-    android.service.power.PowerServiceDumpProto power = 3009;
-    android.service.print.PrintServiceDumpProto print = 3010;
+    optional android.service.pm.PackageServiceDumpProto package = 3008;
+    optional android.service.power.PowerServiceDumpProto power = 3009;
+    optional android.service.print.PrintServiceDumpProto print = 3010;
 
-    android.service.procstats.ProcessStatsServiceDumpProto procstats = 3011 [
+    optional android.service.procstats.ProcessStatsServiceDumpProto procstats = 3011 [
         (section).type = SECTION_DUMPSYS,
         (section).args = "procstats --proto"
     ];
 
-    com.android.server.am.proto.ActivityStackSupervisorProto activities = 3012 [
+    optional com.android.server.am.proto.ActivityStackSupervisorProto activities = 3012 [
         (section).type = SECTION_DUMPSYS,
         (section).args = "activity --proto activities"
     ];
 
-    com.android.server.am.proto.BroadcastProto broadcasts = 3013 [
+    optional com.android.server.am.proto.BroadcastProto broadcasts = 3013 [
         (section).type = SECTION_DUMPSYS,
         (section).args = "activity --proto broadcasts"
     ];
 
-    com.android.server.am.proto.ServiceProto amservices = 3014;
-    com.android.server.am.proto.ProcessProto amprocesses = 3015;
+    optional com.android.server.am.proto.ServiceProto amservices = 3014;
+    optional com.android.server.am.proto.ProcessProto amprocesses = 3015;
 }
diff --git a/core/proto/android/os/incidentheader.proto b/core/proto/android/os/incidentheader.proto
index 55a0616..ce924da 100644
--- a/core/proto/android/os/incidentheader.proto
+++ b/core/proto/android/os/incidentheader.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 option java_multiple_files = true;
 option java_outer_classname = "IncidentHeaderProtoMetadata";
 
@@ -29,6 +28,6 @@
         CAUSE_CRASH = 3;
     }
 
-    Cause cause = 1;
+    optional Cause cause = 1;
 }
 
diff --git a/core/proto/android/os/kernelwake.proto b/core/proto/android/os/kernelwake.proto
index e0b62aa..12649e1 100644
--- a/core/proto/android/os/kernelwake.proto
+++ b/core/proto/android/os/kernelwake.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 option java_multiple_files = true;
 option java_outer_classname = "WakeupSourcesProto";
 
@@ -29,23 +28,23 @@
 // Next Tag: 11
 message WakeupSourceProto {
     // Name of the event which triggers application processor
-    string name = 1;
+    optional string name = 1;
 
-    int32 active_count = 2;
+    optional int32 active_count = 2;
 
-    int32 event_count = 3;
+    optional int32 event_count = 3;
 
-    int32 wakeup_count = 4;
+    optional int32 wakeup_count = 4;
 
-    int32 expire_count = 5;
+    optional int32 expire_count = 5;
 
-    int64 active_since = 6;
+    optional int64 active_since = 6;
 
-    int64 total_time = 7;
+    optional int64 total_time = 7;
 
-    int64 max_time = 8;
+    optional int64 max_time = 8;
 
-    int64 last_change = 9;
+    optional int64 last_change = 9;
 
-    int64 prevent_suspend_time = 10;
+    optional int64 prevent_suspend_time = 10;
 }
diff --git a/core/proto/android/os/looper.proto b/core/proto/android/os/looper.proto
index 9fcc781..ef84bb1 100644
--- a/core/proto/android/os/looper.proto
+++ b/core/proto/android/os/looper.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 package android.os;
 
 option java_multiple_files = true;
@@ -23,8 +22,8 @@
 import "frameworks/base/core/proto/android/os/messagequeue.proto";
 
 message LooperProto {
-    string thread_name = 1;
-    int64 thread_id = 2;
-    int32 identity_hash_code = 3;
-    android.os.MessageQueueProto queue = 4;
+    optional string thread_name = 1;
+    optional int64 thread_id = 2;
+    optional int32 identity_hash_code = 3;
+    optional android.os.MessageQueueProto queue = 4;
 }
diff --git a/core/proto/android/os/message.proto b/core/proto/android/os/message.proto
index 604935d..38e27a1 100644
--- a/core/proto/android/os/message.proto
+++ b/core/proto/android/os/message.proto
@@ -14,24 +14,23 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 package android.os;
 
 option java_multiple_files = true;
 
 message MessageProto {
-    int64 when = 1;
+    optional int64 when = 1;
     // Name of callback class.
-    string callback = 2;
+    optional string callback = 2;
     // User-defined message code so that the recipient can identify what this
     // message is about.
-    int32 what = 3;
-    int32 arg1 = 4;
-    int32 arg2 = 5;
+    optional int32 what = 3;
+    optional int32 arg1 = 4;
+    optional int32 arg2 = 5;
     // String representation of an arbitrary object to send to the recipient.
-    string obj = 6;
+    optional string obj = 6;
     // Name of target class.
-    string target = 7;
-    int32 barrier = 8;
+    optional string target = 7;
+    optional int32 barrier = 8;
 }
diff --git a/core/proto/android/os/messagequeue.proto b/core/proto/android/os/messagequeue.proto
index 9bff13e..5d4bff0 100644
--- a/core/proto/android/os/messagequeue.proto
+++ b/core/proto/android/os/messagequeue.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 package android.os;
 
 option java_multiple_files = true;
@@ -24,6 +23,6 @@
 
 message MessageQueueProto {
     repeated android.os.MessageProto messages = 1;
-    bool is_polling_locked = 2;
-    bool is_quitting = 3;
+    optional bool is_polling_locked = 2;
+    optional bool is_quitting = 3;
 }
diff --git a/core/proto/android/os/pagetypeinfo.proto b/core/proto/android/os/pagetypeinfo.proto
index fbb4ee5..38f1890 100644
--- a/core/proto/android/os/pagetypeinfo.proto
+++ b/core/proto/android/os/pagetypeinfo.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 option java_multiple_files = true;
 option java_outer_classname = "PageTypeInfoProto";
 
@@ -38,9 +37,9 @@
  */
 message PageTypeInfo {
 
-    int32 page_block_order = 1;
+    optional int32 page_block_order = 1;
 
-    int32 pages_per_block = 2;
+    optional int32 pages_per_block = 2;
 
     repeated MigrateTypeProto migrate_types = 3;
 
@@ -50,11 +49,11 @@
 // Next tag: 5
 message MigrateTypeProto {
 
-    int32 node = 1;
+    optional int32 node = 1;
 
-    string zone = 2;
+    optional string zone = 2;
 
-    string type = 3;
+    optional string type = 3;
 
     // order level starts from 0 for 4KB to page_block_order defined above, e.g. 10 for 4096KB
     repeated int32 free_pages_count = 4;
@@ -63,19 +62,19 @@
 // Next tag: 9
 message BlockProto {
 
-    int32 node = 1;
+    optional int32 node = 1;
 
-    string zone = 2;
+    optional string zone = 2;
 
-    int32 unmovable = 3;
+    optional int32 unmovable = 3;
 
-    int32 reclaimable = 4;
+    optional int32 reclaimable = 4;
 
-    int32 movable = 5;
+    optional int32 movable = 5;
 
-    int32 cma = 6;
+    optional int32 cma = 6;
 
-    int32 reserve = 7;
+    optional int32 reserve = 7;
 
-    int32 isolate = 8;
+    optional int32 isolate = 8;
 }
diff --git a/core/proto/android/os/patternmatcher.proto b/core/proto/android/os/patternmatcher.proto
index cd68245..d30315b 100644
--- a/core/proto/android/os/patternmatcher.proto
+++ b/core/proto/android/os/patternmatcher.proto
@@ -14,14 +14,13 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 option java_multiple_files = true;
 
 package android.os;
 
 message PatternMatcherProto {
-    string pattern = 1;
+    optional string pattern = 1;
 
     enum Type {
         TYPE_LITERAL = 0;
@@ -29,7 +28,7 @@
         TYPE_SIMPLE_GLOB = 2;
         TYPE_ADVANCED_GLOB = 3;
     }
-    Type type = 2;
+    optional Type type = 2;
 
     // This data is too much for dump
     // repeated int32 parsed_pattern = 3;
diff --git a/core/proto/android/os/procrank.proto b/core/proto/android/os/procrank.proto
index c7dbf4d..ab6a6a3 100644
--- a/core/proto/android/os/procrank.proto
+++ b/core/proto/android/os/procrank.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 option java_multiple_files = true;
 option java_outer_classname = "ProcrankProto";
 
@@ -27,56 +26,56 @@
     repeated ProcessProto processes = 1;
 
     // Summary
-    SummaryProto summary = 2;
+    optional SummaryProto summary = 2;
 }
 
 // Next Tag: 11
 message ProcessProto {
     // ID of the process
-    int32 pid = 1;
+    optional int32 pid = 1;
 
     // virtual set size, unit KB
-    int64 vss = 2;
+    optional int64 vss = 2;
 
     // resident set size, unit KB
-    int64 rss = 3;
+    optional int64 rss = 3;
 
     // proportional set size, unit KB
-    int64 pss = 4;
+    optional int64 pss = 4;
 
     // unique set size, unit KB
-    int64 uss = 5;
+    optional int64 uss = 5;
 
     // swap size, unit KB
-    int64 swap = 6;
+    optional int64 swap = 6;
 
     // proportional swap size, unit KB
-    int64 pswap = 7;
+    optional int64 pswap = 7;
 
     // unique swap size, unit KB
-    int64 uswap = 8;
+    optional int64 uswap = 8;
 
     // zswap size, unit KB
-    int64 zswap = 9;
+    optional int64 zswap = 9;
 
     // process command
-    string cmdline = 10;
+    optional string cmdline = 10;
 }
 
 // Next Tag: 3
 message SummaryProto {
-    ProcessProto total = 1;
+    optional ProcessProto total = 1;
 
-    ZramProto zram = 2;
+    optional ZramProto zram = 2;
 
-    RamProto ram = 3;
+    optional RamProto ram = 3;
 }
 
 // TODO: sync on how to use these values
 message ZramProto {
-    string raw_text = 1;
+    optional string raw_text = 1;
 }
 
 message RamProto {
-    string raw_text = 1;
+    optional string raw_text = 1;
 }
diff --git a/core/proto/android/os/worksource.proto b/core/proto/android/os/worksource.proto
index c2aa5cb..c60edfc 100644
--- a/core/proto/android/os/worksource.proto
+++ b/core/proto/android/os/worksource.proto
@@ -14,16 +14,15 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 package android.os;
 
 option java_multiple_files = true;
 
 message WorkSourceProto {
     message WorkSourceContentProto {
-        int32 uid = 1;
-        string name = 2;
+        optional int32 uid = 1;
+        optional string name = 2;
     }
 
     repeated WorkSourceContentProto work_source_contents = 1;
diff --git a/core/proto/android/providers/settings.proto b/core/proto/android/providers/settings.proto
index 3db4df0..f092713 100644
--- a/core/proto/android/providers/settings.proto
+++ b/core/proto/android/providers/settings.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 package android.providers.settings;
 
 option java_multiple_files = true;
@@ -26,587 +25,587 @@
     repeated UserSettingsProto user_settings = 1;
 
     // Global settings
-    GlobalSettingsProto global_settings = 2;
+    optional GlobalSettingsProto global_settings = 2;
 }
 
 message UserSettingsProto {
     // Should be 0, 10, 11, 12, etc. where 0 is the owner.
-    int32 user_id = 1;
+    optional int32 user_id = 1;
 
     // The secure settings for this user
-    SecureSettingsProto secure_settings = 2;
+    optional SecureSettingsProto secure_settings = 2;
 
     // The system settings for this user
-    SystemSettingsProto system_settings = 3;
+    optional SystemSettingsProto system_settings = 3;
 }
 
 message GlobalSettingsProto {
     // Historical operations
     repeated SettingsOperationProto historical_op = 1;
 
-    SettingProto add_users_when_locked = 2;
-    SettingProto enable_accessibility_global_gesture_enabled = 3;
-    SettingProto airplane_mode_on = 4;
-    SettingProto theater_mode_on = 5;
-    SettingProto radio_bluetooth = 6;
-    SettingProto radio_wifi = 7;
-    SettingProto radio_wimax = 8;
-    SettingProto radio_cell = 9;
-    SettingProto radio_nfc = 10;
-    SettingProto airplane_mode_radios = 11;
-    SettingProto airplane_mode_toggleable_radios = 12;
-    SettingProto bluetooth_disabled_profiles = 13;
-    SettingProto bluetooth_interoperability_list = 14;
-    SettingProto wifi_sleep_policy = 15;
-    SettingProto auto_time = 16;
-    SettingProto auto_time_zone = 17;
-    SettingProto car_dock_sound = 18;
-    SettingProto car_undock_sound = 19;
-    SettingProto desk_dock_sound = 20;
-    SettingProto desk_undock_sound = 21;
-    SettingProto dock_sounds_enabled = 22;
-    SettingProto dock_sounds_enabled_when_accessibility = 23;
-    SettingProto lock_sound = 24;
-    SettingProto unlock_sound = 25;
-    SettingProto trusted_sound = 26;
-    SettingProto low_battery_sound = 27;
-    SettingProto power_sounds_enabled = 28;
-    SettingProto wireless_charging_started_sound = 29;
-    SettingProto charging_sounds_enabled = 30;
-    SettingProto stay_on_while_plugged_in = 31;
-    SettingProto bugreport_in_power_menu = 32;
-    SettingProto adb_enabled = 33;
-    SettingProto debug_view_attributes = 34;
-    SettingProto assisted_gps_enabled = 35;
-    SettingProto bluetooth_on = 36;
-    SettingProto cdma_cell_broadcast_sms = 37;
-    SettingProto cdma_roaming_mode = 38;
-    SettingProto cdma_subscription_mode = 39;
-    SettingProto data_activity_timeout_mobile = 40;
-    SettingProto data_activity_timeout_wifi = 41;
-    SettingProto data_roaming = 42;
-    SettingProto mdc_initial_max_retry = 43;
-    SettingProto force_allow_on_external = 44;
-    SettingProto development_force_resizable_activities = 45;
-    SettingProto development_enable_freeform_windows_support = 46;
-    SettingProto development_settings_enabled = 47;
-    SettingProto device_provisioned = 48;
-    SettingProto device_provisioning_mobile_data_enabled = 49;
-    SettingProto display_size_forced = 50;
-    SettingProto display_scaling_force = 51;
-    SettingProto download_max_bytes_over_mobile = 52;
-    SettingProto download_recommended_max_bytes_over_mobile = 53;
-    SettingProto hdmi_control_enabled = 54;
-    SettingProto hdmi_system_audio_control_enabled = 55;
-    SettingProto hdmi_control_auto_wakeup_enabled = 56;
-    SettingProto hdmi_control_auto_device_off_enabled = 57;
-    SettingProto mhl_input_switching_enabled = 58;
-    SettingProto mhl_power_charge_enabled = 59;
-    SettingProto mobile_data = 60;
-    SettingProto mobile_data_always_on = 61;
-    SettingProto connectivity_metrics_buffer_size = 62;
-    SettingProto netstats_enabled = 63;
-    SettingProto netstats_poll_interval = 64;
-    SettingProto netstats_time_cache_max_age = 65;
-    SettingProto netstats_global_alert_bytes = 66;
-    SettingProto netstats_sample_enabled = 67;
-    SettingProto netstats_dev_bucket_duration = 68;
-    SettingProto netstats_dev_persist_bytes = 69;
-    SettingProto netstats_dev_rotate_age = 70;
-    SettingProto netstats_dev_delete_age = 71;
-    SettingProto netstats_uid_bucket_duration = 72;
-    SettingProto netstats_uid_persist_bytes = 73;
-    SettingProto netstats_uid_rotate_age = 74;
-    SettingProto netstats_uid_delete_age = 75;
-    SettingProto netstats_uid_tag_bucket_duration = 76;
-    SettingProto netstats_uid_tag_persist_bytes = 77;
-    SettingProto netstats_uid_tag_rotate_age = 78;
-    SettingProto netstats_uid_tag_delete_age = 79;
-    SettingProto network_preference = 80;
-    SettingProto network_scorer_app = 81;
-    SettingProto nitz_update_diff = 82;
-    SettingProto nitz_update_spacing = 83;
-    SettingProto ntp_server = 84;
-    SettingProto ntp_timeout = 85;
-    SettingProto storage_benchmark_interval = 86;
-    SettingProto dns_resolver_sample_validity_seconds = 87;
-    SettingProto dns_resolver_success_threshold_percent = 88;
-    SettingProto dns_resolver_min_samples = 89;
-    SettingProto dns_resolver_max_samples = 90;
-    SettingProto ota_disable_automatic_update = 91;
-    SettingProto package_verifier_enable = 92;
-    SettingProto package_verifier_timeout = 93;
-    SettingProto package_verifier_default_response = 94;
-    SettingProto package_verifier_setting_visible = 95;
-    SettingProto package_verifier_include_adb = 96;
-    SettingProto fstrim_mandatory_interval = 97;
-    SettingProto pdp_watchdog_poll_interval_ms = 98;
-    SettingProto pdp_watchdog_long_poll_interval_ms = 99;
-    SettingProto pdp_watchdog_error_poll_interval_ms = 100;
-    SettingProto pdp_watchdog_trigger_packet_count = 101;
-    SettingProto pdp_watchdog_error_poll_count = 102;
-    SettingProto pdp_watchdog_max_pdp_reset_fail_count = 103;
-    SettingProto setup_prepaid_data_service_url = 105;
-    SettingProto setup_prepaid_detection_target_url = 106;
-    SettingProto setup_prepaid_detection_redir_host = 107;
-    SettingProto sms_outgoing_check_interval_ms = 108;
-    SettingProto sms_outgoing_check_max_count = 109;
-    SettingProto sms_short_code_confirmation = 110;
-    SettingProto sms_short_code_rule = 111;
-    SettingProto tcp_default_init_rwnd = 112;
-    SettingProto tether_supported = 113;
-    SettingProto tether_dun_required = 114;
-    SettingProto tether_dun_apn = 115;
-    SettingProto carrier_app_whitelist = 116;
-    SettingProto usb_mass_storage_enabled = 117;
-    SettingProto use_google_mail = 118;
-    SettingProto webview_data_reduction_proxy_key = 119;
-    SettingProto webview_fallback_logic_enabled = 120;
-    SettingProto webview_provider = 121;
-    SettingProto webview_multiprocess = 122;
-    SettingProto network_switch_notification_daily_limit = 123;
-    SettingProto network_switch_notification_rate_limit_millis = 124;
-    SettingProto network_avoid_bad_wifi = 125;
-    SettingProto wifi_display_on = 126;
-    SettingProto wifi_display_certification_on = 127;
-    SettingProto wifi_display_wps_config = 128;
-    SettingProto wifi_networks_available_notification_on = 129;
-    SettingProto wimax_networks_available_notification_on = 130;
-    SettingProto wifi_networks_available_repeat_delay = 131;
-    SettingProto wifi_country_code = 132;
-    SettingProto wifi_framework_scan_interval_ms = 133;
-    SettingProto wifi_idle_ms = 134;
-    SettingProto wifi_num_open_networks_kept = 135;
-    SettingProto wifi_on = 136;
-    SettingProto wifi_scan_always_available = 137;
-    SettingProto wifi_wakeup_enabled = 138;
-    SettingProto network_recommendations_enabled = 139;
-    SettingProto ble_scan_always_available = 140;
-    SettingProto wifi_saved_state = 141;
-    SettingProto wifi_supplicant_scan_interval_ms = 142;
-    SettingProto wifi_enhanced_auto_join = 143;
-    SettingProto wifi_network_show_rssi = 144;
-    SettingProto wifi_scan_interval_when_p2p_connected_ms = 145;
-    SettingProto wifi_watchdog_on = 146;
-    SettingProto wifi_watchdog_poor_network_test_enabled = 147;
-    SettingProto wifi_suspend_optimizations_enabled = 148;
-    SettingProto wifi_verbose_logging_enabled = 149;
-    SettingProto wifi_max_dhcp_retry_count = 150;
-    SettingProto wifi_mobile_data_transition_wakelock_timeout_ms = 151;
-    SettingProto wifi_device_owner_configs_lockdown = 152;
-    SettingProto wifi_frequency_band = 153;
-    SettingProto wifi_p2p_device_name = 154;
-    SettingProto wifi_reenable_delay_ms = 155;
-    SettingProto wifi_ephemeral_out_of_range_timeout_ms = 156;
-    SettingProto data_stall_alarm_non_aggressive_delay_in_ms = 157;
-    SettingProto data_stall_alarm_aggressive_delay_in_ms = 158;
-    SettingProto provisioning_apn_alarm_delay_in_ms = 159;
-    SettingProto gprs_register_check_period_ms = 160;
-    SettingProto wtf_is_fatal = 161;
-    SettingProto mode_ringer = 162;
-    SettingProto overlay_display_devices = 163;
-    SettingProto battery_discharge_duration_threshold = 164;
-    SettingProto battery_discharge_threshold = 165;
-    SettingProto send_action_app_error = 166;
-    SettingProto dropbox_age_seconds = 167;
-    SettingProto dropbox_max_files = 168;
-    SettingProto dropbox_quota_kb = 169;
-    SettingProto dropbox_quota_percent = 170;
-    SettingProto dropbox_reserve_percent = 171;
-    SettingProto dropbox_tag_prefix = 172;
-    SettingProto error_logcat_prefix = 173;
-    SettingProto sys_free_storage_log_interval = 174;
-    SettingProto disk_free_change_reporting_threshold = 175;
-    SettingProto sys_storage_threshold_percentage = 176;
-    SettingProto sys_storage_threshold_max_bytes = 177;
-    SettingProto sys_storage_full_threshold_bytes = 178;
-    SettingProto sync_max_retry_delay_in_seconds = 179;
-    SettingProto connectivity_change_delay = 180;
-    SettingProto connectivity_sampling_interval_in_seconds = 181;
-    SettingProto pac_change_delay = 182;
-    SettingProto captive_portal_mode = 183;
-    SettingProto captive_portal_server = 184;
-    SettingProto captive_portal_https_url = 185;
-    SettingProto captive_portal_http_url = 186;
-    SettingProto captive_portal_fallback_url = 187;
-    SettingProto captive_portal_use_https = 188;
-    SettingProto captive_portal_user_agent = 189;
-    SettingProto nsd_on = 190;
-    SettingProto set_install_location = 191;
-    SettingProto default_install_location = 192;
-    SettingProto inet_condition_debounce_up_delay = 193;
-    SettingProto inet_condition_debounce_down_delay = 194;
-    SettingProto read_external_storage_enforced_default = 195;
-    SettingProto http_proxy = 196;
-    SettingProto global_http_proxy_host = 197;
-    SettingProto global_http_proxy_port = 198;
-    SettingProto global_http_proxy_exclusion_list = 199;
-    SettingProto global_http_proxy_pac = 200;
-    SettingProto set_global_http_proxy = 201;
-    SettingProto default_dns_server = 202;
-    SettingProto bluetooth_headset_priority_prefix = 203;
-    SettingProto bluetooth_a2dp_sink_priority_prefix = 204;
-    SettingProto bluetooth_a2dp_src_priority_prefix = 205;
-    SettingProto bluetooth_input_device_priority_prefix = 206;
-    SettingProto bluetooth_map_priority_prefix = 207;
-    SettingProto bluetooth_map_client_priority_prefix = 208;
-    SettingProto bluetooth_pbap_client_priority_prefix = 209;
-    SettingProto bluetooth_sap_priority_prefix = 210;
-    SettingProto bluetooth_pan_priority_prefix = 211;
-    SettingProto device_idle_constants = 212;
-    SettingProto device_idle_constants_watch = 213;
-    SettingProto app_idle_constants = 214;
-    SettingProto alarm_manager_constants = 215;
-    SettingProto job_scheduler_constants = 216;
-    SettingProto shortcut_manager_constants = 217;
-    SettingProto window_animation_scale = 218;
-    SettingProto transition_animation_scale = 219;
-    SettingProto animator_duration_scale = 220;
-    SettingProto fancy_ime_animations = 221;
-    SettingProto compatibility_mode = 222;
-    SettingProto emergency_tone = 223;
-    SettingProto call_auto_retry = 224;
-    SettingProto emergency_affordance_needed = 225;
-    SettingProto preferred_network_mode = 226;
-    SettingProto debug_app = 227;
-    SettingProto wait_for_debugger = 228;
-    SettingProto low_power_mode = 229;
-    SettingProto low_power_mode_trigger_level = 230;
-    SettingProto always_finish_activities = 231;
-    SettingProto dock_audio_media_enabled = 232;
-    SettingProto encoded_surround_output = 233;
-    SettingProto audio_safe_volume_state = 234;
-    SettingProto tzinfo_update_content_url = 235;
-    SettingProto tzinfo_update_metadata_url = 236;
-    SettingProto selinux_update_content_url = 237;
-    SettingProto selinux_update_metadata_url = 238;
-    SettingProto sms_short_codes_update_content_url = 239;
-    SettingProto sms_short_codes_update_metadata_url = 240;
-    SettingProto apn_db_update_content_url = 241;
-    SettingProto apn_db_update_metadata_url = 242;
-    SettingProto cert_pin_update_content_url = 243;
-    SettingProto cert_pin_update_metadata_url = 244;
-    SettingProto intent_firewall_update_content_url = 245;
-    SettingProto intent_firewall_update_metadata_url = 246;
-    SettingProto selinux_status = 247;
-    SettingProto development_force_rtl = 248;
-    SettingProto low_battery_sound_timeout = 249;
-    SettingProto wifi_bounce_delay_override_ms = 250;
-    SettingProto policy_control = 251;
-    SettingProto zen_mode = 252;
-    SettingProto zen_mode_ringer_level = 253;
-    SettingProto zen_mode_config_etag = 254;
-    SettingProto heads_up_notifications_enabled = 255;
-    SettingProto device_name = 256;
-    SettingProto network_scoring_provisioned = 257;
-    SettingProto require_password_to_decrypt = 258;
-    SettingProto enhanced_4g_mode_enabled = 259;
-    SettingProto vt_ims_enabled = 260;
-    SettingProto wfc_ims_enabled = 261;
-    SettingProto wfc_ims_mode = 262;
-    SettingProto wfc_ims_roaming_mode = 263;
-    SettingProto wfc_ims_roaming_enabled = 264;
-    SettingProto lte_service_forced = 265;
-    SettingProto ephemeral_cookie_max_size_bytes = 266;
-    SettingProto enable_ephemeral_feature = 267;
-    SettingProto installed_instant_app_min_cache_period = 268;
-    SettingProto allow_user_switching_when_system_user_locked = 269;
-    SettingProto boot_count = 270;
-    SettingProto safe_boot_disallowed = 271;
-    SettingProto device_demo_mode = 272;
-    SettingProto database_downgrade_reason = 274;
-    SettingProto contacts_database_wal_enabled = 275;
-    SettingProto multi_sim_voice_call_subscription = 276;
-    SettingProto multi_sim_voice_prompt = 277;
-    SettingProto multi_sim_data_call_subscription = 278;
-    SettingProto multi_sim_sms_subscription = 279;
-    SettingProto multi_sim_sms_prompt = 280;
-    SettingProto new_contact_aggregator = 281;
-    SettingProto contact_metadata_sync_enabled = 282;
-    SettingProto enable_cellular_on_boot = 283;
-    SettingProto max_notification_enqueue_rate = 284;
-    SettingProto cell_on = 285;
-    SettingProto network_recommendations_package = 286;
-    SettingProto bluetooth_a2dp_supports_optional_codecs_prefix = 287;
-    SettingProto bluetooth_a2dp_optional_codecs_enabled_prefix = 288;
-    SettingProto installed_instant_app_max_cache_period = 289;
-    SettingProto uninstalled_instant_app_min_cache_period = 290;
-    SettingProto uninstalled_instant_app_max_cache_period = 291;
-    SettingProto unused_static_shared_lib_min_cache_period = 292;
+    optional SettingProto add_users_when_locked = 2;
+    optional SettingProto enable_accessibility_global_gesture_enabled = 3;
+    optional SettingProto airplane_mode_on = 4;
+    optional SettingProto theater_mode_on = 5;
+    optional SettingProto radio_bluetooth = 6;
+    optional SettingProto radio_wifi = 7;
+    optional SettingProto radio_wimax = 8;
+    optional SettingProto radio_cell = 9;
+    optional SettingProto radio_nfc = 10;
+    optional SettingProto airplane_mode_radios = 11;
+    optional SettingProto airplane_mode_toggleable_radios = 12;
+    optional SettingProto bluetooth_disabled_profiles = 13;
+    optional SettingProto bluetooth_interoperability_list = 14;
+    optional SettingProto wifi_sleep_policy = 15;
+    optional SettingProto auto_time = 16;
+    optional SettingProto auto_time_zone = 17;
+    optional SettingProto car_dock_sound = 18;
+    optional SettingProto car_undock_sound = 19;
+    optional SettingProto desk_dock_sound = 20;
+    optional SettingProto desk_undock_sound = 21;
+    optional SettingProto dock_sounds_enabled = 22;
+    optional SettingProto dock_sounds_enabled_when_accessibility = 23;
+    optional SettingProto lock_sound = 24;
+    optional SettingProto unlock_sound = 25;
+    optional SettingProto trusted_sound = 26;
+    optional SettingProto low_battery_sound = 27;
+    optional SettingProto power_sounds_enabled = 28;
+    optional SettingProto wireless_charging_started_sound = 29;
+    optional SettingProto charging_sounds_enabled = 30;
+    optional SettingProto stay_on_while_plugged_in = 31;
+    optional SettingProto bugreport_in_power_menu = 32;
+    optional SettingProto adb_enabled = 33;
+    optional SettingProto debug_view_attributes = 34;
+    optional SettingProto assisted_gps_enabled = 35;
+    optional SettingProto bluetooth_on = 36;
+    optional SettingProto cdma_cell_broadcast_sms = 37;
+    optional SettingProto cdma_roaming_mode = 38;
+    optional SettingProto cdma_subscription_mode = 39;
+    optional SettingProto data_activity_timeout_mobile = 40;
+    optional SettingProto data_activity_timeout_wifi = 41;
+    optional SettingProto data_roaming = 42;
+    optional SettingProto mdc_initial_max_retry = 43;
+    optional SettingProto force_allow_on_external = 44;
+    optional SettingProto development_force_resizable_activities = 45;
+    optional SettingProto development_enable_freeform_windows_support = 46;
+    optional SettingProto development_settings_enabled = 47;
+    optional SettingProto device_provisioned = 48;
+    optional SettingProto device_provisioning_mobile_data_enabled = 49;
+    optional SettingProto display_size_forced = 50;
+    optional SettingProto display_scaling_force = 51;
+    optional SettingProto download_max_bytes_over_mobile = 52;
+    optional SettingProto download_recommended_max_bytes_over_mobile = 53;
+    optional SettingProto hdmi_control_enabled = 54;
+    optional SettingProto hdmi_system_audio_control_enabled = 55;
+    optional SettingProto hdmi_control_auto_wakeup_enabled = 56;
+    optional SettingProto hdmi_control_auto_device_off_enabled = 57;
+    optional SettingProto mhl_input_switching_enabled = 58;
+    optional SettingProto mhl_power_charge_enabled = 59;
+    optional SettingProto mobile_data = 60;
+    optional SettingProto mobile_data_always_on = 61;
+    optional SettingProto connectivity_metrics_buffer_size = 62;
+    optional SettingProto netstats_enabled = 63;
+    optional SettingProto netstats_poll_interval = 64;
+    optional SettingProto netstats_time_cache_max_age = 65;
+    optional SettingProto netstats_global_alert_bytes = 66;
+    optional SettingProto netstats_sample_enabled = 67;
+    optional SettingProto netstats_dev_bucket_duration = 68;
+    optional SettingProto netstats_dev_persist_bytes = 69;
+    optional SettingProto netstats_dev_rotate_age = 70;
+    optional SettingProto netstats_dev_delete_age = 71;
+    optional SettingProto netstats_uid_bucket_duration = 72;
+    optional SettingProto netstats_uid_persist_bytes = 73;
+    optional SettingProto netstats_uid_rotate_age = 74;
+    optional SettingProto netstats_uid_delete_age = 75;
+    optional SettingProto netstats_uid_tag_bucket_duration = 76;
+    optional SettingProto netstats_uid_tag_persist_bytes = 77;
+    optional SettingProto netstats_uid_tag_rotate_age = 78;
+    optional SettingProto netstats_uid_tag_delete_age = 79;
+    optional SettingProto network_preference = 80;
+    optional SettingProto network_scorer_app = 81;
+    optional SettingProto nitz_update_diff = 82;
+    optional SettingProto nitz_update_spacing = 83;
+    optional SettingProto ntp_server = 84;
+    optional SettingProto ntp_timeout = 85;
+    optional SettingProto storage_benchmark_interval = 86;
+    optional SettingProto dns_resolver_sample_validity_seconds = 87;
+    optional SettingProto dns_resolver_success_threshold_percent = 88;
+    optional SettingProto dns_resolver_min_samples = 89;
+    optional SettingProto dns_resolver_max_samples = 90;
+    optional SettingProto ota_disable_automatic_update = 91;
+    optional SettingProto package_verifier_enable = 92;
+    optional SettingProto package_verifier_timeout = 93;
+    optional SettingProto package_verifier_default_response = 94;
+    optional SettingProto package_verifier_setting_visible = 95;
+    optional SettingProto package_verifier_include_adb = 96;
+    optional SettingProto fstrim_mandatory_interval = 97;
+    optional SettingProto pdp_watchdog_poll_interval_ms = 98;
+    optional SettingProto pdp_watchdog_long_poll_interval_ms = 99;
+    optional SettingProto pdp_watchdog_error_poll_interval_ms = 100;
+    optional SettingProto pdp_watchdog_trigger_packet_count = 101;
+    optional SettingProto pdp_watchdog_error_poll_count = 102;
+    optional SettingProto pdp_watchdog_max_pdp_reset_fail_count = 103;
+    optional SettingProto setup_prepaid_data_service_url = 105;
+    optional SettingProto setup_prepaid_detection_target_url = 106;
+    optional SettingProto setup_prepaid_detection_redir_host = 107;
+    optional SettingProto sms_outgoing_check_interval_ms = 108;
+    optional SettingProto sms_outgoing_check_max_count = 109;
+    optional SettingProto sms_short_code_confirmation = 110;
+    optional SettingProto sms_short_code_rule = 111;
+    optional SettingProto tcp_default_init_rwnd = 112;
+    optional SettingProto tether_supported = 113;
+    optional SettingProto tether_dun_required = 114;
+    optional SettingProto tether_dun_apn = 115;
+    optional SettingProto carrier_app_whitelist = 116;
+    optional SettingProto usb_mass_storage_enabled = 117;
+    optional SettingProto use_google_mail = 118;
+    optional SettingProto webview_data_reduction_proxy_key = 119;
+    optional SettingProto webview_fallback_logic_enabled = 120;
+    optional SettingProto webview_provider = 121;
+    optional SettingProto webview_multiprocess = 122;
+    optional SettingProto network_switch_notification_daily_limit = 123;
+    optional SettingProto network_switch_notification_rate_limit_millis = 124;
+    optional SettingProto network_avoid_bad_wifi = 125;
+    optional SettingProto wifi_display_on = 126;
+    optional SettingProto wifi_display_certification_on = 127;
+    optional SettingProto wifi_display_wps_config = 128;
+    optional SettingProto wifi_networks_available_notification_on = 129;
+    optional SettingProto wimax_networks_available_notification_on = 130;
+    optional SettingProto wifi_networks_available_repeat_delay = 131;
+    optional SettingProto wifi_country_code = 132;
+    optional SettingProto wifi_framework_scan_interval_ms = 133;
+    optional SettingProto wifi_idle_ms = 134;
+    optional SettingProto wifi_num_open_networks_kept = 135;
+    optional SettingProto wifi_on = 136;
+    optional SettingProto wifi_scan_always_available = 137;
+    optional SettingProto wifi_wakeup_enabled = 138;
+    optional SettingProto network_recommendations_enabled = 139;
+    optional SettingProto ble_scan_always_available = 140;
+    optional SettingProto wifi_saved_state = 141;
+    optional SettingProto wifi_supplicant_scan_interval_ms = 142;
+    optional SettingProto wifi_enhanced_auto_join = 143;
+    optional SettingProto wifi_network_show_rssi = 144;
+    optional SettingProto wifi_scan_interval_when_p2p_connected_ms = 145;
+    optional SettingProto wifi_watchdog_on = 146;
+    optional SettingProto wifi_watchdog_poor_network_test_enabled = 147;
+    optional SettingProto wifi_suspend_optimizations_enabled = 148;
+    optional SettingProto wifi_verbose_logging_enabled = 149;
+    optional SettingProto wifi_max_dhcp_retry_count = 150;
+    optional SettingProto wifi_mobile_data_transition_wakelock_timeout_ms = 151;
+    optional SettingProto wifi_device_owner_configs_lockdown = 152;
+    optional SettingProto wifi_frequency_band = 153;
+    optional SettingProto wifi_p2p_device_name = 154;
+    optional SettingProto wifi_reenable_delay_ms = 155;
+    optional SettingProto wifi_ephemeral_out_of_range_timeout_ms = 156;
+    optional SettingProto data_stall_alarm_non_aggressive_delay_in_ms = 157;
+    optional SettingProto data_stall_alarm_aggressive_delay_in_ms = 158;
+    optional SettingProto provisioning_apn_alarm_delay_in_ms = 159;
+    optional SettingProto gprs_register_check_period_ms = 160;
+    optional SettingProto wtf_is_fatal = 161;
+    optional SettingProto mode_ringer = 162;
+    optional SettingProto overlay_display_devices = 163;
+    optional SettingProto battery_discharge_duration_threshold = 164;
+    optional SettingProto battery_discharge_threshold = 165;
+    optional SettingProto send_action_app_error = 166;
+    optional SettingProto dropbox_age_seconds = 167;
+    optional SettingProto dropbox_max_files = 168;
+    optional SettingProto dropbox_quota_kb = 169;
+    optional SettingProto dropbox_quota_percent = 170;
+    optional SettingProto dropbox_reserve_percent = 171;
+    optional SettingProto dropbox_tag_prefix = 172;
+    optional SettingProto error_logcat_prefix = 173;
+    optional SettingProto sys_free_storage_log_interval = 174;
+    optional SettingProto disk_free_change_reporting_threshold = 175;
+    optional SettingProto sys_storage_threshold_percentage = 176;
+    optional SettingProto sys_storage_threshold_max_bytes = 177;
+    optional SettingProto sys_storage_full_threshold_bytes = 178;
+    optional SettingProto sync_max_retry_delay_in_seconds = 179;
+    optional SettingProto connectivity_change_delay = 180;
+    optional SettingProto connectivity_sampling_interval_in_seconds = 181;
+    optional SettingProto pac_change_delay = 182;
+    optional SettingProto captive_portal_mode = 183;
+    optional SettingProto captive_portal_server = 184;
+    optional SettingProto captive_portal_https_url = 185;
+    optional SettingProto captive_portal_http_url = 186;
+    optional SettingProto captive_portal_fallback_url = 187;
+    optional SettingProto captive_portal_use_https = 188;
+    optional SettingProto captive_portal_user_agent = 189;
+    optional SettingProto nsd_on = 190;
+    optional SettingProto set_install_location = 191;
+    optional SettingProto default_install_location = 192;
+    optional SettingProto inet_condition_debounce_up_delay = 193;
+    optional SettingProto inet_condition_debounce_down_delay = 194;
+    optional SettingProto read_external_storage_enforced_default = 195;
+    optional SettingProto http_proxy = 196;
+    optional SettingProto global_http_proxy_host = 197;
+    optional SettingProto global_http_proxy_port = 198;
+    optional SettingProto global_http_proxy_exclusion_list = 199;
+    optional SettingProto global_http_proxy_pac = 200;
+    optional SettingProto set_global_http_proxy = 201;
+    optional SettingProto default_dns_server = 202;
+    optional SettingProto bluetooth_headset_priority_prefix = 203;
+    optional SettingProto bluetooth_a2dp_sink_priority_prefix = 204;
+    optional SettingProto bluetooth_a2dp_src_priority_prefix = 205;
+    optional SettingProto bluetooth_input_device_priority_prefix = 206;
+    optional SettingProto bluetooth_map_priority_prefix = 207;
+    optional SettingProto bluetooth_map_client_priority_prefix = 208;
+    optional SettingProto bluetooth_pbap_client_priority_prefix = 209;
+    optional SettingProto bluetooth_sap_priority_prefix = 210;
+    optional SettingProto bluetooth_pan_priority_prefix = 211;
+    optional SettingProto device_idle_constants = 212;
+    optional SettingProto device_idle_constants_watch = 213;
+    optional SettingProto app_idle_constants = 214;
+    optional SettingProto alarm_manager_constants = 215;
+    optional SettingProto job_scheduler_constants = 216;
+    optional SettingProto shortcut_manager_constants = 217;
+    optional SettingProto window_animation_scale = 218;
+    optional SettingProto transition_animation_scale = 219;
+    optional SettingProto animator_duration_scale = 220;
+    optional SettingProto fancy_ime_animations = 221;
+    optional SettingProto compatibility_mode = 222;
+    optional SettingProto emergency_tone = 223;
+    optional SettingProto call_auto_retry = 224;
+    optional SettingProto emergency_affordance_needed = 225;
+    optional SettingProto preferred_network_mode = 226;
+    optional SettingProto debug_app = 227;
+    optional SettingProto wait_for_debugger = 228;
+    optional SettingProto low_power_mode = 229;
+    optional SettingProto low_power_mode_trigger_level = 230;
+    optional SettingProto always_finish_activities = 231;
+    optional SettingProto dock_audio_media_enabled = 232;
+    optional SettingProto encoded_surround_output = 233;
+    optional SettingProto audio_safe_volume_state = 234;
+    optional SettingProto tzinfo_update_content_url = 235;
+    optional SettingProto tzinfo_update_metadata_url = 236;
+    optional SettingProto selinux_update_content_url = 237;
+    optional SettingProto selinux_update_metadata_url = 238;
+    optional SettingProto sms_short_codes_update_content_url = 239;
+    optional SettingProto sms_short_codes_update_metadata_url = 240;
+    optional SettingProto apn_db_update_content_url = 241;
+    optional SettingProto apn_db_update_metadata_url = 242;
+    optional SettingProto cert_pin_update_content_url = 243;
+    optional SettingProto cert_pin_update_metadata_url = 244;
+    optional SettingProto intent_firewall_update_content_url = 245;
+    optional SettingProto intent_firewall_update_metadata_url = 246;
+    optional SettingProto selinux_status = 247;
+    optional SettingProto development_force_rtl = 248;
+    optional SettingProto low_battery_sound_timeout = 249;
+    optional SettingProto wifi_bounce_delay_override_ms = 250;
+    optional SettingProto policy_control = 251;
+    optional SettingProto zen_mode = 252;
+    optional SettingProto zen_mode_ringer_level = 253;
+    optional SettingProto zen_mode_config_etag = 254;
+    optional SettingProto heads_up_notifications_enabled = 255;
+    optional SettingProto device_name = 256;
+    optional SettingProto network_scoring_provisioned = 257;
+    optional SettingProto require_password_to_decrypt = 258;
+    optional SettingProto enhanced_4g_mode_enabled = 259;
+    optional SettingProto vt_ims_enabled = 260;
+    optional SettingProto wfc_ims_enabled = 261;
+    optional SettingProto wfc_ims_mode = 262;
+    optional SettingProto wfc_ims_roaming_mode = 263;
+    optional SettingProto wfc_ims_roaming_enabled = 264;
+    optional SettingProto lte_service_forced = 265;
+    optional SettingProto ephemeral_cookie_max_size_bytes = 266;
+    optional SettingProto enable_ephemeral_feature = 267;
+    optional SettingProto installed_instant_app_min_cache_period = 268;
+    optional SettingProto allow_user_switching_when_system_user_locked = 269;
+    optional SettingProto boot_count = 270;
+    optional SettingProto safe_boot_disallowed = 271;
+    optional SettingProto device_demo_mode = 272;
+    optional SettingProto database_downgrade_reason = 274;
+    optional SettingProto contacts_database_wal_enabled = 275;
+    optional SettingProto multi_sim_voice_call_subscription = 276;
+    optional SettingProto multi_sim_voice_prompt = 277;
+    optional SettingProto multi_sim_data_call_subscription = 278;
+    optional SettingProto multi_sim_sms_subscription = 279;
+    optional SettingProto multi_sim_sms_prompt = 280;
+    optional SettingProto new_contact_aggregator = 281;
+    optional SettingProto contact_metadata_sync_enabled = 282;
+    optional SettingProto enable_cellular_on_boot = 283;
+    optional SettingProto max_notification_enqueue_rate = 284;
+    optional SettingProto cell_on = 285;
+    optional SettingProto network_recommendations_package = 286;
+    optional SettingProto bluetooth_a2dp_supports_optional_codecs_prefix = 287;
+    optional SettingProto bluetooth_a2dp_optional_codecs_enabled_prefix = 288;
+    optional SettingProto installed_instant_app_max_cache_period = 289;
+    optional SettingProto uninstalled_instant_app_min_cache_period = 290;
+    optional SettingProto uninstalled_instant_app_max_cache_period = 291;
+    optional SettingProto unused_static_shared_lib_min_cache_period = 292;
 }
 
 message SecureSettingsProto {
     // Historical operations
     repeated SettingsOperationProto historical_op = 1;
 
-    SettingProto android_id = 2;
-    SettingProto default_input_method = 3;
-    SettingProto selected_input_method_subtype = 4;
-    SettingProto input_methods_subtype_history = 5;
-    SettingProto input_method_selector_visibility = 6;
-    SettingProto voice_interaction_service = 7;
-    SettingProto autofill_service = 8;
-    SettingProto bluetooth_hci_log = 9;
-    SettingProto user_setup_complete = 10;
-    SettingProto completed_category_prefix = 11;
-    SettingProto enabled_input_methods = 12;
-    SettingProto disabled_system_input_methods = 13;
-    SettingProto show_ime_with_hard_keyboard = 14;
-    SettingProto always_on_vpn_app = 15;
-    SettingProto always_on_vpn_lockdown = 16;
-    SettingProto install_non_market_apps = 17;
-    SettingProto location_mode = 18;
-    SettingProto location_previous_mode = 19;
-    SettingProto lock_to_app_exit_locked = 20;
-    SettingProto lock_screen_lock_after_timeout = 21;
-    SettingProto lock_screen_allow_remote_input = 22;
-    SettingProto show_note_about_notification_hiding = 23;
-    SettingProto trust_agents_initialized = 24;
-    SettingProto parental_control_enabled = 25;
-    SettingProto parental_control_last_update = 26;
-    SettingProto parental_control_redirect_url = 27;
-    SettingProto settings_classname = 28;
-    SettingProto accessibility_enabled = 29;
-    SettingProto touch_exploration_enabled = 30;
-    SettingProto enabled_accessibility_services = 31;
-    SettingProto touch_exploration_granted_accessibility_services = 32;
-    SettingProto accessibility_speak_password = 33;
-    SettingProto accessibility_high_text_contrast_enabled = 34;
-    SettingProto accessibility_script_injection = 35;
-    SettingProto accessibility_screen_reader_url = 36;
-    SettingProto accessibility_web_content_key_bindings = 37;
-    SettingProto accessibility_display_magnification_enabled = 38;
-    SettingProto accessibility_display_magnification_scale = 39;
-    SettingProto accessibility_soft_keyboard_mode = 40;
-    SettingProto accessibility_captioning_enabled = 41;
-    SettingProto accessibility_captioning_locale = 42;
-    SettingProto accessibility_captioning_preset = 43;
-    SettingProto accessibility_captioning_background_color = 44;
-    SettingProto accessibility_captioning_foreground_color = 45;
-    SettingProto accessibility_captioning_edge_type = 46;
-    SettingProto accessibility_captioning_edge_color = 47;
-    SettingProto accessibility_captioning_window_color = 48;
-    SettingProto accessibility_captioning_typeface = 49;
-    SettingProto accessibility_captioning_font_scale = 50;
-    SettingProto accessibility_display_inversion_enabled = 51;
-    SettingProto accessibility_display_daltonizer_enabled = 52;
-    SettingProto accessibility_display_daltonizer = 53;
-    SettingProto accessibility_autoclick_enabled = 54;
-    SettingProto accessibility_autoclick_delay = 55;
-    SettingProto accessibility_large_pointer_icon = 56;
-    SettingProto long_press_timeout = 57;
-    SettingProto multi_press_timeout = 58;
-    SettingProto enabled_print_services = 59;
-    SettingProto disabled_print_services = 60;
-    SettingProto display_density_forced = 61;
-    SettingProto tts_default_rate = 62;
-    SettingProto tts_default_pitch = 63;
-    SettingProto tts_default_synth = 64;
-    SettingProto tts_default_locale = 65;
-    SettingProto tts_enabled_plugins = 66;
-    SettingProto connectivity_release_pending_intent_delay_ms = 67;
-    SettingProto allowed_geolocation_origins = 68;
-    SettingProto preferred_tty_mode = 69;
-    SettingProto enhanced_voice_privacy_enabled = 70;
-    SettingProto tty_mode_enabled = 71;
-    SettingProto backup_enabled = 72;
-    SettingProto backup_auto_restore = 73;
-    SettingProto backup_provisioned = 74;
-    SettingProto backup_transport = 75;
-    SettingProto last_setup_shown = 76;
-    SettingProto search_global_search_activity = 77;
-    SettingProto search_num_promoted_sources = 78;
-    SettingProto search_max_results_to_display = 79;
-    SettingProto search_max_results_per_source = 80;
-    SettingProto search_web_results_override_limit = 81;
-    SettingProto search_promoted_source_deadline_millis = 82;
-    SettingProto search_source_timeout_millis = 83;
-    SettingProto search_prefill_millis = 84;
-    SettingProto search_max_stat_age_millis = 85;
-    SettingProto search_max_source_event_age_millis = 86;
-    SettingProto search_min_impressions_for_source_ranking = 87;
-    SettingProto search_min_clicks_for_source_ranking = 88;
-    SettingProto search_max_shortcuts_returned = 89;
-    SettingProto search_query_thread_core_pool_size = 90;
-    SettingProto search_query_thread_max_pool_size = 91;
-    SettingProto search_shortcut_refresh_core_pool_size = 92;
-    SettingProto search_shortcut_refresh_max_pool_size = 93;
-    SettingProto search_thread_keepalive_seconds = 94;
-    SettingProto search_per_source_concurrent_query_limit = 95;
-    SettingProto mount_play_notification_snd = 96;
-    SettingProto mount_ums_autostart = 97;
-    SettingProto mount_ums_prompt = 98;
-    SettingProto mount_ums_notify_enabled = 99;
-    SettingProto anr_show_background = 100;
-    SettingProto voice_recognition_service = 101;
-    SettingProto package_verifier_user_consent = 102;
-    SettingProto selected_spell_checker = 103;
-    SettingProto selected_spell_checker_subtype = 104;
-    SettingProto spell_checker_enabled = 105;
-    SettingProto incall_power_button_behavior = 106;
-    SettingProto incall_back_button_behavior = 107;
-    SettingProto wake_gesture_enabled = 108;
-    SettingProto doze_enabled = 109;
-    SettingProto doze_always_on = 110;
-    SettingProto doze_pulse_on_pick_up = 111;
-    SettingProto doze_pulse_on_double_tap = 112;
-    SettingProto ui_night_mode = 113;
-    SettingProto screensaver_enabled = 114;
-    SettingProto screensaver_components = 115;
-    SettingProto screensaver_activate_on_dock = 116;
-    SettingProto screensaver_activate_on_sleep = 117;
-    SettingProto screensaver_default_component = 118;
-    SettingProto nfc_payment_default_component = 119;
-    SettingProto nfc_payment_foreground = 120;
-    SettingProto sms_default_application = 121;
-    SettingProto dialer_default_application = 122;
-    SettingProto emergency_assistance_application = 123;
-    SettingProto assist_structure_enabled = 124;
-    SettingProto assist_screenshot_enabled = 125;
-    SettingProto assist_disclosure_enabled = 126;
-    SettingProto enabled_notification_assistant = 127;
-    SettingProto enabled_notification_listeners = 128;
-    SettingProto enabled_notification_policy_access_packages = 129;
-    SettingProto sync_parent_sounds = 130;
-    SettingProto immersive_mode_confirmations = 131;
-    SettingProto print_service_search_uri = 132;
-    SettingProto payment_service_search_uri = 133;
-    SettingProto skip_first_use_hints = 134;
-    SettingProto unsafe_volume_music_active_ms = 135;
-    SettingProto lock_screen_show_notifications = 136;
-    SettingProto tv_input_hidden_inputs = 137;
-    SettingProto tv_input_custom_labels = 138;
-    SettingProto usb_audio_automatic_routing_disabled = 139;
-    SettingProto sleep_timeout = 140;
-    SettingProto double_tap_to_wake = 141;
-    SettingProto assistant = 142;
-    SettingProto camera_gesture_disabled = 143;
-    SettingProto camera_double_tap_power_gesture_disabled = 144;
-    SettingProto camera_double_twist_to_flip_enabled = 145;
-    SettingProto night_display_activated = 146;
-    SettingProto night_display_auto_mode = 147;
-    SettingProto night_display_custom_start_time = 148;
-    SettingProto night_display_custom_end_time = 149;
-    SettingProto brightness_use_twilight = 150;
-    SettingProto enabled_vr_listeners = 151;
-    SettingProto vr_display_mode = 152;
-    SettingProto carrier_apps_handled = 153;
-    SettingProto managed_profile_contact_remote_search = 154;
-    SettingProto automatic_storage_manager_enabled = 155;
-    SettingProto automatic_storage_manager_days_to_retain = 156;
-    SettingProto automatic_storage_manager_bytes_cleared = 157;
-    SettingProto automatic_storage_manager_last_run = 158;
-    SettingProto system_navigation_keys_enabled = 159;
-    SettingProto downloads_backup_enabled = 160;
-    SettingProto downloads_backup_allow_metered = 161;
-    SettingProto downloads_backup_charging_only = 162;
-    SettingProto automatic_storage_manager_downloads_days_to_retain = 163;
-    SettingProto qs_tiles = 164;
-    SettingProto demo_user_setup_complete = 165;
-    SettingProto instant_apps_enabled = 166;
-    SettingProto device_paired = 167;
-    SettingProto notification_badging = 168;
-    SettingProto backup_manager_constants = 169;
+    optional SettingProto android_id = 2;
+    optional SettingProto default_input_method = 3;
+    optional SettingProto selected_input_method_subtype = 4;
+    optional SettingProto input_methods_subtype_history = 5;
+    optional SettingProto input_method_selector_visibility = 6;
+    optional SettingProto voice_interaction_service = 7;
+    optional SettingProto autofill_service = 8;
+    optional SettingProto bluetooth_hci_log = 9;
+    optional SettingProto user_setup_complete = 10;
+    optional SettingProto completed_category_prefix = 11;
+    optional SettingProto enabled_input_methods = 12;
+    optional SettingProto disabled_system_input_methods = 13;
+    optional SettingProto show_ime_with_hard_keyboard = 14;
+    optional SettingProto always_on_vpn_app = 15;
+    optional SettingProto always_on_vpn_lockdown = 16;
+    optional SettingProto install_non_market_apps = 17;
+    optional SettingProto location_mode = 18;
+    optional SettingProto location_previous_mode = 19;
+    optional SettingProto lock_to_app_exit_locked = 20;
+    optional SettingProto lock_screen_lock_after_timeout = 21;
+    optional SettingProto lock_screen_allow_remote_input = 22;
+    optional SettingProto show_note_about_notification_hiding = 23;
+    optional SettingProto trust_agents_initialized = 24;
+    optional SettingProto parental_control_enabled = 25;
+    optional SettingProto parental_control_last_update = 26;
+    optional SettingProto parental_control_redirect_url = 27;
+    optional SettingProto settings_classname = 28;
+    optional SettingProto accessibility_enabled = 29;
+    optional SettingProto touch_exploration_enabled = 30;
+    optional SettingProto enabled_accessibility_services = 31;
+    optional SettingProto touch_exploration_granted_accessibility_services = 32;
+    optional SettingProto accessibility_speak_password = 33;
+    optional SettingProto accessibility_high_text_contrast_enabled = 34;
+    optional SettingProto accessibility_script_injection = 35;
+    optional SettingProto accessibility_screen_reader_url = 36;
+    optional SettingProto accessibility_web_content_key_bindings = 37;
+    optional SettingProto accessibility_display_magnification_enabled = 38;
+    optional SettingProto accessibility_display_magnification_scale = 39;
+    optional SettingProto accessibility_soft_keyboard_mode = 40;
+    optional SettingProto accessibility_captioning_enabled = 41;
+    optional SettingProto accessibility_captioning_locale = 42;
+    optional SettingProto accessibility_captioning_preset = 43;
+    optional SettingProto accessibility_captioning_background_color = 44;
+    optional SettingProto accessibility_captioning_foreground_color = 45;
+    optional SettingProto accessibility_captioning_edge_type = 46;
+    optional SettingProto accessibility_captioning_edge_color = 47;
+    optional SettingProto accessibility_captioning_window_color = 48;
+    optional SettingProto accessibility_captioning_typeface = 49;
+    optional SettingProto accessibility_captioning_font_scale = 50;
+    optional SettingProto accessibility_display_inversion_enabled = 51;
+    optional SettingProto accessibility_display_daltonizer_enabled = 52;
+    optional SettingProto accessibility_display_daltonizer = 53;
+    optional SettingProto accessibility_autoclick_enabled = 54;
+    optional SettingProto accessibility_autoclick_delay = 55;
+    optional SettingProto accessibility_large_pointer_icon = 56;
+    optional SettingProto long_press_timeout = 57;
+    optional SettingProto multi_press_timeout = 58;
+    optional SettingProto enabled_print_services = 59;
+    optional SettingProto disabled_print_services = 60;
+    optional SettingProto display_density_forced = 61;
+    optional SettingProto tts_default_rate = 62;
+    optional SettingProto tts_default_pitch = 63;
+    optional SettingProto tts_default_synth = 64;
+    optional SettingProto tts_default_locale = 65;
+    optional SettingProto tts_enabled_plugins = 66;
+    optional SettingProto connectivity_release_pending_intent_delay_ms = 67;
+    optional SettingProto allowed_geolocation_origins = 68;
+    optional SettingProto preferred_tty_mode = 69;
+    optional SettingProto enhanced_voice_privacy_enabled = 70;
+    optional SettingProto tty_mode_enabled = 71;
+    optional SettingProto backup_enabled = 72;
+    optional SettingProto backup_auto_restore = 73;
+    optional SettingProto backup_provisioned = 74;
+    optional SettingProto backup_transport = 75;
+    optional SettingProto last_setup_shown = 76;
+    optional SettingProto search_global_search_activity = 77;
+    optional SettingProto search_num_promoted_sources = 78;
+    optional SettingProto search_max_results_to_display = 79;
+    optional SettingProto search_max_results_per_source = 80;
+    optional SettingProto search_web_results_override_limit = 81;
+    optional SettingProto search_promoted_source_deadline_millis = 82;
+    optional SettingProto search_source_timeout_millis = 83;
+    optional SettingProto search_prefill_millis = 84;
+    optional SettingProto search_max_stat_age_millis = 85;
+    optional SettingProto search_max_source_event_age_millis = 86;
+    optional SettingProto search_min_impressions_for_source_ranking = 87;
+    optional SettingProto search_min_clicks_for_source_ranking = 88;
+    optional SettingProto search_max_shortcuts_returned = 89;
+    optional SettingProto search_query_thread_core_pool_size = 90;
+    optional SettingProto search_query_thread_max_pool_size = 91;
+    optional SettingProto search_shortcut_refresh_core_pool_size = 92;
+    optional SettingProto search_shortcut_refresh_max_pool_size = 93;
+    optional SettingProto search_thread_keepalive_seconds = 94;
+    optional SettingProto search_per_source_concurrent_query_limit = 95;
+    optional SettingProto mount_play_notification_snd = 96;
+    optional SettingProto mount_ums_autostart = 97;
+    optional SettingProto mount_ums_prompt = 98;
+    optional SettingProto mount_ums_notify_enabled = 99;
+    optional SettingProto anr_show_background = 100;
+    optional SettingProto voice_recognition_service = 101;
+    optional SettingProto package_verifier_user_consent = 102;
+    optional SettingProto selected_spell_checker = 103;
+    optional SettingProto selected_spell_checker_subtype = 104;
+    optional SettingProto spell_checker_enabled = 105;
+    optional SettingProto incall_power_button_behavior = 106;
+    optional SettingProto incall_back_button_behavior = 107;
+    optional SettingProto wake_gesture_enabled = 108;
+    optional SettingProto doze_enabled = 109;
+    optional SettingProto doze_always_on = 110;
+    optional SettingProto doze_pulse_on_pick_up = 111;
+    optional SettingProto doze_pulse_on_double_tap = 112;
+    optional SettingProto ui_night_mode = 113;
+    optional SettingProto screensaver_enabled = 114;
+    optional SettingProto screensaver_components = 115;
+    optional SettingProto screensaver_activate_on_dock = 116;
+    optional SettingProto screensaver_activate_on_sleep = 117;
+    optional SettingProto screensaver_default_component = 118;
+    optional SettingProto nfc_payment_default_component = 119;
+    optional SettingProto nfc_payment_foreground = 120;
+    optional SettingProto sms_default_application = 121;
+    optional SettingProto dialer_default_application = 122;
+    optional SettingProto emergency_assistance_application = 123;
+    optional SettingProto assist_structure_enabled = 124;
+    optional SettingProto assist_screenshot_enabled = 125;
+    optional SettingProto assist_disclosure_enabled = 126;
+    optional SettingProto enabled_notification_assistant = 127;
+    optional SettingProto enabled_notification_listeners = 128;
+    optional SettingProto enabled_notification_policy_access_packages = 129;
+    optional SettingProto sync_parent_sounds = 130;
+    optional SettingProto immersive_mode_confirmations = 131;
+    optional SettingProto print_service_search_uri = 132;
+    optional SettingProto payment_service_search_uri = 133;
+    optional SettingProto skip_first_use_hints = 134;
+    optional SettingProto unsafe_volume_music_active_ms = 135;
+    optional SettingProto lock_screen_show_notifications = 136;
+    optional SettingProto tv_input_hidden_inputs = 137;
+    optional SettingProto tv_input_custom_labels = 138;
+    optional SettingProto usb_audio_automatic_routing_disabled = 139;
+    optional SettingProto sleep_timeout = 140;
+    optional SettingProto double_tap_to_wake = 141;
+    optional SettingProto assistant = 142;
+    optional SettingProto camera_gesture_disabled = 143;
+    optional SettingProto camera_double_tap_power_gesture_disabled = 144;
+    optional SettingProto camera_double_twist_to_flip_enabled = 145;
+    optional SettingProto night_display_activated = 146;
+    optional SettingProto night_display_auto_mode = 147;
+    optional SettingProto night_display_custom_start_time = 148;
+    optional SettingProto night_display_custom_end_time = 149;
+    optional SettingProto brightness_use_twilight = 150;
+    optional SettingProto enabled_vr_listeners = 151;
+    optional SettingProto vr_display_mode = 152;
+    optional SettingProto carrier_apps_handled = 153;
+    optional SettingProto managed_profile_contact_remote_search = 154;
+    optional SettingProto automatic_storage_manager_enabled = 155;
+    optional SettingProto automatic_storage_manager_days_to_retain = 156;
+    optional SettingProto automatic_storage_manager_bytes_cleared = 157;
+    optional SettingProto automatic_storage_manager_last_run = 158;
+    optional SettingProto system_navigation_keys_enabled = 159;
+    optional SettingProto downloads_backup_enabled = 160;
+    optional SettingProto downloads_backup_allow_metered = 161;
+    optional SettingProto downloads_backup_charging_only = 162;
+    optional SettingProto automatic_storage_manager_downloads_days_to_retain = 163;
+    optional SettingProto qs_tiles = 164;
+    optional SettingProto demo_user_setup_complete = 165;
+    optional SettingProto instant_apps_enabled = 166;
+    optional SettingProto device_paired = 167;
+    optional SettingProto notification_badging = 168;
+    optional SettingProto backup_manager_constants = 169;
 }
 
 message SystemSettingsProto {
     // Historical operations
     repeated SettingsOperationProto historical_op = 1;
 
-    SettingProto end_button_behavior = 2;
-    SettingProto advanced_settings = 3;
-    SettingProto bluetooth_discoverability = 4;
-    SettingProto bluetooth_discoverability_timeout = 5;
-    SettingProto font_scale = 6;
-    SettingProto system_locales = 7;
-    SettingProto screen_off_timeout = 8;
-    SettingProto screen_brightness = 9;
-    SettingProto screen_brightness_for_vr = 10;
-    SettingProto screen_brightness_mode = 11;
-    SettingProto screen_auto_brightness_adj = 12;
-    SettingProto mode_ringer_streams_affected = 13;
-    SettingProto mute_streams_affected = 14;
-    SettingProto vibrate_on = 15;
-    SettingProto vibrate_input_devices = 16;
-    SettingProto volume_ring = 17;
-    SettingProto volume_system = 18;
-    SettingProto volume_voice = 19;
-    SettingProto volume_music = 20;
-    SettingProto volume_alarm = 21;
-    SettingProto volume_notification = 22;
-    SettingProto volume_bluetooth_sco = 23;
-    SettingProto volume_master = 24;
-    SettingProto master_mono = 25;
-    SettingProto vibrate_in_silent = 26;
-    SettingProto append_for_last_audible = 27;
-    SettingProto ringtone = 28;
-    SettingProto ringtone_cache = 29;
-    SettingProto notification_sound = 30;
-    SettingProto notification_sound_cache = 31;
-    SettingProto alarm_alert = 32;
-    SettingProto alarm_alert_cache = 33;
-    SettingProto media_button_receiver = 34;
-    SettingProto text_auto_replace = 35;
-    SettingProto text_auto_caps = 36;
-    SettingProto text_auto_punctuate = 37;
-    SettingProto text_show_password = 38;
-    SettingProto show_gtalk_service_status = 39;
-    SettingProto time_12_24 = 40;
-    SettingProto date_format = 41;
-    SettingProto setup_wizard_has_run = 42;
-    SettingProto accelerometer_rotation = 43;
-    SettingProto user_rotation = 44;
-    SettingProto hide_rotation_lock_toggle_for_accessibility = 45;
-    SettingProto vibrate_when_ringing = 46;
-    SettingProto dtmf_tone_when_dialing = 47;
-    SettingProto dtmf_tone_type_when_dialing = 48;
-    SettingProto hearing_aid = 49;
-    SettingProto tty_mode = 50;
-    SettingProto sound_effects_enabled = 51;
-    SettingProto haptic_feedback_enabled = 52;
-    SettingProto notification_light_pulse = 53;
-    SettingProto pointer_location = 54;
-    SettingProto show_touches = 55;
-    SettingProto window_orientation_listener_log = 56;
-    SettingProto lockscreen_sounds_enabled = 57;
-    SettingProto lockscreen_disabled = 58;
-    SettingProto sip_receive_calls = 59;
-    SettingProto sip_call_options = 60;
-    SettingProto sip_always = 61;
-    SettingProto sip_address_only = 62;
-    SettingProto pointer_speed = 63;
-    SettingProto lock_to_app_enabled = 64;
-    SettingProto egg_mode = 65;
-    SettingProto when_to_make_wifi_calls = 66;
+    optional SettingProto end_button_behavior = 2;
+    optional SettingProto advanced_settings = 3;
+    optional SettingProto bluetooth_discoverability = 4;
+    optional SettingProto bluetooth_discoverability_timeout = 5;
+    optional SettingProto font_scale = 6;
+    optional SettingProto system_locales = 7;
+    optional SettingProto screen_off_timeout = 8;
+    optional SettingProto screen_brightness = 9;
+    optional SettingProto screen_brightness_for_vr = 10;
+    optional SettingProto screen_brightness_mode = 11;
+    optional SettingProto screen_auto_brightness_adj = 12;
+    optional SettingProto mode_ringer_streams_affected = 13;
+    optional SettingProto mute_streams_affected = 14;
+    optional SettingProto vibrate_on = 15;
+    optional SettingProto vibrate_input_devices = 16;
+    optional SettingProto volume_ring = 17;
+    optional SettingProto volume_system = 18;
+    optional SettingProto volume_voice = 19;
+    optional SettingProto volume_music = 20;
+    optional SettingProto volume_alarm = 21;
+    optional SettingProto volume_notification = 22;
+    optional SettingProto volume_bluetooth_sco = 23;
+    optional SettingProto volume_master = 24;
+    optional SettingProto master_mono = 25;
+    optional SettingProto vibrate_in_silent = 26;
+    optional SettingProto append_for_last_audible = 27;
+    optional SettingProto ringtone = 28;
+    optional SettingProto ringtone_cache = 29;
+    optional SettingProto notification_sound = 30;
+    optional SettingProto notification_sound_cache = 31;
+    optional SettingProto alarm_alert = 32;
+    optional SettingProto alarm_alert_cache = 33;
+    optional SettingProto media_button_receiver = 34;
+    optional SettingProto text_auto_replace = 35;
+    optional SettingProto text_auto_caps = 36;
+    optional SettingProto text_auto_punctuate = 37;
+    optional SettingProto text_show_password = 38;
+    optional SettingProto show_gtalk_service_status = 39;
+    optional SettingProto time_12_24 = 40;
+    optional SettingProto date_format = 41;
+    optional SettingProto setup_wizard_has_run = 42;
+    optional SettingProto accelerometer_rotation = 43;
+    optional SettingProto user_rotation = 44;
+    optional SettingProto hide_rotation_lock_toggle_for_accessibility = 45;
+    optional SettingProto vibrate_when_ringing = 46;
+    optional SettingProto dtmf_tone_when_dialing = 47;
+    optional SettingProto dtmf_tone_type_when_dialing = 48;
+    optional SettingProto hearing_aid = 49;
+    optional SettingProto tty_mode = 50;
+    optional SettingProto sound_effects_enabled = 51;
+    optional SettingProto haptic_feedback_enabled = 52;
+    optional SettingProto notification_light_pulse = 53;
+    optional SettingProto pointer_location = 54;
+    optional SettingProto show_touches = 55;
+    optional SettingProto window_orientation_listener_log = 56;
+    optional SettingProto lockscreen_sounds_enabled = 57;
+    optional SettingProto lockscreen_disabled = 58;
+    optional SettingProto sip_receive_calls = 59;
+    optional SettingProto sip_call_options = 60;
+    optional SettingProto sip_always = 61;
+    optional SettingProto sip_address_only = 62;
+    optional SettingProto pointer_speed = 63;
+    optional SettingProto lock_to_app_enabled = 64;
+    optional SettingProto egg_mode = 65;
+    optional SettingProto when_to_make_wifi_calls = 66;
 }
 
 message SettingProto {
     // ID of the setting
-    string id = 1;
+    optional string id = 1;
 
     // Name of the setting
-    string name = 2;
+    optional string name = 2;
 
     // Package name of the setting
-    string pkg = 3;
+    optional string pkg = 3;
 
     // Value of this setting
-    string value = 4;
+    optional string value = 4;
 
     // Default value of this setting
-    string default_value = 5;
+    optional string default_value = 5;
 
     // Whether the default is set by the system
-    bool default_from_system = 6;
+    optional bool default_from_system = 6;
 }
 
 message SettingsOperationProto {
     // When the operation happened
-    int64 timestamp = 1;
+    optional int64 timestamp = 1;
 
     // Type of the operation
-    string operation = 2;
+    optional string operation = 2;
 
     // Name of the setting that was affected (optional)
-    string setting = 3;
+    optional string setting = 3;
 }
diff --git a/core/proto/android/server/activitymanagerservice.proto b/core/proto/android/server/activitymanagerservice.proto
index fe5e3f1..788ac8f 100644
--- a/core/proto/android/server/activitymanagerservice.proto
+++ b/core/proto/android/server/activitymanagerservice.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 import "frameworks/base/core/proto/android/content/intent.proto";
 import "frameworks/base/core/proto/android/server/intentresolver.proto";
 import "frameworks/base/core/proto/android/server/windowmanagerservice.proto";
@@ -27,140 +26,140 @@
 option java_multiple_files = true;
 
 message ActivityManagerServiceProto {
-  ActivityStackSupervisorProto activities = 1;
+  optional ActivityStackSupervisorProto activities = 1;
 
-  BroadcastProto broadcasts = 2;
+  optional BroadcastProto broadcasts = 2;
 
-  ServiceProto services = 3;
+  optional ServiceProto services = 3;
 
-  ProcessProto processes = 4;
+  optional ProcessProto processes = 4;
 }
 
 message ActivityStackSupervisorProto {
-  .com.android.server.wm.proto.ConfigurationContainerProto configuration_container = 1;
+  optional .com.android.server.wm.proto.ConfigurationContainerProto configuration_container = 1;
   repeated ActivityDisplayProto displays = 2;
-  KeyguardControllerProto keyguard_controller = 3;
-  int32 focused_stack_id = 4;
-  .com.android.server.wm.proto.IdentifierProto resumed_activity = 5;
+  optional KeyguardControllerProto keyguard_controller = 3;
+  optional int32 focused_stack_id = 4;
+  optional .com.android.server.wm.proto.IdentifierProto resumed_activity = 5;
 }
 
 /* represents ActivityStackSupervisor.ActivityDisplay */
 message ActivityDisplayProto {
-  .com.android.server.wm.proto.ConfigurationContainerProto configuration_container = 1;
-  int32 id = 2;
+  optional .com.android.server.wm.proto.ConfigurationContainerProto configuration_container = 1;
+  optional int32 id = 2;
   repeated ActivityStackProto stacks = 3;
 }
 
 message ActivityStackProto {
-  .com.android.server.wm.proto.ConfigurationContainerProto configuration_container = 1;
-  int32 id = 2;
+  optional .com.android.server.wm.proto.ConfigurationContainerProto configuration_container = 1;
+  optional int32 id = 2;
   repeated TaskRecordProto tasks = 3;
-  .com.android.server.wm.proto.IdentifierProto resumed_activity = 4;
-  int32 display_id = 5;
-  bool fullscreen = 6;
-  .android.graphics.RectProto bounds = 7;
+  optional .com.android.server.wm.proto.IdentifierProto resumed_activity = 4;
+  optional int32 display_id = 5;
+  optional bool fullscreen = 6;
+  optional .android.graphics.RectProto bounds = 7;
 }
 
 message TaskRecordProto {
-  .com.android.server.wm.proto.ConfigurationContainerProto configuration_container = 1;
-  int32 id = 2;
+  optional .com.android.server.wm.proto.ConfigurationContainerProto configuration_container = 1;
+  optional int32 id = 2;
   repeated ActivityRecordProto activities = 3;
-  int32 stack_id = 4;
-  .android.graphics.RectProto last_non_fullscreen_bounds = 5;
-  string real_activity = 6;
-  string orig_activity = 7;
-  int32 activity_type = 8;
-  int32 return_to_type = 9;
-  int32 resize_mode = 10;
-  bool fullscreen = 11;
-  .android.graphics.RectProto bounds = 12;
-  int32 min_width = 13;
-  int32 min_height = 14;
+  optional int32 stack_id = 4;
+  optional .android.graphics.RectProto last_non_fullscreen_bounds = 5;
+  optional string real_activity = 6;
+  optional string orig_activity = 7;
+  optional int32 activity_type = 8;
+  optional int32 return_to_type = 9;
+  optional int32 resize_mode = 10;
+  optional bool fullscreen = 11;
+  optional .android.graphics.RectProto bounds = 12;
+  optional int32 min_width = 13;
+  optional int32 min_height = 14;
 }
 
 message ActivityRecordProto {
-  .com.android.server.wm.proto.ConfigurationContainerProto configuration_container = 1;
-  .com.android.server.wm.proto.IdentifierProto identifier = 2;
-  string state = 3;
-  bool visible = 4;
-  bool front_of_task = 5;
-  int32 proc_id = 6;
+  optional .com.android.server.wm.proto.ConfigurationContainerProto configuration_container = 1;
+  optional .com.android.server.wm.proto.IdentifierProto identifier = 2;
+  optional string state = 3;
+  optional bool visible = 4;
+  optional bool front_of_task = 5;
+  optional int32 proc_id = 6;
 }
 
 message KeyguardControllerProto {
-  bool keyguard_showing = 1;
-  bool keyguard_occluded = 2;
+  optional bool keyguard_showing = 1;
+  optional bool keyguard_occluded = 2;
 }
 
 message BroadcastProto {
   repeated ReceiverListProto  receiver_list = 1;
 
-  .com.android.server.IntentResolverProto receiver_resolver = 2;
+  optional .com.android.server.IntentResolverProto receiver_resolver = 2;
 
   repeated BroadcastQueueProto broadcast_queue = 3;
 
   repeated StickyBroadcastProto sticky_broadcasts = 4;
 
   message MainHandler {
-    string handler = 1;
-    .android.os.LooperProto looper = 2;
+    optional string handler = 1;
+    optional .android.os.LooperProto looper = 2;
   }
-  MainHandler handler = 5;
+  optional MainHandler handler = 5;
 }
 
 message ReceiverListProto {
-  ProcessRecordProto app = 1;
-  int32 pid = 2;
-  int32 uid = 3;
-  int32 user = 4;
-  BroadcastRecordProto current = 5;
-  bool linked_to_death = 6;
+  optional ProcessRecordProto app = 1;
+  optional int32 pid = 2;
+  optional int32 uid = 3;
+  optional int32 user = 4;
+  optional BroadcastRecordProto current = 5;
+  optional bool linked_to_death = 6;
   repeated BroadcastFilterProto filters = 7;
-  string hex_hash = 8; // this hash is used to find the object in IntentResolver
+  optional string hex_hash = 8; // this hash is used to find the object in IntentResolver
 }
 
 message ProcessRecordProto {
-  int32 pid = 1;
-  string process_name = 2;
-  int32 uid = 3;
-  int32 user_id = 4;
-  int32 app_id = 5;
-  int32 isolated_app_id = 6;
+  optional int32 pid = 1;
+  optional string process_name = 2;
+  optional int32 uid = 3;
+  optional int32 user_id = 4;
+  optional int32 app_id = 5;
+  optional int32 isolated_app_id = 6;
 }
 
 message BroadcastRecordProto {
-  int32 user_id = 1;
-  string intent_action = 2;
+  optional int32 user_id = 1;
+  optional string intent_action = 2;
 }
 
 message BroadcastFilterProto {
-  .android.content.IntentFilterProto intent_filter = 1;
-  string required_permission = 2;
-  string hex_hash = 3; // used to find the object in IntentResolver
-  int32 owning_user_id = 4;
+  optional .android.content.IntentFilterProto intent_filter = 1;
+  optional string required_permission = 2;
+  optional string hex_hash = 3; // used to find the object in IntentResolver
+  optional int32 owning_user_id = 4;
 }
 
 message BroadcastQueueProto {
-  string queue_name = 1;
+  optional string queue_name = 1;
   repeated BroadcastRecordProto parallel_broadcasts = 2;
   repeated BroadcastRecordProto ordered_broadcasts = 3;
-  BroadcastRecordProto pending_broadcast = 4;
+  optional BroadcastRecordProto pending_broadcast = 4;
   repeated BroadcastRecordProto historical_broadcasts = 5;
 
   message BroadcastSummary {
-    .android.content.IntentProto intent = 1;
-    int64 enqueue_clock_time_ms = 2;
-    int64 dispatch_clock_time_ms = 3;
-    int64 finish_clock_time_ms = 4;
+    optional .android.content.IntentProto intent = 1;
+    optional int64 enqueue_clock_time_ms = 2;
+    optional int64 dispatch_clock_time_ms = 3;
+    optional int64 finish_clock_time_ms = 4;
   }
   repeated BroadcastSummary historical_broadcasts_summary = 6;
 }
 
 message StickyBroadcastProto {
-  int32 user = 1;
+  optional int32 user = 1;
 
   message StickyAction {
-    string name = 1;
+    optional string name = 1;
     repeated .android.content.IntentProto intents = 2;
   }
   repeated StickyAction actions = 2;
diff --git a/core/proto/android/server/intentresolver.proto b/core/proto/android/server/intentresolver.proto
index 62ec2ea..60c060c 100644
--- a/core/proto/android/server/intentresolver.proto
+++ b/core/proto/android/server/intentresolver.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 option java_multiple_files = true;
 
 package com.android.server;
@@ -23,7 +22,7 @@
 message IntentResolverProto {
 
     message ArrayMapEntry {
-        string key = 1;
+        optional string key = 1;
         repeated string values = 2;
     }
 
diff --git a/core/proto/android/server/windowmanagerservice.proto b/core/proto/android/server/windowmanagerservice.proto
index d177f1c..064523a 100644
--- a/core/proto/android/server/windowmanagerservice.proto
+++ b/core/proto/android/server/windowmanagerservice.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 import "frameworks/base/core/proto/android/content/configuration.proto";
 import "frameworks/base/core/proto/android/graphics/rect.proto";
 import "frameworks/base/core/proto/android/view/displayinfo.proto";
@@ -26,21 +25,21 @@
 option java_multiple_files = true;
 
 message WindowManagerServiceProto {
-  WindowManagerPolicyProto policy = 1;
+  optional WindowManagerPolicyProto policy = 1;
   /* window hierarchy root */
-  RootWindowContainerProto root_window_container = 2;
-  IdentifierProto focused_window = 3;
-  string focused_app = 4;
-  IdentifierProto input_method_window = 5;
-  bool display_frozen = 6;
-  int32 rotation = 7;
-  int32 last_orientation = 8;
-  AppTransitionProto app_transition = 9;
+  optional RootWindowContainerProto root_window_container = 2;
+  optional IdentifierProto focused_window = 3;
+  optional string focused_app = 4;
+  optional IdentifierProto input_method_window = 5;
+  optional bool display_frozen = 6;
+  optional int32 rotation = 7;
+  optional int32 last_orientation = 8;
+  optional AppTransitionProto app_transition = 9;
 }
 
 /* represents DisplayContent */
 message RootWindowContainerProto {
-  WindowContainerProto window_container = 1;
+  optional WindowContainerProto window_container = 1;
   repeated DisplayProto displays = 2;
   /* window references in top down z order */
   repeated IdentifierProto windows = 3;
@@ -48,7 +47,7 @@
 
 /* represents PhoneWindowManager */
 message WindowManagerPolicyProto {
-  .android.graphics.RectProto stable_bounds = 1;
+  optional .android.graphics.RectProto stable_bounds = 1;
 }
 
 /* represents AppTransition */
@@ -59,7 +58,7 @@
     APP_STATE_RUNNING = 2;
     APP_STATE_TIMEOUT = 3;
   }
-  AppState app_transition_state = 1;
+  optional AppState app_transition_state = 1;
   /* definitions for constants found in {@link com.android.server.wm.AppTransition} */
   enum TransitionType {
     TRANSIT_NONE = 0;
@@ -83,124 +82,124 @@
     TRANSIT_KEYGUARD_OCCLUDE = 22;
     TRANSIT_KEYGUARD_UNOCCLUDE = 23;
   }
-  TransitionType last_used_app_transition = 2;
+  optional TransitionType last_used_app_transition = 2;
 }
 
 /* represents DisplayContent */
 message DisplayProto {
-  WindowContainerProto window_container = 1;
-  int32 id = 2;
+  optional WindowContainerProto window_container = 1;
+  optional int32 id = 2;
   repeated StackProto stacks = 3;
-  DockedStackDividerControllerProto docked_stack_divider_controller = 4;
-  PinnedStackControllerProto pinned_stack_controller = 5;
+  optional DockedStackDividerControllerProto docked_stack_divider_controller = 4;
+  optional PinnedStackControllerProto pinned_stack_controller = 5;
   /* non app windows */
   repeated WindowTokenProto above_app_windows = 6;
   repeated WindowTokenProto below_app_windows = 7;
   repeated WindowTokenProto ime_windows = 8;
-  int32 dpi = 9;
-  .android.view.DisplayInfoProto display_info = 10;
-  int32 rotation = 11;
-  ScreenRotationAnimationProto screen_rotation_animation = 12;
+  optional int32 dpi = 9;
+  optional .android.view.DisplayInfoProto display_info = 10;
+  optional int32 rotation = 11;
+  optional ScreenRotationAnimationProto screen_rotation_animation = 12;
 }
 
 
 /* represents DockedStackDividerController */
 message DockedStackDividerControllerProto {
-  bool minimized_dock = 1;
+  optional bool minimized_dock = 1;
 }
 
 /* represents PinnedStackController */
 message PinnedStackControllerProto {
-  .android.graphics.RectProto default_bounds = 1;
-  .android.graphics.RectProto movement_bounds = 2;
+  optional .android.graphics.RectProto default_bounds = 1;
+  optional .android.graphics.RectProto movement_bounds = 2;
 }
 
 /* represents TaskStack */
 message StackProto {
-  WindowContainerProto window_container = 1;
-  int32 id = 2;
+  optional WindowContainerProto window_container = 1;
+  optional int32 id = 2;
   repeated TaskProto tasks = 3;
-  bool fills_parent = 4;
-  .android.graphics.RectProto bounds = 5;
-  bool animation_background_surface_is_dimming = 6;
+  optional bool fills_parent = 4;
+  optional .android.graphics.RectProto bounds = 5;
+  optional bool animation_background_surface_is_dimming = 6;
 }
 
 /* represents Task */
 message TaskProto {
-  WindowContainerProto window_container = 1;
-  int32 id = 2;
+  optional WindowContainerProto window_container = 1;
+  optional int32 id = 2;
   repeated AppWindowTokenProto app_window_tokens = 3;
-  bool fills_parent = 4;
-  .android.graphics.RectProto bounds = 5;
-  .android.graphics.RectProto temp_inset_bounds = 6;
+  optional bool fills_parent = 4;
+  optional .android.graphics.RectProto bounds = 5;
+  optional .android.graphics.RectProto temp_inset_bounds = 6;
 }
 
 /* represents AppWindowToken */
 message AppWindowTokenProto {
   /* obtained from ActivityRecord */
-  string name = 1;
-  WindowTokenProto window_token = 2;
+  optional string name = 1;
+  optional WindowTokenProto window_token = 2;
 }
 
 /* represents WindowToken */
 message WindowTokenProto {
-  WindowContainerProto window_container = 1;
-  int32 hash_code = 2;
+  optional WindowContainerProto window_container = 1;
+  optional int32 hash_code = 2;
   repeated WindowStateProto windows = 3;
 }
 
 /* represents WindowState */
 message WindowStateProto {
-  WindowContainerProto window_container = 1;
-  IdentifierProto identifier = 2;
-  int32 display_id = 3;
-  int32 stack_id = 4;
-  .android.view.WindowLayoutParamsProto attributes = 5;
-  .android.graphics.RectProto given_content_insets = 6;
-  .android.graphics.RectProto frame = 7;
-  .android.graphics.RectProto containing_frame = 8;
-  .android.graphics.RectProto parent_frame = 9;
-  .android.graphics.RectProto content_frame = 10;
-  .android.graphics.RectProto content_insets = 11;
-  .android.graphics.RectProto surface_insets = 12;
-  WindowStateAnimatorProto animator = 13;
-  bool animating_exit = 14;
+  optional WindowContainerProto window_container = 1;
+  optional IdentifierProto identifier = 2;
+  optional int32 display_id = 3;
+  optional int32 stack_id = 4;
+  optional .android.view.WindowLayoutParamsProto attributes = 5;
+  optional .android.graphics.RectProto given_content_insets = 6;
+  optional .android.graphics.RectProto frame = 7;
+  optional .android.graphics.RectProto containing_frame = 8;
+  optional .android.graphics.RectProto parent_frame = 9;
+  optional .android.graphics.RectProto content_frame = 10;
+  optional .android.graphics.RectProto content_insets = 11;
+  optional .android.graphics.RectProto surface_insets = 12;
+  optional WindowStateAnimatorProto animator = 13;
+  optional bool animating_exit = 14;
   repeated WindowStateProto child_windows = 15;
 }
 
 message IdentifierProto {
-  int32 hash_code = 1;
-  int32 user_id = 2;
-  string title = 3;
+  optional int32 hash_code = 1;
+  optional int32 user_id = 2;
+  optional string title = 3;
 }
 
 /* represents WindowStateAnimator */
 message WindowStateAnimatorProto {
-  .android.graphics.RectProto last_clip_rect = 1;
-  WindowSurfaceControllerProto surface = 2;
+  optional .android.graphics.RectProto last_clip_rect = 1;
+  optional WindowSurfaceControllerProto surface = 2;
 }
 
 /* represents WindowSurfaceController */
 message WindowSurfaceControllerProto {
-  bool shown = 1;
-  int32 layer = 2;
+  optional bool shown = 1;
+  optional int32 layer = 2;
 }
 
 /* represents ScreenRotationAnimation */
 message ScreenRotationAnimationProto {
-  bool started = 1;
-  bool animation_running = 2;
+  optional bool started = 1;
+  optional bool animation_running = 2;
 }
 
 /* represents WindowContainer */
 message WindowContainerProto {
-  ConfigurationContainerProto configuration_container = 1;
-  int32 orientation = 2;
+  optional ConfigurationContainerProto configuration_container = 1;
+  optional int32 orientation = 2;
 }
 
 /* represents ConfigurationContainer */
 message ConfigurationContainerProto {
-  .android.content.ConfigurationProto override_configuration = 1;
-  .android.content.ConfigurationProto full_configuration = 2;
-  .android.content.ConfigurationProto merged_override_configuration = 3;
+  optional .android.content.ConfigurationProto override_configuration = 1;
+  optional .android.content.ConfigurationProto full_configuration = 2;
+  optional .android.content.ConfigurationProto merged_override_configuration = 3;
 }
diff --git a/core/proto/android/service/appwidget.proto b/core/proto/android/service/appwidget.proto
index 1f04f71..3f46d2b 100644
--- a/core/proto/android/service/appwidget.proto
+++ b/core/proto/android/service/appwidget.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 package android.service.appwidget;
 
 option java_multiple_files = true;
@@ -28,13 +27,13 @@
 
 // represents a bound widget
 message WidgetProto {
-  bool isCrossProfile = 1; // true if host and provider belong to diff users
-  bool isHostStopped = 2; // true if host has not called startListening yet
-  string hostPackage = 3;
-  string providerPackage = 4;
-  string providerClass = 5;
-  int32 minWidth = 6;
-  int32 minHeight = 7;
-  int32 maxWidth = 8;
-  int32 maxHeight = 9;
+  optional bool isCrossProfile = 1; // true if host and provider belong to diff users
+  optional bool isHostStopped = 2; // true if host has not called startListening yet
+  optional string hostPackage = 3;
+  optional string providerPackage = 4;
+  optional string providerClass = 5;
+  optional int32 minWidth = 6;
+  optional int32 minHeight = 7;
+  optional int32 maxWidth = 8;
+  optional int32 maxHeight = 9;
 }
diff --git a/core/proto/android/service/battery.proto b/core/proto/android/service/battery.proto
index 33ad682b..998a808 100644
--- a/core/proto/android/service/battery.proto
+++ b/core/proto/android/service/battery.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 package android.service.battery;
 
 option java_multiple_files = true;
@@ -48,29 +47,29 @@
     }
 
     // If true: UPDATES STOPPED -- use 'reset' to restart
-    bool are_updates_stopped = 1;
+    optional bool are_updates_stopped = 1;
     // Plugged status of power sources
-    BatteryPlugged plugged = 2;
+    optional BatteryPlugged plugged = 2;
     // Max current in microamperes
-    int32 max_charging_current = 3;
+    optional int32 max_charging_current = 3;
     // Max voltage
-    int32 max_charging_voltage = 4;
+    optional int32 max_charging_voltage = 4;
     // Battery capacity in microampere-hours
-    int32 charge_counter = 5;
+    optional int32 charge_counter = 5;
     // Charging status
-    BatteryStatus status = 6;
+    optional BatteryStatus status = 6;
     // Battery health
-    BatteryHealth health = 7;
+    optional BatteryHealth health = 7;
     // True if the battery is present
-    bool is_present = 8;
+    optional bool is_present = 8;
     // Charge level, from 0 through "scale" inclusive
-    int32 level = 9;
+    optional int32 level = 9;
     // The maximum value for the charge level
-    int32 scale = 10;
+    optional int32 scale = 10;
     // Battery voltage in millivolts
-    int32 voltage = 11;
+    optional int32 voltage = 11;
     // Battery temperature in tenths of a degree Centigrade
-    int32 temperature = 12;
+    optional int32 temperature = 12;
     // The type of battery installed, e.g. "Li-ion"
-    string technology = 13;
+    optional string technology = 13;
 }
diff --git a/core/proto/android/service/batterystats.proto b/core/proto/android/service/batterystats.proto
index 4e989b7..54d3f40 100644
--- a/core/proto/android/service/batterystats.proto
+++ b/core/proto/android/service/batterystats.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 package android.service.batterystats;
 
 option java_multiple_files = true;
@@ -24,5 +23,5 @@
 import "frameworks/base/core/proto/android/os/batterystats.proto";
 
 message BatteryStatsServiceDumpProto {
-  android.os.BatteryStatsProto batterystats = 1;
+  optional android.os.BatteryStatsProto batterystats = 1;
 }
diff --git a/core/proto/android/service/diskstats.proto b/core/proto/android/service/diskstats.proto
index 4057e45..f725e8a 100644
--- a/core/proto/android/service/diskstats.proto
+++ b/core/proto/android/service/diskstats.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 package android.service.diskstats;
 
 option java_multiple_files = true;
@@ -33,51 +32,51 @@
         ENCRYPTION_FILE_BASED = 3;
     }
     // Whether the latency test resulted in an error
-    bool has_test_error = 1;
+    optional bool has_test_error = 1;
     // If the test errored, error message is contained here
-    string error_message = 2;
+    optional string error_message = 2;
     // 512B write latency in milliseconds, if the test was successful
-    int32 write_512b_latency_millis = 3;
+    optional int32 write_512b_latency_millis = 3;
     // Free Space in the major partitions
     repeated DiskStatsFreeSpaceProto partitions_free_space = 4;
     // Is the device using file-based encryption, full disk encryption or other
-    EncryptionType encryption = 5;
+    optional EncryptionType encryption = 5;
     // Cached values of folder sizes, etc.
-    DiskStatsCachedValuesProto cached_folder_sizes = 6;
+    optional DiskStatsCachedValuesProto cached_folder_sizes = 6;
 }
 
 message DiskStatsCachedValuesProto {
     // Total app code size, in kilobytes
-    int64 agg_apps_size = 1;
+    optional int64 agg_apps_size = 1;
     // Total app cache size, in kilobytes
-    int64 agg_apps_cache_size = 2;
+    optional int64 agg_apps_cache_size = 2;
     // Size of image files, in kilobytes
-    int64 photos_size = 3;
+    optional int64 photos_size = 3;
     // Size of video files, in kilobytes
-    int64 videos_size = 4;
+    optional int64 videos_size = 4;
     // Size of audio files, in kilobytes
-    int64 audio_size = 5;
+    optional int64 audio_size = 5;
     // Size of downloads, in kilobytes
-    int64 downloads_size = 6;
+    optional int64 downloads_size = 6;
     // Size of system directory, in kilobytes
-    int64 system_size = 7;
+    optional int64 system_size = 7;
     // Size of other files, in kilobytes
-    int64 other_size = 8;
+    optional int64 other_size = 8;
     // Sizes of individual packages
     repeated DiskStatsAppSizesProto app_sizes = 9;
     // Total app data size, in kilobytes
-    int64 agg_apps_data_size = 10;
+    optional int64 agg_apps_data_size = 10;
 }
 
 message DiskStatsAppSizesProto {
     // Name of the package
-    string package_name = 1;
+    optional string package_name = 1;
     // App's code size in kilobytes
-    int64 app_size = 2;
+    optional int64 app_size = 2;
     // App's cache size in kilobytes
-    int64 cache_size = 3;
+    optional int64 cache_size = 3;
     // App's data size in kilobytes
-    int64 app_data_size = 4;
+    optional int64 app_data_size = 4;
 }
 
 message DiskStatsFreeSpaceProto {
@@ -90,9 +89,9 @@
         FOLDER_SYSTEM = 2;
     }
     // Which folder?
-    Folder folder = 1;
+    optional Folder folder = 1;
     // Available space, in kilobytes
-    int64 available_space = 2;
+    optional int64 available_space = 2;
     // Total space, in kilobytes
-    int64 total_space = 3;
+    optional int64 total_space = 3;
 }
diff --git a/core/proto/android/service/fingerprint.proto b/core/proto/android/service/fingerprint.proto
index f88b762..0826ad5 100644
--- a/core/proto/android/service/fingerprint.proto
+++ b/core/proto/android/service/fingerprint.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 package android.service.fingerprint;
 
 option java_multiple_files = true;
@@ -28,33 +27,33 @@
 
 message FingerprintUserStatsProto {
     // Should be 0, 10, 11, 12, etc. where 0 is the owner.
-    int32 user_id = 1;
+    optional int32 user_id = 1;
 
     // The number of fingerprints registered to this user.
-    int32 num_fingerprints = 2;
+    optional int32 num_fingerprints = 2;
 
     // Normal fingerprint authentications (e.g. lockscreen).
-    FingerprintActionStatsProto normal = 3;
+    optional FingerprintActionStatsProto normal = 3;
 
     // Crypto authentications (e.g. to unlock password storage, make secure
     // purchases, etc).
-    FingerprintActionStatsProto crypto = 4;
+    optional FingerprintActionStatsProto crypto = 4;
 }
 
 message FingerprintActionStatsProto {
     // Number of accepted fingerprints.
-    int32 accept = 1;
+    optional int32 accept = 1;
 
     // Number of rejected fingerprints.
-    int32 reject = 2;
+    optional int32 reject = 2;
 
     // Total number of acquisitions. Should be >= accept+reject due to poor
     // image acquisition in some cases (too fast, too slow, dirty sensor, etc.)
-    int32 acquire = 3;
+    optional int32 acquire = 3;
 
     // Total number of lockouts.
-    int32 lockout = 4;
+    optional int32 lockout = 4;
 
     // Total number of permanent lockouts.
-    int32 lockout_permanent = 5;
+    optional int32 lockout_permanent = 5;
 }
diff --git a/core/proto/android/service/graphicsstats.proto b/core/proto/android/service/graphicsstats.proto
index b8679b0..ee9d6fc 100644
--- a/core/proto/android/service/graphicsstats.proto
+++ b/core/proto/android/service/graphicsstats.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 package android.service;
 
 option java_multiple_files = true;
@@ -29,19 +28,19 @@
 message GraphicsStatsProto {
 
     // The package name of the app
-    string package_name = 1;
+    optional string package_name = 1;
 
     // The version code of the app
-    int32 version_code = 2;
+    optional int32 version_code = 2;
 
     // The start & end timestamps in UTC as
     // milliseconds since January 1, 1970
     // Compatible with java.util.Date#setTime()
-    int64 stats_start = 3;
-    int64 stats_end = 4;
+    optional int64 stats_start = 3;
+    optional int64 stats_end = 4;
 
     // The aggregated statistics for the package
-    GraphicsStatsJankSummaryProto summary = 5;
+    optional GraphicsStatsJankSummaryProto summary = 5;
 
     // The frame time histogram for the package
     repeated GraphicsStatsHistogramBucketProto histogram = 6;
@@ -49,31 +48,31 @@
 
 message GraphicsStatsJankSummaryProto {
     // Distinct frame count.
-    int32 total_frames = 1;
+    optional int32 total_frames = 1;
 
     // Number of frames with slow render time. Frames are considered janky if
     // they took more than a vsync interval (typically 16.667ms) to be rendered.
-    int32 janky_frames = 2;
+    optional int32 janky_frames = 2;
 
     // Number of "missed vsync" events.
-    int32 missed_vsync_count = 3;
+    optional int32 missed_vsync_count = 3;
 
     // Number of "high input latency" events.
-    int32 high_input_latency_count = 4;
+    optional int32 high_input_latency_count = 4;
 
     // Number of "slow UI thread" events.
-    int32 slow_ui_thread_count = 5;
+    optional int32 slow_ui_thread_count = 5;
 
     // Number of "slow bitmap upload" events.
-    int32 slow_bitmap_upload_count = 6;
+    optional int32 slow_bitmap_upload_count = 6;
 
     // Number of "slow draw" events.
-    int32 slow_draw_count = 7;
+    optional int32 slow_draw_count = 7;
 }
 
 message GraphicsStatsHistogramBucketProto {
     // Lower bound of render time in milliseconds.
-    int32 render_millis = 1;
+    optional int32 render_millis = 1;
     // Number of frames in the bucket.
-    int32 frame_count = 2;
+    optional int32 frame_count = 2;
 }
diff --git a/core/proto/android/service/netstats.proto b/core/proto/android/service/netstats.proto
index 5a577b1..23613fd 100644
--- a/core/proto/android/service/netstats.proto
+++ b/core/proto/android/service/netstats.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 package android.service;
 
 option java_multiple_files = true;
@@ -28,23 +27,23 @@
     repeated NetworkInterfaceProto active_uid_interfaces = 2;
 
     // Device level network stats, which may include non-IP layer traffic.
-    NetworkStatsRecorderProto dev_stats = 3;
+    optional NetworkStatsRecorderProto dev_stats = 3;
 
     // IP-layer traffic stats.
-    NetworkStatsRecorderProto xt_stats = 4;
+    optional NetworkStatsRecorderProto xt_stats = 4;
 
     // Per-UID network stats.
-    NetworkStatsRecorderProto uid_stats = 5;
+    optional NetworkStatsRecorderProto uid_stats = 5;
 
     // Per-UID, per-tag network stats, excluding the default tag (i.e. tag=0).
-    NetworkStatsRecorderProto uid_tag_stats = 6;
+    optional NetworkStatsRecorderProto uid_tag_stats = 6;
 }
 
 // Corresponds to NetworkStatsService.mActiveIfaces/mActiveUidIfaces.
 message NetworkInterfaceProto {
-    string interface = 1;
+    optional string interface = 1;
 
-    NetworkIdentitySetProto identities = 2;
+    optional NetworkIdentitySetProto identities = 2;
 }
 
 // Corresponds to NetworkIdentitySet.
@@ -55,22 +54,22 @@
 // Corresponds to NetworkIdentity.
 message NetworkIdentityProto {
     // Constats from ConnectivityManager.TYPE_*.
-    int32 type = 1;
+    optional int32 type = 1;
 
-    string subscriber_id = 2;
+    optional string subscriber_id = 2;
 
-    string network_id = 3;
+    optional string network_id = 3;
 
-    bool roaming = 4;
+    optional bool roaming = 4;
 
-    bool metered = 5;
+    optional bool metered = 5;
 }
 
 // Corresponds to NetworkStatsRecorder.
 message NetworkStatsRecorderProto {
-    int64 pending_total_bytes = 1;
+    optional int64 pending_total_bytes = 1;
 
-    NetworkStatsCollectionProto complete_history = 2;
+    optional NetworkStatsCollectionProto complete_history = 2;
 }
 
 // Corresponds to NetworkStatsCollection.
@@ -80,26 +79,26 @@
 
 // Corresponds to NetworkStatsCollection.mStats.
 message NetworkStatsCollectionStatsProto {
-    NetworkStatsCollectionKeyProto key = 1;
+    optional NetworkStatsCollectionKeyProto key = 1;
 
-    NetworkStatsHistoryProto history = 2;
+    optional NetworkStatsHistoryProto history = 2;
 }
 
 // Corresponds to NetworkStatsCollection.Key.
 message NetworkStatsCollectionKeyProto {
-    NetworkIdentitySetProto identity = 1;
+    optional NetworkIdentitySetProto identity = 1;
 
-    int32 uid = 2;
+    optional int32 uid = 2;
 
-    int32 set = 3;
+    optional int32 set = 3;
 
-    int32 tag = 4;
+    optional int32 tag = 4;
 }
 
 // Corresponds to NetworkStatsHistory.
 message NetworkStatsHistoryProto {
     // Duration for this bucket in milliseconds.
-    int64 bucket_duration_ms = 1;
+    optional int64 bucket_duration_ms = 1;
 
     repeated NetworkStatsHistoryBucketProto buckets = 2;
 }
@@ -107,15 +106,15 @@
 // Corresponds to each bucket in NetworkStatsHistory.
 message NetworkStatsHistoryBucketProto {
     // Bucket start time in milliseconds since epoch.
-    int64 bucket_start_ms = 1;
+    optional int64 bucket_start_ms = 1;
 
-    int64 rx_bytes = 2;
+    optional int64 rx_bytes = 2;
 
-    int64 rx_packets = 3;
+    optional int64 rx_packets = 3;
 
-    int64 tx_bytes = 4;
+    optional int64 tx_bytes = 4;
 
-    int64 tx_packets = 5;
+    optional int64 tx_packets = 5;
 
-    int64 operations = 6;
+    optional int64 operations = 6;
 }
diff --git a/core/proto/android/service/notification.proto b/core/proto/android/service/notification.proto
index d8cb1a7..7a0e152 100644
--- a/core/proto/android/service/notification.proto
+++ b/core/proto/android/service/notification.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 package android.service.notification;
 
 option java_multiple_files = true;
@@ -29,54 +28,60 @@
 message NotificationServiceDumpProto {
     repeated NotificationRecordProto records = 1;
 
-    ZenModeProto zen = 2;
+    optional ZenModeProto zen = 2;
 
-    ManagedServicesProto notification_listeners = 3;
+    optional ManagedServicesProto notification_listeners = 3;
 
-    int32 listener_hints = 4;
+    optional int32 listener_hints = 4;
 
     repeated ListenersDisablingEffectsProto listeners_disabling_effects = 5;
 
-    ManagedServicesProto notification_assistants = 6;
+    optional ManagedServicesProto notification_assistants = 6;
 
-    ManagedServicesProto condition_providers = 7;
+    optional ManagedServicesProto condition_providers = 7;
 
-    RankingHelperProto ranking_config = 8;
+    optional RankingHelperProto ranking_config = 8;
 }
 
 message NotificationRecordProto {
-    string key = 1;
-    State state = 2;
-    int32 flags = 3;
-    string channelId = 4;
-    string sound = 5;
-    int32 sound_usage = 6;
-    bool can_vibrate = 7;
-    bool can_show_light = 8;
-    string group_key = 9;
-    int32 importance = 10;
+    optional string key = 1;
+
+    enum State {
+        ENQUEUED = 0;
+        POSTED = 1;
+        SNOOZED = 2;
+    }
+    optional State state = 2;
+    optional int32 flags = 3;
+    optional string channelId = 4;
+    optional string sound = 5;
+    optional int32 sound_usage = 6;
+    optional bool can_vibrate = 7;
+    optional bool can_show_light = 8;
+    optional string group_key = 9;
+    optional int32 importance = 10;
 }
 
 message ListenersDisablingEffectsProto {
-    int32 hint = 1;
+    optional int32 hint = 1;
     repeated ManagedServiceInfoProto listeners = 2;
 }
 
 message ManagedServiceInfoProto {
-    android.content.ComponentNameProto component = 1;
-    int32 user_id = 2;
-    string service = 3;
-    bool is_system = 4;
-    bool is_guest = 5;
+    optional android.content.ComponentNameProto component = 1;
+    optional int32 user_id = 2;
+    optional string service = 3;
+    optional bool is_system = 4;
+    optional bool is_guest = 5;
 }
 
 message ManagedServicesProto {
-    string caption = 1;
+    optional string caption = 1;
 
     message ServiceProto {
         repeated string name = 1;
-        int32 user_id = 2;
-        bool is_primary = 3;
+        optional int32 user_id = 2;
+        optional bool is_primary = 3;
     }
     repeated ServiceProto approved = 2;
 
@@ -94,17 +99,17 @@
     repeated string notification_signal_extractors = 1;
 
     message RecordProto {
-        string package = 1;
+        optional string package = 1;
         // Default value is UNKNOWN_UID = USER_NULL = -10000.
-        int32 uid = 2;
+        optional int32 uid = 2;
         // Default is IMPORTANCE_UNSPECIFIED (-1000).
-        int32 importance = 3;
+        optional int32 importance = 3;
         // Default is PRIORITY_DEFAULT (0).
-        int32 priority = 4;
+        optional int32 priority = 4;
         // Default is VISIBILITY_NO_OVERRIDE (-1000).
-        int32 visibility = 5;
+        optional int32 visibility = 5;
         // Default is true.
-        bool show_badge = 6;
+        optional bool show_badge = 6;
         repeated android.app.NotificationChannelProto channels = 7;
         repeated android.app.NotificationChannelGroupProto channel_groups = 8;
     }
@@ -112,25 +117,16 @@
     repeated RecordProto records_restored_without_uid = 3;
 }
 
-enum State {
-    ENQUEUED = 0;
-
-    POSTED = 1;
-
-    SNOOZED = 2;
-}
-
 message ZenModeProto {
-    ZenMode zen_mode = 1;
+    enum ZenMode {
+        ZEN_MODE_OFF = 0;
+        ZEN_MODE_IMPORTANT_INTERRUPTIONS = 1;
+        ZEN_MODE_NO_INTERRUPTIONS = 2;
+        ZEN_MODE_ALARMS = 3;
+    }
+    optional ZenMode zen_mode = 1;
     repeated string enabled_active_conditions = 2;
-    int32 suppressed_effects = 3;
+    optional int32 suppressed_effects = 3;
     repeated string suppressors = 4;
-    android.app.PolicyProto policy = 5;
-}
-
-enum ZenMode {
-    ZEN_MODE_OFF = 0;
-    ZEN_MODE_IMPORTANT_INTERRUPTIONS = 1;
-    ZEN_MODE_NO_INTERRUPTIONS = 2;
-    ZEN_MODE_ALARMS = 3;
+    optional android.app.PolicyProto policy = 5;
 }
diff --git a/core/proto/android/service/package.proto b/core/proto/android/service/package.proto
index 326b0eb..be82e2d 100644
--- a/core/proto/android/service/package.proto
+++ b/core/proto/android/service/package.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 package android.service.pm;
 
 option java_multiple_files = true;
@@ -24,31 +23,31 @@
 message PackageServiceDumpProto {
     message PackageShortProto {
         // Name of package. e.g. "com.android.providers.telephony".
-        string name = 1;
+        optional string name = 1;
         // UID for this package as assigned by Android OS.
-        int32 uid = 2;
+        optional int32 uid = 2;
     }
     message SharedLibraryProto {
-        string name = 1;
+        optional string name = 1;
         // True if library path is not null (jar), false otherwise (apk)
-        bool is_jar = 2;
+        optional bool is_jar = 2;
         // Should be filled if is_jar is true
-        string path = 3;
+        optional string path = 3;
         // Should be filled if is_jar is false
-        string apk = 4;
+        optional string apk = 4;
     }
     message FeatureProto {
-        string name = 1;
-        int32 version = 2;
+        optional string name = 1;
+        optional int32 version = 2;
     }
     message SharedUserProto {
-        int32 user_id = 1;
-        string name = 2;
+        optional int32 user_id = 1;
+        optional string name = 2;
     }
 
     // Installed packages.
-    PackageShortProto required_verifier_package = 1;
-    PackageShortProto verifier_package = 2;
+    optional PackageShortProto required_verifier_package = 1;
+    optional PackageShortProto verifier_package = 2;
     repeated SharedLibraryProto shared_libraries = 3;
     repeated FeatureProto features = 4;
     repeated PackageProto packages = 5;
@@ -59,8 +58,8 @@
 
 message PackageProto {
     message SplitProto {
-        string name = 1;
-        int32 revision_code = 2;
+        optional string name = 1;
+        optional int32 revision_code = 2;
     }
     message UserInfoProto {
         enum InstallType {
@@ -87,32 +86,32 @@
             COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED = 4;
         }
 
-        int32 id = 1;
-        InstallType install_type = 2;
+        optional int32 id = 1;
+        optional InstallType install_type = 2;
         // Is the app restricted by owner / admin
-        bool is_hidden = 3;
-        bool is_suspended = 4;
-        bool is_stopped = 5;
-        bool is_launched = 6;
-        EnabledState enabled_state = 7;
-        string last_disabled_app_caller = 8;
+        optional bool is_hidden = 3;
+        optional bool is_suspended = 4;
+        optional bool is_stopped = 5;
+        optional bool is_launched = 6;
+        optional EnabledState enabled_state = 7;
+        optional string last_disabled_app_caller = 8;
     }
 
     // Name of package. e.g. "com.android.providers.telephony".
-    string name = 1;
+    optional string name = 1;
     // UID for this package as assigned by Android OS.
-    int32 uid = 2;
+    optional int32 uid = 2;
     // Package's reported version.
-    int32 version_code = 3;
+    optional int32 version_code = 3;
     // Package's reported version string (what's displayed to the user).
-    string version_string = 4;
+    optional string version_string = 4;
     // UTC timestamp of install
-    int64 install_time_ms = 5;
+    optional int64 install_time_ms = 5;
     // Millisecond UTC timestamp of latest update adjusted to Google's server clock.
-    int64 update_time_ms = 6;
+    optional int64 update_time_ms = 6;
     // From "dumpsys package" - name of package which installed this one.
     // Typically "" if system app or "com.android.vending" if Play Store.
-    string installer_name = 7;
+    optional string installer_name = 7;
     // Split APKs.
     repeated SplitProto splits = 8;
     // Per-user package info.
diff --git a/core/proto/android/service/power.proto b/core/proto/android/service/power.proto
index 1830dbf..5d53847 100644
--- a/core/proto/android/service/power.proto
+++ b/core/proto/android/service/power.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 package android.service.power;
 
 option java_multiple_files = true;
@@ -27,23 +26,23 @@
 
 message PowerServiceDumpProto {
     message ConstantsProto {
-        bool is_no_cached_wake_locks = 1;
+        optional bool is_no_cached_wake_locks = 1;
     }
     message ActiveWakeLocksProto {
-        bool is_cpu = 1;
-        bool is_screen_bright = 2;
-        bool is_screen_dim = 3;
-        bool is_button_bright = 4;
-        bool is_proximity_screen_off = 5;
+        optional bool is_cpu = 1;
+        optional bool is_screen_bright = 2;
+        optional bool is_screen_dim = 3;
+        optional bool is_button_bright = 4;
+        optional bool is_proximity_screen_off = 5;
         // only set if already awake
-        bool is_stay_awake = 6;
-        bool is_doze = 7;
-        bool is_draw = 8;
+        optional bool is_stay_awake = 6;
+        optional bool is_doze = 7;
+        optional bool is_draw = 8;
     }
     message UserActivityProto {
-        bool is_screen_bright = 1;
-        bool is_screen_dim = 2;
-        bool is_screen_dream = 3;
+        optional bool is_screen_bright = 1;
+        optional bool is_screen_dim = 2;
+        optional bool is_screen_dream = 3;
     }
     message UidProto {
         // Enum values gotten from ActivityManager.java
@@ -88,12 +87,12 @@
             // Process does not exist.
             PROCESS_STATE_NONEXISTENT = 17;
         }
-        int32 uid = 1;
-        string uid_string = 2;
-        bool is_active = 3;
-        int32 num_wake_locks = 4;
-        bool is_process_state_unknown = 5;
-        ProcessState process_state = 6;
+        optional int32 uid = 1;
+        optional string uid_string = 2;
+        optional bool is_active = 3;
+        optional int32 num_wake_locks = 4;
+        optional bool is_process_state_unknown = 5;
+        optional ProcessState process_state = 6;
     }
 
     // Enum values gotten from PowerManagerInternal.java
@@ -120,123 +119,123 @@
         DOCK_STATE_HE_DESK = 4;
     }
 
-    ConstantsProto constants = 1;
+    optional ConstantsProto constants = 1;
     // A bitfield that indicates what parts of the power state have
     // changed and need to be recalculated.
-    int32 dirty = 2;
+    optional int32 dirty = 2;
     // Indicates whether the device is awake or asleep or somewhere in between.
-    Wakefulness wakefulness = 3;
-    bool is_wakefulness_changing = 4;
+    optional Wakefulness wakefulness = 3;
+    optional bool is_wakefulness_changing = 4;
     // True if the device is plugged into a power source.
-    bool is_powered = 5;
+    optional bool is_powered = 5;
     // The current plug type
-    PlugType plug_type = 6;
+    optional PlugType plug_type = 6;
     // The current battery level percentage.
-    int32 battery_level = 7;
+    optional int32 battery_level = 7;
     // The battery level percentage at the time the dream started.
-    int32 battery_level_when_dream_started = 8;
+    optional int32 battery_level_when_dream_started = 8;
     // The current dock state.
-    DockState dock_state = 9;
+    optional DockState dock_state = 9;
     // True if the device should stay on.
-    bool is_stay_on = 10;
+    optional bool is_stay_on = 10;
     // True if the proximity sensor reads a positive result.
-    bool is_proximity_positive = 11;
+    optional bool is_proximity_positive = 11;
     // True if boot completed occurred.  We keep the screen on until this happens.
-    bool is_boot_completed = 12;
+    optional bool is_boot_completed = 12;
     // True if systemReady() has been called.
-    bool is_system_ready = 13;
+    optional bool is_system_ready = 13;
     // True if auto-suspend mode is enabled.
-    bool is_hal_auto_suspend_mode_enabled = 14;
+    optional bool is_hal_auto_suspend_mode_enabled = 14;
     // True if interactive mode is enabled.
-    bool is_hal_auto_interactive_mode_enabled = 15;
+    optional bool is_hal_auto_interactive_mode_enabled = 15;
     // Summarizes the state of all active wakelocks.
-    ActiveWakeLocksProto active_wake_locks = 16;
+    optional ActiveWakeLocksProto active_wake_locks = 16;
     // Have we scheduled a message to check for long wake locks?  This is when
     // we will check. (In milliseconds timestamp)
-    int64 notify_long_scheduled_ms = 17;
+    optional int64 notify_long_scheduled_ms = 17;
     // Last time we checked for long wake locks. (In milliseconds timestamp)
-    int64 notify_long_dispatched_ms = 18;
+    optional int64 notify_long_dispatched_ms = 18;
     // The time we decided to do next long check. (In milliseconds timestamp)
-    int64 notify_long_next_check_ms = 19;
+    optional int64 notify_long_next_check_ms = 19;
     // Summarizes the effect of the user activity timer.
-    UserActivityProto user_activity = 20;
+    optional UserActivityProto user_activity = 20;
     // If true, instructs the display controller to wait for the proximity
     // sensor to go negative before turning the screen on.
-    bool is_request_wait_for_negative_proximity = 21;
+    optional bool is_request_wait_for_negative_proximity = 21;
     // True if MSG_SANDMAN has been scheduled.
-    bool is_sandman_scheduled = 22;
+    optional bool is_sandman_scheduled = 22;
     // True if the sandman has just been summoned for the first time since entering
     // the dreaming or dozing state.  Indicates whether a new dream should begin.
-    bool is_sandman_summoned = 23;
+    optional bool is_sandman_summoned = 23;
     // If true, the device is in low power mode.
-    bool is_low_power_mode_enabled = 24;
+    optional bool is_low_power_mode_enabled = 24;
     // True if the battery level is currently considered low.
-    bool is_battery_level_low = 25;
+    optional bool is_battery_level_low = 25;
     // True if we are currently in light device idle mode.
-    bool is_light_device_idle_mode = 26;
+    optional bool is_light_device_idle_mode = 26;
     // True if we are currently in device idle mode.
-    bool is_device_idle_mode = 27;
+    optional bool is_device_idle_mode = 27;
     // Set of app ids that we will always respect the wake locks for.
     repeated int32 device_idle_whitelist = 28;
     // Set of app ids that are temporarily allowed to acquire wakelocks due to
     // high-pri message
     repeated int32 device_idle_temp_whitelist = 29;
     // Timestamp of the last time the device was awoken.
-    int64 last_wake_time_ms = 30;
+    optional int64 last_wake_time_ms = 30;
     // Timestamp of the last time the device was put to sleep.
-    int64 last_sleep_time_ms = 31;
+    optional int64 last_sleep_time_ms = 31;
     // Timestamp of the last call to user activity.
-    int64 last_user_activity_time_ms = 32;
-    int64 last_user_activity_time_no_change_lights_ms = 33;
+    optional int64 last_user_activity_time_ms = 32;
+    optional int64 last_user_activity_time_no_change_lights_ms = 33;
     // Timestamp of last interactive power hint.
-    int64 last_interactive_power_hint_time_ms = 34;
+    optional int64 last_interactive_power_hint_time_ms = 34;
     // Timestamp of the last screen brightness boost.
-    int64 last_screen_brightness_boost_time_ms = 35;
+    optional int64 last_screen_brightness_boost_time_ms = 35;
     // True if screen brightness boost is in progress.
-    bool is_screen_brightness_boost_in_progress = 36;
+    optional bool is_screen_brightness_boost_in_progress = 36;
     // True if the display power state has been fully applied, which means the
     // display is actually on or actually off or whatever was requested.
-    bool is_display_ready = 37;
+    optional bool is_display_ready = 37;
     // True if the wake lock suspend blocker has been acquired.
-    bool is_holding_wake_lock_suspend_blocker = 38;
+    optional bool is_holding_wake_lock_suspend_blocker = 38;
     // The suspend blocker used to keep the CPU alive when the display is on, the
     // display is getting ready or there is user activity (in which case the
     // display must be on).
-    bool is_holding_display_suspend_blocker = 39;
+    optional bool is_holding_display_suspend_blocker = 39;
     // Settings and configuration
-    PowerServiceSettingsAndConfigurationDumpProto settings_and_configuration = 40;
+    optional PowerServiceSettingsAndConfigurationDumpProto settings_and_configuration = 40;
     // Sleep timeout in ms
-    sint32 sleep_timeout_ms = 41;
+    optional sint32 sleep_timeout_ms = 41;
     // Screen off timeout in ms
-    int32 screen_off_timeout_ms = 42;
+    optional int32 screen_off_timeout_ms = 42;
     // Screen dim duration in ms
-    int32 screen_dim_duration_ms = 43;
+    optional int32 screen_dim_duration_ms = 43;
     // We are currently in the middle of a batch change of uids.
-    bool are_uids_changing = 44;
+    optional bool are_uids_changing = 44;
     // Some uids have actually changed while mUidsChanging was true.
-    bool are_uids_changed = 45;
+    optional bool are_uids_changed = 45;
     // List of UIDs and their states
     repeated UidProto uids = 46;
-    android.os.LooperProto looper = 47;
+    optional android.os.LooperProto looper = 47;
     // List of all wake locks acquired by applications.
     repeated WakeLockProto wake_locks = 48;
     // List of all suspend blockers.
     repeated SuspendBlockerProto suspend_blockers = 49;
-    WirelessChargerDetectorProto wireless_charger_detector = 50;
+    optional WirelessChargerDetectorProto wireless_charger_detector = 50;
 }
 
 message SuspendBlockerProto {
-    string name = 1;
-    int32 reference_count = 2;
+    optional string name = 1;
+    optional int32 reference_count = 2;
 }
 
 message WakeLockProto {
     message WakeLockFlagsProto {
         // Turn the screen on when the wake lock is acquired.
-        bool is_acquire_causes_wakeup = 1;
+        optional bool is_acquire_causes_wakeup = 1;
         // When this wake lock is released, poke the user activity timer
         // so the screen stays on for a little longer.
-        bool is_on_after_release = 2;
+        optional bool is_on_after_release = 2;
     }
 
     // Enum values gotten from PowerManager.java
@@ -259,31 +258,31 @@
         DRAW_WAKE_LOCK = 128;
     }
 
-    LockLevel lock_level = 1;
-    string tag = 2;
-    WakeLockFlagsProto flags = 3;
-    bool is_disabled = 4;
+    optional LockLevel lock_level = 1;
+    optional string tag = 2;
+    optional WakeLockFlagsProto flags = 3;
+    optional bool is_disabled = 4;
     // Acquire time in ms
-    int64 acq_ms = 5;
-    bool is_notified_long = 6;
+    optional int64 acq_ms = 5;
+    optional bool is_notified_long = 6;
     // Owner UID
-    int32 uid = 7;
+    optional int32 uid = 7;
     // Owner PID
-    int32 pid = 8;
-    android.os.WorkSourceProto work_source = 9;
+    optional int32 pid = 8;
+    optional android.os.WorkSourceProto work_source = 9;
 }
 
 message PowerServiceSettingsAndConfigurationDumpProto {
     message StayOnWhilePluggedInProto {
-        bool is_stay_on_while_plugged_in_ac = 1;
-        bool is_stay_on_while_plugged_in_usb = 2;
-        bool is_stay_on_while_plugged_in_wireless = 3;
+        optional bool is_stay_on_while_plugged_in_ac = 1;
+        optional bool is_stay_on_while_plugged_in_usb = 2;
+        optional bool is_stay_on_while_plugged_in_wireless = 3;
     }
     message ScreenBrightnessSettingLimitsProto {
-        int32 setting_minimum = 1;
-        int32 setting_maximum = 2;
-        int32 setting_default = 3;
-        int32 setting_for_vr_default = 4;
+        optional int32 setting_minimum = 1;
+        optional int32 setting_maximum = 2;
+        optional int32 setting_default = 3;
+        optional int32 setting_for_vr_default = 4;
     }
 
     // Enum values gotten from Settings.java
@@ -303,106 +302,106 @@
 
 
     // True to decouple auto-suspend mode from the display state.
-    bool is_decouple_hal_auto_suspend_mode_from_display_config = 1;
+    optional bool is_decouple_hal_auto_suspend_mode_from_display_config = 1;
     // True to decouple interactive mode from the display state.
-    bool is_decouple_hal_interactive_mode_from_display_config = 2;
+    optional bool is_decouple_hal_interactive_mode_from_display_config = 2;
     // True if the device should wake up when plugged or unplugged.
-    bool is_wake_up_when_plugged_or_unplugged_config = 3;
+    optional bool is_wake_up_when_plugged_or_unplugged_config = 3;
     // True if the device should wake up when plugged or unplugged in theater mode.
-    bool is_wake_up_when_plugged_or_unplugged_in_theater_mode_config = 4;
+    optional bool is_wake_up_when_plugged_or_unplugged_in_theater_mode_config = 4;
     // True if theater mode is enabled
-    bool is_theater_mode_enabled = 5;
+    optional bool is_theater_mode_enabled = 5;
     // True if the device should suspend when the screen is off due to proximity.
-    bool is_suspend_when_screen_off_due_to_proximity_config = 6;
+    optional bool is_suspend_when_screen_off_due_to_proximity_config = 6;
     // True if dreams are supported on this device.
-    bool are_dreams_supported_config = 7;
+    optional bool are_dreams_supported_config = 7;
     // Default value for dreams enabled
-    bool are_dreams_enabled_by_default_config = 8;
+    optional bool are_dreams_enabled_by_default_config = 8;
     // Default value for dreams activate-on-sleep
-    bool are_dreams_activated_on_sleep_by_default_config = 9;
+    optional bool are_dreams_activated_on_sleep_by_default_config = 9;
     // Default value for dreams activate-on-dock
-    bool are_dreams_activated_on_dock_by_default_config = 10;
+    optional bool are_dreams_activated_on_dock_by_default_config = 10;
     // True if dreams can run while not plugged in.
-    bool are_dreams_enabled_on_battery_config = 11;
+    optional bool are_dreams_enabled_on_battery_config = 11;
     // Minimum battery level to allow dreaming when powered.
     // Use -1 to disable this safety feature.
-    sint32 dreams_battery_level_minimum_when_powered_config = 12;
+    optional sint32 dreams_battery_level_minimum_when_powered_config = 12;
     // Minimum battery level to allow dreaming when not powered.
     // Use -1 to disable this safety feature.
-    sint32 dreams_battery_level_minimum_when_not_powered_config = 13;
+    optional sint32 dreams_battery_level_minimum_when_not_powered_config = 13;
     // If the battery level drops by this percentage and the user activity
     // timeout has expired, then assume the device is receiving insufficient
     // current to charge effectively and terminate the dream.  Use -1 to disable
     // this safety feature.
-    sint32 dreams_battery_level_drain_cutoff_config = 14;
+    optional sint32 dreams_battery_level_drain_cutoff_config = 14;
     // True if dreams are enabled by the user.
-    bool are_dreams_enabled_setting = 15;
+    optional bool are_dreams_enabled_setting = 15;
     // True if dreams should be activated on sleep.
-    bool are_dreams_activate_on_sleep_setting = 16;
+    optional bool are_dreams_activate_on_sleep_setting = 16;
     // True if dreams should be activated on dock.
-    bool are_dreams_activate_on_dock_setting = 17;
+    optional bool are_dreams_activate_on_dock_setting = 17;
     // True if doze should not be started until after the screen off transition.
-    bool is_doze_after_screen_off_config = 18;
+    optional bool is_doze_after_screen_off_config = 18;
     // If true, the device is in low power mode.
-    bool is_low_power_mode_setting = 19;
+    optional bool is_low_power_mode_setting = 19;
     // Current state of whether the settings are allowing auto low power mode.
-    bool is_auto_low_power_mode_configured = 20;
+    optional bool is_auto_low_power_mode_configured = 20;
     // The user turned off low power mode below the trigger level
-    bool is_auto_low_power_mode_snoozing = 21;
+    optional bool is_auto_low_power_mode_snoozing = 21;
     // The minimum screen off timeout, in milliseconds.
-    int32 minimum_screen_off_timeout_config_ms = 22;
+    optional int32 minimum_screen_off_timeout_config_ms = 22;
     // The screen dim duration, in milliseconds.
-    int32 maximum_screen_dim_duration_config_ms = 23;
+    optional int32 maximum_screen_dim_duration_config_ms = 23;
     // The maximum screen dim time expressed as a ratio relative to the screen off timeout.
-    float maximum_screen_dim_ratio_config = 24;
+    optional float maximum_screen_dim_ratio_config = 24;
     // The screen off timeout setting value in milliseconds.
-    int32 screen_off_timeout_setting_ms = 25;
+    optional int32 screen_off_timeout_setting_ms = 25;
     // The sleep timeout setting value in milliseconds.
-    sint32 sleep_timeout_setting_ms = 26;
+    optional sint32 sleep_timeout_setting_ms = 26;
     // The maximum allowable screen off timeout according to the device administration policy.
-    int32 maximum_screen_off_timeout_from_device_admin_ms = 27;
-    bool is_maximum_screen_off_timeout_from_device_admin_enforced_locked = 28;
+    optional int32 maximum_screen_off_timeout_from_device_admin_ms = 27;
+    optional bool is_maximum_screen_off_timeout_from_device_admin_enforced_locked = 28;
     // The stay on while plugged in setting.
     // A set of battery conditions under which to make the screen stay on.
-    StayOnWhilePluggedInProto stay_on_while_plugged_in = 29;
+    optional StayOnWhilePluggedInProto stay_on_while_plugged_in = 29;
     // The screen brightness setting, from 0 to 255.
     // Use -1 if no value has been set.
-    sint32 screen_brightness_setting = 30;
+    optional sint32 screen_brightness_setting = 30;
     // The screen auto-brightness adjustment setting, from -1 to 1.
     // Use 0 if there is no adjustment.
-    float screen_auto_brightness_adjustment_setting = 31;
+    optional float screen_auto_brightness_adjustment_setting = 31;
     // The screen brightness mode.
-    ScreenBrightnessMode screen_brightness_mode_setting = 32;
+    optional ScreenBrightnessMode screen_brightness_mode_setting = 32;
     // The screen brightness setting override from the window manager
     // to allow the current foreground activity to override the brightness.
     // Use -1 to disable.
-    sint32 screen_brightness_override_from_window_manager = 33;
+    optional sint32 screen_brightness_override_from_window_manager = 33;
     // The user activity timeout override from the window manager
     // to allow the current foreground activity to override the user activity
     // timeout. Use -1 to disable.
-    sint64 user_activity_timeout_override_from_window_manager_ms = 34;
+    optional sint64 user_activity_timeout_override_from_window_manager_ms = 34;
     // The window manager has determined the user to be inactive via other means.
     // Set this to false to disable.
-    bool is_user_inactive_override_from_window_manager = 35;
+    optional bool is_user_inactive_override_from_window_manager = 35;
     // The screen brightness setting override from the settings application
     // to temporarily adjust the brightness until next updated,
     // Use -1 to disable.
-    sint32 temporary_screen_brightness_setting_override = 36;
+    optional sint32 temporary_screen_brightness_setting_override = 36;
     // The screen brightness adjustment setting override from the settings
     // application to temporarily adjust the auto-brightness adjustment factor
     // until next updated, in the range -1..1.
     // Use NaN to disable.
-    float temporary_screen_auto_brightness_adjustment_setting_override = 37;
+    optional float temporary_screen_auto_brightness_adjustment_setting_override = 37;
     // The screen state to use while dozing.
-    DisplayState doze_screen_state_override_from_dream_manager = 38;
+    optional DisplayState doze_screen_state_override_from_dream_manager = 38;
     // The screen brightness to use while dozing.
-    float dozed_screen_brightness_override_from_dream_manager = 39;
+    optional float dozed_screen_brightness_override_from_dream_manager = 39;
     // Screen brightness settings limits.
-    ScreenBrightnessSettingLimitsProto screen_brightness_setting_limits = 40;
+    optional ScreenBrightnessSettingLimitsProto screen_brightness_setting_limits = 40;
     // The screen brightness setting, from 0 to 255, to be used while in VR Mode.
-    int32 screen_brightness_for_vr_setting = 41;
+    optional int32 screen_brightness_for_vr_setting = 41;
     // True if double tap to wake is enabled
-    bool is_double_tap_wake_enabled = 42;
+    optional bool is_double_tap_wake_enabled = 42;
     // True if we are currently in VR Mode.
-    bool is_vr_mode_enabled = 43;
+    optional bool is_vr_mode_enabled = 43;
 }
diff --git a/core/proto/android/service/print.proto b/core/proto/android/service/print.proto
index f099872..c2be7f1 100644
--- a/core/proto/android/service/print.proto
+++ b/core/proto/android/service/print.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 package android.service.print;
 
 option java_multiple_files = true;
@@ -30,7 +29,7 @@
 
 message PrintUserStateProto {
     // Should be 0, 10, 11, 12, etc. where 0 is the owner.
-    int32 user_id = 1;
+    optional int32 user_id = 1;
 
     // The installed print services
     repeated InstalledPrintServiceProto installed_services = 2;
@@ -48,18 +47,18 @@
     repeated PrinterDiscoverySessionProto discovery_sessions = 6;
 
     // The print spooler state
-    PrintSpoolerStateProto print_spooler_state = 7;
+    optional PrintSpoolerStateProto print_spooler_state = 7;
 }
 
 message PrintSpoolerStateProto {
     // Is the print spooler destroyed?
-    bool is_destroyed = 1;
+    optional bool is_destroyed = 1;
 
     // Is the print spooler bound?
-    bool is_bound = 2;
+    optional bool is_bound = 2;
 
     // State internal to the print spooler
-    PrintSpoolerInternalStateProto internal_state = 3;
+    optional PrintSpoolerInternalStateProto internal_state = 3;
 }
 
 message PrintSpoolerInternalStateProto {
@@ -75,7 +74,7 @@
 
 message PrinterCapabilitiesProto {
     // Minimum margins of the printer
-    MarginsProto min_margins = 1;
+    optional MarginsProto min_margins = 1;
 
     // List of supported media sizes
     repeated MediaSizeProto media_sizes = 2;
@@ -92,10 +91,10 @@
 
 message PrinterInfoProto {
     // The id of the printer
-    PrinterIdProto id = 1;
+    optional PrinterIdProto id = 1;
 
     // The name of the printer
-    string name = 2;
+    optional string name = 2;
 
     enum Status {
         // unused
@@ -111,21 +110,21 @@
         STATUS_UNAVAILABLE = 3;
     }
     // The status of the printer
-    Status status = 3;
+    optional Status status = 3;
 
     // The description of the printer
-    string description = 4;
+    optional string description = 4;
 
     // The capabilities of the printer
-    PrinterCapabilitiesProto capabilities = 5;
+    optional PrinterCapabilitiesProto capabilities = 5;
 }
 
 message PrinterDiscoverySessionProto {
     // Is this session destroyed?
-    bool is_destroyed = 1;
+    optional bool is_destroyed = 1;
 
     // Is printer discovery in progress?
-    bool is_printer_discovery_in_progress = 2;
+    optional bool is_printer_discovery_in_progress = 2;
 
     // List of printer discovery observers
     repeated string printer_discovery_observers = 3;
@@ -142,44 +141,44 @@
 
 message InstalledPrintServiceProto {
     // Component name of the service
-    android.content.ComponentNameProto component_name = 1;
+    optional android.content.ComponentNameProto component_name = 1;
 
     // Settings activity for this service
-    string settings_activity = 2;
+    optional string settings_activity = 2;
 
     // Add printers activity for this service
-    string add_printers_activity = 3;
+    optional string add_printers_activity = 3;
 
     // Advances options activity for this service
-    string advanced_options_activity = 4;
+    optional string advanced_options_activity = 4;
 }
 
 message PrinterIdProto {
     // Component name of the service that reported the printer
-    android.content.ComponentNameProto service_name = 1;
+    optional android.content.ComponentNameProto service_name = 1;
 
     // Local id of the printer
-    string local_id = 2;
+    optional string local_id = 2;
 }
 
 message ActivePrintServiceProto {
     // Component name of the service
-    android.content.ComponentNameProto component_name = 1;
+    optional android.content.ComponentNameProto component_name = 1;
 
     // Is the active service destroyed
-    bool is_destroyed = 2;
+    optional bool is_destroyed = 2;
 
     // Is the active service bound
-    bool is_bound = 3;
+    optional bool is_bound = 3;
 
     // Has the active service a discovery session
-    bool has_discovery_session = 4;
+    optional bool has_discovery_session = 4;
 
     // Has the active service a active print jobs
-    bool has_active_print_jobs = 5;
+    optional bool has_active_print_jobs = 5;
 
     // Is the active service discovering printers
-    bool is_discovering_printers = 6;
+    optional bool is_discovering_printers = 6;
 
     // The tracked printers of this active service
     repeated PrinterIdProto tracked_printers = 7;
@@ -187,58 +186,58 @@
 
 message MediaSizeProto {
     // Id of this media size
-    string id = 1;
+    optional string id = 1;
 
     // Label of this media size
-    string label = 2;
+    optional string label = 2;
 
     // Height of the media
-    int32 height_mils = 3;
+    optional int32 height_mils = 3;
 
     // Width of the media
-    int32 width_mils = 4;
+    optional int32 width_mils = 4;
 }
 
 message ResolutionProto {
     // Id of this resolution
-    string id = 1;
+    optional string id = 1;
 
     // Label for this resoltion
-    string label = 2;
+    optional string label = 2;
 
     // Resolution in horizontal orientation
-    int32 horizontal_dpi = 3;
+    optional int32 horizontal_dpi = 3;
 
     // Resolution in vertical orientation
-    int32 vertical_dpi = 4;
+    optional int32 vertical_dpi = 4;
 }
 
 message MarginsProto {
     // Space at the top
-    int32 top_mils = 1;
+    optional int32 top_mils = 1;
 
     // Space at the left
-    int32 left_mils = 2;
+    optional int32 left_mils = 2;
 
     // Space at the right
-    int32 right_mils = 3;
+    optional int32 right_mils = 3;
 
     // Space at the bottom
-    int32 bottom_mils = 4;
+    optional int32 bottom_mils = 4;
 }
 
 message PrintAttributesProto {
     // Media to use
-    ResolutionProto media_size = 1;
+    optional ResolutionProto media_size = 1;
 
     // Is the media in portrait mode?
-    bool is_portrait = 2;
+    optional bool is_portrait = 2;
 
     // Resolution to use
-    ResolutionProto resolution = 3;
+    optional ResolutionProto resolution = 3;
 
     // Margins around the document
-    MarginsProto min_margins = 4;
+    optional MarginsProto min_margins = 4;
 
     enum ColorMode {
         // unused
@@ -251,7 +250,7 @@
         COLOR_MODE_COLOR = 2;
     }
     // Color mode to use
-    ColorMode color_mode = 5;
+    optional ColorMode color_mode = 5;
 
     enum DuplexMode {
         // unused
@@ -267,37 +266,37 @@
         DUPLEX_MODE_SHORT_EDGE = 4;
     }
     // Duplex mode to use
-    DuplexMode duplex_mode = 6;
+    optional DuplexMode duplex_mode = 6;
 }
 
 message PrintDocumentInfoProto {
     // Name of the document to print
-    string name = 1;
+    optional string name = 1;
 
     // Number of pages in the doc
-    int32 page_count = 2;
+    optional int32 page_count = 2;
 
     // Type of content (see PrintDocumentInfo.ContentType)
-    int32 content_type = 3;
+    optional int32 content_type = 3;
 
     // The size of the the document
-    int64 data_size = 4;
+    optional int64 data_size = 4;
 }
 
 message PageRangeProto {
     // Start of the range
-    int32 start = 1;
+    optional int32 start = 1;
 
     // End of the range (included)
-    int32 end = 2;
+    optional int32 end = 2;
 }
 
 message PrintJobInfoProto {
     // Label of the job
-    string label = 1;
+    optional string label = 1;
 
     // Id of the job
-    string print_job_id = 2;
+    optional string print_job_id = 2;
 
     enum State {
         // Unknown state
@@ -326,43 +325,43 @@
     }
 
     // State of the job
-    State state = 3;
+    optional State state = 3;
 
     // Printer handling the job
-    PrinterIdProto printer = 4;
+    optional PrinterIdProto printer = 4;
 
     // Tag assigned to the job
-    string tag = 5;
+    optional string tag = 5;
 
     // Time the job was created
-    int64 creation_time = 6;
+    optional int64 creation_time = 6;
 
     // Attributes of the job
-    PrintAttributesProto attributes = 7;
+    optional PrintAttributesProto attributes = 7;
 
     // Document info of the job
-    PrintDocumentInfoProto document_info = 8;
+    optional PrintDocumentInfoProto document_info = 8;
 
     // If the job current getting canceled
-    bool is_canceling = 9;
+    optional bool is_canceling = 9;
 
     // The selected ranges of the job
     repeated PageRangeProto pages = 10;
 
     // Does the job have any advanced options
-    bool has_advanced_options = 11;
+    optional bool has_advanced_options = 11;
 
     // Progress of the job
-    float progress = 12;
+    optional float progress = 12;
 
     // The current service set state
-    string status = 13;
+    optional string status = 13;
 }
 
 message CachedPrintJobProto {
     // The id of the app the job belongs to
-    int32 app_id = 1;
+    optional int32 app_id = 1;
 
     // The print job
-    PrintJobInfoProto print_job = 2;
+    optional PrintJobInfoProto print_job = 2;
 }
\ No newline at end of file
diff --git a/core/proto/android/service/procstats.proto b/core/proto/android/service/procstats.proto
index 322b212..b2e0373 100644
--- a/core/proto/android/service/procstats.proto
+++ b/core/proto/android/service/procstats.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 option java_multiple_files = true;
 option java_outer_classname = "ProcessStatsServiceProto";
 
@@ -30,11 +29,11 @@
  */
 message ProcessStatsServiceDumpProto {
 
-    ProcessStatsSectionProto procstats_now = 1;
+    optional ProcessStatsSectionProto procstats_now = 1;
 
-    ProcessStatsSectionProto procstats_over_3hrs = 2;
+    optional ProcessStatsSectionProto procstats_over_3hrs = 2;
 
-    ProcessStatsSectionProto procstats_over_24hrs = 3;
+    optional ProcessStatsSectionProto procstats_over_24hrs = 3;
 }
 
 /**
@@ -46,22 +45,22 @@
 message ProcessStatsSectionProto {
 
     // Elapsed realtime at start of report.
-    int64 start_realtime_ms = 1;
+    optional int64 start_realtime_ms = 1;
 
     // Elapsed realtime at end of report.
-    int64 end_realtime_ms = 2;
+    optional int64 end_realtime_ms = 2;
 
     // CPU uptime at start of report.
-    int64 start_uptime_ms = 3;
+    optional int64 start_uptime_ms = 3;
 
     // CPU uptime at end of report.
-    int64 end_uptime_ms = 4;
+    optional int64 end_uptime_ms = 4;
 
     // System runtime library. e.g. "libdvm.so", "libart.so".
-    string runtime = 5;
+    optional string runtime = 5;
 
     // whether kernel reports swapped pss.
-    bool has_swapped_pss = 6;
+    optional bool has_swapped_pss = 6;
 
     // Data completeness. e.g. "complete", "partial", shutdown", or "sysprops".
     enum Status {
@@ -81,23 +80,23 @@
 message ProcessStatsProto {
 
     // Name of process.
-    string process = 1;
+    optional string process = 1;
 
     // Uid of the process.
-    int32 uid = 2;
+    optional int32 uid = 2;
 
     // Information about how often kills occurred
     message Kill {
       // Count of excessive CPU kills
-      int32 cpu = 1;
+      optional int32 cpu = 1;
 
       // Count of kills when cached
-      int32 cached = 2;
+      optional int32 cached = 2;
 
       // PSS stats during cached kill
-      android.util.AggStats cached_pss = 3;
+      optional android.util.AggStats cached_pss = 3;
     }
-    Kill kill = 3;
+    optional Kill kill = 3;
 
     message State {
         enum ScreenState {
@@ -105,7 +104,7 @@
             OFF = 1;
             ON = 2;
         }
-        ScreenState screen_state = 1;
+        optional ScreenState screen_state = 1;
 
         enum MemoryState {
             MEMORY_UNKNOWN = 0;
@@ -114,7 +113,7 @@
             LOW = 3;        // low memory.
             CRITICAL = 4;   // critical memory.
         }
-        MemoryState memory_state = 2;
+        optional MemoryState memory_state = 2;
 
         enum ProcessState {
             PROCESS_UNKNOWN = 0;
@@ -147,19 +146,19 @@
             // Cached process that is empty.
             CACHED_EMPTY = 14;
         }
-        ProcessState process_state = 3;
+        optional ProcessState process_state = 3;
 
         // Millisecond duration spent in this state
-        int64 duration_ms = 4;
+        optional int64 duration_ms = 4;
 
         // # of samples taken
-        int32 sample_size = 5;
+        optional int32 sample_size = 5;
 
         // PSS is memory reserved for this process
-        android.util.AggStats pss = 6;
+        optional android.util.AggStats pss = 6;
 
         // USS is memory shared between processes, divided evenly for accounting
-        android.util.AggStats uss = 7;
+        optional android.util.AggStats uss = 7;
     }
     repeated State states = 5;
 }
diff --git a/core/proto/android/service/wirelesschargerdetector.proto b/core/proto/android/service/wirelesschargerdetector.proto
index 7ba7c17..bd697c8 100644
--- a/core/proto/android/service/wirelesschargerdetector.proto
+++ b/core/proto/android/service/wirelesschargerdetector.proto
@@ -14,37 +14,36 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 package android.service.power;
 
 option java_multiple_files = true;
 
 message WirelessChargerDetectorProto {
     message VectorProto {
-        float x = 1;
-        float y = 2;
-        float z = 3;
+        optional float x = 1;
+        optional float y = 2;
+        optional float z = 3;
     }
 
     // Previously observed wireless power state.
-    bool is_powered_wirelessly = 1;
+    optional bool is_powered_wirelessly = 1;
     // True if the device is thought to be at rest on a wireless charger.
-    bool is_at_rest = 2;
+    optional bool is_at_rest = 2;
     // The gravity vector most recently observed while at rest.
-    VectorProto rest = 3;
+    optional VectorProto rest = 3;
     // True if detection is in progress.
-    bool is_detection_in_progress = 4;
+    optional bool is_detection_in_progress = 4;
     // The time when detection was last performed.
-    int64 detection_start_time_ms = 5;
+    optional int64 detection_start_time_ms = 5;
     // True if the rest position should be updated if at rest.
-    bool is_must_update_rest_position = 6;
+    optional bool is_must_update_rest_position = 6;
     // The total number of samples collected.
-    int32 total_samples = 7;
+    optional int32 total_samples = 7;
     // The number of samples collected that showed evidence of not being at rest.
-    int32 moving_samples = 8;
+    optional int32 moving_samples = 8;
     // The value of the first sample that was collected.
-    VectorProto first_sample = 9;
+    optional VectorProto first_sample = 9;
     // The value of the last sample that was collected.
-    VectorProto last_sample = 10;
+    optional VectorProto last_sample = 10;
 }
\ No newline at end of file
diff --git a/core/proto/android/telephony/signalstrength.proto b/core/proto/android/telephony/signalstrength.proto
index ff230cb..366f1d1 100644
--- a/core/proto/android/telephony/signalstrength.proto
+++ b/core/proto/android/telephony/signalstrength.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 option java_package = "android.telephony";
 option java_multiple_files = true;
 
diff --git a/core/proto/android/util/common.proto b/core/proto/android/util/common.proto
index 6dd4c02..429c3cad 100644
--- a/core/proto/android/util/common.proto
+++ b/core/proto/android/util/common.proto
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 package android.util;
 
 option java_multiple_files = true;
@@ -25,9 +24,9 @@
  */
 message AggStats {
 
-    int64 min = 1;
+    optional int64 min = 1;
 
-    int64 average = 2;
+    optional int64 average = 2;
 
-    int64 max = 3;
+    optional int64 max = 3;
 }
diff --git a/core/proto/android/view/displayinfo.proto b/core/proto/android/view/displayinfo.proto
index 8583868..9ca4046 100644
--- a/core/proto/android/view/displayinfo.proto
+++ b/core/proto/android/view/displayinfo.proto
@@ -14,16 +14,15 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 package android.view;
 
 option java_multiple_files = true;
 
 /* represents DisplayInfo */
 message DisplayInfoProto {
-  int32 logical_width = 1;
-  int32 logical_height = 2;
-  int32 app_width = 3;
-  int32 app_height = 4;
+  optional int32 logical_width = 1;
+  optional int32 logical_height = 2;
+  optional int32 app_width = 3;
+  optional int32 app_height = 4;
 }
diff --git a/core/proto/android/view/windowlayoutparams.proto b/core/proto/android/view/windowlayoutparams.proto
index 5bb84dc..7821212 100644
--- a/core/proto/android/view/windowlayoutparams.proto
+++ b/core/proto/android/view/windowlayoutparams.proto
@@ -14,13 +14,12 @@
  * limitations under the License.
  */
 
-syntax = "proto3";
-
+syntax = "proto2";
 package android.view;
 
 option java_multiple_files = true;
 
 /* represents WindowManager.LayoutParams */
 message WindowLayoutParamsProto {
-  int32 type = 1;
+  optional int32 type = 1;
 }
diff --git a/libs/protoutil/include/android/util/ProtoOutputStream.h b/libs/protoutil/include/android/util/ProtoOutputStream.h
index 49ec169..0f1cced 100644
--- a/libs/protoutil/include/android/util/ProtoOutputStream.h
+++ b/libs/protoutil/include/android/util/ProtoOutputStream.h
@@ -37,7 +37,7 @@
 class ProtoOutputStream
 {
 public:
-    ProtoOutputStream(int fd);
+    ProtoOutputStream();
     ~ProtoOutputStream();
 
     /**
@@ -60,13 +60,19 @@
     void end(long long token);
 
     /**
-     * Flushes the protobuf data out.
+     * Flushes the protobuf data out to given fd.
      */
-    bool flush();
+    size_t size();
+    EncodedBuffer::iterator data();
+    bool flush(int fd);
+
+    // Please don't use the following functions to dump protos unless you are sure about it.
+    void writeRawVarint(uint64_t varint);
+    void writeLengthDelimitedHeader(uint32_t id, size_t size);
+    void writeRawByte(uint8_t byte);
 
 private:
     EncodedBuffer mBuffer;
-    int mFd;
     size_t mCopyBegin;
     bool mCompact;
     int mDepth;
diff --git a/libs/protoutil/src/ProtoOutputStream.cpp b/libs/protoutil/src/ProtoOutputStream.cpp
index e9ca0dc..15144ac 100644
--- a/libs/protoutil/src/ProtoOutputStream.cpp
+++ b/libs/protoutil/src/ProtoOutputStream.cpp
@@ -70,9 +70,8 @@
 const uint64_t FIELD_COUNT_REPEATED = 2ULL << FIELD_COUNT_SHIFT;
 const uint64_t FIELD_COUNT_PACKED = 4ULL << FIELD_COUNT_SHIFT;
 
-ProtoOutputStream::ProtoOutputStream(int fd)
+ProtoOutputStream::ProtoOutputStream()
         :mBuffer(),
-         mFd(fd),
          mCopyBegin(0),
          mCompact(false),
          mDepth(0),
@@ -483,6 +482,13 @@
     return true;
 }
 
+size_t
+ProtoOutputStream::size()
+{
+    compact();
+    return mBuffer.size();
+}
+
 static bool write_all(int fd, uint8_t const* buf, size_t size)
 {
     while (size > 0) {
@@ -497,19 +503,47 @@
 }
 
 bool
-ProtoOutputStream::flush()
+ProtoOutputStream::flush(int fd)
 {
-    if (mFd < 0) return false;
+    if (fd < 0) return false;
     if (!compact()) return false;
 
     EncodedBuffer::iterator it = mBuffer.begin();
     while (it.readBuffer() != NULL) {
-        if (!write_all(mFd, it.readBuffer(), it.currentToRead())) return false;
+        if (!write_all(fd, it.readBuffer(), it.currentToRead())) return false;
         it.rp()->move(it.currentToRead());
     }
     return true;
 }
 
+EncodedBuffer::iterator
+ProtoOutputStream::data()
+{
+    compact();
+    return mBuffer.begin();
+}
+
+void
+ProtoOutputStream::writeRawVarint(uint64_t varint)
+{
+    mBuffer.writeRawVarint64(varint);
+}
+
+void
+ProtoOutputStream::writeLengthDelimitedHeader(uint32_t id, size_t size)
+{
+    mBuffer.writeHeader(id, WIRE_TYPE_LENGTH_DELIMITED);
+    // reserves 64 bits for length delimited fields, if first field is negative, compact it.
+    mBuffer.writeRawFixed32(size);
+    mBuffer.writeRawFixed32(size);
+}
+
+void
+ProtoOutputStream::writeRawByte(uint8_t byte)
+{
+    mBuffer.writeRawByte(byte);
+}
+
 
 // =========================================================================
 // Private functions
@@ -639,9 +673,7 @@
 ProtoOutputStream::writeUtf8StringImpl(uint32_t id, const char* val, size_t size)
 {
     if (val == NULL || size == 0) return;
-    mBuffer.writeHeader(id, WIRE_TYPE_LENGTH_DELIMITED);
-    mBuffer.writeRawFixed32(size);
-    mBuffer.writeRawFixed32(size);
+    writeLengthDelimitedHeader(id, size);
     for (size_t i=0; i<size; i++) {
         mBuffer.writeRawByte((uint8_t)val[i]);
     }
diff --git a/packages/SystemUI/src/com/android/systemui/Dependency.java b/packages/SystemUI/src/com/android/systemui/Dependency.java
index 2937a25..d8a47c5 100644
--- a/packages/SystemUI/src/com/android/systemui/Dependency.java
+++ b/packages/SystemUI/src/com/android/systemui/Dependency.java
@@ -22,6 +22,8 @@
 import android.os.Looper;
 import android.os.Process;
 import android.util.ArrayMap;
+import android.view.IWindowManager;
+import android.view.WindowManagerGlobal;
 
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.app.NightDisplayController;
@@ -304,6 +306,8 @@
 
         mProviders.put(LightBarController.class, () -> new LightBarController(mContext));
 
+        mProviders.put(IWindowManager.class, () -> WindowManagerGlobal.getWindowManagerService());
+
         // Put all dependencies above here so the factory can override them if it wants.
         SystemUIFactory.getInstance().injectDependencies(mProviders, mContext);
     }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarTransitions.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarTransitions.java
index f3ca66f..c950036 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarTransitions.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarTransitions.java
@@ -17,12 +17,19 @@
 package com.android.systemui.statusbar.phone;
 
 import android.content.Context;
+import android.os.Handler;
+import android.os.RemoteException;
 import android.os.ServiceManager;
 import android.util.SparseArray;
+import android.view.Display;
+import android.view.IWallpaperVisibilityListener;
+import android.view.IWindowManager;
 import android.view.MotionEvent;
 import android.view.View;
+import android.view.WindowManagerGlobal;
 
 import com.android.internal.statusbar.IStatusBarService;
+import com.android.systemui.Dependency;
 import com.android.systemui.R;
 
 public final class NavigationBarTransitions extends BarTransitions {
@@ -30,6 +37,7 @@
     private final NavigationBarView mView;
     private final IStatusBarService mBarService;
     private final LightBarTransitionsController mLightTransitionsController;
+    private boolean mWallpaperVisible;
 
     private boolean mLightsOut;
     private boolean mAutoDim;
@@ -41,6 +49,21 @@
                 ServiceManager.getService(Context.STATUS_BAR_SERVICE));
         mLightTransitionsController = new LightBarTransitionsController(view.getContext(),
                 this::applyDarkIntensity);
+
+        IWindowManager windowManagerService = Dependency.get(IWindowManager.class);
+        Handler handler = Handler.getMain();
+        try {
+            mWallpaperVisible = windowManagerService.registerWallpaperVisibilityListener(
+                new IWallpaperVisibilityListener.Stub() {
+                    @Override
+                    public void onWallpaperVisibilityChanged(boolean newVisibility,
+                            int displayId) throws RemoteException {
+                        mWallpaperVisible = newVisibility;
+                        handler.post(() -> applyLightsOut(true, false));
+                    }
+                }, Display.DEFAULT_DISPLAY);
+        } catch (RemoteException e) {
+        }
     }
 
     public void init() {
@@ -57,7 +80,7 @@
 
     @Override
     protected boolean isLightsOut(int mode) {
-        return super.isLightsOut(mode) || mAutoDim;
+        return super.isLightsOut(mode) || (mAutoDim && !mWallpaperVisible);
     }
 
     public LightBarTransitionsController getLightTransitionsController() {
@@ -85,7 +108,7 @@
         // ok, everyone, stop it right there
         navButtons.animate().cancel();
 
-        final float navButtonsAlpha = lightsOut ? 0.5f : 1f;
+        final float navButtonsAlpha = lightsOut ? 0.6f : 1f;
 
         if (!animate) {
             navButtons.setAlpha(navButtonsAlpha);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarTransitionsTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarTransitionsTest.java
index 0c1baaa..76f57f0 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarTransitionsTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NavigationBarTransitionsTest.java
@@ -24,6 +24,7 @@
 import android.support.test.filters.SmallTest;
 import android.testing.AndroidTestingRunner;
 import android.testing.TestableLooper.RunWithLooper;
+import android.view.IWindowManager;
 
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.statusbar.CommandQueue;
@@ -41,6 +42,7 @@
 
     @Before
     public void setup() {
+        mDependency.injectMockDependency(IWindowManager.class);
         mContext.putComponent(CommandQueue.class, mock(CommandQueue.class));
         NavigationBarView navBar = spy(new NavigationBarView(mContext, null));
         when(navBar.getCurrentView()).thenReturn(navBar);
diff --git a/services/core/java/com/android/server/am/BatteryStatsService.java b/services/core/java/com/android/server/am/BatteryStatsService.java
index 7c9cd00..68ed9ae 100644
--- a/services/core/java/com/android/server/am/BatteryStatsService.java
+++ b/services/core/java/com/android/server/am/BatteryStatsService.java
@@ -297,26 +297,12 @@
     void noteProcessStart(String name, int uid) {
         synchronized (mStats) {
             mStats.noteProcessStartLocked(name, uid);
-
-            // TODO: remove this once we figure out properly where and how
-            // PROCESS_EVENT = 1112
-            // KEY_STATE = 1
-            // KEY_PACKAGE_NAME: 1002
-            // KEY_UID: 2
-            StatsLog.writeArray(1112, 1, 1, 1002, name, 2, uid);
         }
     }
 
     void noteProcessCrash(String name, int uid) {
         synchronized (mStats) {
             mStats.noteProcessCrashLocked(name, uid);
-
-            // TODO: remove this once we figure out properly where and how
-            // PROCESS_EVENT = 1112
-            // KEY_STATE = 1
-            // KEY_PACKAGE_NAME: 1002
-            // KEY_UID: 2
-            StatsLog.writeArray(1112, 1, 2, 1002, name, 2, uid);
         }
     }
 
@@ -334,6 +320,9 @@
 
     void noteUidProcessState(int uid, int state) {
         synchronized (mStats) {
+            // TODO: remove this once we figure out properly where and how
+            StatsLog.write(StatsLog.PROCESS_STATE_CHANGED, uid, state);
+
             mStats.noteUidProcessStateLocked(uid, state);
         }
     }
@@ -548,12 +537,10 @@
         enforceCallingPermission();
         if (DBG) Slog.d(TAG, "begin noteScreenState");
         synchronized (mStats) {
-            mStats.noteScreenStateLocked(state);
             // TODO: remove this once we figure out properly where and how
-            // SCREEN_EVENT = 2
-            // KEY_STATE: 1
-            // State value: state. We can change this to our own def later.
-            StatsLog.writeArray(2, 1, state);
+            StatsLog.write(StatsLog.SCREEN_STATE_CHANGED, state);
+
+            mStats.noteScreenStateLocked(state);
         }
         if (DBG) Slog.d(TAG, "end noteScreenState");
     }
diff --git a/services/core/java/com/android/server/notification/NotificationManagerService.java b/services/core/java/com/android/server/notification/NotificationManagerService.java
index 168f070..238d87b 100644
--- a/services/core/java/com/android/server/notification/NotificationManagerService.java
+++ b/services/core/java/com/android/server/notification/NotificationManagerService.java
@@ -133,7 +133,6 @@
 import android.service.notification.NotificationRankingUpdate;
 import android.service.notification.NotificationRecordProto;
 import android.service.notification.NotificationServiceDumpProto;
-import android.service.notification.NotificationServiceProto;
 import android.service.notification.NotificationStats;
 import android.service.notification.SnoozeCriterion;
 import android.service.notification.StatusBarNotification;
@@ -3263,7 +3262,7 @@
                     final NotificationRecord nr = mNotificationList.get(i);
                     if (filter.filtered && !filter.matches(nr.sbn)) continue;
                     nr.dump(proto, filter.redact);
-                    proto.write(NotificationRecordProto.STATE, NotificationServiceProto.POSTED);
+                    proto.write(NotificationRecordProto.STATE, NotificationRecordProto.POSTED);
                 }
             }
             N = mEnqueuedNotifications.size();
@@ -3272,7 +3271,7 @@
                     final NotificationRecord nr = mEnqueuedNotifications.get(i);
                     if (filter.filtered && !filter.matches(nr.sbn)) continue;
                     nr.dump(proto, filter.redact);
-                    proto.write(NotificationRecordProto.STATE, NotificationServiceProto.ENQUEUED);
+                    proto.write(NotificationRecordProto.STATE, NotificationRecordProto.ENQUEUED);
                 }
             }
             List<NotificationRecord> snoozed = mSnoozeHelper.getSnoozed();
@@ -3282,7 +3281,7 @@
                     final NotificationRecord nr = snoozed.get(i);
                     if (filter.filtered && !filter.matches(nr.sbn)) continue;
                     nr.dump(proto, filter.redact);
-                    proto.write(NotificationRecordProto.STATE, NotificationServiceProto.SNOOZED);
+                    proto.write(NotificationRecordProto.STATE, NotificationRecordProto.SNOOZED);
                 }
             }
             proto.end(records);
diff --git a/telephony/java/android/telephony/ServiceState.java b/telephony/java/android/telephony/ServiceState.java
index e448fb2..116e711 100644
--- a/telephony/java/android/telephony/ServiceState.java
+++ b/telephony/java/android/telephony/ServiceState.java
@@ -1197,15 +1197,6 @@
         }
     }
 
-    /**
-     * @Deprecated to be removed Q3 2013 use {@link #getVoiceNetworkType}
-     * @hide
-     */
-    public int getNetworkType() {
-        Rlog.e(LOG_TAG, "ServiceState.getNetworkType() DEPRECATED will be removed *******");
-        return rilRadioTechnologyToNetworkType(mRilVoiceRadioTechnology);
-    }
-
     /** @hide */
     public int getDataNetworkType() {
         return rilRadioTechnologyToNetworkType(mRilDataRadioTechnology);
diff --git a/tools/aapt/ResourceTable.cpp b/tools/aapt/ResourceTable.cpp
index 52b93a9..669afe1 100644
--- a/tools/aapt/ResourceTable.cpp
+++ b/tools/aapt/ResourceTable.cpp
@@ -4847,6 +4847,7 @@
     const String16 animatedVector16("animated-vector");
     const String16 pathInterpolator16("pathInterpolator");
     const String16 objectAnimator16("objectAnimator");
+    const String16 gradient16("gradient");
 
     const int minSdk = getMinSdkVersion(bundle);
     if (minSdk >= SDK_LOLLIPOP_MR1) {
@@ -4874,7 +4875,8 @@
         if (bundle->getNoVersionVectors() && (node->getElementName() == vector16 ||
                     node->getElementName() == animatedVector16 ||
                     node->getElementName() == objectAnimator16 ||
-                    node->getElementName() == pathInterpolator16)) {
+                    node->getElementName() == pathInterpolator16 ||
+                    node->getElementName() == gradient16)) {
             // We were told not to version vector tags, so skip the children here.
             continue;
         }
diff --git a/tools/aapt2/cmd/Link.cpp b/tools/aapt2/cmd/Link.cpp
index 8cc2a61..40d71a3 100644
--- a/tools/aapt2/cmd/Link.cpp
+++ b/tools/aapt2/cmd/Link.cpp
@@ -447,7 +447,7 @@
 
 static bool IsVectorElement(const std::string& name) {
   return name == "vector" || name == "animated-vector" || name == "pathInterpolator" ||
-         name == "objectAnimator";
+         name == "objectAnimator" || name == "gradient";
 }
 
 template <typename T>
diff --git a/tools/bit/Android.bp b/tools/bit/Android.bp
index 258e9b5..a806271 100644
--- a/tools/bit/Android.bp
+++ b/tools/bit/Android.bp
@@ -30,6 +30,11 @@
         "util.cpp",
     ],
 
+    cflags: [
+        "-Wall",
+        "-Werror",
+    ],
+
     static_libs: [
         "libexpat",
         "libinstrumentation",
diff --git a/tools/bit/adb.cpp b/tools/bit/adb.cpp
index c8faf5c..fa7d3d4 100644
--- a/tools/bit/adb.cpp
+++ b/tools/bit/adb.cpp
@@ -302,7 +302,9 @@
     print_command(cmd);
 
     int fds[2];
-    pipe(fds);
+    if (0 != pipe(fds)) {
+        return errno;
+    }
 
     pid_t pid = fork();
 
diff --git a/tools/bit/command.cpp b/tools/bit/command.cpp
index 9a8449b..1ff7c22 100644
--- a/tools/bit/command.cpp
+++ b/tools/bit/command.cpp
@@ -105,7 +105,9 @@
     }
 
     int fds[2];
-    pipe(fds);
+    if (0 != pipe(fds)) {
+        return string();
+    }
 
     pid_t pid = fork();
 
diff --git a/tools/bit/main.cpp b/tools/bit/main.cpp
index 91ca514..a8a4cfc 100644
--- a/tools/bit/main.cpp
+++ b/tools/bit/main.cpp
@@ -596,6 +596,15 @@
     }
 }
 
+static void
+chdir_or_exit(const char *path) {
+    // TODO: print_command("cd", path);
+    if (0 != chdir(path)) {
+        print_error("Error: Could not chdir: %s", path);
+        exit(1);
+    }
+}
+
 /**
  * Run the build, install, and test actions.
  */
@@ -618,8 +627,7 @@
     const string buildId = get_build_var(buildTop, "BUILD_ID", false);
     const string buildOut = get_out_dir();
 
-    // TODO: print_command("cd", buildTop.c_str());
-    chdir(buildTop.c_str());
+    chdir_or_exit(buildTop.c_str());
 
     // Get the modules for the targets
     map<string,Module> modules;
@@ -999,7 +1007,7 @@
     const string buildProduct = get_required_env("TARGET_PRODUCT", false);
     const string buildOut = get_out_dir();
 
-    chdir(buildTop.c_str());
+    chdir_or_exit(buildTop.c_str());
 
     string buildDevice = sniff_device_name(buildOut, buildProduct);
 
diff --git a/tools/bit/make.cpp b/tools/bit/make.cpp
index a800241..b2ee99c 100644
--- a/tools/bit/make.cpp
+++ b/tools/bit/make.cpp
@@ -182,7 +182,7 @@
         for (ssize_t i = module.classes.size() - 1; i >= 0; i--) {
             string cl = module.classes[i];
             if (!(cl == "JAVA_LIBRARIES" || cl == "EXECUTABLES" || cl == "SHARED_LIBRARIES"
-                    || cl == "APPS")) {
+                    || cl == "APPS" || cl == "NATIVE_TESTS")) {
                 module.classes.erase(module.classes.begin() + i);
             }
         }
diff --git a/tools/bit/util.cpp b/tools/bit/util.cpp
index fc93bcb..9223931 100644
--- a/tools/bit/util.cpp
+++ b/tools/bit/util.cpp
@@ -101,7 +101,6 @@
 void
 get_directory_contents(const string& name, map<string,FileInfo>* results)
 {
-    int err;
     DIR* dir = opendir(name.c_str());
     if (dir == NULL) {
         return;
@@ -241,7 +240,9 @@
     fseek(file, 0, SEEK_SET);
 
     char* buf = (char*)malloc(size);
-    fread(buf, 1, size, file);
+    if ((size_t) size != fread(buf, 1, size, file)) {
+        return string();
+    }
 
     string result(buf, size);
 
diff --git a/tools/incident_report/Android.bp b/tools/incident_report/Android.bp
index ab55dbd..f2d0d0f 100644
--- a/tools/incident_report/Android.bp
+++ b/tools/incident_report/Android.bp
@@ -31,5 +31,5 @@
         "libprotobuf-cpp-full",
     ],
 
-    cflags: ["-Wno-unused-parameter"],
+    cflags: ["-Wall", "-Werror"],
 }
diff --git a/tools/incident_report/printer.cpp b/tools/incident_report/printer.cpp
index bd660dd2..bff1025 100644
--- a/tools/incident_report/printer.cpp
+++ b/tools/incident_report/printer.cpp
@@ -70,7 +70,6 @@
 
     len = vsnprintf(mBuf, mBufSize, format, args);
     va_end(args);
-    bool truncated = (len >= mBufSize) && (reallocate(len) < len);
 
     va_start(args, format);
     len = vsnprintf(mBuf, mBufSize, format, args);
diff --git a/tools/incident_section_gen/Android.bp b/tools/incident_section_gen/Android.bp
index 1756e06..f07445a 100644
--- a/tools/incident_section_gen/Android.bp
+++ b/tools/incident_section_gen/Android.bp
@@ -22,6 +22,8 @@
     cflags: [
         "-g",
         "-O0",
+        "-Wall",
+        "-Werror",
     ],
     srcs: ["main.cpp"],
     shared_libs: [
diff --git a/tools/stats_log_api_gen/Android.bp b/tools/stats_log_api_gen/Android.bp
new file mode 100644
index 0000000..a910c62
--- /dev/null
+++ b/tools/stats_log_api_gen/Android.bp
@@ -0,0 +1,98 @@
+//
+// Copyright (C) 2017 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+// ==========================================================
+// Build the host executable: stats-log-api-gen
+// ==========================================================
+cc_binary_host {
+    name: "stats-log-api-gen",
+    srcs: [
+        "Collation.cpp",
+        "main.cpp",
+    ],
+
+    shared_libs: [
+        "libstats_proto_host",
+        "libprotobuf-cpp-full",
+    ],
+
+    proto: {
+        type: "full",
+    },
+}
+
+// ==========================================================
+// Build the host test executable: stats-log-api-gen
+// ==========================================================
+cc_test_host {
+    name: "stats-log-api-gen-test",
+    cflags: [
+        "-Wall",
+        "-Wextra",
+        "-Werror",
+        "-g",
+        "-DUNIT_TEST",
+    ],
+    srcs: [
+        "Collation.cpp",
+        "test_collation.cpp",
+        "test.proto",
+    ],
+
+    static_libs: [
+        "libgmock_host",
+    ],
+
+    shared_libs: [
+        "libstats_proto_host",
+    ],
+
+    proto: {
+        type: "full",
+    },
+}
+
+// ==========================================================
+// Native library
+// ==========================================================
+genrule {
+    name: "statslog.h",
+    tools: ["stats-log-api-gen"],
+    cmd: "$(location stats-log-api-gen) --header $(genDir)/statslog.h",
+    out: [
+        "statslog.h",
+    ],
+}
+
+genrule {
+    name: "statslog.cpp",
+    tools: ["stats-log-api-gen"],
+    cmd: "$(location stats-log-api-gen) --cpp $(genDir)/statslog.cpp",
+    out: [
+        "statslog.cpp",
+    ],
+}
+
+cc_library_shared {
+    name: "libstatslog",
+    generated_sources: ["statslog.cpp"],
+    generated_headers: ["statslog.h"],
+    export_generated_headers: ["statslog.h"],
+    shared_libs: [
+        "liblog",
+    ],
+}
+
diff --git a/tools/stats_log_api_gen/Collation.cpp b/tools/stats_log_api_gen/Collation.cpp
new file mode 100644
index 0000000..5d29268
--- /dev/null
+++ b/tools/stats_log_api_gen/Collation.cpp
@@ -0,0 +1,265 @@
+/*
+ * Copyright (C) 2017, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "Collation.h"
+
+#include <stdio.h>
+#include <map>
+
+namespace android {
+namespace stats_log_api_gen {
+
+using google::protobuf::FieldDescriptor;
+using google::protobuf::FileDescriptor;
+using google::protobuf::SourceLocation;
+using std::map;
+
+
+//
+// AtomDecl class
+//
+
+AtomDecl::AtomDecl()
+    :code(0),
+     name()
+{
+}
+
+AtomDecl::AtomDecl(const AtomDecl& that)
+    :code(that.code),
+     name(that.name),
+     message(that.message),
+     fields(that.fields)
+{
+}
+
+AtomDecl::AtomDecl(int c, const string& n, const string& m)
+    :code(c),
+     name(n),
+     message(m)
+{
+}
+
+AtomDecl::~AtomDecl()
+{
+}
+
+
+/**
+ * Print an error message for a FieldDescriptor, including the file name and line number.
+ */
+static void
+print_error(const FieldDescriptor* field, const char* format, ...)
+{
+    const Descriptor* message = field->containing_type();
+    const FileDescriptor* file = message->file();
+
+    SourceLocation loc;
+    if (field->GetSourceLocation(&loc)) {
+        // TODO: this will work if we can figure out how to pass --include_source_info to protoc
+        fprintf(stderr, "%s:%d: ", file->name().c_str(), loc.start_line);
+    } else {
+        fprintf(stderr, "%s: ", file->name().c_str());
+    }
+    va_list args;
+    va_start(args, format);
+    vfprintf(stderr, format, args);
+    va_end (args);
+}
+
+/**
+ * Convert a protobuf type into a java type.
+ */
+static java_type_t
+java_type(const FieldDescriptor* field)
+{
+    int protoType = field->type();
+    switch (protoType) {
+        case FieldDescriptor::TYPE_DOUBLE:
+            return JAVA_TYPE_DOUBLE;
+        case FieldDescriptor::TYPE_FLOAT:
+            return JAVA_TYPE_FLOAT;
+        case FieldDescriptor::TYPE_INT64:
+            return JAVA_TYPE_LONG;
+        case FieldDescriptor::TYPE_UINT64:
+            return JAVA_TYPE_LONG;
+        case FieldDescriptor::TYPE_INT32:
+            return JAVA_TYPE_INT;
+        case FieldDescriptor::TYPE_FIXED64:
+            return JAVA_TYPE_LONG;
+        case FieldDescriptor::TYPE_FIXED32:
+            return JAVA_TYPE_INT;
+        case FieldDescriptor::TYPE_BOOL:
+            return JAVA_TYPE_BOOLEAN;
+        case FieldDescriptor::TYPE_STRING:
+            return JAVA_TYPE_STRING;
+        case FieldDescriptor::TYPE_GROUP:
+            return JAVA_TYPE_UNKNOWN;
+        case FieldDescriptor::TYPE_MESSAGE:
+            // TODO: not the final package name
+            if (field->message_type()->full_name() == "android.os.statsd.WorkSource") {
+                return JAVA_TYPE_WORK_SOURCE;
+            } else {
+                return JAVA_TYPE_OBJECT;
+            }
+        case FieldDescriptor::TYPE_BYTES:
+            return JAVA_TYPE_BYTE_ARRAY;
+        case FieldDescriptor::TYPE_UINT32:
+            return JAVA_TYPE_INT;
+        case FieldDescriptor::TYPE_ENUM:
+            return JAVA_TYPE_INT;
+        case FieldDescriptor::TYPE_SFIXED32:
+            return JAVA_TYPE_INT;
+        case FieldDescriptor::TYPE_SFIXED64:
+            return JAVA_TYPE_LONG;
+        case FieldDescriptor::TYPE_SINT32:
+            return JAVA_TYPE_INT;
+        case FieldDescriptor::TYPE_SINT64:
+            return JAVA_TYPE_LONG;
+        default:
+            return JAVA_TYPE_UNKNOWN;
+    }
+}
+
+/**
+ * Gather the info about the atoms.
+ */
+int
+collate_atoms(const Descriptor* descriptor, Atoms* atoms)
+{
+    int errorCount = 0;
+    const bool dbg = false;
+
+    for (int i=0; i<descriptor->field_count(); i++) {
+        const FieldDescriptor* atomField = descriptor->field(i);
+
+        if (dbg) {
+            printf("   %s (%d)\n", atomField->name().c_str(), atomField->number());
+        }
+
+        // StatsEvent only has one oneof, which contains only messages. Don't allow other types.
+        if (atomField->type() != FieldDescriptor::TYPE_MESSAGE) {
+            print_error(atomField,
+                    "Bad type for atom. StatsEvent can only have message type fields: %s\n",
+                    atomField->name().c_str());
+            errorCount++;
+            continue;
+        }
+
+        const Descriptor* atom = atomField->message_type();
+
+        // Build a sorted list of the fields. Descriptor has them in source file order.
+        map<int,const FieldDescriptor*> fields;
+        for (int j=0; j<atom->field_count(); j++) {
+            const FieldDescriptor* field = atom->field(j);
+            fields[field->number()] = field;
+        }
+
+        // Check that the parameters start at 1 and go up sequentially.
+        int expectedNumber = 1;
+        for (map<int,const FieldDescriptor*>::const_iterator it = fields.begin();
+                it != fields.end(); it++) {
+            const int number = it->first;
+            const FieldDescriptor* field = it->second;
+            if (number != expectedNumber) {
+                print_error(field, "Fields must be numbered consecutively starting at 1:"
+                        " '%s' is %d but should be %d\n",
+                        field->name().c_str(), number, expectedNumber);
+                errorCount++;
+                expectedNumber = number;
+                continue;
+            }
+            expectedNumber++;
+        }
+
+        // Check that only allowed types are present. Remove any invalid ones.
+        for (map<int,const FieldDescriptor*>::const_iterator it = fields.begin();
+                it != fields.end(); it++) {
+            const FieldDescriptor* field = it->second;
+
+            java_type_t javaType = java_type(field);
+
+            if (javaType == JAVA_TYPE_UNKNOWN) {
+                print_error(field, "Unkown type for field: %s\n", field->name().c_str());
+                errorCount++;
+                continue;
+            } else if (javaType == JAVA_TYPE_OBJECT) {
+                // Allow WorkSources, but only at position 1.
+                print_error(field, "Message type not allowed for field: %s\n",
+                        field->name().c_str());
+                errorCount++;
+                continue;
+            } else if (javaType == JAVA_TYPE_BYTE_ARRAY) {
+                print_error(field, "Raw bytes type not allowed for field: %s\n",
+                        field->name().c_str());
+                errorCount++;
+                continue;
+            }
+
+        }
+
+        // Check that if there's a WorkSource, it's at position 1.
+        for (map<int,const FieldDescriptor*>::const_iterator it = fields.begin();
+                it != fields.end(); it++) {
+            int number = it->first;
+            if (number != 1) {
+                const FieldDescriptor* field = it->second;
+                java_type_t javaType = java_type(field);
+                if (javaType == JAVA_TYPE_WORK_SOURCE) {
+                    print_error(field, "WorkSource fields must have field id 1, in message: '%s'\n",
+                           atom->name().c_str());
+                    errorCount++;
+                }
+            }
+        }
+
+        AtomDecl atomDecl(atomField->number(), atomField->name(), atom->name());
+
+        // Build the type signature
+        vector<java_type_t> signature;
+        for (map<int,const FieldDescriptor*>::const_iterator it = fields.begin();
+                it != fields.end(); it++) {
+            const FieldDescriptor* field = it->second;
+            java_type_t javaType = java_type(field);
+
+            atomDecl.fields.push_back(AtomField(field->name(), javaType));
+            signature.push_back(javaType);
+        }
+
+        atoms->signatures.insert(signature);
+        atoms->decls.insert(atomDecl);
+    }
+
+    if (dbg) {
+        printf("signatures = [\n");
+        for (set<vector<java_type_t>>::const_iterator it = atoms->signatures.begin();
+                it != atoms->signatures.end(); it++) {
+            printf("   ");
+            for (vector<java_type_t>::const_iterator jt = it->begin(); jt != it->end(); jt++) {
+                printf(" %d", (int)*jt);
+            }
+            printf("\n");
+        }
+        printf("]\n");
+    }
+
+    return errorCount;
+}
+
+}  // namespace stats_log_api_gen
+}  // namespace android
+
+
diff --git a/tools/stats_log_api_gen/Collation.h b/tools/stats_log_api_gen/Collation.h
new file mode 100644
index 0000000..50af7ea
--- /dev/null
+++ b/tools/stats_log_api_gen/Collation.h
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2017, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_STATS_LOG_API_GEN_COLLATION_H
+#define ANDROID_STATS_LOG_API_GEN_COLLATION_H
+
+
+#include <google/protobuf/descriptor.h>
+
+#include <set>
+#include <vector>
+
+namespace android {
+namespace stats_log_api_gen {
+
+using std::set;
+using std::string;
+using std::vector;
+using google::protobuf::Descriptor;
+
+/**
+ * The types for atom parameters.
+ */
+typedef enum {
+    JAVA_TYPE_UNKNOWN = 0,
+
+    JAVA_TYPE_WORK_SOURCE = 1,
+    JAVA_TYPE_BOOLEAN = 2,
+    JAVA_TYPE_INT = 3,
+    JAVA_TYPE_LONG = 4,
+    JAVA_TYPE_FLOAT = 5,
+    JAVA_TYPE_DOUBLE = 6,
+    JAVA_TYPE_STRING = 7,
+
+    JAVA_TYPE_OBJECT = -1,
+    JAVA_TYPE_BYTE_ARRAY = -2,
+} java_type_t;
+
+
+/**
+ * The name and type for an atom field.
+ */
+struct AtomField {
+    string name;
+    java_type_t javaType;
+
+    inline AtomField() :name(), javaType(JAVA_TYPE_UNKNOWN) {}
+    inline AtomField(const AtomField& that) :name(that.name), javaType(that.javaType) {}
+    inline AtomField(string n, java_type_t jt) :name(n), javaType(jt) {}
+    inline ~AtomField() {}
+};
+
+/**
+ * The name and code for an atom.
+ */
+struct AtomDecl {
+    int code;
+    string name;
+
+    string message;
+    vector<AtomField> fields;
+
+    AtomDecl();
+    AtomDecl(const AtomDecl& that);
+    AtomDecl(int code, const string& name, const string& message);
+    ~AtomDecl();
+
+    inline bool operator<(const AtomDecl& that) const {
+        return (code == that.code) ? (name < that.name) : (code < that.code);
+    }
+};
+
+struct Atoms {
+    set<vector<java_type_t>> signatures;
+    set<AtomDecl> decls;
+};
+
+/**
+ * Gather the information about the atoms.  Returns the number of errors.
+ */
+int collate_atoms(const Descriptor* descriptor, Atoms* atoms);
+
+}  // namespace stats_log_api_gen
+}  // namespace android
+
+
+#endif // ANDROID_STATS_LOG_API_GEN_COLLATION_H
diff --git a/tools/stats_log_api_gen/main.cpp b/tools/stats_log_api_gen/main.cpp
new file mode 100644
index 0000000..aaea4f6
--- /dev/null
+++ b/tools/stats_log_api_gen/main.cpp
@@ -0,0 +1,623 @@
+
+
+#include "Collation.h"
+
+#include "frameworks/base/cmds/statsd/src/stats_events.pb.h"
+
+#include <set>
+#include <vector>
+
+#include <getopt.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+using namespace google::protobuf;
+using namespace std;
+
+namespace android {
+namespace stats_log_api_gen {
+
+using android::os::statsd::StatsEvent;
+
+// TODO: Support WorkSources
+
+/**
+ * Turn lower and camel case into upper case with underscores.
+ */
+static string
+make_constant_name(const string& str)
+{
+    string result;
+    const int N = str.size();
+    bool underscore_next = false;
+    for (int i=0; i<N; i++) {
+        char c = str[i];
+        if (c >= 'A' && c <= 'Z') {
+            if (underscore_next) {
+                result += '_';
+                underscore_next = false;
+            }
+        } else if (c >= 'a' && c <= 'z') {
+            c = 'A' + c - 'a';
+            underscore_next = true;
+        } else if (c == '_') {
+            underscore_next = false;
+        }
+        result += c;
+    }
+    return result;
+}
+
+static const char*
+cpp_type_name(java_type_t type)
+{
+    switch (type) {
+        case JAVA_TYPE_BOOLEAN:
+            return "bool";
+        case JAVA_TYPE_INT:
+            return "int32_t";
+        case JAVA_TYPE_LONG:
+            return "int64_t";
+        case JAVA_TYPE_FLOAT:
+            return "float";
+        case JAVA_TYPE_DOUBLE:
+            return "double";
+        case JAVA_TYPE_STRING:
+            return "char const*";
+        default:
+            return "UNKNOWN";
+    }
+}
+
+static const char*
+java_type_name(java_type_t type)
+{
+    switch (type) {
+        case JAVA_TYPE_BOOLEAN:
+            return "boolean";
+        case JAVA_TYPE_INT:
+            return "int";
+        case JAVA_TYPE_LONG:
+            return "long";
+        case JAVA_TYPE_FLOAT:
+            return "float";
+        case JAVA_TYPE_DOUBLE:
+            return "double";
+        case JAVA_TYPE_STRING:
+            return "java.lang.String";
+        default:
+            return "UNKNOWN";
+    }
+}
+
+static int
+write_stats_log_cpp(FILE* out, const Atoms& atoms)
+{
+    int errorCount;
+
+    // Print prelude
+    fprintf(out, "// This file is autogenerated\n");
+    fprintf(out, "\n");
+
+    fprintf(out, "#include <log/log_event_list.h>\n");
+    fprintf(out, "#include <log/log.h>\n");
+    fprintf(out, "#include <statslog.h>\n");
+    fprintf(out, "\n");
+
+    fprintf(out, "namespace android {\n");
+    fprintf(out, "namespace util {\n");
+
+    // Print write methods
+    fprintf(out, "\n");
+    for (set<vector<java_type_t>>::const_iterator signature = atoms.signatures.begin();
+            signature != atoms.signatures.end(); signature++) {
+        int argIndex;
+
+        fprintf(out, "void\n");
+        fprintf(out, "stats_write(int code");
+        argIndex = 1;
+        for (vector<java_type_t>::const_iterator arg = signature->begin();
+                arg != signature->end(); arg++) {
+            fprintf(out, ", %s arg%d", cpp_type_name(*arg), argIndex);
+            argIndex++;
+        }
+        fprintf(out, ")\n");
+
+        fprintf(out, "{\n");
+        argIndex = 1;
+        fprintf(out, "    android_log_event_list event(code);\n");
+        for (vector<java_type_t>::const_iterator arg = signature->begin();
+                arg != signature->end(); arg++) {
+            if (*arg == JAVA_TYPE_STRING) {
+                fprintf(out, "    if (arg%d == NULL) {\n", argIndex);
+                fprintf(out, "        arg%d = \"\";\n", argIndex);
+                fprintf(out, "    }\n");
+            }
+            fprintf(out, "    event << arg%d;\n", argIndex);
+            argIndex++;
+        }
+
+        fprintf(out, "    event.write(LOG_ID_STATS);\n");
+        fprintf(out, "}\n");
+        fprintf(out, "\n");
+    }
+
+    // Print footer
+    fprintf(out, "\n");
+    fprintf(out, "} // namespace util\n");
+    fprintf(out, "} // namespace android\n");
+
+    return 0;
+}
+
+
+static int
+write_stats_log_header(FILE* out, const Atoms& atoms)
+{
+    int errorCount;
+
+    // Print prelude
+    fprintf(out, "// This file is autogenerated\n");
+    fprintf(out, "\n");
+    fprintf(out, "#pragma once\n");
+    fprintf(out, "\n");
+    fprintf(out, "#include <stdint.h>\n");
+    fprintf(out, "\n");
+
+    fprintf(out, "namespace android {\n");
+    fprintf(out, "namespace util {\n");
+    fprintf(out, "\n");
+    fprintf(out, "/*\n");
+    fprintf(out, " * API For logging statistics events.\n");
+    fprintf(out, " */\n");
+    fprintf(out, "\n");
+    fprintf(out, "/**\n");
+    fprintf(out, " * Constants for event codes.\n");
+    fprintf(out, " */\n");
+    fprintf(out, "enum {\n");
+
+    size_t i = 0;
+    // Print constants
+    for (set<AtomDecl>::const_iterator atom = atoms.decls.begin();
+            atom != atoms.decls.end(); atom++) {
+        string constant = make_constant_name(atom->name);
+        fprintf(out, "\n");
+        fprintf(out, "    /**\n");
+        fprintf(out, "     * %s %s\n", atom->message.c_str(), atom->name.c_str());
+        fprintf(out, "     * Usage: stats_write(StatsLog.%s", constant.c_str());
+        for (vector<AtomField>::const_iterator field = atom->fields.begin();
+                field != atom->fields.end(); field++) {
+            fprintf(out, ", %s %s", cpp_type_name(field->javaType), field->name.c_str());
+        }
+        fprintf(out, ");\n");
+        fprintf(out, "     */\n");
+        char const* const comma = (i == atoms.decls.size() - 1) ? "" : ",";
+        fprintf(out, "    %s = %d%s\n", constant.c_str(), atom->code, comma);
+        i++;
+    }
+    fprintf(out, "\n");
+    fprintf(out, "};\n");
+    fprintf(out, "\n");
+
+    // Print write methods
+    fprintf(out, "//\n");
+    fprintf(out, "// Write methods\n");
+    fprintf(out, "//\n");
+    for (set<vector<java_type_t>>::const_iterator signature = atoms.signatures.begin();
+            signature != atoms.signatures.end(); signature++) {
+
+        fprintf(out, "void stats_write(int code");
+        int argIndex = 1;
+        for (vector<java_type_t>::const_iterator arg = signature->begin();
+                arg != signature->end(); arg++) {
+            fprintf(out, ", %s arg%d", cpp_type_name(*arg), argIndex);
+            argIndex++;
+        }
+        fprintf(out, ");\n");
+    }
+
+    fprintf(out, "\n");
+    fprintf(out, "} // namespace util\n");
+    fprintf(out, "} // namespace android\n");
+
+    return 0;
+}
+
+static int
+write_stats_log_java(FILE* out, const Atoms& atoms)
+{
+    int errorCount;
+
+    // Print prelude
+    fprintf(out, "// This file is autogenerated\n");
+    fprintf(out, "\n");
+    fprintf(out, "package android.util;\n");
+    fprintf(out, "\n");
+    fprintf(out, "\n");
+    fprintf(out, "/**\n");
+    fprintf(out, " * API For logging statistics events.\n");
+    fprintf(out, " * @hide\n");
+    fprintf(out, " */\n");
+    fprintf(out, "public final class StatsLog {\n");
+    fprintf(out, "    // Constants for event codes.\n");
+
+    // Print constants
+    for (set<AtomDecl>::const_iterator atom = atoms.decls.begin();
+            atom != atoms.decls.end(); atom++) {
+        string constant = make_constant_name(atom->name);
+        fprintf(out, "\n");
+        fprintf(out, "    /**\n");
+        fprintf(out, "     * %s %s\n", atom->message.c_str(), atom->name.c_str());
+        fprintf(out, "     * Usage: StatsLog.write(StatsLog.%s", constant.c_str());
+        for (vector<AtomField>::const_iterator field = atom->fields.begin();
+                field != atom->fields.end(); field++) {
+            fprintf(out, ", %s %s", java_type_name(field->javaType), field->name.c_str());
+        }
+        fprintf(out, ");\n");
+        fprintf(out, "     */\n");
+        fprintf(out, "    public static final int %s = %d;\n", constant.c_str(), atom->code);
+    }
+    fprintf(out, "\n");
+
+    // Print write methods
+    fprintf(out, "    // Write methods\n");
+    for (set<vector<java_type_t>>::const_iterator signature = atoms.signatures.begin();
+            signature != atoms.signatures.end(); signature++) {
+        fprintf(out, "    public static native void write(int code");
+        int argIndex = 1;
+        for (vector<java_type_t>::const_iterator arg = signature->begin();
+                arg != signature->end(); arg++) {
+            fprintf(out, ", %s arg%d", java_type_name(*arg), argIndex);
+            argIndex++;
+        }
+        fprintf(out, ");\n");
+    }
+
+    fprintf(out, "}\n");
+
+    return 0;
+}
+
+static const char*
+jni_type_name(java_type_t type)
+{
+    switch (type) {
+        case JAVA_TYPE_BOOLEAN:
+            return "jboolean";
+        case JAVA_TYPE_INT:
+            return "jint";
+        case JAVA_TYPE_LONG:
+            return "jlong";
+        case JAVA_TYPE_FLOAT:
+            return "jfloat";
+        case JAVA_TYPE_DOUBLE:
+            return "jdouble";
+        case JAVA_TYPE_STRING:
+            return "jstring";
+        default:
+            return "UNKNOWN";
+    }
+}
+
+static string
+jni_function_name(const vector<java_type_t>& signature)
+{
+    string result("StatsLog_write");
+    for (vector<java_type_t>::const_iterator arg = signature.begin();
+            arg != signature.end(); arg++) {
+        switch (*arg) {
+            case JAVA_TYPE_BOOLEAN:
+                result += "_boolean";
+                break;
+            case JAVA_TYPE_INT:
+                result += "_int";
+                break;
+            case JAVA_TYPE_LONG:
+                result += "_long";
+                break;
+            case JAVA_TYPE_FLOAT:
+                result += "_float";
+                break;
+            case JAVA_TYPE_DOUBLE:
+                result += "_double";
+                break;
+            case JAVA_TYPE_STRING:
+                result += "_String";
+                break;
+            default:
+                result += "_UNKNOWN";
+                break;
+        }
+    }
+    return result;
+}
+
+static const char*
+java_type_signature(java_type_t type)
+{
+    switch (type) {
+        case JAVA_TYPE_BOOLEAN:
+            return "Z";
+        case JAVA_TYPE_INT:
+            return "I";
+        case JAVA_TYPE_LONG:
+            return "J";
+        case JAVA_TYPE_FLOAT:
+            return "F";
+        case JAVA_TYPE_DOUBLE:
+            return "D";
+        case JAVA_TYPE_STRING:
+            return "Ljava/lang/String;";
+        default:
+            return "UNKNOWN";
+    }
+}
+
+static string
+jni_function_signature(const vector<java_type_t>& signature)
+{
+    string result("(I");
+    for (vector<java_type_t>::const_iterator arg = signature.begin();
+            arg != signature.end(); arg++) {
+        result += java_type_signature(*arg);
+    }
+    result += ")V";
+    return result;
+}
+
+static int
+write_stats_log_jni(FILE* out, const Atoms& atoms)
+{
+    int errorCount;
+
+    // Print prelude
+    fprintf(out, "// This file is autogenerated\n");
+    fprintf(out, "\n");
+
+    fprintf(out, "#include <statslog.h>\n");
+    fprintf(out, "\n");
+    fprintf(out, "#include <nativehelper/JNIHelp.h>\n");
+    fprintf(out, "#include \"core_jni_helpers.h\"\n");
+    fprintf(out, "#include \"jni.h\"\n");
+    fprintf(out, "\n");
+    fprintf(out, "#define UNUSED  __attribute__((__unused__))\n");
+    fprintf(out, "\n");
+
+    fprintf(out, "namespace android {\n");
+    fprintf(out, "\n");
+
+    // Print write methods
+    for (set<vector<java_type_t>>::const_iterator signature = atoms.signatures.begin();
+            signature != atoms.signatures.end(); signature++) {
+        int argIndex;
+
+        fprintf(out, "static void\n");
+        fprintf(out, "%s(JNIEnv* env, jobject clazz UNUSED, jint code",
+                jni_function_name(*signature).c_str());
+        argIndex = 1;
+        for (vector<java_type_t>::const_iterator arg = signature->begin();
+                arg != signature->end(); arg++) {
+            fprintf(out, ", %s arg%d", jni_type_name(*arg), argIndex);
+            argIndex++;
+        }
+        fprintf(out, ")\n");
+
+        fprintf(out, "{\n");
+
+        // Prepare strings
+        argIndex = 1;
+        bool hadString = false;
+        for (vector<java_type_t>::const_iterator arg = signature->begin();
+                arg != signature->end(); arg++) {
+            if (*arg == JAVA_TYPE_STRING) {
+                fprintf(out, "    const char* str%d;\n", argIndex);
+                fprintf(out, "    if (arg%d != NULL) {\n", argIndex);
+                fprintf(out, "        str%d = env->GetStringUTFChars(arg%d, NULL);\n",
+                        argIndex, argIndex);
+                fprintf(out, "    } else {\n");
+                fprintf(out, "        str%d = NULL;\n", argIndex);
+                fprintf(out, "    }\n");
+                hadString = true;
+            }
+            argIndex++;
+        }
+
+        // Emit this to quiet the unused parameter warning if there were no strings.
+        if (!hadString) {
+            fprintf(out, "    (void)env;\n");
+        }
+
+        // stats_write call
+        argIndex = 1;
+        fprintf(out, "    android::util::stats_write(code");
+        for (vector<java_type_t>::const_iterator arg = signature->begin();
+                arg != signature->end(); arg++) {
+            const char* argName = (*arg == JAVA_TYPE_STRING) ? "str" : "arg";
+            fprintf(out, ", (%s)%s%d", cpp_type_name(*arg), argName, argIndex);
+            argIndex++;
+        }
+        fprintf(out, ");\n");
+
+        // Clean up strings
+        argIndex = 1;
+        for (vector<java_type_t>::const_iterator arg = signature->begin();
+                arg != signature->end(); arg++) {
+            if (*arg == JAVA_TYPE_STRING) {
+                fprintf(out, "    if (str%d != NULL) {\n", argIndex);
+                fprintf(out, "        env->ReleaseStringUTFChars(arg%d, str%d);\n",
+                        argIndex, argIndex);
+                fprintf(out, "    }\n");
+            }
+            argIndex++;
+        }
+
+        fprintf(out, "}\n");
+        fprintf(out, "\n");
+    }
+
+    // Print registration function table
+    fprintf(out, "/*\n");
+    fprintf(out, " * JNI registration.\n");
+    fprintf(out, " */\n");
+    fprintf(out, "static const JNINativeMethod gRegisterMethods[] = {\n");
+    for (set<vector<java_type_t>>::const_iterator signature = atoms.signatures.begin();
+            signature != atoms.signatures.end(); signature++) {
+        fprintf(out, "    { \"write\", \"%s\", (void*)%s },\n",
+                jni_function_signature(*signature).c_str(),
+                jni_function_name(*signature).c_str());
+    }
+    fprintf(out, "};\n");
+    fprintf(out, "\n");
+
+    // Print registration function
+    fprintf(out, "int register_android_util_StatsLog(JNIEnv* env) {\n");
+    fprintf(out, "    return RegisterMethodsOrDie(\n");
+    fprintf(out, "            env,\n");
+    fprintf(out, "            \"android/util/StatsLog\",\n");
+    fprintf(out, "            gRegisterMethods, NELEM(gRegisterMethods));\n");
+    fprintf(out, "}\n");
+
+    fprintf(out, "\n");
+    fprintf(out, "} // namespace android\n");
+
+    return 0;
+}
+
+
+static void
+print_usage()
+{
+    fprintf(stderr, "usage: stats-log-api-gen OPTIONS\n");
+    fprintf(stderr, "\n");
+    fprintf(stderr, "OPTIONS\n");
+    fprintf(stderr, "  --cpp FILENAME       the header file to output\n");
+    fprintf(stderr, "  --header FILENAME    the cpp file to output\n");
+    fprintf(stderr, "  --help               this message\n");
+    fprintf(stderr, "  --java FILENAME      the java file to output\n");
+    fprintf(stderr, "  --jni FILENAME       the jni file to output\n");
+}
+
+/**
+ * Do the argument parsing and execute the tasks.
+ */
+static int
+run(int argc, char const*const* argv)
+{
+    string cppFilename;
+    string headerFilename;
+    string javaFilename;
+    string jniFilename;
+
+    int index = 1;
+    while (index < argc) {
+        if (0 == strcmp("--help", argv[index])) {
+            print_usage();
+            return 0;
+        } else if (0 == strcmp("--cpp", argv[index])) {
+            index++;
+            if (index >= argc) {
+                print_usage();
+                return 1;
+            }
+            cppFilename = argv[index];
+        } else if (0 == strcmp("--header", argv[index])) {
+            index++;
+            if (index >= argc) {
+                print_usage();
+                return 1;
+            }
+            headerFilename = argv[index];
+        } else if (0 == strcmp("--java", argv[index])) {
+            index++;
+            if (index >= argc) {
+                print_usage();
+                return 1;
+            }
+            javaFilename = argv[index];
+        } else if (0 == strcmp("--jni", argv[index])) {
+            index++;
+            if (index >= argc) {
+                print_usage();
+                return 1;
+            }
+            jniFilename = argv[index];
+        }
+        index++;
+    }
+
+    if (cppFilename.size() == 0
+            && headerFilename.size() == 0
+            && javaFilename.size() == 0
+            && jniFilename.size() == 0) {
+        print_usage();
+        return 1;
+    }
+
+    // Collate the parameters
+    Atoms atoms;
+    int errorCount = collate_atoms(StatsEvent::descriptor(), &atoms);
+    if (errorCount != 0) {
+        return 1;
+    }
+
+    // Write the .cpp file
+    if (cppFilename.size() != 0) {
+        FILE* out = fopen(cppFilename.c_str(), "w");
+        if (out == NULL) {
+            fprintf(stderr, "Unable to open file for write: %s\n", cppFilename.c_str());
+            return 1;
+        }
+        errorCount = android::stats_log_api_gen::write_stats_log_cpp(out, atoms);
+        fclose(out);
+    }
+
+    // Write the .h file
+    if (headerFilename.size() != 0) {
+        FILE* out = fopen(headerFilename.c_str(), "w");
+        if (out == NULL) {
+            fprintf(stderr, "Unable to open file for write: %s\n", headerFilename.c_str());
+            return 1;
+        }
+        errorCount = android::stats_log_api_gen::write_stats_log_header(out, atoms);
+        fclose(out);
+    }
+
+    // Write the .java file
+    if (javaFilename.size() != 0) {
+        FILE* out = fopen(javaFilename.c_str(), "w");
+        if (out == NULL) {
+            fprintf(stderr, "Unable to open file for write: %s\n", javaFilename.c_str());
+            return 1;
+        }
+        errorCount = android::stats_log_api_gen::write_stats_log_java(out, atoms);
+        fclose(out);
+    }
+
+    // Write the jni file
+    if (jniFilename.size() != 0) {
+        FILE* out = fopen(jniFilename.c_str(), "w");
+        if (out == NULL) {
+            fprintf(stderr, "Unable to open file for write: %s\n", jniFilename.c_str());
+            return 1;
+        }
+        errorCount = android::stats_log_api_gen::write_stats_log_jni(out, atoms);
+        fclose(out);
+    }
+
+    return 0;
+}
+
+}
+}
+
+/**
+ * Main.
+ */
+int
+main(int argc, char const*const* argv)
+{
+    GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+    return android::stats_log_api_gen::run(argc, argv);
+}
diff --git a/tools/stats_log_api_gen/test.proto b/tools/stats_log_api_gen/test.proto
new file mode 100644
index 0000000..2311a11
--- /dev/null
+++ b/tools/stats_log_api_gen/test.proto
@@ -0,0 +1,112 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+syntax = "proto2";
+
+import "frameworks/base/cmds/statsd/src/stats_events.proto";
+
+package android.stats_log_api_gen;
+
+message IntAtom {
+    optional int32 field1 = 1;
+}
+
+message AnotherIntAtom {
+    optional int32 field1 = 1;
+}
+
+message OutOfOrderAtom {
+    optional int32 field2 = 2;
+    optional int32 field1 = 1;
+}
+
+enum AnEnum {
+    VALUE0 = 0;
+    VALUE1 = 1;
+}
+
+message AllTypesAtom {
+    optional android.os.statsd.WorkSource attribution = 1;
+    optional double double_field = 2;
+    optional float float_field = 3;
+    optional int64 int64_field = 4;
+    optional uint64 uint64_field = 5;
+    optional int32 int32_field = 6;
+    optional fixed64 fixed64_field = 7;
+    optional fixed32 fixed32_field = 8;
+    optional bool bool_field = 9;
+    optional string string_field = 10;
+    optional uint32 uint32_field = 11;
+    optional AnEnum enum_field = 12;
+    optional sfixed32 sfixed32_field = 13;
+    optional sfixed64 sfixed64_field = 14;
+    optional sint32 sint32_field = 15;
+    optional sint64 sint64_field = 16;
+}
+
+message Event {
+    oneof event {
+        OutOfOrderAtom out_of_order_atom = 2;
+        IntAtom int_atom = 1;
+        AnotherIntAtom another_int_atom = 3;
+        AllTypesAtom all_types_atom = 4;
+    }
+}
+
+message BadTypesAtom {
+    optional IntAtom bad_int_atom = 1;
+    optional bytes bad_bytes = 2;
+}
+
+message BadTypesEvent {
+    oneof event {
+        BadTypesAtom bad_types_atom = 1;
+    }
+}
+
+message BadSkippedFieldSingleAtom {
+    optional int32 field2 = 2;
+}
+
+message BadSkippedFieldSingle {
+    oneof event {
+        BadSkippedFieldSingleAtom bad = 1;
+    }
+}
+
+message BadSkippedFieldMultipleAtom {
+    optional int32 field1 = 1;
+    optional int32 field3 = 3;
+    optional int32 field5 = 5;
+}
+
+message BadSkippedFieldMultiple {
+    oneof event {
+        BadSkippedFieldMultipleAtom bad = 1;
+    }
+}
+
+message BadWorkSourcePositionAtom {
+    optional int32 field1 = 1;
+    optional android.os.statsd.WorkSource attribution = 2;
+}
+
+message BadWorkSourcePosition {
+    oneof event {
+        BadWorkSourcePositionAtom bad = 1;
+    }
+}
+
diff --git a/tools/stats_log_api_gen/test_collation.cpp b/tools/stats_log_api_gen/test_collation.cpp
new file mode 100644
index 0000000..1bd2e3d
--- /dev/null
+++ b/tools/stats_log_api_gen/test_collation.cpp
@@ -0,0 +1,171 @@
+/*
+ * Copyright (C) 2017, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+
+#include "frameworks/base/tools/stats_log_api_gen/test.pb.h"
+#include "Collation.h"
+
+#include <stdio.h>
+
+namespace android {
+namespace stats_log_api_gen {
+
+using std::set;
+using std::vector;
+
+/**
+ * Return whether the set contains a vector of the elements provided.
+ */
+static bool
+set_contains_vector(const set<vector<java_type_t>>& s, int count, ...)
+{
+    va_list args;
+    vector<java_type_t> v;
+
+    va_start(args, count);
+    for (int i=0; i<count; i++) {
+        v.push_back((java_type_t)va_arg(args, int));
+    }
+    va_end(args);
+
+    return s.find(v) != s.end();
+}
+
+/**
+ * Expect that the provided set contains the elements provided.
+ */
+#define EXPECT_SET_CONTAINS_SIGNATURE(s, ...) \
+    do { \
+        int count = sizeof((int[]){__VA_ARGS__})/sizeof(int); \
+        EXPECT_TRUE(set_contains_vector(s, count, __VA_ARGS__)); \
+    } while(0)
+
+/**
+ * Test a correct collation, with all the types.
+ */
+TEST(CollationTest, CollateStats) {
+    Atoms atoms;
+    int errorCount = collate_atoms(Event::descriptor(), &atoms);
+
+    EXPECT_EQ(0, errorCount);
+    EXPECT_EQ(3ul, atoms.signatures.size());
+
+    // IntAtom, AnotherIntAtom
+    EXPECT_SET_CONTAINS_SIGNATURE(atoms.signatures, JAVA_TYPE_INT);
+
+    // OutOfOrderAtom
+    EXPECT_SET_CONTAINS_SIGNATURE(atoms.signatures, JAVA_TYPE_INT, JAVA_TYPE_INT);
+
+    // AllTypesAtom
+    EXPECT_SET_CONTAINS_SIGNATURE(atoms.signatures,
+                JAVA_TYPE_WORK_SOURCE, // WorkSource
+                JAVA_TYPE_DOUBLE, // double
+                JAVA_TYPE_FLOAT, // float
+                JAVA_TYPE_LONG, // int64
+                JAVA_TYPE_LONG, // uint64
+                JAVA_TYPE_INT, // int32
+                JAVA_TYPE_LONG, // fixed64
+                JAVA_TYPE_INT, // fixed32
+                JAVA_TYPE_BOOLEAN, // bool
+                JAVA_TYPE_STRING, // string
+                JAVA_TYPE_INT, // uint32
+                JAVA_TYPE_INT, // AnEnum
+                JAVA_TYPE_INT, // sfixed32
+                JAVA_TYPE_LONG, // sfixed64
+                JAVA_TYPE_INT, // sint32
+                JAVA_TYPE_LONG // sint64
+            );
+
+    set<AtomDecl>::const_iterator atom = atoms.decls.begin();
+    EXPECT_EQ(1, atom->code);
+    EXPECT_EQ("int_atom", atom->name);
+    EXPECT_EQ("IntAtom", atom->message);
+    atom++;
+
+    EXPECT_EQ(2, atom->code);
+    EXPECT_EQ("out_of_order_atom", atom->name);
+    EXPECT_EQ("OutOfOrderAtom", atom->message);
+    atom++;
+
+    EXPECT_EQ(3, atom->code);
+    EXPECT_EQ("another_int_atom", atom->name);
+    EXPECT_EQ("AnotherIntAtom", atom->message);
+    atom++;
+
+    EXPECT_EQ(4, atom->code);
+    EXPECT_EQ("all_types_atom", atom->name);
+    EXPECT_EQ("AllTypesAtom", atom->message);
+    atom++;
+
+    EXPECT_TRUE(atom == atoms.decls.end());
+}
+
+/**
+ * Test that event class that contains stuff other than the atoms is rejected.
+ */
+TEST(CollationTest, NonMessageTypeFails) {
+    Atoms atoms;
+    int errorCount = collate_atoms(IntAtom::descriptor(), &atoms);
+
+    EXPECT_EQ(1, errorCount);
+}
+
+/**
+ * Test that atoms that have non-primitve types are rejected.
+ */
+TEST(CollationTest, FailOnBadTypes) {
+    Atoms atoms;
+    int errorCount = collate_atoms(BadTypesEvent::descriptor(), &atoms);
+
+    EXPECT_EQ(2, errorCount);
+}
+
+/**
+ * Test that atoms that skip field numbers (in the first position) are rejected.
+ */
+TEST(CollationTest, FailOnSkippedFieldsSingle) {
+    Atoms atoms;
+    int errorCount = collate_atoms(BadSkippedFieldSingle::descriptor(), &atoms);
+
+    EXPECT_EQ(1, errorCount);
+}
+
+/**
+ * Test that atoms that skip field numbers (not in the first position, and multiple
+ * times) are rejected.
+ */
+TEST(CollationTest, FailOnSkippedFieldsMultiple) {
+    Atoms atoms;
+    int errorCount = collate_atoms(BadSkippedFieldMultiple::descriptor(), &atoms);
+
+    EXPECT_EQ(2, errorCount);
+}
+
+/**
+ * Test that atoms that have a WorkSource not in the first position are rejected.
+ */
+TEST(CollationTest, FailBadWorkSourcePosition) {
+    Atoms atoms;
+    int errorCount = collate_atoms(BadWorkSourcePosition::descriptor(), &atoms);
+
+    EXPECT_EQ(1, errorCount);
+}
+
+
+}  // namespace stats_log_api_gen
+}  // namespace android
+