README.md
1# Soong
2
3Soong is the replacement for the old Android make-based build system. It
4replaces Android.mk files with Android.bp files, which are JSON-like simple
5declarative descriptions of modules to build.
6
7See [Simple Build
8Configuration](https://source.android.com/compatibility/tests/development/blueprints)
9on source.android.com to read how Soong is configured for testing.
10
11## Android.bp file format
12
13By design, Android.bp files are very simple. There are no conditionals or
14control flow statements - any complexity is handled in build logic written in
15Go. The syntax and semantics of Android.bp files are intentionally similar
16to [Bazel BUILD files](https://www.bazel.io/versions/master/docs/be/overview.html)
17when possible.
18
19### Modules
20
21A module in an Android.bp file starts with a module type, followed by a set of
22properties in `name: value,` format:
23
24```
25cc_binary {
26 name: "gzip",
27 srcs: ["src/test/minigzip.c"],
28 shared_libs: ["libz"],
29 stl: "none",
30}
31```
32
33Every module must have a `name` property, and the value must be unique across
34all Android.bp files.
35
36The list of valid module types and their properties can be generated by calling
37`m soong_docs`. It will be written to `$OUT_DIR/soong/docs/soong_build.html`.
38This list for the current version of Soong can be found [here](https://ci.android.com/builds/latest/branches/aosp-build-tools/targets/linux/view/soong_build.html).
39
40### File lists
41
42Properties that take a list of files can also take glob patterns and output path
43expansions.
44
45* Glob patterns can contain the normal Unix wildcard `*`, for example `"*.java"`.
46
47 Glob patterns can also contain a single `**` wildcard as a path element, which
48 will match zero or more path elements. For example, `java/**/*.java` will match
49 `java/Main.java` and `java/com/android/Main.java`.
50
51* Output path expansions take the format `:module` or `:module{.tag}`, where
52 `module` is the name of a module that produces output files, and it expands to
53 a list of those output files. With the optional `{.tag}` suffix, the module
54 may produce a different list of outputs according to `tag`.
55
56 For example, a `droiddoc` module with the name "my-docs" would return its
57 `.stubs.srcjar` output with `":my-docs"`, and its `.doc.zip` file with
58 `":my-docs{.doc.zip}"`.
59
60 This is commonly used to reference `filegroup` modules, whose output files
61 consist of their `srcs`.
62
63### Variables
64
65An Android.bp file may contain top-level variable assignments:
66```
67gzip_srcs = ["src/test/minigzip.c"],
68
69cc_binary {
70 name: "gzip",
71 srcs: gzip_srcs,
72 shared_libs: ["libz"],
73 stl: "none",
74}
75```
76
77Variables are scoped to the remainder of the file they are declared in, as well
78as any child Android.bp files. Variables are immutable with one exception - they
79can be appended to with a += assignment, but only before they have been
80referenced.
81
82### Comments
83
84Android.bp files can contain C-style multiline `/* */` and C++ style single-line
85`//` comments.
86
87### Types
88
89Variables and properties are strongly typed, variables dynamically based on the
90first assignment, and properties statically by the module type. The supported
91types are:
92* Bool (`true` or `false`)
93* Integers (`int`)
94* Strings (`"string"`)
95* Lists of strings (`["string1", "string2"]`)
96* Maps (`{key1: "value1", key2: ["value2"]}`)
97
98Maps may values of any type, including nested maps. Lists and maps may have
99trailing commas after the last value.
100
101Strings can contain double quotes using `\"`, for example `"cat \"a b\""`.
102
103### Operators
104
105Strings, lists of strings, and maps can be appended using the `+` operator.
106Integers can be summed up using the `+` operator. Appending a map produces the
107union of keys in both maps, appending the values of any keys that are present
108in both maps.
109
110### Defaults modules
111
112A defaults module can be used to repeat the same properties in multiple modules.
113For example:
114
115```
116cc_defaults {
117 name: "gzip_defaults",
118 shared_libs: ["libz"],
119 stl: "none",
120}
121
122cc_binary {
123 name: "gzip",
124 defaults: ["gzip_defaults"],
125 srcs: ["src/test/minigzip.c"],
126}
127```
128
129### Packages
130
131The build is organized into packages where each package is a collection of related files and a
132specification of the dependencies among them in the form of modules.
133
134A package is defined as a directory containing a file named `Android.bp`, residing beneath the
135top-level directory in the build and its name is its path relative to the top-level directory. A
136package includes all files in its directory, plus all subdirectories beneath it, except those which
137themselves contain an `Android.bp` file.
138
139The modules in a package's `Android.bp` and included files are part of the module.
140
141For example, in the following directory tree (where `.../android/` is the top-level Android
142directory) there are two packages, `my/app`, and the subpackage `my/app/tests`. Note that
143`my/app/data` is not a package, but a directory belonging to package `my/app`.
144
145 .../android/my/app/Android.bp
146 .../android/my/app/app.cc
147 .../android/my/app/data/input.txt
148 .../android/my/app/tests/Android.bp
149 .../android/my/app/tests/test.cc
150
151This is based on the Bazel package concept.
152
153The `package` module type allows information to be specified about a package. Only a single
154`package` module can be specified per package and in the case where there are multiple `.bp` files
155in the same package directory it is highly recommended that the `package` module (if required) is
156specified in the `Android.bp` file.
157
158Unlike most module type `package` does not have a `name` property. Instead the name is set to the
159name of the package, e.g. if the package is in `top/intermediate/package` then the package name is
160`//top/intermediate/package`.
161
162E.g. The following will set the default visibility for all the modules defined in the package and
163any subpackages that do not set their own default visibility (irrespective of whether they are in
164the same `.bp` file as the `package` module) to be visible to all the subpackages by default.
165
166```
167package {
168 default_visibility: [":__subpackages"]
169}
170```
171
172### Referencing Modules
173
174A module `libfoo` can be referenced by its name
175
176```
177cc_binary {
178 name: "app",
179 shared_libs: ["libfoo"],
180}
181```
182
183Obviously, this works only if there is only one `libfoo` module in the source
184tree. Ensuring such name uniqueness for larger trees may become problematic. We
185might also want to use the same name in multiple mutually exclusive subtrees
186(for example, implementing different devices) deliberately in order to describe
187a functionally equivalent module. Enter Soong namespaces.
188
189#### Namespaces
190
191The presence of the `soong_namespace {..}` in an Android.bp file defines a
192**namespace**. For instance, having
193
194```
195soong_namespace {
196 ...
197}
198...
199```
200
201in `device/google/bonito/Android.bp` informs Soong that within the
202`device/google/bonito` package the module names are unique, that is, all the
203modules defined in the Android.bp files in the `device/google/bonito/` tree have
204unique names. However, there may be modules with the same names outside
205`device/google/bonito` tree. Indeed, there is a module `"pixelstats-vendor"`
206both in `device/google/bonito/pixelstats` and in
207`device/google/coral/pixelstats`.
208
209The name of a namespace is the path of its directory. The name of the namespace
210in the example above is thus `device/google/bonito`.
211
212An implicit **global namespace** corresponds to the source tree as a whole. It
213has empty name.
214
215A module name's **scope** is the smallest namespace containing it. Suppose a
216source tree has `device/my` and `device/my/display` namespaces. If `libfoo`
217module is defined in `device/my/display/lib/Android.bp`, its namespace is
218`device/my/display`.
219
220The name uniqueness thus means that module's name is unique within its scope. In
221other words, "//_scope_:_name_" is globally unique module reference, e.g,
222`"//device/google/bonito:pixelstats-vendor"`. _Note_ that the name of the
223namespace for a module may be different from module's package name: `libfoo`
224belongs to `device/my/display` namespace but is contained in
225`device/my/display/lib` package.
226
227#### Name Resolution
228
229The form of a module reference determines how Soong locates the module.
230
231For a **global reference** of the "//_scope_:_name_" form, Soong verifies there
232is a namespace called "_scope_", then verifies it contains a "_name_" module and
233uses it. Soong verifies there is only one "_name_" in "_scope_" at the beginning
234when it parses Android.bp files.
235
236A **local reference** has "_name_" form, and resolving it involves looking for a
237module "_name_" in one or more namespaces. By default only the global namespace
238is searched for "_name_" (in other words, only the modules not belonging to an
239explicitly defined scope are considered). The `imports` attribute of the
240`soong_namespaces` allows to specify where to look for modules . For instance,
241with `device/google/bonito/Android.bp` containing
242
243```
244soong_namespace {
245 imports: [
246 "hardware/google/interfaces",
247 "hardware/google/pixel",
248 "hardware/qcom/bootctrl",
249 ],
250}
251```
252
253a reference to `"libpixelstats"` will resolve to the module defined in
254`hardware/google/pixel/pixelstats/Android.bp` because this module is in
255`hardware/google/pixel` namespace.
256
257**TODO**: Conventionally, languages with similar concepts provide separate
258constructs for namespace definition and name resolution (`namespace` and `using`
259in C++, for instance). Should Soong do that, too?
260
261#### Referencing modules in makefiles
262
263While we are gradually converting makefiles to Android.bp files, Android build
264is described by a mixture of Android.bp and Android.mk files, and a module
265defined in an Android.mk file can reference a module defined in Android.bp file.
266For instance, a binary still defined in an Android.mk file may have a library
267defined in already converted Android.bp as a dependency.
268
269A module defined in an Android.bp file and belonging to the global namespace can
270be referenced from a makefile without additional effort. If a module belongs to
271an explicit namespace, it can be referenced from a makefile only after after the
272name of the namespace has been added to the value of PRODUCT_SOONG_NAMESPACES
273variable.
274
275Note that makefiles have no notion of namespaces and exposing namespaces with
276the same modules via PRODUCT_SOONG_NAMESPACES may cause Make failure. For
277instance, exposing both `device/google/bonito` and `device/google/coral`
278namespaces will cause Make failure because it will see two targets for the
279`pixelstats-vendor` module.
280
281### Visibility
282
283The `visibility` property on a module controls whether the module can be
284used by other packages. Modules are always visible to other modules declared
285in the same package. This is based on the Bazel visibility mechanism.
286
287If specified the `visibility` property must contain at least one rule.
288
289Each rule in the property must be in one of the following forms:
290* `["//visibility:public"]`: Anyone can use this module.
291* `["//visibility:private"]`: Only rules in the module's package (not its
292subpackages) can use this module.
293* `["//visibility:override"]`: Discards any rules inherited from defaults or a
294creating module. Can only be used at the beginning of a list of visibility
295rules.
296* `["//some/package:__pkg__", "//other/package:__pkg__"]`: Only modules in
297`some/package` and `other/package` (defined in `some/package/*.bp` and
298`other/package/*.bp`) have access to this module. Note that sub-packages do not
299have access to the rule; for example, `//some/package/foo:bar` or
300`//other/package/testing:bla` wouldn't have access. `__pkg__` is a special
301module and must be used verbatim. It represents all of the modules in the
302package.
303* `["//project:__subpackages__", "//other:__subpackages__"]`: Only modules in
304packages `project` or `other` or in one of their sub-packages have access to
305this module. For example, `//project:rule`, `//project/library:lib` or
306`//other/testing/internal:munge` are allowed to depend on this rule (but not
307`//independent:evil`)
308* `["//project"]`: This is shorthand for `["//project:__pkg__"]`
309* `[":__subpackages__"]`: This is shorthand for `["//project:__subpackages__"]`
310where `//project` is the module's package, e.g. using `[":__subpackages__"]` in
311`packages/apps/Settings/Android.bp` is equivalent to
312`//packages/apps/Settings:__subpackages__`.
313* `["//visibility:legacy_public"]`: The default visibility, behaves as
314`//visibility:public` for now. It is an error if it is used in a module.
315
316The visibility rules of `//visibility:public` and `//visibility:private` cannot
317be combined with any other visibility specifications, except
318`//visibility:public` is allowed to override visibility specifications imported
319through the `defaults` property.
320
321Packages outside `vendor/` cannot make themselves visible to specific packages
322in `vendor/`, e.g. a module in `libcore` cannot declare that it is visible to
323say `vendor/google`, instead it must make itself visible to all packages within
324`vendor/` using `//vendor:__subpackages__`.
325
326If a module does not specify the `visibility` property then it uses the
327`default_visibility` property of the `package` module in the module's package.
328
329If the `default_visibility` property is not set for the module's package then
330it will use the `default_visibility` of its closest ancestor package for which
331a `default_visibility` property is specified.
332
333If no `default_visibility` property can be found then the module uses the
334global default of `//visibility:legacy_public`.
335
336The `visibility` property has no effect on a defaults module although it does
337apply to any non-defaults module that uses it. To set the visibility of a
338defaults module, use the `defaults_visibility` property on the defaults module;
339not to be confused with the `default_visibility` property on the package module.
340
341Once the build has been completely switched over to soong it is possible that a
342global refactoring will be done to change this to `//visibility:private` at
343which point all packages that do not currently specify a `default_visibility`
344property will be updated to have
345`default_visibility = [//visibility:legacy_public]` added. It will then be the
346owner's responsibility to replace that with a more appropriate visibility.
347
348### Formatter
349
350Soong includes a canonical formatter for Android.bp files, similar to
351[gofmt](https://golang.org/cmd/gofmt/). To recursively reformat all Android.bp files
352in the current directory:
353```
354bpfmt -w .
355```
356
357The canonical format includes 4 space indents, newlines after every element of a
358multi-element list, and always includes a trailing comma in lists and maps.
359
360### Convert Android.mk files
361
362Soong includes a tool perform a first pass at converting Android.mk files
363to Android.bp files:
364
365```
366androidmk Android.mk > Android.bp
367```
368
369The tool converts variables, modules, comments, and some conditionals, but any
370custom Makefile rules, complex conditionals or extra includes must be converted
371by hand.
372
373#### Differences between Android.mk and Android.bp
374
375* Android.mk files often have multiple modules with the same name (for example
376for static and shared version of a library, or for host and device versions).
377Android.bp files require unique names for every module, but a single module can
378be built in multiple variants, for example by adding `host_supported: true`.
379The androidmk converter will produce multiple conflicting modules, which must
380be resolved by hand to a single module with any differences inside
381`target: { android: { }, host: { } }` blocks.
382
383### Conditionals
384
385Soong deliberately does not support most conditionals in Android.bp files. We
386suggest removing most conditionals from the build. See
387[Best Practices](docs/best_practices.md#removing-conditionals) for some
388examples on how to remove conditionals.
389
390Most conditionals supported natively by Soong are converted to a map
391property. When building the module one of the properties in the map will be
392selected, and its values appended to the property with the same name at the
393top level of the module.
394
395For example, to support architecture specific files:
396```
397cc_library {
398 ...
399 srcs: ["generic.cpp"],
400 arch: {
401 arm: {
402 srcs: ["arm.cpp"],
403 },
404 x86: {
405 srcs: ["x86.cpp"],
406 },
407 },
408}
409```
410
411When building the module for arm the `generic.cpp` and `arm.cpp` sources will
412be built. When building for x86 the `generic.cpp` and 'x86.cpp' sources will
413be built.
414
415#### Soong Config Variables
416
417When converting vendor modules that contain conditionals, simple conditionals
418can be supported through Soong config variables using `soong_config_*`
419modules that describe the module types, variables and possible values:
420
421```
422soong_config_module_type {
423 name: "acme_cc_defaults",
424 module_type: "cc_defaults",
425 config_namespace: "acme",
426 variables: ["board"],
427 bool_variables: ["feature"],
428 value_variables: ["width"],
429 properties: ["cflags", "srcs"],
430}
431
432soong_config_string_variable {
433 name: "board",
434 values: ["soc_a", "soc_b", "soc_c"],
435}
436```
437
438This example describes a new `acme_cc_defaults` module type that extends the
439`cc_defaults` module type, with three additional conditionals based on
440variables `board`, `feature` and `width`, which can affect properties `cflags`
441and `srcs`. Additionally, each conditional will contain a `conditions_default`
442property can affect `cflags` and `srcs` in the following conditions:
443
444* bool variable (e.g. `feature`): the variable is unspecified or not set to a true value
445* value variable (e.g. `width`): the variable is unspecified
446* string variable (e.g. `board`): the variable is unspecified or the variable is set to a string unused in the
447given module. For example, with `board`, if the `board`
448conditional contains the properties `soc_a` and `conditions_default`, when
449board=soc_b, the `cflags` and `srcs` values under `conditions_default` will be
450used. To specify that no properties should be amended for `soc_b`, you can set
451`soc_b: {},`.
452
453The values of the variables can be set from a product's `BoardConfig.mk` file:
454```
455$(call soong_config_set,acme,board,soc_a)
456$(call soong_config_set,acme,feature,true)
457$(call soong_config_set,acme,width,200)
458```
459
460The `acme_cc_defaults` module type can be used anywhere after the definition in
461the file where it is defined, or can be imported into another file with:
462```
463soong_config_module_type_import {
464 from: "device/acme/Android.bp",
465 module_types: ["acme_cc_defaults"],
466}
467```
468
469It can used like any other module type:
470```
471acme_cc_defaults {
472 name: "acme_defaults",
473 cflags: ["-DGENERIC"],
474 soong_config_variables: {
475 board: {
476 soc_a: {
477 cflags: ["-DSOC_A"],
478 },
479 soc_b: {
480 cflags: ["-DSOC_B"],
481 },
482 conditions_default: {
483 cflags: ["-DSOC_DEFAULT"],
484 },
485 },
486 feature: {
487 cflags: ["-DFEATURE"],
488 conditions_default: {
489 cflags: ["-DFEATURE_DEFAULT"],
490 },
491 },
492 width: {
493 cflags: ["-DWIDTH=%s"],
494 conditions_default: {
495 cflags: ["-DWIDTH=DEFAULT"],
496 },
497 },
498 },
499}
500
501cc_library {
502 name: "libacme_foo",
503 defaults: ["acme_defaults"],
504 srcs: ["*.cpp"],
505}
506```
507
508With the `BoardConfig.mk` snippet above, `libacme_foo` would build with
509`cflags: "-DGENERIC -DSOC_A -DFEATURE -DWIDTH=200"`.
510
511Alternatively, with `DefaultBoardConfig.mk`:
512
513```
514SOONG_CONFIG_NAMESPACES += acme
515SOONG_CONFIG_acme += \
516 board \
517 feature \
518 width \
519
520SOONG_CONFIG_acme_feature := false
521```
522
523then `libacme_foo` would build with `cflags: "-DGENERIC -DSOC_DEFAULT -DFEATURE_DEFAULT -DSIZE=DEFAULT"`.
524
525Alternatively, with `DefaultBoardConfig.mk`:
526
527```
528SOONG_CONFIG_NAMESPACES += acme
529SOONG_CONFIG_acme += \
530 board \
531 feature \
532 width \
533
534SOONG_CONFIG_acme_board := soc_c
535```
536
537then `libacme_foo` would build with `cflags: "-DGENERIC -DSOC_DEFAULT
538-DFEATURE_DEFAULT -DSIZE=DEFAULT"`.
539
540`soong_config_module_type` modules will work best when used to wrap defaults
541modules (`cc_defaults`, `java_defaults`, etc.), which can then be referenced
542by all of the vendor's other modules using the normal namespace and visibility
543rules.
544
545## Build logic
546
547The build logic is written in Go using the
548[blueprint](http://godoc.org/github.com/google/blueprint) framework. Build
549logic receives module definitions parsed into Go structures using reflection
550and produces build rules. The build rules are collected by blueprint and
551written to a [ninja](http://ninja-build.org) build file.
552
553## Environment Variables Config File
554
555Soong can optionally load environment variables from a pre-specified
556configuration file during startup. These environment variables can be used
557to control the behavior of the build. For example, these variables can determine
558whether remote-execution should be used for the build or not.
559
560The `ANDROID_BUILD_ENVIRONMENT_CONFIG_DIR` environment variable specifies the
561directory in which the config file should be searched for. The
562`ANDROID_BUILD_ENVIRONMENT_CONFIG` variable determines the name of the config
563file to be searched for within the config directory. For example, the following
564build comand will load `ENV_VAR_1` and `ENV_VAR_2` environment variables from
565the `example_config.json` file inside the `build/soong` directory.
566
567```
568ANDROID_BUILD_ENVIRONMENT_CONFIG_DIR=build/soong \
569 ANDROID_BUILD_ENVIRONMENT_CONFIG=example_config \
570 build/soong/soong_ui.bash
571```
572
573## Other documentation
574
575* [Best Practices](docs/best_practices.md)
576* [Build Performance](docs/perf.md)
577* [Generating CLion Projects](docs/clion.md)
578* [Generating YouCompleteMe/VSCode compile\_commands.json file](docs/compdb.md)
579* Make-specific documentation: [build/make/README.md](https://android.googlesource.com/platform/build/+/master/README.md)
580
581## Developing for Soong
582
583To load the code of Soong in IntelliJ:
584
585* File -> Open, open the `build/soong` directory. It will be opened as a new
586 project.
587* File -> Settings, then Languages & Frameworks -> Go -> GOROOT, then set it to
588 `prebuilts/go/linux-x86`
589* File -> Project Structure, then, Project Settings -> Modules, then Add
590 Content Root, then add the `build/blueprint` directory.
591* Optional: also add the `external/golang-protobuf` directory. In practice,
592 IntelliJ seems to work well enough without this, too.
593### Running Soong in a debugger
594
595To make `soong_build` wait for a debugger connection, install `dlv` and then
596start the build with `SOONG_DELVE=<listen addr>` in the environment.
597For example:
598```bash
599SOONG_DELVE=:5006 m nothing
600```
601
602To make `soong_ui` wait for a debugger connection, use the `SOONG_UI_DELVE`
603variable:
604
605```
606SOONG_UI_DELVE=:5006 m nothing
607```
608
609
610setting or unsetting `SOONG_DELVE` causes a recompilation of `soong_build`. This
611is because in order to debug the binary, it needs to be built with debug
612symbols.
613
614To test the debugger connection, run this command:
615
616```
617dlv connect :5006
618```
619
620If you see an error:
621```
622Could not attach to pid 593: this could be caused by a kernel
623security setting, try writing "0" to /proc/sys/kernel/yama/ptrace_scope
624```
625you can temporarily disable
626[Yama's ptrace protection](https://www.kernel.org/doc/Documentation/security/Yama.txt)
627using:
628```bash
629sudo sysctl -w kernel.yama.ptrace_scope=0
630```
631
632To connect to the process using IntelliJ:
633
634* Run -> Edit Configurations...
635* Choose "Go Remote" on the left
636* Click on the "+" buttion on the top-left
637* Give it a nice name and set "Host" to localhost and "Port" to the port in the
638 environment variable
639
640Debugging works far worse than debugging Java, but is sometimes useful.
641
642Sometimes the `dlv` process hangs on connection. A symptom of this is `dlv`
643spinning a core or two. In that case, `kill -9` `dlv` and try again.
644Anecdotally, it _feels_ like waiting a minute after the start of `soong_build`
645helps.
646
647## Contact
648
649Email android-building@googlegroups.com (external) for any questions, or see
650[go/soong](http://go/soong) (internal).
651