Merge "Remove hidden preconditions, binder usage in Vpn"
diff --git a/core/java/Android.bp b/core/java/Android.bp
index c0a5111..874704e 100644
--- a/core/java/Android.bp
+++ b/core/java/Android.bp
@@ -281,26 +281,6 @@
     },
 }
 
-// Build C++ bindings for OtaDexopt services. Needed by otapreopt_chroot
-aidl_interface {
-    name: "ota_dexopt_aidl_interface",
-    unstable: true,
-    srcs: [
-        "android/content/pm/IOtaDexopt.aidl",
-    ],
-    backend: {
-        java: {
-            sdk_version: "28",
-        },
-        cpp: {
-            enabled: true,
-        },
-        ndk: {
-            enabled: false,
-        },
-    },
-}
-
 // Avoid including Parcelable classes as we don't want to have two copies of
 // Parcelable cross the libraries. This is used by telephony-common (frameworks/opt/telephony)
 // and TeleService app (packages/services/Telephony).
diff --git a/core/java/android/bluetooth/BluetoothGatt.java b/core/java/android/bluetooth/BluetoothGatt.java
index 1d08ddb..b3a7c88 100644
--- a/core/java/android/bluetooth/BluetoothGatt.java
+++ b/core/java/android/bluetooth/BluetoothGatt.java
@@ -75,6 +75,9 @@
     private static final int CONN_STATE_DISCONNECTING = 3;
     private static final int CONN_STATE_CLOSED = 4;
 
+    private static final int WRITE_CHARACTERISTIC_MAX_RETRIES = 5;
+    private static final int WRITE_CHARACTERISTIC_TIME_TO_WAIT = 1000; // milliseconds
+
     private List<BluetoothGattService> mServices;
 
     /** A GATT operation completed successfully */
@@ -127,6 +130,27 @@
     public static final int CONNECTION_PRIORITY_LOW_POWER = 2;
 
     /**
+     * A GATT writeCharacteristic request is started successfully.
+     *
+     * @hide
+     */
+    public static final int GATT_WRITE_REQUEST_SUCCESS = 0;
+
+    /**
+     * A GATT writeCharacteristic request failed to start.
+     *
+     * @hide
+     */
+    public static final int GATT_WRITE_REQUEST_FAIL = 1;
+
+    /**
+     * A GATT writeCharacteristic request is issued to a busy remote device.
+     *
+     * @hide
+     */
+    public static final int GATT_WRITE_REQUEST_BUSY = 2;
+
+    /**
      * No authentication required.
      *
      * @hide
@@ -428,9 +452,19 @@
                         try {
                             final int authReq = (mAuthRetryState == AUTH_RETRY_STATE_IDLE)
                                     ? AUTHENTICATION_NO_MITM : AUTHENTICATION_MITM;
-                            mService.writeCharacteristic(mClientIf, address, handle,
-                                    characteristic.getWriteType(), authReq,
-                                    characteristic.getValue());
+                            int requestStatus = GATT_WRITE_REQUEST_FAIL;
+                            for (int i = 0; i < WRITE_CHARACTERISTIC_MAX_RETRIES; i++) {
+                                requestStatus =  mService.writeCharacteristic(mClientIf, address,
+                                                  handle, characteristic.getWriteType(), authReq,
+                                                  characteristic.getValue());
+                                if (requestStatus != GATT_WRITE_REQUEST_BUSY) {
+                                    break;
+                                }
+                                try {
+                                    Thread.sleep(WRITE_CHARACTERISTIC_TIME_TO_WAIT);
+                                } catch (InterruptedException e) {
+                                }
+                            }
                             mAuthRetryState++;
                             return;
                         } catch (RemoteException e) {
@@ -1228,14 +1262,26 @@
         if (device == null) return false;
 
         synchronized (mDeviceBusyLock) {
-            if (mDeviceBusy) return false;
+            if (mDeviceBusy) {
+              return false;
+            }
             mDeviceBusy = true;
         }
 
+        int requestStatus = GATT_WRITE_REQUEST_FAIL;
         try {
-            mService.writeCharacteristic(mClientIf, device.getAddress(),
+            for (int i = 0; i < WRITE_CHARACTERISTIC_MAX_RETRIES; i++) {
+                requestStatus = mService.writeCharacteristic(mClientIf, device.getAddress(),
                     characteristic.getInstanceId(), characteristic.getWriteType(),
                     AUTHENTICATION_NONE, characteristic.getValue());
+                if (requestStatus != GATT_WRITE_REQUEST_BUSY) {
+                    break;
+                }
+                try {
+                    Thread.sleep(WRITE_CHARACTERISTIC_TIME_TO_WAIT);
+                } catch (InterruptedException e) {
+                }
+            }
         } catch (RemoteException e) {
             Log.e(TAG, "", e);
             synchronized (mDeviceBusyLock) {
@@ -1244,7 +1290,7 @@
             return false;
         }
 
-        return true;
+        return requestStatus == GATT_WRITE_REQUEST_SUCCESS;
     }
 
     /**
diff --git a/keystore/java/android/security/keystore2/AndroidKeyStoreKeyPairGeneratorSpi.java b/keystore/java/android/security/keystore2/AndroidKeyStoreKeyPairGeneratorSpi.java
index c048f3b..2e85b30 100644
--- a/keystore/java/android/security/keystore2/AndroidKeyStoreKeyPairGeneratorSpi.java
+++ b/keystore/java/android/security/keystore2/AndroidKeyStoreKeyPairGeneratorSpi.java
@@ -20,6 +20,7 @@
 import android.annotation.Nullable;
 import android.app.ActivityThread;
 import android.content.Context;
+import android.hardware.security.keymint.EcCurve;
 import android.hardware.security.keymint.KeyParameter;
 import android.hardware.security.keymint.KeyPurpose;
 import android.hardware.security.keymint.SecurityLevel;
@@ -122,6 +123,7 @@
             new HashMap<String, Integer>();
     private static final List<String> SUPPORTED_EC_NIST_CURVE_NAMES = new ArrayList<String>();
     private static final List<Integer> SUPPORTED_EC_NIST_CURVE_SIZES = new ArrayList<Integer>();
+
     static {
         // Aliases for NIST P-224
         SUPPORTED_EC_NIST_CURVE_NAME_TO_SIZE.put("p-224", 224);
@@ -175,12 +177,29 @@
         mOriginalKeymasterAlgorithm = keymasterAlgorithm;
     }
 
+    private @EcCurve int keySize2EcCurve(int keySizeBits)
+            throws InvalidAlgorithmParameterException {
+        switch (keySizeBits) {
+            case 224:
+                return EcCurve.P_224;
+            case 256:
+                return EcCurve.P_256;
+            case 384:
+                return EcCurve.P_384;
+            case 521:
+                return EcCurve.P_521;
+            default:
+                throw new InvalidAlgorithmParameterException(
+                        "Unsupported EC curve keysize: " + keySizeBits);
+        }
+    }
+
     @SuppressWarnings("deprecation")
     @Override
     public void initialize(int keysize, SecureRandom random) {
         throw new IllegalArgumentException(
                 KeyGenParameterSpec.class.getName() + " or " + KeyPairGeneratorSpec.class.getName()
-                + " required to initialize this KeyPairGenerator");
+                        + " required to initialize this KeyPairGenerator");
     }
 
     @SuppressWarnings("deprecation")
@@ -194,7 +213,7 @@
             if (params == null) {
                 throw new InvalidAlgorithmParameterException(
                         "Must supply params of type " + KeyGenParameterSpec.class.getName()
-                        + " or " + KeyPairGeneratorSpec.class.getName());
+                                + " or " + KeyPairGeneratorSpec.class.getName());
             }
 
             KeyGenParameterSpec spec;
@@ -215,8 +234,8 @@
             } else {
                 throw new InvalidAlgorithmParameterException(
                         "Unsupported params class: " + params.getClass().getName()
-                        + ". Supported: " + KeyGenParameterSpec.class.getName()
-                        + ", " + KeyPairGeneratorSpec.class.getName());
+                                + ". Supported: " + KeyGenParameterSpec.class.getName()
+                                + ", " + KeyPairGeneratorSpec.class.getName());
             }
 
             mEntryAlias = spec.getKeystoreAlias();
@@ -250,11 +269,11 @@
                                         keymasterPadding)) {
                             throw new InvalidAlgorithmParameterException(
                                     "Randomized encryption (IND-CPA) required but may be violated"
-                                    + " by padding scheme: "
-                                    + KeyProperties.EncryptionPadding.fromKeymaster(
+                                            + " by padding scheme: "
+                                            + KeyProperties.EncryptionPadding.fromKeymaster(
                                             keymasterPadding)
-                                    + ". See " + KeyGenParameterSpec.class.getName()
-                                    + " documentation.");
+                                            + ". See " + KeyGenParameterSpec.class.getName()
+                                            + " documentation.");
                         }
                     }
                 }
@@ -378,7 +397,7 @@
                 specBuilder = new KeyGenParameterSpec.Builder(
                         legacySpec.getKeystoreAlias(),
                         KeyProperties.PURPOSE_SIGN
-                        | KeyProperties.PURPOSE_VERIFY);
+                                | KeyProperties.PURPOSE_VERIFY);
                 // Authorized to be used with any digest (including no digest).
                 // MD5 was never offered for Android Keystore for ECDSA.
                 specBuilder.setDigests(
@@ -393,9 +412,9 @@
                 specBuilder = new KeyGenParameterSpec.Builder(
                         legacySpec.getKeystoreAlias(),
                         KeyProperties.PURPOSE_ENCRYPT
-                        | KeyProperties.PURPOSE_DECRYPT
-                        | KeyProperties.PURPOSE_SIGN
-                        | KeyProperties.PURPOSE_VERIFY);
+                                | KeyProperties.PURPOSE_DECRYPT
+                                | KeyProperties.PURPOSE_SIGN
+                                | KeyProperties.PURPOSE_VERIFY);
                 // Authorized to be used with any digest (including no digest).
                 specBuilder.setDigests(
                         KeyProperties.DIGEST_NONE,
@@ -459,8 +478,7 @@
     private void initAlgorithmSpecificParameters() throws InvalidAlgorithmParameterException {
         AlgorithmParameterSpec algSpecificSpec = mSpec.getAlgorithmParameterSpec();
         switch (mKeymasterAlgorithm) {
-            case KeymasterDefs.KM_ALGORITHM_RSA:
-            {
+            case KeymasterDefs.KM_ALGORITHM_RSA: {
                 BigInteger publicExponent = null;
                 if (algSpecificSpec instanceof RSAKeyGenParameterSpec) {
                     RSAKeyGenParameterSpec rsaSpec = (RSAKeyGenParameterSpec) algSpecificSpec;
@@ -474,7 +492,7 @@
                     publicExponent = rsaSpec.getPublicExponent();
                 } else if (algSpecificSpec != null) {
                     throw new InvalidAlgorithmParameterException(
-                        "RSA may only use RSAKeyGenParameterSpec");
+                            "RSA may only use RSAKeyGenParameterSpec");
                 }
                 if (publicExponent == null) {
                     publicExponent = RSAKeyGenParameterSpec.F4;
@@ -487,7 +505,8 @@
                         || (publicExponent.compareTo(KeymasterArguments.UINT64_MAX_VALUE) > 0)) {
                     throw new InvalidAlgorithmParameterException(
                             "Unsupported RSA public exponent: " + publicExponent
-                            + ". Maximum supported value: " + KeymasterArguments.UINT64_MAX_VALUE);
+                                    + ". Maximum supported value: "
+                                    + KeymasterArguments.UINT64_MAX_VALUE);
                 }
                 mRSAPublicExponent = publicExponent.longValue();
                 break;
@@ -501,7 +520,7 @@
                     if (ecSpecKeySizeBits == null) {
                         throw new InvalidAlgorithmParameterException(
                                 "Unsupported EC curve name: " + curveName
-                                + ". Supported: " + SUPPORTED_EC_NIST_CURVE_NAMES);
+                                        + ". Supported: " + SUPPORTED_EC_NIST_CURVE_NAMES);
                     }
                     if (mKeySizeBits == -1) {
                         mKeySizeBits = ecSpecKeySizeBits;
@@ -512,7 +531,7 @@
                     }
                 } else if (algSpecificSpec != null) {
                     throw new InvalidAlgorithmParameterException(
-                        "EC may only use ECGenParameterSpec");
+                            "EC may only use ECGenParameterSpec");
                 }
                 break;
             default:
@@ -546,7 +565,7 @@
         final int flags =
                 mSpec.isCriticalToDeviceEncryption()
                         ? IKeystoreSecurityLevel
-                                .KEY_FLAG_AUTH_BOUND_WITHOUT_CRYPTOGRAPHIC_LSKF_BINDING
+                        .KEY_FLAG_AUTH_BOUND_WITHOUT_CRYPTOGRAPHIC_LSKF_BINDING
                         : 0;
 
         byte[] additionalEntropy =
@@ -585,7 +604,7 @@
             success = true;
             return new KeyPair(publicKey, publicKey.getPrivateKey());
         } catch (android.security.KeyStoreException e) {
-            switch(e.getErrorCode()) {
+            switch (e.getErrorCode()) {
                 case KeymasterDefs.KM_ERROR_HARDWARE_TYPE_UNAVAILABLE:
                     throw new StrongBoxUnavailableException("Failed to generated key pair.", e);
                 case ResponseCode.OUT_OF_KEYS:
@@ -605,7 +624,7 @@
                     throw p;
             }
         } catch (UnrecoverableKeyException | IllegalArgumentException
-                    | DeviceIdAttestationException e) {
+                | DeviceIdAttestationException | InvalidAlgorithmParameterException e) {
             throw new ProviderException(
                     "Failed to construct key object from newly generated key pair.", e);
         } finally {
@@ -666,8 +685,8 @@
             if (idTypesSet.contains(AttestationUtils.ID_TYPE_IMEI)
                     || idTypesSet.contains(AttestationUtils.ID_TYPE_MEID)) {
                 telephonyService =
-                    (TelephonyManager) android.app.AppGlobals.getInitialApplication()
-                            .getSystemService(Context.TELEPHONY_SERVICE);
+                        (TelephonyManager) android.app.AppGlobals.getInitialApplication()
+                                .getSystemService(Context.TELEPHONY_SERVICE);
                 if (telephonyService == null) {
                     throw new DeviceIdAttestationException("Unable to access telephony service");
                 }
@@ -715,12 +734,20 @@
     }
 
     private Collection<KeyParameter> constructKeyGenerationArguments()
-            throws DeviceIdAttestationException, IllegalArgumentException {
+            throws DeviceIdAttestationException, IllegalArgumentException,
+            InvalidAlgorithmParameterException {
         List<KeyParameter> params = new ArrayList<>();
         params.add(KeyStore2ParameterUtils.makeInt(KeymasterDefs.KM_TAG_KEY_SIZE, mKeySizeBits));
         params.add(KeyStore2ParameterUtils.makeEnum(
                 KeymasterDefs.KM_TAG_ALGORITHM, mKeymasterAlgorithm
         ));
+
+        if (mKeymasterAlgorithm == KeymasterDefs.KM_ALGORITHM_EC) {
+            params.add(KeyStore2ParameterUtils.makeEnum(
+                    Tag.EC_CURVE, keySize2EcCurve(mKeySizeBits)
+            ));
+        }
+
         ArrayUtils.forEach(mKeymasterPurposes, (purpose) -> {
             params.add(KeyStore2ParameterUtils.makeEnum(
                     KeymasterDefs.KM_TAG_PURPOSE, purpose
@@ -844,7 +871,7 @@
                 if (isStrongBoxBacked && keySize != 256) {
                     throw new InvalidAlgorithmParameterException(
                             "Unsupported StrongBox EC key size: "
-                            + keySize + " bits. Supported: 256");
+                                    + keySize + " bits. Supported: 256");
                 }
                 if (!SUPPORTED_EC_NIST_CURVE_SIZES.contains(keySize)) {
                     throw new InvalidAlgorithmParameterException("Unsupported EC key size: "
@@ -892,8 +919,7 @@
             return null;
         }
         switch (keymasterAlgorithm) {
-            case KeymasterDefs.KM_ALGORITHM_EC:
-            {
+            case KeymasterDefs.KM_ALGORITHM_EC: {
                 Set<Integer> availableKeymasterDigests = getAvailableKeymasterSignatureDigests(
                         spec.getDigests(),
                         AndroidKeyStoreBCWorkaroundProvider.getSupportedEcdsaSignatureDigests());
@@ -940,8 +966,7 @@
                 return KeyProperties.Digest.fromKeymasterToSignatureAlgorithmDigest(
                         bestKeymasterDigest) + "WithECDSA";
             }
-            case KeymasterDefs.KM_ALGORITHM_RSA:
-            {
+            case KeymasterDefs.KM_ALGORITHM_RSA: {
                 // Check whether this key is authorized for PKCS#1 signature padding.
                 // We use Bouncy Castle to generate self-signed RSA certificates. Bouncy Castle
                 // only supports RSA certificates signed using PKCS#1 padding scheme. The key needs
diff --git a/services/core/Android.bp b/services/core/Android.bp
index 4c9ce51..3921da2 100644
--- a/services/core/Android.bp
+++ b/services/core/Android.bp
@@ -155,7 +155,6 @@
         "android.hardware.soundtrigger-V2.3-java",
         "android.hidl.manager-V1.2-java",
         "capture_state_listener-aidl-java",
-        "dnsresolver_aidl_interface-V7-java",
         "icu4j_calendar_astronomer",
         "netd-client",
         "overlayable_policy_aidl-java",
diff --git a/services/core/java/com/android/server/pm/SELinuxMMAC.java b/services/core/java/com/android/server/pm/SELinuxMMAC.java
index 4ba7368..4a913e4e 100644
--- a/services/core/java/com/android/server/pm/SELinuxMMAC.java
+++ b/services/core/java/com/android/server/pm/SELinuxMMAC.java
@@ -17,6 +17,7 @@
 package com.android.server.pm;
 
 import android.compat.annotation.ChangeId;
+import android.compat.annotation.Disabled;
 import android.compat.annotation.EnabledAfter;
 import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageParser.SigningDetails;
@@ -79,13 +80,13 @@
 
     /**
      * Allows opt-in to the latest targetSdkVersion enforced changes without changing target SDK.
-     * Turning this change off for an app targeting the latest SDK or higher is a no-op.
+     * Turning this change on for an app targeting the latest SDK or higher is a no-op.
      *
      * <p>Has no effect for apps using shared user id.
      *
      * TODO(b/143539591): Update description with relevant SELINUX changes this opts in to.
      */
-    @EnabledAfter(targetSdkVersion = android.os.Build.VERSION_CODES.R)
+    @Disabled
     @ChangeId
     static final long SELINUX_LATEST_CHANGES = 143539591L;
 
@@ -364,7 +365,8 @@
         }
         final ApplicationInfo appInfo = pkg.toAppInfoWithoutState();
         if (compatibility.isChangeEnabledInternal(SELINUX_LATEST_CHANGES, appInfo)) {
-            return Math.max(android.os.Build.VERSION_CODES.S, pkg.getTargetSdkVersion());
+            return Math.max(
+                    android.os.Build.VERSION_CODES.CUR_DEVELOPMENT, pkg.getTargetSdkVersion());
         } else if (compatibility.isChangeEnabledInternal(SELINUX_R_CHANGES, appInfo)) {
             return Math.max(android.os.Build.VERSION_CODES.R, pkg.getTargetSdkVersion());
         }
diff --git a/services/core/java/com/android/server/pm/dex/ArtManagerService.java b/services/core/java/com/android/server/pm/dex/ArtManagerService.java
index 42b40e5..882e85b 100644
--- a/services/core/java/com/android/server/pm/dex/ArtManagerService.java
+++ b/services/core/java/com/android/server/pm/dex/ArtManagerService.java
@@ -608,6 +608,8 @@
     private static final int TRON_COMPILATION_REASON_BOOT_AFTER_OTA = 20;
     private static final int TRON_COMPILATION_REASON_POST_BOOT = 21;
     private static final int TRON_COMPILATION_REASON_CMDLINE = 22;
+    private static final int TRON_COMPILATION_REASON_PREBUILT = 23;
+    private static final int TRON_COMPILATION_REASON_VDEX = 24;
 
     // The annotation to add as a suffix to the compilation reason when dexopt was
     // performed with dex metadata.
@@ -628,6 +630,8 @@
             case "ab-ota" : return TRON_COMPILATION_REASON_AB_OTA;
             case "inactive" : return TRON_COMPILATION_REASON_INACTIVE;
             case "shared" : return TRON_COMPILATION_REASON_SHARED;
+            case "prebuilt" : return TRON_COMPILATION_REASON_PREBUILT;
+            case "vdex" : return TRON_COMPILATION_REASON_VDEX;
             case "install-fast" :
                 return TRON_COMPILATION_REASON_INSTALL_FAST;
             case "install-bulk" :
diff --git a/services/tests/servicestests/src/com/android/server/pm/SELinuxMMACTest.java b/services/tests/servicestests/src/com/android/server/pm/SELinuxMMACTest.java
index cee4cda..901b200 100644
--- a/services/tests/servicestests/src/com/android/server/pm/SELinuxMMACTest.java
+++ b/services/tests/servicestests/src/com/android/server/pm/SELinuxMMACTest.java
@@ -44,7 +44,7 @@
 public class SELinuxMMACTest {
 
     private static final String PACKAGE_NAME = "my.package";
-    private static final int LATEST_OPT_IN_VERSION = Build.VERSION_CODES.S;
+    private static final int LATEST_OPT_IN_VERSION = Build.VERSION_CODES.CUR_DEVELOPMENT;
     private static final int R_OPT_IN_VERSION = Build.VERSION_CODES.R;
 
     @Mock