Android init源代码分析(2)init.rc解析
init.rc init.usb.rc init.trace.rc init.{hardware}.rc init.environ.rc init.zygote32.rc这些文件可能分布于如下目录中
- system/core/rootdir
- device/{vendor}/{hardware}/
# Copyright (C) 2012 The Android Open Source Project # # IMPORTANT: Do not create world writable files or directories. # This is a common source of Android security bugs. # import /init.environ.rc import /init.usb.rc import /init.${ro.hardware}.rc import /init.${ro.zygote}.rc import /init.trace.rc on early-init start ueventd on init sysclktz 0 loglevel 3 mkdir /system mkdir /data 0771 system system write /proc/sys/kernel/panic_on_oops 1 # Load properties from /system/ + /factory after fs mount. on load_all_props_action load_all_props on post-fs # once everything is setup, no need to modify / mount rootfs rootfs / ro remount on boot # basic network init ifup lo class_start core class_start main on property:vold.decrypt=trigger_reset_main class_reset main service ueventd /sbin/ueventd class core critical on property:ro.debuggable=1 start console service debuggerd /system/bin/debuggerd class main service bootanim /system/bin/bootanimation class main user graphics group graphics disabled oneshot
为了行文方便,下文提及init.rc,通常泛指Android启动脚本。
on <trigger> <command> <command> <command>
grep -h "^on" --include="*.rc" -r .
可以当前init启动脚本所含有的trigger,如下。
on early-init on init on property:sys.boot_from_charger_mode=1 on load_all_props_action on firmware_mounts_complete on late-init on post-fs on post-fs-data on boot on nonencrypted on property:sys.init_log_level=* on charger on property:vold.decrypt=trigger_reset_main on property:vold.decrypt=trigger_load_persist_props on property:vold.decrypt=trigger_post_fs_data on property:vold.decrypt=trigger_restart_min_framework on property:vold.decrypt=trigger_restart_framework on property:vold.decrypt=trigger_shutdown_framework on property:sys.powerctl=* on property:sys.sysctl.extra_free_kbytes=* on property:sys.sysctl.tcp_def_init_rwnd=* on property:ro.debuggable=1 on property:ro.kernel.qemu=1 on boot on post-fs-data on property:sys.usb.config=none on property:sys.usb.config=adb on property:sys.usb.config=accessory on property:sys.usb.config=accessory,adb on property:sys.usb.config=audio_source on property:sys.usb.config=audio_source,adb on property:sys.usb.config=accessory,audio_source on property:sys.usb.config=accessory,audio_source,adb on property:persist.sys.usb.config=*
service-exited-<name>
command的格式如下
command-name <parament1> [parament2...]
说明:readme.txt中虽然有大部分commands的介绍,但并不完整。init.rc中所有commands都在keywords.h中定义,可使用如下命令提取。
目前Android4.4支持的Commands如下:
chdir <direcotory> 改变工作目录 chroot <directory> 改变当前进程的root目录 class_start <serviceclass> 如果serviceclass内所有services尚未启动,则启动它 class_stop <serviceclass> 停止serviceclass内所有services class_reset <serviceclass> 重启serviceclass内所有services domainname <name> 设置domain名称 enable <servicename> exec <path> [ <argument> ]* fork后执行path所执行的程序,该语句会阻塞直到path指定的程序执行完毕。 export <name> <value> 设置全局环境变量,将会被该命令后所启动的进程继承。 hostname <name> 设置主机名 ifup <interface> 启动interface所指定的网络接口 insmod <path> 安装path所指定的内核模块 mkdir <path> [mode] [owner] [group] 创建path制定的目录,并根据可选的mode、owner、group设定参数。如果未指定可选参数,则创建的文件夹权限将会设置为0755,而owner与group都为root mount_all mount <type> <device> <dir> [ <mountoption] * powerctl restart <service> restorecon restorecon_recursive rm <path> 删除path指定的文件 rmdir <path> 删除path指定的目录(目录为空才能删除) setcon setenforce setkey setprop setrlimit setsebool start <service> stop <service> swapon_all trigger symlink sysclktz wait write copy chown chmod loglevel load_persist_props load_all_props
service <name> <pathname> [ <argument> ]* <option> <option> ...<name>字段为service的名字,<pathname>为该service对应的二进制程序的路径,随后是该程序的参数列表。
capability class <name> 设定service的class console critical disabled group <groupname> [<groupname>]* 设定进程 keycodes oneshot service只执行一次 onrestart 当service终止时自动重启 seclabeli setenv socket user <username> ioprio
为了方便管理多个service,可为service设定class属性,具有同样class的多个service构成一个组,可以在Actions中通过class_start、class_stop、class_reset等命令启动、停止、重启动。
- 以#号开头的行为注释行
- import语句导入其他init脚本文件,
- \可用于转义换行符
- 空格与Tab字符都可用作空白字符
- 引入section的概念。一个Actions、Service、import是一个section,分别实现不同的section解析代码。
- 基于行解析,行解析函数与当前所在的section有关,使用函数指针实现。
- 利用空白字符(一个或多个空行)实现分词,当检测到新的一行时,识别关键词为on、service、import,若是则认为一个section开始了,同时也意味着上一个section终结了。import使用递归实现
- 每个Actions创建一个struct action数据结构,每个command创建一个struct command数据结构,action中有一个command的链表;每个service创建一个struct service数据结构。
- 创建全局Actions链表,将识别到Actions都加入全局链表中,创建全局Service链表,将识别到的Service加入到全局链表中
INFO("reading config file\n"); init_parse_config_file("/init.rc")init_parse_config_file("/init.rc")
static list_declare(service_list); static list_declare(action_list); static list_declare(action_queue);
struct command { /* list of commands in an action */ struct listnode clist; int (*func)(int nargs, char **args); int line; const char *filename; int nargs; char *args[1]; }; struct action { /* node in list of all actions */ struct listnode alist; /* node in the queue of pending actions */ struct listnode qlist; /* node in list of actions for a trigger */ struct listnode tlist; unsigned hash; const char *name; struct listnode commands; struct command *current; };
struct command各字段含义如下:
struct actions各字段含义如下:
类似,tlist的也是一个特殊链表的钩子
struct service { /* list of all services */ struct listnode slist; //用于挂载于service_list的钩子 const char *name; //存放service的名称 const char *classname; //用于存放该service所隶属的class的名称 unsigned flags; //位图变量,其各个位代表不同的servcie的属性(对应service中的option字段) pid_t pid; //当service对应的程序执行时,存放其进程号 time_t time_started; /* time of last start */ //存放进程启动时间 time_t time_crashed; /* first crash within inspection window */ //存放第一次进程崩溃时间 int nr_crashed; /* number of times crashed within window */ //存放进程崩溃次数 uid_t uid; //该servcie对应进程的uid gid_t gid; //该service对应进程的gidinit_parse_config_file("/init.rc"); gid_t supp_gids[NR_SVC_SUPP_GIDS];//该service对应进程的附加群组id size_t nr_supp_gids; //该service所隶属的附件组的数目 char *seclabel; //存放selinux所需要的security context struct socketinfo *sockets; struct svcenvinfo *envvars; struct action onrestart; /* Actions to execute on restart. */ /* keycodes for triggering this service via /dev/keychord */ int *keycodes;"queue_property_triggers" int nkeycodes; int keychord_id; int ioprio_class; int ioprio_pri; int nargs; //对应service语句传入的参数数目 /* "MUST BE AT THE END OF THE STRUCT" */ char *args[1]; //存放service语句实际传入的参数,其长度将会被修正为nargs+1 }; /* ^-------'args' MUST be at the end of this struct! */
service servicemanager /system/bin/servicemanager class core user system group system critical onrestart restart healthd onrestart restart zygote onrestart restart media onrestart restart surfaceflinger onrestart restart drmonrestart属性后必须跟restart关键字,随后必须再跟一个service名称。
//init.h #define SVC_DISABLED 0x01 /* do not autostart with class */ #define SVC_ONESHOT 0x02 /* do not restart on exit */ #define SVC_RUNNING 0x04 /* currently active */ #define SVC_RESTARTING 0x08 /* waiting to restart */ #define SVC_CONSOLE 0x10 /* requires console */ #define SVC_CRITICAL 0x20 /* will reboot into recovery if keeps crashing */ #define SVC_RESET 0x40 /* Use when stopping a process, but not disabling so it can be restarted with its class */ #define SVC_RC_DISABLED 0x80 /* Remember if the disabled flag was set in the rc script */ #define SVC_RESTART 0x100 /* Use to safely restart (stop, wait, start) a service */ #define SVC_DISABLED_START 0x200 /* a start was requested but it was disabled at the time */
action_for_each_trigger("early-init", action_add_queue_tail); queue_builtin_action(wait_for_coldboot_done_action, "wait_for_coldboot_done"); queue_builtin_action(mix_hwrng_into_linux_rng_action, "mix_hwrng_into_lin一部分在ux_rng"); queue_builtin_action(keychord_init_action, "keychord_init"); queue_builtin_action(console_init_action, "console_init"); /* execute all the boot actions to get us started */ action_for_each_trigger("init", action_add_queue_tail); /* skip mounting filesystems in charger mode */ if (!is_charger) { action_for_each_trigger("early-fs", action_add_queue_tail); action_for_each_trigger("fs", action_add_queue_tail); action_for_each_trigger("post-fs", action_add_queue_tail); action_for_each_trigger("post-fs-data", action_add_queue_tail); } /* Repeat mix_hwrng_into_linux_rng in case /dev/hw_random or /dev/random * wasn't ready immediately after wait_for_coldboot_done */ queue_builtin_action(mix_hwrng_into_linux_rng_action, "mix_hwrng_into_linux_rng"); queue_builtin_action(property_service_init_action, "property_service_init"); queue_builtin_action(signal_init_action, "signal_init"); queue_builtin_action(check_startup_action, "check_startup"); if (is_charger) { action_for_each_trigger("charger", action_add_queue_tail); } else { action_for_each_trigger("early-boot", action_add_queue_tail); action_for_each_trigger("boot", action_add_queue_tail); } /* run all property triggers based on current state of the properties */ queue_builtin_action(queue_property_triggers_action, "queue_property_triggers"); #if BOOTCHART queue_builtin_action(bootchart_init_action, "bootchart_init"); #endif
void action_for_each_trigger(const char *trigger, void (*func)(struct action *act))
void queue_builtin_action(int (*func)(int nargs, char **args), char *name)
该函数完成两个操作:
1)构造一个触发器为name的struct action结构体,并创建一个struct command,对应函数为行参func
2)将struct action添加到action_queue链表末尾。
白色节点来自init启动脚本,橘红色节点则有函数queue_builtin_action创建。
for(;;) { execute_one_command(); ... }
on late-init trigger early-fs trigger fs trigger post-fs trigger post-fs-data # Load properties from /system/ + /factory after fs mount. Place # this in another action so that the load will be scheduled after the prior # issued fs triggers have completed. trigger load_all_props_action # Remove a file to wake up anything waiting for firmware. trigger firmware_mounts_complete trigger early-boot trigger boot
//keyword.h //------------- KEYWORD(trigger, COMMAND, 1, do_trigger) //builtins.c //------------- int do_trigger(int nargs, char **args) { action_for_each_trigger(args[1], action_add_queue_tail); return 0; }
bingo!原来trigger命令对应的函数do_trigger中再次调用了action_for_each_trigger,可见之前的猜测正确!
static int queue_property_triggers_action(int nargs, char **args) { queue_all_property_triggers(); /* enable property triggers */ property_triggers_enabled = 1; return 0; } void queue_all_property_triggers() { struct listnode *node; struct action *act; list_for_each(node, &action_list) { act = node_to_item(node, struct action, alist); if (!strncmp(act->name, "property:", strlen("property:"))) { /* parse property name and value syntax is property:<name>=<value> */ const char* name = act->name + strlen("property:"); const char* equals = strchr(name, '='); if (equals) { char prop_name[PROP_NAME_MAX + 1]; char value[PROP_VALUE_MAX];新浪微博 int length = equals - name; if (length > PROP_NAME_MAX) { ERROR("property name too long in trigger %s", act->name); } else { int ret; memcpy(prop_name, name, length); prop_name[length] = 0; /* does the property exist, and match the trigger value? */ ret = property_get(prop_name, value); if (ret > 0 && (!strcmp(equals + 1, value) || !strcmp(equals + 1, "*"))) { action_add_queue_tail(act); } } } } } }
int main(int argc, char* argv[]) { .... for(;;) { execute_one_command(); .... nr = poll(ufds, fd_count, timeout); if (nr <= 0) continue; for (i = 0; i < fd_count; i++) { if (ufds[i].revents == POLLIN) {这部分内容请阅读 if (ufds[i].fd == get_property_set_fd()) handle_property_set_fd(); ... } } } }
当某个程序(进程)调用property_set(libcutils库)来自设置属性,就会给init进程发送一个消息(通过Unix domain socket),最终init接收到整个消息后,会调用
handle_property_set_fd() -> property_set(来自init/property_service.c)-> property_changed() -> queue_property_triggers()->action_add_queue_tail
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。