adb overview

ADB是android debug bridge的缩写,负责计算机与Android设备的几乎所有通信和协作,可以认为是连接两者的桥梁。

在Android开发和恶意代码分析中,经常用到它的install、uninstall、push、pull、logcat、shell等命令。它的用法可以参考SDK的文档:

http://developer.android.com/guide/developing/tools/adb.html

正因为其独特的桥梁作用,有必要详细了解其工作过程。幸运的是,我们可以获得其源码,它位于Android源码树的platform/system/core/adb/目录下,可以通过下面的git命令下载:

git clone git://android.git.kernel.org/platform/system/core.git

如果要编译,还是推荐下载完整的Android源码,并参考上一篇文章所述编译方法。

ADB由两个物理文件组成:

  1. adb或adb.exe,运行于PC端,包括Linux、Windows、Mac OS等系统之中,通常是x86架构上(下文中,ADB指整个模块,而adb单独指这一部分);
  2. adbd,运行于Android设备的底层Linux之中,ARMv5架构上。

为了保持两者代码一致,Google并未将其做源码文件级别的分离,而是统一为一份代码,通过传入Android.mk的$(BUILD_SIMULATOR)变量是否为真,来构建不同的文件。对源码而言,由ADB_HOST宏是否预定义为真来区分。

而adb本身还需要估计多个操作系统平台,这由传入Android.mk的$(HOST_OS)来控制,它的有效取值包括linux、darwin、freebsd和windows。不同平台的主要差异是USB的控制方法和文件路径。

除了物理文件上的区别,adb本身还会在PC中产生两类不同的进程。

其中一个进程将由命令行“adb fork-server server”产生(给用户的调用接口是adb start-server),这个守护进程长期运行于后台,没有控制台界面,称之为adb server(adb服务端),其主要工作有两部分:

  1. 管理PC中的Android模拟器,以及通过USB线连接到PC的Android设备,负责维持运行于其中的adbd进程与自身的数据通道;
  2. 实现PC与设备/模拟器之间的数据拷贝。

adb的另一类进程是提供给用户的命令行工具,对用户暴露了上述install、push、shell等接口,与用户交互,称之为adb client(adb客户端)。其主要工作是解析这些命令的参数,做必要预处理,然后转移为指令或数据,发送给adb服务端。adb服务端再将指令数据转发到模拟器或设备中,由adbd处理,产生结果,再通过adb服务端接收回来。

事实上,当adb客户端运行时,会自动检查当前系统中是否存在adb服务端,如果不存在,则通过“adb fork-server server”启动一个服务端,然后再与之建立连接。这样,用户就不需要关心这些概念和差异了。

因此,从运行实体上看,ADB由三部分构成:

  1. adbd
  2. adb server
  3. adb client

Google还引入了一个adb service(adb服务,注意与adb服务端的区别)的概念,指adbd提供的功能。这就构成了ADB的四个模块。在源码的OVERVIEW.txt文件中对它们的关系进行了描述。而protocol.txt描述了各模块之间通信协作的协议格式。



-------------------------------------------------------------------------------------------------------------------------------------

Overview.txt

Implementation notes regarding ADB.


I. General Overview:
The Android Debug Bridge (ADB) is used to:
- keep track of all Android devices and emulators instances connected to or running on a given host developer machine
- implement various control commands (e.g. "adb shell", "adb pull", etc..) for the benefit of clients (command-line users, or helper programs like DDMS). These commands are what is called a 'service' in ADB.
As a whole, everything works through the following components:
  1. The ADB server
    This is a background process that runs on the host machine. Its purpose if to sense the USB ports to know when devices are attached/removed,
    as well as when emulator instances start/stop.

    It thus maintains a list of "connected devices" and assigns a 'state' to each one of them: OFFLINE, BOOTLOADER, RECOVERY or ONLINE (more on this below).
    The ADB server is really one giant multiplexing loop whose purpose is to orchestrate the exchange of data (packets, really) between clients, services and devices.
  2. The ADB daemon (adbd)
    The 'adbd' program runs as a background process within an Android device or emulated system. Its purpose is to connect to the ADB server
    (through USB for devices, through TCP for emulators) and provide a few services for clients that run on the host.

    The ADB server considers that a device is ONLINE when it has successfully connected to the adbd program within it. Otherwise, the device is OFFLINE, meaning that the ADB server detected a new device/emulator, but could not connect to the adbd daemon.
    the BOOTLOADER and RECOVERY states correspond to alternate states of devices when they are in the bootloader or recovery mode.
  3. The ADB command-line client
    The 'adb' command-line program is used to run adb commands from a shell or a script. It first tries to locate the ADB server on the host machine, and will start one automatically if none is found.
    then, the client sends its service requests to the ADB server. It doesn't need to know.
    Currently, a single 'adb' binary is used for both the server and client. this makes distribution and starting the server easier.
  4. Services
    There are essentially two kinds of services that a client can talk to.
    Host Services: these services run within the ADB Server and thus do not need to communicate with a device at all. A typical example is "adb devices" which is used to return the list of currently known devices and their state. They are a few couple other services though.
    Local Services: these services either run within the adbd daemon, or are started by
      it on the device. The ADB server is used to multiplex streams between the client and the service running in adbd. In this case

      its role is to initiate the connection, then of being a pass-through for the data.


II. Protocol details:
  1. Client <-> Server protocol:
    This details the protocol used between ADB clients and the ADB server itself. The ADB server listens on TCP:localhost:5037.
    A client sends a request using the following format:
        1. A 4-byte hexadecimal string giving the length of the payload
        2. Followed by the payload itself.
    For example, to query the ADB server for its internal version number, the client will do the following:
        1. Connect to tcp:localhost:5037
        2. Send the string "000Chost:version" to the corresponding socket
    The 'host:' prefix is used to indicate that the request is addressed to the server itself (we will talk about other kinds of requests later). The content length is encoded in ASCII for easier debugging.
    The server should answer a request with one of the following:
        1. For success, the 4-byte "OKAY" string
        2. For failure, the 4-byte "FAIL" string, followed by a 4-byte hex length, followed by a string giving the reason
           for failure.
        3. As a special exception, for 'host:version', a 4-byte hex string corresponding to the server's internal version number
    Note that the connection is still alive after an OKAY, which allows the client to make other requests. But in certain cases, an OKAY will even change the state of the connection. 
    For example, the case of the 'host:transport:<serialnumber>' request, where '<serialnumber>' is used to identify a given device/emulator; after the "OKAY" answer, all further requests made by the client will go directly to the corresponding adbd daemon.
    The file SERVICES.TXT lists all services currently implemented by ADB.
  2. Transports:
    An ADB transport models a connection between the ADB server and one device or emulator. There are currently two kinds of transports:
       - USB transports, for physical devices through USB
       - Local transports, for emulators running on the host, connected to the server through TCP
    In theory, it should be possible to write a local transport that proxies a connection between an ADB server and a device/emulator connected to/ running on another machine. This hasn't been done yet though.
    Each transport can carry one or more multiplexed streams between clients and the device/emulator they point to. The ADB server must handle unexpected transport disconnections (e.g. when a device is physically unplugged) properly. 

----------------------------------------------------------------------------------------------------------------------------------------------------

SERVICES.txt

This file tries to document all requests a client can make to the ADB server of an adbd daemon. See the OVERVIEW.TXT document to understand what's going on here.
HOST SERVICES:
host:version Ask the ADB server for its internal version number.
    As a special exception, the server will respond with a 4-byte
    hex string corresponding to its internal version number, without
    any OKAY or FAIL.
host:kill Ask the ADB server to quit immediately. This is used when the
    ADB client detects that an obsolete server is running after an upgrade.
host:devices Ask to return the list of available Android devices and their
    state. After the OKAY, this is followed by a 4-byte hex len,
    and a string that will be dumped as-is by the client, then
    the connection is closed
host:track-devices This is a variant of host:devices which doesn't close the
    connection. Instead, a new device list description is sent
    each time a device is added/removed or the state of a given
    device changes (hex4 + content). This allows tools like DDMS
    to track the state of connected devices in real-time without
    polling the server repeatedly.
host:emulator:<port> This is a special query that is sent to the ADB server when a
    new emulator starts up. <port> is a decimal number corresponding
    to the emulator's ADB control port, i.e. the TCP port that the emulator will forward automatically to the adbd daemon running
    in the emulator system.
    This mechanism allows the ADB server to know when new emulator instances start.
host:transport:<serial-number> Ask to switch the connection to the device/emulator identified by
    <serial-number>. After the OKAY response, every client request will be sent directly to the adbd daemon running on the device.
    (Used to implement the -s option)
host:transport-usb Ask to switch the connection to one device connected through USB
    to the host machine. This will fail if there are more than one such devices. (Used to implement the -d convenience option)
host:transport-local Ask to switch the connection to one emulator connected through TCP.
    This will fail if there is more than one such emulator instance running. (Used to implement the -e convenience option)
host:transport-any Another host:transport variant. Ask to switch the connection to
    either the device or emulator connect to/running on the host.
    Will fail if there is more than one such device/emulator available. (Used when neither -s, -d or -e are provided)
host-serial:<serial-number>:<request> This is a special form of query, where the 'host-serial:<serial-number>:' prefix can be used to indicate that the client is asking the ADB server for information related to a specific device. <request> can be in one
    of the format described below.
host-usb:<request> A variant of host-serial used to target the single USB device connected to the host. This will fail if there is none or more than one.
host-local:<request> A variant of host-serial used to target the single emulator instance running on the host. This will fail if there is none or more than one.
host:<request> When asking for information related to a device, 'host:' can also be interpreted as 'any single device or emulator connected to/running on the host'.
<host-prefix>:get-product XXX
<host-prefix>:get-serialno Returns the serial number of the corresponding device/emulator.
    Note that emulator serial numbers are of the form "emulator-5554"
<host-prefix>:get-state Returns the state of a given device as a string.
<host-prefix>:forward:<local>;<remote> Asks the ADB server to forward local connections from <local>
    to the <remote> address on a given device.
    There, <host-prefix> can be one of the
    host-serial/host-usb/host-local/host prefixes as described previously and indicates which device/emulator to target.
    the format of <local> is one of:
        tcp:<port>      -> TCP connection on localhost:<port>
        local:<path>    -> Unix local domain socket on <path>
    the format of <remote> is one of:
        tcp:<port>      -> TCP localhost:<port> on device
        local:<path>    -> Unix local domain socket on device
        jdwp:<pid>      -> JDWP thread on VM process <pid>
    or even any one of the local services described below.
LOCAL SERVICES:
All the queries below assumed that you already switched the transport to a real device, or that you have used a query prefix as described above.
shell:command arg1 arg2 ... Run 'command arg1 arg2 ...' in a shell on the device, and return
    its output and error streams. Note that arguments must be separated by spaces. If an argument contains a space, it must be quoted with double-quotes. Arguments cannot contain double quotes or things
    will go very wrong.
    Note that this is the non-interactive version of "adb shell"
shell: Start an interactive shell session on the device. Redirect
    stdin/stdout/stderr as appropriate. Note that the ADB server uses this to implement "adb shell", but will also cook the input before sending it to the device (see interactive_shell() in commandline.c)
remount: Ask adbd to remount the device's filesystem in read-write mode,
    instead of read-only. This is usually necessary before performing
    an "adb sync" or "adb push" request.
    This request may not succeed on certain builds which do not allow that.
dev:<path> Opens a device file and connects the client directly to it for
    read/write purposes. Useful for debugging, but may require special privileges and thus may not run on all devices. <path> is a full
    path from the root of the filesystem.
tcp:<port> Tries to connect to tcp port <port> on localhost.
tcp:<port>:<server-name> Tries to connect to tcp port <port> on machine <server-name> from
    the device. This can be useful to debug some networking/proxy
    issues that can only be revealed on the device itself.
local:<path> Tries to connect to a Unix domain socket <path> on the device
localreserved:<path> localabstract:<path> localfilesystem:<path> Variants of local:<path> that are used to access other Android
    socket namespaces.
log:<name> Opens one of the system logs (/dev/log/<name>) and allows the client
    to read them directly. Used to implement 'adb logcat'. The stream will be read-only for the client.
framebuffer: This service is used to send snapshots of the framebuffer to a client. It requires sufficient privileges but works as follow:
      After the OKAY, the service sends 16-byte binary structure containing the following fields (little-endian format):
            depth:   uint32_t:    framebuffer depth
            size:    uint32_t:    framebuffer size in bytes
            width:   uint32_t:    framebuffer width in pixels
            height:  uint32_t:    framebuffer height in pixels
      With the current implementation, depth is always 16, and
      size is always width*height*2
      Then, each time the client wants a snapshot, it should send
      one byte through the channel, which will trigger the service
      to send it 'size' bytes of framebuffer data.
      If the adbd daemon doesn't have sufficient privileges to open
      the framebuffer device, the connection is simply closed immediately.
dns:<server-name> This service is an exception because it only runs within the ADB server. It is used to implement USB networking, i.e. to provide a network connection to the device through the host machine (note: this is the exact opposite of network tethering).
    It is used to perform a gethostbyname(<address>) on the host and return the corresponding IP address as a 4-byte string.
recover:<size> This service is used to upload a recovery image to the device. <size> must be a number corresponding to the size of the file. The service works by:
       - creating a file named /tmp/update
       - reading 'size' bytes from the client and writing them to /tmp/update
       - when everything is read successfully, create a file named /tmp/update.start
    This service can only work when the device is in recovery mode. Otherwise, the /tmp directory doesn't exist and the connection will be closed immediately.
jdwp:<pid> Connects to the JDWP thread running in the VM of process <pid>.
track-jdwp This is used to send the list of JDWP pids periodically to the client. The format of the returned data is the following:
        <hex4>:    the length of all content as a 4-char hexadecimal string <content>: a series of ASCII lines of the following format: <pid> "\n"
    This service is used by DDMS to know which debuggable processes are running on the device/emulator.
    Note that there is no single-shot service to retrieve the list only once.
sync: This starts the file synchronisation service, used to implement "adb push" and "adb pull". Since this service is pretty complex, it will be detailed in a companion document named SYNC.TXT 

----------------------------------------------------------------------------------------------------------------------------------------------------


本文尝试列举客户端能够发送给ADB服务器的所有请求。关于adb客户端、adb服务器、adbd守护进程、adb服务的概念,以及这些组件如何相互配合完成ADB工作的细节,请参考之前发的文章《Android Debug Bridge 技术实现》。
  
  ==============================
  主机服务
  ==============================
  
  host:version
    请求ADB服务器的内部版本号。作为一个特殊的例外,服务器将用4字节的十六进制字符串回应,返回服务器内部版本号,回应中没有“OKAY”和“FAIL”。
  
  host:kill
    请求ADB服务器立即退出。用于ADB客户端检测到在升级之后有废弃的ADB服务器仍在运行的情况。
  
  host:devices
    请求返回可用的Android设备及其状态的列表。在“OKAY”之后是4个字节的长度定义,然后是指定长度的表明当前设备状况的字符串,返回之后连接关闭。
  
  host:track-devices
    “host:devices”的一个变种,它不关闭连接;相反,每次添加或移除设备或者指定设备的状态发生变化,一个新的设备列表描述被发送。这就使得像DDMS这样的工具能够实时跟踪连接设备的状态,而不用重复轮训服务器。
  
  host:emulator:<port>
    这是一个特殊的请求,当启动一个新的模拟器时,该请求被发送到ADB服务器。<port>是一个十进制数字代表模拟器的ADB协议端口号,比如:模拟器将自动转发到adbd守护进程的TCP端口号。这个机制使得ADB服务器能够知道新的模拟器实例启动。
  
  host:transport:<serial-number>
    请求切换连接到<serial-number>指示的设备或模拟器。接到“OKAY”回应之后,所有的客户端请求将被直接发送给运行在指定设备上的adbd守护进程。(用来实现-s)
  
  host:transport-usb
    请求切换连接到通过USB连接到主机的设备上。如果存在多个这样的设备,请求将失败。(用来实现-d)
  
  host:transport-local
    请求切换连接到通过TCP连接的模拟器。如果有多个这样的模拟器实例在运行,请求将失败。(用来实现-e)
  
  host:transport-any
    另一个“host:transport”变种。请求切换连接到已连接的设备或正在运行的模拟器。如果可用的设备或模拟器多于一个,请求将失败。(用在-s、-d、-e都不被提供时)
  
  host-serial:<serial-number>:<request>
    这是一个特殊形式的请求,前缀“host-serial:<serial-number>:”表明客户端正在请求ADB服务器获得指定设备的信息。<request>可以是下述格式的一种。
  
  host-usb:<request>
    host-serial的一个变种,用于将连接到主机的唯一USB设备作为目标。如果没有这样的设备或有多个这样的设备,请求将失败。
  
  host-local:<request>
    host-serial的一个变种,用于将运行在主机上唯一的模拟器实例作为目标。如果没有这样的模拟器或有多个这样的模拟器,请求将失败。
  
  host:<request>
    当请求设备相关的信息时,“host:”也能被解释为“任何连接到主机的唯一设备或运行在主机上的唯一模拟器”。
  
  <host-prefix>:get-product
    暂无解释。
  
  <host-prefix>:get-serialno
    返回对应设备或模拟器的序列号。注意模拟器序列号是“emulator-5544”的形式。
  
  <host-prefix>:get-state
    返回指定设备的状态字符串。
  
  <host-prefix>:forward:<local>;<remote>
    请求ADB服务器将本地连接从<local>转移到指定设备上的<remote>地址。
    这里的<host-prefix>可以是上面描述的host-serial、host-usb、host-local、host的任意一个,它表明目标是哪个设备或模拟器。
    <local>的格式有以下几种:
      tcp:<port>      -> 在localhost:<port>上的TCP连接
      local:<path>    -> 在<path>上的Unix本地域套接字(Unix domain socket)
    <remote>的格式有以下几种:
      tcp:<port>      -> 在设备上localhost:<port>的TCP连接
      local:<path>    -> 在设备上的Unix本地域套接字
      jdwp:<pid>      -> 在虚拟机进程<pid>中的JDWP线程
    或者下面所描述的本地服务的任何一种。
  
  
  ==============================
  本地服务
  ==============================
  
下面所有的请求都假设你已经切换传输到实际的设备,或者你使用上面所描述的请求前缀。
  
  shell:command arg1 arg2 ...
    在设备的shell中运行“command arg1 arg2 ...”,返回输出流及错误流。注意命令参数必须用空格分隔。如果一个参数包含空格,应该对它使用双引号。参数不能包含双引号和其他会导致错误的符号。
    这是“adb shell”的非交互版本。
  
  shell:
    在设备上启动一个交互的shell会话。恰当的重定向标准输入、标准输出和标准错误输出。ADB服务器使用这个服务来实现“adb shell”,但是在输入被发送到设备之前,ADB服务器也会对输入做加工。(参考commandline.c中的interactive_shell()函数)
  
  remount:
    请求adbd守护进程重新挂载设备的文件系统到读/写模式下,而不是只读模式。在执行“adb sync”或者“adb push”之前,通常都需要这个服务。
    在不允许该操作的特定的系统中,这个请求可能不成功。
  
  dev:<path>
    打开一个设备文件,直接将客户端连接到这个文件去执行读写。该服务对于调试除错很有用,但是需要特殊的权限,不能在所有的设备上运行。<path>是从文件系统根目录开始的全路径。
  
  tcp:<port>
    尝试连接到loclhost的tcp端口<port>上。
  
  tcp:<port>:<server-name>
    尝试从设备连接到<server-name>所指定机器的tcp端口<port>上。这个服务对调试只能在设备上显示的网络或代理问题很有用。
  
  local:<path>
    尝试连接到设备上的Unix域套接字<path>。
  
  localreserved:<path>
  localabstract:<path>
  localfilesystem:<path>
    几个local:<path>的变种,用来访问其他Android套接字命名空间。
  
  log:<name>
    打开一个系统日志(/dev/log/<name>),允许客户端直接读取。用来实现“adb logcat”。数据流对客户端是只读的。
  
  framebuffer:
    这个服务用来向客户端发送framebuffer的快照。它需要足够的权限,工作原理如下:
    在“OKAY”之后,服务发送包含下列字段的16字节的二进制结构(低位优先格式):
    depth:   uint32_t:    framebuffer深度
    size:    uint32_t:    framebuffer大小(单位:字节)
    width:   uint32_t:    framebuffer宽度(单位:像素)
    height:  uint32_t:    framebuffer高度(单位:像素)
    在当前的实现中,framebuffer深度总是16,大小总是:宽度*高度*2。
    每当客户端想要一个快照时,它应该通过通道发送一个字节,触发服务将framebuffer数据按framebuffer大小指定的字节数发送给它。
    如果adbd守护进程没有足够的权限打开framebuffer设备,那么连接会立即关闭。
  
  dns:<server-name>
    这个服务是个例外,因为它仅仅运行在ADB服务器中。它被用来实现USB联网,比如:通过主机为设备提供一个网络连接。
    它用来在主机上执行gethostbyname(<address>),IP地址以4个字节的字符串返回。
  
  recover:<size>
    这个服务上传一个recovery影像到设备中。<size>必须与recovery影像文件大小一样。工作原理如下:
    - 创建一个命名为/tmp/update的文件;
    - 从客户端读取<size>大小的字节数,将它们写入到/tmp/update;
    - 当影像文件成功读取之后,创建一个命名为/tmp/update.start的文件。
    只有当设备处于recovery模式时,这个服务才能工作。此外,如果/tmp目录不存在,连接会立即关闭。
  
  jdwp:<pid>
    连接到运行在虚拟机进程<pid>中的JDWP线程。
  
  track-jdwp
    用于周期性的向客户端发送JDWP pids列表。返回数据格式如下:
    <hex4>:        4个字符的十六进制字符串指定所有内容的长度
    <content>:   一连串的格式为<pid> "/n"的ASCII行
    DDMS使用这个服务知道设备或模拟器上正在运行哪些可以调试的进程。
    注意没有仅获取一次列表的单步服务。
  
  sync:
    这个请求启动文件系统同步服务,用来实现“adb push”和“adb pull”。因为这个服务相当复杂,需要专门的文章来解释说明,如果有朋友感兴趣,我们以后专门讨论。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值