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