diff options
80 files changed, 445 insertions, 619 deletions
diff --git a/core/java/android/bluetooth/BluetoothHeadsetClient.java b/core/java/android/bluetooth/BluetoothHeadsetClient.java index 85e0e08b19c8..28363250ebda 100644 --- a/core/java/android/bluetooth/BluetoothHeadsetClient.java +++ b/core/java/android/bluetooth/BluetoothHeadsetClient.java @@ -19,7 +19,6 @@ package android.bluetooth;  import android.Manifest;  import android.annotation.NonNull;  import android.annotation.RequiresPermission; -import android.annotation.SystemApi;  import android.compat.annotation.UnsupportedAppUsage;  import android.content.Context;  import android.os.Binder; @@ -587,7 +586,6 @@ public final class BluetoothHeadsetClient implements BluetoothProfile {       * @return true if connectionPolicy is set, false on error       * @hide       */ -    @SystemApi      @RequiresPermission(Manifest.permission.BLUETOOTH_PRIVILEGED)      public boolean setConnectionPolicy(@NonNull BluetoothDevice device,              @ConnectionPolicy int connectionPolicy) { @@ -637,7 +635,6 @@ public final class BluetoothHeadsetClient implements BluetoothProfile {       * @return connection policy of the device       * @hide       */ -    @SystemApi      @RequiresPermission(Manifest.permission.BLUETOOTH)      public @ConnectionPolicy int getConnectionPolicy(@NonNull BluetoothDevice device) {          if (VDBG) log("getConnectionPolicy(" + device + ")"); diff --git a/core/java/android/bluetooth/BluetoothMapClient.java b/core/java/android/bluetooth/BluetoothMapClient.java index 19240dc0bbc7..4f5c4feb3684 100644 --- a/core/java/android/bluetooth/BluetoothMapClient.java +++ b/core/java/android/bluetooth/BluetoothMapClient.java @@ -19,7 +19,6 @@ package android.bluetooth;  import android.Manifest;  import android.annotation.NonNull;  import android.annotation.RequiresPermission; -import android.annotation.SystemApi;  import android.app.PendingIntent;  import android.compat.annotation.UnsupportedAppUsage;  import android.content.Context; @@ -276,7 +275,6 @@ public final class BluetoothMapClient implements BluetoothProfile {       * @return true if connectionPolicy is set, false on error       * @hide       */ -    @SystemApi      @RequiresPermission(Manifest.permission.BLUETOOTH_PRIVILEGED)      public boolean setConnectionPolicy(@NonNull BluetoothDevice device,              @ConnectionPolicy int connectionPolicy) { @@ -325,7 +323,6 @@ public final class BluetoothMapClient implements BluetoothProfile {       * @return connection policy of the device       * @hide       */ -    @SystemApi      @RequiresPermission(Manifest.permission.BLUETOOTH_PRIVILEGED)      public @ConnectionPolicy int getConnectionPolicy(@NonNull BluetoothDevice device) {          if (VDBG) Log.d(TAG, "getConnectionPolicy(" + device + ")"); diff --git a/core/java/android/bluetooth/BluetoothPbapClient.java b/core/java/android/bluetooth/BluetoothPbapClient.java index d3452ffb4586..f356da18fc73 100644 --- a/core/java/android/bluetooth/BluetoothPbapClient.java +++ b/core/java/android/bluetooth/BluetoothPbapClient.java @@ -19,7 +19,6 @@ package android.bluetooth;  import android.Manifest;  import android.annotation.NonNull;  import android.annotation.RequiresPermission; -import android.annotation.SystemApi;  import android.content.Context;  import android.os.Binder;  import android.os.IBinder; @@ -276,7 +275,6 @@ public final class BluetoothPbapClient implements BluetoothProfile {       * @return true if connectionPolicy is set, false on error       * @hide       */ -    @SystemApi      @RequiresPermission(Manifest.permission.BLUETOOTH_PRIVILEGED)      public boolean setConnectionPolicy(@NonNull BluetoothDevice device,              @ConnectionPolicy int connectionPolicy) { @@ -329,7 +327,6 @@ public final class BluetoothPbapClient implements BluetoothProfile {       * @return connection policy of the device       * @hide       */ -    @SystemApi      @RequiresPermission(Manifest.permission.BLUETOOTH_PRIVILEGED)      public @ConnectionPolicy int getConnectionPolicy(@NonNull BluetoothDevice device) {          if (VDBG) { diff --git a/core/java/android/bluetooth/BluetoothSap.java b/core/java/android/bluetooth/BluetoothSap.java index 6e0348158f48..48e8c1ada255 100644 --- a/core/java/android/bluetooth/BluetoothSap.java +++ b/core/java/android/bluetooth/BluetoothSap.java @@ -18,7 +18,6 @@ package android.bluetooth;  import android.Manifest;  import android.annotation.RequiresPermission; -import android.annotation.SystemApi;  import android.compat.annotation.UnsupportedAppUsage;  import android.content.Context;  import android.os.Binder; @@ -328,7 +327,6 @@ public final class BluetoothSap implements BluetoothProfile {       * @return true if connectionPolicy is set, false on error       * @hide       */ -    @SystemApi      @RequiresPermission(Manifest.permission.BLUETOOTH_PRIVILEGED)      public boolean setConnectionPolicy(BluetoothDevice device,              @ConnectionPolicy int connectionPolicy) { @@ -377,7 +375,6 @@ public final class BluetoothSap implements BluetoothProfile {       * @return connection policy of the device       * @hide       */ -    @SystemApi      @RequiresPermission(Manifest.permission.BLUETOOTH_PRIVILEGED)      public @ConnectionPolicy int getConnectionPolicy(BluetoothDevice device) {          if (VDBG) log("getConnectionPolicy(" + device + ")"); diff --git a/core/java/android/content/pm/PackageParser.java b/core/java/android/content/pm/PackageParser.java index 0e610169ffa6..62669e019558 100644 --- a/core/java/android/content/pm/PackageParser.java +++ b/core/java/android/content/pm/PackageParser.java @@ -46,7 +46,6 @@ import android.annotation.IntRange;  import android.annotation.NonNull;  import android.annotation.Nullable;  import android.annotation.StringRes; -import android.annotation.TestApi;  import android.apex.ApexInfo;  import android.app.ActivityTaskManager;  import android.app.ActivityThread; @@ -2682,7 +2681,6 @@ public class PackageParser {       *         not compatible with this platform       * @hide Exposed for unit testing only.       */ -    @TestApi      public static int computeTargetSdkVersion(@IntRange(from = 0) int targetVers,              @Nullable String targetCode, @NonNull String[] platformSdkCodenames,              @NonNull String[] outError) { @@ -2747,7 +2745,6 @@ public class PackageParser {       *         compatible with this platform       * @hide Exposed for unit testing only.       */ -    @TestApi      public static int computeMinSdkVersion(@IntRange(from = 1) int minVers,              @Nullable String minCode, @IntRange(from = 1) int platformSdkVersion,              @NonNull String[] platformSdkCodenames, @NonNull String[] outError) { @@ -4845,7 +4842,6 @@ public class PackageParser {       *                                AndroidManifest.xml.       * @hide Exposed for unit testing only.       */ -    @TestApi      public static int getActivityConfigChanges(int configChanges, int recreateOnConfigChanges) {          return configChanges | ((~recreateOnConfigChanges) & RECREATE_ON_CONFIG_CHANGES_MASK);      } diff --git a/core/java/android/net/DnsPacket.java b/core/java/android/net/DnsPacket.java deleted file mode 100644 index 83e57e0a047b..000000000000 --- a/core/java/android/net/DnsPacket.java +++ /dev/null @@ -1,235 +0,0 @@ -/* - * Copyright (C) 2019 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.net; - -import android.annotation.NonNull; -import android.annotation.Nullable; -import android.text.TextUtils; - -import com.android.internal.util.BitUtils; - -import java.nio.BufferUnderflowException; -import java.nio.ByteBuffer; -import java.text.DecimalFormat; -import java.text.FieldPosition; -import java.util.ArrayList; -import java.util.List; - -/** - * Defines basic data for DNS protocol based on RFC 1035. - * Subclasses create the specific format used in DNS packet. - * - * @hide - */ -public abstract class DnsPacket { -    public class DnsHeader { -        private static final String TAG = "DnsHeader"; -        public final int id; -        public final int flags; -        public final int rcode; -        private final int[] mRecordCount; - -        /** -         * Create a new DnsHeader from a positioned ByteBuffer. -         * -         * The ByteBuffer must be in network byte order (which is the default). -         * Reads the passed ByteBuffer from its current position and decodes a DNS header. -         * When this constructor returns, the reading position of the ByteBuffer has been -         * advanced to the end of the DNS header record. -         * This is meant to chain with other methods reading a DNS response in sequence. -         */ -        DnsHeader(@NonNull ByteBuffer buf) throws BufferUnderflowException { -            id = BitUtils.uint16(buf.getShort()); -            flags = BitUtils.uint16(buf.getShort()); -            rcode = flags & 0xF; -            mRecordCount = new int[NUM_SECTIONS]; -            for (int i = 0; i < NUM_SECTIONS; ++i) { -                mRecordCount[i] = BitUtils.uint16(buf.getShort()); -            } -        } - -        /** -         * Get record count by type. -         */ -        public int getRecordCount(int type) { -            return mRecordCount[type]; -        } -    } - -    /** -     * Superclass for DNS questions and DNS resource records. -     * -     * DNS questions (No TTL/RDATA) -     * DNS resource records (With TTL/RDATA) -     */ -    public class DnsRecord { -        private static final int MAXNAMESIZE = 255; -        private static final int MAXLABELSIZE = 63; -        private static final int MAXLABELCOUNT = 128; -        private static final int NAME_NORMAL = 0; -        private static final int NAME_COMPRESSION = 0xC0; -        private final DecimalFormat byteFormat = new DecimalFormat(); -        private final FieldPosition pos = new FieldPosition(0); - -        private static final String TAG = "DnsRecord"; - -        public final String dName; -        public final int nsType; -        public final int nsClass; -        public final long ttl; -        private final byte[] mRdata; - -        /** -         * Create a new DnsRecord from a positioned ByteBuffer. -         * -         * Reads the passed ByteBuffer from its current position and decodes a DNS record. -         * When this constructor returns, the reading position of the ByteBuffer has been -         * advanced to the end of the DNS header record. -         * This is meant to chain with other methods reading a DNS response in sequence. -         * -         * @param ByteBuffer input of record, must be in network byte order -         *         (which is the default). -         */ -        DnsRecord(int recordType, @NonNull ByteBuffer buf) -                throws BufferUnderflowException, ParseException { -            dName = parseName(buf, 0 /* Parse depth */); -            if (dName.length() > MAXNAMESIZE) { -                throw new ParseException( -                        "Parse name fail, name size is too long: " + dName.length()); -            } -            nsType = BitUtils.uint16(buf.getShort()); -            nsClass = BitUtils.uint16(buf.getShort()); - -            if (recordType != QDSECTION) { -                ttl = BitUtils.uint32(buf.getInt()); -                final int length = BitUtils.uint16(buf.getShort()); -                mRdata = new byte[length]; -                buf.get(mRdata); -            } else { -                ttl = 0; -                mRdata = null; -            } -        } - -        /** -         * Get a copy of rdata. -         */ -        @Nullable -        public byte[] getRR() { -            return (mRdata == null) ? null : mRdata.clone(); -        } - -        /** -         * Convert label from {@code byte[]} to {@code String} -         * -         * Follows the same conversion rules of the native code (ns_name.c in libc) -         */ -        private String labelToString(@NonNull byte[] label) { -            final StringBuffer sb = new StringBuffer(); -            for (int i = 0; i < label.length; ++i) { -                int b = BitUtils.uint8(label[i]); -                // Control characters and non-ASCII characters. -                if (b <= 0x20 || b >= 0x7f) { -                    // Append the byte as an escaped decimal number, e.g., "\19" for 0x13. -                    sb.append('\\'); -                    byteFormat.format(b, sb, pos); -                } else if (b == '"' || b == '.' || b == ';' || b == '\\' -                        || b == '(' || b == ')' || b == '@' || b == '$') { -                    // Append the byte as an escaped character, e.g., "\:" for 0x3a. -                    sb.append('\\'); -                    sb.append((char) b); -                } else { -                    // Append the byte as a character, e.g., "a" for 0x61. -                    sb.append((char) b); -                } -            } -            return sb.toString(); -        } - -        private String parseName(@NonNull ByteBuffer buf, int depth) throws -                BufferUnderflowException, ParseException { -            if (depth > MAXLABELCOUNT) { -                throw new ParseException("Failed to parse name, too many labels"); -            } -            final int len = BitUtils.uint8(buf.get()); -            final int mask = len & NAME_COMPRESSION; -            if (0 == len) { -                return ""; -            } else if (mask != NAME_NORMAL && mask != NAME_COMPRESSION) { -                throw new ParseException("Parse name fail, bad label type"); -            } else if (mask == NAME_COMPRESSION) { -                // Name compression based on RFC 1035 - 4.1.4 Message compression -                final int offset = ((len & ~NAME_COMPRESSION) << 8) + BitUtils.uint8(buf.get()); -                final int oldPos = buf.position(); -                if (offset >= oldPos - 2) { -                    throw new ParseException("Parse compression name fail, invalid compression"); -                } -                buf.position(offset); -                final String pointed = parseName(buf, depth + 1); -                buf.position(oldPos); -                return pointed; -            } else { -                final byte[] label = new byte[len]; -                buf.get(label); -                final String head = labelToString(label); -                if (head.length() > MAXLABELSIZE) { -                    throw new ParseException("Parse name fail, invalid label length"); -                } -                final String tail = parseName(buf, depth + 1); -                return TextUtils.isEmpty(tail) ? head : head + "." + tail; -            } -        } -    } - -    public static final int QDSECTION = 0; -    public static final int ANSECTION = 1; -    public static final int NSSECTION = 2; -    public static final int ARSECTION = 3; -    private static final int NUM_SECTIONS = ARSECTION + 1; - -    private static final String TAG = DnsPacket.class.getSimpleName(); - -    protected final DnsHeader mHeader; -    protected final List<DnsRecord>[] mRecords; - -    protected DnsPacket(@NonNull byte[] data) throws ParseException { -        if (null == data) throw new ParseException("Parse header failed, null input data"); -        final ByteBuffer buffer; -        try { -            buffer = ByteBuffer.wrap(data); -            mHeader = new DnsHeader(buffer); -        } catch (BufferUnderflowException e) { -            throw new ParseException("Parse Header fail, bad input data", e); -        } - -        mRecords = new ArrayList[NUM_SECTIONS]; - -        for (int i = 0; i < NUM_SECTIONS; ++i) { -            final int count = mHeader.getRecordCount(i); -            if (count > 0) { -                mRecords[i] = new ArrayList(count); -            } -            for (int j = 0; j < count; ++j) { -                try { -                    mRecords[i].add(new DnsRecord(i, buffer)); -                } catch (BufferUnderflowException e) { -                    throw new ParseException("Parse record fail", e); -                } -            } -        } -    } -} diff --git a/core/java/android/net/DnsResolver.java b/core/java/android/net/DnsResolver.java index 0b1a84534e38..3f7660f5709a 100644 --- a/core/java/android/net/DnsResolver.java +++ b/core/java/android/net/DnsResolver.java @@ -38,6 +38,8 @@ import android.os.MessageQueue;  import android.system.ErrnoException;  import android.util.Log; +import com.android.net.module.util.DnsPacket; +  import java.io.FileDescriptor;  import java.lang.annotation.Retention;  import java.lang.annotation.RetentionPolicy; @@ -97,7 +99,7 @@ public final class DnsResolver {      @interface DnsError {}      /**       * Indicates that there was an error parsing the response the query. -     * The cause of this error is available via getCause() and is a ParseException. +     * The cause of this error is available via getCause() and is a {@link ParseException}.       */      public static final int ERROR_PARSE = 0;      /** @@ -290,8 +292,15 @@ public final class DnsResolver {              }              try {                  mAllAnswers.addAll(new DnsAddressAnswer(answer).getAddresses()); -            } catch (ParseException e) { -                mDnsException = new DnsException(ERROR_PARSE, e); +            } catch (DnsPacket.ParseException e) { +                // Convert the com.android.net.module.util.DnsPacket.ParseException to an +                // android.net.ParseException. This is the type that was used in Q and is implied +                // by the public documentation of ERROR_PARSE. +                // +                // DnsPacket cannot throw android.net.ParseException directly because it's @hide. +                ParseException pe = new ParseException(e.reason, e.getCause()); +                pe.setStackTrace(e.getStackTrace()); +                mDnsException = new DnsException(ERROR_PARSE, pe);              }              maybeReportAnswer();          } diff --git a/core/java/android/net/NetworkUtils.java b/core/java/android/net/NetworkUtils.java index 779f7bc91e8f..0b92b95128d3 100644 --- a/core/java/android/net/NetworkUtils.java +++ b/core/java/android/net/NetworkUtils.java @@ -155,6 +155,14 @@ public class NetworkUtils {      public static native Network getDnsNetwork() throws ErrnoException;      /** +     * Allow/Disallow creating AF_INET/AF_INET6 sockets and DNS lookups for current process. +     * +     * @param allowNetworking whether to allow or disallow creating AF_INET/AF_INET6 sockets +     *                        and DNS lookups. +     */ +    public static native void setAllowNetworkingForProcess(boolean allowNetworking); + +    /**       * Get the tcp repair window associated with the {@code fd}.       *       * @param fd the tcp socket's {@link FileDescriptor}. diff --git a/core/java/android/os/Process.java b/core/java/android/os/Process.java index 994ed2148baa..337786734bb8 100644 --- a/core/java/android/os/Process.java +++ b/core/java/android/os/Process.java @@ -194,6 +194,13 @@ public class Process {       */      public static final int FSVERITY_CERT_UID = 1075; +    /** +     * GID that corresponds to the INTERNET permission. +     * Must match the value of AID_INET. +     * @hide +     */ +    public static final int INET_GID = 3003; +      /** {@hide} */      public static final int NOBODY_UID = 9999; diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java index cadae5cecc6d..754b08c21abb 100644 --- a/core/java/android/provider/Settings.java +++ b/core/java/android/provider/Settings.java @@ -14952,6 +14952,21 @@ public final class Settings {           */          public static final String POWER_BUTTON_SUPPRESSION_DELAY_AFTER_GESTURE_WAKE =                  "power_button_suppression_delay_after_gesture_wake"; + +        /** +         * For 5G NSA capable devices, determines whether NR tracking indications are on +         * when the screen is off. +         * +         * Values are: +         * 0: off - All 5G NSA tracking indications are off when the screen is off. +         * 1: extended - All 5G NSA tracking indications are on when the screen is off as long as +         *    the device is camped on 5G NSA (5G icon is showing in status bar). +         *    If the device is not camped on 5G NSA, tracking indications are off. +         * 2: always on - All 5G NSA tracking indications are on whether the screen is on or off. +         * @hide +         */ +        public static final String NR_NSA_TRACKING_SCREEN_OFF_MODE = +                "nr_nsa_tracking_screen_off_mode";      }      /** diff --git a/core/java/android/telephony/TelephonyRegistryManager.java b/core/java/android/telephony/TelephonyRegistryManager.java index 5924421decce..3611d924b904 100644 --- a/core/java/android/telephony/TelephonyRegistryManager.java +++ b/core/java/android/telephony/TelephonyRegistryManager.java @@ -18,7 +18,6 @@ package android.telephony;  import android.annotation.NonNull;  import android.annotation.Nullable;  import android.annotation.RequiresPermission; -import android.annotation.TestApi;  import android.content.Context;  import android.os.Binder;  import android.os.RemoteException; @@ -248,7 +247,6 @@ public class TelephonyRegistryManager {       * @param incomingNumber incoming phone number.       * @hide       */ -    @TestApi      @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)      public void notifyCallStateChangedForAllSubscriptions(@CallState int state,              @Nullable String incomingNumber) { diff --git a/core/java/com/android/internal/os/Zygote.java b/core/java/com/android/internal/os/Zygote.java index f3c3ac1b94e5..2a29dfb71e6c 100644 --- a/core/java/com/android/internal/os/Zygote.java +++ b/core/java/com/android/internal/os/Zygote.java @@ -24,6 +24,7 @@ import android.content.pm.ApplicationInfo;  import android.net.Credentials;  import android.net.LocalServerSocket;  import android.net.LocalSocket; +import android.net.NetworkUtils;  import android.os.FactoryTest;  import android.os.IVold;  import android.os.Process; @@ -239,6 +240,13 @@ public final class Zygote {      private Zygote() {} +    private static boolean containsInetGid(int[] gids) { +        for (int i = 0; i < gids.length; i++) { +            if (gids[i] == android.os.Process.INET_GID) return true; +        } +        return false; +    } +      /**       * Forks a new VM instance.  The current VM must have been started       * with the -Xzygote flag. <b>NOTE: new instance keeps all @@ -286,6 +294,11 @@ public final class Zygote {          if (pid == 0) {              // Note that this event ends at the end of handleChildProc,              Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "PostFork"); + +            // If no GIDs were specified, don't make any permissions changes based on groups. +            if (gids != null && gids.length > 0) { +                NetworkUtils.setAllowNetworkingForProcess(containsInetGid(gids)); +            }          }          // Set the Java Language thread priority to the default value for new apps. diff --git a/core/jni/android/graphics/BitmapFactory.cpp b/core/jni/android/graphics/BitmapFactory.cpp index f040f11ffac4..8cc1b8161de9 100644 --- a/core/jni/android/graphics/BitmapFactory.cpp +++ b/core/jni/android/graphics/BitmapFactory.cpp @@ -22,7 +22,7 @@  #include "core_jni_helpers.h"  #include <HardwareBitmapUploader.h> -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include <androidfw/Asset.h>  #include <androidfw/ResourceTypes.h>  #include <cutils/compiler.h> diff --git a/core/jni/android_app_ActivityThread.cpp b/core/jni/android_app_ActivityThread.cpp index fc88193a8502..002f36cf586d 100644 --- a/core/jni/android_app_ActivityThread.cpp +++ b/core/jni/android_app_ActivityThread.cpp @@ -15,8 +15,9 @@   */  #include "jni.h" +  #include "GraphicsJNI.h" -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include <minikin/Layout.h>  #include <renderthread/RenderProxy.h> diff --git a/core/jni/android_backup_BackupDataInput.cpp b/core/jni/android_backup_BackupDataInput.cpp index aa8acc16bc3f..79fa2a28666c 100644 --- a/core/jni/android_backup_BackupDataInput.cpp +++ b/core/jni/android_backup_BackupDataInput.cpp @@ -17,7 +17,7 @@  #define LOG_TAG "FileBackupHelper_native"  #include <utils/Log.h> -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include <android_runtime/AndroidRuntime.h>  #include <androidfw/BackupHelpers.h> diff --git a/core/jni/android_backup_BackupDataOutput.cpp b/core/jni/android_backup_BackupDataOutput.cpp index 4f5d1f80dffc..324b3e71b8cc 100644 --- a/core/jni/android_backup_BackupDataOutput.cpp +++ b/core/jni/android_backup_BackupDataOutput.cpp @@ -17,7 +17,7 @@  #define LOG_TAG "FileBackupHelper_native"  #include <utils/Log.h> -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include "core_jni_helpers.h"  #include <androidfw/BackupHelpers.h> diff --git a/core/jni/android_backup_BackupHelperDispatcher.cpp b/core/jni/android_backup_BackupHelperDispatcher.cpp index fac7eba4c0a2..efe7d0b6ad0a 100644 --- a/core/jni/android_backup_BackupHelperDispatcher.cpp +++ b/core/jni/android_backup_BackupHelperDispatcher.cpp @@ -17,7 +17,7 @@  #define LOG_TAG "BackupHelperDispatcher_native"  #include <utils/Log.h> -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include <android_runtime/AndroidRuntime.h>  #include <sys/types.h> diff --git a/core/jni/android_backup_FileBackupHelperBase.cpp b/core/jni/android_backup_FileBackupHelperBase.cpp index 65840ee2c016..5f84fafa383e 100644 --- a/core/jni/android_backup_FileBackupHelperBase.cpp +++ b/core/jni/android_backup_FileBackupHelperBase.cpp @@ -17,7 +17,7 @@  #define LOG_TAG "FileBackupHelper_native"  #include <utils/Log.h> -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include "core_jni_helpers.h"  #include <androidfw/BackupHelpers.h> diff --git a/core/jni/android_hardware_SerialPort.cpp b/core/jni/android_hardware_SerialPort.cpp index 3ff24468e3aa..d06107e2e0b2 100644 --- a/core/jni/android_hardware_SerialPort.cpp +++ b/core/jni/android_hardware_SerialPort.cpp @@ -19,7 +19,7 @@  #include "utils/Log.h"  #include "jni.h" -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include "core_jni_helpers.h"  #include <stdio.h> diff --git a/core/jni/android_hardware_UsbDeviceConnection.cpp b/core/jni/android_hardware_UsbDeviceConnection.cpp index b885c285e380..845d65c67719 100644 --- a/core/jni/android_hardware_UsbDeviceConnection.cpp +++ b/core/jni/android_hardware_UsbDeviceConnection.cpp @@ -19,7 +19,7 @@  #include "utils/Log.h"  #include "jni.h" -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include "core_jni_helpers.h"  #include <usbhost/usbhost.h> diff --git a/core/jni/android_net_LocalSocketImpl.cpp b/core/jni/android_net_LocalSocketImpl.cpp index 1163b860977d..42cf1f479122 100644 --- a/core/jni/android_net_LocalSocketImpl.cpp +++ b/core/jni/android_net_LocalSocketImpl.cpp @@ -16,7 +16,7 @@  #define LOG_TAG "LocalSocketImpl" -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include "jni.h"  #include "utils/Log.h"  #include "utils/misc.h" diff --git a/core/jni/android_net_NetUtils.cpp b/core/jni/android_net_NetUtils.cpp index 03b9793ccba8..e56809f66dc7 100644 --- a/core/jni/android_net_NetUtils.cpp +++ b/core/jni/android_net_NetUtils.cpp @@ -30,7 +30,7 @@  #include <DnsProxydProtocol.h> // NETID_USE_LOCAL_NAMESERVERS  #include <android_runtime/AndroidRuntime.h>  #include <cutils/properties.h> -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include <nativehelper/ScopedLocalRef.h>  #include <utils/Log.h>  #include <utils/misc.h> @@ -226,6 +226,11 @@ static jobject android_net_utils_getDnsNetwork(JNIEnv *env, jobject thiz) {              class_Network, ctor, dnsNetId & ~NETID_USE_LOCAL_NAMESERVERS, privateDnsBypass);  } +static void android_net_utils_setAllowNetworkingForProcess(JNIEnv *env, jobject thiz, +                                                           jboolean hasConnectivity) { +    setAllowNetworkingForProcess(hasConnectivity == JNI_TRUE); +} +  static jobject android_net_utils_getTcpRepairWindow(JNIEnv *env, jobject thiz, jobject javaFd) {      if (javaFd == NULL) {          jniThrowNullPointerException(env, NULL); @@ -266,6 +271,7 @@ static jobject android_net_utils_getTcpRepairWindow(JNIEnv *env, jobject thiz, j  /*   * JNI registration.   */ +// clang-format off  static const JNINativeMethod gNetworkUtilMethods[] = {      /* name, signature, funcPtr */      { "bindProcessToNetwork", "(I)Z", (void*) android_net_utils_bindProcessToNetwork }, @@ -282,7 +288,9 @@ static const JNINativeMethod gNetworkUtilMethods[] = {      { "resNetworkResult", "(Ljava/io/FileDescriptor;)Landroid/net/DnsResolver$DnsResponse;", (void*) android_net_utils_resNetworkResult },      { "resNetworkCancel", "(Ljava/io/FileDescriptor;)V", (void*) android_net_utils_resNetworkCancel },      { "getDnsNetwork", "()Landroid/net/Network;", (void*) android_net_utils_getDnsNetwork }, +    { "setAllowNetworkingForProcess", "(Z)V", (void *)android_net_utils_setAllowNetworkingForProcess },  }; +// clang-format on  int register_android_net_NetworkUtils(JNIEnv* env)  { diff --git a/core/jni/android_opengl_EGL14.cpp b/core/jni/android_opengl_EGL14.cpp index de5e3a52a0c1..2f29cae42d07 100644 --- a/core/jni/android_opengl_EGL14.cpp +++ b/core/jni/android_opengl_EGL14.cpp @@ -20,7 +20,7 @@  #pragma GCC diagnostic ignored "-Wunused-function"  #include "jni.h" -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include <android_runtime/AndroidRuntime.h>  #include <android_runtime/android_view_Surface.h>  #include <android_runtime/android_graphics_SurfaceTexture.h> diff --git a/core/jni/android_opengl_EGL15.cpp b/core/jni/android_opengl_EGL15.cpp index 4aeed8765165..b9c36b9ed9aa 100644 --- a/core/jni/android_opengl_EGL15.cpp +++ b/core/jni/android_opengl_EGL15.cpp @@ -20,7 +20,7 @@  #pragma GCC diagnostic ignored "-Wunused-function"  #include "jni.h" -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include <android_runtime/AndroidRuntime.h>  #include <utils/misc.h> diff --git a/core/jni/android_opengl_EGLExt.cpp b/core/jni/android_opengl_EGLExt.cpp index fef8116dc93a..1758807304bf 100644 --- a/core/jni/android_opengl_EGLExt.cpp +++ b/core/jni/android_opengl_EGLExt.cpp @@ -20,7 +20,7 @@  #pragma GCC diagnostic ignored "-Wunused-function"  #include "jni.h" -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include <android_runtime/AndroidRuntime.h>  #include <android_runtime/android_view_Surface.h>  #include <android_runtime/android_graphics_SurfaceTexture.h> diff --git a/core/jni/android_opengl_GLES10.cpp b/core/jni/android_opengl_GLES10.cpp index 3d9a3b6687b1..e4d138d92621 100644 --- a/core/jni/android_opengl_GLES10.cpp +++ b/core/jni/android_opengl_GLES10.cpp @@ -24,7 +24,7 @@  #include <GLES/glext.h>  #include <jni.h> -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include <android_runtime/AndroidRuntime.h>  #include <utils/misc.h>  #include <assert.h> diff --git a/core/jni/android_opengl_GLES10Ext.cpp b/core/jni/android_opengl_GLES10Ext.cpp index 6d7f41e5b3b2..3638b87e201f 100644 --- a/core/jni/android_opengl_GLES10Ext.cpp +++ b/core/jni/android_opengl_GLES10Ext.cpp @@ -24,7 +24,7 @@  #include <GLES/glext.h>  #include <jni.h> -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include <android_runtime/AndroidRuntime.h>  #include <utils/misc.h>  #include <assert.h> diff --git a/core/jni/android_opengl_GLES11.cpp b/core/jni/android_opengl_GLES11.cpp index 39ef41a0e19e..1069a1d3acb1 100644 --- a/core/jni/android_opengl_GLES11.cpp +++ b/core/jni/android_opengl_GLES11.cpp @@ -24,7 +24,7 @@  #include <GLES/glext.h>  #include <jni.h> -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include <android_runtime/AndroidRuntime.h>  #include <utils/misc.h>  #include <assert.h> diff --git a/core/jni/android_opengl_GLES11Ext.cpp b/core/jni/android_opengl_GLES11Ext.cpp index 1144d5bfb4e6..86d7ecdce44d 100644 --- a/core/jni/android_opengl_GLES11Ext.cpp +++ b/core/jni/android_opengl_GLES11Ext.cpp @@ -24,7 +24,7 @@  #include <GLES/glext.h>  #include <jni.h> -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include <android_runtime/AndroidRuntime.h>  #include <utils/misc.h>  #include <assert.h> diff --git a/core/jni/android_opengl_GLES20.cpp b/core/jni/android_opengl_GLES20.cpp index 2add72d14c7b..49baa51f2342 100644 --- a/core/jni/android_opengl_GLES20.cpp +++ b/core/jni/android_opengl_GLES20.cpp @@ -24,7 +24,7 @@  #include <GLES2/gl2ext.h>  #include <jni.h> -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include <android_runtime/AndroidRuntime.h>  #include <utils/misc.h>  #include <assert.h> diff --git a/core/jni/android_opengl_GLES30.cpp b/core/jni/android_opengl_GLES30.cpp index a9c021951758..32a2a24c2d2d 100644 --- a/core/jni/android_opengl_GLES30.cpp +++ b/core/jni/android_opengl_GLES30.cpp @@ -24,7 +24,7 @@  #include <GLES3/gl3ext.h>  #include <jni.h> -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include <android_runtime/AndroidRuntime.h>  #include <utils/misc.h>  #include <assert.h> diff --git a/core/jni/android_opengl_GLES31.cpp b/core/jni/android_opengl_GLES31.cpp index 456da93784d5..afe7c63b6d47 100644 --- a/core/jni/android_opengl_GLES31.cpp +++ b/core/jni/android_opengl_GLES31.cpp @@ -22,7 +22,7 @@  #include <stdint.h>  #include <GLES3/gl31.h>  #include <jni.h> -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include <android_runtime/AndroidRuntime.h>  #include <utils/misc.h>  #include <assert.h> diff --git a/core/jni/android_opengl_GLES31Ext.cpp b/core/jni/android_opengl_GLES31Ext.cpp index dcaf4a58cd53..81274331ffa4 100644 --- a/core/jni/android_opengl_GLES31Ext.cpp +++ b/core/jni/android_opengl_GLES31Ext.cpp @@ -23,7 +23,7 @@  #include <GLES2/gl2ext.h>  #include <jni.h> -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include <android_runtime/AndroidRuntime.h>  #include <utils/misc.h>  #include <assert.h> diff --git a/core/jni/android_opengl_GLES32.cpp b/core/jni/android_opengl_GLES32.cpp index 6bdc711d64a2..07a794d0ef19 100644 --- a/core/jni/android_opengl_GLES32.cpp +++ b/core/jni/android_opengl_GLES32.cpp @@ -22,7 +22,7 @@  #include <stdint.h>  #include <GLES3/gl32.h>  #include <jni.h> -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include <android_runtime/AndroidRuntime.h>  #include <utils/misc.h>  #include <assert.h> diff --git a/core/jni/android_os_Debug.cpp b/core/jni/android_os_Debug.cpp index 8f9f8d211596..cd3611546852 100644 --- a/core/jni/android_os_Debug.cpp +++ b/core/jni/android_os_Debug.cpp @@ -40,7 +40,7 @@  #include <utils/misc.h>  #include <utils/String8.h> -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include <nativehelper/ScopedUtfChars.h>  #include "jni.h"  #include <dmabufinfo/dmabufinfo.h> diff --git a/core/jni/android_os_MemoryFile.cpp b/core/jni/android_os_MemoryFile.cpp index b21566bbc186..8d91e635454c 100644 --- a/core/jni/android_os_MemoryFile.cpp +++ b/core/jni/android_os_MemoryFile.cpp @@ -19,7 +19,7 @@  #include <cutils/ashmem.h>  #include "core_jni_helpers.h" -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include <unistd.h>  #include <sys/mman.h> diff --git a/core/jni/android_os_Parcel.cpp b/core/jni/android_os_Parcel.cpp index eb8d26e7bf71..7247ee068334 100644 --- a/core/jni/android_os_Parcel.cpp +++ b/core/jni/android_os_Parcel.cpp @@ -20,7 +20,7 @@  #include "android_os_Parcel.h"  #include "android_util_Binder.h" -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include <fcntl.h>  #include <stdio.h> diff --git a/core/jni/android_os_SELinux.cpp b/core/jni/android_os_SELinux.cpp index 7634547ae0bf..b772dfd1eb14 100644 --- a/core/jni/android_os_SELinux.cpp +++ b/core/jni/android_os_SELinux.cpp @@ -21,7 +21,7 @@  #include <utils/Log.h> -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include "jni.h"  #include "core_jni_helpers.h"  #include "selinux/selinux.h" diff --git a/core/jni/android_os_SharedMemory.cpp b/core/jni/android_os_SharedMemory.cpp index a812c35036f3..dc86187d8fea 100644 --- a/core/jni/android_os_SharedMemory.cpp +++ b/core/jni/android_os_SharedMemory.cpp @@ -22,7 +22,7 @@  #include <utils/Log.h>  #include <nativehelper/jni_macros.h> -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include <nativehelper/ScopedLocalRef.h>  #include <algorithm> diff --git a/core/jni/android_server_NetworkManagementSocketTagger.cpp b/core/jni/android_server_NetworkManagementSocketTagger.cpp index 58295af50135..afad08a87d37 100644 --- a/core/jni/android_server_NetworkManagementSocketTagger.cpp +++ b/core/jni/android_server_NetworkManagementSocketTagger.cpp @@ -17,7 +17,7 @@  #define LOG_TAG "NMST_QTagUidNative"  #include <utils/Log.h> -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include "jni.h"  #include <utils/misc.h> diff --git a/core/jni/android_util_AssetManager.cpp b/core/jni/android_util_AssetManager.cpp index 9342088cef3f..6fd9c7ef9bdc 100644 --- a/core/jni/android_util_AssetManager.cpp +++ b/core/jni/android_util_AssetManager.cpp @@ -48,7 +48,7 @@  #include "core_jni_helpers.h"  #include "jni.h" -#include "nativehelper/JNIHelp.h" +#include "nativehelper/JNIPlatformHelp.h"  #include "nativehelper/ScopedPrimitiveArray.h"  #include "nativehelper/ScopedStringChars.h"  #include "nativehelper/ScopedUtfChars.h" diff --git a/core/jni/com_google_android_gles_jni_GLImpl.cpp b/core/jni/com_google_android_gles_jni_GLImpl.cpp index 6b893cb94444..ffc1ddc03355 100644 --- a/core/jni/com_google_android_gles_jni_GLImpl.cpp +++ b/core/jni/com_google_android_gles_jni_GLImpl.cpp @@ -21,7 +21,7 @@  #pragma GCC diagnostic ignored "-Wunused-function"  #include "jni.h" -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include <android_runtime/AndroidRuntime.h>  #include <utils/misc.h> diff --git a/core/jni/core_jni_helpers.h b/core/jni/core_jni_helpers.h index f03f42737134..41ccd56925aa 100644 --- a/core/jni/core_jni_helpers.h +++ b/core/jni/core_jni_helpers.h @@ -17,7 +17,7 @@  #ifndef CORE_JNI_HELPERS  #define CORE_JNI_HELPERS -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include <nativehelper/scoped_local_ref.h>  #include <nativehelper/scoped_utf_chars.h>  #include <android_runtime/AndroidRuntime.h> diff --git a/core/proto/android/providers/settings/global.proto b/core/proto/android/providers/settings/global.proto index 829e1f7d0d96..cd4a1c8d77a8 100644 --- a/core/proto/android/providers/settings/global.proto +++ b/core/proto/android/providers/settings/global.proto @@ -693,6 +693,8 @@ message GlobalSettingsProto {      }      optional Notification notification = 82; +    optional SettingProto nr_nsa_tracking_screen_off_mode = 153 [ (android.privacy).dest = DEST_AUTOMATIC ]; +      optional SettingProto nsd_on = 83 [ (android.privacy).dest = DEST_AUTOMATIC ];      message Ntp { @@ -1052,5 +1054,5 @@ message GlobalSettingsProto {      // Please insert fields in alphabetical order and group them into messages      // if possible (to avoid reaching the method limit). -    // Next tag = 151; +    // Next tag = 154;  } diff --git a/core/tests/coretests/src/android/provider/SettingsBackupTest.java b/core/tests/coretests/src/android/provider/SettingsBackupTest.java index cb91db1934a4..2b320408d832 100644 --- a/core/tests/coretests/src/android/provider/SettingsBackupTest.java +++ b/core/tests/coretests/src/android/provider/SettingsBackupTest.java @@ -380,6 +380,7 @@ public class SettingsBackupTest {                      Settings.Global.NITZ_UPDATE_DIFF,                      Settings.Global.NITZ_UPDATE_SPACING,                      Settings.Global.NOTIFICATION_SNOOZE_OPTIONS, +                    Settings.Global.NR_NSA_TRACKING_SCREEN_OFF_MODE,                      Settings.Global.NSD_ON,                      Settings.Global.NTP_SERVER,                      Settings.Global.NTP_TIMEOUT, diff --git a/drm/jni/android_drm_DrmManagerClient.cpp b/drm/jni/android_drm_DrmManagerClient.cpp index 52ea8e3b161f..e2bb6a6f4d1a 100644 --- a/drm/jni/android_drm_DrmManagerClient.cpp +++ b/drm/jni/android_drm_DrmManagerClient.cpp @@ -19,7 +19,7 @@  #include <utils/Log.h>  #include <jni.h> -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include <nativehelper/ScopedLocalRef.h>  #include <android_runtime/AndroidRuntime.h> diff --git a/identity/java/android/security/identity/IdentityCredential.java b/identity/java/android/security/identity/IdentityCredential.java index 493c85a930be..4eb6e420c07f 100644 --- a/identity/java/android/security/identity/IdentityCredential.java +++ b/identity/java/android/security/identity/IdentityCredential.java @@ -41,19 +41,18 @@ public abstract class IdentityCredential {      /**       * Create an ephemeral key pair to use to establish a secure channel with a reader.       * -     * <p>Most applications will use only the public key, and only to send it to the reader, -     * allowing the private key to be used internally for {@link #encryptMessageToReader(byte[])} -     * and {@link #decryptMessageFromReader(byte[])}. The private key is also provided for -     * applications that wish to use a cipher suite that is not supported by -     * {@link IdentityCredentialStore}. +     * <p>Applications should use this key-pair for the communications channel with the reader +     * using a protocol / cipher-suite appropriate for the application. One example of such a +     * protocol is the one used for Mobile Driving Licenses, see ISO 18013-5 section 9.2.1 "Session +     * encryption".       *       * @return ephemeral key pair to use to establish a secure channel with a reader.       */      public @NonNull abstract KeyPair createEphemeralKeyPair();      /** -     * Set the ephemeral public key provided by the reader. This must be called before -     * {@link #encryptMessageToReader} or {@link #decryptMessageFromReader} can be called. +     * Set the ephemeral public key provided by the reader. If called, this must be called before +     * {@link #getEntries(byte[], Map, byte[], byte[])} is called.       *       * @param readerEphemeralPublicKey The ephemeral public key provided by the reader to       *                                 establish a secure session. @@ -65,6 +64,11 @@ public abstract class IdentityCredential {      /**       * Encrypt a message for transmission to the reader.       * +     * <p>Do not use. In this version of the API, this method produces an incorrect +     * result. Instead, applications should implement message encryption/decryption themselves as +     * detailed in the {@link #createEphemeralKeyPair()} method. In a future API-level, this +     * method will be deprecated. +     *       * @param messagePlaintext unencrypted message to encrypt.       * @return encrypted message.       */ @@ -73,6 +77,11 @@ public abstract class IdentityCredential {      /**       * Decrypt a message received from the reader.       * +     * <p>Do not use. In this version of the API, this method produces an incorrect +     * result. Instead, applications should implement message encryption/decryption themselves as +     * detailed in the {@link #createEphemeralKeyPair()} method. In a future API-level, this +     * method will be deprecated. +     *       * @param messageCiphertext encrypted message to decrypt.       * @return decrypted message.       * @throws MessageDecryptionException if the ciphertext couldn't be decrypted. @@ -178,7 +187,7 @@ public abstract class IdentityCredential {       *       * <p>If {@code readerAuth} is not {@code null} it must be the bytes of a {@code COSE_Sign1}       * structure as defined in RFC 8152. For the payload nil shall be used and the -     * detached payload is the ReaderAuthentication CBOR described below. +     * detached payload is the ReaderAuthenticationBytes CBOR described below.       * <pre>       *     ReaderAuthentication = [       *       "ReaderAuthentication", @@ -186,7 +195,9 @@ public abstract class IdentityCredential {       *       ItemsRequestBytes       *     ]       * -     *     ItemsRequestBytes = #6.24(bstr .cbor ItemsRequest)   ; Bytes of ItemsRequest +     *     ItemsRequestBytes = #6.24(bstr .cbor ItemsRequest) +     * +     *     ReaderAuthenticationBytes = #6.24(bstr .cbor ReaderAuthentication)       * </pre>       *       * <p>where {@code ItemsRequestBytes} are the bytes in the {@code requestMessage} parameter. diff --git a/identity/java/android/security/identity/ResultData.java b/identity/java/android/security/identity/ResultData.java index 37de2c4a50ea..71860d261285 100644 --- a/identity/java/android/security/identity/ResultData.java +++ b/identity/java/android/security/identity/ResultData.java @@ -68,8 +68,8 @@ public abstract class ResultData {       * {@link #getMessageAuthenticationCode()} can be used to get a MAC.       *       * <p>The CBOR structure which is cryptographically authenticated is the -     * {@code DeviceAuthentication} structure according to the following -     * <a href="https://tools.ietf.org/html/draft-ietf-cbor-cddl-06">CDDL</a> schema: +     * {@code DeviceAuthenticationBytes} structure according to the following +     * <a href="https://tools.ietf.org/html/rfc8610">CDDL</a> schema:       *       * <pre>       *   DeviceAuthentication = [ @@ -80,15 +80,9 @@ public abstract class ResultData {       *   ]       *       *   DocType = tstr -     * -     *   SessionTranscript = [ -     *     DeviceEngagementBytes, -     *     EReaderKeyBytes -     *   ] -     * -     *   DeviceEngagementBytes = #6.24(bstr .cbor DeviceEngagement) -     *   EReaderKeyBytes = #6.24(bstr .cbor EReaderKey.Pub) +     *   SessionTranscript = any       *   DeviceNameSpacesBytes = #6.24(bstr .cbor DeviceNameSpaces) +     *   DeviceAuthenticationBytes = #6.24(bstr .cbor DeviceAuthentication)       * </pre>       *       * <p>where @@ -115,7 +109,7 @@ public abstract class ResultData {      public abstract @NonNull byte[] getAuthenticatedData();      /** -     * Returns a message authentication code over the {@code DeviceAuthentication} CBOR +     * Returns a message authentication code over the {@code DeviceAuthenticationBytes} CBOR       * specified in {@link #getAuthenticatedData()}, to prove to the reader that the data       * is from a trusted credential.       * diff --git a/media/jni/android_media_JetPlayer.cpp b/media/jni/android_media_JetPlayer.cpp index 8a05f85e4285..481f80b278f8 100644 --- a/media/jni/android_media_JetPlayer.cpp +++ b/media/jni/android_media_JetPlayer.cpp @@ -23,7 +23,7 @@  #include <fcntl.h>  #include <jni.h> -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include "core_jni_helpers.h"  #include <utils/Log.h> diff --git a/media/jni/android_media_MediaExtractor.cpp b/media/jni/android_media_MediaExtractor.cpp index f5ae9d0d5d2f..0d395e58a3c5 100644 --- a/media/jni/android_media_MediaExtractor.cpp +++ b/media/jni/android_media_MediaExtractor.cpp @@ -28,7 +28,7 @@  #include "android_runtime/Log.h"  #include "android_util_Binder.h"  #include "jni.h" -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include <android/hardware/cas/1.0/BpHwCas.h>  #include <android/hardware/cas/1.0/BnHwCas.h> diff --git a/media/jni/android_media_MediaMetadataRetriever.cpp b/media/jni/android_media_MediaMetadataRetriever.cpp index a4807843d7d8..91cd6d3826f6 100644 --- a/media/jni/android_media_MediaMetadataRetriever.cpp +++ b/media/jni/android_media_MediaMetadataRetriever.cpp @@ -30,7 +30,7 @@  #include <private/media/VideoFrame.h>  #include "jni.h" -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include "android_runtime/AndroidRuntime.h"  #include "android_media_MediaDataSource.h"  #include "android_media_Streams.h" diff --git a/media/jni/android_media_MediaMuxer.cpp b/media/jni/android_media_MediaMuxer.cpp index f0aa4c3f1ab6..243ee4f7ebba 100644 --- a/media/jni/android_media_MediaMuxer.cpp +++ b/media/jni/android_media_MediaMuxer.cpp @@ -21,7 +21,7 @@  #include "android_media_Streams.h"  #include "android_runtime/AndroidRuntime.h"  #include "jni.h" -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include <unistd.h>  #include <fcntl.h> diff --git a/media/jni/android_media_MediaPlayer.cpp b/media/jni/android_media_MediaPlayer.cpp index ec0ce8759571..52e266129875 100644 --- a/media/jni/android_media_MediaPlayer.cpp +++ b/media/jni/android_media_MediaPlayer.cpp @@ -32,7 +32,7 @@  #include <fcntl.h>  #include <utils/threads.h>  #include "jni.h" -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include "android_runtime/AndroidRuntime.h"  #include "android_runtime/android_view_Surface.h"  #include "android_runtime/Log.h" diff --git a/media/jni/android_media_MediaRecorder.cpp b/media/jni/android_media_MediaRecorder.cpp index 24fff0635238..a70de6d6f5d3 100644 --- a/media/jni/android_media_MediaRecorder.cpp +++ b/media/jni/android_media_MediaRecorder.cpp @@ -37,7 +37,7 @@  #include <nativehelper/ScopedUtfChars.h>  #include "jni.h" -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include "android_media_AudioErrors.h"  #include "android_media_MediaMetricsJNI.h"  #include "android_media_MicrophoneInfo.h" diff --git a/media/jni/android_media_MediaScanner.cpp b/media/jni/android_media_MediaScanner.cpp index 58044c0307eb..1fb0faa5cd58 100644 --- a/media/jni/android_media_MediaScanner.cpp +++ b/media/jni/android_media_MediaScanner.cpp @@ -24,7 +24,7 @@  #include <private/media/VideoFrame.h>  #include "jni.h" -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include "android_runtime/AndroidRuntime.h"  #include "android_runtime/Log.h"  #include <android-base/macros.h>                // for FALLTHROUGH_INTENDED diff --git a/media/jni/android_mtp_MtpServer.cpp b/media/jni/android_mtp_MtpServer.cpp index 39ff04ab2a0a..8a1ae9252ca3 100644 --- a/media/jni/android_mtp_MtpServer.cpp +++ b/media/jni/android_mtp_MtpServer.cpp @@ -25,7 +25,7 @@  #include <utils/threads.h>  #include "jni.h" -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include "android_runtime/AndroidRuntime.h"  #include "private/android_filesystem_config.h" diff --git a/media/jni/soundpool/android_media_SoundPool.cpp b/media/jni/soundpool/android_media_SoundPool.cpp index f6706369f379..bfecd6b30179 100644 --- a/media/jni/soundpool/android_media_SoundPool.cpp +++ b/media/jni/soundpool/android_media_SoundPool.cpp @@ -21,7 +21,7 @@  #include <utils/Log.h>  #include <jni.h> -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include <android_runtime/AndroidRuntime.h>  #include "SoundPool.h" diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java index 65f68cc5c5b5..5dc1a7734521 100644 --- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java +++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java @@ -1074,6 +1074,10 @@ class SettingsProtoDumpUtil {                  Settings.Global.NSD_ON,                  GlobalSettingsProto.NSD_ON); +        dumpSetting(s, p, +                Settings.Global.NR_NSA_TRACKING_SCREEN_OFF_MODE, +                GlobalSettingsProto.NR_NSA_TRACKING_SCREEN_OFF_MODE); +          final long ntpToken = p.start(GlobalSettingsProto.NTP);          dumpSetting(s, p,                  Settings.Global.NTP_SERVER, diff --git a/packages/Tethering/jarjar-rules.txt b/packages/Tethering/jarjar-rules.txt index e90a2ccaa2a3..8f072e4cd217 100644 --- a/packages/Tethering/jarjar-rules.txt +++ b/packages/Tethering/jarjar-rules.txt @@ -15,3 +15,6 @@ rule com.android.internal.util.TrafficStatsConstants* com.android.networkstack.t  rule android.net.LocalLog* com.android.networkstack.tethering.LocalLog@1  rule android.net.shared.Inet4AddressUtils* com.android.networkstack.tethering.shared.Inet4AddressUtils@1 + +# Classes from net-utils-framework-common +rule com.android.net.module.util.** com.android.networkstack.tethering.util.@1
\ No newline at end of file diff --git a/packages/Tethering/jni/android_net_util_TetheringUtils.cpp b/packages/Tethering/jni/android_net_util_TetheringUtils.cpp index 549344064405..f6eb40a842d5 100644 --- a/packages/Tethering/jni/android_net_util_TetheringUtils.cpp +++ b/packages/Tethering/jni/android_net_util_TetheringUtils.cpp @@ -18,6 +18,7 @@  #include <error.h>  #include <jni.h>  #include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIHelpCompat.h>  #include <nativehelper/ScopedUtfChars.h>  #include <net/if.h>  #include <netinet/icmp6.h> diff --git a/packages/Tethering/src/com/android/networkstack/tethering/OffloadHardwareInterface.java b/packages/Tethering/src/com/android/networkstack/tethering/OffloadHardwareInterface.java index fe92204c25c8..33b9d00e70dc 100644 --- a/packages/Tethering/src/com/android/networkstack/tethering/OffloadHardwareInterface.java +++ b/packages/Tethering/src/com/android/networkstack/tethering/OffloadHardwareInterface.java @@ -16,8 +16,11 @@  package com.android.networkstack.tethering; +import static android.net.netlink.StructNlMsgHdr.NLM_F_DUMP; +import static android.net.netlink.StructNlMsgHdr.NLM_F_REQUEST;  import static android.net.util.TetheringUtils.uint16; +import android.annotation.NonNull;  import android.hardware.tetheroffload.config.V1_0.IOffloadConfig;  import android.hardware.tetheroffload.control.V1_0.IOffloadControl;  import android.hardware.tetheroffload.control.V1_0.ITetheringOffloadCallback; @@ -25,6 +28,7 @@ import android.hardware.tetheroffload.control.V1_0.NatTimeoutUpdate;  import android.hardware.tetheroffload.control.V1_0.NetworkProtocol;  import android.hardware.tetheroffload.control.V1_0.OffloadCallbackEvent;  import android.net.netlink.NetlinkSocket; +import android.net.netlink.StructNlMsgHdr;  import android.net.util.SharedLog;  import android.net.util.SocketUtils;  import android.os.Handler; @@ -37,9 +41,11 @@ import android.system.OsConstants;  import com.android.internal.annotations.VisibleForTesting;  import java.io.FileDescriptor; +import java.io.InterruptedIOException;  import java.io.IOException;  import java.net.SocketAddress;  import java.net.SocketException; +import java.nio.ByteBuffer;  import java.util.ArrayList;  import java.util.NoSuchElementException; @@ -63,6 +69,11 @@ public class OffloadHardwareInterface {      private static final int NF_NETLINK_CONNTRACK_NEW = 1;      private static final int NF_NETLINK_CONNTRACK_UPDATE = 2;      private static final int NF_NETLINK_CONNTRACK_DESTROY = 4; +    // Reference libnetfilter_conntrack/linux_nfnetlink_conntrack.h +    public static final short NFNL_SUBSYS_CTNETLINK = 1; +    public static final short IPCTNL_MSG_CT_GET = 1; + +    private final long NETLINK_MESSAGE_TIMEOUT_MS = 500;      private final Handler mHandler;      private final SharedLog mLog; @@ -226,6 +237,9 @@ public class OffloadHardwareInterface {                  NF_NETLINK_CONNTRACK_NEW | NF_NETLINK_CONNTRACK_DESTROY);          if (h1 == null) return false; +        sendNetlinkMessage(h1, (short) ((NFNL_SUBSYS_CTNETLINK << 8) | IPCTNL_MSG_CT_GET), +                           (short) (NLM_F_REQUEST | NLM_F_DUMP)); +          final NativeHandle h2 = mDeps.createConntrackSocket(                  NF_NETLINK_CONNTRACK_UPDATE | NF_NETLINK_CONNTRACK_DESTROY);          if (h2 == null) { @@ -252,6 +266,25 @@ public class OffloadHardwareInterface {          return results.mSuccess;      } +    @VisibleForTesting +    public void sendNetlinkMessage(@NonNull NativeHandle handle, short type, short flags) { +        final int length = StructNlMsgHdr.STRUCT_SIZE; +        final byte[] msg = new byte[length]; +        final StructNlMsgHdr nlh = new StructNlMsgHdr(); +        final ByteBuffer byteBuffer = ByteBuffer.wrap(msg); +        nlh.nlmsg_len = length; +        nlh.nlmsg_type = type; +        nlh.nlmsg_flags = flags; +        nlh.nlmsg_seq = 1; +        nlh.pack(byteBuffer); +        try { +            NetlinkSocket.sendMessage(handle.getFileDescriptor(), msg, 0 /* offset */, length, +                                      NETLINK_MESSAGE_TIMEOUT_MS); +        } catch (ErrnoException | InterruptedIOException e) { +            mLog.e("Unable to send netfilter message, error: " + e); +        } +    } +      private void closeFdInNativeHandle(final NativeHandle h) {          try {              h.close(); diff --git a/packages/Tethering/tests/unit/src/com/android/networkstack/tethering/OffloadHardwareInterfaceTest.java b/packages/Tethering/tests/unit/src/com/android/networkstack/tethering/OffloadHardwareInterfaceTest.java index f8ff1cb29c23..c543fad62dba 100644 --- a/packages/Tethering/tests/unit/src/com/android/networkstack/tethering/OffloadHardwareInterfaceTest.java +++ b/packages/Tethering/tests/unit/src/com/android/networkstack/tethering/OffloadHardwareInterfaceTest.java @@ -17,13 +17,17 @@  package com.android.networkstack.tethering;  import static android.net.util.TetheringUtils.uint16; +import static android.system.OsConstants.SOCK_STREAM; +import static android.system.OsConstants.AF_UNIX;  import static org.junit.Assert.assertEquals;  import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail;  import static org.mockito.ArgumentMatchers.any;  import static org.mockito.ArgumentMatchers.eq;  import static org.mockito.Mockito.spy;  import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when;  import android.hardware.tetheroffload.config.V1_0.IOffloadConfig;  import android.hardware.tetheroffload.control.V1_0.IOffloadControl; @@ -31,11 +35,14 @@ import android.hardware.tetheroffload.control.V1_0.ITetheringOffloadCallback;  import android.hardware.tetheroffload.control.V1_0.NatTimeoutUpdate;  import android.hardware.tetheroffload.control.V1_0.NetworkProtocol;  import android.hardware.tetheroffload.control.V1_0.OffloadCallbackEvent; +import android.net.netlink.StructNlMsgHdr;  import android.net.util.SharedLog;  import android.os.Handler;  import android.os.NativeHandle;  import android.os.test.TestLooper; +import android.system.ErrnoException;  import android.system.OsConstants; +import android.system.Os;  import androidx.test.filters.SmallTest;  import androidx.test.runner.AndroidJUnit4; @@ -47,6 +54,9 @@ import org.mockito.ArgumentCaptor;  import org.mockito.Mock;  import org.mockito.MockitoAnnotations; +import java.io.FileDescriptor; +import java.io.OutputStream; +import java.nio.ByteBuffer;  import java.util.ArrayList;  @RunWith(AndroidJUnit4.class) @@ -64,6 +74,10 @@ public final class OffloadHardwareInterfaceTest {      @Mock private IOffloadControl mIOffloadControl;      @Mock private NativeHandle mNativeHandle; +    // Random values to test Netlink message. +    private static final short TEST_TYPE = 184; +    private static final short TEST_FLAGS = 263; +      class MyDependencies extends OffloadHardwareInterface.Dependencies {          MyDependencies(SharedLog log) {              super(log); @@ -203,6 +217,31 @@ public final class OffloadHardwareInterfaceTest {                  eq(uint16(udpParams.dst.port)));      } +    @Test +    public void testNetlinkMessage() throws Exception { +        FileDescriptor writeSocket = new FileDescriptor(); +        FileDescriptor readSocket = new FileDescriptor(); +        try { +            Os.socketpair(AF_UNIX, SOCK_STREAM, 0, writeSocket, readSocket); +        } catch (ErrnoException e) { +            fail(); +            return; +        } +        when(mNativeHandle.getFileDescriptor()).thenReturn(writeSocket); + +        mOffloadHw.sendNetlinkMessage(mNativeHandle, TEST_TYPE, TEST_FLAGS); + +        ByteBuffer buffer = ByteBuffer.allocate(StructNlMsgHdr.STRUCT_SIZE); +        int read = Os.read(readSocket, buffer); + +        buffer.flip(); +        assertEquals(StructNlMsgHdr.STRUCT_SIZE, buffer.getInt()); +        assertEquals(TEST_TYPE, buffer.getShort()); +        assertEquals(TEST_FLAGS, buffer.getShort()); +        assertEquals(1 /* seq */, buffer.getInt()); +        assertEquals(0 /* pid */, buffer.getInt()); +    } +      private NatTimeoutUpdate buildNatTimeoutUpdate(final int proto) {          final NatTimeoutUpdate params = new NatTimeoutUpdate();          params.proto = proto; diff --git a/services/core/java/com/android/server/compat/TEST_MAPPING b/services/core/java/com/android/server/compat/TEST_MAPPING index 0c30c790c5dd..dc1e2cb0c803 100644 --- a/services/core/java/com/android/server/compat/TEST_MAPPING +++ b/services/core/java/com/android/server/compat/TEST_MAPPING @@ -15,7 +15,7 @@          },          // CTS tests          { -            "name": "CtsAppCompatHostTestCases#" +            "name": "CtsAppCompatHostTestCases"          }      ] -}
\ No newline at end of file +} diff --git a/services/core/jni/com_android_server_AlarmManagerService.cpp b/services/core/jni/com_android_server_AlarmManagerService.cpp index a99c0a3fa23e..335040a4b92f 100644 --- a/services/core/jni/com_android_server_AlarmManagerService.cpp +++ b/services/core/jni/com_android_server_AlarmManagerService.cpp @@ -1,5 +1,4 @@ -/* //device/libs/android_runtime/android_server_AlarmManagerService.cpp -** +/*  ** Copyright 2006, The Android Open Source Project  **  ** Licensed under the Apache License, Version 2.0 (the "License"); @@ -19,6 +18,8 @@  #include <nativehelper/JNIHelp.h>  #include "jni.h" +#include <android-base/file.h> +#include <android-base/unique_fd.h>  #include <utils/Log.h>  #include <utils/misc.h>  #include <utils/String8.h> @@ -75,8 +76,8 @@ typedef std::array<int, N_ANDROID_TIMERFDS> TimerFds;  class AlarmImpl  {  public: -    AlarmImpl(const TimerFds &fds, int epollfd, int rtc_id) : -        fds{fds}, epollfd{epollfd}, rtc_id{rtc_id} { } +    AlarmImpl(const TimerFds &fds, int epollfd, const std::string& rtc_dev) : +        fds{fds}, epollfd{epollfd}, rtc_dev{rtc_dev} { }      ~AlarmImpl();      int set(int type, struct timespec *ts); @@ -87,7 +88,7 @@ public:  private:      const TimerFds fds;      const int epollfd; -    const int rtc_id; +    std::string rtc_dev;  };  AlarmImpl::~AlarmImpl() @@ -132,38 +133,24 @@ int AlarmImpl::getTime(int type, struct itimerspec *spec)  int AlarmImpl::setTime(struct timeval *tv)  { -    struct rtc_time rtc; -    struct tm tm, *gmtime_res; -    int fd; -    int res; - -    res = settimeofday(tv, NULL); -    if (res < 0) { -        ALOGV("settimeofday() failed: %s\n", strerror(errno)); +    if (settimeofday(tv, NULL) == -1) { +        ALOGV("settimeofday() failed: %s", strerror(errno));          return -1;      } -    if (rtc_id < 0) { -        ALOGV("Not setting RTC because wall clock RTC was not found"); -        errno = ENODEV; +    android::base::unique_fd fd{open(rtc_dev.c_str(), O_RDWR)}; +    if (!fd.ok()) { +        ALOGE("Unable to open %s: %s", rtc_dev.c_str(), strerror(errno));          return -1;      } -    android::String8 rtc_dev = String8::format("/dev/rtc%d", rtc_id); -    fd = open(rtc_dev.string(), O_RDWR); -    if (fd < 0) { -        ALOGV("Unable to open %s: %s\n", rtc_dev.string(), strerror(errno)); -        return res; -    } - -    gmtime_res = gmtime_r(&tv->tv_sec, &tm); -    if (!gmtime_res) { -        ALOGV("gmtime_r() failed: %s\n", strerror(errno)); -        res = -1; -        goto done; +    struct tm tm; +    if (!gmtime_r(&tv->tv_sec, &tm)) { +        ALOGV("gmtime_r() failed: %s", strerror(errno)); +        return -1;      } -    memset(&rtc, 0, sizeof(rtc)); +    struct rtc_time rtc = {};      rtc.tm_sec = tm.tm_sec;      rtc.tm_min = tm.tm_min;      rtc.tm_hour = tm.tm_hour; @@ -173,12 +160,12 @@ int AlarmImpl::setTime(struct timeval *tv)      rtc.tm_wday = tm.tm_wday;      rtc.tm_yday = tm.tm_yday;      rtc.tm_isdst = tm.tm_isdst; -    res = ioctl(fd, RTC_SET_TIME, &rtc); -    if (res < 0) -        ALOGV("RTC_SET_TIME ioctl failed: %s\n", strerror(errno)); -done: -    close(fd); -    return res; +    if (ioctl(fd, RTC_SET_TIME, &rtc) == -1) { +        ALOGV("RTC_SET_TIME ioctl failed: %s", strerror(errno)); +        return -1; +    } + +    return 0;  }  int AlarmImpl::waitForAlarm() @@ -251,65 +238,6 @@ static jint android_server_AlarmManagerService_setKernelTimezone(JNIEnv*, jobjec      return 0;  } -static const char rtc_sysfs[] = "/sys/class/rtc"; - -static bool rtc_is_hctosys(unsigned int rtc_id) -{ -    android::String8 hctosys_path = String8::format("%s/rtc%u/hctosys", -            rtc_sysfs, rtc_id); -    FILE *file = fopen(hctosys_path.string(), "re"); -    if (!file) { -        ALOGE("failed to open %s: %s", hctosys_path.string(), strerror(errno)); -        return false; -    } - -    unsigned int hctosys; -    bool ret = false; -    int err = fscanf(file, "%u", &hctosys); -    if (err == EOF) -        ALOGE("failed to read from %s: %s", hctosys_path.string(), -                strerror(errno)); -    else if (err == 0) -        ALOGE("%s did not have expected contents", hctosys_path.string()); -    else -        ret = hctosys; - -    fclose(file); -    return ret; -} - -static int wall_clock_rtc() -{ -    std::unique_ptr<DIR, int(*)(DIR*)> dir(opendir(rtc_sysfs), closedir); -    if (!dir.get()) { -        ALOGE("failed to open %s: %s", rtc_sysfs, strerror(errno)); -        return -1; -    } - -    struct dirent *dirent; -    while (errno = 0, dirent = readdir(dir.get())) { -        unsigned int rtc_id; -        int matched = sscanf(dirent->d_name, "rtc%u", &rtc_id); - -        if (matched < 0) -            break; -        else if (matched != 1) -            continue; - -        if (rtc_is_hctosys(rtc_id)) { -            ALOGV("found wall clock RTC %u", rtc_id); -            return rtc_id; -        } -    } - -    if (errno == 0) -        ALOGW("no wall clock RTC found"); -    else -        ALOGE("failed to enumerate RTCs: %s", strerror(errno)); - -    return -1; -} -  static void log_timerfd_create_error(clockid_t id)  {      if (errno == EINVAL) { @@ -343,8 +271,7 @@ static jlong android_server_AlarmManagerService_init(JNIEnv*, jobject)      epollfd = epoll_create(fds.size());      if (epollfd < 0) { -        ALOGE("epoll_create(%zu) failed: %s", fds.size(), -                strerror(errno)); +        ALOGE("epoll_create(%zu) failed: %s", fds.size(), strerror(errno));          return 0;      } @@ -360,7 +287,19 @@ static jlong android_server_AlarmManagerService_init(JNIEnv*, jobject)          }      } -    AlarmImpl *ret = new AlarmImpl(fds, epollfd, wall_clock_rtc()); +    // Find the wall clock RTC. We expect this always to be /dev/rtc0, but +    // check the /dev/rtc symlink first so that legacy devices that don't use +    // rtc0 can add a symlink rather than need to carry a local patch to this +    // code. +    // +    // TODO: if you're reading this in a world where all devices are using the +    // GKI, you can remove the readlink and just assume /dev/rtc0. +    std::string dev_rtc; +    if (!android::base::Readlink("/dev/rtc", &dev_rtc)) { +        dev_rtc = "/dev/rtc0"; +    } + +    std::unique_ptr<AlarmImpl> alarm{new AlarmImpl(fds, epollfd, dev_rtc)};      for (size_t i = 0; i < fds.size(); i++) {          epoll_event event; @@ -370,13 +309,11 @@ static jlong android_server_AlarmManagerService_init(JNIEnv*, jobject)          int err = epoll_ctl(epollfd, EPOLL_CTL_ADD, fds[i], &event);          if (err < 0) {              ALOGE("epoll_ctl(EPOLL_CTL_ADD) failed: %s", strerror(errno)); -            delete ret;              return 0;          }      } -    struct itimerspec spec; -    memset(&spec, 0, sizeof(spec)); +    struct itimerspec spec = {};      /* 0 = disarmed; the timerfd doesn't need to be armed to get         RTC change notifications, just set up as cancelable */ @@ -384,11 +321,10 @@ static jlong android_server_AlarmManagerService_init(JNIEnv*, jobject)              TFD_TIMER_ABSTIME | TFD_TIMER_CANCEL_ON_SET, &spec, NULL);      if (err < 0) {          ALOGE("timerfd_settime() failed: %s", strerror(errno)); -        delete ret;          return 0;      } -    return reinterpret_cast<jlong>(ret); +    return reinterpret_cast<jlong>(alarm.release());  }  static jlong android_server_AlarmManagerService_getNextAlarm(JNIEnv*, jobject, jlong nativeData, jint type) diff --git a/services/core/jni/com_android_server_SerialService.cpp b/services/core/jni/com_android_server_SerialService.cpp index c9459994a658..6600c981b68d 100644 --- a/services/core/jni/com_android_server_SerialService.cpp +++ b/services/core/jni/com_android_server_SerialService.cpp @@ -18,7 +18,7 @@  #include "utils/Log.h"  #include "jni.h" -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include "android_runtime/AndroidRuntime.h"  #include <sys/types.h> diff --git a/services/core/jni/com_android_server_UsbDeviceManager.cpp b/services/core/jni/com_android_server_UsbDeviceManager.cpp index 72dce4dca0da..3ab5920d8b59 100644 --- a/services/core/jni/com_android_server_UsbDeviceManager.cpp +++ b/services/core/jni/com_android_server_UsbDeviceManager.cpp @@ -18,7 +18,7 @@  #include "utils/Log.h"  #include "jni.h" -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include <nativehelper/ScopedUtfChars.h>  #include "android_runtime/AndroidRuntime.h"  #include "android_runtime/Log.h" diff --git a/services/core/jni/com_android_server_UsbHostManager.cpp b/services/core/jni/com_android_server_UsbHostManager.cpp index a40bcd0d7c07..a629b69c1c27 100644 --- a/services/core/jni/com_android_server_UsbHostManager.cpp +++ b/services/core/jni/com_android_server_UsbHostManager.cpp @@ -18,7 +18,7 @@  #include "utils/Log.h"  #include "jni.h" -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include "android_runtime/AndroidRuntime.h"  #include "android_runtime/Log.h" diff --git a/services/core/jni/com_android_server_UsbMidiDevice.cpp b/services/core/jni/com_android_server_UsbMidiDevice.cpp index 8ac2c4f37ecd..d6b5bed173eb 100644 --- a/services/core/jni/com_android_server_UsbMidiDevice.cpp +++ b/services/core/jni/com_android_server_UsbMidiDevice.cpp @@ -19,7 +19,7 @@  #include "utils/Log.h"  #include "jni.h" -#include <nativehelper/JNIHelp.h> +#include <nativehelper/JNIPlatformHelp.h>  #include <nativehelper/ScopedLocalRef.h>  #include "android_runtime/AndroidRuntime.h"  #include "android_runtime/Log.h" diff --git a/telephony/java/android/telephony/CarrierConfigManager.java b/telephony/java/android/telephony/CarrierConfigManager.java index 0690a90a9808..d319e37c4ba6 100644 --- a/telephony/java/android/telephony/CarrierConfigManager.java +++ b/telephony/java/android/telephony/CarrierConfigManager.java @@ -560,6 +560,15 @@ public class CarrierConfigManager {      public static final String KEY_CARRIER_VT_AVAILABLE_BOOL = "carrier_vt_available_bool";      /** +     * Flag specifying whether to show an alert dialog for 5G disable when the user disables VoLTE. +     * By default this value is {@code false}. +     * +     * @hide +     */ +    public static final String KEY_VOLTE_5G_LIMITED_ALERT_DIALOG_BOOL = +            "volte_5g_limited_alert_dialog_bool"; + +    /**       * Flag specifying whether the carrier wants to notify the user when a VT call has been handed       * over from WIFI to LTE.       * <p> @@ -1405,6 +1414,14 @@ public class CarrierConfigManager {      public static final String KEY_CARRIER_NAME_STRING = "carrier_name_string";      /** +     * To override wifi calling's carrier name string using ef_pnn from sim card when SPN in empty. +     * +     * @hide +     */ +    public static final String KEY_WFC_CARRIER_NAME_OVERRIDE_BY_PNN_BOOL = +            "wfc_carrier_name_override_by_pnn_bool"; + +    /**       * Override the SPN Display Condition 2 integer bits (lsb). B2, B1 is the last two bits of the       * spn display condition coding.       * @@ -3781,6 +3798,7 @@ public class CarrierConfigManager {          sDefaults.putBoolean(KEY_CARRIER_SETTINGS_ENABLE_BOOL, false);          sDefaults.putBoolean(KEY_CARRIER_VOLTE_AVAILABLE_BOOL, false);          sDefaults.putBoolean(KEY_CARRIER_VT_AVAILABLE_BOOL, false); +        sDefaults.putBoolean(KEY_VOLTE_5G_LIMITED_ALERT_DIALOG_BOOL, false);          sDefaults.putBoolean(KEY_NOTIFY_HANDOVER_VIDEO_FROM_WIFI_TO_LTE_BOOL, false);          sDefaults.putBoolean(KEY_ALLOW_MERGING_RTT_CALLS_BOOL, false);          sDefaults.putBoolean(KEY_NOTIFY_HANDOVER_VIDEO_FROM_LTE_TO_WIFI_BOOL, false); @@ -3960,6 +3978,7 @@ public class CarrierConfigManager {          sDefaults.putBoolean(KEY_CONFIG_WIFI_DISABLE_IN_ECBM, false);          sDefaults.putBoolean(KEY_CARRIER_NAME_OVERRIDE_BOOL, false);          sDefaults.putString(KEY_CARRIER_NAME_STRING, ""); +        sDefaults.putBoolean(KEY_WFC_CARRIER_NAME_OVERRIDE_BY_PNN_BOOL, false);          sDefaults.putInt(KEY_SPN_DISPLAY_CONDITION_OVERRIDE_INT, -1);          sDefaults.putStringArray(KEY_SPDI_OVERRIDE_STRING_ARRAY, null);          sDefaults.putStringArray(KEY_PNN_OVERRIDE_STRING_ARRAY, null); diff --git a/telephony/java/android/telephony/ims/feature/MmTelFeature.java b/telephony/java/android/telephony/ims/feature/MmTelFeature.java index 6840e8eed318..5ee6ec957b50 100644 --- a/telephony/java/android/telephony/ims/feature/MmTelFeature.java +++ b/telephony/java/android/telephony/ims/feature/MmTelFeature.java @@ -346,7 +346,6 @@ public class MmTelFeature extends ImsFeature {           * @hide           */          @Override -        @SystemApi @TestApi          public void onIncomingCall(IImsCallSession c, Bundle extras) {          } @@ -358,7 +357,6 @@ public class MmTelFeature extends ImsFeature {           * @hide           */          @Override -        @SystemApi @TestApi          public void onRejectedCall(ImsCallProfile callProfile, ImsReasonInfo reason) {          } @@ -369,7 +367,6 @@ public class MmTelFeature extends ImsFeature {           * @hide           */          @Override -        @SystemApi @TestApi          public void onVoiceMessageCountUpdate(int count) {          } diff --git a/tests/net/java/android/net/DnsPacketTest.java b/tests/net/java/android/net/DnsPacketTest.java deleted file mode 100644 index 975abf416944..000000000000 --- a/tests/net/java/android/net/DnsPacketTest.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright (C) 2019 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.net; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import androidx.test.filters.SmallTest; -import androidx.test.runner.AndroidJUnit4; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import java.util.Arrays; -import java.util.List; - -@RunWith(AndroidJUnit4.class) -@SmallTest -public class DnsPacketTest { -    private void assertHeaderParses(DnsPacket.DnsHeader header, int id, int flag, -            int qCount, int aCount, int nsCount, int arCount) { -        assertEquals(header.id, id); -        assertEquals(header.flags, flag); -        assertEquals(header.getRecordCount(DnsPacket.QDSECTION), qCount); -        assertEquals(header.getRecordCount(DnsPacket.ANSECTION), aCount); -        assertEquals(header.getRecordCount(DnsPacket.NSSECTION), nsCount); -        assertEquals(header.getRecordCount(DnsPacket.ARSECTION), arCount); -    } - -    private void assertRecordParses(DnsPacket.DnsRecord record, String dname, -            int dtype, int dclass, int ttl, byte[] rr) { -        assertEquals(record.dName, dname); -        assertEquals(record.nsType, dtype); -        assertEquals(record.nsClass, dclass); -        assertEquals(record.ttl, ttl); -        assertTrue(Arrays.equals(record.getRR(), rr)); -    } - -    class TestDnsPacket extends DnsPacket { -        TestDnsPacket(byte[] data) throws ParseException { -            super(data); -        } - -        public DnsHeader getHeader() { -            return mHeader; -        } -        public List<DnsRecord> getRecordList(int secType) { -            return mRecords[secType]; -        } -    } - -    @Test -    public void testNullDisallowed() { -        try { -            new TestDnsPacket(null); -            fail("Exception not thrown for null byte array"); -        } catch (ParseException e) { -        } -    } - -    @Test -    public void testV4Answer() throws Exception { -        final byte[] v4blob = new byte[] { -            /* Header */ -            0x55, 0x66, /* Transaction ID */ -            (byte) 0x81, (byte) 0x80, /* Flags */ -            0x00, 0x01, /* Questions */ -            0x00, 0x01, /* Answer RRs */ -            0x00, 0x00, /* Authority RRs */ -            0x00, 0x00, /* Additional RRs */ -            /* Queries */ -            0x03, 0x77, 0x77, 0x77, 0x06, 0x67, 0x6F, 0x6F, 0x67, 0x6c, 0x65, -            0x03, 0x63, 0x6f, 0x6d, 0x00, /* Name */ -            0x00, 0x01, /* Type */ -            0x00, 0x01, /* Class */ -            /* Answers */ -            (byte) 0xc0, 0x0c, /* Name */ -            0x00, 0x01, /* Type */ -            0x00, 0x01, /* Class */ -            0x00, 0x00, 0x01, 0x2b, /* TTL */ -            0x00, 0x04, /* Data length */ -            (byte) 0xac, (byte) 0xd9, (byte) 0xa1, (byte) 0x84 /* Address */ -        }; -        TestDnsPacket packet = new TestDnsPacket(v4blob); - -        // Header part -        assertHeaderParses(packet.getHeader(), 0x5566, 0x8180, 1, 1, 0, 0); - -        // Record part -        List<DnsPacket.DnsRecord> qdRecordList = -                packet.getRecordList(DnsPacket.QDSECTION); -        assertEquals(qdRecordList.size(), 1); -        assertRecordParses(qdRecordList.get(0), "www.google.com", 1, 1, 0, null); - -        List<DnsPacket.DnsRecord> anRecordList = -                packet.getRecordList(DnsPacket.ANSECTION); -        assertEquals(anRecordList.size(), 1); -        assertRecordParses(anRecordList.get(0), "www.google.com", 1, 1, 0x12b, -                new byte[]{ (byte) 0xac, (byte) 0xd9, (byte) 0xa1, (byte) 0x84 }); -    } - -    @Test -    public void testV6Answer() throws Exception { -        final byte[] v6blob = new byte[] { -            /* Header */ -            0x77, 0x22, /* Transaction ID */ -            (byte) 0x81, (byte) 0x80, /* Flags */ -            0x00, 0x01, /* Questions */ -            0x00, 0x01, /* Answer RRs */ -            0x00, 0x00, /* Authority RRs */ -            0x00, 0x00, /* Additional RRs */ -            /* Queries */ -            0x03, 0x77, 0x77, 0x77, 0x06, 0x67, 0x6F, 0x6F, 0x67, 0x6c, 0x65, -            0x03, 0x63, 0x6f, 0x6d, 0x00, /* Name */ -            0x00, 0x1c, /* Type */ -            0x00, 0x01, /* Class */ -            /* Answers */ -            (byte) 0xc0, 0x0c, /* Name */ -            0x00, 0x1c, /* Type */ -            0x00, 0x01, /* Class */ -            0x00, 0x00, 0x00, 0x37, /* TTL */ -            0x00, 0x10, /* Data length */ -            0x24, 0x04, 0x68, 0x00, 0x40, 0x05, 0x08, 0x0d, -            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x04 /* Address */ -        }; -        TestDnsPacket packet = new TestDnsPacket(v6blob); - -        // Header part -        assertHeaderParses(packet.getHeader(), 0x7722, 0x8180, 1, 1, 0, 0); - -        // Record part -        List<DnsPacket.DnsRecord> qdRecordList = -                packet.getRecordList(DnsPacket.QDSECTION); -        assertEquals(qdRecordList.size(), 1); -        assertRecordParses(qdRecordList.get(0), "www.google.com", 28, 1, 0, null); - -        List<DnsPacket.DnsRecord> anRecordList = -                packet.getRecordList(DnsPacket.ANSECTION); -        assertEquals(anRecordList.size(), 1); -        assertRecordParses(anRecordList.get(0), "www.google.com", 28, 1, 0x37, -                new byte[]{ 0x24, 0x04, 0x68, 0x00, 0x40, 0x05, 0x08, 0x0d, -                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x04 }); -    } -} diff --git a/tests/net/java/android/net/NetworkUtilsTest.java b/tests/net/java/android/net/NetworkUtilsTest.java index 7748288aeb05..3158cc8637e4 100644 --- a/tests/net/java/android/net/NetworkUtilsTest.java +++ b/tests/net/java/android/net/NetworkUtilsTest.java @@ -16,10 +16,24 @@  package android.net; +import static android.system.OsConstants.AF_INET; +import static android.system.OsConstants.AF_INET6; +import static android.system.OsConstants.AF_UNIX; +import static android.system.OsConstants.EPERM; +import static android.system.OsConstants.SOCK_DGRAM; +import static android.system.OsConstants.SOCK_STREAM; +  import static junit.framework.Assert.assertEquals; +import static org.junit.Assert.fail; + +import android.system.ErrnoException; +import android.system.Os; +  import androidx.test.runner.AndroidJUnit4; +import libcore.io.IoUtils; +  import org.junit.Test;  import org.junit.runner.RunWith; @@ -125,4 +139,50 @@ public class NetworkUtilsTest {          assertEquals(BigInteger.valueOf(7l - 4 + 4 + 16 + 65536),                  NetworkUtils.routedIPv6AddressCount(set));      } + +    private static void expectSocketSuccess(String msg, int domain, int type) { +        try { +            IoUtils.closeQuietly(Os.socket(domain, type, 0)); +        } catch (ErrnoException e) { +            fail(msg + e.getMessage()); +        } +    } + +    private static void expectSocketPemissionError(String msg, int domain, int type) { +        try { +            IoUtils.closeQuietly(Os.socket(domain, type, 0)); +            fail(msg); +        } catch (ErrnoException e) { +            assertEquals(msg, e.errno, EPERM); +        } +    } + +    private static void expectHasNetworking() { +        expectSocketSuccess("Creating a UNIX socket should not have thrown ErrnoException", +                AF_UNIX, SOCK_STREAM); +        expectSocketSuccess("Creating a AF_INET socket shouldn't have thrown ErrnoException", +                AF_INET, SOCK_DGRAM); +        expectSocketSuccess("Creating a AF_INET6 socket shouldn't have thrown ErrnoException", +                AF_INET6, SOCK_DGRAM); +    } + +    private static void expectNoNetworking() { +        expectSocketSuccess("Creating a UNIX socket should not have thrown ErrnoException", +                AF_UNIX, SOCK_STREAM); +        expectSocketPemissionError( +                "Creating a AF_INET socket should have thrown ErrnoException(EPERM)", +                AF_INET, SOCK_DGRAM); +        expectSocketPemissionError( +                "Creating a AF_INET6 socket should have thrown ErrnoException(EPERM)", +                AF_INET6, SOCK_DGRAM); +    } + +    @Test +    public void testSetAllowNetworkingForProcess() { +        expectHasNetworking(); +        NetworkUtils.setAllowNetworkingForProcess(false); +        expectNoNetworking(); +        NetworkUtils.setAllowNetworkingForProcess(true); +        expectHasNetworking(); +    }  } diff --git a/tools/aapt2/cmd/Link.cpp b/tools/aapt2/cmd/Link.cpp index 7afb0000aea1..85414fb8a4e5 100644 --- a/tools/aapt2/cmd/Link.cpp +++ b/tools/aapt2/cmd/Link.cpp @@ -1252,7 +1252,8 @@ class Linker {        return false;      } -    ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true, &fout); +    ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true, +                                   false /* strip_api_annotations */, &fout);      fout.Flush();      if (fout.HadError()) { diff --git a/tools/aapt2/java/AnnotationProcessor.cpp b/tools/aapt2/java/AnnotationProcessor.cpp index a4610b2575b9..bb667d6fa539 100644 --- a/tools/aapt2/java/AnnotationProcessor.cpp +++ b/tools/aapt2/java/AnnotationProcessor.cpp @@ -110,7 +110,7 @@ void AnnotationProcessor::AppendNewLine() {    }  } -void AnnotationProcessor::Print(Printer* printer) const { +void AnnotationProcessor::Print(Printer* printer, bool strip_api_annotations) const {    if (has_comments_) {      std::string result = comment_.str();      for (const StringPiece& line : util::Tokenize(result, '\n')) { @@ -123,6 +123,9 @@ void AnnotationProcessor::Print(Printer* printer) const {      printer->Println("@Deprecated");    } +  if (strip_api_annotations) { +    return; +  }    for (const AnnotationRule& rule : sAnnotationRules) {      if (annotation_bit_mask_ & rule.bit_mask) {        printer->Println(rule.annotation); diff --git a/tools/aapt2/java/AnnotationProcessor.h b/tools/aapt2/java/AnnotationProcessor.h index ae7bdb0c3ae2..6d768be8e7dd 100644 --- a/tools/aapt2/java/AnnotationProcessor.h +++ b/tools/aapt2/java/AnnotationProcessor.h @@ -64,7 +64,7 @@ class AnnotationProcessor {    void AppendNewLine();    // Writes the comments and annotations to the Printer. -  void Print(text::Printer* printer) const; +  void Print(text::Printer* printer, bool strip_api_annotations = false) const;   private:    std::stringstream comment_; diff --git a/tools/aapt2/java/AnnotationProcessor_test.cpp b/tools/aapt2/java/AnnotationProcessor_test.cpp index 69f49c8b97c3..c4c8ff934348 100644 --- a/tools/aapt2/java/AnnotationProcessor_test.cpp +++ b/tools/aapt2/java/AnnotationProcessor_test.cpp @@ -76,6 +76,21 @@ TEST(AnnotationProcessorTest, EmitsTestApiAnnotationAndRemovesFromComment) {    EXPECT_THAT(annotations, HasSubstr("This is a test API"));  } +TEST(AnnotationProcessorTest, NotEmitSystemApiAnnotation) { +  AnnotationProcessor processor; +  processor.AppendComment("@SystemApi This is a system API"); + +  std::string annotations; +  StringOutputStream out(&annotations); +  Printer printer(&out); +  processor.Print(&printer, true /* strip_api_annotations */); +  out.Flush(); + +  EXPECT_THAT(annotations, Not(HasSubstr("@android.annotation.SystemApi"))); +  EXPECT_THAT(annotations, Not(HasSubstr("@SystemApi"))); +  EXPECT_THAT(annotations, HasSubstr("This is a system API")); +} +  TEST(AnnotationProcessor, ExtractsFirstSentence) {    EXPECT_THAT(AnnotationProcessor::ExtractFirstSentence("This is the only sentence"),                Eq("This is the only sentence")); diff --git a/tools/aapt2/java/ClassDefinition.cpp b/tools/aapt2/java/ClassDefinition.cpp index f5f5b05491bb..3163497f0da6 100644 --- a/tools/aapt2/java/ClassDefinition.cpp +++ b/tools/aapt2/java/ClassDefinition.cpp @@ -23,15 +23,15 @@ using ::android::StringPiece;  namespace aapt { -void ClassMember::Print(bool /*final*/, Printer* printer) const { -  processor_.Print(printer); +void ClassMember::Print(bool /*final*/, Printer* printer, bool strip_api_annotations) const { +  processor_.Print(printer, strip_api_annotations);  }  void MethodDefinition::AppendStatement(const StringPiece& statement) {    statements_.push_back(statement.to_string());  } -void MethodDefinition::Print(bool final, Printer* printer) const { +void MethodDefinition::Print(bool final, Printer* printer, bool) const {    printer->Print(signature_).Println(" {");    printer->Indent();    for (const auto& statement : statements_) { @@ -74,12 +74,12 @@ bool ClassDefinition::empty() const {    return true;  } -void ClassDefinition::Print(bool final, Printer* printer) const { +void ClassDefinition::Print(bool final, Printer* printer, bool strip_api_annotations) const {    if (empty() && !create_if_empty_) {      return;    } -  ClassMember::Print(final, printer); +  ClassMember::Print(final,  printer, strip_api_annotations);    printer->Print("public ");    if (qualifier_ == ClassQualifier::kStatic) { @@ -93,7 +93,7 @@ void ClassDefinition::Print(bool final, Printer* printer) const {      // and takes precedence over a previous member with the same name. The overridden member is      // set to nullptr.      if (member != nullptr) { -      member->Print(final, printer); +      member->Print(final, printer, strip_api_annotations);        printer->Println();      }    } @@ -111,11 +111,11 @@ constexpr static const char* sWarningHeader =      " */\n\n";  void ClassDefinition::WriteJavaFile(const ClassDefinition* def, const StringPiece& package, -                                    bool final, io::OutputStream* out) { +                                    bool final, bool strip_api_annotations, io::OutputStream* out) {    Printer printer(out);    printer.Print(sWarningHeader).Print("package ").Print(package).Println(";");    printer.Println(); -  def->Print(final, &printer); +  def->Print(final, &printer, strip_api_annotations);  }  }  // namespace aapt diff --git a/tools/aapt2/java/ClassDefinition.h b/tools/aapt2/java/ClassDefinition.h index fb11266f1761..1e4b6816075a 100644 --- a/tools/aapt2/java/ClassDefinition.h +++ b/tools/aapt2/java/ClassDefinition.h @@ -50,7 +50,7 @@ class ClassMember {    // Writes the class member to the Printer. Subclasses should derive this method    // to write their own data. Call this base method from the subclass to write out    // this member's comments/annotations. -  virtual void Print(bool final, text::Printer* printer) const; +  virtual void Print(bool final, text::Printer* printer, bool strip_api_annotations = false) const;   private:    AnnotationProcessor processor_; @@ -70,10 +70,11 @@ class PrimitiveMember : public ClassMember {      return name_;    } -  void Print(bool final, text::Printer* printer) const override { +  void Print(bool final, text::Printer* printer, bool strip_api_annotations = false) +      const override {      using std::to_string; -    ClassMember::Print(final, printer); +    ClassMember::Print(final, printer, strip_api_annotations);      printer->Print("public static ");      if (final) { @@ -104,8 +105,9 @@ class PrimitiveMember<std::string> : public ClassMember {      return name_;    } -  void Print(bool final, text::Printer* printer) const override { -    ClassMember::Print(final, printer); +  void Print(bool final, text::Printer* printer, bool strip_api_annotations = false) +      const override { +    ClassMember::Print(final, printer, strip_api_annotations);      printer->Print("public static ");      if (final) { @@ -142,8 +144,9 @@ class PrimitiveArrayMember : public ClassMember {      return name_;    } -  void Print(bool final, text::Printer* printer) const override { -    ClassMember::Print(final, printer); +  void Print(bool final, text::Printer* printer, bool strip_api_annotations = false) +      const override { +    ClassMember::Print(final, printer, strip_api_annotations);      printer->Print("public static final int[] ").Print(name_).Print("={");      printer->Indent(); @@ -195,7 +198,7 @@ class MethodDefinition : public ClassMember {      return false;    } -  void Print(bool final, text::Printer* printer) const override; +  void Print(bool final, text::Printer* printer, bool strip_api_annotations = false) const override;   private:    DISALLOW_COPY_AND_ASSIGN(MethodDefinition); @@ -209,7 +212,7 @@ enum class ClassQualifier { kNone, kStatic };  class ClassDefinition : public ClassMember {   public:    static void WriteJavaFile(const ClassDefinition* def, const android::StringPiece& package, -                            bool final, io::OutputStream* out); +                            bool final, bool strip_api_annotations, io::OutputStream* out);    ClassDefinition(const android::StringPiece& name, ClassQualifier qualifier, bool createIfEmpty)        : name_(name.to_string()), qualifier_(qualifier), create_if_empty_(createIfEmpty) {} @@ -227,7 +230,7 @@ class ClassDefinition : public ClassMember {      return name_;    } -  void Print(bool final, text::Printer* printer) const override; +  void Print(bool final, text::Printer* printer, bool strip_api_annotations = false) const override;   private:    DISALLOW_COPY_AND_ASSIGN(ClassDefinition); diff --git a/tools/aapt2/java/JavaClassGenerator.cpp b/tools/aapt2/java/JavaClassGenerator.cpp index 31d205e1b9c9..9788f64995fb 100644 --- a/tools/aapt2/java/JavaClassGenerator.cpp +++ b/tools/aapt2/java/JavaClassGenerator.cpp @@ -601,6 +601,8 @@ bool JavaClassGenerator::Generate(const StringPiece& package_name_to_generate,      }    } +  const bool is_public = (options_.types == JavaClassGeneratorOptions::SymbolTypes::kPublic); +    for (const auto& package : table_->packages) {      for (const auto& type : package->types) {        if (type->type == ResourceType::kAttrPrivate) { @@ -609,8 +611,7 @@ bool JavaClassGenerator::Generate(const StringPiece& package_name_to_generate,        }        // Stay consistent with AAPT and generate an empty type class if the R class is public. -      const bool force_creation_if_empty = -          (options_.types == JavaClassGeneratorOptions::SymbolTypes::kPublic); +      const bool force_creation_if_empty = is_public;        std::unique_ptr<ClassDefinition> class_def;        if (out != nullptr) { @@ -634,8 +635,7 @@ bool JavaClassGenerator::Generate(const StringPiece& package_name_to_generate,          }        } -      if (out != nullptr && type->type == ResourceType::kStyleable && -          options_.types == JavaClassGeneratorOptions::SymbolTypes::kPublic) { +      if (out != nullptr && type->type == ResourceType::kStyleable && is_public) {          // When generating a public R class, we don't want Styleable to be part          // of the API. It is only emitted for documentation purposes.          class_def->GetCommentBuilder()->AppendComment("@doconly"); @@ -654,7 +654,7 @@ bool JavaClassGenerator::Generate(const StringPiece& package_name_to_generate,    if (out != nullptr) {      AppendJavaDocAnnotations(options_.javadoc_annotations, r_class.GetCommentBuilder()); -    ClassDefinition::WriteJavaFile(&r_class, out_package_name, options_.use_final, out); +    ClassDefinition::WriteJavaFile(&r_class, out_package_name, options_.use_final, !is_public, out);    }    return true;  } diff --git a/tools/aapt2/java/ManifestClassGenerator_test.cpp b/tools/aapt2/java/ManifestClassGenerator_test.cpp index ab7f9a11d971..3858fc7f765e 100644 --- a/tools/aapt2/java/ManifestClassGenerator_test.cpp +++ b/tools/aapt2/java/ManifestClassGenerator_test.cpp @@ -26,6 +26,7 @@ using ::testing::Not;  namespace aapt {  static ::testing::AssertionResult GetManifestClassText(IAaptContext* context, xml::XmlResource* res, +                                                       bool strip_api_annotations,                                                         std::string* out_str);  TEST(ManifestClassGeneratorTest, NameIsProperlyGeneratedFromSymbol) { @@ -39,7 +40,8 @@ TEST(ManifestClassGeneratorTest, NameIsProperlyGeneratedFromSymbol) {        </manifest>)");    std::string actual; -  ASSERT_TRUE(GetManifestClassText(context.get(), manifest.get(), &actual)); +  ASSERT_TRUE(GetManifestClassText(context.get(), manifest.get(), +                                   false /* strip_api_annotations */, &actual));    ASSERT_THAT(actual, HasSubstr("public static final class permission {"));    ASSERT_THAT(actual, HasSubstr("public static final class permission_group {")); @@ -91,7 +93,8 @@ TEST(ManifestClassGeneratorTest, CommentsAndAnnotationsArePresent) {        </manifest>)");    std::string actual; -  ASSERT_TRUE(GetManifestClassText(context.get(), manifest.get(), &actual)); +  ASSERT_TRUE(GetManifestClassText(context.get(), manifest.get(), +                                   false /* strip_api_annotations */, &actual));    const char* expected_access_internet = R"(    /**       * Required to access the internet. @@ -123,6 +126,55 @@ TEST(ManifestClassGeneratorTest, CommentsAndAnnotationsArePresent) {    EXPECT_THAT(actual, HasSubstr(expected_test));  } +TEST(ManifestClassGeneratorTest, CommentsAndAnnotationsArePresentButNoApiAnnotations) { +  std::unique_ptr<IAaptContext> context = test::ContextBuilder().Build(); +  std::unique_ptr<xml::XmlResource> manifest = test::BuildXmlDom(R"( +      <manifest xmlns:android="http://schemas.android.com/apk/res/android"> +        <!-- Required to access the internet. +             Added in API 1. --> +        <permission android:name="android.permission.ACCESS_INTERNET" /> +        <!-- @deprecated This permission is for playing outside. --> +        <permission android:name="android.permission.PLAY_OUTSIDE" /> +        <!-- This is a private permission for system only! +             @hide +             @SystemApi --> +        <permission android:name="android.permission.SECRET" /> +        <!-- @TestApi This is a test only permission. --> +        <permission android:name="android.permission.TEST_ONLY" /> +      </manifest>)"); + +  std::string actual; +  ASSERT_TRUE(GetManifestClassText(context.get(), manifest.get(), +                                   true /* strip_api_annotations */, &actual)); + +  const char* expected_access_internet = R"(    /** +     * Required to access the internet. +     * Added in API 1. +     */ +    public static final String ACCESS_INTERNET="android.permission.ACCESS_INTERNET";)"; +  EXPECT_THAT(actual, HasSubstr(expected_access_internet)); + +  const char* expected_play_outside = R"(    /** +     * @deprecated This permission is for playing outside. +     */ +    @Deprecated +    public static final String PLAY_OUTSIDE="android.permission.PLAY_OUTSIDE";)"; +  EXPECT_THAT(actual, HasSubstr(expected_play_outside)); + +  const char* expected_secret = R"(    /** +     * This is a private permission for system only! +     * @hide +     */ +    public static final String SECRET="android.permission.SECRET";)"; +  EXPECT_THAT(actual, HasSubstr(expected_secret)); + +  const char* expected_test = R"(    /** +     * This is a test only permission. +     */ +    public static final String TEST_ONLY="android.permission.TEST_ONLY";)"; +  EXPECT_THAT(actual, HasSubstr(expected_test)); +} +  // This is bad but part of public API behaviour so we need to preserve it.  TEST(ManifestClassGeneratorTest, LastSeenPermissionWithSameLeafNameTakesPrecedence) {    std::unique_ptr<IAaptContext> context = test::ContextBuilder().Build(); @@ -135,7 +187,8 @@ TEST(ManifestClassGeneratorTest, LastSeenPermissionWithSameLeafNameTakesPreceden        </manifest>)");    std::string actual; -  ASSERT_TRUE(GetManifestClassText(context.get(), manifest.get(), &actual)); +  ASSERT_TRUE(GetManifestClassText(context.get(), manifest.get(), +                                   false  /* strip_api_annotations */, &actual));    EXPECT_THAT(actual, HasSubstr("ACCESS_INTERNET=\"com.android.aapt.test.ACCESS_INTERNET\";"));    EXPECT_THAT(actual, Not(HasSubstr("ACCESS_INTERNET=\"android.permission.ACCESS_INTERNET\";")));    EXPECT_THAT(actual, Not(HasSubstr("ACCESS_INTERNET=\"com.android.sample.ACCESS_INTERNET\";"))); @@ -149,11 +202,13 @@ TEST(ManifestClassGeneratorTest, NormalizePermissionNames) {          </manifest>)");    std::string actual; -  ASSERT_TRUE(GetManifestClassText(context.get(), manifest.get(), &actual)); +  ASSERT_TRUE(GetManifestClassText(context.get(), manifest.get(), +                                   false  /* strip_api_annotations */, &actual));    EXPECT_THAT(actual, HasSubstr("access_internet=\"android.permission.access-internet\";"));  }  static ::testing::AssertionResult GetManifestClassText(IAaptContext* context, xml::XmlResource* res, +                                                       bool strip_api_annotations,                                                         std::string* out_str) {    std::unique_ptr<ClassDefinition> manifest_class =        GenerateManifestClass(context->GetDiagnostics(), res); @@ -162,7 +217,7 @@ static ::testing::AssertionResult GetManifestClassText(IAaptContext* context, xm    }    StringOutputStream out(out_str); -  manifest_class->WriteJavaFile(manifest_class.get(), "android", true, &out); +  manifest_class->WriteJavaFile(manifest_class.get(), "android", true, strip_api_annotations, &out);    out.Flush();    return ::testing::AssertionSuccess();  }  |