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