IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 移动开发 -> Android init.rc 官方说明文档 -> 正文阅读

[移动开发]Android init.rc 官方说明文档

说明

硬件:ROC-RK3399-PC-Pro
固件:ROC-RK3399-PC-Pro_Industry7.1.2_HDMI
目录: firefly-rk3399-Industry 为工程根目录,所有编译、烧录命令均在改目录下执行
官方教程:https://wiki.t-firefly.com/zh_CN/ROC-RK3399-PC-Pro/
个人专栏:firefly ROC-RK3399-PC-Pro开发板专栏

本文来源:firefly-rk3399-Industry/system/core/init/readme.txt (源码对应目录都会有)

这里有一篇比较好的文档请参考:https://blog.csdn.net/marshal_zsx/article/details/80272760

1. 综述

1.1 Android Init language


The Android Init Language consists of five broad classes of statements,
which are Actions, Commands, Services, Options, and Imports.

  • 包含五部分:Actions, Commands, Services, Options, and Imports

All of these are line-oriented, consisting of tokens separated by
whitespace. The c-style backslash escapes may be used to insert
whitespace into a token. Double quotes may also be used to prevent
whitespace from breaking text into multiple tokens. The backslash,
when it is the last character on a line, may be used for line-folding.

  • 以行为单位,记号以空格分隔
  • 双引号可以包裹字符串,防止被分割为多个记号

Lines which start with a # (leading whitespace allowed) are comments.

  • # 表示注释,可以以空格开头

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.

Actions and Services have unique names. If a second Action is defined
with the same name as an existing one, its commands are appended to
the commands of the existing action. If a second Service is defined
with the same name as an existing one, it is ignored and an error
message is logged.

  • Actions 和 Services 有唯一的名字,第二个同名声明将被忽略

1.2 Init .rc Files


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

/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. It imports /init.${ro.hardware}.rc which is the
primary vendor supplied .rc file.

During the mount_all command, the init executable loads all of the
files contained within the /{system,vendor,odm}/etc/init/ directories.
These directories are intended for all Actions and Services used after
file system mounting.

One may specify paths in the mount_all command line to have it import
.rc files at the specified paths instead of the default ones listed above.
This is primarily for supporting factory mode and other non-standard boot
modes. The three default paths should be used for the normal boot process.

The intention of these directories is as follows

  1. /system/etc/init/ is for core system items such as
    SurfaceFlinger, MediaService, and logcatd.
  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 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.

There are two options “early” and “late” in mount_all command
which can be set after optional paths. With “–early” set, the
init executable will skip mounting entries with “latemount” flag
and triggering fs encryption state event. With “–late” set,
init executable will only mount entries with “latemount” flag but skip
importing rc files. By default, no option is set, and mount_all will
mount_all will process all entries in the given fstab.

2. Actions


Actions are named sequences of commands. Actions have a trigger which
is used to determine when the action should occur. 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).

  • Actions 是一系列被命名的命令
  • Actions 被 trigger 触发后会被加入到对应的执行队列中。

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 <trigger> [&& <trigger>]*
   <command>
   <command>
   <command>
  • 以 on 开头,trigger 是判断条件

trigger 可以是字符串

# 表示当trigger early或QueueEventTrigger("early")调用时触发
on early 

trigger 可以是属性

# 表示当sys.boot_from_charger_mode的值通过property_set设置为1时触发
on property:sys.boot_from_charger_mode=1
# *表示任意值
on property:sys.sysctl.tcp_def_init_rwnd=* 

3. Services


Services are programs which init launches and (optionally) restarts
when they exit. Services take the form of:

service <name> <pathname> [ <argument> ]*
   <option>
   <option>
   ...
  • name 服务名称
  • pathname 服务的执行文件路径
  • argument 参数,相当于main函数的参数
  • option 服务的选项配置

4. Options


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

4.1 critical

This is a device-critical service. If it exits more than four times in
four minutes, the device will reboot into recovery mode.

  • 严格模式,如果该服务4分钟内退出超过四次,系统重启进入 recovery 模式

4.2 disabled

This service will not automatically start with its class.
It must be explicitly started by name.

  • 不能以 class 方式启动,只能以 name 启动

4.3 setenv

setenv <name> <value>
  # Set the environment variable <name> to <value> in the launched process.
  • 在服务启动时设置 name - value 的环境变量

4.4 socket

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

  Create a unix domain socket named /dev/socket/<name> and pass
  its fd to the launched process.  <type> must be "dgram", "stream" or "seqpacket".
  User and group default to 0.
  'seclabel' is the SELinux security context for the socket.
  It defaults to the service security context, as specified by seclabel or
  computed based on the service executable file security context.
  • 创建一个名字叫 /dev/socket/name 的 unix 域 socket,并将其文件描述符传递给本 service
  • type 必须是 “dgram”, “stream” or “seqpacket”
  • User and group default to 0

4.5 user

user <username>
  Change to username before exec'ing this service.
  Currently defaults to root.  (??? probably should default to nobody)
  As of Android M, processes should use this option even if they
  require linux capabilities.  Previously, to acquire linux
  capabilities, a process would need to run as root, request the
  capabilities, then drop to its desired uid.  There is a new
  mechanism through fs_config that allows device manufacturers to add
  linux capabilities to specific binaries on a file system that should
  be used instead. This mechanism is described on
  http://source.android.com/devices/tech/config/filesystem.html.  When
  using this new mechanism, processes can use the user option to
  select their desired uid without ever running as root.
  • 启动前将 user 改为 username
  • 默认为 root

4.6 group

group <groupname> [ <groupname> ]*
  Change to groupname before exec'ing this service.  Additional
  groupnames beyond the (required) first one are used to set the
  supplemental groups of the process (via setgroups()).
  Currently defaults to root.  (??? probably should default to nobody)
  • 启动前将 group 改为 groupname
  • 默认为 root

4.7 seclabel

seclabel <seclabel>
  Change to 'seclabel' before exec'ing this service.
  Primarily for use by services run from the rootfs, e.g. ueventd, adbd.
  Services on the system partition can instead use policy-defined transitions
  based on their file security context.
  If not specified and no transition is defined in policy, defaults to the init context.
  • 在启动Service前将seclabel设置为seclabel. 主要用于在rootfs上启动的service,比如ueventd, adbd.
  • 在系统分区上运行的service有自己的SELinux安全策略
  • 如果不设置,默认使用init的安全策略.

4.8 oneshot

oneshot
  Do not restart the service when it exits.
  • 退出后不重启

4.9 class

class <name>
  Specify a class name for the service.  All services in a
  named class may be started or stopped together.  A service
  is in the class "default" if one is not specified via the
  class option.
  • 为Service指定class名字,同一个class名字的Service会被一起启动或退出,
  • 默认值是"default"

4.10 onrestart

onrestart
  Execute a Command (see below) when service restarts.
  • 在服务重启时执行下列命令

4.11 writepid

writepid <file...>
  Write the child's pid to the given files when it forks. Meant for
  cgroup/cpuset usage.
  • 当Service调用fork时将子进程的pid写入到指定文件

4.12 file

file <path> <type>
  • 打开一个文件,并将fd返回给这个Service
  • type 只能是 “r”, “w” or “rw”

4.13 namespace

namespace <pid|mnt>
# 当fork这个service时,设置pid或mnt标记

4.14 priority

priority <priority>
# 设置进程优先级. 在-20~19之间,默认值是0,能过setpriority实现

5. 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.

  • trigger分为事件 trigger 和 属性 trigger
  • 事件 trigger 触发方式只有一种
  • 属性 tirgger 触发方式有多种

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.

6. Commands


bootchart_init
   Start bootcharting if configured (see below).
   This is included in the default init.rc.
chmod <octal-mode> <path>
   Change file access permissions.
chown <owner> <group> <path>
   Change file owner and group.
class_start <serviceclass>
   Start all services of the specified class if they are
   not already running.
class_stop <serviceclass>
   Stop and disable all services of the specified class if they are
   currently running.
class_reset <serviceclass>
   Stop all services of the specified class if they are
   currently running, without disabling them. They can be restarted
   later using class_start.
copy <src> <dst>
   Copies a file. Similar to write, but useful for binary/large
   amounts of data.
domainname <name>
   Set the domain name.
enable <servicename>
   Turns a disabled service into an enabled one as if the service did not
   specify disabled.
   If the service is supposed to be running, it will be started now.
   Typically used when the bootloader sets a variable that indicates a specific
   service should be started when needed. E.g.
     on property:ro.boot.myfancyhardware=1
        enable my_fancy_service_for_my_fancy_hardware
exec [ <seclabel> [ <user> [ <group> ]* ] ] -- <command> [ <argument> ]*
   Fork and execute command with the given arguments. The command starts
   after "--" so that an optional security context, user, and supplementary
   groups can be provided. No other commands will be run until this one
   finishes. <seclabel> can be a - to denote default.
export <name> <value>
   Set the environment variable <name> equal to <value> in the
   global environment (which will be inherited by all processes
   started after this command is executed)
hostname <name>
   Set the host name.
ifup <interface>
   Bring the network interface <interface> online.
insmod <path>
   Install the module at <path>
load_all_props
   Loads properties from /system, /vendor, et cetera.
   This is included in the default init.rc.
load_persist_props
   Loads persistent properties when /data has been decrypted.
   This is included in the default init.rc.
loglevel <level>
   Sets the kernel log level to level. Properties are expanded within <level>.
mkdir <path> [mode] [owner] [group]
   Create a directory at <path>, optionally with the given mode, owner, and
   group. If not provided, the directory is created with permissions 755 and
   owned by the root user and root group. If provided, the mode, owner and group
   will be updated if the directory exists already.
mount_all <fstab> [ <path> ]* [--<option>]
   Calls fs_mgr_mount_all on the given fs_mgr-format fstab and imports .rc files
   at the specified paths (e.g., on the partitions just mounted) with optional
   options "early" and "late".
   Refer to the section of "Init .rc Files" for detail.
mount <type> <device> <dir> [ <flag> ]* [<options>]
   Attempt to mount the named device at the directory <dir>
   <device> may be of the form mtd@name to specify a mtd block
   device by name.
   <flag>s include "ro", "rw", "remount", "noatime", ...
   <options> include "barrier=1", "noauto_da_alloc", "discard", ... as
   a comma separated string, eg: barrier=1,noauto_da_alloc
powerctl
   Internal implementation detail used to respond to changes to the
   "sys.powerctl" system property, used to implement rebooting.
restart <service>
   Like stop, but doesn't disable the service.
restorecon <path> [ <path> ]*
   Restore the file named by <path> to the security context specified
   in the file_contexts configuration.
   Not required for directories created by the init.rc as these are
   automatically labeled correctly by init.
restorecon_recursive <path> [ <path> ]*
   Recursively restore the directory tree named by <path> to the
   security contexts specified in the file_contexts configuration.
rm <path>
   Calls unlink(2) on the given path. You might want to
   use "exec -- rm ..." instead (provided the system partition is
   already mounted).
rmdir <path>
   Calls rmdir(2) on the given path.
setprop <name> <value>
   Set system property <name> to <value>. Properties are expanded
   within <value>.
setrlimit <resource> <cur> <max>
   Set the rlimit for a resource.
start <service>
   Start a service running if it is not already running.
stop <service>
   Stop a service from running if it is currently running.
swapon_all <fstab>
   Calls fs_mgr_swapon_all on the given fstab file.
symlink <target> <path>
   Create a symbolic link at <path> with the value <target>
sysclktz <mins_west_of_gmt>
   Set the system clock base (0 if system clock ticks in GMT)
trigger <event>
   Trigger an event.  Used to queue an action from another
   action.
umount <path>
   Unmount the filesystem mounted at that path.
verity_load_state
   Internal implementation detail used to load dm-verity state.
verity_update_state <mount_point>
   Internal implementation detail used to update dm-verity state and
   set the partition.<mount_point>.verified properties used by adb remount
   because fs_mgr can't set them directly itself.
wait <path> [ <timeout> ]
   Poll for the existence of the given file and return when found,
   or the timeout has been reached. If timeout is not specified it
   currently defaults to five seconds.
  • 单位秒
write <path> <content>
   Open the file at <path> and write a string to it with write(2).
   If the file does not exist, it will be created. If it does exist,
   it will be truncated. Properties are expanded within <content>.

7. Imports


The import keyword is not a command, but rather its own section and is
handled immediately after the .rc file that contains it has finished
being parsed. It takes the below form:

import
Parse an init config file, extending the current configuration.
If is a directory, each file in the directory is parsed as
a config file. It is not recursive, nested directories will
not be parsed.

There are only two times where the init executable imports .rc files,

  1. When it imports /init.rc during initial boot
  2. When it imports /{system,vendor,odm}/etc/init/ or .rc files at specified
    paths during mount_all

8. Properties


Init provides information about the services that it is responsible
for via the below properties.

init.svc.
State of a named service (“stopped”, “stopping”, “running”, “restarting”)

9. Bootcharting


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

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

On a device, create /data/bootchart/start with a command like the following:

adb shell ‘echo $TIMEOUT > /data/bootchart/start’

Where the value of $TIMEOUT corresponds to the desired bootcharted period in
seconds. Bootcharting will stop after that many seconds have elapsed.
You can also stop the bootcharting at any moment by doing the following:

adb shell ‘echo 1 > /data/bootchart/stop’

Note that /data/bootchart/stop is deleted automatically by init at the end of
the bootcharting. This is not the case with /data/bootchart/start, so don’t
forget to delete it 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.

10. 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 barballs 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)

11. Systrace


Systrace [1] 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.

[1] http://developer.android.com/tools/help/systrace.html

12. Debugging init


By default, programs executed by init will drop stdout and stderr into
/dev/null. To help with debugging, you can execute your program via the
Android program logwrapper. This will redirect stdout/stderr into the
Android logging system (accessed via logcat).

For example

service akmd /system/bin/logwrapper /sbin/akmd

For quicker turnaround when working on init itself, use:

  mm -j
  m ramdisk-nodeps
  m bootimage-nodeps
  adb reboot bootloader
  fastboot boot $ANDROID_PRODUCT_OUT/boot.img

Alternatively, use the emulator:

  emulator -partition-size 1024 -verbose -show-kernel -no-window

You might want to call klog_set_level(6) after the klog_init() call
so you see the kernel logging in dmesg (or the emulator output).

  移动开发 最新文章
Vue3装载axios和element-ui
android adb cmd
【xcode】Xcode常用快捷键与技巧
Android开发中的线程池使用
Java 和 Android 的 Base64
Android 测试文字编码格式
微信小程序支付
安卓权限记录
知乎之自动养号
【Android Jetpack】DataStore
上一篇文章      下一篇文章      查看所有文章
加:2022-06-06 17:28:44  更:2022-06-06 17:29:09 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/25 1:23:46-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码