In-depth analysis and research on Android 13 network Adb related processes

Android 13 Network Adb Analysis Research

Article directory

I. Introduction

Through code analysis, it was discovered that network adb is restricted on Android 13!
Android13 native code requirements: You must be connected to a certain wifi before adb can be used, and switching wifi or turning off wifi will stop adb.
And the wifi adb port number on Android13 changes every time, which is also very inconvenient!

If you want to make Android 11 or the same as before, the computer can directly connect to adb after the device is connected to WiFi/wired network, and the system code must be adapted and modified.

I thought it would be ok to set the port number and persist.adb.tls_server.enable property, but there are still some small bugs, and I still need to study the specific process completely.

The adb default port number setting has been posted before:
https://blog.csdn.net/wenzhi20102321/article/details/131056174

The default adb implements simple analysis:

https://blog.csdn.net/wenzhi20102321/article/details/131774893

By default, adb enables analysis:
https://blog.csdn.net/wenzhi20102321/article/details/132382549

The latter two articles are of simple research and reference value. At that time, the whole process could still be understood in more depth, so I wrote another article specially.

This is also the first article on the entire network that comprehensively analyzes the wifi adb code for Android 12 and above. If you need it, you can like it and save it.

The following are the analyzed adb related source code files of Android13:

https://download.csdn.net/download/wenzhi20102321/88306366

2. Default adb code implementation

The essential:
1、mk 设置系统属性:persist.adb.tls_server.enable=1
2、写死端口号 5555
3、注释若干判断Wifi情况停止adb的代码

1. Modified directory:

packages\modules\adb\daemon\adb_wifi.cpp
framework\base\services\core\java\com\android\server\adb\AdbDebuggingManager.java

//修改前面两个文件就可以实现adb了,后面的文件试辅助分析的。

//虽然 SettingsProvider 也有加载 Settings属性 Settings.Global.ADB_WIFI_ENABLED ,
//但是 prop那个属性更优先,所以可以不用考虑这里默认情况
framework\base\packages\SettingsProvider\src\com\android\providers\settings\SettingsProvider.java

//增加分析定位文件,系统服务启动后会判断 属性persist.adb.tls_server.enable 进行相关操作
//如果属性设置不生效,可以在这里添加打印日志查看过程
framework\base\services\core\java\com\android\server\adb\AdbService.java

2. Specific modifications:

(1) Add attributes in XXX_device.mk

persist.adb.tls_server.enable = 1

Even if you add it manually, it will be remembered!

//设置
setprop persist.adb.tls_server.enable  1
//查询
getprop persist.adb.tls_server.enable
//可以查看其他adb相关属性
getprop | grep adb 

(2) Set a fixed port number

+++ b/release/packages/modules/adb/daemon/adb_wifi.cpp
@@ -160,7 +160,8 @@ static void enable_wifi_debugging() {
     if (sTlsServer != nullptr) {
         delete sTlsServer;
     }
-    sTlsServer = new TlsServer(0);
+    // default port 0 means random,change to 5555 ,by liwenzhi
+    sTlsServer = new TlsServer(5555);
     if (!sTlsServer->Start()) {
         LOG(ERROR) << "Failed to start TlsServer";
         delete sTlsServer;
         

The fixed port number must be set here. Setting it using the service.adb.tls.port property is actually useless!

(3) After removing the code to determine the network, set ADB_WIFI_ENABLED to 0

Check the wifi network to determine whether the wired network adb and wifi can be modified or the key is normal adb.
One is judged during initialization, and the other is judged when monitoring network changes. Just remove them.

+++ b/release/frameworks/base/services/core/java/com/android/server/adb/AdbDebuggingManager.java
public class AdbDebuggingManager {


                case MSG_ADBDWIFI_ENABLE: {
                    if (mAdbWifiEnabled) {
                        break;
                    }

                    //not to check network state ,change by  liwenzhi //(1)去除下面一大段判断网络和监听网络的代码
                    /** AdbConnectionInfo currentInfo = getCurrentWifiApInfo();
                    if (currentInfo == null) {
                        Settings.Global.putInt(mContentResolver,
                                Settings.Global.ADB_WIFI_ENABLED, 0); //关闭 adb wifi
                        break;
                    }

                    if (!verifyWifiNetwork(currentInfo.getBSSID(),
                            currentInfo.getSSID())) {
                        // This means that the network is not in the list of trusted networks.
                        // We'll give user a prompt on whether to allow wireless debugging on
                        // the current wifi network.
                        Settings.Global.putInt(mContentResolver,
                                Settings.Global.ADB_WIFI_ENABLED, 0);
                        break;
                    }

                    setAdbConnectionInfo(currentInfo); **/
                    //no listener network change for disable adb_wifi,by  liwenzhi
                    /** IntentFilter intentFilter =
                            new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION);
                    intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
                    mContext.registerReceiver(mBroadcastReceiver, intentFilter); **/

                    SystemProperties.set(WIFI_PERSISTENT_CONFIG_PROPERTY, "1");


                case MSG_ADBDWIFI_DISABLE:
                    if (!mAdbWifiEnabled) {
                        break;
                    }
                    mAdbWifiEnabled = false;
                    setAdbConnectionInfo(null);
                    //no need unregisterReceiver, because no listener network,chenge by liwenzhi,//(2)监听已经注释,不需要再注销监听
                    //mContext.unregisterReceiver(mBroadcastReceiver);


                case MSG_ADBWIFI_ALLOW:
                    if (mAdbWifiEnabled) {
                        break;
                    }
                    String bssid = (String) msg.obj;
                    boolean alwaysAllow = msg.arg1 == 1;
                    if (alwaysAllow) {
                        mAdbKeyStore.addTrustedNetwork(bssid);
                    }

                    // Let's check again to make sure we didn't switch networks while verifying
                    // the wifi bssid.
                    //no to check network ,change by  liwenzhi //(3)不需要判断网络
                    /** AdbConnectionInfo newInfo = getCurrentWifiApInfo();
                    if (newInfo == null || !bssid.equals(newInfo.getBSSID())) {
                        break;
                    }

                    setAdbConnectionInfo(newInfo); **/
                    Settings.Global.putInt(mContentResolver,
                            Settings.Global.ADB_WIFI_ENABLED, 1);
                    //no listener network change for disable adb_wifi,by  liwenzhi //(4)不需要要监听网络变化
                    /** IntentFilter intentFilter =
                            new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION);
                    intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
                    mContext.registerReceiver(mBroadcastReceiver, intentFilter); **/

                    SystemProperties.set(WIFI_PERSISTENT_CONFIG_PROPERTY, "1");


From the above code, we can see that when wifi is not connected, getCurrentWifiApInfo is null, and wifi adb will be closed!
And there are many judgments about network switch changes and network status changes.

3. Log analysis and viewing

Log analysis and viewing mainly include: AdbService.java, AdbDebuggingManager.java, adb_wifi.cpp.
AdbService logs are in closed mode by default and need to be set to true. If you want to see the specific values ​​of the data inside, the logs of related attributes need to be added and printed out by yourself. AdbDebuggingManager is the printout of the adb_wifi file with related exception process logs. The TAG is adbd. Regardless of whether adb is opened or not, the entire system always has printouts related to adbd. There are about a dozen lines of logs per second
!

Here are the information commands for printing multiple keywords in related logs:

The logs of each system may be different, so here they are for reference:


logcat | grep -E "lwz|AdbService|changed to|adb wifi|AdbDebuggingManager"

lwz is a keyword I added myself.

Viewing the logs, the approximate log process for normal startup is as follows:


01-01 08:00:22.756   496   511 I adbd    : Waiting for persist.adb.tls_server.enable=1
08-16 15:13:50.123   762   762 D SystemServerTiming: StartAdbService
08-16 15:13:51.528   762   762 D AdbService: systemReady //修改 DEBUG = true 才看到的日志
08-16 15:13:51.528   762   762 D AdbService: lwz systemReady= persist.adb.tls_server.enable = 1 //自己加的日志打印
08-16 15:13:51.528   762   762 D AdbService: lwz systemReady mIsAdbWifiEnabled= true //自己加的日志打印,确认查看服务启动是否打开 adb
08-16 15:13:58.993   762   799 D AdbService: setAdbEnabled(true), mIsAdbUsbEnabled=true, mIsAdbWifiEnabled=true, transportType=0
08-16 15:13:58.994   762   762 D AdbService: lwz onChange shouldEnable = true
08-16 15:13:58.995   762   799 D AdbService: setAdbEnabled(true), mIsAdbUsbEnabled=true, mIsAdbWifiEnabled=true, transportType=1
08-16 15:13:59.015   762   802 D ActivityManagerTiming: OnBootPhase_1000_com.android.server.adb.AdbService$Lifecycle
08-16 15:13:59.016   762   802 V ActivityManagerTiming: OnBootPhase_1000_com.android.server.adb.AdbService$Lifecycle took to complete: 1ms
08-16 15:13:59.016   762   799 D AdbService: boot completed
08-16 15:13:59.033   496   511 I adbd    : persist.adb.tls_server.enable changed to 1 //正常开启adb的日志
08-16 15:13:59.056   496   511 I adbd    : adb wifi started on port 5555
08-16 15:13:59.058   496   511 I adbd    : Waiting for persist.adb.tls_server.enable=0

If network judgment is not blocked, add the print log viewing process:

08-18 16:51:20.104   762   762 D SystemServerTiming: OnBootPhase_550_com.android.server.adb.AdbService$Lifecycle
08-18 16:51:20.104   762   762 D AdbService: systemReady
08-18 16:51:20.105   762   762 D AdbService: lwz systemReady mIsAdbWifiEnabled= true //这里说明,prop 属性已经设置了
08-18 16:51:26.248   762   798 I AdbDebuggingManager: Not connected to any wireless network. Not enabling adbwifi. //这里提示没网络,会执行关闭adb
08-18 16:51:26.586   762   762 D AdbService: lwz onChange shouldEnable = false
08-18 16:51:27.411   762   762 D AdbService: lwz onChange shouldEnable = false
08-18 16:51:27.971   762   798 D AdbService: setAdbEnabled(true), mIsAdbUsbEnabled=true, mIsAdbWifiEnabled=true, transportType=0
08-18 16:51:27.972   762   798 D AdbService: setAdbEnabled(false), mIsAdbUsbEnabled=true, mIsAdbWifiEnabled=true, transportType=1 //关闭adb
08-18 16:51:27.973   510   517 I adbd    : persist.adb.tls_server.enable changed to 0  //到这里 persist.adb.tls_server.enable 属性又变成了 0
08-18 16:51:27.973   510   517 I adbd    : adb wifi stopped
08-18 16:51:27.981   762   798 D AdbService: Broadcasting enable = false, type = 1

This is also why after configuring the persist.adb.tls_server.enable =1 attribute, the system startup found that the obtained attribute was still 0, and wifi adb was not turned on.

If you turn on the log switch and do not add custom logs, there will not be so many logs displayed.

If the code and attributes are adapted, but there is still no default adb, then you need to sort out the code or add more log analysis to check.

4. Code process

In fact, the process between the three classes of AdbService.java, AdbDebuggingManager.java, and adb_wifi.cpp is almost the same.

This type of adb_wifi.cpp is not available in Android 11 and previous versions, but other Java classes are always available.
packages\modules\adb This directory is only available since Android 12.

1. adb_wifi bottom startup

The logs inside are run earlier than SystemServer.
This is also why setting persist.adb.tls_server.enable=1 can directly enable network adb.
There are related logs for opening and closing adb normally.
Specifically, adb is started only when the upper layer calls the interface to the lower layer.

Here is a look at the most important piece of code


const char kWifiPortProp[] = "service.adb.tls.port"; //(1)adb 端口号属性

const char kWifiEnabledProp[] = "persist.adb.tls_server.enable"; //(2)adb prop 开关属性

//(3)底层开启adb 具体实现
static void enable_wifi_debugging() {
    start_mdnsd();

    if (sTlsServer != nullptr) {
        delete sTlsServer;
    }
    sTlsServer = new TlsServer(5555); //(4)写死端口号,不写死会随机生成
    if (!sTlsServer->Start()) {
        LOG(ERROR) << "Failed to start TlsServer";
        delete sTlsServer;
        sTlsServer = nullptr;
        return;
    }

    // Start mdns connect service for discovery
    register_adb_secure_connect_service(sTlsServer->port());
   //(5)开启 adb 后,这里是会有打印的,并且对端口号属性进行了赋值
   //所以代码中设置端口号的prop 数值是没啥意义的
    LOG(INFO) << "lwz adb wifi started on port " << sTlsServer->port();
    SetProperty(kWifiPortProp, std::to_string(sTlsServer->port()));
}

//(6)底层关闭adb 具体实现
static void disable_wifi_debugging() {
    if (sTlsServer != nullptr) {
        delete sTlsServer;
        sTlsServer = nullptr;
    }
    if (is_adb_secure_connect_service_registered()) {
        unregister_adb_secure_connect_service();
    }
    kick_all_tcp_tls_transports();
   //(7)关闭 adb 后,这里是会有打印的,并且对端口号属性进行了赋值
   //所以代码中设置端口号的prop 数值是没啥意义的
    LOG(INFO) << "adb wifi stopped";
    SetProperty(kWifiPortProp, "");
}

//(8)关键:这个逻辑不难,刚开始看懵了!!
// Watches for the #kWifiEnabledProp property to toggle the TlsServer
static void start_wifi_enabled_observer() {
    std::thread([]() {
        bool wifi_enabled = false;
        while (true) { // (9)这里不会阻塞,WaitForProperty 会等待属性设置,否则一直等待状态
            std::string toggled_val = wifi_enabled ? "0" : "1";
            LOG(INFO) << "lwz Waiting for " << kWifiEnabledProp << "=" << toggled_val; //(10)正常开机会打印这个,等待进入1,即等待开启状态
            if (WaitForProperty(kWifiEnabledProp, toggled_val)) { //底层的等待状态,等待某个属性变成某个值
                wifi_enabled = !wifi_enabled;
                // (11)prop 属性变化,这里会有打印
                //上面是while true,这里修改后,马上又进入了 “Waiting for”下一次属性变化的监听
                LOG(INFO) << kWifiEnabledProp << " changed to " << toggled_val;
                if (wifi_enabled) {
                    enable_wifi_debugging(); //(12)开启adb
                } else {
                    disable_wifi_debugging(); //(13)关闭adb
                }
            }
        }
    }).detach();
}


The above 13 main points are the important processes in adb cpp.
Other more specific and underlying issues will not be studied and analyzed here.

Refer to the underlying thread logic of adb written by others:

https://blog.csdn.net/qq_35970872/article/details/78912611

Android13 also has related underlying logic, code path:

packages\modules\adb\transport.cpp

There are threads inside that have been reading data. I can’t understand the specific logic, so I won’t analyze it!

2. adb upper layer startup

AdbService is a service started when SystemServer executes startOtherServices.

AdbService extends IAdbManager.Stub //For specific exposed interfaces, see IAdbManager

AdbDebuggingManager is a class that manages adbDebug. It is instantiated in AdbService. It actually divides the specific execution code.

Many situations where adb wifi cannot be accessed are rejected by AdbDebuggingManager, and the Global attribute and Prop attribute are reset to 0.

(1) SystemServce.java starts AdbServices code

framework\base\services\java\com\android\server\SystemServer.java

/**
 * Entry point to {@code system_server}.
 */
public final class SystemServer implements Dumpable {

    private static final String ADB_SERVICE_CLASS =
            "com.android.server.adb.AdbService$Lifecycle";

    /**
     * The main entry point from zygote.
     */
    public static void main(String[] args) { //(1)java 入口方法
        new SystemServer().run();
    }

    private void run() { //(2)启动上层系统相关服务
            t.traceBegin("StartServices");
            startBootstrapServices(t); //启动核心服务,电源管理、AMS、WMS、PMS等服务
            startCoreServices(t);  //启动关键服务,电池状态信息等服务
            startOtherServices(t); //(3)启动其他服务(最多),蓝牙,wifi,通知,adb等服务
            startApexServices(t); //启动app相关服务
    }

    private void startOtherServices(@NonNull TimingsTraceAndSlog t) { //(4)启动其他服务
        t.traceBegin("startOtherServices");
            // Start ADB Debugging Service
            t.traceBegin("StartAdbService");
            try {
                mSystemServiceManager.startService(ADB_SERVICE_CLASS); //启动蓝牙相关服务
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting AdbService");
            }
            t.traceEnd();
    }

}

(2) AdbServices.java key code after service startup

This AdbService is not a specific service (not the Service among the four major components), but a service bound through AIDL.
Other classes can call the implementation through the interface object IXXX/Manager of this service.

One special thing is that it inherits SystemService and can monitor the completion of system startup.

framework\base\services\core\java\com\android\server\adb\AdbService.java

public class AdbService extends IAdbManager.Stub {  //(1)不是普通Service

    private static final boolean DEBUG = true; //打印默认为false,可以修改true 打开她

    private static final String USB_PERSISTENT_CONFIG_PROPERTY = "persist.sys.usb.config";
    private static final String WIFI_PERSISTENT_CONFIG_PROPERTY = "persist.adb.tls_server.enable";

   private AdbService(Context context) {
        mContext = context;
        mContentResolver = context.getContentResolver();
        mDebuggingManager = new AdbDebuggingManager(context); //(2)从这里看就知道 AdbDebuggingManager 不是 AdbServices 的暴露Manager

        registerContentObservers(); //(3)监听 Settings.Global.ADB_WIFI_ENABLED 属性变化
        LocalServices.addService(AdbManagerInternal.class, new AdbManagerInternalImpl());
    }

    /**
     * Manages the service lifecycle for {@code AdbService} in {@code SystemServer}.
     */
    public static class Lifecycle extends SystemService { //(4)监听系统启动
        private AdbService mAdbService;

        public Lifecycle(Context context) {
            super(context);
        }

        @Override
        public void onStart() {
            mAdbService = new AdbService(getContext()); //(5)系统启动,创建对象
            publishBinderService(Context.ADB_SERVICE, mAdbService);
        }

        @Override
        public void onBootPhase(int phase) {
            if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) { //这个消息其实是SystemServer在启动OtherServie中间代码发出的。
                mAdbService.systemReady(); //(6)系统关键服务启动完成,调用。这里比开机广播早。
            } else if (phase == SystemService.PHASE_BOOT_COMPLETED) { // 里面的 bootCompleted 方法也是重新调用了开关Wifi adb,不过不一定会跑这里。我这系统代码没看到跑这里。
                FgThread.getHandler().sendMessage(obtainMessage(
                        AdbService::bootCompleted, mAdbService));
            }
        }
    }

    /**
     * Called in response to {@code SystemService.PHASE_ACTIVITY_MANAGER_READY} from {@code
     * SystemServer}.
     */
    public void systemReady() { //(7)系统关键服务启动完成
        if (DEBUG) Slog.d(TAG, "systemReady");

        /*
         * Use the normal bootmode persistent prop to maintain state of adb across
         * all boot modes.
         */
        //(8)判断Usb调试 是否打开
        mIsAdbUsbEnabled = containsFunction(
                SystemProperties.get(USB_PERSISTENT_CONFIG_PROPERTY, ""), //USB_PERSISTENT_CONFIG_PROPERTY=sys.usb.config
                UsbManager.USB_FUNCTION_ADB); // USB_FUNCTION_ADB=adb
        boolean shouldEnableAdbUsb = mIsAdbUsbEnabled
                || SystemProperties.getBoolean(
                        TestHarnessModeService.TEST_HARNESS_MODE_PROPERTY, false); //属性: persist.sys.test_harness

        // 可以添加打印查看prop属性,
        Slog.d(TAG, "lwz systemReady= " + WIFI_PERSISTENT_CONFIG_PROPERTY + " = " + SystemProperties.get(WIFI_PERSISTENT_CONFIG_PROPERTY, "0"));
        // (9)判断Wifi adb 是否打开,persist.adb.tls_server.enable 属性是否为1
        mIsAdbWifiEnabled = "1".equals(SystemProperties.get(WIFI_PERSISTENT_CONFIG_PROPERTY, "0"));
        // 可以添加打印查看是否是打开wifiadb状态,
        Slog.d(TAG, "lwz systemReady mIsAdbWifiEnabled= " + mIsAdbWifiEnabled);

        // make sure the ADB_ENABLED setting value matches the current state
        try {

            //(10)保存Settings 属性后会有重新调用 setAdbEnabled,因为这里进行了监听
            Settings.Global.putInt(mContentResolver,
                    Settings.Global.ADB_ENABLED, shouldEnableAdbUsb ? 1 : 0);
            Settings.Global.putInt(mContentResolver,
                    Settings.Global.ADB_WIFI_ENABLED, mIsAdbWifiEnabled ? 1 : 0);
        } catch (SecurityException e) {
            // If UserManager.DISALLOW_DEBUGGING_FEATURES is on, that this setting can't be changed.
            Slog.d(TAG, "ADB_ENABLED is restricted.");
        }
    }

    /**
     * Called in response to {@code SystemService.PHASE_BOOT_COMPLETED} from {@code SystemServer}.
     */
    public void bootCompleted() { //开机完成后,调用设置方法,这边不一定调用到!
        if (DEBUG) Slog.d(TAG, "boot completed + mIsAdbWifiEnabled" + mIsAdbWifiEnabled);
        if (mDebuggingManager != null) {
            mDebuggingManager.setAdbEnabled(mIsAdbUsbEnabled, AdbTransportType.USB);
            mDebuggingManager.setAdbEnabled(mIsAdbWifiEnabled, AdbTransportType.WIFI);
        }
    }

}

    // (11)监听Settings属性变化
    private void registerContentObservers() {
        try {
            // register observer to listen for settings changes
            mObserver = new AdbSettingsObserver();
            //(12)注册监听usb开关和wifi adb开关
            mContentResolver.registerContentObserver(
                    Settings.Global.getUriFor(Settings.Global.ADB_ENABLED),
                    false, mObserver);
            mContentResolver.registerContentObserver(
                    Settings.Global.getUriFor(Settings.Global.ADB_WIFI_ENABLED),
                    false, mObserver);
        } catch (Exception e) {
            Slog.e(TAG, "Error in registerContentObservers", e);
        }
    }

    // (13)Settings属性 内部监听类,这里说明代码中修改 ADB_WIFI_ENABLED 属性或者adb shell中动态修改属性,这里也是能收到的
    private class AdbSettingsObserver extends ContentObserver {
        private final Uri mAdbUsbUri = Settings.Global.getUriFor(Settings.Global.ADB_ENABLED);
        private final Uri mAdbWifiUri = Settings.Global.getUriFor(Settings.Global.ADB_WIFI_ENABLED);

        AdbSettingsObserver() {
            super(null);
        }

        @Override
        public void onChange(boolean selfChange, @NonNull Uri uri, @UserIdInt int userId) {
            if (mAdbUsbUri.equals(uri)) {
                boolean shouldEnable = (Settings.Global.getInt(mContentResolver,
                        Settings.Global.ADB_ENABLED, 0) > 0);
                FgThread.getHandler().sendMessage(obtainMessage(
                        AdbService::setAdbEnabled, AdbService.this, shouldEnable,
                            AdbTransportType.USB));
            } else if (mAdbWifiUri.equals(uri)) { // (14)ADB_WIFI_ENABLED 属性监听回调
                boolean shouldEnable = (Settings.Global.getInt(mContentResolver,
                        Settings.Global.ADB_WIFI_ENABLED, 0) > 0);
                 // (15)自己添加的打印,打印一下开关状态值
                Slog.d(TAG, "lwz onChange shouldEnable = " + shouldEnable);
                 // (16)系统属性值变化后,执行 AdbService.setAdbEnabled 方法
                FgThread.getHandler().sendMessage(obtainMessage(
                        AdbService::setAdbEnabled, AdbService.this, shouldEnable,
                            AdbTransportType.WIFI));
            }
        }
    }

    //(17) 执行usb 开关和adb开关的方法
    private void setAdbEnabled(boolean enable, byte transportType) { //transportType ,usb =1,wifi = 1
        if (DEBUG) {
            Slog.d(TAG, "setAdbEnabled(" + enable + "), mIsAdbUsbEnabled=" + mIsAdbUsbEnabled
                    + ", mIsAdbWifiEnabled=" + mIsAdbWifiEnabled + ", transportType="
                        + transportType);
        }

        if (transportType == AdbTransportType.USB && enable != mIsAdbUsbEnabled) {
            mIsAdbUsbEnabled = enable;
        } else if (transportType == AdbTransportType.WIFI && enable != mIsAdbWifiEnabled) {
            mIsAdbWifiEnabled = enable;
            if (mIsAdbWifiEnabled) {
                if (!AdbProperties.secure().orElse(false) && mDebuggingManager == null) {
                    // Start adbd. If this is secure adb, then we defer enabling adb over WiFi.
                    SystemProperties.set(WIFI_PERSISTENT_CONFIG_PROPERTY, "1");
                    mConnectionPortPoller =
                            new AdbDebuggingManager.AdbConnectionPortPoller(mPortListener);
                    mConnectionPortPoller.start(); // (18) AdbConnectionPortPoller 是一个线程对象,不清楚为啥要启动这个线程,底层也有线程!里面没看到做非常重要的事情。
                }
            } else {
                // Stop adb over WiFi.
                SystemProperties.set(WIFI_PERSISTENT_CONFIG_PROPERTY, "0");
                if (mConnectionPortPoller != null) {
                    mConnectionPortPoller.cancelAndWait(); //停止线程
                    mConnectionPortPoller = null;
                }
            }
        } else {
            // No change
            return;
        }

        if (enable) {
            startAdbd(); //这里的start 和 stop 无关紧要,不用关注
        } else {
            stopAdbd();
        }
        。。。。
        // (19)其实这里调用 DebuggingManager 方法才是最关键的,其他都是kalife
        if (mDebuggingManager != null) {
            mDebuggingManager.setAdbEnabled(enable, transportType);
        }
        
    }

    //这个的startAdbd 只设置了一个属性,没看到上层有判断使用,可能底层有读取这个属性
    private void startAdbd() {
        SystemProperties.set(CTL_START, ADBD);
    }

    //这个的stopAdbd 只设置了一个属性,
    private void stopAdbd() {
        if (!mIsAdbUsbEnabled && !mIsAdbWifiEnabled) {
            SystemProperties.set(CTL_STOP, ADBD);
        }
    }


The following is the key code, analysis of AdbDebuggingManager

framework\base\services\core\java\com\android\server\adb\AdbDebuggingManager.java


    private static final String TAG = "AdbDebuggingManager";
    private static final boolean DEBUG = false; //打印默认为false,调试可以修改为true,查看相关日志

    public void setAdbEnabled(boolean enabled, byte transportType) {
        if (transportType == AdbTransportType.USB) {
            mHandler.sendEmptyMessage(enabled ? AdbDebuggingHandler.MESSAGE_ADB_ENABLED
                                              : AdbDebuggingHandler.MESSAGE_ADB_DISABLED);
        } else if (transportType == AdbTransportType.WIFI) {
            mHandler.sendEmptyMessage(enabled ? AdbDebuggingHandler.MSG_ADBDWIFI_ENABLE
                                              : AdbDebuggingHandler.MSG_ADBDWIFI_DISABLE);
        }
    }

       public void handleMessage(Message msg) {
            initKeyStore();

            switch (msg.what) {
                case MESSAGE_ADB_ENABLED:
...

                case MESSAGE_ADB_DISABLED:
...
                case MSG_ADBDWIFI_ENABLE: { //(1)收到打开wifiadb 消息
                    if (mAdbWifiEnabled) { //(2) 已经打开的情况不用继续打开
                        break;
                    }
                    //not to check network state ,change by      liwenzhi
                    // (3) 注释未打开wifi和未连接wifi情况下,调用关闭adb wifi 的代码
                    /** AdbConnectionInfo currentInfo = getCurrentWifiApInfo(); //这里是校验当前网络是否连接wifi
                    if (currentInfo == null) {
                        Settings.Global.putInt(mContentResolver,
                                Settings.Global.ADB_WIFI_ENABLED, 0); //(4)未连接wifi,关闭wifi adb的情况
                        break;
                    }

                    if (!verifyWifiNetwork(currentInfo.getBSSID(),
                            currentInfo.getSSID())) { //这里是校验,当前连接的网络是否是上次连接的那个网络
                        // This means that the network is not in the list of trusted networks.
                        // We'll give user a prompt on whether to allow wireless debugging on
                        // the current wifi network.
                        Settings.Global.putInt(mContentResolver,
                                Settings.Global.ADB_WIFI_ENABLED, 0); //(5)切换到其他网络,关闭wifi adb的情况
                        break;
                    }

                    //这个是保存当前连接的wifi,就是为了区分下次连接的wifi是否和上次一致
                    setAdbConnectionInfo(currentInfo); **/
                    //no listener network change for disable adb_wifi,by      liwenzhi
                     // (6) 注释网络变化的监听,只要网络变化都会导致关闭wifi adb
                    /** IntentFilter intentFilter =
                            new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION);
                    intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
                    mContext.registerReceiver(mBroadcastReceiver, intentFilter); **/

                    SystemProperties.set(WIFI_PERSISTENT_CONFIG_PROPERTY, "1");
                    mConnectionPortPoller =
                            new AdbDebuggingManager.AdbConnectionPortPoller(mPortListener);
                    mConnectionPortPoller.start();

                    startAdbDebuggingThread(); //这线程主要是为了一直监听获取outputStream和inputStream数据,这里好像会记录每一个连接的adb设备,
                    mAdbWifiEnabled = true;

                    if (DEBUG) Slog.i(TAG, "adb start wireless adb");
                    break;

                case MSG_ADBDWIFI_DISABLE: //关闭wifi adb
                    if (!mAdbWifiEnabled) { //已经关闭的情况不用管
                        break;
                    }
                    mAdbWifiEnabled = false;
                    setAdbConnectionInfo(null); //设置保存的连接wifi信息为null
                    mContext.unregisterReceiver(mBroadcastReceiver); //如果上面监听注释了,这里也要注释

                    if (mThread != null) {
                        mThread.sendResponse(MSG_DISABLE_ADBDWIFI);
                    }
                    onAdbdWifiServerDisconnected(-1); //这里主要是发送通知和发送广播
                    stopAdbDebuggingThread(); //停止相关线程
                    break;

            }
        }

    // (7)自定义handler内部类,内部包含接收网络变化自定义广播接收器
  class AdbDebuggingHandler extends Handler {
        private NotificationManager mNotificationManager;
        private boolean mAdbNotificationShown;

        private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                // We only care about when wifi is disabled, and when there is a wifi network
                // change.
                if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) { // (8)监听wifi开关变化
                    int state = intent.getIntExtra(
                            WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_DISABLED);
                    if (state == WifiManager.WIFI_STATE_DISABLED) { // (9)wifi关闭的情况,关闭wifi adb
                        Slog.i(TAG, "Wifi disabled. Disabling adbwifi.");
                        Settings.Global.putInt(mContentResolver,
                                Settings.Global.ADB_WIFI_ENABLED, 0);
                    }
                } else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) { // (10)监听wifi连接情况变化
                    // We only care about wifi type connections
                    NetworkInfo networkInfo = (NetworkInfo) intent.getParcelableExtra(
                            WifiManager.EXTRA_NETWORK_INFO);
                    if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                        // Check for network disconnect
                        if (!networkInfo.isConnected()) { // (10)发生连接变化后,如果不是连接状态,就关闭wifi adb
                            Slog.i(TAG, "Network disconnected. Disabling adbwifi.");
                            Settings.Global.putInt(mContentResolver,
                                    Settings.Global.ADB_WIFI_ENABLED, 0);
                            return;
                        }

                        WifiManager wifiManager =
                                (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
                        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                        if (wifiInfo == null || wifiInfo.getNetworkId() == -1) { // (11)发生连接变化后,如果信息状态不对,就关闭wifi adb
                            Slog.i(TAG, "Not connected to any wireless network."
                                    + " Not enabling adbwifi.");
                            Settings.Global.putInt(mContentResolver,
                                    Settings.Global.ADB_WIFI_ENABLED, 0);
                        }

                        // Check for network change
                        String bssid = wifiInfo.getBSSID();
                        if (bssid == null || bssid.isEmpty()) { // (12)发生连接变化后,如果信息ssid不对,就关闭wifi adb
                            Slog.e(TAG, "Unable to get the wifi ap's BSSID. Disabling adbwifi.");
                            Settings.Global.putInt(mContentResolver,
                                    Settings.Global.ADB_WIFI_ENABLED, 0);
                        }
                        synchronized (mAdbConnectionInfo) {
                            if (!bssid.equals(mAdbConnectionInfo.getBSSID())) { // (12)发生连接变化后,如果和上次连接的wifi不同,就关闭wifi adb
                                Slog.i(TAG, "Detected wifi network change. Disabling adbwifi.");
                                Settings.Global.putInt(mContentResolver,
                                        Settings.Global.ADB_WIFI_ENABLED, 0);
                            }
                        }
                    }
                }
            }
        };

From the above code, you can see that in many cases, ADB_WIFI_ENABLED is set to turn off.
If there are no mandatory security requirements, these can be turned off. The current test has not found any problems.

The Settings.Global.ADB_WIFI_ENABLED property code is set here, so where will it be processed?
Looking further up, I found that AdbService monitors changes in this attribute,
and then calls the setAdbEnabled method, which sets the prop attribute.
Then it calls AdbDebuggingManager.setAdbEnabled to perform related thread startup, attribute judgment, network judgment and other operations!

3. Upper-layer adb related processes

System prop attribute: persist.adb.tls_server.enable 0/1
Settings.GLOBAL attribute: adb_wifi_enabled 0/1

(1) The situation when the system has just started

1、adb_wifi.cpp 优先启动,start_wifi_enabled_observer方法进入等待 prop 属性改变状态
2、SystemServer 启动 AdbService
3、AdbService.systemReady方法判断prop属性,执行是否开启adb,设置Settings.GLOBAL值
4、因为 AdbService 已经监听了 Settings.GLOBAL值的变化,所以会调用监听到变化,先设置prop方法,再执行setAdbEnabled 方法
5、接着调用 AdbDebuggingManager.setAdbEnabled ,进行很相关线程启动,属性判断,网络判断等操作!
6、如果网络未开启或者未连接等情况,AdbDebuggingManager 会设置 Settings.GLOBAL.ADB_WIFI_ENABLED 为0
7、AdbService 监听监听到Settings属性变化,又调用了 setAdbEnabled 关闭wifi adb

Therefore, if AdbDebuggingManager is not blocked, the code to determine the network situation will appear:

设置属性 persist.adb.tls_server.enable = 1,系统启动后,发现还是为0;
设置属性 Settings.GLOBAL.ADB_WIFI_ENABLED =1 ,系统启动后,发现还是为0;
adb或者代码中,手动设置 ADB_WIFI_ENABLED =1 属性后,等下看,属性还是 0 ;

(2) The case of directly setting the Settings attribute

1、AdbService 监听监听到Settings属性变化,设置prop属性值,调用了 setAdbEnabled 方法
2、接着调用 AdbDebuggingManager.setAdbEnabled ,进行很相关线程启动,属性判断,网络判断等操作!
3、未屏蔽网络变化的情况,可能会导致 设置 Settings.GLOBAL.ADB_WIFI_ENABLED 为0
AdbService 监听监听到Settings属性变化,重新设置prop属性值

Note that even if the network judgment code is not blocked here, if Settings.GLOBAL.ADB_WIFI_ENABLED = 1 is set,
the system will first call to enable adb, but then immediately close adb. You can see the relevant logs in adb_wifi.cpp.

(3) The case of directly setting the prop attribute

1、adb_wifi.cpp 的 start_wifi_enabled_observer 方法接收到prop属性变化
2、如果是开启就创建对应Server,随机生成端口号,设置端口号prop属性 service.adb.tls.port 
3、如果关闭就删除Server,并且端口号属性设置空字符串

It can be seen that setting the prop attribute does not go through the java code;
if the network-related judgment is not blocked and the prop is set to enable wifi adb, then restarting the device or network changes will cause wifi adb to be closed.
The port number is set in the system when adb is turned on. Just modifying the prop port number attribute has no effect.

The default process may be:

1、系统默认启动,未设置prop属性,未屏蔽网络判断
SystemServer --> AdbService.systemReady --> 读取prop --> 设置GLOBAL值 --> 
onChange --> setAdbEnabled -- > 设置prop属性( -->adb_wifi.cpp 会收到属性变化) 并且调用 AdbDebuggingManager.setAdbEnabled(false)

2、系统启动:只设置prop属性,未屏蔽网络判断 
SystemServer --> AdbService.systemReady --> 读取prop --> 设置GLOBAL值 --> 
onChange --> setAdbEnabled -- > 设置prop属性( -->adb_wifi.cpp 会收到属性变化) 并且调用 AdbDebuggingManager.setAdbEnabled(true)
-- > 判断到网络未连接 --> 设置GLOBAL值 -->
onChange --> setAdbEnabled -- > 设置prop属性( -->adb_wifi.cpp 会收到属性变化) 并且调用 AdbDebuggingManager.setAdbEnabled(false)

3、系统启动:设置prop属性,并且屏蔽网络判断
SystemServer --> AdbService.systemReady --> 读取prop --> 设置GLOBAL值 --> 
onChange --> setAdbEnabled -- >设置prop属性( -->adb_wifi.cpp 会收到属性变化) 并且调用 AdbDebuggingManager.setAdbEnabled(true)

4、后期设置 Settings.GLOBAL.ADB_WIFI_ENABLED =1 属性值,未屏蔽网络判断

Settings.GLOBAL.ADB_WIFI_ENABLED = 1 -->
AdbService.onChange --> setAdbEnabled -- > 设置prop属性( -->adb_wifi.cpp 会收到属性变化) 并且调用 AdbDebuggingManager.setAdbEnabled(true)
-- > 判断到网络未连接 --> 设置GLOBAL值 -->
onChange --> setAdbEnabled -- > 设置prop属性( -->adb_wifi.cpp 会收到属性变化) 并且调用 AdbDebuggingManager.setAdbEnabled(false)



5、后期设置 Settings.GLOBAL.ADB_WIFI_ENABLED =1 属性值,屏蔽网络判断
Settings.GLOBAL.ADB_WIFI_ENABLED = 1 --> 
AdbService.onChange --> setAdbEnabled -- >设置prop属性( -->adb_wifi.cpp 会收到属性变化) 并且调用 AdbDebuggingManager.setAdbEnabled(true)


6、后期设置 persist.adb.tls_server.enable =1 属性值, 不管屏不屏蔽网络变化,都是一样的

设置prop属性( -->adb_wifi.cpp 会收到属性变化) --> 启动adb ,设置端口号

但是最后一种情况,如果没有屏蔽网络变化,就会很不稳定,因为网络变化,就会关闭 wifi adb。


7、未屏蔽网络判断,网络改变情况
AdbDebuggingManager 广播接收到网络变化 --> 设置GLOBAL值 -->
AdbService.onChange --> setAdbEnabled -- > 设置prop属性( -->adb_wifi.cpp 会收到属性变化) 并且调用 AdbDebuggingManager.setAdbEnabled(false)


There is also a simple conclusion here:

设置默认 Settings.GLOBAL.ADB_WIFI_ENABLED 的值是没用的,系统流程会给他重新设置 0

如果未屏蔽网络变化的代码,即使设置了prop属性和GLOBAL属性也是没有意义的,系统流程也是会给它设置成 0

5. If the network adb connection still cannot be analyzed after modification

(1) View adb default value

getprop persist.adb.tls_server.enable  //查看prop属性
settings get global adb_wifi_enabled  //查看Settings 属性

setprop persist.adb.tls_server.enable 1 //设置prop属性
settings put global adb_wifi_enabled  1 //设置Settings 属性

If adb_wifi_enabled is set to 1 and the query immediately changes to 0, then the monitoring and judgment of network changes have not been removed.

(2) Check whether the network judgment code that restricts adb has been removed

This depends on the code in AdbDebuggingManager.

1、查看是否去除了网络变化的监听
WifiManager.WIFI_STATE_CHANGED_ACTION
WifiManager.NETWORK_STATE_CHANGED_ACTION
2、查看是否对 getCurrentWifiApInfo() 的判断进行了屏蔽
3、查看是否去除了执行:Settings.Global.putInt(mContentResolver,Settings.Global.ADB_WIFI_ENABLED, 0);

(3) Check whether the underlying execution of adb_wifi.cpp adb switch processing is printed.

//开启wifi 的日志
LOG(INFO) << "adb wifi started on port " << sTlsServer->port();

//停止wifi adb的日志
LOG(INFO) << "adb wifi stopped";

So check the keyword "adb wifi" to see the log.

logcat | grep "adb wifi"

The log is as follows:

console:/ # logcat | grep "adb wifi"                                           
09-05 21:09:31.755   668   712 I adbd    : adb wifi stopped //关闭日志
09-05 21:09:48.326   668   712 I adbd    : adb wifi started on port 5555 //开启日志,并且会打印 端口号

(4) There is still a problem. We can only add logs to the code process.

1、打开 AdbService 和 AdbDebuggingManager 的日志开关
2、AdbService.systemReady()添加打印默认属性
Slog.d(TAG, "lwz systemReady= " + WIFI_PERSISTENT_CONFIG_PROPERTY + " = " + SystemProperties.get(WIFI_PERSISTENT_CONFIG_PROPERTY, "0"));
Slog.d(TAG, "lwz systemReady mIsAdbWifiEnabled= " + mIsAdbWifiEnabled); 
3、AdbSettingsObserver.onChange 打印Settings属性变化后的值
Slog.d(TAG, "lwz onChange shouldEnable = " + shouldEnable);

AdbDebuggingManager can also add logs depending on the situation, but the situation of turning off wifi adb is basically printed.

By printing multiple keywords with the logcat command, you can see the cause of the problem.


logcat | grep -E "AdbService|AdbDebuggingManager|adb wifi|XXX" //XXX 是自己定义的


(5)device offline

After connecting, it prompts that the device is offline. Then it may be that the adb version of the computer does not match the Android device. Generally, it is enough to change to a higher version of adb. You may also need to change to a lower version of adb.

6. Others

1. adb related attributes

(1) prop属性:persist.adb.tls_server.enable

After the system starts, AdbService will judge this property to determine whether to subsequently open adb.

(2) prop attribute: service.adb.tls.port

This property is set by adb_wifi.cpp when adb is enabled. It will let you know its port number later.
So setting this property value is meaningless.
In adb_wifi.cpp, initialize TlsServer and set the fixed port 5555, then this attribute will always be 5555. If it is not set, it will be a random 5-digit number.

(3) Settings attribute: Settings.Global.ADB_WIFI_ENABLED The specific name is "adb_wifi_enabled"

At the same time, AdbService monitors changes in the Global attribute, associates it with AdbDebuggingManager, and sets adb enablement.

Query and set commands:


//查询属性;
setttings get global adb_wifi_enabled
//设置属性 0/1:
setttings put global adb_wifi_enabled 1

This attribute is a value set by the upper layer of the system. It was originally mainly used to record the on/off status of adb wifi.
Because Android13 will determine whether the current wifi is trusted, setting this attribute after switching wifi is invalid.

However, if you modify the above countermeasures to remove network restrictions and directly set the Global attribute, adb will be turned on and off normally.

If the network restriction countermeasure is not removed, you will find that adb_wifi_enabled cannot be set to 1,
because AdbDebuggingManager will still determine the network condition when it is turned on, and will be set to 0 if there is no network.

2. The relationship between AdbService.java, AdbDebuggingManager.java and adb_wifi.cpp

(1) adb_wifi is a service started by the underlying init/cpp

The logs inside are run earlier than SystemServer.
There are related logs for opening and closing adb normally.

(2) AdbService startup timing

AdbService is a service started when SystemServer executes startOtherServices.

AdbService extends IAdbManager.Stub //For specific exposed interfaces, see IAdbManager

(3) AdbDebuggingManager is a class that manages adbDebug.

This class is instantiated in AdbService, which actually separates the specific execution code.

Many situations where adb wifi cannot be accessed are rejected by AdbDebuggingManager, and the Global attribute and Prop attribute are reset to 0.

AdbDebuggingManager is not an ordinary SDK class exposed to other classes. It is just an ordinary class, and it listens to network change broadcasts and can receive network changes.

After adapting the above code to remove network restrictions, as far as the application is concerned, it is most appropriate to use Settings.Global.ADB_WIFI_ENABLED to control and or the current network adb status.
Although using the prop attribute can also take effect, the system uses Settings to determine whether the value of Settings.Global.ADB_WIFI_ENABLED is 1, and the
adb status display will be out of sync.

The user version analyzed by others cannot use adb (the version is not the latest, and the writing is more complicated):
https://blog.csdn.net/kc58236582/article/details/53502177/

Guess you like

Origin blog.csdn.net/wenzhi20102321/article/details/132735323