• Home
Name Date Size #Lines LOC

..--

parser/03-May-2024-435301

sysprop/03-May-2024-8476

test_kill_services/03-May-2024-13571

test_service/03-May-2024-166128

test_utils/03-May-2024-9842

.clang-formatD03-May-2024291

Android.bpD03-May-202414.4 KiB600556

Android.mkD03-May-2024513 1913

AndroidTest.xmlD03-May-20242.1 KiB3922

MODULE_LICENSE_APACHE2D03-May-20240

NOTICED03-May-202410.4 KiB191158

OWNERSD03-May-202437 32

README.mdD03-May-202445.8 KiB1,052828

README.ueventd.mdD03-May-20248.3 KiB182138

TEST_MAPPINGD03-May-2024357 2524

action.cppD03-May-20248.1 KiB249180

action.hD03-May-20243.1 KiB10068

action_manager.cppD03-May-20244.2 KiB13289

action_manager.hD03-May-20241.8 KiB6335

action_parser.cppD03-May-20245.5 KiB175126

action_parser.hD03-May-20241.5 KiB5026

block_dev_initializer.cppD03-May-20245.6 KiB163124

block_dev_initializer.hD03-May-20241.3 KiB4723

bootchart.cppD03-May-20246.8 KiB217146

bootchart.hD03-May-2024921 3512

builtin_arguments.hD03-May-20241.3 KiB4420

builtins.cppD03-May-202450.8 KiB1,4491,157

builtins.hD03-May-20241.2 KiB4620

capabilities.cppD03-May-20247.1 KiB230175

capabilities.hD03-May-20241.4 KiB5531

check_builtins.cppD03-May-20246.9 KiB247178

check_builtins.hD03-May-20242 KiB4827

compare-bootcharts.pyD03-May-20245.3 KiB14789

debug_ramdisk.hD03-May-2024888 277

devices.cppD03-May-202421.3 KiB592431

devices.hD03-May-20245.2 KiB157101

devices_test.cppD03-May-202413 KiB333253

epoll.cppD03-May-20243.4 KiB10773

epoll.hD03-May-20241.4 KiB6032

epoll_test.cppD03-May-20242 KiB7746

extra_free_kbytes.shD03-May-20244.7 KiB13750

firmware_handler.cppD03-May-202411.7 KiB339266

firmware_handler.hD03-May-20242.2 KiB6939

firmware_handler_test.cppD03-May-20244.4 KiB14598

first_stage_console.cppD03-May-20244.2 KiB139107

first_stage_console.hD03-May-20241,009 3614

first_stage_init.cppD03-May-202416 KiB436320

first_stage_init.hD03-May-2024917 298

first_stage_main.cppD03-May-2024742 224

first_stage_mount.cppD03-May-202429.8 KiB872654

first_stage_mount.hD03-May-2024824 288

fscrypt_init_extensions.cppD03-May-20245.1 KiB154119

fscrypt_init_extensions.hD03-May-2024920 3111

grab-bootchart.shD03-May-2024626 2313

host_builtin_map.pyD03-May-20241.4 KiB4637

host_import_parser.cppD03-May-20241.2 KiB4117

host_import_parser.hD03-May-20241 KiB3614

host_init_stubs.hD03-May-20241.5 KiB6329

host_init_verifier.cppD03-May-202411.8 KiB348281

host_init_verifier.hD03-May-2024847 287

import_parser.cppD03-May-20241.7 KiB5731

import_parser.hD03-May-20241.4 KiB4822

init.cppD03-May-202438 KiB1,063801

init.hD03-May-20241.4 KiB5121

init_test.cppD03-May-20249.2 KiB302214

interface_utils.cppD03-May-20244.4 KiB12489

interface_utils.hD03-May-20241.9 KiB5118

keychords.cppD03-May-20248.5 KiB294240

keychords.hD03-May-20242.4 KiB10059

keychords_test.cppD03-May-20249.6 KiB352266

keyword_map.hD03-May-20242.9 KiB8848

lmkd_service.cppD03-May-20243.8 KiB13288

lmkd_service.hD03-May-20241.3 KiB4517

main.cppD03-May-20242.7 KiB8451

modalias_handler.cppD03-May-20241 KiB3714

modalias_handler.hD03-May-20241.1 KiB4318

mount_handler.cppD03-May-20247.2 KiB210155

mount_handler.hD03-May-20241.6 KiB6032

mount_namespace.cppD03-May-20248.9 KiB226128

mount_namespace.hD03-May-2024981 3310

oneshot_on_test.cppD03-May-20241.7 KiB5020

parser.cppD03-May-20248.2 KiB247185

parser.hD03-May-20243.8 KiB10340

perfboot.pyD03-May-202415.9 KiB463352

persistent_properties.cppD03-May-20249.7 KiB260197

persistent_properties.hD03-May-20241.2 KiB4015

persistent_properties.protoD03-May-2024879 2824

persistent_properties_test.cppD03-May-20245.8 KiB160111

property_service.cppD03-May-202451.7 KiB1,3981,090

property_service.hD03-May-20241.1 KiB4014

property_service.protoD03-May-20241.2 KiB4640

property_service_test.cppD03-May-20245 KiB13092

property_type.cppD03-May-20242.4 KiB8762

property_type.hD03-May-2024867 319

property_type_test.cppD03-May-20243.4 KiB9667

proto_utils.hD03-May-20241.8 KiB6336

reboot.cppD03-May-202443.9 KiB1,122873

reboot.hD03-May-20241.2 KiB3914

reboot_test.cppD03-May-20246.2 KiB197151

reboot_utils.cppD03-May-20247.9 KiB216151

reboot_utils.hD03-May-20241.4 KiB3914

result.hD03-May-2024933 286

rlimit_parser.cppD03-May-20243 KiB8555

rlimit_parser.hD03-May-2024941 3612

rlimit_parser_test.cppD03-May-20245.9 KiB131100

second_stage_resources.hD03-May-20241,007 3311

security.cppD03-May-20247.4 KiB220125

security.hD03-May-20241 KiB3714

selabel.cppD03-May-20242.5 KiB8042

selabel.hD03-May-20241.1 KiB3312

selinux.cppD03-May-202438 KiB1,009698

selinux.hD03-May-20241.4 KiB4110

service.cppD03-May-202430.2 KiB872662

service.hD03-May-20248.8 KiB234169

service_list.cppD03-May-20243.1 KiB10772

service_list.hD03-May-20242.7 KiB9258

service_parser.cppD03-May-202426.7 KiB728589

service_parser.hD03-May-20244.4 KiB10074

service_test.cppD03-May-20246.5 KiB194147

service_utils.cppD03-May-202411.2 KiB331247

service_utils.hD03-May-20242.7 KiB9859

sigchld_handler.cppD03-May-20244.7 KiB13996

sigchld_handler.hD03-May-2024941 3411

snapuserd_transition.cppD03-May-202413.8 KiB429313

snapuserd_transition.hD03-May-20242.9 KiB9740

subcontext.cppD03-May-202412.3 KiB379295

subcontext.hD03-May-20242.2 KiB7343

subcontext.protoD03-May-20241.3 KiB4338

subcontext_benchmark.cppD03-May-20242.1 KiB7244

subcontext_test.cppD03-May-20247.9 KiB246183

switch_root.cppD03-May-20242.9 KiB10161

switch_root.hD03-May-2024784 287

tokenizer.cppD03-May-20242.9 KiB133120

tokenizer.hD03-May-2024954 4118

tokenizer_test.cppD03-May-20245.5 KiB165102

uevent.hD03-May-20241 KiB4220

uevent_handler.hD03-May-2024909 3512

uevent_listener.cppD03-May-20247.4 KiB228164

uevent_listener.hD03-May-20242.1 KiB6937

ueventd.cppD03-May-202415.1 KiB388229

ueventd.hD03-May-2024805 298

ueventd_parser.cppD03-May-202410.5 KiB298222

ueventd_parser.hD03-May-20241.3 KiB4421

ueventd_parser_test.cppD03-May-202413.5 KiB403310

ueventd_test.cppD03-May-20246.3 KiB200151

util.cppD03-May-202425.9 KiB770592

util.hD03-May-20243.5 KiB11065

util_test.cppD03-May-20245.9 KiB175136

README.md

1Android Init Language
2---------------------
3
4The Android Init Language consists of five broad classes of statements:
5Actions, Commands, Services, Options, and Imports.
6
7All of these are line-oriented, consisting of tokens separated by
8whitespace.  The c-style backslash escapes may be used to insert
9whitespace into a token.  Double quotes may also be used to prevent
10whitespace from breaking text into multiple tokens.  The backslash,
11when it is the last character on a line, may be used for line-folding.
12
13Lines which start with a `#` (leading whitespace allowed) are comments.
14
15System properties can be expanded using the syntax
16`${property.name}`. This also works in contexts where concatenation is
17required, such as `import /init.recovery.${ro.hardware}.rc`.
18
19Actions and Services implicitly declare a new section.  All commands
20or options belong to the section most recently declared.  Commands
21or options before the first section are ignored.
22
23Services have unique names.  If a second Service is defined
24with the same name as an existing one, it is ignored and an error
25message is logged.
26
27
28Init .rc Files
29--------------
30The init language is used in plain text files that take the .rc file
31extension.  There are typically multiple of these in multiple
32locations on the system, described below.
33
34`/system/etc/init/hw/init.rc` is the primary .rc file and is loaded by the init executable at the
35beginning of its execution.  It is responsible for the initial set up of the system.
36
37Init loads all of the files contained within the
38`/{system,system_ext,vendor,odm,product}/etc/init/` directories immediately after loading
39the primary `/system/etc/init/hw/init.rc`.  This is explained in more details in the
40[Imports](#imports) section of this file.
41
42Legacy devices without the first stage mount mechanism previously were
43able to import init scripts during mount_all, however that is deprecated
44and not allowed for devices launching after Q.
45
46The intention of these directories is:
47
48   1. /system/etc/init/ is for core system items such as
49      SurfaceFlinger, MediaService, and logd.
50   2. /vendor/etc/init/ is for SoC vendor items such as actions or
51      daemons needed for core SoC functionality.
52   3. /odm/etc/init/ is for device manufacturer items such as
53      actions or daemons needed for motion sensor or other peripheral
54      functionality.
55
56All services whose binaries reside on the system, vendor, or odm
57partitions should have their service entries placed into a
58corresponding init .rc file, located in the /etc/init/
59directory of the partition where they reside.  There is a build
60system macro, LOCAL\_INIT\_RC, that handles this for developers.  Each
61init .rc file should additionally contain any actions associated with
62its service.
63
64An example is the userdebug logcatd.rc and Android.mk files located in the
65system/core/logcat directory.  The LOCAL\_INIT\_RC macro in the
66Android.mk file places logcatd.rc in /system/etc/init/ during the
67build process.  Init loads logcatd.rc during the mount\_all command and
68allows the service to be run and the action to be queued when
69appropriate.
70
71This break up of init .rc files according to their daemon is preferred
72to the previously used monolithic init .rc files.  This approach
73ensures that the only service entries that init reads and the only
74actions that init performs correspond to services whose binaries are in
75fact present on the file system, which was not the case with the
76monolithic init .rc files.  This additionally will aid in merge
77conflict resolution when multiple services are added to the system, as
78each one will go into a separate file.
79
80Versioned RC files within APEXs
81-------------------------------
82
83With the arrival of mainline on Android Q, the individual mainline
84modules carry their own init.rc files within their boundaries. Init
85processes these files according to the naming pattern `/apex/*/etc/*rc`.
86
87Because APEX modules must run on more than one release of Android,
88they may require different parameters as part of the services they
89define. This is achieved, starting in Android T, by incorporating
90the SDK version information in the name of the init file.  The suffix
91is changed from `.rc` to `.#rc` where # is the first SDK where that
92RC file is accepted. An init file specific to SDK=31 might be named
93`init.31rc`. With this scheme, an APEX may include multiple init files. An
94example is appropriate.
95
96For an APEX module with the following files in /apex/sample-module/apex/etc/:
97
98   1. init.rc
99   2. init.32rc
100   4. init.35rc
101
102The selection rule chooses the highest `.#rc` value that does not
103exceed the SDK of the currently running system. The unadorned `.rc`
104is interpreted as sdk=0.
105
106When this APEX is installed on a device with SDK <=31, the system will
107process init.rc.  When installed on a device running SDK 32, 33, or 34,
108it will use init.32rc.  When installed on a device running SDKs >= 35,
109it will choose init.35rc
110
111This versioning scheme is used only for the init files within APEX
112modules; it does not apply to the init files stored in /system/etc/init,
113/vendor/etc/init, or other directories.
114
115This naming scheme is available after Android S.
116
117Actions
118-------
119Actions are named sequences of commands.  Actions have a trigger which
120is used to determine when the action is executed.  When an event
121occurs which matches an action's trigger, that action is added to
122the tail of a to-be-executed queue (unless it is already on the
123queue).
124
125Each action in the queue is dequeued in sequence and each command in
126that action is executed in sequence.  Init handles other activities
127(device creation/destruction, property setting, process restarting)
128"between" the execution of the commands in activities.
129
130Actions take the form of:
131
132    on <trigger> [&& <trigger>]*
133       <command>
134       <command>
135       <command>
136
137Actions are added to the queue and executed based on the order that
138the file that contains them was parsed (see the Imports section), then
139sequentially within an individual file.
140
141For example if a file contains:
142
143    on boot
144       setprop a 1
145       setprop b 2
146
147    on boot && property:true=true
148       setprop c 1
149       setprop d 2
150
151    on boot
152       setprop e 1
153       setprop f 2
154
155Then when the `boot` trigger occurs and assuming the property `true`
156equals `true`, then the order of the commands executed will be:
157
158    setprop a 1
159    setprop b 2
160    setprop c 1
161    setprop d 2
162    setprop e 1
163    setprop f 2
164
165
166Services
167--------
168Services are programs which init launches and (optionally) restarts
169when they exit.  Services take the form of:
170
171    service <name> <pathname> [ <argument> ]*
172       <option>
173       <option>
174       ...
175
176
177Options
178-------
179Options are modifiers to services.  They affect how and when init
180runs the service.
181
182`capabilities [ <capability>\* ]`
183> Set capabilities when exec'ing this service. 'capability' should be a Linux
184  capability without the "CAP\_" prefix, like "NET\_ADMIN" or "SETPCAP". See
185  http://man7.org/linux/man-pages/man7/capabilities.7.html for a list of Linux
186  capabilities.
187  If no capabilities are provided, then all capabilities are removed from this service, even if it
188  runs as root.
189
190`class <name> [ <name>\* ]`
191> Specify class names for the service.  All services in a
192  named class may be started or stopped together.  A service
193  is in the class "default" if one is not specified via the
194  class option. Additional classnames beyond the (required) first
195  one are used to group services.
196  The `animation` class should include all services necessary for both
197  boot animation and shutdown animation. As these services can be
198  launched very early during bootup and can run until the last stage
199  of shutdown, access to /data partition is not guaranteed. These
200  services can check files under /data but it should not keep files opened
201  and should work when /data is not available.
202
203`console [<console>]`
204> This service needs a console. The optional second parameter chooses a
205  specific console instead of the default. The default "/dev/console" can
206  be changed by setting the "androidboot.console" kernel parameter. In
207  all cases the leading "/dev/" should be omitted, so "/dev/tty0" would be
208  specified as just "console tty0".
209  This option connects stdin, stdout, and stderr to the console. It is mutually exclusive with the
210  stdio_to_kmsg option, which only connects stdout and stderr to kmsg.
211
212`critical [window=<fatal crash window mins>] [target=<fatal reboot target>]`
213> This is a device-critical service. If it exits more than four times in
214  _fatal crash window mins_ minutes or before boot completes, the device
215  will reboot into _fatal reboot target_.
216  The default value of _fatal crash window mins_ is 4, and default value
217  of _fatal reboot target_ is 'bootloader'.
218  For tests, the fatal reboot can be skipped by setting property
219  `init.svc_debug.no_fatal.<service-name>` to `true` for specified critical service.
220
221`disabled`
222> This service will not automatically start with its class.
223  It must be explicitly started by name or by interface name.
224
225`enter_namespace <type> <path>`
226> Enters the namespace of type _type_ located at _path_. Only network namespaces are supported with
227  _type_ set to "net". Note that only one namespace of a given _type_ may be entered.
228
229`file <path> <type>`
230> Open a file path and pass its fd to the launched process. _type_ must be
231  "r", "w" or "rw".  For native executables see libcutils
232  android\_get\_control\_file().
233
234`group <groupname> [ <groupname>\* ]`
235> Change to 'groupname' before exec'ing this service.  Additional
236  groupnames beyond the (required) first one are used to set the
237  supplemental groups of the process (via setgroups()).
238  Currently defaults to root.  (??? probably should default to nobody)
239
240`interface <interface name> <instance name>`
241> Associates this service with a list of the AIDL or HIDL services that it provides. The interface
242  name must be a fully-qualified name and not a value name. For instance, this is used to allow
243  servicemanager or hwservicemanager to lazily start services. When multiple interfaces are served,
244  this tag should be used multiple times. An example of an entry for a HIDL
245  interface is `interface vendor.foo.bar@1.0::IBaz default`. For an AIDL interface, use
246  `interface aidl <instance name>`. The instance name for an AIDL interface is
247  whatever is registered with servicemanager, and these can be listed with `adb
248  shell dumpsys -l`.
249
250`ioprio <class> <priority>`
251> Sets the IO priority and IO priority class for this service via the SYS_ioprio_set syscall.
252  _class_ must be one of "rt", "be", or "idle". _priority_ must be an integer in the range 0 - 7.
253
254`keycodes <keycode> [ <keycode>\* ]`
255> Sets the keycodes that will trigger this service. If all of the keys corresponding to the passed
256  keycodes are pressed at once, the service will start. This is typically used to start the
257  bugreport service.
258
259> This option may take a property instead of a list of keycodes. In this case, only one option is
260  provided: the property name in the typical property expansion format. The property must contain
261  a comma separated list of keycode values or the text 'none' to indicate that
262  this service does not respond to keycodes.
263
264> For example, `keycodes ${some.property.name:-none}` where some.property.name expands
265  to "123,124,125". Since keycodes are handled very early in init,
266  only PRODUCT_DEFAULT_PROPERTY_OVERRIDES properties can be used.
267
268`memcg.limit_in_bytes <value>` and `memcg.limit_percent <value>`
269> Sets the child's memory.limit_in_bytes to the minimum of `limit_in_bytes`
270  bytes and `limit_percent` which is interpreted as a percentage of the size
271  of the device's physical memory (only if memcg is mounted).
272  Values must be equal or greater than 0.
273
274`memcg.limit_property <value>`
275> Sets the child's memory.limit_in_bytes to the value of the specified property
276  (only if memcg is mounted). This property will override the values specified
277  via `memcg.limit_in_bytes` and `memcg.limit_percent`.
278
279`memcg.soft_limit_in_bytes <value>`
280> Sets the child's memory.soft_limit_in_bytes to the specified value (only if memcg is mounted),
281  which must be equal or greater than 0.
282
283`memcg.swappiness <value>`
284> Sets the child's memory.swappiness to the specified value (only if memcg is mounted),
285  which must be equal or greater than 0.
286
287`namespace <pid|mnt>`
288> Enter a new PID or mount namespace when forking the service.
289
290`oneshot`
291> Do not restart the service when it exits.
292
293`onrestart`
294> Execute a Command (see below) when service restarts.
295
296`oom_score_adjust <value>`
297> Sets the child's /proc/self/oom\_score\_adj to the specified value,
298  which must range from -1000 to 1000.
299
300`override`
301> Indicates that this service definition is meant to override a previous definition for a service
302  with the same name. This is typically meant for services on /odm to override those defined on
303  /vendor. The last service definition that init parses with this keyword is the service definition
304  will use for this service. Pay close attention to the order in which init.rc files are parsed,
305  since it has some peculiarities for backwards compatibility reasons. The 'imports' section of
306  this file has more details on the order.
307
308`priority <priority>`
309> Scheduling priority of the service process. This value has to be in range
310  -20 to 19. Default priority is 0. Priority is set via setpriority().
311
312`reboot_on_failure <target>`
313> If this process cannot be started or if the process terminates with an exit code other than
314  CLD_EXITED or an status other than '0', reboot the system with the target specified in
315  _target_. _target_ takes the same format as the parameter to sys.powerctl. This is particularly
316  intended to be used with the `exec_start` builtin for any must-have checks during boot.
317
318`restart_period <seconds>`
319> If a non-oneshot service exits, it will be restarted at its start time plus
320  this period. It defaults to 5s to rate limit crashing services.
321  This can be increased for services that are meant to run periodically. For
322  example, it may be set to 3600 to indicate that the service should run every hour
323  or 86400 to indicate that the service should run every day.
324
325`rlimit <resource> <cur> <max>`
326> This applies the given rlimit to the service. rlimits are inherited by child
327  processes, so this effectively applies the given rlimit to the process tree
328  started by this service.
329  It is parsed similarly to the setrlimit command specified below.
330
331`seclabel <seclabel>`
332> Change to 'seclabel' before exec'ing this service.
333  Primarily for use by services run from the rootfs, e.g. ueventd, adbd.
334  Services on the system partition can instead use policy-defined transitions
335  based on their file security context.
336  If not specified and no transition is defined in policy, defaults to the init context.
337
338`setenv <name> <value>`
339> Set the environment variable _name_ to _value_ in the launched process.
340
341`shutdown <shutdown_behavior>`
342> Set shutdown behavior of the service process. When this is not specified,
343  the service is killed during shutdown process by using SIGTERM and SIGKILL.
344  The service with shutdown_behavior of "critical" is not killed during shutdown
345  until shutdown times out. When shutdown times out, even services tagged with
346  "shutdown critical" will be killed. When the service tagged with "shutdown critical"
347  is not running when shut down starts, it will be started.
348
349`sigstop`
350> Send SIGSTOP to the service immediately before exec is called. This is intended for debugging.
351  See the below section on debugging for how this can be used.
352
353`socket <name> <type> <perm> [ <user> [ <group> [ <seclabel> ] ] ]`
354> Create a UNIX domain socket named /dev/socket/_name_ and pass its fd to the
355  launched process.  The socket is created synchronously when the service starts.
356  _type_ must be "dgram", "stream" or "seqpacket".  _type_ may end with "+passcred"
357  to enable SO_PASSCRED on the socket or "+listen" to synchronously make it a listening socket.
358  User and group default to 0.  'seclabel' is the SELinux security context for the
359  socket.  It defaults to the service security context, as specified by
360  seclabel or computed based on the service executable file security context.
361  For native executables see libcutils android\_get\_control\_socket().
362
363`stdio_to_kmsg`
364> Redirect stdout and stderr to /dev/kmsg_debug. This is useful for services that do not use native
365  Android logging during early boot and whose logs messages we want to capture. This is only enabled
366  when /dev/kmsg_debug is enabled, which is only enabled on userdebug and eng builds.
367  This is mutually exclusive with the console option, which additionally connects stdin to the
368  given console.
369
370`task_profiles <profile> [ <profile>\* ]`
371> Set task profiles for the process when it forks. This is designed to replace the use of
372  writepid option for moving a process into a cgroup.
373
374`timeout_period <seconds>`
375> Provide a timeout after which point the service will be killed. The oneshot keyword is respected
376  here, so oneshot services do not automatically restart, however all other services will.
377  This is particularly useful for creating a periodic service combined with the restart_period
378  option described above.
379
380`updatable`
381> Mark that the service can be overridden (via the 'override' option) later in
382  the boot sequence by APEXes. When a service with updatable option is started
383  before APEXes are all activated, the execution is delayed until the activation
384  is finished. A service that is not marked as updatable cannot be overridden by
385  APEXes.
386
387`user <username>`
388> Change to 'username' before exec'ing this service.
389  Currently defaults to root.  (??? probably should default to nobody)
390  As of Android M, processes should use this option even if they
391  require Linux capabilities.  Previously, to acquire Linux
392  capabilities, a process would need to run as root, request the
393  capabilities, then drop to its desired uid.  There is a new
394  mechanism through fs\_config that allows device manufacturers to add
395  Linux capabilities to specific binaries on a file system that should
396  be used instead. This mechanism is described on
397  <http://source.android.com/devices/tech/config/filesystem.html>.  When
398  using this new mechanism, processes can use the user option to
399  select their desired uid without ever running as root.
400  As of Android O, processes can also request capabilities directly in their .rc
401  files. See the "capabilities" option below.
402
403`writepid <file> [ <file>\* ]`
404> Write the child's pid to the given files when it forks. Meant for
405  cgroup/cpuset usage. If no files under /dev/cpuset/ are specified, but the
406  system property 'ro.cpuset.default' is set to a non-empty cpuset name (e.g.
407  '/foreground'), then the pid is written to file /dev/cpuset/_cpuset\_name_/tasks.
408  The use of this option for moving a process into a cgroup is obsolete. Please
409  use task_profiles option instead.
410
411
412Triggers
413--------
414Triggers are strings which can be used to match certain kinds of
415events and used to cause an action to occur.
416
417Triggers are subdivided into event triggers and property triggers.
418
419Event triggers are strings triggered by the 'trigger' command or by
420the QueueEventTrigger() function within the init executable.  These
421take the form of a simple string such as 'boot' or 'late-init'.
422
423Property triggers are strings triggered when a named property changes
424value to a given new value or when a named property changes value to
425any new value.  These take the form of 'property:<name>=<value>' and
426'property:<name>=\*' respectively.  Property triggers are additionally
427evaluated and triggered accordingly during the initial boot phase of
428init.
429
430An Action can have multiple property triggers but may only have one
431event trigger.
432
433For example:
434`on boot && property:a=b` defines an action that is only executed when
435the 'boot' event trigger happens and the property a equals b.
436
437`on property:a=b && property:c=d` defines an action that is executed
438at three times:
439
440   1. During initial boot if property a=b and property c=d.
441   2. Any time that property a transitions to value b, while property c already equals d.
442   3. Any time that property c transitions to value d, while property a already equals b.
443
444
445Trigger Sequence
446----------------
447
448Init uses the following sequence of triggers during early boot. These are the
449built-in triggers defined in init.cpp.
450
451   1. `early-init` - The first in the sequence, triggered after cgroups has been configured
452      but before ueventd's coldboot is complete.
453   2. `init` - Triggered after coldboot is complete.
454   3. `charger` - Triggered if `ro.bootmode == "charger"`.
455   4. `late-init` - Triggered if `ro.bootmode != "charger"`, or via healthd triggering a boot
456      from charging mode.
457
458Remaining triggers are configured in `init.rc` and are not built-in. The default sequence for
459these is specified under the "on late-init" event in `init.rc`. Actions internal to `init.rc`
460have been omitted.
461
462   1. `early-fs` - Start vold.
463   2. `fs` - Vold is up. Mount partitions not marked as first-stage or latemounted.
464   3. `post-fs` - Configure anything dependent on early mounts.
465   4. `late-fs` - Mount partitions marked as latemounted.
466   5. `post-fs-data` - Mount and configure `/data`; set up encryption. `/metadata` is
467      reformatted here if it couldn't mount in first-stage init.
468   6. `zygote-start` - Start the zygote.
469   7. `early-boot` - After zygote has started.
470   8. `boot` - After `early-boot` actions have completed.
471
472Commands
473--------
474
475`bootchart [start|stop]`
476> Start/stop bootcharting. These are present in the default init.rc files,
477  but bootcharting is only active if the file /data/bootchart/enabled exists;
478  otherwise bootchart start/stop are no-ops.
479
480`chmod <octal-mode> <path>`
481> Change file access permissions.
482
483`chown <owner> <group> <path>`
484> Change file owner and group.
485
486`class_start <serviceclass>`
487> Start all services of the specified class if they are
488  not already running.  See the start entry for more information on
489  starting services.
490
491`class_stop <serviceclass>`
492> Stop and disable all services of the specified class if they are
493  currently running.
494
495`class_reset <serviceclass>`
496> Stop all services of the specified class if they are
497  currently running, without disabling them. They can be restarted
498  later using `class_start`.
499
500`class_restart [--only-enabled] <serviceclass>`
501> Restarts all services of the specified class. If `--only-enabled` is
502  specified, then disabled services are skipped.
503
504`copy <src> <dst>`
505> Copies a file. Similar to write, but useful for binary/large
506  amounts of data.
507  Regarding to the src file, copying from symbolic link file and world-writable
508  or group-writable files are not allowed.
509  Regarding to the dst file, the default mode created is 0600 if it does not
510  exist. And it will be truncated if dst file is a normal regular file and
511  already exists.
512
513`copy_per_line <src> <dst>`
514> Copies a file line by line. Similar to copy, but useful for dst is a sysfs node
515  that doesn't handle multiple lines of data.
516
517`domainname <name>`
518> Set the domain name.
519
520`enable <servicename>`
521> Turns a disabled service into an enabled one as if the service did not
522  specify disabled.
523  If the service is supposed to be running, it will be started now.
524  Typically used when the bootloader sets a variable that indicates a specific
525  service should be started when needed. E.g.
526
527    on property:ro.boot.myfancyhardware=1
528        enable my_fancy_service_for_my_fancy_hardware
529
530`exec [ <seclabel> [ <user> [ <group>\* ] ] ] -- <command> [ <argument>\* ]`
531> Fork and execute command with the given arguments. The command starts
532  after "--" so that an optional security context, user, and supplementary
533  groups can be provided. No other commands will be run until this one
534  finishes. _seclabel_ can be a - to denote default. Properties are expanded
535  within _argument_.
536  Init halts executing commands until the forked process exits.
537
538`exec_background [ <seclabel> [ <user> [ <group>\* ] ] ] -- <command> [ <argument>\* ]`
539> Fork and execute command with the given arguments. This is handled similarly
540  to the `exec` command. The difference is that init does not halt executing
541  commands until the process exits for `exec_background`.
542
543`exec_start <service>`
544> Start a given service and halt the processing of additional init commands
545  until it returns.  The command functions similarly to the `exec` command,
546  but uses an existing service definition in place of the exec argument vector.
547
548`export <name> <value>`
549> Set the environment variable _name_ equal to _value_ in the
550  global environment (which will be inherited by all processes
551  started after this command is executed)
552
553`hostname <name>`
554> Set the host name.
555
556`ifup <interface>`
557> Bring the network interface _interface_ online.
558
559`insmod [-f] <path> [<options>]`
560> Install the module at _path_ with the specified options.
561  -f: force installation of the module even if the version of the running kernel
562  and the version of the kernel for which the module was compiled do not match.
563
564`interface_start <name>` \
565`interface_restart <name>` \
566`interface_stop <name>`
567> Find the service that provides the interface _name_ if it exists and run the `start`, `restart`,
568or `stop` commands on it respectively.  _name_ may be either a fully qualified HIDL name, in which
569case it is specified as `<interface>/<instance>`, or an AIDL name, in which case it is specified as
570`aidl/<interface>` for example `android.hardware.secure_element@1.1::ISecureElement/eSE1` or
571`aidl/aidl_lazy_test_1`.
572
573> Note that these commands only act on interfaces specified by the `interface` service option, not
574on interfaces registered at runtime.
575
576> Example usage of these commands: \
577`interface_start android.hardware.secure_element@1.1::ISecureElement/eSE1`
578will start the HIDL Service that provides the `android.hardware.secure_element@1.1` and `eSI1`
579instance. \
580`interface_start aidl/aidl_lazy_test_1` will start the AIDL service that
581provides the `aidl_lazy_test_1` interface.
582
583`load_exports <path>`
584> Open the file at _path_ and export global environment variables declared
585  there. Each line must be in the format `export <name> <value>`, as described
586  above.
587
588`load_system_props`
589> (This action is deprecated and no-op.)
590
591`load_persist_props`
592> Loads persistent properties when /data has been decrypted.
593  This is included in the default init.rc.
594
595`loglevel <level>`
596> Sets init's log level to the integer level, from 7 (all logging) to 0
597  (fatal logging only). The numeric values correspond to the kernel log
598  levels, but this command does not affect the kernel log level. Use the
599  `write` command to write to `/proc/sys/kernel/printk` to change that.
600  Properties are expanded within _level_.
601
602`mark_post_data`
603> Used to mark the point right after /data is mounted.
604
605`mkdir <path> [<mode>] [<owner>] [<group>] [encryption=<action>] [key=<key>]`
606> Create a directory at _path_, optionally with the given mode, owner, and
607  group. If not provided, the directory is created with permissions 755 and
608  owned by the root user and root group. If provided, the mode, owner and group
609  will be updated if the directory exists already.
610
611 > _action_ can be one of:
612  * `None`: take no encryption action; directory will be encrypted if parent is.
613  * `Require`: encrypt directory, abort boot process if encryption fails
614  * `Attempt`: try to set an encryption policy, but continue if it fails
615  * `DeleteIfNecessary`: recursively delete directory if necessary to set
616  encryption policy.
617
618  > _key_ can be one of:
619  * `ref`: use the systemwide DE key
620  * `per_boot_ref`: use the key freshly generated on each boot.
621
622`mount_all [ <fstab> ] [--<option>]`
623> Calls fs\_mgr\_mount\_all on the given fs\_mgr-format fstab with optional
624  options "early" and "late".
625  With "--early" set, the init executable will skip mounting entries with
626  "latemount" flag and triggering fs encryption state event. With "--late" set,
627  init executable will only mount entries with "latemount" flag. By default,
628  no option is set, and mount\_all will process all entries in the given fstab.
629  If the fstab parameter is not specified, fstab.${ro.boot.fstab_suffix},
630  fstab.${ro.hardware} or fstab.${ro.hardware.platform} will be scanned for
631  under /odm/etc, /vendor/etc, or / at runtime, in that order.
632
633`mount <type> <device> <dir> [ <flag>\* ] [<options>]`
634> Attempt to mount the named device at the directory _dir_
635  _flag_s include "ro", "rw", "remount", "noatime", ...
636  _options_ include "barrier=1", "noauto\_da\_alloc", "discard", ... as
637  a comma separated string, e.g. barrier=1,noauto\_da\_alloc
638
639`perform_apex_config`
640> Performs tasks after APEXes are mounted. For example, creates data directories
641  for the mounted APEXes, parses config file(s) from them, and updates linker
642  configurations. Intended to be used only once when apexd notifies the mount
643  event by setting `apexd.status` to ready.
644
645`restart [--only-if-running] <service>`
646> Stops and restarts a running service, does nothing if the service is currently
647  restarting, otherwise, it just starts the service. If "--only-if-running" is
648  specified, the service is only restarted if it is already running.
649
650`restorecon <path> [ <path>\* ]`
651> Restore the file named by _path_ to the security context specified
652  in the file\_contexts configuration.
653  Not required for directories created by the init.rc as these are
654  automatically labeled correctly by init.
655
656`restorecon_recursive <path> [ <path>\* ]`
657> Recursively restore the directory tree named by _path_ to the
658  security contexts specified in the file\_contexts configuration.
659
660`rm <path>`
661> Calls unlink(2) on the given path. You might want to
662  use "exec -- rm ..." instead (provided the system partition is
663  already mounted).
664
665`rmdir <path>`
666> Calls rmdir(2) on the given path.
667
668`readahead <file|dir> [--fully]`
669> Calls readahead(2) on the file or files within given directory.
670  Use option --fully to read the full file content.
671
672`setprop <name> <value>`
673> Set system property _name_ to _value_. Properties are expanded
674  within _value_.
675
676`setrlimit <resource> <cur> <max>`
677> Set the rlimit for a resource. This applies to all processes launched after
678  the limit is set. It is intended to be set early in init and applied globally.
679  _resource_ is best specified using its text representation ('cpu', 'rtio', etc
680  or 'RLIM_CPU', 'RLIM_RTIO', etc). It also may be specified as the int value
681  that the resource enum corresponds to.
682  _cur_ and _max_ can be 'unlimited' or '-1' to indicate an infinite rlimit.
683
684`start <service>`
685> Start a service running if it is not already running.
686  Note that this is _not_ synchronous, and even if it were, there is
687  no guarantee that the operating system's scheduler will execute the
688  service sufficiently to guarantee anything about the service's status.
689  See the `exec_start` command for a synchronous version of `start`.
690
691> This creates an important consequence that if the service offers
692  functionality to other services, such as providing a
693  communication channel, simply starting this service before those
694  services is _not_ sufficient to guarantee that the channel has
695  been set up before those services ask for it.  There must be a
696  separate mechanism to make any such guarantees.
697
698`stop <service>`
699> Stop a service from running if it is currently running.
700
701`swapon_all [ <fstab> ]`
702> Calls fs\_mgr\_swapon\_all on the given fstab file.
703  If the fstab parameter is not specified, fstab.${ro.boot.fstab_suffix},
704  fstab.${ro.hardware} or fstab.${ro.hardware.platform} will be scanned for
705  under /odm/etc, /vendor/etc, or / at runtime, in that order.
706
707`symlink <target> <path>`
708> Create a symbolic link at _path_ with the value _target_
709
710`sysclktz <minutes_west_of_gmt>`
711> Set the system clock base (0 if system clock ticks in GMT)
712
713`trigger <event>`
714> Trigger an event.  Used to queue an action from another
715  action.
716
717`umount <path>`
718> Unmount the filesystem mounted at that path.
719
720`umount_all [ <fstab> ]`
721> Calls fs\_mgr\_umount\_all on the given fstab file.
722  If the fstab parameter is not specified, fstab.${ro.boot.fstab_suffix},
723  fstab.${ro.hardware} or fstab.${ro.hardware.platform} will be scanned for
724  under /odm/etc, /vendor/etc, or / at runtime, in that order.
725
726`verity_update_state`
727> Internal implementation detail used to update dm-verity state and
728  set the partition._mount-point_.verified properties used by adb remount
729  because fs\_mgr can't set them directly itself. This is required since
730  Android 12, because CtsNativeVerifiedBootTestCases will read property
731  "partition.${partition}.verified.hash_alg" to check that sha1 is not used.
732  See https://r.android.com/1546980 for more details.
733
734`wait <path> [ <timeout> ]`
735> Poll for the existence of the given file and return when found,
736  or the timeout has been reached. If timeout is not specified it
737  currently defaults to five seconds. The timeout value can be
738  fractional seconds, specified in floating point notation.
739
740`wait_for_prop <name> <value>`
741> Wait for system property _name_ to be _value_. Properties are expanded
742  within _value_. If property _name_ is already set to _value_, continue
743  immediately.
744
745`write <path> <content>`
746> Open the file at _path_ and write a string to it with write(2).
747  If the file does not exist, it will be created. If it does exist,
748  it will be truncated. Properties are expanded within _content_.
749
750
751Imports
752-------
753`import <path>`
754> Parse an init config file, extending the current configuration.
755  If _path_ is a directory, each file in the directory is parsed as
756  a config file. It is not recursive, nested directories will
757  not be parsed.
758
759The import keyword is not a command, but rather its own section,
760meaning that it does not happen as part of an Action, but rather,
761imports are handled as a file is being parsed and follow the below logic.
762
763There are only three times where the init executable imports .rc files:
764
765   1. When it imports `/system/etc/init/hw/init.rc` or the script indicated by the property
766      `ro.boot.init_rc` during initial boot.
767   2. When it imports `/{system,system_ext,vendor,odm,product}/etc/init/` immediately after
768      importing `/system/etc/init/hw/init.rc`.
769   3. (Deprecated) When it imports /{system,vendor,odm}/etc/init/ or .rc files
770      at specified paths during mount_all, not allowed for devices launching
771      after Q.
772
773The order that files are imported is a bit complex for legacy reasons.  The below is guaranteed:
774
7751. `/system/etc/init/hw/init.rc` is parsed then recursively each of its imports are
776   parsed.
7772. The contents of `/system/etc/init/` are alphabetized and parsed sequentially, with imports
778   happening recursively after each file is parsed.
7793. Step 2 is repeated for `/system_ext/etc/init`, `/vendor/etc/init`, `/odm/etc/init`,
780   `/product/etc/init`
781
782The below pseudocode may explain this more clearly:
783
784    fn Import(file)
785      Parse(file)
786      for (import : file.imports)
787        Import(import)
788
789    Import(/system/etc/init/hw/init.rc)
790    Directories = [/system/etc/init, /system_ext/etc/init, /vendor/etc/init, /odm/etc/init, /product/etc/init]
791    for (directory : Directories)
792      files = <Alphabetical order of directory's contents>
793      for (file : files)
794        Import(file)
795
796Actions are executed in the order that they are parsed.  For example the `post-fs-data` action(s)
797in `/system/etc/init/hw/init.rc` are always the first `post-fs-data` action(s) to be executed in
798order of how they appear in that file.  Then the `post-fs-data` actions of the imports of
799`/system/etc/init/hw/init.rc` in the order that they're imported, etc.
800
801Properties
802----------
803Init provides state information with the following properties.
804
805`init.svc.<name>`
806> State of a named service ("stopped", "stopping", "running", "restarting")
807
808`dev.mnt.dev.<mount_point>`, `dev.mnt.blk.<mount_point>`, `dev.mnt.rootdisk.<mount_point>`
809> Block device base name associated with a *mount_point*.
810  The *mount_point* has / replaced by . and if referencing the root mount point
811  "/", it will use "/root".
812  `dev.mnt.dev.<mount_point>` indicates a block device attached to filesystems.
813    (e.g., dm-N or sdaN/mmcblk0pN to access `/sys/fs/ext4/${dev.mnt.dev.<mount_point>}/`)
814
815  `dev.mnt.blk.<mount_point>` indicates the disk partition to the above block device.
816    (e.g., sdaN / mmcblk0pN to access `/sys/class/block/${dev.mnt.blk.<mount_point>}/`)
817
818  `dev.mnt.rootdisk.<mount_point>` indicates the root disk to contain the above disk partition.
819    (e.g., sda / mmcblk0 to access `/sys/class/block/${dev.mnt.rootdisk.<mount_point>}/queue`)
820
821Init responds to properties that begin with `ctl.`.  These properties take the format of
822`ctl.[<target>_]<command>` and the _value_ of the system property is used as a parameter.  The
823_target_ is optional and specifies the service option that _value_ is meant to match with.  There is
824only one option for _target_, `interface` which indicates that _value_ will refer to an interface
825that a service provides and not the service name itself.
826
827For example:
828
829`SetProperty("ctl.start", "logd")` will run the `start` command on `logd`.
830
831`SetProperty("ctl.interface_start", "aidl/aidl_lazy_test_1")` will run the `start` command on the
832service that exposes the `aidl aidl_lazy_test_1` interface.
833
834Note that these
835properties are only settable; they will have no value when read.
836
837The _commands_ are listed below.
838
839`start` \
840`restart` \
841`stop` \
842These are equivalent to using the `start`, `restart`, and `stop` commands on the service specified
843by the _value_ of the property.
844
845`oneshot_on` and `oneshot_off` will turn on or off the _oneshot_
846flag for the service specified by the _value_ of the property.  This is
847particularly intended for services that are conditionally lazy HALs.  When
848they are lazy HALs, oneshot must be on, otherwise oneshot should be off.
849
850`sigstop_on` and `sigstop_off` will turn on or off the _sigstop_ feature for the service
851specified by the _value_ of the property.  See the _Debugging init_ section below for more details
852about this feature.
853
854Boot timing
855-----------
856Init records some boot timing information in system properties.
857
858`ro.boottime.init`
859> Time after boot in ns (via the CLOCK\_BOOTTIME clock) at which the first
860  stage of init started.
861
862`ro.boottime.init.first_stage`
863> How long in ns it took to run first stage.
864
865`ro.boottime.init.selinux`
866> How long in ns it took to run SELinux stage.
867
868`ro.boottime.init.modules`
869> How long in ms it took to load kernel modules.
870
871`ro.boottime.init.cold_boot_wait`
872> How long init waited for ueventd's coldboot phase to end.
873
874`ro.boottime.<service-name>`
875> Time after boot in ns (via the CLOCK\_BOOTTIME clock) that the service was
876  first started.
877
878
879Bootcharting
880------------
881This version of init contains code to perform "bootcharting": generating log
882files that can be later processed by the tools provided by <http://www.bootchart.org/>.
883
884On the emulator, use the -bootchart _timeout_ option to boot with bootcharting
885activated for _timeout_ seconds.
886
887On a device:
888
889    adb shell 'touch /data/bootchart/enabled'
890
891Don't forget to delete this file when you're done collecting data!
892
893The log files are written to /data/bootchart/. A script is provided to
894retrieve them and create a bootchart.tgz file that can be used with the
895bootchart command-line utility:
896
897    sudo apt-get install pybootchartgui
898    # grab-bootchart.sh uses $ANDROID_SERIAL.
899    $ANDROID_BUILD_TOP/system/core/init/grab-bootchart.sh
900
901One thing to watch for is that the bootchart will show init as if it started
902running at 0s. You'll have to look at dmesg to work out when the kernel
903actually started init.
904
905
906Comparing two bootcharts
907------------------------
908A handy script named compare-bootcharts.py can be used to compare the
909start/end time of selected processes. The aforementioned grab-bootchart.sh
910will leave a bootchart tarball named bootchart.tgz at /tmp/android-bootchart.
911If two such tarballs are preserved on the host machine under different
912directories, the script can list the timestamps differences. For example:
913
914Usage: system/core/init/compare-bootcharts.py _base-bootchart-dir_ _exp-bootchart-dir_
915
916    process: baseline experiment (delta) - Unit is ms (a jiffy is 10 ms on the system)
917    ------------------------------------
918    /init: 50 40 (-10)
919    /system/bin/surfaceflinger: 4320 4470 (+150)
920    /system/bin/bootanimation: 6980 6990 (+10)
921    zygote64: 10410 10640 (+230)
922    zygote: 10410 10640 (+230)
923    system_server: 15350 15150 (-200)
924    bootanimation ends at: 33790 31230 (-2560)
925
926
927Systrace
928--------
929Systrace (<http://developer.android.com/tools/help/systrace.html>) can be
930used for obtaining performance analysis reports during boot
931time on userdebug or eng builds.
932
933Here is an example of trace events of "wm" and "am" categories:
934
935    $ANDROID_BUILD_TOP/external/chromium-trace/systrace.py \
936          wm am --boot
937
938This command will cause the device to reboot. After the device is rebooted and
939the boot sequence has finished, the trace report is obtained from the device
940and written as trace.html on the host by hitting Ctrl+C.
941
942Limitation: recording trace events is started after persistent properties are loaded, so
943the trace events that are emitted before that are not recorded. Several
944services such as vold, surfaceflinger, and servicemanager are affected by this
945limitation since they are started before persistent properties are loaded.
946Zygote initialization and the processes that are forked from the zygote are not
947affected.
948
949
950Debugging init
951--------------
952When a service starts from init, it may fail to `execv()` the service. This is not typical, and may
953point to an error happening in the linker as the new service is started. The linker in Android
954prints its logs to `logd` and `stderr`, so they are visible in `logcat`. If the error is encountered
955before it is possible to access `logcat`, the `stdio_to_kmsg` service option may be used to direct
956the logs that the linker prints to `stderr` to `kmsg`, where they can be read via a serial port.
957
958Launching init services without init is not recommended as init sets up a significant amount of
959environment (user, groups, security label, capabilities, etc) that is hard to replicate manually.
960
961If it is required to debug a service from its very start, the `sigstop` service option is added.
962This option will send SIGSTOP to a service immediately before calling exec. This gives a window
963where developers can attach a debugger, strace, etc before continuing the service with SIGCONT.
964
965This flag can also be dynamically controlled via the ctl.sigstop_on and ctl.sigstop_off properties.
966
967Below is an example of dynamically debugging logd via the above:
968
969    stop logd
970    setprop ctl.sigstop_on logd
971    start logd
972    ps -e | grep logd
973    > logd          4343     1   18156   1684 do_signal_stop 538280 T init
974    gdbclient.py -p 4343
975    b main
976    c
977    c
978    c
979    > Breakpoint 1, main (argc=1, argv=0x7ff8c9a488) at system/core/logd/main.cpp:427
980
981Below is an example of doing the same but with strace
982
983    stop logd
984    setprop ctl.sigstop_on logd
985    start logd
986    ps -e | grep logd
987    > logd          4343     1   18156   1684 do_signal_stop 538280 T init
988    strace -p 4343
989
990    (From a different shell)
991    kill -SIGCONT 4343
992
993    > strace runs
994
995Host Init Script Verification
996-----------------------------
997
998Init scripts are checked for correctness during build time. Specifically the below is checked.
999
10001) Well formatted action, service and import sections, e.g. no actions without a preceding 'on'
1001line, and no extraneous lines after an 'import' statement.
10022) All commands map to a valid keyword and the argument count is within the correct range.
10033) All service options are valid. This is stricter than how commands are checked as the service
1004options' arguments are fully parsed, e.g. UIDs and GIDs must resolve.
1005
1006There are other parts of init scripts that are only parsed at runtime and therefore not checked
1007during build time, among them are the below.
1008
10091) The validity of the arguments of commands, e.g. no checking if file paths actually exist, if
1010SELinux would permit the operation, or if the UIDs and GIDs resolve.
10112) No checking if a service exists or has a valid SELinux domain defined
10123) No checking if a service has not been previously defined in a different init script.
1013
1014Early Init Boot Sequence
1015------------------------
1016The early init boot sequence is broken up into three stages: first stage init, SELinux setup, and
1017second stage init.
1018
1019First stage init is responsible for setting up the bare minimum requirements to load the rest of the
1020system. Specifically this includes mounting /dev, /proc, mounting 'early mount' partitions (which
1021needs to include all partitions that contain system code, for example system and vendor), and moving
1022the system.img mount to / for devices with a ramdisk.
1023
1024Note that in Android Q, system.img always contains TARGET_ROOT_OUT and always is mounted at / by the
1025time first stage init finishes. Android Q will also require dynamic partitions and therefore will
1026require using a ramdisk to boot Android. The recovery ramdisk can be used to boot to Android instead
1027of a dedicated ramdisk as well.
1028
1029First stage init has three variations depending on the device configuration:
10301) For system-as-root devices, first stage init is part of /system/bin/init and a symlink at /init
1031points to /system/bin/init for backwards compatibility. These devices do not need to do anything to
1032mount system.img, since it is by definition already mounted as the rootfs by the kernel.
1033
10342) For devices with a ramdisk, first stage init is a static executable located at /init. These
1035devices mount system.img as /system then perform a switch root operation to move the mount at
1036/system to /. The contents of the ramdisk are freed after mounting has completed.
1037
10383) For devices that use recovery as a ramdisk, first stage init it contained within the shared init
1039located at /init within the recovery ramdisk. These devices first switch root to
1040/first_stage_ramdisk to remove the recovery components from the environment, then proceed the same
1041as 2). Note that the decision to boot normally into Android instead of booting
1042into recovery mode is made if androidboot.force_normal_boot=1 is present in the
1043kernel commandline, or in bootconfig with Android S and later.
1044
1045Once first stage init finishes it execs /system/bin/init with the "selinux_setup" argument. This
1046phase is where SELinux is optionally compiled and loaded onto the system. selinux.cpp contains more
1047information on the specifics of this process.
1048
1049Lastly once that phase finishes, it execs /system/bin/init again with the "second_stage"
1050argument. At this point the main phase of init runs and continues the boot process via the init.rc
1051scripts.
1052

README.ueventd.md

1# Ueventd
2-------
3Ueventd manages `/dev`, sets permissions for `/sys`, and handles firmware uevents. It has default
4behavior described below, along with a scripting language that allows customizing this behavior,
5built on the same parser as init.
6
7Ueventd has one generic customization parameter, the size of rcvbuf_size for the ueventd socket. It
8is customized by the `uevent_socket_rcvbuf_size` parameter, which takes the format of
9
10    uevent_socket_rcvbuf_size <size>
11For example
12
13    uevent_socket_rcvbuf_size 16M
14Sets the uevent socket rcvbuf_size to 16 megabytes.
15
16## Importing configuration files
17--------------------------------
18Ueventd reads /system/etc/ueventd.rc, all other files are imported via the `import` command, which
19takes the format of
20
21    import <path>
22This command parses an ueventd config file, extending the current configuration.  If _path_ is a
23directory, each file in the directory is parsed as a config file. It is not recursive, nested
24directories will not be parsed.  Imported files are parsed after the current file has been parsed.
25
26## /dev
27----
28Ueventd listens to the kernel uevent sockets and creates/deletes nodes in `/dev` based on the
29incoming add/remove uevents. It defaults to using `0600` mode and `root` user/group. It always
30creates the nodes with the SELabel from the current loaded SEPolicy. It has three default behaviors
31for the node path:
32
33  1. Block devices are created as `/dev/block/<basename uevent DEVPATH>`. There are symlinks created
34     to this node at `/dev/block/<type>/<parent device>/<basename uevent DEVPATH>`,
35     `/dev/block/<type>/<parent device>/by-name/<uevent PARTNAME>`, and `/dev/block/by-name/<uevent
36     PARTNAME>` if the device is a boot device.
37  2. USB devices are created as `/dev/<uevent DEVNAME>` if `DEVNAME` was specified for the uevent,
38     otherwise as `/dev/bus/usb/<bus_id>/<device_id>` where `bus_id` is `uevent MINOR / 128 + 1` and
39     `device_id` is `uevent MINOR % 128 + 1`.
40  3. All other devices are created as `/dev/<basename uevent DEVPATH>`
41
42The permissions can be modified using a ueventd.rc script and a line that beings with `/dev`. These
43lines take the format of
44
45    devname mode uid gid [options]
46For example
47
48    /dev/null 0666 root root
49When `/dev/null` is created, its mode will be set to `0666`, its user to `root` and its group to
50`root`.
51
52The path can be modified using a ueventd.rc script and a `subsystem` section. There are three to set
53for a subsystem: the subsystem name, which device name to use, and which directory to place the
54device in. The section takes the below format of
55
56    subsystem <subsystem_name>
57      devname uevent_devname|uevent_devpath
58      [dirname <directory>]
59
60`subsystem_name` is used to match uevent `SUBSYSTEM` value
61
62`devname` takes one of two options
63  1. `uevent_devname` specifies that the name of the node will be the uevent `DEVNAME`
64  2. `uevent_devpath` specified that the name of the node will be basename uevent `DEVPATH`
65
66`dirname` is an optional parameter that specifies a directory within `/dev` where the node will be
67created.
68
69For example
70
71    subsystem sound
72      devname uevent_devpath
73      dirname /dev/snd
74Indicates that all uevents with `SUBSYSTEM=sound` will create nodes as `/dev/snd/<basename uevent
75DEVPATH>`.
76
77## /sys
78----
79Ueventd by default takes no action for `/sys`, however it can be instructed to set permissions for
80certain files in `/sys` when matching uevents are generated. This is done using a ueventd.rc script
81and a line that begins with `/sys`. These lines take the format of
82
83    nodename attr mode uid gid [options]
84For example
85
86    /sys/devices/system/cpu/cpu* cpufreq/scaling_max_freq 0664 system system
87When a uevent that matches the pattern `/sys/devices/system/cpu/cpu*` is sent, the matching sysfs
88attribute, `cpufreq/scaling_max_freq`, will have its mode set to `0664`, its user to to `system` and
89its group set to `system`.
90
91## Path matching
92----------------
93The path for a `/dev` or `/sys` entry can contain a `*` anywhere in the path.
941. If the only `*` appears at the end of the string or if the _options_ parameter is set to
95`no_fnm_pathname`, ueventd matches the entry by `fnmatch(entry_path, incoming_path, 0)`
962. Otherwise, ueventd matches the entry by `fnmatch(entry_path, incoming_path, FNM_PATHNAME)`
97
98See the [man page for fnmatch](https://www.man7.org/linux/man-pages/man3/fnmatch.3.html) for more
99details.
100
101## Firmware loading
102----------------
103Ueventd by default serves firmware requests by searching through a list of firmware directories
104for a file matching the uevent `FIRMWARE`. It then forks a process to serve this firmware to the
105kernel.
106
107`/apex/*/etc/firmware` is also searched after a list of firmware directories.
108
109The list of firmware directories is customized by a `firmware_directories` line in a ueventd.rc
110file. This line takes the format of
111
112    firmware_directories <firmware_directory> [ <firmware_directory> ]*
113For example
114
115    firmware_directories /etc/firmware/ /odm/firmware/ /vendor/firmware/ /firmware/image/
116Adds those 4 directories, in that order to the list of firmware directories that will be tried by
117ueventd. Note that this option always accumulates to the list; it is not possible to remove previous
118entries.
119
120Ueventd will wait until after `post-fs` in init, to keep retrying before believing the firmwares are
121not present.
122
123The exact firmware file to be served can be customized by running an external program by a
124`external_firmware_handler` line in a ueventd.rc file. This line takes the format of
125
126    external_firmware_handler <devpath> <user [group]> <path to external program>
127
128The handler will be run as the given user, or if a group is provided, as the given user and group.
129
130For example
131
132    external_firmware_handler /devices/leds/red/firmware/coeffs.bin system /vendor/bin/led_coeffs.bin
133Will launch `/vendor/bin/led_coeffs.bin` as the system user instead of serving the default firmware
134for `/devices/leds/red/firmware/coeffs.bin`.
135
136The `devpath` argument may include asterisks (`*`) to match multiple paths. For example, the string
137`/dev/*/red` will match `/dev/leds/red` as well as `/dev/lights/red`. The pattern matching follows
138the rules of the fnmatch() function.
139
140Ueventd will provide the uevent `DEVPATH` and `FIRMWARE` to this external program on the environment
141via environment variables with the same names. Ueventd will use the string written to stdout as the
142new name of the firmware to load. It will still look for the new firmware in the list of firmware
143directories stated above. It will also reject file names with `..` in them, to prevent leaving these
144directories. If stdout cannot be read, or the program returns with any exit code other than
145`EXIT_SUCCESS`, or the program crashes, the default firmware from the uevent will be loaded.
146
147Ueventd will additionally log all messages sent to stderr from the external program to the serial
148console after the external program has exited.
149
150If the kernel command-line argument `firmware_class.path` is set, this path
151will be used first by the kernel to search for the firmware files. If found,
152ueventd will not be called at all. See the
153[kernel documentation](https://www.kernel.org/doc/html/v5.10/driver-api/firmware/fw_search_path.html)
154for more details on this feature.
155
156## Coldboot
157--------
158Ueventd must create devices in `/dev` for all devices that have already sent their uevents before
159ueventd has started. To do so, when ueventd is started it does what it calls a 'coldboot' on `/sys`,
160in which it writes 'add' to every 'uevent' file that it finds in `/sys/class`, `/sys/block`, and
161`/sys/devices`. This causes the kernel to regenerate the uevents for these paths, and thus for
162ueventd to create the nodes.
163
164For boot time purposes, this is done in parallel across a set of child processes. `ueventd.cpp` in
165this directory contains documentation on how the parallelization is done.
166
167There is an option to parallelize the restorecon function during cold boot as well. It is
168recommended that devices use genfscon for labeling sysfs nodes. However, some devices may benefit
169from enabling the parallelization option:
170
171    parallel_restorecon enabled
172
173Do parallel restorecon to speed up boot process, subdirectories under `/sys`
174can be sliced by ueventd.rc, and run on multiple process.
175    parallel_restorecon_dir <directory>
176
177For example
178    parallel_restorecon_dir /sys
179    parallel_restorecon_dir /sys/devices
180    parallel_restorecon_dir /sys/devices/platform
181    parallel_restorecon_dir /sys/devices/platform/soc
182