Merge "Add a field and score flag for first evaluation"
diff --git a/OWNERS_core_networking_xts b/OWNERS_core_networking_xts
index a6627fe..59d6575 100644
--- a/OWNERS_core_networking_xts
+++ b/OWNERS_core_networking_xts
@@ -1,2 +1,7 @@
lorenzo@google.com
-satk@google.com
+satk@google.com #{LAST_RESORT_SUGGESTION}
+
+# For cherry-picks of CLs that are already merged in aosp/master.
+jchalard@google.com #{LAST_RESORT_SUGGESTION}
+maze@google.com #{LAST_RESORT_SUGGESTION}
+reminv@google.com #{LAST_RESORT_SUGGESTION}
\ No newline at end of file
diff --git a/Tethering/src/com/android/networkstack/tethering/Tethering.java b/Tethering/src/com/android/networkstack/tethering/Tethering.java
index 0d1b22e..1f3fc11 100644
--- a/Tethering/src/com/android/networkstack/tethering/Tethering.java
+++ b/Tethering/src/com/android/networkstack/tethering/Tethering.java
@@ -2004,10 +2004,6 @@
return;
}
- if (arg1 == UpstreamNetworkMonitor.NOTIFY_TEST_NETWORK_AVAILABLE) {
- chooseUpstreamType(false);
- }
-
if (ns == null || !pertainsToCurrentUpstream(ns)) {
// TODO: In future, this is where upstream evaluation and selection
// could be handled for notifications which include sufficient data.
diff --git a/Tethering/src/com/android/networkstack/tethering/UpstreamNetworkMonitor.java b/Tethering/src/com/android/networkstack/tethering/UpstreamNetworkMonitor.java
index 15df0c6..16c031b 100644
--- a/Tethering/src/com/android/networkstack/tethering/UpstreamNetworkMonitor.java
+++ b/Tethering/src/com/android/networkstack/tethering/UpstreamNetworkMonitor.java
@@ -85,12 +85,11 @@
private static final boolean DBG = false;
private static final boolean VDBG = false;
- public static final int EVENT_ON_CAPABILITIES = 1;
- public static final int EVENT_ON_LINKPROPERTIES = 2;
- public static final int EVENT_ON_LOST = 3;
- public static final int EVENT_DEFAULT_SWITCHED = 4;
- public static final int NOTIFY_LOCAL_PREFIXES = 10;
- public static final int NOTIFY_TEST_NETWORK_AVAILABLE = 11;
+ public static final int EVENT_ON_CAPABILITIES = 1;
+ public static final int EVENT_ON_LINKPROPERTIES = 2;
+ public static final int EVENT_ON_LOST = 3;
+ public static final int EVENT_DEFAULT_SWITCHED = 4;
+ public static final int NOTIFY_LOCAL_PREFIXES = 10;
// This value is used by deprecated preferredUpstreamIfaceTypes selection which is default
// disabled.
@VisibleForTesting
@@ -468,17 +467,6 @@
notifyTarget(EVENT_DEFAULT_SWITCHED, ns);
}
- private void maybeHandleTestNetwork(@NonNull Network network) {
- if (!mPreferTestNetworks) return;
-
- final UpstreamNetworkState ns = mNetworkMap.get(network);
- if (network.equals(mTetheringUpstreamNetwork) || !isTestNetwork(ns)) return;
-
- // Test network is available. Notify tethering.
- Log.d(TAG, "Handle test network: " + network);
- notifyTarget(NOTIFY_TEST_NETWORK_AVAILABLE, ns);
- }
-
private void recomputeLocalPrefixes() {
final HashSet<IpPrefix> localPrefixes = allLocalPrefixes(mNetworkMap.values());
if (!mLocalPrefixes.equals(localPrefixes)) {
@@ -561,12 +549,6 @@
// So it's not useful to do this work for non-LISTEN_ALL callbacks.
if (mCallbackType == CALLBACK_LISTEN_ALL) {
recomputeLocalPrefixes();
-
- // When the LISTEN_ALL network callback calls onLinkPropertiesChanged, it means that
- // all the network information for the network is known (because
- // onLinkPropertiesChanged is called after onAvailable and onCapabilitiesChanged).
- // Inform tethering that the test network might have changed.
- maybeHandleTestNetwork(network);
}
}
diff --git a/Tethering/tests/integration/Android.bp b/Tethering/tests/integration/Android.bp
index 9aa2cff..11e3dc0 100644
--- a/Tethering/tests/integration/Android.bp
+++ b/Tethering/tests/integration/Android.bp
@@ -28,6 +28,7 @@
static_libs: [
"NetworkStackApiStableLib",
"androidx.test.rules",
+ "cts-net-utils",
"mockito-target-extended-minus-junit4",
"net-tests-utils",
"net-utils-device-common-bpf",
diff --git a/Tethering/tests/integration/AndroidManifest.xml b/Tethering/tests/integration/AndroidManifest.xml
index 9303d0a..7527913 100644
--- a/Tethering/tests/integration/AndroidManifest.xml
+++ b/Tethering/tests/integration/AndroidManifest.xml
@@ -17,6 +17,7 @@
package="com.android.networkstack.tethering.tests.integration">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
+ <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<!-- The test need CHANGE_NETWORK_STATE permission to use requestNetwork API to setup test
network. Since R shell application don't have such permission, grant permission to the test
here. TODO: Remove CHANGE_NETWORK_STATE permission here and use adopt shell perssion to
diff --git a/Tethering/tests/integration/src/android/net/EthernetTetheringTest.java b/Tethering/tests/integration/src/android/net/EthernetTetheringTest.java
index eaa7d21..39812cd 100644
--- a/Tethering/tests/integration/src/android/net/EthernetTetheringTest.java
+++ b/Tethering/tests/integration/src/android/net/EthernetTetheringTest.java
@@ -16,10 +16,12 @@
package android.net;
+import static android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS;
import static android.Manifest.permission.DUMP;
import static android.Manifest.permission.MANAGE_TEST_NETWORKS;
import static android.Manifest.permission.NETWORK_SETTINGS;
import static android.Manifest.permission.TETHER_PRIVILEGED;
+import static android.content.pm.PackageManager.FEATURE_WIFI;
import static android.net.InetAddresses.parseNumericAddress;
import static android.net.TetheringManager.CONNECTIVITY_SCOPE_GLOBAL;
import static android.net.TetheringManager.CONNECTIVITY_SCOPE_LOCAL;
@@ -54,12 +56,14 @@
import android.app.UiAutomation;
import android.content.Context;
+import android.content.pm.PackageManager;
import android.net.EthernetManager.TetheredInterfaceCallback;
import android.net.EthernetManager.TetheredInterfaceRequest;
import android.net.TetheringManager.StartTetheringCallback;
import android.net.TetheringManager.TetheringEventCallback;
import android.net.TetheringManager.TetheringRequest;
import android.net.TetheringTester.TetheredDevice;
+import android.net.cts.util.CtsNetUtils;;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
@@ -75,6 +79,7 @@
import androidx.test.filters.MediumTest;
import androidx.test.runner.AndroidJUnit4;
+import com.android.modules.utils.build.SdkLevel;
import com.android.net.module.util.BpfDump;
import com.android.net.module.util.Ipv6Utils;
import com.android.net.module.util.PacketBuilder;
@@ -237,6 +242,8 @@
private final Context mContext = InstrumentationRegistry.getContext();
private final EthernetManager mEm = mContext.getSystemService(EthernetManager.class);
private final TetheringManager mTm = mContext.getSystemService(TetheringManager.class);
+ private final PackageManager mPackageManager = mContext.getPackageManager();
+ private final CtsNetUtils mCtsNetUtils = new CtsNetUtils(mContext);
private TestNetworkInterface mDownstreamIface;
private HandlerThread mHandlerThread;
@@ -314,6 +321,13 @@
}
private boolean isInterfaceForTetheringAvailable() throws Exception {
+ // Before T, all ethernet interfaces could be used for server mode. Instead of
+ // waiting timeout, just checking whether the system currently has any
+ // ethernet interface is more reliable.
+ if (!SdkLevel.isAtLeastT()) {
+ return runAsShell(CONNECTIVITY_USE_RESTRICTED_NETWORKS, () -> mEm.isAvailable());
+ }
+
// If previous test case doesn't release tethering interface successfully, the other tests
// after that test may be skipped as unexcepted.
// TODO: figure out a better way to check default tethering interface existenion.
@@ -693,10 +707,17 @@
}
}
- public Network awaitUpstreamChanged() throws Exception {
+ public Network awaitUpstreamChanged(boolean throwTimeoutException) throws Exception {
if (!mUpstreamLatch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
- fail("Did not receive upstream " + (mAcceptAnyUpstream ? "any" : mExpectedUpstream)
- + " callback after " + TIMEOUT_MS + "ms");
+ final String errorMessage = "Did not receive upstream "
+ + (mAcceptAnyUpstream ? "any" : mExpectedUpstream)
+ + " callback after " + TIMEOUT_MS + "ms";
+
+ if (throwTimeoutException) {
+ throw new TimeoutException(errorMessage);
+ } else {
+ fail(errorMessage);
+ }
}
return mUpstream;
}
@@ -1238,6 +1259,52 @@
}
}
+ // TODO: remove triggering upstream reselection once test network can replace selected upstream
+ // network in Tethering module.
+ private void maybeRetryTestedUpstreamChanged(final Network expectedUpstream,
+ final TimeoutException fallbackException) throws Exception {
+ // Fall back original exception because no way to reselect if there is no WIFI feature.
+ assertTrue(fallbackException.toString(), mPackageManager.hasSystemFeature(FEATURE_WIFI));
+
+ // Try to toggle wifi network, if any, to reselect upstream network via default network
+ // switching. Because test network has higher priority than internet network, this can
+ // help selecting test network to be upstream network for testing. This tries to avoid
+ // the flaky upstream selection under multinetwork environment. Internet and test network
+ // upstream changed event order is not guaranteed. Once tethering selects non-test
+ // upstream {wifi, ..}, test network won't be selected anymore. If too many test cases
+ // trigger the reselection, the total test time may over test suite 1 minmute timeout.
+ // Probably need to disable/restore all internet networks in a common place of test
+ // process. Currently, EthernetTetheringTest is part of CTS test which needs wifi network
+ // connection if device has wifi feature. CtsNetUtils#toggleWifi() checks wifi connection
+ // during the toggling process.
+ // See Tethering#chooseUpstreamType, CtsNetUtils#toggleWifi.
+ // TODO: toggle cellular network if the device has no WIFI feature.
+ Log.d(TAG, "Toggle WIFI to retry upstream selection");
+ mCtsNetUtils.toggleWifi();
+
+ // Wait for expected upstream.
+ final CompletableFuture<Network> future = new CompletableFuture<>();
+ final TetheringEventCallback callback = new TetheringEventCallback() {
+ @Override
+ public void onUpstreamChanged(Network network) {
+ Log.d(TAG, "Got upstream changed: " + network);
+ if (Objects.equals(expectedUpstream, network)) {
+ future.complete(network);
+ }
+ }
+ };
+ try {
+ mTm.registerTetheringEventCallback(mHandler::post, callback);
+ assertEquals("onUpstreamChanged for unexpected network", expectedUpstream,
+ future.get(TIMEOUT_MS, TimeUnit.MILLISECONDS));
+ } catch (TimeoutException e) {
+ throw new AssertionError("Did not receive upstream " + expectedUpstream
+ + " callback after " + TIMEOUT_MS + "ms");
+ } finally {
+ mTm.unregisterTetheringEventCallback(callback);
+ }
+ }
+
private TetheringTester initTetheringTester(List<LinkAddress> upstreamAddresses,
List<InetAddress> upstreamDnses) throws Exception {
assumeFalse(isInterfaceForTetheringAvailable());
@@ -1256,8 +1323,17 @@
mTetheringEventCallback = enableEthernetTethering(mDownstreamIface.getInterfaceName(),
mUpstreamTracker.getNetwork());
- assertEquals("onUpstreamChanged for unexpected network", mUpstreamTracker.getNetwork(),
- mTetheringEventCallback.awaitUpstreamChanged());
+
+ try {
+ assertEquals("onUpstreamChanged for test network", mUpstreamTracker.getNetwork(),
+ mTetheringEventCallback.awaitUpstreamChanged(
+ true /* throwTimeoutException */));
+ } catch (TimeoutException e) {
+ // Due to race condition inside tethering module, test network may not be selected as
+ // tethering upstream. Force tethering retry upstream if possible. If it is not
+ // possible to retry, fail the test with the original timeout exception.
+ maybeRetryTestedUpstreamChanged(mUpstreamTracker.getNetwork(), e);
+ }
mDownstreamReader = makePacketReader(mDownstreamIface);
mUpstreamReader = makePacketReader(mUpstreamTracker.getTestIface());
diff --git a/Tethering/tests/unit/src/com/android/networkstack/tethering/TestConnectivityManager.java b/Tethering/tests/unit/src/com/android/networkstack/tethering/TestConnectivityManager.java
index e0d77ee..b2cbf75 100644
--- a/Tethering/tests/unit/src/com/android/networkstack/tethering/TestConnectivityManager.java
+++ b/Tethering/tests/unit/src/com/android/networkstack/tethering/TestConnectivityManager.java
@@ -19,7 +19,6 @@
import static android.net.NetworkCapabilities.NET_CAPABILITY_DUN;
import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
-import static android.net.NetworkCapabilities.TRANSPORT_TEST;
import static com.android.networkstack.apishim.common.ShimUtils.isAtLeastS;
@@ -330,28 +329,6 @@
this.legacyType = toLegacyType(networkCapabilities);
}
- // Used for test network only because ConnectivityManager.networkCapabilitiesForType
- // doesn't support "TRANSPORT_TEST -> TYPE_TEST" in #matchesLegacyType. Beware of
- // satisfiedByNetworkCapabilities doesn't check on new |networkCapabilities| as
- // #matchesLegacyType.
- // TODO: refactor when tethering no longer uses CONNECTIVITY_ACTION.
- private TestNetworkAgent(TestConnectivityManager cm) {
- this.cm = cm;
- networkId = new Network(cm.getNetworkId());
- networkCapabilities = new NetworkCapabilities.Builder()
- .addTransportType(TRANSPORT_TEST)
- .addCapability(NET_CAPABILITY_INTERNET)
- .build();
- linkProperties = new LinkProperties();
- legacyType = TYPE_TEST;
- }
-
- // TODO: refactor when tethering no longer uses CONNECTIVITY_ACTION.
- public static TestNetworkAgent buildTestNetworkAgentForTestNetwork(
- TestConnectivityManager cm) {
- return new TestNetworkAgent(cm);
- }
-
private static int toLegacyType(NetworkCapabilities nc) {
for (int type = 0; type < ConnectivityManager.TYPE_TEST; type++) {
if (matchesLegacyType(nc, type)) return type;
diff --git a/Tethering/tests/unit/src/com/android/networkstack/tethering/TetheringServiceTest.java b/Tethering/tests/unit/src/com/android/networkstack/tethering/TetheringServiceTest.java
index e114cb5..38f1e9c 100644
--- a/Tethering/tests/unit/src/com/android/networkstack/tethering/TetheringServiceTest.java
+++ b/Tethering/tests/unit/src/com/android/networkstack/tethering/TetheringServiceTest.java
@@ -664,17 +664,17 @@
assertEquals("Internal callback is not registered", 1, callbacks.size());
assertNotNull(weakTm.get());
+ // Calling System.gc() or System.runFinalization() doesn't guarantee GCs or finalizers
+ // are executed synchronously. The finalizer is called after GC on a separate thread.
final int attempts = 100;
final long waitIntervalMs = 50;
for (int i = 0; i < attempts; i++) {
forceGc();
- if (weakTm.get() == null) break;
+ if (weakTm.get() == null && callbacks.size() == 0) break;
Thread.sleep(waitIntervalMs);
}
- assertNull("TetheringManager weak reference still not null after " + attempts
- + " attempts", weakTm.get());
-
+ assertNull("TetheringManager weak reference is not null", weakTm.get());
assertEquals("Internal callback is not unregistered", 0, callbacks.size());
});
}
diff --git a/Tethering/tests/unit/src/com/android/networkstack/tethering/UpstreamNetworkMonitorTest.java b/Tethering/tests/unit/src/com/android/networkstack/tethering/UpstreamNetworkMonitorTest.java
index b0cb7f2..9b9507b 100644
--- a/Tethering/tests/unit/src/com/android/networkstack/tethering/UpstreamNetworkMonitorTest.java
+++ b/Tethering/tests/unit/src/com/android/networkstack/tethering/UpstreamNetworkMonitorTest.java
@@ -449,36 +449,6 @@
}
@Test
- public void testGetCurrentPreferredUpstream_TestNetworkPreferred() throws Exception {
- mUNM.startTrackDefaultNetwork(mEntitleMgr);
- mUNM.startObserveAllNetworks();
- mUNM.setUpstreamConfig(true /* autoUpstream */, false /* dunRequired */);
- mUNM.setTryCell(true);
- mUNM.setPreferTestNetworks(true);
-
- // [1] Mobile connects, DUN not required -> mobile selected.
- final TestNetworkAgent cellAgent = new TestNetworkAgent(mCM, CELL_CAPABILITIES);
- cellAgent.fakeConnect();
- mCM.makeDefaultNetwork(cellAgent);
- mLooper.dispatchAll();
- assertEquals(cellAgent.networkId, mUNM.getCurrentPreferredUpstream().network);
- assertEquals(0, mCM.mRequested.size());
-
- // [2] Test network connects -> test network selected.
- final TestNetworkAgent testAgent =
- TestNetworkAgent.buildTestNetworkAgentForTestNetwork(mCM);
- testAgent.fakeConnect();
- mLooper.dispatchAll();
- assertEquals(testAgent.networkId, mUNM.getCurrentPreferredUpstream().network);
- assertEquals(0, mCM.mRequested.size());
-
- // [3] Disable test networks preferred -> mobile selected.
- mUNM.setPreferTestNetworks(false);
- assertEquals(cellAgent.networkId, mUNM.getCurrentPreferredUpstream().network);
- assertEquals(0, mCM.mRequested.size());
- }
-
- @Test
public void testLocalPrefixes() throws Exception {
mUNM.startTrackDefaultNetwork(mEntitleMgr);
mUNM.startObserveAllNetworks();
diff --git a/framework/Android.bp b/framework/Android.bp
index fcce7a5..485961c 100644
--- a/framework/Android.bp
+++ b/framework/Android.bp
@@ -228,12 +228,13 @@
],
out: ["framework_connectivity_jarjar_rules.txt"],
cmd: "$(location jarjar-rules-generator) " +
- "--jars $(location :framework-connectivity-pre-jarjar{.jar}) " +
+ "$(location :framework-connectivity-pre-jarjar{.jar}) " +
"$(location :framework-connectivity-t-pre-jarjar{.jar}) " +
"--prefix android.net.connectivity " +
"--apistubs $(location :framework-connectivity.stubs.module_lib{.jar}) " +
- "$(location :framework-connectivity-t.stubs.module_lib{.jar}) " +
- "--unsupportedapi $(locations :connectivity-hiddenapi-files) " +
+ "--apistubs $(location :framework-connectivity-t.stubs.module_lib{.jar}) " +
+ // Make a ":"-separated list. There will be an extra ":" but empty items are ignored.
+ "--unsupportedapi $$(printf ':%s' $(locations :connectivity-hiddenapi-files)) " +
"--excludes $(location jarjar-excludes.txt) " +
"--output $(out)",
visibility: [
diff --git a/service-t/src/com/android/server/net/BpfInterfaceMapUpdater.java b/service-t/src/com/android/server/net/BpfInterfaceMapUpdater.java
index 3b44d81..57466a6 100644
--- a/service-t/src/com/android/server/net/BpfInterfaceMapUpdater.java
+++ b/service-t/src/com/android/server/net/BpfInterfaceMapUpdater.java
@@ -22,10 +22,12 @@
import android.os.RemoteException;
import android.os.ServiceSpecificException;
import android.system.ErrnoException;
+import android.util.IndentingPrintWriter;
import android.util.Log;
import com.android.internal.annotations.VisibleForTesting;
import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
+import com.android.net.module.util.BpfDump;
import com.android.net.module.util.BpfMap;
import com.android.net.module.util.IBpfMap;
import com.android.net.module.util.InterfaceParams;
@@ -136,4 +138,37 @@
mHandler.post(() -> addInterface(ifName));
}
}
+
+ /** get interface name by interface index from bpf map */
+ public String getIfNameByIndex(final long index) {
+ try {
+ final InterfaceMapValue value = mBpfMap.getValue(new U32(index));
+ if (value == null) {
+ Log.e(TAG, "No if name entry for index " + index);
+ return null;
+ }
+ return value.getInterfaceNameString();
+ } catch (ErrnoException e) {
+ Log.e(TAG, "Failed to get entry for index " + index + ": " + e);
+ return null;
+ }
+ }
+
+ /**
+ * Dump BPF map
+ *
+ * @param pw print writer
+ */
+ public void dump(final IndentingPrintWriter pw) {
+ pw.println("BPF map status:");
+ pw.increaseIndent();
+ BpfDump.dumpMapStatus(mBpfMap, pw, "IfaceIndexNameMap", IFACE_INDEX_NAME_MAP_PATH);
+ pw.decreaseIndent();
+ pw.println("BPF map content:");
+ pw.increaseIndent();
+ BpfDump.dumpMap(mBpfMap, pw, "IfaceIndexNameMap",
+ (key, value) -> "ifaceIndex=" + key.val
+ + " ifaceName=" + value.getInterfaceNameString());
+ pw.decreaseIndent();
+ }
}
diff --git a/service-t/src/com/android/server/net/InterfaceMapValue.java b/service-t/src/com/android/server/net/InterfaceMapValue.java
index 42c0044..95da981 100644
--- a/service-t/src/com/android/server/net/InterfaceMapValue.java
+++ b/service-t/src/com/android/server/net/InterfaceMapValue.java
@@ -16,20 +16,45 @@
package com.android.server.net;
import com.android.net.module.util.Struct;
-import com.android.net.module.util.Struct.Field;
-import com.android.net.module.util.Struct.Type;
+
+import java.util.Arrays;
/**
* The value of bpf interface index map which is used for NetworkStatsService.
*/
public class InterfaceMapValue extends Struct {
+ private static final int IF_NAME_SIZE = 16;
+
@Field(order = 0, type = Type.ByteArray, arraysize = 16)
public final byte[] interfaceName;
public InterfaceMapValue(String iface) {
- final byte[] ifaceArray = iface.getBytes();
- interfaceName = new byte[16];
// All array bytes after the interface name, if any, must be 0.
- System.arraycopy(ifaceArray, 0, interfaceName, 0, ifaceArray.length);
+ interfaceName = Arrays.copyOf(iface.getBytes(), IF_NAME_SIZE);
+ }
+
+ /**
+ * Constructor for Struct#parse. Build this struct from byte array of interface name.
+ *
+ * @param ifName Byte array of interface name, length is expected to be IF_NAME_SIZE(16).
+ * If longer or shorter, interface name will be truncated or padded with zeros.
+ * All array bytes after the interface name, if any, must be 0.
+ */
+ public InterfaceMapValue(final byte[] ifName) {
+ interfaceName = Arrays.copyOf(ifName, IF_NAME_SIZE);
+ }
+
+ /** Returns the length of the null-terminated string. */
+ private int strlen(byte[] str) {
+ for (int i = 0; i < str.length; ++i) {
+ if (str[i] == '\0') {
+ return i;
+ }
+ }
+ return str.length;
+ }
+
+ public String getInterfaceNameString() {
+ return new String(interfaceName, 0 /* offset */, strlen(interfaceName));
}
}
diff --git a/service-t/src/com/android/server/net/NetworkStatsService.java b/service-t/src/com/android/server/net/NetworkStatsService.java
index 8d5c881..807f5d7 100644
--- a/service-t/src/com/android/server/net/NetworkStatsService.java
+++ b/service-t/src/com/android/server/net/NetworkStatsService.java
@@ -1321,7 +1321,7 @@
mNetd.bandwidthSetGlobalAlert(mGlobalAlertBytes);
} catch (IllegalStateException e) {
Log.w(TAG, "problem registering for global alert: " + e);
- } catch (RemoteException e) {
+ } catch (RemoteException | ServiceSpecificException e) {
// ignored; service lives in system_server
}
invokeForAllStatsProviderCallbacks((cb) -> cb.mProvider.onSetAlert(mGlobalAlertBytes));
@@ -2741,6 +2741,12 @@
}
pw.println();
+ pw.println("InterfaceMapUpdater:");
+ pw.increaseIndent();
+ mInterfaceMapUpdater.dump(pw);
+ pw.decreaseIndent();
+
+ pw.println();
pw.println("BPF map status:");
pw.increaseIndent();
dumpMapStatus(pw);
@@ -2755,6 +2761,8 @@
dumpCookieTagMapLocked(pw);
dumpUidCounterSetMapLocked(pw);
dumpAppUidStatsMapLocked(pw);
+ dumpStatsMapLocked(mStatsMapA, pw, "mStatsMapA");
+ dumpStatsMapLocked(mStatsMapB, pw, "mStatsMapB");
pw.decreaseIndent();
}
}
@@ -2840,6 +2848,8 @@
pw.println("mUidCounterSetMap: "
+ getMapStatus(mUidCounterSetMap, UID_COUNTERSET_MAP_PATH));
pw.println("mAppUidStatsMap: " + getMapStatus(mAppUidStatsMap, APP_UID_STATS_MAP_PATH));
+ pw.println("mStatsMapA: " + getMapStatus(mStatsMapA, STATS_MAP_A_PATH));
+ pw.println("mStatsMapB: " + getMapStatus(mStatsMapB, STATS_MAP_B_PATH));
}
@GuardedBy("mStatsLock")
@@ -2876,6 +2886,30 @@
+ value.txPackets);
}
+ @GuardedBy("mStatsLock")
+ private void dumpStatsMapLocked(final IBpfMap<StatsMapKey, StatsMapValue> statsMap,
+ final IndentingPrintWriter pw, final String mapName) {
+ if (statsMap == null) {
+ return;
+ }
+
+ BpfDump.dumpMap(statsMap, pw, mapName,
+ "ifaceIndex ifaceName tag_hex uid_int cnt_set rxBytes rxPackets txBytes txPackets",
+ (key, value) -> {
+ final long ifIndex = key.ifaceIndex;
+ final String ifName = mInterfaceMapUpdater.getIfNameByIndex(ifIndex);
+ return ifIndex + " "
+ + (ifName != null ? ifName : "unknown") + " "
+ + "0x" + Long.toHexString(key.tag) + " "
+ + key.uid + " "
+ + key.counterSet + " "
+ + value.rxBytes + " "
+ + value.rxPackets + " "
+ + value.txBytes + " "
+ + value.txPackets;
+ });
+ }
+
private NetworkStats readNetworkStatsSummaryDev() {
try {
return mStatsFactory.readNetworkStatsSummaryDev();
diff --git a/service/Android.bp b/service/Android.bp
index 68c1722..7d3b39a 100644
--- a/service/Android.bp
+++ b/service/Android.bp
@@ -309,7 +309,7 @@
],
out: ["service_connectivity_jarjar_rules.txt"],
cmd: "$(location jarjar-rules-generator) " +
- "--jars $(location :service-connectivity-pre-jarjar{.jar}) " +
+ "$(location :service-connectivity-pre-jarjar{.jar}) " +
"$(location :service-connectivity-tiramisu-pre-jarjar{.jar}) " +
"--prefix android.net.connectivity " +
"--excludes $(location jarjar-excludes.txt) " +
@@ -328,7 +328,7 @@
],
out: ["service_nearby_jarjar_rules.txt"],
cmd: "$(location jarjar-rules-generator) " +
- "--jars $(location :service-nearby-pre-jarjar{.jar}) " +
+ "$(location :service-nearby-pre-jarjar{.jar}) " +
"--prefix com.android.server.nearby " +
"--excludes $(location jarjar-excludes.txt) " +
"--output $(out)",
diff --git a/service/native/TrafficController.cpp b/service/native/TrafficController.cpp
index 7fb1b34..49b23c9 100644
--- a/service/native/TrafficController.cpp
+++ b/service/native/TrafficController.cpp
@@ -647,48 +647,6 @@
dw.println("mCookieTagMap print end with error: %s", res.error().message().c_str());
}
-
- // Print uidStatsMap content.
- std::string statsHeader = StringPrintf("ifaceIndex ifaceName tag_hex uid_int cnt_set rxBytes"
- " rxPackets txBytes txPackets");
- dumpBpfMap("mStatsMapA", dw, statsHeader);
- const auto printStatsInfo = [&dw, this](const StatsKey& key, const StatsValue& value,
- const BpfMap<StatsKey, StatsValue>&) {
- uint32_t ifIndex = key.ifaceIndex;
- auto ifname = mIfaceIndexNameMap.readValue(ifIndex);
- if (!ifname.ok()) {
- ifname = IfaceValue{"unknown"};
- }
- dw.println("%u %s 0x%x %u %u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, ifIndex,
- ifname.value().name, key.tag, key.uid, key.counterSet, value.rxBytes,
- value.rxPackets, value.txBytes, value.txPackets);
- return base::Result<void>();
- };
- res = mStatsMapA.iterateWithValue(printStatsInfo);
- if (!res.ok()) {
- dw.println("mStatsMapA print end with error: %s", res.error().message().c_str());
- }
-
- // Print TagStatsMap content.
- dumpBpfMap("mStatsMapB", dw, statsHeader);
- res = mStatsMapB.iterateWithValue(printStatsInfo);
- if (!res.ok()) {
- dw.println("mStatsMapB print end with error: %s", res.error().message().c_str());
- }
-
- // Print ifaceIndexToNameMap content.
- dumpBpfMap("mIfaceIndexNameMap", dw, "");
- const auto printIfaceNameInfo = [&dw](const uint32_t& key, const IfaceValue& value,
- const BpfMap<uint32_t, IfaceValue>&) {
- const char* ifname = value.name;
- dw.println("ifaceIndex=%u ifaceName=%s", key, ifname);
- return base::Result<void>();
- };
- res = mIfaceIndexNameMap.iterateWithValue(printIfaceNameInfo);
- if (!res.ok()) {
- dw.println("mIfaceIndexNameMap print end with error: %s", res.error().message().c_str());
- }
-
// Print ifaceStatsMap content
std::string ifaceStatsHeader = StringPrintf("ifaceIndex ifaceName rxBytes rxPackets txBytes"
" txPackets");
diff --git a/service/native/TrafficControllerTest.cpp b/service/native/TrafficControllerTest.cpp
index d08ffee..8525738 100644
--- a/service/native/TrafficControllerTest.cpp
+++ b/service/native/TrafficControllerTest.cpp
@@ -60,7 +60,6 @@
constexpr uint32_t TEST_TAG = 42;
constexpr uint32_t TEST_COUNTERSET = 1;
constexpr int TEST_COOKIE = 1;
-constexpr char TEST_IFNAME[] = "test0";
constexpr int TEST_IFINDEX = 999;
constexpr int RXPACKETS = 1;
constexpr int RXBYTES = 100;
@@ -792,17 +791,7 @@
// 999 test0 0x2a 10086 1 100 1 0 0
std::vector<std::string> expectedLines = {
"mCookieTagMap:",
- fmt::format("cookie={} tag={:#x} uid={}", TEST_COOKIE, TEST_TAG, TEST_UID),
- "mStatsMapA",
- "ifaceIndex ifaceName tag_hex uid_int cnt_set rxBytes rxPackets txBytes txPackets",
- fmt::format("{} {} {:#x} {} {} {} {} {} {}",
- TEST_IFINDEX, TEST_IFNAME, TEST_TAG, TEST_UID, TEST_COUNTERSET, RXBYTES,
- RXPACKETS, TXBYTES, TXPACKETS)};
-
- populateFakeIfaceIndexName(TEST_IFNAME, TEST_IFINDEX);
- expectedLines.emplace_back("mIfaceIndexNameMap:");
- expectedLines.emplace_back(fmt::format("ifaceIndex={} ifaceName={}",
- TEST_IFINDEX, TEST_IFNAME));
+ fmt::format("cookie={} tag={:#x} uid={}", TEST_COOKIE, TEST_TAG, TEST_UID)};
ASSERT_TRUE(isOk(updateUidOwnerMaps({TEST_UID}, HAPPY_BOX_MATCH,
TrafficController::IptOpInsert)));
@@ -829,9 +818,6 @@
std::vector<std::string> expectedLines = {
fmt::format("mCookieTagMap {}", kErrIterate),
- fmt::format("mStatsMapA {}", kErrIterate),
- fmt::format("mStatsMapB {}", kErrIterate),
- fmt::format("mIfaceIndexNameMap {}", kErrIterate),
fmt::format("mIfaceStatsMap {}", kErrIterate),
fmt::format("mConfigurationMap {}", kErrReadRulesConfig),
fmt::format("mConfigurationMap {}", kErrReadStatsMapConfig),
diff --git a/tests/cts/net/Android.bp b/tests/cts/net/Android.bp
index a6179fc..23cb15c 100644
--- a/tests/cts/net/Android.bp
+++ b/tests/cts/net/Android.bp
@@ -61,7 +61,9 @@
// uncomment when b/13249961 is fixed
// sdk_version: "current",
platform_apis: true,
- required: ["ConnectivityChecker"],
+ data: [":ConnectivityChecker"],
+ per_testcase_directory: true,
+ host_required: ["net-tests-utils-host-common"],
test_config_template: "AndroidTestTemplate.xml",
}
diff --git a/tests/cts/net/src/android/net/cts/ConnectivityManagerTest.java b/tests/cts/net/src/android/net/cts/ConnectivityManagerTest.java
index cece4df..8dbcc00 100644
--- a/tests/cts/net/src/android/net/cts/ConnectivityManagerTest.java
+++ b/tests/cts/net/src/android/net/cts/ConnectivityManagerTest.java
@@ -165,7 +165,6 @@
import android.os.Process;
import android.os.ServiceManager;
import android.os.SystemClock;
-import android.os.SystemProperties;
import android.os.UserHandle;
import android.os.VintfRuntimeInfo;
import android.platform.test.annotations.AppModeFull;
@@ -353,7 +352,8 @@
// Get com.android.internal.R.array.networkAttributes
int resId = mContext.getResources().getIdentifier("networkAttributes", "array", "android");
String[] naStrings = mContext.getResources().getStringArray(resId);
- boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
+ boolean wifiOnly = mPackageManager.hasSystemFeature(FEATURE_WIFI)
+ && !mPackageManager.hasSystemFeature(FEATURE_TELEPHONY);
for (String naString : naStrings) {
try {
final String[] splitConfig = naString.split(",");
diff --git a/tests/unit/java/com/android/server/ConnectivityServiceTest.java b/tests/unit/java/com/android/server/ConnectivityServiceTest.java
index 9ba466a..5aade99 100755
--- a/tests/unit/java/com/android/server/ConnectivityServiceTest.java
+++ b/tests/unit/java/com/android/server/ConnectivityServiceTest.java
@@ -365,7 +365,6 @@
import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
import com.android.server.connectivity.ClatCoordinator;
import com.android.server.connectivity.ConnectivityFlags;
-import com.android.server.connectivity.MockableSystemProperties;
import com.android.server.connectivity.Nat464Xlat;
import com.android.server.connectivity.NetworkAgentInfo;
import com.android.server.connectivity.NetworkNotificationManager;
@@ -1846,21 +1845,12 @@
class ConnectivityServiceDependencies extends ConnectivityService.Dependencies {
final ConnectivityResources mConnRes;
- @Mock final MockableSystemProperties mSystemProperties;
ConnectivityServiceDependencies(final Context mockResContext) {
- mSystemProperties = mock(MockableSystemProperties.class);
- doReturn(false).when(mSystemProperties).getBoolean("ro.radio.noril", false);
-
mConnRes = new ConnectivityResources(mockResContext);
}
@Override
- public MockableSystemProperties getSystemProperties() {
- return mSystemProperties;
- }
-
- @Override
public HandlerThread makeHandlerThread() {
return mCsHandlerThread;
}
diff --git a/tests/unit/java/com/android/server/net/BpfInterfaceMapUpdaterTest.java b/tests/unit/java/com/android/server/net/BpfInterfaceMapUpdaterTest.java
index c6852d1..83e6b5f 100644
--- a/tests/unit/java/com/android/server/net/BpfInterfaceMapUpdaterTest.java
+++ b/tests/unit/java/com/android/server/net/BpfInterfaceMapUpdaterTest.java
@@ -16,7 +16,14 @@
package com.android.server.net;
+import static android.system.OsConstants.EPERM;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
@@ -27,6 +34,8 @@
import android.os.Build;
import android.os.Handler;
import android.os.test.TestLooper;
+import android.system.ErrnoException;
+import android.util.IndentingPrintWriter;
import androidx.test.filters.SmallTest;
@@ -36,6 +45,7 @@
import com.android.net.module.util.Struct.U32;
import com.android.testutils.DevSdkIgnoreRule;
import com.android.testutils.DevSdkIgnoreRunner;
+import com.android.testutils.TestBpfMap;
import org.junit.Before;
import org.junit.Test;
@@ -44,6 +54,9 @@
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+
@SmallTest
@RunWith(DevSdkIgnoreRunner.class)
@DevSdkIgnoreRule.IgnoreUpTo(Build.VERSION_CODES.S_V2)
@@ -56,7 +69,8 @@
private final TestLooper mLooper = new TestLooper();
private BaseNetdUnsolicitedEventListener mListener;
private BpfInterfaceMapUpdater mUpdater;
- @Mock private IBpfMap<U32, InterfaceMapValue> mBpfMap;
+ private IBpfMap<U32, InterfaceMapValue> mBpfMap =
+ spy(new TestBpfMap<>(U32.class, InterfaceMapValue.class));
@Mock private INetd mNetd;
@Mock private Context mContext;
@@ -118,4 +132,43 @@
mLooper.dispatchAll();
verifyNoMoreInteractions(mBpfMap);
}
+
+ @Test
+ public void testGetIfNameByIndex() throws Exception {
+ mBpfMap.updateEntry(new U32(TEST_INDEX), new InterfaceMapValue(TEST_INTERFACE_NAME));
+ assertEquals(TEST_INTERFACE_NAME, mUpdater.getIfNameByIndex(TEST_INDEX));
+ }
+
+ @Test
+ public void testGetIfNameByIndexNoEntry() {
+ assertNull(mUpdater.getIfNameByIndex(TEST_INDEX));
+ }
+
+ @Test
+ public void testGetIfNameByIndexException() throws Exception {
+ doThrow(new ErrnoException("", EPERM)).when(mBpfMap).getValue(new U32(TEST_INDEX));
+ assertNull(mUpdater.getIfNameByIndex(TEST_INDEX));
+ }
+
+ private void assertDumpContains(final String dump, final String message) {
+ assertTrue(String.format("dump(%s) does not contain '%s'", dump, message),
+ dump.contains(message));
+ }
+
+ private String getDump() {
+ final StringWriter sw = new StringWriter();
+ mUpdater.dump(new IndentingPrintWriter(new PrintWriter(sw), " "));
+ return sw.toString();
+ }
+
+ @Test
+ public void testDump() throws ErrnoException {
+ mBpfMap.updateEntry(new U32(TEST_INDEX), new InterfaceMapValue(TEST_INTERFACE_NAME));
+ mBpfMap.updateEntry(new U32(TEST_INDEX2), new InterfaceMapValue(TEST_INTERFACE_NAME2));
+
+ final String dump = getDump();
+ assertDumpContains(dump, "IfaceIndexNameMap: OK");
+ assertDumpContains(dump, "ifaceIndex=1 ifaceName=test1");
+ assertDumpContains(dump, "ifaceIndex=2 ifaceName=test2");
+ }
}
diff --git a/tests/unit/java/com/android/server/net/InterfaceMapValueTest.java b/tests/unit/java/com/android/server/net/InterfaceMapValueTest.java
new file mode 100644
index 0000000..ee13d5f
--- /dev/null
+++ b/tests/unit/java/com/android/server/net/InterfaceMapValueTest.java
@@ -0,0 +1,68 @@
+/*
+ * 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.net;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public class InterfaceMapValueTest {
+ private static final String IF_NAME = "wlan0";
+ private static final byte[] IF_NAME_BYTE = new byte[]{'w', 'l', 'a', 'n', '0'};
+ private static final byte[] IF_NAME_BYTE_WITH_PADDING =
+ new byte[]{'w', 'l', 'a', 'n', '0', 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0}; // IF_NAME_BYTE_WITH_PADDING.length = 16
+ private static final byte[] IF_NAME_BYTE_LONG =
+ new byte[]{'w', 'l', 'a', 'n', '0', 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0}; // IF_NAME_BYTE_LONG.length = 24
+
+ @Test
+ public void testInterfaceMapValueFromString() {
+ final InterfaceMapValue value = new InterfaceMapValue(IF_NAME);
+ assertArrayEquals(IF_NAME_BYTE_WITH_PADDING, value.interfaceName);
+ }
+
+ @Test
+ public void testInterfaceMapValueFromByte() {
+ final InterfaceMapValue value = new InterfaceMapValue(IF_NAME_BYTE_WITH_PADDING);
+ assertArrayEquals(IF_NAME_BYTE_WITH_PADDING, value.interfaceName);
+ }
+
+ @Test
+ public void testInterfaceMapValueFromByteShort() {
+ final InterfaceMapValue value = new InterfaceMapValue(IF_NAME_BYTE);
+ assertArrayEquals(IF_NAME_BYTE_WITH_PADDING, value.interfaceName);
+ }
+
+ @Test
+ public void testInterfaceMapValueFromByteLong() {
+ final InterfaceMapValue value = new InterfaceMapValue(IF_NAME_BYTE_LONG);
+ assertArrayEquals(IF_NAME_BYTE_WITH_PADDING, value.interfaceName);
+ }
+
+ @Test
+ public void testGetInterfaceNameString() {
+ final InterfaceMapValue value = new InterfaceMapValue(IF_NAME_BYTE_WITH_PADDING);
+ assertEquals(IF_NAME, value.getInterfaceNameString());
+ }
+}
diff --git a/tests/unit/java/com/android/server/net/NetworkStatsServiceTest.java b/tests/unit/java/com/android/server/net/NetworkStatsServiceTest.java
index e27e4e2..fdbccba 100644
--- a/tests/unit/java/com/android/server/net/NetworkStatsServiceTest.java
+++ b/tests/unit/java/com/android/server/net/NetworkStatsServiceTest.java
@@ -2528,4 +2528,28 @@
assertDumpContains(dump, "uid rxBytes rxPackets txBytes txPackets");
assertDumpContains(dump, "1002 10000 10 6000 6");
}
+
+ private void doTestDumpStatsMap(final String expectedIfaceName) throws ErrnoException {
+ initBpfMapsWithTagData(UID_BLUE);
+
+ final String dump = getDump();
+ assertDumpContains(dump, "mStatsMapA: OK");
+ assertDumpContains(dump, "mStatsMapB: OK");
+ assertDumpContains(dump,
+ "ifaceIndex ifaceName tag_hex uid_int cnt_set rxBytes rxPackets txBytes txPackets");
+ assertDumpContains(dump, "10 " + expectedIfaceName + " 0x2 1002 0 5000 5 3000 3");
+ assertDumpContains(dump, "10 " + expectedIfaceName + " 0x1 1002 0 5000 5 3000 3");
+ }
+
+ @Test
+ public void testDumpStatsMap() throws ErrnoException {
+ doReturn("wlan0").when(mBpfInterfaceMapUpdater).getIfNameByIndex(10 /* index */);
+ doTestDumpStatsMap("wlan0");
+ }
+
+ @Test
+ public void testDumpStatsMapUnknownInterface() throws ErrnoException {
+ doReturn(null).when(mBpfInterfaceMapUpdater).getIfNameByIndex(10 /* index */);
+ doTestDumpStatsMap("unknown");
+ }
}
diff --git a/tools/Android.bp b/tools/Android.bp
index 1fa93bb..7d6b248 100644
--- a/tools/Android.bp
+++ b/tools/Android.bp
@@ -48,6 +48,7 @@
java_library {
name: "jarjar-rules-generator-testjavalib",
srcs: ["testdata/java/**/*.java"],
+ libs: ["unsupportedappusage"],
visibility: ["//visibility:private"],
}
@@ -67,6 +68,17 @@
compile_dex: false,
}
+java_library {
+ name: "framework-connectivity-t.stubs.module_lib-for-test",
+ visibility: ["//visibility:private"],
+ static_libs: [
+ "framework-connectivity-t.stubs.module_lib",
+ ],
+ // Not strictly necessary but specified as this MUST not have generate
+ // a dex jar as that will break the tests.
+ compile_dex: false,
+}
+
python_test_host {
name: "jarjar-rules-generator-test",
srcs: [
@@ -75,8 +87,11 @@
],
data: [
"testdata/test-jarjar-excludes.txt",
+ // two unsupportedappusage lists with different classes to test using multiple lists
"testdata/test-unsupportedappusage.txt",
+ "testdata/test-other-unsupportedappusage.txt",
":framework-connectivity.stubs.module_lib-for-test",
+ ":framework-connectivity-t.stubs.module_lib-for-test",
":jarjar-rules-generator-testjavalib",
],
main: "gen_jarjar_test.py",
diff --git a/tools/gen_jarjar.py b/tools/gen_jarjar.py
index 2ff53fa..eb686ce 100755
--- a/tools/gen_jarjar.py
+++ b/tools/gen_jarjar.py
@@ -28,8 +28,8 @@
def parse_arguments(argv):
parser = argparse.ArgumentParser()
parser.add_argument(
- '--jars', nargs='+',
- help='Path to pre-jarjar JAR. Can be followed by multiple space-separated paths.')
+ 'jars', nargs='+',
+ help='Path to pre-jarjar JAR. Multiple jars can be specified.')
parser.add_argument(
'--prefix', required=True,
help='Package prefix to use for jarjared classes, '
@@ -37,18 +37,17 @@
parser.add_argument(
'--output', required=True, help='Path to output jarjar rules file.')
parser.add_argument(
- '--apistubs', nargs='*', default=[],
- help='Path to API stubs jar. Classes that are API will not be jarjared. Can be followed by '
- 'multiple space-separated paths.')
+ '--apistubs', action='append', default=[],
+ help='Path to API stubs jar. Classes that are API will not be jarjared. Can be repeated to '
+ 'specify multiple jars.')
parser.add_argument(
- '--unsupportedapi', nargs='*', default=[],
- help='Path to UnsupportedAppUsage hidden API .txt lists. '
- 'Classes that have UnsupportedAppUsage API will not be jarjared. Can be followed by '
- 'multiple space-separated paths.')
+ '--unsupportedapi',
+ help='Column(:)-separated paths to UnsupportedAppUsage hidden API .txt lists. '
+ 'Classes that have UnsupportedAppUsage API will not be jarjared.')
parser.add_argument(
- '--excludes', nargs='*', default=[],
- help='Path to files listing classes that should not be jarjared. Can be followed by '
- 'multiple space-separated paths. '
+ '--excludes', action='append', default=[],
+ help='Path to files listing classes that should not be jarjared. Can be repeated to '
+ 'specify multiple files.'
'Each file should contain one full-match regex per line. Empty lines or lines '
'starting with "#" are ignored.')
return parser.parse_args(argv)
@@ -103,8 +102,10 @@
for apistubs_file in args.apistubs:
excluded_classes.update(_list_toplevel_jar_classes(apistubs_file))
- for unsupportedapi_file in args.unsupportedapi:
- excluded_classes.update(_list_hiddenapi_classes(unsupportedapi_file))
+ unsupportedapi_files = (args.unsupportedapi and args.unsupportedapi.split(':')) or []
+ for unsupportedapi_file in unsupportedapi_files:
+ if unsupportedapi_file:
+ excluded_classes.update(_list_hiddenapi_classes(unsupportedapi_file))
exclude_regexes = []
for exclude_file in args.excludes:
diff --git a/tools/gen_jarjar_test.py b/tools/gen_jarjar_test.py
index 8d8e82b..f5bf499 100644
--- a/tools/gen_jarjar_test.py
+++ b/tools/gen_jarjar_test.py
@@ -31,11 +31,11 @@
class TestGenJarjar(unittest.TestCase):
def test_gen_rules(self):
args = gen_jarjar.parse_arguments([
- "--jars", "jarjar-rules-generator-testjavalib.jar",
+ "jarjar-rules-generator-testjavalib.jar",
"--prefix", "jarjar.prefix",
"--output", "test-output-rules.txt",
"--apistubs", "framework-connectivity.stubs.module_lib.jar",
- "--unsupportedapi", "testdata/test-unsupportedappusage.txt",
+ "--unsupportedapi", ":testdata/test-unsupportedappusage.txt",
"--excludes", "testdata/test-jarjar-excludes.txt",
])
gen_jarjar.make_jarjar_rules(args)
@@ -43,6 +43,39 @@
with open(args.output) as out:
lines = out.readlines()
+ self.maxDiff = None
+ self.assertListEqual([
+ 'rule android.net.IpSecTransform jarjar.prefix.@0\n',
+ 'rule android.net.IpSecTransformTest jarjar.prefix.@0\n',
+ 'rule android.net.IpSecTransformTest$* jarjar.prefix.@0\n',
+ 'rule test.unsupportedappusage.OtherUnsupportedUsageClass jarjar.prefix.@0\n',
+ 'rule test.unsupportedappusage.OtherUnsupportedUsageClassTest jarjar.prefix.@0\n',
+ 'rule test.unsupportedappusage.OtherUnsupportedUsageClassTest$* jarjar.prefix.@0\n',
+ 'rule test.utils.TestUtilClass jarjar.prefix.@0\n',
+ 'rule test.utils.TestUtilClassTest jarjar.prefix.@0\n',
+ 'rule test.utils.TestUtilClassTest$* jarjar.prefix.@0\n',
+ 'rule test.utils.TestUtilClass$TestInnerClass jarjar.prefix.@0\n',
+ 'rule test.utils.TestUtilClass$TestInnerClassTest jarjar.prefix.@0\n',
+ 'rule test.utils.TestUtilClass$TestInnerClassTest$* jarjar.prefix.@0\n'
+ ], lines)
+
+ def test_gen_rules_repeated_args(self):
+ args = gen_jarjar.parse_arguments([
+ "jarjar-rules-generator-testjavalib.jar",
+ "--prefix", "jarjar.prefix",
+ "--output", "test-output-rules.txt",
+ "--apistubs", "framework-connectivity.stubs.module_lib.jar",
+ "--apistubs", "framework-connectivity-t.stubs.module_lib.jar",
+ "--unsupportedapi",
+ "testdata/test-unsupportedappusage.txt:testdata/test-other-unsupportedappusage.txt",
+ "--excludes", "testdata/test-jarjar-excludes.txt",
+ ])
+ gen_jarjar.make_jarjar_rules(args)
+
+ with open(args.output) as out:
+ lines = out.readlines()
+
+ self.maxDiff = None
self.assertListEqual([
'rule test.utils.TestUtilClass jarjar.prefix.@0\n',
'rule test.utils.TestUtilClassTest jarjar.prefix.@0\n',
diff --git a/tools/testdata/java/android/net/IpSecTransform.java b/tools/testdata/java/android/net/IpSecTransform.java
new file mode 100644
index 0000000..0140bc5
--- /dev/null
+++ b/tools/testdata/java/android/net/IpSecTransform.java
@@ -0,0 +1,23 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.net;
+
+/**
+ * Test class with a name matching a public API in a secondary (framework-connectivity-t) stubs jar.
+ */
+public class IpSecTransform {
+}
diff --git a/tools/testdata/java/test/unsupportedappusage/OtherUnsupportedUsageClass.java b/tools/testdata/java/test/unsupportedappusage/OtherUnsupportedUsageClass.java
new file mode 100644
index 0000000..9d3ae2e0
--- /dev/null
+++ b/tools/testdata/java/test/unsupportedappusage/OtherUnsupportedUsageClass.java
@@ -0,0 +1,25 @@
+/*
+ * 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 test.unsupportedappusage;
+
+import android.compat.annotation.UnsupportedAppUsage;
+
+public class OtherUnsupportedUsageClass {
+ // The annotation is just for completeness, what matters is the unsupportedappusage.txt file
+ @UnsupportedAppUsage
+ public void testSecondMethod() {}
+}
diff --git a/tools/testdata/java/test/unsupportedappusage/TestUnsupportedAppUsageClass.java b/tools/testdata/java/test/unsupportedappusage/TestUnsupportedAppUsageClass.java
index 9d32296..460c91b 100644
--- a/tools/testdata/java/test/unsupportedappusage/TestUnsupportedAppUsageClass.java
+++ b/tools/testdata/java/test/unsupportedappusage/TestUnsupportedAppUsageClass.java
@@ -16,6 +16,11 @@
package test.unsupportedappusage;
+
+import android.compat.annotation.UnsupportedAppUsage;
+
public class TestUnsupportedAppUsageClass {
+ // The annotation is just for completeness, what matters is the unsupportedappusage.txt file
+ @UnsupportedAppUsage
public void testMethod() {}
}
diff --git a/tools/testdata/test-other-unsupportedappusage.txt b/tools/testdata/test-other-unsupportedappusage.txt
new file mode 100644
index 0000000..b7d74a4
--- /dev/null
+++ b/tools/testdata/test-other-unsupportedappusage.txt
@@ -0,0 +1 @@
+Ltest/unsupportedappusage/OtherUnsupportedUsageClass;->testSecondMethod()V
\ No newline at end of file