diff options
147 files changed, 1018 insertions, 1219 deletions
diff --git a/Android.bp b/Android.bp index aeaaca3d7705..7d38a69169a3 100644 --- a/Android.bp +++ b/Android.bp @@ -371,7 +371,7 @@ filegroup { java_library { name: "framework-updatable-stubs-module_libs_api", static_libs: [ - "framework-sdkextensions-stubs-module_libs_api", + "framework-sdkextensions.stubs.module_lib", "framework-tethering.stubs.module_lib", "updatable_media_stubs", ], @@ -717,7 +717,6 @@ filegroup { "core/java/com/android/internal/util/TrafficStatsConstants.java", "core/java/com/android/internal/util/WakeupMessage.java", "core/java/com/android/internal/util/TokenBucket.java", - "core/java/android/net/shared/*.java", ], } @@ -727,7 +726,6 @@ java_library { name: "framework-wifi-util-lib", sdk_version: "module_current", srcs: [ - "core/java/android/net/shared/Inet4AddressUtils.java", "core/java/com/android/internal/util/Preconditions.java", ], libs: [ @@ -744,7 +742,6 @@ filegroup { name: "framework-services-net-module-wifi-shared-srcs", srcs: [ "core/java/android/net/DhcpResults.java", - "core/java/android/net/shared/InetAddressUtils.java", "core/java/android/net/util/IpUtils.java", "core/java/android/util/LocalLog.java", ], @@ -761,7 +758,6 @@ filegroup { "core/java/com/android/internal/util/State.java", "core/java/com/android/internal/util/StateMachine.java", "core/java/com/android/internal/util/TrafficStatsConstants.java", - "core/java/android/net/shared/Inet4AddressUtils.java", ], } diff --git a/cmds/statsd/src/anomaly/AlarmTracker.cpp b/cmds/statsd/src/anomaly/AlarmTracker.cpp index 019a9f7e5f9a..a21327b4aae0 100644 --- a/cmds/statsd/src/anomaly/AlarmTracker.cpp +++ b/cmds/statsd/src/anomaly/AlarmTracker.cpp @@ -61,11 +61,11 @@ void AlarmTracker::addSubscription(const Subscription& subscription) { } int64_t AlarmTracker::findNextAlarmSec(int64_t currentTimeSec) { - if (currentTimeSec <= mAlarmSec) { + if (currentTimeSec < mAlarmSec) { return mAlarmSec; } int64_t periodsForward = - ((currentTimeSec - mAlarmSec) * MS_PER_SEC - 1) / mAlarmConfig.period_millis() + 1; + ((currentTimeSec - mAlarmSec) * MS_PER_SEC) / mAlarmConfig.period_millis() + 1; return mAlarmSec + periodsForward * mAlarmConfig.period_millis() / MS_PER_SEC; } diff --git a/cmds/statsd/tests/anomaly/AlarmTracker_test.cpp b/cmds/statsd/tests/anomaly/AlarmTracker_test.cpp index 5e6de1cc6b91..e664023a1647 100644 --- a/cmds/statsd/tests/anomaly/AlarmTracker_test.cpp +++ b/cmds/statsd/tests/anomaly/AlarmTracker_test.cpp @@ -40,23 +40,47 @@ TEST(AlarmTrackerTest, TestTriggerTimestamp) { alarm.set_offset_millis(15 * MS_PER_SEC); alarm.set_period_millis(60 * 60 * MS_PER_SEC); // 1hr int64_t startMillis = 100000000 * MS_PER_SEC; + int64_t nextAlarmTime = startMillis / MS_PER_SEC + 15; AlarmTracker tracker(startMillis, startMillis, alarm, kConfigKey, subscriberAlarmMonitor); - EXPECT_EQ(tracker.mAlarmSec, (int64_t)(startMillis / MS_PER_SEC + 15)); + EXPECT_EQ(tracker.mAlarmSec, nextAlarmTime); uint64_t currentTimeSec = startMillis / MS_PER_SEC + 10; std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> firedAlarmSet = subscriberAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec)); EXPECT_TRUE(firedAlarmSet.empty()); tracker.informAlarmsFired(currentTimeSec * NS_PER_SEC, firedAlarmSet); - EXPECT_EQ(tracker.mAlarmSec, (int64_t)(startMillis / MS_PER_SEC + 15)); + EXPECT_EQ(tracker.mAlarmSec, nextAlarmTime); + EXPECT_EQ(tracker.getAlarmTimestampSec(), nextAlarmTime); currentTimeSec = startMillis / MS_PER_SEC + 7000; + nextAlarmTime = startMillis / MS_PER_SEC + 15 + 2 * 60 * 60; firedAlarmSet = subscriberAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec)); EXPECT_EQ(firedAlarmSet.size(), 1u); tracker.informAlarmsFired(currentTimeSec * NS_PER_SEC, firedAlarmSet); EXPECT_TRUE(firedAlarmSet.empty()); - EXPECT_EQ(tracker.mAlarmSec, (int64_t)(startMillis / MS_PER_SEC + 15 + 2 * 60 * 60)); + EXPECT_EQ(tracker.mAlarmSec, nextAlarmTime); + EXPECT_EQ(tracker.getAlarmTimestampSec(), nextAlarmTime); + + // Alarm fires exactly on time. + currentTimeSec = startMillis / MS_PER_SEC + 15 + 2 * 60 * 60; + nextAlarmTime = startMillis / MS_PER_SEC + 15 + 3 * 60 * 60; + firedAlarmSet = subscriberAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec)); + ASSERT_EQ(firedAlarmSet.size(), 1u); + tracker.informAlarmsFired(currentTimeSec * NS_PER_SEC, firedAlarmSet); + EXPECT_TRUE(firedAlarmSet.empty()); + EXPECT_EQ(tracker.mAlarmSec, nextAlarmTime); + EXPECT_EQ(tracker.getAlarmTimestampSec(), nextAlarmTime); + + // Alarm fires exactly 1 period late. + currentTimeSec = startMillis / MS_PER_SEC + 15 + 4 * 60 * 60; + nextAlarmTime = startMillis / MS_PER_SEC + 15 + 5 * 60 * 60; + firedAlarmSet = subscriberAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec)); + ASSERT_EQ(firedAlarmSet.size(), 1u); + tracker.informAlarmsFired(currentTimeSec * NS_PER_SEC, firedAlarmSet); + EXPECT_TRUE(firedAlarmSet.empty()); + EXPECT_EQ(tracker.mAlarmSec, nextAlarmTime); + EXPECT_EQ(tracker.getAlarmTimestampSec(), nextAlarmTime); } } // namespace statsd diff --git a/cmds/telecom/src/com/android/commands/telecom/Telecom.java b/cmds/telecom/src/com/android/commands/telecom/Telecom.java index 97074050448e..35f4add46d77 100644 --- a/cmds/telecom/src/com/android/commands/telecom/Telecom.java +++ b/cmds/telecom/src/com/android/commands/telecom/Telecom.java @@ -64,6 +64,8 @@ public final class Telecom extends BaseCommand { private static final String COMMAND_UNREGISTER_PHONE_ACCOUNT = "unregister-phone-account"; private static final String COMMAND_SET_DEFAULT_DIALER = "set-default-dialer"; private static final String COMMAND_GET_DEFAULT_DIALER = "get-default-dialer"; + private static final String COMMAND_STOP_BLOCK_SUPPRESSION = "stop-block-suppression"; + /** * Change the system dialer package name if a package name was specified, * Example: adb shell telecom set-system-dialer <PACKAGE> @@ -111,6 +113,8 @@ public final class Telecom extends BaseCommand { + "usage: telecom set-sim-count <COUNT>\n" + "usage: telecom get-sim-config\n" + "usage: telecom get-max-phones\n" + + "usage: telecom stop-block-suppression: Stop suppressing the blocked number" + + " provider after a call to emergency services.\n" + "usage: telecom set-emer-phone-account-filter <PACKAGE>\n" + "\n" + "telecom set-phone-account-enabled: Enables the given phone account, if it has" @@ -203,6 +207,9 @@ public final class Telecom extends BaseCommand { case COMMAND_UNREGISTER_PHONE_ACCOUNT: runUnregisterPhoneAccount(); break; + case COMMAND_STOP_BLOCK_SUPPRESSION: + runStopBlockSuppression(); + break; case COMMAND_SET_DEFAULT_DIALER: runSetDefaultDialer(); break; @@ -320,8 +327,13 @@ public final class Telecom extends BaseCommand { System.out.println("Success - " + handle + " unregistered."); } + private void runStopBlockSuppression() throws RemoteException { + mTelecomService.stopBlockSuppression(); + } + private void runSetDefaultDialer() throws RemoteException { - final String packageName = nextArgRequired(); + String packageName = nextArg(); + if ("default".equals(packageName)) packageName = null; mTelecomService.setTestDefaultDialer(packageName); System.out.println("Success - " + packageName + " set as override default dialer."); } diff --git a/config/preloaded-classes b/config/preloaded-classes index b05d02c9eb15..e0a3f637645d 100644 --- a/config/preloaded-classes +++ b/config/preloaded-classes @@ -5583,8 +5583,6 @@ dalvik.system.CloseGuard$DefaultReporter dalvik.system.CloseGuard$Reporter dalvik.system.CloseGuard$Tracker dalvik.system.CloseGuard -dalvik.system.DalvikLogHandler -dalvik.system.DalvikLogging dalvik.system.DelegateLastClassLoader dalvik.system.DexClassLoader dalvik.system.DexFile$1 diff --git a/core/java/android/app/Activity.java b/core/java/android/app/Activity.java index 4f1d7f2c761c..262051d0af1e 100644 --- a/core/java/android/app/Activity.java +++ b/core/java/android/app/Activity.java @@ -215,8 +215,8 @@ import java.util.function.Consumer; * <a name="Fragments"></a> * <h3>Fragments</h3> * - * <p>The {@link android.support.v4.app.FragmentActivity} subclass - * can make use of the {@link android.support.v4.app.Fragment} class to better + * <p>The {@link androidx.fragment.app.FragmentActivity} subclass + * can make use of the {@link androidx.fragment.app.Fragment} class to better * modularize their code, build more sophisticated user interfaces for larger * screens, and help scale their application between small and large screens.</p> * @@ -1003,7 +1003,7 @@ public class Activity extends ContextThemeWrapper /** * Return the LoaderManager for this activity, creating it if needed. * - * @deprecated Use {@link android.support.v4.app.FragmentActivity#getSupportLoaderManager()} + * @deprecated Use {@link androidx.fragment.app.FragmentActivity#getSupportLoaderManager()} */ @Deprecated public LoaderManager getLoaderManager() { @@ -3022,7 +3022,7 @@ public class Activity extends ContextThemeWrapper * Return the FragmentManager for interacting with fragments associated * with this activity. * - * @deprecated Use {@link android.support.v4.app.FragmentActivity#getSupportFragmentManager()} + * @deprecated Use {@link androidx.fragment.app.FragmentActivity#getSupportFragmentManager()} */ @Deprecated public FragmentManager getFragmentManager() { @@ -3035,7 +3035,7 @@ public class Activity extends ContextThemeWrapper * method and before {@link Fragment#onCreate Fragment.onCreate()}. * * @deprecated Use {@link - * android.support.v4.app.FragmentActivity#onAttachFragment(android.support.v4.app.Fragment)} + * androidx.fragment.app.FragmentActivity#onAttachFragment(androidx.fragment.app.Fragment)} */ @Deprecated public void onAttachFragment(Fragment fragment) { @@ -5847,8 +5847,8 @@ public class Activity extends ContextThemeWrapper * @see Fragment#startActivity * @see Fragment#startActivityForResult * - * @deprecated Use {@link android.support.v4.app.FragmentActivity#startActivityFromFragment( - * android.support.v4.app.Fragment,Intent,int)} + * @deprecated Use {@link androidx.fragment.app.FragmentActivity#startActivityFromFragment( + * androidx.fragment.app.Fragment,Intent,int)} */ @Deprecated public void startActivityFromFragment(@NonNull Fragment fragment, @@ -5876,8 +5876,8 @@ public class Activity extends ContextThemeWrapper * @see Fragment#startActivity * @see Fragment#startActivityForResult * - * @deprecated Use {@link android.support.v4.app.FragmentActivity#startActivityFromFragment( - * android.support.v4.app.Fragment,Intent,int,Bundle)} + * @deprecated Use {@link androidx.fragment.app.FragmentActivity#startActivityFromFragment( + * androidx.fragment.app.Fragment,Intent,int,Bundle)} */ @Deprecated public void startActivityFromFragment(@NonNull Fragment fragment, diff --git a/core/java/android/app/AlarmManager.java b/core/java/android/app/AlarmManager.java index 647f63025cf7..febb293921cd 100644 --- a/core/java/android/app/AlarmManager.java +++ b/core/java/android/app/AlarmManager.java @@ -35,7 +35,7 @@ import android.util.ArrayMap; import android.util.Log; import android.util.proto.ProtoOutputStream; -import libcore.timezone.ZoneInfoDb; +import com.android.i18n.timezone.ZoneInfoDb; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; diff --git a/core/java/android/app/Fragment.java b/core/java/android/app/Fragment.java index c6a0de458df0..da3bc681ed34 100644 --- a/core/java/android/app/Fragment.java +++ b/core/java/android/app/Fragment.java @@ -102,7 +102,7 @@ import java.lang.reflect.InvocationTargetException; * While the Fragment API was introduced in * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, a version of the API * at is also available for use on older platforms through - * {@link android.support.v4.app.FragmentActivity}. See the blog post + * {@link androidx.fragment.app.FragmentActivity}. See the blog post * <a href="http://android-developers.blogspot.com/2011/03/fragments-for-all.html"> * Fragments For All</a> for more details. * @@ -258,8 +258,8 @@ import java.lang.reflect.InvocationTargetException; * pressing back will pop it to return the user to whatever previous state * the activity UI was in. * - * @deprecated Use the <a href="{@docRoot}tools/extras/support-library.html">Support Library</a> - * {@link android.support.v4.app.Fragment} for consistent behavior across all devices + * @deprecated Use the <a href="{@docRoot}jetpack">Jetpack Fragment Library</a> + * {@link androidx.fragment.app.Fragment} for consistent behavior across all devices * and access to <a href="{@docRoot}topic/libraries/architecture/lifecycle.html">Lifecycle</a>. */ @Deprecated @@ -432,7 +432,7 @@ public class Fragment implements ComponentCallbacks2, OnCreateContextMenuListene * through {@link FragmentManager#saveFragmentInstanceState(Fragment) * FragmentManager.saveFragmentInstanceState}. * - * @deprecated Use {@link android.support.v4.app.Fragment.SavedState} + * @deprecated Use {@link androidx.fragment.app.Fragment.SavedState} */ @Deprecated public static class SavedState implements Parcelable { @@ -479,7 +479,7 @@ public class Fragment implements ComponentCallbacks2, OnCreateContextMenuListene * Thrown by {@link Fragment#instantiate(Context, String, Bundle)} when * there is an instantiation failure. * - * @deprecated Use {@link android.support.v4.app.Fragment.InstantiationException} + * @deprecated Use {@link androidx.fragment.app.Fragment.InstantiationException} */ @Deprecated static public class InstantiationException extends AndroidRuntimeException { @@ -1055,7 +1055,7 @@ public class Fragment implements ComponentCallbacks2, OnCreateContextMenuListene /** * Return the LoaderManager for this fragment, creating it if needed. * - * @deprecated Use {@link android.support.v4.app.Fragment#getLoaderManager()} + * @deprecated Use {@link androidx.fragment.app.Fragment#getLoaderManager()} */ @Deprecated public LoaderManager getLoaderManager() { diff --git a/core/java/android/bluetooth/BluetoothCodecConfig.java b/core/java/android/bluetooth/BluetoothCodecConfig.java index d2a15357aa1f..e07bc0215a6b 100644 --- a/core/java/android/bluetooth/BluetoothCodecConfig.java +++ b/core/java/android/bluetooth/BluetoothCodecConfig.java @@ -614,8 +614,9 @@ public final class BluetoothCodecConfig implements Parcelable { if (other == null && mCodecType != other.mCodecType) { return false; } - // Currently we only care about the LDAC Playback Quality at CodecSpecific1 + // Currently we only care about the AAC VBR and LDAC Playback Quality at CodecSpecific1 switch (mCodecType) { + case SOURCE_CODEC_TYPE_AAC: case SOURCE_CODEC_TYPE_LDAC: if (mCodecSpecific1 != other.mCodecSpecific1) { return false; 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/hardware/GeomagneticField.java b/core/java/android/hardware/GeomagneticField.java index 0d7b695d7f1d..cbfe4fa58e40 100644 --- a/core/java/android/hardware/GeomagneticField.java +++ b/core/java/android/hardware/GeomagneticField.java @@ -16,7 +16,8 @@ package android.hardware; -import java.util.GregorianCalendar; +import java.util.Calendar; +import java.util.TimeZone; /** * Estimates magnetic field at a given point on @@ -26,7 +27,7 @@ import java.util.GregorianCalendar; * <p>This uses the World Magnetic Model produced by the United States National * Geospatial-Intelligence Agency. More details about the model can be found at * <a href="http://www.ngdc.noaa.gov/geomag/WMM/DoDWMM.shtml">http://www.ngdc.noaa.gov/geomag/WMM/DoDWMM.shtml</a>. - * This class currently uses WMM-2015 which is valid until 2020, but should + * This class currently uses WMM-2020 which is valid until 2025, but should * produce acceptable results for several years after that. Future versions of * Android may use a newer version of the model. */ @@ -48,69 +49,72 @@ public class GeomagneticField { static private final float EARTH_REFERENCE_RADIUS_KM = 6371.2f; // These coefficients and the formulae used below are from: - // NOAA Technical Report: The US/UK World Magnetic Model for 2015-2020 - static private final float[][] G_COEFF = new float[][] { - { 0.0f }, - { -29438.5f, -1501.1f }, - { -2445.3f, 3012.5f, 1676.6f }, - { 1351.1f, -2352.3f, 1225.6f, 581.9f }, - { 907.2f, 813.7f, 120.3f, -335.0f, 70.3f }, - { -232.6f, 360.1f, 192.4f, -141.0f, -157.4f, 4.3f }, - { 69.5f, 67.4f, 72.8f, -129.8f, -29.0f, 13.2f, -70.9f }, - { 81.6f, -76.1f, -6.8f, 51.9f, 15.0f, 9.3f, -2.8f, 6.7f }, - { 24.0f, 8.6f, -16.9f, -3.2f, -20.6f, 13.3f, 11.7f, -16.0f, -2.0f }, - { 5.4f, 8.8f, 3.1f, -3.1f, 0.6f, -13.3f, -0.1f, 8.7f, -9.1f, -10.5f }, - { -1.9f, -6.5f, 0.2f, 0.6f, -0.6f, 1.7f, -0.7f, 2.1f, 2.3f, -1.8f, -3.6f }, - { 3.1f, -1.5f, -2.3f, 2.1f, -0.9f, 0.6f, -0.7f, 0.2f, 1.7f, -0.2f, 0.4f, 3.5f }, - { -2.0f, -0.3f, 0.4f, 1.3f, -0.9f, 0.9f, 0.1f, 0.5f, -0.4f, -0.4f, 0.2f, -0.9f, 0.0f } }; - - static private final float[][] H_COEFF = new float[][] { - { 0.0f }, - { 0.0f, 4796.2f }, - { 0.0f, -2845.6f, -642.0f }, - { 0.0f, -115.3f, 245.0f, -538.3f }, - { 0.0f, 283.4f, -188.6f, 180.9f, -329.5f }, - { 0.0f, 47.4f, 196.9f, -119.4f, 16.1f, 100.1f }, - { 0.0f, -20.7f, 33.2f, 58.8f, -66.5f, 7.3f, 62.5f }, - { 0.0f, -54.1f, -19.4f, 5.6f, 24.4f, 3.3f, -27.5f, -2.3f }, - { 0.0f, 10.2f, -18.1f, 13.2f, -14.6f, 16.2f, 5.7f, -9.1f, 2.2f }, - { 0.0f, -21.6f, 10.8f, 11.7f, -6.8f, -6.9f, 7.8f, 1.0f, -3.9f, 8.5f }, - { 0.0f, 3.3f, -0.3f, 4.6f, 4.4f, -7.9f, -0.6f, -4.1f, -2.8f, -1.1f, -8.7f }, - { 0.0f, -0.1f, 2.1f, -0.7f, -1.1f, 0.7f, -0.2f, -2.1f, -1.5f, -2.5f, -2.0f, -2.3f }, - { 0.0f, -1.0f, 0.5f, 1.8f, -2.2f, 0.3f, 0.7f, -0.1f, 0.3f, 0.2f, -0.9f, -0.2f, 0.7f } }; - - static private final float[][] DELTA_G = new float[][] { - { 0.0f }, - { 10.7f, 17.9f }, - { -8.6f, -3.3f, 2.4f }, - { 3.1f, -6.2f, -0.4f, -10.4f }, - { -0.4f, 0.8f, -9.2f, 4.0f, -4.2f }, - { -0.2f, 0.1f, -1.4f, 0.0f, 1.3f, 3.8f }, - { -0.5f, -0.2f, -0.6f, 2.4f, -1.1f, 0.3f, 1.5f }, - { 0.2f, -0.2f, -0.4f, 1.3f, 0.2f, -0.4f, -0.9f, 0.3f }, - { 0.0f, 0.1f, -0.5f, 0.5f, -0.2f, 0.4f, 0.2f, -0.4f, 0.3f }, - { 0.0f, -0.1f, -0.1f, 0.4f, -0.5f, -0.2f, 0.1f, 0.0f, -0.2f, -0.1f }, - { 0.0f, 0.0f, -0.1f, 0.3f, -0.1f, -0.1f, -0.1f, 0.0f, -0.2f, -0.1f, -0.2f }, - { 0.0f, 0.0f, -0.1f, 0.1f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, -0.1f, -0.1f }, - { 0.1f, 0.0f, 0.0f, 0.1f, -0.1f, 0.0f, 0.1f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f } }; - - static private final float[][] DELTA_H = new float[][] { - { 0.0f }, - { 0.0f, -26.8f }, - { 0.0f, -27.1f, -13.3f }, - { 0.0f, 8.4f, -0.4f, 2.3f }, - { 0.0f, -0.6f, 5.3f, 3.0f, -5.3f }, - { 0.0f, 0.4f, 1.6f, -1.1f, 3.3f, 0.1f }, - { 0.0f, 0.0f, -2.2f, -0.7f, 0.1f, 1.0f, 1.3f }, - { 0.0f, 0.7f, 0.5f, -0.2f, -0.1f, -0.7f, 0.1f, 0.1f }, - { 0.0f, -0.3f, 0.3f, 0.3f, 0.6f, -0.1f, -0.2f, 0.3f, 0.0f }, - { 0.0f, -0.2f, -0.1f, -0.2f, 0.1f, 0.1f, 0.0f, -0.2f, 0.4f, 0.3f }, - { 0.0f, 0.1f, -0.1f, 0.0f, 0.0f, -0.2f, 0.1f, -0.1f, -0.2f, 0.1f, -0.1f }, - { 0.0f, 0.0f, 0.1f, 0.0f, 0.1f, 0.0f, 0.0f, 0.1f, 0.0f, -0.1f, 0.0f, -0.1f }, - { 0.0f, 0.0f, 0.0f, -0.1f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f } }; - - static private final long BASE_TIME = - new GregorianCalendar(2015, 1, 1).getTimeInMillis(); + // NOAA Technical Report: The US/UK World Magnetic Model for 2020-2025 + static private final float[][] G_COEFF = new float[][]{ + {0.0f}, + {-29404.5f, -1450.7f}, + {-2500.0f, 2982.0f, 1676.8f}, + {1363.9f, -2381.0f, 1236.2f, 525.7f}, + {903.1f, 809.4f, 86.2f, -309.4f, 47.9f}, + {-234.4f, 363.1f, 187.8f, -140.7f, -151.2f, 13.7f}, + {65.9f, 65.6f, 73.0f, -121.5f, -36.2f, 13.5f, -64.7f}, + {80.6f, -76.8f, -8.3f, 56.5f, 15.8f, 6.4f, -7.2f, 9.8f}, + {23.6f, 9.8f, -17.5f, -0.4f, -21.1f, 15.3f, 13.7f, -16.5f, -0.3f}, + {5.0f, 8.2f, 2.9f, -1.4f, -1.1f, -13.3f, 1.1f, 8.9f, -9.3f, -11.9f}, + {-1.9f, -6.2f, -0.1f, 1.7f, -0.9f, 0.6f, -0.9f, 1.9f, 1.4f, -2.4f, -3.9f}, + {3.0f, -1.4f, -2.5f, 2.4f, -0.9f, 0.3f, -0.7f, -0.1f, 1.4f, -0.6f, 0.2f, 3.1f}, + {-2.0f, -0.1f, 0.5f, 1.3f, -1.2f, 0.7f, 0.3f, 0.5f, -0.2f, -0.5f, 0.1f, -1.1f, -0.3f}}; + + static private final float[][] H_COEFF = new float[][]{ + {0.0f}, + {0.0f, 4652.9f}, + {0.0f, -2991.6f, -734.8f}, + {0.0f, -82.2f, 241.8f, -542.9f}, + {0.0f, 282.0f, -158.4f, 199.8f, -350.1f}, + {0.0f, 47.7f, 208.4f, -121.3f, 32.2f, 99.1f}, + {0.0f, -19.1f, 25.0f, 52.7f, -64.4f, 9.0f, 68.1f}, + {0.0f, -51.4f, -16.8f, 2.3f, 23.5f, -2.2f, -27.2f, -1.9f}, + {0.0f, 8.4f, -15.3f, 12.8f, -11.8f, 14.9f, 3.6f, -6.9f, 2.8f}, + {0.0f, -23.3f, 11.1f, 9.8f, -5.1f, -6.2f, 7.8f, 0.4f, -1.5f, 9.7f}, + {0.0f, 3.4f, -0.2f, 3.5f, 4.8f, -8.6f, -0.1f, -4.2f, -3.4f, -0.1f, -8.8f}, + {0.0f, 0.0f, 2.6f, -0.5f, -0.4f, 0.6f, -0.2f, -1.7f, -1.6f, -3.0f, -2.0f, -2.6f}, + {0.0f, -1.2f, 0.5f, 1.3f, -1.8f, 0.1f, 0.7f, -0.1f, 0.6f, 0.2f, -0.9f, 0.0f, 0.5f}}; + + static private final float[][] DELTA_G = new float[][]{ + {0.0f}, + {6.7f, 7.7f}, + {-11.5f, -7.1f, -2.2f}, + {2.8f, -6.2f, 3.4f, -12.2f}, + {-1.1f, -1.6f, -6.0f, 5.4f, -5.5f}, + {-0.3f, 0.6f, -0.7f, 0.1f, 1.2f, 1.0f}, + {-0.6f, -0.4f, 0.5f, 1.4f, -1.4f, 0.0f, 0.8f}, + {-0.1f, -0.3f, -0.1f, 0.7f, 0.2f, -0.5f, -0.8f, 1.0f}, + {-0.1f, 0.1f, -0.1f, 0.5f, -0.1f, 0.4f, 0.5f, 0.0f, 0.4f}, + {-0.1f, -0.2f, 0.0f, 0.4f, -0.3f, 0.0f, 0.3f, 0.0f, 0.0f, -0.4f}, + {0.0f, 0.0f, 0.0f, 0.2f, -0.1f, -0.2f, 0.0f, -0.1f, -0.2f, -0.1f, 0.0f}, + {0.0f, -0.1f, 0.0f, 0.0f, 0.0f, -0.1f, 0.0f, 0.0f, -0.1f, -0.1f, -0.1f, -0.1f}, + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, -0.1f}}; + + static private final float[][] DELTA_H = new float[][]{ + {0.0f}, + {0.0f, -25.1f}, + {0.0f, -30.2f, -23.9f}, + {0.0f, 5.7f, -1.0f, 1.1f}, + {0.0f, 0.2f, 6.9f, 3.7f, -5.6f}, + {0.0f, 0.1f, 2.5f, -0.9f, 3.0f, 0.5f}, + {0.0f, 0.1f, -1.8f, -1.4f, 0.9f, 0.1f, 1.0f}, + {0.0f, 0.5f, 0.6f, -0.7f, -0.2f, -1.2f, 0.2f, 0.3f}, + {0.0f, -0.3f, 0.7f, -0.2f, 0.5f, -0.3f, -0.5f, 0.4f, 0.1f}, + {0.0f, -0.3f, 0.2f, -0.4f, 0.4f, 0.1f, 0.0f, -0.2f, 0.5f, 0.2f}, + {0.0f, 0.0f, 0.1f, -0.3f, 0.1f, -0.2f, 0.1f, 0.0f, -0.1f, 0.2f, 0.0f}, + {0.0f, 0.0f, 0.1f, 0.0f, 0.2f, 0.0f, 0.0f, 0.1f, 0.0f, -0.1f, 0.0f, 0.0f}, + {0.0f, 0.0f, 0.0f, -0.1f, 0.1f, 0.0f, 0.0f, 0.0f, 0.1f, 0.0f, 0.0f, 0.0f, -0.1f}}; + + static private final long BASE_TIME = new Calendar.Builder() + .setTimeZone(TimeZone.getTimeZone("UTC")) + .setDate(2020, Calendar.JANUARY, 1) + .build() + .getTimeInMillis(); // The ratio between the Gauss-normalized associated Legendre functions and // the Schmid quasi-normalized ones. Compute these once staticly since they @@ -190,7 +194,7 @@ public class GeomagneticField { // We now compute the magnetic field strength given the geocentric // location. The magnetic field is the derivative of the potential // function defined by the model. See NOAA Technical Report: The US/UK - // World Magnetic Model for 2015-2020 for the derivation. + // World Magnetic Model for 2020-2025 for the derivation. float gcX = 0.0f; // Geocentric northwards component. float gcY = 0.0f; // Geocentric eastwards component. float gcZ = 0.0f; // Geocentric downwards component. @@ -203,7 +207,7 @@ public class GeomagneticField { // Negative derivative with respect to latitude, divided by // radius. This looks like the negation of the version in the - // NOAA Techincal report because that report used + // NOAA Technical report because that report used // P_n^m(sin(theta)) and we use P_n^m(cos(90 - theta)), so the // derivative with respect to theta is negated. gcX += relativeRadiusPower[n+2] diff --git a/core/java/android/net/DhcpResults.java b/core/java/android/net/DhcpResults.java index 5ab035496a43..1ef4f1741e3a 100644 --- a/core/java/android/net/DhcpResults.java +++ b/core/java/android/net/DhcpResults.java @@ -18,12 +18,13 @@ package android.net; import android.annotation.Nullable; import android.compat.annotation.UnsupportedAppUsage; -import android.net.shared.InetAddressUtils; import android.os.Parcel; import android.os.Parcelable; import android.text.TextUtils; import android.util.Log; +import com.android.net.module.util.InetAddressUtils; + import java.net.Inet4Address; import java.net.InetAddress; import java.util.ArrayList; 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..97a7ecc3fb15 100644 --- a/core/java/android/net/NetworkUtils.java +++ b/core/java/android/net/NetworkUtils.java @@ -21,13 +21,14 @@ import static android.system.OsConstants.AF_INET6; import android.annotation.NonNull; import android.compat.annotation.UnsupportedAppUsage; -import android.net.shared.Inet4AddressUtils; import android.os.Build; import android.system.ErrnoException; import android.system.Os; import android.util.Log; import android.util.Pair; +import com.android.net.module.util.Inet4AddressUtils; + import java.io.FileDescriptor; import java.math.BigInteger; import java.net.Inet4Address; @@ -155,6 +156,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/net/StaticIpConfiguration.java b/core/java/android/net/StaticIpConfiguration.java index f24a9bd53039..a973455baa04 100644 --- a/core/java/android/net/StaticIpConfiguration.java +++ b/core/java/android/net/StaticIpConfiguration.java @@ -21,11 +21,11 @@ import android.annotation.Nullable; import android.annotation.SystemApi; import android.annotation.TestApi; import android.compat.annotation.UnsupportedAppUsage; -import android.net.shared.InetAddressUtils; import android.os.Parcel; import android.os.Parcelable; import com.android.internal.util.Preconditions; +import com.android.net.module.util.InetAddressUtils; import java.net.InetAddress; import java.util.ArrayList; diff --git a/core/java/android/net/shared/Inet4AddressUtils.java b/core/java/android/net/shared/Inet4AddressUtils.java deleted file mode 100644 index bec0c84fa689..000000000000 --- a/core/java/android/net/shared/Inet4AddressUtils.java +++ /dev/null @@ -1,166 +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.shared; - -import java.net.Inet4Address; -import java.net.InetAddress; -import java.net.UnknownHostException; - -/** - * Collection of utilities to work with IPv4 addresses. - * @hide - */ -public class Inet4AddressUtils { - - /** - * Convert a IPv4 address from an integer to an InetAddress (0x04030201 -> 1.2.3.4) - * - * <p>This method uses the higher-order int bytes as the lower-order IPv4 address bytes, - * which is an unusual convention. Consider {@link #intToInet4AddressHTH(int)} instead. - * @param hostAddress an int coding for an IPv4 address, where higher-order int byte is - * lower-order IPv4 address byte - */ - public static Inet4Address intToInet4AddressHTL(int hostAddress) { - return intToInet4AddressHTH(Integer.reverseBytes(hostAddress)); - } - - /** - * Convert a IPv4 address from an integer to an InetAddress (0x01020304 -> 1.2.3.4) - * @param hostAddress an int coding for an IPv4 address - */ - public static Inet4Address intToInet4AddressHTH(int hostAddress) { - byte[] addressBytes = { (byte) (0xff & (hostAddress >> 24)), - (byte) (0xff & (hostAddress >> 16)), - (byte) (0xff & (hostAddress >> 8)), - (byte) (0xff & hostAddress) }; - - try { - return (Inet4Address) InetAddress.getByAddress(addressBytes); - } catch (UnknownHostException e) { - throw new AssertionError(); - } - } - - /** - * Convert an IPv4 address from an InetAddress to an integer (1.2.3.4 -> 0x01020304) - * - * <p>This conversion can help order IP addresses: considering the ordering - * 192.0.2.1 < 192.0.2.2 < ..., resulting ints will follow that ordering if read as unsigned - * integers with {@link Integer#toUnsignedLong}. - * @param inetAddr is an InetAddress corresponding to the IPv4 address - * @return the IP address as integer - */ - public static int inet4AddressToIntHTH(Inet4Address inetAddr) - throws IllegalArgumentException { - byte [] addr = inetAddr.getAddress(); - return ((addr[0] & 0xff) << 24) | ((addr[1] & 0xff) << 16) - | ((addr[2] & 0xff) << 8) | (addr[3] & 0xff); - } - - /** - * Convert a IPv4 address from an InetAddress to an integer (1.2.3.4 -> 0x04030201) - * - * <p>This method stores the higher-order IPv4 address bytes in the lower-order int bytes, - * which is an unusual convention. Consider {@link #inet4AddressToIntHTH(Inet4Address)} instead. - * @param inetAddr is an InetAddress corresponding to the IPv4 address - * @return the IP address as integer - */ - public static int inet4AddressToIntHTL(Inet4Address inetAddr) { - return Integer.reverseBytes(inet4AddressToIntHTH(inetAddr)); - } - - /** - * Convert a network prefix length to an IPv4 netmask integer (prefixLength 17 -> 0xffff8000) - * @return the IPv4 netmask as an integer - */ - public static int prefixLengthToV4NetmaskIntHTH(int prefixLength) - throws IllegalArgumentException { - if (prefixLength < 0 || prefixLength > 32) { - throw new IllegalArgumentException("Invalid prefix length (0 <= prefix <= 32)"); - } - // (int)a << b is equivalent to a << (b & 0x1f): can't shift by 32 (-1 << 32 == -1) - return prefixLength == 0 ? 0 : 0xffffffff << (32 - prefixLength); - } - - /** - * Convert a network prefix length to an IPv4 netmask integer (prefixLength 17 -> 0x0080ffff). - * - * <p>This method stores the higher-order IPv4 address bytes in the lower-order int bytes, - * which is an unusual convention. Consider {@link #prefixLengthToV4NetmaskIntHTH(int)} instead. - * @return the IPv4 netmask as an integer - */ - public static int prefixLengthToV4NetmaskIntHTL(int prefixLength) - throws IllegalArgumentException { - return Integer.reverseBytes(prefixLengthToV4NetmaskIntHTH(prefixLength)); - } - - /** - * Convert an IPv4 netmask to a prefix length, checking that the netmask is contiguous. - * @param netmask as a {@code Inet4Address}. - * @return the network prefix length - * @throws IllegalArgumentException the specified netmask was not contiguous. - * @hide - */ - public static int netmaskToPrefixLength(Inet4Address netmask) { - // inetAddressToInt returns an int in *network* byte order. - int i = inet4AddressToIntHTH(netmask); - int prefixLength = Integer.bitCount(i); - int trailingZeros = Integer.numberOfTrailingZeros(i); - if (trailingZeros != 32 - prefixLength) { - throw new IllegalArgumentException("Non-contiguous netmask: " + Integer.toHexString(i)); - } - return prefixLength; - } - - /** - * Returns the implicit netmask of an IPv4 address, as was the custom before 1993. - */ - public static int getImplicitNetmask(Inet4Address address) { - int firstByte = address.getAddress()[0] & 0xff; // Convert to an unsigned value. - if (firstByte < 128) { - return 8; - } else if (firstByte < 192) { - return 16; - } else if (firstByte < 224) { - return 24; - } else { - return 32; // Will likely not end well for other reasons. - } - } - - /** - * Get the broadcast address for a given prefix. - * - * <p>For example 192.168.0.1/24 -> 192.168.0.255 - */ - public static Inet4Address getBroadcastAddress(Inet4Address addr, int prefixLength) - throws IllegalArgumentException { - final int intBroadcastAddr = inet4AddressToIntHTH(addr) - | ~prefixLengthToV4NetmaskIntHTH(prefixLength); - return intToInet4AddressHTH(intBroadcastAddr); - } - - /** - * Get a prefix mask as Inet4Address for a given prefix length. - * - * <p>For example 20 -> 255.255.240.0 - */ - public static Inet4Address getPrefixMaskAsInet4Address(int prefixLength) - throws IllegalArgumentException { - return intToInet4AddressHTH(prefixLengthToV4NetmaskIntHTH(prefixLength)); - } -} diff --git a/core/java/android/net/shared/InetAddressUtils.java b/core/java/android/net/shared/InetAddressUtils.java deleted file mode 100644 index c9ee3a7cce4b..000000000000 --- a/core/java/android/net/shared/InetAddressUtils.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (C) 2012 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.shared; - -import android.os.Parcel; - -import java.net.InetAddress; -import java.net.UnknownHostException; - -/** - * Collection of utilities to interact with {@link InetAddress} - * @hide - */ -public class InetAddressUtils { - - /** - * Writes an InetAddress to a parcel. The address may be null. This is likely faster than - * calling writeSerializable. - * @hide - */ - public static void parcelInetAddress(Parcel parcel, InetAddress address, int flags) { - byte[] addressArray = (address != null) ? address.getAddress() : null; - parcel.writeByteArray(addressArray); - } - - /** - * Reads an InetAddress from a parcel. Returns null if the address that was written was null - * or if the data is invalid. - * @hide - */ - public static InetAddress unparcelInetAddress(Parcel in) { - byte[] addressArray = in.createByteArray(); - if (addressArray == null) { - return null; - } - try { - return InetAddress.getByAddress(addressArray); - } catch (UnknownHostException e) { - return null; - } - } - - private InetAddressUtils() {} -} 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/android/text/format/Time.java b/core/java/android/text/format/Time.java index 8e8409d15143..e7339380df69 100644 --- a/core/java/android/text/format/Time.java +++ b/core/java/android/text/format/Time.java @@ -18,8 +18,8 @@ package android.text.format; import android.util.TimeFormatException; -import libcore.timezone.ZoneInfoDb; -import libcore.util.ZoneInfo; +import com.android.i18n.timezone.ZoneInfoData; +import com.android.i18n.timezone.ZoneInfoDb; import java.util.Locale; import java.util.TimeZone; @@ -1059,15 +1059,15 @@ public class Time { * to the enclosing object, but others do not: thus separate state is retained. */ private static class TimeCalculator { - public final ZoneInfo.WallTime wallTime; + public final ZoneInfoData.WallTime wallTime; public String timezone; // Information about the current timezone. - private ZoneInfo zoneInfo; + private ZoneInfoData mZoneInfoData; public TimeCalculator(String timezoneId) { - this.zoneInfo = lookupZoneInfo(timezoneId); - this.wallTime = new ZoneInfo.WallTime(); + this.mZoneInfoData = lookupZoneInfoData(timezoneId); + this.wallTime = new ZoneInfoData.WallTime(); } public long toMillis(boolean ignoreDst) { @@ -1075,7 +1075,7 @@ public class Time { wallTime.setIsDst(-1); } - int r = wallTime.mktime(zoneInfo); + int r = wallTime.mktime(mZoneInfoData); if (r == -1) { return -1; } @@ -1087,7 +1087,7 @@ public class Time { int intSeconds = (int) (millis / 1000); updateZoneInfoFromTimeZone(); - wallTime.localtime(intSeconds, zoneInfo); + wallTime.localtime(intSeconds, mZoneInfoData); } public String format(String format) { @@ -1095,31 +1095,31 @@ public class Time { format = "%c"; } TimeFormatter formatter = new TimeFormatter(); - return formatter.format(format, wallTime, zoneInfo); + return formatter.format(format, wallTime, mZoneInfoData); } private void updateZoneInfoFromTimeZone() { - if (!zoneInfo.getID().equals(timezone)) { - this.zoneInfo = lookupZoneInfo(timezone); + if (!mZoneInfoData.getID().equals(timezone)) { + this.mZoneInfoData = lookupZoneInfoData(timezone); } } - private static ZoneInfo lookupZoneInfo(String timezoneId) { - ZoneInfo zoneInfo = ZoneInfoDb.getInstance().makeTimeZone(timezoneId); - if (zoneInfo == null) { - zoneInfo = ZoneInfoDb.getInstance().makeTimeZone("GMT"); + private static ZoneInfoData lookupZoneInfoData(String timezoneId) { + ZoneInfoData zoneInfoData = ZoneInfoDb.getInstance().makeZoneInfoData(timezoneId); + if (zoneInfoData == null) { + zoneInfoData = ZoneInfoDb.getInstance().makeZoneInfoData("GMT"); } - if (zoneInfo == null) { + if (zoneInfoData == null) { throw new AssertionError("GMT not found: \"" + timezoneId + "\""); } - return zoneInfo; + return zoneInfoData; } public void switchTimeZone(String timezone) { - int seconds = wallTime.mktime(zoneInfo); + int seconds = wallTime.mktime(mZoneInfoData); this.timezone = timezone; updateZoneInfoFromTimeZone(); - wallTime.localtime(seconds, zoneInfo); + wallTime.localtime(seconds, mZoneInfoData); } public String format2445(boolean hasTime) { diff --git a/core/java/android/text/format/TimeFormatter.java b/core/java/android/text/format/TimeFormatter.java index f7fd89d7d819..cd541f2b829f 100644 --- a/core/java/android/text/format/TimeFormatter.java +++ b/core/java/android/text/format/TimeFormatter.java @@ -22,8 +22,9 @@ package android.text.format; import android.content.res.Resources; +import com.android.i18n.timezone.ZoneInfoData; + import libcore.icu.LocaleData; -import libcore.util.ZoneInfo; import java.nio.CharBuffer; import java.time.Instant; @@ -94,8 +95,8 @@ class TimeFormatter { * incorrect digit localization behavior. */ String formatMillisWithFixedFormat(long timeMillis) { - // This method is deliberately not a general purpose replacement for - // format(String, ZoneInfo.WallTime, ZoneInfo): It hard-codes the pattern used; many of the + // This method is deliberately not a general purpose replacement for format(String, + // ZoneInfoData.WallTime, ZoneInfoData): It hard-codes the pattern used; many of the // pattern characters supported by Time.format() have unusual behavior which would make // using java.time.format or similar packages difficult. It would be a lot of work to share // behavior and many internal Android usecases can be covered by this common pattern @@ -144,7 +145,8 @@ class TimeFormatter { /** * Format the specified {@code wallTime} using {@code pattern}. The output is returned. */ - public String format(String pattern, ZoneInfo.WallTime wallTime, ZoneInfo zoneInfo) { + public String format(String pattern, ZoneInfoData.WallTime wallTime, + ZoneInfoData zoneInfoData) { try { StringBuilder stringBuilder = new StringBuilder(); @@ -153,7 +155,7 @@ class TimeFormatter { // and locale sensitive strings are output directly using outputBuilder. numberFormatter = new Formatter(stringBuilder, Locale.US); - formatInternal(pattern, wallTime, zoneInfo); + formatInternal(pattern, wallTime, zoneInfoData); String result = stringBuilder.toString(); // The localizeDigits() behavior is the source of a bug since some formats are defined // as being in ASCII and not localized. @@ -186,13 +188,14 @@ class TimeFormatter { * Format the specified {@code wallTime} using {@code pattern}. The output is written to * {@link #outputBuilder}. */ - private void formatInternal(String pattern, ZoneInfo.WallTime wallTime, ZoneInfo zoneInfo) { + private void formatInternal(String pattern, ZoneInfoData.WallTime wallTime, + ZoneInfoData zoneInfoData) { CharBuffer formatBuffer = CharBuffer.wrap(pattern); while (formatBuffer.remaining() > 0) { boolean outputCurrentChar = true; char currentChar = formatBuffer.get(formatBuffer.position()); if (currentChar == '%') { - outputCurrentChar = handleToken(formatBuffer, wallTime, zoneInfo); + outputCurrentChar = handleToken(formatBuffer, wallTime, zoneInfoData); } if (outputCurrentChar) { outputBuilder.append(formatBuffer.get(formatBuffer.position())); @@ -201,8 +204,8 @@ class TimeFormatter { } } - private boolean handleToken(CharBuffer formatBuffer, ZoneInfo.WallTime wallTime, - ZoneInfo zoneInfo) { + private boolean handleToken(CharBuffer formatBuffer, ZoneInfoData.WallTime wallTime, + ZoneInfoData zoneInfoData) { // The char at formatBuffer.position() is expected to be '%' at this point. int modifier = 0; @@ -247,10 +250,10 @@ class TimeFormatter { outputYear(wallTime.getYear(), true, false, modifier); return false; case 'c': - formatInternal(dateTimeFormat, wallTime, zoneInfo); + formatInternal(dateTimeFormat, wallTime, zoneInfoData); return false; case 'D': - formatInternal("%m/%d/%y", wallTime, zoneInfo); + formatInternal("%m/%d/%y", wallTime, zoneInfoData); return false; case 'd': numberFormatter.format(getFormat(modifier, "%02d", "%2d", "%d", "%02d"), @@ -272,7 +275,7 @@ class TimeFormatter { wallTime.getMonthDay()); return false; case 'F': - formatInternal("%Y-%m-%d", wallTime, zoneInfo); + formatInternal("%Y-%m-%d", wallTime, zoneInfoData); return false; case 'H': numberFormatter.format(getFormat(modifier, "%02d", "%2d", "%d", "%02d"), @@ -315,21 +318,21 @@ class TimeFormatter { : localeData.amPm[0], FORCE_LOWER_CASE); return false; case 'R': - formatInternal("%H:%M", wallTime, zoneInfo); + formatInternal("%H:%M", wallTime, zoneInfoData); return false; case 'r': - formatInternal("%I:%M:%S %p", wallTime, zoneInfo); + formatInternal("%I:%M:%S %p", wallTime, zoneInfoData); return false; case 'S': numberFormatter.format(getFormat(modifier, "%02d", "%2d", "%d", "%02d"), wallTime.getSecond()); return false; case 's': - int timeInSeconds = wallTime.mktime(zoneInfo); + int timeInSeconds = wallTime.mktime(zoneInfoData); outputBuilder.append(Integer.toString(timeInSeconds)); return false; case 'T': - formatInternal("%H:%M:%S", wallTime, zoneInfo); + formatInternal("%H:%M:%S", wallTime, zoneInfoData); return false; case 't': outputBuilder.append('\t'); @@ -383,7 +386,7 @@ class TimeFormatter { return false; } case 'v': - formatInternal("%e-%b-%Y", wallTime, zoneInfo); + formatInternal("%e-%b-%Y", wallTime, zoneInfoData); return false; case 'W': int n = (wallTime.getYearDay() + DAYSPERWEEK - ( @@ -395,10 +398,10 @@ class TimeFormatter { numberFormatter.format("%d", wallTime.getWeekDay()); return false; case 'X': - formatInternal(timeOnlyFormat, wallTime, zoneInfo); + formatInternal(timeOnlyFormat, wallTime, zoneInfoData); return false; case 'x': - formatInternal(dateOnlyFormat, wallTime, zoneInfo); + formatInternal(dateOnlyFormat, wallTime, zoneInfoData); return false; case 'y': outputYear(wallTime.getYear(), false, true, modifier); @@ -411,7 +414,8 @@ class TimeFormatter { return false; } boolean isDst = wallTime.getIsDst() != 0; - modifyAndAppend(zoneInfo.getDisplayName(isDst, TimeZone.SHORT), modifier); + modifyAndAppend(TimeZone.getTimeZone(zoneInfoData.getID()) + .getDisplayName(isDst, TimeZone.SHORT), modifier); return false; case 'z': { if (wallTime.getIsDst() < 0) { @@ -432,7 +436,7 @@ class TimeFormatter { return false; } case '+': - formatInternal("%a %b %e %H:%M:%S %Z %Y", wallTime, zoneInfo); + formatInternal("%a %b %e %H:%M:%S %Z %Y", wallTime, zoneInfoData); return false; case '%': // If conversion char is undefined, behavior is undefined. Print out the diff --git a/core/java/android/timezone/CountryTimeZones.java b/core/java/android/timezone/CountryTimeZones.java index 8fd303b8a64c..44d140242409 100644 --- a/core/java/android/timezone/CountryTimeZones.java +++ b/core/java/android/timezone/CountryTimeZones.java @@ -40,9 +40,9 @@ public final class CountryTimeZones { public static final class TimeZoneMapping { @NonNull - private libcore.timezone.CountryTimeZones.TimeZoneMapping mDelegate; + private com.android.i18n.timezone.CountryTimeZones.TimeZoneMapping mDelegate; - TimeZoneMapping(libcore.timezone.CountryTimeZones.TimeZoneMapping delegate) { + TimeZoneMapping(com.android.i18n.timezone.CountryTimeZones.TimeZoneMapping delegate) { this.mDelegate = Objects.requireNonNull(delegate); } @@ -147,9 +147,9 @@ public final class CountryTimeZones { } @NonNull - private final libcore.timezone.CountryTimeZones mDelegate; + private final com.android.i18n.timezone.CountryTimeZones mDelegate; - CountryTimeZones(libcore.timezone.CountryTimeZones delegate) { + CountryTimeZones(com.android.i18n.timezone.CountryTimeZones delegate) { mDelegate = delegate; } @@ -221,7 +221,7 @@ public final class CountryTimeZones { @Nullable public OffsetResult lookupByOffsetWithBias(long whenMillis, @Nullable TimeZone bias, int totalOffsetMillis, boolean isDst) { - libcore.timezone.CountryTimeZones.OffsetResult delegateOffsetResult = + com.android.i18n.timezone.CountryTimeZones.OffsetResult delegateOffsetResult = mDelegate.lookupByOffsetWithBias( whenMillis, bias, totalOffsetMillis, isDst); return delegateOffsetResult == null ? null : @@ -244,7 +244,7 @@ public final class CountryTimeZones { @Nullable public OffsetResult lookupByOffsetWithBias(long whenMillis, @Nullable TimeZone bias, int totalOffsetMillis) { - libcore.timezone.CountryTimeZones.OffsetResult delegateOffsetResult = + com.android.i18n.timezone.CountryTimeZones.OffsetResult delegateOffsetResult = mDelegate.lookupByOffsetWithBias(whenMillis, bias, totalOffsetMillis); return delegateOffsetResult == null ? null : new OffsetResult( @@ -260,11 +260,12 @@ public final class CountryTimeZones { */ @NonNull public List<TimeZoneMapping> getEffectiveTimeZoneMappingsAt(long whenMillis) { - List<libcore.timezone.CountryTimeZones.TimeZoneMapping> delegateList = + List<com.android.i18n.timezone.CountryTimeZones.TimeZoneMapping> delegateList = mDelegate.getEffectiveTimeZoneMappingsAt(whenMillis); List<TimeZoneMapping> toReturn = new ArrayList<>(delegateList.size()); - for (libcore.timezone.CountryTimeZones.TimeZoneMapping delegateMapping : delegateList) { + for (com.android.i18n.timezone.CountryTimeZones.TimeZoneMapping delegateMapping + : delegateList) { toReturn.add(new TimeZoneMapping(delegateMapping)); } return Collections.unmodifiableList(toReturn); diff --git a/core/java/android/timezone/TelephonyLookup.java b/core/java/android/timezone/TelephonyLookup.java index a4c3fbd33410..c97bf28cebfe 100644 --- a/core/java/android/timezone/TelephonyLookup.java +++ b/core/java/android/timezone/TelephonyLookup.java @@ -41,16 +41,17 @@ public final class TelephonyLookup { public static TelephonyLookup getInstance() { synchronized (sLock) { if (sInstance == null) { - sInstance = new TelephonyLookup(libcore.timezone.TelephonyLookup.getInstance()); + sInstance = new TelephonyLookup(com.android.i18n.timezone.TelephonyLookup + .getInstance()); } return sInstance; } } @NonNull - private final libcore.timezone.TelephonyLookup mDelegate; + private final com.android.i18n.timezone.TelephonyLookup mDelegate; - private TelephonyLookup(@NonNull libcore.timezone.TelephonyLookup delegate) { + private TelephonyLookup(@NonNull com.android.i18n.timezone.TelephonyLookup delegate) { mDelegate = Objects.requireNonNull(delegate); } @@ -60,7 +61,7 @@ public final class TelephonyLookup { */ @Nullable public TelephonyNetworkFinder getTelephonyNetworkFinder() { - libcore.timezone.TelephonyNetworkFinder telephonyNetworkFinderDelegate = + com.android.i18n.timezone.TelephonyNetworkFinder telephonyNetworkFinderDelegate = mDelegate.getTelephonyNetworkFinder(); return telephonyNetworkFinderDelegate != null ? new TelephonyNetworkFinder(telephonyNetworkFinderDelegate) : null; diff --git a/core/java/android/timezone/TelephonyNetwork.java b/core/java/android/timezone/TelephonyNetwork.java index 823cd251fbf0..3b65c6ffc379 100644 --- a/core/java/android/timezone/TelephonyNetwork.java +++ b/core/java/android/timezone/TelephonyNetwork.java @@ -28,9 +28,9 @@ import java.util.Objects; public final class TelephonyNetwork { @NonNull - private final libcore.timezone.TelephonyNetwork mDelegate; + private final com.android.i18n.timezone.TelephonyNetwork mDelegate; - TelephonyNetwork(@NonNull libcore.timezone.TelephonyNetwork delegate) { + TelephonyNetwork(@NonNull com.android.i18n.timezone.TelephonyNetwork delegate) { mDelegate = Objects.requireNonNull(delegate); } diff --git a/core/java/android/timezone/TelephonyNetworkFinder.java b/core/java/android/timezone/TelephonyNetworkFinder.java index 4bfeff8a73ad..c69ddf86d3f8 100644 --- a/core/java/android/timezone/TelephonyNetworkFinder.java +++ b/core/java/android/timezone/TelephonyNetworkFinder.java @@ -29,9 +29,9 @@ import java.util.Objects; public final class TelephonyNetworkFinder { @NonNull - private final libcore.timezone.TelephonyNetworkFinder mDelegate; + private final com.android.i18n.timezone.TelephonyNetworkFinder mDelegate; - TelephonyNetworkFinder(libcore.timezone.TelephonyNetworkFinder delegate) { + TelephonyNetworkFinder(com.android.i18n.timezone.TelephonyNetworkFinder delegate) { mDelegate = Objects.requireNonNull(delegate); } @@ -45,7 +45,7 @@ public final class TelephonyNetworkFinder { Objects.requireNonNull(mcc); Objects.requireNonNull(mnc); - libcore.timezone.TelephonyNetwork telephonyNetworkDelegate = + com.android.i18n.timezone.TelephonyNetwork telephonyNetworkDelegate = mDelegate.findNetworkByMccMnc(mcc, mnc); return telephonyNetworkDelegate != null ? new TelephonyNetwork(telephonyNetworkDelegate) : null; diff --git a/core/java/android/timezone/TimeZoneFinder.java b/core/java/android/timezone/TimeZoneFinder.java index 03f5013f230c..bf4275fb5b56 100644 --- a/core/java/android/timezone/TimeZoneFinder.java +++ b/core/java/android/timezone/TimeZoneFinder.java @@ -41,16 +41,17 @@ public final class TimeZoneFinder { public static TimeZoneFinder getInstance() { synchronized (sLock) { if (sInstance == null) { - sInstance = new TimeZoneFinder(libcore.timezone.TimeZoneFinder.getInstance()); + sInstance = new TimeZoneFinder(com.android.i18n.timezone.TimeZoneFinder + .getInstance()); } } return sInstance; } @NonNull - private final libcore.timezone.TimeZoneFinder mDelegate; + private final com.android.i18n.timezone.TimeZoneFinder mDelegate; - private TimeZoneFinder(@NonNull libcore.timezone.TimeZoneFinder delegate) { + private TimeZoneFinder(@NonNull com.android.i18n.timezone.TimeZoneFinder delegate) { mDelegate = Objects.requireNonNull(delegate); } @@ -70,7 +71,8 @@ public final class TimeZoneFinder { */ @Nullable public CountryTimeZones lookupCountryTimeZones(@NonNull String countryIso) { - libcore.timezone.CountryTimeZones delegate = mDelegate.lookupCountryTimeZones(countryIso); + com.android.i18n.timezone.CountryTimeZones delegate = mDelegate + .lookupCountryTimeZones(countryIso); return delegate == null ? null : new CountryTimeZones(delegate); } } diff --git a/core/java/android/timezone/TzDataSetVersion.java b/core/java/android/timezone/TzDataSetVersion.java index f993012aeb1c..e1fb932b977d 100644 --- a/core/java/android/timezone/TzDataSetVersion.java +++ b/core/java/android/timezone/TzDataSetVersion.java @@ -50,14 +50,14 @@ public final class TzDataSetVersion { * Returns the major tz data format version supported by this device. */ public static int currentFormatMajorVersion() { - return libcore.timezone.TzDataSetVersion.currentFormatMajorVersion(); + return com.android.i18n.timezone.TzDataSetVersion.currentFormatMajorVersion(); } /** * Returns the minor tz data format version supported by this device. */ public static int currentFormatMinorVersion() { - return libcore.timezone.TzDataSetVersion.currentFormatMinorVersion(); + return com.android.i18n.timezone.TzDataSetVersion.currentFormatMinorVersion(); } /** @@ -65,7 +65,7 @@ public final class TzDataSetVersion { * with the current system image, and set of active modules. */ public static boolean isCompatibleWithThisDevice(TzDataSetVersion tzDataSetVersion) { - return libcore.timezone.TzDataSetVersion.isCompatibleWithThisDevice( + return com.android.i18n.timezone.TzDataSetVersion.isCompatibleWithThisDevice( tzDataSetVersion.mDelegate); } @@ -76,8 +76,8 @@ public final class TzDataSetVersion { public static TzDataSetVersion read() throws IOException, TzDataSetException { try { return new TzDataSetVersion( - libcore.timezone.TzDataSetVersion.readTimeZoneModuleVersion()); - } catch (libcore.timezone.TzDataSetVersion.TzDataSetException e) { + com.android.i18n.timezone.TzDataSetVersion.readTimeZoneModuleVersion()); + } catch (com.android.i18n.timezone.TzDataSetVersion.TzDataSetException e) { throw new TzDataSetException(e.getMessage(), e); } } @@ -100,9 +100,9 @@ public final class TzDataSetVersion { } @NonNull - private final libcore.timezone.TzDataSetVersion mDelegate; + private final com.android.i18n.timezone.TzDataSetVersion mDelegate; - private TzDataSetVersion(@NonNull libcore.timezone.TzDataSetVersion delegate) { + private TzDataSetVersion(@NonNull com.android.i18n.timezone.TzDataSetVersion delegate) { mDelegate = Objects.requireNonNull(delegate); } diff --git a/core/java/android/timezone/ZoneInfoDb.java b/core/java/android/timezone/ZoneInfoDb.java index 9354a695812d..65d6eaddf824 100644 --- a/core/java/android/timezone/ZoneInfoDb.java +++ b/core/java/android/timezone/ZoneInfoDb.java @@ -41,16 +41,16 @@ public final class ZoneInfoDb { public static ZoneInfoDb getInstance() { synchronized (sLock) { if (sInstance == null) { - sInstance = new ZoneInfoDb(libcore.timezone.ZoneInfoDb.getInstance()); + sInstance = new ZoneInfoDb(com.android.i18n.timezone.ZoneInfoDb.getInstance()); } } return sInstance; } @NonNull - private final libcore.timezone.ZoneInfoDb mDelegate; + private final com.android.i18n.timezone.ZoneInfoDb mDelegate; - private ZoneInfoDb(libcore.timezone.ZoneInfoDb delegate) { + private ZoneInfoDb(com.android.i18n.timezone.ZoneInfoDb delegate) { mDelegate = Objects.requireNonNull(delegate); } diff --git a/core/java/android/util/TimeUtils.java b/core/java/android/util/TimeUtils.java index 6e41fc8017c1..384040013a6d 100644 --- a/core/java/android/util/TimeUtils.java +++ b/core/java/android/util/TimeUtils.java @@ -23,10 +23,10 @@ import android.compat.annotation.UnsupportedAppUsage; import android.os.Build; import android.os.SystemClock; -import libcore.timezone.CountryTimeZones; -import libcore.timezone.CountryTimeZones.TimeZoneMapping; -import libcore.timezone.TimeZoneFinder; -import libcore.timezone.ZoneInfoDb; +import com.android.i18n.timezone.CountryTimeZones; +import com.android.i18n.timezone.CountryTimeZones.TimeZoneMapping; +import com.android.i18n.timezone.TimeZoneFinder; +import com.android.i18n.timezone.ZoneInfoDb; import java.io.PrintWriter; import java.text.SimpleDateFormat; diff --git a/core/java/com/android/internal/logging/AndroidHandler.java b/core/java/com/android/internal/logging/AndroidHandler.java index f55a31fcc986..119f3662a94f 100644 --- a/core/java/com/android/internal/logging/AndroidHandler.java +++ b/core/java/com/android/internal/logging/AndroidHandler.java @@ -17,9 +17,8 @@ package com.android.internal.logging; import android.util.Log; + import com.android.internal.util.FastPrintWriter; -import dalvik.system.DalvikLogging; -import dalvik.system.DalvikLogHandler; import java.io.PrintWriter; import java.io.StringWriter; @@ -82,7 +81,7 @@ import java.util.logging.Logger; * </tr> * </table> */ -public class AndroidHandler extends Handler implements DalvikLogHandler { +public class AndroidHandler extends Handler { /** * Holds the formatter for all Android log handlers. */ @@ -121,10 +120,32 @@ public class AndroidHandler extends Handler implements DalvikLogHandler { // No need to flush, but must implement abstract method. } + /** + * Returns the short logger tag (up to 23 chars) for the given logger name. + * Traditionally loggers are named by fully-qualified Java classes; this + * method attempts to return a concise identifying part of such names. + */ + private static String loggerNameToTag(String loggerName) { + // Anonymous logger. + if (loggerName == null) { + return "null"; + } + + int length = loggerName.length(); + if (length <= 23) { + return loggerName; + } + + int lastPeriod = loggerName.lastIndexOf("."); + return length - (lastPeriod + 1) <= 23 + ? loggerName.substring(lastPeriod + 1) + : loggerName.substring(loggerName.length() - 23); + } + @Override public void publish(LogRecord record) { int level = getAndroidLevel(record.getLevel()); - String tag = DalvikLogging.loggerNameToTag(record.getLoggerName()); + String tag = loggerNameToTag(record.getLoggerName()); if (!Log.isLoggable(tag, level)) { return; } 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/proto/android/stats/connectivity/tethering.proto b/core/proto/android/stats/connectivity/tethering.proto index 6303b7d1870b..13f0b8c44fb5 100644 --- a/core/proto/android/stats/connectivity/tethering.proto +++ b/core/proto/android/stats/connectivity/tethering.proto @@ -87,7 +87,7 @@ enum UpstreamType { enum UserType { // Unknown. - USER_UNKOWNN = 0; + USER_UNKNOWN = 0; // Settings. USER_SETTINGS = 1; // System UI. diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml index ad1f1f005baa..3d73ade33d5b 100644 --- a/core/res/res/values/config.xml +++ b/core/res/res/values/config.xml @@ -3064,6 +3064,11 @@ empty string is passed in --> <string name="config_wlan_data_service_package" translatable="false"></string> + <!-- Boolean indicating whether the Iwlan data service supports persistence of iwlan ipsec + tunnels across service restart. If iwlan tunnels are not persisted across restart, + Framework will clean up dangling data connections when service restarts --> + <bool name="config_wlan_data_service_conn_persistence_on_restart">true</bool> + <!-- Cellular data service class name to bind to by default. If none is specified in an overlay, an empty string is passed in --> <string name="config_wwan_data_service_class" translatable="false"></string> diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml index b0ee810fee41..ece65ff21487 100644 --- a/core/res/res/values/symbols.xml +++ b/core/res/res/values/symbols.xml @@ -298,6 +298,7 @@ <java-symbol type="string" name="config_wlan_network_service_package" /> <java-symbol type="string" name="config_wwan_network_service_class" /> <java-symbol type="string" name="config_wlan_network_service_class" /> + <java-symbol type="bool" name="config_wlan_data_service_conn_persistence_on_restart" /> <java-symbol type="string" name="config_wwan_data_service_package" /> <java-symbol type="string" name="config_wlan_data_service_package" /> <java-symbol type="string" name="config_wwan_data_service_class" /> 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/audioeffect/Visualizer.cpp b/media/jni/audioeffect/Visualizer.cpp index efeb3352d393..f4d65d0a397f 100644 --- a/media/jni/audioeffect/Visualizer.cpp +++ b/media/jni/audioeffect/Visualizer.cpp @@ -25,6 +25,7 @@ #include <limits.h> #include <audio_utils/fixedfft.h> +#include <cutils/bitops.h> #include <utils/Thread.h> #include "Visualizer.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/SettingsLib/src/com/android/settingslib/datetime/ZoneGetter.java b/packages/SettingsLib/src/com/android/settingslib/datetime/ZoneGetter.java index 231809bfece4..e5fd0ba5d9bc 100644 --- a/packages/SettingsLib/src/com/android/settingslib/datetime/ZoneGetter.java +++ b/packages/SettingsLib/src/com/android/settingslib/datetime/ZoneGetter.java @@ -32,12 +32,11 @@ import androidx.annotation.VisibleForTesting; import androidx.core.text.BidiFormatter; import androidx.core.text.TextDirectionHeuristicsCompat; +import com.android.i18n.timezone.CountryTimeZones; +import com.android.i18n.timezone.CountryTimeZones.TimeZoneMapping; +import com.android.i18n.timezone.TimeZoneFinder; import com.android.settingslib.R; -import libcore.timezone.CountryTimeZones; -import libcore.timezone.CountryTimeZones.TimeZoneMapping; -import libcore.timezone.TimeZoneFinder; - import org.xmlpull.v1.XmlPullParserException; import java.util.ArrayList; 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/SystemUI/src/com/android/systemui/statusbar/policy/MobileSignalController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/MobileSignalController.java index 17481bf601e1..c8aa22fc28f8 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/MobileSignalController.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/MobileSignalController.java @@ -640,8 +640,7 @@ public class MobileSignalController extends SignalController< + " dataState=" + state.getDataRegistrationState()); } mServiceState = state; - // onDisplayInfoChanged is invoked directly after onServiceStateChanged, so not calling - // updateTelephony() to prevent icon flickering in case of overrides. + updateTelephony(); } @Override @@ -651,10 +650,6 @@ public class MobileSignalController extends SignalController< + " type=" + networkType); } mDataState = state; - if (networkType != mTelephonyDisplayInfo.getNetworkType()) { - mTelephonyDisplayInfo = new TelephonyDisplayInfo(networkType, - TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NONE); - } updateTelephony(); } diff --git a/packages/Tethering/Android.bp b/packages/Tethering/Android.bp index 4116afca9816..f89ee24f9594 100644 --- a/packages/Tethering/Android.bp +++ b/packages/Tethering/Android.bp @@ -27,7 +27,8 @@ java_defaults { "androidx.annotation_annotation", "netd_aidl_interface-unstable-java", "netlink-client", - "networkstack-aidl-interfaces-java", + // TODO: use networkstack-client instead of just including the AIDL interface + "networkstack-aidl-interfaces-unstable-java", "android.hardware.tetheroffload.config-V1.0-java", "android.hardware.tetheroffload.control-V1.0-java", "net-utils-framework-common", diff --git a/packages/Tethering/common/TetheringLib/src/android/net/TetheringManager.java b/packages/Tethering/common/TetheringLib/src/android/net/TetheringManager.java index 04ca03382837..87e5c1e52198 100644 --- a/packages/Tethering/common/TetheringLib/src/android/net/TetheringManager.java +++ b/packages/Tethering/common/TetheringLib/src/android/net/TetheringManager.java @@ -171,6 +171,14 @@ public class TetheringManager { */ public static final int TETHERING_ETHERNET = 5; + /** + * WIGIG tethering type. Use a separate type to prevent + * conflicts with TETHERING_WIFI + * This type is only used internally by the tethering module + * @hide + */ + public static final int TETHERING_WIGIG = 6; + /** @hide */ @Retention(RetentionPolicy.SOURCE) @IntDef(value = { diff --git a/packages/Tethering/jarjar-rules.txt b/packages/Tethering/jarjar-rules.txt index e90a2ccaa2a3..591861f5b837 100644 --- a/packages/Tethering/jarjar-rules.txt +++ b/packages/Tethering/jarjar-rules.txt @@ -1,17 +1,11 @@ # These must be kept in sync with the framework-tethering-shared-srcs filegroup. -# If there are files in that filegroup that do not appear here, the classes in the +# Classes from the framework-tethering-shared-srcs filegroup. +# If there are files in that filegroup that are not covered below, the classes in the # module will be overwritten by the ones in the framework. -# Don't jar-jar the entire package because tethering still use some internal classes -# (like TrafficStatsConstants in com.android.internal.util) -# TODO: simply these when tethering is built as system_current. -rule com.android.internal.util.BitUtils* com.android.networkstack.tethering.util.BitUtils@1 -rule com.android.internal.util.IndentingPrintWriter.java* com.android.networkstack.tethering.util.IndentingPrintWriter.java@1 -rule com.android.internal.util.IState.java* com.android.networkstack.tethering.util.IState.java@1 -rule com.android.internal.util.MessageUtils* com.android.networkstack.tethering.util.MessageUtils@1 -rule com.android.internal.util.State* com.android.networkstack.tethering.util.State@1 -rule com.android.internal.util.StateMachine* com.android.networkstack.tethering.util.StateMachine@1 -rule com.android.internal.util.TrafficStatsConstants* com.android.networkstack.tethering.util.TrafficStatsConstants@1 - -rule android.net.LocalLog* com.android.networkstack.tethering.LocalLog@1 +rule com.android.internal.util.** com.android.networkstack.tethering.util.@1 +rule android.util.LocalLog* com.android.networkstack.tethering.util.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/res/values/config.xml b/packages/Tethering/res/values/config.xml index 3f5bc901d07b..4807e52804a1 100644 --- a/packages/Tethering/res/values/config.xml +++ b/packages/Tethering/res/values/config.xml @@ -43,6 +43,13 @@ </string-array> <!-- List of regexpressions describing the interface (if any) that represent tetherable + WiGig interfaces. If the device doesn't want to support tethering over WiGig this + should be empty. An example would be "wigig\\d" --> + <string-array translatable="false" name="config_tether_wigig_regexs"> + <item>"wigig\\d"</item> + </string-array> + + <!-- List of regexpressions describing the interface (if any) that represent tetherable Wifi P2P interfaces. If the device doesn't want to support tethering over Wifi P2p this should be empty. An example would be "p2p-p2p.*" --> <string-array translatable="false" name="config_tether_wifi_p2p_regexs"> diff --git a/packages/Tethering/res/values/overlayable.xml b/packages/Tethering/res/values/overlayable.xml index 4e2bb1e31b2a..6a33d55cb0de 100644 --- a/packages/Tethering/res/values/overlayable.xml +++ b/packages/Tethering/res/values/overlayable.xml @@ -20,6 +20,7 @@ <item type="array" name="config_tether_usb_regexs"/> <item type="array" name="config_tether_ncm_regexs" /> <item type="array" name="config_tether_wifi_regexs"/> + <item type="array" name="config_tether_wigig_regexs"/> <item type="array" name="config_tether_wifi_p2p_regexs"/> <item type="array" name="config_tether_bluetooth_regexs"/> <item type="array" name="config_tether_dhcp_range"/> diff --git a/packages/Tethering/src/android/net/dhcp/DhcpServingParamsParcelExt.java b/packages/Tethering/src/android/net/dhcp/DhcpServingParamsParcelExt.java index 4710a30b2998..aaaec17bf922 100644 --- a/packages/Tethering/src/android/net/dhcp/DhcpServingParamsParcelExt.java +++ b/packages/Tethering/src/android/net/dhcp/DhcpServingParamsParcelExt.java @@ -16,7 +16,7 @@ package android.net.dhcp; -import static android.net.shared.Inet4AddressUtils.inet4AddressToIntHTH; +import static com.android.net.module.util.Inet4AddressUtils.inet4AddressToIntHTH; import android.net.LinkAddress; import android.util.ArraySet; diff --git a/packages/Tethering/src/android/net/ip/IpServer.java b/packages/Tethering/src/android/net/ip/IpServer.java index e24fc2958933..8af1797a9dd7 100644 --- a/packages/Tethering/src/android/net/ip/IpServer.java +++ b/packages/Tethering/src/android/net/ip/IpServer.java @@ -19,13 +19,14 @@ package android.net.ip; import static android.net.RouteInfo.RTN_UNICAST; import static android.net.TetheringManager.TetheringRequest.checkStaticAddressConfiguration; import static android.net.dhcp.IDhcpServer.STATUS_SUCCESS; -import static android.net.shared.Inet4AddressUtils.intToInet4AddressHTH; import static android.net.util.NetworkConstants.RFC7421_PREFIX_LENGTH; import static android.net.util.NetworkConstants.asByte; import static android.net.util.PrefixUtils.asIpPrefix; import static android.net.util.TetheringMessageBase.BASE_IPSERVER; import static android.system.OsConstants.RT_SCOPE_UNIVERSE; +import static com.android.net.module.util.Inet4AddressUtils.intToInet4AddressHTH; + import android.net.INetd; import android.net.INetworkStackStatusCallback; import android.net.IpPrefix; @@ -616,7 +617,8 @@ public class IpServer extends StateMachine { final Boolean setIfaceUp; if (mInterfaceType == TetheringManager.TETHERING_WIFI || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P - || mInterfaceType == TetheringManager.TETHERING_ETHERNET) { + || mInterfaceType == TetheringManager.TETHERING_ETHERNET + || mInterfaceType == TetheringManager.TETHERING_WIGIG) { // The WiFi and Ethernet stack has ownership of the interface up/down state. // It is unclear whether the Bluetooth or USB stacks will manage their own // state. 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/src/com/android/networkstack/tethering/Tethering.java b/packages/Tethering/src/com/android/networkstack/tethering/Tethering.java index 8d720e7539f3..3627085cb6aa 100644 --- a/packages/Tethering/src/com/android/networkstack/tethering/Tethering.java +++ b/packages/Tethering/src/com/android/networkstack/tethering/Tethering.java @@ -40,6 +40,7 @@ import static android.net.TetheringManager.TETHERING_NCM; import static android.net.TetheringManager.TETHERING_USB; import static android.net.TetheringManager.TETHERING_WIFI; import static android.net.TetheringManager.TETHERING_WIFI_P2P; +import static android.net.TetheringManager.TETHERING_WIGIG; import static android.net.TetheringManager.TETHER_ERROR_INTERNAL_ERROR; import static android.net.TetheringManager.TETHER_ERROR_NO_ERROR; import static android.net.TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL; @@ -495,7 +496,8 @@ public class Tethering { if (up) { maybeTrackNewInterfaceLocked(iface); } else { - if (ifaceNameToType(iface) == TETHERING_BLUETOOTH) { + if (ifaceNameToType(iface) == TETHERING_BLUETOOTH + || ifaceNameToType(iface) == TETHERING_WIGIG) { stopTrackingInterfaceLocked(iface); } else { // Ignore usb0 down after enabling RNDIS. @@ -517,6 +519,8 @@ public class Tethering { if (cfg.isWifi(iface)) { return TETHERING_WIFI; + } else if (cfg.isWigig(iface)) { + return TETHERING_WIGIG; } else if (cfg.isWifiP2p(iface)) { return TETHERING_WIFI_P2P; } else if (cfg.isUsb(iface)) { diff --git a/packages/Tethering/src/com/android/networkstack/tethering/TetheringConfiguration.java b/packages/Tethering/src/com/android/networkstack/tethering/TetheringConfiguration.java index 18b2b7804fb0..e1771a561370 100644 --- a/packages/Tethering/src/com/android/networkstack/tethering/TetheringConfiguration.java +++ b/packages/Tethering/src/com/android/networkstack/tethering/TetheringConfiguration.java @@ -92,6 +92,7 @@ public class TetheringConfiguration { public final String[] tetherableUsbRegexs; public final String[] tetherableWifiRegexs; + public final String[] tetherableWigigRegexs; public final String[] tetherableWifiP2pRegexs; public final String[] tetherableBluetoothRegexs; public final String[] tetherableNcmRegexs; @@ -125,6 +126,7 @@ public class TetheringConfiguration { // us an interface name. Careful consideration needs to be given to // implications for Settings and for provisioning checks. tetherableWifiRegexs = getResourceStringArray(res, R.array.config_tether_wifi_regexs); + tetherableWigigRegexs = getResourceStringArray(res, R.array.config_tether_wigig_regexs); tetherableWifiP2pRegexs = getResourceStringArray( res, R.array.config_tether_wifi_p2p_regexs); tetherableBluetoothRegexs = getResourceStringArray( @@ -167,6 +169,11 @@ public class TetheringConfiguration { return matchesDownstreamRegexs(iface, tetherableWifiRegexs); } + /** Check whether input interface belong to wigig.*/ + public boolean isWigig(String iface) { + return matchesDownstreamRegexs(iface, tetherableWigigRegexs); + } + /** Check whether this interface is Wifi P2P interface. */ public boolean isWifiP2p(String iface) { return matchesDownstreamRegexs(iface, tetherableWifiP2pRegexs); diff --git a/packages/Tethering/src/com/android/networkstack/tethering/TetheringNotificationUpdater.java b/packages/Tethering/src/com/android/networkstack/tethering/TetheringNotificationUpdater.java index 593d04a06b93..a0198cc9c126 100644 --- a/packages/Tethering/src/com/android/networkstack/tethering/TetheringNotificationUpdater.java +++ b/packages/Tethering/src/com/android/networkstack/tethering/TetheringNotificationUpdater.java @@ -273,8 +273,9 @@ public class TetheringNotificationUpdater { mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */), 0 /* requestCode */, new Intent(Settings.ACTION_TETHER_SETTINGS) - .setPackage(getSettingsPackageName(mContext.getPackageManager())), - Intent.FLAG_ACTIVITY_NEW_TASK | PendingIntent.FLAG_IMMUTABLE, + .setPackage(getSettingsPackageName(mContext.getPackageManager())) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), + PendingIntent.FLAG_IMMUTABLE, null /* options */); showNotification(R.drawable.stat_sys_tether_general, title, message, @@ -317,8 +318,9 @@ public class TetheringNotificationUpdater { mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */), 0 /* requestCode */, new Intent(Settings.ACTION_TETHER_SETTINGS) - .setPackage(getSettingsPackageName(mContext.getPackageManager())), - Intent.FLAG_ACTIVITY_NEW_TASK | PendingIntent.FLAG_IMMUTABLE, + .setPackage(getSettingsPackageName(mContext.getPackageManager())) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), + PendingIntent.FLAG_IMMUTABLE, null /* options */); showNotification(R.drawable.stat_sys_tether_general, title, message, diff --git a/packages/Tethering/tests/unit/jarjar-rules.txt b/packages/Tethering/tests/unit/jarjar-rules.txt index 1ea56cdf1a3d..ec2d2b02004e 100644 --- a/packages/Tethering/tests/unit/jarjar-rules.txt +++ b/packages/Tethering/tests/unit/jarjar-rules.txt @@ -8,4 +8,4 @@ rule com.android.internal.util.State* com.android.networkstack.tethering.util.St rule com.android.internal.util.StateMachine* com.android.networkstack.tethering.util.StateMachine@1 rule com.android.internal.util.TrafficStatsConstants* com.android.networkstack.tethering.util.TrafficStatsConstants@1 -rule android.net.LocalLog* com.android.networkstack.tethering.LocalLog@1 +rule android.util.LocalLog* com.android.networkstack.tethering.util.LocalLog@1 diff --git a/packages/Tethering/tests/unit/src/android/net/ip/IpServerTest.java b/packages/Tethering/tests/unit/src/android/net/ip/IpServerTest.java index 05cf58ab84ff..30a9d2252ea6 100644 --- a/packages/Tethering/tests/unit/src/android/net/ip/IpServerTest.java +++ b/packages/Tethering/tests/unit/src/android/net/ip/IpServerTest.java @@ -36,7 +36,8 @@ import static android.net.netlink.NetlinkConstants.RTM_NEWNEIGH; import static android.net.netlink.StructNdMsg.NUD_FAILED; import static android.net.netlink.StructNdMsg.NUD_REACHABLE; import static android.net.netlink.StructNdMsg.NUD_STALE; -import static android.net.shared.Inet4AddressUtils.intToInet4AddressHTH; + +import static com.android.net.module.util.Inet4AddressUtils.intToInet4AddressHTH; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; 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/packages/Tethering/tests/unit/src/com/android/networkstack/tethering/TetheringTest.java b/packages/Tethering/tests/unit/src/com/android/networkstack/tethering/TetheringTest.java index d37aad26d1fd..f1da1c722540 100644 --- a/packages/Tethering/tests/unit/src/com/android/networkstack/tethering/TetheringTest.java +++ b/packages/Tethering/tests/unit/src/com/android/networkstack/tethering/TetheringTest.java @@ -40,7 +40,6 @@ import static android.net.TetheringManager.TETHER_HARDWARE_OFFLOAD_FAILED; import static android.net.TetheringManager.TETHER_HARDWARE_OFFLOAD_STARTED; import static android.net.TetheringManager.TETHER_HARDWARE_OFFLOAD_STOPPED; import static android.net.dhcp.IDhcpServer.STATUS_SUCCESS; -import static android.net.shared.Inet4AddressUtils.intToInet4AddressHTH; import static android.net.wifi.WifiManager.EXTRA_WIFI_AP_INTERFACE_NAME; import static android.net.wifi.WifiManager.EXTRA_WIFI_AP_MODE; import static android.net.wifi.WifiManager.EXTRA_WIFI_AP_STATE; @@ -49,6 +48,7 @@ import static android.net.wifi.WifiManager.IFACE_IP_MODE_TETHERED; import static android.net.wifi.WifiManager.WIFI_AP_STATE_ENABLED; import static android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID; +import static com.android.net.module.util.Inet4AddressUtils.intToInet4AddressHTH; import static com.android.networkstack.tethering.TetheringNotificationUpdater.DOWNSTREAM_NONE; import static com.android.networkstack.tethering.UpstreamNetworkMonitor.EVENT_ON_CAPABILITIES; diff --git a/services/Android.bp b/services/Android.bp index 57d9a3850e86..581edceea1cb 100644 --- a/services/Android.bp +++ b/services/Android.bp @@ -111,7 +111,6 @@ droidstubs { " --hide InternalClasses" + // com.android.* classes are okay in this interface // TODO: remove the --hide options below " --hide-package com.google.android.startop.iorap" + - " --hide ReferencesHidden" + " --hide DeprecationMismatch" + " --hide HiddenTypedefConstant", visibility: ["//visibility:private"], diff --git a/services/backup/OWNERS b/services/backup/OWNERS index 9c21e8fe5e45..ba61d1c0849b 100644 --- a/services/backup/OWNERS +++ b/services/backup/OWNERS @@ -1,9 +1,7 @@ +# Bug component: 656484 + alsutton@google.com -anniemeng@google.com -brufino@google.com bryanmawhinney@google.com -ctate@google.com -jorlow@google.com nathch@google.com rthakohov@google.com - +tobiast@google.com diff --git a/services/core/java/com/android/server/ConnectivityService.java b/services/core/java/com/android/server/ConnectivityService.java index 80efd52576d9..e1bcb0c21ce5 100644 --- a/services/core/java/com/android/server/ConnectivityService.java +++ b/services/core/java/com/android/server/ConnectivityService.java @@ -67,6 +67,7 @@ import android.app.BroadcastOptions; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; +import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; @@ -3069,7 +3070,11 @@ public class ConnectivityService extends IConnectivityManager.Stub // Only the system server can register notifications with package "android" final long token = Binder.clearCallingIdentity(); try { - pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0); + pendingIntent = PendingIntent.getBroadcast( + mContext, + 0 /* requestCode */, + intent, + PendingIntent.FLAG_IMMUTABLE); } finally { Binder.restoreCallingIdentity(token); } @@ -3925,6 +3930,15 @@ public class ConnectivityService extends IConnectivityManager.Stub pw.decreaseIndent(); } + // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to + // unify the method. + private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) { + final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS); + final ComponentName settingsComponent = settingsIntent.resolveActivity(pm); + return settingsComponent != null + ? settingsComponent.getPackageName() : "com.android.settings"; + } + private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) { final String action; final boolean highPriority; @@ -3959,12 +3973,20 @@ public class ConnectivityService extends IConnectivityManager.Stub if (type != NotificationType.PRIVATE_DNS_BROKEN) { intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - intent.setClassName("com.android.settings", - "com.android.settings.wifi.WifiNoInternetDialog"); + // Some OEMs have their own Settings package. Thus, need to get the current using + // Settings package name instead of just use default name "com.android.settings". + final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager()); + intent.setClassName(settingsPkgName, + settingsPkgName + ".wifi.WifiNoInternetDialog"); } PendingIntent pendingIntent = PendingIntent.getActivityAsUser( - mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT); + mContext, + 0 /* requestCode */, + intent, + PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE, + null /* options */, + UserHandle.CURRENT); mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, highPriority); } @@ -4293,9 +4315,11 @@ public class ConnectivityService extends IConnectivityManager.Stub enforceInternetPermission(); final int uid = Binder.getCallingUid(); final int connectivityInfo = encodeBool(hasConnectivity); - mHandler.sendMessage( - mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network)); + // Handle ConnectivityDiagnostics event before attempting to revalidate the network. This + // forces an ordering of ConnectivityDiagnostics events in the case where hasConnectivity + // does not match the known connectivity of the network - this causes NetworkMonitor to + // revalidate the network and generate a ConnectivityDiagnostics ConnectivityReport event. final NetworkAgentInfo nai; if (network == null) { nai = getDefaultNetwork(); @@ -4308,6 +4332,9 @@ public class ConnectivityService extends IConnectivityManager.Stub ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED, connectivityInfo, 0, nai)); } + + mHandler.sendMessage( + mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network)); } private void handleReportNetworkConnectivity( @@ -5114,14 +5141,6 @@ public class ConnectivityService extends IConnectivityManager.Stub } } - private void onPackageAdded(String packageName, int uid) { - if (TextUtils.isEmpty(packageName) || uid < 0) { - Slog.wtf(TAG, "Invalid package in onPackageAdded: " + packageName + " | " + uid); - return; - } - mPermissionMonitor.onPackageAdded(packageName, uid); - } - private void onPackageReplaced(String packageName, int uid) { if (TextUtils.isEmpty(packageName) || uid < 0) { Slog.wtf(TAG, "Invalid package in onPackageReplaced: " + packageName + " | " + uid); @@ -5147,7 +5166,6 @@ public class ConnectivityService extends IConnectivityManager.Stub Slog.wtf(TAG, "Invalid package in onPackageRemoved: " + packageName + " | " + uid); return; } - mPermissionMonitor.onPackageRemoved(uid); final int userId = UserHandle.getUserId(uid); synchronized (mVpns) { @@ -5197,8 +5215,6 @@ public class ConnectivityService extends IConnectivityManager.Stub onUserRemoved(userId); } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) { onUserUnlocked(userId); - } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { - onPackageAdded(packageName, uid); } else if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) { onPackageReplaced(packageName, uid); } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) { diff --git a/services/core/java/com/android/server/RuntimeService.java b/services/core/java/com/android/server/RuntimeService.java index bb39ccc52af2..f4249f844873 100644 --- a/services/core/java/com/android/server/RuntimeService.java +++ b/services/core/java/com/android/server/RuntimeService.java @@ -23,10 +23,9 @@ import android.service.runtime.RuntimeServiceInfoProto; import android.util.Slog; import android.util.proto.ProtoOutputStream; -import libcore.timezone.TimeZoneDataFiles; -import libcore.util.CoreLibraryDebug; -import libcore.util.DebugInfo; - +import com.android.i18n.timezone.DebugInfo; +import com.android.i18n.timezone.I18nModuleDebug; +import com.android.i18n.timezone.TimeZoneDataFiles; import com.android.internal.util.DumpUtils; import com.android.timezone.distro.DistroException; import com.android.timezone.distro.DistroVersion; @@ -61,14 +60,14 @@ public class RuntimeService extends Binder { boolean protoFormat = hasOption(args, "--proto"); ProtoOutputStream proto = null; - DebugInfo coreLibraryDebugInfo = CoreLibraryDebug.getDebugInfo(); - addTimeZoneApkDebugInfo(coreLibraryDebugInfo); + DebugInfo i18nLibraryDebugInfo = I18nModuleDebug.getDebugInfo(); + addTimeZoneApkDebugInfo(i18nLibraryDebugInfo); if (protoFormat) { proto = new ProtoOutputStream(fd); - reportTimeZoneInfoProto(coreLibraryDebugInfo, proto); + reportTimeZoneInfoProto(i18nLibraryDebugInfo, proto); } else { - reportTimeZoneInfo(coreLibraryDebugInfo, pw); + reportTimeZoneInfo(i18nLibraryDebugInfo, pw); } if (protoFormat) { 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/java/com/android/server/connectivity/PermissionMonitor.java b/services/core/java/com/android/server/connectivity/PermissionMonitor.java index f0b7150dd84f..c5aa8d5361ec 100644 --- a/services/core/java/com/android/server/connectivity/PermissionMonitor.java +++ b/services/core/java/com/android/server/connectivity/PermissionMonitor.java @@ -72,7 +72,7 @@ import java.util.Set; * * @hide */ -public class PermissionMonitor { +public class PermissionMonitor implements PackageManagerInternal.PackageListObserver { private static final String TAG = "PermissionMonitor"; private static final boolean DBG = true; protected static final Boolean SYSTEM = Boolean.TRUE; @@ -102,44 +102,6 @@ public class PermissionMonitor { @GuardedBy("this") private final Set<Integer> mAllApps = new HashSet<>(); - private class PackageListObserver implements PackageManagerInternal.PackageListObserver { - - private int getPermissionForUid(int uid) { - int permission = 0; - // Check all the packages for this UID. The UID has the permission if any of the - // packages in it has the permission. - String[] packages = mPackageManager.getPackagesForUid(uid); - if (packages != null && packages.length > 0) { - for (String name : packages) { - final PackageInfo app = getPackageInfo(name); - if (app != null && app.requestedPermissions != null) { - permission |= getNetdPermissionMask(app.requestedPermissions, - app.requestedPermissionsFlags); - } - } - } else { - // The last package of this uid is removed from device. Clean the package up. - permission = INetd.PERMISSION_UNINSTALLED; - } - return permission; - } - - @Override - public void onPackageAdded(String packageName, int uid) { - sendPackagePermissionsForUid(uid, getPermissionForUid(uid)); - } - - @Override - public void onPackageChanged(@NonNull String packageName, int uid) { - sendPackagePermissionsForUid(uid, getPermissionForUid(uid)); - } - - @Override - public void onPackageRemoved(String packageName, int uid) { - sendPackagePermissionsForUid(uid, getPermissionForUid(uid)); - } - } - public PermissionMonitor(Context context, INetd netd) { mPackageManager = context.getPackageManager(); mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE); @@ -153,7 +115,7 @@ public class PermissionMonitor { PackageManagerInternal pmi = LocalServices.getService(PackageManagerInternal.class); if (pmi != null) { - pmi.getPackageList(new PackageListObserver()); + pmi.getPackageList(this); } else { loge("failed to get the PackageManagerInternal service"); } @@ -363,15 +325,38 @@ public class PermissionMonitor { return currentPermission; } + private int getPermissionForUid(final int uid) { + int permission = INetd.PERMISSION_NONE; + // Check all the packages for this UID. The UID has the permission if any of the + // packages in it has the permission. + final String[] packages = mPackageManager.getPackagesForUid(uid); + if (packages != null && packages.length > 0) { + for (String name : packages) { + final PackageInfo app = getPackageInfo(name); + if (app != null && app.requestedPermissions != null) { + permission |= getNetdPermissionMask(app.requestedPermissions, + app.requestedPermissionsFlags); + } + } + } else { + // The last package of this uid is removed from device. Clean the package up. + permission = INetd.PERMISSION_UNINSTALLED; + } + return permission; + } + /** - * Called when a package is added. See {link #ACTION_PACKAGE_ADDED}. + * Called when a package is added. * * @param packageName The name of the new package. * @param uid The uid of the new package. * * @hide */ - public synchronized void onPackageAdded(String packageName, int uid) { + @Override + public synchronized void onPackageAdded(@NonNull final String packageName, final int uid) { + sendPackagePermissionsForUid(uid, getPermissionForUid(uid)); + // If multiple packages share a UID (cf: android:sharedUserId) and ask for different // permissions, don't downgrade (i.e., if it's already SYSTEM, leave it as is). final Boolean permission = highestPermissionForUid(mApps.get(uid), packageName); @@ -398,13 +383,17 @@ public class PermissionMonitor { } /** - * Called when a package is removed. See {link #ACTION_PACKAGE_REMOVED}. + * Called when a package is removed. * + * @param packageName The name of the removed package or null. * @param uid containing the integer uid previously assigned to the package. * * @hide */ - public synchronized void onPackageRemoved(int uid) { + @Override + public synchronized void onPackageRemoved(@NonNull final String packageName, final int uid) { + sendPackagePermissionsForUid(uid, getPermissionForUid(uid)); + // If the newly-removed package falls within some VPN's uid range, update Netd with it. // This needs to happen before the mApps update below, since removeBypassingUids() depends // on mApps to check if the package can bypass VPN. @@ -449,6 +438,19 @@ public class PermissionMonitor { } } + /** + * Called when a package is changed. + * + * @param packageName The name of the changed package. + * @param uid The uid of the changed package. + * + * @hide + */ + @Override + public synchronized void onPackageChanged(@NonNull final String packageName, final int uid) { + sendPackagePermissionsForUid(uid, getPermissionForUid(uid)); + } + private static int getNetdPermissionMask(String[] requestedPermissions, int[] requestedPermissionsFlags) { int permissions = 0; diff --git a/services/core/java/com/android/server/pm/OWNERS b/services/core/java/com/android/server/pm/OWNERS index 6fdde7a196cc..fe6aad70c31e 100644 --- a/services/core/java/com/android/server/pm/OWNERS +++ b/services/core/java/com/android/server/pm/OWNERS @@ -10,8 +10,8 @@ toddke@android.com toddke@google.com # apex support -per-file ApexManager.java = dariofreni@google.com -per-file StagingManager.java = dariofreni@google.com +per-file ApexManager.java = dariofreni@google.com, ioffe@google.com, olilan@google.com +per-file StagingManager.java = dariofreni@google.com, ioffe@google.com, olilan@google.com # dex per-file AbstractStatsBase.java = agampe@google.com, calin@google.com, ngeoffray@google.com diff --git a/services/core/java/com/android/server/timezone/RulesManagerService.java b/services/core/java/com/android/server/timezone/RulesManagerService.java index bbd1ae60cb62..fd5c6e91a885 100644 --- a/services/core/java/com/android/server/timezone/RulesManagerService.java +++ b/services/core/java/com/android/server/timezone/RulesManagerService.java @@ -37,6 +37,10 @@ import android.os.ParcelFileDescriptor; import android.os.RemoteException; import android.util.Slog; +import com.android.i18n.timezone.TimeZoneDataFiles; +import com.android.i18n.timezone.TimeZoneFinder; +import com.android.i18n.timezone.TzDataSetVersion; +import com.android.i18n.timezone.ZoneInfoDb; import com.android.internal.annotations.VisibleForTesting; import com.android.server.EventLogTags; import com.android.server.SystemService; @@ -46,10 +50,6 @@ import com.android.timezone.distro.StagedDistroOperation; import com.android.timezone.distro.TimeZoneDistro; import com.android.timezone.distro.installer.TimeZoneDistroInstaller; -import libcore.timezone.TimeZoneDataFiles; -import libcore.timezone.TimeZoneFinder; -import libcore.timezone.TzDataSetVersion; -import libcore.timezone.ZoneInfoDb; import java.io.File; import java.io.FileDescriptor; 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/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java index 23b1512081da..c48ee11237e9 100644 --- a/services/java/com/android/server/SystemServer.java +++ b/services/java/com/android/server/SystemServer.java @@ -74,6 +74,7 @@ import android.view.WindowManager; import android.view.contentcapture.ContentCaptureManager; import android.view.inputmethod.InputMethodSystemProperty; +import com.android.i18n.timezone.ZoneInfoDb; import com.android.internal.R; import com.android.internal.logging.MetricsLogger; import com.android.internal.notification.SystemNotificationChannels; @@ -165,8 +166,6 @@ import com.android.server.wm.ActivityTaskManagerService; import com.android.server.wm.WindowManagerGlobalLock; import com.android.server.wm.WindowManagerService; -import libcore.timezone.ZoneInfoDb; - import dalvik.system.VMRuntime; import java.io.File; diff --git a/services/net/java/android/net/ip/IpClientCallbacks.java b/services/net/java/android/net/ip/IpClientCallbacks.java index b172c4be7b0d..b17fcaa132a1 100644 --- a/services/net/java/android/net/ip/IpClientCallbacks.java +++ b/services/net/java/android/net/ip/IpClientCallbacks.java @@ -68,12 +68,13 @@ public class IpClientCallbacks { */ public void onNewDhcpResults(DhcpResultsParcelable dhcpResults) { // In general callbacks would not use a parcelable directly (DhcpResultsParcelable), and - // would use a wrapper instead. But there are already two classes in the tree for DHCP - // information: DhcpInfo and DhcpResults, and each of them do not expose an appropriate API - // (they are bags of mutable fields and can't be changed because they are public API and - // @UnsupportedAppUsage). Adding a third class would cost more than the gain considering - // that the only client of this callback is WiFi, which will end up converting the results - // to DhcpInfo anyway. + // would use a wrapper instead, because of the lack of safety of stable parcelables. But + // there are already two classes in the tree for DHCP information: DhcpInfo and DhcpResults, + // and neither of them exposes an appropriate API (they are bags of mutable fields and can't + // be changed because they are public API and @UnsupportedAppUsage, being no better than the + // stable parcelable). Adding a third class would cost more than the gain considering that + // the only client of this callback is WiFi, which will end up converting the results to + // DhcpInfo anyway. } /** diff --git a/services/tests/servicestests/src/com/android/server/timezone/RulesManagerServiceTest.java b/services/tests/servicestests/src/com/android/server/timezone/RulesManagerServiceTest.java index 5c6fe0fc4cad..2c4c4d0ee91f 100644 --- a/services/tests/servicestests/src/com/android/server/timezone/RulesManagerServiceTest.java +++ b/services/tests/servicestests/src/com/android/server/timezone/RulesManagerServiceTest.java @@ -43,13 +43,13 @@ import android.app.timezone.RulesManager; import android.app.timezone.RulesState; import android.os.ParcelFileDescriptor; +import com.android.i18n.timezone.TzDataSetVersion; import com.android.timezone.distro.DistroVersion; import com.android.timezone.distro.StagedDistroOperation; import com.android.timezone.distro.TimeZoneDistro; import com.android.timezone.distro.installer.TimeZoneDistroInstaller; import libcore.io.IoUtils; -import libcore.timezone.TzDataSetVersion; import org.junit.Before; import org.junit.Test; diff --git a/telecomm/java/com/android/internal/telecom/ITelecomService.aidl b/telecomm/java/com/android/internal/telecom/ITelecomService.aidl index 9a47ae15e64a..0965249cdad3 100644 --- a/telecomm/java/com/android/internal/telecom/ITelecomService.aidl +++ b/telecomm/java/com/android/internal/telecom/ITelecomService.aidl @@ -273,6 +273,11 @@ interface ITelecomService { boolean setDefaultDialer(in String packageName); /** + * Stop suppressing blocked numbers after a call to emergency services. Shell only. + */ + void stopBlockSuppression(); + + /** * @see TelecomServiceImpl#createManageBlockedNumbersIntent **/ Intent createManageBlockedNumbersIntent(); diff --git a/telephony/common/com/android/internal/telephony/SmsApplication.java b/telephony/common/com/android/internal/telephony/SmsApplication.java index 1a049e6c517e..d69282579b77 100644 --- a/telephony/common/com/android/internal/telephony/SmsApplication.java +++ b/telephony/common/com/android/internal/telephony/SmsApplication.java @@ -542,13 +542,16 @@ public final class SmsApplication { // Assign permission to special system apps assignExclusiveSmsPermissionsToSystemApp(context, packageManager, appOps, - PHONE_PACKAGE_NAME); + PHONE_PACKAGE_NAME, true); assignExclusiveSmsPermissionsToSystemApp(context, packageManager, appOps, - BLUETOOTH_PACKAGE_NAME); + BLUETOOTH_PACKAGE_NAME, true); assignExclusiveSmsPermissionsToSystemApp(context, packageManager, appOps, - MMS_SERVICE_PACKAGE_NAME); + MMS_SERVICE_PACKAGE_NAME, true); assignExclusiveSmsPermissionsToSystemApp(context, packageManager, appOps, - TELEPHONY_PROVIDER_PACKAGE_NAME); + TELEPHONY_PROVIDER_PACKAGE_NAME, true); + // CellbroadcastReceiver is a mainline module thus skip signature match. + assignExclusiveSmsPermissionsToSystemApp(context, packageManager, appOps, + CellBroadcastUtils.getDefaultCellBroadcastReceiverPackageName(context), false); // Give AppOps permission to UID 1001 which contains multiple // apps, all of them should be able to write to telephony provider. @@ -738,17 +741,23 @@ public final class SmsApplication { * @param packageManager The package manager instance * @param appOps The AppOps manager instance * @param packageName The package name of the system app + * @param sigatureMatch whether to check signature match */ private static void assignExclusiveSmsPermissionsToSystemApp(Context context, - PackageManager packageManager, AppOpsManager appOps, String packageName) { + PackageManager packageManager, AppOpsManager appOps, String packageName, + boolean sigatureMatch) { // First check package signature matches the caller's package signature. // Since this class is only used internally by the system, this check makes sure // the package signature matches system signature. - final int result = packageManager.checkSignatures(context.getPackageName(), packageName); - if (result != PackageManager.SIGNATURE_MATCH) { - Log.e(LOG_TAG, packageName + " does not have system signature"); - return; + if (sigatureMatch) { + final int result = packageManager.checkSignatures(context.getPackageName(), + packageName); + if (result != PackageManager.SIGNATURE_MATCH) { + Log.e(LOG_TAG, packageName + " does not have system signature"); + return; + } } + try { PackageInfo info = packageManager.getPackageInfo(packageName, 0); int mode = appOps.unsafeCheckOp(AppOpsManager.OPSTR_WRITE_SMS, info.applicationInfo.uid, diff --git a/telephony/java/android/telephony/CarrierConfigManager.java b/telephony/java/android/telephony/CarrierConfigManager.java index c9ee2a1279bc..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. * @@ -1634,6 +1651,12 @@ public class CarrierConfigManager { "show_precise_failed_cause_bool"; /** + * Boolean to decide whether NR is enabled. + * @hide + */ + public static final String KEY_NR_ENABLED_BOOL = "nr_enabled_bool"; + + /** * Boolean to decide whether LTE is enabled. */ public static final String KEY_LTE_ENABLED_BOOL = "lte_enabled_bool"; @@ -3775,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); @@ -3954,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); @@ -4117,6 +4142,7 @@ public class CarrierConfigManager { sDefaults.putString(KEY_OPERATOR_NAME_FILTER_PATTERN_STRING, ""); sDefaults.putString(KEY_SHOW_CARRIER_DATA_ICON_PATTERN_STRING, ""); sDefaults.putBoolean(KEY_HIDE_LTE_PLUS_DATA_ICON_BOOL, true); + sDefaults.putBoolean(KEY_NR_ENABLED_BOOL, true); sDefaults.putBoolean(KEY_LTE_ENABLED_BOOL, true); sDefaults.putBoolean(KEY_SUPPORT_TDSCDMA_BOOL, false); sDefaults.putStringArray(KEY_SUPPORT_TDSCDMA_ROAMING_NETWORKS_STRING_ARRAY, null); @@ -4184,8 +4210,8 @@ public class CarrierConfigManager { "GPRS:24,24", "EDGE:70,18", "UMTS:115,115", "CDMA-IS95A:14,14", "CDMA-IS95B:14,14", "1xRTT:30,30", "EvDo-rev.0:750,48", "EvDo-rev.A:950,550", "HSDPA:4300,620", "HSUPA:4300,1800", "HSPA:4300,1800", "EvDo-rev.B:1500,550", "eHRPD:750,48", - "HSPAP:13000,3400", "TD-SCDMA:115,115", "LTE:30000,15000", "NR_NSA:47000,15000", - "NR_NSA_MMWAVE:145000,15000", "NR_SA:145000,15000"}); + "HSPAP:13000,3400", "TD-SCDMA:115,115", "LTE:30000,15000", "NR_NSA:47000,18000", + "NR_NSA_MMWAVE:145000,60000", "NR_SA:145000,60000"}); sDefaults.putBoolean(KEY_BANDWIDTH_NR_NSA_USE_LTE_VALUE_FOR_UPSTREAM_BOOL, false); sDefaults.putString(KEY_WCDMA_DEFAULT_SIGNAL_STRENGTH_MEASUREMENT_STRING, "rssi"); sDefaults.putBoolean(KEY_CONFIG_SHOW_ORIG_DIAL_STRING_FOR_CDMA_BOOL, false); diff --git a/telephony/java/android/telephony/TelephonyManager.java b/telephony/java/android/telephony/TelephonyManager.java index 6b498b5f8697..68977068aa74 100644 --- a/telephony/java/android/telephony/TelephonyManager.java +++ b/telephony/java/android/telephony/TelephonyManager.java @@ -12608,7 +12608,6 @@ public class TelephonyManager { @Nullable String mvnoMatchData) { try { if (!mccmnc.equals(getSimOperator())) { - Log.d(TAG, "The mccmnc does not match"); return false; } ITelephony service = getITelephony(); diff --git a/telephony/java/android/telephony/TelephonyScanManager.java b/telephony/java/android/telephony/TelephonyScanManager.java index 359d08d294c3..3f8fd9d68a4f 100644 --- a/telephony/java/android/telephony/TelephonyScanManager.java +++ b/telephony/java/android/telephony/TelephonyScanManager.java @@ -31,6 +31,7 @@ import android.os.RemoteException; import android.os.ServiceManager; import android.util.SparseArray; +import com.android.internal.annotations.GuardedBy; import com.android.internal.telephony.ITelephony; import com.android.telephony.Rlog; @@ -56,6 +57,8 @@ public final class TelephonyScanManager { public static final int CALLBACK_SCAN_COMPLETE = 3; /** @hide */ public static final int CALLBACK_RESTRICTED_SCAN_RESULTS = 4; + /** @hide */ + public static final int CALLBACK_TELEPHONY_DIED = 5; /** @hide */ public static final int INVALID_SCAN_ID = -1; @@ -104,17 +107,44 @@ public final class TelephonyScanManager { } private final Looper mLooper; + private final Handler mHandler; private final Messenger mMessenger; private final SparseArray<NetworkScanInfo> mScanInfo = new SparseArray<NetworkScanInfo>(); + private final Binder.DeathRecipient mDeathRecipient; public TelephonyScanManager() { HandlerThread thread = new HandlerThread(TAG); thread.start(); mLooper = thread.getLooper(); - mMessenger = new Messenger(new Handler(mLooper) { + mHandler = new Handler(mLooper) { @Override public void handleMessage(Message message) { checkNotNull(message, "message cannot be null"); + if (message.what == CALLBACK_TELEPHONY_DIED) { + // If there are no objects in mScanInfo then binder death will simply return. + synchronized (mScanInfo) { + for (int i = 0; i < mScanInfo.size(); i++) { + NetworkScanInfo nsi = mScanInfo.valueAt(i); + // At this point we go into panic mode and ignore errors that would + // normally stop the show in order to try and clean up as gracefully + // as possible. + if (nsi == null) continue; // shouldn't be possible + Executor e = nsi.mExecutor; + NetworkScanCallback cb = nsi.mCallback; + if (e == null || cb == null) continue; + try { + e.execute( + () -> cb.onError(NetworkScan.ERROR_MODEM_UNAVAILABLE)); + } catch (java.util.concurrent.RejectedExecutionException ignore) { + // ignore so that we can continue + } + } + + mScanInfo.clear(); + } + return; + } + NetworkScanInfo nsi; synchronized (mScanInfo) { nsi = mScanInfo.get(message.arg2); @@ -159,6 +189,9 @@ public final class TelephonyScanManager { Rlog.d(TAG, "onError: " + errorCode); callback.onError(errorCode); }); + synchronized (mScanInfo) { + mScanInfo.remove(message.arg2); + } } catch (Exception e) { Rlog.e(TAG, "Exception in networkscan callback onError", e); } @@ -169,7 +202,9 @@ public final class TelephonyScanManager { Rlog.d(TAG, "onComplete"); callback.onComplete(); }); - mScanInfo.remove(message.arg2); + synchronized (mScanInfo) { + mScanInfo.remove(message.arg2); + } } catch (Exception e) { Rlog.e(TAG, "Exception in networkscan callback onComplete", e); } @@ -179,7 +214,14 @@ public final class TelephonyScanManager { break; } } - }); + }; + mMessenger = new Messenger(mHandler); + mDeathRecipient = new Binder.DeathRecipient() { + @Override + public void binderDied() { + mHandler.obtainMessage(CALLBACK_TELEPHONY_DIED).sendToTarget(); + } + }; } /** @@ -190,7 +232,7 @@ public final class TelephonyScanManager { * * <p> * Requires Permission: - * {@link android.Manifest.permission#ACCESS_COARSE_LOCATION} and + * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} and * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} * Or the calling app has carrier privileges. @see #hasCarrierPrivileges * @@ -203,19 +245,26 @@ public final class TelephonyScanManager { NetworkScanRequest request, Executor executor, NetworkScanCallback callback, String callingPackage, String callingFeatureId) { try { - ITelephony telephony = getITelephony(); - if (telephony != null) { - synchronized (mScanInfo) { - int scanId = telephony.requestNetworkScan( - subId, request, mMessenger, new Binder(), callingPackage, - callingFeatureId); - if (scanId == INVALID_SCAN_ID) { - Rlog.e(TAG, "Failed to initiate network scan"); - return null; - } - saveScanInfo(scanId, request, executor, callback); - return new NetworkScan(scanId, subId); - } + final ITelephony telephony = getITelephony(); + if (telephony == null) return null; + + int scanId = telephony.requestNetworkScan( + subId, request, mMessenger, new Binder(), callingPackage, + callingFeatureId); + if (scanId == INVALID_SCAN_ID) { + Rlog.e(TAG, "Failed to initiate network scan"); + return null; + } + synchronized (mScanInfo) { + // We link to death whenever a scan is started to ensure that we are linked + // at the point that phone process death might matter. + // We never unlink because: + // - Duplicate links to death with the same callback do not result in + // extraneous callbacks (the tracking de-dupes). + // - Receiving binderDeath() when no scans are active is a no-op. + telephony.asBinder().linkToDeath(mDeathRecipient, 0); + saveScanInfo(scanId, request, executor, callback); + return new NetworkScan(scanId, subId); } } catch (RemoteException ex) { Rlog.e(TAG, "requestNetworkScan RemoteException", ex); @@ -225,6 +274,7 @@ public final class TelephonyScanManager { return null; } + @GuardedBy("mScanInfo") private void saveScanInfo( int id, NetworkScanRequest request, Executor executor, NetworkScanCallback callback) { mScanInfo.put(id, new NetworkScanInfo(request, executor, callback)); 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/telephony/java/android/telephony/ims/stub/ImsRegistrationImplBase.java b/telephony/java/android/telephony/ims/stub/ImsRegistrationImplBase.java index 7069e0ab9b1e..2cdf70e6cf4c 100644 --- a/telephony/java/android/telephony/ims/stub/ImsRegistrationImplBase.java +++ b/telephony/java/android/telephony/ims/stub/ImsRegistrationImplBase.java @@ -29,6 +29,7 @@ import android.util.Log; import com.android.internal.annotations.VisibleForTesting; import com.android.internal.telephony.util.RemoteCallbackListExt; +import com.android.internal.util.ArrayUtils; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -105,6 +106,11 @@ public class ImsRegistrationImplBase { // Locked on mLock, create unspecified disconnect cause. private ImsReasonInfo mLastDisconnectCause = new ImsReasonInfo(); + // We hold onto the uris each time they change so that we can send it to a callback when its + // first added. + private Uri[] mUris = new Uri[0]; + private boolean mUrisSet = false; + /** * @hide */ @@ -208,19 +214,27 @@ public class ImsRegistrationImplBase { } /** - * The this device's subscriber associated {@link Uri}s have changed, which are used to filter - * out this device's {@link Uri}s during conference calling. - * @param uris + * Invoked when the {@link Uri}s associated to this device's subscriber have changed. + * These {@link Uri}s' are filtered out during conference calls. + * + * The {@link Uri}s are not guaranteed to be different between subsequent calls. + * @param uris changed uris */ public final void onSubscriberAssociatedUriChanged(Uri[] uris) { - mCallbacks.broadcastAction((c) -> { - try { - c.onSubscriberAssociatedUriChanged(uris); - } catch (RemoteException e) { - Log.w(LOG_TAG, e + " " + "onSubscriberAssociatedUriChanged() - Skipping " + - "callback."); - } - }); + synchronized (mLock) { + mUris = ArrayUtils.cloneOrNull(uris); + mUrisSet = true; + } + mCallbacks.broadcastAction((c) -> onSubscriberAssociatedUriChanged(c, uris)); + } + + private void onSubscriberAssociatedUriChanged(IImsRegistrationCallback callback, Uri[] uris) { + try { + callback.onSubscriberAssociatedUriChanged(uris); + } catch (RemoteException e) { + Log.w(LOG_TAG, e + " " + "onSubscriberAssociatedUriChanged() - Skipping " + + "callback."); + } } private void updateToState(@ImsRegistrationTech int connType, int newState) { @@ -233,6 +247,10 @@ public class ImsRegistrationImplBase { private void updateToDisconnectedState(ImsReasonInfo info) { synchronized (mLock) { + //We don't want to send this info over if we are disconnected + mUrisSet = false; + mUris = null; + updateToState(REGISTRATION_TECH_NONE, RegistrationManager.REGISTRATION_STATE_NOT_REGISTERED); if (info != null) { @@ -260,12 +278,17 @@ public class ImsRegistrationImplBase { * @param c the newly registered callback that will be updated with the current registration * state. */ - private void updateNewCallbackWithState(IImsRegistrationCallback c) throws RemoteException { + private void updateNewCallbackWithState(IImsRegistrationCallback c) + throws RemoteException { int state; ImsReasonInfo disconnectInfo; + boolean urisSet; + Uri[] uris; synchronized (mLock) { state = mRegistrationState; disconnectInfo = mLastDisconnectCause; + urisSet = mUrisSet; + uris = mUris; } switch (state) { case RegistrationManager.REGISTRATION_STATE_NOT_REGISTERED: { @@ -285,5 +308,8 @@ public class ImsRegistrationImplBase { break; } } + if (urisSet) { + onSubscriberAssociatedUriChanged(c, uris); + } } } diff --git a/test-base/Android.bp b/test-base/Android.bp index 69c296e7ee9c..c7c9fc739189 100644 --- a/test-base/Android.bp +++ b/test-base/Android.bp @@ -38,6 +38,7 @@ java_sdk_library { ], compile_dex: true, + default_to_stubs: true, } // Build the android.test.base_static library diff --git a/test-mock/Android.bp b/test-mock/Android.bp index 248c117d2e03..7d0f92fac4c7 100644 --- a/test-mock/Android.bp +++ b/test-mock/Android.bp @@ -37,6 +37,7 @@ java_sdk_library { "android.test.mock", ], compile_dex: true, + default_to_stubs: true, } // Make the current.txt available for use by the cts/tests/signature tests. diff --git a/test-mock/src/android/test/mock/MockContentProvider.java b/test-mock/src/android/test/mock/MockContentProvider.java index e9a5ff70a7cc..3206adc31b98 100644 --- a/test-mock/src/android/test/mock/MockContentProvider.java +++ b/test-mock/src/android/test/mock/MockContentProvider.java @@ -29,6 +29,7 @@ import android.content.pm.ProviderInfo; import android.content.res.AssetFileDescriptor; import android.database.Cursor; import android.net.Uri; +import android.os.Binder; import android.os.Bundle; import android.os.IBinder; import android.os.ICancellationSignal; @@ -282,7 +283,7 @@ public class MockContentProvider extends ContentProvider { * @hide */ public IBinder getIContentProviderBinder() { - throw new UnsupportedOperationException("unimplemented mock method"); + return new Binder(); } /** diff --git a/test-runner/Android.bp b/test-runner/Android.bp index 75f5b5a96eb1..1f6db8403eee 100644 --- a/test-runner/Android.bp +++ b/test-runner/Android.bp @@ -41,6 +41,7 @@ java_sdk_library { ], compile_dex: true, + default_to_stubs: true, } // Build the android.test.runner-minus-junit library diff --git a/test-runner/api/current.txt b/test-runner/api/current.txt index 2c19a2e85410..5407b685bb34 100644 --- a/test-runner/api/current.txt +++ b/test-runner/api/current.txt @@ -78,6 +78,7 @@ package android.test { @Deprecated public class InstrumentationTestRunner extends android.app.Instrumentation implements android.test.TestSuiteProvider { ctor @Deprecated public InstrumentationTestRunner(); + method @Deprecated protected void addTestListener(junit.framework.TestListener); method @Deprecated public junit.framework.TestSuite getAllTests(); method @Deprecated protected android.test.AndroidTestRunner getAndroidTestRunner(); method @Deprecated public android.os.Bundle getArguments(); diff --git a/test-runner/src/android/test/InstrumentationTestRunner.java b/test-runner/src/android/test/InstrumentationTestRunner.java index b2582c19b548..07e3f8736cc8 100644 --- a/test-runner/src/android/test/InstrumentationTestRunner.java +++ b/test-runner/src/android/test/InstrumentationTestRunner.java @@ -410,7 +410,6 @@ public class InstrumentationTestRunner extends Instrumentation implements TestSu /** * Add a {@link TestListener} - * @hide */ protected void addTestListener(TestListener listener){ if(mTestRunner!=null && listener!=null){ diff --git a/tests/net/common/java/android/net/DhcpInfoTest.java b/tests/net/common/java/android/net/DhcpInfoTest.java index bd5533f33910..4d45ad72a9b8 100644 --- a/tests/net/common/java/android/net/DhcpInfoTest.java +++ b/tests/net/common/java/android/net/DhcpInfoTest.java @@ -16,8 +16,7 @@ package android.net; -import static android.net.shared.Inet4AddressUtils.inet4AddressToIntHTL; - +import static com.android.net.module.util.Inet4AddressUtils.inet4AddressToIntHTL; import static com.android.testutils.MiscAssertsKt.assertFieldCountEquals; import static com.android.testutils.ParcelUtilsKt.parcelingRoundTrip; 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/tests/net/java/com/android/server/connectivity/DnsManagerTest.java b/tests/net/java/com/android/server/connectivity/DnsManagerTest.java index 26a28da9755c..508b5cd9cb19 100644 --- a/tests/net/java/com/android/server/connectivity/DnsManagerTest.java +++ b/tests/net/java/com/android/server/connectivity/DnsManagerTest.java @@ -105,7 +105,8 @@ public class DnsManagerTest { @NonNull ResolverOptionsParcel expected) { assertEquals(actual.hosts, expected.hosts); assertEquals(actual.tcMode, expected.tcMode); - assertFieldCountEquals(2, ResolverOptionsParcel.class); + assertEquals(actual.enforceDnsUid, expected.enforceDnsUid); + assertFieldCountEquals(3, ResolverOptionsParcel.class); } private void assertResolverParamsEquals(@NonNull ResolverParamsParcel actual, diff --git a/tests/net/java/com/android/server/connectivity/PermissionMonitorTest.java b/tests/net/java/com/android/server/connectivity/PermissionMonitorTest.java index 76e3e2fced6f..5eea0e86eb0e 100644 --- a/tests/net/java/com/android/server/connectivity/PermissionMonitorTest.java +++ b/tests/net/java/com/android/server/connectivity/PermissionMonitorTest.java @@ -76,7 +76,6 @@ import com.android.server.LocalServices; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.invocation.InvocationOnMock; @@ -88,7 +87,6 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Set; - @RunWith(AndroidJUnit4.class) @SmallTest public class PermissionMonitorTest { @@ -117,7 +115,6 @@ public class PermissionMonitorTest { @Mock private PackageManagerInternal mMockPmi; @Mock private UserManager mUserManager; - private PackageManagerInternal.PackageListObserver mObserver; private PermissionMonitor mPermissionMonitor; @Before @@ -139,11 +136,7 @@ public class PermissionMonitorTest { /* observer */ null)); when(mPackageManager.getInstalledPackages(anyInt())).thenReturn(/* empty app list */ null); mPermissionMonitor.startMonitoring(); - - final ArgumentCaptor<PackageManagerInternal.PackageListObserver> observerCaptor = - ArgumentCaptor.forClass(PackageManagerInternal.PackageListObserver.class); - verify(mMockPmi).getPackageList(observerCaptor.capture()); - mObserver = observerCaptor.getValue(); + verify(mMockPmi).getPackageList(mPermissionMonitor); } private boolean hasRestrictedNetworkPermission(String partition, int targetSdkVersion, int uid, @@ -450,13 +443,13 @@ public class PermissionMonitorTest { new int[]{MOCK_UID1}); // Remove MOCK_UID1, expect no permission left for all user. - mPermissionMonitor.onPackageRemoved(MOCK_UID1); - removePackageForUsers(new int[]{MOCK_USER1, MOCK_USER2}, MOCK_UID1); + mPermissionMonitor.onPackageRemoved(MOCK_PACKAGE1, MOCK_UID1); + removePackageForUsers(new int[]{MOCK_USER1, MOCK_USER2}, MOCK_PACKAGE1, MOCK_UID1); mNetdMonitor.expectNoPermission(new int[]{MOCK_USER1, MOCK_USER2}, new int[]{MOCK_UID1}); // Remove SYSTEM_PACKAGE1, expect permission downgrade. when(mPackageManager.getPackagesForUid(anyInt())).thenReturn(new String[]{SYSTEM_PACKAGE2}); - removePackageForUsers(new int[]{MOCK_USER1, MOCK_USER2}, SYSTEM_UID); + removePackageForUsers(new int[]{MOCK_USER1, MOCK_USER2}, SYSTEM_PACKAGE1, SYSTEM_UID); mNetdMonitor.expectPermission(NETWORK, new int[]{MOCK_USER1, MOCK_USER2}, new int[]{SYSTEM_UID}); @@ -465,7 +458,7 @@ public class PermissionMonitorTest { // Remove all packages, expect no permission left. when(mPackageManager.getPackagesForUid(anyInt())).thenReturn(new String[]{}); - removePackageForUsers(new int[]{MOCK_USER2}, SYSTEM_UID); + removePackageForUsers(new int[]{MOCK_USER2}, SYSTEM_PACKAGE2, SYSTEM_UID); mNetdMonitor.expectNoPermission(new int[]{MOCK_USER1, MOCK_USER2}, new int[]{SYSTEM_UID, MOCK_UID1}); @@ -501,7 +494,8 @@ public class PermissionMonitorTest { reset(mNetdService); // When MOCK_UID1 package is uninstalled and reinstalled, expect Netd to be updated - mPermissionMonitor.onPackageRemoved(UserHandle.getUid(MOCK_USER1, MOCK_UID1)); + mPermissionMonitor.onPackageRemoved( + MOCK_PACKAGE1, UserHandle.getUid(MOCK_USER1, MOCK_UID1)); verify(mNetdService).firewallRemoveUidInterfaceRules(aryEq(new int[] {MOCK_UID1})); mPermissionMonitor.onPackageAdded(MOCK_PACKAGE1, UserHandle.getUid(MOCK_USER1, MOCK_UID1)); verify(mNetdService).firewallAddUidInterfaceRules(eq("tun0"), @@ -545,7 +539,8 @@ public class PermissionMonitorTest { aryEq(new int[] {MOCK_UID1})); // Removed package should have its uid rules removed - mPermissionMonitor.onPackageRemoved(UserHandle.getUid(MOCK_USER1, MOCK_UID1)); + mPermissionMonitor.onPackageRemoved( + MOCK_PACKAGE1, UserHandle.getUid(MOCK_USER1, MOCK_UID1)); verify(mNetdService).firewallRemoveUidInterfaceRules(aryEq(new int[] {MOCK_UID1})); } @@ -559,9 +554,9 @@ public class PermissionMonitorTest { } } - private void removePackageForUsers(int[] users, int uid) { + private void removePackageForUsers(int[] users, String packageName, int uid) { for (final int user : users) { - mPermissionMonitor.onPackageRemoved(UserHandle.getUid(user, uid)); + mPermissionMonitor.onPackageRemoved(packageName, UserHandle.getUid(user, uid)); } } @@ -647,7 +642,7 @@ public class PermissionMonitorTest { private PackageInfo addPackage(String packageName, int uid, String[] permissions) throws Exception { PackageInfo packageInfo = setPackagePermissions(packageName, uid, permissions); - mObserver.onPackageAdded(packageName, uid); + mPermissionMonitor.onPackageAdded(packageName, uid); return packageInfo; } @@ -678,7 +673,7 @@ public class PermissionMonitorTest { when(mPackageManager.getPackageInfo(eq(MOCK_PACKAGE2), anyInt())).thenReturn(packageInfo2); when(mPackageManager.getPackagesForUid(MOCK_UID1)) .thenReturn(new String[]{MOCK_PACKAGE1, MOCK_PACKAGE2}); - mObserver.onPackageAdded(MOCK_PACKAGE2, MOCK_UID1); + mPermissionMonitor.onPackageAdded(MOCK_PACKAGE2, MOCK_UID1); mNetdServiceMonitor.expectPermission(INetd.PERMISSION_INTERNET | INetd.PERMISSION_UPDATE_DEVICE_STATS, new int[]{MOCK_UID1}); } @@ -692,7 +687,7 @@ public class PermissionMonitorTest { | INetd.PERMISSION_UPDATE_DEVICE_STATS, new int[]{MOCK_UID1}); when(mPackageManager.getPackagesForUid(MOCK_UID1)).thenReturn(new String[]{}); - mObserver.onPackageRemoved(MOCK_PACKAGE1, MOCK_UID1); + mPermissionMonitor.onPackageRemoved(MOCK_PACKAGE1, MOCK_UID1); mNetdServiceMonitor.expectPermission(INetd.PERMISSION_UNINSTALLED, new int[]{MOCK_UID1}); } @@ -705,7 +700,7 @@ public class PermissionMonitorTest { | INetd.PERMISSION_UPDATE_DEVICE_STATS, new int[]{MOCK_UID1}); when(mPackageManager.getPackagesForUid(MOCK_UID1)).thenReturn(new String[]{}); - mObserver.onPackageRemoved(MOCK_PACKAGE1, MOCK_UID1); + mPermissionMonitor.onPackageRemoved(MOCK_PACKAGE1, MOCK_UID1); mNetdServiceMonitor.expectPermission(INetd.PERMISSION_UNINSTALLED, new int[]{MOCK_UID1}); addPackage(MOCK_PACKAGE1, MOCK_UID1, new String[] {INTERNET}); @@ -719,10 +714,7 @@ public class PermissionMonitorTest { addPackage(MOCK_PACKAGE1, MOCK_UID1, new String[] {}); mNetdServiceMonitor.expectPermission(INetd.PERMISSION_NONE, new int[]{MOCK_UID1}); - // When updating a package, the broadcast receiver gets two broadcasts (a remove and then an - // add), but the observer sees only one callback (an update). - setPackagePermissions(MOCK_PACKAGE1, MOCK_UID1, new String[] {INTERNET}); - mObserver.onPackageChanged(MOCK_PACKAGE1, MOCK_UID1); + addPackage(MOCK_PACKAGE1, MOCK_UID1, new String[] {INTERNET}); mNetdServiceMonitor.expectPermission(INetd.PERMISSION_INTERNET, new int[]{MOCK_UID1}); } @@ -740,7 +732,7 @@ public class PermissionMonitorTest { when(mPackageManager.getPackagesForUid(MOCK_UID1)).thenReturn(new String[]{ MOCK_PACKAGE2}); - mObserver.onPackageRemoved(MOCK_PACKAGE1, MOCK_UID1); + mPermissionMonitor.onPackageRemoved(MOCK_PACKAGE1, MOCK_UID1); mNetdServiceMonitor.expectPermission(INetd.PERMISSION_INTERNET, new int[]{MOCK_UID1}); } 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(); } |