Merge "Update android.text.format tests and regenerate LocaleDataTables.cpp due to ICU 72 upgrade"
diff --git a/GAME_MANAGER_OWNERS b/GAME_MANAGER_OWNERS
index 502a9e36..b65c43a 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 23464f8..9366ff2d 100644
--- a/apct-tests/perftests/core/Android.bp
+++ b/apct-tests/perftests/core/Android.bp
@@ -43,6 +43,9 @@
"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 @@
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 3f4f6af..3ebaa4c 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.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 @@
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 @@
}
@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 @@
}
@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 2ef68ca..05a3e12 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 @@
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 5aacfc2..20f1309 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.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 @@
});
}
- @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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 eec0734..b1b594d 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.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 @@
}
@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 @@
(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 31c92ba..3a45d40 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.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.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 @@
}
@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 faa9628..2e89518 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.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.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 @@
}
@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 db5462c..2c0473e 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.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 3952c12..6a2ce58 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.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 @@
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 @@
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 @@
+ " เดิมทีเป็นการผสมผสานกันระหว่างสำเนียงอยุธยาและชาวไทยเชื้อสายจีนรุ่นหลังที่"
+ "พูดไทยแทนกลุ่มภาษาจีน"
+ " ลักษณะเด่นคือมีการออกเสียงที่ชัดเจนและแข็งกระด้างซึ่งได้รับอิทธิพลจากภาษาแต"
- + "้จิ๋ว"
- + " การออกเสียงพยัญชนะ สระ การผันวรรณยุกต์ที่ในภาษาไทยมาตรฐาน"
+ + "้จิ๋ว การออกเสียงพยัญชนะ สระ การผันวรรณยุกต์ที่ในภาษาไทยมาตรฐาน"
+ " มาจากสำเนียงถิ่นนี้ในขณะที่ภาษาไทยสำเนียงอื่นล้วนเหน่อทั้งสิ้น"
+ " คำศัพท์ที่ใช้ในสำเนียงกรุงเทพจำนวนมากได้รับมาจากกลุ่มภาษาจีนเช่นคำว่า โป๊,"
+ " เฮ็ง, อาหมวย, อาซิ่ม ซึ่งมาจากภาษาแต้จิ๋ว และจากภาษาจีนเช่น ถู(涂), ชิ่ว(去"
+ " อ่านว่า\"ชู่\") และคำว่า ทาย(猜 อ่านว่า \"ชาย\") เป็นต้น"
+ " เนื่องจากสำเนียงกรุงเทพได้รับอิทธิพลมาจากภาษาจีนดังนั้นตัวอักษร \"ร\""
- + " มักออกเสียงเหมารวมเป็น \"ล\" หรือคำควบกล่ำบางคำถูกละทิ้งไปด้วยเช่น รู้ เป็น"
- + " ลู้, เรื่อง เป็น เลื่อง หรือ ประเทศ เป็น ปะเทศ"
+ + " มักออกเสียงเหมารวมเป็น \"ล\" หรือคำควบกล่ำบางคำถูกละทิ้งไปด้วยเช่น รู้"
+ + " เป็น ลู้, เรื่อง เป็น เลื่อง หรือ ประเทศ เป็น ปะเทศ"
+ " เป็นต้นสร้างความลำบากให้แก่ต่างชาติที่ต้องการเรียนภาษาไทย"
+ " แต่อย่างไรก็ตามผู้ที่พูดสำเนียงถิ่นนี้ก็สามารถออกอักขระภาษาไทยตามมาตรฐานได"
+ "้อย่างถูกต้องเพียงแต่มักเผลอไม่ค่อยออกเสียง"),
@@ -151,8 +152,7 @@
}
}
- @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 @@
});
}
- @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 @@
}
@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 855bb9a..b7b7e83 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.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.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 @@
});
}
- @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 @@
}
@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 4bd7c4e..9ac36d0 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.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.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 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 @@
});
}
- @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 @@
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 @@
//
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
//
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@Test
+ @Parameters(method = "getData")
public void time_new_byteArray() throws Exception {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
@@ -523,6 +573,7 @@
}
@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 81f9e59..5dd9d6e 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.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 @@
});
}
- @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 @@
}
@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 28ec6de..0a59899 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.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 @@
* 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 @@
});
}
- @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 @@
// 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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 603b182..8da13a9 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.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 437d186..048c50f 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.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 @@
});
}
- @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 @@
}
@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 15c27f2..42b0588 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.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 @@
* 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 @@
&& 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 @@
AES,
};
- @Parameterized.Parameter(0)
- public Mode mMode;
-
public enum Mode {
CBC,
CFB,
@@ -118,23 +112,11 @@
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 @@
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 @@
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 @@
}
@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 a89efff..69197c3 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.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.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 @@
};
@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 @@
}
@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 @@
}
@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 @@
}
@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 4ff3ba5..8391203 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.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.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 @@
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 @@
}
@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 @@
}
@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 6fe9059..80c4487 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.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 @@
});
}
- @Parameterized.Parameter(0)
- public Algorithm mAlgorithm;
-
- @Parameterized.Parameter(1)
- public Implementation mImplementation;
-
public enum Algorithm {
RSA,
DSA,
@@ -66,26 +58,25 @@
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 414764d..c9b0cbe 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.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 @@
*
* @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 279681b..2dc947a 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.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 @@
});
}
- @Parameterized.Parameter(0)
- public Algorithm mAlgorithm;
-
public String mProvider = "AndroidOpenSSL";
private static final int DATA_SIZE = 8192;
@@ -97,44 +94,44 @@
};
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 @@
}
@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 37bd73c..d9d4bb5 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.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 @@
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 8801a56..48450b4 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.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.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 @@
});
}
- @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 @@
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 @@
}
@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 42dc581..5ad62de 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.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.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 @@
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 96e7cb2..a9a0788 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.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.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 @@
});
}
- @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 @@
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 @@
}
@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 @@
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 @@
}
@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 @@
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 02194b1..36db014 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.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 @@
}
}
- @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 @@
});
}
- @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 @@
}
@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 b0d1ee4..5b4423a 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.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 @@
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 @@
});
}
- @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 d2e657a..4d5c792 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.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 @@
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 @@
});
}
- @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 1efc188..c004d95 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.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 @@
}
}
- @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 @@
});
}
- @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 @@
}
@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 b01948a..15516fc 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.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 @@
});
}
- @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 2ea834d..ae1e8bc 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.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.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 @@
});
}
- @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 @@
}
@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 @@
}
@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 b6361ce..80a70a6 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.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 @@
// 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 @@
// 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 @@
// 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/boot/Android.bp b/boot/Android.bp
index 3f14ebc..24ad9de 100644
--- a/boot/Android.bp
+++ b/boot/Android.bp
@@ -120,6 +120,10 @@
apex: "com.android.car.framework",
module: "com.android.car.framework-bootclasspath-fragment",
},
+ {
+ apex: "com.android.virt",
+ module: "com.android.virt-bootclasspath-fragment",
+ },
],
// Additional information needed by hidden api processing.
diff --git a/cmds/uiautomator/OWNERS b/cmds/uiautomator/OWNERS
new file mode 100644
index 0000000..5c7f452
--- /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 3b14be7..24727c5 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 @@
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 ab198b3..488292d 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 @@
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 b1b432b..1bcd343e 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 @@
Tracer.trace();
Display display = getAutomatorBridge().getDefaultDisplay();
Point p = new Point();
- display.getSize(p);
+ display.getRealSize(p);
return p.x;
}
@@ -394,7 +394,7 @@
Tracer.trace();
Display display = getAutomatorBridge().getDefaultDisplay();
Point p = new Point();
- display.getSize(p);
+ display.getRealSize(p);
return p.y;
}
@@ -767,7 +767,7 @@
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 93cb7e4..6f683295 100644
--- a/core/api/current.txt
+++ b/core/api/current.txt
@@ -32238,6 +32238,7 @@
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 @@
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 @@
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 563ab81..9b556d8 100644
--- a/core/api/module-lib-current.txt
+++ b/core/api/module-lib-current.txt
@@ -339,10 +339,6 @@
method public boolean shouldBypassCache(@NonNull Q);
}
- public interface Parcelable {
- method public default int getStability();
- }
-
public class Process {
method public static final int getAppUidForSdkSandboxUid(int);
method public static final boolean isSdkSandboxUid(int);
@@ -352,6 +348,7 @@
}
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);
}
@@ -386,6 +383,7 @@
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 e6555dd..d5e7892 100644
--- a/core/api/system-current.txt
+++ b/core/api/system-current.txt
@@ -3406,6 +3406,7 @@
field public static final String FEATURE_REBOOT_ESCROW = "android.hardware.reboot_escrow";
field public static final String FEATURE_TELEPHONY_CARRIERLOCK = "android.hardware.telephony.carrierlock";
field public static final String FEATURE_TELEPHONY_IMS_SINGLE_REGISTRATION = "android.hardware.telephony.ims.singlereg";
+ field public static final String FEATURE_VIRTUALIZATION_FRAMEWORK = "android.software.virtualization_framework";
field public static final int FLAGS_PERMISSION_RESERVED_PERMISSION_CONTROLLER = -268435456; // 0xf0000000
field public static final int FLAG_PERMISSION_APPLY_RESTRICTION = 16384; // 0x4000
field public static final int FLAG_PERMISSION_AUTO_REVOKED = 131072; // 0x20000
@@ -9554,6 +9555,7 @@
}
public interface Parcelable {
+ method public default int getStability();
field public static final int PARCELABLE_STABILITY_LOCAL = 0; // 0x0
field public static final int PARCELABLE_STABILITY_VINTF = 1; // 0x1
}
@@ -9562,7 +9564,6 @@
ctor public ParcelableHolder(int);
method public int describeContents();
method @Nullable public <T extends android.os.Parcelable> T getParcelable(@NonNull Class<T>);
- method public int getStability();
method public void readFromParcel(@NonNull android.os.Parcel);
method public void setParcelable(@Nullable android.os.Parcelable);
method public void writeToParcel(@NonNull android.os.Parcel, int);
@@ -13553,6 +13554,7 @@
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 3807b50..2f32fa4 100644
--- a/core/java/android/accounts/AbstractAccountAuthenticator.java
+++ b/core/java/android/accounts/AbstractAccountAuthenticator.java
@@ -120,27 +120,27 @@
/**
* 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 c0aebee..7bfb1b5 100644
--- a/core/java/android/app/AutomaticZenRule.java
+++ b/core/java/android/app/AutomaticZenRule.java
@@ -48,6 +48,13 @@
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 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 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 @@
* 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 @@
* Sets the name of this rule.
*/
public void setName(String name) {
- this.name = name;
+ this.name = getTrimmedString(name);
}
/**
@@ -243,7 +252,7 @@
* 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 @@
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 f3fc468..8ec313ec 100644
--- a/core/java/android/app/OWNERS
+++ b/core/java/android/app/OWNERS
@@ -11,6 +11,7 @@
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 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 5388282..bd5d105 100644
--- a/core/java/android/app/SearchableInfo.java
+++ b/core/java/android/app/SearchableInfo.java
@@ -396,6 +396,17 @@
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 bdecca3..8bbddbf 100644
--- a/core/java/android/app/SystemServiceRegistry.java
+++ b/core/java/android/app/SystemServiceRegistry.java
@@ -171,6 +171,7 @@
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 @@
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 16149bb..5b50189 100644
--- a/core/java/android/content/ActivityNotFoundException.java
+++ b/core/java/android/content/ActivityNotFoundException.java
@@ -31,5 +31,4 @@
{
super(name);
}
-};
-
+}
diff --git a/core/java/android/content/Context.java b/core/java/android/content/Context.java
index fce23cf..0735532 100644
--- a/core/java/android/content/Context.java
+++ b/core/java/android/content/Context.java
@@ -5135,6 +5135,14 @@
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 f888813..1b5f64c 100644
--- a/core/java/android/content/integrity/AtomicFormula.java
+++ b/core/java/android/content/integrity/AtomicFormula.java
@@ -261,8 +261,8 @@
}
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 @@
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 a90f6d6..6c53618 100644
--- a/core/java/android/content/pm/PackageManager.java
+++ b/core/java/android/content/pm/PackageManager.java
@@ -189,12 +189,12 @@
@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 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 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;
@@ -2947,6 +2945,18 @@
public static final String FEATURE_OPENGLES_EXTENSION_PACK = "android.hardware.opengles.aep";
/**
+ * Feature for {@link #getSystemAvailableFeatures()} and {@link #hasSystemFeature(String)}.
+ * This feature indicates whether device supports
+ * <a href="https://source.android.com/docs/core/virtualization">Android Virtualization Framework</a>.
+ *
+ * @hide
+ */
+ @SystemApi
+ @SdkConstant(SdkConstantType.FEATURE)
+ public static final String FEATURE_VIRTUALIZATION_FRAMEWORK =
+ "android.software.virtualization_framework";
+
+ /**
* Feature for {@link #getSystemAvailableFeatures} and
* {@link #hasSystemFeature(String, int)}: If this feature is supported, the Vulkan
* implementation on this device is hardware accelerated, and the Vulkan native API will
diff --git a/core/java/android/content/pm/ShortcutInfo.java b/core/java/android/content/pm/ShortcutInfo.java
index 1f83d75..295df5c 100644
--- a/core/java/android/content/pm/ShortcutInfo.java
+++ b/core/java/android/content/pm/ShortcutInfo.java
@@ -50,6 +50,7 @@
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 @@
@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 @@
@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 072be50..41ef6aa 100644
--- a/core/java/android/hardware/CameraInfo.java
+++ b/core/java/android/hardware/CameraInfo.java
@@ -60,4 +60,4 @@
return new CameraInfo[size];
}
};
-};
+}
diff --git a/core/java/android/hardware/CameraStatus.java b/core/java/android/hardware/CameraStatus.java
index 874af29..fa35efb 100644
--- a/core/java/android/hardware/CameraStatus.java
+++ b/core/java/android/hardware/CameraStatus.java
@@ -68,4 +68,4 @@
return new CameraStatus[size];
}
};
-};
+}
diff --git a/core/java/android/hardware/biometrics/CryptoObject.java b/core/java/android/hardware/biometrics/CryptoObject.java
index d415706..267ef36 100644
--- a/core/java/android/hardware/biometrics/CryptoObject.java
+++ b/core/java/android/hardware/biometrics/CryptoObject.java
@@ -118,4 +118,4 @@
}
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 7b6a457..8304796 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.Iterator;
import java.util.LinkedList;
import java.util.List;
+import java.util.Map;
import java.util.TreeMap;
/**
@@ -63,11 +64,11 @@
}
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 621a418..92a2fb6 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 @@
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 4a25177..bbe2319 100644
--- a/core/java/android/hardware/camera2/params/OutputConfiguration.java
+++ b/core/java/android/hardware/camera2/params/OutputConfiguration.java
@@ -1270,7 +1270,8 @@
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 9ce834ca..c01c94c 100644
--- a/core/java/android/hardware/fingerprint/Fingerprint.java
+++ b/core/java/android/hardware/fingerprint/Fingerprint.java
@@ -69,4 +69,4 @@
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 76ee097..5eeb607 100644
--- a/core/java/android/net/netstats/NetworkStatsDataMigrationUtils.java
+++ b/core/java/android/net/netstats/NetworkStatsDataMigrationUtils.java
@@ -53,8 +53,8 @@
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 @@
@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 4bc5b49..0427742 100644
--- a/core/java/android/net/vcn/persistablebundleutils/TunnelConnectionParamsUtils.java
+++ b/core/java/android/net/vcn/persistablebundleutils/TunnelConnectionParamsUtils.java
@@ -53,7 +53,7 @@
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 64c1211..3282d56 100644
--- a/core/java/android/nfc/NfcAdapter.java
+++ b/core/java/android/nfc/NfcAdapter.java
@@ -29,7 +29,6 @@
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 @@
}
/**
- * 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 @@
* @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 @@
*/
@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 @@
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 @@
/** 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 @@
"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 0b56d19..6a42091 100644
--- a/core/java/android/nfc/cardemulation/CardEmulation.java
+++ b/core/java/android/nfc/cardemulation/CardEmulation.java
@@ -22,11 +22,9 @@
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 @@
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 3c92455..48bbf5b6 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 @@
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 0418a4b..b599028 100644
--- a/core/java/android/os/BaseBundle.java
+++ b/core/java/android/os/BaseBundle.java
@@ -438,8 +438,11 @@
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 @@
// 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 6d5c741..3d10661 100644
--- a/core/java/android/os/Binder.java
+++ b/core/java/android/os/Binder.java
@@ -911,11 +911,15 @@
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 6330661..1929a4d 100644
--- a/core/java/android/os/BinderProxy.java
+++ b/core/java/android/os/BinderProxy.java
@@ -536,8 +536,8 @@
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 d84037f..1924dc6 100644
--- a/core/java/android/os/OWNERS
+++ b/core/java/android/os/OWNERS
@@ -70,3 +70,6 @@
# 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 8ffb94b..7e15f07 100644
--- a/core/java/android/os/Parcel.java
+++ b/core/java/android/os/Parcel.java
@@ -562,9 +562,11 @@
*/
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/Parcelable.java b/core/java/android/os/Parcelable.java
index 8a80457..a2b0486 100644
--- a/core/java/android/os/Parcelable.java
+++ b/core/java/android/os/Parcelable.java
@@ -188,7 +188,7 @@
* @return true if this parcelable is stable.
* @hide
*/
- @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
+ @SystemApi(client = SystemApi.Client.PRIVILEGED_APPS)
default @Stability int getStability() {
return PARCELABLE_STABILITY_LOCAL;
}
diff --git a/core/java/android/os/PermissionEnforcer.java b/core/java/android/os/PermissionEnforcer.java
new file mode 100644
index 0000000..221e89a
--- /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 ba5ed43..9ea4278 100644
--- a/core/java/android/os/ServiceManager.java
+++ b/core/java/android/os/ServiceManager.java
@@ -258,12 +258,14 @@
* 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 4965057..726ef4d 100644
--- a/core/java/android/os/Trace.java
+++ b/core/java/android/os/Trace.java
@@ -100,6 +100,7 @@
/** @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 0ffdfc6..4b9f892 100644
--- a/core/java/android/os/UserManager.java
+++ b/core/java/android/os/UserManager.java
@@ -1485,6 +1485,22 @@
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 @@
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 2c382ef..c78fb1a 100644
--- a/core/java/android/security/keymaster/ExportResult.java
+++ b/core/java/android/security/keymaster/ExportResult.java
@@ -61,4 +61,4 @@
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 bd81623..e280bdf 100644
--- a/core/java/android/text/style/AccessibilityURLSpan.java
+++ b/core/java/android/text/style/AccessibilityURLSpan.java
@@ -26,6 +26,7 @@
* 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 1345ddf..d1b9d9f 100644
--- a/core/java/android/util/AndroidException.java
+++ b/core/java/android/util/AndroidException.java
@@ -40,5 +40,5 @@
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
-};
+}
diff --git a/core/java/android/util/AndroidRuntimeException.java b/core/java/android/util/AndroidRuntimeException.java
index 2b824bf..72c34d8b 100644
--- a/core/java/android/util/AndroidRuntimeException.java
+++ b/core/java/android/util/AndroidRuntimeException.java
@@ -34,5 +34,4 @@
public AndroidRuntimeException(Exception cause) {
super(cause);
}
-};
-
+}
diff --git a/core/java/android/util/OWNERS b/core/java/android/util/OWNERS
index d4cf6e6..3772006 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 9fd0ab9..41c171a 100644
--- a/core/java/android/util/Range.java
+++ b/core/java/android/util/Range.java
@@ -356,4 +356,4 @@
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 19de396..44318bb 100644
--- a/core/java/android/util/TypedValue.java
+++ b/core/java/android/util/TypedValue.java
@@ -696,5 +696,5 @@
sb.append("}");
return sb.toString();
}
-};
+}
diff --git a/core/java/android/util/apk/ApkSignatureSchemeV2Verifier.java b/core/java/android/util/apk/ApkSignatureSchemeV2Verifier.java
index c8c1fd4..eb467e0 100644
--- a/core/java/android/util/apk/ApkSignatureSchemeV2Verifier.java
+++ b/core/java/android/util/apk/ApkSignatureSchemeV2Verifier.java
@@ -93,8 +93,9 @@
* 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 @@
break;
}
}
- return;
}
static byte[] getVerityRootHash(String apkPath)
diff --git a/core/java/android/view/CutoutSpecification.java b/core/java/android/view/CutoutSpecification.java
index f8aa934..3fc3b6a 100644
--- a/core/java/android/view/CutoutSpecification.java
+++ b/core/java/android/view/CutoutSpecification.java
@@ -394,7 +394,6 @@
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 ea97995..ff282ba 100644
--- a/core/java/android/view/RemoteAnimationDefinition.java
+++ b/core/java/android/view/RemoteAnimationDefinition.java
@@ -19,6 +19,7 @@
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 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 @@
return 0;
}
- private static final @android.annotation.NonNull Creator<RemoteAnimationAdapterEntry> CREATOR
- = new Creator<RemoteAnimationAdapterEntry>() {
+ 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 createFromParcel(Parcel in) {
- return new RemoteAnimationAdapterEntry(in);
- }
-
- @Override
- public RemoteAnimationAdapterEntry[] newArray(int size) {
- return new RemoteAnimationAdapterEntry[size];
- }
- };
+ @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 5474557..89cb6b2 100644
--- a/core/java/android/webkit/ConsoleMessage.java
+++ b/core/java/android/webkit/ConsoleMessage.java
@@ -68,4 +68,4 @@
public int lineNumber() {
return mLineNumber;
}
-};
+}
diff --git a/core/java/android/webkit/ValueCallback.java b/core/java/android/webkit/ValueCallback.java
index 5c7d97f..3d5bb49 100644
--- a/core/java/android/webkit/ValueCallback.java
+++ b/core/java/android/webkit/ValueCallback.java
@@ -25,4 +25,4 @@
* @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 5e74381..510a92d 100644
--- a/core/java/android/widget/ListView.java
+++ b/core/java/android/widget/ListView.java
@@ -116,9 +116,7 @@
* <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 db15145..e62d5c9 100644
--- a/core/java/android/window/TransitionFilter.java
+++ b/core/java/android/window/TransitionFilter.java
@@ -296,7 +296,7 @@
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 97f4b0f..a21a842 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 @@
/**
* 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 0000000..7571073
--- /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 e290812..1e0b3cc 100644
--- a/core/java/com/android/internal/os/BatteryStatsImpl.java
+++ b/core/java/com/android/internal/os/BatteryStatsImpl.java
@@ -3656,6 +3656,7 @@
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 0a29fc52..eb62cb0 100644
--- a/core/java/com/android/internal/os/BinderCallsStats.java
+++ b/core/java/com/android/internal/os/BinderCallsStats.java
@@ -735,7 +735,7 @@
}
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 e9d55db..1276fb9 100644
--- a/core/java/com/android/internal/os/BinderLatencyObserver.java
+++ b/core/java/com/android/internal/os/BinderLatencyObserver.java
@@ -236,7 +236,7 @@
}
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 2805dcc..0645eb7 100644
--- a/core/java/com/android/internal/os/LooperStats.java
+++ b/core/java/com/android/internal/os/LooperStats.java
@@ -290,7 +290,7 @@
}
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/os/RuntimeInit.java b/core/java/com/android/internal/os/RuntimeInit.java
index 28b98d6..8a9445d 100644
--- a/core/java/com/android/internal/os/RuntimeInit.java
+++ b/core/java/com/android/internal/os/RuntimeInit.java
@@ -16,10 +16,14 @@
package com.android.internal.os;
+import static com.android.internal.os.SafeZipPathValidatorCallback.VALIDATE_ZIP_PATH_FOR_PATH_TRAVERSAL;
+
+import android.annotation.TestApi;
import android.app.ActivityManager;
import android.app.ActivityThread;
import android.app.ApplicationErrorReport;
import android.app.IActivityManager;
+import android.app.compat.CompatChanges;
import android.compat.annotation.UnsupportedAppUsage;
import android.content.type.DefaultMimeMapFactory;
import android.net.TrafficStats;
@@ -36,6 +40,7 @@
import dalvik.system.RuntimeHooks;
import dalvik.system.VMRuntime;
+import dalvik.system.ZipPathValidator;
import libcore.content.type.MimeMap;
@@ -260,10 +265,31 @@
*/
TrafficStats.attachSocketTagger();
+ /*
+ * Initialize the zip path validator callback depending on the targetSdk.
+ */
+ initZipPathValidatorCallback();
+
initialized = true;
}
/**
+ * If targetSDK >= U: set the safe zip path validator callback which disallows dangerous zip
+ * entry names.
+ * Otherwise: clear the callback to the default validation.
+ *
+ * @hide
+ */
+ @TestApi
+ public static void initZipPathValidatorCallback() {
+ if (CompatChanges.isChangeEnabled(VALIDATE_ZIP_PATH_FOR_PATH_TRAVERSAL)) {
+ ZipPathValidator.setCallback(new SafeZipPathValidatorCallback());
+ } else {
+ ZipPathValidator.clearCallback();
+ }
+ }
+
+ /**
* Returns an HTTP user agent of the form
* "Dalvik/1.1.0 (Linux; U; Android Eclair Build/MAIN)".
*/
diff --git a/core/java/com/android/internal/os/SafeZipPathValidatorCallback.java b/core/java/com/android/internal/os/SafeZipPathValidatorCallback.java
new file mode 100644
index 0000000..a6ee108
--- /dev/null
+++ b/core/java/com/android/internal/os/SafeZipPathValidatorCallback.java
@@ -0,0 +1,67 @@
+/*
+ * 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.os;
+
+import android.annotation.NonNull;
+import android.compat.annotation.ChangeId;
+import android.compat.annotation.EnabledSince;
+import android.os.Build;
+
+import dalvik.system.ZipPathValidator;
+
+import java.io.File;
+import java.util.zip.ZipException;
+
+/**
+ * A child implementation of the {@link dalvik.system.ZipPathValidator.Callback} that removes the
+ * risk of zip path traversal vulnerabilities.
+ *
+ * @hide
+ */
+public class SafeZipPathValidatorCallback implements ZipPathValidator.Callback {
+ /**
+ * This change targets zip path traversal vulnerabilities by throwing
+ * {@link java.util.zip.ZipException} if zip path entries contain ".." or start with "/".
+ * <p>
+ * The exception will be thrown in {@link java.util.zip.ZipInputStream#getNextEntry} or
+ * {@link java.util.zip.ZipFile#ZipFile(String)}.
+ * <p>
+ * This validation is enabled for apps with targetSDK >= U.
+ */
+ @ChangeId
+ @EnabledSince(targetSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
+ public static final long VALIDATE_ZIP_PATH_FOR_PATH_TRAVERSAL = 242716250L;
+
+ @Override
+ public void onZipEntryAccess(@NonNull String path) throws ZipException {
+ if (path.startsWith("/")) {
+ throw new ZipException("Invalid zip entry path: " + path);
+ }
+ if (path.contains("..")) {
+ // If the string does contain "..", break it down into its actual name elements to
+ // ensure it actually contains ".." as a name, not just a name like "foo..bar" or even
+ // "foo..", which should be fine.
+ File file = new File(path);
+ while (file != null) {
+ if (file.getName().equals("..")) {
+ throw new ZipException("Invalid zip entry path: " + path);
+ }
+ file = file.getParentFile();
+ }
+ }
+ }
+}
diff --git a/core/java/com/android/internal/security/TEST_MAPPING b/core/java/com/android/internal/security/TEST_MAPPING
index 9a5e90e..803760c 100644
--- a/core/java/com/android/internal/security/TEST_MAPPING
+++ b/core/java/com/android/internal/security/TEST_MAPPING
@@ -1,6 +1,17 @@
{
"presubmit": [
{
+ "name": "FrameworksCoreTests",
+ "options": [
+ {
+ "include-filter": "com.android.internal.security."
+ },
+ {
+ "include-annotation": "android.platform.test.annotations.Presubmit"
+ }
+ ]
+ },
+ {
"name": "ApkVerityTest",
"file_patterns": ["VerityUtils\\.java"]
}
diff --git a/core/java/com/android/internal/security/VerityUtils.java b/core/java/com/android/internal/security/VerityUtils.java
index cb5820f..7f45c09 100644
--- a/core/java/com/android/internal/security/VerityUtils.java
+++ b/core/java/com/android/internal/security/VerityUtils.java
@@ -23,10 +23,28 @@
import android.system.OsConstants;
import android.util.Slog;
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.org.bouncycastle.asn1.nist.NISTObjectIdentifiers;
+import com.android.internal.org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
+import com.android.internal.org.bouncycastle.cms.CMSException;
+import com.android.internal.org.bouncycastle.cms.CMSProcessableByteArray;
+import com.android.internal.org.bouncycastle.cms.CMSSignedData;
+import com.android.internal.org.bouncycastle.cms.SignerInformation;
+import com.android.internal.org.bouncycastle.cms.SignerInformationVerifier;
+import com.android.internal.org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder;
+import com.android.internal.org.bouncycastle.operator.OperatorCreationException;
+
import java.io.File;
import java.io.IOException;
+import java.io.InputStream;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
+import java.security.cert.CertificateException;
+import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
/** Provides fsverity related operations. */
public abstract class VerityUtils {
@@ -91,6 +109,91 @@
}
/**
+ * Verifies the signature over the fs-verity digest using the provided certificate.
+ *
+ * This method should only be used by any existing fs-verity use cases that require
+ * PKCS#7 signature verification, if backward compatibility is necessary.
+ *
+ * Since PKCS#7 is too flexible, for the current specific need, only specific configuration
+ * will be accepted:
+ * <ul>
+ * <li>Must use SHA256 as the digest algorithm
+ * <li>Must use rsaEncryption as signature algorithm
+ * <li>Must be detached / without content
+ * <li>Must not include any signed or unsigned attributes
+ * </ul>
+ *
+ * It is up to the caller to provide an appropriate/trusted certificate.
+ *
+ * @param signatureBlock byte array of a PKCS#7 detached signature
+ * @param digest fs-verity digest with the common configuration using sha256
+ * @param derCertInputStream an input stream of a X.509 certificate in DER
+ * @return whether the verification succeeds
+ */
+ public static boolean verifyPkcs7DetachedSignature(@NonNull byte[] signatureBlock,
+ @NonNull byte[] digest, @NonNull InputStream derCertInputStream) {
+ if (digest.length != 32) {
+ Slog.w(TAG, "Only sha256 is currently supported");
+ return false;
+ }
+
+ try {
+ CMSSignedData signedData = new CMSSignedData(
+ new CMSProcessableByteArray(toFormattedDigest(digest)),
+ signatureBlock);
+
+ if (!signedData.isDetachedSignature()) {
+ Slog.w(TAG, "Expect only detached siganture");
+ return false;
+ }
+ if (!signedData.getCertificates().getMatches(null).isEmpty()) {
+ Slog.w(TAG, "Expect no certificate in signature");
+ return false;
+ }
+ if (!signedData.getCRLs().getMatches(null).isEmpty()) {
+ Slog.w(TAG, "Expect no CRL in signature");
+ return false;
+ }
+
+ X509Certificate trustedCert = (X509Certificate) CertificateFactory.getInstance("X.509")
+ .generateCertificate(derCertInputStream);
+ SignerInformationVerifier verifier = new JcaSimpleSignerInfoVerifierBuilder()
+ .build(trustedCert);
+
+ // Verify any signature with the trusted certificate.
+ for (SignerInformation si : signedData.getSignerInfos().getSigners()) {
+ // To be the most strict while dealing with the complicated PKCS#7 signature, reject
+ // everything we don't need.
+ if (si.getSignedAttributes() != null && si.getSignedAttributes().size() > 0) {
+ Slog.w(TAG, "Unexpected signed attributes");
+ return false;
+ }
+ if (si.getUnsignedAttributes() != null && si.getUnsignedAttributes().size() > 0) {
+ Slog.w(TAG, "Unexpected unsigned attributes");
+ return false;
+ }
+ if (!NISTObjectIdentifiers.id_sha256.getId().equals(si.getDigestAlgOID())) {
+ Slog.w(TAG, "Unsupported digest algorithm OID: " + si.getDigestAlgOID());
+ return false;
+ }
+ if (!PKCSObjectIdentifiers.rsaEncryption.getId().equals(si.getEncryptionAlgOID())) {
+ Slog.w(TAG, "Unsupported encryption algorithm OID: "
+ + si.getEncryptionAlgOID());
+ return false;
+ }
+
+ if (si.verify(verifier)) {
+ return true;
+ }
+ }
+ return false;
+ } catch (CertificateException | CMSException | OperatorCreationException e) {
+ Slog.w(TAG, "Error occurred during the PKCS#7 signature verification", e);
+ }
+ return false;
+ }
+
+ /**
* Returns fs-verity digest for the file if enabled, otherwise returns null. The digest is a
* hash of root hash of fs-verity's Merkle tree with extra metadata.
*
@@ -110,6 +213,19 @@
return result;
}
+ /** @hide */
+ @VisibleForTesting
+ public static byte[] toFormattedDigest(byte[] digest) {
+ // Construct fsverity_formatted_digest used in fs-verity's built-in signature verification.
+ ByteBuffer buffer = ByteBuffer.allocate(12 + digest.length); // struct size + sha256 size
+ buffer.order(ByteOrder.LITTLE_ENDIAN);
+ buffer.put("FSVerity".getBytes(StandardCharsets.US_ASCII));
+ buffer.putShort((short) 1); // FS_VERITY_HASH_ALG_SHA256
+ buffer.putShort((short) digest.length);
+ buffer.put(digest);
+ return buffer.array();
+ }
+
private static native int enableFsverityNative(@NonNull String filePath,
@NonNull byte[] pkcs7Signature);
private static native int measureFsverityNative(@NonNull String filePath,
diff --git a/core/java/com/android/internal/util/LatencyTracker.java b/core/java/com/android/internal/util/LatencyTracker.java
index ca40a40..ab42f87 100644
--- a/core/java/com/android/internal/util/LatencyTracker.java
+++ b/core/java/com/android/internal/util/LatencyTracker.java
@@ -413,7 +413,7 @@
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 32ce0fe..1ae1307 100644
--- a/core/java/com/android/internal/view/BaseSurfaceHolder.java
+++ b/core/java/com/android/internal/view/BaseSurfaceHolder.java
@@ -241,4 +241,4 @@
mSurfaceFrame.right = width;
mSurfaceFrame.bottom = height;
}
-};
+}
diff --git a/core/jni/Android.bp b/core/jni/Android.bp
index e032fa2..7cd7d29 100644
--- a/core/jni/Android.bp
+++ b/core/jni/Android.bp
@@ -34,6 +34,8 @@
"-Wno-error=deprecated-declarations",
"-Wunused",
"-Wunreachable-code",
+
+ "-DNAMESPACE_FOR_HASH_FUNCTIONS=farmhash",
],
cppflags: ["-Wno-conversion-null"],
@@ -211,6 +213,7 @@
"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 @@
"libscrypt_static",
"libstatssocket_lazy",
"libskia",
+ "libtextclassifier_hash_static",
],
shared_libs: [
@@ -326,6 +330,7 @@
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 6a051c3..949f363 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_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 @@
// 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 @@
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 9f88f33..01837f4 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 @@
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 @@
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 @@
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 0eb999f..a50c011 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 @@
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 0000000..d4a8c23
--- /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 689620c..f244ce4 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 b754100..8697acd 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 1f71bf9..596d89a 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 0000000..0992440
--- /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 1cf4302..372bca4 100644
--- a/core/tests/benchmarks/src/android/os/ParcelableBenchmark.java
+++ b/core/tests/benchmarks/src/android/os/ParcelableBenchmark.java
@@ -88,6 +88,7 @@
}
}
+ @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 04952bd..e2cdbf3 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 0000000..282fdad
--- /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 0862c05..7e24aef 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 d505492..86e95832 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.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 @@
@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 a3bda8b..0fa5ec3 100644
--- a/core/tests/coretests/src/android/os/BundleTest.java
+++ b/core/tests/coretests/src/android/os/BundleTest.java
@@ -409,6 +409,69 @@
}
@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 00b3693..bbf9f3c 100644
--- a/core/tests/coretests/src/android/widget/RemoteViewsTest.java
+++ b/core/tests/coretests/src/android/widget/RemoteViewsTest.java
@@ -128,6 +128,7 @@
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 @@
}
}
+ @SuppressWarnings("ReturnValueIgnored")
@Test
public void nestedAddViews() {
RemoteViews views = new RemoteViews(mPackage, R.layout.remote_views_test);
@@ -509,6 +511,7 @@
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 82b2bf4..8207c9e 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 @@
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 5af7376..7bd53b9 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 @@
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 @@
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/os/SafeZipPathValidatorCallbackTest.java b/core/tests/coretests/src/com/android/internal/os/SafeZipPathValidatorCallbackTest.java
new file mode 100644
index 0000000..c540a15
--- /dev/null
+++ b/core/tests/coretests/src/com/android/internal/os/SafeZipPathValidatorCallbackTest.java
@@ -0,0 +1,244 @@
+/*
+ * 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.os;
+
+import static org.junit.Assert.assertThrows;
+
+import android.compat.testing.PlatformCompatChangeRule;
+
+import androidx.test.runner.AndroidJUnit4;
+
+import libcore.junit.util.compat.CoreCompatChangeRule.DisableCompatChanges;
+import libcore.junit.util.compat.CoreCompatChangeRule.EnableCompatChanges;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TestRule;
+import org.junit.runner.RunWith;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipException;
+import java.util.zip.ZipFile;
+import java.util.zip.ZipInputStream;
+import java.util.zip.ZipOutputStream;
+
+/**
+ * Test SafeZipPathCallback.
+ */
+@RunWith(AndroidJUnit4.class)
+public class SafeZipPathValidatorCallbackTest {
+ @Rule
+ public TestRule mCompatChangeRule = new PlatformCompatChangeRule();
+
+ @Before
+ public void setUp() {
+ RuntimeInit.initZipPathValidatorCallback();
+ }
+
+ @Test
+ @EnableCompatChanges({SafeZipPathValidatorCallback.VALIDATE_ZIP_PATH_FOR_PATH_TRAVERSAL})
+ public void testNewZipFile_whenZipFileHasDangerousEntriesAndChangeEnabled_throws()
+ throws Exception {
+ final String[] dangerousEntryNames = {
+ "../foo.bar",
+ "foo/../bar.baz",
+ "foo/../../bar.baz",
+ "foo.bar/..",
+ "foo.bar/../",
+ "..",
+ "../",
+ "/foo",
+ };
+ for (String entryName : dangerousEntryNames) {
+ final File tempFile = File.createTempFile("smdc", "zip");
+ try {
+ writeZipFileOutputStreamWithEmptyEntry(tempFile, entryName);
+
+ assertThrows(
+ "ZipException expected for entry: " + entryName,
+ ZipException.class,
+ () -> {
+ new ZipFile(tempFile);
+ });
+ } finally {
+ tempFile.delete();
+ }
+ }
+ }
+
+ @Test
+ @EnableCompatChanges({SafeZipPathValidatorCallback.VALIDATE_ZIP_PATH_FOR_PATH_TRAVERSAL})
+ public void
+ testZipInputStreamGetNextEntry_whenZipFileHasDangerousEntriesAndChangeEnabled_throws()
+ throws Exception {
+ final String[] dangerousEntryNames = {
+ "../foo.bar",
+ "foo/../bar.baz",
+ "foo/../../bar.baz",
+ "foo.bar/..",
+ "foo.bar/../",
+ "..",
+ "../",
+ "/foo",
+ };
+ for (String entryName : dangerousEntryNames) {
+ byte[] badZipBytes = getZipBytesFromZipOutputStreamWithEmptyEntry(entryName);
+ try (ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(badZipBytes))) {
+ assertThrows(
+ "ZipException expected for entry: " + entryName,
+ ZipException.class,
+ () -> {
+ zis.getNextEntry();
+ });
+ }
+ }
+ }
+
+ @Test
+ @EnableCompatChanges({SafeZipPathValidatorCallback.VALIDATE_ZIP_PATH_FOR_PATH_TRAVERSAL})
+ public void testNewZipFile_whenZipFileHasNormalEntriesAndChangeEnabled_doesNotThrow()
+ throws Exception {
+ final String[] normalEntryNames = {
+ "foo", "foo.bar", "foo..bar",
+ };
+ for (String entryName : normalEntryNames) {
+ final File tempFile = File.createTempFile("smdc", "zip");
+ try {
+ writeZipFileOutputStreamWithEmptyEntry(tempFile, entryName);
+ try {
+ new ZipFile((tempFile));
+ } catch (ZipException e) {
+ throw new AssertionError("ZipException not expected for entry: " + entryName);
+ }
+ } finally {
+ tempFile.delete();
+ }
+ }
+ }
+
+ @Test
+ @DisableCompatChanges({SafeZipPathValidatorCallback.VALIDATE_ZIP_PATH_FOR_PATH_TRAVERSAL})
+ public void
+ testZipInputStreamGetNextEntry_whenZipFileHasNormalEntriesAndChangeEnabled_doesNotThrow()
+ throws Exception {
+ final String[] normalEntryNames = {
+ "foo", "foo.bar", "foo..bar",
+ };
+ for (String entryName : normalEntryNames) {
+ byte[] zipBytes = getZipBytesFromZipOutputStreamWithEmptyEntry(entryName);
+ try {
+ ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(zipBytes));
+ zis.getNextEntry();
+ } catch (ZipException e) {
+ throw new AssertionError("ZipException not expected for entry: " + entryName);
+ }
+ }
+ }
+
+ @Test
+ @DisableCompatChanges({SafeZipPathValidatorCallback.VALIDATE_ZIP_PATH_FOR_PATH_TRAVERSAL})
+ public void
+ testNewZipFile_whenZipFileHasNormalAndDangerousEntriesAndChangeDisabled_doesNotThrow()
+ throws Exception {
+ final String[] entryNames = {
+ "../foo.bar",
+ "foo/../bar.baz",
+ "foo/../../bar.baz",
+ "foo.bar/..",
+ "foo.bar/../",
+ "..",
+ "../",
+ "/foo",
+ "foo",
+ "foo.bar",
+ "foo..bar",
+ };
+ for (String entryName : entryNames) {
+ final File tempFile = File.createTempFile("smdc", "zip");
+ try {
+ writeZipFileOutputStreamWithEmptyEntry(tempFile, entryName);
+ try {
+ new ZipFile((tempFile));
+ } catch (ZipException e) {
+ throw new AssertionError("ZipException not expected for entry: " + entryName);
+ }
+ } finally {
+ tempFile.delete();
+ }
+ }
+ }
+
+ @Test
+ @DisableCompatChanges({SafeZipPathValidatorCallback.VALIDATE_ZIP_PATH_FOR_PATH_TRAVERSAL})
+ public void
+ testZipInputStreamGetNextEntry_whenZipFileHasNormalAndDangerousEntriesAndChangeDisabled_doesNotThrow()
+ throws Exception {
+ final String[] entryNames = {
+ "../foo.bar",
+ "foo/../bar.baz",
+ "foo/../../bar.baz",
+ "foo.bar/..",
+ "foo.bar/../",
+ "..",
+ "../",
+ "/foo",
+ "foo",
+ "foo.bar",
+ "foo..bar",
+ };
+ for (String entryName : entryNames) {
+ byte[] zipBytes = getZipBytesFromZipOutputStreamWithEmptyEntry(entryName);
+ try {
+ ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(zipBytes));
+ zis.getNextEntry();
+ } catch (ZipException e) {
+ throw new AssertionError("ZipException not expected for entry: " + entryName);
+ }
+ }
+ }
+
+ private void writeZipFileOutputStreamWithEmptyEntry(File tempFile, String entryName)
+ throws IOException {
+ FileOutputStream tempFileStream = new FileOutputStream(tempFile);
+ writeZipOutputStreamWithEmptyEntry(tempFileStream, entryName);
+ tempFileStream.close();
+ }
+
+ private byte[] getZipBytesFromZipOutputStreamWithEmptyEntry(String entryName)
+ throws IOException {
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ writeZipOutputStreamWithEmptyEntry(bos, entryName);
+ return bos.toByteArray();
+ }
+
+ private void writeZipOutputStreamWithEmptyEntry(OutputStream os, String entryName)
+ throws IOException {
+ ZipOutputStream zos = new ZipOutputStream(os);
+ ZipEntry entry = new ZipEntry(entryName);
+ zos.putNextEntry(entry);
+ zos.write(new byte[2]);
+ zos.closeEntry();
+ zos.close();
+ }
+}
diff --git a/core/tests/coretests/src/com/android/internal/security/ContentSignerWrapper.java b/core/tests/coretests/src/com/android/internal/security/ContentSignerWrapper.java
new file mode 100644
index 0000000..0254afe
--- /dev/null
+++ b/core/tests/coretests/src/com/android/internal/security/ContentSignerWrapper.java
@@ -0,0 +1,46 @@
+/*
+ * 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.security;
+
+import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
+import org.bouncycastle.operator.ContentSigner;
+
+import java.io.OutputStream;
+
+/** A wrapper class of ContentSigner */
+class ContentSignerWrapper implements ContentSigner {
+ private final ContentSigner mSigner;
+
+ ContentSignerWrapper(ContentSigner wrapped) {
+ mSigner = wrapped;
+ }
+
+ @Override
+ public AlgorithmIdentifier getAlgorithmIdentifier() {
+ return mSigner.getAlgorithmIdentifier();
+ }
+
+ @Override
+ public OutputStream getOutputStream() {
+ return mSigner.getOutputStream();
+ }
+
+ @Override
+ public byte[] getSignature() {
+ return mSigner.getSignature();
+ }
+}
diff --git a/core/tests/coretests/src/com/android/internal/security/OWNERS b/core/tests/coretests/src/com/android/internal/security/OWNERS
new file mode 100644
index 0000000..4f4d8d7
--- /dev/null
+++ b/core/tests/coretests/src/com/android/internal/security/OWNERS
@@ -0,0 +1,3 @@
+# Bug component: 36824
+
+per-file VerityUtilsTest.java = file:platform/system/security:/fsverity/OWNERS
diff --git a/core/tests/coretests/src/com/android/internal/security/VerityUtilsTest.java b/core/tests/coretests/src/com/android/internal/security/VerityUtilsTest.java
new file mode 100644
index 0000000..d1d8018
--- /dev/null
+++ b/core/tests/coretests/src/com/android/internal/security/VerityUtilsTest.java
@@ -0,0 +1,334 @@
+/*
+ * 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.security;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import android.platform.test.annotations.Presubmit;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
+import org.bouncycastle.asn1.ASN1Encoding;
+import org.bouncycastle.asn1.ASN1ObjectIdentifier;
+import org.bouncycastle.asn1.nist.NISTObjectIdentifiers;
+import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers;
+import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
+import org.bouncycastle.asn1.x500.X500Name;
+import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
+import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
+import org.bouncycastle.cert.X509CertificateHolder;
+import org.bouncycastle.cert.X509v3CertificateBuilder;
+import org.bouncycastle.cms.CMSException;
+import org.bouncycastle.cms.CMSProcessableByteArray;
+import org.bouncycastle.cms.CMSSignedData;
+import org.bouncycastle.cms.CMSSignedDataGenerator;
+import org.bouncycastle.cms.SignerInfoGenerator;
+import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder;
+import org.bouncycastle.operator.ContentSigner;
+import org.bouncycastle.operator.DigestCalculator;
+import org.bouncycastle.operator.OperatorCreationException;
+import org.bouncycastle.operator.bc.BcDigestCalculatorProvider;
+import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.math.BigInteger;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Date;
+
+@Presubmit
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class VerityUtilsTest {
+ private static final byte[] SAMPLE_DIGEST = "12345678901234567890123456789012".getBytes();
+ private static final byte[] FORMATTED_SAMPLE_DIGEST = toFormattedDigest(SAMPLE_DIGEST);
+
+ KeyPair mKeyPair;
+ ContentSigner mContentSigner;
+ X509CertificateHolder mCertificateHolder;
+ byte[] mCertificateDerEncoded;
+
+ @Before
+ public void setUp() throws Exception {
+ mKeyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
+ mContentSigner = newFsverityContentSigner(mKeyPair.getPrivate());
+ mCertificateHolder =
+ newX509CertificateHolder(mContentSigner, mKeyPair.getPublic(), "Someone");
+ mCertificateDerEncoded = mCertificateHolder.getEncoded();
+ }
+
+ @Test
+ public void testOnlyAcceptCorrectDigest() throws Exception {
+ byte[] pkcs7Signature =
+ generatePkcs7Signature(mContentSigner, mCertificateHolder, FORMATTED_SAMPLE_DIGEST);
+
+ byte[] anotherDigest = Arrays.copyOf(SAMPLE_DIGEST, SAMPLE_DIGEST.length);
+ anotherDigest[0] ^= (byte) 1;
+
+ assertTrue(verifySignature(pkcs7Signature, SAMPLE_DIGEST, mCertificateDerEncoded));
+ assertFalse(verifySignature(pkcs7Signature, anotherDigest, mCertificateDerEncoded));
+ }
+
+ @Test
+ public void testDigestWithWrongSize() throws Exception {
+ byte[] pkcs7Signature =
+ generatePkcs7Signature(mContentSigner, mCertificateHolder, FORMATTED_SAMPLE_DIGEST);
+ assertTrue(verifySignature(pkcs7Signature, SAMPLE_DIGEST, mCertificateDerEncoded));
+
+ byte[] digestTooShort = Arrays.copyOfRange(SAMPLE_DIGEST, 0, SAMPLE_DIGEST.length - 1);
+ assertFalse(verifySignature(pkcs7Signature, digestTooShort, mCertificateDerEncoded));
+
+ byte[] digestTooLong = Arrays.copyOfRange(SAMPLE_DIGEST, 0, SAMPLE_DIGEST.length + 1);
+ assertFalse(verifySignature(pkcs7Signature, digestTooLong, mCertificateDerEncoded));
+ }
+
+ @Test
+ public void testOnlyAcceptGoodSignature() throws Exception {
+ byte[] pkcs7Signature =
+ generatePkcs7Signature(mContentSigner, mCertificateHolder, FORMATTED_SAMPLE_DIGEST);
+
+ byte[] anotherDigest = Arrays.copyOf(SAMPLE_DIGEST, SAMPLE_DIGEST.length);
+ anotherDigest[0] ^= (byte) 1;
+ byte[] anotherPkcs7Signature =
+ generatePkcs7Signature(
+ mContentSigner, mCertificateHolder, toFormattedDigest(anotherDigest));
+
+ assertTrue(verifySignature(pkcs7Signature, SAMPLE_DIGEST, mCertificateDerEncoded));
+ assertFalse(verifySignature(anotherPkcs7Signature, SAMPLE_DIGEST, mCertificateDerEncoded));
+ }
+
+ @Test
+ public void testOnlyValidCertCanVerify() throws Exception {
+ byte[] pkcs7Signature =
+ generatePkcs7Signature(mContentSigner, mCertificateHolder, FORMATTED_SAMPLE_DIGEST);
+
+ var wrongKeyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
+ var wrongContentSigner = newFsverityContentSigner(wrongKeyPair.getPrivate());
+ var wrongCertificateHolder =
+ newX509CertificateHolder(wrongContentSigner, wrongKeyPair.getPublic(), "Not Me");
+ byte[] wrongCertificateDerEncoded = wrongCertificateHolder.getEncoded();
+
+ assertFalse(verifySignature(pkcs7Signature, SAMPLE_DIGEST, wrongCertificateDerEncoded));
+ }
+
+ @Test
+ public void testRejectSignatureWithContent() throws Exception {
+ CMSSignedDataGenerator generator =
+ newFsveritySignedDataGenerator(mContentSigner, mCertificateHolder);
+ byte[] pkcs7SignatureNonDetached =
+ generatePkcs7SignatureInternal(
+ generator, FORMATTED_SAMPLE_DIGEST, /* encapsulate */ true);
+
+ assertFalse(
+ verifySignature(pkcs7SignatureNonDetached, SAMPLE_DIGEST, mCertificateDerEncoded));
+ }
+
+ @Test
+ public void testRejectSignatureWithCertificate() throws Exception {
+ CMSSignedDataGenerator generator =
+ newFsveritySignedDataGenerator(mContentSigner, mCertificateHolder);
+ generator.addCertificate(mCertificateHolder);
+ byte[] pkcs7Signature =
+ generatePkcs7SignatureInternal(
+ generator, FORMATTED_SAMPLE_DIGEST, /* encapsulate */ false);
+
+ assertFalse(
+ verifySignature(pkcs7Signature, SAMPLE_DIGEST, mCertificateDerEncoded));
+ }
+
+ @Ignore("No easy way to construct test data")
+ @Test
+ public void testRejectSignatureWithCRL() throws Exception {
+ CMSSignedDataGenerator generator =
+ newFsveritySignedDataGenerator(mContentSigner, mCertificateHolder);
+
+ // The current bouncycastle version does not have an easy way to generate a CRL.
+ // TODO: enable the test once this is doable, e.g. with X509v2CRLBuilder.
+ // generator.addCRL(new X509CRLHolder(CertificateList.getInstance(new DERSequence(...))));
+ byte[] pkcs7Signature =
+ generatePkcs7SignatureInternal(
+ generator, FORMATTED_SAMPLE_DIGEST, /* encapsulate */ false);
+
+ assertFalse(
+ verifySignature(pkcs7Signature, SAMPLE_DIGEST, mCertificateDerEncoded));
+ }
+
+ @Test
+ public void testRejectUnsupportedSignatureAlgorithms() throws Exception {
+ var contentSigner = newFsverityContentSigner(mKeyPair.getPrivate(), "MD5withRSA", null);
+ var certificateHolder =
+ newX509CertificateHolder(contentSigner, mKeyPair.getPublic(), "Someone");
+ byte[] pkcs7Signature =
+ generatePkcs7Signature(contentSigner, certificateHolder, FORMATTED_SAMPLE_DIGEST);
+
+ assertFalse(verifySignature(pkcs7Signature, SAMPLE_DIGEST, certificateHolder.getEncoded()));
+ }
+
+ @Test
+ public void testRejectUnsupportedDigestAlgorithm() throws Exception {
+ CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
+ generator.addSignerInfoGenerator(
+ newSignerInfoGenerator(
+ mContentSigner,
+ mCertificateHolder,
+ OIWObjectIdentifiers.idSHA1,
+ true)); // directSignature
+ byte[] pkcs7Signature =
+ generatePkcs7SignatureInternal(
+ generator, FORMATTED_SAMPLE_DIGEST, /* encapsulate */ false);
+
+ assertFalse(verifySignature(pkcs7Signature, SAMPLE_DIGEST, mCertificateDerEncoded));
+ }
+
+ @Test
+ public void testRejectAnySignerInfoAttributes() throws Exception {
+ var generator = new CMSSignedDataGenerator();
+ generator.addSignerInfoGenerator(
+ newSignerInfoGenerator(
+ mContentSigner,
+ mCertificateHolder,
+ NISTObjectIdentifiers.id_sha256,
+ false)); // directSignature
+ byte[] pkcs7Signature =
+ generatePkcs7SignatureInternal(
+ generator, FORMATTED_SAMPLE_DIGEST, /* encapsulate */ false);
+
+ assertFalse(verifySignature(pkcs7Signature, SAMPLE_DIGEST, mCertificateDerEncoded));
+ }
+
+ private static boolean verifySignature(
+ byte[] pkcs7Signature, byte[] fsverityDigest, byte[] certificateDerEncoded) {
+ return VerityUtils.verifyPkcs7DetachedSignature(
+ pkcs7Signature, fsverityDigest, new ByteArrayInputStream(certificateDerEncoded));
+ }
+
+ private static byte[] toFormattedDigest(byte[] digest) {
+ return VerityUtils.toFormattedDigest(digest);
+ }
+
+ private static byte[] generatePkcs7Signature(
+ ContentSigner contentSigner, X509CertificateHolder certificateHolder, byte[] signedData)
+ throws IOException, CMSException, OperatorCreationException {
+ CMSSignedDataGenerator generator =
+ newFsveritySignedDataGenerator(contentSigner, certificateHolder);
+ return generatePkcs7SignatureInternal(generator, signedData, /* encapsulate */ false);
+ }
+
+ private static byte[] generatePkcs7SignatureInternal(
+ CMSSignedDataGenerator generator, byte[] signedData, boolean encapsulate)
+ throws IOException, CMSException, OperatorCreationException {
+ CMSSignedData cmsSignedData =
+ generator.generate(new CMSProcessableByteArray(signedData), encapsulate);
+ return cmsSignedData.toASN1Structure().getEncoded(ASN1Encoding.DL);
+ }
+
+ private static CMSSignedDataGenerator newFsveritySignedDataGenerator(
+ ContentSigner contentSigner, X509CertificateHolder certificateHolder)
+ throws IOException, CMSException, OperatorCreationException {
+ var generator = new CMSSignedDataGenerator();
+ generator.addSignerInfoGenerator(
+ newSignerInfoGenerator(
+ contentSigner,
+ certificateHolder,
+ NISTObjectIdentifiers.id_sha256,
+ true)); // directSignature
+ return generator;
+ }
+
+ private static SignerInfoGenerator newSignerInfoGenerator(
+ ContentSigner contentSigner,
+ X509CertificateHolder certificateHolder,
+ ASN1ObjectIdentifier digestAlgorithmId,
+ boolean directSignature)
+ throws IOException, CMSException, OperatorCreationException {
+ var provider =
+ new BcDigestCalculatorProvider() {
+ /**
+ * Allow the caller to override the digest algorithm, especially when the
+ * default does not work (i.e. BcDigestCalculatorProvider could return null).
+ *
+ * <p>For example, the current fs-verity signature has to use rsaEncryption for
+ * the signature algorithm, but BcDigestCalculatorProvider will return null,
+ * thus we need a way to override.
+ *
+ * <p>TODO: After bouncycastle 1.70, we can remove this override and just use
+ * {@code JcaSignerInfoGeneratorBuilder#setContentDigest}.
+ */
+ @Override
+ public DigestCalculator get(AlgorithmIdentifier algorithm)
+ throws OperatorCreationException {
+ return super.get(new AlgorithmIdentifier(digestAlgorithmId));
+ }
+ };
+ var builder =
+ new JcaSignerInfoGeneratorBuilder(provider).setDirectSignature(directSignature);
+ return builder.build(contentSigner, certificateHolder);
+ }
+
+ private static ContentSigner newFsverityContentSigner(PrivateKey privateKey)
+ throws OperatorCreationException {
+ // fs-verity expects the signature to have rsaEncryption as the exact algorithm, so
+ // override the default.
+ return newFsverityContentSigner(
+ privateKey, "SHA256withRSA", PKCSObjectIdentifiers.rsaEncryption);
+ }
+
+ private static ContentSigner newFsverityContentSigner(
+ PrivateKey privateKey,
+ String signatureAlgorithm,
+ ASN1ObjectIdentifier signatureAlgorithmIdOverride)
+ throws OperatorCreationException {
+ if (signatureAlgorithmIdOverride != null) {
+ return new ContentSignerWrapper(
+ new JcaContentSignerBuilder(signatureAlgorithm).build(privateKey)) {
+ @Override
+ public AlgorithmIdentifier getAlgorithmIdentifier() {
+ return new AlgorithmIdentifier(signatureAlgorithmIdOverride);
+ }
+ };
+ } else {
+ return new JcaContentSignerBuilder(signatureAlgorithm).build(privateKey);
+ }
+ }
+
+ private static X509CertificateHolder newX509CertificateHolder(
+ ContentSigner contentSigner, PublicKey publicKey, String name) {
+ // Time doesn't really matter, as we only care about the key.
+ Instant now = Instant.now();
+
+ return new X509v3CertificateBuilder(
+ new X500Name("CN=Issuer " + name),
+ /* serial= */ BigInteger.valueOf(now.getEpochSecond()),
+ new Date(now.minus(Duration.ofDays(1)).toEpochMilli()),
+ new Date(now.plus(Duration.ofDays(1)).toEpochMilli()),
+ new X500Name("CN=Subject " + name),
+ SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()))
+ .build(contentSigner);
+ }
+}
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 6c50bce..8b30828 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 @@
}
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 41b8956f..a226325 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 @@
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 c53f4cc..1581abb 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 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 @@
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 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 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 8706a68..42e3046 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 @@
*/
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 @@
*/
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 74cad1a..b170869 100644
--- a/graphics/java/android/graphics/drawable/RippleDrawable.java
+++ b/graphics/java/android/graphics/drawable/RippleDrawable.java
@@ -758,7 +758,7 @@
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 4065bd1..e25ee90 100644
--- a/graphics/java/android/graphics/drawable/VectorDrawable.java
+++ b/graphics/java/android/graphics/drawable/VectorDrawable.java
@@ -60,7 +60,7 @@
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 @@
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 @@
}
};
- 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 @@
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 @@
}
};
- 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 dbd918e..6245598 100644
--- a/keystore/java/android/security/keystore/KeyProperties.java
+++ b/keystore/java/android/security/keystore/KeyProperties.java
@@ -30,6 +30,7 @@
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 @@
}
/**
+ * @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 5216a90..ace2053 100644
--- a/keystore/java/android/security/keystore2/AndroidKeyStoreECDSASignatureSpi.java
+++ b/keystore/java/android/security/keystore2/AndroidKeyStoreECDSASignatureSpi.java
@@ -203,6 +203,11 @@
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 9d424e9..f05cdc5 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.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 @@
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 0000000..7237d2b
--- /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 54d62ed..978ad8a 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 @@
}
@Override
- public @Nullable SplashScreenView get() {
+ @Nullable
+ public SplashScreenView get() {
synchronized (this) {
while (!mIsViewSet) {
try {
@@ -690,7 +691,7 @@
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 @@
// 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 f4efc37..1c28c3d 100644
--- a/libs/WindowManager/Shell/tests/OWNERS
+++ b/libs/WindowManager/Shell/tests/OWNERS
@@ -6,3 +6,4 @@
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 58fc5bb..a1385f2 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 @@
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 @@
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 @@
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 15be80c..d1cfd03 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 @@
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 @@
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 @@
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 ad9aa6c..33f7935 100644
--- a/libs/hwui/Android.bp
+++ b/libs/hwui/Android.bp
@@ -674,6 +674,7 @@
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 ef5eacb..b656b6a 100644
--- a/libs/hwui/AutoBackendTextureRelease.cpp
+++ b/libs/hwui/AutoBackendTextureRelease.cpp
@@ -32,9 +32,17 @@
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 @@
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 c9bb767..f0eb2a8 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 @@
// 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 507d3dc..9e17b9e 100644
--- a/libs/hwui/pipeline/skia/RenderNodeDrawable.cpp
+++ b/libs/hwui/pipeline/skia/RenderNodeDrawable.cpp
@@ -224,10 +224,10 @@
// 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 5092675..fcaa745 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 @@
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 0000000..2ec78a4
--- /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 30fae1d..c3e605e 100644
--- a/media/java/android/media/AudioManager.java
+++ b/media/java/android/media/AudioManager.java
@@ -2325,10 +2325,9 @@
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 @@
// 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 @@
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 ca175b4..0f962f9 100644
--- a/media/java/android/media/AudioMetadata.java
+++ b/media/java/android/media/AudioMetadata.java
@@ -30,6 +30,7 @@
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 @@
// 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 @@
* 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 @@
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 @@
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 @@
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 @@
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 @@
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 18135f2..b7282218 100644
--- a/media/java/android/media/AudioSystem.java
+++ b/media/java/android/media/AudioSystem.java
@@ -431,6 +431,18 @@
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 @@
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 @@
*/
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 85cd342..d51f1e1 100644
--- a/media/java/android/media/AudioTrack.java
+++ b/media/java/android/media/AudioTrack.java
@@ -48,8 +48,8 @@
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 @@
}
// 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 @@
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 e18642c..62d14e1 100644
--- a/media/java/android/media/ExifInterface.java
+++ b/media/java/android/media/ExifInterface.java
@@ -70,6 +70,7 @@
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 @@
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 3008067..2342a42 100644
--- a/media/java/android/media/MediaHTTPService.java
+++ b/media/java/android/media/MediaHTTPService.java
@@ -21,6 +21,8 @@
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 @@
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 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 @@
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 737bc34..a9cbffb 100644
--- a/media/java/android/media/MediaPlayer.java
+++ b/media/java/android/media/MediaPlayer.java
@@ -2473,6 +2473,8 @@
*
* @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 e72026a..1aae8f4 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.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 @@
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 @@
.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 @@
.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 @@
*/
@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 aff2e1b4..89e5e0d 100644
--- a/media/java/android/mtp/MtpPropertyGroup.java
+++ b/media/java/android/mtp/MtpPropertyGroup.java
@@ -230,7 +230,7 @@
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 95599bd..1183ca3 100644
--- a/media/jni/android_media_MediaCodec.cpp
+++ b/media/jni/android_media_MediaCodec.cpp
@@ -174,6 +174,12 @@
jfieldID typeId;
} gDescriptorInfo;
+static struct {
+ jclass clazz;
+ jmethodID ctorId;
+ jmethodID setId;
+} gBufferInfo;
+
struct fields_t {
jmethodID postEventFromNativeID;
jmethodID lockAndGetContextID;
@@ -460,11 +466,7 @@
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 @@
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 @@
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 @@
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 f6fcba7..cbb2736 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 @@
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 a608ef5..e82c046 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 @@
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 779df99..736e511 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 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 8cf9a13..6ff1885 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 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 c5281657..8c05725 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 @@
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 39add7e..c814eba 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 @@
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 fd1c2d3..37dd4b5 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 @@
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 a3aa010..77f37d0 100644
--- a/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/CompanionDeviceActivity.java
+++ b/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/CompanionDeviceActivity.java
@@ -193,6 +193,7 @@
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 93e6271..3029d10 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 @@
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 34e7e3d..0c5de27 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 @@
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 d03bb1d..b9983c3 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 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 @@
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 b9b9098..680dd84 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 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 @@
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 @@
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 ae1bdce..cbd5833 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.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 00b3736..b0aa8f1 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 @@
@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 8eafbdf..24bb3a7 100644
--- a/packages/SettingsLib/OWNERS
+++ b/packages/SettingsLib/OWNERS
@@ -3,9 +3,9 @@
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 6ce72bb..3af64e2 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 @@
Log.e(TAG, "localBluetoothAdapter is NULL!!");
}
}
-};
+}
diff --git a/packages/SettingsLib/src/com/android/settingslib/qrcode/OWNERS b/packages/SettingsLib/src/com/android/settingslib/qrcode/OWNERS
new file mode 100644
index 0000000..61c73fb
--- /dev/null
+++ b/packages/SettingsLib/src/com/android/settingslib/qrcode/OWNERS
@@ -0,0 +1,8 @@
+# Default reviewers for this and subdirectories.
+bonianchen@google.com
+changbetty@google.com
+goldmanj@google.com
+wengsu@google.com
+zoeychen@google.com
+
+# Emergency approvers in case the above are not available
diff --git a/packages/SettingsLib/src/com/android/settingslib/qrcode/QrDecorateView.java b/packages/SettingsLib/src/com/android/settingslib/qrcode/QrDecorateView.java
index 51cf59c..ac9cdac 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 @@
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 @@
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 @@
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 @@
@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);
+ 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);
+ 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 23195af..00f1c01 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.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 @@
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 eb418ff..b8fcb10 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardAbsKeyInputViewController.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardAbsKeyInputViewController.java
@@ -179,7 +179,7 @@
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 12fa401..befd59b 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardHostViewController.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardHostViewController.java
@@ -90,7 +90,7 @@
Log.i(TAG, "TrustAgent dismissed Keyguard.");
}
mSecurityCallback.dismiss(false /* authenticated */, userId,
- /* bypassSecondaryLockScreen */ false);
+ /* bypassSecondaryLockScreen */ false, SecurityMode.Invalid);
} else {
mViewMediatorCallback.playTrustedSound();
}
@@ -102,9 +102,9 @@
@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 @@
* @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 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 98ac640..87300c3 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardInputViewController.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardInputViewController.java
@@ -59,10 +59,11 @@
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 39c3949..1a59b82 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardPatternViewController.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardPatternViewController.java
@@ -171,7 +171,7 @@
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 e384727..bc72f79 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 @@
* @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 cce516d..12bb47b 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java
@@ -233,7 +233,12 @@
// 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 19a2d9e..2b9553d 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainerController.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainerController.java
@@ -153,14 +153,17 @@
}
@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 @@
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 @@
* 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 e337123..821b2e1 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardSimPinViewController.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardSimPinViewController.java
@@ -170,7 +170,8 @@
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 47aa43b..203f9b6 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardSimPukViewController.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardSimPukViewController.java
@@ -69,7 +69,8 @@
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 @@
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 18fb423..d9bcb50 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 @@
@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 0783eeec..90bcb0fe 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 @@
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 00aa138..7f16a6b 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 @@
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 9fbd5c3..6123663 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.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 @@
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 dffad6c..80385e6 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 androidx.test.filters.SmallTest;
+import com.android.keyguard.KeyguardSecurityModel.SecurityMode;
import com.android.systemui.SysuiTestCase;
import org.junit.After;
@@ -190,7 +191,7 @@
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 4d33430..efc9921 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 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 @@
@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 @@
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 7d56339..8a6895e 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 @@
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 8525e36..592045c 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 @@
});
}
+ @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 466f647..8f73436 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 @@
* @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 6908c60..a94167e 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 @@
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 ff1a495..36b82f8 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 @@
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 @@
@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 ce0e69c..27215b2 100644
--- a/services/core/java/com/android/server/DynamicSystemService.java
+++ b/services/core/java/com/android/server/DynamicSystemService.java
@@ -77,6 +77,8 @@
@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 @@
@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 @@
@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 @@
@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 @@
@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 @@
@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 @@
@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 @@
@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 @@
@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 @@
@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 @@
@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 e529010..7d2e276 100644
--- a/services/core/java/com/android/server/GestureLauncherService.java
+++ b/services/core/java/com/android/server/GestureLauncherService.java
@@ -466,7 +466,8 @@
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 @@
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 e915fa1..ff903a0 100644
--- a/services/core/java/com/android/server/SerialService.java
+++ b/services/core/java/com/android/server/SerialService.java
@@ -37,6 +37,8 @@
@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 @@
@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 f7b05f2..ec8745a 100644
--- a/services/core/java/com/android/server/StorageManagerService.java
+++ b/services/core/java/com/android/server/StorageManagerService.java
@@ -19,12 +19,10 @@
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 @@
}
}
- // 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 @@
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/VpnManagerService.java b/services/core/java/com/android/server/VpnManagerService.java
index 3f1d1fe..ae50b23 100644
--- a/services/core/java/com/android/server/VpnManagerService.java
+++ b/services/core/java/com/android/server/VpnManagerService.java
@@ -186,6 +186,10 @@
synchronized (mVpns) {
for (int i = 0; i < mVpns.size(); i++) {
pw.println(mVpns.keyAt(i) + ": " + mVpns.valueAt(i).getPackage());
+ pw.increaseIndent();
+ mVpns.valueAt(i).dump(pw);
+ pw.decreaseIndent();
+ pw.println();
}
pw.decreaseIndent();
}
diff --git a/services/core/java/com/android/server/accounts/AccountManagerService.java b/services/core/java/com/android/server/accounts/AccountManagerService.java
index 6b731c3..8dc02c1 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 @@
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 @@
}
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 @@
@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 b56654f..2f7f2da 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 @@
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 384c9ba..85d796e 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 @@
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 45b0f0a6..bc9bc03 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.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.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.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;
@@ -124,6 +127,8 @@
import android.system.keystore2.KeyPermission;
import android.text.TextUtils;
import android.util.ArraySet;
+import android.util.IndentingPrintWriter;
+import android.util.LocalLog;
import android.util.Log;
import android.util.Range;
@@ -140,6 +145,7 @@
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;
@@ -152,6 +158,8 @@
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;
@@ -165,6 +173,7 @@
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;
@@ -289,6 +298,10 @@
return mVpnProfileStore;
}
+ private static final int MAX_EVENTS_LOGS = 20;
+ private final LocalLog mUnderlyNetworkChanges = new LocalLog(MAX_EVENTS_LOGS);
+ private final LocalLog mVpnManagerEvents = new LocalLog(MAX_EVENTS_LOGS);
+
/**
* Whether to keep the connection active after rebooting, or upgrading or reinstalling. This
* only applies to {@link VpnService} connections.
@@ -551,6 +564,24 @@
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
@@ -614,7 +645,8 @@
.addTransportType(NetworkCapabilities.TRANSPORT_VPN)
.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)
.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED)
- .setTransportInfo(new VpnTransportInfo(VpnManager.TYPE_VPN_NONE, null))
+ .setTransportInfo(new VpnTransportInfo(
+ VpnManager.TYPE_VPN_NONE, null /* sessionId */, false /* bypassable */))
.build();
loadAlwaysOnPackage();
@@ -678,7 +710,8 @@
private void resetNetworkCapabilities() {
mNetworkCapabilities = new NetworkCapabilities.Builder(mNetworkCapabilities)
.setUids(null)
- .setTransportInfo(new VpnTransportInfo(VpnManager.TYPE_VPN_NONE, null))
+ .setTransportInfo(new VpnTransportInfo(
+ VpnManager.TYPE_VPN_NONE, null /* sessionId */, false /* bypassable */))
.build();
}
@@ -816,6 +849,9 @@
int errorCode, @NonNull final String packageName, @Nullable final String sessionKey,
@NonNull final VpnProfileState profileState, @Nullable final Network underlyingNetwork,
@Nullable final NetworkCapabilities nc, @Nullable final LinkProperties lp) {
+ mVpnManagerEvents.log("Event class=" + getVpnManagerEventClassName(errorClass)
+ + ", err=" + getVpnManagerEventErrorName(errorCode) + " for " + packageName
+ + " on session " + sessionKey);
final Intent intent = buildVpnManagerEventIntent(category, errorClass, errorCode,
packageName, sessionKey, profileState, underlyingNetwork, nc, lp);
return sendEventToVpnManagerApp(intent, packageName);
@@ -1397,6 +1433,11 @@
}
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;
@@ -1406,6 +1447,7 @@
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;
@@ -1414,8 +1456,9 @@
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;
@@ -1426,7 +1469,8 @@
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;
@@ -1440,7 +1484,7 @@
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));
@@ -1525,7 +1569,8 @@
capsBuilder.setUids(createUserAndRestrictedProfilesRanges(mUserId,
mConfig.allowedApplications, mConfig.disallowedApplications));
- capsBuilder.setTransportInfo(new VpnTransportInfo(getActiveVpnType(), mConfig.session));
+ capsBuilder.setTransportInfo(
+ new VpnTransportInfo(getActiveVpnType(), mConfig.session, mConfig.allowBypass));
// Only apps targeting Q and above can explicitly declare themselves as metered.
// These VPNs are assumed metered unless they state otherwise.
@@ -1539,6 +1584,7 @@
? Arrays.asList(mConfig.underlyingNetworks) : null);
mNetworkCapabilities = capsBuilder.build();
+ logUnderlyNetworkChanges(mNetworkCapabilities.getUnderlyingNetworks());
mNetworkAgent = mDeps.newNetworkAgent(mContext, mLooper, NETWORKTYPE /* logtag */,
mNetworkCapabilities, lp,
new NetworkScore.Builder().setLegacyInt(VPN_DEFAULT_SCORE).build(),
@@ -1566,6 +1612,11 @@
}
}
+ private void logUnderlyNetworkChanges(List<Network> networks) {
+ mUnderlyNetworkChanges.log("Switch to "
+ + ((networks != null) ? TextUtils.join(", ", networks) : "null"));
+ }
+
private void agentDisconnect(NetworkAgent networkAgent) {
if (networkAgent != null) {
networkAgent.unregister();
@@ -1576,6 +1627,18 @@
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.
@@ -1665,16 +1728,7 @@
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) {
@@ -2711,6 +2765,17 @@
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
*
@@ -2881,7 +2946,6 @@
ikeConfiguration.isIkeExtensionEnabled(
IkeSessionConfiguration.EXTENSION_TYPE_MOBIKE);
onIkeConnectionInfoChanged(token, ikeConfiguration.getIkeSessionConnectionInfo());
- mRetryCount = 0;
}
/**
@@ -2924,15 +2988,27 @@
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());
}
@@ -2950,7 +3026,7 @@
if (mVpnRunner != this) return;
mInterface = interfaceName;
- mConfig.mtu = maxMtu;
+ mConfig.mtu = vpnMtu;
mConfig.interfaze = mInterface;
mConfig.addresses.clear();
@@ -2989,6 +3065,7 @@
}
doSendLinkProperties(networkAgent, lp);
+ mRetryCount = 0;
} catch (Exception e) {
Log.d(TAG, "Error in ChildOpened for token " + token, e);
onSessionLost(token, e);
@@ -3053,12 +3130,54 @@
// 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);
@@ -3108,6 +3227,60 @@
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.
*
@@ -3158,24 +3331,6 @@
// (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();
@@ -3193,8 +3348,8 @@
mSession =
mIkev2SessionCreator.createIkeSession(
mContext,
- ikeSessionParams,
- childSessionParams,
+ getIkeSessionParams(underlyingNetwork),
+ getChildSessionParams(),
mExecutor,
new VpnIkev2Utils.IkeSessionCallbackImpl(
TAG, IkeV2VpnRunner.this, token),
@@ -3208,6 +3363,10 @@
}
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
@@ -4231,6 +4390,7 @@
// TODO(b/230548427): Remove SDK check once VPN related stuff are decoupled from
// ConnectivityServiceTest.
if (SdkLevel.isAtLeastT()) {
+ mVpnManagerEvents.log(packageName + " stopped");
sendEventToVpnManagerApp(intent, packageName);
}
}
@@ -4398,8 +4558,10 @@
/** Proxy to allow different testing setups */
// TODO: b/240492694 Remove VpnNetworkAgentWrapper and this method when
// NetworkAgent#setUnderlyingNetworks can be un-finalized.
- private static void doSetUnderlyingNetworks(
+ private void doSetUnderlyingNetworks(
@NonNull NetworkAgent agent, @NonNull List<Network> networks) {
+ logUnderlyNetworkChanges(networks);
+
if (agent instanceof VpnNetworkAgentWrapper) {
((VpnNetworkAgentWrapper) agent).doSetUnderlyingNetworks(networks);
} else {
@@ -4518,4 +4680,57 @@
static Range<Integer> createUidRangeForUser(int userId) {
return new Range<Integer>(userId * PER_USER_RANGE, (userId + 1) * PER_USER_RANGE - 1);
}
+
+ private String getVpnManagerEventClassName(int code) {
+ switch (code) {
+ case VpnManager.ERROR_CLASS_NOT_RECOVERABLE:
+ return "ERROR_CLASS_NOT_RECOVERABLE";
+ case VpnManager.ERROR_CLASS_RECOVERABLE:
+ return "ERROR_CLASS_RECOVERABLE";
+ default:
+ return "UNKNOWN_CLASS";
+ }
+ }
+
+ private String getVpnManagerEventErrorName(int code) {
+ switch (code) {
+ case VpnManager.ERROR_CODE_NETWORK_UNKNOWN_HOST:
+ return "ERROR_CODE_NETWORK_UNKNOWN_HOST";
+ case VpnManager.ERROR_CODE_NETWORK_PROTOCOL_TIMEOUT:
+ return "ERROR_CODE_NETWORK_PROTOCOL_TIMEOUT";
+ case VpnManager.ERROR_CODE_NETWORK_IO:
+ return "ERROR_CODE_NETWORK_IO";
+ case VpnManager.ERROR_CODE_NETWORK_LOST:
+ return "ERROR_CODE_NETWORK_LOST";
+ default:
+ return "UNKNOWN_ERROR";
+ }
+ }
+
+ /** Dumps VPN state. */
+ public void dump(IndentingPrintWriter pw) {
+ synchronized (Vpn.this) {
+ pw.println("Active package name: " + mPackage);
+ pw.println("Active vpn type: " + getActiveVpnType());
+ pw.println("NetworkCapabilities: " + mNetworkCapabilities);
+ if (isIkev2VpnRunner()) {
+ final IkeV2VpnRunner runner = ((IkeV2VpnRunner) mVpnRunner);
+ pw.println("Token: " + runner.mSessionKey);
+ pw.println("MOBIKE " + (runner.mMobikeEnabled ? "enabled" : "disabled"));
+ if (mDataStallSuspected) pw.println("Data stall suspected");
+ if (runner.mScheduledHandleDataStallFuture != null) {
+ pw.println("Reset session scheduled");
+ }
+ }
+ pw.println("mUnderlyNetworkChanges (most recent first):");
+ pw.increaseIndent();
+ mUnderlyNetworkChanges.reverseDump(pw);
+ pw.decreaseIndent();
+
+ pw.println("mVpnManagerEvent (most recent first):");
+ pw.increaseIndent();
+ mVpnManagerEvents.reverseDump(pw);
+ pw.decreaseIndent();
+ }
+ }
}
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 0000000..2f42363
--- /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/display/DisplayDeviceConfig.java b/services/core/java/com/android/server/display/DisplayDeviceConfig.java
index a25ac21..c725441 100644
--- a/services/core/java/com/android/server/display/DisplayDeviceConfig.java
+++ b/services/core/java/com/android/server/display/DisplayDeviceConfig.java
@@ -458,7 +458,6 @@
*/
public float getNitsFromBacklight(float backlight) {
if (mBacklightToNitsSpline == null) {
- Slog.wtf(TAG, "requesting nits when no mapping exists.");
return NITS_INVALID;
}
backlight = Math.max(backlight, mBacklightMinimum);
diff --git a/services/core/java/com/android/server/hdmi/HdmiUtils.java b/services/core/java/com/android/server/hdmi/HdmiUtils.java
index ba19cf0..308a0c8 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_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.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 @@
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 72612a0..a9d747c 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 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 c199bb3..2d3f176 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 @@
@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 12f8776..25350d0 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 @@
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 018a2fc..2cc0073 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 @@
}
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 @@
&& (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 477b8da..634ee7e 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 @@
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 2b00ad7..85c47a0 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 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 @@
}
}
- 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 5544669..362b26e 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.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 @@
}
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 5a01ccb..e411880 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 @@
@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 @@
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 @@
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 @@
logStatus(status);
synchronized (mLock) {
mLastExecutionStatus = status;
- mLastExecutionDurationIncludingSleepMs =
- SystemClock.elapsedRealtime() - mLastExecutionStartTimeMs;
mLastExecutionDurationMs = SystemClock.uptimeMillis() - mLastExecutionStartUptimeMs;
}
@@ -954,10 +944,9 @@
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 46691a6..1e64701 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 @@
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 3b306a8..b310c62a 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 666776b..ad87b03 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 @@
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 016c1cb..fe797d2 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 @@
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 @@
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 @@
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 905bcf9..1407530 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 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 beea86d..d519c52 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 @@
* 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 fa08add..227a3a1 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 @@
// 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 @@
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 073776f..98bbcb9 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.Collections;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.Set;
/**
@@ -1924,7 +1925,7 @@
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 d34682d..1e13333 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 @@
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 @@
// 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 @@
// 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 3af6e18..2cf6608 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 @@
@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 0c5cc15..08800da 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 @@
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 @@
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 @@
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 @@
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 @@
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 @@
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 @@
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 @@
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 @@
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 @@
$ 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 @@
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 @@
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 @@
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 @@
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 e197319..eb8464e 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 @@
}
}
- 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 8d831d7..91dcc8e 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 @@
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 11bcd8c..a9d0e96 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 @@
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 @@
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 @@
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 @@
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 1ec191e..e14bbbd 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_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 @@
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 @@
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 @@
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);
+ }
+
+ 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);
+ }
// 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 Task task = iter.next();
- list.add(createRunningTaskInfo(task));
- maxNum--;
+ 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 @@
// 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 e1ee045..5d53c20 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 @@
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 6f2930c..1b70d1d 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.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 16eaa77..3678ced 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 @@
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 eab3b77..292320e 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 java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.function.Consumer;
/**
@@ -372,7 +373,8 @@
@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 ea746d1..faad961 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.view.Display;
import android.view.Surface;
-import java.util.HashMap;
+import java.util.Map;
@RunWith(JUnit4.class)
public class CameraServiceProxyTest {
@@ -75,24 +75,22 @@
/*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 df672c9..2c4fe53 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 @@
@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 9092ec3..0884b78 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 @@
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 1e855a9..1eb4fa5 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 @@
} 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 911fb6a..08c2c6e 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 @@
}
@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 480ad11..535183d 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 @@
}
@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 598a22b..d46530c 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 @@
@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 @@
@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 4550b56..2ccdcaa 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 @@
}
@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 33b2366..13fc61c 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 @@
}
@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 @@
.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 @@
.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 @@
}
@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();
- // Ensure that the last active time of visible tasks were updated while the focused one had
- // the largest last active time.
+ final Task visibleTaskTop = tasks.get(numTasks - 2);
+ doReturn(true).when(visibleTaskTop).isVisible();
+
+ 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 df63795..7a41b50 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 @@
// 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 4aa8ca2..32275a6 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 @@
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 5ce842e..0692066 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 @@
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 8e9b0d8..604dd66 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 @@
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 42d446d..af626f5 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 @@
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 a061618..e02f2f0 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 @@
}
}
};
-};
+}
diff --git a/telecomm/OWNERS b/telecomm/OWNERS
index eb0c432..dcaf858 100644
--- a/telecomm/OWNERS
+++ b/telecomm/OWNERS
@@ -4,3 +4,7 @@
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 e0f5b20..983d82b 100644
--- a/telecomm/java/android/telecom/TelecomManager.java
+++ b/telecomm/java/android/telecom/TelecomManager.java
@@ -1269,7 +1269,7 @@
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 @@
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 @@
if (service != null) {
try {
return service.getOwnSelfManagedPhoneAccounts(mContext.getOpPackageName(),
- mContext.getAttributionTag());
+ mContext.getAttributionTag()).getList();
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -1366,7 +1366,7 @@
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 @@
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 @@
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 @@
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 37403a8..74b5545 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.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 @@
/**
* @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 @@
/**
* @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 8b01cb3..2787d83 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 @@
*/
@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 8e6d6a8..bd993f2 100644
--- a/telephony/java/android/telephony/CarrierConfigManager.java
+++ b/telephony/java/android/telephony/CarrierConfigManager.java
@@ -1180,8 +1180,12 @@
"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 @@
*
* 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 @@
* "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 @@
*
* 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 @@
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 5f7cfd1..5186c72 100644
--- a/telephony/java/android/telephony/DataFailCause.java
+++ b/telephony/java/android/telephony/DataFailCause.java
@@ -1613,29 +1613,26 @@
// 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 e0145e6..c2b65f8 100644
--- a/telephony/java/android/telephony/SmsMessage.java
+++ b/telephony/java/android/telephony/SmsMessage.java
@@ -1092,6 +1092,11 @@
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 @@
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 70d8270..a081bc3 100644
--- a/telephony/java/android/telephony/TelephonyManager.java
+++ b/telephony/java/android/telephony/TelephonyManager.java
@@ -9358,7 +9358,8 @@
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 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 @@
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 be233b8..4477f81 100644
--- a/telephony/java/android/telephony/ims/ImsService.java
+++ b/telephony/java/android/telephony/ims/ImsService.java
@@ -50,7 +50,6 @@
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 @@
* 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 @@
}
}
- 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 090d413..9996b86 100644
--- a/telephony/java/android/telephony/ims/RegistrationManager.java
+++ b/telephony/java/android/telephony/ims/RegistrationManager.java
@@ -78,24 +78,22 @@
/**@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 f5b158f..174675f 100644
--- a/telephony/java/android/telephony/ims/feature/ImsFeature.java
+++ b/telephony/java/android/telephony/ims/feature/ImsFeature.java
@@ -34,7 +34,6 @@
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
-import java.util.HashMap;
import java.util.Map;
/**
@@ -85,11 +84,10 @@
* 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 @@
* 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 @@
@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 @@
*/
@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 0f4e122..4bcf5a4 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 @@
};
@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 @@
@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 @@
}
@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 @@
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 @@
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 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 @@
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 2ad0da9..8b9c020 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 @@
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 4de51fb..43dc9de 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 @@
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 c16efbd..d015a56 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 @@
}
}
+ @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 8afe841..17fa210 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 @@
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 241206d..65b7549 100644
--- a/tests/RenderThreadTest/src/com/example/renderthread/MainActivity.java
+++ b/tests/RenderThreadTest/src/com/example/renderthread/MainActivity.java
@@ -24,18 +24,14 @@
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 a18488d..074c7bc 100644
--- a/tests/RollbackTest/SampleRollbackApp/Android.bp
+++ b/tests/RollbackTest/SampleRollbackApp/Android.bp
@@ -29,4 +29,5 @@
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 c11b0f3..f85fb0f 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 @@
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 3da8b46..133c176 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 @@
@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 f924b2e..ad06830 100644
--- a/tests/vcn/java/com/android/server/VcnManagementServiceTest.java
+++ b/tests/vcn/java/com/android/server/VcnManagementServiceTest.java
@@ -637,8 +637,7 @@
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 6efd1f6..ff1f8e2 100644
--- a/tools/locked_region_code_injection/Android.bp
+++ b/tools/locked_region_code_injection/Android.bp
@@ -16,6 +16,6 @@
"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 39d1b1c..bb32df6 100644
--- a/tools/traceinjection/Android.bp
+++ b/tools/traceinjection/Android.bp
@@ -16,7 +16,7 @@
"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 a750696..5012622 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 @@
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 @@
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 {