This module provides the HTTP data request capability. An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**.
>**NOTE**
>
>
>The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
>
...
@@ -18,17 +20,17 @@ import http from '@ohos.net.http';
...
@@ -18,17 +20,17 @@ import http from '@ohos.net.http';
// Each HttpRequest corresponds to an HttpRequestTask object and cannot be reused.
// Each HttpRequest corresponds to an HttpRequestTask object and cannot be reused.
lethttpRequest=http.createHttp();
lethttpRequest=http.createHttp();
// Subscribe to the HTTP response header, which is returned earlier than HttpRequest. You can subscribe to HTTP Response Header events based on service requirements.
// Subscribe to the HTTP response header, which is returned earlier than httpRequest. Whether to subscribe to the HTTP response header is up to your decision.
// on('headerReceive', AsyncCallback) will be replaced by on('headersReceive', Callback) in API version 8. 8+
// on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8.
httpRequest.on('headersReceive',(header)=>{
httpRequest.on('headersReceive',(header)=>{
console.info('header: '+JSON.stringify(header));
console.info('header: '+JSON.stringify(header));
});
});
httpRequest.request(
httpRequest.request(
// Set the URL of the HTTP request. You need to define the URL. Set the parameters of the request in extraData.
// Customize EXAMPLE_URL on your own. It is up to you whether to add parameters to the URL.
"EXAMPLE_URL",
"EXAMPLE_URL",
{
{
method:http.RequestMethod.POST,// Optional. The default value is http.RequestMethod.GET.
method:http.RequestMethod.POST,// Optional. The default value is http.RequestMethod.GET.
// You can add the header field based on service requirements.
// You can add header fields based on service requirements.
header:{
header:{
'Content-Type':'application/json'
'Content-Type':'application/json'
},
},
...
@@ -48,7 +50,7 @@ httpRequest.request(
...
@@ -48,7 +50,7 @@ httpRequest.request(
console.info('cookies:'+data.cookies);// 8+
console.info('cookies:'+data.cookies);// 8+
}else{
}else{
console.info('error:'+JSON.stringify(err));
console.info('error:'+JSON.stringify(err));
// Call the destroy() method to release resources after the call is complete.
// Call the destroy() method to release resources after HttpRequest is complete.
httpRequest.destroy();
httpRequest.destroy();
}
}
}
}
...
@@ -79,7 +81,7 @@ let httpRequest = http.createHttp();
...
@@ -79,7 +81,7 @@ let httpRequest = http.createHttp();
## HttpRequest
## HttpRequest
Defines an **HttpRequest** object. Before invoking HttpRequest APIs, you must call [createHttp\(\)](#httpcreatehttp) to create an **HttpRequestTask** object.
HTTP request task. Before invoking APIs provided by **HttpRequest**, you must call [createHttp\(\)](#httpcreatehttp) to create an **HttpRequestTask** object.
### request
### request
...
@@ -94,7 +96,7 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback
...
@@ -94,7 +96,7 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback
Unregisters the observer for HTTP Response Header events.
Unregisters the observer for HTTP Response Header events.
> **NOTE**
> **NOTE**
>
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
| method | [RequestMethod](#requestmethod) | No | Request method. |
| method | [RequestMethod](#requestmethod) | No | Request method. |
| extraData | string \| Object \| ArrayBuffer<sup>8+</sup> | No | Additional data of the request.<br>- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request.<br>- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter is a supplement to the HTTP request parameters and will be added to the URL when the request is sent.<sup>8+</sup><br>- To pass in a string object, you first need to encode the object on your own.<sup>8+</sup> |
| extraData | string \| Object \| ArrayBuffer<sup>8+</sup> | No | Additional data of the request.<br>- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request.<br>- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter is a supplement to the HTTP request parameters and will be added to the URL when the request is sent.<sup>8+</sup><br>- To pass in a string object, you first need to encode the object on your own.<sup>8+</sup> |
| header | Object | No | HTTP request header. The default value is {'Content-Type': 'application/json'}.|
| header | Object | No | HTTP request header. The default value is **{'Content-Type': 'application/json'}**. |
| readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. |
| readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. |
| connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. |
| connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. |
...
@@ -388,7 +388,7 @@ Enumerates the response codes for an HTTP request.
...
@@ -388,7 +388,7 @@ Enumerates the response codes for an HTTP request.
| result | string \| Object \| ArrayBuffer<sup>8+</sup> | Yes | Response content returned based on **Content-type** in the response header:<br>- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.<br>- application/octet-stream: ArrayBuffer<br>- Others: string|
| result | string \| Object \| ArrayBuffer<sup>8+</sup> | Yes | Response content returned based on **Content-type** in the response header:<br>- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.<br>- application/octet-stream: ArrayBuffer<br>- Others: string|
| responseCode | [ResponseCode](#responsecode)\| number | Yes | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**. The error code can be one of the following:<br>- 200: common error<br>- 202: parameter error<br>- 300: I/O error|
| responseCode | [ResponseCode](#responsecode)\| number | Yes | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**. For details, see [Error Codes](#error-codes).|
| header | Object | Yes | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:<br>- Content-Type: header['Content-Type'];<br>- Status-Line: header['Status-Line'];<br>- Date: header.Date/header['Date'];<br>- Server: header.Server/header['Server'];|
| header | Object | Yes | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:<br>- Content-Type: header['Content-Type'];<br>- Status-Line: header['Status-Line'];<br>- Date: header.Date/header['Date'];<br>- Server: header.Server/header['Server'];|
| cookies<sup>8+</sup> | Array\<string\> | Yes | Cookies returned by the server. |
| cookies<sup>8+</sup> | Array\<string\> | Yes | Cookies returned by the server. |
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 = [
...
@@ -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:
Name the subtargets in templates in the ${target_name}+double underscores (__)+suffix format. This naming convention has the following advantages:
-The ${*target\_name*} part can prevent duplicate subtarget names.
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
### Guidelines
The build script completes the following two tasks:
The build script completes the following tasks:
1.**Describe the dependency between modules (deps).**
1.Describes the dependency (deps) between modules.
In practice, the most frequent problem is **lack of dependency**.
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, common problems are **unclear input** and **unclear output**.
In practice, unclear input and output are common problems.
Lack of dependency can result in the following:
Lack of dependency leads to the following problems:
-**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") {
...
...
}
}
...
@@ -165,21 +165,21 @@ Lack of dependency can result in the following:
...
@@ -165,21 +165,21 @@ Lack of dependency can result in the following:
}
}
```
```
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.
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.
From this example we can see that lack of dependency does not necessarily lead to a compilation error. It poses a possibility of errors.
If **liba.so** is available, the compilation is successful. Therefore, lack of dependency poses a possibility of compilation errors.
-**Missing involvement of dependent modules**
-Missing compilation of 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.
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.
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"
...
@@ -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.
-**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,42 +252,39 @@ write_file("a.out")
...
@@ -252,42 +252,39 @@ 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**.
These native templates are discouraged 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.
- 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 GN native templates include **source_set**, **shared_library**, **static_library**, **action**, **executable** and **group**.
The native templates are not recommended due to the following reasons:
- The native templates provide only the minimal build configuration. They cannot provide functions, such as parsing **external_deps**, collecting notice, and generating installation information.
Mapping between native templates and templates provided by the compilation system:
- The native **action** template cannot automatically detect the changes in the dependencies of the input file, and cannot start recompilation. See Example 8.
| Template Provided by the Compilation System | Native Template |
The table below lists the mapping between the GN native templates and templates provided by the compilation system.
@@ -334,13 +331,13 @@ Prioritize the Python script over the shell script in **action**. The Python scr
...
@@ -334,13 +331,13 @@ 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 sharing within the same **BUILD.gn**
Data in the same **BUILD.gn**file can be shared by defining global variables.
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**. Module **a** shares data with module **b** 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
...
@@ -355,24 +352,24 @@ Data sharing between modules is common. For example, a module may want to know t
...
@@ -355,24 +352,24 @@ 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
...
@@ -382,7 +379,7 @@ Data sharing between modules is common. For example, a module may want to know t
...
@@ -382,7 +379,7 @@ 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, [
...
@@ -396,11 +393,11 @@ Data sharing between modules is common. For example, a module may want to know t
...
@@ -396,11 +393,11 @@ Data sharing between modules is common. For example, a module may want to know t
### 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.
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
- In OpenHarmony, a part is a group of modules that can provide a certain capability.
- An OpenHarmony component is a group of modules that can provide a capability.
- 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.
- When defining a module, you must specify **part_name** to indicate the component to which the module belongs.
- 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**.
-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.
- 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.
-**inner-kit** applies only to dependent modules in different components.
- 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
...
@@ -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_
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:
@@ -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.
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.
- Build a single component independently.
### Basic Concepts
### Basic Concepts
Learn the following concepts before you start compilation and building:
Learn the following basic concepts before you start:
- Subsystem
- 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.
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
- 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.
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
Generate Ninja \(GN\) is used to generate Ninja files.
GN is short for Generate Ninja. It is used to build Ninja files.
- Ninja
- Ninja
Ninja is a small high-speed build system.
Ninja is a small high-speed building system.
- hb
- hb
hb is a command line tool for OpenHarmony to execute build commands.
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
└── 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


1. Use **hb set** to set the OpenHarmony source code directory and the product to build.
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:
- 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.
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.
(2) Run the **gn gen** command to read the product configuration and generate the **out** directory and **ninja** files for the solution.
(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:
>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:
```
```
{
"components": [
{
{
"component": "sensor_lite", # Component name
"name": "@ohos/sensor_lite", # OpenHarmony Package Manager (HPM) component name, in the @Organization/Component name format.
"description": "Sensor services", # Brief description of the component
"description": "Sensor services", # Description of the component functions.
"optional": "true", # Whether the component is mandatory for the system
"version": "3.1", # Version, which must be the same as the version of OpenHarmony.
"dirs": [ # Source code directory of the component
"license": "MIT", # Component license.
"base/sensors/sensor_lite"
"publishAs": "code-segment", # Mode for publishing the HPM package. The default value is code-segment.
"adapted_kernel": [ "liteos_a" ], # Adapted kernel for the component
"en": "README.rst"
"features": [], # Configurable features of the component
},
"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": {
"deps": {
"components": [ # Other components on which the component depends
"components": [ # Other components on which this component depends.
"samgr_lite"
"samgr_lite"
],
],
"third_party": [ # Open-source third-party software on which the component depends
"third_party": [ # Third-party open-source software on which this component depends.
], # 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 configuring**BUILD.gn**:
Observe the following rules when writing the component's**BUILD.gn**:
- The build target name must be the same as the component name.
- 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.
> **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.
- 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.
The following example shows how to build the **foundation/graphic/ui/BUILD.gn** file for a graphics UI component:
> 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 the configurable features of the component.
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
ohos_ohos_graphic_ui_font = "vector" # Configurable font type, which can be vector or bitmap.
}
}
# Basic component functions
# Basic component functions.
shared_library("base") {
shared_library("base") {
sources = [
sources = [
......
...
]
]
include_dirs = [
include_dirs = [
......
...
]
]
}
}
# Build only when the animator is enabled
# Build only when the animator is enabled.
if(enable_ohos_graphic_ui_animator ) {
if(enable_ohos_graphic_ui_animator ) {
shared_library("animator") {
shared_library("animator") {
sources = [
sources = [
......
...
]
]
include_dirs = [
include_dirs = [
......
...
]
]
deps = [ :base ]
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.
# 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") {
executable("ui") {
deps = [
deps = [
":base"
":base"
...
@@ -175,51 +191,53 @@ The following example shows how to build the **foundation/graphic/ui/BUILD.gn**
...
@@ -175,51 +191,53 @@ The following example shows how to build the **foundation/graphic/ui/BUILD.gn**
]
]
}
}
}
}
```
```
### 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.
### 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
>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,85 +250,86 @@ vendor
...
@@ -232,85 +250,86 @@ 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
>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.
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.
-**chmod**: changes the permission on a specified directory or file.
-**chown**: changes the owner group of a specified directory or file.
-**chown**: changes the owner group of a specified directory or file.
-**mount**: mounts a device.
-**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.
This file contains the 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**
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 components, and kernel.
The **config.json** file is the main entry for the build and contains configurations of the development board, OS, and kernel.
The following example shows the **config.json** file of the IP camera developed based on the hispark\_taurus development board:
The following example shows the **config.json** file of the IP camera developed based on the hispark_taurus board:
```
```
{
{
"product_name": "ipcamera", # Product name
"product_name": "ipcamera", # 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": "hisilicon", # Chipset vendor
"device_company": "hisilicon", # Chipset vendor
"board": "hispark_taurus", # Name of the development board
"board": "hispark_taurus", # Name of the development board
...
@@ -320,84 +339,73 @@ The key directories and files are described as follows:
...
@@ -320,84 +339,73 @@ The key directories and files are described as follows:
{
{
"subsystem": "aafwk", # Subsystem
"subsystem": "aafwk", # Subsystem
"components": [
"components": [
{ "component": "ability", "features":[ "enable_ohos_appexecfwk_feature_ability = true" ] } # Component and its features
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\}
5.**vendor/company/product/fs.yml**
**out** directory of the product, which corresponds to **$\{root\_out\_dir\}** of GN
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\}
```
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.
```
File system directory, which consists of the following variables
The **fs_symlink** and **fs_make_cmd** fields support the following variables:
- $\{root\_path\}
- ${root_path}: code root directory, which corresponds to **${ohos_root_path}** of GN.
- $\{fs\_dir\_name\}
- ${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}.
>**fs.yml** is optional and does not need to be configured for devices without a file system.
-**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.
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:
The following is an example of the **BUILD.gn** file of a product:
```
```
group("product") { # The target name must be the same as the product name (level-3 directory name under the product directory).
group("product") { # The name must be the same as the product name (level-3 directory name under the product directory).
deps = []
deps = []
# Copy the init configuration.
# Copy the init configuration.
deps += [ "init_configs" ]
deps += [ "init_configs" ]
# Others
# Others
......
...
}
}
```
```
## Usage Guidelines
## 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.
--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
...
@@ -497,7 +516,7 @@ To add a component, determine the subsystem to which the component belongs and t
...
@@ -497,7 +516,7 @@ To add a component, determine the subsystem to which the component belongs and t
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") {
...
@@ -510,27 +529,27 @@ To add a component, determine the subsystem to which the component belongs and t
...
@@ -510,27 +529,27 @@ To add a component, determine the subsystem to which the component belongs and t
}
}
```
```
The above script is used to build **hello\_world** that can run on OpenHarmony.
This script can be used to build a file named **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.
To build the preceding component separately, run **hb set** to select a product and run the following command to build **hello_world** separately.
```
```
hb build -f -T //applications/sample/hello_world
hb build -f -T //applications/sample/hello_world
```
```
After the component functions are verified on the development board, perform steps 2 to 4 to configure the component to the product.
After the component functions are verified on the development board, perform steps 2 to 4 to add the component to the product.
2. Add component description.
2.Add the component description.
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:
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:
- **component**: name of the component
-**component**: component name.
- **description**: brief description of the component
-**description**: description of the component functions.
- **optional**: whether the component is optional
-**optional**: whether the component is optional.
- **dirs**: source code directory of the component
-**dirs**: source code directory of the component.
- **targets**: component build entry
-**targets**: component build entry.
For example, to add the **hello\_world** component to the application subsystem, add the **hello\_world** object to the **applications.json** file.
The following is an example of adding the **hello_world** component to the **applications.json** file.
```
```
{
{
...
@@ -551,9 +570,9 @@ To add a component, determine the subsystem to which the component belongs and t
...
@@ -551,9 +570,9 @@ To add a component, determine the subsystem to which the component belongs and t
}
}
```
```
3. Configure the component for the product.
3.Add the component to 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:
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:
```
```
{
{
...
@@ -581,22 +600,19 @@ To add a component, determine the subsystem to which the component belongs and t
...
@@ -581,22 +600,19 @@ To add a component, determine the subsystem to which the component belongs and t
2. Run the **hb build** command.
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/realtek/rtl8720
mkdir -p device/board/realtek/rtl8720
```
```
2. Create a directory for kernel adaptation and build the **config.gni** file of the development board.
2. Create a directory for kernel adaptation and write 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, e.g. "linux", "liteos_a", "liteos_m".
...
@@ -616,7 +632,7 @@ The following uses the RTL8720 development board provided by Realtek as an examp
...
@@ -616,7 +632,7 @@ The following uses the RTL8720 development board provided by Realtek as an examp
# Note: The default toolchain is "ohos-clang". It's not mandatory if you use the default toochain.
# Note: The default toolchain is "ohos-clang". It's not mandatory if you use the default toochain.
board_toolchain = "gcc-arm-none-eabi"
board_toolchain = "gcc-arm-none-eabi"
# The toolchain path instatlled, it's not mandatory if you have added toolchian path to your ~/.bashrc.
# The toolchain path installed, it's not mandatory if you have added toolchain path to your ~/.bashrc.
@@ -633,14 +649,13 @@ The following uses the RTL8720 development board provided by Realtek as an examp
...
@@ -633,14 +649,13 @@ The following uses the RTL8720 development board provided by Realtek as an examp
board_ld_flags = []
board_ld_flags = []
```
```
3. Build the script.
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:
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 target can be shared_library, static_library, or an executable file.
group("rtl8720") { # The build target can be shared_library, static_library, or an executable file.
# Content
# Content
......
...
}
}
```
```
...
@@ -648,14 +663,13 @@ The following uses the RTL8720 development board provided by Realtek as an examp
...
@@ -648,14 +663,13 @@ The following uses the RTL8720 development board provided by Realtek as an examp
Run the **hb build** command in the development board directory to start the build.
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
...
@@ -663,13 +677,13 @@ You can use the Compilation and Building subsystem to customize product solution
...
@@ -663,13 +677,13 @@ You can use the Compilation and Building subsystem to customize product solution
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
...
@@ -690,23 +704,24 @@ You can use the Compilation and Building subsystem to customize product solution
...
@@ -690,23 +704,24 @@ You can use the Compilation and Building subsystem to customize product solution
}
}
```
```
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.
> 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:
```
```
-
-
...
@@ -793,7 +808,7 @@ You can use the Compilation and Building subsystem to customize product solution
...
@@ -793,7 +808,7 @@ You can use the Compilation and Building subsystem to customize product solution
source: mksh
source: mksh
link_name: ${fs_dir}/bin/shell
link_name: ${fs_dir}/bin/shell
fs_make_cmd:
fs_make_cmd:
# Create an ext4 image for the rootfs directory using the script.
# Run the script to create an ext4 image from rootfs.
@@ -809,14 +824,14 @@ You can use the Compilation and Building subsystem to customize product solution
...
@@ -809,14 +824,14 @@ You can use the Compilation and Building subsystem to customize product solution
```
```
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
# Directory in which the patch is to be installed
foundation/communication/dsoftbus:
foundation/communication/dsoftbus:
# Directory in which the patch is stored
# Directory in which the patch is stored.
- foundation/communication/dsoftbus/1.patch
- foundation/communication/dsoftbus/1.patch
- foundation/communication/dsoftbus/2.patch
- foundation/communication/dsoftbus/2.patch
third_party/wpa_supplicant:
third_party/wpa_supplicant:
...
@@ -826,25 +841,25 @@ You can use the Compilation and Building subsystem to customize product solution
...
@@ -826,25 +841,25 @@ You can use the Compilation and Building subsystem to customize product solution
...
...
```
```
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.
group("wifiiot") { # The target name must be the same as the product name.
deps = []
deps = []
# Copy the init configuration.
# Copy the init configuration.
deps += [ "init_configs" ]
deps += [ "init_configs" ]
# Build the hals directory.
# Add **hals**.
deps += [ "hals" ]
deps += [ "hals" ]
# Others
# Others
......
...
}
}
```
```
...
@@ -852,31 +867,29 @@ You can use the Compilation and Building subsystem to customize product solution
...
@@ -852,31 +867,29 @@ You can use the Compilation and Building subsystem to customize product solution
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**
-**Symptom**
The build fails, and "usr/sbin/ninja: invalid option -- w" is displayed.
The build fails, and **usr/sbin/ninja: invalid option -- w** is displayed.
-**Cause**
-**Possible Causes**
The Ninja version in the build environment is outdated and does not support the **--w** option.
The Ninja version in use does not support the **--w** option.
-**Solution**
-**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.
Uninstall Ninja and GN, and [install Ninja and GN of the required version](../get-code/gettools-ide.md).
### Library ncurses Not Found
### "/usr/bin/ld: cannot find -lncurses" Displayed During the Build Process
-**Symptom**
-**Symptom**
The build fails, and "/usr/bin/ld: cannot find -lncurses" is displayed.
The build fails, and **/usr/bin/ld: cannot find -lncurses** is displayed.
-**Cause**
-**Possible Causes**
The ncurses library is not installed.
The ncurses library is not installed.
...
@@ -886,14 +899,13 @@ You can use the Compilation and Building subsystem to customize product solution
...
@@ -886,14 +899,13 @@ You can use the Compilation and Building subsystem to customize product solution
sudo apt-get install lib32ncurses5-dev
sudo apt-get install lib32ncurses5-dev
```
```
### "line 77: mcopy: command not found" Displayed During the Build Process
### mcopy not Found
-**Symptom**
-**Symptom**
The build fails, and "line 77: mcopy: command not found" is displayed.
The build fails, and **line 77: mcopy: command not found** is displayed.
-**Cause**
-**Possible Causes**
mcopy is not installed.
mcopy is not installed.
...
@@ -903,64 +915,63 @@ You can use the Compilation and Building subsystem to customize product solution
...
@@ -903,64 +915,63 @@ You can use the Compilation and Building subsystem to customize product solution
sudo apt-get install dosfstools mtools
sudo apt-get install dosfstools mtools
```
```
### "riscv32-unknown-elf-gcc: error trying to exec 'cc1': execvp: No such file or directory" Displayed During the Build Process
### No riscv File or Directory
-**Symptom**
-**Symptom**
The build fails, and the following information is displayed:
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**
riscv32-unknown-elf-gcc: error trying to exec 'cc1': execvp: No such file or directory.
-**Cause**
-**Possible Causes**
Permission is required to access files in the **riscv** compiler directory.
Permission is required to access files in the RISC-V compiler directory.
-**Solution**
-**Solution**
Run the following command to query the directory where **gcc\_riscv32** is located:
1. Run the following command to locate **gcc_riscv32**:
```
```
which riscv32-unknown-elf-gcc
which riscv32-unknown-elf-gcc
```
```
Run the **chmod** command to change the directory permission to **755**.
2. Run the **chmod** command to change the directory permission to **755**.
### No Crypto
### "No module named 'Crypto'" Displayed During the Build Process
-**Symptom**
-**Symptom**
The build fails, and "No component named 'Crypto'" is displayed.
The build fails, and **No module named 'Crypto'** is displayed.
-**Cause**
-**Possible Causes**
Crypto is not installed in Python 3.
Crypto is not installed in Python 3.
-**Solution**
-**Solution**
1. Run the following command to query the Python version:
1. Run the following command to query the Python version:
```
```
python3 --version
python3 --version
```
```
2. Ensure that Python 3.7 or later is installed, and then run the following command to install pycryptodome:
2. Ensure that Python 3.9.2 or later is installed, and then run the following command to install PyCryptodome:
```
```
sudo pip3 install pycryptodome
sudo pip3 install pycryptodome
```
```
### "xx.sh : xx unexpected operator" Displayed During the Build Process
### Unexpected Operator
-**Symptom**
-**Symptom**
The build fails, and "xx.sh \[: xx unexpected operator" is displayed.
The build fails, and **xx.sh [: xx unexpected operator** is displayed.
-**Cause**
-**Possible Causes**
The build environment is shell, not bash.
The build environment shell is not bash.
-**Solution**
-**Solution**
...
@@ -968,4 +979,3 @@ You can use the Compilation and Building subsystem to customize product solution
...
@@ -968,4 +979,3 @@ You can use the Compilation and Building subsystem to customize product solution
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 is a combination of development boards and kernels.
A platform consists of the development board and kernel. The supported subsystems and components vary with the platform.
Supported subsystems and modules vary according to the platform.
- Subsystem
-**Subsystems**
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.
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.
- Component
-**Module**
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.
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.
- GN
-**GN**
GN is short for Generate Ninja. It is used to build Ninja files.
GN is short for Generate Ninja, which is used to generate Ninja files.
- Ninja
-**Ninja**
Ninja is a small high-speed building system.
Ninja is a small high-speed build system.
### Working Principles
The process for building an OpenHarmony system is as follows:
### Working Principles<a name="section12541217142510"></a>
- Parsing commands: Parse the name of the product to build and load related configurations.
The process to build OpenHarmony is as follows:
- Running GN: Configure the toolchain and global options based on the product name and compilation type.
- 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.
- Running Ninja: Start building and generate a product distribution.
### Limitations and Constraints<a name="section886933762513"></a>
### Constraints
- You must download the source code using method 3 described in [Source Code Acquisition](../get-code/sourcecode-acquire.md).
- You need to obtain the source code using method 3 described in [Obtaining Source Code](../get-code/sourcecode-acquire.md).
- 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:
- Ubuntu 18.04 or later must be used.
- You must install the software packages required for build.
# 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.
#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.
```
```
## Compilation and Building Guidelines<a name="section16901215262"></a>
--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
### How to Develop<a name="section591084422719"></a>
1. Add a component.
1. Add a module.
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.
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.
In this example, **partA** consists of **feature1**, **feature2**, and **feature3**, which represent a dynamic library, an executable file, and an etc configuration file, respectively.
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**.
Add **partA** to a subsystem, for example, **subsystem_examples** (defined in the **test/examples/** directory).
Add **partA** to a subsystem, for example, **subsystem\_examples** \(defined in the **test/examples/** directory\).
The complete directory structure of **partA** is as follows:
The directory structure of **partA** is as follows:
```
```
test/examples/partA
test/examples/partA
├── feature1
├── feature1
│ ├── BUILD.gn
│ ├── BUILD.gn
...
@@ -131,14 +194,16 @@ The process to build OpenHarmony is as follows:
...
@@ -131,14 +194,16 @@ The process to build OpenHarmony is as follows:
├── BUILD.gn
├── BUILD.gn
└── src
└── src
└── config.conf
└── config.conf
```
Example 1: GN script \(**test/examples/partA/feature1/BUILD.gn**\) for building a dynamic library
```
(a) Write **test/examples/partA/feature1/BUILD.gn** for the dynamic library.
```
```
config("helloworld_lib_config") {
config("helloworld_lib_config") {
include_dirs = [ "include" ]
include_dirs = [ "include" ]
}
}
ohos_shared_library("helloworld_lib") {
ohos_shared_library("helloworld_lib") {
sources = [
sources = [
...
@@ -147,80 +212,602 @@ The process to build OpenHarmony is as follows:
...
@@ -147,80 +212,602 @@ The process to build OpenHarmony is as follows:
]
]
public_configs = [ ":helloworld_lib_config" ]
public_configs = [ ":helloworld_lib_config" ]
part_name = "partA"
part_name = "partA"
}
}
```
Example 2: GN script \(**test/examples/partA/feature2/BUILD.gn**\) for building an executable file
```
(b) Write **test/examples/partA/feature2/BUILD.gn** for the executable file.
```
```
ohos_executable("helloworld_bin") {
ohos_executable("helloworld_bin") {
sources = [
sources = [
"src/helloworld2.cpp"
"src/helloworld2.cpp"
]
]
include_dirs = [ "include" ]
include_dirs = [ "include" ]
deps = [ # Dependent submodule
deps = [ # Dependent modules in the component
"../feature1:helloworld_lib"
"../feature1:helloworld_lib"
]
]
external_deps = [ "partB:module1" ] # (Optional) If there is a cross-module dependency, the format is "module name: submodule name"
external_deps = [ "partB:module1" ] # (Optional) Dependent modules of another component are named in Component name:Module name format.
install_enable = true # By default, the executable file is not installed. You need to set this parameter to true for installation.
install_enable = true # By default, the executable file is not installed. You need to set this parameter to true for installation.
part_name = "partA"
part_name = "partA"
}
}
```
Example 3: GN script \(**test/examples/partA/feature3/BUILD.gn**\) for building the etc configuration file \(submodule\).
```
(c) Write **test/examples/partA/feature3/BUILD.gn** for the etc module.
```
```
ohos_prebuilt_etc("feature3_etc") {
ohos_prebuilt_etc("feature3_etc") {
source = "src/config.conf"
source = "src/config.conf"
relative_install_dir = "init" # (Optional) Directory for installing the submodule, which is relative to the default installation directory (/system/etc)
relative_install_dir = "init" # (Optional) Relative directory for installing the module. The default installation directory is **/system/etc**.
part_name = "partA"
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.
}
}
}
}
```
```
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:
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**:
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_list": [
"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.
> 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.
], # 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.
The declaration of a module contains the following parts:
#### Configuration Files
- **module\_list**: submodule list of the module
There are four OpenHarmony configuration files.
- **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.
"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.
4. Obtain the build result.
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**
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**.
### What Does an Open-Source Software Notice Collect?
#### Information to Collect
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.
The final **Notice.txt** file must include all licenses used by the files in the image and the mapping between modules and licenses.
The **Notice.txt** file is located in the **/system/etc/** directory.
#### Rules for Collecting Information
Licenses are collected by priority.
1. Licenses that are directly declared in a module's **BUILD.gn** are given the top priority. The following is an example:
```
ohos_shared_library("example") {
...
license_file = "path-to-license-file"
...
}
```
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.
4. If no license is found, the default license (Apache License 2.0) will be used.
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.
HiSysEvent provides event logging APIs for OpenHarmony to record important information of key processes during system running, helping you locate faults. In addition, you can upload the log data to the cloud for big data analytics.
HiSysEvent provides event logging APIs for OpenHarmony to record important information of key processes during system running. Besides, it supports shielding of event logging by event domain, helping you to evaluate the impact of event logging.
Before logging system events, you need to configure HiSysEvent logging. For details, see [HiSysEvent Logging Configuration](subsys-dfx-hisysevent-logging-config.md).
Before logging system events, you need to complete HiSysEvent logging configuration. For details, see [HiSysEvent Logging Configuration](subsys-dfx-hisysevent-logging-config.md).
## Development Guidelines<a name="section314416685113"></a>
## Development Guidelines
### Available APIs<a name="section13480315886"></a>
### When to Use
The following table lists the C++ APIs provided by the HiSysEvent class.
Use HiSysEvent logging to flush logged event data to disks.
For details about the HiSysEvent class, see the API reference.
### Available APIs
**Table 1** C++ APIs provided by HiSysEvent
#### C++ Event Logging APIs
| API| Description|
HiSysEvent logging is implemented using the API provided by the **HiSysEvent** class. For details, see the API Reference.
| -------- | --------- |
| template<typename... Types> static int Write(const std::string &domain, const std::string &eventName, EventType type, Types... keyValues) | Logs system events. <br><br>Input arguments: <ul><li>**domain**: Indicates the domain related to the event. You can use a preconfigured domain or customize a domain as needed. The name of a custom domain can contain a maximum of 16 characters, including digits (0-9) and uppercase letters (A-Z). It must start with a letter. </li><li>**eventName**: Indicates the event name. The value contains a maximum of 32 characters, including digits (0 to 9), letters (A-Z), and underscores (_). It must start with a letter and cannot end with an underscore. </li><li>**type**: Indicates the event type. For details, see EventType. </li><li>**keyValues**: Indicates the key-value pairs of event parameters. It can be in the format of the basic data type, std::string, std::vector<basic data type>, or std:vector<std::string>. The value contains a maximum of 48 characters, including digits (0 to 9), letters (A-Z), and underscores (_). It must start with a letter and cannot end with an underscore. The number of parameter names cannot exceed 32. </li></ul>Return value: <ul><li>**0**: The logging is successful. </li><li>Negative value: The logging has failed.</li></ul> |
> In OpenHarmony-3.2-Beta3, HiSysEvent logging is open for restricted use to avoid event storms. The **HiSysEvent::Write** API in Table 1 is replaced by the **HiSysEventWrite** API in Table 2. The **HiSysEvent::Write** API has been deprecated. Use the **HiSysEventWrite** API instead for HiSysEvent logging.
**Table 2** Description of HiSysEvent::Domain APIs
| static const std::string APPEXECFWK | User program framework subsystem|
| template<typename... Types> <br>static int Write(const std::string &domain, const std::string &eventName, EventType type, Types... keyValues) | Flushes logged event data to disks.|
| int hisysevent_put_integer(struct hiview_hisysevent *event, const char *key, long long value); | Adds event parameters of the integer type to a **hisysevent** object. |
| int hisysevent_put_string(struct hiview_hisysevent *event, const char *key, const char *value); | Adds event parameters of the string type to a **hisysevent** object.|
2. Pass the customized event parameters to the **hisysevent** object.
```c
// Add a parameter of the integer type.
hisysevent_put_integer(event,"BOOT_TIME",100);
// Add a parameter of the string type.
hisysevent_put_string(event,"MSG","This is a test message");
```
```
Add the event logging code. For example, if you want to log events specific to the app start time (start\_app), then add the following code to the service implementation source file:
2. Configure compilation information. Specifically, add the subsystem SDK dependency to **BUILD.gn**.
#### Shielding of Event Logging by Event Domain
1. In the corresponding file, define the **DOMAIN_MASKS** macro with content similar to DOMAIN_NAME_1|DOMAIN_NAME_2|...|DOMAIN_NAME_n. There are three scenarios:
- Shielding only event logging for the event domains configured in the current source code file: Define the **DOMAIN_MASKS** macro before importing the **.cpp** file to the **hisysevent.h** file.
HiSysEventWrite(domain,eventName,eventType);// Event logging is shielded for DOMAIN_NAME_1 because it has been defined in the DOMAIN_MASKS macro.
```
### Development Examples
#### C++ Event Logging
Assume that a service module needs to trigger event logging during application startup to record the application startup event and application bundle name. The following is the complete sample code:
1. Add the HiSysEvent component dependency to the **BUILD.gn** file of the service module.
```c++
external_deps=["hisysevent_native:libhisysevent"]
external_deps=["hisysevent_native:libhisysevent"]
```
```
2. In the application startup function **StartAbility()** of the service module, call the event logging API with the event parameters passed in.
Assume that the kernel service module needs to trigger event logging during device startup to record the device startup event. The following is the complete sample code:
1. In the device startup function **device_boot()**, construct a **hisysevent** object. After that, trigger event reporting, and then destroy the **hisysevent** object.
ret = hisysevent_put_string(event, "MSG", "This is a test message");
if (ret != 0) {
pr_err("failed to put sting to event, ret=%d", ret);
goto hisysevent_end;
}
ret = hisysevent_write(event);
hisysevent_end:
hisysevent_destroy(&event);
... // Other service logic
}
```
#### Shielding of Event Logging by Event Domain
- If you want to shield event logging for the **AAFWK** and **POWER** domains in a **.cpp** file, define the **DOMAIN_MASKS** macro before including the **hisysevent.h** header file to the **.cpp** file.
```c++
#define DOMAIN_MASKS "AAFWK|POWER"
#include "hisysevent.h"
...// Other service logic
HiSysEventWrite(OHOS:HiviewDFX::HiSysEvent::Domain::AAFWK,"JS_ERROR",OHOS:HiviewDFX::HiSysEvent::EventType::FAULT,"MODULE","com.ohos.module");// HiSysEvent logging is not performed.
...// Other service logic
HiSysEventWrite(OHOS:HiviewDFX::HiSysEvent::Domain::POWER,"POWER_RUNNINGLOCK",OHOS:HiviewDFX::HiSysEvent::EventType::FAULT,"NAME","com.ohos.module");// HiSysEvent logging is not performed.
```
- If you want to shield event logging for the **AAFWK** and **POWER** domains of the entire service module, define the **DOMAIN_MASKS** macro as follows in the **BUILG.gn** file of the service module.
```gn
config("module_a") {
... // Other configuration items
cflags_cc += ["-DDOMAIN_MASKS=\"AAFWK|POWER\""]
}
```
- If you want to shield event logging for the **AAFWK** and **POWER** domains globally, define the **DOMAIN_MASKS** macro as follows in **/build/config/compiler/BUILD.gn**.
```gn
... // Other configuration items
cflags_cc += ["-DDOMAIN_MASKS=\"AAFWK|POWER\""]
```
# Reference
The HiSysEvent module writes the logged event data to the node file, and the Hiview module parses and processes the event data in a unified manner. For details, see the [Hiview Development Guide](subsys-dfx-hiview.md).
The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** directory of the system. You can use this tool to subscribe to real-time system events or query historical system vents.
The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** directory of the system. You can use this tool to subscribe to real-time system events or query historical system vents.
## Subscribing to Real-Time System Events<a name="section1210623418527"></a>
## Subscribing to Real-Time System Events
- Command for subscribing to real-time system events:
- Command for subscribing to real-time system events:
...
@@ -15,8 +16,8 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin**
...
@@ -15,8 +16,8 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin**
Description of command options:
Description of command options:
| Option| Description|
| Option| Description|
| -------- | --------- |
| -------- | -------- |
| -r | Subscribes to real-time system events based on the default settings. When this option is specified, any real-time system event will be printed on the console.|
| -r | Subscribes to real-time system events based on the default settings. When this option is specified, any real-time system event will be printed on the console.|
- Command for enabling the debugging mode:
- Command for enabling the debugging mode:
...
@@ -27,7 +28,7 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin**
...
@@ -27,7 +28,7 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin**
Description of command options:
Description of command options:
| Option| Description|
| Option| Description|
| -------- | --------- |
| -------- | -------- |
| -d | Subscribes to real-time system events in debugging mode.|
| -d | Subscribes to real-time system events in debugging mode.|
- Command for subscribing to real-time system events by event tag:
- Command for subscribing to real-time system events by event tag:
...
@@ -39,21 +40,19 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin**
...
@@ -39,21 +40,19 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin**
Description of command options:
Description of command options:
| Option| Description|
| Option| Description|
| -------- | --------- |
| -------- | -------- |
| -t | Event tag used to filter subscribed real-time system events.|
| -t | Event tag used to filter subscribed real-time system events.|
| -c | Matching rule for event tags. The options can be **WHOLE_WORD**, **PREFIX**, or **REGULAR**.|
| -c | Matching rule for event tags. The options can be **WHOLE_WORD**, **PREFIX**, or **REGULAR**.|
>If **-t**, **-o**, and **-n** are specified, the system checks whether the configured event tag is null. If the event tag is not null, the system filters system events based on the matching rules for the event tag. Otherwise, the system filters system events based on the matching rules for the event domain and event name.
> If **-t**, **-o**, and **-n** are specified, the system checks whether the configured event tag is null. If the event tag is not null, the system filters system events based on the matching rules for the event tag. Otherwise, the system filters system events based on the matching rules for the event domain and event name.
## Querying Historical System Events<a name="section1210623418539"></a>
## Querying Historical System Events
- Command for querying historical system events:
- Command for querying historical system events:
...
@@ -98,7 +95,7 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin**
...
@@ -98,7 +95,7 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin**
Description of command options:
Description of command options:
| Option| Description|
| Option| Description|
| -------- | --------- |
| -------- | -------- |
| -l | Queries historical system events based on the default settings. A maximum of 1,000 latest system events will be returned.|
| -l | Queries historical system events based on the default settings. A maximum of 1,000 latest system events will be returned.|
- Command for querying historical system events within the specified period of time:
- Command for querying historical system events within the specified period of time:
...
@@ -110,18 +107,17 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin**
...
@@ -110,18 +107,17 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin**
Description of command options:
Description of command options:
| Option| Description|
| Option| Description|
| -------- | --------- |
| -------- | -------- |
| -s | Start time for querying historical system events. Only system events generated after the start time are returned.|
| -s | Start time for querying historical system events. Only system events generated after the start time are returned.|
| -e | End time for querying historical system events. Only system events generated before the end time are returned.|
| -e | End time for querying historical system events. Only system events generated before the end time are returned.|
{"domain_":"GRAPHIC","name_":"NO_DRAW","type_":1,"time_":1501964222980,"tz_":"+0000","pid_":1505,"tid_":1585,"uid_":10002,"PID":1505,"UID":10002,"ABILITY_NAME":"","MSG":"It took 1957104259905ns to draw, UI took 0ns to draw, RSRenderThread took 8962625ns to draw, RSRenderThread dropped 0 UI Frames","level_":"MINOR","id_":"1708287249901948387","info_":"isResolved,eventId:0"}
{"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501964222994,"tz_":"+0000","pid_":623,"tid_":1445,"uid_":1201,"SUB_EVENT_TYPE":"NO_DRAW","EVENT_TIME":"20170805201702","MODULE":"NO_DRAW","PNAME":"NO_DRAW","REASON":"NO_DRAW","DIAG_INFO":"","STACK":"SUMMARY:\n","HIVIEW_LOG_FILE_PATHS":["/data/log/faultlog/faultlogger/appfreeze-NO_DRAW-10002-20170805201702"],"DOMAIN":"GRAPHIC","STRING_ID":"NO_DRAW","PID":1505,"UID":10002,"PACKAGE_NAME":"NO_DRAW","PROCESS_NAME":"","MSG":"It took 1956945826265ns to draw, UI took 0ns to draw, RSRenderThread took 9863293ns to draw, RSRenderThread dropped 0 UI Frames\n","level_":"CRITICAL","tag_":"STABILITY","id_":"10448522101019619655","info_":""}
- Command for setting the maximum number of historical events that can be queried:
- Command for setting the maximum number of historical events that can be queried:
...
@@ -133,18 +129,36 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin**
...
@@ -133,18 +129,36 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin**
Description of command options:
Description of command options:
| Option| Description|
| Option| Description|
| -------- | --------- |
| -------- | -------- |
| -m | Maximum number of historical system events that can be queried. The value ranges from **0** to **1000**. The number of returned system events is not more than the value of this parameter.|
| -m | Maximum number of historical system events that can be queried. The value ranges from **0** to **1000**. The number of returned system events is not more than the value of this parameter.|
| -v | Used with the subscription command **-r** and query command **-l**. If system event validity check is enabled, invalid content contained in system events will be highlighted in red.|
# The **HAPPEN_TIME** and **VERSION** fields are not configured in the YAML file for the **APP_FREEZE** event that belongs to the **RELIABILITY** domain. Therefore, the two fields are highlighted in red.
Hiview is a module that provides toolkits for device maintenance across different platforms. It consists of the plugin management platform and the service plugins running on the platform. Hiview works in event-driven mode. The core of Hiview is a collection of HiSysEvent stubs distributed in the system. Formatted events are reported to Hiview through the HiSysEvent API for processing. The following figure shows the data interaction process.
**Figure 1** Data interaction between Hiview modules
1. The service process calls the event logging API to report logged event information and writes the information to the node file.
2. SysEventSource of the Hiview process asynchronously reads event information from the node file and distributes the event to SysEventPipeline for processing.
- The SysEventService plugin verifies events and flushes them to disks.
- The Faultlogger plugin processes fault-related events.
- The EventLogger plugin collects event-related log information.
3. On completion of event processing, SysEventPipeline sends the events to the event subscription queue and then dispatches the events to the subscription plugin for processing.
Before you get started, familiarize yourself with the following concepts:
- Plug-in
An independent module running in the Hiview process. A plugin is delivered with the Hiview binary file to implement maintenance and fault management functions independently. Plug-ins can be disassembled independently during compilation, and can be hosted on the platform during running and dynamically configured.
- Pipeline
An ordered set of event processing plugins. Events entering the pipeline are processed by plugins on the pipeline in sequence.
- Event source
A special plugin that can produce events. Different from common plugins, a special plugin can be bound to a pipeline, and can produce events and distribute them to the pipeline.
- Pipeline group
A group of pipelines configured on the same event source.
### Working Principles
Hiview supports plugin development on the plugin management platform and provides the required plugin development capabilities. You can add plugins to the Hiview platform to implement HiSysEvent event processing. Before you get started, you're expected to have a basic understanding of plugin working principles.
#### Plug-in Registration
A plugin can be registered in any of the following modes.
| Static registration | Use the **REGISTER(xxx);** macro to register the plugin. Such a plugin cannot be unloaded.|
| Proxy registration | Use the **REGISTER_PROXY(xxx);** macro to register the plugin. Such a plugin is not loaded upon startup and can be loaded and unloaded dynamically during system running.|
| Proxy registration and loading upon startup| Use the **REGISTER_PROXY_WITH_LOADED(xxx);** macro to register the plugin. Such a plugin is loaded upon startup and can be unloaded and loaded dynamically during system running.|
#### Plug-in Event-Driven Modes
There are two event-driven modes available for plugins: pipeline-driven and subscription-driven. The differences are as follows:
- Pipeline-driven plugins need to be configured on the pipeline. After an event is distributed from an event source to the pipeline, the event traverses the plugins configured on the pipeline in sequence for processing.
- Subscription-driven plugins do not need to be configured on the pipeline. However, a listener needs to be registered with the Hiview platform upon plugin startup, and the plugin needs to implement the event listener function.
#### Plug-in Loading
Depending on your service demand, you can compile all or some plugins into the Hiview binary file.
Multiple plugins can be built into an independent plugin package and preset in the system as an independent **.so** file. One **.so** file corresponds to one **plugin_config** file. For example, **libxxx.z.so** corresponds to the** xxx_plugin_config** file. When the Hiview process starts, it scans for the plugin package (**.so** file) and the corresponding configuration file and loads the plugins in the plugin package.
The plugin package is described as follows:
1. The plugin package runs on the plugin management platform as an independent entity. The plugins, pipelines, or event sources in it provide the same functions as the plugins in the Hiview binary.
2. Plug-ins in the plugin package can be inserted into the Hiview binary pipeline.
3. Subscribers, wherever they are located, can receive events sent by the platform based on the subscription rules.
## Plug-in Development Guide
### When to Use
You can deploy a plugin on the Hiview platform if you want to perform specific service processing on the HiSysEvent events distributed from the event source. The following table describes the APIs used for plugin development.
### Available APIs
The following table lists the APIs related to plugin development. For details about the APIs, see the API Reference.
| virtual void OnLoad() | Loads plugins. After plugins are loaded, you can call this API to initialize data.|
| virtual void OnUnload() | Unloads plugins. Before plugins are unloaded, you can call this API to reclaim data. |
| virtual bool ReadyToLoad() | Checks whether the current plugin can be loaded when the Hiview starts plugin loading. |
| virtual bool OnEvent(std::shared_ptr\<Event\>& event) | Implements event processing. You can call this API to receive events distributed by the pipeline or platform perform service processing.|
| virtual bool CanProcessEvent(std::shared_ptr\<Event\> event) | Checks whether an event can traverse backward throughout the entire pipeline. This function takes effect only when the plugin is the first one in the pipeline.|
| HiviewContext* GetHiviewContext() | Obtains the context of the Hiview plugin management platform. |