Merge "Revert "Start auto-generating the stats log API.""
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/apct-tests/perftests/core/src/android/database/SQLiteDatabasePerfTest.java b/apct-tests/perftests/core/src/android/database/SQLiteDatabasePerfTest.java
new file mode 100644
index 0000000..7a32c0c
--- /dev/null
+++ b/apct-tests/perftests/core/src/android/database/SQLiteDatabasePerfTest.java
@@ -0,0 +1,223 @@
+/*
+ * 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
+ */
+
+package android.database;
+
+import android.content.ContentValues;
+import android.content.Context;
+import android.database.sqlite.SQLiteDatabase;
+import android.perftests.utils.BenchmarkState;
+import android.perftests.utils.PerfStatusReporter;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.filters.LargeTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.Random;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * Performance tests for typical CRUD operations and loading rows into the Cursor
+ *
+ * <p>To run: bit CorePerfTests:android.database.SQLiteDatabasePerfTest
+ */
+@RunWith(AndroidJUnit4.class)
+@LargeTest
+public class SQLiteDatabasePerfTest {
+    // TODO b/64262688 Add Concurrency tests to compare WAL vs DELETE read/write
+    private static final String DB_NAME = "dbperftest";
+    private static final int DEFAULT_DATASET_SIZE = 1000;
+
+    @Rule
+    public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
+    private SQLiteDatabase mDatabase;
+    private Context mContext;
+
+    @Before
+    public void setUp() {
+        mContext = InstrumentationRegistry.getTargetContext();
+        mContext.deleteDatabase(DB_NAME);
+        mDatabase = mContext.openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null);
+        mDatabase.execSQL("CREATE TABLE T1 "
+                + "(_ID INTEGER PRIMARY KEY, COL_A INTEGER, COL_B VARCHAR(100), COL_C REAL)");
+        mDatabase.execSQL("CREATE TABLE T2 ("
+                + "_ID INTEGER PRIMARY KEY, COL_A VARCHAR(100), T1_ID INTEGER,"
+                + "FOREIGN KEY(T1_ID) REFERENCES T1 (_ID))");
+    }
+
+    @After
+    public void tearDown() {
+        mDatabase.close();
+        mContext.deleteDatabase(DB_NAME);
+    }
+
+    @Test
+    public void testSelect() {
+        insertT1TestDataSet();
+
+        BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+
+        Random rnd = new Random(0);
+        while (state.keepRunning()) {
+            int index = rnd.nextInt(DEFAULT_DATASET_SIZE);
+            try (Cursor cursor = mDatabase.rawQuery("SELECT _ID, COL_A, COL_B, COL_C FROM T1 "
+                    + "WHERE _ID=?", new String[]{String.valueOf(index)})) {
+                assertTrue(cursor.moveToNext());
+                assertEquals(index, cursor.getInt(0));
+                assertEquals(index, cursor.getInt(1));
+                assertEquals("T1Value" + index, cursor.getString(2));
+                assertEquals(1.1 * index, cursor.getDouble(3), 0.0000001d);
+            }
+        }
+    }
+
+    @Test
+    public void testSelectMultipleRows() {
+        insertT1TestDataSet();
+
+        BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        Random rnd = new Random(0);
+        final int querySize = 50;
+        while (state.keepRunning()) {
+            int index = rnd.nextInt(DEFAULT_DATASET_SIZE - querySize - 1);
+            try (Cursor cursor = mDatabase.rawQuery("SELECT _ID, COL_A, COL_B, COL_C FROM T1 "
+                            + "WHERE _ID BETWEEN ? and ? ORDER BY _ID",
+                    new String[]{String.valueOf(index), String.valueOf(index + querySize - 1)})) {
+                int i = 0;
+                while(cursor.moveToNext()) {
+                    assertEquals(index, cursor.getInt(0));
+                    assertEquals(index, cursor.getInt(1));
+                    assertEquals("T1Value" + index, cursor.getString(2));
+                    assertEquals(1.1 * index, cursor.getDouble(3), 0.0000001d);
+                    index++;
+                    i++;
+                }
+                assertEquals(querySize, i);
+            }
+        }
+    }
+
+    @Test
+    public void testInnerJoin() {
+        mDatabase.setForeignKeyConstraintsEnabled(true);
+        mDatabase.beginTransaction();
+        insertT1TestDataSet();
+        insertT2TestDataSet();
+        mDatabase.setTransactionSuccessful();
+        mDatabase.endTransaction();
+
+        BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+
+        Random rnd = new Random(0);
+        while (state.keepRunning()) {
+            int index = rnd.nextInt(1000);
+            try (Cursor cursor = mDatabase.rawQuery(
+                    "SELECT T1._ID, T1.COL_A, T1.COL_B, T1.COL_C, T2.COL_A FROM T1 "
+                    + "INNER JOIN T2 on T2.T1_ID=T1._ID WHERE T1._ID = ?",
+                    new String[]{String.valueOf(index)})) {
+                assertTrue(cursor.moveToNext());
+                assertEquals(index, cursor.getInt(0));
+                assertEquals(index, cursor.getInt(1));
+                assertEquals("T1Value" + index, cursor.getString(2));
+                assertEquals(1.1 * index, cursor.getDouble(3), 0.0000001d);
+                assertEquals("T2Value" + index, cursor.getString(4));
+            }
+        }
+    }
+
+    @Test
+    public void testInsert() {
+        insertT1TestDataSet();
+
+        BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+
+        ContentValues cv = new ContentValues();
+        cv.put("_ID", DEFAULT_DATASET_SIZE);
+        cv.put("COL_B", "NewValue");
+        cv.put("COL_C", 1.1);
+        String[] deleteArgs = new String[]{String.valueOf(DEFAULT_DATASET_SIZE)};
+        while (state.keepRunning()) {
+            assertEquals(DEFAULT_DATASET_SIZE, mDatabase.insert("T1", null, cv));
+            state.pauseTiming();
+            assertEquals(1, mDatabase.delete("T1", "_ID=?", deleteArgs));
+            state.resumeTiming();
+        }
+    }
+
+    @Test
+    public void testDelete() {
+        insertT1TestDataSet();
+        BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        String[] deleteArgs = new String[]{String.valueOf(DEFAULT_DATASET_SIZE)};
+        Object[] insertsArgs = new Object[]{DEFAULT_DATASET_SIZE, DEFAULT_DATASET_SIZE,
+                "ValueToDelete", 1.1};
+
+        while (state.keepRunning()) {
+            state.pauseTiming();
+            mDatabase.execSQL("INSERT INTO T1 VALUES (?, ?, ?, ?)", insertsArgs);
+            state.resumeTiming();
+            assertEquals(1, mDatabase.delete("T1", "_ID=?", deleteArgs));
+        }
+    }
+
+    @Test
+    public void testUpdate() {
+        insertT1TestDataSet();
+        BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+
+        Random rnd = new Random(0);
+        int i = 0;
+        ContentValues cv = new ContentValues();
+        String[] argArray = new String[1];
+        while (state.keepRunning()) {
+            int id = rnd.nextInt(DEFAULT_DATASET_SIZE);
+            cv.put("COL_A", i);
+            cv.put("COL_B", "UpdatedValue");
+            cv.put("COL_C", i);
+            argArray[0] = String.valueOf(id);
+            assertEquals(1, mDatabase.update("T1", cv, "_ID=?", argArray));
+            i++;
+        }
+    }
+
+    private void insertT1TestDataSet() {
+        mDatabase.beginTransaction();
+        for (int i = 0; i < DEFAULT_DATASET_SIZE; i++) {
+            mDatabase.execSQL("INSERT INTO T1 VALUES (?, ?, ?, ?)",
+                    new Object[]{i, i, "T1Value" + i, i * 1.1});
+        }
+        mDatabase.setTransactionSuccessful();
+        mDatabase.endTransaction();
+    }
+
+    private void insertT2TestDataSet() {
+        mDatabase.beginTransaction();
+        for (int i = 0; i < DEFAULT_DATASET_SIZE; i++) {
+            mDatabase.execSQL("INSERT INTO T2 VALUES (?, ?, ?)",
+                    new Object[]{i, "T2Value" + i, i});
+        }
+        mDatabase.setTransactionSuccessful();
+        mDatabase.endTransaction();
+    }
+}
+
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/core/java/android/app/WallpaperManager.java b/core/java/android/app/WallpaperManager.java
index 942cc99..081bd81 100644
--- a/core/java/android/app/WallpaperManager.java
+++ b/core/java/android/app/WallpaperManager.java
@@ -388,11 +388,12 @@
 
         public Bitmap peekWallpaperBitmap(Context context, boolean returnDefault,
                 @SetWallpaperFlags int which) {
-            return peekWallpaperBitmap(context, returnDefault, which, context.getUserId());
+            return peekWallpaperBitmap(context, returnDefault, which, context.getUserId(),
+                    false /* hardware */);
         }
 
         public Bitmap peekWallpaperBitmap(Context context, boolean returnDefault,
-                @SetWallpaperFlags int which, int userId) {
+                @SetWallpaperFlags int which, int userId, boolean hardware) {
             if (mService != null) {
                 try {
                     if (!mService.isWallpaperSupported(context.getOpPackageName())) {
@@ -409,7 +410,7 @@
                 mCachedWallpaper = null;
                 mCachedWallpaperUserId = 0;
                 try {
-                    mCachedWallpaper = getCurrentWallpaperLocked(context, userId);
+                    mCachedWallpaper = getCurrentWallpaperLocked(context, userId, hardware);
                     mCachedWallpaperUserId = userId;
                 } catch (OutOfMemoryError e) {
                     Log.w(TAG, "Out of memory loading the current wallpaper: " + e);
@@ -447,7 +448,7 @@
             }
         }
 
-        private Bitmap getCurrentWallpaperLocked(Context context, int userId) {
+        private Bitmap getCurrentWallpaperLocked(Context context, int userId, boolean hardware) {
             if (mService == null) {
                 Log.w(TAG, "WallpaperService not running");
                 return null;
@@ -460,6 +461,9 @@
                 if (fd != null) {
                     try {
                         BitmapFactory.Options options = new BitmapFactory.Options();
+                        if (hardware) {
+                            options.inPreferredConfig = Bitmap.Config.HARDWARE;
+                        }
                         return BitmapFactory.decodeFileDescriptor(
                                 fd.getFileDescriptor(), null, options);
                     } catch (OutOfMemoryError e) {
@@ -814,12 +818,23 @@
     }
 
     /**
-     * Like {@link #getDrawable()} but returns a Bitmap.
+     * Like {@link #getDrawable()} but returns a Bitmap with default {@link Bitmap.Config}.
      *
      * @hide
      */
     public Bitmap getBitmap() {
-        return getBitmapAsUser(mContext.getUserId());
+        return getBitmap(false);
+    }
+
+    /**
+     * Like {@link #getDrawable()} but returns a Bitmap.
+     *
+     * @param hardware Asks for a hardware backed bitmap.
+     * @see Bitmap.Config#HARDWARE
+     * @hide
+     */
+    public Bitmap getBitmap(boolean hardware) {
+        return getBitmapAsUser(mContext.getUserId(), hardware);
     }
 
     /**
@@ -827,8 +842,8 @@
      *
      * @hide
      */
-    public Bitmap getBitmapAsUser(int userId) {
-        return sGlobals.peekWallpaperBitmap(mContext, true, FLAG_SYSTEM, userId);
+    public Bitmap getBitmapAsUser(int userId, boolean hardware) {
+        return sGlobals.peekWallpaperBitmap(mContext, true, FLAG_SYSTEM, userId, hardware);
     }
 
     /**
diff --git a/core/java/android/text/Hyphenator.java b/core/java/android/text/Hyphenator.java
index ddfc00c..4f1488e 100644
--- a/core/java/android/text/Hyphenator.java
+++ b/core/java/android/text/Hyphenator.java
@@ -16,262 +16,15 @@
 
 package android.text;
 
-import android.annotation.IntRange;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.system.ErrnoException;
-import android.system.Os;
-import android.system.OsConstants;
-import android.util.Log;
-
-import com.android.internal.annotations.GuardedBy;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.RandomAccessFile;
-import java.util.HashMap;
-import java.util.Locale;
-
 /**
- * Hyphenator is a wrapper class for a native implementation of automatic hyphenation,
+ * Hyphenator just initializes the native implementation of automatic hyphenation,
  * in essence finding valid hyphenation opportunities in a word.
  *
  * @hide
  */
 public class Hyphenator {
-    private static String TAG = "Hyphenator";
-
-    private final static Object sLock = new Object();
-
-    @GuardedBy("sLock")
-    final static HashMap<Locale, Hyphenator> sMap = new HashMap<Locale, Hyphenator>();
-
-    private final long mNativePtr;
-    private final HyphenationData mData;
-
-    private Hyphenator(long nativePtr, HyphenationData data) {
-        mNativePtr = nativePtr;
-        mData = data;
-    }
-
-    public long getNativePtr() {
-        return mNativePtr;
-    }
-
-    public static Hyphenator get(@Nullable Locale locale) {
-        synchronized (sLock) {
-            Hyphenator result = sMap.get(locale);
-            if (result != null) {
-                return result;
-            }
-
-            // If there's a variant, fall back to language+variant only, if available
-            final String variant = locale.getVariant();
-            if (!variant.isEmpty()) {
-                final Locale languageAndVariantOnlyLocale =
-                        new Locale(locale.getLanguage(), "", variant);
-                result = sMap.get(languageAndVariantOnlyLocale);
-                if (result != null) {
-                    return putAlias(locale, result);
-                }
-            }
-
-            // Fall back to language-only, if available
-            final Locale languageOnlyLocale = new Locale(locale.getLanguage());
-            result = sMap.get(languageOnlyLocale);
-            if (result != null) {
-                return putAlias(locale, result);
-            }
-
-            // Fall back to script-only, if available
-            final String script = locale.getScript();
-            if (!script.equals("")) {
-                final Locale scriptOnlyLocale = new Locale.Builder()
-                        .setLanguage("und")
-                        .setScript(script)
-                        .build();
-                result = sMap.get(scriptOnlyLocale);
-                if (result != null) {
-                    return putAlias(locale, result);
-                }
-            }
-
-            return putEmptyAlias(locale);
-        }
-    }
-
-    private static class HyphenationData {
-        private static final String SYSTEM_HYPHENATOR_LOCATION = "/system/usr/hyphen-data";
-
-        public final int mMinPrefix, mMinSuffix;
-        public final long mDataAddress;
-
-        // Reasonable enough values for cases where we have no hyphenation patterns but may be able
-        // to do some automatic hyphenation based on characters. These values would be used very
-        // rarely.
-        private static final int DEFAULT_MIN_PREFIX = 2;
-        private static final int DEFAULT_MIN_SUFFIX = 2;
-
-        public static final HyphenationData sEmptyData =
-                new HyphenationData(DEFAULT_MIN_PREFIX, DEFAULT_MIN_SUFFIX);
-
-        // Create empty HyphenationData.
-        private HyphenationData(int minPrefix, int minSuffix) {
-            mMinPrefix = minPrefix;
-            mMinSuffix = minSuffix;
-            mDataAddress = 0;
-        }
-
-        HyphenationData(String languageTag, int minPrefix, int minSuffix) {
-            mMinPrefix = minPrefix;
-            mMinSuffix = minSuffix;
-
-            final String patternFilename = "hyph-" + languageTag.toLowerCase(Locale.US) + ".hyb";
-            final File patternFile = new File(SYSTEM_HYPHENATOR_LOCATION, patternFilename);
-            if (!patternFile.canRead()) {
-                mDataAddress = 0;
-            } else {
-                long address;
-                try (RandomAccessFile f = new RandomAccessFile(patternFile, "r")) {
-                    address = Os.mmap(0, f.length(), OsConstants.PROT_READ,
-                            OsConstants.MAP_SHARED, f.getFD(), 0 /* offset */);
-                } catch (IOException | ErrnoException e) {
-                    Log.e(TAG, "error loading hyphenation " + patternFile, e);
-                    address = 0;
-                }
-                mDataAddress = address;
-            }
-        }
-    }
-
-    // Do not call this method outside of init method.
-    private static Hyphenator putNewHyphenator(Locale loc, HyphenationData data) {
-        final Hyphenator hyphenator = new Hyphenator(nBuildHyphenator(
-                data.mDataAddress, loc.getLanguage(), data.mMinPrefix, data.mMinSuffix), data);
-        sMap.put(loc, hyphenator);
-        return hyphenator;
-    }
-
-    // Do not call this method outside of init method.
-    private static void loadData(String langTag, int minPrefix, int maxPrefix) {
-        final HyphenationData data = new HyphenationData(langTag, minPrefix, maxPrefix);
-        putNewHyphenator(Locale.forLanguageTag(langTag), data);
-    }
-
-    // Caller must acquire sLock before calling this method.
-    // The Hyphenator for the baseLangTag must exists.
-    private static Hyphenator addAliasByTag(String langTag, String baseLangTag) {
-        return putAlias(Locale.forLanguageTag(langTag),
-                sMap.get(Locale.forLanguageTag(baseLangTag)));
-    }
-
-    // Caller must acquire sLock before calling this method.
-    private static Hyphenator putAlias(Locale locale, Hyphenator base) {
-        return putNewHyphenator(locale, base.mData);
-    }
-
-    // Caller must acquire sLock before calling this method.
-    private static Hyphenator putEmptyAlias(Locale locale) {
-        return putNewHyphenator(locale, HyphenationData.sEmptyData);
-    }
-
-    // TODO: Confirm that these are the best values. Various sources suggest (1, 1), but
-    // that appears too small.
-    private static final int INDIC_MIN_PREFIX = 2;
-    private static final int INDIC_MIN_SUFFIX = 2;
-
-    /**
-     * Load hyphenation patterns at initialization time. We want to have patterns
-     * for all locales loaded and ready to use so we don't have to do any file IO
-     * on the UI thread when drawing text in different locales.
-     *
-     * @hide
-     */
     public static void init() {
-        synchronized (sLock) {
-            sMap.put(null, null);
-
-            loadData("as", INDIC_MIN_PREFIX, INDIC_MIN_SUFFIX); // Assamese
-            loadData("bg", 2, 2); // Bulgarian
-            loadData("bn", INDIC_MIN_PREFIX, INDIC_MIN_SUFFIX); // Bengali
-            loadData("cu", 1, 2); // Church Slavonic
-            loadData("cy", 2, 3); // Welsh
-            loadData("da", 2, 2); // Danish
-            loadData("de-1901", 2, 2); // German 1901 orthography
-            loadData("de-1996", 2, 2); // German 1996 orthography
-            loadData("de-CH-1901", 2, 2); // Swiss High German 1901 orthography
-            loadData("en-GB", 2, 3); // British English
-            loadData("en-US", 2, 3); // American English
-            loadData("es", 2, 2); // Spanish
-            loadData("et", 2, 3); // Estonian
-            loadData("eu", 2, 2); // Basque
-            loadData("fr", 2, 3); // French
-            loadData("ga", 2, 3); // Irish
-            loadData("gu", INDIC_MIN_PREFIX, INDIC_MIN_SUFFIX); // Gujarati
-            loadData("hi", INDIC_MIN_PREFIX, INDIC_MIN_SUFFIX); // Hindi
-            loadData("hr", 2, 2); // Croatian
-            loadData("hu", 2, 2); // Hungarian
-            // texhyphen sources say Armenian may be (1, 2); but that it needs confirmation.
-            // Going with a more conservative value of (2, 2) for now.
-            loadData("hy", 2, 2); // Armenian
-            loadData("kn", INDIC_MIN_PREFIX, INDIC_MIN_SUFFIX); // Kannada
-            loadData("ml", INDIC_MIN_PREFIX, INDIC_MIN_SUFFIX); // Malayalam
-            loadData("mn-Cyrl", 2, 2); // Mongolian in Cyrillic script
-            loadData("mr", INDIC_MIN_PREFIX, INDIC_MIN_SUFFIX); // Marathi
-            loadData("nb", 2, 2); // Norwegian Bokmål
-            loadData("nn", 2, 2); // Norwegian Nynorsk
-            loadData("or", INDIC_MIN_PREFIX, INDIC_MIN_SUFFIX); // Oriya
-            loadData("pa", INDIC_MIN_PREFIX, INDIC_MIN_SUFFIX); // Punjabi
-            loadData("pt", 2, 3); // Portuguese
-            loadData("sl", 2, 2); // Slovenian
-            loadData("ta", INDIC_MIN_PREFIX, INDIC_MIN_SUFFIX); // Tamil
-            loadData("te", INDIC_MIN_PREFIX, INDIC_MIN_SUFFIX); // Telugu
-            loadData("tk", 2, 2); // Turkmen
-            loadData("und-Ethi", 1, 1); // Any language in Ethiopic script
-
-            // Following two hyphenators do not have pattern files but there is some special logic
-            // based on language.
-            loadData("ca", 2, 2);  // Catalan
-            loadData("pl", 2, 2);  // Polish
-
-            // English locales that fall back to en-US. The data is
-            // from CLDR. It's all English locales, minus the locales whose
-            // parent is en-001 (from supplementalData.xml, under <parentLocales>).
-            // TODO: Figure out how to get this from ICU.
-            addAliasByTag("en-AS", "en-US"); // English (American Samoa)
-            addAliasByTag("en-GU", "en-US"); // English (Guam)
-            addAliasByTag("en-MH", "en-US"); // English (Marshall Islands)
-            addAliasByTag("en-MP", "en-US"); // English (Northern Mariana Islands)
-            addAliasByTag("en-PR", "en-US"); // English (Puerto Rico)
-            addAliasByTag("en-UM", "en-US"); // English (United States Minor Outlying Islands)
-            addAliasByTag("en-VI", "en-US"); // English (Virgin Islands)
-
-            // All English locales other than those falling back to en-US are mapped to en-GB.
-            addAliasByTag("en", "en-GB");
-
-            // For German, we're assuming the 1996 (and later) orthography by default.
-            addAliasByTag("de", "de-1996");
-            // Liechtenstein uses the Swiss hyphenation rules for the 1901 orthography.
-            addAliasByTag("de-LI-1901", "de-CH-1901");
-
-            // Norwegian is very probably Norwegian Bokmål.
-            addAliasByTag("no", "nb");
-
-            // Use mn-Cyrl. According to CLDR's likelySubtags.xml, mn is most likely to be mn-Cyrl.
-            addAliasByTag("mn", "mn-Cyrl"); // Mongolian
-
-            // Fall back to Ethiopic script for languages likely to be written in Ethiopic.
-            // Data is from CLDR's likelySubtags.xml.
-            // TODO: Convert this to a mechanism using ICU4J's ULocale#addLikelySubtags().
-            addAliasByTag("am", "und-Ethi"); // Amharic
-            addAliasByTag("byn", "und-Ethi"); // Blin
-            addAliasByTag("gez", "und-Ethi"); // Geʻez
-            addAliasByTag("ti", "und-Ethi"); // Tigrinya
-            addAliasByTag("wal", "und-Ethi"); // Wolaytta
-        }
-    };
-
-    private static native long nBuildHyphenator(long dataAddress,
-            @NonNull String langTag, @IntRange(from = 1) int minPrefix,
-            @IntRange(from = 1) int minSuffix);
+        nInit();
+    }
+    private static native void nInit();
 }
diff --git a/core/java/android/text/StaticLayout.java b/core/java/android/text/StaticLayout.java
index 4b6b6ae..5c60188 100644
--- a/core/java/android/text/StaticLayout.java
+++ b/core/java/android/text/StaticLayout.java
@@ -21,21 +21,18 @@
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.graphics.Paint;
-import android.os.LocaleList;
 import android.text.style.LeadingMarginSpan;
 import android.text.style.LeadingMarginSpan.LeadingMarginSpan2;
 import android.text.style.LineHeightSpan;
 import android.text.style.MetricAffectingSpan;
 import android.text.style.TabStopSpan;
 import android.util.Log;
-import android.util.Pair;
 import android.util.Pools.SynchronizedPool;
 
 import com.android.internal.util.ArrayUtils;
 import com.android.internal.util.GrowingArrayUtils;
 
 import java.util.Arrays;
-import java.util.Locale;
 
 /**
  * StaticLayout is a Layout for text that will not be edited after it
@@ -101,7 +98,6 @@
             b.mBreakStrategy = Layout.BREAK_STRATEGY_SIMPLE;
             b.mHyphenationFrequency = Layout.HYPHENATION_FREQUENCY_NONE;
             b.mJustificationMode = Layout.JUSTIFICATION_MODE_NONE;
-            b.mLocales = null;
 
             b.mMeasuredText = MeasuredText.obtain();
             return b;
@@ -118,7 +114,6 @@
             b.mMeasuredText = null;
             b.mLeftIndents = null;
             b.mRightIndents = null;
-            b.mLocales = null;
             b.mLeftPaddings = null;
             b.mRightPaddings = null;
             nFinishBuilder(b.mNativePtr);
@@ -409,17 +404,6 @@
             return this;
         }
 
-        @NonNull
-        private long[] getHyphenators(@NonNull LocaleList locales) {
-            final int length = locales.size();
-            final long[] result = new long[length];
-            for (int i = 0; i < length; i++) {
-                final Locale locale = locales.get(i);
-                result[i] = Hyphenator.get(locale).getNativePtr();
-            }
-            return result;
-        }
-
         /**
          * Measurement and break iteration is done in native code. The protocol for using
          * the native code is as follows.
@@ -438,27 +422,12 @@
          * After all paragraphs, call finish() to release expensive buffers.
          */
 
-        private Pair<String, long[]> getLocaleAndHyphenatorIfChanged(TextPaint paint) {
-            final LocaleList locales = paint.getTextLocales();
-            if (!locales.equals(mLocales)) {
-                mLocales = locales;
-                return new Pair(locales.toLanguageTags(), getHyphenators(locales));
-            } else {
-                // passing null means keep current locale.
-                // TODO: move locale change detection to native.
-                return new Pair(null, null);
-            }
-        }
-
         /* package */ void addStyleRun(TextPaint paint, int start, int end, boolean isRtl) {
-            Pair<String, long[]> locHyph = getLocaleAndHyphenatorIfChanged(paint);
-            nAddStyleRun(mNativePtr, paint.getNativeInstance(), start, end, isRtl, locHyph.first,
-                    locHyph.second);
+            nAddStyleRun(mNativePtr, paint.getNativeInstance(), start, end, isRtl);
         }
 
         /* package */ void addReplacementRun(TextPaint paint, int start, int end, float width) {
-            Pair<String, long[]> locHyph = getLocaleAndHyphenatorIfChanged(paint);
-            nAddReplacementRun(mNativePtr, start, end, width, locHyph.first, locHyph.second);
+            nAddReplacementRun(mNativePtr, paint.getNativeInstance(), start, end, width);
         }
 
         /**
@@ -516,8 +485,6 @@
         // This will go away and be subsumed by native builder code
         private MeasuredText mMeasuredText;
 
-        private LocaleList mLocales;
-
         private static final SynchronizedPool<Builder> sPool = new SynchronizedPool<>(3);
     }
 
@@ -807,9 +774,6 @@
                 }
             }
 
-            // TODO: Move locale tracking code to native.
-            b.mLocales = null;  // Reset the locale tracking.
-
             nSetupParagraph(b.mNativePtr, chs, paraEnd - paraStart,
                     firstWidth, firstWidthLineCount, restWidth,
                     variableTabStops, TAB_INCREMENT, b.mBreakStrategy, b.mHyphenationFrequency,
@@ -1537,15 +1501,16 @@
             @Nullable int[] indents, @Nullable int[] leftPaddings, @Nullable int[] rightPaddings,
             @IntRange(from = 0) int indentsOffset);
 
+    // TODO: Make this method CriticalNative once native code defers doing layouts.
     private static native void nAddStyleRun(
             /* non-zero */ long nativePtr, /* non-zero */ long nativePaint,
-            @IntRange(from = 0) int start, @IntRange(from = 0) int end, boolean isRtl,
-            @Nullable String languageTags, @Nullable long[] hyphenators);
+            @IntRange(from = 0) int start, @IntRange(from = 0) int end, boolean isRtl);
 
-    private static native void nAddReplacementRun(/* non-zero */ long nativePtr,
+    // TODO: Make this method CriticalNative once native code defers doing layouts.
+    private static native void nAddReplacementRun(
+            /* non-zero */ long nativePtr, /* non-zero */ long nativePaint,
             @IntRange(from = 0) int start, @IntRange(from = 0) int end,
-            @FloatRange(from = 0.0f) float width, @Nullable String languageTags,
-            @Nullable long[] hyphenators);
+            @FloatRange(from = 0.0f) float width);
 
     // populates LineBreaks and returns the number of breaks found
     //
diff --git a/core/java/android/widget/Editor.java b/core/java/android/widget/Editor.java
index afd1188..91f6799 100644
--- a/core/java/android/widget/Editor.java
+++ b/core/java/android/widget/Editor.java
@@ -165,7 +165,7 @@
     private static final int MENU_ITEM_ORDER_PASTE_AS_PLAIN_TEXT = 11;
     private static final int MENU_ITEM_ORDER_PROCESS_TEXT_INTENT_ACTIONS_START = 100;
 
-    private static final float MAGNIFIER_ZOOM = 1.5f;
+    private static final float MAGNIFIER_ZOOM = 1.25f;
     @IntDef({MagnifierHandleTrigger.SELECTION_START,
             MagnifierHandleTrigger.SELECTION_END,
             MagnifierHandleTrigger.INSERTION})
@@ -4550,12 +4550,14 @@
             final float centerYOnScreen = yPosInView + mTextView.getTotalPaddingTop()
                     - mTextView.getScrollY() + coordinatesOnScreen[1];
 
+            suspendBlink();
             mMagnifier.show(centerXOnScreen, centerYOnScreen, MAGNIFIER_ZOOM);
         }
 
         protected final void dismissMagnifier() {
             if (mMagnifier != null) {
                 mMagnifier.dismiss();
+                resumeBlink();
             }
         }
 
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/java/com/android/internal/widget/Magnifier.java b/core/java/com/android/internal/widget/Magnifier.java
index 86e7b38..284f2b2 100644
--- a/core/java/com/android/internal/widget/Magnifier.java
+++ b/core/java/com/android/internal/widget/Magnifier.java
@@ -41,6 +41,8 @@
  */
 public final class Magnifier {
     private static final String LOG_TAG = "magnifier";
+    private static final int MINIMUM_MAGNIFIER_SCALE = 1;
+    private static final int MAXIMUM_MAGNIFIER_SCALE = 4;
     // The view for which this magnifier is attached.
     private final View mView;
     // The window containing the magnifier.
@@ -94,7 +96,23 @@
      */
     public void show(@FloatRange(from=0) float centerXOnScreen,
             @FloatRange(from=0) float centerYOnScreen,
-            @FloatRange(from=1, to=10) float scale) {
+            @FloatRange(from=MINIMUM_MAGNIFIER_SCALE, to=MAXIMUM_MAGNIFIER_SCALE) float scale) {
+        if (scale > MAXIMUM_MAGNIFIER_SCALE) {
+            scale = MAXIMUM_MAGNIFIER_SCALE;
+        }
+
+        if (scale < MINIMUM_MAGNIFIER_SCALE) {
+            scale = MINIMUM_MAGNIFIER_SCALE;
+        }
+
+        if (centerXOnScreen < 0) {
+            centerXOnScreen = 0;
+        }
+
+        if (centerYOnScreen < 0) {
+            centerYOnScreen = 0;
+        }
+
         maybeResizeBitmap(scale);
         configureCoordinates(centerXOnScreen, centerYOnScreen);
         performPixelCopy();
@@ -144,12 +162,8 @@
 
         final int verticalMagnifierOffset = mView.getContext().getResources().getDimensionPixelSize(
                 R.dimen.magnifier_offset);
-        final int availableTopSpace = (mCenterZoomCoords.y - mWindowHeight / 2)
-                - verticalMagnifierOffset - (mBitmap.getHeight() / 2);
-
         mWindowCoords.x = mCenterZoomCoords.x - mWindowWidth / 2;
-        mWindowCoords.y = mCenterZoomCoords.y - mWindowHeight / 2
-                + verticalMagnifierOffset * (availableTopSpace > 0 ? -1 : 1);
+        mWindowCoords.y = mCenterZoomCoords.y - mWindowHeight / 2 - verticalMagnifierOffset;
     }
 
     private void performPixelCopy() {
diff --git a/core/jni/AndroidRuntime.cpp b/core/jni/AndroidRuntime.cpp
index e312478..820933b 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.
      */
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_text_Hyphenator.cpp b/core/jni/android_text_Hyphenator.cpp
index da025da..b46f389 100644
--- a/core/jni/android_text_Hyphenator.cpp
+++ b/core/jni/android_text_Hyphenator.cpp
@@ -14,24 +14,155 @@
  * limitations under the License.
  */
 
-#include <cstdint>
+#include <sys/mman.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include <algorithm>
+
 #include <core_jni_helpers.h>
 #include <minikin/Hyphenator.h>
-#include <nativehelper/ScopedUtfChars.h>
 
 namespace android {
 
-static jlong nBuildHyphenator(JNIEnv* env, jclass, jlong dataAddress, jstring lang,
-        jint minPrefix, jint minSuffix) {
-    const uint8_t* bytebuf = reinterpret_cast<const uint8_t*>(dataAddress);  // null allowed.
-    ScopedUtfChars language(env, lang);
-    minikin::Hyphenator* hyphenator = minikin::Hyphenator::loadBinary(
-            bytebuf, minPrefix, minSuffix, language.c_str(), language.size());
-    return reinterpret_cast<jlong>(hyphenator);
+static std::string buildFileName(const std::string& locale) {
+    constexpr char SYSTEM_HYPHENATOR_PREFIX[] = "/system/usr/hyphen-data/hyph-";
+    constexpr char SYSTEM_HYPHENATOR_SUFFIX[] = ".hyb";
+    std::string lowerLocale;
+    lowerLocale.reserve(locale.size());
+    std::transform(locale.begin(), locale.end(), std::back_inserter(lowerLocale), ::tolower);
+    return SYSTEM_HYPHENATOR_PREFIX + lowerLocale + SYSTEM_HYPHENATOR_SUFFIX;
+}
+
+static const uint8_t* mmapPatternFile(const std::string& locale) {
+    const std::string hyFilePath = buildFileName(locale);
+    const int fd = open(hyFilePath.c_str(), O_RDONLY);
+    if (fd == -1) {
+        return nullptr;  // Open failed.
+    }
+
+    struct stat st = {};
+    if (fstat(fd, &st) == -1) {  // Unlikely to happen.
+        close(fd);
+        return nullptr;
+    }
+
+    void* ptr = mmap(nullptr, st.st_size, PROT_READ, MAP_SHARED, fd, 0 /* offset */);
+    close(fd);
+    if (ptr == MAP_FAILED) {
+        return nullptr;
+    }
+    return reinterpret_cast<const uint8_t*>(ptr);
+}
+
+static void addHyphenatorWithoutPatternFile(const std::string& locale, int minPrefix,
+        int minSuffix) {
+    minikin::addHyphenator(locale, minikin::Hyphenator::loadBinary(
+            nullptr, minPrefix, minSuffix, locale));
+}
+
+static void addHyphenator(const std::string& locale, int minPrefix, int minSuffix) {
+    const uint8_t* ptr = mmapPatternFile(locale);
+    if (ptr == nullptr) {
+        ALOGE("Unable to find pattern file or unable to map it for %s", locale.c_str());
+        return;
+    }
+    minikin::addHyphenator(locale, minikin::Hyphenator::loadBinary(
+            ptr, minPrefix, minSuffix, locale));
+}
+
+static void addHyphenatorAlias(const std::string& from, const std::string& to) {
+    minikin::addHyphenatorAlias(from, to);
+}
+
+static void init() {
+    // TODO: Confirm that these are the best values. Various sources suggest (1, 1), but that
+    // appears too small.
+    constexpr int INDIC_MIN_PREFIX = 2;
+    constexpr int INDIC_MIN_SUFFIX = 2;
+
+    addHyphenator("as", INDIC_MIN_PREFIX, INDIC_MIN_SUFFIX); // Assamese
+    addHyphenator("bg", 2, 2); // Bulgarian
+    addHyphenator("bn", INDIC_MIN_PREFIX, INDIC_MIN_SUFFIX); // Bengali
+    addHyphenator("cu", 1, 2); // Church Slavonic
+    addHyphenator("cy", 2, 3); // Welsh
+    addHyphenator("da", 2, 2); // Danish
+    addHyphenator("de-1901", 2, 2); // German 1901 orthography
+    addHyphenator("de-1996", 2, 2); // German 1996 orthography
+    addHyphenator("de-CH-1901", 2, 2); // Swiss High German 1901 orthography
+    addHyphenator("en-GB", 2, 3); // British English
+    addHyphenator("en-US", 2, 3); // American English
+    addHyphenator("es", 2, 2); // Spanish
+    addHyphenator("et", 2, 3); // Estonian
+    addHyphenator("eu", 2, 2); // Basque
+    addHyphenator("fr", 2, 3); // French
+    addHyphenator("ga", 2, 3); // Irish
+    addHyphenator("gu", INDIC_MIN_PREFIX, INDIC_MIN_SUFFIX); // Gujarati
+    addHyphenator("hi", INDIC_MIN_PREFIX, INDIC_MIN_SUFFIX); // Hindi
+    addHyphenator("hr", 2, 2); // Croatian
+    addHyphenator("hu", 2, 2); // Hungarian
+    // texhyphen sources say Armenian may be (1, 2); but that it needs confirmation.
+    // Going with a more conservative value of (2, 2) for now.
+    addHyphenator("hy", 2, 2); // Armenian
+    addHyphenator("kn", INDIC_MIN_PREFIX, INDIC_MIN_SUFFIX); // Kannada
+    addHyphenator("ml", INDIC_MIN_PREFIX, INDIC_MIN_SUFFIX); // Malayalam
+    addHyphenator("mn-Cyrl", 2, 2); // Mongolian in Cyrillic script
+    addHyphenator("mr", INDIC_MIN_PREFIX, INDIC_MIN_SUFFIX); // Marathi
+    addHyphenator("nb", 2, 2); // Norwegian Bokmål
+    addHyphenator("nn", 2, 2); // Norwegian Nynorsk
+    addHyphenator("or", INDIC_MIN_PREFIX, INDIC_MIN_SUFFIX); // Oriya
+    addHyphenator("pa", INDIC_MIN_PREFIX, INDIC_MIN_SUFFIX); // Punjabi
+    addHyphenator("pt", 2, 3); // Portuguese
+    addHyphenator("sl", 2, 2); // Slovenian
+    addHyphenator("ta", INDIC_MIN_PREFIX, INDIC_MIN_SUFFIX); // Tamil
+    addHyphenator("te", INDIC_MIN_PREFIX, INDIC_MIN_SUFFIX); // Telugu
+    addHyphenator("tk", 2, 2); // Turkmen
+    addHyphenator("und-Ethi", 1, 1); // Any language in Ethiopic script
+
+    // Following two hyphenators do not have pattern files but there is some special logic based on
+    // language.
+    addHyphenatorWithoutPatternFile("ca", 2, 2);  // Catalan
+    addHyphenatorWithoutPatternFile("pl", 2, 2);  // Polish
+
+    // English locales that fall back to en-US. The data is from CLDR. It's all English locales,
+    // minus the locales whose parent is en-001 (from supplementalData.xml, under <parentLocales>).
+    // TODO: Figure out how to get this from ICU.
+    addHyphenatorAlias("en-AS", "en-US"); // English (American Samoa)
+    addHyphenatorAlias("en-GU", "en-US"); // English (Guam)
+    addHyphenatorAlias("en-MH", "en-US"); // English (Marshall Islands)
+    addHyphenatorAlias("en-MP", "en-US"); // English (Northern Mariana Islands)
+    addHyphenatorAlias("en-PR", "en-US"); // English (Puerto Rico)
+    addHyphenatorAlias("en-UM", "en-US"); // English (United States Minor Outlying Islands)
+    addHyphenatorAlias("en-VI", "en-US"); // English (Virgin Islands)
+
+    // All English locales other than those falling back to en-US are mapped to en-GB.
+    addHyphenatorAlias("en", "en-GB");
+
+    // For German, we're assuming the 1996 (and later) orthography by default.
+    addHyphenatorAlias("de", "de-1996");
+    // Liechtenstein uses the Swiss hyphenation rules for the 1901 orthography.
+    addHyphenatorAlias("de-LI-1901", "de-CH-1901");
+
+    // Norwegian is very probably Norwegian Bokmål.
+    addHyphenatorAlias("no", "nb");
+
+    // Use mn-Cyrl. According to CLDR's likelySubtags.xml, mn is most likely to be mn-Cyrl.
+    addHyphenatorAlias("mn", "mn-Cyrl"); // Mongolian
+
+    // Fall back to Ethiopic script for languages likely to be written in Ethiopic.
+    // Data is from CLDR's likelySubtags.xml.
+    // TODO: Convert this to a mechanism using ICU4J's ULocale#addLikelySubtags().
+    addHyphenatorAlias("am", "und-Ethi"); // Amharic
+    addHyphenatorAlias("byn", "und-Ethi"); // Blin
+    addHyphenatorAlias("gez", "und-Ethi"); // Geʻez
+    addHyphenatorAlias("ti", "und-Ethi"); // Tigrinya
+    addHyphenatorAlias("wal", "und-Ethi"); // Wolaytta
+
 }
 
 static const JNINativeMethod gMethods[] = {
-    {"nBuildHyphenator", "(JLjava/lang/String;II)J", (void*) nBuildHyphenator},
+    {"nInit", "()V", (void*) init},
 };
 
 int register_android_text_Hyphenator(JNIEnv* env) {
diff --git a/core/jni/android_text_StaticLayout.cpp b/core/jni/android_text_StaticLayout.cpp
index 1f7277a..04e9dfd 100644
--- a/core/jni/android_text_StaticLayout.cpp
+++ b/core/jni/android_text_StaticLayout.cpp
@@ -195,49 +195,9 @@
     b->finish();
 }
 
-class ScopedNullableUtfString {
-public:
-    ScopedNullableUtfString(JNIEnv* env, jstring s) : mEnv(env), mStr(s) {
-        if (s == nullptr) {
-            mUtf8Chars = nullptr;
-        } else {
-            mUtf8Chars = mEnv->GetStringUTFChars(s, nullptr);
-        }
-    }
-
-    ~ScopedNullableUtfString() {
-        if (mUtf8Chars != nullptr) {
-            mEnv->ReleaseStringUTFChars(mStr, mUtf8Chars);
-        }
-    }
-
-    const char* get() const {
-        return mUtf8Chars;
-    }
-
-private:
-    JNIEnv* mEnv;
-    jstring mStr;
-    const char* mUtf8Chars;
-};
-
-static std::vector<minikin::Hyphenator*> makeHyphenators(JNIEnv* env, jlongArray hyphenators) {
-    std::vector<minikin::Hyphenator*> out;
-    if (hyphenators == nullptr) {
-        return out;
-    }
-    ScopedLongArrayRO longArray(env, hyphenators);
-    size_t size = longArray.size();
-    out.reserve(size);
-    for (size_t i = 0; i < size; i++) {
-        out.push_back(reinterpret_cast<minikin::Hyphenator*>(longArray[i]));
-    }
-    return out;
-}
-
 // Basically similar to Paint.getTextRunAdvances but with C++ interface
 static void nAddStyleRun(JNIEnv* env, jclass, jlong nativePtr, jlong nativePaint, jint start,
-        jint end, jboolean isRtl, jstring langTags, jlongArray hyphenators) {
+        jint end, jboolean isRtl) {
     minikin::LineBreaker* b = reinterpret_cast<minikin::LineBreaker*>(nativePtr);
     Paint* paint = reinterpret_cast<Paint*>(nativePaint);
     const Typeface* typeface = paint->getAndroidTypeface();
@@ -246,16 +206,14 @@
     minikin::FontStyle style = MinikinUtils::prepareMinikinPaint(&minikinPaint, paint,
             typeface);
 
-    ScopedNullableUtfString langTagsString(env, langTags);
-    b->addStyleRun(&minikinPaint, resolvedTypeface->fFontCollection, style, start,
-            end, isRtl, langTagsString.get(), makeHyphenators(env, hyphenators));
+    b->addStyleRun(&minikinPaint, resolvedTypeface->fFontCollection, style, start, end, isRtl);
 }
 
-static void nAddReplacementRun(JNIEnv* env, jclass, jlong nativePtr,
-        jint start, jint end, jfloat width, jstring langTags, jlongArray hyphenators) {
+static void nAddReplacementRun(JNIEnv* env, jclass, jlong nativePtr, jlong nativePaint,
+        jint start, jint end, jfloat width) {
     minikin::LineBreaker* b = reinterpret_cast<minikin::LineBreaker*>(nativePtr);
-    ScopedNullableUtfString langTagsString(env, langTags);
-    b->addReplacement(start, end, width, langTagsString.get(), makeHyphenators(env, hyphenators));
+    Paint* paint = reinterpret_cast<Paint*>(nativePaint);
+    b->addReplacement(start, end, width, paint->getMinikinLangListId());
 }
 
 static const JNINativeMethod gMethods[] = {
@@ -264,8 +222,8 @@
     {"nFreeBuilder", "(J)V", (void*) nFreeBuilder},
     {"nFinishBuilder", "(J)V", (void*) nFinishBuilder},
     {"nSetupParagraph", "(J[CIFIF[IIIIZ[I[I[II)V", (void*) nSetupParagraph},
-    {"nAddStyleRun", "(JJIIZLjava/lang/String;[J)V", (void*) nAddStyleRun},
-    {"nAddReplacementRun", "(JIIFLjava/lang/String;[J)V", (void*) nAddReplacementRun},
+    {"nAddStyleRun", "(JJIIZ)V", (void*) nAddStyleRun},
+    {"nAddReplacementRun", "(JJIIF)V", (void*) nAddReplacementRun},
     {"nComputeLineBreaks", "(JLandroid/text/StaticLayout$LineBreaks;[I[F[F[F[II[F)I",
         (void*) nComputeLineBreaks}
 };
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/ImageWallpaper.java b/packages/SystemUI/src/com/android/systemui/ImageWallpaper.java
index 907a79e..593bb50 100644
--- a/packages/SystemUI/src/com/android/systemui/ImageWallpaper.java
+++ b/packages/SystemUI/src/com/android/systemui/ImageWallpaper.java
@@ -16,11 +16,6 @@
 
 package com.android.systemui;
 
-import static android.opengl.GLES20.*;
-
-import static javax.microedition.khronos.egl.EGL10.*;
-
-import android.app.ActivityManager;
 import android.app.WallpaperManager;
 import android.content.ComponentCallbacks2;
 import android.graphics.Bitmap;
@@ -28,31 +23,18 @@
 import android.graphics.Rect;
 import android.graphics.RectF;
 import android.graphics.Region.Op;
-import android.opengl.GLUtils;
 import android.os.AsyncTask;
-import android.os.SystemProperties;
 import android.os.Trace;
-import android.renderscript.Matrix4f;
 import android.service.wallpaper.WallpaperService;
 import android.util.Log;
 import android.view.Display;
 import android.view.DisplayInfo;
-import android.view.MotionEvent;
 import android.view.SurfaceHolder;
 import android.view.WindowManager;
 
 import java.io.FileDescriptor;
 import java.io.IOException;
 import java.io.PrintWriter;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import java.nio.FloatBuffer;
-
-import javax.microedition.khronos.egl.EGL10;
-import javax.microedition.khronos.egl.EGLConfig;
-import javax.microedition.khronos.egl.EGLContext;
-import javax.microedition.khronos.egl.EGLDisplay;
-import javax.microedition.khronos.egl.EGLSurface;
 
 /**
  * Default built-in wallpaper that simply shows a static image.
@@ -64,24 +46,13 @@
     private static final boolean DEBUG = false;
     private static final String PROPERTY_KERNEL_QEMU = "ro.kernel.qemu";
 
-    static final boolean FIXED_SIZED_SURFACE = true;
-    static final boolean USE_OPENGL = true;
-
-    WallpaperManager mWallpaperManager;
-
-    DrawableEngine mEngine;
-
-    boolean mIsHwAccelerated;
+    private WallpaperManager mWallpaperManager;
+    private DrawableEngine mEngine;
 
     @Override
     public void onCreate() {
         super.onCreate();
-        mWallpaperManager = (WallpaperManager) getSystemService(WALLPAPER_SERVICE);
-
-        //noinspection PointlessBooleanExpression,ConstantConditions
-        if (FIXED_SIZED_SURFACE && USE_OPENGL) {
-            mIsHwAccelerated = ActivityManager.isHighEndGfx();
-        }
+        mWallpaperManager = getSystemService(WallpaperManager.class);
     }
 
     @Override
@@ -98,15 +69,12 @@
     }
 
     class DrawableEngine extends Engine {
-        static final int EGL_CONTEXT_CLIENT_VERSION = 0x3098;
-        static final int EGL_OPENGL_ES2_BIT = 4;
-
         Bitmap mBackground;
         int mBackgroundWidth = -1, mBackgroundHeight = -1;
         int mLastSurfaceWidth = -1, mLastSurfaceHeight = -1;
         int mLastRotation = -1;
-        float mXOffset = 0.5f;
-        float mYOffset = 0.5f;
+        float mXOffset = 0f;
+        float mYOffset = 0f;
         float mScale = 1f;
 
         private Display mDefaultDisplay;
@@ -117,34 +85,6 @@
         int mLastXTranslation;
         int mLastYTranslation;
 
-        private EGL10 mEgl;
-        private EGLDisplay mEglDisplay;
-        private EGLConfig mEglConfig;
-        private EGLContext mEglContext;
-        private EGLSurface mEglSurface;
-
-        private static final String sSimpleVS =
-                "attribute vec4 position;\n" +
-                "attribute vec2 texCoords;\n" +
-                "varying vec2 outTexCoords;\n" +
-                "uniform mat4 projection;\n" +
-                "\nvoid main(void) {\n" +
-                "    outTexCoords = texCoords;\n" +
-                "    gl_Position = projection * position;\n" +
-                "}\n\n";
-        private static final String sSimpleFS =
-                "precision mediump float;\n\n" +
-                "varying vec2 outTexCoords;\n" +
-                "uniform sampler2D texture;\n" +
-                "\nvoid main(void) {\n" +
-                "    gl_FragColor = texture2D(texture, outTexCoords);\n" +
-                "}\n\n";
-
-        private static final int FLOAT_SIZE_BYTES = 4;
-        private static final int TRIANGLE_VERTICES_DATA_STRIDE_BYTES = 5 * FLOAT_SIZE_BYTES;
-        private static final int TRIANGLE_VERTICES_DATA_POS_OFFSET = 0;
-        private static final int TRIANGLE_VERTICES_DATA_UV_OFFSET = 3;
-
         private int mRotationAtLastSurfaceSizeUpdate = -1;
         private int mDisplayWidthAtLastSurfaceSizeUpdate = -1;
         private int mDisplayHeightAtLastSurfaceSizeUpdate = -1;
@@ -154,13 +94,14 @@
         private AsyncTask<Void, Void, Bitmap> mLoader;
         private boolean mNeedsDrawAfterLoadingWallpaper;
         private boolean mSurfaceValid;
+        private boolean mSurfaceRedrawNeeded;
 
-        public DrawableEngine() {
+        DrawableEngine() {
             super();
             setFixedSizeAllowed(true);
         }
 
-        public void trimMemory(int level) {
+        void trimMemory(int level) {
             if (level >= ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW
                     && level <= ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL
                     && mBackground != null) {
@@ -179,6 +120,7 @@
 
             super.onCreate(surfaceHolder);
 
+            //noinspection ConstantConditions
             mDefaultDisplay = getSystemService(WindowManager.class).getDefaultDisplay();
             setOffsetNotificationsEnabled(false);
 
@@ -199,7 +141,7 @@
             // Load background image dimensions, if we haven't saved them yet
             if (mBackgroundWidth <= 0 || mBackgroundHeight <= 0) {
                 // Need to load the image to get dimensions
-                loadWallpaper(forDraw, false /* needsReset */);
+                loadWallpaper(forDraw);
                 if (DEBUG) {
                     Log.d(TAG, "Reloading, redoing updateSurfaceSize later.");
                 }
@@ -210,16 +152,13 @@
             int surfaceWidth = Math.max(displayInfo.logicalWidth, mBackgroundWidth);
             int surfaceHeight = Math.max(displayInfo.logicalHeight, mBackgroundHeight);
 
-            if (FIXED_SIZED_SURFACE) {
-                // Used a fixed size surface, because we are special.  We can do
-                // this because we know the current design of window animations doesn't
-                // cause this to break.
-                surfaceHolder.setFixedSize(surfaceWidth, surfaceHeight);
-                mLastRequestedWidth = surfaceWidth;
-                mLastRequestedHeight = surfaceHeight;
-            } else {
-                surfaceHolder.setSizeFromLayout();
-            }
+            // Used a fixed size surface, because we are special.  We can do
+            // this because we know the current design of window animations doesn't
+            // cause this to break.
+            surfaceHolder.setFixedSize(surfaceWidth, surfaceHeight);
+            mLastRequestedWidth = surfaceWidth;
+            mLastRequestedHeight = surfaceHeight;
+
             return hasWallpaper;
         }
 
@@ -300,6 +239,13 @@
                 Log.d(TAG, "onSurfaceRedrawNeeded");
             }
             super.onSurfaceRedrawNeeded(holder);
+            // At the end of this method we should have drawn into the surface.
+            // This means that the bitmap should be loaded synchronously if
+            // it was already unloaded.
+            if (mBackground == null) {
+                updateBitmap(mWallpaperManager.getBitmap(true /* hardware */));
+            }
+            mSurfaceRedrawNeeded = true;
             drawFrame();
         }
 
@@ -336,7 +282,8 @@
                 boolean surfaceDimensionsChanged = dw != mLastSurfaceWidth
                         || dh != mLastSurfaceHeight;
 
-                boolean redrawNeeded = surfaceDimensionsChanged || newRotation != mLastRotation;
+                boolean redrawNeeded = surfaceDimensionsChanged || newRotation != mLastRotation
+                        || mSurfaceRedrawNeeded;
                 if (!redrawNeeded && !mOffsetsChanged) {
                     if (DEBUG) {
                         Log.d(TAG, "Suppressed drawFrame since redraw is not needed "
@@ -345,40 +292,24 @@
                     return;
                 }
                 mLastRotation = newRotation;
+                mSurfaceRedrawNeeded = false;
 
                 // Load bitmap if it is not yet loaded
                 if (mBackground == null) {
-                    if (DEBUG) {
-                        Log.d(TAG, "Reloading bitmap: mBackground, bgw, bgh, dw, dh = " +
-                                mBackground + ", " +
-                                ((mBackground == null) ? 0 : mBackground.getWidth()) + ", " +
-                                ((mBackground == null) ? 0 : mBackground.getHeight()) + ", " +
-                                dw + ", " + dh);
-                    }
-                    loadWallpaper(true /* needDraw */, true /* needReset */);
+                    loadWallpaper(true);
                     if (DEBUG) {
                         Log.d(TAG, "Reloading, resuming draw later");
                     }
                     return;
                 }
 
-                // Center the scaled image
+                // Left align the scaled image
                 mScale = Math.max(1f, Math.max(dw / (float) mBackground.getWidth(),
                         dh / (float) mBackground.getHeight()));
-                final int availw = dw - (int) (mBackground.getWidth() * mScale);
-                final int availh = dh - (int) (mBackground.getHeight() * mScale);
-                int xPixels = availw / 2;
-                int yPixels = availh / 2;
-
-                // Adjust the image for xOffset/yOffset values. If window manager is handling offsets,
-                // mXOffset and mYOffset are set to 0.5f by default and therefore xPixels and yPixels
-                // will remain unchanged
-                final int availwUnscaled = dw - mBackground.getWidth();
-                final int availhUnscaled = dh - mBackground.getHeight();
-                if (availwUnscaled < 0)
-                    xPixels += (int) (availwUnscaled * (mXOffset - .5f) + .5f);
-                if (availhUnscaled < 0)
-                    yPixels += (int) (availhUnscaled * (mYOffset - .5f) + .5f);
+                final int availw = (int) (mBackground.getWidth() * mScale) - dw;
+                final int availh = (int) (mBackground.getHeight() * mScale) - dh;
+                int xPixels = (int) (availw * mXOffset);
+                int yPixels = (int) (availh * mYOffset);
 
                 mOffsetsChanged = false;
                 if (surfaceDimensionsChanged) {
@@ -399,21 +330,7 @@
                     Log.d(TAG, "Redrawing wallpaper");
                 }
 
-                if (mIsHwAccelerated) {
-                    if (!drawWallpaperWithOpenGL(sh, availw, availh, xPixels, yPixels)) {
-                        drawWallpaperWithCanvas(sh, availw, availh, xPixels, yPixels);
-                    }
-                } else {
-                    drawWallpaperWithCanvas(sh, availw, availh, xPixels, yPixels);
-                    if (FIXED_SIZED_SURFACE) {
-                        // If the surface is fixed-size, we should only need to
-                        // draw it once and then we'll let the window manager
-                        // position it appropriately.  As such, we no longer needed
-                        // the loaded bitmap.  Yay!
-                        // hw-accelerated renderer retains bitmap for faster rotation
-                        unloadWallpaper(false /* forgetSize */);
-                    }
-                }
+                drawWallpaperWithCanvas(sh, availw, availh, xPixels, yPixels);
             } finally {
                 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
             }
@@ -428,28 +345,20 @@
          *
          * If {@param needsReset} is set also clears the cache in WallpaperManager first.
          */
-        private void loadWallpaper(boolean needsDraw, boolean needsReset) {
+        private void loadWallpaper(boolean needsDraw) {
             mNeedsDrawAfterLoadingWallpaper |= needsDraw;
             if (mLoader != null) {
-                if (needsReset) {
-                    mLoader.cancel(false /* interrupt */);
-                    mLoader = null;
-                } else {
-                    if (DEBUG) {
-                        Log.d(TAG, "Skipping loadWallpaper, already in flight ");
-                    }
-                    return;
+                if (DEBUG) {
+                    Log.d(TAG, "Skipping loadWallpaper, already in flight ");
                 }
+                return;
             }
             mLoader = new AsyncTask<Void, Void, Bitmap>() {
                 @Override
                 protected Bitmap doInBackground(Void... params) {
                     Throwable exception;
                     try {
-                        if (needsReset) {
-                            mWallpaperManager.forgetLoadedWallpaper();
-                        }
-                        return mWallpaperManager.getBitmap();
+                        return mWallpaperManager.getBitmap(true /* hardware */);
                     } catch (RuntimeException | OutOfMemoryError e) {
                         exception = e;
                     }
@@ -458,48 +367,33 @@
                         return null;
                     }
 
-                    if (exception != null) {
-                        // Note that if we do fail at this, and the default wallpaper can't
-                        // be loaded, we will go into a cycle.  Don't do a build where the
-                        // default wallpaper can't be loaded.
-                        Log.w(TAG, "Unable to load wallpaper!", exception);
-                        try {
-                            mWallpaperManager.clear();
-                        } catch (IOException ex) {
-                            // now we're really screwed.
-                            Log.w(TAG, "Unable reset to default wallpaper!", ex);
-                        }
+                    // Note that if we do fail at this, and the default wallpaper can't
+                    // be loaded, we will go into a cycle.  Don't do a build where the
+                    // default wallpaper can't be loaded.
+                    Log.w(TAG, "Unable to load wallpaper!", exception);
+                    try {
+                        mWallpaperManager.clear();
+                    } catch (IOException ex) {
+                        // now we're really screwed.
+                        Log.w(TAG, "Unable reset to default wallpaper!", ex);
+                    }
 
-                        if (isCancelled()) {
-                            return null;
-                        }
+                    if (isCancelled()) {
+                        return null;
+                    }
 
-                        try {
-                            return mWallpaperManager.getBitmap();
-                        } catch (RuntimeException | OutOfMemoryError e) {
-                            Log.w(TAG, "Unable to load default wallpaper!", e);
-                        }
+                    try {
+                        return mWallpaperManager.getBitmap(true /* hardware */);
+                    } catch (RuntimeException | OutOfMemoryError e) {
+                        Log.w(TAG, "Unable to load default wallpaper!", e);
                     }
                     return null;
                 }
 
                 @Override
                 protected void onPostExecute(Bitmap b) {
-                    mBackground = null;
-                    mBackgroundWidth = -1;
-                    mBackgroundHeight = -1;
+                    updateBitmap(b);
 
-                    if (b != null) {
-                        mBackground = b;
-                        mBackgroundWidth = mBackground.getWidth();
-                        mBackgroundHeight = mBackground.getHeight();
-                    }
-
-                    if (DEBUG) {
-                        Log.d(TAG, "Wallpaper loaded: " + mBackground);
-                    }
-                    updateSurfaceSize(getSurfaceHolder(), getDefaultDisplayInfo(),
-                            false /* forDraw */);
                     if (mNeedsDrawAfterLoadingWallpaper) {
                         drawFrame();
                     }
@@ -510,6 +404,24 @@
             }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
         }
 
+        private void updateBitmap(Bitmap bitmap) {
+            mBackground = null;
+            mBackgroundWidth = -1;
+            mBackgroundHeight = -1;
+
+            if (bitmap != null) {
+                mBackground = bitmap;
+                mBackgroundWidth = mBackground.getWidth();
+                mBackgroundHeight = mBackground.getHeight();
+            }
+
+            if (DEBUG) {
+                Log.d(TAG, "Wallpaper loaded: " + mBackground);
+            }
+            updateSurfaceSize(getSurfaceHolder(), getDefaultDisplayInfo(),
+                    false /* forDraw */);
+        }
+
         private void unloadWallpaper(boolean forgetSize) {
             if (mLoader != null) {
                 mLoader.cancel(false);
@@ -564,7 +476,7 @@
         }
 
         private void drawWallpaperWithCanvas(SurfaceHolder sh, int w, int h, int left, int top) {
-            Canvas c = sh.lockCanvas();
+            Canvas c = sh.lockHardwareCanvas();
             if (c != null) {
                 try {
                     if (DEBUG) {
@@ -590,278 +502,5 @@
                 }
             }
         }
-
-        private boolean drawWallpaperWithOpenGL(SurfaceHolder sh, int w, int h, int left, int top) {
-            if (!initGL(sh)) return false;
-
-            final float right = left + mBackground.getWidth() * mScale;
-            final float bottom = top + mBackground.getHeight() * mScale;
-
-            final Rect frame = sh.getSurfaceFrame();
-            final Matrix4f ortho = new Matrix4f();
-            ortho.loadOrtho(0.0f, frame.width(), frame.height(), 0.0f, -1.0f, 1.0f);
-
-            final FloatBuffer triangleVertices = createMesh(left, top, right, bottom);
-
-            final int texture = loadTexture(mBackground);
-            final int program = buildProgram(sSimpleVS, sSimpleFS);
-
-            final int attribPosition = glGetAttribLocation(program, "position");
-            final int attribTexCoords = glGetAttribLocation(program, "texCoords");
-            final int uniformTexture = glGetUniformLocation(program, "texture");
-            final int uniformProjection = glGetUniformLocation(program, "projection");
-
-            checkGlError();
-
-            glViewport(0, 0, frame.width(), frame.height());
-            glBindTexture(GL_TEXTURE_2D, texture);
-
-            glUseProgram(program);
-            glEnableVertexAttribArray(attribPosition);
-            glEnableVertexAttribArray(attribTexCoords);
-            glUniform1i(uniformTexture, 0);
-            glUniformMatrix4fv(uniformProjection, 1, false, ortho.getArray(), 0);
-
-            checkGlError();
-
-            if (w > 0 || h > 0) {
-                glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
-                glClear(GL_COLOR_BUFFER_BIT);
-            }
-
-            // drawQuad
-            triangleVertices.position(TRIANGLE_VERTICES_DATA_POS_OFFSET);
-            glVertexAttribPointer(attribPosition, 3, GL_FLOAT, false,
-                    TRIANGLE_VERTICES_DATA_STRIDE_BYTES, triangleVertices);
-
-            triangleVertices.position(TRIANGLE_VERTICES_DATA_UV_OFFSET);
-            glVertexAttribPointer(attribTexCoords, 3, GL_FLOAT, false,
-                    TRIANGLE_VERTICES_DATA_STRIDE_BYTES, triangleVertices);
-
-            glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
-
-            boolean status = mEgl.eglSwapBuffers(mEglDisplay, mEglSurface);
-            checkEglError();
-
-            finishGL(texture, program);
-
-            return status;
-        }
-
-        private FloatBuffer createMesh(int left, int top, float right, float bottom) {
-            final float[] verticesData = {
-                    // X, Y, Z, U, V
-                     left,  bottom, 0.0f, 0.0f, 1.0f,
-                     right, bottom, 0.0f, 1.0f, 1.0f,
-                     left,  top,    0.0f, 0.0f, 0.0f,
-                     right, top,    0.0f, 1.0f, 0.0f,
-            };
-
-            final int bytes = verticesData.length * FLOAT_SIZE_BYTES;
-            final FloatBuffer triangleVertices = ByteBuffer.allocateDirect(bytes).order(
-                    ByteOrder.nativeOrder()).asFloatBuffer();
-            triangleVertices.put(verticesData).position(0);
-            return triangleVertices;
-        }
-
-        private int loadTexture(Bitmap bitmap) {
-            int[] textures = new int[1];
-
-            glActiveTexture(GL_TEXTURE0);
-            glGenTextures(1, textures, 0);
-            checkGlError();
-
-            int texture = textures[0];
-            glBindTexture(GL_TEXTURE_2D, texture);
-            checkGlError();
-
-            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
-            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
-
-            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
-            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
-
-            GLUtils.texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bitmap, GL_UNSIGNED_BYTE, 0);
-            checkGlError();
-
-            return texture;
-        }
-
-        private int buildProgram(String vertex, String fragment) {
-            int vertexShader = buildShader(vertex, GL_VERTEX_SHADER);
-            if (vertexShader == 0) return 0;
-
-            int fragmentShader = buildShader(fragment, GL_FRAGMENT_SHADER);
-            if (fragmentShader == 0) return 0;
-
-            int program = glCreateProgram();
-            glAttachShader(program, vertexShader);
-            glAttachShader(program, fragmentShader);
-            glLinkProgram(program);
-            checkGlError();
-
-            glDeleteShader(vertexShader);
-            glDeleteShader(fragmentShader);
-
-            int[] status = new int[1];
-            glGetProgramiv(program, GL_LINK_STATUS, status, 0);
-            if (status[0] != GL_TRUE) {
-                String error = glGetProgramInfoLog(program);
-                Log.d(GL_LOG_TAG, "Error while linking program:\n" + error);
-                glDeleteProgram(program);
-                return 0;
-            }
-
-            return program;
-        }
-
-        private int buildShader(String source, int type) {
-            int shader = glCreateShader(type);
-
-            glShaderSource(shader, source);
-            checkGlError();
-
-            glCompileShader(shader);
-            checkGlError();
-
-            int[] status = new int[1];
-            glGetShaderiv(shader, GL_COMPILE_STATUS, status, 0);
-            if (status[0] != GL_TRUE) {
-                String error = glGetShaderInfoLog(shader);
-                Log.d(GL_LOG_TAG, "Error while compiling shader:\n" + error);
-                glDeleteShader(shader);
-                return 0;
-            }
-
-            return shader;
-        }
-
-        private void checkEglError() {
-            int error = mEgl.eglGetError();
-            if (error != EGL_SUCCESS) {
-                Log.w(GL_LOG_TAG, "EGL error = " + GLUtils.getEGLErrorString(error));
-            }
-        }
-
-        private void checkGlError() {
-            int error = glGetError();
-            if (error != GL_NO_ERROR) {
-                Log.w(GL_LOG_TAG, "GL error = 0x" + Integer.toHexString(error), new Throwable());
-            }
-        }
-
-        private void finishGL(int texture, int program) {
-            int[] textures = new int[1];
-            textures[0] = texture;
-            glDeleteTextures(1, textures, 0);
-            glDeleteProgram(program);
-            mEgl.eglMakeCurrent(mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
-            mEgl.eglDestroySurface(mEglDisplay, mEglSurface);
-            mEgl.eglDestroyContext(mEglDisplay, mEglContext);
-            mEgl.eglTerminate(mEglDisplay);
-        }
-
-        private boolean initGL(SurfaceHolder surfaceHolder) {
-            mEgl = (EGL10) EGLContext.getEGL();
-
-            mEglDisplay = mEgl.eglGetDisplay(EGL_DEFAULT_DISPLAY);
-            if (mEglDisplay == EGL_NO_DISPLAY) {
-                throw new RuntimeException("eglGetDisplay failed " +
-                        GLUtils.getEGLErrorString(mEgl.eglGetError()));
-            }
-
-            int[] version = new int[2];
-            if (!mEgl.eglInitialize(mEglDisplay, version)) {
-                throw new RuntimeException("eglInitialize failed " +
-                        GLUtils.getEGLErrorString(mEgl.eglGetError()));
-            }
-
-            mEglConfig = chooseEglConfig();
-            if (mEglConfig == null) {
-                throw new RuntimeException("eglConfig not initialized");
-            }
-
-            mEglContext = createContext(mEgl, mEglDisplay, mEglConfig);
-            if (mEglContext == EGL_NO_CONTEXT) {
-                throw new RuntimeException("createContext failed " +
-                        GLUtils.getEGLErrorString(mEgl.eglGetError()));
-            }
-
-            int attribs[] = {
-                EGL_WIDTH, 1,
-                EGL_HEIGHT, 1,
-                EGL_NONE
-            };
-            EGLSurface tmpSurface = mEgl.eglCreatePbufferSurface(mEglDisplay, mEglConfig, attribs);
-            mEgl.eglMakeCurrent(mEglDisplay, tmpSurface, tmpSurface, mEglContext);
-
-            int[] maxSize = new int[1];
-            Rect frame = surfaceHolder.getSurfaceFrame();
-            glGetIntegerv(GL_MAX_TEXTURE_SIZE, maxSize, 0);
-
-            mEgl.eglMakeCurrent(mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
-            mEgl.eglDestroySurface(mEglDisplay, tmpSurface);
-
-            if(frame.width() > maxSize[0] || frame.height() > maxSize[0]) {
-                mEgl.eglDestroyContext(mEglDisplay, mEglContext);
-                mEgl.eglTerminate(mEglDisplay);
-                Log.e(GL_LOG_TAG, "requested  texture size " +
-                    frame.width() + "x" + frame.height() + " exceeds the support maximum of " +
-                    maxSize[0] + "x" + maxSize[0]);
-                return false;
-            }
-
-            mEglSurface = mEgl.eglCreateWindowSurface(mEglDisplay, mEglConfig, surfaceHolder, null);
-            if (mEglSurface == null || mEglSurface == EGL_NO_SURFACE) {
-                int error = mEgl.eglGetError();
-                if (error == EGL_BAD_NATIVE_WINDOW || error == EGL_BAD_ALLOC) {
-                    Log.e(GL_LOG_TAG, "createWindowSurface returned " +
-                                         GLUtils.getEGLErrorString(error) + ".");
-                    return false;
-                }
-                throw new RuntimeException("createWindowSurface failed " +
-                        GLUtils.getEGLErrorString(error));
-            }
-
-            if (!mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext)) {
-                throw new RuntimeException("eglMakeCurrent failed " +
-                        GLUtils.getEGLErrorString(mEgl.eglGetError()));
-            }
-
-            return true;
-        }
-
-
-        EGLContext createContext(EGL10 egl, EGLDisplay eglDisplay, EGLConfig eglConfig) {
-            int[] attrib_list = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE };
-            return egl.eglCreateContext(eglDisplay, eglConfig, EGL_NO_CONTEXT, attrib_list);
-        }
-
-        private EGLConfig chooseEglConfig() {
-            int[] configsCount = new int[1];
-            EGLConfig[] configs = new EGLConfig[1];
-            int[] configSpec = getConfig();
-            if (!mEgl.eglChooseConfig(mEglDisplay, configSpec, configs, 1, configsCount)) {
-                throw new IllegalArgumentException("eglChooseConfig failed " +
-                        GLUtils.getEGLErrorString(mEgl.eglGetError()));
-            } else if (configsCount[0] > 0) {
-                return configs[0];
-            }
-            return null;
-        }
-
-        private int[] getConfig() {
-            return new int[] {
-                    EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
-                    EGL_RED_SIZE, 8,
-                    EGL_GREEN_SIZE, 8,
-                    EGL_BLUE_SIZE, 8,
-                    EGL_ALPHA_SIZE, 0,
-                    EGL_DEPTH_SIZE, 0,
-                    EGL_STENCIL_SIZE, 0,
-                    EGL_CONFIG_CAVEAT, EGL_NONE,
-                    EGL_NONE
-            };
-        }
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/LockscreenWallpaper.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/LockscreenWallpaper.java
index 87f5ca7..40ddf5b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/LockscreenWallpaper.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/LockscreenWallpaper.java
@@ -124,8 +124,8 @@
         } else {
             if (selectedUser != null) {
                 // Show the selected user's static wallpaper.
-                return LoaderResult.success(
-                        mWallpaperManager.getBitmapAsUser(selectedUser.getIdentifier()));
+                return LoaderResult.success(mWallpaperManager.getBitmapAsUser(
+                        selectedUser.getIdentifier(), true /* hardware */));
 
             } else {
                 // When there is no selected user, show the system wallpaper
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/RecentTasks.java b/services/core/java/com/android/server/am/RecentTasks.java
index 8fef6be..78274bd 100644
--- a/services/core/java/com/android/server/am/RecentTasks.java
+++ b/services/core/java/com/android/server/am/RecentTasks.java
@@ -427,8 +427,7 @@
     }
 
     void removeTasksByPackageName(String packageName, int userId) {
-        final int size = mTasks.size();
-        for (int i = 0; i < size; i++) {
+        for (int i = mTasks.size() - 1; i >= 0; --i) {
             final TaskRecord tr = mTasks.get(i);
             final String taskPackageName =
                     tr.getBaseIntent().getComponent().getPackageName();
@@ -441,8 +440,7 @@
 
     void cleanupDisabledPackageTasksLocked(String packageName, Set<String> filterByClasses,
             int userId) {
-        final int size = mTasks.size();
-        for (int i = 0; i < size; i++) {
+        for (int i = mTasks.size() - 1; i >= 0; --i) {
             final TaskRecord tr = mTasks.get(i);
             if (userId != UserHandle.USER_ALL && tr.userId != userId) {
                 continue;
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/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: [