Merge "Fix NPE on ShutdownCheckPoints"
diff --git a/core/api/system-current.txt b/core/api/system-current.txt
index 6d42bb8..712ac94 100644
--- a/core/api/system-current.txt
+++ b/core/api/system-current.txt
@@ -393,6 +393,8 @@
   }
 
   public static final class R.bool {
+    field public static final int config_enableDefaultNotes;
+    field public static final int config_enableDefaultNotesForWorkProfile;
     field public static final int config_enableQrCodeScannerOnLockScreen = 17891336; // 0x1110008
     field public static final int config_safetyProtectionEnabled;
     field public static final int config_sendPackageName = 17891328; // 0x1110000
@@ -429,6 +431,7 @@
     field public static final int config_defaultCallRedirection = 17039397; // 0x1040025
     field public static final int config_defaultCallScreening = 17039398; // 0x1040026
     field public static final int config_defaultDialer = 17039395; // 0x1040023
+    field public static final int config_defaultNotes;
     field public static final int config_defaultSms = 17039396; // 0x1040024
     field public static final int config_devicePolicyManagement = 17039421; // 0x104003d
     field public static final int config_feedbackIntentExtraKey = 17039391; // 0x104001f
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index 184f869..2310367 100644
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -2135,6 +2135,12 @@
     <string name="config_defaultAutomotiveNavigation" translatable="false"></string>
     <!-- The name of the package that will hold the system wear health service role. -->
     <string name="config_systemWearHealthService" translatable="false"></string>
+    <!-- The name of the package that will hold the default notes role. -->
+    <string name="config_defaultNotes" translatable="false"></string>
+    <!-- Whether the default notes role should be enabled. -->
+    <bool name="config_enableDefaultNotes">false</bool>
+    <!-- Whether the default notes role for work profile should be enabled. -->
+    <bool name="config_enableDefaultNotesForWorkProfile">false</bool>
 
     <!-- The name of the package that will handle updating the device management role. -->
     <string name="config_devicePolicyManagementUpdater" translatable="false"></string>
diff --git a/core/res/res/values/public-staging.xml b/core/res/res/values/public-staging.xml
index 97feaac..dfd4d9a 100644
--- a/core/res/res/values/public-staging.xml
+++ b/core/res/res/values/public-staging.xml
@@ -139,6 +139,8 @@
   <staging-public-group type="string" first-id="0x01cb0000">
     <!-- @hide @SystemApi -->
     <public name="config_systemWearHealthService" />
+    <!-- @hide @SystemApi -->
+    <public name="config_defaultNotes" />
   </staging-public-group>
 
   <staging-public-group type="dimen" first-id="0x01ca0000">
@@ -182,6 +184,10 @@
   <staging-public-group type="bool" first-id="0x01be0000">
     <!-- @hide @SystemApi -->
     <public name="config_safetyProtectionEnabled" />
+    <!-- @hide @SystemApi -->
+    <public name="config_enableDefaultNotes" />
+    <!-- @hide @SystemApi -->
+    <public name="config_enableDefaultNotesForWorkProfile" />
   </staging-public-group>
 
   <staging-public-group type="fraction" first-id="0x01bd0000">
diff --git a/keystore/java/android/security/keystore2/AndroidKeyStoreProvider.java b/keystore/java/android/security/keystore2/AndroidKeyStoreProvider.java
index 9947d34..c55a781 100644
--- a/keystore/java/android/security/keystore2/AndroidKeyStoreProvider.java
+++ b/keystore/java/android/security/keystore2/AndroidKeyStoreProvider.java
@@ -38,6 +38,7 @@
 import java.security.Security;
 import java.security.Signature;
 import java.security.UnrecoverableKeyException;
+import java.security.cert.X509Certificate;
 import java.security.interfaces.ECPublicKey;
 import java.security.interfaces.RSAPublicKey;
 
@@ -221,7 +222,14 @@
         }
         final byte[] x509PublicCert = metadata.certificate;
 
-        PublicKey publicKey = AndroidKeyStoreSpi.toCertificate(x509PublicCert).getPublicKey();
+        final X509Certificate parsedX509Certificate =
+                AndroidKeyStoreSpi.toCertificate(x509PublicCert);
+        if (parsedX509Certificate == null) {
+            throw new UnrecoverableKeyException("Failed to parse the X.509 certificate containing"
+                   + " the public key. This likely indicates a hardware problem.");
+        }
+
+        PublicKey publicKey = parsedX509Certificate.getPublicKey();
 
         String jcaKeyAlgorithm = publicKey.getAlgorithm();
 
diff --git a/media/jni/android_media_tv_Tuner.cpp b/media/jni/android_media_tv_Tuner.cpp
index 58078cf..aacea3d 100644
--- a/media/jni/android_media_tv_Tuner.cpp
+++ b/media/jni/android_media_tv_Tuner.cpp
@@ -609,6 +609,7 @@
     jobject obj = env->NewObject(eventClazz, eventInit, tableId, version, sectionNum, dataLength);
     env->SetObjectArrayElement(arr, size, obj);
     env->DeleteLocalRef(obj);
+    env->DeleteLocalRef(eventClazz);
 }
 
 void FilterClientCallbackImpl::getMediaEvent(jobjectArray &arr, const int size,
@@ -639,6 +640,7 @@
 
         audioDescriptor = env->NewObject(adClazz, adInit, adFade, adPan, versionTextTag,
                                          adGainCenter, adGainFront, adGainSurround);
+        env->DeleteLocalRef(adClazz);
     }
 
     jlong dataLength = mediaEvent.dataLength;
@@ -685,6 +687,7 @@
         env->DeleteLocalRef(audioDescriptor);
     }
     env->DeleteLocalRef(obj);
+    env->DeleteLocalRef(eventClazz);
 }
 
 void FilterClientCallbackImpl::getPesEvent(jobjectArray &arr, const int size,
@@ -701,6 +704,7 @@
     jobject obj = env->NewObject(eventClazz, eventInit, streamId, dataLength, mpuSequenceNumber);
     env->SetObjectArrayElement(arr, size, obj);
     env->DeleteLocalRef(obj);
+    env->DeleteLocalRef(eventClazz);
 }
 
 void FilterClientCallbackImpl::getTsRecordEvent(jobjectArray &arr, const int size,
@@ -741,6 +745,7 @@
             env->NewObject(eventClazz, eventInit, jpid, ts, sc, byteNumber, pts, firstMbInSlice);
     env->SetObjectArrayElement(arr, size, obj);
     env->DeleteLocalRef(obj);
+    env->DeleteLocalRef(eventClazz);
 }
 
 void FilterClientCallbackImpl::getMmtpRecordEvent(jobjectArray &arr, const int size,
@@ -762,6 +767,7 @@
                                  mpuSequenceNumber, pts, firstMbInSlice, tsIndexMask);
     env->SetObjectArrayElement(arr, size, obj);
     env->DeleteLocalRef(obj);
+    env->DeleteLocalRef(eventClazz);
 }
 
 void FilterClientCallbackImpl::getDownloadEvent(jobjectArray &arr, const int size,
@@ -782,6 +788,7 @@
                                  itemFragmentIndex, lastItemFragmentIndex, dataLength);
     env->SetObjectArrayElement(arr, size, obj);
     env->DeleteLocalRef(obj);
+    env->DeleteLocalRef(eventClazz);
 }
 
 void FilterClientCallbackImpl::getIpPayloadEvent(jobjectArray &arr, const int size,
@@ -795,6 +802,7 @@
     jobject obj = env->NewObject(eventClazz, eventInit, dataLength);
     env->SetObjectArrayElement(arr, size, obj);
     env->DeleteLocalRef(obj);
+    env->DeleteLocalRef(eventClazz);
 }
 
 void FilterClientCallbackImpl::getTemiEvent(jobjectArray &arr, const int size,
@@ -815,6 +823,7 @@
     env->SetObjectArrayElement(arr, size, obj);
     env->DeleteLocalRef(array);
     env->DeleteLocalRef(obj);
+    env->DeleteLocalRef(eventClazz);
 }
 
 void FilterClientCallbackImpl::getScramblingStatusEvent(jobjectArray &arr, const int size,
@@ -829,6 +838,7 @@
     jobject obj = env->NewObject(eventClazz, eventInit, scramblingStatus);
     env->SetObjectArrayElement(arr, size, obj);
     env->DeleteLocalRef(obj);
+    env->DeleteLocalRef(eventClazz);
 }
 
 void FilterClientCallbackImpl::getIpCidChangeEvent(jobjectArray &arr, const int size,
@@ -842,6 +852,7 @@
     jobject obj = env->NewObject(eventClazz, eventInit, cid);
     env->SetObjectArrayElement(arr, size, obj);
     env->DeleteLocalRef(obj);
+    env->DeleteLocalRef(eventClazz);
 }
 
 void FilterClientCallbackImpl::getRestartEvent(jobjectArray &arr, const int size,
@@ -854,6 +865,7 @@
     jobject obj = env->NewObject(eventClazz, eventInit, startId);
     env->SetObjectArrayElement(arr, size, obj);
     env->DeleteLocalRef(obj);
+    env->DeleteLocalRef(eventClazz);
 }
 
 void FilterClientCallbackImpl::onFilterEvent(const vector<DemuxFilterEvent> &events) {
@@ -952,6 +964,7 @@
               "Filter object has been freed. Ignoring callback.");
     }
     env->DeleteLocalRef(array);
+    env->DeleteLocalRef(eventClazz);
 }
 
 void FilterClientCallbackImpl::onFilterStatus(const DemuxFilterStatus status) {
@@ -1058,6 +1071,7 @@
         executeOnScanMessage(env, clazz, frontend, type, message);
         env->DeleteLocalRef(frontend);
     }
+    env->DeleteLocalRef(clazz);
 }
 
 void FrontendClientCallbackImpl::executeOnScanMessage(
@@ -1184,6 +1198,7 @@
                                                  "Atsc3PlpInfo;)V"),
                                 array);
             env->DeleteLocalRef(array);
+            env->DeleteLocalRef(plpClazz);
             break;
         }
         case FrontendScanMessageType::MODULATION: {
@@ -2195,6 +2210,7 @@
                                        static_cast<long>(s.get<FrontendStatus::Tag::innerFec>()));
                 env->SetObjectField(statusObj, field, newLongObj);
                 env->DeleteLocalRef(newLongObj);
+                env->DeleteLocalRef(longClazz);
                 break;
             }
             case FrontendStatus::Tag::modulationStatus: {
@@ -2360,6 +2376,7 @@
 
                 env->SetObjectField(statusObj, field, valObj);
                 env->DeleteLocalRef(valObj);
+                env->DeleteLocalRef(plpClazz);
                 break;
             }
             case FrontendStatus::Tag::modulations: {
@@ -2770,6 +2787,7 @@
 
                 env->SetObjectField(statusObj, field, valObj);
                 env->DeleteLocalRef(valObj);
+                env->DeleteLocalRef(plpClazz);
                 break;
             }
         }
diff --git a/packages/SettingsLib/res/values/strings.xml b/packages/SettingsLib/res/values/strings.xml
index 2845916..8508878 100644
--- a/packages/SettingsLib/res/values/strings.xml
+++ b/packages/SettingsLib/res/values/strings.xml
@@ -1368,7 +1368,7 @@
     <string name="user_add_user_message_long">You can share this device with other people by creating additional users. Each user has their own space, which they can customize with apps, wallpaper, and so on. Users can also adjust device settings like Wi\u2011Fi that affect everyone.\n\nWhen you add a new user, that person needs to set up their space.\n\nAny user can update apps for all other users. Accessibility settings and services may not transfer to the new user.</string>
     <!-- Message for add user confirmation dialog - short version. [CHAR LIMIT=none] -->
     <string name="user_add_user_message_short">When you add a new user, that person needs to set up their space.\n\nAny user can update apps for all other users. </string>
-    <!-- Title for grant user admin privileges dialog [CHAR LIMIT=30] -->
+    <!-- Title for grant user admin privileges dialog [CHAR LIMIT=65] -->
     <string name="user_grant_admin_title">Give this user admin privileges?</string>
     <!-- Message for grant admin privileges dialog. [CHAR LIMIT=none] -->
     <string name="user_grant_admin_message">As an admin, they will be able to manage other users, modify device settings and factory reset the device.</string>
diff --git a/services/autofill/java/com/android/server/autofill/Session.java b/services/autofill/java/com/android/server/autofill/Session.java
index b3f8af5..81fbd78 100644
--- a/services/autofill/java/com/android/server/autofill/Session.java
+++ b/services/autofill/java/com/android/server/autofill/Session.java
@@ -4281,6 +4281,7 @@
         if (mContexts == null) {
             mContexts = new ArrayList<>(1);
         }
+        mContexts.add(new FillContext(requestId, new AssistStructure(), mCurrentViewId));
 
         if (inlineSuggestionsRequest != null && !inlineSuggestionsRequest.isClientSupported()) {
             inlineSuggestionsRequest = null;
diff --git a/services/core/java/com/android/server/display/DisplayPowerController2.java b/services/core/java/com/android/server/display/DisplayPowerController2.java
index 234a46c..09136b0 100644
--- a/services/core/java/com/android/server/display/DisplayPowerController2.java
+++ b/services/core/java/com/android/server/display/DisplayPowerController2.java
@@ -267,10 +267,12 @@
     // Must only be accessed on the handler thread.
     private DisplayPowerState mPowerState;
 
+
+
     // The currently active screen on unblocker.  This field is non-null whenever
     // we are waiting for a callback to release it and unblock the screen.
-    private WindowManagerPolicy.ScreenOnListener mPendingScreenOnUnblocker;
-    private WindowManagerPolicy.ScreenOffListener mPendingScreenOffUnblocker;
+    private ScreenOnUnblocker mPendingScreenOnUnblocker;
+    private ScreenOffUnblocker mPendingScreenOffUnblocker;
 
     // True if we were in the process of turning off the screen.
     // This allows us to recover more gracefully from situations where we abort
@@ -1756,9 +1758,7 @@
     private void blockScreenOn() {
         if (mPendingScreenOnUnblocker == null) {
             Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, SCREEN_ON_BLOCKED_TRACE_NAME, 0);
-            mPendingScreenOnUnblocker =  () -> {
-                mHandler.obtainMessage(MSG_SCREEN_ON_UNBLOCKED, this).sendToTarget();
-            };
+            mPendingScreenOnUnblocker = new ScreenOnUnblocker();
             mScreenOnBlockStartRealTime = SystemClock.elapsedRealtime();
             Slog.i(mTag, "Blocking screen on until initial contents have been drawn.");
         }
@@ -1776,9 +1776,7 @@
     private void blockScreenOff() {
         if (mPendingScreenOffUnblocker == null) {
             Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, SCREEN_OFF_BLOCKED_TRACE_NAME, 0);
-            mPendingScreenOffUnblocker = () -> {
-                mHandler.obtainMessage(MSG_SCREEN_ON_UNBLOCKED, this).sendToTarget();
-            };
+            mPendingScreenOffUnblocker = new ScreenOffUnblocker();
             mScreenOffBlockStartRealTime = SystemClock.elapsedRealtime();
             Slog.i(mTag, "Blocking screen off");
         }
@@ -2562,6 +2560,22 @@
         }
     }
 
+    private final class ScreenOnUnblocker implements WindowManagerPolicy.ScreenOnListener {
+        @Override
+        public void onScreenOn() {
+            Message msg = mHandler.obtainMessage(MSG_SCREEN_ON_UNBLOCKED, this);
+            mHandler.sendMessage(msg);
+        }
+    }
+
+    private final class ScreenOffUnblocker implements WindowManagerPolicy.ScreenOffListener {
+        @Override
+        public void onScreenOff() {
+            Message msg = mHandler.obtainMessage(MSG_SCREEN_OFF_UNBLOCKED, this);
+            mHandler.sendMessage(msg);
+        }
+    }
+
     @Override
     public void setAutoBrightnessLoggingEnabled(boolean enabled) {
         if (mAutomaticBrightnessController != null) {
diff --git a/services/core/java/com/android/server/infra/AbstractMasterSystemService.java b/services/core/java/com/android/server/infra/AbstractMasterSystemService.java
index b813995..3ae699b 100644
--- a/services/core/java/com/android/server/infra/AbstractMasterSystemService.java
+++ b/services/core/java/com/android/server/infra/AbstractMasterSystemService.java
@@ -684,6 +684,16 @@
      */
     @GuardedBy("mLock")
     protected List<S> updateCachedServiceListLocked(@UserIdInt int userId, boolean disabled) {
+        if (mServiceNameResolver != null
+                && mServiceNameResolver.isConfiguredInMultipleMode()) {
+            // In multiple mode, we have multiple instances of AbstractPerUserSystemService, per
+            // user where each instance holds information needed to connect to a backend. An
+            // update operation in this mode needs to account for addition, deletion, change
+            // of backends and cannot be executed in the scope of a given
+            // AbstractPerUserSystemService.
+            return updateCachedServiceListMultiModeLocked(userId, disabled);
+        }
+        // isConfiguredInMultipleMode is false
         final List<S> services = getServiceListForUserLocked(userId);
         if (services == null) {
             return null;
@@ -704,6 +714,19 @@
         return services;
     }
 
+    @GuardedBy("mLock")
+    private List<S> updateCachedServiceListMultiModeLocked(int userId, boolean disabled) {
+        final int resolvedUserId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
+                Binder.getCallingUid(), userId, false, false, null,
+                null);
+        List<S> services = new ArrayList<>();
+        synchronized (mLock) {
+            removeCachedServiceListLocked(resolvedUserId);
+            services = getServiceListForUserLocked(userId);
+        }
+        return services;
+    }
+
     /**
      * Gets the Settings property that defines the name of the component name used to bind this
      * service to an external service, or {@code null} when the service is not defined by such
diff --git a/services/core/java/com/android/server/infra/AbstractPerUserSystemService.java b/services/core/java/com/android/server/infra/AbstractPerUserSystemService.java
index ddb19f0..af025c0 100644
--- a/services/core/java/com/android/server/infra/AbstractPerUserSystemService.java
+++ b/services/core/java/com/android/server/infra/AbstractPerUserSystemService.java
@@ -154,7 +154,14 @@
 
         if (mMaster.mServiceNameResolver != null
                 && mMaster.mServiceNameResolver.isConfiguredInMultipleMode()) {
-            updateServiceInfoListLocked();
+            // Update of multi configured mode should always happen in AbstractMasterSystemService
+            // as this class is not aware of the complete list of multiple backends. Since we
+            // should never end up in this state, it is safe to not do anything if we end up here
+            // through a different code path.
+            if (mMaster.debug) {
+                Slog.d(mTag, "Should not end up in updateLocked when "
+                        + "isConfiguredInMultipleMode is true");
+            }
         } else {
             updateServiceInfoLocked();
         }
diff --git a/services/tests/mockingservicestests/src/com/android/server/display/DisplayPowerController2Test.java b/services/tests/mockingservicestests/src/com/android/server/display/DisplayPowerController2Test.java
index 7726b73..f2cba40 100644
--- a/services/tests/mockingservicestests/src/com/android/server/display/DisplayPowerController2Test.java
+++ b/services/tests/mockingservicestests/src/com/android/server/display/DisplayPowerController2Test.java
@@ -16,11 +16,12 @@
 
 package com.android.server.display;
 
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.verify;
+
 import static org.junit.Assert.assertNotNull;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.ArgumentMatchers.isA;
 import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
 import android.content.Context;
diff --git a/services/tests/mockingservicestests/src/com/android/server/display/DisplayPowerControllerTest.java b/services/tests/mockingservicestests/src/com/android/server/display/DisplayPowerControllerTest.java
index f380a7d..4f8cb88 100644
--- a/services/tests/mockingservicestests/src/com/android/server/display/DisplayPowerControllerTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/display/DisplayPowerControllerTest.java
@@ -16,11 +16,13 @@
 
 package com.android.server.display;
 
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.verify;
+
+
 import static org.junit.Assert.assertNotNull;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.ArgumentMatchers.isA;
 import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
 import android.content.Context;