分享

Android ADB实现解析

 icecity1306 2014-11-25
  ADB是Android系统提供的调试工具,整个ADB工具由三部分组成:adb client、adb service、adb daemon。
 1、ADB client
       提供HOST端运行的命令
 2、ADB service
       HOST端上的一个后台进程
 3、ADB daemom
       DEVICE端(真实的机器或者模拟器)的守护进程
       ADB代码位于/system/core/adb目录下,通过查看Android.mk,可以知道,该目录下的代码生成了两个MODULE,分别是adb和adbd,  adb client和adb service都是由adb这个可执行文件实现, adb daemon由adbd实现。adb和adbd的一些源代码文件是用同一个的,编译时通过LOCAL_CFLAGS的参数ADB_HOST来区分,这种你中有我我中有你的关系,对于初次接触的朋友们,多少增加了些困扰。理清了ADB几部分的关系,以及源代码的结构,对ADB的认识已经有一个飞越了。
        一、main函数
        adb.c的main函数是adb client、adb service、adb daemon的共同入口,
  1. int main(int argc, char **argv)  
  2. {  
  3. #if ADB_HOST  
  4.     adb_sysdeps_init();  
  5.     adb_trace_init();  
  6.     D("Handling commandline()\n");  
  7.     return adb_commandline(argc - 1, argv + 1);  
  8. #else  
  9.     /* If adbd runs inside the emulator this will enable adb tracing via 
  10.      * adb-debug qemud service in the emulator. */  
  11.     adb_qemu_trace_init();  
  12.     if((argc > 1) && (!strcmp(argv[1],"recovery"))) {  
  13.         adb_device_banner = "recovery";  
  14.         recovery_mode = 1;  
  15.     }  
  16.   
  17.     start_device_log();  
  18.     D("Handling main()\n");  
  19.     return adb_main(0, DEFAULT_ADB_PORT);  
  20. #endif  
  21. }  
        根据Android.mk中传的ADB_HOST确定编译的是adb client\adb service, 或者是adb daemon, ADB_HOST为1时编译adb client\adb service的代码, ADB_HOST为0时编译adb daemon的代码。
        以上代码中,adb client\adb service端代码如,
  1. adb_sysdeps_init();  
  2. adb_trace_init();  
  3. D("Handling commandline()\n");  
  4. return adb_commandline(argc - 1, argv + 1);  

       1、adb_sysdeps_init():  adb client\adb service适用于linux和windows版本,所以代码中有平台相关的部分。

       2、adb_trace_init():   初始化log输出配置,初始化后在HOST上设置ADB_TRACE这个环境变量,可以控制client\service端的log输出等级,

             配置为1或者all的话,将输出所有 的log。

       3、adb_commandline():  关键函数,代码如下。

  1. int adb_commandline(int argc, char **argv)  
  2. {  
  3.     char buf[4096];  
  4.     int no_daemon = 0;  
  5.     int is_daemon = 0;  
  6.     int is_server = 0;  
  7.     int persist = 0;  
  8.     int r;  
  9.     int quote;  
  10.     transport_type ttype = kTransportAny;  
  11.     char* serial = NULL;  
  12.     char* server_port_str = NULL;  
  13.   
  14.         /* If defined, this should be an absolute path to 
  15.          * the directory containing all of the various system images 
  16.          * for a particular product.  If not defined, and the adb 
  17.          * command requires this information, then the user must 
  18.          * specify the path using "-p". 
  19.          */  
  20.     gProductOutPath = getenv("ANDROID_PRODUCT_OUT");  
  21.     if (gProductOutPath == NULL || gProductOutPath[0] == '\0') {  
  22.         gProductOutPath = NULL;  
  23.     }  
  24.     // TODO: also try TARGET_PRODUCT/TARGET_DEVICE as a hint  
  25.   
  26.     serial = getenv("ANDROID_SERIAL");  
  27.   
  28.     /* Validate and assign the server port */  
  29.     server_port_str = getenv("ANDROID_ADB_SERVER_PORT");  
  30.     int server_port = DEFAULT_ADB_PORT;  
  31.     if (server_port_str && strlen(server_port_str) > 0) {  
  32.         server_port = (int) strtol(server_port_str, NULL, 0);  
  33.         if (server_port <= 0 || server_port > 65535) {  
  34.             fprintf(stderr,  
  35.                     "adb: Env var ANDROID_ADB_SERVER_PORT must be a positive number less than 65535. Got \"%s\"\n",  
  36.                     server_port_str);  
  37.             return usage();  
  38.         }  
  39.     }  
  40.   
  41.     /* modifiers and flags */  
  42.     while(argc > 0) {  
  43.         if(!strcmp(argv[0],"server")) {  
  44.             is_server = 1;  
  45.         } else if(!strcmp(argv[0],"nodaemon")) {  
  46.             no_daemon = 1;  
  47.         } else if (!strcmp(argv[0], "fork-server")) {  
  48.             /* this is a special flag used only when the ADB client launches the ADB Server */  
  49.             is_daemon = 1;  
  50.         } else if(!strcmp(argv[0],"persist")) {  
  51.             persist = 1;  
  52.         } else if(!strncmp(argv[0], "-p", 2)) {  
  53.             const char *product = NULL;  
  54.             if (argv[0][2] == '\0') {  
  55.                 if (argc < 2) return usage();  
  56.                 product = argv[1];  
  57.                 argc--;  
  58.                 argv++;  
  59.             } else {  
  60.                 product = argv[0] + 2;  
  61.             }  
  62.             gProductOutPath = find_product_out_path(product);  
  63.             if (gProductOutPath == NULL) {  
  64.                 fprintf(stderr, "adb: could not resolve \"-p %s\"\n",  
  65.                         product);  
  66.                 return usage();  
  67.             }  
  68.         } else if (argv[0][0]=='-' && argv[0][1]=='s') {  
  69.             if (isdigit(argv[0][2])) {  
  70.                 serial = argv[0] + 2;  
  71.             } else {  
  72.                 if(argc < 2 || argv[0][2] != '\0') return usage();  
  73.                 serial = argv[1];  
  74.                 argc--;  
  75.                 argv++;  
  76.             }  
  77.         } else if (!strcmp(argv[0],"-d")) {  
  78.             ttype = kTransportUsb;  
  79.         } else if (!strcmp(argv[0],"-e")) {  
  80.             ttype = kTransportLocal;  
  81.         } else if (!strcmp(argv[0],"-a")) {  
  82.             gListenAll = 1;  
  83.         } else if(!strncmp(argv[0], "-H", 2)) {  
  84.             const char *hostname = NULL;  
  85.             if (argv[0][2] == '\0') {  
  86.                 if (argc < 2) return usage();  
  87.                 hostname = argv[1];  
  88.                 argc--;  
  89.                 argv++;  
  90.             } else {  
  91.                 hostname = argv[0] + 2;  
  92.             }  
  93.             adb_set_tcp_name(hostname);  
  94.   
  95.         } else if(!strncmp(argv[0], "-P", 2)) {  
  96.             if (argv[0][2] == '\0') {  
  97.                 if (argc < 2) return usage();  
  98.                 server_port_str = argv[1];  
  99.                 argc--;  
  100.                 argv++;  
  101.             } else {  
  102.                 server_port_str = argv[0] + 2;  
  103.             }  
  104.             if (strlen(server_port_str) > 0) {  
  105.                 server_port = (int) strtol(server_port_str, NULL, 0);  
  106.                 if (server_port <= 0 || server_port > 65535) {  
  107.                     fprintf(stderr,  
  108.                             "adb: port number must be a positive number less than 65536. Got \"%s\"\n",  
  109.                             server_port_str);  
  110.                     return usage();  
  111.                 }  
  112.             } else {  
  113.                 fprintf(stderr,  
  114.                 "adb: port number must be a positive number less than 65536. Got empty string.\n");  
  115.                 return usage();  
  116.             }  
  117.         } else {  
  118.                 /* out of recognized modifiers and flags */  
  119.             break;  
  120.         }  
  121.         argc--;  
  122.         argv++;  
  123.     }  
  124.   
  125.     adb_set_transport(ttype, serial);  
  126.     adb_set_tcp_specifics(server_port);  
  127.   
  128.     if (is_server) {  
  129.         if (no_daemon || is_daemon) {  
  130.             r = adb_main(is_daemon, server_port);  
  131.         } else {  
  132.             r = launch_server(server_port);  
  133.         }  
  134.         if(r) {  
  135.             fprintf(stderr,"* could not start server *\n");  
  136.         }  
  137.         return r;  
  138.     }  
  139.   
  140. top:  
  141.     if(argc == 0) {  
  142.         return usage();  
  143.     }  
  144.   
  145.     /* adb_connect() commands */  
  146.   
  147.     if(!strcmp(argv[0], "devices")) {  
  148.         char *tmp;  
  149.         char *listopt;  
  150.         if (argc < 2)  
  151.             listopt = "";  
  152.         else if (argc == 2 && !strcmp(argv[1], "-l"))  
  153.             listopt = argv[1];  
  154.         else {  
  155.             fprintf(stderr, "Usage: adb devices [-l]\n");  
  156.             return 1;  
  157.         }  
  158.         snprintf(buf, sizeof buf, "host:%s%s", argv[0], listopt);  
  159.         tmp = adb_query(buf);  
  160.         if(tmp) {  
  161.             printf("List of devices attached \n");  
  162.             printf("%s\n", tmp);  
  163.             return 0;  
  164.         } else {  
  165.             return 1;  
  166.         }  
  167.     }  
  168.   
  169.     if(!strcmp(argv[0], "connect")) {  
  170.         char *tmp;  
  171.         if (argc != 2) {  
  172.             fprintf(stderr, "Usage: adb connect <host>[:<port>]\n");  
  173.             return 1;  
  174.         }  
  175.         snprintf(buf, sizeof buf, "host:connect:%s", argv[1]);  
  176.         tmp = adb_query(buf);  
  177.         if(tmp) {  
  178.             printf("%s\n", tmp);  
  179.             return 0;  
  180.         } else {  
  181.             return 1;  
  182.         }  
  183.     }  
  184.   
  185.     if(!strcmp(argv[0], "disconnect")) {  
  186.         char *tmp;  
  187.         if (argc > 2) {  
  188.             fprintf(stderr, "Usage: adb disconnect [<host>[:<port>]]\n");  
  189.             return 1;  
  190.         }  
  191.         if (argc == 2) {  
  192.             snprintf(buf, sizeof buf, "host:disconnect:%s", argv[1]);  
  193.         } else {  
  194.             snprintf(buf, sizeof buf, "host:disconnect:");  
  195.         }  
  196.         tmp = adb_query(buf);  
  197.         if(tmp) {  
  198.             printf("%s\n", tmp);  
  199.             return 0;  
  200.         } else {  
  201.             return 1;  
  202.         }  
  203.     }  
  204.   
  205.     if (!strcmp(argv[0], "emu")) {  
  206.         return adb_send_emulator_command(argc, argv);  
  207.     }  
  208.   
  209.     if(!strcmp(argv[0], "shell") || !strcmp(argv[0], "hell")) {  
  210.         int r;  
  211.         int fd;  
  212.   
  213.         char h = (argv[0][0] == 'h');  
  214.   
  215.         if (h) {  
  216.             printf("\x1b[41;33m");  
  217.             fflush(stdout);  
  218.         }  
  219.   
  220.         if(argc < 2) {  
  221.             D("starting interactive shell\n");  
  222.             r = interactive_shell();  
  223.             if (h) {  
  224.                 printf("\x1b[0m");  
  225.                 fflush(stdout);  
  226.             }  
  227.             return r;  
  228.         }  
  229.   
  230.         snprintf(buf, sizeof buf, "shell:%s", argv[1]);  
  231.         argc -= 2;  
  232.         argv += 2;  
  233.         while(argc-- > 0) {  
  234.             strcat(buf, " ");  
  235.   
  236.             /* quote empty strings and strings with spaces */  
  237.             quote = (**argv == 0 || strchr(*argv, ' '));  
  238.             if (quote)  
  239.                 strcat(buf, "\"");  
  240.             strcat(buf, *argv++);  
  241.             if (quote)  
  242.                 strcat(buf, "\"");  
  243.         }  
  244.   
  245.         for(;;) {  
  246.             D("interactive shell loop. buff=%s\n", buf);  
  247.             fd = adb_connect(buf);  
  248.             if(fd >= 0) {  
  249.                 D("about to read_and_dump(fd=%d)\n", fd);  
  250.                 read_and_dump(fd);  
  251.                 D("read_and_dump() done.\n");  
  252.                 adb_close(fd);  
  253.                 r = 0;  
  254.             } else {  
  255.                 fprintf(stderr,"error: %s\n", adb_error());  
  256.                 r = -1;  
  257.             }  
  258.   
  259.             if(persist) {  
  260.                 fprintf(stderr,"\n- waiting for device -\n");  
  261.                 adb_sleep_ms(1000);  
  262.                 do_cmd(ttype, serial, "wait-for-device", 0);  
  263.             } else {  
  264.                 if (h) {  
  265.                     printf("\x1b[0m");  
  266.                     fflush(stdout);  
  267.                 }  
  268.                 D("interactive shell loop. return r=%d\n", r);  
  269.                 return r;  
  270.             }  
  271.         }  
  272.     }  
  273.   
  274.     if(!strcmp(argv[0], "kill-server")) {  
  275.         int fd;  
  276.         fd = _adb_connect("host:kill");  
  277.         if(fd == -1) {  
  278.             fprintf(stderr,"* server not running *\n");  
  279.             return 1;  
  280.         }  
  281.         return 0;  
  282.     }  
  283.   
  284.     if(!strcmp(argv[0], "sideload")) {  
  285.         if(argc != 2) return usage();  
  286.         if(adb_download("sideload", argv[1], 1)) {  
  287.             return 1;  
  288.         } else {  
  289.             return 0;  
  290.         }  
  291.     }  
  292.   
  293.     if(!strcmp(argv[0], "remount") || !strcmp(argv[0], "reboot")  
  294.             || !strcmp(argv[0], "reboot-bootloader")  
  295.             || !strcmp(argv[0], "tcpip") || !strcmp(argv[0], "usb")  
  296.             || !strcmp(argv[0], "root")) {  
  297.         char command[100];  
  298.         if (!strcmp(argv[0], "reboot-bootloader"))  
  299.             snprintf(command, sizeof(command), "reboot:bootloader");  
  300.         else if (argc > 1)  
  301.             snprintf(command, sizeof(command), "%s:%s", argv[0], argv[1]);  
  302.         else  
  303.             snprintf(command, sizeof(command), "%s:", argv[0]);  
  304.         int fd = adb_connect(command);  
  305.         if(fd >= 0) {  
  306.             read_and_dump(fd);  
  307.             adb_close(fd);  
  308.             return 0;  
  309.         }  
  310.         fprintf(stderr,"error: %s\n", adb_error());  
  311.         return 1;  
  312.     }  
  313.   
  314.     if(!strcmp(argv[0], "bugreport")) {  
  315.         if (argc != 1) return usage();  
  316.         do_cmd(ttype, serial, "shell", "bugreport", 0);  
  317.         return 0;  
  318.     }  
  319.   
  320.     /* adb_command() wrapper commands */  
  321.   
  322.     if(!strncmp(argv[0], "wait-for-", strlen("wait-for-"))) {  
  323.         char* service = argv[0];  
  324.         if (!strncmp(service, "wait-for-device", strlen("wait-for-device"))) {  
  325.             if (ttype == kTransportUsb) {  
  326.                 service = "wait-for-usb";  
  327.             } else if (ttype == kTransportLocal) {  
  328.                 service = "wait-for-local";  
  329.             } else {  
  330.                 service = "wait-for-any";  
  331.             }  
  332.         }  
  333.   
  334.         format_host_command(buf, sizeof buf, service, ttype, serial);  
  335.   
  336.         if (adb_command(buf)) {  
  337.             D("failure: %s *\n",adb_error());  
  338.             fprintf(stderr,"error: %s\n", adb_error());  
  339.             return 1;  
  340.         }  
  341.   
  342.         /* Allow a command to be run after wait-for-device, 
  343.             * e.g. 'adb wait-for-device shell'. 
  344.             */  
  345.         if(argc > 1) {  
  346.             argc--;  
  347.             argv++;  
  348.             goto top;  
  349.         }  
  350.         return 0;  
  351.     }  
  352.   
  353.     if(!strcmp(argv[0], "forward")) {  
  354.         char host_prefix[64];  
  355.         char remove = 0;  
  356.         char remove_all = 0;  
  357.         char list = 0;  
  358.         char no_rebind = 0;  
  359.   
  360.         // Parse options here.  
  361.         while (argc > 1 && argv[1][0] == '-') {  
  362.             if (!strcmp(argv[1], "--list"))  
  363.                 list = 1;  
  364.             else if (!strcmp(argv[1], "--remove"))  
  365.                 remove = 1;  
  366.             else if (!strcmp(argv[1], "--remove-all"))  
  367.                 remove_all = 1;  
  368.             else if (!strcmp(argv[1], "--no-rebind"))  
  369.                 no_rebind = 1;  
  370.             else {  
  371.                 return usage();  
  372.             }  
  373.             argc--;  
  374.             argv++;  
  375.         }  
  376.   
  377.         // Ensure we can only use one option at a time.  
  378.         if (list + remove + remove_all + no_rebind > 1) {  
  379.             return usage();  
  380.         }  
  381.   
  382.         // Determine the <host-prefix> for this command.  
  383.         if (serial) {  
  384.             snprintf(host_prefix, sizeof host_prefix, "host-serial:%s",  
  385.                     serial);  
  386.         } else if (ttype == kTransportUsb) {  
  387.             snprintf(host_prefix, sizeof host_prefix, "host-usb");  
  388.         } else if (ttype == kTransportLocal) {  
  389.             snprintf(host_prefix, sizeof host_prefix, "host-local");  
  390.         } else {  
  391.             snprintf(host_prefix, sizeof host_prefix, "host");  
  392.         }  
  393.   
  394.         // Implement forward --list  
  395.         if (list) {  
  396.             if (argc != 1)  
  397.                 return usage();  
  398.             snprintf(buf, sizeof buf, "%s:list-forward", host_prefix);  
  399.             char* forwards = adb_query(buf);  
  400.             if (forwards == NULL) {  
  401.                 fprintf(stderr, "error: %s\n", adb_error());  
  402.                 return 1;  
  403.             }  
  404.             printf("%s", forwards);  
  405.             free(forwards);  
  406.             return 0;  
  407.         }  
  408.   
  409.         // Implement forward --remove-all  
  410.         else if (remove_all) {  
  411.             if (argc != 1)  
  412.                 return usage();  
  413.             snprintf(buf, sizeof buf, "%s:killforward-all", host_prefix);  
  414.         }  
  415.   
  416.         // Implement forward --remove <local>  
  417.         else if (remove) {  
  418.             if (argc != 2)  
  419.                 return usage();  
  420.             snprintf(buf, sizeof buf, "%s:killforward:%s", host_prefix, argv[1]);  
  421.         }  
  422.         // Or implement one of:  
  423.         //    forward <local> <remote>  
  424.         //    forward --no-rebind <local> <remote>  
  425.         else  
  426.         {  
  427.           if (argc != 3)  
  428.             return usage();  
  429.           const char* command = no_rebind ? "forward:norebind:" : "forward";  
  430.           snprintf(buf, sizeof buf, "%s:%s:%s;%s", host_prefix, command, argv[1], argv[2]);  
  431.         }  
  432.   
  433.         if(adb_command(buf)) {  
  434.             fprintf(stderr,"error: %s\n", adb_error());  
  435.             return 1;  
  436.         }  
  437.         return 0;  
  438.     }  
  439.   
  440.     /* do_sync_*() commands */  
  441.   
  442.     if(!strcmp(argv[0], "ls")) {  
  443.         if(argc != 2) return usage();  
  444.         return do_sync_ls(argv[1]);  
  445.     }  
  446.   
  447.     if(!strcmp(argv[0], "push")) {  
  448.         if(argc != 3) return usage();  
  449.         return do_sync_push(argv[1], argv[2], 0 /* no verify APK */);  
  450.     }  
  451.   
  452.     if(!strcmp(argv[0], "pull")) {  
  453.         if (argc == 2) {  
  454.             return do_sync_pull(argv[1], ".");  
  455.         } else if (argc == 3) {  
  456.             return do_sync_pull(argv[1], argv[2]);  
  457.         } else {  
  458.             return usage();  
  459.         }  
  460.     }  
  461.   
  462.     if(!strcmp(argv[0], "install")) {  
  463.         if (argc < 2) return usage();  
  464.         return install_app(ttype, serial, argc, argv);  
  465.     }  
  466.   
  467.     if(!strcmp(argv[0], "uninstall")) {  
  468.         if (argc < 2) return usage();  
  469.         return uninstall_app(ttype, serial, argc, argv);  
  470.     }  
  471.   
  472.     if(!strcmp(argv[0], "sync")) {  
  473.         char *srcarg, *android_srcpath, *data_srcpath;  
  474.         int listonly = 0;  
  475.   
  476.         int ret;  
  477.         if(argc < 2) {  
  478.             /* No local path was specified. */  
  479.             srcarg = NULL;  
  480.         } else if (argc >= 2 && strcmp(argv[1], "-l") == 0) {  
  481.             listonly = 1;  
  482.             if (argc == 3) {  
  483.                 srcarg = argv[2];  
  484.             } else {  
  485.                 srcarg = NULL;  
  486.             }  
  487.         } else if(argc == 2) {  
  488.             /* A local path or "android"/"data" arg was specified. */  
  489.             srcarg = argv[1];  
  490.         } else {  
  491.             return usage();  
  492.         }  
  493.         ret = find_sync_dirs(srcarg, &android_srcpath, &data_srcpath);  
  494.         if(ret != 0) return usage();  
  495.   
  496.         if(android_srcpath != NULL)  
  497.             ret = do_sync_sync(android_srcpath, "/system", listonly);  
  498.         if(ret == 0 && data_srcpath != NULL)  
  499.             ret = do_sync_sync(data_srcpath, "/data", listonly);  
  500.   
  501.         free(android_srcpath);  
  502.         free(data_srcpath);  
  503.         return ret;  
  504.     }  
  505.   
  506.     /* passthrough commands */  
  507.   
  508.     if(!strcmp(argv[0],"get-state") ||  
  509.         !strcmp(argv[0],"get-serialno") ||  
  510.         !strcmp(argv[0],"get-devpath"))  
  511.     {  
  512.         char *tmp;  
  513.   
  514.         format_host_command(buf, sizeof buf, argv[0], ttype, serial);  
  515.         tmp = adb_query(buf);  
  516.         if(tmp) {  
  517.             printf("%s\n", tmp);  
  518.             return 0;  
  519.         } else {  
  520.             return 1;  
  521.         }  
  522.     }  
  523.   
  524.     /* other commands */  
  525.   
  526.     if(!strcmp(argv[0],"status-window")) {  
  527.         status_window(ttype, serial);  
  528.         return 0;  
  529.     }  
  530.   
  531.     if(!strcmp(argv[0],"logcat") || !strcmp(argv[0],"lolcat") || !strcmp(argv[0],"longcat")) {  
  532.         return logcat(ttype, serial, argc, argv);  
  533.     }  
  534.   
  535.     if(!strcmp(argv[0],"ppp")) {  
  536.         return ppp(argc, argv);  
  537.     }  
  538.   
  539.     if (!strcmp(argv[0], "start-server")) {  
  540.         return adb_connect("host:start-server");  
  541.     }  
  542.   
  543.     if (!strcmp(argv[0], "backup")) {  
  544.         return backup(argc, argv);  
  545.     }  
  546.   
  547.     if (!strcmp(argv[0], "restore")) {  
  548.         return restore(argc, argv);  
  549.     }  
  550.   
  551.     if (!strcmp(argv[0], "jdwp")) {  
  552.         int  fd = adb_connect("jdwp");  
  553.         if (fd >= 0) {  
  554.             read_and_dump(fd);  
  555.             adb_close(fd);  
  556.             return 0;  
  557.         } else {  
  558.             fprintf(stderr, "error: %s\n", adb_error());  
  559.             return -1;  
  560.         }  
  561.     }  
  562.   
  563.     /* "adb /?" is a common idiom under Windows */  
  564.     if(!strcmp(argv[0], "help") || !strcmp(argv[0], "/?")) {  
  565.         help();  
  566.         return 0;  
  567.     }  
  568.   
  569.     if(!strcmp(argv[0], "version")) {  
  570.         version(stdout);  
  571.         return 0;  
  572.     }  
  573.   
  574.     usage();  
  575.     return 1;  
  576. }  
   adb_commandline解析adb命令,如adb devices,  关于某个命令具体执行过程,后面专门针对某个命令进行解析。
 
   main()中, adbd端代码如下,
  1. /* If adbd runs inside the emulator this will enable adb tracing via 
  2.   * adb-debug qemud service in the emulator. */  
  3.  adb_qemu_trace_init();  
  4.  if((argc > 1) && (!strcmp(argv[1],"recovery"))) {  
  5.      adb_device_banner = "recovery";  
  6.      recovery_mode = 1;  
  7.  }  
  8.   
  9.  start_device_log();  
  10.  D("Handling main()\n");  
  11.  return adb_main(0, DEFAULT_ADB_PORT);                                
  1、adb_qemu_trace_init():  建立和模拟器中的adb-debug qemud service的连接。
  2、if((argc > 1) && (!strcmp(argv[1],"recovery"))) {
            adb_device_banner = "recovery";
            recovery_mode = 1;
        }
     启动adbd的时候,可以加参数, 例如,在recovery模式中init.rc文件中的adbd service是带recovery参数的,如果带
     recovery参数就设置这两个标志,但目前没有看到哪里用到了这两个标志。
  3、start_device_log(): 配置adb daemon的log输出, 前面说了adb client和service端的log输出可以通过ADB_TRACE这个环境
     变量来控制,adb daemon端的log可以通过persist.adb.trace_mask控制, start_device_log()中判persist.adb.trace_mask
     的值,如果有值,就会将log输出到/data/adb/目录下。
  4、adb_main():如下
  1. int adb_main(int is_daemon, int server_port)  
  2. {  
  3. #if !ADB_HOST  
  4.     int port;  
  5.     char value[PROPERTY_VALUE_MAX];  
  6.   
  7.     umask(000);  
  8. #endif  
  9.   
  10.     atexit(adb_cleanup);  
  11. #ifdef HAVE_WIN32_PROC  
  12.     SetConsoleCtrlHandler( ctrlc_handler, TRUE );  
  13. #elif defined(HAVE_FORKEXEC)  
  14.     // No SIGCHLD. Let the service subproc handle its children.  
  15.     signal(SIGPIPE, SIG_IGN);  
  16. #endif  
  17.   
  18.     init_transport_registration();  
  19.   
  20. #if ADB_HOST  
  21.     HOST = 1;  
  22.   
  23. #ifdef WORKAROUND_BUG6558362  
  24.     if(is_daemon) adb_set_affinity();  
  25. #endif  
  26.     usb_vendors_init();  
  27.     usb_init();  
  28.     local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);  
  29.     adb_auth_init();  
  30.   
  31.     char local_name[30];  
  32.     build_local_name(local_name, sizeof(local_name), server_port);  
  33.     if(install_listener(local_name, "*smartsocket*", NULL, 0)) {  
  34.         exit(1);  
  35.     }  
  36. #else  
  37.     property_get("ro.adb.secure", value, "0");  
  38.     auth_enabled = !strcmp(value, "1");  
  39.     if (auth_enabled)  
  40.         adb_auth_init();  
  41.   
  42.     // Our external storage path may be different than apps, since  
  43.     // we aren't able to bind mount after dropping root.  
  44.     const char* adb_external_storage = getenv("ADB_EXTERNAL_STORAGE");  
  45.     if (NULL != adb_external_storage) {  
  46.         setenv("EXTERNAL_STORAGE", adb_external_storage, 1);  
  47.     } else {  
  48.         D("Warning: ADB_EXTERNAL_STORAGE is not set.  Leaving EXTERNAL_STORAGE"  
  49.           " unchanged.\n");  
  50.     }  
  51.   
  52.     /* don't listen on a port (default 5037) if running in secure mode */  
  53.     /* don't run as root if we are running in secure mode */  
  54.     if (should_drop_privileges()) {  
  55.         drop_capabilities_bounding_set_if_needed();  
  56.   
  57.         /* add extra groups: 
  58.         ** AID_ADB to access the USB driver 
  59.         ** AID_LOG to read system logs (adb logcat) 
  60.         ** AID_INPUT to diagnose input issues (getevent) 
  61.         ** AID_INET to diagnose network issues (netcfg, ping) 
  62.         ** AID_GRAPHICS to access the frame buffer 
  63.         ** AID_NET_BT and AID_NET_BT_ADMIN to diagnose bluetooth (hcidump) 
  64.         ** AID_SDCARD_R to allow reading from the SD card 
  65.         ** AID_SDCARD_RW to allow writing to the SD card 
  66.         ** AID_MOUNT to allow unmounting the SD card before rebooting 
  67.         ** AID_NET_BW_STATS to read out qtaguid statistics 
  68.         */  
  69.         gid_t groups[] = { AID_ADB, AID_LOG, AID_INPUT, AID_INET, AID_GRAPHICS,  
  70.                            AID_NET_BT, AID_NET_BT_ADMIN, AID_SDCARD_R, AID_SDCARD_RW,  
  71.                            AID_MOUNT, AID_NET_BW_STATS };  
  72.         if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {  
  73.             exit(1);  
  74.         }  
  75.   
  76.         /* then switch user and group to "shell" */  
  77.         if (setgid(AID_SHELL) != 0) {  
  78.             exit(1);  
  79.         }  
  80.         if (setuid(AID_SHELL) != 0) {  
  81.             exit(1);  
  82.         }  
  83.   
  84.         D("Local port disabled\n");  
  85.     } else {  
  86.         char local_name[30];  
  87.         build_local_name(local_name, sizeof(local_name), server_port);  
  88.         if(install_listener(local_name, "*smartsocket*", NULL, 0)) {  
  89.             exit(1);  
  90.         }  
  91.     }  
  92.   
  93.     int usb = 0;  
  94.     if (access(USB_ADB_PATH, F_OK) == 0 || access(USB_FFS_ADB_EP0, F_OK) == 0) {  
  95.         // listen on USB  
  96.         usb_init();  
  97.         usb = 1;  
  98.     }  
  99.   
  100.     // If one of these properties is set, also listen on that port  
  101.     // If one of the properties isn't set and we couldn't listen on usb,  
  102.     // listen on the default port.  
  103.     property_get("service.adb.tcp.port", value, "");  
  104.     if (!value[0]) {  
  105.         property_get("persist.adb.tcp.port", value, "");  
  106.     }  
  107.     if (sscanf(value, "%d", &port) == 1 && port > 0) {  
  108.         printf("using port=%d\n", port);  
  109.         // listen on TCP port specified by service.adb.tcp.port property  
  110.         local_init(port);  
  111.     } else if (!usb) {  
  112.         // listen on default port  
  113.         local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);  
  114.     }  
  115.   
  116.     D("adb_main(): pre init_jdwp()\n");  
  117.     init_jdwp();  
  118.     D("adb_main(): post init_jdwp()\n");  
  119. #endif  
  120.   
  121.     if (is_daemon)  
  122.     {  
  123.         // inform our parent that we are up and running.  
  124. #ifdef HAVE_WIN32_PROC  
  125.         DWORD  count;  
  126.         WriteFile( GetStdHandle( STD_OUTPUT_HANDLE ), "OK\n", 3, &count, NULL );  
  127. #elif defined(HAVE_FORKEXEC)  
  128.         fprintf(stderr, "OK\n");  
  129. #endif  
  130.         start_logging();  
  131.     }  
  132.     D("Event loop starting\n");  
  133.   
  134.     fdevent_loop();  
  135.   
  136.     usb_cleanup();  
  137.   
  138.     return 0;  
  139. }  

        二、adb_main()函数
        上一节中已经附上adb_main()函数代码, 其中,adb service端的代码如下,
  1. usb_vendors_init();  
  2. usb_init();  
  3. local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);  
  4. adb_auth_init();  
  5.   
  6. char local_name[30];  
  7. build_local_name(local_name, sizeof(local_name), server_port);  
  8. if(install_listener(local_name, "*smartsocket*", NULL, 0)) {  
  9.     exit(1);  
  10. }  
  11.    
  12.  .........  
  13.   
  14.     start_logging();  
  15. }  
  16. D("Event loop starting\n");  
  17.   
  18. fdevent_loop();  
  19.   
  20. usb_cleanup();  

    1、usb_vendors_init(): 每个设备产家都会定义一个vender id来标识自己的usb 设备,ADB service端只会连接已知的vender
     id,这个函数的作用就是初始化一个vender id的数组,初始化后这个数组中将包含adb代码中内建的一些产家的id以及HOST
     端的android配置文件中定义的id。
  2、usb_init(): 创建一个线程,线程处理函数device_poll_thread, 进入一个循环,每隔1s执行一次find_usb_device和 
     kick_disconnected_devices,find_usb_device搜索所有的usb设备,判断vender id是否在上面初始化的列表中,如果是,则
     将该usb设备注册到一个handle_list中。调用register_usb_transport基于这个fd 构造一个atransport类型的对象,再基于
     这atransport对象调用register_transport构造一个tmsg类型的对象。
     最后,将这个tmsg对象写到transport_registration_send个fd,  将触发相应的socket监控。kick_disconnected_devices
     判断adb设备是否还正常,不正常的话从handle_list中支掉。
  3、local_init(): 创建一个线程,尝试连接HOST端5555-5585端口,如果连接成功,则返回一个fd, register_socket_transport
     基于这个fd 构造一个atransport类型的对象,再基于这个atransport对象调用register_transport构造一个tmsg类型的
     对象。后,将这个tmsg对象写 transport_registration_send这个fd,  将触发相应的socket监控。
  4、install_listener():  监听"tcp:5037" ,  adb client与adb service之间通讯用这个端口。
  5、start_logging():  将stdin重写向到/dev/null, 将stdout、stderr重定向/tmp/adb.log, 然后输出"adb starting"到
     stderr。
  6、fdevent_loop():  前面通过fdinstall()注册了几个fde, 这里就通过一个无限循环epoll相应的fd,  有相应的事件则调用
     fdinstall时注册的处理函数。
  7、usb_cleanup(): usb相关的清理工作,对应linux平台的实现目前为空。

     其中,adb daemon端代码如下, 
  1. property_get("ro.adb.secure", value, "0");  
  2. auth_enabled = !strcmp(value, "1");  
  3. if (auth_enabled)  
  4.     adb_auth_init();  
  5.   
  6. // Our external storage path may be different than apps, since  
  7. // we aren't able to bind mount after dropping root.  
  8. const char* adb_external_storage = getenv("ADB_EXTERNAL_STORAGE");  
  9. if (NULL != adb_external_storage) {  
  10.     setenv("EXTERNAL_STORAGE", adb_external_storage, 1);  
  11. } else {  
  12.     D("Warning: ADB_EXTERNAL_STORAGE is not set.  Leaving EXTERNAL_STORAGE"  
  13.       " unchanged.\n");  
  14. }  
  15.   
  16. /* don't listen on a port (default 5037) if running in secure mode */  
  17. /* don't run as root if we are running in secure mode */  
  18. if (should_drop_privileges()) {  
  19.     drop_capabilities_bounding_set_if_needed();  
  20.   
  21.     /* add extra groups: 
  22.     ** AID_ADB to access the USB driver 
  23.     ** AID_LOG to read system logs (adb logcat) 
  24.     ** AID_INPUT to diagnose input issues (getevent) 
  25.     ** AID_INET to diagnose network issues (netcfg, ping) 
  26.     ** AID_GRAPHICS to access the frame buffer 
  27.     ** AID_NET_BT and AID_NET_BT_ADMIN to diagnose bluetooth (hcidump) 
  28.     ** AID_SDCARD_R to allow reading from the SD card 
  29.     ** AID_SDCARD_RW to allow writing to the SD card 
  30.     ** AID_MOUNT to allow unmounting the SD card before rebooting 
  31.     ** AID_NET_BW_STATS to read out qtaguid statistics 
  32.     */  
  33.     gid_t groups[] = { AID_ADB, AID_LOG, AID_INPUT, AID_INET, AID_GRAPHICS,  
  34.                        AID_NET_BT, AID_NET_BT_ADMIN, AID_SDCARD_R, AID_SDCARD_RW,  
  35.                        AID_MOUNT, AID_NET_BW_STATS };  
  36.     if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {  
  37.         exit(1);  
  38.     }  
  39.   
  40.     /* then switch user and group to "shell" */  
  41.     if (setgid(AID_SHELL) != 0) {  
  42.         exit(1);  
  43.     }  
  44.     if (setuid(AID_SHELL) != 0) {  
  45.         exit(1);  
  46.     }  
  47.   
  48.     D("Local port disabled\n");  
  49. } else {  
  50.     char local_name[30];  
  51.     build_local_name(local_name, sizeof(local_name), server_port);  
  52.     if(install_listener(local_name, "*smartsocket*", NULL, 0)) {  
  53.         exit(1);  
  54.     }  
  55. }  
  56.   
  57. int usb = 0;  
  58. if (access(USB_ADB_PATH, F_OK) == 0 || access(USB_FFS_ADB_EP0, F_OK) == 0) {  
  59.     // listen on USB  
  60.     usb_init();  
  61.     usb = 1;  
  62. }  
  63.   
  64. // If one of these properties is set, also listen on that port  
  65. // If one of the properties isn't set and we couldn't listen on usb,  
  66. // listen on the default port.  
  67. property_get("service.adb.tcp.port", value, "");  
  68. if (!value[0]) {  
  69.     property_get("persist.adb.tcp.port", value, "");  
  70. }  
  71. if (sscanf(value, "%d", &port) == 1 && port > 0) {  
  72.     printf("using port=%d\n", port);  
  73.     // listen on TCP port specified by service.adb.tcp.port property  
  74.     local_init(port);  
  75. } else if (!usb) {  
  76.     // listen on default port  
  77.     local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);  
  78. }  
  79.   
  80. D("adb_main(): pre init_jdwp()\n");  
  81. init_jdwp();  
  82. D("adb_main(): post init_jdwp()\n");  

   1、local_init():  adb daemon的这个函数与adb service端的有所不同,adb service端的local_init只在adb service初始化
      的时候扫描一下5555-5585端口,而adb daemon端的local_init会在线程中运行一个无限循环,不停尝试连接5555端口或者由
      service.adb.tcp.port\persist.adb.tcp.port设置的端口,因为作为daemon随时要准备为他人服务。  
   2、init_jdwp():  jdwp全称为java debug wire protocol, 每dalvik VM都会创建一个jdwp, 可以建立在adb或者tcp基础上,
      与DDMS或debugger进行通信, 这个函数就是初始化了监听socket描述符"\0jdwp-control"动作。
   
   adb daemon其它部分的代码与adb service都比较类似,可能参考adb service部分。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多