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