Merge changes Ibf58f981,I2c007222,I23d13c71,I4c1a8be6,I96e4c083, ...

* changes:
  gn2bp: add support for building against Android zlib
  gn2bp: support architecture in builtin_deps
  gn2bp: correctly flatten source_sets under linker unit target
  gn2bp: add is_linker_unit_type helper to Target
  gn2bp: fix include dir denylist
  gn2bp: fix Android.bp.swp
diff --git a/framework/api/system-current.txt b/framework/api/system-current.txt
index 0b0f2bb..dd3404c 100644
--- a/framework/api/system-current.txt
+++ b/framework/api/system-current.txt
@@ -515,8 +515,8 @@
     ctor public VpnTransportInfo(int, @Nullable String, boolean, boolean);
     method public boolean areLongLivedTcpConnectionsExpensive();
     method public int describeContents();
-    method public boolean getBypassable();
     method public int getType();
+    method public boolean isBypassable();
     method public void writeToParcel(@NonNull android.os.Parcel, int);
     field @NonNull public static final android.os.Parcelable.Creator<android.net.VpnTransportInfo> CREATOR;
   }
diff --git a/framework/src/android/net/VpnTransportInfo.java b/framework/src/android/net/VpnTransportInfo.java
index e335c0f..6bb00c8 100644
--- a/framework/src/android/net/VpnTransportInfo.java
+++ b/framework/src/android/net/VpnTransportInfo.java
@@ -86,7 +86,7 @@
         // When the module runs on older SDKs, |bypassable| will always be false since the old Vpn
         // code will call this constructor. For Settings VPNs, this is always correct as they are
         // never bypassable. For VpnManager and VpnService types, this may be wrong since both of
-        // them have a choice. However, on these SDKs VpnTransportInfo#getBypassable is not
+        // them have a choice. However, on these SDKs VpnTransportInfo#isBypassable is not
         // available anyway, so this should be harmless. False is a better choice than true here
         // regardless because it is the default value for both VpnManager and VpnService if the app
         // does not do anything about it.
@@ -111,7 +111,7 @@
      * {@code UnsupportedOperationException} if called.
      */
     @RequiresApi(UPSIDE_DOWN_CAKE)
-    public boolean getBypassable() {
+    public boolean isBypassable() {
         if (!SdkLevel.isAtLeastU()) {
             throw new UnsupportedOperationException("Not supported before U");
         }
@@ -134,7 +134,7 @@
      * VPNs can be bypassable or not. When the VPN is not bypassable, the user has
      * expressed explicit intent to have no connection outside of the VPN, so even
      * privileged apps with permission to bypass non-bypassable VPNs should not do
-     * so. See {@link #getBypassable()}.
+     * so. See {@link #isBypassable()}.
      * For bypassable VPNs however, the user expects apps choose reasonable tradeoffs
      * about whether they use the VPN.
      *
diff --git a/service/mdns/com/android/server/connectivity/mdns/MdnsAnnouncer.java b/service/mdns/com/android/server/connectivity/mdns/MdnsAnnouncer.java
new file mode 100644
index 0000000..91e08a8
--- /dev/null
+++ b/service/mdns/com/android/server/connectivity/mdns/MdnsAnnouncer.java
@@ -0,0 +1,99 @@
+/*
+ * 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.server.connectivity.mdns;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.os.Looper;
+
+import com.android.internal.annotations.VisibleForTesting;
+
+import java.net.SocketAddress;
+import java.util.Collections;
+import java.util.List;
+import java.util.function.Supplier;
+
+/**
+ * Sends mDns announcements when a service registration changes and at regular intervals.
+ *
+ * This allows maintaining other hosts' caches up-to-date. See RFC6762 8.3.
+ */
+public class MdnsAnnouncer extends MdnsPacketRepeater<MdnsAnnouncer.AnnouncementInfo> {
+    private static final long ANNOUNCEMENT_INITIAL_DELAY_MS = 1000L;
+    @VisibleForTesting
+    static final int ANNOUNCEMENT_COUNT = 8;
+
+    @NonNull
+    private final String mLogTag;
+
+    static class AnnouncementInfo implements MdnsPacketRepeater.Request {
+        @NonNull
+        private final MdnsPacket mPacket;
+        @NonNull
+        private final Supplier<Iterable<SocketAddress>> mDestinationsSupplier;
+
+        AnnouncementInfo(List<MdnsRecord> announcedRecords, List<MdnsRecord> additionalRecords,
+                Supplier<Iterable<SocketAddress>> destinationsSupplier) {
+            // Records to announce (as answers)
+            // Records to place in the "Additional records", with NSEC negative responses
+            // to mark records that have been verified unique
+            final int flags = 0x8400; // Response, authoritative (rfc6762 18.4)
+            mPacket = new MdnsPacket(flags,
+                    Collections.emptyList() /* questions */,
+                    announcedRecords,
+                    Collections.emptyList() /* authorityRecords */,
+                    additionalRecords);
+            mDestinationsSupplier = destinationsSupplier;
+        }
+
+        @Override
+        public MdnsPacket getPacket(int index) {
+            return mPacket;
+        }
+
+        @Override
+        public Iterable<SocketAddress> getDestinations(int index) {
+            return mDestinationsSupplier.get();
+        }
+
+        @Override
+        public long getDelayMs(int nextIndex) {
+            // Delay is doubled for each announcement
+            return ANNOUNCEMENT_INITIAL_DELAY_MS << (nextIndex - 1);
+        }
+
+        @Override
+        public int getNumSends() {
+            return ANNOUNCEMENT_COUNT;
+        }
+    }
+
+    public MdnsAnnouncer(@NonNull String interfaceTag, @NonNull Looper looper,
+            @NonNull MdnsReplySender replySender,
+            @Nullable PacketRepeaterCallback<AnnouncementInfo> cb) {
+        super(looper, replySender, cb);
+        mLogTag = MdnsAnnouncer.class.getSimpleName() + "/" + interfaceTag;
+    }
+
+    @Override
+    protected String getTag() {
+        return mLogTag;
+    }
+
+    // TODO: Notify MdnsRecordRepository that the records were announced for that service ID,
+    // so it can update the last advertised timestamp of the associated records.
+}
diff --git a/service/mdns/com/android/server/connectivity/mdns/MdnsPacketWriter.java b/service/mdns/com/android/server/connectivity/mdns/MdnsPacketWriter.java
index 1f22fa9..c0f9b8b 100644
--- a/service/mdns/com/android/server/connectivity/mdns/MdnsPacketWriter.java
+++ b/service/mdns/com/android/server/connectivity/mdns/MdnsPacketWriter.java
@@ -192,22 +192,31 @@
             }
         }
 
+        final int[] offsets;
         if (suffixLength > 0) {
-            for (int i = 0; i < (labels.length - suffixLength); ++i) {
-                writeString(labels[i]);
-            }
+            offsets = writePartialLabelsNoCompression(labels, labels.length - suffixLength);
             writePointer(suffixPointer);
         } else {
-            int[] offsets = writeLabelsNoCompression(labels);
-
-            // Add entries to the label dictionary for each suffix of the label list, including
-            // the whole list itself.
-            for (int i = 0, len = labels.length; i < labels.length; ++i, --len) {
-                String[] value = new String[len];
-                System.arraycopy(labels, i, value, 0, len);
-                labelDictionary.put(offsets[i], value);
-            }
+            offsets = writeLabelsNoCompression(labels);
         }
+
+        // Add entries to the label dictionary for each suffix of the label list, including
+        // the whole list itself.
+        // Do not replace the last suffixLength suffixes that already have dictionary entries.
+        for (int i = 0, len = labels.length; i < labels.length - suffixLength; ++i, --len) {
+            String[] value = new String[len];
+            System.arraycopy(labels, i, value, 0, len);
+            labelDictionary.put(offsets[i], value);
+        }
+    }
+
+    private int[] writePartialLabelsNoCompression(String[] labels, int count) throws IOException {
+        int[] offsets = new int[count];
+        for (int i = 0; i < count; ++i) {
+            offsets[i] = getWritePosition();
+            writeString(labels[i]);
+        }
+        return offsets;
     }
 
     /**
@@ -216,11 +225,7 @@
      * @return The offsets where each label was written to.
      */
     public int[] writeLabelsNoCompression(String[] labels) throws IOException {
-        int[] offsets = new int[labels.length];
-        for (int i = 0; i < labels.length; ++i) {
-            offsets[i] = getWritePosition();
-            writeString(labels[i]);
-        }
+        final int[] offsets = writePartialLabelsNoCompression(labels, labels.length);
         writeUInt8(0); // NUL terminator
         return offsets;
     }
@@ -246,4 +251,4 @@
     public DatagramPacket getPacket(SocketAddress destAddress) throws IOException {
         return new DatagramPacket(data, pos, destAddress);
     }
-}
\ No newline at end of file
+}
diff --git a/service/src/com/android/server/ConnectivityService.java b/service/src/com/android/server/ConnectivityService.java
index a44494c..d547d83 100755
--- a/service/src/com/android/server/ConnectivityService.java
+++ b/service/src/com/android/server/ConnectivityService.java
@@ -279,9 +279,10 @@
 import com.android.server.connectivity.NetworkNotificationManager;
 import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
 import com.android.server.connectivity.NetworkOffer;
+import com.android.server.connectivity.NetworkPreferenceList;
 import com.android.server.connectivity.NetworkRanker;
 import com.android.server.connectivity.PermissionMonitor;
-import com.android.server.connectivity.ProfileNetworkPreferenceList;
+import com.android.server.connectivity.ProfileNetworkPreferenceInfo;
 import com.android.server.connectivity.ProxyTracker;
 import com.android.server.connectivity.QosCallbackTracker;
 import com.android.server.connectivity.UidRangeUtils;
@@ -3413,7 +3414,7 @@
         if (!mProfileNetworkPreferences.isEmpty()) {
             pw.println("Profile preferences:");
             pw.increaseIndent();
-            pw.println(mProfileNetworkPreferences.preferences);
+            pw.println(mProfileNetworkPreferences);
             pw.decreaseIndent();
         }
         if (!mOemNetworkPreferences.isEmpty()) {
@@ -5498,10 +5499,8 @@
                     break;
                 }
                 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
-                    final Pair<List<ProfileNetworkPreferenceList.Preference>,
-                            IOnCompleteListener> arg =
-                            (Pair<List<ProfileNetworkPreferenceList.Preference>,
-                                    IOnCompleteListener>) msg.obj;
+                    final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
+                            (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
                     handleSetProfileNetworkPreference(arg.first, arg.second);
                     break;
                 }
@@ -6142,7 +6141,7 @@
     private void onUserRemoved(@NonNull final UserHandle user) {
         // If there was a network preference for this user, remove it.
         handleSetProfileNetworkPreference(
-                List.of(new ProfileNetworkPreferenceList.Preference(user, null, true)),
+                List.of(new ProfileNetworkPreferenceInfo(user, null, true)),
                 null /* listener */);
         if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
             handleSetOemNetworkPreference(mOemNetworkPreferences, null);
@@ -7112,8 +7111,8 @@
     // Current per-profile network preferences. This object follows the same threading rules as
     // the OEM network preferences above.
     @NonNull
-    private ProfileNetworkPreferenceList mProfileNetworkPreferences =
-            new ProfileNetworkPreferenceList();
+    private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
+            mProfileNetworkPreferences = new NetworkPreferenceList<>();
 
     // A set of UIDs that should use mobile data preferentially if available. This object follows
     // the same threading rules as the OEM network preferences above.
@@ -10816,7 +10815,7 @@
                     + "or the device owner must be set. ");
         }
 
-        final List<ProfileNetworkPreferenceList.Preference> preferenceList = new ArrayList<>();
+        final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
         boolean hasDefaultPreference = false;
         for (final ProfileNetworkPreference preference : preferences) {
             final NetworkCapabilities nc;
@@ -10863,8 +10862,7 @@
                     throw new IllegalArgumentException(
                             "Invalid preference in setProfileNetworkPreferences");
             }
-            preferenceList.add(new ProfileNetworkPreferenceList.Preference(
-                    profile, nc, allowFallback));
+            preferenceList.add(new ProfileNetworkPreferenceInfo(profile, nc, allowFallback));
             if (hasDefaultPreference && preferenceList.size() > 1) {
                 throw new IllegalArgumentException(
                         "Default profile preference should not be set along with other preference");
@@ -10913,9 +10911,9 @@
     }
 
     private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
-            @NonNull final ProfileNetworkPreferenceList prefs) {
+            @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
         final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
-        for (final ProfileNetworkPreferenceList.Preference pref : prefs.preferences) {
+        for (final ProfileNetworkPreferenceInfo pref : prefs) {
             // The NRI for a user should contain the request for capabilities.
             // If fallback to default network is needed then NRI should include
             // the request for the default network. Create an image of it to
@@ -10945,12 +10943,12 @@
      *
      */
     private boolean isRangeAlreadyInPreferenceList(
-            @NonNull List<ProfileNetworkPreferenceList.Preference> preferenceList,
+            @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
             @NonNull Set<UidRange> uidRangeSet) {
         if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
             return false;
         }
-        for (ProfileNetworkPreferenceList.Preference pref : preferenceList) {
+        for (ProfileNetworkPreferenceInfo pref : preferenceList) {
             if (UidRangeUtils.doesRangeSetOverlap(
                     UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
                 return true;
@@ -10960,7 +10958,7 @@
     }
 
     private void handleSetProfileNetworkPreference(
-            @NonNull final List<ProfileNetworkPreferenceList.Preference> preferenceList,
+            @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
             @Nullable final IOnCompleteListener listener) {
         /*
          * handleSetProfileNetworkPreference is always called for single user.
@@ -10969,9 +10967,8 @@
          * Clear all the existing preferences for the user before applying new preferences.
          *
          */
-        mProfileNetworkPreferences = mProfileNetworkPreferences.withoutUser(
-                preferenceList.get(0).user);
-        for (final ProfileNetworkPreferenceList.Preference preference : preferenceList) {
+        mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
+        for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
             mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
         }
 
diff --git a/service/src/com/android/server/connectivity/NetworkPreferenceList.java b/service/src/com/android/server/connectivity/NetworkPreferenceList.java
new file mode 100644
index 0000000..fa6d157
--- /dev/null
+++ b/service/src/com/android/server/connectivity/NetworkPreferenceList.java
@@ -0,0 +1,100 @@
+/*
+ * 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.server.connectivity;
+
+import android.annotation.NonNull;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ * A generic data class containing network preferences.
+ * @param <K> The type of key in T
+ * @param <T> The type of preference stored in this preference list
+ */
+public class NetworkPreferenceList<K, T extends NetworkPreferenceList.NetworkPreference<K>>
+        implements Iterable<T> {
+    /**
+     * A network preference
+     * @param <K> the type of key by which this preference is indexed. A NetworkPreferenceList
+     *            can have multiple preferences associated with this key, but has methods to
+     *            work on the keys.
+     */
+    public interface NetworkPreference<K> {
+        /**
+         * Whether this preference codes for cancelling the preference for this key
+         *
+         * A preference that codes for cancelling is removed from the list of preferences, since
+         * it means the behavior should be the same as if there was no preference for this key.
+         */
+        boolean isCancel();
+        /** The key */
+        K getKey();
+    }
+
+    @NonNull private final List<T> mPreferences;
+
+    public NetworkPreferenceList() {
+        mPreferences = Collections.EMPTY_LIST;
+    }
+
+    private NetworkPreferenceList(@NonNull final List<T> list) {
+        mPreferences = Collections.unmodifiableList(list);
+    }
+
+    /**
+     * Returns a new object consisting of this object plus the passed preference.
+     *
+     * If the passed preference is a cancel preference (see {@link NetworkPreference#isCancel()}
+     * then it is not added.
+     */
+    public NetworkPreferenceList<K, T> plus(@NonNull final T pref) {
+        final ArrayList<T> newPrefs = new ArrayList<>(mPreferences);
+        if (!pref.isCancel()) {
+            newPrefs.add(pref);
+        }
+        return new NetworkPreferenceList<>(newPrefs);
+    }
+
+    /**
+     * Remove all preferences corresponding to a key.
+     */
+    public NetworkPreferenceList<K, T> minus(@NonNull final K key) {
+        final ArrayList<T> newPrefs = new ArrayList<>();
+        for (final T existingPref : mPreferences) {
+            if (!existingPref.getKey().equals(key)) {
+                newPrefs.add(existingPref);
+            }
+        }
+        return new NetworkPreferenceList<>(newPrefs);
+    }
+
+    public boolean isEmpty() {
+        return mPreferences.isEmpty();
+    }
+
+    @Override
+    public Iterator<T> iterator() {
+        return mPreferences.iterator();
+    }
+
+    @Override public String toString() {
+        return "NetworkPreferenceList : " + mPreferences;
+    }
+}
diff --git a/service/src/com/android/server/connectivity/ProfileNetworkPreferenceInfo.java b/service/src/com/android/server/connectivity/ProfileNetworkPreferenceInfo.java
new file mode 100644
index 0000000..10f3886
--- /dev/null
+++ b/service/src/com/android/server/connectivity/ProfileNetworkPreferenceInfo.java
@@ -0,0 +1,62 @@
+/*
+ * 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.server.connectivity;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.net.NetworkCapabilities;
+import android.os.UserHandle;
+
+/**
+ * A single profile preference, as it applies to a given user profile.
+ */
+public class ProfileNetworkPreferenceInfo
+        implements NetworkPreferenceList.NetworkPreference<UserHandle> {
+    @NonNull
+    public final UserHandle user;
+    // Capabilities are only null when sending an object to remove the setting for a user
+    @Nullable
+    public final NetworkCapabilities capabilities;
+    public final boolean allowFallback;
+
+    public ProfileNetworkPreferenceInfo(@NonNull final UserHandle user,
+            @Nullable final NetworkCapabilities capabilities,
+            final boolean allowFallback) {
+        this.user = user;
+        this.capabilities = null == capabilities ? null : new NetworkCapabilities(capabilities);
+        this.allowFallback = allowFallback;
+    }
+
+    @Override
+    public boolean isCancel() {
+        return null == capabilities;
+    }
+
+    @Override
+    @NonNull
+    public UserHandle getKey() {
+        return user;
+    }
+
+    /** toString */
+    public String toString() {
+        return "[ProfileNetworkPreference user=" + user
+                + " caps=" + capabilities
+                + " allowFallback=" + allowFallback
+                + "]";
+    }
+}
diff --git a/service/src/com/android/server/connectivity/ProfileNetworkPreferenceList.java b/service/src/com/android/server/connectivity/ProfileNetworkPreferenceList.java
deleted file mode 100644
index 5bafef9..0000000
--- a/service/src/com/android/server/connectivity/ProfileNetworkPreferenceList.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright (C) 2021 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.server.connectivity;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.net.NetworkCapabilities;
-import android.os.UserHandle;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-/**
- * A data class containing all the per-profile network preferences.
- *
- * A given profile can only have one preference.
- */
-public class ProfileNetworkPreferenceList {
-    /**
-     * A single preference, as it applies to a given user profile.
-     */
-    public static class Preference {
-        @NonNull public final UserHandle user;
-        // Capabilities are only null when sending an object to remove the setting for a user
-        @Nullable public final NetworkCapabilities capabilities;
-        public final boolean allowFallback;
-
-        public Preference(@NonNull final UserHandle user,
-                @Nullable final NetworkCapabilities capabilities,
-                final boolean allowFallback) {
-            this.user = user;
-            this.capabilities = null == capabilities ? null : new NetworkCapabilities(capabilities);
-            this.allowFallback = allowFallback;
-        }
-
-        /** toString */
-        public String toString() {
-            return "[ProfileNetworkPreference user=" + user
-                    + " caps=" + capabilities
-                    + " allowFallback=" + allowFallback
-                    + "]";
-        }
-    }
-
-    @NonNull public final List<Preference> preferences;
-
-    public ProfileNetworkPreferenceList() {
-        preferences = Collections.EMPTY_LIST;
-    }
-
-    private ProfileNetworkPreferenceList(@NonNull final List<Preference> list) {
-        preferences = Collections.unmodifiableList(list);
-    }
-
-    /**
-     * Returns a new object consisting of this object plus the passed preference.
-     *
-     * It is not expected that unwanted preference already exists for the same user.
-     * All preferences for the user that were previously configured should be cleared before
-     * adding a new preference.
-     * Passing a Preference object containing a null capabilities object is equivalent
-     * to removing the preference for this user.
-     */
-    public ProfileNetworkPreferenceList plus(@NonNull final Preference pref) {
-        final ArrayList<Preference> newPrefs = new ArrayList<>(preferences);
-        if (null != pref.capabilities) {
-            newPrefs.add(pref);
-        }
-        return new ProfileNetworkPreferenceList(newPrefs);
-    }
-
-    /**
-     * Remove all preferences corresponding to a user.
-     */
-    public ProfileNetworkPreferenceList withoutUser(UserHandle user) {
-        final ArrayList<Preference> newPrefs = new ArrayList<>();
-        for (final Preference existingPref : preferences) {
-            if (!existingPref.user.equals(user)) {
-                newPrefs.add(existingPref);
-            }
-        }
-        return new ProfileNetworkPreferenceList(newPrefs);
-    }
-
-    public boolean isEmpty() {
-        return preferences.isEmpty();
-    }
-}
diff --git a/tests/common/java/android/net/VpnTransportInfoTest.java b/tests/common/java/android/net/VpnTransportInfoTest.java
index f32ab8b..2d01df7 100644
--- a/tests/common/java/android/net/VpnTransportInfoTest.java
+++ b/tests/common/java/android/net/VpnTransportInfoTest.java
@@ -94,20 +94,20 @@
 
     @DevSdkIgnoreRule.IgnoreAfter(Build.VERSION_CODES.TIRAMISU)
     @Test
-    public void testGetBypassable_beforeU() {
+    public void testIsBypassable_beforeU() {
         final VpnTransportInfo v = new VpnTransportInfo(VpnManager.TYPE_VPN_PLATFORM, "12345");
-        assertThrows(UnsupportedOperationException.class, () -> v.getBypassable());
+        assertThrows(UnsupportedOperationException.class, () -> v.isBypassable());
     }
 
     @DevSdkIgnoreRule.IgnoreUpTo(Build.VERSION_CODES.TIRAMISU)
     @Test
-    public void testGetBypassable_afterU() {
+    public void testIsBypassable_afterU() {
         final VpnTransportInfo v = new VpnTransportInfo(VpnManager.TYPE_VPN_PLATFORM, "12345");
-        assertFalse(v.getBypassable());
+        assertFalse(v.isBypassable());
 
         final VpnTransportInfo v2 =
                 new VpnTransportInfo(VpnManager.TYPE_VPN_PLATFORM, "12345", true, false);
-        assertTrue(v2.getBypassable());
+        assertTrue(v2.isBypassable());
     }
 
     @DevSdkIgnoreRule.IgnoreUpTo(Build.VERSION_CODES.TIRAMISU)
diff --git a/tests/unit/java/com/android/server/connectivity/VpnTest.java b/tests/unit/java/com/android/server/connectivity/VpnTest.java
index 677e7b6..3f87ffd 100644
--- a/tests/unit/java/com/android/server/connectivity/VpnTest.java
+++ b/tests/unit/java/com/android/server/connectivity/VpnTest.java
@@ -1893,7 +1893,7 @@
 
         // Check if allowBypass is set or not.
         assertTrue(nacCaptor.getValue().isBypassableVpn());
-        assertTrue(((VpnTransportInfo) ncCaptor.getValue().getTransportInfo()).getBypassable());
+        assertTrue(((VpnTransportInfo) ncCaptor.getValue().getTransportInfo()).isBypassable());
 
         return new PlatformVpnSnapshot(vpn, nwCb, ikeCb, childCb);
     }
diff --git a/tests/unit/java/com/android/server/connectivity/mdns/MdnsAnnouncerTest.kt b/tests/unit/java/com/android/server/connectivity/mdns/MdnsAnnouncerTest.kt
new file mode 100644
index 0000000..e9325d5
--- /dev/null
+++ b/tests/unit/java/com/android/server/connectivity/mdns/MdnsAnnouncerTest.kt
@@ -0,0 +1,283 @@
+/*
+ * 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.server.connectivity.mdns
+
+import android.net.InetAddresses.parseNumericAddress
+import android.os.Build
+import android.os.HandlerThread
+import android.os.SystemClock
+import com.android.internal.util.HexDump
+import com.android.server.connectivity.mdns.MdnsAnnouncer.AnnouncementInfo
+import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo
+import com.android.testutils.DevSdkIgnoreRunner
+import java.net.DatagramPacket
+import java.net.Inet6Address
+import java.net.InetAddress
+import java.net.InetSocketAddress
+import java.net.MulticastSocket
+import kotlin.test.assertEquals
+import kotlin.test.assertTrue
+import org.junit.After
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.ArgumentCaptor
+import org.mockito.Mockito.any
+import org.mockito.Mockito.atLeast
+import org.mockito.Mockito.mock
+import org.mockito.Mockito.timeout
+import org.mockito.Mockito.verify
+
+private const val FIRST_ANNOUNCES_DELAY = 100L
+private const val FIRST_ANNOUNCES_COUNT = 2
+private const val NEXT_ANNOUNCES_DELAY = 1L
+private const val TEST_TIMEOUT_MS = 1000L
+
+private val destinationsSupplier = {
+    listOf(InetSocketAddress(MdnsConstants.getMdnsIPv6Address(), MdnsConstants.MDNS_PORT)) }
+
+@RunWith(DevSdkIgnoreRunner::class)
+@IgnoreUpTo(Build.VERSION_CODES.S_V2)
+class MdnsAnnouncerTest {
+
+    private val thread = HandlerThread(MdnsAnnouncerTest::class.simpleName)
+    private val socket = mock(MulticastSocket::class.java)
+    private val buffer = ByteArray(1500)
+
+    @Before
+    fun setUp() {
+        thread.start()
+    }
+
+    @After
+    fun tearDown() {
+        thread.quitSafely()
+    }
+
+    private class TestAnnouncementInfo(
+        announcedRecords: List<MdnsRecord>,
+        additionalRecords: List<MdnsRecord>
+    )
+        : AnnouncementInfo(announcedRecords, additionalRecords, destinationsSupplier) {
+        override fun getDelayMs(nextIndex: Int) =
+                if (nextIndex < FIRST_ANNOUNCES_COUNT) {
+                    FIRST_ANNOUNCES_DELAY
+                } else {
+                    NEXT_ANNOUNCES_DELAY
+                }
+    }
+
+    @Test
+    fun testAnnounce() {
+        val replySender = MdnsReplySender(thread.looper, socket, buffer)
+        @Suppress("UNCHECKED_CAST")
+        val cb = mock(MdnsPacketRepeater.PacketRepeaterCallback::class.java)
+                as MdnsPacketRepeater.PacketRepeaterCallback<AnnouncementInfo>
+        val announcer = MdnsAnnouncer("testiface", thread.looper, replySender, cb)
+        /*
+        The expected packet replicates records announced when registering a service, as observed in
+        the legacy mDNS implementation (some ordering differs to be more readable).
+        Obtained with scapy 2.5.0 RC3 (2.4.5 does not compress TLDs like .arpa properly) with:
+        scapy.raw(scapy.dns_compress(scapy.DNS(rd=0, qr=1, aa=1,
+        qd = None,
+        an =
+        scapy.DNSRR(type='PTR', rrname='123.0.2.192.in-addr.arpa.', rdata='Android.local',
+            rclass=0x8001, ttl=120) /
+        scapy.DNSRR(type='PTR',
+            rrname='3.2.1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.B.D.0.1.0.0.2.ip6.arpa',
+            rdata='Android.local', rclass=0x8001, ttl=120) /
+        scapy.DNSRR(type='PTR',
+            rrname='6.5.4.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.B.D.0.1.0.0.2.ip6.arpa',
+            rdata='Android.local', rclass=0x8001, ttl=120) /
+        scapy.DNSRR(type='PTR', rrname='_testtype._tcp.local',
+            rdata='testservice._testtype._tcp.local', rclass='IN', ttl=4500) /
+	    scapy.DNSRRSRV(rrname='testservice._testtype._tcp.local', rclass=0x8001, port=31234,
+	        target='Android.local', ttl=120) /
+	    scapy.DNSRR(type='TXT', rrname='testservice._testtype._tcp.local', rclass=0x8001, rdata='',
+	        ttl=4500) /
+        scapy.DNSRR(type='A', rrname='Android.local', rclass=0x8001, rdata='192.0.2.123', ttl=120) /
+        scapy.DNSRR(type='AAAA', rrname='Android.local', rclass=0x8001, rdata='2001:db8::123',
+            ttl=120) /
+        scapy.DNSRR(type='AAAA', rrname='Android.local', rclass=0x8001, rdata='2001:db8::456',
+            ttl=120),
+        ar =
+        scapy.DNSRRNSEC(rrname='123.0.2.192.in-addr.arpa.', rclass=0x8001, ttl=120,
+            nextname='123.0.2.192.in-addr.arpa.', typebitmaps=[12]) /
+        scapy.DNSRRNSEC(
+            rrname='3.2.1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.B.D.0.1.0.0.2.ip6.arpa',
+            rclass=0x8001, ttl=120,
+            nextname='3.2.1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.B.D.0.1.0.0.2.ip6.arpa',
+            typebitmaps=[12]) /
+        scapy.DNSRRNSEC(
+            rrname='6.5.4.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.B.D.0.1.0.0.2.ip6.arpa',
+            rclass=0x8001, ttl=120,
+            nextname='6.5.4.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.B.D.0.1.0.0.2.ip6.arpa',
+            typebitmaps=[12]) /
+	    scapy.DNSRRNSEC(
+	        rrname='testservice._testtype._tcp.local', rclass=0x8001, ttl=4500,
+	        nextname='testservice._testtype._tcp.local', typebitmaps=[16, 33]) /
+        scapy.DNSRRNSEC(
+            rrname='Android.local', rclass=0x8001, ttl=120, nextname='Android.local',
+            typebitmaps=[1, 28]))
+        )).hex().upper()
+        */
+        val expected = "00008400000000090000000503313233013001320331393207696E2D61646472046172706" +
+                "100000C800100000078000F07416E64726F6964056C6F63616C00013301320131013001300130013" +
+                "00130013001300130013001300130013001300130013001300130013001300130013001380142014" +
+                "40130013101300130013203697036C020000C8001000000780002C030013601350134C045000C800" +
+                "1000000780002C030095F7465737474797065045F746370C038000C000100001194000E0B7465737" +
+                "473657276696365C0A5C0C000218001000000780008000000007A02C030C0C000108001000011940" +
+                "000C03000018001000000780004C000027BC030001C800100000078001020010DB80000000000000" +
+                "00000000123C030001C800100000078001020010DB8000000000000000000000456C00C002F80010" +
+                "00000780006C00C00020008C03F002F8001000000780006C03F00020008C091002F8001000000780" +
+                "006C09100020008C0C0002F8001000011940009C0C000050000800040C030002F800100000078000" +
+                "8C030000440000008"
+
+        val hostname = arrayOf("Android", "local")
+        val serviceType = arrayOf("_testtype", "_tcp", "local")
+        val serviceName = arrayOf("testservice", "_testtype", "_tcp", "local")
+        val v4Addr = parseNumericAddress("192.0.2.123")
+        val v6Addr1 = parseNumericAddress("2001:DB8::123")
+        val v6Addr2 = parseNumericAddress("2001:DB8::456")
+        val v4AddrRev = arrayOf("123", "0", "2", "192", "in-addr", "arpa")
+        val v6Addr1Rev = getReverseV6AddressName(v6Addr1)
+        val v6Addr2Rev = getReverseV6AddressName(v6Addr2)
+
+        val announcedRecords = listOf(
+                // Reverse address records
+                MdnsPointerRecord(v4AddrRev,
+                        0L /* receiptTimeMillis */,
+                        true /* cacheFlush */,
+                        120000L /* ttlMillis */,
+                        hostname),
+                MdnsPointerRecord(v6Addr1Rev,
+                        0L /* receiptTimeMillis */,
+                        true /* cacheFlush */,
+                        120000L /* ttlMillis */,
+                        hostname),
+                MdnsPointerRecord(v6Addr2Rev,
+                        0L /* receiptTimeMillis */,
+                        true /* cacheFlush */,
+                        120000L /* ttlMillis */,
+                        hostname),
+                // Service registration records (RFC6763)
+                MdnsPointerRecord(
+                        serviceType,
+                        0L /* receiptTimeMillis */,
+                        // Not a unique name owned by the announcer, so cacheFlush=false
+                        false /* cacheFlush */,
+                        4500000L /* ttlMillis */,
+                        serviceName),
+                MdnsServiceRecord(
+                        serviceName,
+                        0L /* receiptTimeMillis */,
+                        true /* cacheFlush */,
+                        120000L /* ttlMillis */,
+                        0 /* servicePriority */,
+                        0 /* serviceWeight */,
+                        31234 /* servicePort */,
+                        hostname),
+                MdnsTextRecord(
+                        serviceName,
+                        0L /* receiptTimeMillis */,
+                        true /* cacheFlush */,
+                        4500000L /* ttlMillis */,
+                        emptyList() /* entries */),
+                // Address records for the hostname
+                MdnsInetAddressRecord(hostname,
+                        0L /* receiptTimeMillis */,
+                        true /* cacheFlush */,
+                        120000L /* ttlMillis */,
+                        v4Addr),
+                MdnsInetAddressRecord(hostname,
+                        0L /* receiptTimeMillis */,
+                        true /* cacheFlush */,
+                        120000L /* ttlMillis */,
+                        v6Addr1),
+                MdnsInetAddressRecord(hostname,
+                        0L /* receiptTimeMillis */,
+                        true /* cacheFlush */,
+                        120000L /* ttlMillis */,
+                        v6Addr2))
+        // Negative responses (RFC6762 6.1)
+        val additionalRecords = listOf(
+                MdnsNsecRecord(v4AddrRev,
+                        0L /* receiptTimeMillis */,
+                        true /* cacheFlush */,
+                        120000L /* ttlMillis */,
+                        v4AddrRev,
+                        intArrayOf(MdnsRecord.TYPE_PTR)),
+                MdnsNsecRecord(v6Addr1Rev,
+                        0L /* receiptTimeMillis */,
+                        true /* cacheFlush */,
+                        120000L /* ttlMillis */,
+                        v6Addr1Rev,
+                        intArrayOf(MdnsRecord.TYPE_PTR)),
+                MdnsNsecRecord(v6Addr2Rev,
+                        0L /* receiptTimeMillis */,
+                        true /* cacheFlush */,
+                        120000L /* ttlMillis */,
+                        v6Addr2Rev,
+                        intArrayOf(MdnsRecord.TYPE_PTR)),
+                MdnsNsecRecord(serviceName,
+                        0L /* receiptTimeMillis */,
+                        true /* cacheFlush */,
+                        4500000L /* ttlMillis */,
+                        serviceName,
+                        intArrayOf(MdnsRecord.TYPE_TXT, MdnsRecord.TYPE_SRV)),
+                MdnsNsecRecord(hostname,
+                        0L /* receiptTimeMillis */,
+                        true /* cacheFlush */,
+                        120000L /* ttlMillis */,
+                        hostname,
+                        intArrayOf(MdnsRecord.TYPE_A, MdnsRecord.TYPE_AAAA)))
+        val request = TestAnnouncementInfo(announcedRecords, additionalRecords)
+
+        val timeStart = SystemClock.elapsedRealtime()
+        val startDelay = 50L
+        val sendId = 1
+        announcer.startSending(sendId, request, startDelay)
+
+        val captor = ArgumentCaptor.forClass(DatagramPacket::class.java)
+        repeat(FIRST_ANNOUNCES_COUNT) { i ->
+            verify(cb, timeout(TEST_TIMEOUT_MS)).onSent(i, request)
+            verify(socket, atLeast(i + 1)).send(any())
+            val now = SystemClock.elapsedRealtime()
+            assertTrue(now > timeStart + startDelay + i * FIRST_ANNOUNCES_DELAY)
+            assertTrue(now < timeStart + startDelay + (i + 1) * FIRST_ANNOUNCES_DELAY)
+        }
+
+        // Subsequent announces should happen quickly (NEXT_ANNOUNCES_DELAY)
+        verify(socket, timeout(TEST_TIMEOUT_MS).times(MdnsAnnouncer.ANNOUNCEMENT_COUNT))
+                .send(captor.capture())
+        verify(cb, timeout(TEST_TIMEOUT_MS)).onFinished(request)
+
+        captor.allValues.forEach {
+            assertEquals(expected, HexDump.toHexString(it.data))
+        }
+    }
+}
+
+/**
+ * Compute 2001:db8::1 --> 1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.B.D.1.0.0.2.ip6.arpa
+ */
+private fun getReverseV6AddressName(addr: InetAddress): Array<String> {
+    assertTrue(addr is Inet6Address)
+    return addr.address.flatMapTo(mutableListOf("arpa", "ip6")) {
+        HexDump.toHexString(it).toCharArray().map(Char::toString)
+    }.reversed().toTypedArray()
+}
diff --git a/tests/unit/java/com/android/server/connectivity/mdns/MdnsPacketWriterTest.kt b/tests/unit/java/com/android/server/connectivity/mdns/MdnsPacketWriterTest.kt
new file mode 100644
index 0000000..5c9c294
--- /dev/null
+++ b/tests/unit/java/com/android/server/connectivity/mdns/MdnsPacketWriterTest.kt
@@ -0,0 +1,55 @@
+/*
+ * 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.server.connectivity.mdns
+
+import android.net.InetAddresses
+import android.os.Build
+import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo
+import com.android.testutils.DevSdkIgnoreRunner
+import java.net.InetSocketAddress
+import kotlin.test.assertContentEquals
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@RunWith(DevSdkIgnoreRunner::class)
+@IgnoreUpTo(Build.VERSION_CODES.S_V2)
+class MdnsPacketWriterTest {
+    @Test
+    fun testNameCompression() {
+        val writer = MdnsPacketWriter(ByteArray(1000))
+        writer.writeLabels(arrayOf("my", "first", "name"))
+        writer.writeLabels(arrayOf("my", "second", "name"))
+        writer.writeLabels(arrayOf("other", "first", "name"))
+        writer.writeLabels(arrayOf("my", "second", "name"))
+        writer.writeLabels(arrayOf("unrelated"))
+
+        val packet = writer.getPacket(
+                InetSocketAddress(InetAddresses.parseNumericAddress("2001:db8::123"), 123))
+
+        // Each label takes length + 1. So "first.name" offset = 3, "name" offset = 9
+        val expected = "my".label() + "first".label() + "name".label() + 0x00.toByte() +
+                // "my.second.name" offset = 15
+                "my".label() + "second".label() + byteArrayOf(0xC0.toByte(), 9) +
+                "other".label() + byteArrayOf(0xC0.toByte(), 3) +
+                byteArrayOf(0xC0.toByte(), 15) +
+                "unrelated".label() + 0x00.toByte()
+
+        assertContentEquals(expected, packet.data.copyOfRange(0, packet.length))
+    }
+}
+
+private fun String.label() = byteArrayOf(length.toByte()) + encodeToByteArray()
diff --git a/tests/unit/java/com/android/server/connectivity/mdns/MdnsProberTest.kt b/tests/unit/java/com/android/server/connectivity/mdns/MdnsProberTest.kt
index cc75191..419121c 100644
--- a/tests/unit/java/com/android/server/connectivity/mdns/MdnsProberTest.kt
+++ b/tests/unit/java/com/android/server/connectivity/mdns/MdnsProberTest.kt
@@ -160,14 +160,11 @@
                 scapy.DNSRR(type='TXT', ttl=120, rrname='testservice._nmt._tcp.local.',
                     rdata='testKey=testValue'))
         )).hex().upper()
-        // NOTE: due to a bug the second "myhostname" is not getting DNS compressed in the current
-        // actual probe, so data below is slightly different. Fix compression so it gets compressed.
          */
         val expected = "0000000000020000000300000B7465737473657276696365045F6E6D74045F746370056C6" +
                 "F63616C0000FF00010C746573747365727669636532C01800FF0001C00C002100010000007800130" +
-                "000000094020A6D79686F73746E616D65C0220C746573747365727669636532C0180021000100000" +
-                "07800130000000094030A6D79686F73746E616D65C022C00C0010000100000078001211746573744" +
-                "B65793D7465737456616C7565"
+                "000000094020A6D79686F73746E616D65C022C02D00210001000000780008000000009403C052C00" +
+                "C0010000100000078001211746573744B65793D7465737456616C7565"
         assertProbesSent(probeInfo, expected)
     }