diff options
255 files changed, 2996 insertions, 1898 deletions
diff --git a/GAME_MANAGER_OWNERS b/GAME_MANAGER_OWNERS index 502a9e362202..b65c43a8d7f0 100644 --- a/GAME_MANAGER_OWNERS +++ b/GAME_MANAGER_OWNERS @@ -1,2 +1,3 @@ lpy@google.com -timvp@google.com +chingtangyu@google.com +xwxw@google.com diff --git a/apct-tests/perftests/core/Android.bp b/apct-tests/perftests/core/Android.bp index 23464f879518..9366ff2d81a9 100644 --- a/apct-tests/perftests/core/Android.bp +++ b/apct-tests/perftests/core/Android.bp @@ -43,6 +43,9 @@ android_test { "apct-perftests-resources-manager-apps", "apct-perftests-utils", "collector-device-lib", + "compatibility-device-util-axt", + "junit", + "junit-params", "core-tests-support", "guava", ], @@ -59,4 +62,10 @@ android_test { test_suites: ["device-tests"], certificate: "platform", + + errorprone: { + javacflags: [ + "-Xep:ReturnValueIgnored:WARN", + ], + }, } diff --git a/apct-tests/perftests/core/src/android/libcore/DeepArrayOpsPerfTest.java b/apct-tests/perftests/core/src/android/libcore/DeepArrayOpsPerfTest.java index 3f4f6af7554c..3ebaa4cd0bfa 100644 --- a/apct-tests/perftests/core/src/android/libcore/DeepArrayOpsPerfTest.java +++ b/apct-tests/perftests/core/src/android/libcore/DeepArrayOpsPerfTest.java @@ -20,18 +20,19 @@ import android.perftests.utils.BenchmarkState; import android.perftests.utils.PerfStatusReporter; import android.test.suitebuilder.annotation.LargeTest; -import org.junit.Before; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; + import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.util.Arrays; import java.util.Collection; -@RunWith(Parameterized.class) +@RunWith(JUnitParamsRunner.class) @LargeTest public class DeepArrayOpsPerfTest { @Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); @@ -39,19 +40,14 @@ public class DeepArrayOpsPerfTest { private Object[] mArray; private Object[] mArray2; - @Parameterized.Parameter(0) - public int mArrayLength; - - @Parameterized.Parameters(name = "mArrayLength({0})") - public static Collection<Object[]> data() { + public static Collection<Object[]> getData() { return Arrays.asList(new Object[][] {{1}, {4}, {16}, {32}, {2048}}); } - @Before - public void setUp() throws Exception { - mArray = new Object[mArrayLength * 14]; - mArray2 = new Object[mArrayLength * 14]; - for (int i = 0; i < mArrayLength; i += 14) { + public void setUp(int arrayLength) throws Exception { + mArray = new Object[arrayLength * 14]; + mArray2 = new Object[arrayLength * 14]; + for (int i = 0; i < arrayLength; i += 14) { mArray[i] = new IntWrapper(i); mArray2[i] = new IntWrapper(i); @@ -99,7 +95,9 @@ public class DeepArrayOpsPerfTest { } @Test - public void deepHashCode() { + @Parameters(method = "getData") + public void deepHashCode(int arrayLength) throws Exception { + setUp(arrayLength); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { Arrays.deepHashCode(mArray); @@ -107,7 +105,9 @@ public class DeepArrayOpsPerfTest { } @Test - public void deepEquals() { + @Parameters(method = "getData") + public void deepEquals(int arrayLength) throws Exception { + setUp(arrayLength); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { Arrays.deepEquals(mArray, mArray2); diff --git a/apct-tests/perftests/core/src/android/libcore/ReferencePerfTest.java b/apct-tests/perftests/core/src/android/libcore/ReferencePerfTest.java index 2ef68ca7bdb2..05a3e1201a00 100644 --- a/apct-tests/perftests/core/src/android/libcore/ReferencePerfTest.java +++ b/apct-tests/perftests/core/src/android/libcore/ReferencePerfTest.java @@ -118,7 +118,7 @@ public class ReferencePerfTest { int got = count.get(); if (n != got) { throw new IllegalStateException( - String.format("Only %i of %i objects finalized?", got, n)); + String.format("Only %d of %d objects finalized?", got, n)); } } } diff --git a/apct-tests/perftests/core/src/android/libcore/SystemArrayCopyPerfTest.java b/apct-tests/perftests/core/src/android/libcore/SystemArrayCopyPerfTest.java index 5aacfc25bfd1..20f1309bd8e6 100644 --- a/apct-tests/perftests/core/src/android/libcore/SystemArrayCopyPerfTest.java +++ b/apct-tests/perftests/core/src/android/libcore/SystemArrayCopyPerfTest.java @@ -20,22 +20,22 @@ import android.perftests.utils.BenchmarkState; import android.perftests.utils.PerfStatusReporter; import android.test.suitebuilder.annotation.LargeTest; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; + import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; import java.util.Collection; -@RunWith(Parameterized.class) +@RunWith(JUnitParamsRunner.class) @LargeTest public class SystemArrayCopyPerfTest { @Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); - @Parameters(name = "arrayLength={0}") - public static Collection<Object[]> data() { + public static Collection<Object[]> getData() { return Arrays.asList( new Object[][] { {2}, {4}, {8}, {16}, {32}, {64}, {128}, {256}, {512}, {1024}, {2048}, {4096}, @@ -43,12 +43,10 @@ public class SystemArrayCopyPerfTest { }); } - @Parameterized.Parameter(0) - public int arrayLength; - // Provides benchmarking for different types of arrays using the arraycopy function. @Test - public void timeSystemCharArrayCopy() { + @Parameters(method = "getData") + public void timeSystemCharArrayCopy(int arrayLength) { final int len = arrayLength; char[] src = new char[len]; char[] dst = new char[len]; @@ -59,7 +57,8 @@ public class SystemArrayCopyPerfTest { } @Test - public void timeSystemByteArrayCopy() { + @Parameters(method = "getData") + public void timeSystemByteArrayCopy(int arrayLength) { final int len = arrayLength; byte[] src = new byte[len]; byte[] dst = new byte[len]; @@ -70,7 +69,8 @@ public class SystemArrayCopyPerfTest { } @Test - public void timeSystemShortArrayCopy() { + @Parameters(method = "getData") + public void timeSystemShortArrayCopy(int arrayLength) { final int len = arrayLength; short[] src = new short[len]; short[] dst = new short[len]; @@ -81,7 +81,8 @@ public class SystemArrayCopyPerfTest { } @Test - public void timeSystemIntArrayCopy() { + @Parameters(method = "getData") + public void timeSystemIntArrayCopy(int arrayLength) { final int len = arrayLength; int[] src = new int[len]; int[] dst = new int[len]; @@ -92,7 +93,8 @@ public class SystemArrayCopyPerfTest { } @Test - public void timeSystemLongArrayCopy() { + @Parameters(method = "getData") + public void timeSystemLongArrayCopy(int arrayLength) { final int len = arrayLength; long[] src = new long[len]; long[] dst = new long[len]; @@ -103,7 +105,8 @@ public class SystemArrayCopyPerfTest { } @Test - public void timeSystemFloatArrayCopy() { + @Parameters(method = "getData") + public void timeSystemFloatArrayCopy(int arrayLength) { final int len = arrayLength; float[] src = new float[len]; float[] dst = new float[len]; @@ -114,7 +117,8 @@ public class SystemArrayCopyPerfTest { } @Test - public void timeSystemDoubleArrayCopy() { + @Parameters(method = "getData") + public void timeSystemDoubleArrayCopy(int arrayLength) { final int len = arrayLength; double[] src = new double[len]; double[] dst = new double[len]; @@ -125,7 +129,8 @@ public class SystemArrayCopyPerfTest { } @Test - public void timeSystemBooleanArrayCopy() { + @Parameters(method = "getData") + public void timeSystemBooleanArrayCopy(int arrayLength) { final int len = arrayLength; boolean[] src = new boolean[len]; boolean[] dst = new boolean[len]; diff --git a/apct-tests/perftests/core/src/android/libcore/XmlSerializePerfTest.java b/apct-tests/perftests/core/src/android/libcore/XmlSerializePerfTest.java index eec0734cffda..b1b594d64324 100644 --- a/apct-tests/perftests/core/src/android/libcore/XmlSerializePerfTest.java +++ b/apct-tests/perftests/core/src/android/libcore/XmlSerializePerfTest.java @@ -20,42 +20,32 @@ import android.perftests.utils.BenchmarkState; import android.perftests.utils.PerfStatusReporter; import android.test.suitebuilder.annotation.LargeTest; -import org.junit.Before; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; + import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; import org.xmlpull.v1.XmlSerializer; import java.io.CharArrayWriter; import java.lang.reflect.Constructor; -import java.util.Arrays; -import java.util.Collection; import java.util.Random; -@RunWith(Parameterized.class) +@RunWith(JUnitParamsRunner.class) @LargeTest public class XmlSerializePerfTest { @Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); - @Parameters(name = "mDatasetAsString({0}), mSeed({1})") - public static Collection<Object[]> data() { - return Arrays.asList( - new Object[][] { - {"0.99 0.7 0.7 0.7 0.7 0.7", 854328}, - {"0.999 0.3 0.3 0.95 0.9 0.9", 854328}, - {"0.99 0.7 0.7 0.7 0.7 0.7", 312547}, - {"0.999 0.3 0.3 0.95 0.9 0.9", 312547} - }); + private Object[] getParams() { + return new Object[][] { + new Object[] {"0.99 0.7 0.7 0.7 0.7 0.7", 854328}, + new Object[] {"0.999 0.3 0.3 0.95 0.9 0.9", 854328}, + new Object[] {"0.99 0.7 0.7 0.7 0.7 0.7", 312547}, + new Object[] {"0.999 0.3 0.3 0.95 0.9 0.9", 312547} + }; } - @Parameterized.Parameter(0) - public String mDatasetAsString; - - @Parameterized.Parameter(1) - public int mSeed; - double[] mDataset; private Constructor<? extends XmlSerializer> mKxmlConstructor; private Constructor<? extends XmlSerializer> mFastConstructor; @@ -100,8 +90,7 @@ public class XmlSerializePerfTest { } @SuppressWarnings("unchecked") - @Before - public void setUp() throws Exception { + public void setUp(String datasetAsString) throws Exception { mKxmlConstructor = (Constructor) Class.forName("com.android.org.kxml2.io.KXmlSerializer").getConstructor(); @@ -109,28 +98,32 @@ public class XmlSerializePerfTest { (Constructor) Class.forName("com.android.internal.util.FastXmlSerializer") .getConstructor(); - String[] splitStrings = mDatasetAsString.split(" "); + String[] splitStrings = datasetAsString.split(" "); mDataset = new double[splitStrings.length]; for (int i = 0; i < splitStrings.length; i++) { mDataset[i] = Double.parseDouble(splitStrings[i]); } } - private void internalTimeSerializer(Constructor<? extends XmlSerializer> ctor) + private void internalTimeSerializer(Constructor<? extends XmlSerializer> ctor, int seed) throws Exception { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - serializeRandomXml(ctor, mSeed); + serializeRandomXml(ctor, seed); } } @Test - public void timeKxml() throws Exception { - internalTimeSerializer(mKxmlConstructor); + @Parameters(method = "getParams") + public void timeKxml(String datasetAsString, int seed) throws Exception { + setUp(datasetAsString); + internalTimeSerializer(mKxmlConstructor, seed); } @Test - public void timeFast() throws Exception { - internalTimeSerializer(mFastConstructor); + @Parameters(method = "getParams") + public void timeFast(String datasetAsString, int seed) throws Exception { + setUp(datasetAsString); + internalTimeSerializer(mFastConstructor, seed); } } diff --git a/apct-tests/perftests/core/src/android/libcore/ZipFilePerfTest.java b/apct-tests/perftests/core/src/android/libcore/ZipFilePerfTest.java index 31c92ba5e207..3a45d4045d62 100644 --- a/apct-tests/perftests/core/src/android/libcore/ZipFilePerfTest.java +++ b/apct-tests/perftests/core/src/android/libcore/ZipFilePerfTest.java @@ -20,12 +20,12 @@ import android.perftests.utils.BenchmarkState; import android.perftests.utils.PerfStatusReporter; import android.test.suitebuilder.annotation.LargeTest; -import org.junit.Before; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; + import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; import java.io.File; import java.io.FileOutputStream; @@ -38,23 +38,18 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; -@RunWith(Parameterized.class) +@RunWith(JUnitParamsRunner.class) @LargeTest public class ZipFilePerfTest { @Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); private File mFile; - @Parameters(name = "numEntries={0}") - public static Collection<Object[]> data() { + public static Collection<Object[]> getData() { return Arrays.asList(new Object[][] {{128}, {1024}, {8192}}); } - @Parameterized.Parameter(0) - public int numEntries; - - @Before - public void setUp() throws Exception { + public void setUp(int numEntries) throws Exception { mFile = File.createTempFile(getClass().getName(), ".zip"); mFile.deleteOnExit(); writeEntries(new ZipOutputStream(new FileOutputStream(mFile)), numEntries, 0); @@ -66,7 +61,9 @@ public class ZipFilePerfTest { } @Test - public void timeZipFileOpen() throws Exception { + @Parameters(method = "getData") + public void timeZipFileOpen(int numEntries) throws Exception { + setUp(numEntries); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { ZipFile zf = new ZipFile(mFile); diff --git a/apct-tests/perftests/core/src/android/libcore/ZipFileReadPerfTest.java b/apct-tests/perftests/core/src/android/libcore/ZipFileReadPerfTest.java index faa96285cefd..2e89518ec9fb 100644 --- a/apct-tests/perftests/core/src/android/libcore/ZipFileReadPerfTest.java +++ b/apct-tests/perftests/core/src/android/libcore/ZipFileReadPerfTest.java @@ -20,12 +20,13 @@ import android.perftests.utils.BenchmarkState; import android.perftests.utils.PerfStatusReporter; import android.test.suitebuilder.annotation.LargeTest; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; + import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; import java.io.File; import java.io.FileOutputStream; @@ -39,21 +40,17 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; -@RunWith(Parameterized.class) +@RunWith(JUnitParamsRunner.class) @LargeTest public class ZipFileReadPerfTest { @Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); - @Parameters(name = "readBufferSize={0}") - public static Collection<Object[]> data() { + public static Collection<Object[]> getData() { return Arrays.asList(new Object[][] {{1024}, {16384}, {65536}}); } private File mFile; - @Parameterized.Parameter(0) - public int readBufferSize; - @Before public void setUp() throws Exception { mFile = File.createTempFile(getClass().getName(), ".zip"); @@ -90,7 +87,8 @@ public class ZipFileReadPerfTest { } @Test - public void timeZipFileRead() throws Exception { + @Parameters(method = "getData") + public void timeZipFileRead(int readBufferSize) throws Exception { byte[] readBuffer = new byte[readBufferSize]; BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { diff --git a/apct-tests/perftests/core/src/android/libcore/regression/BitSetPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/BitSetPerfTest.java index db5462cd69bf..2c0473eda830 100644 --- a/apct-tests/perftests/core/src/android/libcore/regression/BitSetPerfTest.java +++ b/apct-tests/perftests/core/src/android/libcore/regression/BitSetPerfTest.java @@ -20,96 +20,99 @@ import android.perftests.utils.BenchmarkState; import android.perftests.utils.PerfStatusReporter; import android.test.suitebuilder.annotation.LargeTest; -import org.junit.Before; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; + import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; import java.util.BitSet; import java.util.Collection; -@RunWith(Parameterized.class) +@RunWith(JUnitParamsRunner.class) @LargeTest public class BitSetPerfTest { @Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); - @Parameters(name = "mSize={0}") - public static Collection<Object[]> data() { + public static Collection<Object[]> getData() { return Arrays.asList(new Object[][] {{1000}, {10000}}); } - @Parameterized.Parameter(0) - public int mSize; - - private BitSet mBitSet; - - @Before - public void setUp() throws Exception { - mBitSet = new BitSet(mSize); - } - @Test - public void timeIsEmptyTrue() { + @Parameters(method = "getData") + public void timeIsEmptyTrue(int size) { + BitSet bitSet = new BitSet(size); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - if (!mBitSet.isEmpty()) throw new RuntimeException(); + if (!bitSet.isEmpty()) throw new RuntimeException(); } } @Test - public void timeIsEmptyFalse() { - mBitSet.set(mBitSet.size() - 1); + @Parameters(method = "getData") + public void timeIsEmptyFalse(int size) { + BitSet bitSet = new BitSet(size); + bitSet.set(bitSet.size() - 1); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - if (mBitSet.isEmpty()) throw new RuntimeException(); + if (bitSet.isEmpty()) throw new RuntimeException(); } } @Test - public void timeGet() { + @Parameters(method = "getData") + public void timeGet(int size) { + BitSet bitSet = new BitSet(size); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); int i = 1; while (state.keepRunning()) { - mBitSet.get(++i % mSize); + bitSet.get(++i % size); } } @Test - public void timeClear() { + @Parameters(method = "getData") + public void timeClear(int size) { + BitSet bitSet = new BitSet(size); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); int i = 1; while (state.keepRunning()) { - mBitSet.clear(++i % mSize); + bitSet.clear(++i % size); } } @Test - public void timeSet() { + @Parameters(method = "getData") + public void timeSet(int size) { + BitSet bitSet = new BitSet(size); int i = 1; BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - mBitSet.set(++i % mSize); + bitSet.set(++i % size); } } @Test - public void timeSetOn() { + @Parameters(method = "getData") + public void timeSetOn(int size) { + BitSet bitSet = new BitSet(size); int i = 1; BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - mBitSet.set(++i % mSize, true); + bitSet.set(++i % size, true); } } @Test - public void timeSetOff() { + @Parameters(method = "getData") + public void timeSetOff(int size) { + BitSet bitSet = new BitSet(size); int i = 1; BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - mBitSet.set(++i % mSize, false); + bitSet.set(++i % size, false); } } } diff --git a/apct-tests/perftests/core/src/android/libcore/regression/BreakIteratorPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/BreakIteratorPerfTest.java index 3952c12b3bfe..6a2ce5847daa 100644 --- a/apct-tests/perftests/core/src/android/libcore/regression/BreakIteratorPerfTest.java +++ b/apct-tests/perftests/core/src/android/libcore/regression/BreakIteratorPerfTest.java @@ -20,18 +20,19 @@ import android.perftests.utils.BenchmarkState; import android.perftests.utils.PerfStatusReporter; import android.test.suitebuilder.annotation.LargeTest; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; + import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; import java.text.BreakIterator; import java.util.Arrays; import java.util.Collection; import java.util.Locale; -@RunWith(Parameterized.class) +@RunWith(JUnitParamsRunner.class) @LargeTest public final class BreakIteratorPerfTest { @Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); @@ -41,36 +42,37 @@ public final class BreakIteratorPerfTest { Locale.US, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi mollis consequat" + " nisl non pharetra. Praesent pretium vehicula odio sed ultrices. Aenean a" - + " felis libero. Vivamus sed commodo nibh. Pellentesque turpis lectus, euismod" - + " vel ante nec, cursus posuere orci. Suspendisse velit neque, fermentum" - + " luctus ultrices in, ultrices vitae arcu. Duis tincidunt cursus lorem. Nam" - + " ultricies accumsan quam vitae imperdiet. Pellentesque habitant morbi" - + " tristique senectus et netus et malesuada fames ac turpis egestas. Quisque" - + " aliquet pretium nisi, eget laoreet enim molestie sit amet. Class aptent" - + " taciti sociosqu ad litora torquent per conubia nostra, per inceptos" + + " felis libero. Vivamus sed commodo nibh. Pellentesque turpis lectus," + + " euismod vel ante nec, cursus posuere orci. Suspendisse velit neque," + + " fermentum luctus ultrices in, ultrices vitae arcu. Duis tincidunt cursus" + + " lorem. Nam ultricies accumsan quam vitae imperdiet. Pellentesque habitant" + + " morbi tristique senectus et netus et malesuada fames ac turpis egestas." + + " Quisque aliquet pretium nisi, eget laoreet enim molestie sit amet. Class" + + " aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos" + " himenaeos.\n" + "Nam dapibus aliquam lacus ac suscipit. Proin in nibh sit amet purus congue" + " laoreet eget quis nisl. Morbi gravida dignissim justo, a venenatis ante" - + " pulvinar at. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin" - + " ultrices vestibulum dui, vel aliquam lacus aliquam quis. Duis fringilla" - + " sapien ac lacus egestas, vel adipiscing elit euismod. Donec non tellus" - + " odio. Donec gravida eu massa ac feugiat. Aliquam erat volutpat. Praesent id" - + " adipiscing metus, nec laoreet enim. Aliquam vitae posuere turpis. Mauris ac" - + " pharetra sem. In at placerat tortor. Vivamus ac vehicula neque. Cras" - + " volutpat ullamcorper massa et varius. Praesent sagittis neque vitae nulla" - + " euismod pharetra.\n" + + " pulvinar at. Lorem ipsum dolor sit amet, consectetur adipiscing elit." + + " Proin ultrices vestibulum dui, vel aliquam lacus aliquam quis. Duis" + + " fringilla sapien ac lacus egestas, vel adipiscing elit euismod. Donec non" + + " tellus odio. Donec gravida eu massa ac feugiat. Aliquam erat volutpat." + + " Praesent id adipiscing metus, nec laoreet enim. Aliquam vitae posuere" + + " turpis. Mauris ac pharetra sem. In at placerat tortor. Vivamus ac vehicula" + + " neque. Cras volutpat ullamcorper massa et varius. Praesent sagittis neque" + + " vitae nulla euismod pharetra.\n" + "Sed placerat sapien non molestie sollicitudin. Nullam sit amet dictum quam." + " Etiam tincidunt tortor vel pretium vehicula. Praesent fringilla ipsum vel" + " velit luctus dignissim. Nulla massa ligula, mattis in enim et, mattis" + " lacinia odio. Suspendisse tristique urna a orci commodo tempor. Duis" + " lacinia egestas arcu a sollicitudin.\n" + "In ac feugiat lacus. Nunc fermentum eu est at tristique. Pellentesque quis" - + " ligula et orci placerat lacinia. Maecenas quis mauris diam. Etiam mi ipsum," - + " tempus in purus quis, euismod faucibus orci. Nulla facilisi. Praesent sit" - + " amet sapien vel elit porta adipiscing. Phasellus sit amet volutpat diam.\n" - + "Proin bibendum elit non lacus pharetra, quis eleifend tellus placerat. Nulla" - + " facilisi. Maecenas ante diam, pellentesque mattis mattis in, porta ut" - + " lorem. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices" + + " ligula et orci placerat lacinia. Maecenas quis mauris diam. Etiam mi" + + " ipsum, tempus in purus quis, euismod faucibus orci. Nulla facilisi." + + " Praesent sit amet sapien vel elit porta adipiscing. Phasellus sit amet" + + " volutpat diam.\n" + + "Proin bibendum elit non lacus pharetra, quis eleifend tellus placerat." + + " Nulla facilisi. Maecenas ante diam, pellentesque mattis mattis in, porta" + + " ut lorem. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices" + " posuere cubilia Curae; Nunc interdum tristique metus, in scelerisque odio" + " fermentum eget. Cras nec venenatis lacus. Aenean euismod eget metus quis" + " molestie. Cras tincidunt dolor ut massa ornare, in elementum lacus auctor." @@ -80,29 +82,29 @@ public final class BreakIteratorPerfTest { LONGPARA( Locale.US, "During dinner, Mr. Bennet scarcely spoke at all; but when the servants were" - + " withdrawn, he thought it time to have some conversation with his guest, and" - + " therefore started a subject in which he expected him to shine, by observing" - + " that he seemed very fortunate in his patroness. Lady Catherine de Bourgh's" - + " attention to his wishes, and consideration for his comfort, appeared very" - + " remarkable. Mr. Bennet could not have chosen better. Mr. Collins was" - + " eloquent in her praise. The subject elevated him to more than usual" - + " solemnity of manner, and with a most important aspect he protested that" - + " \"he had never in his life witnessed such behaviour in a person of" - + " rank--such affability and condescension, as he had himself experienced from" - + " Lady Catherine. She had been graciously pleased to approve of both of the" - + " discourses which he had already had the honour of preaching before her. She" - + " had also asked him twice to dine at Rosings, and had sent for him only the" - + " Saturday before, to make up her pool of quadrille in the evening. Lady" - + " Catherine was reckoned proud by many people he knew, but _he_ had never" - + " seen anything but affability in her. She had always spoken to him as she" - + " would to any other gentleman; she made not the smallest objection to his" - + " joining in the society of the neighbourhood nor to his leaving the parish" - + " occasionally for a week or two, to visit his relations. She had even" - + " condescended to advise him to marry as soon as he could, provided he chose" - + " with discretion; and had once paid him a visit in his humble parsonage," - + " where she had perfectly approved all the alterations he had been making," - + " and had even vouchsafed to suggest some herself--some shelves in the closet" - + " up stairs.\""), + + " withdrawn, he thought it time to have some conversation with his guest," + + " and therefore started a subject in which he expected him to shine, by" + + " observing that he seemed very fortunate in his patroness. Lady Catherine" + + " de Bourgh's attention to his wishes, and consideration for his comfort," + + " appeared very remarkable. Mr. Bennet could not have chosen better. Mr." + + " Collins was eloquent in her praise. The subject elevated him to more than" + + " usual solemnity of manner, and with a most important aspect he protested" + + " that \"he had never in his life witnessed such behaviour in a person of" + + " rank--such affability and condescension, as he had himself experienced" + + " from Lady Catherine. She had been graciously pleased to approve of both of" + + " the discourses which he had already had the honour of preaching before" + + " her. She had also asked him twice to dine at Rosings, and had sent for him" + + " only the Saturday before, to make up her pool of quadrille in the evening." + + " Lady Catherine was reckoned proud by many people he knew, but _he_ had" + + " never seen anything but affability in her. She had always spoken to him as" + + " she would to any other gentleman; she made not the smallest objection to" + + " his joining in the society of the neighbourhood nor to his leaving the" + + " parish occasionally for a week or two, to visit his relations. She had" + + " even condescended to advise him to marry as soon as he could, provided he" + + " chose with discretion; and had once paid him a visit in his humble" + + " parsonage, where she had perfectly approved all the alterations he had" + + " been making, and had even vouchsafed to suggest some herself--some shelves" + + " in the closet up stairs.\""), GERMAN( Locale.GERMANY, "Aber dieser Freiheit setzte endlich der Winter ein Ziel. Draußen auf den Feldern" @@ -119,15 +121,14 @@ public final class BreakIteratorPerfTest { + " เดิมทีเป็นการผสมผสานกันระหว่างสำเนียงอยุธยาและชาวไทยเชื้อสายจีนรุ่นหลังที่" + "พูดไทยแทนกลุ่มภาษาจีน" + " ลักษณะเด่นคือมีการออกเสียงที่ชัดเจนและแข็งกระด้างซึ่งได้รับอิทธิพลจากภาษาแต" - + "้จิ๋ว" - + " การออกเสียงพยัญชนะ สระ การผันวรรณยุกต์ที่ในภาษาไทยมาตรฐาน" + + "้จิ๋ว การออกเสียงพยัญชนะ สระ การผันวรรณยุกต์ที่ในภาษาไทยมาตรฐาน" + " มาจากสำเนียงถิ่นนี้ในขณะที่ภาษาไทยสำเนียงอื่นล้วนเหน่อทั้งสิ้น" + " คำศัพท์ที่ใช้ในสำเนียงกรุงเทพจำนวนมากได้รับมาจากกลุ่มภาษาจีนเช่นคำว่า โป๊," + " เฮ็ง, อาหมวย, อาซิ่ม ซึ่งมาจากภาษาแต้จิ๋ว และจากภาษาจีนเช่น ถู(涂), ชิ่ว(去" + " อ่านว่า\"ชู่\") และคำว่า ทาย(猜 อ่านว่า \"ชาย\") เป็นต้น" + " เนื่องจากสำเนียงกรุงเทพได้รับอิทธิพลมาจากภาษาจีนดังนั้นตัวอักษร \"ร\"" - + " มักออกเสียงเหมารวมเป็น \"ล\" หรือคำควบกล่ำบางคำถูกละทิ้งไปด้วยเช่น รู้ เป็น" - + " ลู้, เรื่อง เป็น เลื่อง หรือ ประเทศ เป็น ปะเทศ" + + " มักออกเสียงเหมารวมเป็น \"ล\" หรือคำควบกล่ำบางคำถูกละทิ้งไปด้วยเช่น รู้" + + " เป็น ลู้, เรื่อง เป็น เลื่อง หรือ ประเทศ เป็น ปะเทศ" + " เป็นต้นสร้างความลำบากให้แก่ต่างชาติที่ต้องการเรียนภาษาไทย" + " แต่อย่างไรก็ตามผู้ที่พูดสำเนียงถิ่นนี้ก็สามารถออกอักขระภาษาไทยตามมาตรฐานได" + "้อย่างถูกต้องเพียงแต่มักเผลอไม่ค่อยออกเสียง"), @@ -151,8 +152,7 @@ public final class BreakIteratorPerfTest { } } - @Parameters(name = "mText={0}") - public static Collection<Object[]> data() { + public static Collection<Object[]> getData() { return Arrays.asList( new Object[][] { {Text.ACCENT}, {Text.BIDI}, {Text.EMOJI}, {Text.EMPTY}, {Text.GERMAN}, @@ -161,15 +161,13 @@ public final class BreakIteratorPerfTest { }); } - @Parameterized.Parameter(0) - public Text mText; - @Test - public void timeBreakIterator() { + @Parameters(method = "getData") + public void timeBreakIterator(Text text) { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - BreakIterator it = BreakIterator.getLineInstance(mText.mLocale); - it.setText(mText.mText); + BreakIterator it = BreakIterator.getLineInstance(text.mLocale); + it.setText(text.mText); while (it.next() != BreakIterator.DONE) { // Keep iterating @@ -178,12 +176,13 @@ public final class BreakIteratorPerfTest { } @Test - public void timeIcuBreakIterator() { + @Parameters(method = "getData") + public void timeIcuBreakIterator(Text text) { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { android.icu.text.BreakIterator it = - android.icu.text.BreakIterator.getLineInstance(mText.mLocale); - it.setText(mText.mText); + android.icu.text.BreakIterator.getLineInstance(text.mLocale); + it.setText(text.mText); while (it.next() != android.icu.text.BreakIterator.DONE) { // Keep iterating diff --git a/apct-tests/perftests/core/src/android/libcore/regression/BulkPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/BulkPerfTest.java index 855bb9a43d34..b7b7e83f147c 100644 --- a/apct-tests/perftests/core/src/android/libcore/regression/BulkPerfTest.java +++ b/apct-tests/perftests/core/src/android/libcore/regression/BulkPerfTest.java @@ -20,11 +20,12 @@ import android.perftests.utils.BenchmarkState; import android.perftests.utils.PerfStatusReporter; import android.test.suitebuilder.annotation.LargeTest; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; + import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; import java.io.File; import java.io.IOException; @@ -34,13 +35,12 @@ import java.nio.channels.FileChannel; import java.util.Arrays; import java.util.Collection; -@RunWith(Parameterized.class) +@RunWith(JUnitParamsRunner.class) @LargeTest public class BulkPerfTest { @Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); - @Parameters(name = "mAlign({0}), mSBuf({1}), mDBuf({2}), mSize({3})") - public static Collection<Object[]> data() { + public static Collection<Object[]> getData() { return Arrays.asList( new Object[][] { {true, MyBufferType.DIRECT, MyBufferType.DIRECT, 4096}, @@ -82,24 +82,12 @@ public class BulkPerfTest { }); } - @Parameterized.Parameter(0) - public boolean mAlign; - enum MyBufferType { DIRECT, HEAP, MAPPED } - @Parameterized.Parameter(1) - public MyBufferType mSBuf; - - @Parameterized.Parameter(2) - public MyBufferType mDBuf; - - @Parameterized.Parameter(3) - public int mSize; - public static ByteBuffer newBuffer(boolean aligned, MyBufferType bufferType, int bsize) throws IOException { int size = aligned ? bsize : bsize + 8 + 1; @@ -126,13 +114,15 @@ public class BulkPerfTest { } @Test - public void timePut() throws Exception { - ByteBuffer src = BulkPerfTest.newBuffer(mAlign, mSBuf, mSize); - ByteBuffer data = BulkPerfTest.newBuffer(mAlign, mDBuf, mSize); + @Parameters(method = "getData") + public void timePut(boolean align, MyBufferType sBuf, MyBufferType dBuf, int size) + throws Exception { + ByteBuffer src = BulkPerfTest.newBuffer(align, sBuf, size); + ByteBuffer data = BulkPerfTest.newBuffer(align, dBuf, size); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - src.position(mAlign ? 0 : 1); - data.position(mAlign ? 0 : 1); + src.position(align ? 0 : 1); + data.position(align ? 0 : 1); src.put(data); } } diff --git a/apct-tests/perftests/core/src/android/libcore/regression/ByteBufferPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/ByteBufferPerfTest.java index 4bd7c4e4fa82..9ac36d076c7b 100644 --- a/apct-tests/perftests/core/src/android/libcore/regression/ByteBufferPerfTest.java +++ b/apct-tests/perftests/core/src/android/libcore/regression/ByteBufferPerfTest.java @@ -20,11 +20,12 @@ import android.perftests.utils.BenchmarkState; import android.perftests.utils.PerfStatusReporter; import android.test.suitebuilder.annotation.LargeTest; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; + import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; import java.io.File; import java.io.IOException; @@ -41,7 +42,7 @@ import java.nio.channels.FileChannel; import java.util.Arrays; import java.util.Collection; -@RunWith(Parameterized.class) +@RunWith(JUnitParamsRunner.class) @LargeTest public class ByteBufferPerfTest { @Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); @@ -49,15 +50,14 @@ public class ByteBufferPerfTest { public enum MyByteOrder { BIG(ByteOrder.BIG_ENDIAN), LITTLE(ByteOrder.LITTLE_ENDIAN); - final ByteOrder mByteOrder; + final ByteOrder byteOrder; - MyByteOrder(ByteOrder mByteOrder) { - this.mByteOrder = mByteOrder; + MyByteOrder(ByteOrder byteOrder) { + this.byteOrder = byteOrder; } } - @Parameters(name = "mByteOrder={0}, mAligned={1}, mBufferType={2}") - public static Collection<Object[]> data() { + public static Collection<Object[]> getData() { return Arrays.asList( new Object[][] { {MyByteOrder.BIG, true, MyBufferType.DIRECT}, @@ -75,21 +75,12 @@ public class ByteBufferPerfTest { }); } - @Parameterized.Parameter(0) - public MyByteOrder mByteOrder; - - @Parameterized.Parameter(1) - public boolean mAligned; - enum MyBufferType { DIRECT, HEAP, MAPPED; } - @Parameterized.Parameter(2) - public MyBufferType mBufferType; - public static ByteBuffer newBuffer( MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws IOException { int size = aligned ? 8192 : 8192 + 8 + 1; @@ -115,7 +106,7 @@ public class ByteBufferPerfTest { result = fc.map(FileChannel.MapMode.READ_WRITE, 0, fc.size()); break; } - result.order(byteOrder.mByteOrder); + result.order(byteOrder.byteOrder); result.position(aligned ? 0 : 1); return result; } @@ -125,11 +116,13 @@ public class ByteBufferPerfTest { // @Test - public void timeByteBuffer_getByte() throws Exception { - ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType); + @Parameters(method = "getData") + public void timeByteBuffer_getByte( + MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception { + ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - src.position(mAligned ? 0 : 1); + src.position(aligned ? 0 : 1); for (int i = 0; i < 1024; ++i) { src.get(); } @@ -137,24 +130,28 @@ public class ByteBufferPerfTest { } @Test - public void timeByteBuffer_getByteArray() throws Exception { - ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType); + @Parameters(method = "getData") + public void timeByteBuffer_getByteArray( + MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception { + ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType); byte[] dst = new byte[1024]; BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { for (int i = 0; i < 1024; ++i) { - src.position(mAligned ? 0 : 1); + src.position(aligned ? 0 : 1); src.get(dst); } } } @Test - public void timeByteBuffer_getByte_indexed() throws Exception { - ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType); + @Parameters(method = "getData") + public void timeByteBuffer_getByte_indexed( + MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception { + ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - src.position(mAligned ? 0 : 1); + src.position(aligned ? 0 : 1); for (int i = 0; i < 1024; ++i) { src.get(i); } @@ -162,11 +159,13 @@ public class ByteBufferPerfTest { } @Test - public void timeByteBuffer_getChar() throws Exception { - ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType); + @Parameters(method = "getData") + public void timeByteBuffer_getChar( + MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception { + ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - src.position(mAligned ? 0 : 1); + src.position(aligned ? 0 : 1); for (int i = 0; i < 1024; ++i) { src.getChar(); } @@ -174,9 +173,11 @@ public class ByteBufferPerfTest { } @Test - public void timeCharBuffer_getCharArray() throws Exception { + @Parameters(method = "getData") + public void timeCharBuffer_getCharArray( + MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception { CharBuffer src = - ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType).asCharBuffer(); + ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType).asCharBuffer(); char[] dst = new char[1024]; BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { @@ -188,11 +189,13 @@ public class ByteBufferPerfTest { } @Test - public void timeByteBuffer_getChar_indexed() throws Exception { - ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType); + @Parameters(method = "getData") + public void timeByteBuffer_getChar_indexed( + MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception { + ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - src.position(mAligned ? 0 : 1); + src.position(aligned ? 0 : 1); for (int i = 0; i < 1024; ++i) { src.getChar(i * 2); } @@ -200,11 +203,13 @@ public class ByteBufferPerfTest { } @Test - public void timeByteBuffer_getDouble() throws Exception { - ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType); + @Parameters(method = "getData") + public void timeByteBuffer_getDouble( + MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception { + ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - src.position(mAligned ? 0 : 1); + src.position(aligned ? 0 : 1); for (int i = 0; i < 1024; ++i) { src.getDouble(); } @@ -212,9 +217,11 @@ public class ByteBufferPerfTest { } @Test - public void timeDoubleBuffer_getDoubleArray() throws Exception { + @Parameters(method = "getData") + public void timeDoubleBuffer_getDoubleArray( + MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception { DoubleBuffer src = - ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType).asDoubleBuffer(); + ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType).asDoubleBuffer(); double[] dst = new double[1024]; BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { @@ -226,11 +233,13 @@ public class ByteBufferPerfTest { } @Test - public void timeByteBuffer_getFloat() throws Exception { - ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType); + @Parameters(method = "getData") + public void timeByteBuffer_getFloat( + MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception { + ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - src.position(mAligned ? 0 : 1); + src.position(aligned ? 0 : 1); for (int i = 0; i < 1024; ++i) { src.getFloat(); } @@ -238,9 +247,11 @@ public class ByteBufferPerfTest { } @Test - public void timeFloatBuffer_getFloatArray() throws Exception { + @Parameters(method = "getData") + public void timeFloatBuffer_getFloatArray( + MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception { FloatBuffer src = - ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType).asFloatBuffer(); + ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType).asFloatBuffer(); float[] dst = new float[1024]; BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { @@ -252,11 +263,13 @@ public class ByteBufferPerfTest { } @Test - public void timeByteBuffer_getInt() throws Exception { - ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType); + @Parameters(method = "getData") + public void timeByteBuffer_getInt( + MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception { + ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - src.position(mAligned ? 0 : 1); + src.position(aligned ? 0 : 1); for (int i = 0; i < 1024; ++i) { src.getInt(); } @@ -264,9 +277,10 @@ public class ByteBufferPerfTest { } @Test - public void timeIntBuffer_getIntArray() throws Exception { - IntBuffer src = - ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType).asIntBuffer(); + @Parameters(method = "getData") + public void timeIntBuffer_getIntArray( + MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception { + IntBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType).asIntBuffer(); int[] dst = new int[1024]; BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { @@ -278,11 +292,13 @@ public class ByteBufferPerfTest { } @Test - public void timeByteBuffer_getLong() throws Exception { - ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType); + @Parameters(method = "getData") + public void timeByteBuffer_getLong( + MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception { + ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - src.position(mAligned ? 0 : 1); + src.position(aligned ? 0 : 1); for (int i = 0; i < 1024; ++i) { src.getLong(); } @@ -290,9 +306,11 @@ public class ByteBufferPerfTest { } @Test - public void timeLongBuffer_getLongArray() throws Exception { + @Parameters(method = "getData") + public void timeLongBuffer_getLongArray( + MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception { LongBuffer src = - ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType).asLongBuffer(); + ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType).asLongBuffer(); long[] dst = new long[1024]; BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { @@ -304,11 +322,13 @@ public class ByteBufferPerfTest { } @Test - public void timeByteBuffer_getShort() throws Exception { - ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType); + @Parameters(method = "getData") + public void timeByteBuffer_getShort( + MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception { + ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - src.position(mAligned ? 0 : 1); + src.position(aligned ? 0 : 1); for (int i = 0; i < 1024; ++i) { src.getShort(); } @@ -316,9 +336,11 @@ public class ByteBufferPerfTest { } @Test - public void timeShortBuffer_getShortArray() throws Exception { + @Parameters(method = "getData") + public void timeShortBuffer_getShortArray( + MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception { ShortBuffer src = - ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType).asShortBuffer(); + ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType).asShortBuffer(); short[] dst = new short[1024]; BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { @@ -334,8 +356,10 @@ public class ByteBufferPerfTest { // @Test - public void timeByteBuffer_putByte() throws Exception { - ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType); + @Parameters(method = "getData") + public void timeByteBuffer_putByte( + MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception { + ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { src.position(0); @@ -346,24 +370,28 @@ public class ByteBufferPerfTest { } @Test - public void timeByteBuffer_putByteArray() throws Exception { - ByteBuffer dst = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType); + @Parameters(method = "getData") + public void timeByteBuffer_putByteArray( + MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception { + ByteBuffer dst = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType); byte[] src = new byte[1024]; BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { for (int i = 0; i < 1024; ++i) { - dst.position(mAligned ? 0 : 1); + dst.position(aligned ? 0 : 1); dst.put(src); } } } @Test - public void timeByteBuffer_putChar() throws Exception { - ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType); + @Parameters(method = "getData") + public void timeByteBuffer_putChar( + MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception { + ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - src.position(mAligned ? 0 : 1); + src.position(aligned ? 0 : 1); for (int i = 0; i < 1024; ++i) { src.putChar(' '); } @@ -371,9 +399,11 @@ public class ByteBufferPerfTest { } @Test - public void timeCharBuffer_putCharArray() throws Exception { + @Parameters(method = "getData") + public void timeCharBuffer_putCharArray( + MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception { CharBuffer dst = - ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType).asCharBuffer(); + ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType).asCharBuffer(); char[] src = new char[1024]; BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { @@ -385,11 +415,13 @@ public class ByteBufferPerfTest { } @Test - public void timeByteBuffer_putDouble() throws Exception { - ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType); + @Parameters(method = "getData") + public void timeByteBuffer_putDouble( + MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception { + ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - src.position(mAligned ? 0 : 1); + src.position(aligned ? 0 : 1); for (int i = 0; i < 1024; ++i) { src.putDouble(0.0); } @@ -397,9 +429,11 @@ public class ByteBufferPerfTest { } @Test - public void timeDoubleBuffer_putDoubleArray() throws Exception { + @Parameters(method = "getData") + public void timeDoubleBuffer_putDoubleArray( + MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception { DoubleBuffer dst = - ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType).asDoubleBuffer(); + ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType).asDoubleBuffer(); double[] src = new double[1024]; BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { @@ -411,11 +445,13 @@ public class ByteBufferPerfTest { } @Test - public void timeByteBuffer_putFloat() throws Exception { - ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType); + @Parameters(method = "getData") + public void timeByteBuffer_putFloat( + MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception { + ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - src.position(mAligned ? 0 : 1); + src.position(aligned ? 0 : 1); for (int i = 0; i < 1024; ++i) { src.putFloat(0.0f); } @@ -423,9 +459,11 @@ public class ByteBufferPerfTest { } @Test - public void timeFloatBuffer_putFloatArray() throws Exception { + @Parameters(method = "getData") + public void timeFloatBuffer_putFloatArray( + MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception { FloatBuffer dst = - ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType).asFloatBuffer(); + ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType).asFloatBuffer(); float[] src = new float[1024]; BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { @@ -437,11 +475,13 @@ public class ByteBufferPerfTest { } @Test - public void timeByteBuffer_putInt() throws Exception { - ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType); + @Parameters(method = "getData") + public void timeByteBuffer_putInt( + MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception { + ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - src.position(mAligned ? 0 : 1); + src.position(aligned ? 0 : 1); for (int i = 0; i < 1024; ++i) { src.putInt(0); } @@ -449,9 +489,10 @@ public class ByteBufferPerfTest { } @Test - public void timeIntBuffer_putIntArray() throws Exception { - IntBuffer dst = - ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType).asIntBuffer(); + @Parameters(method = "getData") + public void timeIntBuffer_putIntArray( + MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception { + IntBuffer dst = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType).asIntBuffer(); int[] src = new int[1024]; BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { @@ -463,11 +504,13 @@ public class ByteBufferPerfTest { } @Test - public void timeByteBuffer_putLong() throws Exception { - ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType); + @Parameters(method = "getData") + public void timeByteBuffer_putLong( + MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception { + ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - src.position(mAligned ? 0 : 1); + src.position(aligned ? 0 : 1); for (int i = 0; i < 1024; ++i) { src.putLong(0L); } @@ -475,9 +518,11 @@ public class ByteBufferPerfTest { } @Test - public void timeLongBuffer_putLongArray() throws Exception { + @Parameters(method = "getData") + public void timeLongBuffer_putLongArray( + MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception { LongBuffer dst = - ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType).asLongBuffer(); + ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType).asLongBuffer(); long[] src = new long[1024]; BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { @@ -489,11 +534,13 @@ public class ByteBufferPerfTest { } @Test - public void timeByteBuffer_putShort() throws Exception { - ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType); + @Parameters(method = "getData") + public void timeByteBuffer_putShort( + MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception { + ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - src.position(mAligned ? 0 : 1); + src.position(aligned ? 0 : 1); for (int i = 0; i < 1024; ++i) { src.putShort((short) 0); } @@ -501,9 +548,11 @@ public class ByteBufferPerfTest { } @Test - public void timeShortBuffer_putShortArray() throws Exception { + @Parameters(method = "getData") + public void timeShortBuffer_putShortArray( + MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception { ShortBuffer dst = - ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType).asShortBuffer(); + ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType).asShortBuffer(); short[] src = new short[1024]; BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { @@ -515,6 +564,7 @@ public class ByteBufferPerfTest { } @Test + @Parameters(method = "getData") public void time_new_byteArray() throws Exception { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { @@ -523,6 +573,7 @@ public class ByteBufferPerfTest { } @Test + @Parameters(method = "getData") public void time_ByteBuffer_allocate() throws Exception { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { diff --git a/apct-tests/perftests/core/src/android/libcore/regression/ByteBufferScalarVersusVectorPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/ByteBufferScalarVersusVectorPerfTest.java index 81f9e59f2423..5dd9d6e2bc2c 100644 --- a/apct-tests/perftests/core/src/android/libcore/regression/ByteBufferScalarVersusVectorPerfTest.java +++ b/apct-tests/perftests/core/src/android/libcore/regression/ByteBufferScalarVersusVectorPerfTest.java @@ -20,23 +20,23 @@ import android.perftests.utils.BenchmarkState; import android.perftests.utils.PerfStatusReporter; import android.test.suitebuilder.annotation.LargeTest; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; + import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Collection; -@RunWith(Parameterized.class) +@RunWith(JUnitParamsRunner.class) @LargeTest public class ByteBufferScalarVersusVectorPerfTest { @Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); - @Parameters(name = "mByteOrder={0}, mAligned={1}, mBufferType={2}") - public static Collection<Object[]> data() { + public static Collection<Object[]> getData() { return Arrays.asList( new Object[][] { { @@ -102,19 +102,15 @@ public class ByteBufferScalarVersusVectorPerfTest { }); } - @Parameterized.Parameter(0) - public ByteBufferPerfTest.MyByteOrder mByteOrder; - - @Parameterized.Parameter(1) - public boolean mAligned; - - @Parameterized.Parameter(2) - public ByteBufferPerfTest.MyBufferType mBufferType; - @Test - public void timeManualByteBufferCopy() throws Exception { - ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType); - ByteBuffer dst = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType); + @Parameters(method = "getData") + public void timeManualByteBufferCopy( + ByteBufferPerfTest.MyByteOrder byteOrder, + boolean aligned, + ByteBufferPerfTest.MyBufferType bufferType) + throws Exception { + ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType); + ByteBuffer dst = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { src.position(0); @@ -126,23 +122,25 @@ public class ByteBufferScalarVersusVectorPerfTest { } @Test - public void timeByteBufferBulkGet() throws Exception { - ByteBuffer src = ByteBuffer.allocate(mAligned ? 8192 : 8192 + 1); + @Parameters({"true", "false"}) + public void timeByteBufferBulkGet(boolean aligned) throws Exception { + ByteBuffer src = ByteBuffer.allocate(aligned ? 8192 : 8192 + 1); byte[] dst = new byte[8192]; BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - src.position(mAligned ? 0 : 1); + src.position(aligned ? 0 : 1); src.get(dst, 0, dst.length); } } @Test - public void timeDirectByteBufferBulkGet() throws Exception { - ByteBuffer src = ByteBuffer.allocateDirect(mAligned ? 8192 : 8192 + 1); + @Parameters({"true", "false"}) + public void timeDirectByteBufferBulkGet(boolean aligned) throws Exception { + ByteBuffer src = ByteBuffer.allocateDirect(aligned ? 8192 : 8192 + 1); byte[] dst = new byte[8192]; BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - src.position(mAligned ? 0 : 1); + src.position(aligned ? 0 : 1); src.get(dst, 0, dst.length); } } diff --git a/apct-tests/perftests/core/src/android/libcore/regression/CharacterPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/CharacterPerfTest.java index 28ec6ded3c86..0a598998bced 100644 --- a/apct-tests/perftests/core/src/android/libcore/regression/CharacterPerfTest.java +++ b/apct-tests/perftests/core/src/android/libcore/regression/CharacterPerfTest.java @@ -20,12 +20,12 @@ import android.perftests.utils.BenchmarkState; import android.perftests.utils.PerfStatusReporter; import android.test.suitebuilder.annotation.LargeTest; -import org.junit.Before; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; + import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; import java.util.Collection; @@ -34,13 +34,12 @@ import java.util.Collection; * Tests various Character methods, intended for testing multiple implementations against each * other. */ -@RunWith(Parameterized.class) +@RunWith(JUnitParamsRunner.class) @LargeTest public class CharacterPerfTest { @Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); - @Parameters(name = "mCharacterSet({0}), mOverload({1})") - public static Collection<Object[]> data() { + public static Collection<Object[]> getData() { return Arrays.asList( new Object[][] { {CharacterSet.ASCII, Overload.CHAR}, @@ -50,17 +49,10 @@ public class CharacterPerfTest { }); } - @Parameterized.Parameter(0) - public CharacterSet mCharacterSet; - - @Parameterized.Parameter(1) - public Overload mOverload; - private char[] mChars; - @Before - public void setUp() throws Exception { - this.mChars = mCharacterSet.mChars; + public void setUp(CharacterSet characterSet) { + this.mChars = characterSet.mChars; } public enum Overload { @@ -87,10 +79,12 @@ public class CharacterPerfTest { // A fake benchmark to give us a baseline. @Test - public void timeIsSpace() { + @Parameters(method = "getData") + public void timeIsSpace(CharacterSet characterSet, Overload overload) { + setUp(characterSet); boolean fake = false; BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); - if (mOverload == Overload.CHAR) { + if (overload == Overload.CHAR) { while (state.keepRunning()) { for (int ch = 0; ch < 65536; ++ch) { fake ^= ((char) ch == ' '); @@ -106,9 +100,11 @@ public class CharacterPerfTest { } @Test - public void timeDigit() { + @Parameters(method = "getData") + public void timeDigit(CharacterSet characterSet, Overload overload) { + setUp(characterSet); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); - if (mOverload == Overload.CHAR) { + if (overload == Overload.CHAR) { while (state.keepRunning()) { for (int ch = 0; ch < 65536; ++ch) { Character.digit(mChars[ch], 10); @@ -124,9 +120,11 @@ public class CharacterPerfTest { } @Test - public void timeGetNumericValue() { + @Parameters(method = "getData") + public void timeGetNumericValue(CharacterSet characterSet, Overload overload) { + setUp(characterSet); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); - if (mOverload == Overload.CHAR) { + if (overload == Overload.CHAR) { while (state.keepRunning()) { for (int ch = 0; ch < 65536; ++ch) { Character.getNumericValue(mChars[ch]); @@ -142,9 +140,11 @@ public class CharacterPerfTest { } @Test - public void timeIsDigit() { + @Parameters(method = "getData") + public void timeIsDigit(CharacterSet characterSet, Overload overload) { + setUp(characterSet); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); - if (mOverload == Overload.CHAR) { + if (overload == Overload.CHAR) { while (state.keepRunning()) { for (int ch = 0; ch < 65536; ++ch) { Character.isDigit(mChars[ch]); @@ -160,9 +160,11 @@ public class CharacterPerfTest { } @Test - public void timeIsIdentifierIgnorable() { + @Parameters(method = "getData") + public void timeIsIdentifierIgnorable(CharacterSet characterSet, Overload overload) { + setUp(characterSet); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); - if (mOverload == Overload.CHAR) { + if (overload == Overload.CHAR) { while (state.keepRunning()) { for (int ch = 0; ch < 65536; ++ch) { Character.isIdentifierIgnorable(mChars[ch]); @@ -178,9 +180,11 @@ public class CharacterPerfTest { } @Test - public void timeIsJavaIdentifierPart() { + @Parameters(method = "getData") + public void timeIsJavaIdentifierPart(CharacterSet characterSet, Overload overload) { + setUp(characterSet); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); - if (mOverload == Overload.CHAR) { + if (overload == Overload.CHAR) { while (state.keepRunning()) { for (int ch = 0; ch < 65536; ++ch) { Character.isJavaIdentifierPart(mChars[ch]); @@ -196,9 +200,11 @@ public class CharacterPerfTest { } @Test - public void timeIsJavaIdentifierStart() { + @Parameters(method = "getData") + public void timeIsJavaIdentifierStart(CharacterSet characterSet, Overload overload) { + setUp(characterSet); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); - if (mOverload == Overload.CHAR) { + if (overload == Overload.CHAR) { while (state.keepRunning()) { for (int ch = 0; ch < 65536; ++ch) { Character.isJavaIdentifierStart(mChars[ch]); @@ -214,9 +220,11 @@ public class CharacterPerfTest { } @Test - public void timeIsLetter() { + @Parameters(method = "getData") + public void timeIsLetter(CharacterSet characterSet, Overload overload) { + setUp(characterSet); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); - if (mOverload == Overload.CHAR) { + if (overload == Overload.CHAR) { while (state.keepRunning()) { for (int ch = 0; ch < 65536; ++ch) { Character.isLetter(mChars[ch]); @@ -232,9 +240,11 @@ public class CharacterPerfTest { } @Test - public void timeIsLetterOrDigit() { + @Parameters(method = "getData") + public void timeIsLetterOrDigit(CharacterSet characterSet, Overload overload) { + setUp(characterSet); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); - if (mOverload == Overload.CHAR) { + if (overload == Overload.CHAR) { while (state.keepRunning()) { for (int ch = 0; ch < 65536; ++ch) { Character.isLetterOrDigit(mChars[ch]); @@ -250,9 +260,11 @@ public class CharacterPerfTest { } @Test - public void timeIsLowerCase() { + @Parameters(method = "getData") + public void timeIsLowerCase(CharacterSet characterSet, Overload overload) { + setUp(characterSet); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); - if (mOverload == Overload.CHAR) { + if (overload == Overload.CHAR) { while (state.keepRunning()) { for (int ch = 0; ch < 65536; ++ch) { Character.isLowerCase(mChars[ch]); @@ -268,9 +280,11 @@ public class CharacterPerfTest { } @Test - public void timeIsSpaceChar() { + @Parameters(method = "getData") + public void timeIsSpaceChar(CharacterSet characterSet, Overload overload) { + setUp(characterSet); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); - if (mOverload == Overload.CHAR) { + if (overload == Overload.CHAR) { while (state.keepRunning()) { for (int ch = 0; ch < 65536; ++ch) { Character.isSpaceChar(mChars[ch]); @@ -286,9 +300,11 @@ public class CharacterPerfTest { } @Test - public void timeIsUpperCase() { + @Parameters(method = "getData") + public void timeIsUpperCase(CharacterSet characterSet, Overload overload) { + setUp(characterSet); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); - if (mOverload == Overload.CHAR) { + if (overload == Overload.CHAR) { while (state.keepRunning()) { for (int ch = 0; ch < 65536; ++ch) { Character.isUpperCase(mChars[ch]); @@ -304,9 +320,11 @@ public class CharacterPerfTest { } @Test - public void timeIsWhitespace() { + @Parameters(method = "getData") + public void timeIsWhitespace(CharacterSet characterSet, Overload overload) { + setUp(characterSet); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); - if (mOverload == Overload.CHAR) { + if (overload == Overload.CHAR) { while (state.keepRunning()) { for (int ch = 0; ch < 65536; ++ch) { Character.isWhitespace(mChars[ch]); @@ -322,9 +340,11 @@ public class CharacterPerfTest { } @Test - public void timeToLowerCase() { + @Parameters(method = "getData") + public void timeToLowerCase(CharacterSet characterSet, Overload overload) { + setUp(characterSet); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); - if (mOverload == Overload.CHAR) { + if (overload == Overload.CHAR) { while (state.keepRunning()) { for (int ch = 0; ch < 65536; ++ch) { Character.toLowerCase(mChars[ch]); @@ -340,9 +360,11 @@ public class CharacterPerfTest { } @Test - public void timeToUpperCase() { + @Parameters(method = "getData") + public void timeToUpperCase(CharacterSet characterSet, Overload overload) { + setUp(characterSet); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); - if (mOverload == Overload.CHAR) { + if (overload == Overload.CHAR) { while (state.keepRunning()) { for (int ch = 0; ch < 65536; ++ch) { Character.toUpperCase(mChars[ch]); diff --git a/apct-tests/perftests/core/src/android/libcore/regression/CharsetForNamePerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/CharsetForNamePerfTest.java index 603b182e7c36..8da13a9b7f91 100644 --- a/apct-tests/perftests/core/src/android/libcore/regression/CharsetForNamePerfTest.java +++ b/apct-tests/perftests/core/src/android/libcore/regression/CharsetForNamePerfTest.java @@ -20,44 +20,40 @@ import android.perftests.utils.BenchmarkState; import android.perftests.utils.PerfStatusReporter; import android.test.suitebuilder.annotation.LargeTest; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; + import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; import java.nio.charset.Charset; -import java.util.Arrays; -import java.util.Collection; -@RunWith(Parameterized.class) +@RunWith(JUnitParamsRunner.class) @LargeTest public class CharsetForNamePerfTest { @Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); - @Parameterized.Parameters(name = "mCharsetName({0})") - public static Collection<Object[]> data() { - return Arrays.asList( - new Object[][] { - {"UTF-16"}, - {"UTF-8"}, - {"UTF8"}, - {"ISO-8859-1"}, - {"8859_1"}, - {"ISO-8859-2"}, - {"8859_2"}, - {"US-ASCII"}, - {"ASCII"}, - }); + public static String[] charsetNames() { + return new String[] { + "UTF-16", + "UTF-8", + "UTF8", + "ISO-8859-1", + "8859_1", + "ISO-8859-2", + "8859_2", + "US-ASCII", + "ASCII", + }; } - @Parameterized.Parameter(0) - public String mCharsetName; - @Test - public void timeCharsetForName() throws Exception { + @Parameters(method = "charsetNames") + public void timeCharsetForName(String charsetName) throws Exception { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - Charset.forName(mCharsetName); + Charset.forName(charsetName); } } } diff --git a/apct-tests/perftests/core/src/android/libcore/regression/CharsetPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/CharsetPerfTest.java index 437d186834e0..048c50f044c8 100644 --- a/apct-tests/perftests/core/src/android/libcore/regression/CharsetPerfTest.java +++ b/apct-tests/perftests/core/src/android/libcore/regression/CharsetPerfTest.java @@ -20,22 +20,22 @@ import android.perftests.utils.BenchmarkState; import android.perftests.utils.PerfStatusReporter; import android.test.suitebuilder.annotation.LargeTest; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; + import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; import java.util.Collection; -@RunWith(Parameterized.class) +@RunWith(JUnitParamsRunner.class) @LargeTest public class CharsetPerfTest { @Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); - @Parameters(name = "mLength({0}), mName({1})") - public static Collection<Object[]> data() { + public static Collection<Object[]> getData() { return Arrays.asList( new Object[][] { {1, "UTF-16"}, @@ -86,24 +86,20 @@ public class CharsetPerfTest { }); } - @Parameterized.Parameter(0) - public int mLength; - - @Parameterized.Parameter(1) - public String mName; - @Test - public void time_new_String_BString() throws Exception { - byte[] bytes = makeBytes(makeString(mLength)); + @Parameters(method = "getData") + public void time_new_String_BString(int length, String name) throws Exception { + byte[] bytes = makeBytes(makeString(length)); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - new String(bytes, mName); + new String(bytes, name); } } @Test - public void time_new_String_BII() throws Exception { - byte[] bytes = makeBytes(makeString(mLength)); + @Parameters(method = "getData") + public void time_new_String_BII(int length, String name) throws Exception { + byte[] bytes = makeBytes(makeString(length)); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { new String(bytes, 0, bytes.length); @@ -111,20 +107,22 @@ public class CharsetPerfTest { } @Test - public void time_new_String_BIIString() throws Exception { - byte[] bytes = makeBytes(makeString(mLength)); + @Parameters(method = "getData") + public void time_new_String_BIIString(int length, String name) throws Exception { + byte[] bytes = makeBytes(makeString(length)); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - new String(bytes, 0, bytes.length, mName); + new String(bytes, 0, bytes.length, name); } } @Test - public void time_String_getBytes() throws Exception { - String string = makeString(mLength); + @Parameters(method = "getData") + public void time_String_getBytes(int length, String name) throws Exception { + String string = makeString(length); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - string.getBytes(mName); + string.getBytes(name); } } diff --git a/apct-tests/perftests/core/src/android/libcore/regression/CipherPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/CipherPerfTest.java index 15c27f2366e1..42b058815bfe 100644 --- a/apct-tests/perftests/core/src/android/libcore/regression/CipherPerfTest.java +++ b/apct-tests/perftests/core/src/android/libcore/regression/CipherPerfTest.java @@ -20,11 +20,12 @@ import android.perftests.utils.BenchmarkState; import android.perftests.utils.PerfStatusReporter; import android.test.suitebuilder.annotation.LargeTest; -import org.junit.Before; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; + import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; import java.security.spec.AlgorithmParameterSpec; import java.util.ArrayList; @@ -42,17 +43,13 @@ import javax.crypto.spec.IvParameterSpec; * Cipher benchmarks. Only runs on AES currently because of the combinatorial explosion of the test * as it stands. */ -@RunWith(Parameterized.class) +@RunWith(JUnitParamsRunner.class) @LargeTest public class CipherPerfTest { @Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); - @Parameterized.Parameters( - name = - "mMode({0}), mPadding({1}), mKeySize({2}), mInputSize({3})," - + " mImplementation({4})") - public static Collection cases() { - int[] mKeySizes = new int[] {128, 192, 256}; + public static Collection getCases() { + int[] keySizes = new int[] {128, 192, 256}; int[] inputSizes = new int[] {16, 32, 64, 128, 1024, 8192}; final List<Object[]> params = new ArrayList<>(); for (Mode mode : Mode.values()) { @@ -71,11 +68,11 @@ public class CipherPerfTest { && implementation == Implementation.OpenSSL) { continue; } - for (int mKeySize : mKeySizes) { + for (int keySize : keySizes) { for (int inputSize : inputSizes) { params.add( new Object[] { - mode, padding, mKeySize, inputSize, implementation + mode, padding, keySize, inputSize, implementation }); } } @@ -107,9 +104,6 @@ public class CipherPerfTest { AES, }; - @Parameterized.Parameter(0) - public Mode mMode; - public enum Mode { CBC, CFB, @@ -118,23 +112,11 @@ public class CipherPerfTest { OFB, }; - @Parameterized.Parameter(1) - public Padding mPadding; - public enum Padding { NOPADDING, PKCS1PADDING, }; - @Parameterized.Parameter(2) - public int mKeySize; - - @Parameterized.Parameter(3) - public int mInputSize; - - @Parameterized.Parameter(4) - public Implementation mImplementation; - public enum Implementation { OpenSSL, BouncyCastle @@ -156,21 +138,20 @@ public class CipherPerfTest { private AlgorithmParameterSpec mSpec; - @Before - public void setUp() throws Exception { - mCipherAlgorithm = - mAlgorithm.toString() + "/" + mMode.toString() + "/" + mPadding.toString(); + public void setUp(Mode mode, Padding padding, int keySize, Implementation implementation) + throws Exception { + mCipherAlgorithm = mAlgorithm.toString() + "/" + mode.toString() + "/" + padding.toString(); String mKeyAlgorithm = mAlgorithm.toString(); - mKey = sKeySizes.get(mKeySize); + mKey = sKeySizes.get(keySize); if (mKey == null) { KeyGenerator generator = KeyGenerator.getInstance(mKeyAlgorithm); - generator.init(mKeySize); + generator.init(keySize); mKey = generator.generateKey(); - sKeySizes.put(mKeySize, mKey); + sKeySizes.put(keySize, mKey); } - switch (mImplementation) { + switch (implementation) { case OpenSSL: mProviderName = "AndroidOpenSSL"; break; @@ -178,10 +159,10 @@ public class CipherPerfTest { mProviderName = "BC"; break; default: - throw new RuntimeException(mImplementation.toString()); + throw new RuntimeException(implementation.toString()); } - if (mMode != Mode.ECB) { + if (mode != Mode.ECB) { mSpec = new IvParameterSpec(IV); } @@ -193,18 +174,26 @@ public class CipherPerfTest { } @Test - public void timeEncrypt() throws Exception { + @Parameters(method = "getCases") + public void timeEncrypt( + Mode mode, Padding padding, int keySize, int inputSize, Implementation implementation) + throws Exception { + setUp(mode, padding, keySize, implementation); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - mCipherEncrypt.doFinal(DATA, 0, mInputSize, mOutput); + mCipherEncrypt.doFinal(DATA, 0, inputSize, mOutput); } } @Test - public void timeDecrypt() throws Exception { + @Parameters(method = "getCases") + public void timeDecrypt( + Mode mode, Padding padding, int keySize, int inputSize, Implementation implementation) + throws Exception { + setUp(mode, padding, keySize, implementation); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - mCipherDecrypt.doFinal(DATA, 0, mInputSize, mOutput); + mCipherDecrypt.doFinal(DATA, 0, inputSize, mOutput); } } } diff --git a/apct-tests/perftests/core/src/android/libcore/regression/CollectionsPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/CollectionsPerfTest.java index a89efffcdd1f..69197c3325f4 100644 --- a/apct-tests/perftests/core/src/android/libcore/regression/CollectionsPerfTest.java +++ b/apct-tests/perftests/core/src/android/libcore/regression/CollectionsPerfTest.java @@ -20,11 +20,12 @@ import android.perftests.utils.BenchmarkState; import android.perftests.utils.PerfStatusReporter; import android.test.suitebuilder.annotation.LargeTest; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; + import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; import java.util.ArrayList; import java.util.Arrays; @@ -35,19 +36,15 @@ import java.util.List; import java.util.Random; import java.util.Vector; -@RunWith(Parameterized.class) +@RunWith(JUnitParamsRunner.class) @LargeTest public class CollectionsPerfTest { @Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); - @Parameters(name = "mArrayListLength({0})") - public static Collection<Object[]> data() { + public static Collection<Object[]> getData() { return Arrays.asList(new Object[][] {{4}, {16}, {64}, {256}, {1024}}); } - @Parameterized.Parameter(0) - public int arrayListLength; - public static Comparator<Integer> REVERSE = new Comparator<Integer>() { @Override @@ -59,7 +56,8 @@ public class CollectionsPerfTest { }; @Test - public void timeSort_arrayList() throws Exception { + @Parameters(method = "getData") + public void timeSort_arrayList(int arrayListLength) throws Exception { List<Integer> input = buildList(arrayListLength, ArrayList.class); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { @@ -68,7 +66,8 @@ public class CollectionsPerfTest { } @Test - public void timeSortWithComparator_arrayList() throws Exception { + @Parameters(method = "getData") + public void timeSortWithComparator_arrayList(int arrayListLength) throws Exception { List<Integer> input = buildList(arrayListLength, ArrayList.class); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { @@ -77,7 +76,8 @@ public class CollectionsPerfTest { } @Test - public void timeSort_vector() throws Exception { + @Parameters(method = "getData") + public void timeSort_vector(int arrayListLength) throws Exception { List<Integer> input = buildList(arrayListLength, Vector.class); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { @@ -86,7 +86,8 @@ public class CollectionsPerfTest { } @Test - public void timeSortWithComparator_vector() throws Exception { + @Parameters(method = "getData") + public void timeSortWithComparator_vector(int arrayListLength) throws Exception { List<Integer> input = buildList(arrayListLength, Vector.class); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { diff --git a/apct-tests/perftests/core/src/android/libcore/regression/EqualsHashCodePerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/EqualsHashCodePerfTest.java index 4ff3ba5b0aaa..839120336697 100644 --- a/apct-tests/perftests/core/src/android/libcore/regression/EqualsHashCodePerfTest.java +++ b/apct-tests/perftests/core/src/android/libcore/regression/EqualsHashCodePerfTest.java @@ -20,11 +20,12 @@ import android.perftests.utils.BenchmarkState; import android.perftests.utils.PerfStatusReporter; import android.test.suitebuilder.annotation.LargeTest; -import org.junit.Before; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; + import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; import java.net.URI; import java.net.URL; @@ -32,39 +33,39 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; -@RunWith(Parameterized.class) +@RunWith(JUnitParamsRunner.class) @LargeTest public final class EqualsHashCodePerfTest { @Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); private enum Type { URI() { - @Override Object newInstance(String text) throws Exception { + @Override + Object newInstance(String text) throws Exception { return new URI(text); } }, URL() { - @Override Object newInstance(String text) throws Exception { + @Override + Object newInstance(String text) throws Exception { return new URL(text); } }; + abstract Object newInstance(String text) throws Exception; } - private static final String QUERY = "%E0%AE%A8%E0%AE%BE%E0%AE%AE%E0%AF%8D+%E0%AE%AE%E0%AF%81%E0%AE%95%E0%AF%8D%E0%AE%95%E0%AE%BF%E0%AE%AF%E0%AE%AE%E0%AE%BE%E0%AE%A9%2C+%E0%AE%9A%E0%AF%81%E0%AE%B5%E0%AE%BE%E0%AE%B0%E0%AE%B8%E0%AF%8D%E0%AE%AF%E0%AE%AE%E0%AE%BE%E0%AE%A9+%E0%AE%87%E0%AE%B0%E0%AF%81%E0%AE%AA%E0%AF%8D%E0%AE%AA%E0%AF%87%E0%AE%BE%E0%AE%AE%E0%AF%8D%2C+%E0%AE%86%E0%AE%A9%E0%AE%BE%E0%AE%B2%E0%AF%8D+%E0%AE%9A%E0%AE%BF%E0%AE%B2+%E0%AE%A8%E0%AF%87%E0%AE%B0%E0%AE%99%E0%AF%8D%E0%AE%95%E0%AE%B3%E0%AE%BF%E0%AE%B2%E0%AF%8D+%E0%AE%9A%E0%AF%82%E0%AE%B4%E0%AF%8D%E0%AE%A8%E0%AE%BF%E0%AE%B2%E0%AF%88+%E0%AE%8F%E0%AE%B1%E0%AF%8D%E0%AE%AA%E0%AE%9F%E0%AF%81%E0%AE%AE%E0%AF%8D+%E0%AE%8E%E0%AE%A9%E0%AF%8D%E0%AE%AA%E0%AE%A4%E0%AE%BE%E0%AE%B2%E0%AF%8D+%E0%AE%AA%E0%AE%A3%E0%AE%BF%E0%AE%AF%E0%AF%88%E0%AE%AF%E0%AF%81%E0%AE%AE%E0%AF%8D+%E0%AE%B5%E0%AE%B2%E0%AE%BF+%E0%AE%85%E0%AE%B5%E0%AE%B0%E0%AF%88+%E0%AE%9A%E0%AE%BF%E0%AE%B2+%E0%AE%AA%E0%AF%86%E0%AE%B0%E0%AE%BF%E0%AE%AF+%E0%AE%95%E0%AF%86%E0%AE%BE%E0%AE%B3%E0%AF%8D%E0%AE%AE%E0%AF%81%E0%AE%A4%E0%AE%B2%E0%AF%8D+%E0%AE%AE%E0%AF%81%E0%AE%9F%E0%AE%BF%E0%AE%AF%E0%AF%81%E0%AE%AE%E0%AF%8D.+%E0%AE%85%E0%AE%A4%E0%AF%81+%E0%AE%9A%E0%AE%BF%E0%AE%B2+%E0%AE%A8%E0%AE%A9%E0%AF%8D%E0%AE%AE%E0%AF%88%E0%AE%95%E0%AE%B3%E0%AF%88+%E0%AE%AA%E0%AF%86%E0%AE%B1+%E0%AE%A4%E0%AE%B5%E0%AE%BF%E0%AE%B0%2C+%E0%AE%8E%E0%AE%AA%E0%AF%8D%E0%AE%AA%E0%AF%87%E0%AE%BE%E0%AE%A4%E0%AF%81%E0%AE%AE%E0%AF%8D+%E0%AE%89%E0%AE%B4%E0%AF%88%E0%AE%95%E0%AF%8D%E0%AE%95+%E0%AE%89%E0%AE%9F%E0%AE%B1%E0%AF%8D%E0%AE%AA%E0%AE%AF%E0%AE%BF%E0%AE%B1%E0%AF%8D%E0%AE%9A%E0%AE%BF+%E0%AE%AE%E0%AF%87%E0%AE%B1%E0%AF%8D%E0%AE%95%E0%AF%86%E0%AE%BE%E0%AE%B3%E0%AF%8D%E0%AE%95%E0%AE%BF%E0%AE%B1%E0%AE%A4%E0%AF%81+%E0%AE%8E%E0%AE%99%E0%AF%8D%E0%AE%95%E0%AE%B3%E0%AF%81%E0%AE%95%E0%AF%8D%E0%AE%95%E0%AF%81+%E0%AE%87%E0%AE%A4%E0%AF%81+%E0%AE%92%E0%AE%B0%E0%AF%81+%E0%AE%9A%E0%AE%BF%E0%AE%B1%E0%AE%BF%E0%AE%AF+%E0%AE%89%E0%AE%A4%E0%AE%BE%E0%AE%B0%E0%AE%A3%E0%AE%AE%E0%AF%8D%2C+%E0%AE%8E%E0%AE%9F%E0%AF%81%E0%AE%95%E0%AF%8D%E0%AE%95.+%E0%AE%B0%E0%AE%AF%E0%AE%BF%E0%AE%B2%E0%AF%8D+%E0%AE%8E%E0%AE%A8%E0%AF%8D%E0%AE%A4+%E0%AE%B5%E0%AE%BF%E0%AE%B3%E0%AF%88%E0%AE%B5%E0%AE%BE%E0%AE%95+%E0%AE%87%E0%AE%A9%E0%AF%8D%E0%AE%AA%E0%AE%AE%E0%AF%8D+%E0%AE%86%E0%AE%A9%E0%AF%8D%E0%AE%B2%E0%AF%88%E0%AE%A9%E0%AF%8D+%E0%AE%AA%E0%AE%AF%E0%AE%A9%E0%AF%8D%E0%AE%AA%E0%AE%BE%E0%AE%9F%E0%AF%81%E0%AE%95%E0%AE%B3%E0%AF%8D+%E0%AE%87%E0%AE%B0%E0%AF%81%E0%AE%95%E0%AF%8D%E0%AE%95+%E0%AE%B5%E0%AF%87%E0%AE%A3%E0%AF%8D%E0%AE%9F%E0%AF%81%E0%AE%AE%E0%AF%8D+%E0%AE%A4%E0%AE%AF%E0%AE%BE%E0%AE%B0%E0%AE%BF%E0%AE%95%E0%AF%8D%E0%AE%95%E0%AF%81%E0%AE%AE%E0%AF%8D+%E0%AE%A4%E0%AE%B5%E0%AE%B1%E0%AF%81+%E0%AE%95%E0%AE%A3%E0%AF%8D%E0%AE%9F%E0%AF%81%E0%AE%AA%E0%AE%BF%E0%AE%9F%E0%AE%BF%E0%AE%95%E0%AF%8D%E0%AE%95+%E0%AE%B5%E0%AE%B0%E0%AF%81%E0%AE%AE%E0%AF%8D+%E0%AE%A8%E0%AE%BE%E0%AE%AE%E0%AF%8D+%E0%AE%A4%E0%AE%B1%E0%AF%8D%E0%AE%AA%E0%AF%87%E0%AE%BE%E0%AE%A4%E0%AF%81+%E0%AE%87%E0%AE%B0%E0%AF%81%E0%AE%95%E0%AF%8D%E0%AE%95%E0%AE%BF%E0%AE%B1%E0%AF%87%E0%AE%BE%E0%AE%AE%E0%AF%8D.+%E0%AE%87%E0%AE%A8%E0%AF%8D%E0%AE%A4+%E0%AE%A8%E0%AE%BF%E0%AE%95%E0%AE%B4%E0%AF%8D%E0%AE%B5%E0%AF%81%E0%AE%95%E0%AE%B3%E0%AE%BF%E0%AE%B2%E0%AF%8D+%E0%AE%9A%E0%AF%86%E0%AE%AF%E0%AF%8D%E0%AE%A4%E0%AE%AA%E0%AE%BF%E0%AE%A9%E0%AF%8D+%E0%AE%85%E0%AE%AE%E0%AF%88%E0%AE%AA%E0%AF%8D%E0%AE%AA%E0%AE%BF%E0%AE%A9%E0%AF%8D+%E0%AE%95%E0%AE%A3%E0%AE%95%E0%AF%8D%E0%AE%95%E0%AF%81%2C+%E0%AE%85%E0%AE%B5%E0%AE%B0%E0%AF%8D%E0%AE%95%E0%AE%B3%E0%AF%8D+%E0%AE%A4%E0%AE%B5%E0%AE%B1%E0%AF%81+%E0%AE%B5%E0%AE%BF%E0%AE%9F%E0%AF%8D%E0%AE%9F%E0%AF%81+quae+%E0%AE%AA%E0%AE%9F%E0%AF%8D%E0%AE%9F%E0%AE%B1%E0%AF%88+%E0%AE%A8%E0%AF%80%E0%AE%99%E0%AF%8D%E0%AE%95%E0%AE%B3%E0%AF%8D+%E0%AE%AA%E0%AE%B0%E0%AE%BF%E0%AE%A8%E0%AF%8D%E0%AE%A4%E0%AF%81%E0%AE%B0%E0%AF%88%E0%AE%95%E0%AF%8D%E0%AE%95%E0%AE%BF%E0%AE%B1%E0%AF%87%E0%AE%BE%E0%AE%AE%E0%AF%8D+%E0%AE%AE%E0%AF%86%E0%AE%A9%E0%AF%8D%E0%AE%AE%E0%AF%88%E0%AE%AF%E0%AE%BE%E0%AE%95+%E0%AE%AE%E0%AE%BE%E0%AE%B1%E0%AF%81%E0%AE%AE%E0%AF%8D"; + private static final String QUERY = + "%E0%AE%A8%E0%AE%BE%E0%AE%AE%E0%AF%8D+%E0%AE%AE%E0%AF%81%E0%AE%95%E0%AF%8D%E0%AE%95%E0%AE%BF%E0%AE%AF%E0%AE%AE%E0%AE%BE%E0%AE%A9%2C+%E0%AE%9A%E0%AF%81%E0%AE%B5%E0%AE%BE%E0%AE%B0%E0%AE%B8%E0%AF%8D%E0%AE%AF%E0%AE%AE%E0%AE%BE%E0%AE%A9+%E0%AE%87%E0%AE%B0%E0%AF%81%E0%AE%AA%E0%AF%8D%E0%AE%AA%E0%AF%87%E0%AE%BE%E0%AE%AE%E0%AF%8D%2C+%E0%AE%86%E0%AE%A9%E0%AE%BE%E0%AE%B2%E0%AF%8D+%E0%AE%9A%E0%AE%BF%E0%AE%B2+%E0%AE%A8%E0%AF%87%E0%AE%B0%E0%AE%99%E0%AF%8D%E0%AE%95%E0%AE%B3%E0%AE%BF%E0%AE%B2%E0%AF%8D+%E0%AE%9A%E0%AF%82%E0%AE%B4%E0%AF%8D%E0%AE%A8%E0%AE%BF%E0%AE%B2%E0%AF%88+%E0%AE%8F%E0%AE%B1%E0%AF%8D%E0%AE%AA%E0%AE%9F%E0%AF%81%E0%AE%AE%E0%AF%8D+%E0%AE%8E%E0%AE%A9%E0%AF%8D%E0%AE%AA%E0%AE%A4%E0%AE%BE%E0%AE%B2%E0%AF%8D+%E0%AE%AA%E0%AE%A3%E0%AE%BF%E0%AE%AF%E0%AF%88%E0%AE%AF%E0%AF%81%E0%AE%AE%E0%AF%8D+%E0%AE%B5%E0%AE%B2%E0%AE%BF+%E0%AE%85%E0%AE%B5%E0%AE%B0%E0%AF%88+%E0%AE%9A%E0%AE%BF%E0%AE%B2+%E0%AE%AA%E0%AF%86%E0%AE%B0%E0%AE%BF%E0%AE%AF+%E0%AE%95%E0%AF%86%E0%AE%BE%E0%AE%B3%E0%AF%8D%E0%AE%AE%E0%AF%81%E0%AE%A4%E0%AE%B2%E0%AF%8D+%E0%AE%AE%E0%AF%81%E0%AE%9F%E0%AE%BF%E0%AE%AF%E0%AF%81%E0%AE%AE%E0%AF%8D.+%E0%AE%85%E0%AE%A4%E0%AF%81+%E0%AE%9A%E0%AE%BF%E0%AE%B2+%E0%AE%A8%E0%AE%A9%E0%AF%8D%E0%AE%AE%E0%AF%88%E0%AE%95%E0%AE%B3%E0%AF%88+%E0%AE%AA%E0%AF%86%E0%AE%B1+%E0%AE%A4%E0%AE%B5%E0%AE%BF%E0%AE%B0%2C+%E0%AE%8E%E0%AE%AA%E0%AF%8D%E0%AE%AA%E0%AF%87%E0%AE%BE%E0%AE%A4%E0%AF%81%E0%AE%AE%E0%AF%8D+%E0%AE%89%E0%AE%B4%E0%AF%88%E0%AE%95%E0%AF%8D%E0%AE%95+%E0%AE%89%E0%AE%9F%E0%AE%B1%E0%AF%8D%E0%AE%AA%E0%AE%AF%E0%AE%BF%E0%AE%B1%E0%AF%8D%E0%AE%9A%E0%AE%BF+%E0%AE%AE%E0%AF%87%E0%AE%B1%E0%AF%8D%E0%AE%95%E0%AF%86%E0%AE%BE%E0%AE%B3%E0%AF%8D%E0%AE%95%E0%AE%BF%E0%AE%B1%E0%AE%A4%E0%AF%81+%E0%AE%8E%E0%AE%99%E0%AF%8D%E0%AE%95%E0%AE%B3%E0%AF%81%E0%AE%95%E0%AF%8D%E0%AE%95%E0%AF%81+%E0%AE%87%E0%AE%A4%E0%AF%81+%E0%AE%92%E0%AE%B0%E0%AF%81+%E0%AE%9A%E0%AE%BF%E0%AE%B1%E0%AE%BF%E0%AE%AF+%E0%AE%89%E0%AE%A4%E0%AE%BE%E0%AE%B0%E0%AE%A3%E0%AE%AE%E0%AF%8D%2C+%E0%AE%8E%E0%AE%9F%E0%AF%81%E0%AE%95%E0%AF%8D%E0%AE%95.+%E0%AE%B0%E0%AE%AF%E0%AE%BF%E0%AE%B2%E0%AF%8D+%E0%AE%8E%E0%AE%A8%E0%AF%8D%E0%AE%A4+%E0%AE%B5%E0%AE%BF%E0%AE%B3%E0%AF%88%E0%AE%B5%E0%AE%BE%E0%AE%95+%E0%AE%87%E0%AE%A9%E0%AF%8D%E0%AE%AA%E0%AE%AE%E0%AF%8D+%E0%AE%86%E0%AE%A9%E0%AF%8D%E0%AE%B2%E0%AF%88%E0%AE%A9%E0%AF%8D+%E0%AE%AA%E0%AE%AF%E0%AE%A9%E0%AF%8D%E0%AE%AA%E0%AE%BE%E0%AE%9F%E0%AF%81%E0%AE%95%E0%AE%B3%E0%AF%8D+%E0%AE%87%E0%AE%B0%E0%AF%81%E0%AE%95%E0%AF%8D%E0%AE%95+%E0%AE%B5%E0%AF%87%E0%AE%A3%E0%AF%8D%E0%AE%9F%E0%AF%81%E0%AE%AE%E0%AF%8D+%E0%AE%A4%E0%AE%AF%E0%AE%BE%E0%AE%B0%E0%AE%BF%E0%AE%95%E0%AF%8D%E0%AE%95%E0%AF%81%E0%AE%AE%E0%AF%8D+%E0%AE%A4%E0%AE%B5%E0%AE%B1%E0%AF%81+%E0%AE%95%E0%AE%A3%E0%AF%8D%E0%AE%9F%E0%AF%81%E0%AE%AA%E0%AE%BF%E0%AE%9F%E0%AE%BF%E0%AE%95%E0%AF%8D%E0%AE%95+%E0%AE%B5%E0%AE%B0%E0%AF%81%E0%AE%AE%E0%AF%8D+%E0%AE%A8%E0%AE%BE%E0%AE%AE%E0%AF%8D+%E0%AE%A4%E0%AE%B1%E0%AF%8D%E0%AE%AA%E0%AF%87%E0%AE%BE%E0%AE%A4%E0%AF%81+%E0%AE%87%E0%AE%B0%E0%AF%81%E0%AE%95%E0%AF%8D%E0%AE%95%E0%AE%BF%E0%AE%B1%E0%AF%87%E0%AE%BE%E0%AE%AE%E0%AF%8D.+%E0%AE%87%E0%AE%A8%E0%AF%8D%E0%AE%A4+%E0%AE%A8%E0%AE%BF%E0%AE%95%E0%AE%B4%E0%AF%8D%E0%AE%B5%E0%AF%81%E0%AE%95%E0%AE%B3%E0%AE%BF%E0%AE%B2%E0%AF%8D+%E0%AE%9A%E0%AF%86%E0%AE%AF%E0%AF%8D%E0%AE%A4%E0%AE%AA%E0%AE%BF%E0%AE%A9%E0%AF%8D+%E0%AE%85%E0%AE%AE%E0%AF%88%E0%AE%AA%E0%AF%8D%E0%AE%AA%E0%AE%BF%E0%AE%A9%E0%AF%8D+%E0%AE%95%E0%AE%A3%E0%AE%95%E0%AF%8D%E0%AE%95%E0%AF%81%2C+%E0%AE%85%E0%AE%B5%E0%AE%B0%E0%AF%8D%E0%AE%95%E0%AE%B3%E0%AF%8D+%E0%AE%A4%E0%AE%B5%E0%AE%B1%E0%AF%81+%E0%AE%B5%E0%AE%BF%E0%AE%9F%E0%AF%8D%E0%AE%9F%E0%AF%81+quae+%E0%AE%AA%E0%AE%9F%E0%AF%8D%E0%AE%9F%E0%AE%B1%E0%AF%88+%E0%AE%A8%E0%AF%80%E0%AE%99%E0%AF%8D%E0%AE%95%E0%AE%B3%E0%AF%8D+%E0%AE%AA%E0%AE%B0%E0%AE%BF%E0%AE%A8%E0%AF%8D%E0%AE%A4%E0%AF%81%E0%AE%B0%E0%AF%88%E0%AE%95%E0%AF%8D%E0%AE%95%E0%AE%BF%E0%AE%B1%E0%AF%87%E0%AE%BE%E0%AE%AE%E0%AF%8D+%E0%AE%AE%E0%AF%86%E0%AE%A9%E0%AF%8D%E0%AE%AE%E0%AF%88%E0%AE%AF%E0%AE%BE%E0%AE%95+%E0%AE%AE%E0%AE%BE%E0%AE%B1%E0%AF%81%E0%AE%AE%E0%AF%8D"; - @Parameterized.Parameters(name = "mType({0})") - public static Collection cases() { + public static Collection getCases() { final List<Object[]> params = new ArrayList<>(); for (Type type : Type.values()) { - params.add(new Object[]{type}); + params.add(new Object[] {type}); } return params; } - @Parameterized.Parameter(0) - public Type mType; - Object mA1; Object mA2; Object mB1; @@ -73,20 +74,13 @@ public final class EqualsHashCodePerfTest { Object mC1; Object mC2; - @Before - public void setUp() throws Exception { - mA1 = mType.newInstance("https://mail.google.com/mail/u/0/?shva=1#inbox"); - mA2 = mType.newInstance("https://mail.google.com/mail/u/0/?shva=1#inbox"); - mB1 = mType.newInstance("http://developer.android.com/reference/java/net/URI.html"); - mB2 = mType.newInstance("http://developer.android.com/reference/java/net/URI.html"); - - mC1 = mType.newInstance("http://developer.android.com/query?q=" + QUERY); - // Replace the very last char. - mC2 = mType.newInstance("http://developer.android.com/query?q=" + QUERY.substring(0, QUERY.length() - 3) + "%AF"); - } - @Test - public void timeEquals() { + @Parameters(method = "getCases") + public void timeEquals(Type type) throws Exception { + mA1 = type.newInstance("https://mail.google.com/mail/u/0/?shva=1#inbox"); + mA2 = type.newInstance("https://mail.google.com/mail/u/0/?shva=1#inbox"); + mB1 = type.newInstance("http://developer.android.com/reference/java/net/URI.html"); + mB2 = type.newInstance("http://developer.android.com/reference/java/net/URI.html"); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { mA1.equals(mB1); @@ -96,7 +90,10 @@ public final class EqualsHashCodePerfTest { } @Test - public void timeHashCode() { + @Parameters(method = "getCases") + public void timeHashCode(Type type) throws Exception { + mA1 = type.newInstance("https://mail.google.com/mail/u/0/?shva=1#inbox"); + mB1 = type.newInstance("http://developer.android.com/reference/java/net/URI.html"); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { mA1.hashCode(); @@ -105,7 +102,15 @@ public final class EqualsHashCodePerfTest { } @Test - public void timeEqualsWithHeavilyEscapedComponent() { + @Parameters(method = "getCases") + public void timeEqualsWithHeavilyEscapedComponent(Type type) throws Exception { + mC1 = type.newInstance("http://developer.android.com/query?q=" + QUERY); + // Replace the very last char. + mC2 = + type.newInstance( + "http://developer.android.com/query?q=" + + QUERY.substring(0, QUERY.length() - 3) + + "%AF"); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { mC1.equals(mC2); diff --git a/apct-tests/perftests/core/src/android/libcore/regression/KeyPairGeneratorPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/KeyPairGeneratorPerfTest.java index 6fe9059cb3de..80c448732b59 100644 --- a/apct-tests/perftests/core/src/android/libcore/regression/KeyPairGeneratorPerfTest.java +++ b/apct-tests/perftests/core/src/android/libcore/regression/KeyPairGeneratorPerfTest.java @@ -20,26 +20,24 @@ import android.perftests.utils.BenchmarkState; import android.perftests.utils.PerfStatusReporter; import android.test.suitebuilder.annotation.LargeTest; -import org.junit.Before; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; + import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; import java.security.KeyPair; import java.security.KeyPairGenerator; -import java.security.SecureRandom; import java.util.Arrays; import java.util.Collection; -@RunWith(Parameterized.class) +@RunWith(JUnitParamsRunner.class) @LargeTest public class KeyPairGeneratorPerfTest { @Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); - @Parameters(name = "mAlgorithm={0}, mImplementation={1}") - public static Collection<Object[]> data() { + public static Collection<Object[]> getData() { return Arrays.asList( new Object[][] { {Algorithm.RSA, Implementation.BouncyCastle}, @@ -48,12 +46,6 @@ public class KeyPairGeneratorPerfTest { }); } - @Parameterized.Parameter(0) - public Algorithm mAlgorithm; - - @Parameterized.Parameter(1) - public Implementation mImplementation; - public enum Algorithm { RSA, DSA, @@ -66,26 +58,25 @@ public class KeyPairGeneratorPerfTest { private String mGeneratorAlgorithm; private KeyPairGenerator mGenerator; - private SecureRandom mRandom; - @Before - public void setUp() throws Exception { - this.mGeneratorAlgorithm = mAlgorithm.toString(); + public void setUp(Algorithm algorithm, Implementation implementation) throws Exception { + this.mGeneratorAlgorithm = algorithm.toString(); final String provider; - if (mImplementation == Implementation.BouncyCastle) { + if (implementation == Implementation.BouncyCastle) { provider = "BC"; } else { provider = "AndroidOpenSSL"; } this.mGenerator = KeyPairGenerator.getInstance(mGeneratorAlgorithm, provider); - this.mRandom = SecureRandom.getInstance("SHA1PRNG"); this.mGenerator.initialize(1024); } @Test - public void time() throws Exception { + @Parameters(method = "getData") + public void time(Algorithm algorithm, Implementation implementation) throws Exception { + setUp(algorithm, implementation); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { KeyPair keyPair = mGenerator.generateKeyPair(); diff --git a/apct-tests/perftests/core/src/android/libcore/regression/LoopingBackwardsPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/LoopingBackwardsPerfTest.java index 414764d292b8..c9b0cbe1bedb 100644 --- a/apct-tests/perftests/core/src/android/libcore/regression/LoopingBackwardsPerfTest.java +++ b/apct-tests/perftests/core/src/android/libcore/regression/LoopingBackwardsPerfTest.java @@ -20,11 +20,12 @@ import android.perftests.utils.BenchmarkState; import android.perftests.utils.PerfStatusReporter; import android.test.suitebuilder.annotation.LargeTest; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; + import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; import java.util.Collection; @@ -34,36 +35,34 @@ import java.util.Collection; * * @author Kevin Bourrillion */ -@RunWith(Parameterized.class) +@RunWith(JUnitParamsRunner.class) @LargeTest public class LoopingBackwardsPerfTest { @Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); - @Parameters(name = "mMax={0}") - public static Collection<Object[]> data() { + public static Collection<Object[]> getData() { return Arrays.asList(new Object[][] {{2}, {20}, {2000}, {20000000}}); } - @Parameterized.Parameter(0) - public int mMax; - @Test - public void timeForwards() { + @Parameters(method = "getData") + public void timeForwards(int max) { int fake = 0; BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - for (int j = 0; j < mMax; j++) { + for (int j = 0; j < max; j++) { fake += j; } } } @Test - public void timeBackwards() { + @Parameters(method = "getData") + public void timeBackwards(int max) { int fake = 0; BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - for (int j = mMax - 1; j >= 0; j--) { + for (int j = max - 1; j >= 0; j--) { fake += j; } } diff --git a/apct-tests/perftests/core/src/android/libcore/regression/MessageDigestPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/MessageDigestPerfTest.java index 279681bc0d15..2dc947a613d2 100644 --- a/apct-tests/perftests/core/src/android/libcore/regression/MessageDigestPerfTest.java +++ b/apct-tests/perftests/core/src/android/libcore/regression/MessageDigestPerfTest.java @@ -20,24 +20,24 @@ import android.perftests.utils.BenchmarkState; import android.perftests.utils.PerfStatusReporter; import android.test.suitebuilder.annotation.LargeTest; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; + import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; import java.nio.ByteBuffer; import java.security.MessageDigest; import java.util.Arrays; import java.util.Collection; -@RunWith(Parameterized.class) +@RunWith(JUnitParamsRunner.class) @LargeTest public class MessageDigestPerfTest { @Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); - @Parameters(name = "mAlgorithm={0}") - public static Collection<Object[]> data() { + public static Collection<Object[]> getData() { return Arrays.asList( new Object[][] { {Algorithm.MD5}, @@ -48,9 +48,6 @@ public class MessageDigestPerfTest { }); } - @Parameterized.Parameter(0) - public Algorithm mAlgorithm; - public String mProvider = "AndroidOpenSSL"; private static final int DATA_SIZE = 8192; @@ -97,44 +94,44 @@ public class MessageDigestPerfTest { }; @Test - public void time() throws Exception { + @Parameters(method = "getData") + public void time(Algorithm algorithm) throws Exception { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - MessageDigest digest = - MessageDigest.getInstance(mAlgorithm.toString(), mProvider); + MessageDigest digest = MessageDigest.getInstance(algorithm.toString(), mProvider); digest.update(DATA, 0, DATA_SIZE); digest.digest(); } } @Test - public void timeLargeArray() throws Exception { + @Parameters(method = "getData") + public void timeLargeArray(Algorithm algorithm) throws Exception { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - MessageDigest digest = - MessageDigest.getInstance(mAlgorithm.toString(), mProvider); + MessageDigest digest = MessageDigest.getInstance(algorithm.toString(), mProvider); digest.update(LARGE_DATA, 0, LARGE_DATA_SIZE); digest.digest(); } } @Test - public void timeSmallChunkOfLargeArray() throws Exception { + @Parameters(method = "getData") + public void timeSmallChunkOfLargeArray(Algorithm algorithm) throws Exception { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - MessageDigest digest = - MessageDigest.getInstance(mAlgorithm.toString(), mProvider); + MessageDigest digest = MessageDigest.getInstance(algorithm.toString(), mProvider); digest.update(LARGE_DATA, LARGE_DATA_SIZE / 2, DATA_SIZE); digest.digest(); } } @Test - public void timeSmallByteBuffer() throws Exception { + @Parameters(method = "getData") + public void timeSmallByteBuffer(Algorithm algorithm) throws Exception { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - MessageDigest digest = - MessageDigest.getInstance(mAlgorithm.toString(), mProvider); + MessageDigest digest = MessageDigest.getInstance(algorithm.toString(), mProvider); SMALL_BUFFER.position(0); SMALL_BUFFER.limit(SMALL_BUFFER.capacity()); digest.update(SMALL_BUFFER); @@ -143,11 +140,11 @@ public class MessageDigestPerfTest { } @Test - public void timeSmallDirectByteBuffer() throws Exception { + @Parameters(method = "getData") + public void timeSmallDirectByteBuffer(Algorithm algorithm) throws Exception { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - MessageDigest digest = - MessageDigest.getInstance(mAlgorithm.toString(), mProvider); + MessageDigest digest = MessageDigest.getInstance(algorithm.toString(), mProvider); SMALL_DIRECT_BUFFER.position(0); SMALL_DIRECT_BUFFER.limit(SMALL_DIRECT_BUFFER.capacity()); digest.update(SMALL_DIRECT_BUFFER); @@ -156,11 +153,11 @@ public class MessageDigestPerfTest { } @Test - public void timeLargeByteBuffer() throws Exception { + @Parameters(method = "getData") + public void timeLargeByteBuffer(Algorithm algorithm) throws Exception { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - MessageDigest digest = - MessageDigest.getInstance(mAlgorithm.toString(), mProvider); + MessageDigest digest = MessageDigest.getInstance(algorithm.toString(), mProvider); LARGE_BUFFER.position(0); LARGE_BUFFER.limit(LARGE_BUFFER.capacity()); digest.update(LARGE_BUFFER); @@ -169,11 +166,11 @@ public class MessageDigestPerfTest { } @Test - public void timeLargeDirectByteBuffer() throws Exception { + @Parameters(method = "getData") + public void timeLargeDirectByteBuffer(Algorithm algorithm) throws Exception { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - MessageDigest digest = - MessageDigest.getInstance(mAlgorithm.toString(), mProvider); + MessageDigest digest = MessageDigest.getInstance(algorithm.toString(), mProvider); LARGE_DIRECT_BUFFER.position(0); LARGE_DIRECT_BUFFER.limit(LARGE_DIRECT_BUFFER.capacity()); digest.update(LARGE_DIRECT_BUFFER); @@ -182,11 +179,11 @@ public class MessageDigestPerfTest { } @Test - public void timeSmallChunkOfLargeByteBuffer() throws Exception { + @Parameters(method = "getData") + public void timeSmallChunkOfLargeByteBuffer(Algorithm algorithm) throws Exception { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - MessageDigest digest = - MessageDigest.getInstance(mAlgorithm.toString(), mProvider); + MessageDigest digest = MessageDigest.getInstance(algorithm.toString(), mProvider); LARGE_BUFFER.position(LARGE_BUFFER.capacity() / 2); LARGE_BUFFER.limit(LARGE_BUFFER.position() + DATA_SIZE); digest.update(LARGE_BUFFER); @@ -195,11 +192,11 @@ public class MessageDigestPerfTest { } @Test - public void timeSmallChunkOfLargeDirectByteBuffer() throws Exception { + @Parameters(method = "getData") + public void timeSmallChunkOfLargeDirectByteBuffer(Algorithm algorithm) throws Exception { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - MessageDigest digest = - MessageDigest.getInstance(mAlgorithm.toString(), mProvider); + MessageDigest digest = MessageDigest.getInstance(algorithm.toString(), mProvider); LARGE_DIRECT_BUFFER.position(LARGE_DIRECT_BUFFER.capacity() / 2); LARGE_DIRECT_BUFFER.limit(LARGE_DIRECT_BUFFER.position() + DATA_SIZE); digest.update(LARGE_DIRECT_BUFFER); diff --git a/apct-tests/perftests/core/src/android/libcore/regression/MutableIntPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/MutableIntPerfTest.java index 37bd73c8731a..d9d4bb5d0ae1 100644 --- a/apct-tests/perftests/core/src/android/libcore/regression/MutableIntPerfTest.java +++ b/apct-tests/perftests/core/src/android/libcore/regression/MutableIntPerfTest.java @@ -20,17 +20,18 @@ import android.perftests.utils.BenchmarkState; import android.perftests.utils.PerfStatusReporter; import android.test.suitebuilder.annotation.LargeTest; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; + import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; import java.util.Collection; import java.util.concurrent.atomic.AtomicInteger; -@RunWith(Parameterized.class) +@RunWith(JUnitParamsRunner.class) @LargeTest public final class MutableIntPerfTest { @Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); @@ -96,29 +97,28 @@ public final class MutableIntPerfTest { abstract int timeGet(BenchmarkState state); } - @Parameters(name = "mKind={0}") - public static Collection<Object[]> data() { + public static Collection<Object[]> getData() { return Arrays.asList(new Object[][] {{Kind.ARRAY}, {Kind.ATOMIC}}); } - @Parameterized.Parameter(0) - public Kind mKind; - @Test - public void timeCreate() { + @Parameters(method = "getData") + public void timeCreate(Kind kind) { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); - mKind.timeCreate(state); + kind.timeCreate(state); } @Test - public void timeIncrement() { + @Parameters(method = "getData") + public void timeIncrement(Kind kind) { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); - mKind.timeIncrement(state); + kind.timeIncrement(state); } @Test - public void timeGet() { + @Parameters(method = "getData") + public void timeGet(Kind kind) { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); - mKind.timeGet(state); + kind.timeGet(state); } } diff --git a/apct-tests/perftests/core/src/android/libcore/regression/PriorityQueuePerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/PriorityQueuePerfTest.java index 8801a5690cb2..48450b4616e6 100644 --- a/apct-tests/perftests/core/src/android/libcore/regression/PriorityQueuePerfTest.java +++ b/apct-tests/perftests/core/src/android/libcore/regression/PriorityQueuePerfTest.java @@ -20,12 +20,12 @@ import android.perftests.utils.BenchmarkState; import android.perftests.utils.PerfStatusReporter; import android.test.suitebuilder.annotation.LargeTest; -import org.junit.Before; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; + import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; import java.util.ArrayList; import java.util.Arrays; @@ -35,13 +35,12 @@ import java.util.List; import java.util.PriorityQueue; import java.util.Random; -@RunWith(Parameterized.class) +@RunWith(JUnitParamsRunner.class) @LargeTest public class PriorityQueuePerfTest { @Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); - @Parameters(name = "mQueueSize={0}, mHitRate={1}") - public static Collection<Object[]> data() { + public static Collection<Object[]> getData() { return Arrays.asList( new Object[][] { {100, 0}, @@ -62,26 +61,19 @@ public class PriorityQueuePerfTest { }); } - @Parameterized.Parameter(0) - public int mQueueSize; - - @Parameterized.Parameter(1) - public int mHitRate; - private PriorityQueue<Integer> mPq; private PriorityQueue<Integer> mUsepq; private List<Integer> mSeekElements; private Random mRandom = new Random(189279387L); - @Before - public void setUp() throws Exception { + public void setUp(int queueSize, int hitRate) throws Exception { mPq = new PriorityQueue<Integer>(); mUsepq = new PriorityQueue<Integer>(); mSeekElements = new ArrayList<Integer>(); List<Integer> allElements = new ArrayList<Integer>(); - int numShared = (int) (mQueueSize * ((double) mHitRate / 100)); - // the total number of elements we require to engineer a hit rate of mHitRate% - int totalElements = 2 * mQueueSize - numShared; + int numShared = (int) (queueSize * ((double) hitRate / 100)); + // the total number of elements we require to engineer a hit rate of hitRate% + int totalElements = 2 * queueSize - numShared; for (int i = 0; i < totalElements; i++) { allElements.add(i); } @@ -93,11 +85,11 @@ public class PriorityQueuePerfTest { mSeekElements.add(allElements.get(i)); } // add priority queue only elements (these won't be touched) - for (int i = numShared; i < mQueueSize; i++) { + for (int i = numShared; i < queueSize; i++) { mPq.add(allElements.get(i)); } // add non-priority queue elements (these will be misses) - for (int i = mQueueSize; i < totalElements; i++) { + for (int i = queueSize; i < totalElements; i++) { mSeekElements.add(allElements.get(i)); } mUsepq = new PriorityQueue<Integer>(mPq); @@ -107,16 +99,18 @@ public class PriorityQueuePerfTest { } @Test - public void timeRemove() { + @Parameters(method = "getData") + public void timeRemove(int queueSize, int hitRate) throws Exception { + setUp(queueSize, hitRate); boolean fake = false; int elementsSize = mSeekElements.size(); // At most allow the queue to empty 10%. - int resizingThreshold = mQueueSize / 10; + int resizingThreshold = queueSize / 10; int i = 0; BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { // Reset queue every so often. This will be called more often for smaller - // mQueueSizes, but since a copy is linear, it will also cost proportionally + // queueSizes, but since a copy is linear, it will also cost proportionally // less, and hopefully it will approximately balance out. if (++i % resizingThreshold == 0) { mUsepq = new PriorityQueue<Integer>(mPq); diff --git a/apct-tests/perftests/core/src/android/libcore/regression/SchemePrefixPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/SchemePrefixPerfTest.java index 42dc5811e6db..5ad62dedcae7 100644 --- a/apct-tests/perftests/core/src/android/libcore/regression/SchemePrefixPerfTest.java +++ b/apct-tests/perftests/core/src/android/libcore/regression/SchemePrefixPerfTest.java @@ -20,11 +20,12 @@ import android.perftests.utils.BenchmarkState; import android.perftests.utils.PerfStatusReporter; import android.test.suitebuilder.annotation.LargeTest; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; + import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; import java.util.Collection; @@ -32,7 +33,7 @@ import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; -@RunWith(Parameterized.class) +@RunWith(JUnitParamsRunner.class) @LargeTest public final class SchemePrefixPerfTest { @Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); @@ -85,19 +86,16 @@ public final class SchemePrefixPerfTest { abstract String execute(String spec); } - @Parameters(name = "mStrategy={0}") - public static Collection<Object[]> data() { + public static Collection<Object[]> getData() { return Arrays.asList(new Object[][] {{Strategy.REGEX}, {Strategy.JAVA}}); } - @Parameterized.Parameter(0) - public Strategy mStrategy; - @Test - public void timeSchemePrefix() { + @Parameters(method = "getData") + public void timeSchemePrefix(Strategy strategy) { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - mStrategy.execute("http://android.com"); + strategy.execute("http://android.com"); } } } diff --git a/apct-tests/perftests/core/src/android/libcore/regression/SignaturePerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/SignaturePerfTest.java index 96e7cb27afef..a9a0788f6136 100644 --- a/apct-tests/perftests/core/src/android/libcore/regression/SignaturePerfTest.java +++ b/apct-tests/perftests/core/src/android/libcore/regression/SignaturePerfTest.java @@ -19,12 +19,12 @@ import android.perftests.utils.BenchmarkState; import android.perftests.utils.PerfStatusReporter; import android.test.suitebuilder.annotation.LargeTest; -import org.junit.Before; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; + import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; import java.security.KeyPair; import java.security.KeyPairGenerator; @@ -37,13 +37,12 @@ import java.util.HashMap; import java.util.Map; /** Tests RSA and DSA mSignature creation and verification. */ -@RunWith(Parameterized.class) +@RunWith(JUnitParamsRunner.class) @LargeTest public class SignaturePerfTest { @Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); - @Parameters(name = "mAlgorithm={0}, mImplementation={1}") - public static Collection<Object[]> data() { + public static Collection<Object[]> getData() { return Arrays.asList( new Object[][] { {Algorithm.MD5WithRSA, Implementation.OpenSSL}, @@ -55,12 +54,6 @@ public class SignaturePerfTest { }); } - @Parameterized.Parameter(0) - public Algorithm mAlgorithm; - - @Parameterized.Parameter(1) - public Implementation mImplementation; - private static final int DATA_SIZE = 8192; private static final byte[] DATA = new byte[DATA_SIZE]; @@ -94,9 +87,8 @@ public class SignaturePerfTest { private PrivateKey mPrivateKey; private PublicKey mPublicKey; - @Before - public void setUp() throws Exception { - this.mSignatureAlgorithm = mAlgorithm.toString(); + public void setUp(Algorithm algorithm) throws Exception { + this.mSignatureAlgorithm = algorithm.toString(); String keyAlgorithm = mSignatureAlgorithm.substring( @@ -121,11 +113,13 @@ public class SignaturePerfTest { } @Test - public void timeSign() throws Exception { + @Parameters(method = "getData") + public void timeSign(Algorithm algorithm, Implementation implementation) throws Exception { + setUp(algorithm); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { Signature signer; - switch (mImplementation) { + switch (implementation) { case OpenSSL: signer = Signature.getInstance(mSignatureAlgorithm, "AndroidOpenSSL"); break; @@ -133,7 +127,7 @@ public class SignaturePerfTest { signer = Signature.getInstance(mSignatureAlgorithm, "BC"); break; default: - throw new RuntimeException(mImplementation.toString()); + throw new RuntimeException(implementation.toString()); } signer.initSign(mPrivateKey); signer.update(DATA); @@ -142,11 +136,13 @@ public class SignaturePerfTest { } @Test - public void timeVerify() throws Exception { + @Parameters(method = "getData") + public void timeVerify(Algorithm algorithm, Implementation implementation) throws Exception { + setUp(algorithm); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { Signature verifier; - switch (mImplementation) { + switch (implementation) { case OpenSSL: verifier = Signature.getInstance(mSignatureAlgorithm, "AndroidOpenSSL"); break; @@ -154,7 +150,7 @@ public class SignaturePerfTest { verifier = Signature.getInstance(mSignatureAlgorithm, "BC"); break; default: - throw new RuntimeException(mImplementation.toString()); + throw new RuntimeException(implementation.toString()); } verifier.initVerify(mPublicKey); verifier.update(DATA); diff --git a/apct-tests/perftests/core/src/android/libcore/regression/StringPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/StringPerfTest.java index 02194b1b9745..36db014b75a5 100644 --- a/apct-tests/perftests/core/src/android/libcore/regression/StringPerfTest.java +++ b/apct-tests/perftests/core/src/android/libcore/regression/StringPerfTest.java @@ -20,16 +20,17 @@ import android.perftests.utils.BenchmarkState; import android.perftests.utils.PerfStatusReporter; import android.test.suitebuilder.annotation.LargeTest; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; + import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; import java.util.Collection; -@RunWith(Parameterized.class) +@RunWith(JUnitParamsRunner.class) @LargeTest public class StringPerfTest { @Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); @@ -46,8 +47,7 @@ public class StringPerfTest { } } - @Parameters(name = "mStringLengths={0}") - public static Collection<Object[]> data() { + public static Collection<Object[]> getData() { return Arrays.asList( new Object[][] { {StringLengths.EIGHT_KI}, @@ -57,9 +57,6 @@ public class StringPerfTest { }); } - @Parameterized.Parameter(0) - public StringLengths mStringLengths; - private static String makeString(int length) { StringBuilder result = new StringBuilder(length); for (int i = 0; i < length; ++i) { @@ -69,10 +66,11 @@ public class StringPerfTest { } @Test - public void timeHashCode() { + @Parameters(method = "getData") + public void timeHashCode(StringLengths stringLengths) { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - mStringLengths.mValue.hashCode(); + stringLengths.mValue.hashCode(); } } } diff --git a/apct-tests/perftests/core/src/android/libcore/regression/StringReplaceAllPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/StringReplaceAllPerfTest.java index b0d1ee4132fa..5b4423a32831 100644 --- a/apct-tests/perftests/core/src/android/libcore/regression/StringReplaceAllPerfTest.java +++ b/apct-tests/perftests/core/src/android/libcore/regression/StringReplaceAllPerfTest.java @@ -20,16 +20,17 @@ import android.perftests.utils.BenchmarkState; import android.perftests.utils.PerfStatusReporter; import android.test.suitebuilder.annotation.LargeTest; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; + import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; import java.util.Collection; -@RunWith(Parameterized.class) +@RunWith(JUnitParamsRunner.class) @LargeTest public class StringReplaceAllPerfTest { @Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); @@ -69,8 +70,7 @@ public class StringReplaceAllPerfTest { return stringBuilder.toString(); } - @Parameters(name = "mStringLengths={0}") - public static Collection<Object[]> data() { + public static Collection<Object[]> getData() { return Arrays.asList( new Object[][] { {StringLengths.BOOT_IMAGE}, @@ -82,30 +82,30 @@ public class StringReplaceAllPerfTest { }); } - @Parameterized.Parameter(0) - public StringLengths mStringLengths; - @Test - public void timeReplaceAllTrivialPatternNonExistent() { + @Parameters(method = "getData") + public void timeReplaceAllTrivialPatternNonExistent(StringLengths stringLengths) { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - mStringLengths.mValue.replaceAll("fish", "0"); + stringLengths.mValue.replaceAll("fish", "0"); } } @Test - public void timeReplaceTrivialPatternAllRepeated() { + @Parameters(method = "getData") + public void timeReplaceTrivialPatternAllRepeated(StringLengths stringLengths) { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - mStringLengths.mValue.replaceAll("jklm", "0"); + stringLengths.mValue.replaceAll("jklm", "0"); } } @Test - public void timeReplaceAllTrivialPatternSingleOccurrence() { + @Parameters(method = "getData") + public void timeReplaceAllTrivialPatternSingleOccurrence(StringLengths stringLengths) { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - mStringLengths.mValue.replaceAll("qrst", "0"); + stringLengths.mValue.replaceAll("qrst", "0"); } } } diff --git a/apct-tests/perftests/core/src/android/libcore/regression/StringReplacePerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/StringReplacePerfTest.java index d2e657a78608..4d5c792295b9 100644 --- a/apct-tests/perftests/core/src/android/libcore/regression/StringReplacePerfTest.java +++ b/apct-tests/perftests/core/src/android/libcore/regression/StringReplacePerfTest.java @@ -20,16 +20,17 @@ import android.perftests.utils.BenchmarkState; import android.perftests.utils.PerfStatusReporter; import android.test.suitebuilder.annotation.LargeTest; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; + import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; import java.util.Collection; -@RunWith(Parameterized.class) +@RunWith(JUnitParamsRunner.class) @LargeTest public class StringReplacePerfTest { @Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); @@ -64,8 +65,7 @@ public class StringReplacePerfTest { return stringBuilder.toString(); } - @Parameters(name = "mStringLengths={0}") - public static Collection<Object[]> data() { + public static Collection<Object[]> getData() { return Arrays.asList( new Object[][] { {StringLengths.EMPTY}, @@ -76,54 +76,57 @@ public class StringReplacePerfTest { }); } - @Parameterized.Parameter(0) - public StringLengths mStringLengths; - @Test - public void timeReplaceCharNonExistent() { + @Parameters(method = "getData") + public void timeReplaceCharNonExistent(StringLengths stringLengths) { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - mStringLengths.mValue.replace('z', '0'); + stringLengths.mValue.replace('z', '0'); } } @Test - public void timeReplaceCharRepeated() { + @Parameters(method = "getData") + public void timeReplaceCharRepeated(StringLengths stringLengths) { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - mStringLengths.mValue.replace('a', '0'); + stringLengths.mValue.replace('a', '0'); } } @Test - public void timeReplaceSingleChar() { + @Parameters(method = "getData") + public void timeReplaceSingleChar(StringLengths stringLengths) { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - mStringLengths.mValue.replace('q', '0'); + stringLengths.mValue.replace('q', '0'); } } @Test - public void timeReplaceSequenceNonExistent() { + @Parameters(method = "getData") + public void timeReplaceSequenceNonExistent(StringLengths stringLengths) { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - mStringLengths.mValue.replace("fish", "0"); + stringLengths.mValue.replace("fish", "0"); } } @Test - public void timeReplaceSequenceRepeated() { + @Parameters(method = "getData") + public void timeReplaceSequenceRepeated(StringLengths stringLengths) { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - mStringLengths.mValue.replace("jklm", "0"); + stringLengths.mValue.replace("jklm", "0"); } } @Test - public void timeReplaceSingleSequence() { + @Parameters(method = "getData") + public void timeReplaceSingleSequence(StringLengths stringLengths) { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - mStringLengths.mValue.replace("qrst", "0"); + stringLengths.mValue.replace("qrst", "0"); } } } diff --git a/apct-tests/perftests/core/src/android/libcore/regression/StringToBytesPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/StringToBytesPerfTest.java index 1efc188f4e4d..c004d959b9b3 100644 --- a/apct-tests/perftests/core/src/android/libcore/regression/StringToBytesPerfTest.java +++ b/apct-tests/perftests/core/src/android/libcore/regression/StringToBytesPerfTest.java @@ -20,17 +20,18 @@ import android.perftests.utils.BenchmarkState; import android.perftests.utils.PerfStatusReporter; import android.test.suitebuilder.annotation.LargeTest; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; + import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collection; -@RunWith(Parameterized.class) +@RunWith(JUnitParamsRunner.class) @LargeTest public class StringToBytesPerfTest { @Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); @@ -53,8 +54,7 @@ public class StringToBytesPerfTest { } } - @Parameters(name = "mStringLengths={0}") - public static Collection<Object[]> data() { + public static Collection<Object[]> getData() { return Arrays.asList( new Object[][] { {StringLengths.EMPTY}, @@ -69,9 +69,6 @@ public class StringToBytesPerfTest { }); } - @Parameterized.Parameter(0) - public StringLengths mStringLengths; - private static String makeString(int length) { char[] chars = new char[length]; for (int i = 0; i < length; ++i) { @@ -89,26 +86,29 @@ public class StringToBytesPerfTest { } @Test - public void timeGetBytesUtf8() { + @Parameters(method = "getData") + public void timeGetBytesUtf8(StringLengths stringLengths) { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - mStringLengths.mValue.getBytes(StandardCharsets.UTF_8); + stringLengths.mValue.getBytes(StandardCharsets.UTF_8); } } @Test - public void timeGetBytesIso88591() { + @Parameters(method = "getData") + public void timeGetBytesIso88591(StringLengths stringLengths) { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - mStringLengths.mValue.getBytes(StandardCharsets.ISO_8859_1); + stringLengths.mValue.getBytes(StandardCharsets.ISO_8859_1); } } @Test - public void timeGetBytesAscii() { + @Parameters(method = "getData") + public void timeGetBytesAscii(StringLengths stringLengths) { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - mStringLengths.mValue.getBytes(StandardCharsets.US_ASCII); + stringLengths.mValue.getBytes(StandardCharsets.US_ASCII); } } } diff --git a/apct-tests/perftests/core/src/android/libcore/regression/StringToRealPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/StringToRealPerfTest.java index b01948aa2255..15516fc1c51c 100644 --- a/apct-tests/perftests/core/src/android/libcore/regression/StringToRealPerfTest.java +++ b/apct-tests/perftests/core/src/android/libcore/regression/StringToRealPerfTest.java @@ -20,22 +20,22 @@ import android.perftests.utils.BenchmarkState; import android.perftests.utils.PerfStatusReporter; import android.test.suitebuilder.annotation.LargeTest; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; + import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; import java.util.Collection; -@RunWith(Parameterized.class) +@RunWith(JUnitParamsRunner.class) @LargeTest public class StringToRealPerfTest { @Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); - @Parameters(name = "mString={0}") - public static Collection<Object[]> data() { + public static Collection<Object[]> getData() { return Arrays.asList( new Object[][] { {"NaN"}, @@ -49,22 +49,21 @@ public class StringToRealPerfTest { }); } - @Parameterized.Parameter(0) - public String mString; - @Test - public void timeFloat_parseFloat() { + @Parameters(method = "getData") + public void timeFloat_parseFloat(String string) { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - Float.parseFloat(mString); + Float.parseFloat(string); } } @Test - public void timeDouble_parseDouble() { + @Parameters(method = "getData") + public void timeDouble_parseDouble(String string) { BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { - Double.parseDouble(mString); + Double.parseDouble(string); } } } diff --git a/apct-tests/perftests/core/src/android/libcore/regression/XMLEntitiesPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/XMLEntitiesPerfTest.java index 2ea834d0b71c..ae1e8bce42ac 100644 --- a/apct-tests/perftests/core/src/android/libcore/regression/XMLEntitiesPerfTest.java +++ b/apct-tests/perftests/core/src/android/libcore/regression/XMLEntitiesPerfTest.java @@ -20,12 +20,12 @@ import android.perftests.utils.BenchmarkState; import android.perftests.utils.PerfStatusReporter; import android.test.suitebuilder.annotation.LargeTest; -import org.junit.Before; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; + import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; import org.xml.sax.InputSource; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory; @@ -38,13 +38,12 @@ import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; // http://code.google.com/p/android/issues/detail?id=18102 -@RunWith(Parameterized.class) +@RunWith(JUnitParamsRunner.class) @LargeTest public final class XMLEntitiesPerfTest { @Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); - @Parameters(name = "mLength={0}, mEntityFraction={1}") - public static Collection<Object[]> data() { + public static Collection<Object[]> getData() { return Arrays.asList( new Object[][] { {10, 0}, @@ -59,29 +58,22 @@ public final class XMLEntitiesPerfTest { }); } - @Parameterized.Parameter(0) - public int mLength; - - @Parameterized.Parameter(1) - public float mEntityFraction; - private XmlPullParserFactory mXmlPullParserFactory; private DocumentBuilderFactory mDocumentBuilderFactory; /** a string like {@code <doc>&&++</doc>}. */ private String mXml; - @Before - public void setUp() throws Exception { + public void setUp(int length, float entityFraction) throws Exception { mXmlPullParserFactory = XmlPullParserFactory.newInstance(); mDocumentBuilderFactory = DocumentBuilderFactory.newInstance(); StringBuilder xmlBuilder = new StringBuilder(); xmlBuilder.append("<doc>"); - for (int i = 0; i < (mLength * mEntityFraction); i++) { + for (int i = 0; i < (length * entityFraction); i++) { xmlBuilder.append("&"); } - while (xmlBuilder.length() < mLength) { + while (xmlBuilder.length() < length) { xmlBuilder.append("+"); } xmlBuilder.append("</doc>"); @@ -89,7 +81,9 @@ public final class XMLEntitiesPerfTest { } @Test - public void timeXmlParser() throws Exception { + @Parameters(method = "getData") + public void timeXmlParser(int length, float entityFraction) throws Exception { + setUp(length, entityFraction); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { XmlPullParser parser = mXmlPullParserFactory.newPullParser(); @@ -101,7 +95,9 @@ public final class XMLEntitiesPerfTest { } @Test - public void timeDocumentBuilder() throws Exception { + @Parameters(method = "getData") + public void timeDocumentBuilder(int length, float entityFraction) throws Exception { + setUp(length, entityFraction); BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); while (state.keepRunning()) { DocumentBuilder documentBuilder = mDocumentBuilderFactory.newDocumentBuilder(); diff --git a/apex/jobscheduler/service/java/com/android/server/job/controllers/TimeController.java b/apex/jobscheduler/service/java/com/android/server/job/controllers/TimeController.java index b6361ce56569..80a70a6e9e9e 100644 --- a/apex/jobscheduler/service/java/com/android/server/job/controllers/TimeController.java +++ b/apex/jobscheduler/service/java/com/android/server/job/controllers/TimeController.java @@ -31,6 +31,7 @@ import android.util.TimeUtils; import android.util.proto.ProtoOutputStream; import com.android.internal.annotations.VisibleForTesting; +import com.android.internal.expresslog.Counter; import com.android.server.job.JobSchedulerService; import com.android.server.job.StateControllerProto; @@ -88,6 +89,8 @@ public final class TimeController extends StateController { // will never be unsatisfied (our time base can not go backwards). final long nowElapsedMillis = sElapsedRealtimeClock.millis(); if (job.hasDeadlineConstraint() && evaluateDeadlineConstraint(job, nowElapsedMillis)) { + // We're intentionally excluding jobs whose deadlines have passed + // (mostly like deadlines of 0) when the job was scheduled. return; } else if (job.hasTimingDelayConstraint() && evaluateTimingDelayConstraint(job, nowElapsedMillis)) { @@ -159,6 +162,8 @@ public final class TimeController extends StateController { // Scheduler. mStateChangedListener.onRunJobNow(job); } + Counter.logIncrement( + "job_scheduler.value_job_scheduler_job_deadline_expired_counter"); } else if (wouldBeReadyWithConstraintLocked(job, JobStatus.CONSTRAINT_DEADLINE)) { // This job's deadline is earlier than the current set alarm. Update the alarm. setDeadlineExpiredAlarmLocked(job.getLatestRunTimeElapsed(), @@ -229,6 +234,8 @@ public final class TimeController extends StateController { // Scheduler. mStateChangedListener.onRunJobNow(job); } + Counter.logIncrement( + "job_scheduler.value_job_scheduler_job_deadline_expired_counter"); it.remove(); } else { // Sorted by expiry time, so take the next one and stop. if (!wouldBeReadyWithConstraintLocked(job, JobStatus.CONSTRAINT_DEADLINE)) { diff --git a/cmds/uiautomator/OWNERS b/cmds/uiautomator/OWNERS new file mode 100644 index 000000000000..5c7f45230ff3 --- /dev/null +++ b/cmds/uiautomator/OWNERS @@ -0,0 +1,4 @@ +# Bug component: 833089 +peykov@google.com +normancheung@google.com +guran@google.com diff --git a/cmds/uiautomator/cmds/uiautomator/src/com/android/commands/uiautomator/DumpCommand.java b/cmds/uiautomator/cmds/uiautomator/src/com/android/commands/uiautomator/DumpCommand.java index 3b14be7327f7..24727c5f2448 100644 --- a/cmds/uiautomator/cmds/uiautomator/src/com/android/commands/uiautomator/DumpCommand.java +++ b/cmds/uiautomator/cmds/uiautomator/src/com/android/commands/uiautomator/DumpCommand.java @@ -107,7 +107,7 @@ public class DumpCommand extends Command { DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); int rotation = display.getRotation(); Point size = new Point(); - display.getSize(size); + display.getRealSize(size); AccessibilityNodeInfoDumper.dumpWindowToFile(info, dumpFile, rotation, size.x, size.y); } diff --git a/cmds/uiautomator/library/core-src/com/android/uiautomator/core/AccessibilityNodeInfoDumper.java b/cmds/uiautomator/library/core-src/com/android/uiautomator/core/AccessibilityNodeInfoDumper.java index ab198b319e27..488292d68620 100644 --- a/cmds/uiautomator/library/core-src/com/android/uiautomator/core/AccessibilityNodeInfoDumper.java +++ b/cmds/uiautomator/library/core-src/com/android/uiautomator/core/AccessibilityNodeInfoDumper.java @@ -139,7 +139,7 @@ public class AccessibilityNodeInfoDumper { serializer.attribute("", "id", Integer.toString(displayId)); int rotation = display.getRotation(); Point size = new Point(); - display.getSize(size); + display.getRealSize(size); for (int i = 0, n = windows.size(); i < n; ++i) { dumpWindowRec(windows.get(i), serializer, i, size.x, size.y, rotation); } diff --git a/cmds/uiautomator/library/core-src/com/android/uiautomator/core/UiDevice.java b/cmds/uiautomator/library/core-src/com/android/uiautomator/core/UiDevice.java index b1b432bf79ab..1bcd343e5668 100644 --- a/cmds/uiautomator/library/core-src/com/android/uiautomator/core/UiDevice.java +++ b/cmds/uiautomator/library/core-src/com/android/uiautomator/core/UiDevice.java @@ -380,7 +380,7 @@ public class UiDevice { Tracer.trace(); Display display = getAutomatorBridge().getDefaultDisplay(); Point p = new Point(); - display.getSize(p); + display.getRealSize(p); return p.x; } @@ -394,7 +394,7 @@ public class UiDevice { Tracer.trace(); Display display = getAutomatorBridge().getDefaultDisplay(); Point p = new Point(); - display.getSize(p); + display.getRealSize(p); return p.y; } @@ -767,7 +767,7 @@ public class UiDevice { if(root != null) { Display display = getAutomatorBridge().getDefaultDisplay(); Point size = new Point(); - display.getSize(size); + display.getRealSize(size); AccessibilityNodeInfoDumper.dumpWindowToFile(root, new File(new File(Environment.getDataDirectory(), "local/tmp"), fileName), display.getRotation(), size.x, size.y); diff --git a/core/api/current.txt b/core/api/current.txt index 93cb7e45a047..6f6832956747 100644 --- a/core/api/current.txt +++ b/core/api/current.txt @@ -32238,6 +32238,7 @@ package android.os { field public static final String DISALLOW_BLUETOOTH = "no_bluetooth"; field public static final String DISALLOW_BLUETOOTH_SHARING = "no_bluetooth_sharing"; field public static final String DISALLOW_CAMERA_TOGGLE = "disallow_camera_toggle"; + field public static final String DISALLOW_CELLULAR_2G = "no_cellular_2g"; field public static final String DISALLOW_CHANGE_WIFI_STATE = "no_change_wifi_state"; field public static final String DISALLOW_CONFIG_BLUETOOTH = "no_config_bluetooth"; field public static final String DISALLOW_CONFIG_BRIGHTNESS = "no_config_brightness"; @@ -41226,7 +41227,7 @@ package android.telephony { field public static final String KEY_CARRIER_CONFIG_APPLIED_BOOL = "carrier_config_applied_bool"; field public static final String KEY_CARRIER_CONFIG_VERSION_STRING = "carrier_config_version_string"; field public static final String KEY_CARRIER_CROSS_SIM_IMS_AVAILABLE_BOOL = "carrier_cross_sim_ims_available_bool"; - field public static final String KEY_CARRIER_DATA_CALL_PERMANENT_FAILURE_STRINGS = "carrier_data_call_permanent_failure_strings"; + field @Deprecated public static final String KEY_CARRIER_DATA_CALL_PERMANENT_FAILURE_STRINGS = "carrier_data_call_permanent_failure_strings"; field public static final String KEY_CARRIER_DEFAULT_ACTIONS_ON_DCFAILURE_STRING_ARRAY = "carrier_default_actions_on_dcfailure_string_array"; field public static final String KEY_CARRIER_DEFAULT_ACTIONS_ON_DEFAULT_NETWORK_AVAILABLE = "carrier_default_actions_on_default_network_available_string_array"; field public static final String KEY_CARRIER_DEFAULT_ACTIONS_ON_REDIRECTION_STRING_ARRAY = "carrier_default_actions_on_redirection_string_array"; @@ -41322,7 +41323,7 @@ package android.telephony { field public static final String KEY_GSM_ROAMING_NETWORKS_STRING_ARRAY = "gsm_roaming_networks_string_array"; field public static final String KEY_HAS_IN_CALL_NOISE_SUPPRESSION_BOOL = "has_in_call_noise_suppression_bool"; field public static final String KEY_HIDE_CARRIER_NETWORK_SETTINGS_BOOL = "hide_carrier_network_settings_bool"; - field public static final String KEY_HIDE_ENABLE_2G = "hide_enable_2g_bool"; + field @Deprecated public static final String KEY_HIDE_ENABLE_2G = "hide_enable_2g_bool"; field public static final String KEY_HIDE_ENHANCED_4G_LTE_BOOL = "hide_enhanced_4g_lte_bool"; field public static final String KEY_HIDE_IMS_APN_BOOL = "hide_ims_apn_bool"; field public static final String KEY_HIDE_LTE_PLUS_DATA_ICON_BOOL = "hide_lte_plus_data_icon_bool"; diff --git a/core/api/module-lib-current.txt b/core/api/module-lib-current.txt index 068b40ad5270..9b556d8219cb 100644 --- a/core/api/module-lib-current.txt +++ b/core/api/module-lib-current.txt @@ -348,6 +348,7 @@ package android.os { } public final class ServiceManager { + method @NonNull public static String[] getDeclaredInstances(@NonNull String); method public static boolean isDeclared(@NonNull String); method @Nullable public static android.os.IBinder waitForDeclaredService(@NonNull String); } @@ -382,6 +383,7 @@ package android.os { method public static void traceBegin(long, @NonNull String); method public static void traceCounter(long, @NonNull String, int); method public static void traceEnd(long); + field public static final long TRACE_TAG_AIDL = 16777216L; // 0x1000000L field public static final long TRACE_TAG_NETWORK = 2097152L; // 0x200000L } diff --git a/core/api/system-current.txt b/core/api/system-current.txt index dad772abc771..4a0d7711769d 100644 --- a/core/api/system-current.txt +++ b/core/api/system-current.txt @@ -13553,6 +13553,7 @@ package android.telephony { field public static final String ACTION_SIM_SLOT_STATUS_CHANGED = "android.telephony.action.SIM_SLOT_STATUS_CHANGED"; field public static final int ALLOWED_NETWORK_TYPES_REASON_ENABLE_2G = 3; // 0x3 field public static final int ALLOWED_NETWORK_TYPES_REASON_POWER = 1; // 0x1 + field public static final int ALLOWED_NETWORK_TYPES_REASON_USER_RESTRICTIONS = 4; // 0x4 field public static final int CALL_WAITING_STATUS_DISABLED = 2; // 0x2 field public static final int CALL_WAITING_STATUS_ENABLED = 1; // 0x1 field public static final int CALL_WAITING_STATUS_FDN_CHECK_FAILURE = 5; // 0x5 diff --git a/core/java/android/accounts/AbstractAccountAuthenticator.java b/core/java/android/accounts/AbstractAccountAuthenticator.java index 3807b503ce70..2f32fa4216f1 100644 --- a/core/java/android/accounts/AbstractAccountAuthenticator.java +++ b/core/java/android/accounts/AbstractAccountAuthenticator.java @@ -120,27 +120,27 @@ public abstract class AbstractAccountAuthenticator { /** * Bundle key used for the {@link String} account type in session bundle. * This is used in the default implementation of - * {@link #startAddAccountSession} and {@link startUpdateCredentialsSession}. + * {@link #startAddAccountSession} and {@link #startUpdateCredentialsSession}. */ private static final String KEY_AUTH_TOKEN_TYPE = "android.accounts.AbstractAccountAuthenticato.KEY_AUTH_TOKEN_TYPE"; /** * Bundle key used for the {@link String} array of required features in * session bundle. This is used in the default implementation of - * {@link #startAddAccountSession} and {@link startUpdateCredentialsSession}. + * {@link #startAddAccountSession} and {@link #startUpdateCredentialsSession}. */ private static final String KEY_REQUIRED_FEATURES = "android.accounts.AbstractAccountAuthenticator.KEY_REQUIRED_FEATURES"; /** * Bundle key used for the {@link Bundle} options in session bundle. This is * used in default implementation of {@link #startAddAccountSession} and - * {@link startUpdateCredentialsSession}. + * {@link #startUpdateCredentialsSession}. */ private static final String KEY_OPTIONS = "android.accounts.AbstractAccountAuthenticator.KEY_OPTIONS"; /** * Bundle key used for the {@link Account} account in session bundle. This is used - * used in default implementation of {@link startUpdateCredentialsSession}. + * used in default implementation of {@link #startUpdateCredentialsSession}. */ private static final String KEY_ACCOUNT = "android.accounts.AbstractAccountAuthenticator.KEY_ACCOUNT"; diff --git a/core/java/android/app/AutomaticZenRule.java b/core/java/android/app/AutomaticZenRule.java index c0aebeed596a..7bfb1b5c1ba6 100644 --- a/core/java/android/app/AutomaticZenRule.java +++ b/core/java/android/app/AutomaticZenRule.java @@ -48,6 +48,13 @@ public final class AutomaticZenRule implements Parcelable { private String mPkg; /** + * The maximum string length for any string contained in this automatic zen rule. This pertains + * both to fields in the rule itself (such as its name) and items with sub-fields. + * @hide + */ + public static final int MAX_STRING_LENGTH = 1000; + + /** * Creates an automatic zen rule. * * @param name The name of the rule. @@ -93,10 +100,10 @@ public final class AutomaticZenRule implements Parcelable { public AutomaticZenRule(@NonNull String name, @Nullable ComponentName owner, @Nullable ComponentName configurationActivity, @NonNull Uri conditionId, @Nullable ZenPolicy policy, int interruptionFilter, boolean enabled) { - this.name = name; - this.owner = owner; - this.configurationActivity = configurationActivity; - this.conditionId = conditionId; + this.name = getTrimmedString(name); + this.owner = getTrimmedComponentName(owner); + this.configurationActivity = getTrimmedComponentName(configurationActivity); + this.conditionId = getTrimmedUri(conditionId); this.interruptionFilter = interruptionFilter; this.enabled = enabled; this.mZenPolicy = policy; @@ -115,12 +122,14 @@ public final class AutomaticZenRule implements Parcelable { public AutomaticZenRule(Parcel source) { enabled = source.readInt() == ENABLED; if (source.readInt() == ENABLED) { - name = source.readString(); + name = getTrimmedString(source.readString()); } interruptionFilter = source.readInt(); - conditionId = source.readParcelable(null, android.net.Uri.class); - owner = source.readParcelable(null, android.content.ComponentName.class); - configurationActivity = source.readParcelable(null, android.content.ComponentName.class); + conditionId = getTrimmedUri(source.readParcelable(null, android.net.Uri.class)); + owner = getTrimmedComponentName( + source.readParcelable(null, android.content.ComponentName.class)); + configurationActivity = getTrimmedComponentName( + source.readParcelable(null, android.content.ComponentName.class)); creationTime = source.readLong(); mZenPolicy = source.readParcelable(null, android.service.notification.ZenPolicy.class); mModified = source.readInt() == ENABLED; @@ -196,7 +205,7 @@ public final class AutomaticZenRule implements Parcelable { * Sets the representation of the state that causes this rule to become active. */ public void setConditionId(Uri conditionId) { - this.conditionId = conditionId; + this.conditionId = getTrimmedUri(conditionId); } /** @@ -211,7 +220,7 @@ public final class AutomaticZenRule implements Parcelable { * Sets the name of this rule. */ public void setName(String name) { - this.name = name; + this.name = getTrimmedString(name); } /** @@ -243,7 +252,7 @@ public final class AutomaticZenRule implements Parcelable { * that are not backed by {@link android.service.notification.ConditionProviderService}. */ public void setConfigurationActivity(@Nullable ComponentName componentName) { - this.configurationActivity = componentName; + this.configurationActivity = getTrimmedComponentName(componentName); } /** @@ -333,4 +342,35 @@ public final class AutomaticZenRule implements Parcelable { return new AutomaticZenRule[size]; } }; + + /** + * If the package or class name of the provided ComponentName are longer than MAX_STRING_LENGTH, + * return a trimmed version that truncates each of the package and class name at the max length. + */ + private static ComponentName getTrimmedComponentName(ComponentName cn) { + if (cn == null) return null; + return new ComponentName(getTrimmedString(cn.getPackageName()), + getTrimmedString(cn.getClassName())); + } + + /** + * Returns a truncated copy of the string if the string is longer than MAX_STRING_LENGTH. + */ + private static String getTrimmedString(String input) { + if (input != null && input.length() > MAX_STRING_LENGTH) { + return input.substring(0, MAX_STRING_LENGTH); + } + return input; + } + + /** + * Returns a truncated copy of the Uri by trimming the string representation to the maximum + * string length. + */ + private static Uri getTrimmedUri(Uri input) { + if (input != null && input.toString().length() > MAX_STRING_LENGTH) { + return Uri.parse(getTrimmedString(input.toString())); + } + return input; + } } diff --git a/core/java/android/app/OWNERS b/core/java/android/app/OWNERS index f3fc46869916..8ec313ecdd09 100644 --- a/core/java/android/app/OWNERS +++ b/core/java/android/app/OWNERS @@ -11,6 +11,7 @@ per-file ApplicationLoaders.java = file:/services/core/java/com/android/server/a per-file ApplicationThreadConstants.java = file:/services/core/java/com/android/server/am/OWNERS per-file BroadcastOptions.java = file:/services/core/java/com/android/server/am/OWNERS per-file ContentProviderHolder* = file:/services/core/java/com/android/server/am/OWNERS +per-file ForegroundService* = file:/services/core/java/com/android/server/am/OWNERS per-file IActivityController.aidl = file:/services/core/java/com/android/server/am/OWNERS per-file IActivityManager.aidl = file:/services/core/java/com/android/server/am/OWNERS per-file IApplicationThread.aidl = file:/services/core/java/com/android/server/am/OWNERS @@ -29,10 +30,12 @@ per-file ProfilerInfo* = file:/services/core/java/com/android/server/am/OWNERS per-file Service* = file:/services/core/java/com/android/server/am/OWNERS per-file SystemServiceRegistry.java = file:/services/core/java/com/android/server/am/OWNERS per-file *UserSwitchObserver* = file:/services/core/java/com/android/server/am/OWNERS -per-file UiAutomation* = file:/services/accessibility/OWNERS +per-file *UiAutomation* = file:/services/accessibility/OWNERS per-file GameManager* = file:/GAME_MANAGER_OWNERS +per-file GameMode* = file:/GAME_MANAGER_OWNERS per-file GameState* = file:/GAME_MANAGER_OWNERS per-file IGameManager* = file:/GAME_MANAGER_OWNERS +per-file IGameMode* = file:/GAME_MANAGER_OWNERS # ActivityThread per-file ActivityThread.java = file:/services/core/java/com/android/server/am/OWNERS diff --git a/core/java/android/app/SearchableInfo.java b/core/java/android/app/SearchableInfo.java index 5388282a1b46..bd5d1057f5bf 100644 --- a/core/java/android/app/SearchableInfo.java +++ b/core/java/android/app/SearchableInfo.java @@ -396,6 +396,17 @@ public final class SearchableInfo implements Parcelable { private final String mSuggestActionMsg; private final String mSuggestActionMsgColumn; + public static final Parcelable.Creator<ActionKeyInfo> CREATOR = + new Parcelable.Creator<ActionKeyInfo>() { + public ActionKeyInfo createFromParcel(Parcel in) { + return new ActionKeyInfo(in); + } + + public ActionKeyInfo[] newArray(int size) { + return new ActionKeyInfo[size]; + } + }; + /** * Create one object using attributeset as input data. * @param activityContext runtime context of the activity that the action key information diff --git a/core/java/android/app/SystemServiceRegistry.java b/core/java/android/app/SystemServiceRegistry.java index bdecca379b20..8bbddbf136b9 100644 --- a/core/java/android/app/SystemServiceRegistry.java +++ b/core/java/android/app/SystemServiceRegistry.java @@ -171,6 +171,7 @@ import android.os.IThermalService; import android.os.IUserManager; import android.os.IncidentManager; import android.os.PerformanceHintManager; +import android.os.PermissionEnforcer; import android.os.PowerManager; import android.os.RecoverySystem; import android.os.ServiceManager; @@ -1351,6 +1352,14 @@ public final class SystemServiceRegistry { return new PermissionCheckerManager(ctx.getOuterContext()); }}); + registerService(Context.PERMISSION_ENFORCER_SERVICE, PermissionEnforcer.class, + new CachedServiceFetcher<PermissionEnforcer>() { + @Override + public PermissionEnforcer createService(ContextImpl ctx) + throws ServiceNotFoundException { + return new PermissionEnforcer(ctx.getOuterContext()); + }}); + registerService(Context.DYNAMIC_SYSTEM_SERVICE, DynamicSystemManager.class, new CachedServiceFetcher<DynamicSystemManager>() { @Override diff --git a/core/java/android/content/ActivityNotFoundException.java b/core/java/android/content/ActivityNotFoundException.java index 16149bbc7012..5b50189015af 100644 --- a/core/java/android/content/ActivityNotFoundException.java +++ b/core/java/android/content/ActivityNotFoundException.java @@ -31,5 +31,4 @@ public class ActivityNotFoundException extends RuntimeException { super(name); } -}; - +} diff --git a/core/java/android/content/Context.java b/core/java/android/content/Context.java index fce23cf6819a..0735532ce037 100644 --- a/core/java/android/content/Context.java +++ b/core/java/android/content/Context.java @@ -5135,6 +5135,14 @@ public abstract class Context { public static final String PERMISSION_CHECKER_SERVICE = "permission_checker"; /** + * Official published name of the (internal) permission enforcer service. + * + * @see #getSystemService(String) + * @hide + */ + public static final String PERMISSION_ENFORCER_SERVICE = "permission_enforcer"; + + /** * Use with {@link #getSystemService(String) to retrieve an * {@link android.apphibernation.AppHibernationManager}} for * communicating with the hibernation service. diff --git a/core/java/android/content/integrity/AtomicFormula.java b/core/java/android/content/integrity/AtomicFormula.java index f888813135be..1b5f64c456a1 100644 --- a/core/java/android/content/integrity/AtomicFormula.java +++ b/core/java/android/content/integrity/AtomicFormula.java @@ -261,8 +261,8 @@ public abstract class AtomicFormula extends IntegrityFormula { } LongAtomicFormula that = (LongAtomicFormula) o; return getKey() == that.getKey() - && mValue == that.mValue - && mOperator == that.mOperator; + && Objects.equals(mValue, that.mValue) + && Objects.equals(mOperator, that.mOperator); } @Override @@ -628,7 +628,7 @@ public abstract class AtomicFormula extends IntegrityFormula { return false; } BooleanAtomicFormula that = (BooleanAtomicFormula) o; - return getKey() == that.getKey() && mValue == that.mValue; + return getKey() == that.getKey() && Objects.equals(mValue, that.mValue); } @Override diff --git a/core/java/android/content/pm/PackageManager.java b/core/java/android/content/pm/PackageManager.java index a90f6d625c51..c41d5850577c 100644 --- a/core/java/android/content/pm/PackageManager.java +++ b/core/java/android/content/pm/PackageManager.java @@ -189,12 +189,12 @@ public abstract class PackageManager { @VisibleForTesting public Property(@NonNull String name, int type, @NonNull String packageName, @Nullable String className) { - assert name != null; - assert type >= TYPE_BOOLEAN && type <= TYPE_STRING; - assert packageName != null; - this.mName = name; + if (type < TYPE_BOOLEAN || type > TYPE_STRING) { + throw new IllegalArgumentException("Invalid type"); + } + this.mName = Objects.requireNonNull(name); this.mType = type; - this.mPackageName = packageName; + this.mPackageName = Objects.requireNonNull(packageName); this.mClassName = className; } /** @hide */ @@ -442,9 +442,8 @@ public abstract class PackageManager { */ public ComponentEnabledSetting(@NonNull ComponentName componentName, @EnabledState int newState, @EnabledFlags int flags) { - Objects.nonNull(componentName); mPackageName = null; - mComponentName = componentName; + mComponentName = Objects.requireNonNull(componentName); mEnabledState = newState; mEnabledFlags = flags; } @@ -460,8 +459,7 @@ public abstract class PackageManager { */ public ComponentEnabledSetting(@NonNull String packageName, @EnabledState int newState, @EnabledFlags int flags) { - Objects.nonNull(packageName); - mPackageName = packageName; + mPackageName = Objects.requireNonNull(packageName); mComponentName = null; mEnabledState = newState; mEnabledFlags = flags; diff --git a/core/java/android/content/pm/ShortcutInfo.java b/core/java/android/content/pm/ShortcutInfo.java index 1f83d7532f04..295df5cc42d0 100644 --- a/core/java/android/content/pm/ShortcutInfo.java +++ b/core/java/android/content/pm/ShortcutInfo.java @@ -50,6 +50,7 @@ import android.view.contentcapture.ContentCaptureContext; import com.android.internal.annotations.VisibleForTesting; import com.android.internal.util.Preconditions; +import java.lang.IllegalArgumentException; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; @@ -1360,7 +1361,9 @@ public final class ShortcutInfo implements Parcelable { @NonNull public Builder setIntents(@NonNull Intent[] intents) { Objects.requireNonNull(intents, "intents cannot be null"); - Objects.requireNonNull(intents.length, "intents cannot be empty"); + if (intents.length == 0) { + throw new IllegalArgumentException("intents cannot be empty"); + } for (Intent intent : intents) { Objects.requireNonNull(intent, "intents cannot contain null"); Objects.requireNonNull(intent.getAction(), "intent's action must be set"); @@ -1398,7 +1401,9 @@ public final class ShortcutInfo implements Parcelable { @NonNull public Builder setPersons(@NonNull Person[] persons) { Objects.requireNonNull(persons, "persons cannot be null"); - Objects.requireNonNull(persons.length, "persons cannot be empty"); + if (persons.length == 0) { + throw new IllegalArgumentException("persons cannot be empty"); + } for (Person person : persons) { Objects.requireNonNull(person, "persons cannot contain null"); } diff --git a/core/java/android/hardware/CameraInfo.java b/core/java/android/hardware/CameraInfo.java index 072be50ad2fb..41ef6aa54ae3 100644 --- a/core/java/android/hardware/CameraInfo.java +++ b/core/java/android/hardware/CameraInfo.java @@ -60,4 +60,4 @@ public class CameraInfo implements Parcelable { return new CameraInfo[size]; } }; -}; +} diff --git a/core/java/android/hardware/CameraStatus.java b/core/java/android/hardware/CameraStatus.java index 874af297683e..fa35efbcee91 100644 --- a/core/java/android/hardware/CameraStatus.java +++ b/core/java/android/hardware/CameraStatus.java @@ -68,4 +68,4 @@ public class CameraStatus implements Parcelable { return new CameraStatus[size]; } }; -}; +} diff --git a/core/java/android/hardware/biometrics/CryptoObject.java b/core/java/android/hardware/biometrics/CryptoObject.java index d41570682fe1..267ef3637ce7 100644 --- a/core/java/android/hardware/biometrics/CryptoObject.java +++ b/core/java/android/hardware/biometrics/CryptoObject.java @@ -118,4 +118,4 @@ public class CryptoObject { } return AndroidKeyStoreProvider.getKeyStoreOperationHandle(mCrypto); } -}; +} diff --git a/core/java/android/hardware/camera2/impl/FrameNumberTracker.java b/core/java/android/hardware/camera2/impl/FrameNumberTracker.java index 7b6a457411f3..8304796f636a 100644 --- a/core/java/android/hardware/camera2/impl/FrameNumberTracker.java +++ b/core/java/android/hardware/camera2/impl/FrameNumberTracker.java @@ -26,6 +26,7 @@ import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; +import java.util.Map; import java.util.TreeMap; /** @@ -63,11 +64,11 @@ public class FrameNumberTracker { } private void update() { - Iterator iter = mFutureErrorMap.entrySet().iterator(); + Iterator<Map.Entry<Long, Integer>> iter = mFutureErrorMap.entrySet().iterator(); while (iter.hasNext()) { - TreeMap.Entry pair = (TreeMap.Entry)iter.next(); - Long errorFrameNumber = (Long)pair.getKey(); - int requestType = (int) pair.getValue(); + Map.Entry<Long, Integer> pair = iter.next(); + long errorFrameNumber = pair.getKey(); + int requestType = pair.getValue(); Boolean removeError = false; if (errorFrameNumber == mCompletedFrameNumber[requestType] + 1) { removeError = true; diff --git a/core/java/android/hardware/camera2/marshal/impl/MarshalQueryableEnum.java b/core/java/android/hardware/camera2/marshal/impl/MarshalQueryableEnum.java index 621a418f43c9..92a2fb6f16b1 100644 --- a/core/java/android/hardware/camera2/marshal/impl/MarshalQueryableEnum.java +++ b/core/java/android/hardware/camera2/marshal/impl/MarshalQueryableEnum.java @@ -103,6 +103,7 @@ public class MarshalQueryableEnum<T extends Enum<T>> implements MarshalQueryable return new MarshalerEnum(managedType, nativeType); } + @SuppressWarnings("ReturnValueIgnored") @Override public boolean isTypeMappingSupported(TypeReference<T> managedType, int nativeType) { if (nativeType == TYPE_INT32 || nativeType == TYPE_BYTE) { diff --git a/core/java/android/hardware/camera2/params/OutputConfiguration.java b/core/java/android/hardware/camera2/params/OutputConfiguration.java index 4a2517763aae..bbe2319d88cc 100644 --- a/core/java/android/hardware/camera2/params/OutputConfiguration.java +++ b/core/java/android/hardware/camera2/params/OutputConfiguration.java @@ -1270,7 +1270,8 @@ public final class OutputConfiguration implements Parcelable { return false; } for (int j = 0; j < mSensorPixelModesUsed.size(); j++) { - if (mSensorPixelModesUsed.get(j) != other.mSensorPixelModesUsed.get(j)) { + if (!Objects.equals( + mSensorPixelModesUsed.get(j), other.mSensorPixelModesUsed.get(j))) { return false; } } diff --git a/core/java/android/hardware/fingerprint/Fingerprint.java b/core/java/android/hardware/fingerprint/Fingerprint.java index 9ce834ca5981..c01c94c43997 100644 --- a/core/java/android/hardware/fingerprint/Fingerprint.java +++ b/core/java/android/hardware/fingerprint/Fingerprint.java @@ -69,4 +69,4 @@ public final class Fingerprint extends BiometricAuthenticator.Identifier { return new Fingerprint[size]; } }; -};
\ No newline at end of file +}
\ No newline at end of file diff --git a/core/java/android/net/netstats/NetworkStatsDataMigrationUtils.java b/core/java/android/net/netstats/NetworkStatsDataMigrationUtils.java index 76ee097c8c93..5eeb6076b71d 100644 --- a/core/java/android/net/netstats/NetworkStatsDataMigrationUtils.java +++ b/core/java/android/net/netstats/NetworkStatsDataMigrationUtils.java @@ -53,8 +53,8 @@ import java.lang.annotation.RetentionPolicy; import java.net.ProtocolException; import java.util.ArrayList; import java.util.Arrays; -import java.util.HashMap; import java.util.HashSet; +import java.util.Map; import java.util.Set; /** @@ -89,12 +89,10 @@ public class NetworkStatsDataMigrationUtils { @Retention(RetentionPolicy.SOURCE) public @interface Prefix {} - private static final HashMap<String, String> sPrefixLegacyFileNameMap = - new HashMap<String, String>() {{ - put(PREFIX_XT, "netstats_xt.bin"); - put(PREFIX_UID, "netstats_uid.bin"); - put(PREFIX_UID_TAG, "netstats_uid.bin"); - }}; + private static final Map<String, String> sPrefixLegacyFileNameMap = Map.of( + PREFIX_XT, "netstats_xt.bin", + PREFIX_UID, "netstats_uid.bin", + PREFIX_UID_TAG, "netstats_uid.bin"); // These version constants are copied from NetworkStatsCollection/History, which is okay for // OEMs to modify to adapt their own logic. diff --git a/core/java/android/net/vcn/persistablebundleutils/TunnelConnectionParamsUtils.java b/core/java/android/net/vcn/persistablebundleutils/TunnelConnectionParamsUtils.java index 4bc5b49aa207..0427742f9c0a 100644 --- a/core/java/android/net/vcn/persistablebundleutils/TunnelConnectionParamsUtils.java +++ b/core/java/android/net/vcn/persistablebundleutils/TunnelConnectionParamsUtils.java @@ -53,7 +53,7 @@ public final class TunnelConnectionParamsUtils { if (in.keySet().size() != EXPECTED_BUNDLE_KEY_CNT) { throw new IllegalArgumentException( String.format( - "Expect PersistableBundle to have %d element but found: %d", + "Expect PersistableBundle to have %d element but found: %s", EXPECTED_BUNDLE_KEY_CNT, in.keySet())); } diff --git a/core/java/android/nfc/NfcAdapter.java b/core/java/android/nfc/NfcAdapter.java index 64c121194932..3282d567d369 100644 --- a/core/java/android/nfc/NfcAdapter.java +++ b/core/java/android/nfc/NfcAdapter.java @@ -29,7 +29,6 @@ import android.app.PendingIntent; import android.compat.annotation.UnsupportedAppUsage; import android.content.Context; import android.content.IntentFilter; -import android.content.pm.IPackageManager; import android.content.pm.PackageManager; import android.net.Uri; import android.nfc.tech.MifareClassic; @@ -525,66 +524,6 @@ public final class NfcAdapter { } /** - * Helper to check if this device has FEATURE_NFC_BEAM, but without using - * a context. - * Equivalent to - * context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_NFC_BEAM) - */ - private static boolean hasBeamFeature() { - IPackageManager pm = ActivityThread.getPackageManager(); - if (pm == null) { - Log.e(TAG, "Cannot get package manager, assuming no Android Beam feature"); - return false; - } - try { - return pm.hasSystemFeature(PackageManager.FEATURE_NFC_BEAM, 0); - } catch (RemoteException e) { - Log.e(TAG, "Package manager query failed, assuming no Android Beam feature", e); - return false; - } - } - - /** - * Helper to check if this device has FEATURE_NFC, but without using - * a context. - * Equivalent to - * context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_NFC) - */ - private static boolean hasNfcFeature() { - IPackageManager pm = ActivityThread.getPackageManager(); - if (pm == null) { - Log.e(TAG, "Cannot get package manager, assuming no NFC feature"); - return false; - } - try { - return pm.hasSystemFeature(PackageManager.FEATURE_NFC, 0); - } catch (RemoteException e) { - Log.e(TAG, "Package manager query failed, assuming no NFC feature", e); - return false; - } - } - - /** - * Helper to check if this device is NFC HCE capable, by checking for - * FEATURE_NFC_HOST_CARD_EMULATION and/or FEATURE_NFC_HOST_CARD_EMULATION_NFCF, - * but without using a context. - */ - private static boolean hasNfcHceFeature() { - IPackageManager pm = ActivityThread.getPackageManager(); - if (pm == null) { - Log.e(TAG, "Cannot get package manager, assuming no NFC feature"); - return false; - } - try { - return pm.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION, 0) - || pm.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION_NFCF, 0); - } catch (RemoteException e) { - Log.e(TAG, "Package manager query failed, assuming no NFC feature", e); - return false; - } - } - - /** * Return list of Secure Elements which support off host card emulation. * * @return List<String> containing secure elements on the device which supports @@ -593,23 +532,21 @@ public final class NfcAdapter { * @hide */ public @NonNull List<String> getSupportedOffHostSecureElements() { + if (mContext == null) { + throw new UnsupportedOperationException("You need a context on NfcAdapter to use the " + + " getSupportedOffHostSecureElements APIs"); + } List<String> offHostSE = new ArrayList<String>(); - IPackageManager pm = ActivityThread.getPackageManager(); + PackageManager pm = mContext.getPackageManager(); if (pm == null) { Log.e(TAG, "Cannot get package manager, assuming no off-host CE feature"); return offHostSE; } - try { - if (pm.hasSystemFeature(PackageManager.FEATURE_NFC_OFF_HOST_CARD_EMULATION_UICC, 0)) { - offHostSE.add("SIM"); - } - if (pm.hasSystemFeature(PackageManager.FEATURE_NFC_OFF_HOST_CARD_EMULATION_ESE, 0)) { - offHostSE.add("eSE"); - } - } catch (RemoteException e) { - Log.e(TAG, "Package manager query failed, assuming no off-host CE feature", e); - offHostSE.clear(); - return offHostSE; + if (pm.hasSystemFeature(PackageManager.FEATURE_NFC_OFF_HOST_CARD_EMULATION_UICC)) { + offHostSE.add("SIM"); + } + if (pm.hasSystemFeature(PackageManager.FEATURE_NFC_OFF_HOST_CARD_EMULATION_ESE)) { + offHostSE.add("eSE"); } return offHostSE; } @@ -621,10 +558,19 @@ public final class NfcAdapter { */ @UnsupportedAppUsage public static synchronized NfcAdapter getNfcAdapter(Context context) { + if (context == null) { + if (sNullContextNfcAdapter == null) { + sNullContextNfcAdapter = new NfcAdapter(null); + } + return sNullContextNfcAdapter; + } if (!sIsInitialized) { - sHasNfcFeature = hasNfcFeature(); - sHasBeamFeature = hasBeamFeature(); - boolean hasHceFeature = hasNfcHceFeature(); + PackageManager pm = context.getPackageManager(); + sHasNfcFeature = pm.hasSystemFeature(PackageManager.FEATURE_NFC); + sHasBeamFeature = pm.hasSystemFeature(PackageManager.FEATURE_NFC_BEAM); + boolean hasHceFeature = + pm.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION) + || pm.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION_NFCF); /* is this device meant to have NFC */ if (!sHasNfcFeature && !hasHceFeature) { Log.v(TAG, "this device does not have NFC support"); @@ -660,12 +606,6 @@ public final class NfcAdapter { sIsInitialized = true; } - if (context == null) { - if (sNullContextNfcAdapter == null) { - sNullContextNfcAdapter = new NfcAdapter(null); - } - return sNullContextNfcAdapter; - } NfcAdapter adapter = sNfcAdapters.get(context); if (adapter == null) { adapter = new NfcAdapter(context); @@ -676,8 +616,12 @@ public final class NfcAdapter { /** get handle to NFC service interface */ private static INfcAdapter getServiceInterface() { + if (!sHasNfcFeature) { + /* NFC is not supported */ + return null; + } /* get a handle to NFC service */ - IBinder b = ServiceManager.getService("nfc"); + IBinder b = ServiceManager.waitForService("nfc"); if (b == null) { return null; } @@ -707,6 +651,15 @@ public final class NfcAdapter { "context not associated with any application (using a mock context?)"); } + synchronized (NfcAdapter.class) { + if (!sIsInitialized) { + PackageManager pm = context.getPackageManager(); + sHasNfcFeature = pm.hasSystemFeature(PackageManager.FEATURE_NFC); + } + if (!sHasNfcFeature) { + return null; + } + } if (getServiceInterface() == null) { // NFC is not available return null; diff --git a/core/java/android/nfc/cardemulation/CardEmulation.java b/core/java/android/nfc/cardemulation/CardEmulation.java index 0b56d19201fb..6a4209135c66 100644 --- a/core/java/android/nfc/cardemulation/CardEmulation.java +++ b/core/java/android/nfc/cardemulation/CardEmulation.java @@ -22,11 +22,9 @@ import android.annotation.RequiresPermission; import android.annotation.SdkConstant; import android.annotation.SdkConstant.SdkConstantType; import android.app.Activity; -import android.app.ActivityThread; import android.content.ComponentName; import android.content.Context; import android.content.Intent; -import android.content.pm.IPackageManager; import android.content.pm.PackageManager; import android.nfc.INfcCardEmulation; import android.nfc.NfcAdapter; @@ -158,18 +156,13 @@ public final class CardEmulation { throw new UnsupportedOperationException(); } if (!sIsInitialized) { - IPackageManager pm = ActivityThread.getPackageManager(); + PackageManager pm = context.getPackageManager(); if (pm == null) { Log.e(TAG, "Cannot get PackageManager"); throw new UnsupportedOperationException(); } - try { - if (!pm.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION, 0)) { - Log.e(TAG, "This device does not support card emulation"); - throw new UnsupportedOperationException(); - } - } catch (RemoteException e) { - Log.e(TAG, "PackageManager query failed."); + if (!pm.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION)) { + Log.e(TAG, "This device does not support card emulation"); throw new UnsupportedOperationException(); } sIsInitialized = true; diff --git a/core/java/android/nfc/cardemulation/NfcFCardEmulation.java b/core/java/android/nfc/cardemulation/NfcFCardEmulation.java index 3c924556365e..48bbf5b61052 100644 --- a/core/java/android/nfc/cardemulation/NfcFCardEmulation.java +++ b/core/java/android/nfc/cardemulation/NfcFCardEmulation.java @@ -17,10 +17,8 @@ package android.nfc.cardemulation; import android.app.Activity; -import android.app.ActivityThread; import android.content.ComponentName; import android.content.Context; -import android.content.pm.IPackageManager; import android.content.pm.PackageManager; import android.nfc.INfcFCardEmulation; import android.nfc.NfcAdapter; @@ -70,18 +68,13 @@ public final class NfcFCardEmulation { throw new UnsupportedOperationException(); } if (!sIsInitialized) { - IPackageManager pm = ActivityThread.getPackageManager(); + PackageManager pm = context.getPackageManager(); if (pm == null) { Log.e(TAG, "Cannot get PackageManager"); throw new UnsupportedOperationException(); } - try { - if (!pm.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION_NFCF, 0)) { - Log.e(TAG, "This device does not support NFC-F card emulation"); - throw new UnsupportedOperationException(); - } - } catch (RemoteException e) { - Log.e(TAG, "PackageManager query failed."); + if (!pm.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION_NFCF)) { + Log.e(TAG, "This device does not support NFC-F card emulation"); throw new UnsupportedOperationException(); } sIsInitialized = true; diff --git a/core/java/android/os/BaseBundle.java b/core/java/android/os/BaseBundle.java index 0418a4bb9f80..b599028ccb9b 100644 --- a/core/java/android/os/BaseBundle.java +++ b/core/java/android/os/BaseBundle.java @@ -438,8 +438,11 @@ public class BaseBundle { map.ensureCapacity(count); } try { + // recycleParcel being false implies that we do not own the parcel. In this case, do + // not use lazy values to be safe, as the parcel could be recycled outside of our + // control. recycleParcel &= parcelledData.readArrayMap(map, count, !parcelledByNative, - /* lazy */ true, mClassLoader); + /* lazy */ recycleParcel, mClassLoader); } catch (BadParcelableException e) { if (sShouldDefuse) { Log.w(TAG, "Failed to parse Bundle, but defusing quietly", e); @@ -1845,7 +1848,6 @@ public class BaseBundle { // bundle immediately; neither of which is obvious. synchronized (this) { initializeFromParcelLocked(parcel, /*recycleParcel=*/ false, isNativeBundle); - unparcel(/* itemwise */ true); } return; } diff --git a/core/java/android/os/Binder.java b/core/java/android/os/Binder.java index 6d5c741e7dc7..3d10661062ea 100644 --- a/core/java/android/os/Binder.java +++ b/core/java/android/os/Binder.java @@ -911,11 +911,15 @@ public class Binder implements IBinder { final String transactionName = getTransactionName(transactionCode); final StringBuffer buf = new StringBuffer(); + // Keep trace name consistent with cpp trace name in: + // system/tools/aidl/generate_cpp.cpp + buf.append("AIDL::java::"); if (transactionName != null) { - buf.append(mSimpleDescriptor).append(":").append(transactionName); + buf.append(mSimpleDescriptor).append("::").append(transactionName); } else { - buf.append(mSimpleDescriptor).append("#").append(transactionCode); + buf.append(mSimpleDescriptor).append("::#").append(transactionCode); } + buf.append("::server"); transactionTraceName = buf.toString(); mTransactionTraceNames.setRelease(index, transactionTraceName); diff --git a/core/java/android/os/BinderProxy.java b/core/java/android/os/BinderProxy.java index 63306612fdaf..1929a4d562d4 100644 --- a/core/java/android/os/BinderProxy.java +++ b/core/java/android/os/BinderProxy.java @@ -536,8 +536,8 @@ public final class BinderProxy implements IBinder { mWarnOnBlocking = false; warnOnBlocking = false; - if (Build.IS_USERDEBUG) { - // Log this as a WTF on userdebug builds. + if (Build.IS_USERDEBUG || Build.IS_ENG) { + // Log this as a WTF on userdebug and eng builds. Log.wtf(Binder.TAG, "Outgoing transactions from this process must be FLAG_ONEWAY", new Throwable()); diff --git a/core/java/android/os/OWNERS b/core/java/android/os/OWNERS index d84037f66648..1924dc6b651b 100644 --- a/core/java/android/os/OWNERS +++ b/core/java/android/os/OWNERS @@ -70,3 +70,6 @@ per-file Vintf* = file:/platform/system/libvintf:/OWNERS # Tracing per-file Trace.java = file:/TRACE_OWNERS + +# PermissionEnforcer +per-file PermissionEnforcer.java = tweek@google.com, brufino@google.com diff --git a/core/java/android/os/Parcel.java b/core/java/android/os/Parcel.java index 8ffb94b6ffd1..7e15f07be05a 100644 --- a/core/java/android/os/Parcel.java +++ b/core/java/android/os/Parcel.java @@ -562,9 +562,11 @@ public final class Parcel { */ public final void recycle() { if (mRecycled) { - Log.w(TAG, "Recycle called on unowned Parcel. (recycle twice?) Here: " + Log.wtf(TAG, "Recycle called on unowned Parcel. (recycle twice?) Here: " + Log.getStackTraceString(new Throwable()) + " Original recycle call (if DEBUG_RECYCLE): ", mStack); + + return; } mRecycled = true; diff --git a/core/java/android/os/PermissionEnforcer.java b/core/java/android/os/PermissionEnforcer.java new file mode 100644 index 000000000000..221e89a6a76f --- /dev/null +++ b/core/java/android/os/PermissionEnforcer.java @@ -0,0 +1,101 @@ +/* + * Copyright (C) 2022 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.os; + +import android.annotation.NonNull; +import android.annotation.SystemService; +import android.content.AttributionSource; +import android.content.Context; +import android.content.PermissionChecker; +import android.permission.PermissionCheckerManager; + +/** + * PermissionEnforcer check permissions for AIDL-generated services which use + * the @EnforcePermission annotation. + * + * <p>AIDL services may be annotated with @EnforcePermission which will trigger + * the generation of permission check code. This generated code relies on + * PermissionEnforcer to validate the permissions. The methods available are + * purposely similar to the AIDL annotation syntax. + * + * @see android.permission.PermissionManager + * + * @hide + */ +@SystemService(Context.PERMISSION_ENFORCER_SERVICE) +public class PermissionEnforcer { + + private final Context mContext; + + /** Protected constructor. Allows subclasses to instantiate an object + * without using a Context. + */ + protected PermissionEnforcer() { + mContext = null; + } + + /** Constructor, prefer using the fromContext static method when possible */ + public PermissionEnforcer(@NonNull Context context) { + mContext = context; + } + + @PermissionCheckerManager.PermissionResult + protected int checkPermission(@NonNull String permission, @NonNull AttributionSource source) { + return PermissionChecker.checkPermissionForDataDelivery( + mContext, permission, PermissionChecker.PID_UNKNOWN, source, "" /* message */); + } + + public void enforcePermission(@NonNull String permission, @NonNull + AttributionSource source) throws SecurityException { + int result = checkPermission(permission, source); + if (result != PermissionCheckerManager.PERMISSION_GRANTED) { + throw new SecurityException("Access denied, requires: " + permission); + } + } + + public void enforcePermissionAllOf(@NonNull String[] permissions, + @NonNull AttributionSource source) throws SecurityException { + for (String permission : permissions) { + int result = checkPermission(permission, source); + if (result != PermissionCheckerManager.PERMISSION_GRANTED) { + throw new SecurityException("Access denied, requires: allOf={" + + String.join(", ", permissions) + "}"); + } + } + } + + public void enforcePermissionAnyOf(@NonNull String[] permissions, + @NonNull AttributionSource source) throws SecurityException { + for (String permission : permissions) { + int result = checkPermission(permission, source); + if (result == PermissionCheckerManager.PERMISSION_GRANTED) { + return; + } + } + throw new SecurityException("Access denied, requires: anyOf={" + + String.join(", ", permissions) + "}"); + } + + /** + * Returns a new PermissionEnforcer based on a Context. + * + * @hide + */ + public static PermissionEnforcer fromContext(@NonNull Context context) { + return context.getSystemService(PermissionEnforcer.class); + } +} diff --git a/core/java/android/os/ServiceManager.java b/core/java/android/os/ServiceManager.java index ba5ed4360cd7..9ea42780981d 100644 --- a/core/java/android/os/ServiceManager.java +++ b/core/java/android/os/ServiceManager.java @@ -258,12 +258,14 @@ public final class ServiceManager { * waitForService should always be able to return the service. * @hide */ + @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) + @NonNull public static String[] getDeclaredInstances(@NonNull String iface) { try { return getIServiceManager().getDeclaredInstances(iface); } catch (RemoteException e) { Log.e(TAG, "error in getDeclaredInstances", e); - return null; + throw e.rethrowFromSystemServer(); } } diff --git a/core/java/android/os/Trace.java b/core/java/android/os/Trace.java index 4965057a7fdb..726ef4d2e311 100644 --- a/core/java/android/os/Trace.java +++ b/core/java/android/os/Trace.java @@ -100,6 +100,7 @@ public final class Trace { /** @hide */ public static final long TRACE_TAG_VIBRATOR = 1L << 23; /** @hide */ + @SystemApi(client = MODULE_LIBRARIES) public static final long TRACE_TAG_AIDL = 1L << 24; /** @hide */ public static final long TRACE_TAG_NNAPI = 1L << 25; diff --git a/core/java/android/os/UserManager.java b/core/java/android/os/UserManager.java index 0ffdfc6cbcb1..4b9f8921d34f 100644 --- a/core/java/android/os/UserManager.java +++ b/core/java/android/os/UserManager.java @@ -1485,6 +1485,22 @@ public class UserManager { public static final String KEY_RESTRICTIONS_PENDING = "restrictions_pending"; /** + * Specifies if a user is not allowed to use 2g networks. + * + * <p>This restriction can only be set by a device owner or a profile owner of an + * organization-owned managed profile on the parent profile. + * In all cases, the setting applies globally on the device and will prevent the device from + * scanning for or connecting to 2g networks, except in the case of an emergency. + * + * <p>The default value is <code>false</code>. + * + * @see DevicePolicyManager#addUserRestriction(ComponentName, String) + * @see DevicePolicyManager#clearUserRestriction(ComponentName, String) + * @see #getUserRestrictions() + */ + public static final String DISALLOW_CELLULAR_2G = "no_cellular_2g"; + + /** * List of key values that can be passed into the various user restriction related methods * in {@link UserManager} & {@link DevicePolicyManager}. * Note: This is slightly different from the real set of user restrictions listed in {@link @@ -1565,6 +1581,7 @@ public class UserManager { DISALLOW_SHARING_ADMIN_CONFIGURED_WIFI, DISALLOW_WIFI_DIRECT, DISALLOW_ADD_WIFI_CONFIG, + DISALLOW_CELLULAR_2G, }) @Retention(RetentionPolicy.SOURCE) public @interface UserRestrictionKey {} diff --git a/core/java/android/security/keymaster/ExportResult.java b/core/java/android/security/keymaster/ExportResult.java index 2c382efab1be..c78fb1a1f6b5 100644 --- a/core/java/android/security/keymaster/ExportResult.java +++ b/core/java/android/security/keymaster/ExportResult.java @@ -61,4 +61,4 @@ public class ExportResult implements Parcelable { out.writeInt(resultCode); out.writeByteArray(exportData); } -}; +} diff --git a/core/java/android/text/style/AccessibilityURLSpan.java b/core/java/android/text/style/AccessibilityURLSpan.java index bd816234a652..e280bdf8b339 100644 --- a/core/java/android/text/style/AccessibilityURLSpan.java +++ b/core/java/android/text/style/AccessibilityURLSpan.java @@ -26,6 +26,7 @@ import android.view.accessibility.AccessibilityNodeInfo; * It is used to replace URLSpans in {@link AccessibilityNodeInfo#setText(CharSequence)} * @hide */ +@SuppressWarnings("ParcelableCreator") public class AccessibilityURLSpan extends URLSpan implements Parcelable { final AccessibilityClickableSpan mAccessibilityClickableSpan; diff --git a/core/java/android/util/AndroidException.java b/core/java/android/util/AndroidException.java index 1345ddf189e1..d1b9d9f3c53a 100644 --- a/core/java/android/util/AndroidException.java +++ b/core/java/android/util/AndroidException.java @@ -40,5 +40,5 @@ public class AndroidException extends Exception { boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } -}; +} diff --git a/core/java/android/util/AndroidRuntimeException.java b/core/java/android/util/AndroidRuntimeException.java index 2b824bf9cb2a..72c34d8b75ac 100644 --- a/core/java/android/util/AndroidRuntimeException.java +++ b/core/java/android/util/AndroidRuntimeException.java @@ -34,5 +34,4 @@ public class AndroidRuntimeException extends RuntimeException { public AndroidRuntimeException(Exception cause) { super(cause); } -}; - +} diff --git a/core/java/android/util/OWNERS b/core/java/android/util/OWNERS index d4cf6e6e90c2..377200675ddf 100644 --- a/core/java/android/util/OWNERS +++ b/core/java/android/util/OWNERS @@ -1,6 +1,6 @@ per-file Dump* = file:/core/java/com/android/internal/util/dump/OWNERS per-file FeatureFlagUtils.java = sbasi@google.com -per-file FeatureFlagUtils.java = tmfang@google.com +per-file FeatureFlagUtils.java = edgarwang@google.com per-file AttributeSet.java = file:/core/java/android/content/res/OWNERS per-file TypedValue.java = file:/core/java/android/content/res/OWNERS diff --git a/core/java/android/util/Range.java b/core/java/android/util/Range.java index 9fd0ab99f01b..41c171a0bbd7 100644 --- a/core/java/android/util/Range.java +++ b/core/java/android/util/Range.java @@ -356,4 +356,4 @@ public final class Range<T extends Comparable<? super T>> { private final T mLower; private final T mUpper; -}; +} diff --git a/core/java/android/util/TypedValue.java b/core/java/android/util/TypedValue.java index 19de396c4a4a..44318bbc5468 100644 --- a/core/java/android/util/TypedValue.java +++ b/core/java/android/util/TypedValue.java @@ -696,5 +696,5 @@ public class TypedValue { sb.append("}"); return sb.toString(); } -}; +} diff --git a/core/java/android/util/apk/ApkSignatureSchemeV2Verifier.java b/core/java/android/util/apk/ApkSignatureSchemeV2Verifier.java index c8c1fd4eba21..eb467e0dcc38 100644 --- a/core/java/android/util/apk/ApkSignatureSchemeV2Verifier.java +++ b/core/java/android/util/apk/ApkSignatureSchemeV2Verifier.java @@ -93,8 +93,9 @@ public class ApkSignatureSchemeV2Verifier { * associated with each signer. * * @throws SignatureNotFoundException if the APK is not signed using APK Signature Scheme v2. - * @throws SecurityException if a APK Signature Scheme v2 signature of this APK does not verify. - * @throws IOException if an I/O error occurs while reading the APK file. + * @throws SecurityException if an APK Signature Scheme v2 signature of this APK does + * not verify. + * @throws IOException if an I/O error occurs while reading the APK file. */ public static X509Certificate[][] verify(String apkFile) throws SignatureNotFoundException, SecurityException, IOException { @@ -386,7 +387,6 @@ public class ApkSignatureSchemeV2Verifier { break; } } - return; } static byte[] getVerityRootHash(String apkPath) diff --git a/core/java/android/view/CutoutSpecification.java b/core/java/android/view/CutoutSpecification.java index f8aa934af595..3fc3b6a3ccb3 100644 --- a/core/java/android/view/CutoutSpecification.java +++ b/core/java/android/view/CutoutSpecification.java @@ -394,7 +394,6 @@ public class CutoutSpecification { Log.e(TAG, "According to SVG definition, it shouldn't happen"); return; } - spec.trim(); translateMatrix(); final Path newPath = PathParser.createPathFromPathData(spec); diff --git a/core/java/android/view/RemoteAnimationDefinition.java b/core/java/android/view/RemoteAnimationDefinition.java index ea9799584e20..ff282ba0da39 100644 --- a/core/java/android/view/RemoteAnimationDefinition.java +++ b/core/java/android/view/RemoteAnimationDefinition.java @@ -19,6 +19,7 @@ package android.view; import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED; import android.annotation.Nullable; +import android.annotation.NonNull; import android.app.WindowConfiguration.ActivityType; import android.compat.annotation.UnsupportedAppUsage; import android.os.IBinder; @@ -157,7 +158,7 @@ public class RemoteAnimationDefinition implements Parcelable { } } - public static final @android.annotation.NonNull Creator<RemoteAnimationDefinition> CREATOR = + public static final @NonNull Creator<RemoteAnimationDefinition> CREATOR = new Creator<RemoteAnimationDefinition>() { public RemoteAnimationDefinition createFromParcel(Parcel in) { return new RemoteAnimationDefinition(in); @@ -199,18 +200,17 @@ public class RemoteAnimationDefinition implements Parcelable { return 0; } - private static final @android.annotation.NonNull Creator<RemoteAnimationAdapterEntry> CREATOR - = new Creator<RemoteAnimationAdapterEntry>() { - - @Override - public RemoteAnimationAdapterEntry createFromParcel(Parcel in) { - return new RemoteAnimationAdapterEntry(in); - } - - @Override - public RemoteAnimationAdapterEntry[] newArray(int size) { - return new RemoteAnimationAdapterEntry[size]; - } - }; + public static final @NonNull Parcelable.Creator<RemoteAnimationAdapterEntry> CREATOR = + new Parcelable.Creator<RemoteAnimationAdapterEntry>() { + @Override + public RemoteAnimationAdapterEntry createFromParcel(Parcel in) { + return new RemoteAnimationAdapterEntry(in); + } + + @Override + public RemoteAnimationAdapterEntry[] newArray(int size) { + return new RemoteAnimationAdapterEntry[size]; + } + }; } } diff --git a/core/java/android/webkit/ConsoleMessage.java b/core/java/android/webkit/ConsoleMessage.java index 5474557c9998..89cb6b2761be 100644 --- a/core/java/android/webkit/ConsoleMessage.java +++ b/core/java/android/webkit/ConsoleMessage.java @@ -68,4 +68,4 @@ public class ConsoleMessage { public int lineNumber() { return mLineNumber; } -}; +} diff --git a/core/java/android/webkit/ValueCallback.java b/core/java/android/webkit/ValueCallback.java index 5c7d97fc5d8c..3d5bb4922a77 100644 --- a/core/java/android/webkit/ValueCallback.java +++ b/core/java/android/webkit/ValueCallback.java @@ -25,4 +25,4 @@ public interface ValueCallback<T> { * @param value The value. */ public void onReceiveValue(T value); -}; +} diff --git a/core/java/android/widget/ListView.java b/core/java/android/widget/ListView.java index 5e74381dce22..510a92d1b2ca 100644 --- a/core/java/android/widget/ListView.java +++ b/core/java/android/widget/ListView.java @@ -116,9 +116,7 @@ import java.util.function.Predicate; * <p class="note">ListView attempts to reuse view objects in order to improve performance and * avoid a lag in response to user scrolls. To take advantage of this feature, check if the * {@code convertView} provided to {@code getView(...)} is null before creating or inflating a new - * view object. See - * <a href="{@docRoot}training/improving-layouts/smooth-scrolling.html"> - * Making ListView Scrolling Smooth</a> for more ways to ensure a smooth user experience.</p> + * view object.</p> * * <p>To specify an action when a user clicks or taps on a single list item, see * <a href="{@docRoot}guide/topics/ui/declaring-layout.html#HandlingUserSelections"> diff --git a/core/java/android/window/TransitionFilter.java b/core/java/android/window/TransitionFilter.java index db15145b0a1e..e62d5c95a1f8 100644 --- a/core/java/android/window/TransitionFilter.java +++ b/core/java/android/window/TransitionFilter.java @@ -296,7 +296,7 @@ public final class TransitionFilter implements Parcelable { out.append((i == 0 ? "" : ",") + TransitionInfo.modeToString(mModes[i])); } } - out.append("]").toString(); + out.append("]"); out.append(" flags=" + TransitionInfo.flagsToString(mFlags)); out.append(" mustBeTask=" + mMustBeTask); out.append(" order=" + containerOrderToString(mOrder)); diff --git a/core/java/com/android/internal/app/procstats/AssociationState.java b/core/java/com/android/internal/app/procstats/AssociationState.java index 97f4b0fc8733..a21a84261ae0 100644 --- a/core/java/com/android/internal/app/procstats/AssociationState.java +++ b/core/java/com/android/internal/app/procstats/AssociationState.java @@ -59,6 +59,7 @@ public final class AssociationState { /** * The state of the source process of an association. */ + @SuppressWarnings("ParcelableCreator") public static final class SourceState implements Parcelable { private @NonNull final ProcessStats mProcessStats; private @Nullable final AssociationState mAssociationState; diff --git a/core/java/com/android/internal/expresslog/Counter.java b/core/java/com/android/internal/expresslog/Counter.java new file mode 100644 index 000000000000..7571073a9822 --- /dev/null +++ b/core/java/com/android/internal/expresslog/Counter.java @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2022 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 com.android.internal.expresslog; + +import android.annotation.NonNull; + +import com.android.internal.util.FrameworkStatsLog; + +/** Counter encapsulates StatsD write API calls */ +public final class Counter { + + // Not instantiable. + private Counter() {} + + /** + * Increments Telemetry Express Counter metric by 1 + * @hide + */ + public static void logIncrement(@NonNull String metricId) { + logIncrement(metricId, 1); + } + + /** + * Increments Telemetry Express Counter metric by arbitrary value + * @hide + */ + public static void logIncrement(@NonNull String metricId, long amount) { + final long metricIdHash = hashString(metricId); + FrameworkStatsLog.write(FrameworkStatsLog.EXPRESS_EVENT_REPORTED, metricIdHash, amount); + } + + private static native long hashString(String stringToHash); +} diff --git a/core/java/com/android/internal/os/BatteryStatsImpl.java b/core/java/com/android/internal/os/BatteryStatsImpl.java index e290812dd73e..1e0b3cc5f27d 100644 --- a/core/java/com/android/internal/os/BatteryStatsImpl.java +++ b/core/java/com/android/internal/os/BatteryStatsImpl.java @@ -3656,6 +3656,7 @@ public class BatteryStatsImpl extends BatteryStats { public abstract T instantiateObject(); } + @SuppressWarnings("ParcelableCreator") public static class ControllerActivityCounterImpl extends ControllerActivityCounter implements Parcelable { private final Clock mClock; diff --git a/core/java/com/android/internal/os/BinderCallsStats.java b/core/java/com/android/internal/os/BinderCallsStats.java index 0a29fc5285a5..eb62cb07ee68 100644 --- a/core/java/com/android/internal/os/BinderCallsStats.java +++ b/core/java/com/android/internal/os/BinderCallsStats.java @@ -735,7 +735,7 @@ public class BinderCallsStats implements BinderInternal.Observer { } protected boolean shouldRecordDetailedData() { - return mRandom.nextInt() % mPeriodicSamplingInterval == 0; + return mRandom.nextInt(mPeriodicSamplingInterval) == 0; } /** diff --git a/core/java/com/android/internal/os/BinderLatencyObserver.java b/core/java/com/android/internal/os/BinderLatencyObserver.java index e9d55db3a5b4..1276fb980799 100644 --- a/core/java/com/android/internal/os/BinderLatencyObserver.java +++ b/core/java/com/android/internal/os/BinderLatencyObserver.java @@ -236,7 +236,7 @@ public class BinderLatencyObserver { } protected boolean shouldKeepSample() { - return mRandom.nextInt() % mPeriodicSamplingInterval == 0; + return mRandom.nextInt(mPeriodicSamplingInterval) == 0; } /** Updates the sampling interval. */ diff --git a/core/java/com/android/internal/os/LooperStats.java b/core/java/com/android/internal/os/LooperStats.java index 2805dccffe50..0645eb7f0835 100644 --- a/core/java/com/android/internal/os/LooperStats.java +++ b/core/java/com/android/internal/os/LooperStats.java @@ -290,7 +290,7 @@ public class LooperStats implements Looper.Observer { } protected boolean shouldCollectDetailedData() { - return ThreadLocalRandom.current().nextInt() % mSamplingInterval == 0; + return ThreadLocalRandom.current().nextInt(mSamplingInterval) == 0; } private static class DispatchSession { diff --git a/core/java/com/android/internal/util/LatencyTracker.java b/core/java/com/android/internal/util/LatencyTracker.java index ca40a4052ca1..ab42f877cc09 100644 --- a/core/java/com/android/internal/util/LatencyTracker.java +++ b/core/java/com/android/internal/util/LatencyTracker.java @@ -413,7 +413,7 @@ public class LatencyTracker { boolean shouldSample; int traceThreshold; synchronized (mLock) { - shouldSample = ThreadLocalRandom.current().nextInt() % mSamplingInterval == 0; + shouldSample = ThreadLocalRandom.current().nextInt(mSamplingInterval) == 0; traceThreshold = mTraceThresholdPerAction[action]; } diff --git a/core/java/com/android/internal/view/BaseSurfaceHolder.java b/core/java/com/android/internal/view/BaseSurfaceHolder.java index 32ce0fe1282b..1ae1307633bb 100644 --- a/core/java/com/android/internal/view/BaseSurfaceHolder.java +++ b/core/java/com/android/internal/view/BaseSurfaceHolder.java @@ -241,4 +241,4 @@ public abstract class BaseSurfaceHolder implements SurfaceHolder { mSurfaceFrame.right = width; mSurfaceFrame.bottom = height; } -}; +} diff --git a/core/jni/Android.bp b/core/jni/Android.bp index e032fa2d5547..7cd7d2957d25 100644 --- a/core/jni/Android.bp +++ b/core/jni/Android.bp @@ -34,6 +34,8 @@ cc_library_shared { "-Wno-error=deprecated-declarations", "-Wunused", "-Wunreachable-code", + + "-DNAMESPACE_FOR_HASH_FUNCTIONS=farmhash", ], cppflags: ["-Wno-conversion-null"], @@ -211,6 +213,7 @@ cc_library_shared { "android_content_res_Configuration.cpp", "android_security_Scrypt.cpp", "com_android_internal_content_om_OverlayConfig.cpp", + "com_android_internal_expresslog_Counter.cpp", "com_android_internal_net_NetworkUtilsInternal.cpp", "com_android_internal_os_ClassLoaderFactory.cpp", "com_android_internal_os_FuseAppLoop.cpp", @@ -244,6 +247,7 @@ cc_library_shared { "libscrypt_static", "libstatssocket_lazy", "libskia", + "libtextclassifier_hash_static", ], shared_libs: [ @@ -326,6 +330,7 @@ cc_library_shared { header_libs: [ "bionic_libc_platform_headers", "dnsproxyd_protocol_headers", + "libtextclassifier_hash_headers", ], }, host: { diff --git a/core/jni/AndroidRuntime.cpp b/core/jni/AndroidRuntime.cpp index 6a051c39cab0..949f363a58f0 100644 --- a/core/jni/AndroidRuntime.cpp +++ b/core/jni/AndroidRuntime.cpp @@ -19,6 +19,7 @@ #define LOG_NDEBUG 1 #include <android-base/macros.h> +#include <android-base/parsebool.h> #include <android-base/properties.h> #include <android/graphics/jni_runtime.h> #include <android_runtime/AndroidRuntime.h> @@ -52,6 +53,8 @@ using namespace android; using android::base::GetBoolProperty; using android::base::GetProperty; +using android::base::ParseBool; +using android::base::ParseBoolResult; extern int register_android_os_Binder(JNIEnv* env); extern int register_android_os_Process(JNIEnv* env); @@ -193,6 +196,7 @@ extern int register_android_security_Scrypt(JNIEnv *env); extern int register_com_android_internal_content_F2fsUtils(JNIEnv* env); extern int register_com_android_internal_content_NativeLibraryHelper(JNIEnv *env); extern int register_com_android_internal_content_om_OverlayConfig(JNIEnv *env); +extern int register_com_android_internal_expresslog_Counter(JNIEnv* env); extern int register_com_android_internal_net_NetworkUtilsInternal(JNIEnv* env); extern int register_com_android_internal_os_ClassLoaderFactory(JNIEnv* env); extern int register_com_android_internal_os_FuseAppLoop(JNIEnv* env); @@ -700,17 +704,24 @@ int AndroidRuntime::startVm(JavaVM** pJavaVM, JNIEnv** pEnv, bool zygote, bool p // Read if we are using the profile configuration, do this at the start since the last ART args // take precedence. - property_get("dalvik.vm.profilebootclasspath", propBuf, ""); - std::string profile_boot_class_path_flag = propBuf; - // Empty means the property is unset and we should default to the phenotype property. - // The possible values are {"true", "false", ""} - if (profile_boot_class_path_flag.empty()) { - profile_boot_class_path_flag = server_configurable_flags::GetServerConfigurableFlag( - RUNTIME_NATIVE_BOOT_NAMESPACE, - PROFILE_BOOT_CLASS_PATH, - /*default_value=*/ ""); + std::string profile_boot_class_path_flag = + server_configurable_flags::GetServerConfigurableFlag(RUNTIME_NATIVE_BOOT_NAMESPACE, + PROFILE_BOOT_CLASS_PATH, + /*default_value=*/""); + bool profile_boot_class_path; + switch (ParseBool(profile_boot_class_path_flag)) { + case ParseBoolResult::kError: + // Default to the system property. + profile_boot_class_path = + GetBoolProperty("dalvik.vm.profilebootclasspath", /*default_value=*/false); + break; + case ParseBoolResult::kTrue: + profile_boot_class_path = true; + break; + case ParseBoolResult::kFalse: + profile_boot_class_path = false; + break; } - const bool profile_boot_class_path = (profile_boot_class_path_flag == "true"); if (profile_boot_class_path) { addOption("-Xcompiler-option"); addOption("--count-hotness-in-compiled-code"); @@ -1584,6 +1595,7 @@ static const RegJNIRec gRegJNI[] = { REG_JNI(register_android_os_SharedMemory), REG_JNI(register_android_os_incremental_IncrementalManager), REG_JNI(register_com_android_internal_content_om_OverlayConfig), + REG_JNI(register_com_android_internal_expresslog_Counter), REG_JNI(register_com_android_internal_net_NetworkUtilsInternal), REG_JNI(register_com_android_internal_os_ClassLoaderFactory), REG_JNI(register_com_android_internal_os_LongArrayMultiStateCounter), diff --git a/core/jni/android_util_Binder.cpp b/core/jni/android_util_Binder.cpp index 9f88f3369ae8..01837f483f10 100644 --- a/core/jni/android_util_Binder.cpp +++ b/core/jni/android_util_Binder.cpp @@ -25,6 +25,7 @@ #include <inttypes.h> #include <mutex> #include <stdio.h> +#include <string> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> @@ -880,7 +881,7 @@ void signalExceptionForError(JNIEnv* env, jobject obj, status_t err, case FAILED_TRANSACTION: { ALOGE("!!! FAILED BINDER TRANSACTION !!! (parcel size = %d)", parcelSize); const char* exceptionToThrow; - char msg[128]; + std::string msg; // TransactionTooLargeException is a checked exception, only throw from certain methods. // TODO(b/28321379): Transaction size is the most common cause for FAILED_TRANSACTION // but it is not the only one. The Binder driver can return BR_FAILED_REPLY @@ -890,7 +891,7 @@ void signalExceptionForError(JNIEnv* env, jobject obj, status_t err, if (canThrowRemoteException && parcelSize > 200*1024) { // bona fide large payload exceptionToThrow = "android/os/TransactionTooLargeException"; - snprintf(msg, sizeof(msg)-1, "data parcel size %d bytes", parcelSize); + msg = base::StringPrintf("data parcel size %d bytes", parcelSize); } else { // Heuristic: a payload smaller than this threshold "shouldn't" be too // big, so it's probably some other, more subtle problem. In practice @@ -899,11 +900,10 @@ void signalExceptionForError(JNIEnv* env, jobject obj, status_t err, exceptionToThrow = (canThrowRemoteException) ? "android/os/DeadObjectException" : "java/lang/RuntimeException"; - snprintf(msg, sizeof(msg) - 1, - "Transaction failed on small parcel; remote process probably died, but " - "this could also be caused by running out of binder buffer space"); + msg = "Transaction failed on small parcel; remote process probably died, but " + "this could also be caused by running out of binder buffer space"; } - jniThrowException(env, exceptionToThrow, msg); + jniThrowException(env, exceptionToThrow, msg.c_str()); } break; case FDS_NOT_ALLOWED: jniThrowException(env, "java/lang/RuntimeException", diff --git a/core/jni/com_android_internal_content_NativeLibraryHelper.cpp b/core/jni/com_android_internal_content_NativeLibraryHelper.cpp index 0eb999f772d3..a50c01178083 100644 --- a/core/jni/com_android_internal_content_NativeLibraryHelper.cpp +++ b/core/jni/com_android_internal_content_NativeLibraryHelper.cpp @@ -36,6 +36,7 @@ #include <inttypes.h> #include <sys/stat.h> #include <sys/types.h> +#include <linux/fs.h> #include <memory> @@ -253,6 +254,16 @@ copyFileIfChanged(JNIEnv *env, void* arg, ZipFileRO* zipFile, ZipEntryRO zipEntr return INSTALL_FAILED_CONTAINER_ERROR; } + // If a filesystem like f2fs supports per-file compression, set the compression bit before data + // writes + unsigned int flags; + if (ioctl(fd, FS_IOC_GETFLAGS, &flags) == -1) { + ALOGE("Failed to call FS_IOC_GETFLAGS on %s: %s\n", localTmpFileName, strerror(errno)); + } else if ((flags & FS_COMPR_FL) == 0) { + flags |= FS_COMPR_FL; + ioctl(fd, FS_IOC_SETFLAGS, &flags); + } + if (!zipFile->uncompressEntry(zipEntry, fd)) { ALOGE("Failed uncompressing %s to %s\n", fileName, localTmpFileName); close(fd); diff --git a/core/jni/com_android_internal_expresslog_Counter.cpp b/core/jni/com_android_internal_expresslog_Counter.cpp new file mode 100644 index 000000000000..d4a8c23b8343 --- /dev/null +++ b/core/jni/com_android_internal_expresslog_Counter.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2022 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. + */ + +#include <nativehelper/JNIHelp.h> +#include <utils/hash/farmhash.h> + +#include "core_jni_helpers.h" + +// ---------------------------------------------------------------------------- +// JNI Glue +// ---------------------------------------------------------------------------- + +static jclass g_stringClass = nullptr; + +/** + * Class: com_android_internal_expresslog_Counter + * Method: hashString + * Signature: (Ljava/lang/String;)J + */ +static jlong hashString(JNIEnv* env, jclass /*class*/, jstring metricNameObj) { + ScopedUtfChars name(env, metricNameObj); + if (name.c_str() == nullptr) { + return 0; + } + + return static_cast<jlong>(farmhash::Fingerprint64(name.c_str(), name.size())); +} + +static const JNINativeMethod g_methods[] = { + {"hashString", "(Ljava/lang/String;)J", (void*)hashString}, +}; + +static const char* const kCounterPathName = "com/android/internal/expresslog/Counter"; + +namespace android { + +int register_com_android_internal_expresslog_Counter(JNIEnv* env) { + jclass stringClass = FindClassOrDie(env, "java/lang/String"); + g_stringClass = MakeGlobalRefOrDie(env, stringClass); + + return RegisterMethodsOrDie(env, kCounterPathName, g_methods, NELEM(g_methods)); +} + +} // namespace android diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml index 689620c13918..f244ce412d5e 100644 --- a/core/res/res/values/config.xml +++ b/core/res/res/values/config.xml @@ -342,22 +342,6 @@ <!-- Mask to use when checking skb mark defined in config_networkWakeupPacketMark above. --> <integer name="config_networkWakeupPacketMask">0</integer> - <!-- Whether the APF Filter in the device should filter out IEEE 802.3 Frames - Those frames are identified by the field Eth-type having values - less than 0x600 --> - <bool translatable="false" name="config_apfDrop802_3Frames">true</bool> - - <!-- An array of Denylisted EtherType, packets with EtherTypes within this array - will be dropped - TODO: need to put proper values, these are for testing purposes only --> - <integer-array translatable="false" name="config_apfEthTypeBlackList"> - <item>0x88A2</item> - <item>0x88A4</item> - <item>0x88B8</item> - <item>0x88CD</item> - <item>0x88E3</item> - </integer-array> - <!-- Default value for ConnectivityManager.getMultipathPreference() on metered networks. Actual device behaviour is controlled by Settings.Global.NETWORK_METERED_MULTIPATH_PREFERENCE. This is the default value of that setting. --> @@ -3589,6 +3573,12 @@ experience while the device is non-interactive. --> <bool name="config_emergencyGestureEnabled">true</bool> + <!-- Default value for Use Emergency SOS in Settings false = disabled, true = enabled --> + <bool name="config_defaultEmergencyGestureEnabled">true</bool> + + <!-- Default value for Use Play countdown alarm in Settings false = disabled, true = enabled --> + <bool name="config_defaultEmergencyGestureSoundEnabled">false</bool> + <!-- Allow the gesture power + volume up to change the ringer mode while the device is interactive. --> <bool name="config_volumeHushGestureEnabled">true</bool> @@ -4320,13 +4310,13 @@ <string name="config_mediaProjectionPermissionDialogComponent" translatable="false">com.android.systemui/com.android.systemui.media.MediaProjectionPermissionActivity</string> <!-- Corner radius of system dialogs --> - <dimen name="config_dialogCornerRadius">2dp</dimen> + <dimen name="config_dialogCornerRadius">28dp</dimen> <!-- Corner radius of system buttons --> - <dimen name="config_buttonCornerRadius">@dimen/control_corner_material</dimen> + <dimen name="config_buttonCornerRadius">4dp</dimen> <!-- Corner radius for bottom sheet system dialogs --> - <dimen name="config_bottomDialogCornerRadius">@dimen/config_dialogCornerRadius</dimen> + <dimen name="config_bottomDialogCornerRadius">16dp</dimen> <!-- Corner radius of system progress bars --> - <dimen name="config_progressBarCornerRadius">@dimen/progress_bar_corner_material</dimen> + <dimen name="config_progressBarCornerRadius">1000dp</dimen> <!-- Controls whether system buttons use all caps for text --> <bool name="config_buttonTextAllCaps">true</bool> <!-- Name of the font family used for system surfaces where the font should use medium weight --> diff --git a/core/res/res/values/dimens.xml b/core/res/res/values/dimens.xml index b754100a3ed6..8697acd71304 100644 --- a/core/res/res/values/dimens.xml +++ b/core/res/res/values/dimens.xml @@ -979,9 +979,9 @@ <dimen name="controls_thumbnail_image_max_width">280dp</dimen> <!-- System-provided radius for the background view of app widgets. The resolved value of this resource may change at runtime. --> - <dimen name="system_app_widget_background_radius">16dp</dimen> + <dimen name="system_app_widget_background_radius">28dp</dimen> <!-- System-provided radius for inner views on app widgets. The resolved value of this resource may change at runtime. --> - <dimen name="system_app_widget_inner_radius">8dp</dimen> + <dimen name="system_app_widget_inner_radius">20dp</dimen> <!-- System-provided padding for inner views on app widgets. The resolved value of this resource may change at runtime. @removed --> <dimen name="__removed_system_app_widget_internal_padding">16dp</dimen> diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml index 1f71bf9f95dd..596d89af99a6 100644 --- a/core/res/res/values/symbols.xml +++ b/core/res/res/values/symbols.xml @@ -2016,8 +2016,6 @@ <java-symbol type="integer" name="config_networkAvoidBadWifi" /> <java-symbol type="integer" name="config_networkWakeupPacketMark" /> <java-symbol type="integer" name="config_networkWakeupPacketMask" /> - <java-symbol type="bool" name="config_apfDrop802_3Frames" /> - <java-symbol type="array" name="config_apfEthTypeBlackList" /> <java-symbol type="integer" name="config_networkDefaultDailyMultipathQuotaBytes" /> <java-symbol type="integer" name="config_networkMeteredMultipathPreference" /> <java-symbol type="array" name="config_networkSupportedKeepaliveCount" /> @@ -2970,6 +2968,8 @@ <java-symbol type="integer" name="config_cameraLiftTriggerSensorType" /> <java-symbol type="string" name="config_cameraLiftTriggerSensorStringType" /> <java-symbol type="bool" name="config_emergencyGestureEnabled" /> + <java-symbol type="bool" name="config_defaultEmergencyGestureEnabled" /> + <java-symbol type="bool" name="config_defaultEmergencyGestureSoundEnabled" /> <java-symbol type="bool" name="config_volumeHushGestureEnabled" /> <java-symbol type="drawable" name="platlogo_m" /> diff --git a/core/tests/GameManagerTests/OWNERS b/core/tests/GameManagerTests/OWNERS new file mode 100644 index 000000000000..0992440226f0 --- /dev/null +++ b/core/tests/GameManagerTests/OWNERS @@ -0,0 +1 @@ +include /GAME_MANAGER_OWNERS
\ No newline at end of file diff --git a/core/tests/benchmarks/src/android/os/ParcelableBenchmark.java b/core/tests/benchmarks/src/android/os/ParcelableBenchmark.java index 1cf430205627..372bca4664a2 100644 --- a/core/tests/benchmarks/src/android/os/ParcelableBenchmark.java +++ b/core/tests/benchmarks/src/android/os/ParcelableBenchmark.java @@ -88,6 +88,7 @@ public class ParcelableBenchmark { } } + @SuppressWarnings("ParcelableCreator") @SuppressLint("ParcelCreator") private static class PointArray implements Parcelable { Rect mBounds = new Rect(); diff --git a/core/tests/coretests/AndroidTest.xml b/core/tests/coretests/AndroidTest.xml index 04952bdfa389..e2cdbf36b530 100644 --- a/core/tests/coretests/AndroidTest.xml +++ b/core/tests/coretests/AndroidTest.xml @@ -25,6 +25,11 @@ <option name="test-file-name" value="BinderDeathRecipientHelperApp2.apk" /> </target_preparer> + <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer"> + <!-- TODO(b/254155965): Design a mechanism to finally remove this command. --> + <option name="run-command" value="settings put global device_config_sync_disabled 0" /> + </target_preparer> + <target_preparer class="com.android.compatibility.common.tradefed.targetprep.DeviceInteractionHelperInstaller" /> <option name="test-tag" value="FrameworksCoreTests" /> diff --git a/core/tests/coretests/src/android/app/AutomaticZenRuleTest.java b/core/tests/coretests/src/android/app/AutomaticZenRuleTest.java new file mode 100644 index 000000000000..282fdad294eb --- /dev/null +++ b/core/tests/coretests/src/android/app/AutomaticZenRuleTest.java @@ -0,0 +1,153 @@ +/* + * Copyright (C) 2022 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.app; + +import static junit.framework.Assert.assertEquals; +import static junit.framework.Assert.fail; + +import android.content.ComponentName; +import android.net.Uri; +import android.os.Parcel; + +import androidx.test.ext.junit.runners.AndroidJUnit4; +import androidx.test.filters.SmallTest; + +import com.google.common.base.Strings; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import java.lang.reflect.Field; + +@RunWith(AndroidJUnit4.class) +@SmallTest +public class AutomaticZenRuleTest { + private static final String CLASS = "android.app.AutomaticZenRule"; + + @Test + public void testLongFields_inConstructor() { + String longString = Strings.repeat("A", 65536); + Uri longUri = Uri.parse("uri://" + Strings.repeat("A", 65530)); + + // test both variants where there's an owner, and where there's a configuration activity + AutomaticZenRule rule1 = new AutomaticZenRule( + longString, // name + new ComponentName("pkg", longString), // owner + null, // configuration activity + longUri, // conditionId + null, // zen policy + 0, // interruption filter + true); // enabled + + assertEquals(AutomaticZenRule.MAX_STRING_LENGTH, rule1.getName().length()); + assertEquals(AutomaticZenRule.MAX_STRING_LENGTH, + rule1.getConditionId().toString().length()); + assertEquals(AutomaticZenRule.MAX_STRING_LENGTH, rule1.getOwner().getClassName().length()); + + AutomaticZenRule rule2 = new AutomaticZenRule( + longString, // name + null, // owner + new ComponentName(longString, "SomeClassName"), // configuration activity + longUri, // conditionId + null, // zen policy + 0, // interruption filter + false); // enabled + + assertEquals(AutomaticZenRule.MAX_STRING_LENGTH, rule2.getName().length()); + assertEquals(AutomaticZenRule.MAX_STRING_LENGTH, + rule2.getConditionId().toString().length()); + assertEquals(AutomaticZenRule.MAX_STRING_LENGTH, + rule2.getConfigurationActivity().getPackageName().length()); + } + + @Test + public void testLongFields_inSetters() { + String longString = Strings.repeat("A", 65536); + Uri longUri = Uri.parse("uri://" + Strings.repeat("A", 65530)); + + AutomaticZenRule rule = new AutomaticZenRule( + "sensible name", + new ComponentName("pkg", "ShortClass"), + null, + Uri.parse("uri://short"), + null, 0, true); + + rule.setName(longString); + rule.setConditionId(longUri); + rule.setConfigurationActivity(new ComponentName(longString, longString)); + + assertEquals(AutomaticZenRule.MAX_STRING_LENGTH, rule.getName().length()); + assertEquals(AutomaticZenRule.MAX_STRING_LENGTH, + rule.getConditionId().toString().length()); + assertEquals(AutomaticZenRule.MAX_STRING_LENGTH, + rule.getConfigurationActivity().getPackageName().length()); + assertEquals(AutomaticZenRule.MAX_STRING_LENGTH, + rule.getConfigurationActivity().getClassName().length()); + } + + @Test + public void testLongInputsFromParcel() { + // Create a rule with long fields, set directly via reflection so that we can confirm that + // a rule with too-long fields that comes in via a parcel has its fields truncated directly. + AutomaticZenRule rule = new AutomaticZenRule( + "placeholder", + new ComponentName("place", "holder"), + null, + Uri.parse("uri://placeholder"), + null, 0, true); + + try { + String longString = Strings.repeat("A", 65536); + Uri longUri = Uri.parse("uri://" + Strings.repeat("A", 65530)); + Field name = Class.forName(CLASS).getDeclaredField("name"); + name.setAccessible(true); + name.set(rule, longString); + Field conditionId = Class.forName(CLASS).getDeclaredField("conditionId"); + conditionId.setAccessible(true); + conditionId.set(rule, longUri); + Field owner = Class.forName(CLASS).getDeclaredField("owner"); + owner.setAccessible(true); + owner.set(rule, new ComponentName(longString, longString)); + Field configActivity = Class.forName(CLASS).getDeclaredField("configurationActivity"); + configActivity.setAccessible(true); + configActivity.set(rule, new ComponentName(longString, longString)); + } catch (NoSuchFieldException e) { + fail(e.toString()); + } catch (ClassNotFoundException e) { + fail(e.toString()); + } catch (IllegalAccessException e) { + fail(e.toString()); + } + + Parcel parcel = Parcel.obtain(); + rule.writeToParcel(parcel, 0); + parcel.setDataPosition(0); + + AutomaticZenRule fromParcel = new AutomaticZenRule(parcel); + assertEquals(AutomaticZenRule.MAX_STRING_LENGTH, fromParcel.getName().length()); + assertEquals(AutomaticZenRule.MAX_STRING_LENGTH, + fromParcel.getConditionId().toString().length()); + assertEquals(AutomaticZenRule.MAX_STRING_LENGTH, + fromParcel.getConfigurationActivity().getPackageName().length()); + assertEquals(AutomaticZenRule.MAX_STRING_LENGTH, + fromParcel.getConfigurationActivity().getClassName().length()); + assertEquals(AutomaticZenRule.MAX_STRING_LENGTH, + fromParcel.getOwner().getPackageName().length()); + assertEquals(AutomaticZenRule.MAX_STRING_LENGTH, + fromParcel.getOwner().getClassName().length()); + } +} diff --git a/core/tests/coretests/src/android/app/activity/OWNERS b/core/tests/coretests/src/android/app/activity/OWNERS index 0862c05e0ee4..7e24aef076d1 100644 --- a/core/tests/coretests/src/android/app/activity/OWNERS +++ b/core/tests/coretests/src/android/app/activity/OWNERS @@ -1 +1,2 @@ include /services/core/java/com/android/server/wm/OWNERS +include /services/core/java/com/android/server/am/OWNERS diff --git a/core/tests/coretests/src/android/content/pm/PackageManagerPropertyTests.java b/core/tests/coretests/src/android/content/pm/PackageManagerPropertyTests.java index d505492f3b80..86e958320a04 100644 --- a/core/tests/coretests/src/android/content/pm/PackageManagerPropertyTests.java +++ b/core/tests/coretests/src/android/content/pm/PackageManagerPropertyTests.java @@ -20,6 +20,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.fail; import android.content.pm.PackageManager.Property; @@ -162,40 +163,30 @@ public class PackageManagerPropertyTests { @Test public void testProperty_invalidName() throws Exception { - try { + assertThrows(NullPointerException.class, () -> { final Property p = new Property(null, 1, "android", null); - fail("expected assertion error"); - } catch (AssertionError expected) { - } + }); } @Test public void testProperty_invalidType() throws Exception { - try { + assertThrows(IllegalArgumentException.class, () -> { final Property p = new Property("invalidTypeProperty", 0, "android", null); - fail("expected assertion error"); - } catch (AssertionError expected) { - } + }); - try { + assertThrows(IllegalArgumentException.class, () -> { final Property p = new Property("invalidTypeProperty", 6, "android", null); - fail("expected assertion error"); - } catch (AssertionError expected) { - } + }); - try { + assertThrows(IllegalArgumentException.class, () -> { final Property p = new Property("invalidTypeProperty", -1, "android", null); - fail("expected assertion error"); - } catch (AssertionError expected) { - } + }); } @Test public void testProperty_noPackageName() throws Exception { - try { + assertThrows(NullPointerException.class, () -> { final Property p = new Property(null, 1, null, null); - fail("expected assertion error"); - } catch (AssertionError expected) { - } + }); } } diff --git a/core/tests/coretests/src/android/os/BundleTest.java b/core/tests/coretests/src/android/os/BundleTest.java index a3bda8b23f30..0fa5ec33749f 100644 --- a/core/tests/coretests/src/android/os/BundleTest.java +++ b/core/tests/coretests/src/android/os/BundleTest.java @@ -409,6 +409,69 @@ public class BundleTest { } @Test + public void readFromParcel_withLazyValues_copiesUnderlyingParcel() { + Bundle bundle = new Bundle(); + Parcelable parcelable = new CustomParcelable(13, "Tiramisu"); + bundle.putParcelable("key", parcelable); + bundle.putString("string", "value"); + Parcel parcelledBundle = getParcelledBundle(bundle); + + Bundle testBundle = new Bundle(); + testBundle.setClassLoader(getClass().getClassLoader()); + testBundle.readFromParcel(parcelledBundle); + // Recycle the parcel as it should have been copied + parcelledBundle.recycle(); + assertThat(testBundle.getString("string")).isEqualTo("value"); + assertThat(testBundle.<Parcelable>getParcelable("key")).isEqualTo(parcelable); + } + + @Test + public void readFromParcelWithRwHelper_whenThrowingAndNotDefusing_throws() { + Bundle bundle = new Bundle(); + Parcelable parcelable = new CustomParcelable(13, "Tiramisu"); + bundle.putParcelable("key", parcelable); + bundle.putString("string", "value"); + Parcel parcelledBundle = getParcelledBundle(bundle); + parcelledBundle.setReadWriteHelper(new Parcel.ReadWriteHelper()); + + Bundle testBundle = new Bundle(); + assertThrows(BadParcelableException.class, + () -> testBundle.readFromParcel(parcelledBundle)); + } + + @Test + public void readFromParcelWithRwHelper_whenThrowingAndDefusing_returnsNull() { + Bundle bundle = new Bundle(); + Parcelable parcelable = new CustomParcelable(13, "Tiramisu"); + bundle.putParcelable("key", parcelable); + bundle.putString("string", "value"); + Parcel parcelledBundle = getParcelledBundle(bundle); + parcelledBundle.setReadWriteHelper(new Parcel.ReadWriteHelper()); + + Bundle.setShouldDefuse(true); + Bundle testBundle = new Bundle(); + testBundle.readFromParcel(parcelledBundle); + // Recycle the parcel as it should not be referenced + parcelledBundle.recycle(); + assertThat(testBundle.getString("string")).isNull(); + assertThat(testBundle.<Parcelable>getParcelable("key")).isNull(); + } + + @Test + public void readFromParcelWithRwHelper_withoutLazyObject_returnsValue() { + Bundle bundle = new Bundle(); + bundle.putString("string", "value"); + Parcel parcelledBundle = getParcelledBundle(bundle); + parcelledBundle.setReadWriteHelper(new Parcel.ReadWriteHelper()); + + Bundle testBundle = new Bundle(); + testBundle.readFromParcel(parcelledBundle); + // Recycle the parcel as it should not be referenced + parcelledBundle.recycle(); + assertThat(testBundle.getString("string")).isEqualTo("value"); + } + + @Test public void partialDeserialization_whenNotDefusing_throws() throws Exception { Bundle.setShouldDefuse(false); Bundle bundle = getMalformedBundle(); diff --git a/core/tests/coretests/src/android/widget/RemoteViewsTest.java b/core/tests/coretests/src/android/widget/RemoteViewsTest.java index 00b3693c902b..bbf9f3c99402 100644 --- a/core/tests/coretests/src/android/widget/RemoteViewsTest.java +++ b/core/tests/coretests/src/android/widget/RemoteViewsTest.java @@ -128,6 +128,7 @@ public class RemoteViewsTest { RemoteViews clone = child.clone(); } + @SuppressWarnings("ReturnValueIgnored") @Test public void clone_repeatedly() { RemoteViews original = new RemoteViews(mPackage, R.layout.remote_views_test); @@ -485,6 +486,7 @@ public class RemoteViewsTest { } } + @SuppressWarnings("ReturnValueIgnored") @Test public void nestedAddViews() { RemoteViews views = new RemoteViews(mPackage, R.layout.remote_views_test); @@ -509,6 +511,7 @@ public class RemoteViewsTest { parcelAndRecreate(views); } + @SuppressWarnings("ReturnValueIgnored") @Test public void nestedLandscapeViews() { RemoteViews views = new RemoteViews(mPackage, R.layout.remote_views_test); diff --git a/core/tests/coretests/src/com/android/internal/os/BinderCallsStatsTest.java b/core/tests/coretests/src/com/android/internal/os/BinderCallsStatsTest.java index 82b2bf4185e6..8207c9ee5ff3 100644 --- a/core/tests/coretests/src/com/android/internal/os/BinderCallsStatsTest.java +++ b/core/tests/coretests/src/com/android/internal/os/BinderCallsStatsTest.java @@ -1054,10 +1054,23 @@ public class BinderCallsStatsTest { super(new Injector() { public Random getRandomGenerator() { return new Random() { - int mCallCount = 0; + int mCallCount = -1; public int nextInt() { - return mCallCount++; + throw new IllegalStateException("Should not use nextInt()"); + } + + public int nextInt(int x) { + if (mCallCount == -1) { + // The tests are written such that they expect + // the first call to nextInt() to be on the first + // callEnded(). However, the BinderCallsStats + // constructor also calls nextInt(). Fake 0 being + // rolled twice. + mCallCount++; + return 0; + } + return (mCallCount++) % x; } }; } diff --git a/core/tests/coretests/src/com/android/internal/os/BinderLatencyObserverTest.java b/core/tests/coretests/src/com/android/internal/os/BinderLatencyObserverTest.java index 5af7376dc132..7bd53b9d4fcc 100644 --- a/core/tests/coretests/src/com/android/internal/os/BinderLatencyObserverTest.java +++ b/core/tests/coretests/src/com/android/internal/os/BinderLatencyObserverTest.java @@ -98,7 +98,7 @@ public class BinderLatencyObserverTest { assertEquals(1, latencyHistograms.size()); LatencyDims dims = latencyHistograms.keySet().iterator().next(); assertEquals(binder.getClass(), dims.getBinderClass()); - assertEquals(1, dims.getTransactionCode()); + assertEquals(2, dims.getTransactionCode()); // the first nextInt() is in the constructor assertThat(latencyHistograms.get(dims)).asList().containsExactly(1, 0, 0, 0, 0).inOrder(); } @@ -313,11 +313,11 @@ public class BinderLatencyObserverTest { int mCallCount = 0; public int nextInt() { - return mCallCount++; + throw new IllegalStateException("Should not use nextInt()"); } public int nextInt(int x) { - return 1; + return (mCallCount++) % x; } }; } diff --git a/core/tests/coretests/src/com/android/internal/util/TokenBucketTest.java b/core/tests/coretests/src/com/android/internal/util/TokenBucketTest.java index 6c50bce86638..8b30828a8936 100644 --- a/core/tests/coretests/src/com/android/internal/util/TokenBucketTest.java +++ b/core/tests/coretests/src/com/android/internal/util/TokenBucketTest.java @@ -16,6 +16,8 @@ package com.android.internal.util; +import static org.junit.Assert.assertThrows; + import android.os.SystemClock; import android.text.format.DateUtils; @@ -170,10 +172,9 @@ public class TokenBucketTest extends TestCase { } void assertThrow(Fn fn) { - try { + assertThrows(Throwable.class, () -> { fn.call(); - fail("expected n exception to be thrown."); - } catch (Throwable t) { } + }); } interface Fn { void call(); } diff --git a/core/tests/hosttests/test-apps/MultiDexLegacyTestApp/src/com/android/multidexlegacytestapp/Test.java b/core/tests/hosttests/test-apps/MultiDexLegacyTestApp/src/com/android/multidexlegacytestapp/Test.java index 41b8956f55d0..a2263256508b 100644 --- a/core/tests/hosttests/test-apps/MultiDexLegacyTestApp/src/com/android/multidexlegacytestapp/Test.java +++ b/core/tests/hosttests/test-apps/MultiDexLegacyTestApp/src/com/android/multidexlegacytestapp/Test.java @@ -31,6 +31,7 @@ public class Test extends ActivityInstrumentationTestCase2<MainActivity> { assertEquals(3366, getActivity().getValue()); } + @SuppressWarnings("ReturnValueIgnored") public void testAnnotation() throws Exception { assertEquals(ReferencedByAnnotation.B, ((AnnotationWithEnum) TestApplication.annotation).value()); diff --git a/core/tests/utiltests/src/com/android/internal/util/CallbackRegistryTest.java b/core/tests/utiltests/src/com/android/internal/util/CallbackRegistryTest.java index c53f4cc7ee52..1581abb5a9c6 100644 --- a/core/tests/utiltests/src/com/android/internal/util/CallbackRegistryTest.java +++ b/core/tests/utiltests/src/com/android/internal/util/CallbackRegistryTest.java @@ -20,6 +20,7 @@ import junit.framework.TestCase; import org.junit.Test; import java.util.ArrayList; +import java.util.Objects; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -39,11 +40,11 @@ public class CallbackRegistryTest extends TestCase { Integer argValue; private void addNotifyCount(Integer callback) { - if (callback == callback1) { + if (Objects.equals(callback, callback1)) { notify1++; - } else if (callback == callback2) { + } else if (Objects.equals(callback, callback2)) { notify2++; - } else if (callback == callback3) { + } else if (Objects.equals(callback, callback3)) { notify3++; } deepNotifyCount[callback]++; @@ -114,7 +115,7 @@ public class CallbackRegistryTest extends TestCase { public void onNotifyCallback(Integer callback, CallbackRegistryTest sender, int arg1, Integer arg) { addNotifyCount(callback); - if (callback == callback1) { + if (Objects.equals(callback, callback1)) { registry.remove(callback1); registry.remove(callback2); } @@ -166,9 +167,9 @@ public class CallbackRegistryTest extends TestCase { public void onNotifyCallback(Integer callback, CallbackRegistryTest sender, int arg1, Integer arg) { addNotifyCount(callback); - if (callback == callback1) { + if (Objects.equals(callback, callback1)) { registry.remove(callback2); - } else if (callback == callback3) { + } else if (Objects.equals(callback, callback3)) { registry.add(callback2); } } diff --git a/errorprone/java/com/google/errorprone/bugpatterns/android/EfficientXmlChecker.java b/errorprone/java/com/google/errorprone/bugpatterns/android/EfficientXmlChecker.java index 8706a68226ef..42e304699cd4 100644 --- a/errorprone/java/com/google/errorprone/bugpatterns/android/EfficientXmlChecker.java +++ b/errorprone/java/com/google/errorprone/bugpatterns/android/EfficientXmlChecker.java @@ -168,6 +168,7 @@ public final class EfficientXmlChecker extends BugChecker */ private static final Matcher<ExpressionTree> CONVERT_PRIMITIVE_TO_STRING = new Matcher<ExpressionTree>() { + @SuppressWarnings("TreeToString") //TODO: Fix me @Override public boolean matches(ExpressionTree tree, VisitorState state) { if (PRIMITIVE_TO_STRING.matches(tree, state)) { @@ -205,6 +206,7 @@ public final class EfficientXmlChecker extends BugChecker */ private static final Matcher<ExpressionTree> CONVERT_STRING_TO_PRIMITIVE = new Matcher<ExpressionTree>() { + @SuppressWarnings("TreeToString") //TODO: Fix me @Override public boolean matches(ExpressionTree tree, VisitorState state) { if (PRIMITIVE_PARSE.matches(tree, state)) { diff --git a/graphics/java/android/graphics/drawable/RippleDrawable.java b/graphics/java/android/graphics/drawable/RippleDrawable.java index 74cad1aaa057..b170869672eb 100644 --- a/graphics/java/android/graphics/drawable/RippleDrawable.java +++ b/graphics/java/android/graphics/drawable/RippleDrawable.java @@ -758,7 +758,7 @@ public class RippleDrawable extends LayerDrawable { if (mBackground != null) { mBackground.onHotspotBoundsChanged(); } - float newRadius = Math.round(getComputedRadius()); + float newRadius = getComputedRadius(); for (int i = 0; i < mRunningAnimations.size(); i++) { RippleAnimationSession s = mRunningAnimations.get(i); s.setRadius(newRadius); diff --git a/graphics/java/android/graphics/drawable/VectorDrawable.java b/graphics/java/android/graphics/drawable/VectorDrawable.java index 4065bd110c7e..e25ee906b410 100644 --- a/graphics/java/android/graphics/drawable/VectorDrawable.java +++ b/graphics/java/android/graphics/drawable/VectorDrawable.java @@ -60,7 +60,7 @@ import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; -import java.util.HashMap; +import java.util.Map; import java.util.Stack; /** @@ -1171,18 +1171,14 @@ public class VectorDrawable extends Drawable { private static final int NATIVE_ALLOCATION_SIZE = 100; - private static final HashMap<String, Integer> sPropertyIndexMap = - new HashMap<String, Integer>() { - { - put("translateX", TRANSLATE_X_INDEX); - put("translateY", TRANSLATE_Y_INDEX); - put("scaleX", SCALE_X_INDEX); - put("scaleY", SCALE_Y_INDEX); - put("pivotX", PIVOT_X_INDEX); - put("pivotY", PIVOT_Y_INDEX); - put("rotation", ROTATION_INDEX); - } - }; + private static final Map<String, Integer> sPropertyIndexMap = Map.of( + "translateX", TRANSLATE_X_INDEX, + "translateY", TRANSLATE_Y_INDEX, + "scaleX", SCALE_X_INDEX, + "scaleY", SCALE_Y_INDEX, + "pivotX", PIVOT_X_INDEX, + "pivotY", PIVOT_Y_INDEX, + "rotation", ROTATION_INDEX); static int getPropertyIndex(String propertyName) { if (sPropertyIndexMap.containsKey(propertyName)) { @@ -1285,18 +1281,15 @@ public class VectorDrawable extends Drawable { } }; - private static final HashMap<String, Property> sPropertyMap = - new HashMap<String, Property>() { - { - put("translateX", TRANSLATE_X); - put("translateY", TRANSLATE_Y); - put("scaleX", SCALE_X); - put("scaleY", SCALE_Y); - put("pivotX", PIVOT_X); - put("pivotY", PIVOT_Y); - put("rotation", ROTATION); - } - }; + private static final Map<String, Property> sPropertyMap = Map.of( + "translateX", TRANSLATE_X, + "translateY", TRANSLATE_Y, + "scaleX", SCALE_X, + "scaleY", SCALE_Y, + "pivotX", PIVOT_X, + "pivotY", PIVOT_Y, + "rotation", ROTATION); + // Temp array to store transform values obtained from native. private float[] mTransform; ///////////////////////////////////////////////////// @@ -1762,19 +1755,15 @@ public class VectorDrawable extends Drawable { private static final int NATIVE_ALLOCATION_SIZE = 264; // Property map for animatable attributes. - private final static HashMap<String, Integer> sPropertyIndexMap - = new HashMap<String, Integer> () { - { - put("strokeWidth", STROKE_WIDTH_INDEX); - put("strokeColor", STROKE_COLOR_INDEX); - put("strokeAlpha", STROKE_ALPHA_INDEX); - put("fillColor", FILL_COLOR_INDEX); - put("fillAlpha", FILL_ALPHA_INDEX); - put("trimPathStart", TRIM_PATH_START_INDEX); - put("trimPathEnd", TRIM_PATH_END_INDEX); - put("trimPathOffset", TRIM_PATH_OFFSET_INDEX); - } - }; + private static final Map<String, Integer> sPropertyIndexMap = Map.of( + "strokeWidth", STROKE_WIDTH_INDEX, + "strokeColor", STROKE_COLOR_INDEX, + "strokeAlpha", STROKE_ALPHA_INDEX, + "fillColor", FILL_COLOR_INDEX, + "fillAlpha", FILL_ALPHA_INDEX, + "trimPathStart", TRIM_PATH_START_INDEX, + "trimPathEnd", TRIM_PATH_END_INDEX, + "trimPathOffset", TRIM_PATH_OFFSET_INDEX); // Below are the Properties that wrap the setters to avoid reflection overhead in animations private static final Property<VFullPath, Float> STROKE_WIDTH = @@ -1881,19 +1870,15 @@ public class VectorDrawable extends Drawable { } }; - private final static HashMap<String, Property> sPropertyMap - = new HashMap<String, Property> () { - { - put("strokeWidth", STROKE_WIDTH); - put("strokeColor", STROKE_COLOR); - put("strokeAlpha", STROKE_ALPHA); - put("fillColor", FILL_COLOR); - put("fillAlpha", FILL_ALPHA); - put("trimPathStart", TRIM_PATH_START); - put("trimPathEnd", TRIM_PATH_END); - put("trimPathOffset", TRIM_PATH_OFFSET); - } - }; + private static final Map<String, Property> sPropertyMap = Map.of( + "strokeWidth", STROKE_WIDTH, + "strokeColor", STROKE_COLOR, + "strokeAlpha", STROKE_ALPHA, + "fillColor", FILL_COLOR, + "fillAlpha", FILL_ALPHA, + "trimPathStart", TRIM_PATH_START, + "trimPathEnd", TRIM_PATH_END, + "trimPathOffset", TRIM_PATH_OFFSET); // Temp array to store property data obtained from native getter. private byte[] mPropertyData; diff --git a/keystore/java/android/security/keystore/KeyProperties.java b/keystore/java/android/security/keystore/KeyProperties.java index dbd918e35d70..62455988db34 100644 --- a/keystore/java/android/security/keystore/KeyProperties.java +++ b/keystore/java/android/security/keystore/KeyProperties.java @@ -30,6 +30,7 @@ import libcore.util.EmptyArray; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.security.spec.AlgorithmParameterSpec; +import java.security.spec.ECParameterSpec; import java.security.spec.MGF1ParameterSpec; import java.util.Collection; import java.util.Locale; @@ -914,6 +915,51 @@ public abstract class KeyProperties { } /** + * @hide + */ + public abstract static class EcCurve { + private EcCurve() {} + + /** + * @hide + */ + public static int toKeymasterCurve(ECParameterSpec spec) { + int keySize = spec.getCurve().getField().getFieldSize(); + switch (keySize) { + case 224: + return android.hardware.security.keymint.EcCurve.P_224; + case 256: + return android.hardware.security.keymint.EcCurve.P_256; + case 384: + return android.hardware.security.keymint.EcCurve.P_384; + case 521: + return android.hardware.security.keymint.EcCurve.P_521; + default: + return -1; + } + } + + /** + * @hide + */ + public static int fromKeymasterCurve(int ecCurve) { + switch (ecCurve) { + case android.hardware.security.keymint.EcCurve.P_224: + return 224; + case android.hardware.security.keymint.EcCurve.P_256: + case android.hardware.security.keymint.EcCurve.CURVE_25519: + return 256; + case android.hardware.security.keymint.EcCurve.P_384: + return 384; + case android.hardware.security.keymint.EcCurve.P_521: + return 521; + default: + return -1; + } + } + } + + /** * Namespaces provide system developers and vendors with a way to use keystore without * requiring an applications uid. Namespaces can be configured using SEPolicy. * See <a href="https://source.android.com/security/keystore#access-control"> diff --git a/keystore/java/android/security/keystore2/AndroidKeyStoreECDSASignatureSpi.java b/keystore/java/android/security/keystore2/AndroidKeyStoreECDSASignatureSpi.java index 5216a908826b..ace2053cc1a7 100644 --- a/keystore/java/android/security/keystore2/AndroidKeyStoreECDSASignatureSpi.java +++ b/keystore/java/android/security/keystore2/AndroidKeyStoreECDSASignatureSpi.java @@ -203,6 +203,11 @@ abstract class AndroidKeyStoreECDSASignatureSpi extends AndroidKeyStoreSignature for (Authorization a : key.getAuthorizations()) { if (a.keyParameter.tag == KeymasterDefs.KM_TAG_KEY_SIZE) { keySizeBits = KeyStore2ParameterUtils.getUnsignedInt(a); + break; + } else if (a.keyParameter.tag == KeymasterDefs.KM_TAG_EC_CURVE) { + keySizeBits = KeyProperties.EcCurve.fromKeymasterCurve( + a.keyParameter.value.getEcCurve()); + break; } } diff --git a/keystore/java/android/security/keystore2/AndroidKeyStoreSpi.java b/keystore/java/android/security/keystore2/AndroidKeyStoreSpi.java index 9d424e904d59..f05cdc57fb70 100644 --- a/keystore/java/android/security/keystore2/AndroidKeyStoreSpi.java +++ b/keystore/java/android/security/keystore2/AndroidKeyStoreSpi.java @@ -66,6 +66,7 @@ import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; +import java.security.interfaces.ECKey; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -566,6 +567,22 @@ public class AndroidKeyStoreSpi extends KeyStoreSpi { spec.getMaxUsageCount() )); } + if (KeyProperties.KEY_ALGORITHM_EC.equalsIgnoreCase(key.getAlgorithm())) { + if (key instanceof ECKey) { + ECKey ecKey = (ECKey) key; + importArgs.add(KeyStore2ParameterUtils.makeEnum( + KeymasterDefs.KM_TAG_EC_CURVE, + KeyProperties.EcCurve.toKeymasterCurve(ecKey.getParams()) + )); + } + } + /* TODO: check for Ed25519(EdDSA) or X25519(XDH) key algorithm and + * add import args for KM_TAG_EC_CURVE as EcCurve.CURVE_25519. + * Currently conscrypt does not support EdDSA key import and XDH keys are not an + * instance of XECKey, hence these conditions are not added, once it is fully + * implemented by conscrypt, we can add CURVE_25519 argument for EdDSA and XDH + * algorithms. + */ } catch (IllegalArgumentException | IllegalStateException e) { throw new KeyStoreException(e); } diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/common/split/OWNERS b/libs/WindowManager/Shell/src/com/android/wm/shell/common/split/OWNERS new file mode 100644 index 000000000000..7237d2bde39f --- /dev/null +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/common/split/OWNERS @@ -0,0 +1,2 @@ +# WM shell sub-modules splitscreen owner +chenghsiuchang@google.com diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/startingsurface/StartingSurfaceDrawer.java b/libs/WindowManager/Shell/src/com/android/wm/shell/startingsurface/StartingSurfaceDrawer.java index 54d62edf2570..978ad8ac10f2 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/startingsurface/StartingSurfaceDrawer.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/startingsurface/StartingSurfaceDrawer.java @@ -429,7 +429,8 @@ public class StartingSurfaceDrawer { } @Override - public @Nullable SplashScreenView get() { + @Nullable + public SplashScreenView get() { synchronized (this) { while (!mIsViewSet) { try { @@ -690,7 +691,7 @@ public class StartingSurfaceDrawer { private final TaskSnapshotWindow mTaskSnapshotWindow; private SplashScreenView mContentView; private boolean mSetSplashScreen; - private @StartingWindowType int mSuggestType; + @StartingWindowType private int mSuggestType; private int mBGColor; private final long mCreateTime; private int mSystemBarAppearance; @@ -731,7 +732,7 @@ public class StartingSurfaceDrawer { // Reset the system bar color which set by splash screen, make it align to the app. private void clearSystemBarColor() { - if (mDecorView == null) { + if (mDecorView == null || !mDecorView.isAttachedToWindow()) { return; } if (mDecorView.getLayoutParams() instanceof WindowManager.LayoutParams) { diff --git a/libs/WindowManager/Shell/tests/OWNERS b/libs/WindowManager/Shell/tests/OWNERS index f4efc374ecc2..1c28c3d58ccb 100644 --- a/libs/WindowManager/Shell/tests/OWNERS +++ b/libs/WindowManager/Shell/tests/OWNERS @@ -6,3 +6,4 @@ pablogamito@google.com lbill@google.com madym@google.com hwwang@google.com +chenghsiuchang@google.com diff --git a/libs/androidfw/ZipUtils.cpp b/libs/androidfw/ZipUtils.cpp index 58fc5bbbab5e..a1385f2cf7b1 100644 --- a/libs/androidfw/ZipUtils.cpp +++ b/libs/androidfw/ZipUtils.cpp @@ -35,7 +35,7 @@ using namespace android; // TODO: This can go away once the only remaining usage in aapt goes away. -class FileReader : public zip_archive::Reader { +class FileReader final : public zip_archive::Reader { public: explicit FileReader(FILE* fp) : Reader(), mFp(fp), mCurrentOffset(0) { } @@ -66,7 +66,7 @@ class FileReader : public zip_archive::Reader { mutable off64_t mCurrentOffset; }; -class FdReader : public zip_archive::Reader { +class FdReader final : public zip_archive::Reader { public: explicit FdReader(int fd) : mFd(fd) { } @@ -79,7 +79,7 @@ class FdReader : public zip_archive::Reader { const int mFd; }; -class BufferReader : public zip_archive::Reader { +class BufferReader final : public zip_archive::Reader { public: BufferReader(incfs::map_ptr<void> input, size_t inputSize) : Reader(), mInput(input.convert<uint8_t>()), @@ -105,7 +105,7 @@ class BufferReader : public zip_archive::Reader { const size_t mInputSize; }; -class BufferWriter : public zip_archive::Writer { +class BufferWriter final : public zip_archive::Writer { public: BufferWriter(void* output, size_t outputSize) : Writer(), mOutput(reinterpret_cast<uint8_t*>(output)), mOutputSize(outputSize), mBytesWritten(0) { diff --git a/libs/androidfw/tests/CursorWindow_test.cpp b/libs/androidfw/tests/CursorWindow_test.cpp index 15be80c48192..d1cfd03276c2 100644 --- a/libs/androidfw/tests/CursorWindow_test.cpp +++ b/libs/androidfw/tests/CursorWindow_test.cpp @@ -14,6 +14,7 @@ * limitations under the License. */ +#include <memory> #include <utility> #include "androidfw/CursorWindow.h" @@ -184,7 +185,7 @@ TEST(CursorWindowTest, Inflate) { ASSERT_EQ(w->allocRow(), OK); // Scratch buffer that will fit before inflation - void* buf = malloc(kHalfInlineSize); + char buf[kHalfInlineSize]; // Store simple value ASSERT_EQ(w->putLong(0, 0, 0xcafe), OK); @@ -262,7 +263,7 @@ TEST(CursorWindowTest, ParcelSmall) { ASSERT_EQ(w->allocRow(), OK); // Scratch buffer that will fit before inflation - void* buf = malloc(kHalfInlineSize); + char buf[kHalfInlineSize]; // Store simple value ASSERT_EQ(w->putLong(0, 0, 0xcafe), OK); @@ -322,7 +323,8 @@ TEST(CursorWindowTest, ParcelLarge) { ASSERT_EQ(w->putLong(0, 0, 0xcafe), OK); // Store object that forces inflation - void* buf = malloc(kGiantSize); + std::unique_ptr<char> bufPtr(new char[kGiantSize]); + void* buf = bufPtr.get(); memset(buf, 42, kGiantSize); ASSERT_EQ(w->putBlob(0, 1, buf, kGiantSize), OK); diff --git a/libs/hwui/Android.bp b/libs/hwui/Android.bp index ad9aa6cdd3d9..33f79352b8b8 100644 --- a/libs/hwui/Android.bp +++ b/libs/hwui/Android.bp @@ -674,6 +674,7 @@ cc_test { srcs: [ "tests/unit/main.cpp", "tests/unit/ABitmapTests.cpp", + "tests/unit/AutoBackendTextureReleaseTests.cpp", "tests/unit/CacheManagerTests.cpp", "tests/unit/CanvasContextTests.cpp", "tests/unit/CanvasOpTests.cpp", diff --git a/libs/hwui/AutoBackendTextureRelease.cpp b/libs/hwui/AutoBackendTextureRelease.cpp index ef5eacbdb4ad..b656b6ac8204 100644 --- a/libs/hwui/AutoBackendTextureRelease.cpp +++ b/libs/hwui/AutoBackendTextureRelease.cpp @@ -32,9 +32,17 @@ AutoBackendTextureRelease::AutoBackendTextureRelease(GrDirectContext* context, bool createProtectedImage = 0 != (desc.usage & AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT); GrBackendFormat backendFormat = GrAHardwareBufferUtils::GetBackendFormat(context, buffer, desc.format, false); + LOG_ALWAYS_FATAL_IF(!backendFormat.isValid(), + __FILE__ " Invalid GrBackendFormat. GrBackendApi==%" PRIu32 + ", AHardwareBuffer_Format==%" PRIu32 ".", + static_cast<int>(context->backend()), desc.format); mBackendTexture = GrAHardwareBufferUtils::MakeBackendTexture( context, buffer, desc.width, desc.height, &mDeleteProc, &mUpdateProc, &mImageCtx, createProtectedImage, backendFormat, false); + LOG_ALWAYS_FATAL_IF(!mBackendTexture.isValid(), + __FILE__ " Invalid GrBackendTexture. Width==%" PRIu32 ", height==%" PRIu32 + ", protected==%d", + desc.width, desc.height, createProtectedImage); } void AutoBackendTextureRelease::unref(bool releaseImage) { @@ -74,13 +82,13 @@ void AutoBackendTextureRelease::makeImage(AHardwareBuffer* buffer, AHardwareBuffer_Desc desc; AHardwareBuffer_describe(buffer, &desc); SkColorType colorType = GrAHardwareBufferUtils::GetSkColorTypeFromBufferFormat(desc.format); + // The following ref will be counteracted by Skia calling releaseProc, either during + // MakeFromTexture if there is a failure, or later when SkImage is discarded. It must + // be called before MakeFromTexture, otherwise Skia may remove HWUI's ref on failure. + ref(); mImage = SkImage::MakeFromTexture( context, mBackendTexture, kTopLeft_GrSurfaceOrigin, colorType, kPremul_SkAlphaType, uirenderer::DataSpaceToColorSpace(dataspace), releaseProc, this); - if (mImage.get()) { - // The following ref will be counteracted by releaseProc, when SkImage is discarded. - ref(); - } } void AutoBackendTextureRelease::newBufferContent(GrDirectContext* context) { diff --git a/libs/hwui/AutoBackendTextureRelease.h b/libs/hwui/AutoBackendTextureRelease.h index c9bb767a3185..f0eb2a8b6eab 100644 --- a/libs/hwui/AutoBackendTextureRelease.h +++ b/libs/hwui/AutoBackendTextureRelease.h @@ -25,6 +25,9 @@ namespace android { namespace uirenderer { +// Friend TestUtils serves as a proxy for any test cases that require access to private members. +class TestUtils; + /** * AutoBackendTextureRelease manages EglImage/VkImage lifetime. It is a ref-counted object * that keeps GPU resources alive until the last SkImage object using them is destroyed. @@ -66,6 +69,9 @@ private: // mImage is the SkImage created from mBackendTexture. sk_sp<SkImage> mImage; + + // Friend TestUtils serves as a proxy for any test cases that require access to private members. + friend class TestUtils; }; } /* namespace uirenderer */ diff --git a/libs/hwui/pipeline/skia/RenderNodeDrawable.cpp b/libs/hwui/pipeline/skia/RenderNodeDrawable.cpp index 507d3dcdcde9..9e17b9e6d985 100644 --- a/libs/hwui/pipeline/skia/RenderNodeDrawable.cpp +++ b/libs/hwui/pipeline/skia/RenderNodeDrawable.cpp @@ -224,10 +224,10 @@ void RenderNodeDrawable::drawContent(SkCanvas* canvas) const { // TODO should we let the bound of the drawable do this for us? const SkRect bounds = SkRect::MakeWH(properties.getWidth(), properties.getHeight()); bool quickRejected = properties.getClipToBounds() && canvas->quickReject(bounds); - auto clipBounds = canvas->getLocalClipBounds(); - SkIRect srcBounds = SkIRect::MakeWH(bounds.width(), bounds.height()); - SkIPoint offset = SkIPoint::Make(0.0f, 0.0f); if (!quickRejected) { + auto clipBounds = canvas->getLocalClipBounds(); + SkIRect srcBounds = SkIRect::MakeWH(bounds.width(), bounds.height()); + SkIPoint offset = SkIPoint::Make(0.0f, 0.0f); SkiaDisplayList* displayList = renderNode->getDisplayList().asSkiaDl(); const LayerProperties& layerProperties = properties.layerProperties(); // composing a hardware layer diff --git a/libs/hwui/tests/common/TestUtils.h b/libs/hwui/tests/common/TestUtils.h index 5092675a8104..fcaa745e9fc6 100644 --- a/libs/hwui/tests/common/TestUtils.h +++ b/libs/hwui/tests/common/TestUtils.h @@ -16,6 +16,7 @@ #pragma once +#include <AutoBackendTextureRelease.h> #include <DisplayList.h> #include <Matrix.h> #include <Properties.h> @@ -283,6 +284,11 @@ public: static SkRect getClipBounds(const SkCanvas* canvas); static SkRect getLocalClipBounds(const SkCanvas* canvas); + static int getUsageCount(const AutoBackendTextureRelease* textureRelease) { + EXPECT_NE(nullptr, textureRelease); + return textureRelease->mUsageCount; + } + struct CallCounts { int sync = 0; int contextDestroyed = 0; diff --git a/libs/hwui/tests/unit/AutoBackendTextureReleaseTests.cpp b/libs/hwui/tests/unit/AutoBackendTextureReleaseTests.cpp new file mode 100644 index 000000000000..2ec78a429481 --- /dev/null +++ b/libs/hwui/tests/unit/AutoBackendTextureReleaseTests.cpp @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2022 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. + */ + +#include <gtest/gtest.h> + +#include "AutoBackendTextureRelease.h" +#include "tests/common/TestUtils.h" + +using namespace android; +using namespace android::uirenderer; + +AHardwareBuffer* allocHardwareBuffer() { + AHardwareBuffer* buffer; + AHardwareBuffer_Desc desc = { + .width = 16, + .height = 16, + .layers = 1, + .format = AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM, + .usage = AHARDWAREBUFFER_USAGE_CPU_READ_RARELY | AHARDWAREBUFFER_USAGE_CPU_WRITE_RARELY, + }; + constexpr int kSucceeded = 0; + int status = AHardwareBuffer_allocate(&desc, &buffer); + EXPECT_EQ(kSucceeded, status); + return buffer; +} + +// Expands to AutoBackendTextureRelease_makeImage_invalid_RenderThreadTest, +// set as friend in AutoBackendTextureRelease.h +RENDERTHREAD_TEST(AutoBackendTextureRelease, makeImage_invalid) { + AHardwareBuffer* buffer = allocHardwareBuffer(); + AutoBackendTextureRelease* textureRelease = + new AutoBackendTextureRelease(renderThread.getGrContext(), buffer); + + EXPECT_EQ(1, TestUtils::getUsageCount(textureRelease)); + + // SkImage::MakeFromTexture should fail if given null GrDirectContext. + textureRelease->makeImage(buffer, HAL_DATASPACE_UNKNOWN, /*context = */ nullptr); + + EXPECT_EQ(1, TestUtils::getUsageCount(textureRelease)); + + textureRelease->unref(true); + AHardwareBuffer_release(buffer); +} + +// Expands to AutoBackendTextureRelease_makeImage_valid_RenderThreadTest, +// set as friend in AutoBackendTextureRelease.h +RENDERTHREAD_TEST(AutoBackendTextureRelease, makeImage_valid) { + AHardwareBuffer* buffer = allocHardwareBuffer(); + AutoBackendTextureRelease* textureRelease = + new AutoBackendTextureRelease(renderThread.getGrContext(), buffer); + + EXPECT_EQ(1, TestUtils::getUsageCount(textureRelease)); + + textureRelease->makeImage(buffer, HAL_DATASPACE_UNKNOWN, renderThread.getGrContext()); + + EXPECT_EQ(2, TestUtils::getUsageCount(textureRelease)); + + textureRelease->unref(true); + AHardwareBuffer_release(buffer); +} diff --git a/media/java/android/media/AudioManager.java b/media/java/android/media/AudioManager.java index 30fae1d12d44..c3e605e396f3 100644 --- a/media/java/android/media/AudioManager.java +++ b/media/java/android/media/AudioManager.java @@ -2325,10 +2325,9 @@ public class AudioManager { return AudioSystem.SUCCESS; } - private final Map<Integer, Object> mDevRoleForCapturePresetListeners = new HashMap<>(){{ - put(AudioSystem.DEVICE_ROLE_PREFERRED, - new DevRoleListeners<OnPreferredDevicesForCapturePresetChangedListener>()); - }}; + private final Map<Integer, Object> mDevRoleForCapturePresetListeners = Map.of( + AudioSystem.DEVICE_ROLE_PREFERRED, + new DevRoleListeners<OnPreferredDevicesForCapturePresetChangedListener>()); private class DevRoleListenerInfo<T> { final @NonNull Executor mExecutor; @@ -6483,15 +6482,17 @@ public class AudioManager { // AudioPort implementation // - static final int AUDIOPORT_GENERATION_INIT = 0; - static Integer sAudioPortGeneration = new Integer(AUDIOPORT_GENERATION_INIT); - static ArrayList<AudioPort> sAudioPortsCached = new ArrayList<AudioPort>(); - static ArrayList<AudioPort> sPreviousAudioPortsCached = new ArrayList<AudioPort>(); - static ArrayList<AudioPatch> sAudioPatchesCached = new ArrayList<AudioPatch>(); + private static final int AUDIOPORT_GENERATION_INIT = 0; + private static Object sAudioPortGenerationLock = new Object(); + @GuardedBy("sAudioPortGenerationLock") + private static int sAudioPortGeneration = AUDIOPORT_GENERATION_INIT; + private static ArrayList<AudioPort> sAudioPortsCached = new ArrayList<AudioPort>(); + private static ArrayList<AudioPort> sPreviousAudioPortsCached = new ArrayList<AudioPort>(); + private static ArrayList<AudioPatch> sAudioPatchesCached = new ArrayList<AudioPatch>(); static int resetAudioPortGeneration() { int generation; - synchronized (sAudioPortGeneration) { + synchronized (sAudioPortGenerationLock) { generation = sAudioPortGeneration; sAudioPortGeneration = AUDIOPORT_GENERATION_INIT; } @@ -6501,7 +6502,7 @@ public class AudioManager { static int updateAudioPortCache(ArrayList<AudioPort> ports, ArrayList<AudioPatch> patches, ArrayList<AudioPort> previousPorts) { sAudioPortEventHandler.init(); - synchronized (sAudioPortGeneration) { + synchronized (sAudioPortGenerationLock) { if (sAudioPortGeneration == AUDIOPORT_GENERATION_INIT) { int[] patchGeneration = new int[1]; diff --git a/media/java/android/media/AudioMetadata.java b/media/java/android/media/AudioMetadata.java index ca175b4853a6..0f962f9e9d4b 100644 --- a/media/java/android/media/AudioMetadata.java +++ b/media/java/android/media/AudioMetadata.java @@ -30,6 +30,7 @@ import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.HashSet; +import java.util.Map; import java.util.Objects; import java.util.Set; @@ -446,14 +447,13 @@ public final class AudioMetadata { // BaseMap is corresponding to audio_utils::metadata::Data private static final int AUDIO_METADATA_OBJ_TYPE_BASEMAP = 6; - private static final HashMap<Class, Integer> AUDIO_METADATA_OBJ_TYPES = new HashMap<>() {{ - put(Integer.class, AUDIO_METADATA_OBJ_TYPE_INT); - put(Long.class, AUDIO_METADATA_OBJ_TYPE_LONG); - put(Float.class, AUDIO_METADATA_OBJ_TYPE_FLOAT); - put(Double.class, AUDIO_METADATA_OBJ_TYPE_DOUBLE); - put(String.class, AUDIO_METADATA_OBJ_TYPE_STRING); - put(BaseMap.class, AUDIO_METADATA_OBJ_TYPE_BASEMAP); - }}; + private static final Map<Class, Integer> AUDIO_METADATA_OBJ_TYPES = Map.of( + Integer.class, AUDIO_METADATA_OBJ_TYPE_INT, + Long.class, AUDIO_METADATA_OBJ_TYPE_LONG, + Float.class, AUDIO_METADATA_OBJ_TYPE_FLOAT, + Double.class, AUDIO_METADATA_OBJ_TYPE_DOUBLE, + String.class, AUDIO_METADATA_OBJ_TYPE_STRING, + BaseMap.class, AUDIO_METADATA_OBJ_TYPE_BASEMAP); private static final Charset AUDIO_METADATA_CHARSET = StandardCharsets.UTF_8; @@ -634,8 +634,8 @@ public final class AudioMetadata { * Datum corresponds to Object ****************************************************************************************/ - private static final HashMap<Integer, DataPackage<?>> DATA_PACKAGES = new HashMap<>() {{ - put(AUDIO_METADATA_OBJ_TYPE_INT, new DataPackage<Integer>() { + private static final Map<Integer, DataPackage<?>> DATA_PACKAGES = Map.of( + AUDIO_METADATA_OBJ_TYPE_INT, new DataPackage<Integer>() { @Override @Nullable public Integer unpack(ByteBuffer buffer) { @@ -647,8 +647,8 @@ public final class AudioMetadata { output.putInt(obj); return true; } - }); - put(AUDIO_METADATA_OBJ_TYPE_LONG, new DataPackage<Long>() { + }, + AUDIO_METADATA_OBJ_TYPE_LONG, new DataPackage<Long>() { @Override @Nullable public Long unpack(ByteBuffer buffer) { @@ -660,8 +660,8 @@ public final class AudioMetadata { output.putLong(obj); return true; } - }); - put(AUDIO_METADATA_OBJ_TYPE_FLOAT, new DataPackage<Float>() { + }, + AUDIO_METADATA_OBJ_TYPE_FLOAT, new DataPackage<Float>() { @Override @Nullable public Float unpack(ByteBuffer buffer) { @@ -673,8 +673,8 @@ public final class AudioMetadata { output.putFloat(obj); return true; } - }); - put(AUDIO_METADATA_OBJ_TYPE_DOUBLE, new DataPackage<Double>() { + }, + AUDIO_METADATA_OBJ_TYPE_DOUBLE, new DataPackage<Double>() { @Override @Nullable public Double unpack(ByteBuffer buffer) { @@ -686,8 +686,8 @@ public final class AudioMetadata { output.putDouble(obj); return true; } - }); - put(AUDIO_METADATA_OBJ_TYPE_STRING, new DataPackage<String>() { + }, + AUDIO_METADATA_OBJ_TYPE_STRING, new DataPackage<String>() { @Override @Nullable public String unpack(ByteBuffer buffer) { @@ -713,9 +713,9 @@ public final class AudioMetadata { output.put(valueArr); return true; } - }); - put(AUDIO_METADATA_OBJ_TYPE_BASEMAP, new BaseMapPackage()); - }}; + }, + AUDIO_METADATA_OBJ_TYPE_BASEMAP, new BaseMapPackage()); + // ObjectPackage is a special case that it is expected to unpack audio_utils::metadata::Datum, // which contains data type and data size besides the payload for the data. private static final ObjectPackage OBJECT_PACKAGE = new ObjectPackage(); diff --git a/media/java/android/media/AudioSystem.java b/media/java/android/media/AudioSystem.java index 18135f2061a6..b7282218af35 100644 --- a/media/java/android/media/AudioSystem.java +++ b/media/java/android/media/AudioSystem.java @@ -431,6 +431,18 @@ public class AudioSystem return "AUDIO_FORMAT_APTX_TWSP"; case /* AUDIO_FORMAT_LC3 */ 0x2B000000: return "AUDIO_FORMAT_LC3"; + case /* AUDIO_FORMAT_MPEGH */ 0x2C000000: + return "AUDIO_FORMAT_MPEGH"; + case /* AUDIO_FORMAT_IEC60958 */ 0x2D000000: + return "AUDIO_FORMAT_IEC60958"; + case /* AUDIO_FORMAT_DTS_UHD */ 0x2E000000: + return "AUDIO_FORMAT_DTS_UHD"; + case /* AUDIO_FORMAT_DRA */ 0x2F000000: + return "AUDIO_FORMAT_DRA"; + case /* AUDIO_FORMAT_APTX_ADAPTIVE_QLEA */ 0x30000000: + return "AUDIO_FORMAT_APTX_ADAPTIVE_QLEA"; + case /* AUDIO_FORMAT_APTX_ADAPTIVE_R4 */ 0x31000000: + return "AUDIO_FORMAT_APTX_ADAPTIVE_R4"; /* Aliases */ case /* AUDIO_FORMAT_PCM_16_BIT */ 0x1: @@ -503,10 +515,14 @@ public class AudioSystem return "AUDIO_FORMAT_MAT_2_0"; // (MAT | MAT_SUB_2_0) case /* AUDIO_FORMAT_MAT_2_1 */ 0x24000003: return "AUDIO_FORMAT_MAT_2_1"; // (MAT | MAT_SUB_2_1) - case /* AUDIO_FORMAT_DTS_UHD */ 0x2E000000: - return "AUDIO_FORMAT_DTS_UHD"; - case /* AUDIO_FORMAT_DRA */ 0x2F000000: - return "AUDIO_FORMAT_DRA"; + case /* AUDIO_FORMAT_MPEGH_SUB_BL_L3 */ 0x2C000013: + return "AUDIO_FORMAT_MPEGH_SUB_BL_L3"; + case /* AUDIO_FORMAT_MPEGH_SUB_BL_L4 */ 0x2C000014: + return "AUDIO_FORMAT_MPEGH_SUB_BL_L4"; + case /* AUDIO_FORMAT_MPEGH_SUB_LC_L3 */ 0x2C000023: + return "AUDIO_FORMAT_MPEGH_SUB_LC_L3"; + case /* AUDIO_FORMAT_MPEGH_SUB_LC_L4 */ 0x2C000024: + return "AUDIO_FORMAT_MPEGH_SUB_LC_L4"; default: return "AUDIO_FORMAT_(" + audioFormat + ")"; } @@ -2400,4 +2416,3 @@ public class AudioSystem */ final static int NATIVE_EVENT_ROUTING_CHANGE = 1000; } - diff --git a/media/java/android/media/AudioTrack.java b/media/java/android/media/AudioTrack.java index 85cd342b5e11..d51f1e1327bd 100644 --- a/media/java/android/media/AudioTrack.java +++ b/media/java/android/media/AudioTrack.java @@ -48,8 +48,8 @@ import java.lang.ref.WeakReference; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.NioUtils; -import java.util.HashMap; import java.util.LinkedList; +import java.util.Map; import java.util.Objects; import java.util.concurrent.Executor; @@ -1867,26 +1867,24 @@ public class AudioTrack extends PlayerBase } // General pair map - private static final HashMap<String, Integer> CHANNEL_PAIR_MAP = new HashMap<>() {{ - put("front", AudioFormat.CHANNEL_OUT_FRONT_LEFT - | AudioFormat.CHANNEL_OUT_FRONT_RIGHT); - put("back", AudioFormat.CHANNEL_OUT_BACK_LEFT - | AudioFormat.CHANNEL_OUT_BACK_RIGHT); - put("front of center", AudioFormat.CHANNEL_OUT_FRONT_LEFT_OF_CENTER - | AudioFormat.CHANNEL_OUT_FRONT_RIGHT_OF_CENTER); - put("side", AudioFormat.CHANNEL_OUT_SIDE_LEFT - | AudioFormat.CHANNEL_OUT_SIDE_RIGHT); - put("top front", AudioFormat.CHANNEL_OUT_TOP_FRONT_LEFT - | AudioFormat.CHANNEL_OUT_TOP_FRONT_RIGHT); - put("top back", AudioFormat.CHANNEL_OUT_TOP_BACK_LEFT - | AudioFormat.CHANNEL_OUT_TOP_BACK_RIGHT); - put("top side", AudioFormat.CHANNEL_OUT_TOP_SIDE_LEFT - | AudioFormat.CHANNEL_OUT_TOP_SIDE_RIGHT); - put("bottom front", AudioFormat.CHANNEL_OUT_BOTTOM_FRONT_LEFT - | AudioFormat.CHANNEL_OUT_BOTTOM_FRONT_RIGHT); - put("front wide", AudioFormat.CHANNEL_OUT_FRONT_WIDE_LEFT - | AudioFormat.CHANNEL_OUT_FRONT_WIDE_RIGHT); - }}; + private static final Map<String, Integer> CHANNEL_PAIR_MAP = Map.of( + "front", AudioFormat.CHANNEL_OUT_FRONT_LEFT + | AudioFormat.CHANNEL_OUT_FRONT_RIGHT, + "back", AudioFormat.CHANNEL_OUT_BACK_LEFT + | AudioFormat.CHANNEL_OUT_BACK_RIGHT, + "front of center", AudioFormat.CHANNEL_OUT_FRONT_LEFT_OF_CENTER + | AudioFormat.CHANNEL_OUT_FRONT_RIGHT_OF_CENTER, + "side", AudioFormat.CHANNEL_OUT_SIDE_LEFT | AudioFormat.CHANNEL_OUT_SIDE_RIGHT, + "top front", AudioFormat.CHANNEL_OUT_TOP_FRONT_LEFT + | AudioFormat.CHANNEL_OUT_TOP_FRONT_RIGHT, + "top back", AudioFormat.CHANNEL_OUT_TOP_BACK_LEFT + | AudioFormat.CHANNEL_OUT_TOP_BACK_RIGHT, + "top side", AudioFormat.CHANNEL_OUT_TOP_SIDE_LEFT + | AudioFormat.CHANNEL_OUT_TOP_SIDE_RIGHT, + "bottom front", AudioFormat.CHANNEL_OUT_BOTTOM_FRONT_LEFT + | AudioFormat.CHANNEL_OUT_BOTTOM_FRONT_RIGHT, + "front wide", AudioFormat.CHANNEL_OUT_FRONT_WIDE_LEFT + | AudioFormat.CHANNEL_OUT_FRONT_WIDE_RIGHT); /** * Convenience method to check that the channel configuration (a.k.a channel mask) is supported @@ -1924,7 +1922,7 @@ public class AudioTrack extends PlayerBase return false; } // Check all pairs to see that they are matched (front duplicated here). - for (HashMap.Entry<String, Integer> e : CHANNEL_PAIR_MAP.entrySet()) { + for (Map.Entry<String, Integer> e : CHANNEL_PAIR_MAP.entrySet()) { final int positionPair = e.getValue(); if ((channelConfig & positionPair) != 0 && (channelConfig & positionPair) != positionPair) { diff --git a/media/java/android/media/ExifInterface.java b/media/java/android/media/ExifInterface.java index e18642ce9856..62d14e155f57 100644 --- a/media/java/android/media/ExifInterface.java +++ b/media/java/android/media/ExifInterface.java @@ -70,6 +70,7 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.TimeZone; import java.util.regex.Matcher; @@ -4833,12 +4834,13 @@ public class ExifInterface { for (int i = 1; i < entryValues.length; ++i) { final Pair<Integer, Integer> guessDataFormat = guessDataFormat(entryValues[i]); int first = -1, second = -1; - if (guessDataFormat.first == dataFormat.first - || guessDataFormat.second == dataFormat.first) { + if (Objects.equals(guessDataFormat.first, dataFormat.first) + || Objects.equals(guessDataFormat.second, dataFormat.first)) { first = dataFormat.first; } - if (dataFormat.second != -1 && (guessDataFormat.first == dataFormat.second - || guessDataFormat.second == dataFormat.second)) { + if (dataFormat.second != -1 + && (Objects.equals(guessDataFormat.first, dataFormat.second) + || Objects.equals(guessDataFormat.second, dataFormat.second))) { second = dataFormat.second; } if (first == -1 && second == -1) { diff --git a/media/java/android/media/MediaHTTPService.java b/media/java/android/media/MediaHTTPService.java index 3008067daefb..2342a426e77c 100644 --- a/media/java/android/media/MediaHTTPService.java +++ b/media/java/android/media/MediaHTTPService.java @@ -21,6 +21,8 @@ import android.compat.annotation.UnsupportedAppUsage; import android.os.IBinder; import android.util.Log; +import com.android.internal.annotations.GuardedBy; + import java.net.CookieHandler; import java.net.CookieManager; import java.net.CookieStore; @@ -31,7 +33,9 @@ import java.util.List; public class MediaHTTPService extends IMediaHTTPService.Stub { private static final String TAG = "MediaHTTPService"; @Nullable private List<HttpCookie> mCookies; - private Boolean mCookieStoreInitialized = new Boolean(false); + private final Object mCookieStoreInitializedLock = new Object(); + @GuardedBy("mCookieStoreInitializedLock") + private boolean mCookieStoreInitialized = false; public MediaHTTPService(@Nullable List<HttpCookie> cookies) { mCookies = cookies; @@ -40,7 +44,7 @@ public class MediaHTTPService extends IMediaHTTPService.Stub { public IMediaHTTPConnection makeHTTPConnection() { - synchronized (mCookieStoreInitialized) { + synchronized (mCookieStoreInitializedLock) { // Only need to do it once for all connections if ( !mCookieStoreInitialized ) { CookieHandler cookieHandler = CookieHandler.getDefault(); @@ -78,8 +82,8 @@ public class MediaHTTPService extends IMediaHTTPService.Stub { Log.v(TAG, "makeHTTPConnection(" + this + "): cookieHandler: " + cookieHandler + " Cookies: " + mCookies); - } // mCookieStoreInitialized - } // synchronized + } + } return new MediaHTTPConnection(); } diff --git a/media/java/android/media/MediaPlayer.java b/media/java/android/media/MediaPlayer.java index 737bc344c033..a9cbffb54b49 100644 --- a/media/java/android/media/MediaPlayer.java +++ b/media/java/android/media/MediaPlayer.java @@ -2473,6 +2473,8 @@ public class MediaPlayer extends PlayerBase * * @see android.media.MediaPlayer#getTrackInfo */ + // The creator needs to be pulic, which requires removing the @UnsupportedAppUsage + @SuppressWarnings("ParcelableCreator") static public class TrackInfo implements Parcelable { /** * Gets the track type. diff --git a/media/java/android/media/tv/tuner/dvr/DvrRecorder.java b/media/java/android/media/tv/tuner/dvr/DvrRecorder.java index e72026aab992..1aae8f413559 100644 --- a/media/java/android/media/tv/tuner/dvr/DvrRecorder.java +++ b/media/java/android/media/tv/tuner/dvr/DvrRecorder.java @@ -27,6 +27,7 @@ import android.os.ParcelFileDescriptor; import android.os.Process; import android.util.Log; +import com.android.internal.annotations.GuardedBy; import com.android.internal.util.FrameworkStatsLog; import java.util.concurrent.Executor; @@ -47,7 +48,9 @@ public class DvrRecorder implements AutoCloseable { private static int sInstantId = 0; private int mSegmentId = 0; private int mOverflow; - private Boolean mIsStopped = true; + private final Object mIsStoppedLock = new Object(); + @GuardedBy("mIsStoppedLock") + private boolean mIsStopped = true; private final Object mListenerLock = new Object(); private native int nativeAttachFilter(Filter filter); @@ -147,7 +150,7 @@ public class DvrRecorder implements AutoCloseable { .write(FrameworkStatsLog.TV_TUNER_DVR_STATUS, mUserId, FrameworkStatsLog.TV_TUNER_DVR_STATUS__TYPE__RECORD, FrameworkStatsLog.TV_TUNER_DVR_STATUS__STATE__STARTED, mSegmentId, 0); - synchronized (mIsStopped) { + synchronized (mIsStoppedLock) { int result = nativeStartDvr(); if (result == Tuner.RESULT_SUCCESS) { mIsStopped = false; @@ -170,7 +173,7 @@ public class DvrRecorder implements AutoCloseable { .write(FrameworkStatsLog.TV_TUNER_DVR_STATUS, mUserId, FrameworkStatsLog.TV_TUNER_DVR_STATUS__TYPE__RECORD, FrameworkStatsLog.TV_TUNER_DVR_STATUS__STATE__STOPPED, mSegmentId, mOverflow); - synchronized (mIsStopped) { + synchronized (mIsStoppedLock) { int result = nativeStopDvr(); if (result == Tuner.RESULT_SUCCESS) { mIsStopped = true; @@ -188,7 +191,7 @@ public class DvrRecorder implements AutoCloseable { */ @Result public int flush() { - synchronized (mIsStopped) { + synchronized (mIsStoppedLock) { if (mIsStopped) { return nativeFlushDvr(); } diff --git a/media/java/android/mtp/MtpPropertyGroup.java b/media/java/android/mtp/MtpPropertyGroup.java index aff2e1b4cf31..89e5e0d783ff 100644 --- a/media/java/android/mtp/MtpPropertyGroup.java +++ b/media/java/android/mtp/MtpPropertyGroup.java @@ -230,7 +230,7 @@ class MtpPropertyGroup { case MtpConstants.PROPERTY_PERSISTENT_UID: // The persistent uid must be unique and never reused among all objects, // and remain the same between sessions. - long puid = (object.getPath().toString().hashCode() << 32) + long puid = (((long) object.getPath().toString().hashCode()) << 32) + object.getModifiedTime(); list.append(id, property.code, property.type, puid); break; diff --git a/media/jni/android_media_MediaCodec.cpp b/media/jni/android_media_MediaCodec.cpp index 95599bd41e8d..1183ca3b4977 100644 --- a/media/jni/android_media_MediaCodec.cpp +++ b/media/jni/android_media_MediaCodec.cpp @@ -174,6 +174,12 @@ static struct { jfieldID typeId; } gDescriptorInfo; +static struct { + jclass clazz; + jmethodID ctorId; + jmethodID setId; +} gBufferInfo; + struct fields_t { jmethodID postEventFromNativeID; jmethodID lockAndGetContextID; @@ -460,11 +466,7 @@ status_t JMediaCodec::dequeueOutputBuffer( return err; } - ScopedLocalRef<jclass> clazz( - env, env->FindClass("android/media/MediaCodec$BufferInfo")); - - jmethodID method = env->GetMethodID(clazz.get(), "set", "(IIJI)V"); - env->CallVoidMethod(bufferInfo, method, (jint)offset, (jint)size, timeUs, flags); + env->CallVoidMethod(bufferInfo, gBufferInfo.setId, (jint)offset, (jint)size, timeUs, flags); return OK; } @@ -1091,13 +1093,7 @@ void JMediaCodec::handleCallback(const sp<AMessage> &msg) { CHECK(msg->findInt64("timeUs", &timeUs)); CHECK(msg->findInt32("flags", (int32_t *)&flags)); - ScopedLocalRef<jclass> clazz( - env, env->FindClass("android/media/MediaCodec$BufferInfo")); - jmethodID ctor = env->GetMethodID(clazz.get(), "<init>", "()V"); - jmethodID method = env->GetMethodID(clazz.get(), "set", "(IIJI)V"); - - obj = env->NewObject(clazz.get(), ctor); - + obj = env->NewObject(gBufferInfo.clazz, gBufferInfo.ctorId); if (obj == NULL) { if (env->ExceptionCheck()) { ALOGE("Could not create MediaCodec.BufferInfo."); @@ -1107,7 +1103,7 @@ void JMediaCodec::handleCallback(const sp<AMessage> &msg) { return; } - env->CallVoidMethod(obj, method, (jint)offset, (jint)size, timeUs, flags); + env->CallVoidMethod(obj, gBufferInfo.setId, (jint)offset, (jint)size, timeUs, flags); break; } @@ -3235,6 +3231,16 @@ static void android_media_MediaCodec_native_init(JNIEnv *env, jclass) { gDescriptorInfo.typeId = env->GetFieldID(clazz.get(), "mType", "I"); CHECK(gDescriptorInfo.typeId != NULL); + + clazz.reset(env->FindClass("android/media/MediaCodec$BufferInfo")); + CHECK(clazz.get() != NULL); + gBufferInfo.clazz = (jclass)env->NewGlobalRef(clazz.get()); + + gBufferInfo.ctorId = env->GetMethodID(clazz.get(), "<init>", "()V"); + CHECK(gBufferInfo.ctorId != NULL); + + gBufferInfo.setId = env->GetMethodID(clazz.get(), "set", "(IIJI)V"); + CHECK(gBufferInfo.setId != NULL); } static void android_media_MediaCodec_native_setup( diff --git a/media/mca/effect/java/android/media/effect/EffectFactory.java b/media/mca/effect/java/android/media/effect/EffectFactory.java index f6fcba71e339..cbb273608ad7 100644 --- a/media/mca/effect/java/android/media/effect/EffectFactory.java +++ b/media/mca/effect/java/android/media/effect/EffectFactory.java @@ -486,11 +486,9 @@ public class EffectFactory { private Effect instantiateEffect(Class effectClass, String name) { // Make sure this is an Effect subclass - try { - effectClass.asSubclass(Effect.class); - } catch (ClassCastException e) { + if (!Effect.class.isAssignableFrom(effectClass)) { throw new IllegalArgumentException("Attempting to allocate effect '" + effectClass - + "' which is not a subclass of Effect!", e); + + "' which is not a subclass of Effect!"); } // Look for the correct constructor diff --git a/media/mca/filterfw/java/android/filterfw/core/Filter.java b/media/mca/filterfw/java/android/filterfw/core/Filter.java index a608ef5be3f4..e82c046b7390 100644 --- a/media/mca/filterfw/java/android/filterfw/core/Filter.java +++ b/media/mca/filterfw/java/android/filterfw/core/Filter.java @@ -90,9 +90,7 @@ public abstract class Filter { return false; } // Then make sure it's a subclass of Filter. - try { - filterClass.asSubclass(Filter.class); - } catch (ClassCastException e) { + if (!Filter.class.isAssignableFrom(filterClass)) { return false; } return true; diff --git a/media/mca/filterfw/java/android/filterfw/core/FilterFactory.java b/media/mca/filterfw/java/android/filterfw/core/FilterFactory.java index 779df990a9a5..736e51131ca1 100644 --- a/media/mca/filterfw/java/android/filterfw/core/FilterFactory.java +++ b/media/mca/filterfw/java/android/filterfw/core/FilterFactory.java @@ -112,9 +112,7 @@ public class FilterFactory { public Filter createFilterByClass(Class filterClass, String filterName) { // Make sure this is a Filter subclass - try { - filterClass.asSubclass(Filter.class); - } catch (ClassCastException e) { + if (!Filter.class.isAssignableFrom(filterClass)) { throw new IllegalArgumentException("Attempting to allocate class '" + filterClass + "' which is not a subclass of Filter!"); } diff --git a/media/mca/filterfw/java/android/filterfw/core/KeyValueMap.java b/media/mca/filterfw/java/android/filterfw/core/KeyValueMap.java index 8cf9a13438e5..6ff1885fa8eb 100644 --- a/media/mca/filterfw/java/android/filterfw/core/KeyValueMap.java +++ b/media/mca/filterfw/java/android/filterfw/core/KeyValueMap.java @@ -55,12 +55,12 @@ public class KeyValueMap extends HashMap<String, Object> { public int getInt(String key) { Object result = get(key); - return result != null ? (Integer)result : null; + return result != null ? (Integer) result : 0; } public float getFloat(String key) { Object result = get(key); - return result != null ? (Float)result : null; + return result != null ? (Float) result : 0; } @Override diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/performance/MediaPlayerPerformance.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/performance/MediaPlayerPerformance.java index c52816571ffb..8c05725a9ef1 100644 --- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/performance/MediaPlayerPerformance.java +++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/performance/MediaPlayerPerformance.java @@ -296,7 +296,7 @@ public class MediaPlayerPerformance extends ActivityInstrumentationTestCase2<Med mMemWriter.write("End Memory :" + mEndMemory + "\n"); } } catch (Exception e) { - e.toString(); + // TODO } } diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/CameraMetadataTest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/CameraMetadataTest.java index 39add7ea8a42..c814eba7d187 100644 --- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/CameraMetadataTest.java +++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/CameraMetadataTest.java @@ -264,8 +264,14 @@ public class CameraMetadataTest extends junit.framework.TestCase { builder.append("**"); } - if (elem instanceof Number) { - builder.append(String.format("%x", elem)); + if (elem instanceof Byte) { + builder.append(String.format("%x", (Byte) elem)); + } else if (elem instanceof Short) { + builder.append(String.format("%x", (Short) elem)); + } else if (elem instanceof Integer) { + builder.append(String.format("%x", (Integer) elem)); + } else if (elem instanceof Long) { + builder.append(String.format("%x", (Long) elem)); } else { builder.append(elem); } diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaPlayerGetCurrentPositionStateUnitTest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaPlayerGetCurrentPositionStateUnitTest.java index fd1c2d3e8e94..37dd4b5330c5 100644 --- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaPlayerGetCurrentPositionStateUnitTest.java +++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaPlayerGetCurrentPositionStateUnitTest.java @@ -18,7 +18,7 @@ package com.android.mediaframeworktest.unit; import android.media.MediaPlayer; import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.LargeTest;; +import android.test.suitebuilder.annotation.LargeTest; /** * Unit test class to test the set of valid and invalid states that diff --git a/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/CompanionDeviceActivity.java b/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/CompanionDeviceActivity.java index a3aa0100870a..77f37d014010 100644 --- a/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/CompanionDeviceActivity.java +++ b/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/CompanionDeviceActivity.java @@ -193,6 +193,7 @@ public class CompanionDeviceActivity extends FragmentActivity implements initUI(); } + @SuppressWarnings("MissingSuperCall") // TODO: Fix me @Override protected void onNewIntent(Intent intent) { // Handle another incoming request (while we are not done with the original - mRequest - diff --git a/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/google/CloudPrintPlugin.java b/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/google/CloudPrintPlugin.java index 93e6271319f6..3029d10d4cf3 100644 --- a/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/google/CloudPrintPlugin.java +++ b/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/google/CloudPrintPlugin.java @@ -55,18 +55,15 @@ public class CloudPrintPlugin implements PrintServicePlugin { private static final String PRIVET_SERVICE = "_privet._tcp"; /** The required mDNS service types */ - private static final Set<String> PRINTER_SERVICE_TYPE = new HashSet<String>() {{ - // Not checking _printer_._sub - add(PRIVET_SERVICE); - }}; + private static final Set<String> PRINTER_SERVICE_TYPE = Set.of( + PRIVET_SERVICE); // Not checking _printer_._sub /** All possible connection states */ - private static final Set<String> POSSIBLE_CONNECTION_STATES = new HashSet<String>() {{ - add("online"); - add("offline"); - add("connecting"); - add("not-configured"); - }}; + private static final Set<String> POSSIBLE_CONNECTION_STATES = Set.of( + "online", + "offline", + "connecting", + "not-configured"); private static final byte SUPPORTED_TXTVERS = '1'; diff --git a/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/mdnsFilter/MDNSFilterPlugin.java b/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/mdnsFilter/MDNSFilterPlugin.java index 34e7e3d1cd6b..0c5de2741d1b 100644 --- a/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/mdnsFilter/MDNSFilterPlugin.java +++ b/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/mdnsFilter/MDNSFilterPlugin.java @@ -37,9 +37,7 @@ import java.util.Set; public class MDNSFilterPlugin implements PrintServicePlugin { /** The mDNS service types supported */ - private static final Set<String> PRINTER_SERVICE_TYPES = new HashSet<String>() {{ - add("_ipp._tcp"); - }}; + private static final Set<String> PRINTER_SERVICE_TYPES = Set.of("_ipp._tcp"); /** * The printer filter for {@link MDNSFilteredDiscovery} passing only mDNS results diff --git a/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/samsung/PrinterFilterMopria.java b/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/samsung/PrinterFilterMopria.java index d03bb1d76003..b9983c306289 100644 --- a/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/samsung/PrinterFilterMopria.java +++ b/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/samsung/PrinterFilterMopria.java @@ -23,7 +23,6 @@ import android.util.Log; import com.android.printservice.recommendation.util.MDNSFilteredDiscovery; import com.android.printservice.recommendation.util.MDNSUtils; -import java.util.HashSet; import java.util.Set; /** @@ -32,10 +31,7 @@ import java.util.Set; class PrinterFilterMopria implements MDNSFilteredDiscovery.PrinterFilter { private static final String TAG = "PrinterFilterMopria"; - static final Set<String> MOPRIA_MDNS_SERVICES = new HashSet<String>() {{ - add("_ipp._tcp"); - add("_ipps._tcp"); - }}; + static final Set<String> MOPRIA_MDNS_SERVICES = Set.of("_ipp._tcp", "_ipps._tcp"); private static final String PDL__PDF = "application/pdf"; private static final String PDL__PCLM = "application/PCLm"; diff --git a/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/samsung/PrinterFilterSamsung.java b/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/samsung/PrinterFilterSamsung.java index b9b90988c37b..680dd84a25df 100644 --- a/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/samsung/PrinterFilterSamsung.java +++ b/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/samsung/PrinterFilterSamsung.java @@ -25,7 +25,6 @@ import androidx.annotation.NonNull; import com.android.printservice.recommendation.util.MDNSFilteredDiscovery; import com.android.printservice.recommendation.util.MDNSUtils; -import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; @@ -36,9 +35,7 @@ import java.util.Set; class PrinterFilterSamsung implements MDNSFilteredDiscovery.PrinterFilter { private static final String TAG = "PrinterFilterSamsung"; - static final Set<String> SAMSUNG_MDNS_SERVICES = new HashSet<String>() {{ - add("_pdl-datastream._tcp"); - }}; + static final Set<String> SAMSUNG_MDNS_SERVICES = Set.of("_pdl-datastream._tcp"); private static final String[] NOT_SUPPORTED_MODELS = new String[]{ "SCX-5x15", @@ -57,9 +54,7 @@ class PrinterFilterSamsung implements MDNSFilteredDiscovery.PrinterFilter { private static final String ATTR_PRODUCT = "product"; private static final String ATTR_TY = "ty"; - private static Set<String> SAMUNG_VENDOR_SET = new HashSet<String>() {{ - add("samsung"); - }}; + private static final Set<String> SAMUNG_VENDOR_SET = Set.of("samsung"); @Override public boolean matchesCriteria(NsdServiceInfo nsdServiceInfo) { diff --git a/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/samsung/SamsungRecommendationPlugin.java b/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/samsung/SamsungRecommendationPlugin.java index ae1bdcedaabb..cbd5833925b8 100644 --- a/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/samsung/SamsungRecommendationPlugin.java +++ b/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/samsung/SamsungRecommendationPlugin.java @@ -29,10 +29,11 @@ import java.util.HashSet; import java.util.Set; public class SamsungRecommendationPlugin implements PrintServicePlugin { - private static final Set<String> ALL_MDNS_SERVICES = new HashSet<String>() {{ - addAll(PrinterFilterMopria.MOPRIA_MDNS_SERVICES); - addAll(PrinterFilterSamsung.SAMSUNG_MDNS_SERVICES); - }}; + private static final Set<String> ALL_MDNS_SERVICES = new HashSet<String>(); + static { + ALL_MDNS_SERVICES.addAll(PrinterFilterMopria.MOPRIA_MDNS_SERVICES); + ALL_MDNS_SERVICES.addAll(PrinterFilterSamsung.SAMSUNG_MDNS_SERVICES); + } private final @NonNull Context mContext; private final @NonNull MDNSFilteredDiscovery mMDNSFilteredDiscovery; diff --git a/packages/PrintSpooler/src/com/android/printspooler/widget/PrintContentView.java b/packages/PrintSpooler/src/com/android/printspooler/widget/PrintContentView.java index 00b3736f8d6b..b0aa8f19f24b 100644 --- a/packages/PrintSpooler/src/com/android/printspooler/widget/PrintContentView.java +++ b/packages/PrintSpooler/src/com/android/printspooler/widget/PrintContentView.java @@ -402,7 +402,7 @@ public final class PrintContentView extends ViewGroup implements View.OnClickLis @Override public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) { - if ((isOptionsClosed() || isOptionsClosed()) && dy <= 0) { + if (isOptionsClosed() && dy <= 0) { return; } diff --git a/packages/SettingsLib/OWNERS b/packages/SettingsLib/OWNERS index 8eafbdfdf6bc..24bb3a7de147 100644 --- a/packages/SettingsLib/OWNERS +++ b/packages/SettingsLib/OWNERS @@ -3,9 +3,9 @@ dsandler@android.com edgarwang@google.com emilychuang@google.com evanlaird@google.com +hanxu@google.com juliacr@google.com leifhendrik@google.com -tmfang@google.com virgild@google.com # Exempt resource files (because they are in a flat directory and too hard to manage via OWNERS) diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/BluetoothDiscoverableTimeoutReceiver.java b/packages/SettingsLib/src/com/android/settingslib/bluetooth/BluetoothDiscoverableTimeoutReceiver.java index 6ce72bbc6909..3af64e2889e7 100644 --- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/BluetoothDiscoverableTimeoutReceiver.java +++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/BluetoothDiscoverableTimeoutReceiver.java @@ -82,4 +82,4 @@ public class BluetoothDiscoverableTimeoutReceiver extends BroadcastReceiver { Log.e(TAG, "localBluetoothAdapter is NULL!!"); } } -}; +} diff --git a/packages/SettingsLib/src/com/android/settingslib/qrcode/QrDecorateView.java b/packages/SettingsLib/src/com/android/settingslib/qrcode/QrDecorateView.java index 51cf59c25502..ac9cdacec598 100644 --- a/packages/SettingsLib/src/com/android/settingslib/qrcode/QrDecorateView.java +++ b/packages/SettingsLib/src/com/android/settingslib/qrcode/QrDecorateView.java @@ -34,16 +34,16 @@ public class QrDecorateView extends View { private static final float CORNER_LINE_LENGTH = 264f; // 264dp private static final float CORNER_RADIUS = 16f; // 16dp - final private int mCornerColor; - final private int mFocusedCornerColor; - final private int mBackgroundColor; + private final int mCornerColor; + private final int mFocusedCornerColor; + private final int mBackgroundColor; - final private Paint mStrokePaint; - final private Paint mTransparentPaint; - final private Paint mBackgroundPaint; + private final Paint mStrokePaint; + private final Paint mTransparentPaint; + private final Paint mBackgroundPaint; - final private float mRadius; - final private float mInnerRidus; + private final float mRadius; + private final float mInnerRadius; private Bitmap mMaskBitmap; private Canvas mMaskCanvas; @@ -72,7 +72,7 @@ public class QrDecorateView extends View { mRadius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, CORNER_RADIUS, getResources().getDisplayMetrics()); // Inner radius needs to minus stroke width for keeping the width of border consistent. - mInnerRidus = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, + mInnerRadius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, CORNER_RADIUS - CORNER_STROKE_WIDTH, getResources().getDisplayMetrics()); mCornerColor = context.getResources().getColor(R.color.qr_corner_line_color); @@ -95,7 +95,10 @@ public class QrDecorateView extends View { protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); - if(mMaskBitmap == null) { + if (!isLaidOut()) { + return; + } + if (mMaskBitmap == null) { mMaskBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888); mMaskCanvas = new Canvas(mMaskBitmap); } @@ -105,16 +108,18 @@ public class QrDecorateView extends View { @Override protected void onDraw(Canvas canvas) { - // Set frame line color. - mStrokePaint.setColor(mFocused ? mFocusedCornerColor : mCornerColor); - // Draw background color. - mMaskCanvas.drawColor(mBackgroundColor); - // Draw outer corner. - mMaskCanvas.drawRoundRect(mOuterFrame, mRadius, mRadius, mStrokePaint); - // Draw inner transparent corner. - mMaskCanvas.drawRoundRect(mInnerFrame, mInnerRidus, mInnerRidus, mTransparentPaint); - - canvas.drawBitmap(mMaskBitmap, 0, 0, mBackgroundPaint); + if (mMaskCanvas != null && mMaskBitmap != null) { + // Set frame line color. + mStrokePaint.setColor(mFocused ? mFocusedCornerColor : mCornerColor); + // Draw background color. + mMaskCanvas.drawColor(mBackgroundColor); + // Draw outer corner. + mMaskCanvas.drawRoundRect(mOuterFrame, mRadius, mRadius, mStrokePaint); + // Draw inner transparent corner. + mMaskCanvas.drawRoundRect(mInnerFrame, mInnerRadius, mInnerRadius, mTransparentPaint); + + canvas.drawBitmap(mMaskBitmap, 0, 0, mBackgroundPaint); + } super.onDraw(canvas); } diff --git a/packages/SystemUI/src/com/android/keyguard/AdminSecondaryLockScreenController.java b/packages/SystemUI/src/com/android/keyguard/AdminSecondaryLockScreenController.java index 23195af8bdea..00f1c0108d0b 100644 --- a/packages/SystemUI/src/com/android/keyguard/AdminSecondaryLockScreenController.java +++ b/packages/SystemUI/src/com/android/keyguard/AdminSecondaryLockScreenController.java @@ -33,6 +33,7 @@ import android.view.SurfaceView; import android.view.ViewGroup; import com.android.internal.annotations.VisibleForTesting; +import com.android.keyguard.KeyguardSecurityModel.SecurityMode; import com.android.keyguard.dagger.KeyguardBouncerScope; import com.android.systemui.dagger.qualifiers.Main; @@ -208,7 +209,7 @@ public class AdminSecondaryLockScreenController { hide(); if (mKeyguardCallback != null) { mKeyguardCallback.dismiss(/* securityVerified= */ true, userId, - /* bypassSecondaryLockScreen= */true); + /* bypassSecondaryLockScreen= */true, SecurityMode.Invalid); } } } diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardAbsKeyInputViewController.java b/packages/SystemUI/src/com/android/keyguard/KeyguardAbsKeyInputViewController.java index eb418ff3b142..b8fcb103402d 100644 --- a/packages/SystemUI/src/com/android/keyguard/KeyguardAbsKeyInputViewController.java +++ b/packages/SystemUI/src/com/android/keyguard/KeyguardAbsKeyInputViewController.java @@ -179,7 +179,7 @@ public abstract class KeyguardAbsKeyInputViewController<T extends KeyguardAbsKey if (dismissKeyguard) { mDismissing = true; mLatencyTracker.onActionStart(LatencyTracker.ACTION_LOCKSCREEN_UNLOCK); - getKeyguardSecurityCallback().dismiss(true, userId); + getKeyguardSecurityCallback().dismiss(true, userId, getSecurityMode()); } } else { if (isValidPassword) { diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardHostViewController.java b/packages/SystemUI/src/com/android/keyguard/KeyguardHostViewController.java index 12fa401d7fea..befd59be061d 100644 --- a/packages/SystemUI/src/com/android/keyguard/KeyguardHostViewController.java +++ b/packages/SystemUI/src/com/android/keyguard/KeyguardHostViewController.java @@ -90,7 +90,7 @@ public class KeyguardHostViewController extends ViewController<KeyguardHostView> Log.i(TAG, "TrustAgent dismissed Keyguard."); } mSecurityCallback.dismiss(false /* authenticated */, userId, - /* bypassSecondaryLockScreen */ false); + /* bypassSecondaryLockScreen */ false, SecurityMode.Invalid); } else { mViewMediatorCallback.playTrustedSound(); } @@ -102,9 +102,9 @@ public class KeyguardHostViewController extends ViewController<KeyguardHostView> @Override public boolean dismiss(boolean authenticated, int targetUserId, - boolean bypassSecondaryLockScreen) { + boolean bypassSecondaryLockScreen, SecurityMode expectedSecurityMode) { return mKeyguardSecurityContainerController.showNextSecurityScreenOrFinish( - authenticated, targetUserId, bypassSecondaryLockScreen); + authenticated, targetUserId, bypassSecondaryLockScreen, expectedSecurityMode); } @Override @@ -212,7 +212,8 @@ public class KeyguardHostViewController extends ViewController<KeyguardHostView> * @return True if the keyguard is done. */ public boolean dismiss(int targetUserId) { - return mSecurityCallback.dismiss(false, targetUserId, false); + return mSecurityCallback.dismiss(false, targetUserId, false, + getCurrentSecurityMode()); } /** @@ -355,10 +356,10 @@ public class KeyguardHostViewController extends ViewController<KeyguardHostView> } public boolean handleBackKey() { - if (mKeyguardSecurityContainerController.getCurrentSecurityMode() - != SecurityMode.None) { + SecurityMode securityMode = mKeyguardSecurityContainerController.getCurrentSecurityMode(); + if (securityMode != SecurityMode.None) { mKeyguardSecurityContainerController.dismiss( - false, KeyguardUpdateMonitor.getCurrentUser()); + false, KeyguardUpdateMonitor.getCurrentUser(), securityMode); return true; } return false; diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardInputViewController.java b/packages/SystemUI/src/com/android/keyguard/KeyguardInputViewController.java index 98ac640bf703..87300c3f0504 100644 --- a/packages/SystemUI/src/com/android/keyguard/KeyguardInputViewController.java +++ b/packages/SystemUI/src/com/android/keyguard/KeyguardInputViewController.java @@ -59,10 +59,11 @@ public abstract class KeyguardInputViewController<T extends KeyguardInputView> return false; } @Override - public void dismiss(boolean securityVerified, int targetUserId) { } + public void dismiss(boolean securityVerified, int targetUserId, + SecurityMode expectedSecurityMode) { } @Override public void dismiss(boolean authenticated, int targetId, - boolean bypassSecondaryLockScreen) { } + boolean bypassSecondaryLockScreen, SecurityMode expectedSecurityMode) { } @Override public void onUserInput() { } @Override diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardPatternViewController.java b/packages/SystemUI/src/com/android/keyguard/KeyguardPatternViewController.java index 39c394981193..1a59b820c1bd 100644 --- a/packages/SystemUI/src/com/android/keyguard/KeyguardPatternViewController.java +++ b/packages/SystemUI/src/com/android/keyguard/KeyguardPatternViewController.java @@ -171,7 +171,7 @@ public class KeyguardPatternViewController if (dismissKeyguard) { mLockPatternView.setDisplayMode(LockPatternView.DisplayMode.Correct); mLatencyTracker.onActionStart(LatencyTracker.ACTION_LOCKSCREEN_UNLOCK); - getKeyguardSecurityCallback().dismiss(true, userId); + getKeyguardSecurityCallback().dismiss(true, userId, SecurityMode.Pattern); } } else { mLockPatternView.setDisplayMode(LockPatternView.DisplayMode.Wrong); diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityCallback.java b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityCallback.java index e38472745234..bc72f7979a74 100644 --- a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityCallback.java +++ b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityCallback.java @@ -15,14 +15,17 @@ */ package com.android.keyguard; +import com.android.keyguard.KeyguardSecurityModel.SecurityMode; + public interface KeyguardSecurityCallback { /** * Dismiss the given security screen. * @param securityVerified true if the user correctly entered credentials for the given screen. * @param targetUserId a user that needs to be the foreground user at the dismissal completion. + * @param expectedSecurityMode The security mode that is invoking this dismiss. */ - void dismiss(boolean securityVerified, int targetUserId); + void dismiss(boolean securityVerified, int targetUserId, SecurityMode expectedSecurityMode); /** * Dismiss the given security screen. @@ -30,8 +33,10 @@ public interface KeyguardSecurityCallback { * @param targetUserId a user that needs to be the foreground user at the dismissal completion. * @param bypassSecondaryLockScreen true if the user can bypass the secondary lock screen, * if any, during this dismissal. + * @param expectedSecurityMode The security mode that is invoking this dismiss. */ - void dismiss(boolean securityVerified, int targetUserId, boolean bypassSecondaryLockScreen); + void dismiss(boolean securityVerified, int targetUserId, boolean bypassSecondaryLockScreen, + SecurityMode expectedSecurityMode); /** * Manually report user activity to keep the device awake. diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java index cce516d981a5..12bb47b81d7f 100644 --- a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java +++ b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java @@ -233,7 +233,12 @@ public class KeyguardSecurityContainer extends FrameLayout { // Used to notify the container when something interesting happens. public interface SecurityCallback { - boolean dismiss(boolean authenticated, int targetUserId, boolean bypassSecondaryLockScreen); + /** + * Potentially dismiss the current security screen, after validating that all device + * security has been unlocked. Otherwise show the next screen. + */ + boolean dismiss(boolean authenticated, int targetUserId, boolean bypassSecondaryLockScreen, + SecurityMode expectedSecurityMode); void userActivity(); diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainerController.java b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainerController.java index 19a2d9ed5b7b..2b9553d3eda2 100644 --- a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainerController.java +++ b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainerController.java @@ -153,14 +153,17 @@ public class KeyguardSecurityContainerController extends ViewController<Keyguard } @Override - public void dismiss(boolean authenticated, int targetId) { - dismiss(authenticated, targetId, /* bypassSecondaryLockScreen */ false); + public void dismiss(boolean authenticated, int targetId, + SecurityMode expectedSecurityMode) { + dismiss(authenticated, targetId, /* bypassSecondaryLockScreen */ false, + expectedSecurityMode); } @Override public void dismiss(boolean authenticated, int targetId, - boolean bypassSecondaryLockScreen) { - mSecurityCallback.dismiss(authenticated, targetId, bypassSecondaryLockScreen); + boolean bypassSecondaryLockScreen, SecurityMode expectedSecurityMode) { + mSecurityCallback.dismiss(authenticated, targetId, bypassSecondaryLockScreen, + expectedSecurityMode); } public boolean isVerifyUnlockOnly() { @@ -350,8 +353,13 @@ public class KeyguardSecurityContainerController extends ViewController<Keyguard return mCurrentSecurityMode; } - public void dismiss(boolean authenticated, int targetUserId) { - mKeyguardSecurityCallback.dismiss(authenticated, targetUserId); + /** + * Potentially dismiss the current security screen, after validating that all device + * security has been unlocked. Otherwise show the next screen. + */ + public void dismiss(boolean authenticated, int targetUserId, + SecurityMode expectedSecurityMode) { + mKeyguardSecurityCallback.dismiss(authenticated, targetUserId, expectedSecurityMode); } public void reset() { @@ -410,12 +418,21 @@ public class KeyguardSecurityContainerController extends ViewController<Keyguard * completion. * @param bypassSecondaryLockScreen true if the user is allowed to bypass the secondary * secondary lock screen requirement, if any. + * @param expectedSecurityMode SecurityMode that is invoking this request. SecurityMode.Invalid + * indicates that no check should be done * @return true if keyguard is done */ public boolean showNextSecurityScreenOrFinish(boolean authenticated, int targetUserId, - boolean bypassSecondaryLockScreen) { + boolean bypassSecondaryLockScreen, SecurityMode expectedSecurityMode) { if (DEBUG) Log.d(TAG, "showNextSecurityScreenOrFinish(" + authenticated + ")"); + if (expectedSecurityMode != SecurityMode.Invalid + && expectedSecurityMode != getCurrentSecurityMode()) { + Log.w(TAG, "Attempted to invoke showNextSecurityScreenOrFinish with securityMode " + + expectedSecurityMode + ", but current mode is " + getCurrentSecurityMode()); + return false; + } + boolean finish = false; boolean strongAuth = false; int eventSubtype = -1; diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardSimPinViewController.java b/packages/SystemUI/src/com/android/keyguard/KeyguardSimPinViewController.java index e33712383ed5..821b2e1d4dc5 100644 --- a/packages/SystemUI/src/com/android/keyguard/KeyguardSimPinViewController.java +++ b/packages/SystemUI/src/com/android/keyguard/KeyguardSimPinViewController.java @@ -170,7 +170,8 @@ public class KeyguardSimPinViewController mRemainingAttempts = -1; mShowDefaultMessage = true; getKeyguardSecurityCallback().dismiss( - true, KeyguardUpdateMonitor.getCurrentUser()); + true, KeyguardUpdateMonitor.getCurrentUser(), + SecurityMode.SimPin); } else { mShowDefaultMessage = false; if (result.getResult() == PinResult.PIN_RESULT_TYPE_INCORRECT) { diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardSimPukViewController.java b/packages/SystemUI/src/com/android/keyguard/KeyguardSimPukViewController.java index 47aa43b86599..203f9b660536 100644 --- a/packages/SystemUI/src/com/android/keyguard/KeyguardSimPukViewController.java +++ b/packages/SystemUI/src/com/android/keyguard/KeyguardSimPukViewController.java @@ -69,7 +69,8 @@ public class KeyguardSimPukViewController if (simState == TelephonyManager.SIM_STATE_READY) { mRemainingAttempts = -1; mShowDefaultMessage = true; - getKeyguardSecurityCallback().dismiss(true, KeyguardUpdateMonitor.getCurrentUser()); + getKeyguardSecurityCallback().dismiss(true, KeyguardUpdateMonitor.getCurrentUser(), + SecurityMode.SimPuk); } else { resetState(); } @@ -278,7 +279,8 @@ public class KeyguardSimPukViewController mShowDefaultMessage = true; getKeyguardSecurityCallback().dismiss( - true, KeyguardUpdateMonitor.getCurrentUser()); + true, KeyguardUpdateMonitor.getCurrentUser(), + SecurityMode.SimPuk); } else { mShowDefaultMessage = false; if (result.getResult() == PinResult.PIN_RESULT_TYPE_INCORRECT) { diff --git a/packages/SystemUI/src/com/android/systemui/fragments/ExtensionFragmentListener.java b/packages/SystemUI/src/com/android/systemui/fragments/ExtensionFragmentListener.java index 18fb423b87a5..d9bcb508c8e2 100644 --- a/packages/SystemUI/src/com/android/systemui/fragments/ExtensionFragmentListener.java +++ b/packages/SystemUI/src/com/android/systemui/fragments/ExtensionFragmentListener.java @@ -50,13 +50,12 @@ public class ExtensionFragmentListener<T extends FragmentBase> implements Consum @Override public void accept(T extension) { - try { - Fragment.class.cast(extension); + if (Fragment.class.isInstance(extension)) { mFragmentHostManager.getExtensionManager().setCurrentExtension(mId, mTag, mOldClass, extension.getClass().getName(), mExtension.getContext()); mOldClass = extension.getClass().getName(); - } catch (ClassCastException e) { - Log.e(TAG, extension.getClass().getName() + " must be a Fragment", e); + } else { + Log.e(TAG, extension.getClass().getName() + " must be a Fragment"); } mExtension.clearItem(true); } diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java index 0783eeec176f..90bcb0fe85fa 100644 --- a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java +++ b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java @@ -1641,7 +1641,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, try { callback.onKeyguardExitResult(true); } catch (RemoteException e) { - Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e); + Slog.w(TAG, "Failed to call onKeyguardExitResult(true)", e); } } else { diff --git a/packages/SystemUI/src/com/android/systemui/people/PeopleTileViewHelper.java b/packages/SystemUI/src/com/android/systemui/people/PeopleTileViewHelper.java index 00aa1381ace1..7f16a6b9166b 100644 --- a/packages/SystemUI/src/com/android/systemui/people/PeopleTileViewHelper.java +++ b/packages/SystemUI/src/com/android/systemui/people/PeopleTileViewHelper.java @@ -1093,7 +1093,7 @@ public class PeopleTileViewHelper { Pair<Integer, Integer> first = emojiIndices.get(i - 1); // Check if second emoji starts right after first starts - if (second.first == first.second) { + if (Objects.equals(second.first, first.second)) { // Check if emojis in sequence are the same if (Objects.equals(emojiTexts.get(i), emojiTexts.get(i - 1))) { if (DEBUG) { diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotificationLogger.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotificationLogger.java index 9fbd5c39dedd..61236630194f 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotificationLogger.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotificationLogger.java @@ -56,6 +56,7 @@ import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.concurrent.Executor; import javax.inject.Inject; @@ -592,7 +593,7 @@ public class NotificationLogger implements StateListener { return; } if (loggedExpansionState != null - && state.mIsExpanded == loggedExpansionState) { + && Objects.equals(state.mIsExpanded, loggedExpansionState)) { return; } mLoggedExpansionState.put(key, state.mIsExpanded); diff --git a/packages/SystemUI/tests/src/com/android/keyguard/AdminSecondaryLockScreenControllerTest.java b/packages/SystemUI/tests/src/com/android/keyguard/AdminSecondaryLockScreenControllerTest.java index dffad6ccbea5..80385e69cfa4 100644 --- a/packages/SystemUI/tests/src/com/android/keyguard/AdminSecondaryLockScreenControllerTest.java +++ b/packages/SystemUI/tests/src/com/android/keyguard/AdminSecondaryLockScreenControllerTest.java @@ -44,6 +44,7 @@ import android.view.SurfaceView; import androidx.test.filters.SmallTest; +import com.android.keyguard.KeyguardSecurityModel.SecurityMode; import com.android.systemui.SysuiTestCase; import org.junit.After; @@ -190,7 +191,7 @@ public class AdminSecondaryLockScreenControllerTest extends SysuiTestCase { private void verifyViewDismissed(SurfaceView v) throws Exception { verify(mKeyguardSecurityContainer).removeView(v); - verify(mKeyguardCallback).dismiss(true, TARGET_USER_ID, true); + verify(mKeyguardCallback).dismiss(true, TARGET_USER_ID, true, SecurityMode.Invalid); assertThat(mContext.isBound(mComponentName)).isFalse(); } } diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSecurityContainerControllerTest.java b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSecurityContainerControllerTest.java index 4d3343059718..efc9921fe8b9 100644 --- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSecurityContainerControllerTest.java +++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSecurityContainerControllerTest.java @@ -21,7 +21,10 @@ import static android.view.WindowInsets.Type.ime; import static com.android.keyguard.KeyguardSecurityContainer.MODE_DEFAULT; import static com.android.keyguard.KeyguardSecurityContainer.MODE_ONE_HANDED; +import static com.google.common.truth.Truth.assertThat; + import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; @@ -69,6 +72,7 @@ import org.mockito.junit.MockitoRule; @TestableLooper.RunWithLooper() public class KeyguardSecurityContainerControllerTest extends SysuiTestCase { private static final int VIEW_WIDTH = 1600; + private static final int TARGET_USER_ID = 100; @Rule public MockitoRule mRule = MockitoJUnit.rule(); @@ -299,4 +303,42 @@ public class KeyguardSecurityContainerControllerTest extends SysuiTestCase { verify(mUserSwitcherController) .removeUserSwitchCallback(any(UserSwitcherController.UserSwitchCallback.class)); } + + @Test + public void showNextSecurityScreenOrFinish_setsSecurityScreenToPinAfterSimPinUnlock() { + // GIVEN the current security method is SimPin + when(mKeyguardUpdateMonitor.getUserHasTrust(anyInt())).thenReturn(false); + when(mKeyguardUpdateMonitor.getUserUnlockedWithBiometric(TARGET_USER_ID)).thenReturn(false); + mKeyguardSecurityContainerController.showSecurityScreen(SecurityMode.SimPin); + + // WHEN a request is made from the SimPin screens to show the next security method + when(mKeyguardSecurityModel.getSecurityMode(TARGET_USER_ID)).thenReturn(SecurityMode.PIN); + mKeyguardSecurityContainerController.showNextSecurityScreenOrFinish( + /* authenticated= */true, + TARGET_USER_ID, + /* bypassSecondaryLockScreen= */true, + SecurityMode.SimPin); + + // THEN the next security method of PIN is set, and the keyguard is not marked as done + verify(mSecurityCallback, never()).finish(anyBoolean(), anyInt()); + assertThat(mKeyguardSecurityContainerController.getCurrentSecurityMode()) + .isEqualTo(SecurityMode.PIN); + } + + @Test + public void showNextSecurityScreenOrFinish_ignoresCallWhenSecurityMethodHasChanged() { + //GIVEN current security mode has been set to PIN + mKeyguardSecurityContainerController.showSecurityScreen(SecurityMode.PIN); + + //WHEN a request comes from SimPin to dismiss the security screens + boolean keyguardDone = mKeyguardSecurityContainerController.showNextSecurityScreenOrFinish( + /* authenticated= */true, + TARGET_USER_ID, + /* bypassSecondaryLockScreen= */true, + SecurityMode.SimPin); + + //THEN no action has happened, which will not dismiss the security screens + assertThat(keyguardDone).isEqualTo(false); + verify(mKeyguardUpdateMonitor, never()).getUserHasTrust(anyInt()); + } } diff --git a/packages/SystemUI/tests/src/com/android/systemui/screenshot/ImageExporterTest.java b/packages/SystemUI/tests/src/com/android/systemui/screenshot/ImageExporterTest.java index 7d563399ee1c..8a6895e5a80b 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/screenshot/ImageExporterTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/screenshot/ImageExporterTest.java @@ -65,7 +65,7 @@ public class ImageExporterTest extends SysuiTestCase { private static final byte[] EXIF_FILE_TAG = "Exif\u0000\u0000".getBytes(US_ASCII); private static final ZonedDateTime CAPTURE_TIME = - ZonedDateTime.of(LocalDateTime.of(2020, 12, 15, 13, 15), ZoneId.of("EST")); + ZonedDateTime.of(LocalDateTime.of(2020, 12, 15, 13, 15), ZoneId.of("America/New_York")); @Test public void testImageFilename() { diff --git a/services/autofill/java/com/android/server/autofill/RemoteAugmentedAutofillService.java b/services/autofill/java/com/android/server/autofill/RemoteAugmentedAutofillService.java index 8525e3634e3a..592045c23372 100644 --- a/services/autofill/java/com/android/server/autofill/RemoteAugmentedAutofillService.java +++ b/services/autofill/java/com/android/server/autofill/RemoteAugmentedAutofillService.java @@ -245,6 +245,7 @@ final class RemoteAugmentedAutofillService }); } + @SuppressWarnings("ReturnValueIgnored") private void maybeRequestShowInlineSuggestions(int sessionId, @Nullable InlineSuggestionsRequest request, @Nullable List<Dataset> inlineSuggestionsData, @Nullable Bundle clientState, diff --git a/services/backup/java/com/android/server/backup/OperationStorage.java b/services/backup/java/com/android/server/backup/OperationStorage.java index 466f647fd034..8f73436d193a 100644 --- a/services/backup/java/com/android/server/backup/OperationStorage.java +++ b/services/backup/java/com/android/server/backup/OperationStorage.java @@ -153,4 +153,4 @@ public interface OperationStorage { * @return a set of operation tokens for operations in that state. */ Set<Integer> operationTokensForOpState(@OpState int state); -}; +} diff --git a/services/backup/java/com/android/server/backup/internal/LifecycleOperationStorage.java b/services/backup/java/com/android/server/backup/internal/LifecycleOperationStorage.java index 6908c60034b6..a94167eb9fa7 100644 --- a/services/backup/java/com/android/server/backup/internal/LifecycleOperationStorage.java +++ b/services/backup/java/com/android/server/backup/internal/LifecycleOperationStorage.java @@ -353,4 +353,4 @@ public class LifecycleOperationStorage implements OperationStorage { op.callback.handleCancel(cancelAll); } } -}; +} diff --git a/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureManagerService.java b/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureManagerService.java index ff1a495edcbb..36b82f845ce3 100644 --- a/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureManagerService.java +++ b/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureManagerService.java @@ -657,7 +657,6 @@ public final class ContentCaptureManagerService extends int sessionId, int flags, @NonNull IResultReceiver result) { Objects.requireNonNull(activityToken); Objects.requireNonNull(shareableActivityToken); - Objects.requireNonNull(sessionId); final int userId = UserHandle.getCallingUserId(); final ActivityPresentationInfo activityPresentationInfo = getAmInternal() @@ -676,7 +675,6 @@ public final class ContentCaptureManagerService extends @Override public void finishSession(int sessionId) { - Objects.requireNonNull(sessionId); final int userId = UserHandle.getCallingUserId(); synchronized (mLock) { diff --git a/services/core/java/com/android/server/DynamicSystemService.java b/services/core/java/com/android/server/DynamicSystemService.java index ce0e69c40f67..27215b2fbf30 100644 --- a/services/core/java/com/android/server/DynamicSystemService.java +++ b/services/core/java/com/android/server/DynamicSystemService.java @@ -77,6 +77,8 @@ public class DynamicSystemService extends IDynamicSystemService.Stub { @Override @EnforcePermission(android.Manifest.permission.MANAGE_DYNAMIC_SYSTEM) public boolean startInstallation(String dsuSlot) throws RemoteException { + super.startInstallation_enforcePermission(); + IGsiService service = getGsiService(); mGsiService = service; // priority from high to low: sysprop -> sdcard -> /data @@ -124,6 +126,8 @@ public class DynamicSystemService extends IDynamicSystemService.Stub { @Override @EnforcePermission(android.Manifest.permission.MANAGE_DYNAMIC_SYSTEM) public int createPartition(String name, long size, boolean readOnly) throws RemoteException { + super.createPartition_enforcePermission(); + IGsiService service = getGsiService(); int status = service.createPartition(name, size, readOnly); if (status != IGsiService.INSTALL_OK) { @@ -135,6 +139,8 @@ public class DynamicSystemService extends IDynamicSystemService.Stub { @Override @EnforcePermission(android.Manifest.permission.MANAGE_DYNAMIC_SYSTEM) public boolean closePartition() throws RemoteException { + super.closePartition_enforcePermission(); + IGsiService service = getGsiService(); if (service.closePartition() != 0) { Slog.i(TAG, "Partition installation completes with error"); @@ -146,6 +152,8 @@ public class DynamicSystemService extends IDynamicSystemService.Stub { @Override @EnforcePermission(android.Manifest.permission.MANAGE_DYNAMIC_SYSTEM) public boolean finishInstallation() throws RemoteException { + super.finishInstallation_enforcePermission(); + IGsiService service = getGsiService(); if (service.closeInstall() != 0) { Slog.i(TAG, "Failed to finish installation"); @@ -157,12 +165,16 @@ public class DynamicSystemService extends IDynamicSystemService.Stub { @Override @EnforcePermission(android.Manifest.permission.MANAGE_DYNAMIC_SYSTEM) public GsiProgress getInstallationProgress() throws RemoteException { + super.getInstallationProgress_enforcePermission(); + return getGsiService().getInstallProgress(); } @Override @EnforcePermission(android.Manifest.permission.MANAGE_DYNAMIC_SYSTEM) public boolean abort() throws RemoteException { + super.abort_enforcePermission(); + return getGsiService().cancelGsiInstall(); } @@ -183,12 +195,16 @@ public class DynamicSystemService extends IDynamicSystemService.Stub { @Override @EnforcePermission(android.Manifest.permission.MANAGE_DYNAMIC_SYSTEM) public boolean isEnabled() throws RemoteException { + super.isEnabled_enforcePermission(); + return getGsiService().isGsiEnabled(); } @Override @EnforcePermission(android.Manifest.permission.MANAGE_DYNAMIC_SYSTEM) public boolean remove() throws RemoteException { + super.remove_enforcePermission(); + try { GsiServiceCallback callback = new GsiServiceCallback(); synchronized (callback) { @@ -205,6 +221,8 @@ public class DynamicSystemService extends IDynamicSystemService.Stub { @Override @EnforcePermission(android.Manifest.permission.MANAGE_DYNAMIC_SYSTEM) public boolean setEnable(boolean enable, boolean oneShot) throws RemoteException { + super.setEnable_enforcePermission(); + IGsiService gsiService = getGsiService(); if (enable) { try { @@ -229,6 +247,8 @@ public class DynamicSystemService extends IDynamicSystemService.Stub { @Override @EnforcePermission(android.Manifest.permission.MANAGE_DYNAMIC_SYSTEM) public boolean setAshmem(ParcelFileDescriptor ashmem, long size) { + super.setAshmem_enforcePermission(); + try { return getGsiService().setGsiAshmem(ashmem, size); } catch (RemoteException e) { @@ -239,6 +259,8 @@ public class DynamicSystemService extends IDynamicSystemService.Stub { @Override @EnforcePermission(android.Manifest.permission.MANAGE_DYNAMIC_SYSTEM) public boolean submitFromAshmem(long size) { + super.submitFromAshmem_enforcePermission(); + try { return getGsiService().commitGsiChunkFromAshmem(size); } catch (RemoteException e) { @@ -249,6 +271,8 @@ public class DynamicSystemService extends IDynamicSystemService.Stub { @Override @EnforcePermission(android.Manifest.permission.MANAGE_DYNAMIC_SYSTEM) public boolean getAvbPublicKey(AvbPublicKey dst) { + super.getAvbPublicKey_enforcePermission(); + try { return getGsiService().getAvbPublicKey(dst) == 0; } catch (RemoteException e) { @@ -259,6 +283,8 @@ public class DynamicSystemService extends IDynamicSystemService.Stub { @Override @EnforcePermission(android.Manifest.permission.MANAGE_DYNAMIC_SYSTEM) public long suggestScratchSize() throws RemoteException { + super.suggestScratchSize_enforcePermission(); + return getGsiService().suggestScratchSize(); } } diff --git a/services/core/java/com/android/server/GestureLauncherService.java b/services/core/java/com/android/server/GestureLauncherService.java index e529010e6b7d..7d2e2766fd0b 100644 --- a/services/core/java/com/android/server/GestureLauncherService.java +++ b/services/core/java/com/android/server/GestureLauncherService.java @@ -466,7 +466,8 @@ public class GestureLauncherService extends SystemService { public static boolean isEmergencyGestureSettingEnabled(Context context, int userId) { return isEmergencyGestureEnabled(context.getResources()) && Settings.Secure.getIntForUser(context.getContentResolver(), - Settings.Secure.EMERGENCY_GESTURE_ENABLED, 1, userId) != 0; + Settings.Secure.EMERGENCY_GESTURE_ENABLED, + isDefaultEmergencyGestureEnabled(context.getResources()) ? 1 : 0, userId) != 0; } /** @@ -513,6 +514,11 @@ public class GestureLauncherService extends SystemService { return resources.getBoolean(com.android.internal.R.bool.config_emergencyGestureEnabled); } + private static boolean isDefaultEmergencyGestureEnabled(Resources resources) { + return resources.getBoolean( + com.android.internal.R.bool.config_defaultEmergencyGestureEnabled); + } + /** * Whether GestureLauncherService should be enabled according to system properties. */ diff --git a/services/core/java/com/android/server/SerialService.java b/services/core/java/com/android/server/SerialService.java index e915fa1522a1..ff903a0b4c24 100644 --- a/services/core/java/com/android/server/SerialService.java +++ b/services/core/java/com/android/server/SerialService.java @@ -37,6 +37,8 @@ public class SerialService extends ISerialManager.Stub { @EnforcePermission(android.Manifest.permission.SERIAL_PORT) public String[] getSerialPorts() { + super.getSerialPorts_enforcePermission(); + ArrayList<String> ports = new ArrayList<String>(); for (int i = 0; i < mSerialPorts.length; i++) { String path = mSerialPorts[i]; @@ -51,6 +53,8 @@ public class SerialService extends ISerialManager.Stub { @EnforcePermission(android.Manifest.permission.SERIAL_PORT) public ParcelFileDescriptor openSerialPort(String path) { + super.openSerialPort_enforcePermission(); + for (int i = 0; i < mSerialPorts.length; i++) { if (mSerialPorts[i].equals(path)) { return native_open(path); diff --git a/services/core/java/com/android/server/StorageManagerService.java b/services/core/java/com/android/server/StorageManagerService.java index f7b05f2b895a..ec8745aa7371 100644 --- a/services/core/java/com/android/server/StorageManagerService.java +++ b/services/core/java/com/android/server/StorageManagerService.java @@ -19,12 +19,10 @@ package com.android.server; import static android.Manifest.permission.ACCESS_MTP; import static android.Manifest.permission.INSTALL_PACKAGES; import static android.Manifest.permission.MANAGE_EXTERNAL_STORAGE; -import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; import static android.app.AppOpsManager.MODE_ALLOWED; import static android.app.AppOpsManager.OP_LEGACY_STORAGE; import static android.app.AppOpsManager.OP_MANAGE_EXTERNAL_STORAGE; import static android.app.AppOpsManager.OP_REQUEST_INSTALL_PACKAGES; -import static android.app.AppOpsManager.OP_WRITE_EXTERNAL_STORAGE; import static android.app.PendingIntent.FLAG_CANCEL_CURRENT; import static android.app.PendingIntent.FLAG_IMMUTABLE; import static android.app.PendingIntent.FLAG_ONE_SHOT; @@ -4461,11 +4459,7 @@ class StorageManagerService extends IStorageManager.Stub } } - // Determine if caller is holding runtime permission - final boolean hasWrite = StorageManager.checkPermissionAndCheckOp(mContext, false, 0, - uid, packageName, WRITE_EXTERNAL_STORAGE, OP_WRITE_EXTERNAL_STORAGE); - - // We're only willing to give out installer access if they also hold + // We're only willing to give out installer access if they hold // runtime permission; this is a firm CDD requirement final boolean hasInstall = mIPackageManager.checkUidPermission(INSTALL_PACKAGES, uid) == PERMISSION_GRANTED; @@ -4481,7 +4475,7 @@ class StorageManagerService extends IStorageManager.Stub break; } } - if ((hasInstall || hasInstallOp) && hasWrite) { + if (hasInstall || hasInstallOp) { return StorageManager.MOUNT_MODE_EXTERNAL_INSTALLER; } return StorageManager.MOUNT_MODE_EXTERNAL_DEFAULT; diff --git a/services/core/java/com/android/server/accounts/AccountManagerService.java b/services/core/java/com/android/server/accounts/AccountManagerService.java index 6b731c319c4b..8dc02c107a5a 100644 --- a/services/core/java/com/android/server/accounts/AccountManagerService.java +++ b/services/core/java/com/android/server/accounts/AccountManagerService.java @@ -4794,6 +4794,7 @@ public class AccountManagerService private abstract class Session extends IAccountAuthenticatorResponse.Stub implements IBinder.DeathRecipient, ServiceConnection { + private final Object mSessionLock = new Object(); IAccountManagerResponse mResponse; final String mAccountType; final boolean mExpectActivityLaunch; @@ -4959,9 +4960,11 @@ public class AccountManagerService } private void unbind() { - if (mAuthenticator != null) { - mAuthenticator = null; - mContext.unbindService(this); + synchronized (mSessionLock) { + if (mAuthenticator != null) { + mAuthenticator = null; + mContext.unbindService(this); + } } } @@ -4971,12 +4974,14 @@ public class AccountManagerService @Override public void onServiceConnected(ComponentName name, IBinder service) { - mAuthenticator = IAccountAuthenticator.Stub.asInterface(service); - try { - run(); - } catch (RemoteException e) { - onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, - "remote exception"); + synchronized (mSessionLock) { + mAuthenticator = IAccountAuthenticator.Stub.asInterface(service); + try { + run(); + } catch (RemoteException e) { + onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, + "remote exception"); + } } } diff --git a/services/core/java/com/android/server/appop/AppOpsService.java b/services/core/java/com/android/server/appop/AppOpsService.java index b56654fd7b9a..2f7f2da925dd 100644 --- a/services/core/java/com/android/server/appop/AppOpsService.java +++ b/services/core/java/com/android/server/appop/AppOpsService.java @@ -7551,7 +7551,6 @@ public class AppOpsService extends IAppOpsService.Stub { Objects.requireNonNull(stackTrace); Preconditions.checkArgument(op >= 0); Preconditions.checkArgument(op < AppOpsManager._NUM_OP); - Objects.requireNonNull(version); NoteOpTrace noteOpTrace = new NoteOpTrace(stackTrace, op, packageName, version); diff --git a/services/core/java/com/android/server/broadcastradio/hal2/Utils.java b/services/core/java/com/android/server/broadcastradio/hal2/Utils.java index 384c9bab94b4..85d796e8404d 100644 --- a/services/core/java/com/android/server/broadcastradio/hal2/Utils.java +++ b/services/core/java/com/android/server/broadcastradio/hal2/Utils.java @@ -25,7 +25,7 @@ enum FrequencyBand { AM_LW, AM_MW, AM_SW, -}; +} class Utils { private static final String TAG = "BcRadio2Srv.utils"; diff --git a/services/core/java/com/android/server/connectivity/Vpn.java b/services/core/java/com/android/server/connectivity/Vpn.java index 1edaed014614..bc9bc031ca35 100644 --- a/services/core/java/com/android/server/connectivity/Vpn.java +++ b/services/core/java/com/android/server/connectivity/Vpn.java @@ -28,6 +28,7 @@ import static android.net.VpnManager.NOTIFICATION_CHANNEL_VPN; import static android.os.PowerWhitelistManager.REASON_VPN; import static android.os.UserHandle.PER_USER_RANGE; +import static com.android.net.module.util.NetworkStackConstants.IPV6_MIN_MTU; import static com.android.server.vcn.util.PersistableBundleUtils.STRING_DESERIALIZER; import static java.util.Objects.requireNonNull; @@ -84,6 +85,7 @@ import android.net.VpnManager; import android.net.VpnProfileState; import android.net.VpnService; import android.net.VpnTransportInfo; +import android.net.ipsec.ike.ChildSaProposal; import android.net.ipsec.ike.ChildSessionCallback; import android.net.ipsec.ike.ChildSessionConfiguration; import android.net.ipsec.ike.ChildSessionParams; @@ -93,6 +95,7 @@ import android.net.ipsec.ike.IkeSessionConfiguration; import android.net.ipsec.ike.IkeSessionConnectionInfo; import android.net.ipsec.ike.IkeSessionParams; import android.net.ipsec.ike.IkeTunnelConnectionParams; +import android.net.ipsec.ike.exceptions.IkeIOException; import android.net.ipsec.ike.exceptions.IkeNetworkLostException; import android.net.ipsec.ike.exceptions.IkeNonProtocolException; import android.net.ipsec.ike.exceptions.IkeProtocolException; @@ -142,6 +145,7 @@ import com.android.net.module.util.NetworkStackConstants; import com.android.server.DeviceIdleInternal; import com.android.server.LocalServices; import com.android.server.net.BaseNetworkObserver; +import com.android.server.vcn.util.MtuUtils; import com.android.server.vcn.util.PersistableBundleUtils; import libcore.io.IoUtils; @@ -154,6 +158,8 @@ import java.io.OutputStream; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.SocketException; import java.net.UnknownHostException; import java.nio.charset.StandardCharsets; import java.security.GeneralSecurityException; @@ -167,6 +173,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; +import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; @@ -557,6 +564,24 @@ public class Vpn { return DATA_STALL_RESET_DELAYS_SEC[count]; } } + + /** Gets the MTU of an interface using Java NetworkInterface primitives */ + public int getJavaNetworkInterfaceMtu(@Nullable String iface, int defaultValue) + throws SocketException { + if (iface == null) return defaultValue; + + final NetworkInterface networkInterface = NetworkInterface.getByName(iface); + return networkInterface == null ? defaultValue : networkInterface.getMTU(); + } + + /** Calculates the VPN Network's max MTU based on underlying network and configuration */ + public int calculateVpnMtu( + @NonNull List<ChildSaProposal> childProposals, + int maxMtu, + int underlyingMtu, + boolean isIpv4) { + return MtuUtils.getMtu(childProposals, maxMtu, underlyingMtu, isIpv4); + } } @VisibleForTesting @@ -1408,6 +1433,11 @@ public class Vpn { } private LinkProperties makeLinkProperties() { + // The design of disabling IPv6 is only enabled for IKEv2 VPN because it needs additional + // logic to handle IPv6 only VPN, and the IPv6 only VPN may be restarted when its MTU + // is lower than 1280. The logic is controlled by IKEv2VpnRunner, so the design is only + // enabled for IKEv2 VPN. + final boolean disableIPV6 = (isIkev2VpnRunner() && mConfig.mtu < IPV6_MIN_MTU); boolean allowIPv4 = mConfig.allowIPv4; boolean allowIPv6 = mConfig.allowIPv6; @@ -1417,6 +1447,7 @@ public class Vpn { if (mConfig.addresses != null) { for (LinkAddress address : mConfig.addresses) { + if (disableIPV6 && address.isIpv6()) continue; lp.addLinkAddress(address); allowIPv4 |= address.getAddress() instanceof Inet4Address; allowIPv6 |= address.getAddress() instanceof Inet6Address; @@ -1425,8 +1456,9 @@ public class Vpn { if (mConfig.routes != null) { for (RouteInfo route : mConfig.routes) { + final InetAddress address = route.getDestination().getAddress(); + if (disableIPV6 && address instanceof Inet6Address) continue; lp.addRoute(route); - InetAddress address = route.getDestination().getAddress(); if (route.getType() == RouteInfo.RTN_UNICAST) { allowIPv4 |= address instanceof Inet4Address; @@ -1437,7 +1469,8 @@ public class Vpn { if (mConfig.dnsServers != null) { for (String dnsServer : mConfig.dnsServers) { - InetAddress address = InetAddresses.parseNumericAddress(dnsServer); + final InetAddress address = InetAddresses.parseNumericAddress(dnsServer); + if (disableIPV6 && address instanceof Inet6Address) continue; lp.addDnsServer(address); allowIPv4 |= address instanceof Inet4Address; allowIPv6 |= address instanceof Inet6Address; @@ -1451,7 +1484,7 @@ public class Vpn { NetworkStackConstants.IPV4_ADDR_ANY, 0), null /*gateway*/, null /*iface*/, RTN_UNREACHABLE)); } - if (!allowIPv6) { + if (!allowIPv6 || disableIPV6) { lp.addRoute(new RouteInfo(new IpPrefix( NetworkStackConstants.IPV6_ADDR_ANY, 0), null /*gateway*/, null /*iface*/, RTN_UNREACHABLE)); @@ -1594,6 +1627,18 @@ public class Vpn { updateState(DetailedState.DISCONNECTED, "agentDisconnect"); } + @GuardedBy("this") + private void startNewNetworkAgent(NetworkAgent oldNetworkAgent, String reason) { + // Initialize the state for a new agent, while keeping the old one connected + // in case this new connection fails. + mNetworkAgent = null; + updateState(DetailedState.CONNECTING, reason); + // Bringing up a new NetworkAgent to prevent the data leakage before tearing down the old + // NetworkAgent. + agentConnect(); + agentDisconnect(oldNetworkAgent); + } + /** * Establish a VPN network and return the file descriptor of the VPN interface. This methods * returns {@code null} if the application is revoked or not prepared. @@ -1683,16 +1728,7 @@ public class Vpn { setUnderlyingNetworks(config.underlyingNetworks); } } else { - // Initialize the state for a new agent, while keeping the old one connected - // in case this new connection fails. - mNetworkAgent = null; - updateState(DetailedState.CONNECTING, "establish"); - // Set up forwarding and DNS rules. - agentConnect(); - // Remove the old tun's user forwarding rules - // The new tun's user rules have already been added above so they will take over - // as rules are deleted. This prevents data leakage as the rules are moved over. - agentDisconnect(oldNetworkAgent); + startNewNetworkAgent(oldNetworkAgent, "establish"); } if (oldConnection != null) { @@ -2729,6 +2765,17 @@ public class Vpn { void onSessionLost(int token, @Nullable Exception exception); } + private static boolean isIPv6Only(List<LinkAddress> linkAddresses) { + boolean hasIPV6 = false; + boolean hasIPV4 = false; + for (final LinkAddress address : linkAddresses) { + hasIPV6 |= address.isIpv6(); + hasIPV4 |= address.isIpv4(); + } + + return hasIPV6 && !hasIPV4; + } + /** * Internal class managing IKEv2/IPsec VPN connectivity * @@ -2899,7 +2946,6 @@ public class Vpn { ikeConfiguration.isIkeExtensionEnabled( IkeSessionConfiguration.EXTENSION_TYPE_MOBIKE); onIkeConnectionInfoChanged(token, ikeConfiguration.getIkeSessionConnectionInfo()); - mRetryCount = 0; } /** @@ -2942,15 +2988,27 @@ public class Vpn { try { final String interfaceName = mTunnelIface.getInterfaceName(); - final int maxMtu = mProfile.getMaxMtu(); final List<LinkAddress> internalAddresses = childConfig.getInternalAddresses(); final List<String> dnsAddrStrings = new ArrayList<>(); + int vpnMtu; + vpnMtu = calculateVpnMtu(); + + // If the VPN is IPv6 only and its MTU is lower than 1280, mark the network as lost + // and send the VpnManager event to the VPN app. + if (isIPv6Only(internalAddresses) && vpnMtu < IPV6_MIN_MTU) { + onSessionLost( + token, + new IkeIOException( + new IOException("No valid addresses for MTU < 1280"))); + return; + } final Collection<RouteInfo> newRoutes = VpnIkev2Utils.getRoutesFromTrafficSelectors( childConfig.getOutboundTrafficSelectors()); for (final LinkAddress address : internalAddresses) { mTunnelIface.addAddress(address.getAddress(), address.getPrefixLength()); } + for (InetAddress addr : childConfig.getInternalDnsServers()) { dnsAddrStrings.add(addr.getHostAddress()); } @@ -2968,7 +3026,7 @@ public class Vpn { if (mVpnRunner != this) return; mInterface = interfaceName; - mConfig.mtu = maxMtu; + mConfig.mtu = vpnMtu; mConfig.interfaze = mInterface; mConfig.addresses.clear(); @@ -3007,6 +3065,7 @@ public class Vpn { } doSendLinkProperties(networkAgent, lp); + mRetryCount = 0; } catch (Exception e) { Log.d(TAG, "Error in ChildOpened for token " + token, e); onSessionLost(token, e); @@ -3071,12 +3130,54 @@ public class Vpn { // Ignore stale runner. if (mVpnRunner != this) return; + final LinkProperties oldLp = makeLinkProperties(); + + final boolean underlyingNetworkHasChanged = + !Arrays.equals(mConfig.underlyingNetworks, new Network[]{network}); mConfig.underlyingNetworks = new Network[] {network}; - mNetworkCapabilities = - new NetworkCapabilities.Builder(mNetworkCapabilities) - .setUnderlyingNetworks(Collections.singletonList(network)) - .build(); - doSetUnderlyingNetworks(mNetworkAgent, Collections.singletonList(network)); + mConfig.mtu = calculateVpnMtu(); + + final LinkProperties newLp = makeLinkProperties(); + + // If MTU is < 1280, IPv6 addresses will be removed. If there are no addresses + // left (e.g. IPv6-only VPN network), mark VPN as having lost the session. + if (newLp.getLinkAddresses().isEmpty()) { + onSessionLost( + token, + new IkeIOException( + new IOException("No valid addresses for MTU < 1280"))); + return; + } + + final Set<LinkAddress> removedAddrs = new HashSet<>(oldLp.getLinkAddresses()); + removedAddrs.removeAll(newLp.getLinkAddresses()); + + // If addresses were removed despite no IKE config change, IPv6 addresses must + // have been removed due to MTU size. Restart the VPN to ensure all IPv6 + // unconnected sockets on the new VPN network are closed and retried on the new + // VPN network. + if (!removedAddrs.isEmpty()) { + startNewNetworkAgent( + mNetworkAgent, "MTU too low for IPv6; restarting network agent"); + + for (LinkAddress removed : removedAddrs) { + mTunnelIface.removeAddress( + removed.getAddress(), removed.getPrefixLength()); + } + } else { + // Put below 3 updates into else block is because agentConnect() will do + // those things, so there is no need to do the redundant work. + if (!newLp.equals(oldLp)) doSendLinkProperties(mNetworkAgent, newLp); + if (underlyingNetworkHasChanged) { + mNetworkCapabilities = + new NetworkCapabilities.Builder(mNetworkCapabilities) + .setUnderlyingNetworks( + Collections.singletonList(network)) + .build(); + doSetUnderlyingNetworks(mNetworkAgent, + Collections.singletonList(network)); + } + } } mTunnelIface.setUnderlyingNetwork(network); @@ -3126,6 +3227,60 @@ public class Vpn { startOrMigrateIkeSession(network); } + @NonNull + private IkeSessionParams getIkeSessionParams(@NonNull Network underlyingNetwork) { + final IkeTunnelConnectionParams ikeTunConnParams = + mProfile.getIkeTunnelConnectionParams(); + if (ikeTunConnParams != null) { + final IkeSessionParams.Builder builder = + new IkeSessionParams.Builder(ikeTunConnParams.getIkeSessionParams()) + .setNetwork(underlyingNetwork); + return builder.build(); + } else { + return VpnIkev2Utils.buildIkeSessionParams(mContext, mProfile, underlyingNetwork); + } + } + + @NonNull + private ChildSessionParams getChildSessionParams() { + final IkeTunnelConnectionParams ikeTunConnParams = + mProfile.getIkeTunnelConnectionParams(); + if (ikeTunConnParams != null) { + return ikeTunConnParams.getTunnelModeChildSessionParams(); + } else { + return VpnIkev2Utils.buildChildSessionParams(mProfile.getAllowedAlgorithms()); + } + } + + private int calculateVpnMtu() { + final Network underlyingNetwork = mIkeConnectionInfo.getNetwork(); + final LinkProperties lp = mConnectivityManager.getLinkProperties(underlyingNetwork); + if (underlyingNetwork == null || lp == null) { + // Return the max MTU defined in VpnProfile as the fallback option when there is no + // underlying network or LinkProperties is null. + return mProfile.getMaxMtu(); + } + + int underlyingMtu = lp.getMtu(); + + // Try to get MTU from kernel if MTU is not set in LinkProperties. + if (underlyingMtu == 0) { + try { + underlyingMtu = mDeps.getJavaNetworkInterfaceMtu(lp.getInterfaceName(), + mProfile.getMaxMtu()); + } catch (SocketException e) { + Log.d(TAG, "Got a SocketException when getting MTU from kernel: " + e); + return mProfile.getMaxMtu(); + } + } + + return mDeps.calculateVpnMtu( + getChildSessionParams().getSaProposals(), + mProfile.getMaxMtu(), + underlyingMtu, + mIkeConnectionInfo.getLocalAddress() instanceof Inet4Address); + } + /** * Start a new IKE session. * @@ -3176,24 +3331,6 @@ public class Vpn { // (non-default) network, and start the new one. resetIkeState(); - // Get Ike options from IkeTunnelConnectionParams if it's available in the - // profile. - final IkeTunnelConnectionParams ikeTunConnParams = - mProfile.getIkeTunnelConnectionParams(); - final IkeSessionParams ikeSessionParams; - final ChildSessionParams childSessionParams; - if (ikeTunConnParams != null) { - final IkeSessionParams.Builder builder = new IkeSessionParams.Builder( - ikeTunConnParams.getIkeSessionParams()).setNetwork(underlyingNetwork); - ikeSessionParams = builder.build(); - childSessionParams = ikeTunConnParams.getTunnelModeChildSessionParams(); - } else { - ikeSessionParams = VpnIkev2Utils.buildIkeSessionParams( - mContext, mProfile, underlyingNetwork); - childSessionParams = VpnIkev2Utils.buildChildSessionParams( - mProfile.getAllowedAlgorithms()); - } - // TODO: Remove the need for adding two unused addresses with // IPsec tunnels. final InetAddress address = InetAddress.getLocalHost(); @@ -3211,8 +3348,8 @@ public class Vpn { mSession = mIkev2SessionCreator.createIkeSession( mContext, - ikeSessionParams, - childSessionParams, + getIkeSessionParams(underlyingNetwork), + getChildSessionParams(), mExecutor, new VpnIkev2Utils.IkeSessionCallbackImpl( TAG, IkeV2VpnRunner.this, token), @@ -3226,6 +3363,10 @@ public class Vpn { } private void scheduleRetryNewIkeSession() { + if (mScheduledHandleRetryIkeSessionFuture != null) { + Log.d(TAG, "There is a pending retrying task, skip the new retrying task"); + return; + } final long retryDelay = mDeps.getNextRetryDelaySeconds(mRetryCount++); Log.d(TAG, "Retry new IKE session after " + retryDelay + " seconds."); // If the default network is lost during the retry delay, the mActiveNetwork will be diff --git a/services/core/java/com/android/server/cpu/OWNERS b/services/core/java/com/android/server/cpu/OWNERS new file mode 100644 index 000000000000..2f42363ee7e4 --- /dev/null +++ b/services/core/java/com/android/server/cpu/OWNERS @@ -0,0 +1,4 @@ +# Bug component: 608533 + +include platform/packages/services/Car:/OWNERS +lakshmana@google.com diff --git a/services/core/java/com/android/server/hdmi/HdmiUtils.java b/services/core/java/com/android/server/hdmi/HdmiUtils.java index ba19cf062cdf..308a0c801076 100644 --- a/services/core/java/com/android/server/hdmi/HdmiUtils.java +++ b/services/core/java/com/android/server/hdmi/HdmiUtils.java @@ -20,6 +20,8 @@ import static com.android.server.hdmi.Constants.ADDR_BACKUP_1; import static com.android.server.hdmi.Constants.ADDR_BACKUP_2; import static com.android.server.hdmi.Constants.ADDR_TV; +import static java.util.Map.entry; + import android.annotation.Nullable; import android.hardware.hdmi.HdmiControlManager; import android.hardware.hdmi.HdmiDeviceInfo; @@ -45,7 +47,6 @@ import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; @@ -57,38 +58,34 @@ final class HdmiUtils { private static final String TAG = "HdmiUtils"; - private static final Map<Integer, List<Integer>> ADDRESS_TO_TYPE = - new HashMap<Integer, List<Integer>>() { - { - put(Constants.ADDR_TV, Lists.newArrayList(HdmiDeviceInfo.DEVICE_TV)); - put(Constants.ADDR_RECORDER_1, - Lists.newArrayList(HdmiDeviceInfo.DEVICE_RECORDER)); - put(Constants.ADDR_RECORDER_2, - Lists.newArrayList(HdmiDeviceInfo.DEVICE_RECORDER)); - put(Constants.ADDR_TUNER_1, Lists.newArrayList(HdmiDeviceInfo.DEVICE_TUNER)); - put(Constants.ADDR_PLAYBACK_1, - Lists.newArrayList(HdmiDeviceInfo.DEVICE_PLAYBACK)); - put(Constants.ADDR_AUDIO_SYSTEM, - Lists.newArrayList(HdmiDeviceInfo.DEVICE_AUDIO_SYSTEM)); - put(Constants.ADDR_TUNER_2, Lists.newArrayList(HdmiDeviceInfo.DEVICE_TUNER)); - put(Constants.ADDR_TUNER_3, Lists.newArrayList(HdmiDeviceInfo.DEVICE_TUNER)); - put(Constants.ADDR_PLAYBACK_2, - Lists.newArrayList(HdmiDeviceInfo.DEVICE_PLAYBACK)); - put(Constants.ADDR_RECORDER_3, - Lists.newArrayList(HdmiDeviceInfo.DEVICE_RECORDER)); - put(Constants.ADDR_TUNER_4, Lists.newArrayList(HdmiDeviceInfo.DEVICE_TUNER)); - put(Constants.ADDR_PLAYBACK_3, - Lists.newArrayList(HdmiDeviceInfo.DEVICE_PLAYBACK)); - put(Constants.ADDR_BACKUP_1, Lists.newArrayList(HdmiDeviceInfo.DEVICE_PLAYBACK, - HdmiDeviceInfo.DEVICE_RECORDER, HdmiDeviceInfo.DEVICE_TUNER, - HdmiDeviceInfo.DEVICE_VIDEO_PROCESSOR)); - put(Constants.ADDR_BACKUP_2, Lists.newArrayList(HdmiDeviceInfo.DEVICE_PLAYBACK, - HdmiDeviceInfo.DEVICE_RECORDER, HdmiDeviceInfo.DEVICE_TUNER, - HdmiDeviceInfo.DEVICE_VIDEO_PROCESSOR)); - put(Constants.ADDR_SPECIFIC_USE, Lists.newArrayList(ADDR_TV)); - put(Constants.ADDR_UNREGISTERED, Collections.emptyList()); - } - }; + private static final Map<Integer, List<Integer>> ADDRESS_TO_TYPE = Map.ofEntries( + entry(Constants.ADDR_TV, Lists.newArrayList(HdmiDeviceInfo.DEVICE_TV)), + entry(Constants.ADDR_RECORDER_1, + Lists.newArrayList(HdmiDeviceInfo.DEVICE_RECORDER)), + entry(Constants.ADDR_RECORDER_2, + Lists.newArrayList(HdmiDeviceInfo.DEVICE_RECORDER)), + entry(Constants.ADDR_TUNER_1, Lists.newArrayList(HdmiDeviceInfo.DEVICE_TUNER)), + entry(Constants.ADDR_PLAYBACK_1, + Lists.newArrayList(HdmiDeviceInfo.DEVICE_PLAYBACK)), + entry(Constants.ADDR_AUDIO_SYSTEM, + Lists.newArrayList(HdmiDeviceInfo.DEVICE_AUDIO_SYSTEM)), + entry(Constants.ADDR_TUNER_2, Lists.newArrayList(HdmiDeviceInfo.DEVICE_TUNER)), + entry(Constants.ADDR_TUNER_3, Lists.newArrayList(HdmiDeviceInfo.DEVICE_TUNER)), + entry(Constants.ADDR_PLAYBACK_2, + Lists.newArrayList(HdmiDeviceInfo.DEVICE_PLAYBACK)), + entry(Constants.ADDR_RECORDER_3, + Lists.newArrayList(HdmiDeviceInfo.DEVICE_RECORDER)), + entry(Constants.ADDR_TUNER_4, Lists.newArrayList(HdmiDeviceInfo.DEVICE_TUNER)), + entry(Constants.ADDR_PLAYBACK_3, + Lists.newArrayList(HdmiDeviceInfo.DEVICE_PLAYBACK)), + entry(Constants.ADDR_BACKUP_1, Lists.newArrayList(HdmiDeviceInfo.DEVICE_PLAYBACK, + HdmiDeviceInfo.DEVICE_RECORDER, HdmiDeviceInfo.DEVICE_TUNER, + HdmiDeviceInfo.DEVICE_VIDEO_PROCESSOR)), + entry(Constants.ADDR_BACKUP_2, Lists.newArrayList(HdmiDeviceInfo.DEVICE_PLAYBACK, + HdmiDeviceInfo.DEVICE_RECORDER, HdmiDeviceInfo.DEVICE_TUNER, + HdmiDeviceInfo.DEVICE_VIDEO_PROCESSOR)), + entry(Constants.ADDR_SPECIFIC_USE, Lists.newArrayList(ADDR_TV)), + entry(Constants.ADDR_UNREGISTERED, Collections.emptyList())); private static final String[] DEFAULT_NAMES = { "TV", diff --git a/services/core/java/com/android/server/input/InputManagerService.java b/services/core/java/com/android/server/input/InputManagerService.java index 72612a0468cd..a9d747cc61e4 100644 --- a/services/core/java/com/android/server/input/InputManagerService.java +++ b/services/core/java/com/android/server/input/InputManagerService.java @@ -1799,8 +1799,8 @@ public class InputManagerService extends IInputManager.Stub */ public boolean transferTouchFocus(@NonNull IBinder fromChannelToken, @NonNull IBinder toChannelToken) { - Objects.nonNull(fromChannelToken); - Objects.nonNull(toChannelToken); + Objects.requireNonNull(fromChannelToken); + Objects.requireNonNull(toChannelToken); return mNative.transferTouchFocus(fromChannelToken, toChannelToken, false /* isDragDrop */); } diff --git a/services/core/java/com/android/server/location/contexthub/ContextHubTransactionManager.java b/services/core/java/com/android/server/location/contexthub/ContextHubTransactionManager.java index c199bb30a6d3..2d3f176f5d4d 100644 --- a/services/core/java/com/android/server/location/contexthub/ContextHubTransactionManager.java +++ b/services/core/java/com/android/server/location/contexthub/ContextHubTransactionManager.java @@ -519,9 +519,9 @@ import java.util.concurrent.atomic.AtomicInteger; @Override public String toString() { StringBuilder sb = new StringBuilder(100); - TransactionRecord[] arr; + ContextHubServiceTransaction[] arr; synchronized (this) { - arr = mTransactionQueue.toArray(new TransactionRecord[0]); + arr = mTransactionQueue.toArray(new ContextHubServiceTransaction[0]); } for (int i = 0; i < arr.length; i++) { sb.append(i + ": " + arr[i] + "\n"); diff --git a/services/core/java/com/android/server/location/gnss/GnssConfiguration.java b/services/core/java/com/android/server/location/gnss/GnssConfiguration.java index 12f8776a8e18..25350d0f128e 100644 --- a/services/core/java/com/android/server/location/gnss/GnssConfiguration.java +++ b/services/core/java/com/android/server/location/gnss/GnssConfiguration.java @@ -260,26 +260,24 @@ public class GnssConfiguration { Log.e(TAG, "Unable to set " + CONFIG_ES_EXTENSION_SEC + ": " + mEsExtensionSec); } - Map<String, SetCarrierProperty> map = new HashMap<String, SetCarrierProperty>() { - { - put(CONFIG_SUPL_VER, GnssConfiguration::native_set_supl_version); - put(CONFIG_SUPL_MODE, GnssConfiguration::native_set_supl_mode); + Map<String, SetCarrierProperty> map = new HashMap<String, SetCarrierProperty>(); - if (isConfigSuplEsSupported(gnssConfigurationIfaceVersion)) { - put(CONFIG_SUPL_ES, GnssConfiguration::native_set_supl_es); - } + map.put(CONFIG_SUPL_VER, GnssConfiguration::native_set_supl_version); + map.put(CONFIG_SUPL_MODE, GnssConfiguration::native_set_supl_mode); - put(CONFIG_LPP_PROFILE, GnssConfiguration::native_set_lpp_profile); - put(CONFIG_A_GLONASS_POS_PROTOCOL_SELECT, - GnssConfiguration::native_set_gnss_pos_protocol_select); - put(CONFIG_USE_EMERGENCY_PDN_FOR_EMERGENCY_SUPL, - GnssConfiguration::native_set_emergency_supl_pdn); + if (isConfigSuplEsSupported(gnssConfigurationIfaceVersion)) { + map.put(CONFIG_SUPL_ES, GnssConfiguration::native_set_supl_es); + } - if (isConfigGpsLockSupported(gnssConfigurationIfaceVersion)) { - put(CONFIG_GPS_LOCK, GnssConfiguration::native_set_gps_lock); - } - } - }; + map.put(CONFIG_LPP_PROFILE, GnssConfiguration::native_set_lpp_profile); + map.put(CONFIG_A_GLONASS_POS_PROTOCOL_SELECT, + GnssConfiguration::native_set_gnss_pos_protocol_select); + map.put(CONFIG_USE_EMERGENCY_PDN_FOR_EMERGENCY_SUPL, + GnssConfiguration::native_set_emergency_supl_pdn); + + if (isConfigGpsLockSupported(gnssConfigurationIfaceVersion)) { + map.put(CONFIG_GPS_LOCK, GnssConfiguration::native_set_gps_lock); + } for (Entry<String, SetCarrierProperty> entry : map.entrySet()) { String propertyName = entry.getKey(); diff --git a/services/core/java/com/android/server/notification/NotificationManagerService.java b/services/core/java/com/android/server/notification/NotificationManagerService.java index 018a2fc734b8..2cc0073679c7 100755 --- a/services/core/java/com/android/server/notification/NotificationManagerService.java +++ b/services/core/java/com/android/server/notification/NotificationManagerService.java @@ -4927,7 +4927,16 @@ public class NotificationManagerService extends SystemService { } enforcePolicyAccess(Binder.getCallingUid(), "addAutomaticZenRule"); - return mZenModeHelper.addAutomaticZenRule(pkg, automaticZenRule, + // If the caller is system, take the package name from the rule's owner rather than + // from the caller's package. + String rulePkg = pkg; + if (isCallingUidSystem()) { + if (automaticZenRule.getOwner() != null) { + rulePkg = automaticZenRule.getOwner().getPackageName(); + } + } + + return mZenModeHelper.addAutomaticZenRule(rulePkg, automaticZenRule, "addAutomaticZenRule"); } @@ -7850,7 +7859,8 @@ public class NotificationManagerService extends SystemService { && (record.getSuppressedVisualEffects() & SUPPRESSED_EFFECT_STATUS_BAR) != 0; if (!record.isUpdate && record.getImportance() > IMPORTANCE_MIN - && !suppressedByDnd) { + && !suppressedByDnd + && isNotificationForCurrentUser(record)) { sendAccessibilityEvent(record); sentAccessibilityEvent = true; } diff --git a/services/core/java/com/android/server/notification/PreferencesHelper.java b/services/core/java/com/android/server/notification/PreferencesHelper.java index 477b8da61e0f..634ee7e57f50 100644 --- a/services/core/java/com/android/server/notification/PreferencesHelper.java +++ b/services/core/java/com/android/server/notification/PreferencesHelper.java @@ -852,7 +852,9 @@ public class PreferencesHelper implements RankingConfig { Objects.requireNonNull(pkg); Objects.requireNonNull(group); Objects.requireNonNull(group.getId()); - Objects.requireNonNull(!TextUtils.isEmpty(group.getName())); + if (TextUtils.isEmpty(group.getName())) { + throw new IllegalArgumentException("group.getName() can't be empty"); + } boolean needsDndChange = false; synchronized (mPackagePreferences) { PackagePreferences r = getOrCreatePackagePreferencesLocked(pkg, uid); diff --git a/services/core/java/com/android/server/notification/ZenModeHelper.java b/services/core/java/com/android/server/notification/ZenModeHelper.java index 2b00ad7c5cd7..85c47a02bb90 100644 --- a/services/core/java/com/android/server/notification/ZenModeHelper.java +++ b/services/core/java/com/android/server/notification/ZenModeHelper.java @@ -314,7 +314,7 @@ public class ZenModeHelper { public String addAutomaticZenRule(String pkg, AutomaticZenRule automaticZenRule, String reason) { - if (!isSystemRule(automaticZenRule)) { + if (!ZenModeConfig.SYSTEM_AUTHORITY.equals(pkg)) { PackageItemInfo component = getServiceInfo(automaticZenRule.getOwner()); if (component == null) { component = getActivityInfo(automaticZenRule.getConfigurationActivity()); @@ -570,11 +570,6 @@ public class ZenModeHelper { } } - private boolean isSystemRule(AutomaticZenRule rule) { - return rule.getOwner() != null - && ZenModeConfig.SYSTEM_AUTHORITY.equals(rule.getOwner().getPackageName()); - } - private ServiceInfo getServiceInfo(ComponentName owner) { Intent queryIntent = new Intent(); queryIntent.setComponent(owner); diff --git a/services/core/java/com/android/server/om/OverlayManagerService.java b/services/core/java/com/android/server/om/OverlayManagerService.java index 5544669e1252..362b26ec762a 100644 --- a/services/core/java/com/android/server/om/OverlayManagerService.java +++ b/services/core/java/com/android/server/om/OverlayManagerService.java @@ -56,6 +56,7 @@ import android.content.pm.overlay.OverlayPaths; import android.content.res.ApkAssets; import android.net.Uri; import android.os.Binder; +import android.os.Build; import android.os.Environment; import android.os.FabricatedOverlayInternal; import android.os.HandlerThread; @@ -876,7 +877,7 @@ public final class OverlayManagerService extends SystemService { } Slog.d(TAG, "commit failed: " + e.getMessage(), e); throw new SecurityException("commit failed" - + (DEBUG ? ": " + e.getMessage() : "")); + + (DEBUG || Build.IS_DEBUGGABLE ? ": " + e.getMessage() : "")); } } finally { traceEnd(TRACE_TAG_RRO); diff --git a/services/core/java/com/android/server/pm/BackgroundDexOptService.java b/services/core/java/com/android/server/pm/BackgroundDexOptService.java index 5a01ccbb7d6f..e41188049876 100644 --- a/services/core/java/com/android/server/pm/BackgroundDexOptService.java +++ b/services/core/java/com/android/server/pm/BackgroundDexOptService.java @@ -149,8 +149,6 @@ public final class BackgroundDexOptService { @GuardedBy("mLock") @Status private int mLastExecutionStatus = STATUS_OK; - @GuardedBy("mLock") private long mLastExecutionStartTimeMs; - @GuardedBy("mLock") private long mLastExecutionDurationIncludingSleepMs; @GuardedBy("mLock") private long mLastExecutionStartUptimeMs; @GuardedBy("mLock") private long mLastExecutionDurationMs; @@ -229,10 +227,6 @@ public final class BackgroundDexOptService { writer.println(mFinishedPostBootUpdate); writer.print("mLastExecutionStatus:"); writer.println(mLastExecutionStatus); - writer.print("mLastExecutionStartTimeMs:"); - writer.println(mLastExecutionStartTimeMs); - writer.print("mLastExecutionDurationIncludingSleepMs:"); - writer.println(mLastExecutionDurationIncludingSleepMs); writer.print("mLastExecutionStartUptimeMs:"); writer.println(mLastExecutionStartUptimeMs); writer.print("mLastExecutionDurationMs:"); @@ -539,8 +533,6 @@ public final class BackgroundDexOptService { private boolean runIdleOptimization( PackageManagerService pm, List<String> pkgs, boolean isPostBootUpdate) { synchronized (mLock) { - mLastExecutionStartTimeMs = SystemClock.elapsedRealtime(); - mLastExecutionDurationIncludingSleepMs = -1; mLastExecutionStartUptimeMs = SystemClock.uptimeMillis(); mLastExecutionDurationMs = -1; } @@ -549,8 +541,6 @@ public final class BackgroundDexOptService { logStatus(status); synchronized (mLock) { mLastExecutionStatus = status; - mLastExecutionDurationIncludingSleepMs = - SystemClock.elapsedRealtime() - mLastExecutionStartTimeMs; mLastExecutionDurationMs = SystemClock.uptimeMillis() - mLastExecutionStartUptimeMs; } @@ -954,10 +944,9 @@ public final class BackgroundDexOptService { synchronized (mLock) { status = mLastExecutionStatus; durationMs = mLastExecutionDurationMs; - durationIncludingSleepMs = mLastExecutionDurationIncludingSleepMs; } - mStatsLogger.write(status, params.getStopReason(), durationMs, durationIncludingSleepMs); + mStatsLogger.write(status, params.getStopReason(), durationMs); } /** Injector pattern for testing purpose */ diff --git a/services/core/java/com/android/server/pm/PackageManagerShellCommand.java b/services/core/java/com/android/server/pm/PackageManagerShellCommand.java index 46691a61930e..1e64701ebab7 100644 --- a/services/core/java/com/android/server/pm/PackageManagerShellCommand.java +++ b/services/core/java/com/android/server/pm/PackageManagerShellCommand.java @@ -3630,7 +3630,7 @@ class PackageManagerShellCommand extends ShellCommand { fd = ParcelFileDescriptor.dup(getInFileDescriptor()); } if (sizeBytes <= 0) { - getErrPrintWriter().println("Error: must specify a APK size"); + getErrPrintWriter().println("Error: must specify an APK size"); return 1; } diff --git a/services/core/java/com/android/server/pm/PerPackageReadTimeouts.java b/services/core/java/com/android/server/pm/PerPackageReadTimeouts.java index 3b306a850b64..b310c62aafb4 100644 --- a/services/core/java/com/android/server/pm/PerPackageReadTimeouts.java +++ b/services/core/java/com/android/server/pm/PerPackageReadTimeouts.java @@ -16,7 +16,7 @@ package com.android.server.pm; -import android.annotation.NonNull;; +import android.annotation.NonNull; import android.text.TextUtils; import com.android.internal.util.HexDump; diff --git a/services/core/java/com/android/server/pm/StorageEventHelper.java b/services/core/java/com/android/server/pm/StorageEventHelper.java index 666776b4161e..ad87b03e9ed3 100644 --- a/services/core/java/com/android/server/pm/StorageEventHelper.java +++ b/services/core/java/com/android/server/pm/StorageEventHelper.java @@ -197,8 +197,11 @@ public final class StorageEventHelper extends StorageEventListener { appDataHelper.reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); } - } catch (IllegalStateException e) { - // Device was probably ejected, and we'll process that event momentarily + } catch (RuntimeException e) { + // The volume was probably already unmounted. We'll probably process the unmount + // event momentarily. TODO(b/256909937): ignoring errors from prepareUserStorage() + // is very dangerous. Instead, we should fix the race condition that allows this + // code to run on an unmounted volume in the first place. Slog.w(TAG, "Failed to prepare storage: " + e); } } diff --git a/services/core/java/com/android/server/pm/UserRestrictionsUtils.java b/services/core/java/com/android/server/pm/UserRestrictionsUtils.java index 016c1cb7bdf0..fe797d211a8c 100644 --- a/services/core/java/com/android/server/pm/UserRestrictionsUtils.java +++ b/services/core/java/com/android/server/pm/UserRestrictionsUtils.java @@ -147,7 +147,8 @@ public class UserRestrictionsUtils { UserManager.DISALLOW_WIFI_TETHERING, UserManager.DISALLOW_SHARING_ADMIN_CONFIGURED_WIFI, UserManager.DISALLOW_WIFI_DIRECT, - UserManager.DISALLOW_ADD_WIFI_CONFIG + UserManager.DISALLOW_ADD_WIFI_CONFIG, + UserManager.DISALLOW_CELLULAR_2G }); public static final Set<String> DEPRECATED_USER_RESTRICTIONS = Sets.newArraySet( @@ -195,7 +196,8 @@ public class UserRestrictionsUtils { UserManager.DISALLOW_CHANGE_WIFI_STATE, UserManager.DISALLOW_WIFI_TETHERING, UserManager.DISALLOW_WIFI_DIRECT, - UserManager.DISALLOW_ADD_WIFI_CONFIG + UserManager.DISALLOW_ADD_WIFI_CONFIG, + UserManager.DISALLOW_CELLULAR_2G ); /** @@ -234,7 +236,8 @@ public class UserRestrictionsUtils { UserManager.DISALLOW_CHANGE_WIFI_STATE, UserManager.DISALLOW_WIFI_TETHERING, UserManager.DISALLOW_WIFI_DIRECT, - UserManager.DISALLOW_ADD_WIFI_CONFIG + UserManager.DISALLOW_ADD_WIFI_CONFIG, + UserManager.DISALLOW_CELLULAR_2G ); /** diff --git a/services/core/java/com/android/server/pm/dex/ArtStatsLogUtils.java b/services/core/java/com/android/server/pm/dex/ArtStatsLogUtils.java index 905bcf969eaf..14075301d523 100644 --- a/services/core/java/com/android/server/pm/dex/ArtStatsLogUtils.java +++ b/services/core/java/com/android/server/pm/dex/ArtStatsLogUtils.java @@ -320,12 +320,15 @@ public class ArtStatsLogUtils { public static class BackgroundDexoptJobStatsLogger { /** Writes background dexopt job stats to statsd. */ public void write(@BackgroundDexOptService.Status int status, - @JobParameters.StopReason int cancellationReason, long durationMs, - long durationIncludingSleepMs) { - ArtStatsLog.write(ArtStatsLog.BACKGROUND_DEXOPT_JOB_ENDED, + @JobParameters.StopReason int cancellationReason, + long durationMs) { + ArtStatsLog.write( + ArtStatsLog.BACKGROUND_DEXOPT_JOB_ENDED, STATUS_MAP.getOrDefault(status, ArtStatsLog.BACKGROUND_DEXOPT_JOB_ENDED__STATUS__STATUS_UNKNOWN), - cancellationReason, durationMs, durationIncludingSleepMs); + cancellationReason, + durationMs, + 0); // deprecated, used to be durationIncludingSleepMs } } } diff --git a/services/core/java/com/android/server/pm/dex/DexoptUtils.java b/services/core/java/com/android/server/pm/dex/DexoptUtils.java index beea86d1b0df..d519c529a512 100644 --- a/services/core/java/com/android/server/pm/dex/DexoptUtils.java +++ b/services/core/java/com/android/server/pm/dex/DexoptUtils.java @@ -295,6 +295,7 @@ public final class DexoptUtils { * NOTE: Keep this in sync with the dexopt expectations! Right now that is either "PCL[path]" * for a PathClassLoader or "DLC[path]" for a DelegateLastClassLoader. */ + @SuppressWarnings("ReturnValueIgnored") /*package*/ static String encodeClassLoader(String classpath, String classLoaderName) { classpath.getClass(); // Throw NPE if classpath is null String classLoaderDexoptEncoding = classLoaderName; diff --git a/services/core/java/com/android/server/pm/dex/OdsignStatsLogger.java b/services/core/java/com/android/server/pm/dex/OdsignStatsLogger.java index fa08addc9b69..227a3a1d4317 100644 --- a/services/core/java/com/android/server/pm/dex/OdsignStatsLogger.java +++ b/services/core/java/com/android/server/pm/dex/OdsignStatsLogger.java @@ -39,6 +39,7 @@ public class OdsignStatsLogger { // These need to be kept in sync with system/security/ondevice-signing/StatsReporter.{h, cpp}. private static final String METRICS_FILE = "/data/misc/odsign/metrics/odsign-metrics.txt"; private static final String COMPOS_METRIC_NAME = "comp_os_artifacts_check_record"; + private static final String ODSIGN_METRIC_NAME = "odsign_record"; /** * Arrange for stats to be uploaded in the background. @@ -64,18 +65,45 @@ public class OdsignStatsLogger { for (String line : lines.split("\n")) { String[] metrics = line.split(" "); - if (metrics.length != 4 || !metrics[0].equals(COMPOS_METRIC_NAME)) { - Slog.w(TAG, "Malformed metrics file"); - break; + if (line.isEmpty() || metrics.length < 1) { + Slog.w(TAG, "Empty metrics line"); + continue; } - boolean currentArtifactsOk = metrics[1].equals("1"); - boolean compOsPendingArtifactsExists = metrics[2].equals("1"); - boolean useCompOsGeneratedArtifacts = metrics[3].equals("1"); + switch (metrics[0]) { + case COMPOS_METRIC_NAME: { + if (metrics.length != 4) { + Slog.w(TAG, "Malformed CompOS metrics line '" + line + "'"); + continue; + } - ArtStatsLog.write(ArtStatsLog.EARLY_BOOT_COMP_OS_ARTIFACTS_CHECK_REPORTED, - currentArtifactsOk, compOsPendingArtifactsExists, - useCompOsGeneratedArtifacts); + boolean currentArtifactsOk = metrics[1].equals("1"); + boolean compOsPendingArtifactsExists = metrics[2].equals("1"); + boolean useCompOsGeneratedArtifacts = metrics[3].equals("1"); + + ArtStatsLog.write(ArtStatsLog.EARLY_BOOT_COMP_OS_ARTIFACTS_CHECK_REPORTED, + currentArtifactsOk, compOsPendingArtifactsExists, + useCompOsGeneratedArtifacts); + break; + } + case ODSIGN_METRIC_NAME: { + if (metrics.length != 2) { + Slog.w(TAG, "Malformed odsign metrics line '" + line + "'"); + continue; + } + + try { + int status = Integer.parseInt(metrics[1]); + ArtStatsLog.write(ArtStatsLog.ODSIGN_REPORTED, status); + } catch (NumberFormatException e) { + Slog.w(TAG, "Malformed odsign metrics line '" + line + "'"); + } + + break; + } + default: + Slog.w(TAG, "Malformed metrics line '" + line + "'"); + } } } catch (FileNotFoundException e) { // This is normal and probably means no new metrics have been generated. diff --git a/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java b/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java index 073776f14e68..98bbcb94701a 100644 --- a/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java +++ b/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java @@ -86,6 +86,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; /** @@ -1924,7 +1925,7 @@ final class DefaultPermissionGrantPolicy { mPkgRequestingPerm, newRestrictionExcemptFlags, -1, mUser); } - if (newGranted != null && newGranted != mOriginalGranted) { + if (newGranted != null && !Objects.equals(newGranted, mOriginalGranted)) { if (newGranted) { NO_PM_CACHE.grantPermission(mPermission, mPkgRequestingPerm, mUser); } else { diff --git a/services/core/java/com/android/server/pm/permission/PermissionManagerServiceImpl.java b/services/core/java/com/android/server/pm/permission/PermissionManagerServiceImpl.java index d34682df3413..1e13333c1ce0 100644 --- a/services/core/java/com/android/server/pm/permission/PermissionManagerServiceImpl.java +++ b/services/core/java/com/android/server/pm/permission/PermissionManagerServiceImpl.java @@ -2664,7 +2664,6 @@ public class PermissionManagerServiceImpl implements PermissionManagerServiceInt final Permission bp = mRegistry.getPermission(permName); final boolean appSupportsRuntimePermissions = pkg.getTargetSdkVersion() >= Build.VERSION_CODES.M; - String legacyActivityRecognitionPermission = null; if (DEBUG_INSTALL && bp != null) { Log.i(TAG, "Package " + friendlyName @@ -2688,47 +2687,12 @@ public class PermissionManagerServiceImpl implements PermissionManagerServiceInt // Cache newImplicitPermissions before modifing permissionsState as for the // shared uids the original and new state are the same object if (!origState.hasPermissionState(permName) - && (pkg.getImplicitPermissions().contains(permName) - || (permName.equals(Manifest.permission.ACTIVITY_RECOGNITION)))) { - if (pkg.getImplicitPermissions().contains(permName)) { + && (pkg.getImplicitPermissions().contains(permName))) { // If permName is an implicit permission, try to auto-grant newImplicitPermissions.add(permName); - if (DEBUG_PERMISSIONS) { Slog.i(TAG, permName + " is newly added for " + friendlyName); } - } else { - // Special case for Activity Recognition permission. Even if AR - // permission is not an implicit permission we want to add it to the - // list (try to auto-grant it) if the app was installed on a device - // before AR permission was split, regardless of if the app now requests - // the new AR permission or has updated its target SDK and AR is no - // longer implicit to it. This is a compatibility workaround for apps - // when AR permission was split in Q. - // TODO(zhanghai): This calls into SystemConfig, which generally - // shouldn't cause deadlock, but maybe we should keep a cache of the - // split permission list and just eliminate the possibility. - final List<PermissionManager.SplitPermissionInfo> permissionList = - getSplitPermissionInfos(); - int numSplitPerms = permissionList.size(); - for (int splitPermNum = 0; splitPermNum < numSplitPerms; - splitPermNum++) { - PermissionManager.SplitPermissionInfo sp = permissionList.get( - splitPermNum); - String splitPermName = sp.getSplitPermission(); - if (sp.getNewPermissions().contains(permName) - && origState.isPermissionGranted(splitPermName)) { - legacyActivityRecognitionPermission = splitPermName; - newImplicitPermissions.add(permName); - - if (DEBUG_PERMISSIONS) { - Slog.i(TAG, permName + " is newly added for " - + friendlyName); - } - break; - } - } - } } // TODO(b/140256621): The package instant app method has been removed @@ -2862,8 +2826,7 @@ public class PermissionManagerServiceImpl implements PermissionManagerServiceInt // Hard restricted permissions cannot be held. } else if (!permissionPolicyInitialized || (!hardRestricted || restrictionExempt)) { - if ((origPermState != null && origPermState.isGranted()) - || legacyActivityRecognitionPermission != null) { + if ((origPermState != null && origPermState.isGranted())) { if (!uidState.grantPermission(bp)) { wasChanged = true; } diff --git a/services/core/java/com/android/server/policy/PhoneWindowManager.java b/services/core/java/com/android/server/policy/PhoneWindowManager.java index 3af6e18547ad..2cf6608b7629 100644 --- a/services/core/java/com/android/server/policy/PhoneWindowManager.java +++ b/services/core/java/com/android/server/policy/PhoneWindowManager.java @@ -3474,7 +3474,12 @@ public class PhoneWindowManager implements WindowManagerPolicy { @Override public void onKeyguardExitResult(boolean success) { if (success) { - startDockOrHome(displayId, true /*fromHomeKey*/, awakenFromDreams); + final long origId = Binder.clearCallingIdentity(); + try { + startDockOrHome(displayId, true /*fromHomeKey*/, awakenFromDreams); + } finally { + Binder.restoreCallingIdentity(origId); + } } } }); diff --git a/services/core/java/com/android/server/rollback/README.md b/services/core/java/com/android/server/rollback/README.md index 0c5cc156f86d..08800dada564 100644 --- a/services/core/java/com/android/server/rollback/README.md +++ b/services/core/java/com/android/server/rollback/README.md @@ -1,4 +1,4 @@ -#Rollback Manager +# Rollback Manager ## Introduction @@ -7,9 +7,9 @@ updatability efforts. RollbackManager adds support for rolling back an APK or APEX update to the previous version installed on the device, and reverting any APK or APEX data to the state it was in at the time of install. -##Rollback Basics +## Rollback Basics -###How Rollbacks Work +### How Rollbacks Work A new install parameter ENABLE_ROLLBACK can be specified to enable rollback when updating an application. For example: @@ -42,27 +42,27 @@ data taken when FooV2.apk was first installed. See below for more details of shell commands for rollback. -###Rollback Triggers +### Rollback Triggers -####Manually Triggered Rollback +#### Manually Triggered Rollback As mentioned above, it is possible to trigger rollback on device using a shell command. This is for testing purposes only. We do not expect this mechanism to be used in production in practice. -####Watchdog Triggered Rollback +#### Watchdog Triggered Rollback Watchdog triggered rollback is intended to address severe issues with the device. The platform provides several different watchdogs that can trigger rollback. -#####Package Watchdog +##### Package Watchdog There is a package watchdog service running on device that will trigger rollback of an update if there are 5 ANRs or process crashes within a 1 minute window for a package in the update. -#####Native Watchdog +##### Native Watchdog If a native service crashes repeatedly after an update is installed, rollback will be triggered. This particularly applies to updates that include APEXes @@ -70,25 +70,25 @@ that may update native services, but note that as it is difficult to tell which native services have been affected by an update, *any* crashing native service will cause the rollback to be triggered. -#####Explicit Health Check +##### Explicit Health Check There is an explicit check to verify the network stack is functional after an update. If there is no network connectivity within a certain time period after an update, rollback is triggered. -####Server Triggered Rollback +#### Server Triggered Rollback The RollbackManager API may be used by the installer to roll back an update based on a request from the server. -##Rollback Details +## Rollback Details -###RollbackManager API +### RollbackManager API The RollbackManager API is an @SystemAPI guarded by the MANAGE_ROLLBACKS and TEST_MANAGE_ROLLBACKS permissions. See RollbackManager.java for details about the RollbackManager API. -###Rollback of APEX modules +### Rollback of APEX modules Rollback is supported for APEX modules in addition to APK modules. In Q, there was no concept of data associated with an APEX, so only the APEX itself is @@ -100,7 +100,7 @@ terms of any state they persist on the system (outside of the APEX data directories). For example, FooV2.apex must not change the file format of some state stored on the device in such a way that FooV1.apex cannot read the file. -###Rollback of MultiPackage Installs +### Rollback of MultiPackage Installs Rollback can be enabled for multi-package installs. This requires that all packages in the install session, including the parent session, have the @@ -119,7 +119,7 @@ If there is a problem enabling rollback for any package in the multi-package install session, rollback will not be enabled for any package in the multi-package install session. -###Rollback of Staged Installs +### Rollback of Staged Installs Rollback can be enabled for staged installs, which require reboot to take effect. If reboot was required when the package was updated, then reboot is @@ -127,21 +127,21 @@ required when the package is rolled back. If no reboot was required when the package was updated, then no reboot is required when the package is rolled back. -###Rollbacks on Multi User Devices +### Rollbacks on Multi User Devices Rollbacks should work properly on devices with multiple users. There is special handling of user data backup to ensure app user data is properly backed up and restored for all users, even for credential encrypted users that have not been unlocked at various points during the flow. -###Rollback whitelist +### Rollback whitelist Outside of testing, rollback may only be enabled for packages listed in the sysconfig rollback whitelist - see `SystemConfig#getRollbackWhitelistedPackages`. Attempts to enable rollback for non-whitelisted packages will fail. -###Failure to Enable Rollback +### Failure to Enable Rollback There are a number of reasons why we may be unable to enable rollback for a package, including: @@ -158,13 +158,13 @@ If we are unable to enable rollback, the installation will proceed without rollback enabled. Failing to enable rollback does not cause the installation to fail. -###Failure to Commit Rollback +### Failure to Commit Rollback For the most part, a rollback will remain available after failure to commit it. This allows the caller to retry the rollback if they have reason to believe it will not fail again the next time the commit of the rollback is attempted. -###Installing Previously Rolled Back Packages +### Installing Previously Rolled Back Packages There is no logic in the platform itself to prevent installing a version of a package that was previously rolled back. @@ -175,7 +175,7 @@ package versions believed to be the main source of the bad update. The list of installer to prevent reinstall of a previously rolled back package version if so desired. -###Rollback Expiration +### Rollback Expiration An available rollback is expired if the rollback lifetime has been exceeded or if there is a new update to package associated with the rollback. When an @@ -183,9 +183,9 @@ available rollback is expired, the backed up apk and userdata associated with the rollback are deleted. Once a rollback is expired, it can no longer be executed. -##Shell Commands for Rollback +## Shell Commands for Rollback -###Installing an App with Rollback Enabled +### Installing an App with Rollback Enabled The `adb install` command accepts the `--enable-rollback` flag to install an app with rollback enabled. For example: @@ -194,7 +194,7 @@ with rollback enabled. For example: $ adb install --enable-rollback FooV2.apk ``` -###Triggering Rollback Manually +### Triggering Rollback Manually If rollback is available for an application, the pm command can be used to trigger rollback manually on device: @@ -206,7 +206,7 @@ $ adb shell pm rollback-app com.example.foo For rollback of staged installs, you have to manually reboot the device for the rollback to take effect after running the 'pm rollback-app' command. -###Listing the Status of Rollbacks on Device +### Listing the Status of Rollbacks on Device You can get a list with details about available and recently committed rollbacks using dumpsys. For example: @@ -246,9 +246,9 @@ committed. The list of rollbacks is also included in bug reports. Search for "DUMP OF SERVICE rollback". -##Configuration Properties +## Configuration Properties -###Rollback Lifetime +### Rollback Lifetime Rollback lifetime refers to the maximum duration of time after the rollback is first enabled that it will be available. The default is for rollbacks to be @@ -263,7 +263,7 @@ $ adb shell device_config put rollback_boot rollback_lifetime_in_millis 17280000 The update will not take effect until after system server has been restarted. -###Enable Rollback Timeout +### Enable Rollback Timeout The enable rollback timeout is how long RollbackManager is allowed to take to enable rollback when performing an update. This includes the time needed to make @@ -279,7 +279,7 @@ $ adb shell device_config put rollback enable_rollback_timeout 10000 The update will take effect for the next install with rollback enabled. -##Limitations +## Limitations * You cannot enable rollback for the first version of an application installed on the device. Only updates to a package previously installed on the device can diff --git a/services/core/java/com/android/server/wallpaper/WallpaperManagerService.java b/services/core/java/com/android/server/wallpaper/WallpaperManagerService.java index e197319707e3..eb8464e8d671 100644 --- a/services/core/java/com/android/server/wallpaper/WallpaperManagerService.java +++ b/services/core/java/com/android/server/wallpaper/WallpaperManagerService.java @@ -1888,12 +1888,9 @@ public class WallpaperManagerService extends IWallpaperManager.Stub } } - private static final HashMap<Integer, String> sWallpaperType = new HashMap<Integer, String>() { - { - put(FLAG_SYSTEM, RECORD_FILE); - put(FLAG_LOCK, RECORD_LOCK_FILE); - } - }; + private static final Map<Integer, String> sWallpaperType = Map.of( + FLAG_SYSTEM, RECORD_FILE, + FLAG_LOCK, RECORD_LOCK_FILE); private void errorCheck(int userID) { sWallpaperType.forEach((type, filename) -> { diff --git a/services/core/java/com/android/server/wm/ActivityTaskManagerService.java b/services/core/java/com/android/server/wm/ActivityTaskManagerService.java index 8d831d72c05b..91dcc8e412dc 100644 --- a/services/core/java/com/android/server/wm/ActivityTaskManagerService.java +++ b/services/core/java/com/android/server/wm/ActivityTaskManagerService.java @@ -1441,7 +1441,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { a.colorMode = ActivityInfo.COLOR_MODE_DEFAULT; a.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; a.resizeMode = RESIZE_MODE_UNRESIZEABLE; - a.configChanges = ActivityInfo.CONFIG_ORIENTATION; + a.configChanges = 0xffffffff; final ActivityOptions options = ActivityOptions.makeBasic(); options.setLaunchActivityType(ACTIVITY_TYPE_DREAM); diff --git a/services/core/java/com/android/server/wm/DisplayWindowSettings.java b/services/core/java/com/android/server/wm/DisplayWindowSettings.java index 11bcd8ca3681..a9d0e96e484f 100644 --- a/services/core/java/com/android/server/wm/DisplayWindowSettings.java +++ b/services/core/java/com/android/server/wm/DisplayWindowSettings.java @@ -436,11 +436,12 @@ class DisplayWindowSettings { mRemoveContentMode = other.mRemoveContentMode; changed = true; } - if (other.mShouldShowWithInsecureKeyguard != mShouldShowWithInsecureKeyguard) { + if (!Objects.equals( + other.mShouldShowWithInsecureKeyguard, mShouldShowWithInsecureKeyguard)) { mShouldShowWithInsecureKeyguard = other.mShouldShowWithInsecureKeyguard; changed = true; } - if (other.mShouldShowSystemDecors != mShouldShowSystemDecors) { + if (!Objects.equals(other.mShouldShowSystemDecors, mShouldShowSystemDecors)) { mShouldShowSystemDecors = other.mShouldShowSystemDecors; changed = true; } @@ -452,15 +453,15 @@ class DisplayWindowSettings { mFixedToUserRotation = other.mFixedToUserRotation; changed = true; } - if (other.mIgnoreOrientationRequest != mIgnoreOrientationRequest) { + if (!Objects.equals(other.mIgnoreOrientationRequest, mIgnoreOrientationRequest)) { mIgnoreOrientationRequest = other.mIgnoreOrientationRequest; changed = true; } - if (other.mIgnoreDisplayCutout != mIgnoreDisplayCutout) { + if (!Objects.equals(other.mIgnoreDisplayCutout, mIgnoreDisplayCutout)) { mIgnoreDisplayCutout = other.mIgnoreDisplayCutout; changed = true; } - if (other.mDontMoveToTop != mDontMoveToTop) { + if (!Objects.equals(other.mDontMoveToTop, mDontMoveToTop)) { mDontMoveToTop = other.mDontMoveToTop; changed = true; } @@ -516,14 +517,13 @@ class DisplayWindowSettings { mRemoveContentMode = delta.mRemoveContentMode; changed = true; } - if (delta.mShouldShowWithInsecureKeyguard != null - && delta.mShouldShowWithInsecureKeyguard - != mShouldShowWithInsecureKeyguard) { + if (delta.mShouldShowWithInsecureKeyguard != null && !Objects.equals( + delta.mShouldShowWithInsecureKeyguard, mShouldShowWithInsecureKeyguard)) { mShouldShowWithInsecureKeyguard = delta.mShouldShowWithInsecureKeyguard; changed = true; } - if (delta.mShouldShowSystemDecors != null - && delta.mShouldShowSystemDecors != mShouldShowSystemDecors) { + if (delta.mShouldShowSystemDecors != null && !Objects.equals( + delta.mShouldShowSystemDecors, mShouldShowSystemDecors)) { mShouldShowSystemDecors = delta.mShouldShowSystemDecors; changed = true; } @@ -537,18 +537,18 @@ class DisplayWindowSettings { mFixedToUserRotation = delta.mFixedToUserRotation; changed = true; } - if (delta.mIgnoreOrientationRequest != null - && delta.mIgnoreOrientationRequest != mIgnoreOrientationRequest) { + if (delta.mIgnoreOrientationRequest != null && !Objects.equals( + delta.mIgnoreOrientationRequest, mIgnoreOrientationRequest)) { mIgnoreOrientationRequest = delta.mIgnoreOrientationRequest; changed = true; } - if (delta.mIgnoreDisplayCutout != null - && delta.mIgnoreDisplayCutout != mIgnoreDisplayCutout) { + if (delta.mIgnoreDisplayCutout != null && !Objects.equals( + delta.mIgnoreDisplayCutout, mIgnoreDisplayCutout)) { mIgnoreDisplayCutout = delta.mIgnoreDisplayCutout; changed = true; } - if (delta.mDontMoveToTop != null - && delta.mDontMoveToTop != mDontMoveToTop) { + if (delta.mDontMoveToTop != null && !Objects.equals( + delta.mDontMoveToTop, mDontMoveToTop)) { mDontMoveToTop = delta.mDontMoveToTop; changed = true; } diff --git a/services/core/java/com/android/server/wm/RunningTasks.java b/services/core/java/com/android/server/wm/RunningTasks.java index 1ec191ed7c05..e14bbbd78ded 100644 --- a/services/core/java/com/android/server/wm/RunningTasks.java +++ b/services/core/java/com/android/server/wm/RunningTasks.java @@ -20,16 +20,15 @@ import static android.app.WindowConfiguration.ACTIVITY_TYPE_HOME; import static android.app.WindowConfiguration.ACTIVITY_TYPE_RECENTS; import android.app.ActivityManager.RunningTaskInfo; +import android.os.SystemClock; import android.os.UserHandle; import android.util.ArraySet; import com.android.internal.util.function.pooled.PooledConsumer; import com.android.internal.util.function.pooled.PooledLambda; -import java.util.Comparator; -import java.util.Iterator; +import java.util.ArrayList; import java.util.List; -import java.util.TreeSet; /** * Class for resolving the set of running tasks in the system. @@ -41,15 +40,13 @@ class RunningTasks { static final int FLAG_CROSS_USERS = 1 << 2; static final int FLAG_KEEP_INTENT_EXTRA = 1 << 3; - // Comparator to sort by last active time (descending) - private static final Comparator<Task> LAST_ACTIVE_TIME_COMPARATOR = - (o1, o2) -> { - return o1.lastActiveTime == o2.lastActiveTime - ? Integer.signum(o2.mTaskId - o1.mTaskId) : - Long.signum(o2.lastActiveTime - o1.lastActiveTime); - }; - - private final TreeSet<Task> mTmpSortedSet = new TreeSet<>(LAST_ACTIVE_TIME_COMPARATOR); + // Tasks are sorted in order {focusedVisibleTasks, visibleTasks, invisibleTasks}. + private final ArrayList<Task> mTmpSortedTasks = new ArrayList<>(); + // mTmpVisibleTasks, mTmpInvisibleTasks and mTmpFocusedTasks are sorted from top + // to bottom. + private final ArrayList<Task> mTmpVisibleTasks = new ArrayList<>(); + private final ArrayList<Task> mTmpInvisibleTasks = new ArrayList<>(); + private final ArrayList<Task> mTmpFocusedTasks = new ArrayList<>(); private int mCallingUid; private int mUserId; @@ -67,8 +64,6 @@ class RunningTasks { return; } - // Gather all of the tasks across all of the tasks, and add them to the sorted set - mTmpSortedSet.clear(); mCallingUid = callingUid; mUserId = UserHandle.getUserId(callingUid); mCrossUser = (flags & FLAG_CROSS_USERS) == FLAG_CROSS_USERS; @@ -79,22 +74,67 @@ class RunningTasks { mRecentTasks = root.mService.getRecentTasks(); mKeepIntentExtra = (flags & FLAG_KEEP_INTENT_EXTRA) == FLAG_KEEP_INTENT_EXTRA; - final PooledConsumer c = PooledLambda.obtainConsumer(RunningTasks::processTask, this, - PooledLambda.__(Task.class)); - root.forAllLeafTasks(c, false); - c.recycle(); + if (root instanceof RootWindowContainer) { + ((RootWindowContainer) root).forAllDisplays(dc -> { + final Task focusedTask = dc.mFocusedApp != null ? dc.mFocusedApp.getTask() : null; + if (focusedTask != null) { + mTmpFocusedTasks.add(focusedTask); + } + processTaskInWindowContainer(dc); + }); + } else { + final DisplayContent dc = root.getDisplayContent(); + final Task focusedTask = dc != null + ? (dc.mFocusedApp != null ? dc.mFocusedApp.getTask() : null) + : null; + // May not be include focusedTask if root is DisplayArea. + final boolean rootContainsFocusedTask = focusedTask != null + && focusedTask.isDescendantOf(root); + if (rootContainsFocusedTask) { + mTmpFocusedTasks.add(focusedTask); + } + processTaskInWindowContainer(root); + } - // Take the first {@param maxNum} tasks and create running task infos for them - final Iterator<Task> iter = mTmpSortedSet.iterator(); - while (iter.hasNext()) { - if (maxNum == 0) { - break; + final int visibleTaskCount = mTmpVisibleTasks.size(); + for (int i = 0; i < mTmpFocusedTasks.size(); i++) { + final Task focusedTask = mTmpFocusedTasks.get(i); + final boolean containsFocusedTask = mTmpVisibleTasks.remove(focusedTask); + if (containsFocusedTask) { + // Put the visible focused task at the first position. + mTmpSortedTasks.add(focusedTask); } + } + if (!mTmpVisibleTasks.isEmpty()) { + mTmpSortedTasks.addAll(mTmpVisibleTasks); + } + if (!mTmpInvisibleTasks.isEmpty()) { + mTmpSortedTasks.addAll(mTmpInvisibleTasks); + } - final Task task = iter.next(); - list.add(createRunningTaskInfo(task)); - maxNum--; + // Take the first {@param maxNum} tasks and create running task infos for them + final int size = Math.min(maxNum, mTmpSortedTasks.size()); + final long now = SystemClock.elapsedRealtime(); + for (int i = 0; i < size; i++) { + final Task task = mTmpSortedTasks.get(i); + // Override the last active to current time for the visible tasks because the visible + // tasks can be considered to be currently active, the values are descending as + // the item order. + final long visibleActiveTime = i < visibleTaskCount ? now + size - i : -1; + list.add(createRunningTaskInfo(task, visibleActiveTime)); } + + mTmpFocusedTasks.clear(); + mTmpVisibleTasks.clear(); + mTmpInvisibleTasks.clear(); + mTmpSortedTasks.clear(); + } + + private void processTaskInWindowContainer(WindowContainer wc) { + final PooledConsumer c = PooledLambda.obtainConsumer(RunningTasks::processTask, this, + PooledLambda.__(Task.class)); + wc.forAllLeafTasks(c, true); + c.recycle(); } private void processTask(Task task) { @@ -121,25 +161,20 @@ class RunningTasks { // home & recent tasks return; } - if (task.isVisible()) { - // For the visible task, update the last active time so that it can be used to determine - // the order of the tasks (it may not be set for newly created tasks) - task.touchActiveTime(); - if (!task.isFocused()) { - // TreeSet doesn't allow the same value and make sure this task is lower than the - // focused one. - task.lastActiveTime -= mTmpSortedSet.size(); - } + mTmpVisibleTasks.add(task); + } else { + mTmpInvisibleTasks.add(task); } - - mTmpSortedSet.add(task); } /** Constructs a {@link RunningTaskInfo} from a given {@param task}. */ - private RunningTaskInfo createRunningTaskInfo(Task task) { + private RunningTaskInfo createRunningTaskInfo(Task task, long visibleActiveTime) { final RunningTaskInfo rti = new RunningTaskInfo(); task.fillTaskInfo(rti, !mKeepIntentExtra); + if (visibleActiveTime > 0) { + rti.lastActiveTime = visibleActiveTime; + } // Fill in some deprecated values rti.id = rti.taskId; return rti; diff --git a/services/core/java/com/android/server/wm/Task.java b/services/core/java/com/android/server/wm/Task.java index e1ee045a0a87..5d53c20270b5 100644 --- a/services/core/java/com/android/server/wm/Task.java +++ b/services/core/java/com/android/server/wm/Task.java @@ -5458,7 +5458,23 @@ class Task extends TaskFragment { parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK || parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP || (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) { - parent.deliverNewIntentLocked(callingUid, destIntent, destGrants, srec.packageName); + boolean abort; + try { + abort = !mTaskSupervisor.checkStartAnyActivityPermission(destIntent, + parent.info, null /* resultWho */, -1 /* requestCode */, srec.getPid(), + callingUid, srec.info.packageName, null /* callingFeatureId */, + false /* ignoreTargetSecurity */, false /* launchingInTask */, srec.app, + null /* resultRecord */, null /* resultRootTask */); + } catch (SecurityException e) { + abort = true; + } + if (abort) { + android.util.EventLog.writeEvent(0x534e4554, "238605611", callingUid, ""); + foundParentInTask = false; + } else { + parent.deliverNewIntentLocked(callingUid, destIntent, destGrants, + srec.packageName); + } } else { try { ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo( diff --git a/services/core/java/com/android/server/wm/WindowManagerThreadPriorityBooster.java b/services/core/java/com/android/server/wm/WindowManagerThreadPriorityBooster.java index 6f2930c46b12..1b70d1d4a8b6 100644 --- a/services/core/java/com/android/server/wm/WindowManagerThreadPriorityBooster.java +++ b/services/core/java/com/android/server/wm/WindowManagerThreadPriorityBooster.java @@ -21,7 +21,7 @@ import static android.os.Process.THREAD_PRIORITY_TOP_APP_BOOST; import static android.os.Process.myTid; import static android.os.Process.setThreadPriority; -import static com.android.server.LockGuard.INDEX_WINDOW;; +import static com.android.server.LockGuard.INDEX_WINDOW; import com.android.internal.annotations.GuardedBy; import com.android.server.AnimationThread; diff --git a/services/core/jni/com_android_server_am_BatteryStatsService.cpp b/services/core/jni/com_android_server_am_BatteryStatsService.cpp index 16eaa77e0822..3678cedeb87f 100644 --- a/services/core/jni/com_android_server_am_BatteryStatsService.cpp +++ b/services/core/jni/com_android_server_am_BatteryStatsService.cpp @@ -98,7 +98,7 @@ class WakeupCallback : public BnSuspendCallback { public: binder::Status notifyWakeup(bool success, const std::vector<std::string>& wakeupReasons) override { - ALOGI("In wakeup_callback: %s", success ? "resumed from suspend" : "suspend aborted"); + ALOGV("In wakeup_callback: %s", success ? "resumed from suspend" : "suspend aborted"); bool reasonsCaptured = false; { std::unique_lock<std::mutex> reasonsLock(mReasonsMutex, std::defer_lock); diff --git a/services/people/java/com/android/server/people/PeopleService.java b/services/people/java/com/android/server/people/PeopleService.java index eab3b770a94a..292320e498a3 100644 --- a/services/people/java/com/android/server/people/PeopleService.java +++ b/services/people/java/com/android/server/people/PeopleService.java @@ -53,6 +53,7 @@ import com.android.server.people.data.DataManager; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.function.Consumer; /** @@ -372,7 +373,8 @@ public class PeopleService extends SystemService { @Override public boolean equals(Object o) { ListenerKey key = (ListenerKey) o; - return key.getPackageName().equals(mPackageName) && key.getUserId() == mUserId + return key.getPackageName().equals(mPackageName) + && Objects.equals(key.getUserId(), mUserId) && key.getShortcutId().equals(mShortcutId); } diff --git a/services/tests/servicestests/src/com/android/server/camera/CameraServiceProxyTest.java b/services/tests/servicestests/src/com/android/server/camera/CameraServiceProxyTest.java index ea746d1f4fd3..faad961510d6 100644 --- a/services/tests/servicestests/src/com/android/server/camera/CameraServiceProxyTest.java +++ b/services/tests/servicestests/src/com/android/server/camera/CameraServiceProxyTest.java @@ -30,7 +30,7 @@ import android.hardware.camera2.CameraMetadata; import android.view.Display; import android.view.Surface; -import java.util.HashMap; +import java.util.Map; @RunWith(JUnit4.class) public class CameraServiceProxyTest { @@ -75,24 +75,22 @@ public class CameraServiceProxyTest { /*ignoreResizableAndSdkCheck*/true)).isEqualTo( CameraMetadata.SCALER_ROTATE_AND_CROP_NONE); // Check rotation and lens facing combinations - HashMap<Integer, Integer> backFacingMap = new HashMap<Integer, Integer>() {{ - put(Surface.ROTATION_0, CameraMetadata.SCALER_ROTATE_AND_CROP_NONE); - put(Surface.ROTATION_90, CameraMetadata.SCALER_ROTATE_AND_CROP_90); - put(Surface.ROTATION_270, CameraMetadata.SCALER_ROTATE_AND_CROP_270); - put(Surface.ROTATION_180, CameraMetadata.SCALER_ROTATE_AND_CROP_180); - }}; + Map<Integer, Integer> backFacingMap = Map.of( + Surface.ROTATION_0, CameraMetadata.SCALER_ROTATE_AND_CROP_NONE, + Surface.ROTATION_90, CameraMetadata.SCALER_ROTATE_AND_CROP_90, + Surface.ROTATION_270, CameraMetadata.SCALER_ROTATE_AND_CROP_270, + Surface.ROTATION_180, CameraMetadata.SCALER_ROTATE_AND_CROP_180); taskInfo.isFixedOrientationPortrait = true; backFacingMap.forEach((key, value) -> { assertThat(CameraServiceProxy.getCropRotateScale(ctx, ctx.getPackageName(), taskInfo, key, CameraCharacteristics.LENS_FACING_BACK, /*ignoreResizableAndSdkCheck*/true)).isEqualTo(value); }); - HashMap<Integer, Integer> frontFacingMap = new HashMap<Integer, Integer>() {{ - put(Surface.ROTATION_0, CameraMetadata.SCALER_ROTATE_AND_CROP_NONE); - put(Surface.ROTATION_90, CameraMetadata.SCALER_ROTATE_AND_CROP_270); - put(Surface.ROTATION_270, CameraMetadata.SCALER_ROTATE_AND_CROP_90); - put(Surface.ROTATION_180, CameraMetadata.SCALER_ROTATE_AND_CROP_180); - }}; + Map<Integer, Integer> frontFacingMap = Map.of( + Surface.ROTATION_0, CameraMetadata.SCALER_ROTATE_AND_CROP_NONE, + Surface.ROTATION_90, CameraMetadata.SCALER_ROTATE_AND_CROP_270, + Surface.ROTATION_270, CameraMetadata.SCALER_ROTATE_AND_CROP_90, + Surface.ROTATION_180, CameraMetadata.SCALER_ROTATE_AND_CROP_180); frontFacingMap.forEach((key, value) -> { assertThat(CameraServiceProxy.getCropRotateScale(ctx, ctx.getPackageName(), taskInfo, key, CameraCharacteristics.LENS_FACING_FRONT, diff --git a/services/tests/servicestests/src/com/android/server/display/AmbientBrightnessStatsTrackerTest.java b/services/tests/servicestests/src/com/android/server/display/AmbientBrightnessStatsTrackerTest.java index df672c9f248d..2c4fe536b75c 100644 --- a/services/tests/servicestests/src/com/android/server/display/AmbientBrightnessStatsTrackerTest.java +++ b/services/tests/servicestests/src/com/android/server/display/AmbientBrightnessStatsTrackerTest.java @@ -424,7 +424,7 @@ public class AmbientBrightnessStatsTrackerTest { @Override public LocalDate getLocalDate() { - return LocalDate.from(mLocalDate); + return mLocalDate; } } diff --git a/services/tests/servicestests/src/com/android/server/inputmethod/InputMethodSubtypeSwitchingControllerTest.java b/services/tests/servicestests/src/com/android/server/inputmethod/InputMethodSubtypeSwitchingControllerTest.java index 9092ec325946..0884b784ac73 100644 --- a/services/tests/servicestests/src/com/android/server/inputmethod/InputMethodSubtypeSwitchingControllerTest.java +++ b/services/tests/servicestests/src/com/android/server/inputmethod/InputMethodSubtypeSwitchingControllerTest.java @@ -367,6 +367,7 @@ public class InputMethodSubtypeSwitchingControllerTest { assertFalse(item_en_us_allcaps.mIsSystemLocale); } + @SuppressWarnings("SelfComparison") @Test public void testImeSubtypeListComparator() throws Exception { final ComponentName imeX1 = new ComponentName("com.example.imeX", "Ime1"); diff --git a/services/tests/servicestests/src/com/android/server/locksettings/PasswordSlotManagerTestable.java b/services/tests/servicestests/src/com/android/server/locksettings/PasswordSlotManagerTestable.java index 1e855a9819ac..1eb4fa5439e6 100644 --- a/services/tests/servicestests/src/com/android/server/locksettings/PasswordSlotManagerTestable.java +++ b/services/tests/servicestests/src/com/android/server/locksettings/PasswordSlotManagerTestable.java @@ -58,4 +58,4 @@ public class PasswordSlotManagerTestable extends PasswordSlotManager { } catch (Exception e) { } } -}; +} diff --git a/services/tests/uiservicestests/src/com/android/server/notification/BuzzBeepBlinkTest.java b/services/tests/uiservicestests/src/com/android/server/notification/BuzzBeepBlinkTest.java index 911fb6a87e96..08c2c6e6f26e 100644 --- a/services/tests/uiservicestests/src/com/android/server/notification/BuzzBeepBlinkTest.java +++ b/services/tests/uiservicestests/src/com/android/server/notification/BuzzBeepBlinkTest.java @@ -1301,6 +1301,21 @@ public class BuzzBeepBlinkTest extends UiServiceTestCase { } @Test + public void testA11yCrossUserEventNotSent() throws Exception { + final Notification n = new Builder(getContext(), "test") + .setSmallIcon(android.R.drawable.sym_def_app_icon).build(); + int userId = mUser.getIdentifier() + 1; + StatusBarNotification sbn = new StatusBarNotification(mPkg, mPkg, 0, mTag, mUid, + mPid, n, UserHandle.of(userId), null, System.currentTimeMillis()); + NotificationRecord r = new NotificationRecord(getContext(), sbn, + new NotificationChannel("test", "test", IMPORTANCE_HIGH)); + + mService.buzzBeepBlinkLocked(r); + + verify(mAccessibilityService, never()).sendAccessibilityEvent(any(), anyInt()); + } + + @Test public void testLightsScreenOn() { mService.mScreenOn = true; NotificationRecord r = getLightsNotification(); diff --git a/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java b/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java index 480ad110f357..535183dabd4a 100755 --- a/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java +++ b/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java @@ -7509,6 +7509,43 @@ public class NotificationManagerServiceTest extends UiServiceTestCase { } @Test + public void testAddAutomaticZenRule_systemCallTakesPackageFromOwner() throws Exception { + mService.isSystemUid = true; + ZenModeHelper mockZenModeHelper = mock(ZenModeHelper.class); + when(mConditionProviders.isPackageOrComponentAllowed(anyString(), anyInt())) + .thenReturn(true); + mService.setZenHelper(mockZenModeHelper); + ComponentName owner = new ComponentName("android", "ProviderName"); + ZenPolicy zenPolicy = new ZenPolicy.Builder().allowAlarms(true).build(); + boolean isEnabled = true; + AutomaticZenRule rule = new AutomaticZenRule("test", owner, owner, mock(Uri.class), + zenPolicy, NotificationManager.INTERRUPTION_FILTER_PRIORITY, isEnabled); + mBinderService.addAutomaticZenRule(rule, "com.android.settings"); + + // verify that zen mode helper gets passed in a package name of "android" + verify(mockZenModeHelper).addAutomaticZenRule(eq("android"), eq(rule), anyString()); + } + + @Test + public void testAddAutomaticZenRule_nonSystemCallTakesPackageFromArg() throws Exception { + mService.isSystemUid = false; + ZenModeHelper mockZenModeHelper = mock(ZenModeHelper.class); + when(mConditionProviders.isPackageOrComponentAllowed(anyString(), anyInt())) + .thenReturn(true); + mService.setZenHelper(mockZenModeHelper); + ComponentName owner = new ComponentName("android", "ProviderName"); + ZenPolicy zenPolicy = new ZenPolicy.Builder().allowAlarms(true).build(); + boolean isEnabled = true; + AutomaticZenRule rule = new AutomaticZenRule("test", owner, owner, mock(Uri.class), + zenPolicy, NotificationManager.INTERRUPTION_FILTER_PRIORITY, isEnabled); + mBinderService.addAutomaticZenRule(rule, "another.package"); + + // verify that zen mode helper gets passed in the package name from the arg, not the owner + verify(mockZenModeHelper).addAutomaticZenRule( + eq("another.package"), eq(rule), anyString()); + } + + @Test public void testAreNotificationsEnabledForPackage() throws Exception { mBinderService.areNotificationsEnabledForPackage(mContext.getPackageName(), mUid); diff --git a/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java b/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java index 598a22bbde39..d46530c27690 100644 --- a/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java +++ b/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java @@ -2727,7 +2727,7 @@ public class PreferencesHelperTest extends UiServiceTestCase { @Test public void testCreateChannel_addToGroup() { - NotificationChannelGroup group = new NotificationChannelGroup("group", ""); + NotificationChannelGroup group = new NotificationChannelGroup("group", "group"); mHelper.createNotificationChannelGroup(PKG_N_MR1, UID_N_MR1, group, true); NotificationChannel nc = new NotificationChannel("id", "hello", IMPORTANCE_DEFAULT); assertTrue(mHelper.createNotificationChannel(PKG_N_MR1, UID_N_MR1, nc, true, false)); @@ -3177,8 +3177,8 @@ public class PreferencesHelperTest extends UiServiceTestCase { @Test public void testGetNotificationChannelGroupWithChannels() throws Exception { - NotificationChannelGroup group = new NotificationChannelGroup("group", ""); - NotificationChannelGroup other = new NotificationChannelGroup("something else", ""); + NotificationChannelGroup group = new NotificationChannelGroup("group", "group"); + NotificationChannelGroup other = new NotificationChannelGroup("something else", "name"); mHelper.createNotificationChannelGroup(PKG_N_MR1, UID_N_MR1, group, true); mHelper.createNotificationChannelGroup(PKG_N_MR1, UID_N_MR1, other, true); diff --git a/services/tests/uiservicestests/src/com/android/server/notification/ZenModeHelperTest.java b/services/tests/uiservicestests/src/com/android/server/notification/ZenModeHelperTest.java index 4550b56f6fd0..2ccdcaace8bf 100644 --- a/services/tests/uiservicestests/src/com/android/server/notification/ZenModeHelperTest.java +++ b/services/tests/uiservicestests/src/com/android/server/notification/ZenModeHelperTest.java @@ -1672,6 +1672,36 @@ public class ZenModeHelperTest extends UiServiceTestCase { } @Test + public void testAddAutomaticZenRule_claimedSystemOwner() { + // Make sure anything that claims to have a "system" owner but not actually part of the + // system package still gets limited on number of rules + for (int i = 0; i < RULE_LIMIT_PER_PACKAGE; i++) { + ScheduleInfo si = new ScheduleInfo(); + si.startHour = i; + AutomaticZenRule zenRule = new AutomaticZenRule("name" + i, + new ComponentName("android", "ScheduleConditionProvider" + i), + null, // configuration activity + ZenModeConfig.toScheduleConditionId(si), + new ZenPolicy.Builder().build(), + NotificationManager.INTERRUPTION_FILTER_PRIORITY, true); + String id = mZenModeHelperSpy.addAutomaticZenRule("pkgname", zenRule, "test"); + assertNotNull(id); + } + try { + AutomaticZenRule zenRule = new AutomaticZenRule("name", + new ComponentName("android", "ScheduleConditionProviderFinal"), + null, // configuration activity + ZenModeConfig.toScheduleConditionId(new ScheduleInfo()), + new ZenPolicy.Builder().build(), + NotificationManager.INTERRUPTION_FILTER_PRIORITY, true); + String id = mZenModeHelperSpy.addAutomaticZenRule("pkgname", zenRule, "test"); + fail("allowed too many rules to be created"); + } catch (IllegalArgumentException e) { + // yay + } + } + + @Test public void testAddAutomaticZenRule_CA() { AutomaticZenRule zenRule = new AutomaticZenRule("name", null, diff --git a/services/tests/wmtests/src/com/android/server/wm/RunningTasksTest.java b/services/tests/wmtests/src/com/android/server/wm/RunningTasksTest.java index 33b236669ec7..13fc61cbf2fa 100644 --- a/services/tests/wmtests/src/com/android/server/wm/RunningTasksTest.java +++ b/services/tests/wmtests/src/com/android/server/wm/RunningTasksTest.java @@ -61,55 +61,6 @@ public class RunningTasksTest extends WindowTestsBase { } @Test - public void testCollectTasksByLastActiveTime() { - // Create a number of stacks with tasks (of incrementing active time) - final ArrayList<DisplayContent> displays = new ArrayList<>(); - final DisplayContent display = new TestDisplayContent.Builder(mAtm, 1000, 2500).build(); - displays.add(display); - - final int numStacks = 2; - for (int stackIndex = 0; stackIndex < numStacks; stackIndex++) { - final Task stack = new TaskBuilder(mSupervisor) - .setDisplay(display) - .setOnTop(false) - .build(); - } - - final int numTasks = 10; - int activeTime = 0; - final List<Task> rootTasks = new ArrayList<>(); - display.getDefaultTaskDisplayArea().forAllRootTasks(task -> { - rootTasks.add(task); - }, false /* traverseTopToBottom */); - for (int i = 0; i < numTasks; i++) { - final Task task = - createTask(rootTasks.get(i % numStacks), ".Task" + i, i, activeTime++, null); - doReturn(false).when(task).isVisible(); - } - - // Ensure that the latest tasks were returned in order of decreasing last active time, - // collected from all tasks across all the stacks - final int numFetchTasks = 5; - ArrayList<RunningTaskInfo> tasks = new ArrayList<>(); - mRunningTasks.getTasks(5, tasks, FLAG_ALLOWED | FLAG_CROSS_USERS, mRootWindowContainer, - -1 /* callingUid */, PROFILE_IDS); - assertThat(tasks).hasSize(numFetchTasks); - for (int i = 0; i < numFetchTasks; i++) { - assertEquals(numTasks - i - 1, tasks.get(i).id); - } - - // Ensure that requesting more than the total number of tasks only returns the subset - // and does not crash - tasks.clear(); - mRunningTasks.getTasks(100, tasks, FLAG_ALLOWED | FLAG_CROSS_USERS, - mRootWindowContainer, -1 /* callingUid */, PROFILE_IDS); - assertThat(tasks).hasSize(numTasks); - for (int i = 0; i < numTasks; i++) { - assertEquals(numTasks - i - 1, tasks.get(i).id); - } - } - - @Test public void testTaskInfo_expectNoExtrasByDefault() { final DisplayContent display = new TestDisplayContent.Builder(mAtm, 1000, 2500).build(); final int numTasks = 10; @@ -120,7 +71,7 @@ public class RunningTasksTest extends WindowTestsBase { .build(); final Bundle data = new Bundle(); data.putInt("key", 100); - createTask(stack, ".Task" + i, i, i, data); + createTask(stack, ".Task" + i, i, data); } final int numFetchTasks = 5; @@ -145,7 +96,7 @@ public class RunningTasksTest extends WindowTestsBase { .build(); final Bundle data = new Bundle(); data.putInt("key", 100); - createTask(stack, ".Task" + i, i, i, data); + createTask(stack, ".Task" + i, i, data); } final int numFetchTasks = 5; @@ -162,46 +113,63 @@ public class RunningTasksTest extends WindowTestsBase { } @Test - public void testUpdateLastActiveTimeOfVisibleTasks() { + public void testGetTasksSortByFocusAndVisibility() { final DisplayContent display = new TestDisplayContent.Builder(mAtm, 1000, 2500).build(); + final Task stack = new TaskBuilder(mSupervisor) + .setDisplay(display) + .setOnTop(true) + .build(); + final int numTasks = 10; final ArrayList<Task> tasks = new ArrayList<>(); for (int i = 0; i < numTasks; i++) { - final Task task = createTask(null, ".Task" + i, i, i, null); + final Task task = createTask(stack, ".Task" + i, i, null); doReturn(false).when(task).isVisible(); tasks.add(task); } - final Task visibleTask = tasks.get(0); - doReturn(true).when(visibleTask).isVisible(); - - final Task focusedTask = tasks.get(1); + final Task focusedTask = tasks.get(numTasks - 1); doReturn(true).when(focusedTask).isVisible(); - doReturn(true).when(focusedTask).isFocused(); + display.mFocusedApp = focusedTask.getTopNonFinishingActivity(); + + final Task visibleTaskTop = tasks.get(numTasks - 2); + doReturn(true).when(visibleTaskTop).isVisible(); - // Ensure that the last active time of visible tasks were updated while the focused one had - // the largest last active time. + final Task visibleTaskBottom = tasks.get(numTasks - 3); + doReturn(true).when(visibleTaskBottom).isVisible(); + + // Ensure that the focused Task is on top, visible tasks below, then invisible tasks. final int numFetchTasks = 5; final ArrayList<RunningTaskInfo> fetchTasks = new ArrayList<>(); mRunningTasks.getTasks(numFetchTasks, fetchTasks, FLAG_ALLOWED | FLAG_CROSS_USERS | FLAG_KEEP_INTENT_EXTRA, mRootWindowContainer, -1 /* callingUid */, PROFILE_IDS); assertThat(fetchTasks).hasSize(numFetchTasks); - assertEquals(fetchTasks.get(0).id, focusedTask.mTaskId); - assertEquals(fetchTasks.get(1).id, visibleTask.mTaskId); + for (int i = 0; i < numFetchTasks; i++) { + assertEquals(numTasks - i - 1, fetchTasks.get(i).id); + } + + // Ensure that requesting more than the total number of tasks only returns the subset + // and does not crash + fetchTasks.clear(); + mRunningTasks.getTasks(100, fetchTasks, + FLAG_ALLOWED | FLAG_CROSS_USERS | FLAG_KEEP_INTENT_EXTRA, mRootWindowContainer, + -1 /* callingUid */, PROFILE_IDS); + assertThat(fetchTasks).hasSize(numTasks); + for (int i = 0; i < numTasks; i++) { + assertEquals(numTasks - i - 1, fetchTasks.get(i).id); + } } /** - * Create a task with a single activity in it, with the given last active time. + * Create a task with a single activity in it. */ - private Task createTask(Task stack, String className, int taskId, - int lastActiveTime, Bundle extras) { + private Task createTask(Task stack, String className, int taskId, Bundle extras) { final Task task = new TaskBuilder(mAtm.mTaskSupervisor) .setComponent(new ComponentName(mContext.getPackageName(), className)) .setTaskId(taskId) .setParentTaskFragment(stack) .build(); - task.lastActiveTime = lastActiveTime; final ActivityRecord activity = new ActivityBuilder(mAtm) .setTask(task) .setComponent(new ComponentName(mContext.getPackageName(), ".TaskActivity")) diff --git a/services/usb/java/com/android/server/usb/descriptors/UsbVCInputTerminal.java b/services/usb/java/com/android/server/usb/descriptors/UsbVCInputTerminal.java index df637950899b..7a41b50e26bd 100644 --- a/services/usb/java/com/android/server/usb/descriptors/UsbVCInputTerminal.java +++ b/services/usb/java/com/android/server/usb/descriptors/UsbVCInputTerminal.java @@ -46,4 +46,4 @@ public final class UsbVCInputTerminal extends UsbVCInterface { // TODO Add reporting specific to this descriptor super.report(canvas); } -}; +} diff --git a/services/usb/java/com/android/server/usb/descriptors/UsbVCOutputTerminal.java b/services/usb/java/com/android/server/usb/descriptors/UsbVCOutputTerminal.java index 4aa8ca22cc4e..32275a60644c 100644 --- a/services/usb/java/com/android/server/usb/descriptors/UsbVCOutputTerminal.java +++ b/services/usb/java/com/android/server/usb/descriptors/UsbVCOutputTerminal.java @@ -46,4 +46,4 @@ public final class UsbVCOutputTerminal extends UsbVCInterface { super.report(canvas); // TODO Add reporting specific to this descriptor } -}; +} diff --git a/services/usb/java/com/android/server/usb/descriptors/UsbVCProcessingUnit.java b/services/usb/java/com/android/server/usb/descriptors/UsbVCProcessingUnit.java index 5ce842e82598..0692066e1dee 100644 --- a/services/usb/java/com/android/server/usb/descriptors/UsbVCProcessingUnit.java +++ b/services/usb/java/com/android/server/usb/descriptors/UsbVCProcessingUnit.java @@ -47,4 +47,4 @@ public final class UsbVCProcessingUnit extends UsbVCInterface { super.report(canvas); // TODO Add reporting specific to this descriptor } -}; +} diff --git a/services/usb/java/com/android/server/usb/descriptors/UsbVCSelectorUnit.java b/services/usb/java/com/android/server/usb/descriptors/UsbVCSelectorUnit.java index 8e9b0d886389..604dd66905da 100644 --- a/services/usb/java/com/android/server/usb/descriptors/UsbVCSelectorUnit.java +++ b/services/usb/java/com/android/server/usb/descriptors/UsbVCSelectorUnit.java @@ -47,4 +47,4 @@ public final class UsbVCSelectorUnit extends UsbVCInterface { super.report(canvas); // TODO Add reporting specific to this descriptor } -}; +} diff --git a/services/voiceinteraction/java/com/android/server/voiceinteraction/HotwordDetectionConnection.java b/services/voiceinteraction/java/com/android/server/voiceinteraction/HotwordDetectionConnection.java index 42d446d058b4..af626f57356e 100644 --- a/services/voiceinteraction/java/com/android/server/voiceinteraction/HotwordDetectionConnection.java +++ b/services/voiceinteraction/java/com/android/server/voiceinteraction/HotwordDetectionConnection.java @@ -1196,4 +1196,4 @@ final class HotwordDetectionConnection { private static final String OP_MESSAGE = "Providing hotword detection result to VoiceInteractionService"; -}; +} diff --git a/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionSessionConnection.java b/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionSessionConnection.java index a061618b1ca7..e02f2f00afa0 100644 --- a/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionSessionConnection.java +++ b/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionSessionConnection.java @@ -810,4 +810,4 @@ final class VoiceInteractionSessionConnection implements ServiceConnection, } } }; -}; +} diff --git a/telecomm/OWNERS b/telecomm/OWNERS index eb0c4327ec46..dcaf858a0a0b 100644 --- a/telecomm/OWNERS +++ b/telecomm/OWNERS @@ -4,3 +4,7 @@ breadley@google.com tgunn@google.com xiaotonj@google.com rgreenwalt@google.com +chinmayd@google.com +grantmenke@google.com +pmadapurmath@google.com +tjstuart@google.com
\ No newline at end of file diff --git a/telecomm/java/android/telecom/TelecomManager.java b/telecomm/java/android/telecom/TelecomManager.java index e0f5b2095190..983d82b4f860 100644 --- a/telecomm/java/android/telecom/TelecomManager.java +++ b/telecomm/java/android/telecom/TelecomManager.java @@ -1269,7 +1269,7 @@ public class TelecomManager { if (service != null) { try { return service.getPhoneAccountsSupportingScheme(uriScheme, - mContext.getOpPackageName()); + mContext.getOpPackageName()).getList(); } catch (RemoteException e) { Log.e(TAG, "Error calling ITelecomService#getPhoneAccountsSupportingScheme", e); } @@ -1312,7 +1312,7 @@ public class TelecomManager { if (service != null) { try { return service.getSelfManagedPhoneAccounts(mContext.getOpPackageName(), - mContext.getAttributionTag()); + mContext.getAttributionTag()).getList(); } catch (RemoteException e) { Log.e(TAG, "Error calling ITelecomService#getSelfManagedPhoneAccounts()", e); } @@ -1340,7 +1340,7 @@ public class TelecomManager { if (service != null) { try { return service.getOwnSelfManagedPhoneAccounts(mContext.getOpPackageName(), - mContext.getAttributionTag()); + mContext.getAttributionTag()).getList(); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } @@ -1366,7 +1366,7 @@ public class TelecomManager { if (service != null) { try { return service.getCallCapablePhoneAccounts(includeDisabledAccounts, - mContext.getOpPackageName(), mContext.getAttributionTag()); + mContext.getOpPackageName(), mContext.getAttributionTag()).getList(); } catch (RemoteException e) { Log.e(TAG, "Error calling ITelecomService#getCallCapablePhoneAccounts(" + includeDisabledAccounts + ")", e); @@ -1390,7 +1390,7 @@ public class TelecomManager { ITelecomService service = getTelecomService(); if (service != null) { try { - return service.getPhoneAccountsForPackage(mContext.getPackageName()); + return service.getPhoneAccountsForPackage(mContext.getPackageName()).getList(); } catch (RemoteException e) { Log.e(TAG, "Error calling ITelecomService#getPhoneAccountsForPackage", e); } @@ -1450,7 +1450,7 @@ public class TelecomManager { ITelecomService service = getTelecomService(); if (service != null) { try { - return service.getAllPhoneAccounts(); + return service.getAllPhoneAccounts().getList(); } catch (RemoteException e) { Log.e(TAG, "Error calling ITelecomService#getAllPhoneAccounts", e); } @@ -1469,7 +1469,7 @@ public class TelecomManager { ITelecomService service = getTelecomService(); if (service != null) { try { - return service.getAllPhoneAccountHandles(); + return service.getAllPhoneAccountHandles().getList(); } catch (RemoteException e) { Log.e(TAG, "Error calling ITelecomService#getAllPhoneAccountHandles", e); } diff --git a/telecomm/java/com/android/internal/telecom/ITelecomService.aidl b/telecomm/java/com/android/internal/telecom/ITelecomService.aidl index 37403a806daf..74b5545e75de 100644 --- a/telecomm/java/com/android/internal/telecom/ITelecomService.aidl +++ b/telecomm/java/com/android/internal/telecom/ITelecomService.aidl @@ -24,6 +24,7 @@ import android.net.Uri; import android.os.Bundle; import android.os.UserHandle; import android.telecom.PhoneAccount; +import android.content.pm.ParceledListSlice; /** * Interface used to interact with Telecom. Mostly this is used by TelephonyManager for passing @@ -57,31 +58,31 @@ interface ITelecomService { /** * @see TelecomServiceImpl#getCallCapablePhoneAccounts */ - List<PhoneAccountHandle> getCallCapablePhoneAccounts( + ParceledListSlice<PhoneAccountHandle> getCallCapablePhoneAccounts( boolean includeDisabledAccounts, String callingPackage, String callingFeatureId); /** * @see TelecomServiceImpl#getSelfManagedPhoneAccounts */ - List<PhoneAccountHandle> getSelfManagedPhoneAccounts(String callingPackage, + ParceledListSlice<PhoneAccountHandle> getSelfManagedPhoneAccounts(String callingPackage, String callingFeatureId); /** * @see TelecomServiceImpl#getOwnSelfManagedPhoneAccounts */ - List<PhoneAccountHandle> getOwnSelfManagedPhoneAccounts(String callingPackage, + ParceledListSlice<PhoneAccountHandle> getOwnSelfManagedPhoneAccounts(String callingPackage, String callingFeatureId); /** * @see TelecomManager#getPhoneAccountsSupportingScheme */ - List<PhoneAccountHandle> getPhoneAccountsSupportingScheme(in String uriScheme, + ParceledListSlice<PhoneAccountHandle> getPhoneAccountsSupportingScheme(in String uriScheme, String callingPackage); /** * @see TelecomManager#getPhoneAccountsForPackage */ - List<PhoneAccountHandle> getPhoneAccountsForPackage(in String packageName); + ParceledListSlice<PhoneAccountHandle> getPhoneAccountsForPackage(in String packageName); /** * @see TelecomManager#getPhoneAccount @@ -96,12 +97,12 @@ interface ITelecomService { /** * @see TelecomManager#getAllPhoneAccounts */ - List<PhoneAccount> getAllPhoneAccounts(); + ParceledListSlice<PhoneAccount> getAllPhoneAccounts(); /** * @see TelecomManager#getAllPhoneAccountHandles */ - List<PhoneAccountHandle> getAllPhoneAccountHandles(); + ParceledListSlice<PhoneAccountHandle> getAllPhoneAccountHandles(); /** * @see TelecomServiceImpl#getSimCallManager diff --git a/telephony/common/com/google/android/mms/pdu/EncodedStringValue.java b/telephony/common/com/google/android/mms/pdu/EncodedStringValue.java index 8b01cb3c4405..2787d83a99a3 100644 --- a/telephony/common/com/google/android/mms/pdu/EncodedStringValue.java +++ b/telephony/common/com/google/android/mms/pdu/EncodedStringValue.java @@ -199,7 +199,6 @@ public class EncodedStringValue implements Cloneable { */ @Override public Object clone() throws CloneNotSupportedException { - super.clone(); int len = mData.length; byte[] dstBytes = new byte[len]; System.arraycopy(mData, 0, dstBytes, 0, len); diff --git a/telephony/java/android/telephony/CarrierConfigManager.java b/telephony/java/android/telephony/CarrierConfigManager.java index 8e6d6a81e579..bd993f213f2d 100644 --- a/telephony/java/android/telephony/CarrierConfigManager.java +++ b/telephony/java/android/telephony/CarrierConfigManager.java @@ -1180,8 +1180,12 @@ public class CarrierConfigManager { "carrier_data_call_retry_network_requested_max_count_int"; /** - * Data call setup permanent failure causes by the carrier + * Data call setup permanent failure causes by the carrier. + * + * @deprecated This API key was added in mistake and is not used anymore by the telephony data + * frameworks. */ + @Deprecated public static final String KEY_CARRIER_DATA_CALL_PERMANENT_FAILURE_STRINGS = "carrier_data_call_permanent_failure_strings"; @@ -8308,7 +8312,8 @@ public class CarrierConfigManager { * * The syntax of the retry rule: * 1. Retry based on {@link NetworkCapabilities}. Note that only APN-type network capabilities - * are supported. + * are supported. If the capabilities are not specified, then the retry rule only applies + * to the current failed APN used in setup data call request. * "capabilities=[netCaps1|netCaps2|...], [retry_interval=n1|n2|n3|n4...], [maximum_retries=n]" * * 2. Retry based on {@link DataFailCause} @@ -8319,15 +8324,16 @@ public class CarrierConfigManager { * "capabilities=[netCaps1|netCaps2|...], fail_causes=[cause1|cause2|cause3|...], * [retry_interval=n1|n2|n3|n4...], [maximum_retries=n]" * + * 4. Permanent fail causes (no timer-based retry) on the current failed APN. Retry interval + * is specified for retrying the next available APN. + * "permanent_fail_causes=8|27|28|29|30|32|33|35|50|51|111|-5|-6|65537|65538|-3|65543|65547| + * 2252|2253|2254, retry_interval=2500" + * * For example, * "capabilities=eims, retry_interval=1000, maximum_retries=20" means if the attached * network request is emergency, then retry data network setup every 1 second for up to 20 * times. * - * "fail_causes=8|27|28|29|30|32|33|35|50|51|111|-5|-6|65537|65538|-3|2253|2254 - * , maximum_retries=0" means for those fail causes, never retry with timers. Note that - * when environment changes, retry can still happen. - * * "capabilities=internet|enterprise|dun|ims|fota, retry_interval=2500|3000|" * "5000|10000|15000|20000|40000|60000|120000|240000|600000|1200000|1800000" * "1800000, maximum_retries=20" means for those capabilities, retry happens in 2.5s, 3s, 5s, @@ -8472,7 +8478,12 @@ public class CarrierConfigManager { * * Used to trade privacy/security against potentially reduced carrier coverage for some * carriers. + * + * @deprecated Future versions of Android will disallow carriers from hiding this toggle + * because disabling 2g is a security feature that users should always have access to at + * their discretion. */ + @Deprecated public static final String KEY_HIDE_ENABLE_2G = "hide_enable_2g_bool"; /** @@ -9205,8 +9216,13 @@ public class CarrierConfigManager { sDefaults.putStringArray( KEY_TELEPHONY_DATA_SETUP_RETRY_RULES_STRING_ARRAY, new String[] { "capabilities=eims, retry_interval=1000, maximum_retries=20", - "fail_causes=8|27|28|29|30|32|33|35|50|51|111|-5|-6|65537|65538|-3|2252|" - + "2253|2254, maximum_retries=0", // No retry for those causes + // Permanent fail causes. When setup data call fails with the following + // fail causes, telephony data frameworks will stop timer-based retry on + // the failed APN until power cycle, APM, or some special events. Note that + // even timer-based retry is not performed, condition-based (RAT changes, + // registration state changes) retry can still happen. + "permanent_fail_causes=8|27|28|29|30|32|33|35|50|51|111|-5|-6|65537|65538|" + + "-3|65543|65547|2252|2253|2254, retry_interval=2500", "capabilities=mms|supl|cbs, retry_interval=2000", "capabilities=internet|enterprise|dun|ims|fota, retry_interval=2500|3000|" + "5000|10000|15000|20000|40000|60000|120000|240000|" diff --git a/telephony/java/android/telephony/DataFailCause.java b/telephony/java/android/telephony/DataFailCause.java index 5f7cfd109ec9..5186c7268cb6 100644 --- a/telephony/java/android/telephony/DataFailCause.java +++ b/telephony/java/android/telephony/DataFailCause.java @@ -1613,29 +1613,26 @@ public final class DataFailCause { // If we are not able to find the configuration from carrier config, use the default // ones. if (permanentFailureSet == null) { - permanentFailureSet = new HashSet<Integer>() { - { - add(OPERATOR_BARRED); - add(MISSING_UNKNOWN_APN); - add(UNKNOWN_PDP_ADDRESS_TYPE); - add(USER_AUTHENTICATION); - add(ACTIVATION_REJECT_GGSN); - add(SERVICE_OPTION_NOT_SUPPORTED); - add(SERVICE_OPTION_NOT_SUBSCRIBED); - add(NSAPI_IN_USE); - add(ONLY_IPV4_ALLOWED); - add(ONLY_IPV6_ALLOWED); - add(PROTOCOL_ERRORS); - add(RADIO_POWER_OFF); - add(TETHERED_CALL_ACTIVE); - add(RADIO_NOT_AVAILABLE); - add(UNACCEPTABLE_NETWORK_PARAMETER); - add(SIGNAL_LOST); - add(DUPLICATE_CID); - add(MATCH_ALL_RULE_NOT_ALLOWED); - add(ALL_MATCHING_RULES_FAILED); - } - }; + permanentFailureSet = new HashSet<Integer>(); + permanentFailureSet.add(OPERATOR_BARRED); + permanentFailureSet.add(MISSING_UNKNOWN_APN); + permanentFailureSet.add(UNKNOWN_PDP_ADDRESS_TYPE); + permanentFailureSet.add(USER_AUTHENTICATION); + permanentFailureSet.add(ACTIVATION_REJECT_GGSN); + permanentFailureSet.add(SERVICE_OPTION_NOT_SUPPORTED); + permanentFailureSet.add(SERVICE_OPTION_NOT_SUBSCRIBED); + permanentFailureSet.add(NSAPI_IN_USE); + permanentFailureSet.add(ONLY_IPV4_ALLOWED); + permanentFailureSet.add(ONLY_IPV6_ALLOWED); + permanentFailureSet.add(PROTOCOL_ERRORS); + permanentFailureSet.add(RADIO_POWER_OFF); + permanentFailureSet.add(TETHERED_CALL_ACTIVE); + permanentFailureSet.add(RADIO_NOT_AVAILABLE); + permanentFailureSet.add(UNACCEPTABLE_NETWORK_PARAMETER); + permanentFailureSet.add(SIGNAL_LOST); + permanentFailureSet.add(DUPLICATE_CID); + permanentFailureSet.add(MATCH_ALL_RULE_NOT_ALLOWED); + permanentFailureSet.add(ALL_MATCHING_RULES_FAILED); } permanentFailureSet.add(NO_RETRY_FAILURE); diff --git a/telephony/java/android/telephony/SmsMessage.java b/telephony/java/android/telephony/SmsMessage.java index e0145e661660..c2b65f86ff02 100644 --- a/telephony/java/android/telephony/SmsMessage.java +++ b/telephony/java/android/telephony/SmsMessage.java @@ -1092,6 +1092,11 @@ public class SmsMessage { if (!TextUtils.isEmpty(simOperator)) { for (NoEmsSupportConfig currentConfig : mNoEmsSupportConfigList) { + if (currentConfig == null) { + Rlog.w("SmsMessage", "hasEmsSupport currentConfig is null"); + continue; + } + if (simOperator.startsWith(currentConfig.mOperatorNumber) && (TextUtils.isEmpty(currentConfig.mGid1) || (!TextUtils.isEmpty(currentConfig.mGid1) && @@ -1155,18 +1160,21 @@ public class SmsMessage { private static boolean mIsNoEmsSupportConfigListLoaded = false; private static boolean isNoEmsSupportConfigListExisted() { - if (!mIsNoEmsSupportConfigListLoaded) { - Resources r = Resources.getSystem(); - if (r != null) { - String[] listArray = r.getStringArray( - com.android.internal.R.array.no_ems_support_sim_operators); - if ((listArray != null) && (listArray.length > 0)) { - mNoEmsSupportConfigList = new NoEmsSupportConfig[listArray.length]; - for (int i=0; i<listArray.length; i++) { - mNoEmsSupportConfigList[i] = new NoEmsSupportConfig(listArray[i].split(";")); + synchronized (SmsMessage.class) { + if (!mIsNoEmsSupportConfigListLoaded) { + Resources r = Resources.getSystem(); + if (r != null) { + String[] listArray = r.getStringArray( + com.android.internal.R.array.no_ems_support_sim_operators); + if ((listArray != null) && (listArray.length > 0)) { + mNoEmsSupportConfigList = new NoEmsSupportConfig[listArray.length]; + for (int i = 0; i < listArray.length; i++) { + mNoEmsSupportConfigList[i] = new NoEmsSupportConfig( + listArray[i].split(";")); + } } + mIsNoEmsSupportConfigListLoaded = true; } - mIsNoEmsSupportConfigListLoaded = true; } } diff --git a/telephony/java/android/telephony/TelephonyManager.java b/telephony/java/android/telephony/TelephonyManager.java index 70d82701da66..a081bc320921 100644 --- a/telephony/java/android/telephony/TelephonyManager.java +++ b/telephony/java/android/telephony/TelephonyManager.java @@ -9358,7 +9358,8 @@ public class TelephonyManager { ALLOWED_NETWORK_TYPES_REASON_USER, ALLOWED_NETWORK_TYPES_REASON_POWER, ALLOWED_NETWORK_TYPES_REASON_CARRIER, - ALLOWED_NETWORK_TYPES_REASON_ENABLE_2G + ALLOWED_NETWORK_TYPES_REASON_ENABLE_2G, + ALLOWED_NETWORK_TYPES_REASON_USER_RESTRICTIONS, }) @Retention(RetentionPolicy.SOURCE) public @interface AllowedNetworkTypesReason { @@ -9397,6 +9398,15 @@ public class TelephonyManager { public static final int ALLOWED_NETWORK_TYPES_REASON_ENABLE_2G = 3; /** + * To indicate allowed network type change is requested by an update to the + * {@link android.os.UserManager.DISALLOW_CELLULAR_2G} user restriction. + * + * @hide + */ + @SystemApi + public static final int ALLOWED_NETWORK_TYPES_REASON_USER_RESTRICTIONS = 4; + + /** * Set the allowed network types of the device and provide the reason triggering the allowed * network change. * <p>Requires permission: android.Manifest.MODIFY_PHONE_STATE or @@ -9488,6 +9498,7 @@ public class TelephonyManager { case TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_POWER: case TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_CARRIER: case TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_ENABLE_2G: + case ALLOWED_NETWORK_TYPES_REASON_USER_RESTRICTIONS: return true; } return false; diff --git a/telephony/java/android/telephony/ims/ImsService.java b/telephony/java/android/telephony/ims/ImsService.java index be233b82c426..4477f81a378d 100644 --- a/telephony/java/android/telephony/ims/ImsService.java +++ b/telephony/java/android/telephony/ims/ImsService.java @@ -50,7 +50,6 @@ import com.android.internal.telephony.util.TelephonyUtils; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; -import java.util.HashMap; import java.util.Map; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; @@ -164,10 +163,9 @@ public class ImsService extends Service { * Used for logging purposes, see {@link #getCapabilitiesString(long)} * @hide */ - private static final Map<Long, String> CAPABILITIES_LOG_MAP = new HashMap<Long, String>() {{ - put(CAPABILITY_EMERGENCY_OVER_MMTEL, "EMERGENCY_OVER_MMTEL"); - put(CAPABILITY_SIP_DELEGATE_CREATION, "SIP_DELEGATE_CREATION"); - }}; + private static final Map<Long, String> CAPABILITIES_LOG_MAP = Map.of( + CAPABILITY_EMERGENCY_OVER_MMTEL, "EMERGENCY_OVER_MMTEL", + CAPABILITY_SIP_DELEGATE_CREATION, "SIP_DELEGATE_CREATION"); /** * The intent that must be defined as an intent-filter in the AndroidManifest of the ImsService. @@ -425,8 +423,8 @@ public class ImsService extends Service { } } - private IImsRcsFeature createRcsFeatureInternal(int slotId, int subI) { - RcsFeature f = createRcsFeatureForSubscription(slotId, subI); + private IImsRcsFeature createRcsFeatureInternal(int slotId, int subId) { + RcsFeature f = createRcsFeatureForSubscription(slotId, subId); if (f != null) { f.setDefaultExecutor(mExecutor); setupFeature(f, slotId, ImsFeature.FEATURE_RCS); diff --git a/telephony/java/android/telephony/ims/RegistrationManager.java b/telephony/java/android/telephony/ims/RegistrationManager.java index 090d4136872e..9996b868afc7 100644 --- a/telephony/java/android/telephony/ims/RegistrationManager.java +++ b/telephony/java/android/telephony/ims/RegistrationManager.java @@ -78,24 +78,22 @@ public interface RegistrationManager { /**@hide*/ // Translate ImsRegistrationImplBase API to new AccessNetworkConstant because WLAN // and WWAN are more accurate constants. - Map<Integer, Integer> IMS_REG_TO_ACCESS_TYPE_MAP = - new HashMap<Integer, Integer>() {{ - // Map NONE to -1 to make sure that we handle the REGISTRATION_TECH_NONE - // case, since it is defined. - put(ImsRegistrationImplBase.REGISTRATION_TECH_NONE, - AccessNetworkConstants.TRANSPORT_TYPE_INVALID); - put(ImsRegistrationImplBase.REGISTRATION_TECH_LTE, - AccessNetworkConstants.TRANSPORT_TYPE_WWAN); - put(ImsRegistrationImplBase.REGISTRATION_TECH_NR, - AccessNetworkConstants.TRANSPORT_TYPE_WWAN); - put(ImsRegistrationImplBase.REGISTRATION_TECH_IWLAN, - AccessNetworkConstants.TRANSPORT_TYPE_WLAN); - /* As the cross sim will be using ePDG tunnel over internet, it behaves - like IWLAN in most cases. Hence setting the access type as IWLAN - */ - put(ImsRegistrationImplBase.REGISTRATION_TECH_CROSS_SIM, - AccessNetworkConstants.TRANSPORT_TYPE_WLAN); - }}; + Map<Integer, Integer> IMS_REG_TO_ACCESS_TYPE_MAP = Map.of( + // Map NONE to -1 to make sure that we handle the REGISTRATION_TECH_NONE + // case, since it is defined. + ImsRegistrationImplBase.REGISTRATION_TECH_NONE, + AccessNetworkConstants.TRANSPORT_TYPE_INVALID, + ImsRegistrationImplBase.REGISTRATION_TECH_LTE, + AccessNetworkConstants.TRANSPORT_TYPE_WWAN, + ImsRegistrationImplBase.REGISTRATION_TECH_NR, + AccessNetworkConstants.TRANSPORT_TYPE_WWAN, + ImsRegistrationImplBase.REGISTRATION_TECH_IWLAN, + AccessNetworkConstants.TRANSPORT_TYPE_WLAN, + /* As the cross sim will be using ePDG tunnel over internet, it behaves + like IWLAN in most cases. Hence setting the access type as IWLAN + */ + ImsRegistrationImplBase.REGISTRATION_TECH_CROSS_SIM, + AccessNetworkConstants.TRANSPORT_TYPE_WLAN); /** @hide */ @NonNull diff --git a/telephony/java/android/telephony/ims/feature/ImsFeature.java b/telephony/java/android/telephony/ims/feature/ImsFeature.java index f5b158fedd37..174675fcde4c 100644 --- a/telephony/java/android/telephony/ims/feature/ImsFeature.java +++ b/telephony/java/android/telephony/ims/feature/ImsFeature.java @@ -34,7 +34,6 @@ import com.android.internal.telephony.util.RemoteCallbackListExt; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; -import java.util.HashMap; import java.util.Map; /** @@ -85,11 +84,10 @@ public abstract class ImsFeature { * Used for logging purposes. * @hide */ - public static final Map<Integer, String> FEATURE_LOG_MAP = new HashMap<Integer, String>() {{ - put(FEATURE_EMERGENCY_MMTEL, "EMERGENCY_MMTEL"); - put(FEATURE_MMTEL, "MMTEL"); - put(FEATURE_RCS, "RCS"); - }}; + public static final Map<Integer, String> FEATURE_LOG_MAP = Map.of( + FEATURE_EMERGENCY_MMTEL, "EMERGENCY_MMTEL", + FEATURE_MMTEL, "MMTEL", + FEATURE_RCS, "RCS"); /** * Integer values defining IMS features that are supported in ImsFeature. @@ -145,11 +143,10 @@ public abstract class ImsFeature { * Used for logging purposes. * @hide */ - public static final Map<Integer, String> STATE_LOG_MAP = new HashMap<Integer, String>() {{ - put(STATE_UNAVAILABLE, "UNAVAILABLE"); - put(STATE_INITIALIZING, "INITIALIZING"); - put(STATE_READY, "READY"); - }}; + public static final Map<Integer, String> STATE_LOG_MAP = Map.of( + STATE_UNAVAILABLE, "UNAVAILABLE", + STATE_INITIALIZING, "INITIALIZING", + STATE_READY, "READY"); /** * Integer values defining the result codes that should be returned from @@ -394,10 +391,12 @@ public abstract class ImsFeature { @VisibleForTesting public void addImsFeatureStatusCallback(@NonNull IImsFeatureStatusCallback c) { try { - // If we have just connected, send queued status. - c.notifyImsFeatureStatus(getFeatureState()); - // Add the callback if the callback completes successfully without a RemoteException. - mStatusCallbacks.register(c); + synchronized (mStatusCallbacks) { + // Add the callback if the callback completes successfully without a RemoteException + mStatusCallbacks.register(c); + // If we have just connected, send queued status. + c.notifyImsFeatureStatus(getFeatureState()); + } } catch (RemoteException e) { Log.w(LOG_TAG, "Couldn't notify feature state: " + e.getMessage()); } @@ -409,7 +408,9 @@ public abstract class ImsFeature { */ @VisibleForTesting public void removeImsFeatureStatusCallback(@NonNull IImsFeatureStatusCallback c) { - mStatusCallbacks.unregister(c); + synchronized (mStatusCallbacks) { + mStatusCallbacks.unregister(c); + } } /** diff --git a/tests/CanvasCompare/src/com/android/test/hwuicompare/DisplayModifier.java b/tests/CanvasCompare/src/com/android/test/hwuicompare/DisplayModifier.java index 0f4e122d147a..4bcf5a4e30d5 100644 --- a/tests/CanvasCompare/src/com/android/test/hwuicompare/DisplayModifier.java +++ b/tests/CanvasCompare/src/com/android/test/hwuicompare/DisplayModifier.java @@ -16,14 +16,16 @@ package com.android.test.hwuicompare; -import java.util.LinkedHashMap; -import java.util.Map.Entry; +import static java.util.Map.entry; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.RectF; import android.util.Log; +import java.util.Map; +import java.util.Map.Entry; + public abstract class DisplayModifier { // automated tests ignore any combination of operations that don't together return TOTAL_MASK @@ -76,41 +78,36 @@ public abstract class DisplayModifier { }; @SuppressWarnings("serial") - private static final LinkedHashMap<String, LinkedHashMap<String, DisplayModifier>> gMaps = new LinkedHashMap<String, LinkedHashMap<String, DisplayModifier>>() { - { - put("aa", new LinkedHashMap<String, DisplayModifier>() { - { - put("true", new DisplayModifier() { + private static final Map<String, Map<String, DisplayModifier>> gMaps = Map.of( + "aa", Map.of( + "true", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { paint.setAntiAlias(true); } - }); - put("false", new DisplayModifier() { + }, + "false", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { paint.setAntiAlias(false); } - }); - } - }); - put("style", new LinkedHashMap<String, DisplayModifier>() { - { - put("fill", new DisplayModifier() { + }), + "style", Map.of( + "fill", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { paint.setStyle(Paint.Style.FILL); } - }); - put("stroke", new DisplayModifier() { + }, + "stroke", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { paint.setStyle(Paint.Style.STROKE); } @Override protected int mask() { return SWEEP_STROKE_WIDTH_BIT; } - }); - put("fillAndStroke", new DisplayModifier() { + }, + "fillAndStroke", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { paint.setStyle(Paint.Style.FILL_AND_STROKE); @@ -118,131 +115,118 @@ public abstract class DisplayModifier { @Override protected int mask() { return SWEEP_STROKE_WIDTH_BIT; } - }); - } - }); - put("strokeWidth", new LinkedHashMap<String, DisplayModifier>() { - { - put("hair", new DisplayModifier() { + }), + "strokeWidth", Map.of( + "hair", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { paint.setStrokeWidth(0); } @Override protected int mask() { return SWEEP_STROKE_WIDTH_BIT; } - }); - put("0.3", new DisplayModifier() { + }, + "0.3", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { paint.setStrokeWidth(0.3f); } - }); - put("1", new DisplayModifier() { + }, + "1", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { paint.setStrokeWidth(1); } - }); - put("5", new DisplayModifier() { + }, + "5", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { paint.setStrokeWidth(5); } - }); - put("30", new DisplayModifier() { + }, + "30", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { paint.setStrokeWidth(30); } - }); - } - }); - put("strokeCap", new LinkedHashMap<String, DisplayModifier>() { - { - put("butt", new DisplayModifier() { + }), + "strokeCap", Map.of( + "butt", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { paint.setStrokeCap(Paint.Cap.BUTT); } @Override protected int mask() { return SWEEP_STROKE_CAP_BIT; } - }); - put("round", new DisplayModifier() { + }, + "round", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { paint.setStrokeCap(Paint.Cap.ROUND); } - }); - put("square", new DisplayModifier() { + }, + "square", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { paint.setStrokeCap(Paint.Cap.SQUARE); } - }); - } - }); - put("strokeJoin", new LinkedHashMap<String, DisplayModifier>() { - { - put("bevel", new DisplayModifier() { + }), + "strokeJoin", Map.of( + "bevel", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { paint.setStrokeJoin(Paint.Join.BEVEL); } @Override protected int mask() { return SWEEP_STROKE_JOIN_BIT; } - }); - put("round", new DisplayModifier() { + }, + "round", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { paint.setStrokeJoin(Paint.Join.ROUND); } - }); - put("miter", new DisplayModifier() { + }, + "miter", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { paint.setStrokeJoin(Paint.Join.MITER); } - }); + }), // TODO: add miter0, miter1 etc to test miter distances - } - }); - - put("transform", new LinkedHashMap<String, DisplayModifier>() { - { - put("noTransform", new DisplayModifier() { + "transform", Map.of( + "noTransform", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) {} @Override protected int mask() { return SWEEP_TRANSFORM_BIT; }; - }); - put("rotate5", new DisplayModifier() { + }, + "rotate5", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { canvas.rotate(5); } - }); - put("rotate45", new DisplayModifier() { + }, + "rotate45", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { canvas.rotate(45); } - }); - put("rotate90", new DisplayModifier() { + }, + "rotate90", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { canvas.rotate(90); canvas.translate(0, -200); } - }); - put("scale2x2", new DisplayModifier() { + }, + "scale2x2", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { canvas.scale(2, 2); } @Override protected int mask() { return SWEEP_TRANSFORM_BIT; }; - }); - put("rot20scl1x4", new DisplayModifier() { + }, + "rot20scl1x4", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { canvas.rotate(20); @@ -250,180 +234,167 @@ public abstract class DisplayModifier { } @Override protected int mask() { return SWEEP_TRANSFORM_BIT; }; - }); - } - }); - - put("shader", new LinkedHashMap<String, DisplayModifier>() { - { - put("noShader", new DisplayModifier() { + }), + "shader", Map.ofEntries( + entry("noShader", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) {} @Override protected int mask() { return SWEEP_SHADER_BIT; }; - }); - put("repeatShader", new DisplayModifier() { + }), + entry("repeatShader", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { paint.setShader(ResourceModifiers.instance().mRepeatShader); } @Override protected int mask() { return SWEEP_SHADER_BIT; }; - }); - put("translatedShader", new DisplayModifier() { + }), + entry("translatedShader", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { paint.setShader(ResourceModifiers.instance().mTranslatedShader); } - }); - put("scaledShader", new DisplayModifier() { + }), + entry("scaledShader", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { paint.setShader(ResourceModifiers.instance().mScaledShader); } - }); - put("horGradient", new DisplayModifier() { + }), + entry("horGradient", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { paint.setShader(ResourceModifiers.instance().mHorGradient); } - }); - put("diagGradient", new DisplayModifier() { + }), + entry("diagGradient", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { paint.setShader(ResourceModifiers.instance().mDiagGradient); } @Override protected int mask() { return SWEEP_SHADER_BIT; }; - }); - put("vertGradient", new DisplayModifier() { + }), + entry("vertGradient", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { paint.setShader(ResourceModifiers.instance().mVertGradient); } - }); - put("radGradient", new DisplayModifier() { + }), + entry("radGradient", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { paint.setShader(ResourceModifiers.instance().mRadGradient); } - }); - put("sweepGradient", new DisplayModifier() { + }), + entry("sweepGradient", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { paint.setShader(ResourceModifiers.instance().mSweepGradient); } - }); - put("composeShader", new DisplayModifier() { + }), + entry("composeShader", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { paint.setShader(ResourceModifiers.instance().mComposeShader); } - }); - put("bad composeShader", new DisplayModifier() { + }), + entry("bad composeShader", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { paint.setShader(ResourceModifiers.instance().mBadComposeShader); } - }); - put("bad composeShader 2", new DisplayModifier() { + }), + entry("bad composeShader 2", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { paint.setShader(ResourceModifiers.instance().mAnotherBadComposeShader); } - }); - } - }); - - // FINAL MAP: DOES ACTUAL DRAWING - put("drawing", new LinkedHashMap<String, DisplayModifier>() { - { - put("roundRect", new DisplayModifier() { + })), + "drawing", Map.ofEntries( + entry("roundRect", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { canvas.drawRoundRect(gRect, 20, 20, paint); } - }); - put("rect", new DisplayModifier() { + }), + entry("rect", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { canvas.drawRect(gRect, paint); } @Override protected int mask() { return SWEEP_SHADER_BIT | SWEEP_STROKE_CAP_BIT; }; - }); - put("circle", new DisplayModifier() { + }), + entry("circle", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { canvas.drawCircle(100, 100, 75, paint); } - }); - put("oval", new DisplayModifier() { + }), + entry("oval", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { canvas.drawOval(gRect, paint); } - }); - put("lines", new DisplayModifier() { + }), + entry("lines", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { canvas.drawLines(gLinePts, paint); } @Override protected int mask() { return SWEEP_STROKE_CAP_BIT; }; - }); - put("plusPoints", new DisplayModifier() { + }), + entry("plusPoints", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { canvas.drawPoints(gPts, paint); } - }); - put("text", new DisplayModifier() { + }), + entry("text", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { paint.setTextSize(36); canvas.drawText("TEXTTEST", 0, 50, paint); } - }); - put("shadowtext", new DisplayModifier() { + }), + entry("shadowtext", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { paint.setTextSize(36); paint.setShadowLayer(3.0f, 0.0f, 3.0f, 0xffff00ff); canvas.drawText("TEXTTEST", 0, 50, paint); } - }); - put("bitmapMesh", new DisplayModifier() { + }), + entry("bitmapMesh", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { canvas.drawBitmapMesh(ResourceModifiers.instance().mBitmap, 3, 3, ResourceModifiers.instance().mBitmapVertices, 0, null, 0, null); } - }); - put("arc", new DisplayModifier() { + }), + entry("arc", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { canvas.drawArc(gRect, 260, 285, false, paint); } @Override protected int mask() { return SWEEP_STROKE_CAP_BIT; }; - }); - put("arcFromCenter", new DisplayModifier() { + }), + entry("arcFromCenter", new DisplayModifier() { @Override public void modifyDrawing(Paint paint, Canvas canvas) { canvas.drawArc(gRect, 260, 285, true, paint); } @Override protected int mask() { return SWEEP_STROKE_JOIN_BIT; }; - }); - } - }); + }))); // WARNING: DON'T PUT MORE MAPS BELOW THIS - } - }; - private static LinkedHashMap<String, DisplayModifier> getMapAtIndex(int index) { - for (LinkedHashMap<String, DisplayModifier> map : gMaps.values()) { + private static Map<String, DisplayModifier> getMapAtIndex(int index) { + for (Map<String, DisplayModifier> map : gMaps.values()) { if (index == 0) { return map; } @@ -439,7 +410,7 @@ public abstract class DisplayModifier { private static boolean stepInternal(boolean forward) { int modifierMapIndex = gMaps.size() - 1; while (modifierMapIndex >= 0) { - LinkedHashMap<String, DisplayModifier> map = getMapAtIndex(modifierMapIndex); + Map<String, DisplayModifier> map = getMapAtIndex(modifierMapIndex); mIndices[modifierMapIndex] += (forward ? 1 : -1); if (mIndices[modifierMapIndex] >= 0 && mIndices[modifierMapIndex] < map.size()) { @@ -471,7 +442,7 @@ public abstract class DisplayModifier { private static boolean checkModificationStateMask() { int operatorMask = 0x0; int mapIndex = 0; - for (LinkedHashMap<String, DisplayModifier> map : gMaps.values()) { + for (Map<String, DisplayModifier> map : gMaps.values()) { int displayModifierIndex = mIndices[mapIndex]; for (Entry<String, DisplayModifier> modifierEntry : map.entrySet()) { if (displayModifierIndex == 0) { @@ -488,7 +459,7 @@ public abstract class DisplayModifier { public static void apply(Paint paint, Canvas canvas) { int mapIndex = 0; - for (LinkedHashMap<String, DisplayModifier> map : gMaps.values()) { + for (Map<String, DisplayModifier> map : gMaps.values()) { int displayModifierIndex = mIndices[mapIndex]; for (Entry<String, DisplayModifier> modifierEntry : map.entrySet()) { if (displayModifierIndex == 0) { @@ -510,7 +481,7 @@ public abstract class DisplayModifier { String[][] keys = new String[gMaps.size()][]; int i = 0; - for (LinkedHashMap<String, DisplayModifier> map : gMaps.values()) { + for (Map<String, DisplayModifier> map : gMaps.values()) { keys[i] = new String[map.size()]; int j = 0; for (String key : map.keySet()) { diff --git a/tests/HierarchyViewerTest/src/com/android/test/hierarchyviewer/ViewDumpParser.java b/tests/HierarchyViewerTest/src/com/android/test/hierarchyviewer/ViewDumpParser.java index 2ad0da98c409..8b9c02049351 100644 --- a/tests/HierarchyViewerTest/src/com/android/test/hierarchyviewer/ViewDumpParser.java +++ b/tests/HierarchyViewerTest/src/com/android/test/hierarchyviewer/ViewDumpParser.java @@ -58,7 +58,7 @@ public class ViewDumpParser { Object hash = getProperty(props, "__hash__"); if (name instanceof String && hash instanceof Integer) { - return String.format(Locale.US, "%s@%x", name, hash); + return String.format(Locale.US, "%s@%x", name, (Integer) hash); } else { return null; } diff --git a/tests/JankBench/app/src/main/java/com/android/benchmark/app/HomeActivity.java b/tests/JankBench/app/src/main/java/com/android/benchmark/app/HomeActivity.java index 4de51fb57308..43dc9de6c90a 100644 --- a/tests/JankBench/app/src/main/java/com/android/benchmark/app/HomeActivity.java +++ b/tests/JankBench/app/src/main/java/com/android/benchmark/app/HomeActivity.java @@ -140,9 +140,9 @@ public class HomeActivity extends AppCompatActivity implements Button.OnClickLis handleNextBenchmark(); } + @SuppressWarnings("MissingSuperCall") // TODO: Fix me @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { - } private void handleNextBenchmark() { diff --git a/tests/JankBench/app/src/main/java/com/android/benchmark/app/RunLocalBenchmarksActivity.java b/tests/JankBench/app/src/main/java/com/android/benchmark/app/RunLocalBenchmarksActivity.java index c16efbda1830..d015a5695ec0 100644 --- a/tests/JankBench/app/src/main/java/com/android/benchmark/app/RunLocalBenchmarksActivity.java +++ b/tests/JankBench/app/src/main/java/com/android/benchmark/app/RunLocalBenchmarksActivity.java @@ -367,6 +367,7 @@ public class RunLocalBenchmarksActivity extends AppCompatActivity { } } + @SuppressWarnings("MissingSuperCall") // TODO: Fix me @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { diff --git a/tests/MirrorSurfaceTest/src/com/google/android/test/mirrorsurface/MirrorSurfaceActivity.java b/tests/MirrorSurfaceTest/src/com/google/android/test/mirrorsurface/MirrorSurfaceActivity.java index 8afe8411a790..17fa210a1db6 100644 --- a/tests/MirrorSurfaceTest/src/com/google/android/test/mirrorsurface/MirrorSurfaceActivity.java +++ b/tests/MirrorSurfaceTest/src/com/google/android/test/mirrorsurface/MirrorSurfaceActivity.java @@ -295,8 +295,8 @@ public class MirrorSurfaceActivity extends Activity implements View.OnClickListe private void updateMirror(Rect displayFrame, float scale) { if (displayFrame.isEmpty()) { Rect bounds = mWindowBounds; - int defaultCropW = Math.round(bounds.width() / 2); - int defaultCropH = Math.round(bounds.height() / 2); + int defaultCropW = bounds.width() / 2; + int defaultCropH = bounds.height() / 2; displayFrame.set(0, 0, defaultCropW, defaultCropH); } diff --git a/tests/RenderThreadTest/src/com/example/renderthread/MainActivity.java b/tests/RenderThreadTest/src/com/example/renderthread/MainActivity.java index 241206d8919b..65b7549f22d1 100644 --- a/tests/RenderThreadTest/src/com/example/renderthread/MainActivity.java +++ b/tests/RenderThreadTest/src/com/example/renderthread/MainActivity.java @@ -24,18 +24,14 @@ public class MainActivity extends Activity implements OnItemClickListener { static final String KEY_NAME = "name"; static final String KEY_CLASS = "clazz"; - static Map<String,?> make(String name) { - Map<String,Object> ret = new HashMap<String,Object>(); - ret.put(KEY_NAME, name); - return ret; - } - - @SuppressWarnings("serial") - static final ArrayList<Map<String,?>> SAMPLES = new ArrayList<Map<String,?>>() {{ + static final ArrayList<Map<String, ?>> SAMPLES = new ArrayList<>(); + static { for (int i = 1; i < 25; i++) { - add(make("List Item: " + i)); + Map<String, Object> sample = new HashMap<String, Object>(); + sample.put(KEY_NAME, "List Item: " + i); + SAMPLES.add(sample); } - }}; + } Handler mHandler = new Handler(); diff --git a/tests/RollbackTest/SampleRollbackApp/Android.bp b/tests/RollbackTest/SampleRollbackApp/Android.bp index a18488d8f57f..074c7bc39155 100644 --- a/tests/RollbackTest/SampleRollbackApp/Android.bp +++ b/tests/RollbackTest/SampleRollbackApp/Android.bp @@ -29,4 +29,5 @@ android_app { resource_dirs: ["res"], certificate: "platform", sdk_version: "system_current", + min_sdk_version: "29", } diff --git a/tests/SmokeTestApps/src/com/android/smoketest/triggers/CrashyApp.java b/tests/SmokeTestApps/src/com/android/smoketest/triggers/CrashyApp.java index c11b0f3acf79..f85fb0f267d5 100644 --- a/tests/SmokeTestApps/src/com/android/smoketest/triggers/CrashyApp.java +++ b/tests/SmokeTestApps/src/com/android/smoketest/triggers/CrashyApp.java @@ -30,6 +30,7 @@ public class CrashyApp extends Activity { setContentView(tv); } + @SuppressWarnings("ReturnValueIgnored") @Override public void onResume() { ((String) null).length(); diff --git a/tests/utils/testutils/java/com/android/internal/util/test/BroadcastInterceptingContext.java b/tests/utils/testutils/java/com/android/internal/util/test/BroadcastInterceptingContext.java index 3da8b460df13..133c1767c9b4 100644 --- a/tests/utils/testutils/java/com/android/internal/util/test/BroadcastInterceptingContext.java +++ b/tests/utils/testutils/java/com/android/internal/util/test/BroadcastInterceptingContext.java @@ -147,12 +147,39 @@ public class BroadcastInterceptingContext extends ContextWrapper { @Override public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) { - return registerReceiver(receiver, filter, null, null); + return registerReceiver(receiver, filter, null, null, 0); + } + + /** + * Registers the specified {@code receiver} to listen for broadcasts that match the {@code + * filter} in the current process. + * + * <p>Since this method only listens for broadcasts in the current process, the provided {@code + * flags} are ignored; this method is primarily intended to allow receivers that register with + * flags to register in the current process during tests. + */ + @Override + public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, int flags) { + return registerReceiver(receiver, filter, null, null, flags); } @Override public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler) { + return registerReceiver(receiver, filter, broadcastPermission, scheduler, 0); + } + + /** + * Registers the specified {@code receiver} to listen for broadcasts that match the {@code + * filter} to run in the context of the specified {@code scheduler} in the current process. + * + * <p>Since this method only listens for broadcasts in the current process, the provided {@code + * flags} are ignored; this method is primarily intended to allow receivers that register with + * flags to register in the current process during tests. + */ + @Override + public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, + String broadcastPermission, Handler scheduler, int flags) { synchronized (mInterceptors) { mInterceptors.add(new BroadcastInterceptor(receiver, filter, scheduler)); } diff --git a/tests/vcn/java/com/android/server/VcnManagementServiceTest.java b/tests/vcn/java/com/android/server/VcnManagementServiceTest.java index f924b2e9b932..ad068308d481 100644 --- a/tests/vcn/java/com/android/server/VcnManagementServiceTest.java +++ b/tests/vcn/java/com/android/server/VcnManagementServiceTest.java @@ -637,8 +637,7 @@ public class VcnManagementServiceTest { final BroadcastReceiver receiver = getPackageChangeReceiver(); verify(mMockContext).registerReceiver(any(), argThat(filter -> { - return filter.hasAction(Intent.ACTION_PACKAGE_REMOVED) - && filter.hasAction(Intent.ACTION_PACKAGE_REMOVED); + return filter.hasAction(Intent.ACTION_PACKAGE_REMOVED); }), any(), any()); receiver.onReceive(mMockContext, new Intent(Intent.ACTION_PACKAGE_REMOVED)); diff --git a/tools/locked_region_code_injection/Android.bp b/tools/locked_region_code_injection/Android.bp index 6efd1f64d8fe..ff1f8e2c9d30 100644 --- a/tools/locked_region_code_injection/Android.bp +++ b/tools/locked_region_code_injection/Android.bp @@ -16,6 +16,6 @@ java_binary_host { "asm-commons-9.2", "asm-tree-9.2", "asm-analysis-9.2", - "guava-21.0", + "guava", ], } diff --git a/tools/traceinjection/Android.bp b/tools/traceinjection/Android.bp index 39d1b1c2defd..bb32df6c65af 100644 --- a/tools/traceinjection/Android.bp +++ b/tools/traceinjection/Android.bp @@ -16,7 +16,7 @@ java_binary_host { "asm-commons-9.2", "asm-tree-9.2", "asm-analysis-9.2", - "guava-21.0", + "guava", ], } diff --git a/wifi/tests/src/android/net/wifi/nl80211/WifiNl80211ManagerTest.java b/wifi/tests/src/android/net/wifi/nl80211/WifiNl80211ManagerTest.java index a750696628f9..50126226eb94 100644 --- a/wifi/tests/src/android/net/wifi/nl80211/WifiNl80211ManagerTest.java +++ b/wifi/tests/src/android/net/wifi/nl80211/WifiNl80211ManagerTest.java @@ -117,13 +117,12 @@ public class WifiNl80211ManagerTest { private static final byte[] TEST_PSK = new byte[]{'T', 'e', 's', 't'}; - private static final Set<Integer> SCAN_FREQ_SET = - new HashSet<Integer>() {{ - add(2410); - add(2450); - add(5050); - add(5200); - }}; + private static final Set<Integer> SCAN_FREQ_SET = Set.of( + 2410, + 2450, + 5050, + 5200); + private static final String TEST_QUOTED_SSID_1 = "\"testSsid1\""; private static final String TEST_QUOTED_SSID_2 = "\"testSsid2\""; private static final int[] TEST_FREQUENCIES_1 = {}; @@ -131,13 +130,11 @@ public class WifiNl80211ManagerTest { private static final MacAddress TEST_RAW_MAC_BYTES = MacAddress.fromBytes( new byte[]{0x00, 0x01, 0x02, 0x03, 0x04, 0x05}); - private static final List<byte[]> SCAN_HIDDEN_NETWORK_SSID_LIST = - new ArrayList<byte[]>() {{ - add(LocalNativeUtil.byteArrayFromArrayList( - LocalNativeUtil.decodeSsid(TEST_QUOTED_SSID_1))); - add(LocalNativeUtil.byteArrayFromArrayList( - LocalNativeUtil.decodeSsid(TEST_QUOTED_SSID_2))); - }}; + private static final List<byte[]> SCAN_HIDDEN_NETWORK_SSID_LIST = List.of( + LocalNativeUtil.byteArrayFromArrayList( + LocalNativeUtil.decodeSsid(TEST_QUOTED_SSID_1)), + LocalNativeUtil.byteArrayFromArrayList( + LocalNativeUtil.decodeSsid(TEST_QUOTED_SSID_2))); private static final PnoSettings TEST_PNO_SETTINGS = new PnoSettings(); static { |