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