Add a NetworkStackCoverageTests target.

This target will include all tests that are necessary to calculate
code coverage of the network stack. It is currently the union of
NetworkStackTests and NetworkStackIntegrationTests

Also apply jarjar rules on top of NetworkStackIntegrationTests and
NetworkStackTests, to make sure that the test classes (and not the
framework classes) are used during the test. This requires the tests to
stop using external (hidden) references to classes in
com.android.internal, as the references would be broken when applying
jarjar.

Test: atest NetworkStackIntegrationTests NetworkStackTests \
          NetworkStackCoverageTests
Change-Id: Ib945cb9faa960862593a6ac2ac26058948e777a4
diff --git a/Android.bp b/Android.bp
index 13eec44..0a8b263 100644
--- a/Android.bp
+++ b/Android.bp
@@ -133,6 +133,15 @@
     manifest: "AndroidManifestBase.xml",
 }
 
+filegroup {
+    name: "NetworkStackJarJarRules",
+    srcs: ["jarjar-rules-shared.txt"],
+    visibility: [
+        "//packages/modules/NetworkStack/tests/unit",
+        "//packages/modules/NetworkStack/tests/integration",
+    ]
+}
+
 // Common defaults for compiling the actual APK, based on the NetworkStackApiXBase android libraries
 java_defaults {
     name: "NetworkStackAppDefaults",
@@ -143,7 +152,7 @@
     ],
     // Resources already included in NetworkStackBase
     resource_dirs: [],
-    jarjar_rules: "jarjar-rules-shared.txt",
+    jarjar_rules: ":NetworkStackJarJarRules",
     use_embedded_native_libs: true,
     optimize: {
         proguard_flags_files: ["proguard.flags"],
@@ -193,6 +202,7 @@
     defaults: ["NetworkStackAppDefaults", "NetworkStackReleaseApiLevel"],
     static_libs: ["NetworkStackApiStableLib"],
     manifest: "AndroidManifestBase.xml",
+    visibility: ["//frameworks/base/tests/net/integration"],
 }
 
 cc_library_shared {
diff --git a/tests/integration/Android.bp b/tests/integration/Android.bp
index 3aac230..b782efc 100644
--- a/tests/integration/Android.bp
+++ b/tests/integration/Android.bp
@@ -14,25 +14,8 @@
 // limitations under the License.
 //
 
-android_test {
-    name: "NetworkStackIntegrationTests",
-    certificate: "networkstack",
-    min_sdk_version: "29",
-    srcs: ["src/**/*.java"],
-    test_suites: ["device-tests"],
-    static_libs: [
-        "androidx.annotation_annotation",
-        "androidx.test.rules",
-        "mockito-target-extended-minus-junit4",
-        "net-tests-utils",
-        "testables",
-        "TestNetworkStackLib",
-    ],
-    libs: [
-        "android.test.runner",
-        "android.test.base",
-        "android.test.mock",
-    ],
+java_defaults {
+    name: "NetworkStackIntegrationTestsJniDefaults",
     defaults: ["libnetworkstackutilsjni_deps"],
     jni_libs: [
         // For mockito extended
@@ -41,4 +24,51 @@
         // For NetworkStackUtils included in NetworkStackBase
         "libnetworkstackutilsjni",
     ],
+    visibility: ["//visibility:private"],
+}
+
+android_library {
+    name: "NetworkStackIntegrationTestsLib",
+    min_sdk_version: "29",
+    srcs: ["src/**/*.java"],
+    static_libs: [
+        "androidx.annotation_annotation",
+        "androidx.test.rules",
+        "mockito-target-extended-minus-junit4",
+        "net-tests-utils",
+        "testables",
+        "NetworkStackApiStableLib",
+    ],
+    libs: [
+        "android.test.runner",
+        "android.test.base",
+        "android.test.mock",
+    ],
+    jarjar_rules: ":NetworkStackJarJarRules",
+    visibility: ["//visibility:private"],
+}
+
+// Network stack integration tests.
+android_test {
+    name: "NetworkStackIntegrationTests",
+    defaults: ["NetworkStackIntegrationTestsJniDefaults"],
+    static_libs: ["NetworkStackIntegrationTestsLib"],
+    certificate: "networkstack",
+    platform_apis: true,
+    test_suites: ["device-tests"],
+    min_sdk_version: "29",
+}
+
+// Special version of the network stack tests that includes all tests necessary for code coverage
+// purposes. This is currently the union of NetworkStackTests and NetworkStackIntegrationTests.
+android_test {
+    name: "NetworkStackCoverageTests",
+    certificate: "networkstack",
+    platform_apis: true,
+    min_sdk_version: "29",
+    test_suites: ["device-tests", "mts"],
+    defaults: ["NetworkStackIntegrationTestsJniDefaults"],
+    static_libs: ["NetworkStackTestsLib", "NetworkStackIntegrationTestsLib"],
+    compile_multilib: "both",
+    manifest: "AndroidManifest_coverage.xml",
 }
diff --git a/tests/integration/AndroidManifest_coverage.xml b/tests/integration/AndroidManifest_coverage.xml
new file mode 100644
index 0000000..660e42d
--- /dev/null
+++ b/tests/integration/AndroidManifest_coverage.xml
@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2020 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.
+-->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="com.android.server.networkstack.coverage"
+          android:sharedUserId="android.uid.networkstack">
+    <uses-sdk android:minSdkVersion="29" android:targetSdkVersion="29" />
+
+    <!-- Note: do not add any privileged or signature permissions that are granted
+         to the network stack app. Otherwise, the test APK will install, but when the device is
+         rebooted, it will bootloop with something like:
+
+         05-14 00:41:02.723 18330 18330 E AndroidRuntime: java.lang.IllegalStateException: Signature|privileged permissions not in privapp-permissions whitelist: {com.android.server.networkstack.integrationtests: android.permission.CONNECTIVITY_INTERNAL}
+    -->
+    <uses-permission android:name="android.permission.MAINLINE_NETWORK_STACK" />
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+    </application>
+    <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
+        android:targetPackage="com.android.server.networkstack.coverage"
+        android:label="Networking stack coverage tests">
+    </instrumentation>
+</manifest>
diff --git a/tests/integration/AndroidTest.xml b/tests/integration/AndroidTest.xml
deleted file mode 100644
index c592568..0000000
--- a/tests/integration/AndroidTest.xml
+++ /dev/null
@@ -1,29 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2019 The Android Open Source Project
-
-     Licensed under the Apache License, Version 2.0 (the "License");
-     you may not use this file except in compliance with the License.
-     You may obtain a copy of the License at
-
-          http://www.apache.org/licenses/LICENSE-2.0
-
-     Unless required by applicable law or agreed to in writing, software
-     distributed under the License is distributed on an "AS IS" BASIS,
-     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-     See the License for the specific language governing permissions and
-     limitations under the License.
--->
-<configuration description="Runs Integration Tests for NetworkStack">
-    <target_preparer class="com.android.tradefed.targetprep.TestAppInstallSetup">
-        <option name="test-file-name" value="NetworkStackIntegrationTests.apk" />
-    </target_preparer>
-
-    <option name="test-suite-tag" value="apct" />
-    <option name="test-suite-tag" value="framework-base-presubmit" />
-    <option name="test-tag" value="NetworkStackIntegrationTests" />
-    <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
-        <option name="package" value="com.android.server.networkstack.integrationtests" />
-        <option name="runner" value="androidx.test.runner.AndroidJUnitRunner" />
-        <option name="hidden-api-checks" value="false"/>
-    </test>
-</configuration>
diff --git a/tests/integration/src/android/net/ip/IpClientIntegrationTest.java b/tests/integration/src/android/net/ip/IpClientIntegrationTest.java
index 30b1b19..8ca3fc6 100644
--- a/tests/integration/src/android/net/ip/IpClientIntegrationTest.java
+++ b/tests/integration/src/android/net/ip/IpClientIntegrationTest.java
@@ -25,13 +25,12 @@
 import static android.net.dhcp.DhcpPacket.INADDR_BROADCAST;
 import static android.net.dhcp.DhcpPacket.INFINITE_LEASE;
 import static android.net.ipmemorystore.Status.SUCCESS;
-import static android.net.networkstack.shared.Inet4AddressUtils.getBroadcastAddress;
-import static android.net.networkstack.shared.Inet4AddressUtils.getPrefixMaskAsInet4Address;
+import static android.net.shared.Inet4AddressUtils.getBroadcastAddress;
+import static android.net.shared.Inet4AddressUtils.getPrefixMaskAsInet4Address;
 import static android.system.OsConstants.ETH_P_IPV6;
 import static android.system.OsConstants.IPPROTO_ICMPV6;
 import static android.system.OsConstants.IPPROTO_TCP;
 
-import static com.android.internal.util.BitUtils.uint16;
 import static com.android.server.util.NetworkStackConstants.ARP_REPLY;
 import static com.android.server.util.NetworkStackConstants.ARP_REQUEST;
 import static com.android.server.util.NetworkStackConstants.ETHER_ADDR_LEN;
@@ -96,7 +95,6 @@
 import android.net.ipmemorystore.NetworkAttributes;
 import android.net.ipmemorystore.OnNetworkAttributesRetrievedListener;
 import android.net.ipmemorystore.Status;
-import android.net.networkstack.util.StateMachine;
 import android.net.shared.ProvisioningConfiguration;
 import android.net.util.InterfaceParams;
 import android.net.util.IpUtils;
@@ -116,6 +114,7 @@
 import androidx.test.filters.SmallTest;
 import androidx.test.runner.AndroidJUnit4;
 
+import com.android.internal.util.StateMachine;
 import com.android.networkstack.arp.ArpPacket;
 import com.android.server.NetworkObserverRegistry;
 import com.android.server.NetworkStackService.NetworkStackServiceManager;
@@ -1137,6 +1136,10 @@
         return (short) ~tempSum;
     }
 
+    public static int uint16(short s) {
+        return s & 0xffff;
+    }
+
     private static short icmpv6Checksum(ByteBuffer buf, int ipOffset, int transportOffset,
             int transportLen) {
         // The ICMPv6 checksum is the same as the TCP checksum, except the pseudo-header uses
diff --git a/tests/unit/Android.bp b/tests/unit/Android.bp
index 9209dc4..bdb2d74 100644
--- a/tests/unit/Android.bp
+++ b/tests/unit/Android.bp
@@ -38,8 +38,10 @@
         "libstaticjvmtiagent",
         "libnetworkstackutilsjni",
     ],
+    jarjar_rules: ":NetworkStackJarJarRules",
 }
 
+// Tests for NetworkStackNext.
 android_test {
     name: "NetworkStackNextTests",
     srcs: [], // TODO: tests that only apply to the current, non-stable API can be added here
@@ -48,6 +50,17 @@
     static_libs: ["NetworkStackApiCurrentLib"],
 }
 
+// Library containing the unit tests. This is used by the coverage test target to pull in the
+// unit test code. It is not currently used by the tests themselves because all the build
+// configuration needed by the tests is in the NetworkStackTestsDefaults rule.
+android_library {
+    name: "NetworkStackTestsLib",
+    min_sdk_version: "29",
+    defaults: ["NetworkStackTestsDefaults"],
+    static_libs: ["NetworkStackApiStableLib"],
+    visibility: ["//packages/modules/NetworkStack/tests/integration"]
+}
+
 android_test {
     name: "NetworkStackTests",
     min_sdk_version: "29",
diff --git a/tests/unit/AndroidManifest.xml b/tests/unit/AndroidManifest.xml
index c7ea774..f45cfc7 100644
--- a/tests/unit/AndroidManifest.xml
+++ b/tests/unit/AndroidManifest.xml
@@ -17,32 +17,26 @@
           package="com.android.server.networkstack.tests">
     <uses-sdk android:minSdkVersion="29" android:targetSdkVersion="29" />
 
-    <uses-permission android:name="android.permission.READ_LOGS" />
+    <!-- DO NOT add privapp permissions here: they are inherited by
+         NetworkStackCoverageTests, which is not signed by the platform key,
+         and on Q rebooting the device would cause a bootloop because of
+         the missing priv-app whitelisting. -->
+    <!-- TODO: many of the below permissions seem to be unused, remove them. -->
     <uses-permission android:name="android.permission.WRITE_SETTINGS" />
-    <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
     <uses-permission android:name="android.permission.READ_PHONE_STATE" />
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
     <uses-permission android:name="android.permission.BROADCAST_STICKY" />
-    <uses-permission android:name="android.permission.UPDATE_DEVICE_STATS" />
     <uses-permission android:name="android.permission.MANAGE_APP_TOKENS" />
     <uses-permission android:name="android.permission.WAKE_LOCK" />
-    <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS" />
-    <uses-permission android:name="android.permission.REAL_GET_TASKS" />
     <uses-permission android:name="android.permission.GET_DETAILED_TASKS" />
     <uses-permission android:name="android.permission.MANAGE_NETWORK_POLICY" />
-    <uses-permission android:name="android.permission.READ_NETWORK_USAGE_HISTORY" />
-    <uses-permission android:name="android.permission.CONNECTIVITY_INTERNAL" />
     <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
-    <uses-permission android:name="android.permission.MANAGE_USERS" />
     <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" />
     <uses-permission android:name="android.permission.MANAGE_DEVICE_ADMINS" />
-    <uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
     <uses-permission android:name="android.permission.INTERNET" />
     <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
-    <uses-permission android:name="android.permission.PACKET_KEEPALIVE_OFFLOAD" />
     <uses-permission android:name="android.permission.GET_INTENT_SENDER_INTENT" />
     <uses-permission android:name="android.permission.MANAGE_ACTIVITY_STACKS" />
-    <uses-permission android:name="android.permission.INSTALL_PACKAGES" />
     <uses-permission android:name="android.permission.NETWORK_STACK" />
 
     <application android:debuggable="true">
@@ -52,4 +46,4 @@
         android:targetPackage="com.android.server.networkstack.tests"
         android:label="Networking service tests">
     </instrumentation>
-</manifest>
\ No newline at end of file
+</manifest>
diff --git a/tests/unit/src/android/net/apf/ApfTest.java b/tests/unit/src/android/net/apf/ApfTest.java
index 006ad19..f018fde 100644
--- a/tests/unit/src/android/net/apf/ApfTest.java
+++ b/tests/unit/src/android/net/apf/ApfTest.java
@@ -26,7 +26,6 @@
 import static android.system.OsConstants.IPPROTO_UDP;
 import static android.system.OsConstants.SOCK_STREAM;
 
-import static com.android.internal.util.BitUtils.bytesToBEInt;
 import static com.android.server.util.NetworkStackConstants.ICMPV6_ECHO_REQUEST_TYPE;
 import static com.android.server.util.NetworkStackConstants.IPV6_ADDR_LEN;
 
@@ -39,6 +38,7 @@
 import static org.mockito.Mockito.verify;
 
 import android.content.Context;
+import android.net.InetAddresses;
 import android.net.IpPrefix;
 import android.net.LinkAddress;
 import android.net.LinkProperties;
@@ -51,6 +51,7 @@
 import android.net.ip.IpClient.IpClientCallbacksWrapper;
 import android.net.metrics.IpConnectivityLog;
 import android.net.metrics.RaEvent;
+import android.net.shared.Inet4AddressUtils;
 import android.net.util.InterfaceParams;
 import android.net.util.SharedLog;
 import android.os.ConditionVariable;
@@ -85,6 +86,7 @@
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
+import java.net.Inet4Address;
 import java.net.InetAddress;
 import java.nio.ByteBuffer;
 import java.util.Arrays;
@@ -2303,7 +2305,8 @@
     }
 
     public void assertEqualsIp(String expected, int got) throws Exception {
-        int want = bytesToBEInt(InetAddress.getByName(expected).getAddress());
+        int want = Inet4AddressUtils.inet4AddressToIntHTH(
+                (Inet4Address) InetAddresses.parseNumericAddress(expected));
         assertEquals(want, got);
     }
 }
diff --git a/tests/unit/src/com/android/server/connectivity/NetworkMonitorTest.java b/tests/unit/src/com/android/server/connectivity/NetworkMonitorTest.java
index ae234b1..6bf9236 100644
--- a/tests/unit/src/com/android/server/connectivity/NetworkMonitorTest.java
+++ b/tests/unit/src/com/android/server/connectivity/NetworkMonitorTest.java
@@ -61,6 +61,8 @@
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
+import static java.util.stream.Collectors.toList;
+
 import android.annotation.NonNull;
 import android.content.BroadcastReceiver;
 import android.content.Context;
@@ -104,7 +106,6 @@
 import androidx.test.filters.SmallTest;
 import androidx.test.runner.AndroidJUnit4;
 
-import com.android.internal.util.CollectionUtils;
 import com.android.networkstack.R;
 import com.android.networkstack.apishim.ShimUtils;
 import com.android.networkstack.metrics.DataStallDetectionStats;
@@ -257,9 +258,8 @@
                 return null;
             }
 
-            DnsEntry answer = CollectionUtils.find(mAnswers, e -> e.matches(hostname, type));
-            if (answer != null) return answer.mAddresses;
-            else return null;
+            return mAnswers.stream().filter(e -> e.matches(hostname, type))
+                    .map(answer -> answer.mAddresses).findFirst().orElse(null);
         }
 
         /** Sets the answer for a given name and type. */
@@ -274,8 +274,8 @@
 
         private List<InetAddress> generateAnswer(String[] answer) {
             if (answer == null) return new ArrayList<>();
-            return CollectionUtils.map(Arrays.asList(answer),
-                    addr -> InetAddress.parseNumericAddress(addr));
+            return Arrays.stream(answer).map(addr -> InetAddress.parseNumericAddress(addr))
+                    .collect(toList());
         }
 
         /** Simulates a getAllByName call for the specified name on the specified mock network. */