本文转载自:http://blog.csdn.net/u010223349/article/details/41120255

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

最新文章

  1. IOS开发基础知识--碎片51
  2. 【MySQL】mysql 1449 : The user specified as a definer (&#39;root&#39;@&#39;%&#39;) does not exist
  3. 简单回顾NPOI导入导出excel文件
  4. c++ redis-client
  5. Linux shell相关
  6. 仿QQ列表左滑删除
  7. C# Winform 脱离 Framework (二)
  8. Eclipse卸载插件
  9. 【redis】05Redis的常用命令及高级应用
  10. jeewx的使用_02 解析微信服务器post过来的数据
  11. POJ3279 Fliptile 枚举+简单搜索
  12. epoll讲解
  13. 最简便的MySql数据库备份方法
  14. webservice发送数据,取数据的方式
  15. 文字排版--字号、颜色(font-size, color)
  16. 分析NTFS文件系统得到特定文件的内容
  17. Hdu 5073 Galaxy 精度问题
  18. MySQL定时逻辑备份
  19. 使用docker 解决一个小问题,你也可能用的到
  20. 【Visual Studio】VS发布应用未能创建默认证书的问题解决方法

热门文章

  1. 洛谷P2365 任务安排 [解法一]
  2. Linux crontab 定时任务Demo
  3. msp430项目编程57
  4. C语言函数调用及栈帧结构
  5. T3137 栈练习1 codevs
  6. 【JSON注解】注解@JsonIgnoreProperties和@JsonIgnore的另一个使用情况
  7. ASP.NET Core 依赖注入(构造函数注入,属性注入等)
  8. 若菜acmer感觉自己智商全然被碾压了QAQ~~
  9. Angularjs: call other scope which in iframe
  10. Deleting array elements in JavaScript - delete vs splice