未验证 提交 fa0aaf91 编写于 作者: O openharmony_ci 提交者: Gitee

!7135 【翻译完成】#I5EJT0

Merge pull request !7135 from Annie_wang/PR5973
...@@ -2,46 +2,46 @@ ...@@ -2,46 +2,46 @@
## Overview ## Overview
Generate Ninja (GN) a meta-build system that generates build files for Ninja, which allows you to build your OpenHarmony projects with Ninja. Generate Ninja (GN) is a meta-build system that generates build files for Ninja. It is the front end of Ninja. GN and Ninja together complete OpenHarmony build tasks.
### Introduction to GN ### GN
- GN is currently used in several popular systems, including Chromium, Fuchsia, and OpenHarmony. - GN is used in large software systems such as Chromium, Fuchsia, and OpenHarmony.
- The GN syntax has limitations rooted in its design philosophy. For example, there is no way to get the length of a list and wildcards are not supported. To learn about the GN design philosophy, see https://gn.googlesource.com/gn/+/main/docs/language.md#Design-philosophy. Therefore, if you find that it is complex to implement something using GN, look it over and think about whether it is really necessary. - However, the GN syntax has limitations rooted in its [design philosophy](https://gn.googlesource.com/gn/+/main/docs/language.md#Design-philosophy). For example, it does not support wildcards and cannot get the length of a list. If you find it complex to implement something with GN, stop and consider whether it is necessary to do it.
- For details about GN, see the official GN document at https://gn.googlesource.com/gn/+/main/docs/. - For more details about GN, visit https://gn.googlesource.com/gn/+/main/docs/.
### Intended Audience and Scope ### Intended Audience and Purpose
This document is intended for OpenHarmony developers. Its focus is on the GN coding style and issues that may occur during the use of GN. The GN syntax is not covered here. For details about the basics of GN, see the GN reference document at https://gn.googlesource.com/gn/+/main/docs/reference.md. This document is intended for OpenHarmony developers. This document describes the GN coding style and practices. It does not cover the GN syntax. For details about the GN basics, see [GN Reference](https://gn.googlesource.com/gn/+/main/docs/reference.md).
### General Principles ### General Principles
On the premise that functions are available, scripts must be easy to read, easy to maintain, and exhibit good scalability and performance. Scripts must be easy to read and maintain, and have good scalability and performance while functioning well.
## Coding Style ## Coding Style
### Naming ### Naming
In general cases, the naming follows the Linux kernel coding style, that is, **lowercase letters+underscore**. Follow the Linux kernel naming style, that is, lowercase letters + underscores (_).
#### Local Variables #### Local Variables
For the purpose of this document, a local variable refers to a variable that is restricted to use in a certain scope and not passed down. A local variable is a variable restricted to use in a certain scope and cannot be passed down.
To better distinguish local variables from global variables, local variables start with an underscore (**_**). Different from global variables, local variables start with an underscore (_).
``` ```
# Example 1 # Example 1:
action("some_action") { action("some_action") {
... ...
# _output is a local variable. Hence, it starts with an underscore (_). # _output is a local variable.
_output = "${target_out_dir}/${target_name}.out" _output = "${target_out_dir}/${target_name}.out"
outputs = [ _output ] outputs = [ _output ]
args = [ args = [
... ...
"--output", "--output",
rebase_path(_output, root_build_dir), rebase_path(_output, root_build_dir),
... ...
] ]
... ...
} }
...@@ -49,32 +49,32 @@ action("some_action") { ...@@ -49,32 +49,32 @@ action("some_action") {
#### Global Variables #### Global Variables
A global variable starts with a **lowercase letter**. A global variable starts with a lowercase letter.
If you want a variable value to be modified by **gn args**, use **declare\_args**. Otherwise, do not use **declare\_args**. Use **declare_args** to declare the variable value only if the variable value can be modified by **gn args**.
``` ```
# Example 2 # Example 2
declare_args() { declare_args() {
# You can use gn args to change the value of some_feature. # The value of some_feature can be changed by gn args.
some_feature = false some_feature = false
} }
``` ```
#### Targets #### Targets
The target is named in the format of **lowercase letters+underscore**. Name the targets in the lowercase letters + underscores (_) format.
A subtarget in the template is named in the ${*target\_name*}\__*suffix* format. This naming convention has the following advantages:
- The ${*target\_name*} part can prevent duplicate subtarget names. Name the subtargets in templates in the ${target_name}+double underscores (__)+suffix format. This naming convention has the following advantages:
- The double underscores (\__) can help identify the module to which the subtarget belongs, thereby facilitating fault locating. - ${target_name} prevents duplicate subtarget names.
- The double underscores (__) help locate the module to which a subtarget belongs.
``` ```
# Example 3 # Example 3
template("ohos_shared_library") { template("ohos_shared_library") {
# "{target_name}" (primary target name) + "__" (double underscores) + "notice" (suffix) # "{target_name}" (Target name) + "__" (double underscores) + "notice" (suffix)
_notice_target = "${target_name}__notice" _notice_target = "${target_name}__notice"
collect_notice(_notice_target) { collect_notice(_notice_target) {
... ...
...@@ -87,7 +87,7 @@ A subtarget in the template is named in the ${*target\_name*}\__*suffix* format. ...@@ -87,7 +87,7 @@ A subtarget in the template is named in the ${*target\_name*}\__*suffix* format.
#### Custom Templates #### Custom Templates
Whenever possible, **use verbs** for template names. Name templates in the verb+object format.
``` ```
# Example 4 # Example 4
...@@ -99,15 +99,15 @@ template("compile_resources") { ...@@ -99,15 +99,15 @@ template("compile_resources") {
### Formatting ### Formatting
To maintain consistency in styles such as code alignment and line feed, a GN script needs to be formatted before being submitted. Use the format tool provided by GN to format your script. The command is as follows: GN scripts must be formatted before being submitted. Formatting ensures consistency in style, such as code alignment and line feed. Use the format tool provided by GN to format your scripts. The command is as follows:
```shell ```shell
$ gn format path-to-BUILD.gn $ gn format path-to-BUILD.gn
``` ```
**gn format** sorts imports in alphabetical order. To maintain the original sequence, you can add an empty comment line. **gn format** sorts the imported files in alphabetical order. To maintain the original sequence, add an empty comment line.
Assume that the original import sequence is as follows: For example, the original import sequence is as follows:
``` ```
# Example 5 # Example 5
...@@ -115,42 +115,42 @@ import("//b.gni") ...@@ -115,42 +115,42 @@ import("//b.gni")
import("//a.gni") import("//a.gni")
``` ```
After the format command is executed, the import sequence is changed as follows: **gn format** sorts the files as follows:
``` ```
import("//a.gni") import("//a.gni")
import("//b.gni") import("//b.gni")
``` ```
To maintain the original import sequence, add an empty comment line. To maintain the original sequence, add an empty comment line.
``` ```
import("//b.gni") import("//b.gni")
# Comment to maintain the original import sequence. # Comment to keep the original sequence
import("//a.gni") import("//a.gni")
``` ```
## Coding Practice ## Coding Practices
### Principles of Practice
The build script completes the following two tasks: ### Guidelines
1. **Describe the dependency between modules (deps).** The build script completes the following tasks:
In practice, the most frequent problem is **lack of dependency**. 1. Describes the dependency (deps) between modules.
In practice, the most common problem is lack of dependency.
2. **Describe the module compilation rules (rule).** 2. Defines the module build rules (rule).
In practice, unclear input and output are common problems.
In practice, common problems are **unclear input** and **unclear output**. Lack of dependency leads to the following problems:
Lack of dependency can result in the following:
- **Possible compilation error**
- Unexpected compilation error
``` ```
# Example 6 # Example 6
# The compilation is prone to errors as a result of lack of dependency. # Lack of dependency poses a possibility of compilation errors.
shared_library("a") { shared_library("a") {
... ...
} }
...@@ -164,35 +164,35 @@ Lack of dependency can result in the following: ...@@ -164,35 +164,35 @@ Lack of dependency can result in the following:
deps = [ ":b" ] deps = [ ":b" ]
} }
``` ```
In this example, **libb.so** is linked to **liba.so**, which means that **b** depends on **a**. However, the dependency of **b** on **a** is not declared in the dependency list (**deps**) of **b**. Compilation is performed concurrently. An error occurs if **liba.so** is not available when **libb.so** attempts to create a link to it.
If **liba.so** is available, the compilation is successful. Therefore, lack of dependency poses a possibility of compilation errors.
In the preceding example, **liba.so** is linked to **libb.so** when being linked. This means that **b** depends on **a**. However, the dependency list (**deps**) of **b** does not declare its dependency on **a**. As compilation is performed concurrently, a compilation error will occur if compilation of **liba.so** is not yet complete when **libb.so** is being linked. - Missing compilation of modules
From this example we can see that lack of dependency does not necessarily lead to a compilation error. It poses a possibility of errors. In example 6, images are the target to build. Since images depend only on **b**, **a** will not be compiled. However, as **b** depends on **a**, an error occurs when **b** is linked.
- **Missing involvement of dependent modules**
In the preceding example, because **images** depends on **b** only, **a** does not participate in the compilation of **images** using Ninja. However, as **b** depends on **a**, an error occurs when **b** is linked.
One less common problem is **too many dependencies**. **Too many dependencies can reduce concurrency and slow down compilation**. Another problem is unnecessary dependencies. Unnecessary dependencies reduce concurrency and slow down compilation. The following is an example:
In the example below, adding the unwanted **_compile\_resource\_target** dependency to **_compile\_js_target** means that **_compile\_js_target** can be compiled only after compilation of **_compile\_resource\_target** is complete. **_compile_js_target** does not necessarily depend on **_compile_resource_target**. If this dependency is added, **_compile_js_target** can be compiled only after **_compile_resource_target** is compiled.
``` ```
# Example 7 # Example 7:
# Too many dependencies slow down compilation. # Unnecessary dependencies slow down compilation.
template("too_much_deps") { template("too_much_deps") {
... ...
_gen_resource_target = "${target_name}__res" _gen_resource_target = "${target_name}__res"
action(_gen_resource_target) { action(_gen_resource_target) {
... ...
} }
_compile_resource_target = "${target_name}__compile_res" _compile_resource_target = "${target_name}__compile_res"
action(_compile_resource_target) { action(_compile_resource_target) {
deps = [":$_gen_resource_target"] deps = [":$_gen_resource_target"]
... ...
} }
_compile_js_target = "${target_name}__js" _compile_js_target = "${target_name}__js"
action(_compile_js_target) { action(_compile_js_target) {
# This deps is not required. # This deps is not required.
...@@ -201,15 +201,15 @@ template("too_much_deps") { ...@@ -201,15 +201,15 @@ template("too_much_deps") {
} }
``` ```
Unclear input can result in the following: Unclear input leads to the following problems:
- **Modified code is not compiled during the incremental compilation.** - Modified code is not compiled during incremental compilation.
- **After code changes, the cache being used is still hit.** - The cache being used is still hit after the code is changed.
In the following example, **foo.py** references functions in **bar.py**. This means that **bar.py** is the input of **foo.py** and must be added to the **input** or **depfile** of **implict_input_action**. Otherwise, if **bar.py** is modified, the **implict_input_action** module will not be recompiled. In the following example, **foo.py** references the functions in **bar.py**. This means **bar.py** is the input of **foo.py**. You need to add **bar.py** to **input** or **depfile** of **implict_input_action**. Otherwise, if **bar.py** is modified, **implict_input_action** will not be recompiled.
``` ```
# Example 8 # Example 8:
action("implict_input_action") { action("implict_input_action") {
script = "//path-to-foo.py" script = "//path-to-foo.py"
... ...
...@@ -218,19 +218,19 @@ action("implict_input_action") { ...@@ -218,19 +218,19 @@ action("implict_input_action") {
``` ```
#!/usr/bin/env #!/usr/bin/env
# Contents of foo.py # Content of foo.py
import bar import bar
... ...
bar.some_function() bar.some_function()
... ...
``` ```
Unclear output can result in the following: Unclear output leads to the following problems:
- **The output is implicit.** - Implicit output
- **When the cache is used, implicit output cannot be obtained from the cache.** - A failure to obtain the implicit output from the cache
In the following example, **foo.py** generates two files: **a.out** and **b.out**; the output of **implict_output_action** declares only **a.out**. In this case, **b.out** is an implicit output, and the cache stores **a.out** but not **b.out**. When the cache is hit, **b.out** cannot be compiled. In the following example, **foo.py** generates two files: **a.out** and **b.out**. However, the output of **implict_output_action** declares only **a.out**. In this case, **b.out** is an implicit output, and the cache stores only **a.out**. When the cache is hit, **b.out** cannot be compiled.
``` ```
# Example 9 # Example 9
...@@ -252,43 +252,40 @@ write_file("a.out") ...@@ -252,43 +252,40 @@ write_file("a.out")
### Templates ### Templates
**Do not use the GN native templates. Use the templates provided by the compilation system.** **Do not use GN native templates. Use the templates provided by the build system.**
The GN native templates are **source_set**, **shared_library**, **static_library**, **action**, **executable**, and **group**. The GN native templates include **source_set**, **shared_library**, **static_library**, **action**, **executable** and **group**.
These native templates are discouraged due to the following reasons: The native templates are not recommended due to the following reasons:
- **The native templates only provide minimum functions**. They do not provide extra functions such as external_deps parsing, notice collection, and installation information generation. These extra functions are generated during module compilation. Therefore, the native templates must be extended. - The native templates provide only the minimal build configuration. They cannot provide functions, such as parsing **external_deps**, collecting notice, and generating installation information.
- When the file on which the input file depends changes, the native template **action** cannot automatically detect the change and cannot be recompiled. See Example 8. - The native **action** template cannot automatically detect the changes in the dependencies of the input file, and cannot start recompilation. See Example 8.
The table below lists the mapping between the GN native templates and templates provided by the compilation system.
Mapping between native templates and templates provided by the compilation system: | Template Provided by the Compilation System | GN Native Template |
|:------------------- | -------------- |
| Template Provided by the Compilation System | Native Template | | ohos_shared_library | shared_library |
| :------------------------------------------ | --------------- | | ohos_source_set | source_set |
| ohos_shared_library | shared_library | | ohos_executable | executable |
| ohos_source_set | source_set | | ohos_static_library | static_library |
| ohos_executable | executable | | action_with_pydeps | action |
| ohos_static_library | static_library | | ohos_group | group |
| action_with_pydeps | action |
| ohos_group | group |
### Using Python Scripts ### Using Python Scripts
Prioritize the Python script over the shell script in **action**. The Python script has the following advantages over the shell script: You are advised to use Python scripts instead of shell scripts in **action**. Compared with shell scripts, Python scripts feature:
- More user-friendly syntax: It will not generate strange errors just because a space is missing. - More user-friendly syntax, which eliminates errors caused by lack of a space
- More readable. - Easier to read
- Higher maintainability and debugability. - Easier to maintain and debug
- Faster compilation: thanks to Python task caching by OpenHarmony. - Faster compilation due to caching of Python tasks
### rebase_path ### rebase_path
- Call **rebase_path** only in the **args** list of **action**. - Call **rebase_path** only in **args** of **action**.
``` ```
# Example 10 # Example 10
template("foo") { template("foo") {
...@@ -309,15 +306,15 @@ Prioritize the Python script over the shell script in **action**. The Python scr ...@@ -309,15 +306,15 @@ Prioritize the Python script over the shell script in **action**. The Python scr
} }
``` ```
- If **rebase_path** is executed twice for the same variable, unexpected results may occur. - If rebase_path is called twice for the same variable, unexpected results occur.
``` ```
# Example 11 # Example 11
template("foo") { template("foo") {
action(target_name) { action(target_name) {
... ...
args = [ args = [
# rebase_path is executed twice for bar, and the passed bar value is incorrect. # After rebase_path is called twice for bar, the bar value passed is incorrect.
"--bar=" + rebase_path(invoker.bar, root_build_dir), "--bar=" + rebase_path(invoker.bar, root_build_dir),
... ...
] ]
...@@ -334,14 +331,14 @@ Prioritize the Python script over the shell script in **action**. The Python scr ...@@ -334,14 +331,14 @@ Prioritize the Python script over the shell script in **action**. The Python scr
### Sharing Data Between Modules ### Sharing Data Between Modules
Data sharing between modules is common. For example, a module may want to know the **outputs** and **deps** of another module. It is common to share data between modules. For example, module A wants to know the output and **deps** of module B.
- Data sharing within the same **BUILD.gn** file
Data in the same **BUILD.gn** file can be shared by defining global variables.
In the following example, the output of module **a** is the input of module **b**. Module **a** shares data with module **b** by defining global variables.
- Data sharing within the same **BUILD.gn**
Data in the same **BUILD.gn** can be shared by defining global variables.
In the following example, the output of module **a** is the input of module **b**, and can be shared with module **b** via global variables.
``` ```
# Example 12 # Example 12
_output_a = get_label_info(":a", "out_dir") + "/a.out" _output_a = get_label_info(":a", "out_dir") + "/a.out"
...@@ -355,25 +352,25 @@ Data sharing between modules is common. For example, a module may want to know t ...@@ -355,25 +352,25 @@ Data sharing between modules is common. For example, a module may want to know t
} }
``` ```
- Data sharing between different **BUILD.gn** files - Data sharing between different **BUILD.gn**s
The best way to share data between different **BUILD.gn** files is to save the data as files and then transfer the files between modules. This scenario is complex. For details, see **write_meta_data** in the OpenHarmony HAP compilation process. The best way to share data between different **BUILD.gn** is to save the data as files and transfer the files between modules. You can refer to **write_meta_data** in the OpenHarmony HAP build process.
### forward_variable_from ### forward_variable_from
- To customize a template, you need to forward **testonly** first, since the target of the template may be depended on by that of **testonly**. - To customize a template, pass (**forward**) **testonly** first because the **testonly** target may depend on the template target.
``` ```
# Example 13 # Example 13
# Forward testonly for a custom template. # For a customized template, pass testonly first.
template("foo") { template("foo") {
forward_variable_from(invoker, ["testonly"]) forward_variable_from(invoker, ["testonly"])
... ...
} }
``` ```
- Do not use asterisks (*) to forward variables. Required variables should be explicitly forwarded one by one. - Do not use asterisks (*) to **forward** variables. Required variables must be explicitly forwarded one by one.
``` ```
# Example 14 # Example 14
# Bad. The asterisk (*) is used to forward the variable. # Bad. The asterisk (*) is used to forward the variable.
...@@ -382,25 +379,25 @@ Data sharing between modules is common. For example, a module may want to know t ...@@ -382,25 +379,25 @@ Data sharing between modules is common. For example, a module may want to know t
... ...
} }
# Good. Variables are explicitly forward one by one. # Good. Variables are explicitly forwarded one by one.
template("bar") { template("bar") {
# #
forward_variable_from(invoker, [ forward_variable_from(invoker, [
"testonly", "testonly",
"deps", "deps",
... ...
]) ])
... ...
} }
``` ```
### target_name ### target_name
The value of **target_name** varies according to the scope. The value of **target_name** varies with the scope.
``` ```
# Example 15 # Example 15
# The value of target_name varies according to the scope. # The value of target_name varies with the scope.
template("foo") { template("foo") {
# The displayed target_name is "${target_name}". # The displayed target_name is "${target_name}".
print(target_name) print(target_name)
...@@ -426,7 +423,7 @@ To export header files from a module, use **public_configs**. ...@@ -426,7 +423,7 @@ To export header files from a module, use **public_configs**.
``` ```
# Example 16 # Example 16
# b depends on a and inherits the headers of a. # b depends on a and inherits from the headers of a.
config("headers") { config("headers") {
include_dirs = ["//path-to-headers"] include_dirs = ["//path-to-headers"]
... ...
...@@ -443,11 +440,11 @@ executable("b") { ...@@ -443,11 +440,11 @@ executable("b") {
### template ### template
A custom template must contain a subtarget named *target_name*. This subtarget is used as the main target of the template. It should depend on other subtargets so that the subtargets can be compiled. A custom template must contain a subtarget named **target_name**. This subtarget is used as the target of the template and depends on other subtargets. Otherwise, the subtargets will not be compiled.
``` ```
# Example 17 # Example 17
# A custom template must contain a subtarget named target_name. # A custom template must have a subtarget named target_name.
template("foo") { template("foo") {
_code_gen_target = "${target_name}__gen" _code_gen_target = "${target_name}__gen"
code_gen(_code_gen_target) { code_gen(_code_gen_target) {
...@@ -462,7 +459,7 @@ template("foo") { ...@@ -462,7 +459,7 @@ template("foo") {
... ...
group(target_name) { group(target_name) {
deps = [ deps = [
# Since _compile_gen_target depends on _code_gen_target, the main target only needs to depend on _compile_gen_target. # _compile_gen_target depends on _code_gen_target. Therefore, target_name only needs to depend on _compile_gen_target.
":$_compile_gen_target" ":$_compile_gen_target"
] ]
} }
...@@ -471,11 +468,11 @@ template("foo") { ...@@ -471,11 +468,11 @@ template("foo") {
### set_source_assignment_filter ### set_source_assignment_filter
In addition to filtering **sources**, **set_source_assignment_filter** can also be used to filter other variables. After the filtering is complete, clear the filter and **sources** list. In addition to **sources**, **set_source_assignment_filter** can be used to filter other variables. After the filtering is complete, clear the filter and **sources**.
``` ```
# Example 18 # Example 18
# Use set_source_assignment_filter to filter dependencies and add the dependencies whose label matches *:*_res to the dependency list. # Use set_source_assignment_filter to filter dependencies and add the dependencies with labels matching *:*_res to the dependency list.
_deps = [] _deps = []
foreach(_possible_dep, invoker.deps) { foreach(_possible_dep, invoker.deps) {
set_source_assignment_filter(["*:*_res"]) set_source_assignment_filter(["*:*_res"])
...@@ -492,18 +489,20 @@ set_source_assignment_filter([]) ...@@ -492,18 +489,20 @@ set_source_assignment_filter([])
In the latest version, **set_source_assignment_filter** is replaced by **filter_include** and **filter_exclude**. In the latest version, **set_source_assignment_filter** is replaced by **filter_include** and **filter_exclude**.
### Using **deps** for Intra-part Dependencies and **external_deps** for Cross-part Dependencies ### Using deps and external_deps
- An OpenHarmony component is a group of modules that can provide a capability.
- In OpenHarmony, a part is a group of modules that can provide a certain capability. - When defining a module, you must specify **part_name** to indicate the component to which the module belongs.
- When defining a module, you can declare the **part_name** to signify the part to which the module belongs.
- Each part declares its inner-kit for other parts to invoke. For details about the declaration of inner-kit, see **ohos.build** in the source code. - You must also declare **inner-kit** of a component for other components to call. For details about the declaration of component **innerkit**, see **bundle.json** in the source code.
- Inter-part dependencies can only be inner-kit modules.
- If the values of **part_name** of modules **a** and **b** are the same, the two modules belong to the same part. In this case, the dependency between the modules can be declared using **deps**. - **inner-kit** applies only to dependent modules in different components.
- If the values of **part_name** of modules **a** and **b** are different, the two modules belong to different parts. In this case, the dependency between the modules must be declared using **external_deps** in the format of *componentName:moduleName*. See Example 19. - If modules **a** and **b** has the same **part_name**, modules **a** and **b** belong to the same component. In this case, declare the dependency between them using **deps**.
- If modules **a** and **b** have different **part_name**, modules **a** and **b** belong to different components. In this case, declare the dependency between them using **external_deps** in the Component name:Module name format. See Example 19.
``` ```
# Example 19 # Example 19
shared_library("a") { shared_library("a") {
...@@ -512,11 +511,3 @@ In the latest version, **set_source_assignment_filter** is replaced by **filter_ ...@@ -512,11 +511,3 @@ In the latest version, **set_source_assignment_filter** is replaced by **filter_
... ...
} }
``` ```
...@@ -5,12 +5,12 @@ ...@@ -5,12 +5,12 @@
### Kconfig Visual Configuration ### Kconfig Visual Configuration
Kconfig visual configuration is implemented on [Kconfiglib](https://github.com/ulfalizer/Kconfiglib) and [Kconfig](https://www.kernel.org/doc/html/latest/kbuild/kconfig-language.html#introduction). It allows customized configuration of OpenHarmony subsystem components. Kconfig visual configuration is implemented on [Kconfiglib](https://github.com/ulfalizer/Kconfiglib) and [Kconfig](https://www.kernel.org/doc/html/latest/kbuild/kconfig-language.html#introduction). It allows customized configuration of OpenHarmony subsystem components.
This function has the following advantages: Kconfig visual configuration has the following advantages:
- Intuitive display of software component options - Intuitive display of software component options
- High reliability (Linux kernel and Buildroot use Kconfig for visualized configuration) - High reliability (Linux kernel and Buildroot use Kconfig for visualized configuration)
### Key Concepts ### Basic Concepts
- [Kconfig](https://www.kernel.org/doc/html/latest/kbuild/kconfig-language.html#introduction): a visual configuration file format for Linux. - [Kconfig](https://www.kernel.org/doc/html/latest/kbuild/kconfig-language.html#introduction): a visual configuration file format for Linux.
...@@ -22,20 +22,20 @@ This function has the following advantages: ...@@ -22,20 +22,20 @@ This function has the following advantages:
- [Config format conversion](https://gitee.com/openharmony/build/blob/master/tools/component_tools/parse_kconf.py): converts the **config** file generated on the GUI to the standard format for compilation and build. - [Config format conversion](https://gitee.com/openharmony/build/blob/master/tools/component_tools/parse_kconf.py): converts the **config** file generated on the GUI to the standard format for compilation and build.
## Procedure ## Operation Guide
1. Obtain the source code. 1. Obtain the source code.
For details, see [Obtaining Source Code](https://gitee.com/openharmony/docs/blob/master/en/device-dev/get-code/sourcecode-acquire.md). For details, see [Obtaining Source Code](../get-code/sourcecode-acquire.md).
2. Set up the environment. 2. Set up the environment.
The Kconfiglib required for environment configuration has been embedded in the OpenHarmony hb tool. For details about how to install the hb tool, see [Install hb](https://gitee.com/openharmony/docs/blob/master/en/device-dev/quick-start/quickstart-lite-env-setup.md#install-hb). The Kconfiglib required for environment configuration has been embedded in the OpenHarmony hb tool. For details about how to install the hb tool, see [Installing hb](../quick-start/quickstart-lite-env-setup.md).
3. Open the Kconfig configuration interface. 3. Open the Kconfig configuration interface.
```shell ```shell
#Go to the build repository directory. # Go to the build repository directory.
cd build/tools/component_tools cd build/tools/component_tools
menuconfig kconfig menuconfig kconfig
``` ```
...@@ -68,7 +68,7 @@ This function has the following advantages: ...@@ -68,7 +68,7 @@ This function has the following advantages:
Example: Example:
1. Perform a global build. 1. Perform a full build.
```shell ```shell
cp productdefine/common/base/base_product.json productdefine/common/products/ohos-arm64.json cp productdefine/common/base/base_product.json productdefine/common/products/ohos-arm64.json
...@@ -91,23 +91,23 @@ This function has the following advantages: ...@@ -91,23 +91,23 @@ This function has the following advantages:
By default, the file **product.json** is generated in the current directory. You can also use `python3 parse_kconf.py --out="example/out.json"` to specify the file path. By default, the file **product.json** is generated in the current directory. You can also use `python3 parse_kconf.py --out="example/out.json"` to specify the file path.
For more operations, see `python3 parse_kconf.py -h`. For more operations, run `python3 parse_kconf.py -h`.
## FAQs ## FAQs
### The latest component information is missing from the menu. ### Latest Components Not Displayed in the Menu List
The component list [productdefine/common/base/base_product.json](https://gitee.com/openharmony/productdefine_common/blob/master/base/base_product.json) is updated with product updates and iterations. As a result, the Kconfig menu does not contain the latest components. The component list [productdefine/common/base/base_product.json](https://gitee.com/openharmony/productdefine_common/blob/master/base/base_product.json) is updated with product updates and iterations. The Kconfig menu does not contain the latest components.
Solution: **Solution**
- Update the [Kconfig file](https://gitee.com/openharmony/build/blob/master/tools/component_tools/kconfig). Update the [Kconfig file](https://gitee.com/openharmony/build/blob/master/tools/component_tools/kconfig).
```shell ```shell
cd build/tools/component_tools cd build/tools/component_tools
python3 generate_kconfig.py python3 generate_kconfig.py
``` ```
For more details, see `python3 generate_kconfig.py -h`. You can run `python3 generate_kconfig.py -h` to view more options.
...@@ -2,38 +2,33 @@ ...@@ -2,38 +2,33 @@
## Overview ## Overview
The Compilation and Building subsystem is a build framework that supports component-based OpenHarmony development using Generate Ninja \(GN\) and Ninja. You can use this subsystem to: The Compilation and Building subsystem provides a build framework based on Generate Ninja (GN) and Ninja. This subsystem allows you to:
- Assemble components for a product and build the product. - Assemble components into a product and build the product.
- Build chipset source code independently. - Build chipset source code independently.
- Build a single component independently.
### Basic Concepts - Build a single component independently.
Learn the following concepts before you start compilation and building:
- Subsystem
A subsystem is a logical concept. It consists of one or more components. OpenHarmony is designed with a layered architecture, which consists of the kernel layer, system service layer, framework layer, and application layer from bottom to top. System functions are developed by the level of system, subsystem, and component. In a multi-device deployment scenario, you can customize subsystems and components as required.
- Component
A component is a reusable, configurable, and tailorable function unit. Each component has an independent directory, and multiple components can be developed concurrently and built and tested independently.
- GN
Generate Ninja \(GN\) is used to generate Ninja files.
- Ninja
Ninja is a small high-speed build system.
- hb
hb is a command line tool for OpenHarmony to execute build commands. ### Basic Concepts
Learn the following basic concepts before you start:
- Subsystem
A subsystem, as a logical concept, consists of one or more components. OpenHarmony is designed with a layered architecture, which consists of the kernel layer, system service layer, framework layer, and application layer from the bottom up. System functions are developed by levels, from system to subsystem and then to component. In a multi-device deployment scenario, you can customize subsystems and components as required.
- Component
A component is a reusable, configurable, and tailorable function unit. Each component has an independent directory, and can be built and tested independently and developed concurrently.
- GN
GN is short for Generate Ninja. It is used to build Ninja files.
- Ninja
Ninja is a small high-speed building system.
- hb
hb is an OpenHarmony command line tool used to execute build commands.
### Directory Structure ### Directory Structure
...@@ -42,8 +37,8 @@ build/lite ...@@ -42,8 +37,8 @@ build/lite
├── components # Component description file ├── components # Component description file
├── figures # Figures in the readme file ├── figures # Figures in the readme file
├── hb # hb pip installation package ├── hb # hb pip installation package
├── make_rootfs # Script used to create the file system image ├── make_rootfs # Script used to create a file system image
├── config # Build configuration ├── config # Build configurations
│ ├── component # Component-related template definition │ ├── component # Component-related template definition
│ ├── kernel # Kernel-related build configuration │ ├── kernel # Kernel-related build configuration
│ └── subsystem # Subsystem build configuration │ └── subsystem # Subsystem build configuration
...@@ -52,174 +47,197 @@ build/lite ...@@ -52,174 +47,197 @@ build/lite
└── toolchain # Build toolchain configuration, which contains the compiler directories, build options, and linking options └── toolchain # Build toolchain configuration, which contains the compiler directories, build options, and linking options
``` ```
### Build Process ### **Build Process**
The figure below shows the build process. The figure below shows the build process.
**Figure 1** Build process **Figure 1** Build process
![](figure/build-process.jpg "build-process")
![](figure/build-process.jpg)
1. Use **hb set** to set the OpenHarmony source code directory and the product to build.
2. Use **hb build** to build the product, development board, or component.
The procedure is as follows:
(1) Read the **config.gni** file of the development board selected. The file contains the build toolchain, linking commands, and build options.
1. Use **hb set** to set the OpenHarmony source code directory and the product to build. (2) Run the **gn gen** command to read the product configuration and generate the **out** directory and **ninja** files for the solution.
2. Use **hb build** to build the product, development board, or component. The procedure is as follows:
- Read the **config.gni** file of the development board selected. The file contains the build toolchain, linking commands, and build options.
- Run the **gn gen** command to read the product configuration and generate the **out** directory and **ninja** files for the solution.
- Run **ninja -C out/board/product** to start the build.
- Package the build result, set the file attributes and permissions, and create a file system image.
(3) Run **ninja -C out/board/product** to start the build.
(4) Package the files built, set file attributes and permissions, and create a file system image.
## Configuration Rules ## Configuration Rules
To ensure that the chipset and product solutions are pluggable and decoupled from OpenHarmony, the paths, directory trees, and configuration of components, chipset solutions, and product solutions must comply with the following rules: You can build a component, a chipset solution, and a product solution. To ensure that the chipset and product solutions are decoupled from OpenHarmony, follow the rules below:
### Component ### Component
The source code directory for a component is named in the _\{Domain\}/\{Subsystem\}/\{Component\}_ format. The component directory tree is as follows: The component source code directory is named in the *{Domain}/{Subsystem}/{Component}* format. The component directory structure is as follows:
>![](../public_sys-resources/icon-caution.gif) **CAUTION**<br/> > ![icon-caution.gif](../public_sys-resources/icon-caution.gif) **CAUTION**<br/>
>Define component attributes, such as the name, source code directory, function description, mandatory or not, build targets, RAM, ROM, build outputs, adapted kernels, configurable features, and dependencies, in the JSON file of the subsystem in the **build/lite/components** directory. When adding a component, add its definition to the JSON file of the corresponding subsystem. The component configured for a product must have been defined in a subsystem. Otherwise, the verification will fail. > The .json file of the subsystem in the **build/lite/components** directory contains component attributes, including the name, source code directory, function description, mandatory or not, build targets, RAM, ROM, build outputs, adapted kernels, configurable features, and dependencies of the component. When adding a component, add the component information in the .json file of the corresponding subsystem. The component configured for a product must have been defined in a subsystem. Otherwise, the verification will fail.
``` ```
component component
├── interfaces ├── interfaces
│ ├── innerkits # APIs exposed internally among components │ ├── innerkits # APIs exposed internally among components
│ └── kits # App APIs provided for app developers │ └── kits # APIs provided for application developers
├── frameworks # Framework implementation ├── frameworks # Framework implementation
├── services # Service implementation ├── services # Service implementation
── BUILD.gn # Build script ── BUILD.gn # Build script
``` ```
The following example shows how to define attributes of the sensor component of the pan-sensor subsystem: The following example shows how to configure attributes of the sensor service component of the pan-sensor subsystem:
```
{
"name": "@ohos/sensor_lite", # OpenHarmony Package Manager (HPM) component name, in the @Organization/Component name format.
"description": "Sensor services", # Description of the component functions.
"version": "3.1", # Version, which must be the same as the version of OpenHarmony.
"license": "MIT", # Component license.
"publishAs": "code-segment", # Mode for publishing the HPM package. The default value is code-segment.
"segment": {
"destPath": ""
}, # Code restoration path (source code path) set when "publishAs is code-segment.
"dirs": {"base/sensors/sensor_lite"} # Directory structure of the HPM package. This field is mandatory and can be left empty.
"scripts": {}, # Scripts to be executed. This field is mandatory and can be left empty.
"licensePath": "COPYING",
"readmePath": {
"en": "README.rst"
},
"component": { # Component attributes.
"name": "sensor_lite", # Component name.
"subsystem": "", # Subsystem to which the component belongs.
"syscap": [], # System capabilities provided by the component for applications.
"features": [], # List of the component's configurable features. Generally, this parameter corresponds to sub_component in build and can be configured.
"adapted_system_type": [], # Adapted system types, which can be mini, small, and standard. Multiple values are allowed.
"rom": "92KB", # Size of the component's ROM.
"ram": "~200KB", # Size of the component's RAM.
"deps": {
"components": [ # Other components on which this component depends.
"samgr_lite"
],
"third_party": [ # Third-party open-source software on which this component depends.
"bounds_checking_function"
]
}
"build": { # Build-related configurations.
"sub_component": [
""//base/sensors/sensor_lite/services:sensor_service"", # Component build entry
], # Component build entry. Configure the module here.
"inner_kits": [], # APIs between components.
"test": [] # Entry for building the component's test cases.
}
}
}
```
Observe the following rules when writing the component's **BUILD.gn**:
- The build target name must be the same as the component name.
- Define the configurable features in the **BUILD.gn** file of the component. Name the configurable features in the ohos_{subsystem}*{component}*{feature} format. Define the features in component description and configure them in the **config.json** file.
- Define macros in the OHOS_{SUBSYSTEM}*{COMPONENT}*{FEATURE} format.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br>
> The component build script is written in GN. For details about how to use GN, see [GN Quick Start Guide](https://gn.googlesource.com/gn/+/master/docs/quick_start.md). The component is the build target, which can be a static library, a dynamic library, an executable file, or a group.
The following example shows the **foundation/graphic/ui/BUILD.gn** file for a graphics UI component:
```
# Declare the configurable features of the component.
declare_args() {
enable_ohos_graphic_ui_animator = false # Whether to enable animation.
ohos_ohos_graphic_ui_font = "vector" # Configurable font type, which can be vector or bitmap.
}
``` # Basic component functions.
{ shared_library("base") {
"components": [ sources = [
{ ...
"component": "sensor_lite", # Component name ]
"description": "Sensor services", # Brief description of the component include_dirs = [
"optional": "true", # Whether the component is mandatory for the system ...
"dirs": [ # Source code directory of the component ]
"base/sensors/sensor_lite" }
],
"targets": [ # Build entry of the component # Build only when the animator is enabled.
"//base/sensors/sensor_lite/services:sensor_service" if(enable_ohos_graphic_ui_animator ) {
], shared_library("animator") {
"rom": "92KB", # Component ROM sources = [
"ram": "~200KB", # Component RAM (estimated) ...
"output": [ "libsensor_frameworks.so" ], # Component build outputs
"adapted_kernel": [ "liteos_a" ], # Adapted kernel for the component
"features": [], # Configurable features of the component
"deps": {
"components": [ # Other components on which the component depends
"samgr_lite"
],
"third_party": [ # Open-source third-party software on which the component depends
"bounds_checking_function"
] ]
include_dirs = [
...
]
deps = [ :base ]
} }
} }
] ...
} # It is recommended that the target name be the same as the name of the component, which can be an executable file (.bin), shared_library (.so file), static_library (.a file), or a group.
``` executable("ui") {
deps = [
Observe the following rules when configuring **BUILD.gn**: ":base"
]
- The build target name must be the same as the component name.
- Define the configurable features in the **BUILD.gn** file of the component. Name the configurable features in the **ohos\_**\{_subsystem_\}**\_**\{_component_\}**\_**\{_feature_\} format. Define the features in component description and configure them in the **config.json** file.
- Define macros in the **OHOS\_**\{_SUBSYSTEM_\}**\_**\{_COMPONENT_\}**\_**\{_FEATURE_\} format.
>![](../public_sys-resources/icon-note.gif) **NOTE**<br/> GN is used as the build script language for components. For details about how to use GN, see [GN Quick Start Guide](https://gn.googlesource.com/gn/+/master/docs/quick_start.md). In GN, a component is a target to build, which can be a static library, a dynamic library, an executable file, or a group.
# The animator feature is configured by the product.
if(enable_ohos_graphic_ui_animator ) {
deps += [
"animator"
]
}
}
```
The following example shows how to build the **foundation/graphic/ui/BUILD.gn** file for a graphics UI component: ### Chipset Solution
``` The chipset solution is a special component. It is built based on a development board, including the drivers, device API adaptation, and SDK.
# Declare the configurable features of the component
declare_args() {
enable_ohos_graphic_ui_animator = false # Animation switch
ohos_ohos_graphic_ui_font = "vector" # Configurable font type, which can be vector or bitmap
}
# Basic component functions
shared_library("base") {
sources = [
......
]
include_dirs = [
......
]
}
# Build only when the animator is enabled
if(enable_ohos_graphic_ui_animator ) {
shared_library("animator") {
sources = [
......
]
include_dirs = [
......
]
deps = [ :base ]
}
}
......
# It is recommended that the target name be the same as the component name, which can be an executable .bin file, shared_library (.so file), static_library (.a file), or a group.
executable("ui") {
deps = [
":base"
]
# The animator feature is configured by the product.
if(enable_ohos_graphic_ui_animator ) {
deps += [
"animator"
]
}
}
```
### Chipset The source code path is named in the **device/{Development board}/{Chipset solution vendor}** format.
- The chipset solution is a complete solution based on a development board. The solution includes the drivers, API adaptation, and SDK. The chipset solution component is built by default based on the development board selected.
- The chipset solution is a special component, whose source code directory is named in the _**device**/\{Chipset solution vendor\}/\{Development board\}_ format.
- The chipset component is built by default based on the development board selected by the product.
The chipset solution directory tree is as follows: The chipset solution directory structure is as follows:
``` ```
device device
└── company # Chipset solution vendor └── board # Chipset solution vendor
└── board # Name of the development board └── company # Development board name
├── BUILD.gn # Build script ├── BUILD.gn # Build script
├── hals # Southbound APIs for OS adaptation ├── hals # OS device API adaptation
├── linux # Linux kernel version (optional) ├── linux # (Optional) Linux kernel version
│ └── config.gni # Build options for the Linux version │ └── config.gni # Linux build configuration
└── liteos_a # LiteOS kernel version (optional) └── liteos_a # (Optional) LiteOS kernel version
└── config.gni # Build options for the LiteOS Cortex-A version └── config.gni # LiteOS_A build configuration
``` ```
>![](../public_sys-resources/icon-note.gif) **NOTE** <br/> > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br>
>The **config.gni** file contains build-related configurations of the development board. The parameters in the file are globally visible to the system and can be used to build all OS components during the build process. > The **config.gni** file contains build-related configuration of the development board. The parameters in the file are used to build all OS components, and are globally visible to the system during the build process.
The **config.gni** file contains the following key parameters: - The **config.gni** file contains the following key parameters:
``` ```
kernel_type: kernel used by the development board, for example, liteos_a, liteos_m, or linux. kernel_type: Kernel used by the development board, for example, LiteOS_A, LiteOS_M, or Linux.
kernel_version: kernel version used by the development board, for example, 4.19. kernel_version: Kernel version of the development board, for example, 4.19.
board_cpu: CPU of the development board, for example, cortex-a7 or riscv32. board_cpu: CPU of the development board, for example, Cortex-A7 or RISCV32.
board_arch: chipset architecture of the development board, for example, armv7-a or rv32imac. board_arch: Chipset architecture of the development board, for example, ARMv7-A or RV32IMAC.
board_toolchain: name of the customized build toolchain used by the development board, for example, gcc-arm-none-eabi. If this field is not specified, ohos-clang will be used by default. board_toolchain: Name of the customized build toolchain used by the development board, for example, gcc-arm-none-eabi. If this field is not specified, ohos-clang will be used by default.
board_toolchain_prefix: prefix of the build toolchain, for example, gcc-arm-none-eabi. board_toolchain_prefix: Prefix of the toolchain, for example, gcc-arm-none-eabi.
board_toolchain_type: build toolchain type, for example, gcc or clang. Currently, only GCC and clang are supported. board_toolchain_type: Toolchain type. Currently, only GCC and clang are supported.
board_cflags: build options of the .c file configured for the development board. board_cflags: Build options of the .c file configured for the development board.
board_cxx_flags: build options of the .cpp file configured for the development board. board_cxx_flags: Build options of the .cpp file configured for the development board.
board_ld_flags: link options configured for the development board. board_ld_flags: Linking options configured for the development board.
``` ```
### Product ### Product Solution
The product solution is a complete product based on a development board. It includes the OS adaptation, component assembly configuration, startup configuration, and file system configuration. The source code directory of a product solution is named in the **vendor**/\{_Product solution vendor_\}/\{_Product name_\} format. A product solution is also a special component. The product solution is a special component. It is a product built based on a development board. It includes the OS adaptation, component assembly and configuration, startup configuration, and file system configuration. The source code directory is named in the **vendor**/{*Product solution vendor*}/{*Product name*} format.
The product solution directory tree is as follows: The product solution directory structure is as follows:
``` ```
vendor vendor
...@@ -232,172 +250,162 @@ vendor ...@@ -232,172 +250,162 @@ vendor
│ ├── BUILD.gn # Product build script │ ├── BUILD.gn # Product build script
│ └── config.json # Product configuration file │ └── config.json # Product configuration file
│ └── fs.yml # File system packaging configuration │ └── fs.yml # File system packaging configuration
└── ...... └── ...
``` ```
>![](../public_sys-resources/icon-caution.gif) **CAUTION**<br/> > ![icon-caution.gif](/public_sys-resources/icon-caution.gif) **CAUTION**<br/>
>Create directories and files based on the preceding rules for new products. The Compilation and Building subsystem scans the configured products based on the rules. > Follow the preceding rules to create directories and files for new products. The Compilation and Building subsystem scans the configured products based on the rules.
The key directories and files are described as follows: The key directories and files are described as follows:
- **vendor/company/product/init\_configs/etc** 1. **vendor/company/product/init_configs/etc**
This folder contains the **rcS**, **S**_xxx_, and **fstab** scripts. The **init** process runs the **rcS**, **fstab**, and **S**_00_-_xxx_ scripts in sequence before starting system services. The **S**_xxx_ script contains content related to the development board and product. It is used to create device nodes and directories, scan device nodes, and change file permissions. These scripts are copied from the **BUILD.gn** file to the **out** directory of the product as required and packaged into the **rootfs** image. This folder contains the rcS, Sxxx, and fstab scripts. The init process runs the rcS, fstab, and S00-xxx scripts in sequence before starting system services. The **S***xxx* script is used to create device nodes and directories, scan device nodes, and change file permissions for the development board and product. These scripts are copied from the **BUILD.gn** file to the **out** directory of the product as required and packaged into the **rootfs** image.
- **vendor/company/product/init\_configs/init.cfg** 2. **vendor/company/product/init_configs/init.cfg**
This file is the configuration file for the **init** process to start services. Currently, the following commands are supported: This file is the configuration file for the **init** process to start services. Currently, the following commands are supported:
- **start**: starts a service. - **start**: starts a service.
- **mkdir**: creates a folder. - **mkdir**: creates a folder.
- **chmod**: changes the permission on a specified directory or file.
- **chown**: changes the owner group of a specified directory or file. - **chmod**: changes the permission on a specified directory or file.
- **mount**: mounts a device. - **chown**: changes the owner group of a specified directory or file.
- **mount**: mounts a device.
The fields in the file are described as follows: The fields in the file are described as follows:
``` ```
{ {
"jobs" : [{ # Job array. A job corresponds to a command set. Jobs are executed in the following sequence: pre-init > init > post-init. "jobs" : [{ # Job array. A job corresponds to a command set. Jobs are executed in the following sequence: pre-init > init > post-init.
"name" : "pre-init", "name" : "pre-init",
"cmds" : [ "cmds" : [
"mkdir /storage/data", # Create a directory. "mkdir /storage/data", # Create a directory.
"chmod 0755 /storage/data", # Change the permission, which is in 0xxx format, for example, 0755. "chmod 0755 /storage/data", #Modify the permissions. The format of the permission value is 0xxx, for example, 0755.
"mkdir /storage/data/log", "mkdir /storage/data/log",
"chmod 0755 /storage/data/log", "chmod 0755 /storage/data/log",
"chown 4 4 /storage/data/log", # Change the owner group. The first number indicates the UID, and the second indicates the GID. "chown 4 4 /storage/data/log", # Change the owner group. The first number is the user ID (UID), and the second number is the group ID (GID).
...... ...
"mount vfat /dev/mmcblock0 /sdcard rw, umask=000" # The command is in the mount [File system type][source] [target] [flags] [data] format. "mount vfat /dev/mmcblock0 /sdcard rw,umask=000" # The command format is mount [File system type] [source] [target] [flags] [data].
# Currently, flags can only be nodev, noexec, nosuid, or rdonly. # The value of flags can be nodev, noexec, nosuid, or rdonly only.
] ]
}, { }, {
"name" : "init", "name" : "init",
"cmds" : [ # Start services based on the sequence of the cmds array. "cmds" : [ # Start services based on the sequence of the cmds array.
"start shell", # Note that there is only one space between start and the service name. "start shell", # There is only one space between start and the service name.
...... ...
"start service1" "start service1"
] ]
}, { }, {
"name" : "post-init", # Job that is finally executed. Operations performed after the init process is started, for example, mounting a device after the driver initialization. "name" : "post-init", # Job that is finally executed. Operations performed after the init process is started, for example, mounting a device after the driver initialization).
"cmds" : [] "cmds" : []
} }
], ],
"services" : [{ # Service array. A service corresponds to a process. "services" : [{ # Service array. A service corresponds to a process.
"name" : "shell", # Service name "name" : "shell", # Service name.
"path" : ["/sbin/getty", "-n", "-l", "/bin/sh", "-L", "115200", "ttyS000", "vt100"], # Full path of the executable file. It must start with "path". "path" : ["/sbin/getty", "-n", "-l", "/bin/sh", "-L", "115200", "ttyS000", "vt100"], # Full path of the executable file. It must start with "path".
"uid" : 0, # Process UID, which must be the same as that in the binary file. "uid" : 0, # Process UID, which must be the same as that in the binary file.
"gid" : 0, # Process GID, which must be the same as that in the binary file. "gid" : 0, # Process GID, which must be the same as that in the binary file.
"once" : 0, # Whether the process is a one-off process. 1: The proces is a one-off process. The init process does not restart it after the process exits. 0: The process is not a one-off process. The init process restarts it if the process exits. "once" : 0, # Whether the process is a one-off process. The value 1 indicates that process is a one-off process, and the value 0 indicates the opposite. The init process does not restart the one-off process after the process exits.
"importance" : 0, # Whether the process is a key process. 1: The process is a key process. If it exits, the init process restarts the board. 0: The process is not a key process. If it exits, the init process does not restart the board. "importance" : 0, # Whether the process is a key process. The value 1 indicates a key process, and the value 0 indicates the opposite. If a key process exits, the init process will restart the board.
"caps" : [4294967295] "caps" : [4294967295]
}, },
...... ...
] ]
} }
``` ```
- **vendor/company/product/init\_configs/hals** 3. **vendor/company/product/init_configs/hals**
This file stores the content related to OS adaptation of the product. For details about APIs for implementing OS adaptation, see the readme file of each component.
- **vendor/company/product/config.json**
The **config.json** file is the main entry for the build and contains configurations of the development board, OS components, and kernel.
The following example shows the **config.json** file of the IP camera developed based on the hispark\_taurus development board:
```
{
"product_name": "ipcamera", # Product name
"version": "3.0", # config.json version, which is 3.0
"type": "small", # System type, which can be mini, small, or standard
"ohos_version": "OpenHarmony 1.0", # OS version
"device_company": "hisilicon", # Chipset vendor
"board": "hispark_taurus", # Name of the development board
"kernel_type": "liteos_a", # Kernel type
"kernel_version": "3.0.0", # Kernel version
"subsystems": [
{
"subsystem": "aafwk", # Subsystem
"components": [
{ "component": "ability", "features":[ "enable_ohos_appexecfwk_feature_ability = true" ] } # Component and its features
]
},
{
......
}
......
More subsystems and components
}
}
```
- **vendor/company/product/fs.yml**
This file packages the build result to create a configuration file system image, for example, **rootfs.img** \(user-space root file system\) and **userfs.img** \(readable and writable file\). It consists of multiple lists, and each list corresponds to a file system. The fields are described as follows:
```
fs_dir_name: (Mandatory) declares the name of the file system, for example, rootfs or userfs.
fs_dirs: (Optional) configures the mapping between the file directory in the out directory and the system file directory. Each file directory corresponds to a list.
source_dir: (Optional) specifies the target file directory in the out directory. If this field is missing, an empty directory will be created in the file system based on target_dir.
target_dir: (Mandatory) specifies the corresponding file directory in the file system.
ignore_files: (Optional) declares ignored files during the copy operation.
dir_mode: (Optional) specifies the file directory permission, which is set to 755 by default.
file_mode: (Optional) declares permissions of all files in the directory, which is set to 555 by default.
fs_filemode: (Optional) configures files that require special permissions. Each file corresponds to a list.
file_dir: (Mandatory) specifies the detailed file path in the file system.
file_mode: (Mandatory) declares file permissions.
fs_symlink: (Optional) configures the soft link of the file system.
fs_make_cmd: (Mandatory) creates the file system script. The script provided by the OS is stored in the build/lite/make_rootfs directory. Linux, LiteOS, ext4, jffs2, and vfat are supported. Chipset vendors can also customize the script as required.
fs_attr: (Optional) dynamically adjusts the file system based on configuration items.
```
The **fs\_symlink** and **fs\_make\_cmd** fields support the following variables:
- $\{root\_path\}
Code root directory, which corresponds to **$\{ohos\_root\_path\}** of GN
- $\{out\_path\}
**out** directory of the product, which corresponds to **$\{root\_out\_dir\}** of GN
- $\{fs\_dir\}
File system directory, which consists of the following variables
- $\{root\_path\}
- $\{fs\_dir\_name\}
>![](../public_sys-resources/icon-note.gif) **NOTE**<br/>
>**fs.yml** is optional and does not need to be configured for devices without a file system.
- **vendor/company/product/BUILD.gn** This file contains the OS adaptation of the product. For details about APIs for implementing OS adaptation, see the readme file of each component.
This file is the entry for building the source code of the solution vendor and copying the startup configuration file. The **BUILD.gn** file in the corresponding product directory will be built by default if a product is selected. The following example shows how to build the **BUILD.gn** file of a product: 4. **vendor/company/product/config.json**
``` The **config.json** file is the main entry for the build and contains configurations of the development board, OS, and kernel.
group("product") { # The target name must be the same as the product name (level-3 directory name under the product directory).
deps = []
# Copy the init configuration.
deps += [ "init_configs" ]
# Others
......
}
```
The following example shows the **config.json** file of the IP camera developed based on the hispark_taurus board:
## Usage Guidelines ```
{
"product_name": "ipcamera", # Product name
"version": "3.0", # Version of config.json. The value is 3.0.
"type": "small", # System type. The value can be mini, small, or standard.
"ohos_version": "OpenHarmony 1.0", # OS version
"device_company": "hisilicon", # Chipset vendor
"board": "hispark_taurus", # Name of the development board
"kernel_type": "liteos_a", # Kernel type
"kernel_version": "3.0.0", # Kernel version
"subsystems": [
{
"subsystem": "aafwk", # Subsystem
"components": [
{ "component": "ability", "features":[ "enable_ohos_appexecfwk_feature_ability = true" ] } # Selected component and feature configuration
]
},
{
...
}
...
More subsystems and components
}
}
```
5. **vendor/company/product/fs.yml**
This file defines the process for creating a file system image, for example, **rootfs.img** (user-space root file system) and **userfs.img** (readable and writable file). It consists of multiple lists, and each list corresponds to a file system. The fields are described as follows:
```
fs_dir_name: (Mandatory) specifies name of the file system, for example, rootfs or userfs.
fs_dirs: (Optional) specifies the mapping between the file directory in the out directory and the system file directory. Each file directory corresponds to a list.
source_dir: (Optional) specifies target file directory in the out directory. If this field is not specified, an empty directory will be created in the file system based on target_dir.
target_dir: (Mandatory) specifies the file directory in the file system.
ignore_files: (Optional) declares ignored files during the copy operation.
dir_mode: (Optional) specifies the file directory permissions. The default value is 755.
file_mode: (Optional) specifies the permissions of all files in the directory. The default value is 555.
fs_filemode: (Optional) specifies the files that require special permissions. Each file corresponds to a list.
file_dir: (Mandatory) specifies the detailed file path in the file system.
file_mode: (Mandatory) declares file permissions.
fs_symlink: (Optional) specifies the soft link of the file system.
fs_make_cmd: (Mandatory) creates the file system script. The script provided by the OS is located in the build/lite/make_rootfs directory. Linux, LiteOS, ext4, jffs2, and vfat are supported. Chipset vendors can also customize the script as required.
fs_attr: (Optional) dynamically adjusts the file system based on configuration items.
```
The **fs_symlink** and **fs_make_cmd** fields support the following variables:
- ${root_path}: code root directory, which corresponds to **${ohos_root_path}** of GN.
- ${out_path}: **out** directory of the product, which corresponds to **${root_out_dir}** of GN.
- ${fs_dir}: file system directory, which consists of variables ${root_path} and ${fs_dir_name}.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br>
> **fs.yml** is optional and not required for devices without a file system.
6. **vendor/company/product/BUILD.gn**
This file provides the product built entry. It is used to build the source code of the solution vendor and copy the startup configuration file. The **BUILD.gn** file in the corresponding product directory will be built by default if a product is selected.
The following is an example of the **BUILD.gn** file of a product:
```
group("product") { # The name must be the same as the product name (level-3 directory name under the product directory).
deps = []
# Copy the init configuration.
deps += [ "init_configs" ]
# Others
...
}
```
## Guidelines
### Prerequisites ### Prerequisites
The development environment has GN, Ninja, Python 3.7.4 or later, and hb available. For details about installation methods, see [Environment Setup](../quick-start/quickstart-lite-env-setup.md). The development environment has GN, Ninja, Python 3.9.2 or later, and hb available. For details about the installation method, see [Setting Up Environments for the Mini and Small Systems](../quick-start/quickstart-lite-env-setup.md).
### Using hb ### Using hb
**hb** is a command line tool for OpenHarmony to execute build commands. Common hb commands are described as follows: **hb** is an OpenHarmony command line tool for executing build commands. Common hb commands are described as follows:
**hb set** **hb set**
``` ```
hb set -h hb set -h
...@@ -410,13 +418,15 @@ optional arguments: ...@@ -410,13 +418,15 @@ optional arguments:
-p, --product Set OHOS board and kernel -p, --product Set OHOS board and kernel
``` ```
- **hb set** \(without argument\): starts the default setting process. - If you run **hb set** with no argument, the default setting process starts.
- **hb set -root** _dir_: sets the root directory of the code.
- **hb set -p**: sets the product to build. - You can run **hb set -root** *dir* to set the root directory of the source code.
- You can run **hb set -p** to set the product to build.
**hb env** **hb env**
Displays the current configuration. Displays the current settings.
``` ```
hb env hb env
...@@ -428,57 +438,66 @@ hb env ...@@ -428,57 +438,66 @@ hb env
[OHOS INFO] device path: xxx/device/hisilicon/hispark_taurus/sdk_linux_4.19 [OHOS INFO] device path: xxx/device/hisilicon/hispark_taurus/sdk_linux_4.19
``` ```
**hb build** **hb build**
``` ```
hb build -h hb build -h
usage: hb build [-h] [-b BUILD_TYPE] [-c COMPILER] [-t [TEST [TEST ...]]] usage: hb build [-h] [-b BUILD_TYPE] [-c COMPILER] [-t [TEST [TEST ...]]] [-cpu TARGET_CPU] [--dmverity] [--tee]
[--dmverity] [--tee] [-p PRODUCT] [-f] [-n] [-p PRODUCT] [-f] [-n] [-T [TARGET [TARGET ...]]] [-v] [-shs] [--patch] [--compact-mode]
[-T [TARGET [TARGET ...]]] [-v] [-shs] [--patch] [--gn-args GN_ARGS] [--keep-ninja-going] [--build-only-gn] [--log-level LOG_LEVEL] [--fast-rebuild]
[--device-type DEVICE_TYPE] [--build-variant BUILD_VARIANT]
[component [component ...]] [component [component ...]]
positional arguments: positional arguments:
component name of the component component name of the component, mini/small only
optional arguments: optional arguments:
-h, --help show this help message and exit -h, --help show this help message and exit
-b BUILD_TYPE, --build_type BUILD_TYPE -b BUILD_TYPE, --build_type BUILD_TYPE
release or debug version release or debug version, mini/small only
-c COMPILER, --compiler COMPILER -c COMPILER, --compiler COMPILER
specify compiler specify compiler, mini/small only
-t [TEST [TEST ...]], --test [TEST [TEST ...]] -t [TEST [TEST ...]], --test [TEST [TEST ...]]
compile test suit compile test suit
--dmverity Enable dmverity -cpu TARGET_CPU, --target-cpu TARGET_CPU
select cpu
--dmverity enable dmverity
--tee Enable tee --tee Enable tee
-p PRODUCT, --product PRODUCT -p PRODUCT, --product PRODUCT
build a specified product with build a specified product with {product_name}@{company}
{product_name}@{company}, eg: camera@huawei
-f, --full full code compilation -f, --full full code compilation
-n, --ndk compile ndk -n, --ndk compile ndk
-T [TARGET [TARGET ...]], --target [TARGET [TARGET ...]] -T [TARGET [TARGET ...]], --target [TARGET [TARGET ...]]
Compile single target compile single target
-v, --verbose show all command lines while building -v, --verbose show all command lines while building
-shs, --sign_haps_by_server -shs, --sign_haps_by_server
sign haps by server sign haps by server
--patch apply product patch before compiling --patch apply product patch before compiling
--compact-mode compatible with standard build system set to false if we use build.sh as build entrance
--dmverity Enable dmverity --gn-args GN_ARGS specifies gn build arguments, eg: --gn-args="foo="bar" enable=true blah=7"
-p PRODUCT, --product PRODUCT --keep-ninja-going keeps ninja going until 1000000 jobs fail
build a specified product with --build-only-gn only do gn parse, donot run ninja
{product_name}@{company}, eg: ipcamera@hisilcon --log-level LOG_LEVEL
-f, --full full code compilation specifies the log level during compilationyou can select three levels: debug, info and error
-T [TARGET [TARGET ...]], --target [TARGET [TARGET ...]] --fast-rebuild it will skip prepare, preloader, gn_gen steps so we can enable it only when there is no change
Compile single target for gn related script
--device-type DEVICE_TYPE
specifies device type
--build-variant BUILD_VARIANT
specifies device operating mode
``` ```
- **hb build** \(without argument\): builds the code based on the configured code directory, product, and options. The **-f** option deletes all products to be built, which is equivalent to running **hb clean** and **hb build**. - If you run **hb build** with no argument, the previously configured code directory, product, and options are used for the build. The **-f** option deletes all products to be built. It is equivalent to running **hb clean** and **hb build**.
- **hb build** _\{component\_name\}_: builds a product component separately based on the development board and kernel set for the product, for example, **hb build kv\_store**.
- **hb build -p ipcamera@hisilicon**: skips the **set** step and builds the product directly. - You can run **hb build** *{component_name}* to build product components separately based on the development board and kernel set for the product, for example, **hb build kv_store**.
- You can run **hb build** in **device/device\_company/board** to select the kernel and start the build based on the current development board and the selected kernel to generate an image that contains the kernel and driver only.
- You can run **hb build -p ipcamera@hisilicon** to skip the setting step and build the product directly.
- You can run **hb build** in **device/board/device_company** to select the kernel and build an image that contains the kernel and drivers only based on the current development board and the selected kernel.
**hb clean** **hb clean**
You can run **hb clean** to clear the build result of the product in the **out** directory and retain the **args.gn** and **build.log** files only. To clear files in a specified directory, add the directory parameter to the command, for example, **hb clean out/xxx/xxx**. You can run **hb clean** to delete all the files except **args.gn** and **build.log** in the **out** directory. To clear files in a specified directory, add the directory parameter to the command, for example, **hb clean out/board/product**. By default, the files in the **out** directory are cleared.
``` ```
hb clean hb clean
...@@ -495,477 +514,468 @@ optional arguments: ...@@ -495,477 +514,468 @@ optional arguments:
To add a component, determine the subsystem to which the component belongs and the component name, and then perform the following steps: To add a component, determine the subsystem to which the component belongs and the component name, and then perform the following steps:
1. Add the component build script after the source code development is complete. 1. Add the component build script after the source code development is complete.
The following example adds the **BUILD.gn** script \(stored in the **applications/sample/hello\_world** directory\) to build the **hello\_world** component \(as an executable file\). The following example shows the **BUILD.gn** script (in the **applications/sample/hello_world** directory) for the **hello_world** executable file.
``` ```
executable("hello_world") { executable("hello_world") {
include_dirs = [ include_dirs = [
"include", "include",
]
sources = [
"src/hello_world.c"
] ]
} sources = [
``` "src/hello_world.c"
]
The above script is used to build **hello\_world** that can run on OpenHarmony. }
```
To build the preceding component separately, select a product via the **hb set** command and run the **-T** command.
This script can be used to build a file named **hello_world** that can run on OpenHarmony.
```
hb build -f -T //applications/sample/hello_world To build the preceding component separately, run **hb set** to select a product and run the following command to build **hello_world** separately.
```
```
After the component functions are verified on the development board, perform steps 2 to 4 to configure the component to the product. hb build -f -T //applications/sample/hello_world
```
2. Add component description.
After the component functions are verified on the development board, perform steps 2 to 4 to add the component to the product.
The component description is stored in the **build/lite/components** directory. New components must be added to the JSON file of the corresponding subsystem. The component description must contain the following fields:
2. Add the component description.
- **component**: name of the component
- **description**: brief description of the component The component description is stored in the **build/lite/components** directory. Add the new component to the .json file of the corresponding subsystem. The component description must contain the following fields:
- **optional**: whether the component is optional
- **dirs**: source code directory of the component - **component**: component name.
- **targets**: component build entry - **description**: description of the component functions.
- **optional**: whether the component is optional.
For example, to add the **hello\_world** component to the application subsystem, add the **hello\_world** object to the **applications.json** file. - **dirs**: source code directory of the component.
- **targets**: component build entry.
```
{ The following is an example of adding the **hello_world** component to the **applications.json** file.
"components": [
{ ```
"component": "hello_world", {
"description": "Hello world.", "components": [
"optional": "true", {
"dirs": [ "component": "hello_world",
"applications/sample/hello_world" "description": "Hello world.",
], "optional": "true",
"targets": [ "dirs": [
"//applications/sample/hello_world" "applications/sample/hello_world"
] ],
}, "targets": [
... "//applications/sample/hello_world"
]
},
...
]
}
```
3. Add the component to the product.
The product configuration file **config.json** is located in the **vendor/company/product/** directory. This file contains the product name, OpenHarmony version, device vendor, development board, kernel type, kernel version, subsystems, and components. The following example adds **hello_world** to the **my_product.json** file:
```
{
"product_name": "hello_world_test",
"ohos_version": "OpenHarmony 1.0",
"device_company": "hisilicon",
"board": "hispark_taurus",
"kernel_type": "liteos_a",
"kernel_version": "1.0.0",
"subsystems": [
{
"subsystem": "applications",
"components": [
{ "component": "hello_world", "features":[] }
]
},
...
] ]
} }
``` ```
3. Configure the component for the product.
The **config.json** file is stored in the **vendor/company/product/** directory. The file must contain the product name, OpenHarmony version, device vendor, development board, kernel type, kernel version, and the subsystem and component to configure. The following example adds the **hello\_world** component to the **my\_product.json** configuration file:
```
{
"product_name": "hello_world_test",
"ohos_version": "OpenHarmony 1.0",
"device_company": "hisilicon",
"board": "hispark_taurus",
"kernel_type": "liteos_a",
"kernel_version": "1.0.0",
"subsystems": [
{
"subsystem": "applications",
"components": [
{ "component": "hello_world", "features":[] }
]
},
...
]
}
```
4. Build the product.
1. Run the **hb set** command in the root code directory and select the product.
2. Run the **hb build** command.
4. Build the product.
1. Run the **hb set** command in the root code directory and select the product.
2. Run the **hb build** command.
### Adding a Chipset Solution ### Adding a Chipset Solution
The following uses the RTL8720 development board provided by Realtek as an example. To a chipset solution, perform the following steps: The following uses the RTL8720 development board provided by Realtek as an example. To a chipset solution, perform the following steps:
1. Create a directory for the chipset solution. 1. Create a directory for the chipset solution based on the [configuration rules](#chipset-solution).
Run the following command in the root directory of the code:
To create a directory based on [Configuration Rules](#configuration-rules), run the following command in the root code directory:
```
``` mkdir -p device/board/realtek/rtl8720
mkdir -p device/realtek/rtl8720 ```
```
2. Create a directory for kernel adaptation and write the **config.gni** file of the development board.
2. Create a directory for kernel adaptation and build the **config.gni** file of the development board. For example, to adapt the LiteOS-A kernel to the RTL8720 development board, write the **device/realtek/rtl8720/liteo_a/config.gni** file as follows:
For example, to adapt the LiteOS-A kernel to the RTL8720 development board, configure the **device/realtek/rtl8720/liteos\_a/config.gni** file as follows: ```
# Kernel type, e.g. "linux", "liteos_a", "liteos_m".
``` kernel_type = "liteos_a"
# Kernel type, e.g. "linux", "liteos_a", "liteos_m".
kernel_type = "liteos_a" # Kernel version.
kernel_version = "3.0.0"
# Kernel version.
kernel_version = "3.0.0" # Board CPU type, e.g. "cortex-a7", "riscv32".
board_cpu = "real-m300"
# Board CPU type, e.g. "cortex-a7", "riscv32".
board_cpu = "real-m300" # Board arch, e.g. "armv7-a", "rv32imac".
board_arch = ""
# Board arch, e.g. "armv7-a", "rv32imac".
board_arch = "" # Toolchain name used for system compiling.
# E.g. gcc-arm-none-eabi, arm-linux-harmonyeabi-gcc, ohos-clang, riscv32-unknown-elf.
# Toolchain name used for system compiling. # Note: The default toolchain is "ohos-clang". It's not mandatory if you use the default toochain.
# E.g. gcc-arm-none-eabi, arm-linux-harmonyeabi-gcc, ohos-clang, riscv32-unknown-elf. board_toolchain = "gcc-arm-none-eabi"
# Note: The default toolchain is "ohos-clang". It's not mandatory if you use the default toochain.
board_toolchain = "gcc-arm-none-eabi" # The toolchain path installed, it's not mandatory if you have added toolchain path to your ~/.bashrc.
board_toolchain_path =
# The toolchain path instatlled, it's not mandatory if you have added toolchian path to your ~/.bashrc. rebase_path("//prebuilts/gcc/linux-x86/arm/gcc-arm-none-eabi/bin",
board_toolchain_path = root_build_dir)
rebase_path("//prebuilts/gcc/linux-x86/arm/gcc-arm-none-eabi/bin",
root_build_dir) # Compiler prefix.
board_toolchain_prefix = "gcc-arm-none-eabi-"
# Compiler prefix.
board_toolchain_prefix = "gcc-arm-none-eabi-" # Compiler type, "gcc" or "clang".
board_toolchain_type = "gcc"
# Compiler type, "gcc" or "clang".
board_toolchain_type = "gcc" # Board related common compile flags.
board_cflags = []
# Board related common compile flags. board_cxx_flags = []
board_cflags = [] board_ld_flags = []
board_cxx_flags = [] ```
board_ld_flags = []
``` 3. Write the build script.
Create the **BUILD.gn** file in the development board directory. The target name must be the same as that of the development board. The following is an example of the **device/realtek/rtl8720/BUILD.gn** file for the RTL8720 development board:
3. Build the script.
```
Create the **BUILD.gn** file in the development board directory. The target name must be the same as that of the development board. The content in the **device/realtek/rtl8720/BUILD.gn** file is configured as follows: group("rtl8720") { # The build target can be shared_library, static_library, or an executable file.
# Content
``` ...
group("rtl8720") { # The target can be shared_library, static_library, or an executable file. }
# Content ```
......
} 4. Build the chipset solution.
```
Run the **hb build** command in the development board directory to start the build.
4. Build the chipset solution.
Run the **hb build** command in the development board directory to start the build.
### Adding a Product Solution ### Adding a Product Solution
You can use the Compilation and Building subsystem to customize product solutions by assembling chipset solutions and components. The procedure is as follows: You can customize a product solution by flexibly assembling a chipset solution and components. The procedure is as follows:
1. Create a product directory. 1. Create a product directory based on the [configuration rules](#product-solution).
The following uses the Wi-Fi IoT component on the RTL8720 development board as an example. Run the following command in the root code directory to create a product directory based on [Configuration Rules](#configuration-rules): The following uses the Wi-Fi IoT module on the RTL8720 development board as an example. Run the following command in the root directory to create a product directory:
``` ```
mkdir -p vendor/my_company/wifiiot mkdir -p vendor/my_company/wifiiot
``` ```
2. Assemble the product. 2. Assemble the product.
Create the **config.json** file in the product directory. The **vendor/my\_company/wifiiot/config.json** file is as follows: Create a **config.json** file, for example for wifiiot, in the product directory. The **vendor/my_company/wifiiot/config.json** file is as follows:
``` ```
{ {
"product_name": "wifiiot", # Product name "product_name": "wifiiot", # Product name
"version": "3.0", # config.json version, which is 3.0 "version": "3.0", # Version of config.json. The value is 3.0.
"type": "small", # System type, which can be mini, small, or standard "type": "small", # System type. The value can be mini, small, or standard.
"ohos_version": "OpenHarmony 1.0", # OS version "ohos_version": "OpenHarmony 1.0", # OS version
"device_company": "realtek", # Name of the chipset solution vendor "device_company": "realtek", # Name of the chipset solution vendor
"board": "rtl8720", # Name of the development board "board": "rtl8720", # Name of the development board
"kernel_type": "liteos_m", # Kernel type "kernel_type": "liteos_m", # Kernel type
"kernel_version": "3.0.0", # Kernel version "kernel_version": "3.0.0", # Kernel version
"subsystems": [ "subsystems": [
{ {
"subsystem": "kernel", # Subsystem "subsystem": "kernel", # Subsystem
"components": [ "components": [
{ "component": "liteos_m", "features":[] } # Component and its features { "component": "liteos_m", "features":[] } # Component and its features
] ]
}, },
... ...
{ {
More subsystems and components More subsystems and components
} }
] ]
} }
``` ```
Before the build, the Compilation and Building subsystem checks the validity of fields, including **device\_company**, **board**, **kernel\_type**, **kernel\_version**, **subsystem**, and **component**. The **device\_company**, **board**, **kernel\_type**, and **kernel\_version** fields must match the current chipset solution, and **subsystem** and **component** must match the component description in the **build/lite/components** file. > ![icon-caution.gif](../public_sys-resources/icon-caution.gif) **CAUTION**<br/>
> Before the build, the Compilation and Building subsystem checks the validity of fields in **config.json**. The **device_company**, **board**, **kernel_type**, and **kernel_version** fields must match the fields of the chipset solution, and **subsystem** and **component** must match the component description in the **build/lite/components** file.
3. Implement adaptation to OS APIs.
3. Implement adaptation to OS APIs.
Create the **hals** directory in the product directory and store the source code as well as the build script for OS adaptation in this directory.
Create the **hals** directory in the product directory and save the source code as well as the build script for OS adaptation in this directory.
4. Configure the system service.
4. Configure system services.
Create the **init\_configs** directory in the product directory and then the **init.cfg** file in the newly created directory. Configure the system service to be started.
Create the **init_configs** directory in the product directory and then the **init.cfg** file in the **init_configs** directory, and configure the system services to be started.
5. \(Optional\) Configure the init process only for the Linux kernel.
5. (Optional) Configure the init process for the Linux kernel.
Create the **etc** directory in the **init\_configs** directory, and then the **init.d** folder and the **fstab** file in the newly created directory. Then, create the **rcS** and **S**_xxx_ files in the **init.d** file and edit them based on product requirements.
Create the **etc** directory in the **init_configs** directory, and then the **init.d** folder and the **fstab** file in the **etc** directory. Then, create the **rcS** and **S***xxx* files in the **init.d** file and edit them based on product requirements.
6. \(Optional\) Configure the file system image only for the development board that supports the file system.
6. (Optional) Configure the file system image for the development board that supports the file system.
Create the **fs.yml** file in the product directory and configure it as required. A typical **fs.yml** file is as follows:
Create a **fs.yml** file in the product directory and configure it as required. A typical **fs.yml** file is as follows:
```
- ```
fs_dir_name: rootfs # Image name -
fs_dirs: fs_dir_name: rootfs # Image name
- fs_dirs:
# Copy the files in the out/my_board/my_product/bin directory to the rootfs/bin directory and ignore the .bin files related to testing. -
source_dir: bin # Copy the files in the out/my_board/my_product/bin directory to the rootfs/bin directory and ignore the .bin files related to testing.
target_dir: bin source_dir: bin
ignore_files: target_dir: bin
- Test.bin ignore_files:
- TestSuite.bin - Test.bin
- - TestSuite.bin
# Copy the files in the out/my_board/my_product/libs directory to the rootfs/lib directory, ignore all .a files, and set the file permissions to 644 and folder permissions 755. -
source_dir: libs # Copy the files in the out/my_board/my_product/libs directory to the rootfs/lib directory, ignore all .a files, and set the file permissions to 644 and folder permissions 755.
target_dir: lib source_dir: libs
ignore_files: target_dir: lib
- .a ignore_files:
dir_mode: 755 - .a
file_mode: 644 dir_mode: 755
- file_mode: 644
source_dir: usr/lib -
target_dir: usr/lib source_dir: usr/lib
ignore_files: target_dir: usr/lib
- .a ignore_files:
dir_mode: 755 - .a
file_mode: 644 dir_mode: 755
- file_mode: 644
source_dir: config -
target_dir: etc source_dir: config
- target_dir: etc
source_dir: system -
target_dir: system source_dir: system
- target_dir: system
source_dir: sbin -
target_dir: sbin source_dir: sbin
- target_dir: sbin
source_dir: usr/bin -
target_dir: usr/bin source_dir: usr/bin
- target_dir: usr/bin
source_dir: usr/sbin -
target_dir: usr/sbin source_dir: usr/sbin
- target_dir: usr/sbin
# Create an empty proc directory. -
target_dir: proc # Create an empty proc directory.
- target_dir: proc
target_dir: mnt -
- target_dir: mnt
target_dir: opt -
- target_dir: opt
target_dir: tmp -
- target_dir: tmp
target_dir: var -
- target_dir: var
target_dir: sys -
- target_dir: sys
source_dir: etc -
target_dir: etc source_dir: etc
- target_dir: etc
source_dir: vendor -
target_dir: vendor source_dir: vendor
- target_dir: vendor
target_dir: storage -
target_dir: storage
fs_filemode:
- fs_filemode:
file_dir: lib/ld-uClibc-0.9.33.2.so -
file_mode: 555 file_dir: lib/ld-uClibc-0.9.33.2.so
- file_mode: 555
file_dir: lib/ld-2.24.so -
file_mode: 555 file_dir: lib/ld-2.24.so
- file_mode: 555
file_dir: etc/init.cfg -
file_mode: 400 file_dir: etc/init.cfg
fs_symlink: file_mode: 400
- fs_symlink:
# Create the soft link ld-musl-arm.so.1 -> libc.so in the rootfs/lib directory. -
source: libc.so # Create the soft link ld-musl-arm.so.1 -> libc.so in the rootfs/lib directory.
link_name: ${fs_dir}/lib/ld-musl-arm.so.1 source: libc.so
- link_name: ${fs_dir}/lib/ld-musl-arm.so.1
source: mksh -
link_name: ${fs_dir}/bin/sh source: mksh
- link_name: ${fs_dir}/bin/sh
source: mksh -
link_name: ${fs_dir}/bin/shell source: mksh
fs_make_cmd: link_name: ${fs_dir}/bin/shell
# Create an ext4 image for the rootfs directory using the script. fs_make_cmd:
- ${root_path}/build/lite/make_rootfs/rootfsimg_linux.sh ${fs_dir} ext4 # Run the script to create an ext4 image from rootfs.
- - ${root_path}/build/lite/make_rootfs/rootfsimg_linux.sh ${fs_dir} ext4
fs_dir_name: userfs -
fs_dirs: fs_dir_name: userfs
- fs_dirs:
source_dir: storage/etc -
target_dir: etc source_dir: storage/etc
- target_dir: etc
source_dir: data -
target_dir: data source_dir: data
fs_make_cmd: target_dir: data
- ${root_path}/build/lite/make_rootfs/rootfsimg_linux.sh ${fs_dir} ext4 fs_make_cmd:
- ${root_path}/build/lite/make_rootfs/rootfsimg_linux.sh ${fs_dir} ext4
```
```
7. \(Optional\) Configure patches if the product and components need to be patched.
7. (Optional) Configure patches if the product and components need to be patched.
Create the **patch.yml** file in the product directory and configure it as required. A typical **patch.yml** file is as follows:
Create a **patch.yml** file in the product directory and configure it as required. A typical **patch.yml** file is as follows:
```
# Directory in which the patch is to be installed ```
foundation/communication/dsoftbus: # Directory in which the patch is to be installed
# Directory in which the patch is stored foundation/communication/dsoftbus:
- foundation/communication/dsoftbus/1.patch # Directory in which the patch is stored.
- foundation/communication/dsoftbus/2.patch - foundation/communication/dsoftbus/1.patch
third_party/wpa_supplicant: - foundation/communication/dsoftbus/2.patch
- third_party/wpa_supplicant/1.patch third_party/wpa_supplicant:
- third_party/wpa_supplicant/2.patch - third_party/wpa_supplicant/1.patch
- third_party/wpa_supplicant/3.patch - third_party/wpa_supplicant/2.patch
... - third_party/wpa_supplicant/3.patch
``` ...
```
If you add **--patch** when running the **hb build** command, the patch file can be added to the specified directory before the build.
Add **--patch** when running the **hb build** command. Then, the patch files can be added to the specified directory before the build.
```
hb build -f --patch ```
``` hb build -f --patch
```
8. Build the script.
8. Write the build script.
Create the **BUILD.gn** file in the product directory and write the script. The following **BUILD.gn** file uses the Wi-Fi IoT component in [1](#li1970321162111) as an example:
Create a **BUILD.gn** file in the product directory and write the script. The following **BUILD.gn** file uses the Wi-Fi IoT module in step 1 as an example:
```
group("wifiiot") { # The target name must be the same as the product name. ```
deps = [] group("wifiiot") { # The target name must be the same as the product name.
# Copy the init configuration. deps = []
deps += [ "init_configs" ] # Copy the init configuration.
# Build the hals directory. deps += [ "init_configs" ]
deps += [ "hals" ] # Add **hals**.
# Others deps += [ "hals" ]
...... # Others
} ...
``` }
```
9. Build the product.
9. Build the product.
Run the **hb set** command in the code root directory, select the new product as prompted, and run the **hb build** command.
Run the **hb set** command in the code root directory, select the new product as prompted, and run the **hb build** command.
## Troubleshooting ## Troubleshooting
### Invalid -- w Option ### "usr/sbin/ninja: invalid option -- w" Displayed During the Build Process
- **Symptom**
The build fails, and "usr/sbin/ninja: invalid option -- w" is displayed.
- **Cause**
The Ninja version in the build environment is outdated and does not support the **--w** option.
- **Solution**
Uninstall Ninja and GN and follow the instructions provided in [IDE](../get-code/gettools-ide.md) to install Ninja and GN of the required version.
### Library ncurses Not Found
- **Symptom**
The build fails, and "/usr/bin/ld: cannot find -lncurses" is displayed.
- **Cause**
The ncurses library is not installed.
- **Solution**
```
sudo apt-get install lib32ncurses5-dev
```
### mcopy not Found
- **Symptom**
The build fails, and "line 77: mcopy: command not found" is displayed.
- **Cause**
mcopy is not installed.
- **Solution**
```
sudo apt-get install dosfstools mtools
```
### No riscv File or Directory
- **Symptom**
The build fails, and the following information is displayed:
riscv32-unknown-elf-gcc: error trying to exec 'cc1': execvp: No such file or directory. - **Symptom**
The build fails, and **usr/sbin/ninja: invalid option -- w** is displayed.
- **Cause** - **Possible Causes**
The Ninja version in use does not support the **--w** option.
Permission is required to access files in the **riscv** compiler directory. - **Solution**
Uninstall Ninja and GN, and [install Ninja and GN of the required version](../get-code/gettools-ide.md).
- **Solution** ### "/usr/bin/ld: cannot find -lncurses" Displayed During the Build Process
Run the following command to query the directory where **gcc\_riscv32** is located: - **Symptom**
The build fails, and **/usr/bin/ld: cannot find -lncurses** is displayed.
``` - **Possible Causes**
which riscv32-unknown-elf-gcc
``` The ncurses library is not installed.
- **Solution**
```
sudo apt-get install lib32ncurses5-dev
```
Run the **chmod** command to change the directory permission to **755**. ### "line 77: mcopy: command not found" Displayed During the Build Process
- **Symptom**
The build fails, and **line 77: mcopy: command not found** is displayed.
### No Crypto - **Possible Causes**
mcopy is not installed.
- **Symptom** - **Solution**
```
sudo apt-get install dosfstools mtools
```
The build fails, and "No component named 'Crypto'" is displayed. ### "riscv32-unknown-elf-gcc: error trying to exec 'cc1': execvp: No such file or directory" Displayed During the Build Process
- **Cause** - **Symptom**
The build fails, and the following information is displayed: <br>**riscv32-unknown-elf-gcc: error trying to exec 'cc1': execvp: No such file or directory**
Crypto is not installed in Python 3. - **Possible Causes**
Permission is required to access files in the RISC-V compiler directory.
- **Solution** - **Solution**
1. Run the following command to query the Python version:
``` 1. Run the following command to locate **gcc_riscv32**:
python3 --version
```
2. Ensure that Python 3.7 or later is installed, and then run the following command to install pycryptodome: ```
which riscv32-unknown-elf-gcc
```
``` 2. Run the **chmod** command to change the directory permission to **755**.
sudo pip3 install pycryptodome
```
### Unexpected Operator ### "No module named 'Crypto'" Displayed During the Build Process
- **Symptom** - **Symptom**
The build fails, and **No module named 'Crypto'** is displayed.
The build fails, and "xx.sh \[: xx unexpected operator" is displayed. - **Possible Causes**
Crypto is not installed in Python 3.
- **Cause** - **Solution**
1. Run the following command to query the Python version:
```
python3 --version
```
2. Ensure that Python 3.9.2 or later is installed, and then run the following command to install PyCryptodome:
```
sudo pip3 install pycryptodome
```
The build environment is shell, not bash. ### "xx.sh : xx unexpected operator" Displayed During the Build Process
- **Solution** - **Symptom**
The build fails, and **xx.sh [: xx unexpected operator** is displayed.
``` - **Possible Causes**
sudo rm -rf /bin/sh
sudo ln -s /bin/bash /bin/sh The build environment shell is not bash.
```
- **Solution**
```
sudo rm -rf /bin/sh
sudo ln -s /bin/bash /bin/sh
```
# Building the Standard System<a name="EN-US_TOPIC_0000001076490572"></a> # Building the Standard System
## Overview<a name="section17466112012244"></a> ## Overview
The compilation and building subsystem provides a framework based on Generate Ninja \(GN\) and Ninja. This subsystem allows you to: The Compilation and Building subsystem provides a build framework based on Generate Ninja (GN) and Ninja. This subsystem allows you to:
- Build products based on different chipset platforms, for example, Hi3516D V300. - Build products based on different chipset platforms, for example, hispark_taurus_standard.
- Package capabilities required by a product by assembling modules based on the product configuration. - Package capabilities required by a product by assembling components based on the product configuration.
### Basic Concepts<a name="section445513507246"></a> ### Basic Concepts
It is considered best practice to learn the following basic concepts before you start building: Learn the following basic concepts before you start:
- **Platform** - Platform
A platform consists of the development board and kernel. The supported subsystems and components vary with the platform.
A platform is a combination of development boards and kernels. - Subsystem
OpenHarmony is designed with a layered architecture, which consists of the kernel layer, system service layer, framework layer, and application layer from the bottom up. System functions are developed by levels, from system to subsystem and then to component. In a multi-device deployment scenario, you can customize subsystems and components as required. A subsystem, as a logical concept, consists of the least required components.
Supported subsystems and modules vary according to the platform. - Component
A component is a reusable software unit that contains source code, configuration files, resource files, and build scripts. Integrated in binary mode, a component can be built and tested independently.
- **Subsystems** - GN
GN is short for Generate Ninja. It is used to build Ninja files.
OpenHarmony is designed with a layered architecture, which from bottom to top consists of the kernel layer, system service layer, framework layer, and application layer. System functions are expanded by levels, from system to subsystem, and further to module. In a multi-device deployment scenario, unnecessary subsystems and modules can be excluded from the system as required. A subsystem is a logical concept and is a flexible combination of functions. - Ninja
Ninja is a small high-speed building system.
- **Module** ### Working Principles
A module is a reusable software binary unit that contains source code, configuration files, resource files, and build scripts. A module can be built independently, integrated in binary mode, and then tested independently. The process for building an OpenHarmony system is as follows:
- **GN** - Parsing commands: Parse the name of the product to build and load related configurations.
GN is short for Generate Ninja, which is used to generate Ninja files. - Running GN: Configure the toolchain and global options based on the product name and compilation type.
- **Ninja** - Running Ninja: Start building and generate a product distribution.
Ninja is a small high-speed build system. ### Constraints
- You need to obtain the source code using method 3 described in [Obtaining Source Code](../get-code/sourcecode-acquire.md).
### Working Principles<a name="section12541217142510"></a> - Ubuntu 18.04 or later must be used.
The process to build OpenHarmony is as follows: - You must install the software packages required for build.
The command is as follows:
```
# Run the script in the home directory.
# ./build/build_scripts/env_setup.sh
# Do not run the command as the **root** user. Otherwise, the environment variables will be added to the **root** user. If your **shell** is not **bash** or **Zsh**, you need to manually configure the following content to your environment variables after the execution. To view your environment variables, run the **cd** command to go to your home directory and view the hidden files.
# export PATH=/home/tools/llvm/bin:$PATH
# export PATH=/home/tools/hc-gen:$PATH
# export PATH=/home/tools/gcc_riscv32/bin:$PATH
# export PATH=/home/tools/ninja:$PATH
# export PATH=/home/tools/node-v12.20.0-linux-x64/bin:$PATH
# export PATH=/home/tools/gn:$PATH
# export PATH=/root/.local/bin:$PATH
# If you do not need to run the script, you need to install the following:
apt-get update -y
apt-get install -y apt-utils binutils bison flex bc build-essential make mtd-utils gcc-arm-linux-gnueabi u-boot-tools python3.9.2 python3-pip git zip unzip curl wget gcc g++ ruby dosfstools mtools default-jre default-jdk scons python3-distutils perl openssl libssl-dev cpio git-lfs m4 ccache zlib1g-dev tar rsync liblz4-tool genext2fs binutils-dev device-tree-compiler e2fsprogs git-core gnupg gnutls-bin gperf lib32ncurses5-dev libffi-dev zlib* libelf-dev libx11-dev libgl1-mesa-dev lib32z1-dev xsltproc x11proto-core-dev libc6-dev-i386 libxml2-dev lib32z-dev libdwarf-dev
apt-get install -y grsync xxd libglib2.0-dev libpixman-1-dev kmod jfsutils reiserfsprogs xfsprogs squashfs-tools pcmciautils quota ppp libtinfo-dev libtinfo5 libncurses5 libncurses5-dev libncursesw5 libstdc++6 python2.7 gcc-arm-none-eabi vim ssh locales doxygen
# Install the following modules for Python:
chmod +x /usr/bin/repo
pip3 install --trusted-host https://repo.huaweicloud.com -i https://repo.huaweicloud.com/repository/pypi/simple requests setuptools pymongo kconfiglib pycryptodome ecdsa ohos-build pyyaml prompt_toolkit==1.0.14 redis json2html yagmail python-jenkins
pip3 install esdk-obs-python --trusted-host pypi.org
pip3 install six --upgrade --ignore-installed six
#You also need to install LLVM, hc-gen, gcc_riscv32, Ninja, node-v14.15.4-linux-x64, and GN, and import the non-bash or non-Zsh configuration in the shell to your environment variables.
```
- Parsing commands: Parse the name of the product to build and load related configurations.
- Running GN: Configure toolchains and global options based on the parsed product name and compilation type.
- Running Ninja: Start building and generate a product distribution.
### Limitations and Constraints<a name="section886933762513"></a>
- You must download the source code using method 3 described in [Source Code Acquisition](../get-code/sourcecode-acquire.md). ## Building Guidelines
- The build environment must be Ubuntu 18.04 or later.
- You must install the software package required for build.
The installation command is as follows: ### Directory Structure
``` ```
sudo apt-get install binutils git-core gnupg flex bison gperf build-essential zip curl zlib1g-dev gcc-multilib g++-multilib libc6-dev-i386 lib32ncurses5-dev x11proto-core-dev libx11-dev lib32z-dev ccache libgl1-mesa-dev libxml2-utils xsltproc unzip m4
```
/build # Directory for build
## Compilation and Building Guidelines<a name="section16901215262"></a> ├── __pycache__
├── build_scripts/ # Python scripts for build
├── common/
├── config/ # Build-related configurations
├── core
│ └── gn/ # BUILD.gn configuration
└── build_scripts/
├── docs
gn_helpers.py*
lite/ # hb and preloader entry
misc/
├── ohos # Process for building and packaging OpenHarmony
│ ├── kits # Kits build and packaging templates and processing
│ ├── ndk # NDK templates and processing
│ ├── notice # Notice templates and processing
│ ├── packages # Distribution packaging templates and processing
│ ├── sa_profile # SA profiles and processing
│ ├── sdk # SDK templates and processing, which contains the module configuration in the SDK
│ └── testfwk # Testing-related processing
├── ohos.gni* # Common .gni files for importing a module at a time.
├── ohos_system.prop
├── ohos_var.gni*
├── prebuilts_download.sh*
├── print_python_deps.py*
├── scripts/
├── subsystem_config.json
├── subsystem_config_example.json
├── templates/ # C/C++ build templates
├── test.gni*
├── toolchain # Build toolchain configuration
├── tools # Common tools
├── version.gni
├── zip.py*
### Directory Structure<a name="section109065332264"></a>
```
/build # Primary directory
├── config # Build configuration items
├── core
│ └── gn # Build entry BUILD.gn configuration
├── loader # Loader of module configuration, which also generates a template for the module
├── ohos # Configuration of the process for building and packaging OpenHarmony
│ ├── kits # Build and packaging templates and processing flow for kits
│ ├── ndk # NDK template and processing flow
│ ├── notice # Notice template and processing flow
│ ├── packages # Distribution packaging template and processing flow
│ ├── sa_profile # SA template and processing flow
│ ├── sdk # SDK template and processing flow, which contains the module configuration in the SDK
│ └── testfwk # Processing flow related to the test
├── scripts # Build-related Python script
├── templates # C/C++ build templates
└── toolchain # Toolchain configuration
``` ```
### Build Command<a name="section123265539266"></a> ### Build Command
- Run the following command in the root directory of the source code to build the full distribution: - Run the following command in the root directory of the source code to build a full distribution:
``` ```
./build.sh --product-name {product_name}
```
**product\_name** indicates the product supported by the current distribution, for example, hispark_taurus_standard. ./build.sh --product-name {product_name}
```
The image generated after build is stored in the **out/{device_name}/packages/phone/images/** directory. **{product_name}** specifies the product platform supported by the current distribution, for example, **hispark_taurus_standard**.
- The build command supports the following options: The image generated is stored in the **out/{device_name}/packages/phone/images/** directory.
``` - The **./build.sh** command supports the following options:
--product-name # (Mandatory) Name of the product to build, for example, Hi3516D V300
--build-target # (Optional) One or more build targets
--gn-args # (Optional) One or more gn parameters
--ccache # (Optional) Use of Ccache for build. This option takes effect only when Ccache is installed on the local PC.
```
```
-h, --help # Display help information and exit.
--source-root-dir=SOURCE_ROOT_DIR # Specify the path.
--product-name=PRODUCT_NAME # Specify the product name.
--device-name=DEVICE_NAME # Specify the device name.
--target-cpu=TARGET_CPU # Specify the CPU.
--target-os=TARGET_OS # Specify the operating system.
-T BUILD_TARGET, --build-target=BUILD_TARGET # specifies one or more targets to build.
--gn-args=GN_ARGS # Specify GN parameters.
--ninja-args=NINJA_ARGS # Specify Ninja parameters.
-v, --verbose # Display all commands used.
--keep-ninja-going # Keep Ninja going until 1,000,000 jobs fail.
--sparse-image
--jobs=JOBS
--export-para=EXPORT_PARA
--build-only-gn # Perform GN parsing and does not run Ninja.
--ccache # (Optional) Use ccache for build. You need to install ccache locally.
--fast-rebuild # Whether to use fast rebuild. The default value is False.
--log-level=LOG_LEVEL # Specify the log level during the build. The options are debug, info, and error. The default value is info.
--device-type=DEVICE_TYPE # Specify the device type. The default value is default.
--build-variant=BUILD_VARIANT # Specify the device operation mode. The default value is user.
### How to Develop<a name="section591084422719"></a> ```
1. Add a module. ### How to Develop
The following steps use a custom module as an example to describe how to build the module, including build a library, an executable file, and a configuration file. 1. Add a component.
The following use a custom component as an example to describe how to write .gn scripts for a library, an executable file, and a configuration file.
In this example, **partA** consists of **feature1**, **feature2**, and **feature3**, which represent a dynamic library, an executable file, and an etc configuration file, respectively.
Add **partA** to a subsystem, for example, **subsystem_examples** (defined in the **test/examples/** directory).
The example module **partA** consists of **feature1**, **feature2**, and **feature3**. The target is a dynamic library for **feature1**, an executable file for **feature2**, and an etc configuration file for **feature3**. The directory structure of **partA** is as follows:
Add **partA** to a subsystem, for example, **subsystem\_examples** \(defined in the **test/examples/** directory\). ```
test/examples/partA
├── feature1
│ ├── BUILD.gn
│ ├── include
│ │ └── helloworld1.h
│ └── src
│ └── helloworld1.cpp
├── feature2
│ ├── BUILD.gn
│ ├── include
│ │ └── helloworld2.h
│ └── src
│ └── helloworld2.cpp
└── feature3
├── BUILD.gn
└── src
└── config.conf
```
The complete directory structure of **partA** is as follows: (a) Write **test/examples/partA/feature1/BUILD.gn** for the dynamic library.
``` ```
test/examples/partA
├── feature1 config("helloworld_lib_config") {
│ ├── BUILD.gn include_dirs = [ "include" ]
│ ├── include }
│ │ └── helloworld1.h
│ └── src ohos_shared_library("helloworld_lib") {
│ └── helloworld1.cpp sources = [
├── feature2 "include/helloworld1.h",
│ ├── BUILD.gn "src/helloworld1.cpp",
│ ├── include ]
│ │ └── helloworld2.h public_configs = [ ":helloworld_lib_config" ]
│ └── src part_name = "partA"
│ └── helloworld2.cpp }
└── feature3
├── BUILD.gn ```
└── src
└── config.conf
```
Example 1: GN script \(**test/examples/partA/feature1/BUILD.gn**\) for building a dynamic library (b) Write **test/examples/partA/feature2/BUILD.gn** for the executable file.
``` ```
config("helloworld_lib_config") {
ohos_executable("helloworld_bin") {
sources = [
"src/helloworld2.cpp"
]
include_dirs = [ "include" ] include_dirs = [ "include" ]
} deps = [ # Dependent modules in the component
"../feature1:helloworld_lib"
ohos_shared_library("helloworld_lib") { ]
sources = [ external_deps = [ "partB:module1" ] # (Optional) Dependent modules of another component are named in Component name:Module name format.
"include/helloworld1.h", install_enable = true # By default, the executable file is not installed. You need to set this parameter to true for installation.
"src/helloworld1.cpp", part_name = "partA"
}
```
(c) Write **test/examples/partA/feature3/BUILD.gn** for the etc module.
```
ohos_prebuilt_etc("feature3_etc") {
source = "src/config.conf"
relative_install_dir = "init" # (Optional) Relative directory for installing the module. The default installation directory is **/system/etc**.
part_name = "partA"
}
```
(d) Add the module configuration **test/examples/bundle.json** to the **bundle.json** file of the component. Each component has a **bundle.json** file in the root directory of the component. The sample code is as follows:
```
{
"name": "@ohos/<component_name>, # OpenHarmony Package Manager (HPM) component name, in the "@Organization/Component name" format.
"description": "xxxxxxxxxxxxxxxxxxx", # Description of the component functions.
"version": "3.1", # Version, which must be the same as the version of OpenHarmony.
"license": "MIT", # Component license.
"publishAs": "code-segment", # Mode for publishing the HPM package. The default value is code-segment.
"segment": {
"destPath": ""
}, # Set the code restoration path (source code path) when publishAs is code-segment.
"dirs": {}, # Directory structure of the HPM package. This field is mandatory and can be left empty.
"scripts": {}, # Scripts to be executed. This field is mandatory and can be left empty.
"licensePath": "COPYING", # Path of the module's license.
"readmePath": {
"en": "README.rst"
}, # Path of module's reademe.opensource.
"component": { # Component attributes.
"name": "<component_name>", # Component name.
"subsystem": "", # Subsystem to which the component belongs.
"syscap": [], # System capabilities provided by the component for applications.
"features": [], # List of the component's configurable features. Generally, this parameter corresponds to sub_component in build and can be configured.
"adapted_system_type": [], # Adapted system types, which can be mini, small, and standard. Multiple values are allowed.
"rom": "xxxKB" # ROM baseline. If there is no baseline, enter the current value.
"ram": "xxxKB", # RAM baseline. If there is no baseline, enter the current value.
"deps": {
"components": [], # Other components on which this component depends.
"third_party": [] # Third-party open-source software on which this component depends.
},
"build": { # Build-related configurations.
"sub_component": [], # Component build entry. Configure the module here.
"inner_kits": [], # APIs between components.
"test": [] # Entry for building the component's test cases.
}
}
}
```
2. Add the component to the product configuration file.
Add the component to **//vendor/{*product_company*}/{*product-name*}/config.json**.
For example, add "subsystem_examples:partA" to the product **config.json** file. **partA** will be built and packaged into the distribution.
3. Start the build.
For example, run the following command to build **hispark_taurus_standard**:
```
./build.sh --product-name hispark_taurus_standard --ccache
```
4. Obtain the build result.
You can obtain the generated files from the **out/hispark_taurus/** directory and the image in the **out/hispark_taurus/packages/phone/images/** directory.
## FAQs
### How Do I Build a Module and Package It into a Distribution?
- Set **part_name** for the module. A module can belong to only one part.
- Add the module to **component.build.sub_component** of the component, or define the dependency between the module and the modules in **component.build.sub_component**.
- Add the component to the component list of the product.
### How Do I Set deps and external_deps?
When adding a module, you need to declare its dependencies in **BUILD.gn**. **deps** specifies dependent modules in the same component, and **external_deps** specifies dependent modules between components.
The dependency between modules can be classified into:
**deps**: The dependent module to be added belongs to the same component with the current module. For example, module 2 depends on module 1, and modules 1 and 2 belong to the same component.
**external_deps**: The dependent module to be added belongs to another component. For example, module 2 depends on module 1, and modules 1 and 2 belong to different components.
- Example of **deps**:
```
import("//build/ohos.gni")
ohos_shared_library("module1") {
...
part_name = "part1" # (Mandatory) Name of the component to which the module belongs.
...
}
```
```
import("//build/ohos.gni")
ohos_shared_library("module2") {
...
deps = [
"GN target of module 1",
...
] # Intra-component dependency
part_name = "part1" # (Mandatory) Name of the part to which the module belongs.
}
```
- Example of **external_deps**:
```
import("//build/ohos.gni")
ohos_shared_library("module1") {
...
part_name = "part1" # (Mandatory) Name of the component to which the module belongs.
...
}
```
- **bundle.json** file of the component to which module 1 belongs
```
{
"name": "@ohos/<component_name>", # HPM component name, in the "@Organization/Component name" format.
"description": "xxxxxxxxxxxxxxxx", # Description of the component functions.
"version": "3.1", # Version, which must be the same as the version of OpenHarmony.
"license": "MIT", # Component license.
"publishAs": "code-segment", # Mode for publishing the HPM package. The default value is code-segment.
"segment": {
"destPath": ""
}, # Code restoration path (source code path) when publishAs is code-segment.
"dirs": {}, # Directory structure of the HPM package. This field is mandatory and can be left empty.
"scripts": {}, # Scripts to be executed. This field is mandatory and can be left empty.
"licensePath "licensePath": "COPYING",
": "COPYING",
"readmePath": {
"en": "README.rst"
},
"component": { # Component attributes.
"name": "<component_name>", # Component name.
"subsystem": "", # Subsystem to which the component belongs.
"syscap": [], # System capabilities provided by the component for applications.
"features": [], # List of the component's configurable features. Generally, this parameter corresponds to sub_component in build and can be configured.
"adapted_system_type": [], # Adapted system types, which can be mini, small, and standard. Multiple values are allowed.
"rom": "xxxKB" # ROM baseline. If there is no baseline, enter the current value.
"ram": "xxxKB", # RAM baseline. If there is no baseline, enter the current value.
"deps": {
"components": [], # Other components on which this component depends.
"third_party": [] # Third-party open-source software on which this component depends.
},
"build": { # Build-related configurations.
"sub_component": ["part1"], # Component build entry. All modules of the component are listed here.
"inner_kits": [], # APIs between components.
{
"header": {
"header_base": "Header file directory", # Directory of the header files.
"header_files": [
"Header file name"
] # List of header file names.
},
"name": "GN target of module 1"
},
],
"test": [] # Entry for building the component's test cases.
}
}
}
```
```
import("//build/ohos.gni")
ohos_shared_library("module2") {
...
external_deps = [
"part1:module1",
...
] # Inter-component dependency. The dependent module must be declared in **inner_kits** by the dependent component.
part_name = "part2" # (Mandatory) Name of the component to which the module belongs.
}
```
> ![icon-caution.gif](../public_sys-resources/icon-caution.gif) **CAUTION**<br/>
> The values of **external_deps** are in the *Component name*:*Module name* format. The module name must exist in **inner_kits** of the dependent component.
### How Do I Add a Module to a Standard System?
You may need to:
- Add a module to an existing component.
- Add a module to a new component.
- Add a module to a new subsystem.
#### Adding a Module to an Existing Component
1. Configure the **BUILD.gn** file in the module directory and select the corresponding template.
Follow the procedure for adding a module to an existing component. Note that **part_name** in the **BUILD.gn** file is the name of the existing component.
2. Modify the **bundle.json** file. "GN target of the module in the component"
```
{
"name": "@ohos/<component_name>, # HPM component name, in the "@Organization/Component name" format.
"description": "xxxxxxxxxxxxxxxxxxx", # Description of the component functions.
"version": "3.1", # Version, which must be the same as the version of OpenHarmony.
"license": "MIT", # Component license.
"publishAs": "code-segment", # Mode for publishing the HPM package. The default value is code-segment.
"segment": {
"destPath": "third_party/nghttp2"
}, # Code restoration path (source code path) when publishAs is code-segment.
"dirs": {}, # Directory structure of the HPM package. This field is mandatory and can be left empty.
"scripts": {}, # Scripts to be executed. This field is mandatory and can be left empty.
"licensePath": "COPYING",
"readmePath": {
"en": "README.rst"
},
"component": { # Component attributes.
"name": "<component_name>", # Component name.
"subsystem": "", # Subsystem to which the component belongs.
"syscap": [], # System capabilities provided by the component for applications.
"features": [], # List of the component's configurable features. Generally, this parameter corresponds to sub_component in build and can be configured.
"adapted_system_type": [], # Adapted system types, which can be mini, small, and standard. Multiple values are allowed.
"rom": "xxxKB" # ROM baseline. If there is no baseline, enter the current value.
"ram": "xxxKB", # RAM baseline. If there is no baseline, enter the current value.
"deps": {
"components": [], # Other components on which this component depends.
"third_party": [] # Third-party open-source software on which this component depends.
},
"build": { # Build-related configurations
"sub_component": [
"//foundation/arkui/napi:napi_packages", # Existing module 1
"//foundation/arkui/napi:napi_packages_ndk" # Existing module 2
"//foundation/arkui/napi:new" # Module to add
], # Component build entry. Configure the module here.
"inner_kits": [], # APIs between components
"test": [] # Entry for building the component's test cases.
}
}
}
```
Note that the **bundle.json** file must be in the folder of the corresponding subsystem.
#### Creating a Component and Adding a Module
1. Configure the **BUILD.gn** file in the module directory and select the corresponding template. Note that **part_name** in the **BUILD.gn** file is the name of the newly added component.
2. Create a **bundle.json** file in the folder of the corresponding subsystem.
The **bundle.json** file consists of two parts: **subsystem** and **parts**. Add the component information to **parts**. When adding a component, you need to specify the **sub_component** of the component. If there are APIs provided for other components, add them in **inner_kits**. If there are test cases, add them in **test**.
3. Add the new component to the end of existing components in **//vendor/{product_company}/{product-name}/config.json**.
```
"subsystems": [
{
"subsystem": "Name of the subsystem to which the component belongs",
"components": [
{"component": "Component 1 name", "features":[]}, # Existing component 1 in the subsystem
{ "component": "Component 2 name", "features":[] }, # Existing component 2 in the subsystem
{"component": "New component name", "features":[]} # New component in the subsystem
]
},
...
]
```
#### Creating a Subsystem and Adding a Module
1. Configure the **BUILD.gn** file in the module directory and select the corresponding template.
Note that **part_name** in the **BUILD.gn** file is the name of the newly added component.
2. Create a **bundle.json** file in the folder of the component of the subsystem.
This step is the same as the step in "Creating a Component and Adding a Module."
3. Modify the **subsystem_config.json** file in the **build** directory.
```
{
"Subsystem 1 name": { # Existing subsystem 1
"path": "Subsystem 1 directory",
"name": "Subsystem 1 name"
},
"Subsystem 2 name": { # Existing subsystem 2
"path": "Subsystem 2 directory",
"name": "Subsystem 2 name"
},
"Subsystem name new": { # Subsystem to add
"path": "New subsystem directory",
"name": "New subsystem name"
},
...
}
```
This file defines the subsystems and their paths. To add a subsystem, specify **path** and **name** for the subsystem.
4. If **product-name** in the **//vendor/{product_company}/{product-name}** directory is **hispark_taurus_standard**, add the new component information to the end of existing components in the **config.json** file.
```
"subsystems": [
{
"subsystem": "arkui", # Name of the existing subsystem
"components": [ # All components of the subsystem
{
"component": "ace_engine_standard", # Name of the existing component
"features": []
},
{
"component": "napi", # Name of the existing component
"features": []
}
{
"component": "component_new1", # Name of the new component added to the existing subsystem
"features": []
}
]
},
{
"subsystem": "subsystem_new", # Name of the new subsystem to add
"components": [
{
"component": "component_new2", # Name of the component added to the new subsystem
"features": []
}
]
},
...
]
```
Verification:
- Check that **module_list** in the **BUILD.gn** file in the component directory under the corresponding subsystem directory contains the target defined in the **BUILD.gn** file of the new module.
- Check the .so file or binary file generated in the image created.
#### Configuration Files
There are four OpenHarmony configuration files.
1. **vendor\Product vendor\Product name\config.json**
```
{
"product_name": "MyProduct",
"version": "3.0",
"type": "standard",
"target_cpu": "arm",
"ohos_version": "OpenHarmony 1.0",
"device_company": "MyProductVendor",
"board": "MySOC",
"enable_ramdisk": true,
"subsystems": [
{
"subsystem": "ace",
"components": [
{ "component": "ace_engine_lite", "features":[""] }
]
},
...
] ]
public_configs = [ ":helloworld_lib_config" ] }
part_name = "partA"
```
This file specifies the name, manufacturer, device, version, type of system to be built, and subsystems of the product.
2. **subsystem_config.json** in the **build** directory
```
{
"arkui": {
"path": "foundation/arkui",
"name": "arkui"
},
"ai": {
"path": "foundation/ai",
"name": "ai"
},
......
} }
``` ```
This file contains subsystem information. You need to configure **name** and **path** for each subsystem.
3. **bundle.json** of a subsystem
```
{
"name": "@ohos/<component_name>, # HPM component name, in the "@Organization/Component name" format.
"description": "xxxxxxxxxxxxxxxxxxx", # Description of the component functions.
"version": "3.1", # Version, which must be the same as the version of OpenHarmony.
"license": "MIT", # Component license.
"publishAs": "code-segment", # Mode for publishing the HPM package. The default value is code-segment.
"segment": {
"destPath": ""
}, # Code restoration path (source code path) when publishAs is code-segment.
"dirs": {}, # Directory structure of the HPM package. This field is mandatory and can be left empty.
"scripts": {}, # Scripts to be executed. This field is mandatory and can be left empty.
"licensePath": "COPYING",
"readmePath": {
"en": "README.rst"
},
"component": { # Component attributes.
"name": "<component_name>", # Component name.
"subsystem": "", # Subsystem to which the component belongs.
"syscap": [], # System capabilities provided by the component for applications.
"features": [], # List of the component's configurable features. Generally, this parameter corresponds to sub_component in build and can be configured.
"adapted_system_type": [], # Adapted system types, which can be mini, small, and standard. Multiple values are allowed.
"rom": "xxxKB" # ROM baseline. If there is no baseline, enter the current value.
"ram": "xxxKB", # RAM baseline. If there is no baseline, enter the current value.
"deps": {
"components": [], # Other components on which this component depends.
"third_party": [] # Third-party open-source software on which this component depends.
},
"build": { # Build-related configurations.
"sub_component": ["gn target of the module"], # Component build entry
"inner_kits": [], # APIs between components.
"test": [] # Entry for building the component's test cases.
}
}
}
```
The **bundle.json** file defines the components of a subsystem.
Each component contains the module's target **component.build.sub_component**, **component.build.inner_kits** for interaction between components, and test cases **component.build.test_list**. The **component.build.sub_component** is mandatory.
4. **BUILD.gn** of each module
You can create **BUILD.gn** from a template or using the GN syntax.
### How Do I Build a HAP?
#### **HAP Description**
An OpenHarmony Ability Package (HAP) includes resources, raw assets, JS assets, native libraries, and **config.json**.
#### **Templates**
Example 2: GN script \(**test/examples/partA/feature2/BUILD.gn**\) for building an executable file The compilation and build subsystem provides four templates for building HAPs. The templates are integrated in **ohos.gni**. Before using the templates, import **build/ohos.gni**.
1. **ohos_resources**
This template declares resource targets. After a target is built by restool, an index file is generated. The resource source file and index file are both packaged into the HAP.
A **ResourceTable.h** file is also generated after resource building. This header file can be referenced if the resource target is relied on.
The resource target name must end with **resources**, **resource**, or **res**. Otherwise, a build error may occur.
The following variables are supported:
- **sources**: a list of resource paths.
- **hap_profile**: **config.json** of the HAP required for resource building.
- **deps**: (optional) dependency of the current target.
2. **ohos_assets**
This template declares asset targets.
Beware that the spelling is "assets" as opposed to "assert".
The asset target name must end with **assets** or **asset**.
The following variables are supported:
- **sources**: a list for raw asset paths.
- **deps**: (optional) dependency of the current target.
3. **ohos_js_assets**
This template declares a JS resource target. The JS resource is the executable part of an L2 HAP.
The JS asset target name must end with **assets** or **asset**.
The following variables are supported:
- **source_dir**: JS resource path, which is of the string type.
- **deps**: (optional) dependency of the current target.
4. **ohos_hap**
This template declares a HAP target. A HAP that will be generated and packaged into the system image.
The following variables are supported:
- **hap_profile**: **config.json** of the HAP.
- **deps**: dependency of the current target.
- **shared_libraries**: native libraries on which the current target depends.
- **hap_name**: (optional) name of the HAP. The default value is the target name.
- **final_hap_path**: (optional) destination path of the HAP. It takes precedence over **hap_name**.
- **subsystem_name**: name of the subsystem to which the HAP belongs. The value must be the same as that in **bundle.json**. Otherwise, the HAP will fail to be installed in the system image.
- **part_name**: name of the component to which the HAP belongs. The value must be the same as that in **bundle.json**.
- **js2abc**: whether to convert the HAP into ARK bytecode.
- **certificate_profile**: certificate profile of the HAP, which is used for signature. For details about signatures, see [Configuring Signature Information](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-debugging-and-running-0000001263040487#section17660437768).
- **certificate_file**: Certificate file. You must apply for the certificate and its profile from the official OpenHarmony website.
- **keystore_path**: keystore file, which is used for signature.
- **keystore_password**: keystore password, which is used for signature.
- **key_alias**: key alias.
- **module_install_name**: name of the HAP used during installation.
- **module_install_dir**: installation path. The default path is **system/app**.
**HAP Example**
``` ```
ohos_executable("helloworld_bin") { import("//build/ohos.gni") # Import **ohos.gni**.
sources = [ ohos_hap("clock") {
"src/helloworld2.cpp" hap_profile = "./src/main/config.json" # config.json
deps = [
":clock_js_assets", # JS assets
":clock_resources", # Resources
] ]
include_dirs = [ "include" ] shared_libraries = [
deps = [ # Dependent submodule "//third_party/libpng:libpng", # Native library
"../feature1:helloworld_lib"
] ]
external_deps = [ "partB:module1" ] # (Optional) If there is a cross-module dependency, the format is "module name: submodule name" certificate_profile = "../signature/systemui.p7b" # Certificate profile
install_enable = true # By default, the executable file is not installed. You need to set this parameter to true for installation. hap_name = "SystemUI-NavigationBar" # HAP name
part_name = "partA" part_name = "prebuilt_hap"
subsystem_name = "applications"
}
ohos_js_assets("clock_js_assets") {
source_dir = "./src/main/js/default"
}
ohos_resources("clock_resources") {
sources = [ "./src/main/resources" ]
hap_profile = "./src/main/config.json"
} }
``` ```
Example 3: GN script \(**test/examples/partA/feature3/BUILD.gn**\) for building the etc configuration file \(submodule\). ### What Does an Open-Source Software Notice Collect?
``` #### Information to Collect
ohos_prebuilt_etc("feature3_etc") {
source = "src/config.conf"
relative_install_dir = "init" # (Optional) Directory for installing the submodule, which is relative to the default installation directory (/system/etc)
part_name = "partA"
}
```
Example 4: Adding the module configuration file **test/examples/ohos.build** to the **ohos.build** file of this subsystem. Each subsystem has an **ohos.build** file in its root directory. Example: The notice collects only the licenses of the modules packaged in the image. For example, the licenses of the tools (such as Clang, Python, and Ninja) used during the build process are not collected.
``` A static library itself is not packaged. However, if it is packaged into the system as part of a dynamic library or executable file, the license of the static library will be collected for completeness.
"partA": {
"module_list": [
"//test/examples/partA/feature1:helloworld_lib",
"//test/examples/partA/feature2:helloworld_bin",
"//test/examples/partA/feature3:feature3_etc",
],
"inner_kits": [
],
"system_kits": [
],
"test_list": [
]
}
```
The declaration of a module contains the following parts: The final **Notice.txt** file must include all licenses used by the files in the image and the mapping between modules and licenses.
- **module\_list**: submodule list of the module The **Notice.txt** file is located in the **/system/etc/** directory.
- **inner\_kits**: APIs for other modules that depend on this module through **external\_deps**
- **system\_kits**: APIs for developers
- **test\_list**: test cases for the submodules of the module
2. Add the module to the product configuration file. #### Rules for Collecting Information
Add the module to the product configuration file **//vendor/{product_company}/{product-name}/config.json**. Licenses are collected by priority.
Add "subsystem\_examples:partA" to the product configuration file. **partA** will be built and packaged into the distribution. 1. Licenses that are directly declared in a module's **BUILD.gn** are given the top priority. The following is an example:
3. Build the module. ```
ohos_shared_library("example") {
...
license_file = "path-to-license-file"
...
}
```
For example, run the following command to build hispark_taurus_standard: 2. If there is no explicitly declared license, the build script searches for the **Readme.OpenSource** file in the directory of **BUILD.gn**, parses the file, and collects the obtained licenses.
If the **Readme.OpenSource** file does not contain license information, an error will be reported.
``` 3. If the **Readme.OpenSource** file does not exist, the build script searches for the **License**, **Copyright**, and **Notice** files from the current directory to the root directory of the source code by default. If obtained license information will be used as the licenses of the module.
./build.sh --product-name hispark_taurus_standard --ccache
``` 4. If no license is found, the default license (Apache License 2.0) will be used.
4. Obtain the build result. Check items:
Files generated during the build process are stored in the **out/hispark_taurus/** directory, and the generated image is stored in the **out/hispark_taurus/packages/phone/images/** directory. 1. For third-party open-source software, such as OpenSSL and ICU, **Readme.OpenSource** must be configured in the source code directory. Check whether **Readme.OpenSource** is in the same directory as **BUILD.gn** and whether the license configured in **Readme.OpenSource** is valid.
2. If the source code is not licensed under the Apache License 2.0, the corresponding license file must be provided in the source code directory or declared by **license_file** for the module.
3. If the source code file added to **BUILD.gn** is not from the current directory, check whether the license in the repository where the source code file is located is the same as that in the repository of **BUILD.gn**. License inconsistency entails follow-up operations.
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册