Android Init语言介绍

2025年02月08日 Android Init语言介绍 极客笔记

Android Init 语言

Android Init语言由五部分组成:

  • Actions
  • Commands
  • Services
  • Options(选项)
  • Imports

rc文件都是面向行的,由以空白分隔的标记组成。如果要表达空白字符,可以使用C语言中的反斜杠(或双引号)来转义。当反斜杠是一行的最后一个字符时,可用于续行。

注释,以#开头。

System properties can be expanded using the syntax
${property.name}. This also works in contexts where concatenation is
required, such as import /init.recovery.${ro.hardware}.rc.

Actions and Services implicitly declare a new section. All commands
or options belong to the section most recently declared. Commands
or options before the first section are ignored.

Services have unique names. If a second Service is defined
with the same name as an existing one, it is ignored and an error
message is logged.

Init .rc 文件

The init language is used in plain text files that take the .rc file
extension. There are typically multiple of these in multiple
locations on the system, described below.

/system/etc/init/hw/init.rc is the primary .rc file and is loaded by the init executable at the
beginning of its execution. It is responsible for the initial set up of the system.

Init loads all of the files contained within the
/{system,system_ext,vendor,odm,product}/etc/init/ directories immediately after loading
the primary /system/etc/init/hw/init.rc. This is explained in more details in the
Imports section of this file.

Legacy devices without the first stage mount mechanism previously were
able to import init scripts during mount_all, however that is deprecated
and not allowed for devices launching after Q.

The intention of these directories is:

  1. /system/etc/init/ is for core system items such as
    SurfaceFlinger, MediaService, and logd.
  2. /vendor/etc/init/ is for SoC vendor items such as actions or
    daemons needed for core SoC functionality.
  3. /odm/etc/init/ is for device manufacturer items such as
    actions or daemons needed for motion sensor or other peripheral
    functionality.

All services whose binaries reside on the system, vendor, or odm
partitions should have their service entries placed into a
corresponding init .rc file, located in the /etc/init/
directory of the partition where they reside. There is a build
system macro, LOCAL_INIT_RC, that handles this for developers. Each
init .rc file should additionally contain any actions associated with
its service.

An example is the userdebug logcatd.rc and Android.mk files located in the
system/core/logcat directory. The LOCAL_INIT_RC macro in the
Android.mk file places logcatd.rc in /system/etc/init/ during the
build process. Init loads logcatd.rc during the mount_all command and
allows the service to be run and the action to be queued when
appropriate.

This break up of init .rc files according to their daemon is preferred
to the previously used monolithic init .rc files. This approach
ensures that the only service entries that init reads and the only
actions that init performs correspond to services whose binaries are in
fact present on the file system, which was not the case with the
monolithic init .rc files. This additionally will aid in merge
conflict resolution when multiple services are added to the system, as
each one will go into a separate file.

Versioned RC files within APEXs

With the arrival of mainline on Android Q, the individual mainline
modules carry their own init.rc files within their boundaries. Init
processes these files according to the naming pattern /apex/*/etc/*rc.

Because APEX modules must run on more than one release of Android,
they may require different parameters as part of the services they
define. This is achieved, starting in Android T, by incorporating
the SDK version information in the name of the init file. The suffix
is changed from .rc to .#rc where # is the first SDK where that
RC file is accepted. An init file specific to SDK=31 might be named
init.31rc. With this scheme, an APEX may include multiple init files. An
example is appropriate.

For an APEX module with the following files in /apex/sample-module/apex/etc/:

  1. init.rc
  2. init.32rc
  3. init.35rc

The selection rule chooses the highest .#rc value that does not
exceed the SDK of the currently running system. The unadorned .rc
is interpreted as sdk=0.

When this APEX is installed on a device with SDK <=31, the system will
process init.rc. When installed on a device running SDK 32, 33, or 34,
it will use init.32rc. When installed on a device running SDKs >= 35,
it will choose init.35rc

This versioning scheme is used only for the init files within APEX
modules; it does not apply to the init files stored in /system/etc/init,
/vendor/etc/init, or other directories.

This naming scheme is available after Android S.

Actions

Actions are named sequences of commands. Actions have a trigger which
is used to determine when the action is executed. When an event
occurs which matches an action’s trigger, that action is added to
the tail of a to-be-executed queue (unless it is already on the
queue).

Each action in the queue is dequeued in sequence and each command in
that action is executed in sequence. Init handles other activities
(device creation/destruction, property setting, process restarting)
"between" the execution of the commands in activities.

Actions take the form of:

on  [&& ]*
   
   
   

Actions are added to the queue and executed based on the order that
the file that contains them was parsed (see the Imports section), then
sequentially within an individual file.

For example if a file contains:

on boot
   setprop a 1
   setprop b 2

on boot && property:true=true
   setprop c 1
   setprop d 2

on boot
   setprop e 1
   setprop f 2

Then when the boot trigger occurs and assuming the property true
equals true, then the order of the commands executed will be:

setprop a 1
setprop b 2
setprop c 1
setprop d 2
setprop e 1
setprop f 2

Services

Services是系统启动时由init启动起来的进程,当进程异常退出时会自动重启(可选)。

Services 的语法如下:

service <name> <pathname> [ <argument> ]*
   <option>
   <option>
   ...

Options(选项)

Options are modifiers to services. They affect how and when init
runs the service.

capabilities [ <capability>* ]

class <name> [ <name>\* ]

console [<console>]

critical [window=<fatal crash window mins>] [target=<fatal reboot target>]

disabled

enter_namespace <type> <path>

file <path> <type>

group <groupname> [ <groupname>\* ]

interface <interface name> <instance name>

ioprio <class> <priority>

keycodes <keycode> [ <keycode>\* ]

memcg.limit_in_bytes <value> and memcg.limit_percent <value>

memcg.limit_property <value>

memcg.soft_limit_in_bytes <value>

memcg.swappiness <value>

namespace <pid|mnt>

oneshot

onrestart

oom_score_adjust <value>

override

priority <priority>

reboot_on_failure <target>

restart_period <seconds>

rlimit <resource> <cur> <max>

seclabel <seclabel>

setenv <name> <value>

shutdown <shutdown_behavior>

sigstop

socket <name> <type> <perm> [ <user> [ <group> [ <seclabel> ] ] ]

stdio_to_kmsg

task_profiles <profile> [ <profile>\* ]

timeout_period <seconds>

updatable

user <username>

writepid <file> [ <file>\* ]

Triggers

Triggers are strings which can be used to match certain kinds of
events and used to cause an action to occur.

Triggers are subdivided into event triggers and property triggers.

Event triggers are strings triggered by the ‘trigger’ command or by
the QueueEventTrigger() function within the init executable. These
take the form of a simple string such as ‘boot’ or ‘late-init’.

Property triggers are strings triggered when a named property changes
value to a given new value or when a named property changes value to
any new value. These take the form of ‘property:=‘ and
‘property:=*’ respectively. Property triggers are additionally
evaluated and triggered accordingly during the initial boot phase of
init.

An Action can have multiple property triggers but may only have one
event trigger.

For example:
on boot && property:a=b defines an action that is only executed when
the ‘boot’ event trigger happens and the property a equals b.

on property:a=b && property:c=d defines an action that is executed
at three times:

  1. During initial boot if property a=b and property c=d.
  2. Any time that property a transitions to value b, while property c already equals d.
  3. Any time that property c transitions to value d, while property a already equals b.

Trigger Sequence

Init uses the following sequence of triggers during early boot. These are the
built-in triggers defined in init.cpp.

  1. early-init – The first in the sequence, triggered after cgroups has been configured
    but before ueventd’s coldboot is complete.
  2. init – Triggered after coldboot is complete.
  3. charger – Triggered if ro.bootmode == "charger".
  4. late-init – Triggered if ro.bootmode != "charger", or via healthd triggering a boot
    from charging mode.

Remaining triggers are configured in init.rc and are not built-in. The default sequence for
these is specified under the "on late-init" event in init.rc. Actions internal to init.rc
have been omitted.

  1. early-fs – Start vold.
  2. fs – Vold is up. Mount partitions not marked as first-stage or latemounted.
  3. post-fs – Configure anything dependent on early mounts.
  4. late-fs – Mount partitions marked as latemounted.
  5. post-fs-data – Mount and configure /data; set up encryption. /metadata is
    reformatted here if it couldn’t mount in first-stage init.
  6. zygote-start – Start the zygote.
  7. early-boot – After zygote has started.
  8. boot – After early-boot actions have completed.

Commands

bootchart [start|stop]

chmod <octal-mode> <path>

chown <owner> <group> <path>

class_start <serviceclass>

class_stop <serviceclass>

class_reset <serviceclass>

class_restart [--only-enabled] <serviceclass>

copy <src> <dst>

copy_per_line <src> <dst>

domainname <name>

enable <servicename>

on property:ro.boot.myfancyhardware=1
    enable my_fancy_service_for_my_fancy_hardware

exec [ <seclabel> [ <user> [ <group>\* ] ] ] -- <command> [ <argument>\* ]

exec_background [ <seclabel> [ <user> [ <group>\* ] ] ] -- <command> [ <argument>\* ]

exec_start <service>

export <name> <value>

hostname <name>

ifup <interface>

insmod [-f] <path> [<options>]

interface_start <name> \
interface_restart <name> \
interface_stop <name>

load_exports <path>

load_system_props

load_persist_props

loglevel <level>

mark_post_data

mkdir <path> [<mode>] [<owner>] [<group>] [encryption=<action>] [key=<key>]

mount_all [ <fstab> ] [--<option>]

mount <type> <device> <dir> [ <flag>\* ] [<options>]

perform_apex_config

restart [--only-if-running] <service>

restorecon <path> [ <path>\* ]

restorecon_recursive <path> [ <path>\* ]

rm <path>

rmdir <path>

readahead <file|dir> [--fully]

setprop <name> <value>

setrlimit <resource> <cur> <max>

start <service>

stop <service>

swapon_all [ <fstab> ]

symlink <target> <path>

sysclktz <minutes_west_of_gmt>

trigger <event>

umount <path>

umount_all [ <fstab> ]

verity_update_state

wait <path> [ <timeout> ]

wait_for_prop <name> <value>

write <path> <content>

Imports

import <path>

The import keyword is not a command, but rather its own section,
meaning that it does not happen as part of an Action, but rather,
imports are handled as a file is being parsed and follow the below logic.

There are only three times where the init executable imports .rc files:

  1. When it imports /system/etc/init/hw/init.rc or the script indicated by the property
    ro.boot.init_rc during initial boot.
  2. When it imports /{system,system_ext,vendor,odm,product}/etc/init/ immediately after
    importing /system/etc/init/hw/init.rc.
  3. (Deprecated) When it imports /{system,vendor,odm}/etc/init/ or .rc files
    at specified paths during mount_all, not allowed for devices launching
    after Q.

The order that files are imported is a bit complex for legacy reasons. The below is guaranteed:

  1. /system/etc/init/hw/init.rc is parsed then recursively each of its imports are
    parsed.
  2. The contents of /system/etc/init/ are alphabetized and parsed sequentially, with imports
    happening recursively after each file is parsed.
  3. Step 2 is repeated for /system_ext/etc/init, /vendor/etc/init, /odm/etc/init,
    /product/etc/init

The below pseudocode may explain this more clearly:

fn Import(file)
  Parse(file)
  for (import : file.imports)
    Import(import)

Import(/system/etc/init/hw/init.rc)
Directories = [/system/etc/init, /system_ext/etc/init, /vendor/etc/init, /odm/etc/init, /product/etc/init]
for (directory : Directories)
  files = 
  for (file : files)
    Import(file)

Actions are executed in the order that they are parsed. For example the post-fs-data action(s)
in /system/etc/init/hw/init.rc are always the first post-fs-data action(s) to be executed in
order of how they appear in that file. Then the post-fs-data actions of the imports of
/system/etc/init/hw/init.rc in the order that they’re imported, etc.

Properties

Init provides state information with the following properties.

init.svc.<name>

dev.mnt.dev.<mount_point>, dev.mnt.blk.<mount_point>, dev.mnt.rootdisk.<mount_point>

dev.mnt.blk.<mount_point> indicates the disk partition to the above block device.
(e.g., sdaN / mmcblk0pN to access /sys/class/block/${dev.mnt.blk.<mount_point>}/)

dev.mnt.rootdisk.<mount_point> indicates the root disk to contain the above disk partition.
(e.g., sda / mmcblk0 to access /sys/class/block/${dev.mnt.rootdisk.<mount_point>}/queue)

Init responds to properties that begin with ctl.. These properties take the format of
ctl.[<target>_]<command> and the value of the system property is used as a parameter. The
target is optional and specifies the service option that value is meant to match with. There is
only one option for target, interface which indicates that value will refer to an interface
that a service provides and not the service name itself.

For example:

SetProperty("ctl.start", "logd") will run the start command on logd.

SetProperty("ctl.interface_start", "aidl/aidl_lazy_test_1") will run the start command on the
service that exposes the aidl aidl_lazy_test_1 interface.

Note that these
properties are only settable; they will have no value when read.

The commands are listed below.

start \
restart \
stop \
These are equivalent to using the start, restart, and stop commands on the service specified
by the value of the property.

oneshot_on and oneshot_off will turn on or off the oneshot
flag for the service specified by the value of the property. This is
particularly intended for services that are conditionally lazy HALs. When
they are lazy HALs, oneshot must be on, otherwise oneshot should be off.

sigstop_on and sigstop_off will turn on or off the sigstop feature for the service
specified by the value of the property. See the Debugging init section below for more details
about this feature.

Boot timing

Init records some boot timing information in system properties.

ro.boottime.init

ro.boottime.init.first_stage

ro.boottime.init.selinux

ro.boottime.init.modules

ro.boottime.init.cold_boot_wait

ro.boottime.<service-name>

Bootcharting

This version of init contains code to perform "bootcharting": generating log
files that can be later processed by the tools provided by http://www.bootchart.org/.

On the emulator, use the -bootchart timeout option to boot with bootcharting
activated for timeout seconds.

On a device:

adb shell 'touch /data/bootchart/enabled'

Don’t forget to delete this file when you’re done collecting data!

The log files are written to /data/bootchart/. A script is provided to
retrieve them and create a bootchart.tgz file that can be used with the
bootchart command-line utility:

sudo apt-get install pybootchartgui
# grab-bootchart.sh uses ANDROID_SERIAL.ANDROID_BUILD_TOP/system/core/init/grab-bootchart.sh

One thing to watch for is that the bootchart will show init as if it started
running at 0s. You’ll have to look at dmesg to work out when the kernel
actually started init.

Comparing two bootcharts

A handy script named compare-bootcharts.py can be used to compare the
start/end time of selected processes. The aforementioned grab-bootchart.sh
will leave a bootchart tarball named bootchart.tgz at /tmp/android-bootchart.
If two such tarballs are preserved on the host machine under different
directories, the script can list the timestamps differences. For example:

Usage: system/core/init/compare-bootcharts.py base-bootchart-dir exp-bootchart-dir

process: baseline experiment (delta) - Unit is ms (a jiffy is 10 ms on the system)
------------------------------------
/init: 50 40 (-10)
/system/bin/surfaceflinger: 4320 4470 (+150)
/system/bin/bootanimation: 6980 6990 (+10)
zygote64: 10410 10640 (+230)
zygote: 10410 10640 (+230)
system_server: 15350 15150 (-200)
bootanimation ends at: 33790 31230 (-2560)

Systrace

Systrace (http://developer.android.com/tools/help/systrace.html) can be
used for obtaining performance analysis reports during boot
time on userdebug or eng builds.

Here is an example of trace events of "wm" and "am" categories:

$ANDROID_BUILD_TOP/external/chromium-trace/systrace.py \
      wm am --boot

This command will cause the device to reboot. After the device is rebooted and
the boot sequence has finished, the trace report is obtained from the device
and written as trace.html on the host by hitting Ctrl+C.

Limitation: recording trace events is started after persistent properties are loaded, so
the trace events that are emitted before that are not recorded. Several
services such as vold, surfaceflinger, and servicemanager are affected by this
limitation since they are started before persistent properties are loaded.
Zygote initialization and the processes that are forked from the zygote are not
affected.

Debugging init

When a service starts from init, it may fail to execv() the service. This is not typical, and may
point to an error happening in the linker as the new service is started. The linker in Android
prints its logs to logd and stderr, so they are visible in logcat. If the error is encountered
before it is possible to access logcat, the stdio_to_kmsg service option may be used to direct
the logs that the linker prints to stderr to kmsg, where they can be read via a serial port.

Launching init services without init is not recommended as init sets up a significant amount of
environment (user, groups, security label, capabilities, etc) that is hard to replicate manually.

If it is required to debug a service from its very start, the sigstop service option is added.
This option will send SIGSTOP to a service immediately before calling exec. This gives a window
where developers can attach a debugger, strace, etc before continuing the service with SIGCONT.

This flag can also be dynamically controlled via the ctl.sigstop_on and ctl.sigstop_off properties.

Below is an example of dynamically debugging logd via the above:

stop logd
setprop ctl.sigstop_on logd
start logd
ps -e | grep logd
> logd          4343     1   18156   1684 do_signal_stop 538280 T init
gdbclient.py -p 4343
b main
c
c
c
> Breakpoint 1, main (argc=1, argv=0x7ff8c9a488) at system/core/logd/main.cpp:427

Below is an example of doing the same but with strace

stop logd
setprop ctl.sigstop_on logd
start logd
ps -e | grep logd
> logd          4343     1   18156   1684 do_signal_stop 538280 T init
strace -p 4343

(From a different shell)
kill -SIGCONT 4343

> strace runs

Host Init Script Verification

Init scripts are checked for correctness during build time. Specifically the below is checked.

1) Well formatted action, service and import sections, e.g. no actions without a preceding ‘on’
line, and no extraneous lines after an ‘import’ statement.
2) All commands map to a valid keyword and the argument count is within the correct range.
3) All service options are valid. This is stricter than how commands are checked as the service
options’ arguments are fully parsed, e.g. UIDs and GIDs must resolve.

There are other parts of init scripts that are only parsed at runtime and therefore not checked
during build time, among them are the below.

1) The validity of the arguments of commands, e.g. no checking if file paths actually exist, if
SELinux would permit the operation, or if the UIDs and GIDs resolve.
2) No checking if a service exists or has a valid SELinux domain defined
3) No checking if a service has not been previously defined in a different init script.

Early Init Boot Sequence

The early init boot sequence is broken up into three stages: first stage init, SELinux setup, and
second stage init.

First stage init is responsible for setting up the bare minimum requirements to load the rest of the
system. Specifically this includes mounting /dev, /proc, mounting ‘early mount’ partitions (which
needs to include all partitions that contain system code, for example system and vendor), and moving
the system.img mount to / for devices with a ramdisk.

Note that in Android Q, system.img always contains TARGET_ROOT_OUT and always is mounted at / by the
time first stage init finishes. Android Q will also require dynamic partitions and therefore will
require using a ramdisk to boot Android. The recovery ramdisk can be used to boot to Android instead
of a dedicated ramdisk as well.

First stage init has three variations depending on the device configuration:
1) For system-as-root devices, first stage init is part of /system/bin/init and a symlink at /init
points to /system/bin/init for backwards compatibility. These devices do not need to do anything to
mount system.img, since it is by definition already mounted as the rootfs by the kernel.

2) For devices with a ramdisk, first stage init is a static executable located at /init. These
devices mount system.img as /system then perform a switch root operation to move the mount at
/system to /. The contents of the ramdisk are freed after mounting has completed.

3) For devices that use recovery as a ramdisk, first stage init it contained within the shared init
located at /init within the recovery ramdisk. These devices first switch root to
/first_stage_ramdisk to remove the recovery components from the environment, then proceed the same
as 2). Note that the decision to boot normally into Android instead of booting
into recovery mode is made if androidboot.force_normal_boot=1 is present in the
kernel commandline, or in bootconfig with Android S and later.

Once first stage init finishes it execs /system/bin/init with the "selinux_setup" argument. This
phase is where SELinux is optionally compiled and loaded onto the system. selinux.cpp contains more
information on the specifics of this process.

Lastly once that phase finishes, it execs /system/bin/init again with the "second_stage"
argument. At this point the main phase of init runs and continues the boot process via the init.rc
scripts.

本文链接:http://so.lmcjl.com/news/22760/

展开阅读全文