Merge "Switch from std::result_of to std::invoke_result"
diff --git a/staticlibs/Android.bp b/staticlibs/Android.bp
index c04d1d4..4dfc752 100644
--- a/staticlibs/Android.bp
+++ b/staticlibs/Android.bp
@@ -284,7 +284,7 @@
     // TODO: remove "apex_available:platform".
     apex_available: [
         "//apex_available:platform",
-        "com.android.bluetooth",
+        "com.android.btservices",
         "com.android.tethering",
         "com.android.wifi",
     ],
diff --git a/staticlibs/device/com/android/net/module/util/BpfDump.java b/staticlibs/device/com/android/net/module/util/BpfDump.java
index fec225c..67e9c93 100644
--- a/staticlibs/device/com/android/net/module/util/BpfDump.java
+++ b/staticlibs/device/com/android/net/module/util/BpfDump.java
@@ -16,16 +16,20 @@
 package com.android.net.module.util;
 
 import android.util.Base64;
+import android.util.Pair;
 
 import androidx.annotation.NonNull;
 
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
 /**
  * The classes and the methods for BPF dump utilization.
  */
 public class BpfDump {
     // Using "," as a separator between base64 encoded key and value is safe because base64
     // characters are [0-9a-zA-Z/=+].
-    public static final String BASE64_DELIMITER = ",";
+    private static final String BASE64_DELIMITER = ",";
 
     /**
      * Encode BPF key and value into a base64 format string which uses the delimiter ',':
@@ -43,6 +47,33 @@
         return keyBase64Str + BASE64_DELIMITER + valueBase64Str;
     }
 
+    /**
+     * Decode Struct from a base64 format string
+     */
+    private static <T extends Struct> T parseStruct(
+            Class<T> structClass, @NonNull String base64Str) {
+        final byte[] bytes = Base64.decode(base64Str, Base64.DEFAULT);
+        final ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
+        byteBuffer.order(ByteOrder.nativeOrder());
+        return Struct.parse(structClass, byteBuffer);
+    }
+
+    /**
+     * Decode BPF key and value from a base64 format string which uses the delimiter ',':
+     * <base64 encoded key>,<base64 encoded value>
+     */
+    public static <K extends Struct, V extends Struct> Pair<K, V> fromBase64EncodedString(
+            Class<K> keyClass, Class<V> valueClass, @NonNull String base64Str) {
+        String[] keyValueStrs = base64Str.split(BASE64_DELIMITER);
+        if (keyValueStrs.length != 2 /* key + value */) {
+            throw new IllegalArgumentException("Invalid base64Str (" + base64Str + "), base64Str"
+                    + " must contain exactly one delimiter '" + BASE64_DELIMITER + "'");
+        }
+        final K k = parseStruct(keyClass, keyValueStrs[0]);
+        final V v = parseStruct(valueClass, keyValueStrs[1]);
+        return new Pair<>(k, v);
+    }
+
     // TODO: add a helper to dump bpf map content with the map name, the header line
     // (ex: "BPF ingress map: iif nat64Prefix v6Addr -> v4Addr oif"), a lambda that
     // knows how to dump each line, and the PrintWriter.
diff --git a/staticlibs/device/com/android/net/module/util/netlink/StructInetDiagSockId.java b/staticlibs/device/com/android/net/module/util/netlink/StructInetDiagSockId.java
index 95d60e5..95723cb 100644
--- a/staticlibs/device/com/android/net/module/util/netlink/StructInetDiagSockId.java
+++ b/staticlibs/device/com/android/net/module/util/netlink/StructInetDiagSockId.java
@@ -16,10 +16,22 @@
 
 package com.android.net.module.util.netlink;
 
+import static android.system.OsConstants.AF_INET;
+import static android.system.OsConstants.AF_INET6;
+
+import static com.android.net.module.util.NetworkStackConstants.IPV4_ADDR_LEN;
+import static com.android.net.module.util.NetworkStackConstants.IPV6_ADDR_LEN;
+
 import static java.nio.ByteOrder.BIG_ENDIAN;
 
+import android.util.Log;
+
+import androidx.annotation.Nullable;
+
 import java.net.Inet4Address;
+import java.net.InetAddress;
 import java.net.InetSocketAddress;
+import java.net.UnknownHostException;
 import java.nio.ByteBuffer;
 import java.nio.ByteOrder;
 
@@ -41,19 +53,79 @@
  * @hide
  */
 public class StructInetDiagSockId {
+    private static final String TAG = StructInetDiagSockId.class.getSimpleName();
     public static final int STRUCT_SIZE = 48;
 
-    private static final byte[] INET_DIAG_NOCOOKIE = new byte[]{
-            (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
-            (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff};
+    private static final long INET_DIAG_NOCOOKIE = ~0L;
     private static final byte[] IPV4_PADDING = new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
 
-    private final InetSocketAddress mLocSocketAddress;
-    private final InetSocketAddress mRemSocketAddress;
+    public final InetSocketAddress locSocketAddress;
+    public final InetSocketAddress remSocketAddress;
+    public final int ifIndex;
+    public final long cookie;
 
     public StructInetDiagSockId(InetSocketAddress loc, InetSocketAddress rem) {
-        mLocSocketAddress = loc;
-        mRemSocketAddress = rem;
+        this(loc, rem, 0 /* ifIndex */, INET_DIAG_NOCOOKIE);
+    }
+
+    public StructInetDiagSockId(InetSocketAddress loc, InetSocketAddress rem,
+            int ifIndex, long cookie) {
+        this.locSocketAddress = loc;
+        this.remSocketAddress = rem;
+        this.ifIndex = ifIndex;
+        this.cookie = cookie;
+    }
+
+    /**
+     * Parse inet diag socket id from buffer.
+     */
+    @Nullable
+    public static StructInetDiagSockId parse(final ByteBuffer byteBuffer, final byte family) {
+        if (byteBuffer.remaining() < STRUCT_SIZE) {
+            return null;
+        }
+
+        byteBuffer.order(BIG_ENDIAN);
+        final int srcPort = Short.toUnsignedInt(byteBuffer.getShort());
+        final int dstPort = Short.toUnsignedInt(byteBuffer.getShort());
+
+        final byte[] srcAddrByte;
+        final byte[] dstAddrByte;
+        if (family == AF_INET) {
+            srcAddrByte = new byte[IPV4_ADDR_LEN];
+            dstAddrByte = new byte[IPV4_ADDR_LEN];
+            byteBuffer.get(srcAddrByte);
+            // Address always uses IPV6_ADDR_LEN in the buffer. So if the address is IPv4, position
+            // needs to be advanced to the next field.
+            byteBuffer.position(byteBuffer.position() + (IPV6_ADDR_LEN - IPV4_ADDR_LEN));
+            byteBuffer.get(dstAddrByte);
+            byteBuffer.position(byteBuffer.position() + (IPV6_ADDR_LEN - IPV4_ADDR_LEN));
+        } else if (family == AF_INET6) {
+            srcAddrByte = new byte[IPV6_ADDR_LEN];
+            dstAddrByte = new byte[IPV6_ADDR_LEN];
+            byteBuffer.get(srcAddrByte);
+            byteBuffer.get(dstAddrByte);
+        } else {
+            Log.e(TAG, "Invalid address family: " + family);
+            return null;
+        }
+
+        final InetSocketAddress srcAddr;
+        final InetSocketAddress dstAddr;
+        try {
+            srcAddr = new InetSocketAddress(InetAddress.getByAddress(srcAddrByte), srcPort);
+            dstAddr = new InetSocketAddress(InetAddress.getByAddress(dstAddrByte), dstPort);
+        } catch (UnknownHostException e) {
+            // Should not happen. UnknownHostException is thrown only if addr byte array is of
+            // illegal length.
+            Log.e(TAG, "Failed to parse address: " + e);
+            return null;
+        }
+
+        byteBuffer.order(ByteOrder.nativeOrder());
+        final int ifIndex = byteBuffer.getInt();
+        final long cookie = byteBuffer.getLong();
+        return new StructInetDiagSockId(srcAddr, dstAddr, ifIndex, cookie);
     }
 
     /**
@@ -61,30 +133,31 @@
      */
     public void pack(ByteBuffer byteBuffer) {
         byteBuffer.order(BIG_ENDIAN);
-        byteBuffer.putShort((short) mLocSocketAddress.getPort());
-        byteBuffer.putShort((short) mRemSocketAddress.getPort());
-        byteBuffer.put(mLocSocketAddress.getAddress().getAddress());
-        if (mLocSocketAddress.getAddress() instanceof Inet4Address) {
+        byteBuffer.putShort((short) locSocketAddress.getPort());
+        byteBuffer.putShort((short) remSocketAddress.getPort());
+        byteBuffer.put(locSocketAddress.getAddress().getAddress());
+        if (locSocketAddress.getAddress() instanceof Inet4Address) {
             byteBuffer.put(IPV4_PADDING);
         }
-        byteBuffer.put(mRemSocketAddress.getAddress().getAddress());
-        if (mRemSocketAddress.getAddress() instanceof Inet4Address) {
+        byteBuffer.put(remSocketAddress.getAddress().getAddress());
+        if (remSocketAddress.getAddress() instanceof Inet4Address) {
             byteBuffer.put(IPV4_PADDING);
         }
         byteBuffer.order(ByteOrder.nativeOrder());
-        byteBuffer.putInt(0);
-        byteBuffer.put(INET_DIAG_NOCOOKIE);
+        byteBuffer.putInt(ifIndex);
+        byteBuffer.putLong(cookie);
     }
 
     @Override
     public String toString() {
         return "StructInetDiagSockId{ "
-                + "idiag_sport{" + mLocSocketAddress.getPort() + "}, "
-                + "idiag_dport{" + mRemSocketAddress.getPort() + "}, "
-                + "idiag_src{" + mLocSocketAddress.getAddress().getHostAddress() + "}, "
-                + "idiag_dst{" + mRemSocketAddress.getAddress().getHostAddress() + "}, "
-                + "idiag_if{" + 0 + "} "
-                + "idiag_cookie{INET_DIAG_NOCOOKIE}"
+                + "idiag_sport{" + locSocketAddress.getPort() + "}, "
+                + "idiag_dport{" + remSocketAddress.getPort() + "}, "
+                + "idiag_src{" + locSocketAddress.getAddress().getHostAddress() + "}, "
+                + "idiag_dst{" + remSocketAddress.getAddress().getHostAddress() + "}, "
+                + "idiag_if{" + ifIndex + "}, "
+                + "idiag_cookie{"
+                + (cookie == INET_DIAG_NOCOOKIE ? "INET_DIAG_NOCOOKIE" : cookie) + "}"
                 + "}";
     }
 }
diff --git a/staticlibs/framework/com/android/net/module/util/CollectionUtils.java b/staticlibs/framework/com/android/net/module/util/CollectionUtils.java
index a16ef33..d1728c2 100644
--- a/staticlibs/framework/com/android/net/module/util/CollectionUtils.java
+++ b/staticlibs/framework/com/android/net/module/util/CollectionUtils.java
@@ -22,6 +22,7 @@
 
 import java.util.ArrayList;
 import java.util.Collection;
+import java.util.List;
 import java.util.Objects;
 import java.util.function.Predicate;
 
@@ -165,6 +166,26 @@
     }
 
     /**
+     * Returns the index of the needle array in the haystack array, or -1 if it can't be found.
+     * This is a byte array equivalent of Collections.indexOfSubList().
+     */
+    public static int indexOfSubArray(@NonNull byte[] haystack, @NonNull byte[] needle) {
+        for (int i = 0; i < haystack.length - needle.length + 1; i++) {
+            boolean found = true;
+            for (int j = 0; j < needle.length; j++) {
+                if (haystack[i + j] != needle[j]) {
+                    found = false;
+                    break;
+                }
+            }
+            if (found) {
+                return i;
+            }
+        }
+        return -1;
+    }
+
+    /**
      * Returns a new collection of elements that match the passed predicate.
      * @param source the elements to filter.
      * @param test the predicate to test for.
@@ -219,4 +240,38 @@
         return haystack.containsAll(needles);
     }
 
+    /**
+     * Returns the first item of a collection that matches the predicate.
+     * @param haystack The collection to search.
+     * @param condition The predicate to match.
+     * @param <T> The type of element in the collection.
+     * @return The first element matching the predicate, or null if none.
+     */
+    @Nullable
+    public static <T> T findFirst(Collection<T> haystack, Predicate<? super T> condition) {
+        for (T needle : haystack) {
+            if (condition.test(needle)) return needle;
+        }
+        return null;
+    }
+
+    /**
+     * Returns the last item of a List that matches the predicate.
+     * @param haystack The List to search.
+     * @param condition The predicate to match.
+     * @param <T> The type of element in the list.
+     * @return The last element matching the predicate, or null if none.
+     */
+    // There is no way to reverse iterate a Collection in Java (e.g. the collection may
+    // be a single-linked list), so implementing this on Collection is necessarily very
+    // wasteful (store and reverse a copy, test all elements, or recurse to the end of the
+    // list to test on the up path and possibly blow the call stack)
+    @Nullable
+    public static <T> T findLast(List<T> haystack, Predicate<? super T> condition) {
+        for (int i = haystack.size() - 1; i >= 0; --i) {
+            final T needle = haystack.get(i);
+            if (condition.test(needle)) return needle;
+        }
+        return null;
+    }
 }
diff --git a/staticlibs/framework/com/android/net/module/util/IpRange.java b/staticlibs/framework/com/android/net/module/util/IpRange.java
index 40b57b1..0a3f95b 100644
--- a/staticlibs/framework/com/android/net/module/util/IpRange.java
+++ b/staticlibs/framework/com/android/net/module/util/IpRange.java
@@ -200,7 +200,7 @@
 
     @Override
     public int hashCode() {
-        return Objects.hash(mStartAddr, mEndAddr);
+        return Objects.hash(Arrays.hashCode(mStartAddr), Arrays.hashCode(mEndAddr));
     }
 
     @Override
diff --git a/staticlibs/framework/com/android/net/module/util/PerUidCounter.java b/staticlibs/framework/com/android/net/module/util/PerUidCounter.java
index 0b2de7a..463b0c4 100644
--- a/staticlibs/framework/com/android/net/module/util/PerUidCounter.java
+++ b/staticlibs/framework/com/android/net/module/util/PerUidCounter.java
@@ -32,7 +32,7 @@
 
     // Map from UID to count that UID has filed.
     @VisibleForTesting
-    @GuardedBy("mUidToCount")
+    @GuardedBy("this")
     final SparseIntArray mUidToCount = new SparseIntArray();
 
     /**
@@ -57,15 +57,8 @@
      *
      * @param uid the uid that the counter was made under
      */
-    public void incrementCountOrThrow(final int uid) {
-        incrementCountOrThrow(uid, 1 /* numToIncrement */);
-    }
-
-    public synchronized void incrementCountOrThrow(final int uid, final int numToIncrement) {
-        if (numToIncrement <= 0) {
-            throw new IllegalArgumentException("Increment count must be positive");
-        }
-        final long newCount = ((long) mUidToCount.get(uid, 0)) + numToIncrement;
+    public synchronized void incrementCountOrThrow(final int uid) {
+        final long newCount = ((long) mUidToCount.get(uid, 0)) + 1;
         if (newCount > mMaxCountPerUid) {
             throw new IllegalStateException("Uid " + uid + " exceeded its allowed limit");
         }
@@ -83,15 +76,8 @@
      *
      * @param uid the uid that the count was made under
      */
-    public void decrementCountOrThrow(final int uid) {
-        decrementCountOrThrow(uid, 1 /* numToDecrement */);
-    }
-
-    public synchronized void decrementCountOrThrow(final int uid, final int numToDecrement) {
-        if (numToDecrement <= 0) {
-            throw new IllegalArgumentException("Decrement count must be positive");
-        }
-        final int newCount = mUidToCount.get(uid, 0) - numToDecrement;
+    public synchronized void decrementCountOrThrow(final int uid) {
+        final int newCount = mUidToCount.get(uid, 0) - 1;
         if (newCount < 0) {
             throw new IllegalStateException("BUG: too small count " + newCount + " for UID " + uid);
         } else if (newCount == 0) {
@@ -100,4 +86,9 @@
             mUidToCount.put(uid, newCount);
         }
     }
+
+    @VisibleForTesting
+    public synchronized int get(int uid) {
+        return mUidToCount.get(uid, 0);
+    }
 }
diff --git a/staticlibs/tests/unit/src/com/android/net/module/util/BpfDumpTest.java b/staticlibs/tests/unit/src/com/android/net/module/util/BpfDumpTest.java
index b166b4a..395011c 100644
--- a/staticlibs/tests/unit/src/com/android/net/module/util/BpfDumpTest.java
+++ b/staticlibs/tests/unit/src/com/android/net/module/util/BpfDumpTest.java
@@ -17,6 +17,9 @@
 package com.android.net.module.util;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThrows;
+
+import android.util.Pair;
 
 import androidx.test.filters.SmallTest;
 import androidx.test.runner.AndroidJUnit4;
@@ -27,17 +30,53 @@
 @RunWith(AndroidJUnit4.class)
 @SmallTest
 public class BpfDumpTest {
+    private static final int TEST_KEY = 123;
+    private static final String TEST_KEY_BASE64 = "ewAAAA==";
+    private static final int TEST_VAL = 456;
+    private static final String TEST_VAL_BASE64 = "yAEAAA==";
+    private static final String BASE64_DELIMITER = ",";
+    private static final String TEST_KEY_VAL_BASE64 =
+            TEST_KEY_BASE64 + BASE64_DELIMITER + TEST_VAL_BASE64;
+    private static final String INVALID_BASE64_STRING = "Map is null";
+
     @Test
     public void testToBase64EncodedString() {
-        final Struct.U32 key = new Struct.U32(123);
-        final Struct.U32 value = new Struct.U32(456);
+        final Struct.U32 key = new Struct.U32(TEST_KEY);
+        final Struct.U32 value = new Struct.U32(TEST_VAL);
 
         // Verified in python:
         //   import base64
-        //   print(base64.b64encode(b'\x7b\x00\x00\x00')) # key: ewAAAA==
-        //   print(base64.b64encode(b'\xc8\x01\x00\x00')) # value: yAEAAA==
+        //   print(base64.b64encode(b'\x7b\x00\x00\x00')) # key: ewAAAA== (TEST_KEY_BASE64)
+        //   print(base64.b64encode(b'\xc8\x01\x00\x00')) # value: yAEAAA== (TEST_VAL_BASE64)
         assertEquals("7B000000", HexDump.toHexString(key.writeToBytes()));
         assertEquals("C8010000", HexDump.toHexString(value.writeToBytes()));
-        assertEquals("ewAAAA==,yAEAAA==", BpfDump.toBase64EncodedString(key, value));
+        assertEquals(TEST_KEY_VAL_BASE64, BpfDump.toBase64EncodedString(key, value));
+    }
+
+    @Test
+    public void testFromBase64EncodedString() {
+        Pair<Struct.U32, Struct.U32> decodedKeyValue = BpfDump.fromBase64EncodedString(
+                Struct.U32.class, Struct.U32.class, TEST_KEY_VAL_BASE64);
+        assertEquals(TEST_KEY, decodedKeyValue.first.val);
+        assertEquals(TEST_VAL, decodedKeyValue.second.val);
+    }
+
+    private void assertThrowsIllegalArgumentException(final String testStr) {
+        assertThrows(IllegalArgumentException.class,
+                () -> BpfDump.fromBase64EncodedString(Struct.U32.class, Struct.U32.class, testStr));
+    }
+
+    @Test
+    public void testFromBase64EncodedStringInvalidString() {
+        assertThrowsIllegalArgumentException(INVALID_BASE64_STRING);
+        assertThrowsIllegalArgumentException(TEST_KEY_BASE64);
+        assertThrowsIllegalArgumentException(
+                TEST_KEY_BASE64 + BASE64_DELIMITER + INVALID_BASE64_STRING);
+        assertThrowsIllegalArgumentException(
+                INVALID_BASE64_STRING + BASE64_DELIMITER + TEST_VAL_BASE64);
+        assertThrowsIllegalArgumentException(
+                INVALID_BASE64_STRING + BASE64_DELIMITER + INVALID_BASE64_STRING);
+        assertThrowsIllegalArgumentException(
+                TEST_KEY_VAL_BASE64 + BASE64_DELIMITER + TEST_KEY_BASE64);
     }
 }
diff --git a/staticlibs/tests/unit/src/com/android/net/module/util/CollectionUtilsTest.kt b/staticlibs/tests/unit/src/com/android/net/module/util/CollectionUtilsTest.kt
index 911483a..0991352 100644
--- a/staticlibs/tests/unit/src/com/android/net/module/util/CollectionUtilsTest.kt
+++ b/staticlibs/tests/unit/src/com/android/net/module/util/CollectionUtilsTest.kt
@@ -18,10 +18,13 @@
 
 import androidx.test.filters.SmallTest
 import androidx.test.runner.AndroidJUnit4
+import com.android.testutils.assertThrows
 import org.junit.Test
 import org.junit.runner.RunWith
 import kotlin.test.assertEquals
 import kotlin.test.assertFalse
+import kotlin.test.assertNull
+import kotlin.test.assertSame
 import kotlin.test.assertTrue
 
 @RunWith(AndroidJUnit4::class)
@@ -50,6 +53,21 @@
     }
 
     @Test
+    fun testIndexOfSubArray() {
+        val haystack = byteArrayOf(1, 2, 3, 4, 5)
+        assertEquals(2, CollectionUtils.indexOfSubArray(haystack, byteArrayOf(3, 4)))
+        assertEquals(3, CollectionUtils.indexOfSubArray(haystack, byteArrayOf(4, 5)))
+        assertEquals(4, CollectionUtils.indexOfSubArray(haystack, byteArrayOf(5)))
+        assertEquals(-1, CollectionUtils.indexOfSubArray(haystack, byteArrayOf(3, 2)))
+        assertEquals(0, CollectionUtils.indexOfSubArray(haystack, byteArrayOf()))
+        assertEquals(-1, CollectionUtils.indexOfSubArray(byteArrayOf(), byteArrayOf(3, 2)))
+        assertEquals(0, CollectionUtils.indexOfSubArray(byteArrayOf(), byteArrayOf()))
+        assertThrows(NullPointerException::class.java) {
+            CollectionUtils.indexOfSubArray(haystack, null)
+        }
+    }
+
+    @Test
     fun testAll() {
         assertFalse(CollectionUtils.all(listOf("A", "B", "C", "D", "E")) { it != "E" })
         assertTrue(CollectionUtils.all(listOf("A", "B", "C", "D", "E")) { it != "F" })
@@ -86,4 +104,27 @@
         assertEquals(3, CollectionUtils.total(longArrayOf(1, 1, 1)))
         assertEquals(0, CollectionUtils.total(null))
     }
+
+    @Test
+    fun testFindFirstFindLast() {
+        val listAE = listOf("A", "B", "C", "D", "E")
+        assertSame(CollectionUtils.findFirst(listAE) { it == "A" }, listAE[0])
+        assertSame(CollectionUtils.findFirst(listAE) { it == "B" }, listAE[1])
+        assertSame(CollectionUtils.findFirst(listAE) { it == "E" }, listAE[4])
+        assertNull(CollectionUtils.findFirst(listAE) { it == "F" })
+        assertSame(CollectionUtils.findLast(listAE) { it == "A" }, listAE[0])
+        assertSame(CollectionUtils.findLast(listAE) { it == "B" }, listAE[1])
+        assertSame(CollectionUtils.findLast(listAE) { it == "E" }, listAE[4])
+        assertNull(CollectionUtils.findLast(listAE) { it == "F" })
+
+        val listMulti = listOf("A", "B", "A", "C", "D", "E", "A", "E")
+        assertSame(CollectionUtils.findFirst(listMulti) { it == "A" }, listMulti[0])
+        assertSame(CollectionUtils.findFirst(listMulti) { it == "B" }, listMulti[1])
+        assertSame(CollectionUtils.findFirst(listMulti) { it == "E" }, listMulti[5])
+        assertNull(CollectionUtils.findFirst(listMulti) { it == "F" })
+        assertSame(CollectionUtils.findLast(listMulti) { it == "A" }, listMulti[6])
+        assertSame(CollectionUtils.findLast(listMulti) { it == "B" }, listMulti[1])
+        assertSame(CollectionUtils.findLast(listMulti) { it == "E" }, listMulti[7])
+        assertNull(CollectionUtils.findLast(listMulti) { it == "F" })
+    }
 }
diff --git a/staticlibs/tests/unit/src/com/android/net/module/util/PerUidCounterTest.kt b/staticlibs/tests/unit/src/com/android/net/module/util/PerUidCounterTest.kt
index 0f2d52a..321fe59 100644
--- a/staticlibs/tests/unit/src/com/android/net/module/util/PerUidCounterTest.kt
+++ b/staticlibs/tests/unit/src/com/android/net/module/util/PerUidCounterTest.kt
@@ -20,6 +20,7 @@
 import androidx.test.runner.AndroidJUnit4
 import org.junit.Test
 import org.junit.runner.RunWith
+import kotlin.test.assertEquals
 import kotlin.test.assertFailsWith
 
 @RunWith(AndroidJUnit4::class)
@@ -27,6 +28,7 @@
 class PerUidCounterTest {
     private val UID_A = 1000
     private val UID_B = 1001
+    private val UID_C = 1002
 
     @Test
     fun testCounterMaximum() {
@@ -37,31 +39,35 @@
             PerUidCounter(0)
         }
 
-        val largeMaxCounter = PerUidCounter(Integer.MAX_VALUE)
-        largeMaxCounter.incrementCountOrThrow(UID_A, Integer.MAX_VALUE)
-        assertFailsWith<IllegalStateException> {
-            largeMaxCounter.incrementCountOrThrow(UID_A)
+        val testLimit = 1000
+        val testCounter = PerUidCounter(testLimit)
+        assertEquals(0, testCounter[UID_A])
+        repeat(testLimit) {
+            testCounter.incrementCountOrThrow(UID_A)
         }
+        assertEquals(testLimit, testCounter[UID_A])
+        assertFailsWith<IllegalStateException> {
+            testCounter.incrementCountOrThrow(UID_A)
+        }
+        assertEquals(testLimit, testCounter[UID_A])
     }
 
     @Test
     fun testIncrementCountOrThrow() {
         val counter = PerUidCounter(3)
 
-        // Verify the increment count cannot be zero.
-        assertFailsWith<IllegalArgumentException> {
-            counter.incrementCountOrThrow(UID_A, 0)
-        }
-
         // Verify the counters work independently.
         counter.incrementCountOrThrow(UID_A)
-        counter.incrementCountOrThrow(UID_B, 2)
+        counter.incrementCountOrThrow(UID_B)
         counter.incrementCountOrThrow(UID_B)
         counter.incrementCountOrThrow(UID_A)
         counter.incrementCountOrThrow(UID_A)
+        assertEquals(3, counter[UID_A])
+        assertEquals(2, counter[UID_B])
         assertFailsWith<IllegalStateException> {
             counter.incrementCountOrThrow(UID_A)
         }
+        counter.incrementCountOrThrow(UID_B)
         assertFailsWith<IllegalStateException> {
             counter.incrementCountOrThrow(UID_B)
         }
@@ -71,39 +77,66 @@
             counter.incrementCountOrThrow(UID_A)
         }
         assertFailsWith<IllegalStateException> {
-            counter.incrementCountOrThrow(UID_A, 3)
+            repeat(3) {
+                counter.incrementCountOrThrow(UID_A)
+            }
         }
+        assertEquals(3, counter[UID_A])
+        assertEquals(3, counter[UID_B])
+        assertEquals(0, counter[UID_C])
     }
 
     @Test
     fun testDecrementCountOrThrow() {
         val counter = PerUidCounter(3)
 
-        // Verify the decrement count cannot be zero.
-        assertFailsWith<IllegalArgumentException> {
-            counter.decrementCountOrThrow(UID_A, 0)
-        }
-
         // Verify the count cannot go below zero.
         assertFailsWith<IllegalStateException> {
             counter.decrementCountOrThrow(UID_A)
         }
         assertFailsWith<IllegalStateException> {
-            counter.decrementCountOrThrow(UID_A, 5)
-        }
-        assertFailsWith<IllegalStateException> {
-            counter.decrementCountOrThrow(UID_A, Integer.MAX_VALUE)
+            repeat(5) {
+                counter.decrementCountOrThrow(UID_A)
+            }
         }
 
         // Verify the counters work independently.
         counter.incrementCountOrThrow(UID_A)
         counter.incrementCountOrThrow(UID_B)
+        assertEquals(1, counter[UID_A])
+        assertEquals(1, counter[UID_B])
         assertFailsWith<IllegalStateException> {
-            counter.decrementCountOrThrow(UID_A, 3)
+            repeat(3) {
+                counter.decrementCountOrThrow(UID_A)
+            }
         }
-        counter.decrementCountOrThrow(UID_A)
         assertFailsWith<IllegalStateException> {
             counter.decrementCountOrThrow(UID_A)
         }
+        assertEquals(0, counter[UID_A])
+        assertEquals(1, counter[UID_B])
+
+        // Verify mixing increment and decrement.
+        val largeCounter = PerUidCounter(100)
+        repeat(90) {
+            largeCounter.incrementCountOrThrow(UID_A)
+        }
+        repeat(70) {
+            largeCounter.decrementCountOrThrow(UID_A)
+        }
+        repeat(80) {
+            largeCounter.incrementCountOrThrow(UID_A)
+        }
+        assertFailsWith<IllegalStateException> {
+            largeCounter.incrementCountOrThrow(UID_A)
+        }
+        assertEquals(100, largeCounter[UID_A])
+        repeat(100) {
+            largeCounter.decrementCountOrThrow(UID_A)
+        }
+        assertFailsWith<IllegalStateException> {
+            largeCounter.decrementCountOrThrow(UID_A)
+        }
+        assertEquals(0, largeCounter[UID_A])
     }
 }
\ No newline at end of file
diff --git a/staticlibs/tests/unit/src/com/android/net/module/util/netlink/StructInetDiagSockIdTest.java b/staticlibs/tests/unit/src/com/android/net/module/util/netlink/StructInetDiagSockIdTest.java
new file mode 100644
index 0000000..ce190f2
--- /dev/null
+++ b/staticlibs/tests/unit/src/com/android/net/module/util/netlink/StructInetDiagSockIdTest.java
@@ -0,0 +1,225 @@
+/*
+ * 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.net.module.util.netlink;
+
+import static android.system.OsConstants.AF_INET;
+import static android.system.OsConstants.AF_INET6;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+
+import android.net.InetAddresses;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.net.Inet4Address;
+import java.net.Inet6Address;
+import java.net.InetSocketAddress;
+import java.nio.ByteBuffer;
+
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class StructInetDiagSockIdTest {
+    private static final Inet4Address IPV4_SRC_ADDR =
+            (Inet4Address) InetAddresses.parseNumericAddress("192.0.2.1");
+    private static final Inet4Address IPV4_DST_ADDR =
+            (Inet4Address) InetAddresses.parseNumericAddress("198.51.100.1");
+    private static final Inet6Address IPV6_SRC_ADDR =
+            (Inet6Address) InetAddresses.parseNumericAddress("2001:db8::1");
+    private static final Inet6Address IPV6_DST_ADDR =
+            (Inet6Address) InetAddresses.parseNumericAddress("2001:db8::2");
+    private static final int SRC_PORT = 65297;
+    private static final int DST_PORT = 443;
+    private static final int IF_INDEX = 7;
+    private static final long COOKIE = 561;
+
+    private static final byte[] INET_DIAG_SOCKET_ID_IPV4 =
+            new byte[] {
+                    // src port, dst port
+                    (byte) 0xff, (byte) 0x11, (byte) 0x01, (byte) 0xbb,
+                    // src address
+                    (byte) 0xc0, (byte) 0x00, (byte) 0x02, (byte) 0x01,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    // dst address
+                    (byte) 0xc6, (byte) 0x33, (byte) 0x64, (byte) 0x01,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    // if index
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    // cookie
+                    (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
+                    (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff
+            };
+
+    private static final byte[] INET_DIAG_SOCKET_ID_IPV4_IF_COOKIE =
+            new byte[] {
+                    // src port, dst port
+                    (byte) 0xff, (byte) 0x11, (byte) 0x01, (byte) 0xbb,
+                    // src address
+                    (byte) 0xc0, (byte) 0x00, (byte) 0x02, (byte) 0x01,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    // dst address
+                    (byte) 0xc6, (byte) 0x33, (byte) 0x64, (byte) 0x01,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    // if index
+                    (byte) 0x07, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    // cookie
+                    (byte) 0x31, (byte) 0x02, (byte) 0x00, (byte) 0x00,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+            };
+
+    private static final byte[] INET_DIAG_SOCKET_ID_IPV6 =
+            new byte[] {
+                    // src port, dst port
+                    (byte) 0xff, (byte) 0x11, (byte) 0x01, (byte) 0xbb,
+                    // src address
+                    (byte) 0x20, (byte) 0x01, (byte) 0x0d, (byte) 0xb8,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01,
+                    // dst address
+                    (byte) 0x20, (byte) 0x01, (byte) 0x0d, (byte) 0xb8,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x02,
+                    // if index
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    // cookie
+                    (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
+                    (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff
+            };
+
+    private static final byte[] INET_DIAG_SOCKET_ID_IPV6_IF_COOKIE =
+            new byte[] {
+                    // src port, dst port
+                    (byte) 0xff, (byte) 0x11, (byte) 0x01, (byte) 0xbb,
+                    // src address
+                    (byte) 0x20, (byte) 0x01, (byte) 0x0d, (byte) 0xb8,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01,
+                    // dst address
+                    (byte) 0x20, (byte) 0x01, (byte) 0x0d, (byte) 0xb8,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x02,
+                    // if index
+                    (byte) 0x07, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    // cookie
+                    (byte) 0x31, (byte) 0x02, (byte) 0x00, (byte) 0x00,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+            };
+
+    @Test
+    public void testPackStructInetDiagSockIdWithIpv4() {
+        final InetSocketAddress srcAddr = new InetSocketAddress(IPV4_SRC_ADDR, SRC_PORT);
+        final InetSocketAddress dstAddr = new InetSocketAddress(IPV4_DST_ADDR, DST_PORT);
+        final StructInetDiagSockId sockId = new StructInetDiagSockId(srcAddr, dstAddr);
+        final ByteBuffer buffer = ByteBuffer.allocate(StructInetDiagSockId.STRUCT_SIZE);
+        sockId.pack(buffer);
+        assertArrayEquals(INET_DIAG_SOCKET_ID_IPV4, buffer.array());
+    }
+
+    @Test
+    public void testPackStructInetDiagSockIdWithIpv6() {
+        final InetSocketAddress srcAddr = new InetSocketAddress(IPV6_SRC_ADDR, SRC_PORT);
+        final InetSocketAddress dstAddr = new InetSocketAddress(IPV6_DST_ADDR, DST_PORT);
+        final StructInetDiagSockId sockId = new StructInetDiagSockId(srcAddr, dstAddr);
+        final ByteBuffer buffer = ByteBuffer.allocate(StructInetDiagSockId.STRUCT_SIZE);
+        sockId.pack(buffer);
+        assertArrayEquals(INET_DIAG_SOCKET_ID_IPV6, buffer.array());
+    }
+
+    @Test
+    public void testPackStructInetDiagSockIdWithIpv4IfIndexCookie() {
+        final InetSocketAddress srcAddr = new InetSocketAddress(IPV4_SRC_ADDR, SRC_PORT);
+        final InetSocketAddress dstAddr = new InetSocketAddress(IPV4_DST_ADDR, DST_PORT);
+        final StructInetDiagSockId sockId =
+                new StructInetDiagSockId(srcAddr, dstAddr, IF_INDEX, COOKIE);
+        final ByteBuffer buffer = ByteBuffer.allocate(StructInetDiagSockId.STRUCT_SIZE);
+        sockId.pack(buffer);
+        assertArrayEquals(INET_DIAG_SOCKET_ID_IPV4_IF_COOKIE, buffer.array());
+    }
+
+    @Test
+    public void testPackStructInetDiagSockIdWithIpv6IfIndexCookie() {
+        final InetSocketAddress srcAddr = new InetSocketAddress(IPV6_SRC_ADDR, SRC_PORT);
+        final InetSocketAddress dstAddr = new InetSocketAddress(IPV6_DST_ADDR, DST_PORT);
+        final StructInetDiagSockId sockId =
+                new StructInetDiagSockId(srcAddr, dstAddr, IF_INDEX, COOKIE);
+        final ByteBuffer buffer = ByteBuffer.allocate(StructInetDiagSockId.STRUCT_SIZE);
+        sockId.pack(buffer);
+        assertArrayEquals(INET_DIAG_SOCKET_ID_IPV6_IF_COOKIE, buffer.array());
+    }
+
+    @Test
+    public void testParseStructInetDiagSockIdWithIpv4() {
+        final ByteBuffer buffer = ByteBuffer.wrap(INET_DIAG_SOCKET_ID_IPV4_IF_COOKIE);
+        final StructInetDiagSockId sockId = StructInetDiagSockId.parse(buffer, (byte) AF_INET);
+
+        assertEquals(SRC_PORT, sockId.locSocketAddress.getPort());
+        assertEquals(IPV4_SRC_ADDR, sockId.locSocketAddress.getAddress());
+        assertEquals(DST_PORT, sockId.remSocketAddress.getPort());
+        assertEquals(IPV4_DST_ADDR, sockId.remSocketAddress.getAddress());
+        assertEquals(IF_INDEX, sockId.ifIndex);
+        assertEquals(COOKIE, sockId.cookie);
+    }
+
+    @Test
+    public void testParseStructInetDiagSockIdWithIpv6() {
+        final ByteBuffer buffer = ByteBuffer.wrap(INET_DIAG_SOCKET_ID_IPV6_IF_COOKIE);
+        final StructInetDiagSockId sockId = StructInetDiagSockId.parse(buffer, (byte) AF_INET6);
+
+        assertEquals(SRC_PORT, sockId.locSocketAddress.getPort());
+        assertEquals(IPV6_SRC_ADDR, sockId.locSocketAddress.getAddress());
+        assertEquals(DST_PORT, sockId.remSocketAddress.getPort());
+        assertEquals(IPV6_DST_ADDR, sockId.remSocketAddress.getAddress());
+        assertEquals(IF_INDEX, sockId.ifIndex);
+        assertEquals(COOKIE, sockId.cookie);
+    }
+
+    @Test
+    public void testToStringStructInetDiagSockIdWithIpv4() {
+        final InetSocketAddress srcAddr = new InetSocketAddress(IPV4_SRC_ADDR, SRC_PORT);
+        final InetSocketAddress dstAddr = new InetSocketAddress(IPV4_DST_ADDR, DST_PORT);
+        final StructInetDiagSockId sockId = new StructInetDiagSockId(srcAddr, dstAddr);
+        assertEquals("StructInetDiagSockId{ idiag_sport{65297}, idiag_dport{443},"
+                + " idiag_src{192.0.2.1}, idiag_dst{198.51.100.1}, idiag_if{0},"
+                + " idiag_cookie{INET_DIAG_NOCOOKIE}}", sockId.toString());
+    }
+
+    @Test
+    public void testToStringStructInetDiagSockIdWithIpv6() {
+        final InetSocketAddress srcAddr = new InetSocketAddress(IPV6_SRC_ADDR, SRC_PORT);
+        final InetSocketAddress dstAddr = new InetSocketAddress(IPV6_DST_ADDR, DST_PORT);
+        final StructInetDiagSockId sockId = new StructInetDiagSockId(srcAddr, dstAddr);
+        assertEquals("StructInetDiagSockId{ idiag_sport{65297}, idiag_dport{443},"
+                + " idiag_src{2001:db8::1}, idiag_dst{2001:db8::2}, idiag_if{0},"
+                + " idiag_cookie{INET_DIAG_NOCOOKIE}}", sockId.toString());
+    }
+}
diff --git a/staticlibs/testutils/app/connectivitychecker/src/com/android/testutils/connectivitychecker/ConnectivityCheckTest.kt b/staticlibs/testutils/app/connectivitychecker/src/com/android/testutils/connectivitychecker/ConnectivityCheckTest.kt
index 43b130b..f34ca22 100644
--- a/staticlibs/testutils/app/connectivitychecker/src/com/android/testutils/connectivitychecker/ConnectivityCheckTest.kt
+++ b/staticlibs/testutils/app/connectivitychecker/src/com/android/testutils/connectivitychecker/ConnectivityCheckTest.kt
@@ -18,10 +18,17 @@
 
 import android.content.pm.PackageManager.FEATURE_TELEPHONY
 import android.content.pm.PackageManager.FEATURE_WIFI
+import android.net.ConnectivityManager
+import android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET
+import android.net.NetworkCapabilities.TRANSPORT_CELLULAR
+import android.net.NetworkRequest
 import android.telephony.TelephonyManager
 import androidx.test.ext.junit.runners.AndroidJUnit4
 import androidx.test.platform.app.InstrumentationRegistry
 import com.android.testutils.ConnectUtil
+import com.android.testutils.RecorderCallback
+import com.android.testutils.TestableNetworkCallback
+import com.android.testutils.tryTest
 import org.junit.Test
 import org.junit.runner.RunWith
 import kotlin.test.assertTrue
@@ -61,5 +68,20 @@
         assertTrue(tm.isDataConnectivityPossible,
             "The device is not setup with a SIM card that supports data connectivity. " +
                     commonError)
+        val cb = TestableNetworkCallback()
+        val cm = context.getSystemService(ConnectivityManager::class.java)
+                ?: fail("Could not get ConnectivityManager")
+        cm.registerNetworkCallback(
+                NetworkRequest.Builder()
+                        .addTransportType(TRANSPORT_CELLULAR)
+                        .addCapability(NET_CAPABILITY_INTERNET).build(), cb)
+        tryTest {
+            cb.eventuallyExpectOrNull<RecorderCallback.CallbackEntry.Available>()
+                    ?: fail("The device does not have mobile data available. Check that it is " +
+                            "setup with a SIM card that has a working data plan, and that the " +
+                            "APN configuration is valid.")
+        } cleanup {
+            cm.unregisterNetworkCallback(cb)
+        }
     }
 }
\ No newline at end of file
diff --git a/staticlibs/testutils/devicetests/com/android/testutils/TestPermissionUtil.kt b/staticlibs/testutils/devicetests/com/android/testutils/TestPermissionUtil.kt
index a4dbd9a..f571f64 100644
--- a/staticlibs/testutils/devicetests/com/android/testutils/TestPermissionUtil.kt
+++ b/staticlibs/testutils/devicetests/com/android/testutils/TestPermissionUtil.kt
@@ -20,8 +20,8 @@
 
 import androidx.test.platform.app.InstrumentationRegistry
 import com.android.modules.utils.build.SdkLevel
-import com.android.testutils.ExceptionUtils.ThrowingRunnable
-import com.android.testutils.ExceptionUtils.ThrowingSupplier
+import com.android.testutils.FunctionalUtils.ThrowingRunnable
+import com.android.testutils.FunctionalUtils.ThrowingSupplier
 
 /**
  * Run the specified [task] with the specified [permissions] obtained through shell
diff --git a/staticlibs/testutils/hostdevice/com/android/testutils/Cleanup.kt b/staticlibs/testutils/hostdevice/com/android/testutils/Cleanup.kt
index 3db357b..9f28234 100644
--- a/staticlibs/testutils/hostdevice/com/android/testutils/Cleanup.kt
+++ b/staticlibs/testutils/hostdevice/com/android/testutils/Cleanup.kt
@@ -18,8 +18,8 @@
 
 package com.android.testutils
 
-import com.android.testutils.ExceptionUtils.ThrowingRunnable
-import com.android.testutils.ExceptionUtils.ThrowingSupplier
+import com.android.testutils.FunctionalUtils.ThrowingRunnable
+import com.android.testutils.FunctionalUtils.ThrowingSupplier
 import javax.annotation.CheckReturnValue
 
 /**
diff --git a/staticlibs/testutils/hostdevice/com/android/testutils/ExceptionUtils.java b/staticlibs/testutils/hostdevice/com/android/testutils/FunctionalUtils.java
similarity index 74%
rename from staticlibs/testutils/hostdevice/com/android/testutils/ExceptionUtils.java
rename to staticlibs/testutils/hostdevice/com/android/testutils/FunctionalUtils.java
index d3bda98..da36e4d 100644
--- a/staticlibs/testutils/hostdevice/com/android/testutils/ExceptionUtils.java
+++ b/staticlibs/testutils/hostdevice/com/android/testutils/FunctionalUtils.java
@@ -21,7 +21,7 @@
 /**
  * A class grouping some utilities to deal with exceptions.
  */
-public class ExceptionUtils {
+public class FunctionalUtils {
     /**
      * Like a Consumer, but declared to throw an exception.
      * @param <T>
@@ -79,4 +79,21 @@
             }
         };
     }
+
+    // Java has Function<T, R> and BiFunction<T, U, V> but nothing for higher-arity functions.
+    // Function3 is what Kotlin and Scala use (they also have higher-arity variants, with
+    // FunctionN taking N arguments, as the JVM does not have variadic formal parameters)
+    /**
+     * A function with three arguments.
+     * @param <TArg1> Type of the first argument
+     * @param <TArg2> Type of the second argument
+     * @param <TArg3> Type of the third argument
+     * @param <TResult> Type of the return value
+     */
+    public interface Function3<TArg1, TArg2, TArg3, TResult> {
+        /**
+         * Apply the function to the arguments
+         */
+        TResult apply(TArg1 a1, TArg2 a2, TArg3 a3);
+    }
 }
diff --git a/staticlibs/testutils/hostdevice/com/android/testutils/MiscAsserts.kt b/staticlibs/testutils/hostdevice/com/android/testutils/MiscAsserts.kt
index efd9402..1883387 100644
--- a/staticlibs/testutils/hostdevice/com/android/testutils/MiscAsserts.kt
+++ b/staticlibs/testutils/hostdevice/com/android/testutils/MiscAsserts.kt
@@ -18,7 +18,7 @@
 
 package com.android.testutils
 
-import com.android.testutils.ExceptionUtils.ThrowingRunnable
+import com.android.testutils.FunctionalUtils.ThrowingRunnable
 import java.lang.reflect.Modifier
 import kotlin.system.measureTimeMillis
 import kotlin.test.assertEquals