README.md revision 132ac31b4738094e62cc1744e75f3756a035302c
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
15Actions and Services implicitly declare a new section.  All commands
16or options belong to the section most recently declared.  Commands
17or options before the first section are ignored.
18
19Actions and Services have unique names.  If a second Action is defined
20with the same name as an existing one, its commands are appended to
21the commands of the existing action.  If a second Service is defined
22with the same name as an existing one, it is ignored and an error
23message is logged.
24
25
26Init .rc Files
27--------------
28The init language is used in plain text files that take the .rc file
29extension.  These are typically multiple of these in multiple
30locations on the system, described below.
31
32/init.rc is the primary .rc file and is loaded by the init executable
33at the beginning of its execution.  It is responsible for the initial
34set up of the system.  It imports /init.${ro.hardware}.rc which is the
35primary vendor supplied .rc file.
36
37During the mount\_all command, the init executable loads all of the
38files contained within the /{system,vendor,odm}/etc/init/ directories.
39These directories are intended for all Actions and Services used after
40file system mounting.
41
42One may specify paths in the mount\_all command line to have it import
43.rc files at the specified paths instead of the default ones listed above.
44This is primarily for supporting factory mode and other non-standard boot
45modes.  The three default paths should be used for the normal boot process.
46
47The intention of these directories is:
48
49   1. /system/etc/init/ is for core system items such as
50      SurfaceFlinger, MediaService, and logcatd.
51   2. /vendor/etc/init/ is for SoC vendor items such as actions or
52      daemons needed for core SoC functionality.
53   3. /odm/etc/init/ is for device manufacturer items such as
54      actions or daemons needed for motion sensor or other peripheral
55      functionality.
56
57All services whose binaries reside on the system, vendor, or odm
58partitions should have their service entries placed into a
59corresponding init .rc file, located in the /etc/init/
60directory of the partition where they reside.  There is a build
61system macro, LOCAL\_INIT\_RC, that handles this for developers.  Each
62init .rc file should additionally contain any actions associated with
63its service.
64
65An example is the logcatd.rc and Android.mk files located in the
66system/core/logcat directory.  The LOCAL\_INIT\_RC macro in the
67Android.mk file places logcatd.rc in /system/etc/init/ during the
68build process.  Init loads logcatd.rc during the mount\_all command and
69allows the service to be run and the action to be queued when
70appropriate.
71
72This break up of init .rc files according to their daemon is preferred
73to the previously used monolithic init .rc files.  This approach
74ensures that the only service entries that init reads and the only
75actions that init performs correspond to services whose binaries are in
76fact present on the file system, which was not the case with the
77monolithic init .rc files.  This additionally will aid in merge
78conflict resolution when multiple services are added to the system, as
79each one will go into a separate file.
80
81There are two options "early" and "late" in mount\_all command
82which can be set after optional paths. With "--early" set, the
83init executable will skip mounting entries with "latemount" flag
84and triggering fs encryption state event. With "--late" set,
85init executable will only mount entries with "latemount" flag but skip
86importing rc files. By default, no option is set, and mount\_all will
87process all entries in the given fstab.
88
89Actions
90-------
91Actions are named sequences of commands.  Actions have a trigger which
92is used to determine when the action should occur.  When an event
93occurs which matches an action's trigger, that action is added to
94the tail of a to-be-executed queue (unless it is already on the
95queue).
96
97Each action in the queue is dequeued in sequence and each command in
98that action is executed in sequence.  Init handles other activities
99(device creation/destruction, property setting, process restarting)
100"between" the execution of the commands in activities.
101
102Actions take the form of:
103
104    on <trigger> [&& <trigger>]*
105       <command>
106       <command>
107       <command>
108
109
110Services
111--------
112Services are programs which init launches and (optionally) restarts
113when they exit.  Services take the form of:
114
115    service <name> <pathname> [ <argument> ]*
116       <option>
117       <option>
118       ...
119
120
121Options
122-------
123Options are modifiers to services.  They affect how and when init
124runs the service.
125
126`console [<console>]`
127> This service needs a console. The optional second parameter chooses a
128  specific console instead of the default. The default "/dev/console" can
129  be changed by setting the "androidboot.console" kernel parameter. In
130  all cases the leading "/dev/" should be omitted, so "/dev/tty0" would be
131  specified as just "console tty0".
132
133`critical`
134> This is a device-critical service. If it exits more than four times in
135  four minutes, the device will reboot into recovery mode.
136
137`disabled`
138> This service will not automatically start with its class.
139  It must be explicitly started by name.
140
141`setenv <name> <value>`
142> Set the environment variable _name_ to _value_ in the launched process.
143
144`socket <name> <type> <perm> [ <user> [ <group> [ <seclabel> ] ] ]`
145> Create a unix domain socket named /dev/socket/_name_ and pass its fd to the
146  launched process.  _type_ must be "dgram", "stream" or "seqpacket".  User and
147  group default to 0.  'seclabel' is the SELinux security context for the
148  socket.  It defaults to the service security context, as specified by
149  seclabel or computed based on the service executable file security context.
150  For native executables see libcutils android\_get\_control\_socket().
151
152`file <path> <type>`
153> Open a file path and pass its fd to the launched process. _type_ must be
154  "r", "w" or "rw".  For native executables see libcutils
155  android\_get\_control\_file().
156
157`user <username>`
158> Change to 'username' before exec'ing this service.
159  Currently defaults to root.  (??? probably should default to nobody)
160  As of Android M, processes should use this option even if they
161  require Linux capabilities.  Previously, to acquire Linux
162  capabilities, a process would need to run as root, request the
163  capabilities, then drop to its desired uid.  There is a new
164  mechanism through fs\_config that allows device manufacturers to add
165  Linux capabilities to specific binaries on a file system that should
166  be used instead. This mechanism is described on
167  <http://source.android.com/devices/tech/config/filesystem.html>.  When
168  using this new mechanism, processes can use the user option to
169  select their desired uid without ever running as root.
170  As of Android O, processes can also request capabilities directly in their .rc
171  files. See the "capabilities" option below.
172
173`group <groupname> [ <groupname>\* ]`
174> Change to 'groupname' before exec'ing this service.  Additional
175  groupnames beyond the (required) first one are used to set the
176  supplemental groups of the process (via setgroups()).
177  Currently defaults to root.  (??? probably should default to nobody)
178
179`capabilities <capability> [ <capability>\* ]`
180> Set capabilities when exec'ing this service. 'capability' should be a Linux
181  capability without the "CAP\_" prefix, like "NET\_ADMIN" or "SETPCAP". See
182  http://man7.org/linux/man-pages/man7/capabilities.7.html for a list of Linux
183  capabilities.
184
185`seclabel <seclabel>`
186> Change to 'seclabel' before exec'ing this service.
187  Primarily for use by services run from the rootfs, e.g. ueventd, adbd.
188  Services on the system partition can instead use policy-defined transitions
189  based on their file security context.
190  If not specified and no transition is defined in policy, defaults to the init context.
191
192`oneshot`
193> Do not restart the service when it exits.
194
195`class <name>`
196> Specify a class name for the service.  All services in a
197  named class may be started or stopped together.  A service
198  is in the class "default" if one is not specified via the
199  class option.
200
201`onrestart`
202> Execute a Command (see below) when service restarts.
203
204`writepid <file...>`
205> Write the child's pid to the given files when it forks. Meant for
206  cgroup/cpuset usage.
207
208`priority <priority>`
209> Scheduling priority of the service process. This value has to be in range
210  -20 to 19. Default priority is 0. Priority is set via setpriority().
211
212`namespace <pid|mnt>`
213> Enter a new PID or mount namespace when forking the service.
214
215`oom_score_adjust <value>`
216> Sets the child's /proc/self/oom\_score\_adj to the specified value,
217  which must range from -1000 to 1000.
218
219
220Triggers
221--------
222Triggers are strings which can be used to match certain kinds of
223events and used to cause an action to occur.
224
225Triggers are subdivided into event triggers and property triggers.
226
227Event triggers are strings triggered by the 'trigger' command or by
228the QueueEventTrigger() function within the init executable.  These
229take the form of a simple string such as 'boot' or 'late-init'.
230
231Property triggers are strings triggered when a named property changes
232value to a given new value or when a named property changes value to
233any new value.  These take the form of 'property:<name>=<value>' and
234'property:<name>=\*' respectively.  Property triggers are additionally
235evaluated and triggered accordingly during the initial boot phase of
236init.
237
238An Action can have multiple property triggers but may only have one
239event trigger.
240
241For example:
242`on boot && property:a=b` defines an action that is only executed when
243the 'boot' event trigger happens and the property a equals b.
244
245`on property:a=b && property:c=d` defines an action that is executed
246at three times:
247
248   1. During initial boot if property a=b and property c=d.
249   2. Any time that property a transitions to value b, while property c already equals d.
250   3. Any time that property c transitions to value d, while property a already equals b.
251
252
253Commands
254--------
255
256`bootchart [start|stop]`
257> Start/stop bootcharting. These are present in the default init.rc files,
258  but bootcharting is only active if the file /data/bootchart/enabled exists;
259  otherwise bootchart start/stop are no-ops.
260
261`chmod <octal-mode> <path>`
262> Change file access permissions.
263
264`chown <owner> <group> <path>`
265> Change file owner and group.
266
267`class_start <serviceclass>`
268> Start all services of the specified class if they are
269  not already running.
270
271`class_stop <serviceclass>`
272> Stop and disable all services of the specified class if they are
273  currently running.
274
275`class_reset <serviceclass>`
276> Stop all services of the specified class if they are
277  currently running, without disabling them. They can be restarted
278  later using `class_start`.
279
280`copy <src> <dst>`
281> Copies a file. Similar to write, but useful for binary/large
282  amounts of data.
283
284`domainname <name>`
285> Set the domain name.
286
287`enable <servicename>`
288> Turns a disabled service into an enabled one as if the service did not
289  specify disabled.
290  If the service is supposed to be running, it will be started now.
291  Typically used when the bootloader sets a variable that indicates a specific
292  service should be started when needed. E.g.
293
294    on property:ro.boot.myfancyhardware=1
295        enable my_fancy_service_for_my_fancy_hardware
296
297`exec [ <seclabel> [ <user> [ <group>\* ] ] ] -- <command> [ <argument>\* ]`
298> Fork and execute command with the given arguments. The command starts
299  after "--" so that an optional security context, user, and supplementary
300  groups can be provided. No other commands will be run until this one
301  finishes. _seclabel_ can be a - to denote default. Properties are expanded
302  within _argument_.
303
304`export <name> <value>`
305> Set the environment variable _name_ equal to _value_ in the
306  global environment (which will be inherited by all processes
307  started after this command is executed)
308
309`hostname <name>`
310> Set the host name.
311
312`ifup <interface>`
313> Bring the network interface _interface_ online.
314
315`insmod [-f] <path> [<options>]`
316> Install the module at _path_ with the specified options.
317  -f: force installation of the module even if the version of the running kernel
318  and the version of the kernel for which the module was compiled do not match.
319
320`load_all_props`
321> Loads properties from /system, /vendor, et cetera.
322  This is included in the default init.rc.
323
324`load_persist_props`
325> Loads persistent properties when /data has been decrypted.
326  This is included in the default init.rc.
327
328`loglevel <level>`
329> Sets the kernel log level to level. Properties are expanded within _level_.
330
331`mkdir <path> [mode] [owner] [group]`
332> Create a directory at _path_, optionally with the given mode, owner, and
333  group. If not provided, the directory is created with permissions 755 and
334  owned by the root user and root group. If provided, the mode, owner and group
335  will be updated if the directory exists already.
336
337`mount_all <fstab> [ <path> ]\* [--<option>]`
338> Calls fs\_mgr\_mount\_all on the given fs\_mgr-format fstab and imports .rc files
339  at the specified paths (e.g., on the partitions just mounted) with optional
340  options "early" and "late".
341  Refer to the section of "Init .rc Files" for detail.
342
343`mount <type> <device> <dir> [ <flag>\* ] [<options>]`
344> Attempt to mount the named device at the directory _dir_
345  _flag_s include "ro", "rw", "remount", "noatime", ...
346  _options_ include "barrier=1", "noauto\_da\_alloc", "discard", ... as
347  a comma separated string, eg: barrier=1,noauto\_da\_alloc
348
349`powerctl`
350> Internal implementation detail used to respond to changes to the
351  "sys.powerctl" system property, used to implement rebooting.
352
353`restart <service>`
354> Like stop, but doesn't disable the service.
355
356`restorecon <path> [ <path>\* ]`
357> Restore the file named by _path_ to the security context specified
358  in the file\_contexts configuration.
359  Not required for directories created by the init.rc as these are
360  automatically labeled correctly by init.
361
362`restorecon_recursive <path> [ <path>\* ]`
363> Recursively restore the directory tree named by _path_ to the
364  security contexts specified in the file\_contexts configuration.
365
366`rm <path>`
367> Calls unlink(2) on the given path. You might want to
368  use "exec -- rm ..." instead (provided the system partition is
369  already mounted).
370
371`rmdir <path>`
372> Calls rmdir(2) on the given path.
373
374`setprop <name> <value>`
375> Set system property _name_ to _value_. Properties are expanded
376  within _value_.
377
378`setrlimit <resource> <cur> <max>`
379> Set the rlimit for a resource.
380
381`start <service>`
382> Start a service running if it is not already running.
383
384`stop <service>`
385> Stop a service from running if it is currently running.
386
387`swapon_all <fstab>`
388> Calls fs\_mgr\_swapon\_all on the given fstab file.
389
390`symlink <target> <path>`
391> Create a symbolic link at _path_ with the value _target_
392
393`sysclktz <mins_west_of_gmt>`
394> Set the system clock base (0 if system clock ticks in GMT)
395
396`trigger <event>`
397> Trigger an event.  Used to queue an action from another
398  action.
399
400`umount <path>`
401> Unmount the filesystem mounted at that path.
402
403`verity_load_state`
404> Internal implementation detail used to load dm-verity state.
405
406`verity_update_state <mount-point>`
407> Internal implementation detail used to update dm-verity state and
408  set the partition._mount-point_.verified properties used by adb remount
409  because fs\_mgr can't set them directly itself.
410
411`wait <path> [ <timeout> ]`
412> Poll for the existence of the given file and return when found,
413  or the timeout has been reached. If timeout is not specified it
414  currently defaults to five seconds.
415
416`wait_for_prop <name> <value>`
417> Wait for system property _name_ to be _value_. Properties are expanded
418  within _value_. If property _name_ is already set to _value_, continue
419  immediately.
420
421`write <path> <content>`
422> Open the file at _path_ and write a string to it with write(2).
423  If the file does not exist, it will be created. If it does exist,
424  it will be truncated. Properties are expanded within _content_.
425
426
427Imports
428-------
429The import keyword is not a command, but rather its own section and is
430handled immediately after the .rc file that contains it has finished
431being parsed.  It takes the below form:
432
433`import <path>`
434> Parse an init config file, extending the current configuration.
435  If _path_ is a directory, each file in the directory is parsed as
436  a config file. It is not recursive, nested directories will
437  not be parsed.
438
439There are only two times where the init executable imports .rc files:
440
441   1. When it imports /init.rc during initial boot
442   2. When it imports /{system,vendor,odm}/etc/init/ or .rc files at specified
443      paths during mount_all
444
445
446Properties
447----------
448Init provides information about the services that it is responsible
449for via the below properties.
450
451`init.svc.<name>`
452> State of a named service ("stopped", "stopping", "running", "restarting")
453
454
455Boot timing
456-----------
457Init records some boot timing information in system properties.
458
459`ro.boottime.init`
460> Time after boot in ns (via the CLOCK\_BOOTTIME clock) at which the first
461  stage of init started.
462
463`ro.boottime.init.selinux`
464> How long it took the first stage to initialize SELinux.
465
466`ro.boottime.init.cold_boot_wait`
467> How long init waited for ueventd's coldboot phase to end.
468
469`ro.boottime.<service-name>`
470> Time after boot in ns (via the CLOCK\_BOOTTIME clock) that the service was
471  first started.
472
473
474Bootcharting
475------------
476This version of init contains code to perform "bootcharting": generating log
477files that can be later processed by the tools provided by <http://www.bootchart.org/>.
478
479On the emulator, use the -bootchart _timeout_ option to boot with bootcharting
480activated for _timeout_ seconds.
481
482On a device:
483
484    adb shell 'touch /data/bootchart/enabled'
485
486Don't forget to delete this file when you're done collecting data!
487
488The log files are written to /data/bootchart/. A script is provided to
489retrieve them and create a bootchart.tgz file that can be used with the
490bootchart command-line utility:
491
492    sudo apt-get install pybootchartgui
493    # grab-bootchart.sh uses $ANDROID_SERIAL.
494    $ANDROID_BUILD_TOP/system/core/init/grab-bootchart.sh
495
496One thing to watch for is that the bootchart will show init as if it started
497running at 0s. You'll have to look at dmesg to work out when the kernel
498actually started init.
499
500
501Comparing two bootcharts
502------------------------
503A handy script named compare-bootcharts.py can be used to compare the
504start/end time of selected processes. The aforementioned grab-bootchart.sh
505will leave a bootchart tarball named bootchart.tgz at /tmp/android-bootchart.
506If two such barballs are preserved on the host machine under different
507directories, the script can list the timestamps differences. For example:
508
509Usage: system/core/init/compare-bootcharts.py _base-bootchart-dir_ _exp-bootchart-dir_
510
511    process: baseline experiment (delta) - Unit is ms (a jiffy is 10 ms on the system)
512    ------------------------------------
513    /init: 50 40 (-10)
514    /system/bin/surfaceflinger: 4320 4470 (+150)
515    /system/bin/bootanimation: 6980 6990 (+10)
516    zygote64: 10410 10640 (+230)
517    zygote: 10410 10640 (+230)
518    system_server: 15350 15150 (-200)
519    bootanimation ends at: 33790 31230 (-2560)
520
521
522Systrace
523--------
524Systrace (<http://developer.android.com/tools/help/systrace.html>) can be
525used for obtaining performance analysis reports during boot
526time on userdebug or eng builds.
527
528Here is an example of trace events of "wm" and "am" categories:
529
530    $ANDROID_BUILD_TOP/external/chromium-trace/systrace.py \
531          wm am --boot
532
533This command will cause the device to reboot. After the device is rebooted and
534the boot sequence has finished, the trace report is obtained from the device
535and written as trace.html on the host by hitting Ctrl+C.
536
537Limitation: recording trace events is started after persistent properties are loaded, so
538the trace events that are emitted before that are not recorded. Several
539services such as vold, surfaceflinger, and servicemanager are affected by this
540limitation since they are started before persistent properties are loaded.
541Zygote initialization and the processes that are forked from the zygote are not
542affected.
543
544
545Debugging init
546--------------
547By default, programs executed by init will drop stdout and stderr into
548/dev/null. To help with debugging, you can execute your program via the
549Android program logwrapper. This will redirect stdout/stderr into the
550Android logging system (accessed via logcat).
551
552For example
553service akmd /system/bin/logwrapper /sbin/akmd
554
555For quicker turnaround when working on init itself, use:
556
557    mm -j &&
558    m ramdisk-nodeps &&
559    m bootimage-nodeps &&
560    adb reboot bootloader &&
561    fastboot boot $ANDROID_PRODUCT_OUT/boot.img
562
563Alternatively, use the emulator:
564
565    emulator -partition-size 1024 \
566        -verbose -show-kernel -no-window
567