diff --git a/CODEOWNERS b/CODEOWNERS index 677e3bcd63ef928fbabf68ebc2ac1a6597a93571..025c30e10317662d65ab6b1d45688bf87ef41817 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -24,11 +24,16 @@ zh-cn/device-dev/driver/ @li-yan339 zh-cn/device-dev/get-code/ @li-yan339 zh-cn/device-dev/hpm-part/ @duangavin123_admin zh-cn/device-dev/reference/hdi-apis/ @li-yan339 -zh-cn/device-dev/subsystems/subsys-build-mini-lite.md @Austin23 -zh-cn/device-dev/subsystems/subsys-build-standard-large.md @Austin23 -zh-cn/device-dev/subsystems/subsys-build-gn-coding-style-and-best-practice.md @Austin23 -zh-cn/device-dev/subsystems/subsys-build-gn-kconfig-visual-config-guid.md @Austin23 -zh-cn/device-dev/subsystems/subsys-build-gn-hap-compilation-guide.md @Austin23 +zh-cn/device-dev/quick-start/quickstart-standard-env-setup.md @li-yan339 @chenmudan +zh-cn/device-dev/quick-start/quickstart-lite-env-setup.md @li-yan339 @chenmudan +zh-cn/device-dev/porting/porting-thirdparty-overview.md @Austin23 @chenmudan +zh-cn/device-dev/porting/porting-thirdparty-makefile.md @Austin23 @chenmudan +zh-cn/device-dev/porting/porting-thirdparty-cmake.md @Austin23 @chenmudan +zh-cn/device-dev/subsystems/subsys-build-mini-lite.md @Austin23 @chenmudan +zh-cn/device-dev/subsystems/subsys-build-standard-large.md @Austin23 @chenmudan +zh-cn/device-dev/subsystems/subsys-build-gn-coding-style-and-best-practice.md @Austin23 @chenmudan +zh-cn/device-dev/subsystems/subsys-build-gn-kconfig-visual-config-guid.md @Austin23 @chenmudan +zh-cn/device-dev/subsystems/subsys-build-gn-hap-compilation-guide.md @Austin23 @chenmudan zh-cn/device-dev/subsystems/subsys-remote-start.md @duangavin123_admin zh-cn/device-dev/subsystems/subsys-graphics-overview.md @duangavin123_admin zh-cn/device-dev/subsystems/subsys-graphics-container-guide.md @duangavin123_admin @@ -46,7 +51,7 @@ zh-cn/device-dev/subsystems/subsys-utils-overview.md @Austin23 zh-cn/device-dev/subsystems/subsys-utils-guide.md @Austin23 zh-cn/device-dev/subsystems/subsys-utils-faqs.md @Austin23 zh-cn/device-dev/subsystems/subsys-aiframework-guide.md @Austin23 -zh-cn/device-dev/subsystems/subsys-aiframework-envbuild.md @Austin23 +zh-cn/device-dev/subsystems/subsys-aiframework-envbuild.md @Austin23 zh-cn/device-dev/subsystems/subsys-aiframework-tech-codemanage.md @Austin23 zh-cn/device-dev/subsystems/subsys-aiframework-tech-name.md @Austin23 zh-cn/device-dev/subsystems/subsys-aiframework-tech-interface.md @Austin23 diff --git a/en/application-dev/reference/apis/js-apis-http.md b/en/application-dev/reference/apis/js-apis-http.md index f1ef654168a4696ee3f0e54e361a5e81ac7dc6a9..9e0e0bf5160d01596d0c6e0969c3cc783712f45a 100644 --- a/en/application-dev/reference/apis/js-apis-http.md +++ b/en/application-dev/reference/apis/js-apis-http.md @@ -1,6 +1,8 @@ # Data Request ->![](public_sys-resources/icon-note.gif) **NOTE** +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. > @@ -18,17 +20,17 @@ import http from '@ohos.net.http'; // Each HttpRequest corresponds to an HttpRequestTask object and cannot be reused. let httpRequest = 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. -// on('headerReceive', AsyncCallback) will be replaced by on('headersReceive', Callback) in API version 8. 8+ +// 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) is replaced by on('headersReceive', Callback) since API version 8. httpRequest.on('headersReceive', (header) => { console.info('header: ' + JSON.stringify(header)); }); 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", { 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: { 'Content-Type': 'application/json' }, @@ -48,7 +50,7 @@ httpRequest.request( console.info('cookies:' + data.cookies); // 8+ } else { 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(); } } @@ -79,7 +81,7 @@ let httpRequest = http.createHttp(); ## 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 @@ -93,9 +95,9 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------- | ---- | ----------------------- | -| url | string | Yes | URL for initiating an HTTP request.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------- | ---- | ----------------------- | +| url | string | Yes | URL for initiating an HTTP request.| | callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | Yes | Callback used to return the result. | **Example** @@ -169,15 +171,15 @@ Initiates an HTTP request to a given URL. This API uses a promise to return the **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------------------ | ---- | -------------------------------------------------- | -| url | string | Yes | URL for initiating an HTTP request. | +| Name | Type | Mandatory| Description | +| ------- | ------------------ | ---- | ----------------------------------------------- | +| url | string | Yes | URL for initiating an HTTP request. | | options | HttpRequestOptions | Yes | Request options. For details, see [HttpRequestOptions](#httprequestoptions).| **Return value** -| Type | Description | -| :-------------------- | :-------------------------------- | +| Type | Description | +| :------------------------------------- | :-------------------------------- | | Promise<[HttpResponse](#httpresponse)> | Promise used to return the result.| @@ -225,8 +227,7 @@ on\(type: 'headerReceive', callback: AsyncCallback\): void Registers an observer for HTTP Response Header events. >![](public_sys-resources/icon-note.gif) **NOTE** -> -> This API has been deprecated. You are advised to use [on\('headersReceive'\)8+](#onheadersreceive8) instead. +>This API has been deprecated. You are advised to use [on\('headersReceive'\)8+](#onheadersreceive8) instead. **System capability**: SystemCapability.Communication.NetStack @@ -308,7 +309,6 @@ off\(type: 'headersReceive', callback?: Callback\): void Unregisters the observer for HTTP Response Header events. >![](public_sys-resources/icon-note.gif) **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. **System capability**: SystemCapability.Communication.NetStack @@ -355,13 +355,13 @@ Specifies the type and value range of the optional parameters in the HTTP reques **System capability**: SystemCapability.Communication.NetStack -| Name | Type | Mandatory| Description | -| -------------- | ------------------------------------ | ---- | ---------------------------------------------------------- | -| method | [RequestMethod](#requestmethod) | No | Request method. | +| Name | Type | Mandatory| Description | +| -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| method | [RequestMethod](#requestmethod) | No | Request method. | | extraData | string \| Object \| ArrayBuffer8+ | No | Additional data of the request.
- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request.
- 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.8+
- To pass in a string object, you first need to encode the object on your own.8+ | -| 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. | -| connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. | +| 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. | +| connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. | ## RequestMethod @@ -388,13 +388,13 @@ Enumerates the response codes for an HTTP request. | Name | Value | Description | | ----------------- | ---- | ------------------------------------------------------------ | -| OK | 200 | "OK." The request has been processed successfully. This return code is generally used for GET and POST requests. | +| OK | 200 | Request succeeded. The request has been processed successfully. This return code is generally used for GET and POST requests. | | CREATED | 201 | "Created." The request has been successfully sent and a new resource is created. | -| ACCEPTED | 202 | "Accepted." The request has been accepted, but the processing has not been completed. | +| ACCEPTED | 202 | "Accepted." The request has been accepted, but the processing has not been completed. | | NOT_AUTHORITATIVE | 203 | "Non-Authoritative Information." The request is successful. | | NO_CONTENT | 204 | "No Content." The server has successfully fulfilled the request but there is no additional content to send in the response payload body. | | RESET | 205 | "Reset Content." The server has successfully fulfilled the request and desires that the user agent reset the content. | -| PARTIAL | 206 | "Partial Content." The server has successfully fulfilled the partial GET request for a given resource. | +| PARTIAL | 206 | "Partial Content." The server has successfully fulfilled the partial GET request for a given resource. | | MULT_CHOICE | 300 | "Multiple Choices." The requested resource corresponds to any one of a set of representations. | | MOVED_PERM | 301 | "Moved Permanently." The requested resource has been assigned a new permanent URI and any future references to this resource will be redirected to this URI.| | MOVED_TEMP | 302 | "Moved Temporarily." The requested resource is moved temporarily to a different URI. | @@ -418,7 +418,7 @@ Enumerates the response codes for an HTTP request. | REQ_TOO_LONG | 414 | "Request-URI Too Long." The Request-URI is too long for the server to process. | | UNSUPPORTED_TYPE | 415 | "Unsupported Media Type." The server is unable to process the media format in the request. | | INTERNAL_ERROR | 500 | "Internal Server Error." The server encounters an unexpected error that prevents it from fulfilling the request. | -| NOT_IMPLEMENTED | 501 | "Not Implemented." The server does not support the function required to fulfill the request. | +| NOT_IMPLEMENTED | 501 | "Not Implemented." The server does not support the function required to fulfill the request. | | BAD_GATEWAY | 502 | "Bad Gateway." The server acting as a gateway or proxy receives an invalid response from the upstream server.| | UNAVAILABLE | 503 | "Service Unavailable." The server is currently unable to process the request due to a temporary overload or system maintenance. | | GATEWAY_TIMEOUT | 504 | "Gateway Timeout." The server acting as a gateway or proxy does not receive requests from the remote server within the timeout period. | @@ -433,6 +433,17 @@ Defines the response to an HTTP request. | Name | Type | Mandatory| Description | | -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | | result | string \| Object \| ArrayBuffer8+ | Yes | Response content returned based on **Content-type** in the response header:
- 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.
- application/octet-stream: ArrayBuffer
- 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:
- 200: common error
- 202: parameter error
- 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:
- Content-Type: header['Content-Type'];
- Status-Line: header['Status-Line'];
- Date: header.Date/header['Date'];
- Server: header.Server/header['Server'];| | cookies8+ | Array\ | Yes | Cookies returned by the server. | + +## Error Codes + +| Error Code| Description | +| ------ | ------------------------------------------------------------ | +| -1 | Incorrect parameters. | +| 3 | Incorrect URL format. | +| 4 | Built-in request function, protocol, or option not found during build. | +| 5 | Unable to resolve the proxy. | +| 6 | Unable to resolve the host. | +| 7 | Unable to connect to the proxy or host. | diff --git a/en/device-dev/subsystems/figure/Hiview_module_data_interaction.png b/en/device-dev/subsystems/figure/Hiview_module_data_interaction.png new file mode 100644 index 0000000000000000000000000000000000000000..b2b734bc03a4a6556f3c4128b7a86244ffaa3d09 Binary files /dev/null and b/en/device-dev/subsystems/figure/Hiview_module_data_interaction.png differ diff --git a/en/device-dev/subsystems/figure/build-process.jpg b/en/device-dev/subsystems/figure/build-process.jpg index a48ea734509526b3ed0fe85b7c4a98b0a2a9c4f0..68fba0c4265dc6899eb6576dd243a7887d5cf615 100644 Binary files a/en/device-dev/subsystems/figure/build-process.jpg and b/en/device-dev/subsystems/figure/build-process.jpg differ diff --git a/en/device-dev/subsystems/subsys-build-gn-coding-style-and-best-practice.md b/en/device-dev/subsystems/subsys-build-gn-coding-style-and-best-practice.md index 61ee379301ce6efd16ba3fa3642599932719b085..66181d0660e07c52462a009aa360ca48f27cd3fa 100644 --- a/en/device-dev/subsystems/subsys-build-gn-coding-style-and-best-practice.md +++ b/en/device-dev/subsystems/subsys-build-gn-coding-style-and-best-practice.md @@ -2,46 +2,46 @@ ## Overview -Generate Ninja (GN) a meta-build system that generates build files for Ninja, which allows you to build your OpenHarmony projects with Ninja. +Generate Ninja (GN) is a meta-build system that generates build files for Ninja. It is the front end of Ninja. GN and Ninja together complete OpenHarmony build tasks. -### Introduction to GN +### GN -- GN is currently used in several popular systems, including Chromium, Fuchsia, and OpenHarmony. -- 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. -- For details about GN, see the official GN document at https://gn.googlesource.com/gn/+/main/docs/. +- GN is used in large software systems such as Chromium, Fuchsia, and OpenHarmony. +- 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 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 -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 ### 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 -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") { ... - # _output is a local variable. Hence, it starts with an underscore (_). + # _output is a local variable. _output = "${target_out_dir}/${target_name}.out" outputs = [ _output ] args = [ ... - "--output", - rebase_path(_output, root_build_dir), - ... + "--output", + rebase_path(_output, root_build_dir), + ... ] ... } @@ -49,32 +49,32 @@ action("some_action") { #### 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 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 } ``` #### Targets -The target is named in the format of **lowercase letters+underscore**. - -A subtarget in the template is named in the ${*target\_name*}\__*suffix* format. This naming convention has the following advantages: +Name the targets in the lowercase letters + underscores (_) format. -- The ${*target\_name*} part can prevent duplicate subtarget names. +Name the subtargets in templates in the ${target_name}+double underscores (__)+suffix format. This naming convention has the following advantages: -- The double underscores (\__) can help identify the module to which the subtarget belongs, thereby facilitating fault locating. +- ${target_name} prevents duplicate subtarget names. +- The double underscores (__) help locate the module to which a subtarget belongs. + ``` # Example 3 template("ohos_shared_library") { - # "{target_name}" (primary target name) + "__" (double underscores) + "notice" (suffix) + # "{target_name}" (Target name) + "__" (double underscores) + "notice" (suffix) _notice_target = "${target_name}__notice" collect_notice(_notice_target) { ... @@ -87,7 +87,7 @@ A subtarget in the template is named in the ${*target\_name*}\__*suffix* format. #### Custom Templates -Whenever possible, **use verbs** for template names. +Name templates in the verb+object format. ``` # Example 4 @@ -99,15 +99,15 @@ template("compile_resources") { ### Formatting -To maintain consistency in styles such as code alignment and line feed, a GN script needs to be formatted before being submitted. Use the format tool provided by GN to format your script. The command is as follows: +GN scripts must be formatted before being submitted. Formatting ensures consistency in style, such as code alignment and line feed. Use the format tool provided by GN to format your scripts. The command is as follows: ```shell $ 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 @@ -115,42 +115,42 @@ import("//b.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("//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") -# Comment to maintain the original import sequence. +# Comment to keep the original sequence import("//a.gni") ``` -## Coding Practice - -### Principles of Practice +## Coding Practices -The build script completes the following two tasks: +### Guidelines -1. **Describe the dependency between modules (deps).** +The build script completes the following tasks: - In practice, the most frequent problem is **lack of dependency**. +1. Describes the dependency (deps) between modules. + + In practice, the most common problem is lack of dependency. -2. **Describe the module compilation rules (rule).** +2. Defines the module build rules (rule). + + In practice, unclear input and output are common problems. - In practice, common problems are **unclear input** and **unclear output**. - -Lack of dependency can result in the following: - -- **Possible compilation error** +Lack of dependency leads to the following problems: +- Unexpected compilation error + ``` # 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") { ... } @@ -164,35 +164,35 @@ Lack of dependency can result in the following: deps = [ ":b" ] } ``` + + In this example, **libb.so** is linked to **liba.so**, which means that **b** depends on **a**. However, the dependency of **b** on **a** is not declared in the dependency list (**deps**) of **b**. Compilation is performed concurrently. An error occurs if **liba.so** is not available when **libb.so** attempts to create a link to it. + + If **liba.so** is available, the compilation is successful. Therefore, lack of dependency poses a possibility of compilation errors. - In the preceding example, **liba.so** is linked to **libb.so** when being linked. This means that **b** depends on **a**. However, the dependency list (**deps**) of **b** does not declare its dependency on **a**. As compilation is performed concurrently, a compilation error will occur if compilation of **liba.so** is not yet complete when **libb.so** is being linked. - - From this example we can see that lack of dependency does not necessarily lead to a compilation error. It poses a possibility of errors. - -- **Missing involvement of dependent modules** - - In the preceding example, because **images** depends on **b** only, **a** does not participate in the compilation of **images** using Ninja. However, as **b** depends on **a**, an error occurs when **b** is linked. +- Missing compilation of modules + + 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 -# Too many dependencies slow down compilation. +# Example 7: +# Unnecessary dependencies slow down compilation. template("too_much_deps") { ... _gen_resource_target = "${target_name}__res" action(_gen_resource_target) { ... } - + _compile_resource_target = "${target_name}__compile_res" action(_compile_resource_target) { deps = [":$_gen_resource_target"] ... } - + _compile_js_target = "${target_name}__js" action(_compile_js_target) { # This deps is not required. @@ -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.** -- **After code changes, the cache being used is still hit.** +- Modified code is not compiled during incremental compilation. +- The cache being used is still hit after the code is changed. -In the following example, **foo.py** references functions in **bar.py**. This means that **bar.py** is the input of **foo.py** and must be added to the **input** or **depfile** of **implict_input_action**. Otherwise, if **bar.py** is modified, the **implict_input_action** module will not be recompiled. +In the following example, **foo.py** references the functions in **bar.py**. This means **bar.py** is the input of **foo.py**. You need to add **bar.py** to **input** or **depfile** of **implict_input_action**. Otherwise, if **bar.py** is modified, **implict_input_action** will not be recompiled. ``` -# Example 8 +# Example 8: action("implict_input_action") { script = "//path-to-foo.py" ... @@ -218,19 +218,19 @@ action("implict_input_action") { ``` #!/usr/bin/env -# Contents of foo.py +# Content of foo.py import bar ... bar.some_function() ... ``` -Unclear output can result in the following: +Unclear output leads to the following problems: -- **The output is implicit.** -- **When the cache is used, implicit output cannot be obtained from the cache.** +- Implicit output +- 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 @@ -252,43 +252,40 @@ write_file("a.out") ### Templates -**Do not use the GN native templates. Use the templates provided by the compilation system.** +**Do not use GN native templates. Use the templates provided by the build system.** -The GN native templates are **source_set**, **shared_library**, **static_library**, **action**, **executable**, and **group**. +The GN native templates include **source_set**, **shared_library**, **static_library**, **action**, **executable** and **group**. -These native templates are discouraged due to the following reasons: +The native templates are not recommended due to the following reasons: -- **The native templates only provide minimum functions**. They do not provide extra functions such as external_deps parsing, notice collection, and installation information generation. These extra functions are generated during module compilation. Therefore, the native templates must be extended. +- The native templates provide only the minimal build configuration. They cannot provide functions, such as parsing **external_deps**, collecting notice, and generating installation information. -- When the file on which the input file depends changes, the native template **action** cannot automatically detect the change and cannot be recompiled. See Example 8. - - - - Mapping between native templates and templates provided by the compilation system: - - | Template Provided by the Compilation System | Native Template | - | :------------------------------------------ | --------------- | - | ohos_shared_library | shared_library | - | ohos_source_set | source_set | - | ohos_executable | executable | - | ohos_static_library | static_library | - | action_with_pydeps | action | - | ohos_group | group | - +- The native **action** template cannot automatically detect the changes in the dependencies of the input file, and cannot start recompilation. See Example 8. + + The table below lists the mapping between the GN native templates and templates provided by the compilation system. + +| Template Provided by the Compilation System | GN Native Template | +|:------------------- | -------------- | +| ohos_shared_library | shared_library | +| ohos_source_set | source_set | +| ohos_executable | executable | +| ohos_static_library | static_library | +| action_with_pydeps | action | +| ohos_group | group | ### Using Python Scripts -Prioritize the Python script over the shell script in **action**. The Python script has the following advantages over the shell script: +You are advised to use Python scripts instead of shell scripts in **action**. Compared with shell scripts, Python scripts feature: -- More user-friendly syntax: It will not generate strange errors just because a space is missing. -- More readable. -- Higher maintainability and debugability. -- Faster compilation: thanks to Python task caching by OpenHarmony. +- More user-friendly syntax, which eliminates errors caused by lack of a space +- Easier to read +- Easier to maintain and debug +- Faster compilation due to caching of Python tasks ### rebase_path -- Call **rebase_path** only in the **args** list of **action**. - +- Call **rebase_path** only in **args** of **action**. + ``` # Example 10 template("foo") { @@ -309,15 +306,15 @@ Prioritize the Python script over the shell script in **action**. The Python scr } ``` -- If **rebase_path** is executed twice for the same variable, unexpected results may occur. - +- If rebase_path is called twice for the same variable, unexpected results occur. + ``` # Example 11 template("foo") { action(target_name) { ... args = [ - # rebase_path is executed twice for bar, and the passed bar value is incorrect. + # After rebase_path is called twice for bar, the bar value passed is incorrect. "--bar=" + rebase_path(invoker.bar, root_build_dir), ... ] @@ -334,14 +331,14 @@ Prioritize the Python script over the shell script in **action**. The Python scr ### 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. - -- Data sharing within the same **BUILD.gn** file - - Data in the same **BUILD.gn** file can be shared by defining global variables. - - In the following example, the output of module **a** is the input of module **b**. Module **a** shares data with module **b** by defining global variables. +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** + + Data in the same **BUILD.gn** can be shared by defining global variables. + + In the following example, the output of module **a** is the input of module **b**, and can be shared with module **b** via global variables. + ``` # Example 12 _output_a = get_label_info(":a", "out_dir") + "/a.out" @@ -355,25 +352,25 @@ Data sharing between modules is common. For example, a module may want to know t } ``` -- Data sharing between different **BUILD.gn** files - - 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. +- Data sharing between different **BUILD.gn**s + + 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 -- 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 - # Forward testonly for a custom template. + # For a customized template, pass testonly first. template("foo") { 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 # Bad. The asterisk (*) is used to forward the variable. @@ -382,25 +379,25 @@ Data sharing between modules is common. For example, a module may want to know t ... } - # Good. Variables are explicitly forward one by one. + # Good. Variables are explicitly forwarded one by one. template("bar") { # forward_variable_from(invoker, [ - "testonly", - "deps", - ... - ]) + "testonly", + "deps", + ... + ]) ... } ``` ### target_name -The value of **target_name** varies according to the scope. +The value of **target_name** varies with the scope. ``` # Example 15 -# The value of target_name varies according to the scope. +# The value of target_name varies with the scope. template("foo") { # The displayed target_name is "${target_name}". print(target_name) @@ -426,7 +423,7 @@ To export header files from a module, use **public_configs**. ``` # 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") { include_dirs = ["//path-to-headers"] ... @@ -443,11 +440,11 @@ executable("b") { ### 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 -# A custom template must contain a subtarget named target_name. +# A custom template must have a subtarget named target_name. template("foo") { _code_gen_target = "${target_name}__gen" code_gen(_code_gen_target) { @@ -462,7 +459,7 @@ template("foo") { ... group(target_name) { 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" ] } @@ -471,11 +468,11 @@ template("foo") { ### 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 -# Use set_source_assignment_filter to filter dependencies and add the dependencies whose label matches *:*_res to the dependency list. +# Use set_source_assignment_filter to filter dependencies and add the dependencies with labels matching *:*_res to the dependency list. _deps = [] foreach(_possible_dep, invoker.deps) { set_source_assignment_filter(["*:*_res"]) @@ -492,18 +489,20 @@ set_source_assignment_filter([]) In the latest version, **set_source_assignment_filter** is replaced by **filter_include** and **filter_exclude**. -### Using **deps** for Intra-part Dependencies and **external_deps** for Cross-part Dependencies +### Using deps and external_deps + +- An OpenHarmony component is a group of modules that can provide a capability. -- In OpenHarmony, a part is a group of modules that can provide a certain capability. -- When defining a module, you can declare the **part_name** to signify the part to which the module belongs. +- When defining a module, you must specify **part_name** to indicate the component 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. -- Inter-part dependencies can only be inner-kit modules. +- 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 the same, the two modules belong to the same part. In this case, the dependency between the modules can be declared using **deps**. +- **inner-kit** applies only to dependent modules in different components. -- If the values of **part_name** of modules **a** and **b** are different, the two modules belong to different parts. In this case, the dependency between the modules must be declared using **external_deps** in the format of *componentName:moduleName*. See Example 19. +- If modules **a** and **b** has the same **part_name**, modules **a** and **b** belong to the same component. In this case, declare the dependency between them using **deps**. +- If modules **a** and **b** have different **part_name**, modules **a** and **b** belong to different components. In this case, declare the dependency between them using **external_deps** in the Component name:Module name format. See Example 19. + ``` # Example 19 shared_library("a") { @@ -512,11 +511,3 @@ In the latest version, **set_source_assignment_filter** is replaced by **filter_ ... } ``` - - - - - - - - diff --git a/en/device-dev/subsystems/subsys-build-gn-kconfig-visual-config-guide.md b/en/device-dev/subsystems/subsys-build-gn-kconfig-visual-config-guide.md index 929b6e4d050e0ed0428c0a423e2beca86936f8de..f6f28d7352ad2bdc1226cf3b0228395d4d4e3c7d 100644 --- a/en/device-dev/subsystems/subsys-build-gn-kconfig-visual-config-guide.md +++ b/en/device-dev/subsystems/subsys-build-gn-kconfig-visual-config-guide.md @@ -5,12 +5,12 @@ ### Kconfig Visual Configuration Kconfig visual configuration is implemented on [Kconfiglib](https://github.com/ulfalizer/Kconfiglib) and [Kconfig](https://www.kernel.org/doc/html/latest/kbuild/kconfig-language.html#introduction). It allows customized configuration of OpenHarmony subsystem components. -This function has the following advantages: +Kconfig visual configuration has the following advantages: - Intuitive display of software component options - 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. @@ -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. -## Procedure +## Operation Guide 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. - 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. ```shell - #Go to the build repository directory. + # Go to the build repository directory. cd build/tools/component_tools menuconfig kconfig ``` @@ -68,7 +68,7 @@ This function has the following advantages: Example: - 1. Perform a global build. + 1. Perform a full build. ```shell cp productdefine/common/base/base_product.json productdefine/common/products/ohos-arm64.json @@ -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. - For more operations, see `python3 parse_kconf.py -h`. + For more operations, run `python3 parse_kconf.py -h`. ​ ## 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 - cd build/tools/component_tools - python3 generate_kconfig.py - ``` +```shell +cd build/tools/component_tools +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. diff --git a/en/device-dev/subsystems/subsys-build-mini-lite.md b/en/device-dev/subsystems/subsys-build-mini-lite.md index d8b4c946818710f2d669a26d91b940c08cd6a44e..2f82037899cd8d74fe2388b3c34b1f0137a032e9 100644 --- a/en/device-dev/subsystems/subsys-build-mini-lite.md +++ b/en/device-dev/subsystems/subsys-build-mini-lite.md @@ -2,38 +2,33 @@ ## Overview -The Compilation and Building subsystem is a build framework that supports component-based OpenHarmony development using Generate Ninja \(GN\) and Ninja. You can use this subsystem to: + The Compilation and Building subsystem provides a build framework based on Generate Ninja (GN) and Ninja. This subsystem allows you to: -- Assemble components for a product and build the product. +- Assemble components into a product and build the product. -- Build chipset source code independently. -- Build a single component independently. +- Build chipset source code independently. -### Basic Concepts - -Learn the following concepts before you start compilation and building: - -- Subsystem - - A subsystem is a logical concept. It consists of one or more components. OpenHarmony is designed with a layered architecture, which consists of the kernel layer, system service layer, framework layer, and application layer from bottom to top. System functions are developed by the level of system, subsystem, and component. In a multi-device deployment scenario, you can customize subsystems and components as required. - - -- Component - - A component is a reusable, configurable, and tailorable function unit. Each component has an independent directory, and multiple components can be developed concurrently and built and tested independently. - -- GN - - Generate Ninja \(GN\) is used to generate Ninja files. - -- Ninja - - Ninja is a small high-speed build system. - -- hb +- Build a single component independently. - hb is a command line tool for OpenHarmony to execute build commands. +### Basic Concepts +Learn the following basic concepts before you start: + +- Subsystem + + A subsystem, as a logical concept, consists of one or more components. OpenHarmony is designed with a layered architecture, which consists of the kernel layer, system service layer, framework layer, and application layer from the bottom up. System functions are developed by levels, from system to subsystem and then to component. In a multi-device deployment scenario, you can customize subsystems and components as required. +- Component + + A component is a reusable, configurable, and tailorable function unit. Each component has an independent directory, and can be built and tested independently and developed concurrently. +- GN + + GN is short for Generate Ninja. It is used to build Ninja files. +- Ninja + + Ninja is a small high-speed building system. +- hb + + hb is an OpenHarmony command line tool used to execute build commands. ### Directory Structure @@ -42,8 +37,8 @@ build/lite ├── components # Component description file ├── figures # Figures in the readme file ├── hb # hb pip installation package -├── make_rootfs # Script used to create the file system image -├── config # Build configuration +├── make_rootfs # Script used to create a file system image +├── config # Build configurations │ ├── component # Component-related template definition │ ├── kernel # Kernel-related build configuration │ └── subsystem # Subsystem build configuration @@ -52,174 +47,197 @@ build/lite └── 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. -**Figure 1** Build process -![](figure/build-process.jpg "build-process") + **Figure 1** Build process + + ![](figure/build-process.jpg) + +1. Use **hb set** to set the OpenHarmony source code directory and the product to build. + +2. Use **hb build** to build the product, development board, or component. + + The procedure is as follows: + + (1) Read the **config.gni** file of the development board selected. The file contains the build toolchain, linking commands, and build options. -1. Use **hb set** to set the OpenHarmony source code directory and the product to build. -2. 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) 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 -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 -The source code directory for a component is named in the _\{Domain\}/\{Subsystem\}/\{Component\}_ format. The component directory tree is as follows: + The component source code directory is named in the *{Domain}/{Subsystem}/{Component}* format. The component directory structure is as follows: ->![](../public_sys-resources/icon-caution.gif) **CAUTION**
->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. +> ![icon-caution.gif](../public_sys-resources/icon-caution.gif) **CAUTION**
+> 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 ├── interfaces │ ├── innerkits # APIs exposed internally among components -│ └── kits # App APIs provided for app developers +│ └── kits # APIs provided for application developers ├── frameworks # Framework implementation ├── services # Service implementation -└── BUILD.gn # Build script +├── BUILD.gn # Build script ``` -The following example shows how to define attributes of the sensor component of the pan-sensor subsystem: + The following example shows how to configure attributes of the sensor service component of the pan-sensor subsystem: + + ``` + { + "name": "@ohos/sensor_lite", # OpenHarmony Package Manager (HPM) component name, in the @Organization/Component name format. + "description": "Sensor services", # Description of the component functions. + "version": "3.1", # Version, which must be the same as the version of OpenHarmony. + "license": "MIT", # Component license. + "publishAs": "code-segment", # Mode for publishing the HPM package. The default value is code-segment. + "segment": { + "destPath": "" + }, # Code restoration path (source code path) set when "publishAs is code-segment. + "dirs": {"base/sensors/sensor_lite"} # Directory structure of the HPM package. This field is mandatory and can be left empty. + "scripts": {}, # Scripts to be executed. This field is mandatory and can be left empty. + "licensePath": "COPYING", + "readmePath": { + "en": "README.rst" + }, + "component": { # Component attributes. + "name": "sensor_lite", # Component name. + "subsystem": "", # Subsystem to which the component belongs. + "syscap": [], # System capabilities provided by the component for applications. + "features": [], # List of the component's configurable features. Generally, this parameter corresponds to sub_component in build and can be configured. + "adapted_system_type": [], # Adapted system types, which can be mini, small, and standard. Multiple values are allowed. + "rom": "92KB", # Size of the component's ROM. + "ram": "~200KB", # Size of the component's RAM. + "deps": { + "components": [ # Other components on which this component depends. + "samgr_lite" + ], + "third_party": [ # Third-party open-source software on which this component depends. + "bounds_checking_function" + ] + } + "build": { # Build-related configurations. + "sub_component": [ + ""//base/sensors/sensor_lite/services:sensor_service"", # Component build entry + ], # Component build entry. Configure the module here. + "inner_kits": [], # APIs between components. + "test": [] # Entry for building the component's test cases. + } + } + } + ``` + + Observe the following rules when writing the component's **BUILD.gn**: + +- The build target name must be the same as the component name. + +- Define the configurable features in the **BUILD.gn** file of the component. Name the configurable features in the ohos_{subsystem}*{component}*{feature} format. Define the features in component description and configure them in the **config.json** file. + +- Define macros in the OHOS_{SUBSYSTEM}*{COMPONENT}*{FEATURE} format. + + > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+ > The component build script is written in GN. For details about how to use GN, see [GN Quick Start Guide](https://gn.googlesource.com/gn/+/master/docs/quick_start.md). The component is the build target, which can be a static library, a dynamic library, an executable file, or a group. + + The following example shows the **foundation/graphic/ui/BUILD.gn** file for a graphics UI component: + + ``` + # Declare the configurable features of the component. + declare_args() { + enable_ohos_graphic_ui_animator = false # Whether to enable animation. + ohos_ohos_graphic_ui_font = "vector" # Configurable font type, which can be vector or bitmap. + } -``` -{ - "components": [ - { - "component": "sensor_lite", # Component name - "description": "Sensor services", # Brief description of the component - "optional": "true", # Whether the component is mandatory for the system - "dirs": [ # Source code directory of the component - "base/sensors/sensor_lite" - ], - "targets": [ # Build entry of the component - "//base/sensors/sensor_lite/services:sensor_service" - ], - "rom": "92KB", # Component ROM - "ram": "~200KB", # Component RAM (estimated) - "output": [ "libsensor_frameworks.so" ], # Component build outputs - "adapted_kernel": [ "liteos_a" ], # Adapted kernel for the component - "features": [], # Configurable features of the component - "deps": { - "components": [ # Other components on which the component depends - "samgr_lite" - ], - "third_party": [ # Open-source third-party software on which the component depends - "bounds_checking_function" + # Basic component functions. + shared_library("base") { + sources = [ + ... + ] + include_dirs = [ + ... + ] + } + + # Build only when the animator is enabled. + if(enable_ohos_graphic_ui_animator ) { + shared_library("animator") { + sources = [ + ... ] + include_dirs = [ + ... + ] + deps = [ :base ] } } - ] -} -``` - -Observe the following rules when configuring **BUILD.gn**: - -- The build target name must be the same as the component name. -- Define the configurable features in the **BUILD.gn** file of the component. Name the configurable features in the **ohos\_**\{_subsystem_\}**\_**\{_component_\}**\_**\{_feature_\} format. Define the features in component description and configure them in the **config.json** file. -- Define macros in the **OHOS\_**\{_SUBSYSTEM_\}**\_**\{_COMPONENT_\}**\_**\{_FEATURE_\} format. - - >![](../public_sys-resources/icon-note.gif) **NOTE**
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. + ... + # It is recommended that the target name be the same as the name of the component, which can be an executable file (.bin), shared_library (.so file), static_library (.a file), or a group. + executable("ui") { + deps = [ + ":base" + ] + # The animator feature is configured by the product. + if(enable_ohos_graphic_ui_animator ) { + deps += [ + "animator" + ] + } + } + ``` -The following example shows how to build the **foundation/graphic/ui/BUILD.gn** file for a graphics UI component: +### Chipset Solution -``` - # Declare the configurable features of the component - declare_args() { - enable_ohos_graphic_ui_animator = false # Animation switch - ohos_ohos_graphic_ui_font = "vector" # Configurable font type, which can be vector or bitmap - } - - # Basic component functions - shared_library("base") { - sources = [ - ...... - ] - include_dirs = [ - ...... - ] - } - - # Build only when the animator is enabled - if(enable_ohos_graphic_ui_animator ) { - shared_library("animator") { - sources = [ - ...... - ] - include_dirs = [ - ...... - ] - deps = [ :base ] - } - } - ...... - # It is recommended that the target name be the same as the component name, which can be an executable .bin file, shared_library (.so file), static_library (.a file), or a group. - executable("ui") { - deps = [ - ":base" - ] - - # The animator feature is configured by the product. - if(enable_ohos_graphic_ui_animator ) { - deps += [ - "animator" - ] - } - } -``` +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 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 component is built by default based on the development board selected. -The chipset solution directory tree is as follows: +The chipset solution directory structure is as follows: ``` device -└── company # Chipset solution vendor - └── board # Name of the development board - ├── BUILD.gn # Build script - ├── hals # Southbound APIs for OS adaptation - ├── linux # Linux kernel version (optional) - │ └── config.gni # Build options for the Linux version - └── liteos_a # LiteOS kernel version (optional) - └── config.gni # Build options for the LiteOS Cortex-A version +└── board # Chipset solution vendor + └── company # Development board name + ├── BUILD.gn # Build script + ├── hals # OS device API adaptation + ├── linux # (Optional) Linux kernel version + │ └── config.gni # Linux build configuration + └── liteos_a # (Optional) LiteOS kernel version + └── config.gni # LiteOS_A build configuration ``` ->![](../public_sys-resources/icon-note.gif) **NOTE**
->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. +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> 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_version: kernel version used by the development board, for example, 4.19. -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_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_type: build toolchain type, for example, gcc or clang. Currently, only GCC and clang are supported. -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_ld_flags: link options configured for the development board. -``` + ``` + kernel_type: Kernel used by the development board, for example, LiteOS_A, LiteOS_M, or Linux. + 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_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_prefix: Prefix of the toolchain, for example, gcc-arm-none-eabi. + 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_cxx_flags: Build options of the .cpp file 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 @@ -232,172 +250,162 @@ vendor │ ├── BUILD.gn # Product build script │ └── config.json # Product configuration file │ └── fs.yml # File system packaging configuration - └── ...... + └── ... ``` ->![](../public_sys-resources/icon-caution.gif) **CAUTION**
->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. +> ![icon-caution.gif](/public_sys-resources/icon-caution.gif) **CAUTION**
+> 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: -- **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. +1. **vendor/company/product/init_configs/etc** + + This folder contains the rcS, Sxxx, and fstab scripts. The init process runs the rcS, fstab, and S00-xxx scripts in sequence before starting system services. The **S***xxx* script is used to create device nodes and directories, scan device nodes, and change file permissions for the development board and product. These scripts are copied from the **BUILD.gn** file to the **out** directory of the product as required and packaged into the **rootfs** image. -- **vendor/company/product/init\_configs/init.cfg** +2. **vendor/company/product/init_configs/init.cfg** - This file is the configuration file for the **init** process to start services. Currently, the following commands are supported: + This file is the configuration file for the **init** process to start services. Currently, the following commands are supported: - - **start**: starts a service. - - **mkdir**: creates a folder. - - **chmod**: changes the permission on a specified directory or file. - - **chown**: changes the owner group of a specified directory or file. - - **mount**: mounts a device. + - **start**: starts a service. +- **mkdir**: creates a folder. + + - **chmod**: changes the permission on a specified directory or file. +- **chown**: changes the owner group of a specified directory or file. + - **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", - "cmds" : [ - "mkdir /storage/data", # Create a directory. - "chmod 0755 /storage/data", # Change the permission, which is in 0xxx format, for example, 0755. - "mkdir /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. - ...... - "mount vfat /dev/mmcblock0 /sdcard rw, umask=000" # The command is in the mount [File system type][source] [target] [flags] [data] format. - # Currently, flags can only be nodev, noexec, nosuid, or rdonly. - ] - }, { - "name" : "init", - "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 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. - "cmds" : [] - } - ], - "services" : [{ # Service array. A service corresponds to a process. - "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". - "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. - "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. - "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. - "caps" : [4294967295] - }, - ...... - ] -} -``` - -- **vendor/company/product/init\_configs/hals** - - This file stores the content related to OS adaptation of the product. For details about APIs for implementing OS adaptation, see the readme file of each component. - -- **vendor/company/product/config.json** - - The **config.json** file is the main entry for the build and contains configurations of the development board, OS components, and kernel. - - The following example shows the **config.json** file of the IP camera developed based on the hispark\_taurus development board: - -``` -{ - "product_name": "ipcamera", # Product name - "version": "3.0", # config.json version, which is 3.0 - "type": "small", # System type, which can be mini, small, or standard - "ohos_version": "OpenHarmony 1.0", # OS version - "device_company": "hisilicon", # Chipset vendor - "board": "hispark_taurus", # Name of the development board - "kernel_type": "liteos_a", # Kernel type - "kernel_version": "3.0.0", # Kernel version - "subsystems": [ - { - "subsystem": "aafwk", # Subsystem - "components": [ - { "component": "ability", "features":[ "enable_ohos_appexecfwk_feature_ability = true" ] } # Component and its features - ] - }, - { - ...... - } - ...... - More subsystems and components - } -} -``` - -- **vendor/company/product/fs.yml** - - This file packages the build result to create a configuration file system image, for example, **rootfs.img** \(user-space root file system\) and **userfs.img** \(readable and writable file\). It consists of multiple lists, and each list corresponds to a file system. The fields are described as follows: - -``` -fs_dir_name: (Mandatory) declares the name of the file system, for example, rootfs or userfs. -fs_dirs: (Optional) configures the mapping between the file directory in the out directory and the system file directory. Each file directory corresponds to a list. -source_dir: (Optional) specifies the target file directory in the out directory. If this field is missing, an empty directory will be created in the file system based on target_dir. -target_dir: (Mandatory) specifies the corresponding file directory in the file system. -ignore_files: (Optional) declares ignored files during the copy operation. -dir_mode: (Optional) specifies the file directory permission, which is set to 755 by default. -file_mode: (Optional) declares permissions of all files in the directory, which is set to 555 by default. -fs_filemode: (Optional) configures files that require special permissions. Each file corresponds to a list. -file_dir: (Mandatory) specifies the detailed file path in the file system. -file_mode: (Mandatory) declares file permissions. -fs_symlink: (Optional) configures the soft link of the file system. -fs_make_cmd: (Mandatory) creates the file system script. The script provided by the OS is stored in the build/lite/make_rootfs directory. Linux, LiteOS, ext4, jffs2, and vfat are supported. Chipset vendors can also customize the script as required. -fs_attr: (Optional) dynamically adjusts the file system based on configuration items. -``` - -The **fs\_symlink** and **fs\_make\_cmd** fields support the following variables: - -- $\{root\_path\} - - Code root directory, which corresponds to **$\{ohos\_root\_path\}** of GN - -- $\{out\_path\} - - **out** directory of the product, which corresponds to **$\{root\_out\_dir\}** of GN - -- $\{fs\_dir\} - - File system directory, which consists of the following variables - - - $\{root\_path\} - - $\{fs\_dir\_name\} - ->![](../public_sys-resources/icon-note.gif) **NOTE**
->**fs.yml** is optional and does not need to be configured for devices without a file system. + "cmds" : [ + "mkdir /storage/data", # Create a directory. + "chmod 0755 /storage/data", #Modify the permissions. The format of the permission value is 0xxx, for example, 0755. + "mkdir /storage/data/log", + "chmod 0755 /storage/data/log", + "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 format is mount [File system type] [source] [target] [flags] [data]. + # The value of flags can be nodev, noexec, nosuid, or rdonly only. + ] + }, { + "name" : "init", + "cmds" : [ # Start services based on the sequence of the cmds array. + "start shell", # There is only one space between start and the service name. + ... + "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). + "cmds" : [] + } + ], + "services" : [{ # Service array. A service corresponds to a process. + "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". + "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. + "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. 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] + }, + ... + ] + } + ``` + +3. **vendor/company/product/init_configs/hals** -- **vendor/company/product/BUILD.gn** + This file contains the OS adaptation of the product. For details about APIs for implementing OS adaptation, see the readme file of each component. - This file is the entry for building the source code of the solution vendor and copying the startup configuration file. The **BUILD.gn** file in the corresponding product directory will be built by default if a product is selected. The following example shows how to build the **BUILD.gn** file of a product: +4. **vendor/company/product/config.json** -``` -group("product") { # The target name must be the same as the product name (level-3 directory name under the product directory). - deps = [] - # Copy the init configuration. - deps += [ "init_configs" ] - # Others - ...... -} -``` + The **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 board: -## Usage Guidelines + ``` + { + "product_name": "ipcamera", # Product name + "version": "3.0", # Version of config.json. The value is 3.0. + "type": "small", # System type. The value can be mini, small, or standard. + "ohos_version": "OpenHarmony 1.0", # OS version + "device_company": "hisilicon", # Chipset vendor + "board": "hispark_taurus", # Name of the development board + "kernel_type": "liteos_a", # Kernel type + "kernel_version": "3.0.0", # Kernel version + "subsystems": [ + { + "subsystem": "aafwk", # Subsystem + "components": [ + { "component": "ability", "features":[ "enable_ohos_appexecfwk_feature_ability = true" ] } # Selected component and feature configuration + ] + }, + { + ... + } + ... + More subsystems and components + } + } + ``` + +5. **vendor/company/product/fs.yml** + + This file defines the process for creating a file system image, for example, **rootfs.img** (user-space root file system) and **userfs.img** (readable and writable file). It consists of multiple lists, and each list corresponds to a file system. The fields are described as follows: + + ``` + fs_dir_name: (Mandatory) specifies name of the file system, for example, rootfs or userfs. + fs_dirs: (Optional) specifies the mapping between the file directory in the out directory and the system file directory. Each file directory corresponds to a list. + source_dir: (Optional) specifies target file directory in the out directory. If this field is not specified, an empty directory will be created in the file system based on target_dir. + target_dir: (Mandatory) specifies the file directory in the file system. + ignore_files: (Optional) declares ignored files during the copy operation. + dir_mode: (Optional) specifies the file directory permissions. The default value is 755. + file_mode: (Optional) specifies the permissions of all files in the directory. The default value is 555. + fs_filemode: (Optional) specifies the files that require special permissions. Each file corresponds to a list. + file_dir: (Mandatory) specifies the detailed file path in the file system. + file_mode: (Mandatory) declares file permissions. + fs_symlink: (Optional) specifies the soft link of the file system. + fs_make_cmd: (Mandatory) creates the file system script. The script provided by the OS is located in the build/lite/make_rootfs directory. Linux, LiteOS, ext4, jffs2, and vfat are supported. Chipset vendors can also customize the script as required. + fs_attr: (Optional) dynamically adjusts the file system based on configuration items. + ``` + + The **fs_symlink** and **fs_make_cmd** fields support the following variables: + + - ${root_path}: code root directory, which corresponds to **${ohos_root_path}** of GN. + - ${out_path}: **out** directory of the product, which corresponds to **${root_out_dir}** of GN. + - ${fs_dir}: file system directory, which consists of variables ${root_path} and ${fs_dir_name}. +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> **fs.yml** is optional and not required for devices without a file system. + +6. **vendor/company/product/BUILD.gn** + + This file provides the product built entry. It is used to build the source code of the solution vendor and copy the startup configuration file. The **BUILD.gn** file in the corresponding product directory will be built by default if a product is selected. + + The following is an example of the **BUILD.gn** file of a product: + + ``` + group("product") { # The name must be the same as the product name (level-3 directory name under the product directory). + deps = [] + # Copy the init configuration. + deps += [ "init_configs" ] + # Others + ... + } + ``` + +## Guidelines ### Prerequisites -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 -**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 @@ -410,13 +418,15 @@ optional arguments: -p, --product Set OHOS board and kernel ``` -- **hb set** \(without argument\): starts the default setting process. -- **hb set -root** _dir_: sets the root directory of the code. -- **hb set -p**: sets the product to build. +- If you run **hb set** with no argument, the default setting process starts. + +- You can run **hb set -root** *dir* to set the root directory of the source code. + +- You can run **hb set -p** to set the product to build. **hb env** -Displays the current configuration. +Displays the current settings. ``` hb env @@ -428,57 +438,66 @@ hb env [OHOS INFO] device path: xxx/device/hisilicon/hispark_taurus/sdk_linux_4.19 ``` -**hb build** + **hb build** ``` hb build -h -usage: hb build [-h] [-b BUILD_TYPE] [-c COMPILER] [-t [TEST [TEST ...]]] - [--dmverity] [--tee] [-p PRODUCT] [-f] [-n] - [-T [TARGET [TARGET ...]]] [-v] [-shs] [--patch] +usage: hb build [-h] [-b BUILD_TYPE] [-c COMPILER] [-t [TEST [TEST ...]]] [-cpu TARGET_CPU] [--dmverity] [--tee] + [-p PRODUCT] [-f] [-n] [-T [TARGET [TARGET ...]]] [-v] [-shs] [--patch] [--compact-mode] + [--gn-args GN_ARGS] [--keep-ninja-going] [--build-only-gn] [--log-level LOG_LEVEL] [--fast-rebuild] + [--device-type DEVICE_TYPE] [--build-variant BUILD_VARIANT] [component [component ...]] positional arguments: - component name of the component + component name of the component, mini/small only optional arguments: -h, --help show this help message and exit -b BUILD_TYPE, --build_type BUILD_TYPE - release or debug version + release or debug version, mini/small only -c COMPILER, --compiler COMPILER - specify compiler + specify compiler, mini/small only -t [TEST [TEST ...]], --test [TEST [TEST ...]] compile test suit - --dmverity Enable dmverity + -cpu TARGET_CPU, --target-cpu TARGET_CPU + select cpu + --dmverity enable dmverity --tee Enable tee -p PRODUCT, --product PRODUCT - build a specified product with - {product_name}@{company}, eg: camera@huawei + build a specified product with {product_name}@{company} -f, --full full code compilation -n, --ndk compile ndk -T [TARGET [TARGET ...]], --target [TARGET [TARGET ...]] - Compile single target + compile single target -v, --verbose show all command lines while building -shs, --sign_haps_by_server sign haps by server --patch apply product patch before compiling - - --dmverity Enable dmverity - -p PRODUCT, --product PRODUCT - build a specified product with - {product_name}@{company}, eg: ipcamera@hisilcon - -f, --full full code compilation - -T [TARGET [TARGET ...]], --target [TARGET [TARGET ...]] - Compile single target + --compact-mode compatible with standard build system set to false if we use build.sh as build entrance + --gn-args GN_ARGS specifies gn build arguments, eg: --gn-args="foo="bar" enable=true blah=7" + --keep-ninja-going keeps ninja going until 1000000 jobs fail + --build-only-gn only do gn parse, donot run ninja + --log-level LOG_LEVEL + specifies the log level during compilationyou can select three levels: debug, info and error + --fast-rebuild it will skip prepare, preloader, gn_gen steps so we can enable it only when there is no change + 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**. -- **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** 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. +- 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**. + +- 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 -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** -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 @@ -495,477 +514,468 @@ optional arguments: To add a component, determine the subsystem to which the component belongs and the component name, and then perform the following steps: -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\). +1. Add the component build script after the source code development is complete. + + The following example shows the **BUILD.gn** script (in the **applications/sample/hello_world** directory) for the **hello_world** executable file. - ``` - executable("hello_world") { - include_dirs = [ - "include", - ] - sources = [ - "src/hello_world.c" + ``` + executable("hello_world") { + include_dirs = [ + "include", ] - } - ``` - - The above script is used to build **hello\_world** that can run on OpenHarmony. - - To build the preceding component separately, select a product via the **hb set** command and run the **-T** command. - - ``` - 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. - -2. Add 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: - - - **component**: name of the component - - **description**: brief description of the component - - **optional**: whether the component is optional - - **dirs**: source code directory of the component - - **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. - - ``` - { - "components": [ - { - "component": "hello_world", - "description": "Hello world.", - "optional": "true", - "dirs": [ - "applications/sample/hello_world" - ], - "targets": [ - "//applications/sample/hello_world" - ] - }, - ... + sources = [ + "src/hello_world.c" + ] + } + ``` + + This script can be used to build a file named **hello_world** that can run on OpenHarmony. + + 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 + ``` + + After the component functions are verified on the development board, perform steps 2 to 4 to add the component to the product. + +2. Add the component description. + + 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**: component name. + - **description**: description of the component functions. + - **optional**: whether the component is optional. + - **dirs**: source code directory of the component. + - **targets**: component build entry. + + The following is an example of adding the **hello_world** component to the **applications.json** file. + + ``` + { + "components": [ + { + "component": "hello_world", + "description": "Hello world.", + "optional": "true", + "dirs": [ + "applications/sample/hello_world" + ], + "targets": [ + "//applications/sample/hello_world" + ] + }, + ... + ] + } + ``` + +3. Add the component to the product. + + The product configuration file **config.json** is located in the **vendor/company/product/** directory. This file contains the product name, OpenHarmony version, device vendor, development board, kernel type, kernel version, subsystems, and components. The following example adds **hello_world** to the **my_product.json** file: + + ``` + { + "product_name": "hello_world_test", + "ohos_version": "OpenHarmony 1.0", + "device_company": "hisilicon", + "board": "hispark_taurus", + "kernel_type": "liteos_a", + "kernel_version": "1.0.0", + "subsystems": [ + { + "subsystem": "applications", + "components": [ + { "component": "hello_world", "features":[] } + ] + }, + ... ] - } - ``` - -3. Configure the component for the product. - - The **config.json** file is stored in the **vendor/company/product/** directory. The file must contain the product name, OpenHarmony version, device vendor, development board, kernel type, kernel version, and the subsystem and component to configure. The following example adds the **hello\_world** component to the **my\_product.json** configuration file: - - ``` - { - "product_name": "hello_world_test", - "ohos_version": "OpenHarmony 1.0", - "device_company": "hisilicon", - "board": "hispark_taurus", - "kernel_type": "liteos_a", - "kernel_version": "1.0.0", - "subsystems": [ - { - "subsystem": "applications", - "components": [ - { "component": "hello_world", "features":[] } - ] - }, - ... - ] - } - ``` - -4. Build the product. - - 1. Run the **hb set** command in the root code directory and select the product. - - 2. Run the **hb build** command. + } + ``` +4. Build the product. + + 1. Run the **hb set** command in the root code directory and select the product. + + 2. Run the **hb build** command. ### Adding a Chipset Solution 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. - - To create a directory based on [Configuration Rules](#configuration-rules), run the following command in the root code directory: - - ``` - mkdir -p device/realtek/rtl8720 - ``` - -2. Create a directory for kernel adaptation and build the **config.gni** file of the development board. - - For example, to adapt the LiteOS-A kernel to the RTL8720 development board, configure the **device/realtek/rtl8720/liteos\_a/config.gni** file as follows: - - ``` - # Kernel type, e.g. "linux", "liteos_a", "liteos_m". - kernel_type = "liteos_a" - - # Kernel version. - kernel_version = "3.0.0" - - # Board CPU type, e.g. "cortex-a7", "riscv32". - board_cpu = "real-m300" - - # Board arch, e.g. "armv7-a", "rv32imac". - board_arch = "" - - # Toolchain name used for system compiling. - # E.g. gcc-arm-none-eabi, arm-linux-harmonyeabi-gcc, ohos-clang, riscv32-unknown-elf. - # Note: The default toolchain is "ohos-clang". It's not mandatory if you use the default toochain. - board_toolchain = "gcc-arm-none-eabi" - - # The toolchain path instatlled, it's not mandatory if you have added toolchian path to your ~/.bashrc. - board_toolchain_path = - rebase_path("//prebuilts/gcc/linux-x86/arm/gcc-arm-none-eabi/bin", - root_build_dir) - - # Compiler prefix. - board_toolchain_prefix = "gcc-arm-none-eabi-" - - # Compiler type, "gcc" or "clang". - board_toolchain_type = "gcc" - - # Board related common compile flags. - board_cflags = [] - board_cxx_flags = [] - board_ld_flags = [] - ``` - -3. Build the script. - - Create the **BUILD.gn** file in the development board directory. The target name must be the same as that of the development board. The content in the **device/realtek/rtl8720/BUILD.gn** file is configured as follows: - - ``` - group("rtl8720") { # The target can be shared_library, static_library, or an executable file. - # Content - ...... - } - ``` - -4. Build the chipset solution. - - Run the **hb build** command in the development board directory to start the build. - +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: + + ``` + mkdir -p device/board/realtek/rtl8720 + ``` + +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: + + ``` + # Kernel type, e.g. "linux", "liteos_a", "liteos_m". + kernel_type = "liteos_a" + + # Kernel version. + kernel_version = "3.0.0" + + # Board CPU type, e.g. "cortex-a7", "riscv32". + board_cpu = "real-m300" + + # Board arch, e.g. "armv7-a", "rv32imac". + board_arch = "" + + # Toolchain name used for system compiling. + # E.g. gcc-arm-none-eabi, arm-linux-harmonyeabi-gcc, ohos-clang, riscv32-unknown-elf. + # Note: The default toolchain is "ohos-clang". It's not mandatory if you use the default toochain. + board_toolchain = "gcc-arm-none-eabi" + + # The toolchain path installed, it's not mandatory if you have added toolchain path to your ~/.bashrc. + board_toolchain_path = + rebase_path("//prebuilts/gcc/linux-x86/arm/gcc-arm-none-eabi/bin", + root_build_dir) + + # Compiler prefix. + board_toolchain_prefix = "gcc-arm-none-eabi-" + + # Compiler type, "gcc" or "clang". + board_toolchain_type = "gcc" + + # Board related common compile flags. + board_cflags = [] + board_cxx_flags = [] + board_ld_flags = [] + ``` + +3. Write the build script. + Create the **BUILD.gn** file in the development board directory. The target name must be the same as that of the development board. The following is an example of the **device/realtek/rtl8720/BUILD.gn** file for the RTL8720 development board: + + ``` + group("rtl8720") { # The build target can be shared_library, static_library, or an executable file. + # Content + ... + } + ``` + +4. Build the chipset solution. + + Run the **hb build** command in the development board directory to start the build. ### 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: - -1. Create a product directory. - - 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): - - ``` - mkdir -p vendor/my_company/wifiiot - ``` - -2. Assemble the product. - - Create the **config.json** file in the product directory. The **vendor/my\_company/wifiiot/config.json** file is as follows: - - ``` - { - "product_name": "wifiiot", # Product name - "version": "3.0", # config.json version, which is 3.0 - "type": "small", # System type, which can be mini, small, or standard - "ohos_version": "OpenHarmony 1.0", # OS version - "device_company": "realtek", # Name of the chipset solution vendor - "board": "rtl8720", # Name of the development board - "kernel_type": "liteos_m", # Kernel type - "kernel_version": "3.0.0", # Kernel version - "subsystems": [ - { - "subsystem": "kernel", # Subsystem - "components": [ - { "component": "liteos_m", "features":[] } # Component and its features - ] - }, - ... - { - More subsystems and components - } - ] - } - ``` - - Before the build, the Compilation and Building subsystem checks the validity of fields, including **device\_company**, **board**, **kernel\_type**, **kernel\_version**, **subsystem**, and **component**. The **device\_company**, **board**, **kernel\_type**, and **kernel\_version** fields must match the current chipset solution, and **subsystem** and **component** must match the component description in the **build/lite/components** file. - -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. - -4. Configure the system service. - - 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. - -5. \(Optional\) Configure the init process only 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. - -6. \(Optional\) Configure the file system image only 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: - - ``` - - - fs_dir_name: rootfs # Image name - fs_dirs: - - - # Copy the files in the out/my_board/my_product/bin directory to the rootfs/bin directory and ignore the .bin files related to testing. - source_dir: bin - target_dir: bin - ignore_files: - - Test.bin - - TestSuite.bin - - - # Copy the files in the out/my_board/my_product/libs directory to the rootfs/lib directory, ignore all .a files, and set the file permissions to 644 and folder permissions 755. - source_dir: libs - target_dir: lib - ignore_files: - - .a - dir_mode: 755 - file_mode: 644 - - - source_dir: usr/lib - target_dir: usr/lib - ignore_files: - - .a - dir_mode: 755 - file_mode: 644 - - - source_dir: config - target_dir: etc - - - source_dir: system - target_dir: system - - - source_dir: sbin - target_dir: sbin - - - source_dir: usr/bin - target_dir: usr/bin - - - source_dir: usr/sbin - target_dir: usr/sbin - - - # Create an empty proc directory. - target_dir: proc - - - target_dir: mnt - - - target_dir: opt - - - target_dir: tmp - - - target_dir: var - - - target_dir: sys - - - source_dir: etc - target_dir: etc - - - source_dir: vendor - target_dir: vendor - - - target_dir: storage - - fs_filemode: - - - file_dir: lib/ld-uClibc-0.9.33.2.so - file_mode: 555 - - - file_dir: lib/ld-2.24.so - file_mode: 555 - - - file_dir: etc/init.cfg - file_mode: 400 - fs_symlink: - - - # Create the soft link ld-musl-arm.so.1 -> libc.so in the rootfs/lib directory. - source: libc.so - link_name: ${fs_dir}/lib/ld-musl-arm.so.1 - - - source: mksh - link_name: ${fs_dir}/bin/sh - - - source: mksh - link_name: ${fs_dir}/bin/shell - fs_make_cmd: - # Create an ext4 image for the rootfs directory using the script. - - ${root_path}/build/lite/make_rootfs/rootfsimg_linux.sh ${fs_dir} ext4 - - - fs_dir_name: userfs - fs_dirs: - - - source_dir: storage/etc - target_dir: etc - - - source_dir: data - target_dir: data - fs_make_cmd: - - ${root_path}/build/lite/make_rootfs/rootfsimg_linux.sh ${fs_dir} ext4 - - ``` - -7. \(Optional\) Configure patches if the product and components need to be patched. - - Create the **patch.yml** file in the product directory and configure it as required. A typical **patch.yml** file is as follows: - - ``` - # Directory in which the patch is to be installed - foundation/communication/dsoftbus: - # Directory in which the patch is stored - - foundation/communication/dsoftbus/1.patch - - foundation/communication/dsoftbus/2.patch - third_party/wpa_supplicant: - - third_party/wpa_supplicant/1.patch - - third_party/wpa_supplicant/2.patch - - third_party/wpa_supplicant/3.patch - ... - ``` - - If you add **--patch** when running the **hb build** command, the patch file can be added to the specified directory before the build. - - ``` - hb build -f --patch - ``` - -8. Build the 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: - - ``` - group("wifiiot") { # The target name must be the same as the product name. - deps = [] - # Copy the init configuration. - deps += [ "init_configs" ] - # Build the hals directory. - deps += [ "hals" ] - # Others - ...... - } - ``` - -9. Build the product. - - Run the **hb set** command in the code root directory, select the new product as prompted, and run the **hb build** command. - +You can customize a product solution by flexibly assembling a chipset solution and components. The procedure is as follows: + +1. Create a product directory based on the [configuration rules](#product-solution). + + 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 + ``` + +2. Assemble the product. + + 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 + "version": "3.0", # Version of config.json. The value is 3.0. + "type": "small", # System type. The value can be mini, small, or standard. + "ohos_version": "OpenHarmony 1.0", # OS version + "device_company": "realtek", # Name of the chipset solution vendor + "board": "rtl8720", # Name of the development board + "kernel_type": "liteos_m", # Kernel type + "kernel_version": "3.0.0", # Kernel version + "subsystems": [ + { + "subsystem": "kernel", # Subsystem + "components": [ + { "component": "liteos_m", "features":[] } # Component and its features + ] + }, + ... + { + More subsystems and components + } + ] + } + ``` + +> ![icon-caution.gif](../public_sys-resources/icon-caution.gif) **CAUTION**
+> 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. + + 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 system services. + + 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 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 **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 for the development board that supports the file system. + + Create a **fs.yml** file in the product directory and configure it as required. A typical **fs.yml** file is as follows: + + ``` + - + fs_dir_name: rootfs # Image name + fs_dirs: + - + # Copy the files in the out/my_board/my_product/bin directory to the rootfs/bin directory and ignore the .bin files related to testing. + source_dir: bin + target_dir: bin + ignore_files: + - Test.bin + - TestSuite.bin + - + # Copy the files in the out/my_board/my_product/libs directory to the rootfs/lib directory, ignore all .a files, and set the file permissions to 644 and folder permissions 755. + source_dir: libs + target_dir: lib + ignore_files: + - .a + dir_mode: 755 + file_mode: 644 + - + source_dir: usr/lib + target_dir: usr/lib + ignore_files: + - .a + dir_mode: 755 + file_mode: 644 + - + source_dir: config + target_dir: etc + - + source_dir: system + target_dir: system + - + source_dir: sbin + target_dir: sbin + - + source_dir: usr/bin + target_dir: usr/bin + - + source_dir: usr/sbin + target_dir: usr/sbin + - + # Create an empty proc directory. + target_dir: proc + - + target_dir: mnt + - + target_dir: opt + - + target_dir: tmp + - + target_dir: var + - + target_dir: sys + - + source_dir: etc + target_dir: etc + - + source_dir: vendor + target_dir: vendor + - + target_dir: storage + + fs_filemode: + - + file_dir: lib/ld-uClibc-0.9.33.2.so + file_mode: 555 + - + file_dir: lib/ld-2.24.so + file_mode: 555 + - + file_dir: etc/init.cfg + file_mode: 400 + fs_symlink: + - + # Create the soft link ld-musl-arm.so.1 -> libc.so in the rootfs/lib directory. + source: libc.so + link_name: ${fs_dir}/lib/ld-musl-arm.so.1 + - + source: mksh + link_name: ${fs_dir}/bin/sh + - + source: mksh + link_name: ${fs_dir}/bin/shell + fs_make_cmd: + # Run the script to create an ext4 image from rootfs. + - ${root_path}/build/lite/make_rootfs/rootfsimg_linux.sh ${fs_dir} ext4 + - + fs_dir_name: userfs + fs_dirs: + - + source_dir: storage/etc + target_dir: etc + - + source_dir: data + target_dir: data + fs_make_cmd: + - ${root_path}/build/lite/make_rootfs/rootfsimg_linux.sh ${fs_dir} ext4 + + ``` + +7. (Optional) Configure patches if the product and components need to be patched. + + Create a **patch.yml** file in the product directory and configure it as required. A typical **patch.yml** file is as follows: + + ``` + # Directory in which the patch is to be installed + foundation/communication/dsoftbus: + # Directory in which the patch is stored. + - foundation/communication/dsoftbus/1.patch + - foundation/communication/dsoftbus/2.patch + third_party/wpa_supplicant: + - third_party/wpa_supplicant/1.patch + - third_party/wpa_supplicant/2.patch + - third_party/wpa_supplicant/3.patch + ... + ``` + + 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 + ``` + +8. Write the build script. + + Create a **BUILD.gn** file in the product directory and write the script. The following **BUILD.gn** file uses the Wi-Fi IoT module in step 1 as an example: + + ``` + group("wifiiot") { # The target name must be the same as the product name. + deps = [] + # Copy the init configuration. + deps += [ "init_configs" ] + # Add **hals**. + deps += [ "hals" ] + # Others + ... + } + ``` + +9. Build the product. + + Run the **hb set** command in the code root directory, select the new product as prompted, and run the **hb build** command. ## Troubleshooting -### Invalid -- w Option - -- **Symptom** - - The build fails, and "usr/sbin/ninja: invalid option -- w" is displayed. - -- **Cause** - - The Ninja version in the build environment is outdated and does not support the **--w** option. - -- **Solution** - - Uninstall Ninja and GN and follow the instructions provided in [IDE](../get-code/gettools-ide.md) to install Ninja and GN of the required version. - - -### Library ncurses Not Found - -- **Symptom** - - The build fails, and "/usr/bin/ld: cannot find -lncurses" is displayed. - -- **Cause** - - The ncurses library is not installed. - -- **Solution** - - ``` - sudo apt-get install lib32ncurses5-dev - ``` - - -### mcopy not Found - -- **Symptom** - - The build fails, and "line 77: mcopy: command not found" is displayed. - -- **Cause** - - mcopy is not installed. - -- **Solution** - - ``` - sudo apt-get install dosfstools mtools - ``` - - -### No riscv File or Directory - -- **Symptom** - - The build fails, and the following information is displayed: +### "usr/sbin/ninja: invalid option -- w" Displayed During the Build Process - riscv32-unknown-elf-gcc: error trying to exec 'cc1': execvp: No such file or directory. +- **Symptom** + + The build fails, and **usr/sbin/ninja: invalid option -- w** is displayed. -- **Cause** +- **Possible Causes** + + The Ninja version in use does not support the **--w** option. - Permission is required to access files in the **riscv** compiler directory. +- **Solution** + + Uninstall Ninja and GN, and [install Ninja and GN of the required version](../get-code/gettools-ide.md). -- **Solution** +### "/usr/bin/ld: cannot find -lncurses" Displayed During the Build Process - Run the following command to query the directory where **gcc\_riscv32** is located: +- **Symptom** + + The build fails, and **/usr/bin/ld: cannot find -lncurses** is displayed. - ``` - which riscv32-unknown-elf-gcc - ``` +- **Possible Causes** + + The ncurses library is not installed. + +- **Solution** + + ``` + sudo apt-get install lib32ncurses5-dev + ``` - Run the **chmod** command to change the directory permission to **755**. +### "line 77: mcopy: command not found" Displayed During the Build Process +- **Symptom** + + The build fails, and **line 77: mcopy: command not found** is displayed. -### No Crypto +- **Possible Causes** + + mcopy is not installed. -- **Symptom** +- **Solution** + + ``` + sudo apt-get install dosfstools mtools + ``` - The build fails, and "No component named 'Crypto'" is displayed. +### "riscv32-unknown-elf-gcc: error trying to exec 'cc1': execvp: No such file or directory" Displayed During the Build Process -- **Cause** +- **Symptom** + + The build fails, and the following information is displayed:
**riscv32-unknown-elf-gcc: error trying to exec 'cc1': execvp: No such file or directory** - Crypto is not installed in Python 3. +- **Possible Causes** + + Permission is required to access files in the RISC-V compiler directory. -- **Solution** - 1. Run the following command to query the Python version: +- **Solution** - ``` - python3 --version - ``` + 1. Run the following command to locate **gcc_riscv32**: - 2. Ensure that Python 3.7 or later is installed, and then run the following command to install pycryptodome: + ``` + which riscv32-unknown-elf-gcc + ``` - ``` - sudo pip3 install pycryptodome - ``` + 2. Run the **chmod** command to change the directory permission to **755**. + + -### Unexpected Operator +### "No module named 'Crypto'" Displayed During the Build Process -- **Symptom** +- **Symptom** + + The build fails, and **No module named 'Crypto'** is displayed. - The build fails, and "xx.sh \[: xx unexpected operator" is displayed. +- **Possible Causes** + + Crypto is not installed in Python 3. -- **Cause** +- **Solution** + + 1. Run the following command to query the Python version: + + ``` + python3 --version + ``` + + 2. Ensure that Python 3.9.2 or later is installed, and then run the following command to install PyCryptodome: + + ``` + sudo pip3 install pycryptodome + ``` - The build environment is shell, not bash. +### "xx.sh : xx unexpected operator" Displayed During the Build Process -- **Solution** +- **Symptom** + + The build fails, and **xx.sh [: xx unexpected operator** is displayed. - ``` - sudo rm -rf /bin/sh - sudo ln -s /bin/bash /bin/sh - ``` +- **Possible Causes** + + The build environment shell is not bash. +- **Solution** + + ``` + sudo rm -rf /bin/sh + sudo ln -s /bin/bash /bin/sh + ``` diff --git a/en/device-dev/subsystems/subsys-build-standard-large.md b/en/device-dev/subsystems/subsys-build-standard-large.md index 588d41c97447e31a06b67f21e226f27e00183efe..d1f3eb9fd89a82aee966221853706f0d7562e776 100644 --- a/en/device-dev/subsystems/subsys-build-standard-large.md +++ b/en/device-dev/subsystems/subsys-build-standard-large.md @@ -1,226 +1,813 @@ -# Building the Standard System +# Building the Standard System -## Overview +## Overview -The compilation and building subsystem provides a framework based on Generate Ninja \(GN\) and Ninja. This subsystem allows you to: +The Compilation and Building subsystem provides a build framework based on Generate Ninja (GN) and Ninja. This subsystem allows you to: -- Build products based on different chipset platforms, for example, Hi3516D V300. +- Build products based on different chipset platforms, for example, hispark_taurus_standard. -- Package capabilities required by a product by assembling modules based on the product configuration. +- Package capabilities required by a product by assembling components based on the product configuration. -### Basic Concepts +### Basic Concepts -It is considered best practice to learn the following basic concepts before you start building: +Learn the following basic concepts before you start: -- **Platform** +- Platform + + A platform consists of the development board and kernel. The supported subsystems and components vary with the platform. - A platform is a combination of development boards and kernels. +- Subsystem + + OpenHarmony is designed with a layered architecture, which consists of the kernel layer, system service layer, framework layer, and application layer from the bottom up. System functions are developed by levels, from system to subsystem and then to component. In a multi-device deployment scenario, you can customize subsystems and components as required. A subsystem, as a logical concept, consists of the least required components. - Supported subsystems and modules vary according to the platform. +- Component + + A component is a reusable software unit that contains source code, configuration files, resource files, and build scripts. Integrated in binary mode, a component can be built and tested independently. -- **Subsystems** +- GN + + GN is short for Generate Ninja. It is used to build Ninja files. - OpenHarmony is designed with a layered architecture, which from bottom to top consists of the kernel layer, system service layer, framework layer, and application layer. System functions are expanded by levels, from system to subsystem, and further to module. In a multi-device deployment scenario, unnecessary subsystems and modules can be excluded from the system as required. A subsystem is a logical concept and is a flexible combination of functions. +- Ninja + + Ninja is a small high-speed building system. -- **Module** +### Working Principles - A module is a reusable software binary unit that contains source code, configuration files, resource files, and build scripts. A module can be built independently, integrated in binary mode, and then tested independently. +The process for building an OpenHarmony system is as follows: -- **GN** +- Parsing commands: Parse the name of the product to build and load related configurations. - GN is short for Generate Ninja, which is used to generate Ninja files. +- Running GN: Configure the toolchain and global options based on the product name and compilation type. -- **Ninja** +- Running Ninja: Start building and generate a product distribution. - Ninja is a small high-speed build system. +### Constraints +- You need to obtain the source code using method 3 described in [Obtaining Source Code](../get-code/sourcecode-acquire.md). -### Working Principles +- Ubuntu 18.04 or later must be used. -The process to build OpenHarmony is as follows: +- You must install the software packages required for build. + The command is as follows: + + ``` + # Run the script in the home directory. + # ./build/build_scripts/env_setup.sh + # Do not run the command as the **root** user. Otherwise, the environment variables will be added to the **root** user. If your **shell** is not **bash** or **Zsh**, you need to manually configure the following content to your environment variables after the execution. To view your environment variables, run the **cd** command to go to your home directory and view the hidden files. + # export PATH=/home/tools/llvm/bin:$PATH + # export PATH=/home/tools/hc-gen:$PATH + # export PATH=/home/tools/gcc_riscv32/bin:$PATH + # export PATH=/home/tools/ninja:$PATH + # export PATH=/home/tools/node-v12.20.0-linux-x64/bin:$PATH + # export PATH=/home/tools/gn:$PATH + # export PATH=/root/.local/bin:$PATH + + # If you do not need to run the script, you need to install the following: + apt-get update -y + apt-get install -y apt-utils binutils bison flex bc build-essential make mtd-utils gcc-arm-linux-gnueabi u-boot-tools python3.9.2 python3-pip git zip unzip curl wget gcc g++ ruby dosfstools mtools default-jre default-jdk scons python3-distutils perl openssl libssl-dev cpio git-lfs m4 ccache zlib1g-dev tar rsync liblz4-tool genext2fs binutils-dev device-tree-compiler e2fsprogs git-core gnupg gnutls-bin gperf lib32ncurses5-dev libffi-dev zlib* libelf-dev libx11-dev libgl1-mesa-dev lib32z1-dev xsltproc x11proto-core-dev libc6-dev-i386 libxml2-dev lib32z-dev libdwarf-dev + apt-get install -y grsync xxd libglib2.0-dev libpixman-1-dev kmod jfsutils reiserfsprogs xfsprogs squashfs-tools pcmciautils quota ppp libtinfo-dev libtinfo5 libncurses5 libncurses5-dev libncursesw5 libstdc++6 python2.7 gcc-arm-none-eabi vim ssh locales doxygen + # Install the following modules for Python: + chmod +x /usr/bin/repo + pip3 install --trusted-host https://repo.huaweicloud.com -i https://repo.huaweicloud.com/repository/pypi/simple requests setuptools pymongo kconfiglib pycryptodome ecdsa ohos-build pyyaml prompt_toolkit==1.0.14 redis json2html yagmail python-jenkins + pip3 install esdk-obs-python --trusted-host pypi.org + pip3 install six --upgrade --ignore-installed six + #You also need to install LLVM, hc-gen, gcc_riscv32, Ninja, node-v14.15.4-linux-x64, and GN, and import the non-bash or non-Zsh configuration in the shell to your environment variables. + ``` -- Parsing commands: Parse the name of the product to build and load related configurations. -- Running GN: Configure toolchains and global options based on the parsed product name and compilation type. -- Running Ninja: Start building and generate a product distribution. -### Limitations and Constraints -- You must download the source code using method 3 described in [Source Code Acquisition](../get-code/sourcecode-acquire.md). -- The build environment must be Ubuntu 18.04 or later. -- You must install the software package required for build. +## Building Guidelines - The installation command is as follows: +### Directory Structure - ``` - sudo apt-get install binutils git-core gnupg flex bison gperf build-essential zip curl zlib1g-dev gcc-multilib g++-multilib libc6-dev-i386 lib32ncurses5-dev x11proto-core-dev libx11-dev lib32z-dev ccache libgl1-mesa-dev libxml2-utils xsltproc unzip m4 - ``` +``` +/build # Directory for build -## Compilation and Building Guidelines +├── __pycache__ +├── build_scripts/ # Python scripts for build +├── common/ +├── config/ # Build-related configurations +├── core +│ └── gn/ # BUILD.gn configuration + └── build_scripts/ +├── docs +gn_helpers.py* +lite/ # hb and preloader entry +misc/ +├── ohos # Process for building and packaging OpenHarmony +│ ├── kits # Kits build and packaging templates and processing +│ ├── ndk # NDK templates and processing +│ ├── notice # Notice templates and processing +│ ├── packages # Distribution packaging templates and processing +│ ├── sa_profile # SA profiles and processing +│ ├── sdk # SDK templates and processing, which contains the module configuration in the SDK +│ └── testfwk # Testing-related processing +├── ohos.gni* # Common .gni files for importing a module at a time. +├── ohos_system.prop +├── ohos_var.gni* +├── prebuilts_download.sh* +├── print_python_deps.py* +├── scripts/ +├── subsystem_config.json +├── subsystem_config_example.json +├── templates/ # C/C++ build templates +├── test.gni* +├── toolchain # Build toolchain configuration +├── tools # Common tools +├── version.gni +├── zip.py* -### Directory Structure -``` -/build # Primary directory -├── config # Build configuration items -├── core -│ └── gn # Build entry BUILD.gn configuration -├── loader # Loader of module configuration, which also generates a template for the module -├── ohos # Configuration of the process for building and packaging OpenHarmony -│ ├── kits # Build and packaging templates and processing flow for kits -│ ├── ndk # NDK template and processing flow -│ ├── notice # Notice template and processing flow -│ ├── packages # Distribution packaging template and processing flow -│ ├── sa_profile # SA template and processing flow -│ ├── sdk # SDK template and processing flow, which contains the module configuration in the SDK -│ └── testfwk # Processing flow related to the test -├── scripts # Build-related Python script -├── templates # C/C++ build templates -└── toolchain # Toolchain configuration ``` -### Build Command +### Build Command -- Run the following command in the root directory of the source code to build the full distribution: +- Run the following command in the root directory of the source code to build a full distribution: - ``` - ./build.sh --product-name {product_name} - ``` + ``` - **product\_name** indicates the product supported by the current distribution, for example, hispark_taurus_standard. + ./build.sh --product-name {product_name} + + ``` - The image generated after build is stored in the **out/{device_name}/packages/phone/images/** directory. + **{product_name}** specifies the product platform supported by the current distribution, for example, **hispark_taurus_standard**. -- The build command supports the following options: + The image generated is stored in the **out/{device_name}/packages/phone/images/** directory. - ``` - --product-name # (Mandatory) Name of the product to build, for example, Hi3516D V300 - --build-target # (Optional) One or more build targets - --gn-args # (Optional) One or more gn parameters - --ccache # (Optional) Use of Ccache for build. This option takes effect only when Ccache is installed on the local PC. - ``` +- The **./build.sh** command supports the following options: + ``` + -h, --help # Display help information and exit. + --source-root-dir=SOURCE_ROOT_DIR # Specify the path. + --product-name=PRODUCT_NAME # Specify the product name. + --device-name=DEVICE_NAME # Specify the device name. + --target-cpu=TARGET_CPU # Specify the CPU. + --target-os=TARGET_OS # Specify the operating system. + -T BUILD_TARGET, --build-target=BUILD_TARGET # specifies one or more targets to build. + --gn-args=GN_ARGS # Specify GN parameters. + --ninja-args=NINJA_ARGS # Specify Ninja parameters. + -v, --verbose # Display all commands used. + --keep-ninja-going # Keep Ninja going until 1,000,000 jobs fail. + --sparse-image + --jobs=JOBS + --export-para=EXPORT_PARA + --build-only-gn # Perform GN parsing and does not run Ninja. + --ccache # (Optional) Use ccache for build. You need to install ccache locally. + --fast-rebuild # Whether to use fast rebuild. The default value is False. + --log-level=LOG_LEVEL # Specify the log level during the build. The options are debug, info, and error. The default value is info. + --device-type=DEVICE_TYPE # Specify the device type. The default value is default. + --build-variant=BUILD_VARIANT # Specify the device operation mode. The default value is user. -### How to Develop + ``` -1. Add a module. +### How to Develop - The following steps use a custom module as an example to describe how to build the module, including build a library, an executable file, and a configuration file. +1. Add a component. + + The following use a custom component as an example to describe how to write .gn scripts for a library, an executable file, and a configuration file. + + In this example, **partA** consists of **feature1**, **feature2**, and **feature3**, which represent a dynamic library, an executable file, and an etc configuration file, respectively. + + Add **partA** to a subsystem, for example, **subsystem_examples** (defined in the **test/examples/** directory). + - The example module **partA** consists of **feature1**, **feature2**, and **feature3**. The target is a dynamic library for **feature1**, an executable file for **feature2**, and an etc configuration file for **feature3**. +The directory structure of **partA** is as follows: - Add **partA** to a subsystem, for example, **subsystem\_examples** \(defined in the **test/examples/** directory\). +``` + + test/examples/partA + ├── feature1 + │ ├── BUILD.gn + │ ├── include + │ │ └── helloworld1.h + │ └── src + │ └── helloworld1.cpp + ├── feature2 + │ ├── BUILD.gn + │ ├── include + │ │ └── helloworld2.h + │ └── src + │ └── helloworld2.cpp + └── feature3 + ├── BUILD.gn + └── src + └── config.conf + +``` - The complete directory structure of **partA** is as follows: +(a) Write **test/examples/partA/feature1/BUILD.gn** for the dynamic library. - ``` - test/examples/partA - ├── feature1 - │ ├── BUILD.gn - │ ├── include - │ │ └── helloworld1.h - │ └── src - │ └── helloworld1.cpp - ├── feature2 - │ ├── BUILD.gn - │ ├── include - │ │ └── helloworld2.h - │ └── src - │ └── helloworld2.cpp - └── feature3 - ├── BUILD.gn - └── src - └── config.conf - ``` +``` + + config("helloworld_lib_config") { + include_dirs = [ "include" ] +} + + ohos_shared_library("helloworld_lib") { + sources = [ + "include/helloworld1.h", + "src/helloworld1.cpp", + ] + public_configs = [ ":helloworld_lib_config" ] + part_name = "partA" +} + +``` - Example 1: GN script \(**test/examples/partA/feature1/BUILD.gn**\) for building a dynamic library +(b) Write **test/examples/partA/feature2/BUILD.gn** for the executable file. - ``` - config("helloworld_lib_config") { +``` + + ohos_executable("helloworld_bin") { + sources = [ + "src/helloworld2.cpp" + ] include_dirs = [ "include" ] - } - - ohos_shared_library("helloworld_lib") { - sources = [ - "include/helloworld1.h", - "src/helloworld1.cpp", + deps = [ # Dependent modules in the component + "../feature1:helloworld_lib" + ] + 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. + part_name = "partA" +} + +``` + +(c) Write **test/examples/partA/feature3/BUILD.gn** for the etc module. + +``` + + ohos_prebuilt_etc("feature3_etc") { + source = "src/config.conf" + relative_install_dir = "init" # (Optional) Relative directory for installing the module. The default installation directory is **/system/etc**. + part_name = "partA" +} + +``` + + (d) Add the module configuration **test/examples/bundle.json** to the **bundle.json** file of the component. Each component has a **bundle.json** file in the root directory of the component. The sample code is as follows: + + ``` + { + "name": "@ohos/, # 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. + "subsystem": "", # Subsystem to which the component belongs. + "syscap": [], # System capabilities provided by the component for applications. + "features": [], # List of the component's configurable features. Generally, this parameter corresponds to sub_component in build and can be configured. + "adapted_system_type": [], # Adapted system types, which can be mini, small, and standard. Multiple values are allowed. + "rom": "xxxKB" # ROM baseline. If there is no baseline, enter the current value. + "ram": "xxxKB", # RAM baseline. If there is no baseline, enter the current value. + "deps": { + "components": [], # Other components on which this component depends. + "third_party": [] # Third-party open-source software on which this component depends. + }, + "build": { # Build-related configurations. + "sub_component": [], # Component build entry. Configure the module here. + "inner_kits": [], # APIs between components. + "test": [] # Entry for building the component's test cases. + } + } + } + ``` + +2. Add the component to the product configuration file. + Add the component to **//vendor/{*product_company*}/{*product-name*}/config.json**. + + For example, add "subsystem_examples:partA" to the product **config.json** file. **partA** will be built and packaged into the distribution. + +3. Start the build. + For example, run the following command to build **hispark_taurus_standard**: + + ``` + + ./build.sh --product-name hispark_taurus_standard --ccache + + ``` + +4. Obtain the build result. + You can obtain the generated files from the **out/hispark_taurus/** directory and the image in the **out/hispark_taurus/packages/phone/images/** directory. + +## FAQs + +### How Do I Build a Module and Package It into a Distribution? + +- Set **part_name** for the module. A module can belong to only one part. + +- Add the module to **component.build.sub_component** of the component, or define the dependency between the module and the modules in **component.build.sub_component**. + +- Add the component to the component list of the product. + +### How Do I Set deps and external_deps? + +When adding a module, you need to declare its dependencies in **BUILD.gn**. **deps** specifies dependent modules in the same component, and **external_deps** specifies dependent modules between components. + +The dependency between modules can be classified into: + +**deps**: The dependent module to be added belongs to the same component with the current module. For example, module 2 depends on module 1, and modules 1 and 2 belong to the same component. + +**external_deps**: The dependent module to be added belongs to another component. For example, module 2 depends on module 1, and modules 1 and 2 belong to different components. + +- Example of **deps**: + + ``` + import("//build/ohos.gni") + ohos_shared_library("module1") { + ... + part_name = "part1" # (Mandatory) Name of the component to which the module belongs. + ... + } + ``` + + ``` + import("//build/ohos.gni") + ohos_shared_library("module2") { + ... + deps = [ + "GN target of module 1", + ... + ] # Intra-component dependency + part_name = "part1" # (Mandatory) Name of the part to which the module belongs. + } + ``` + +- Example of **external_deps**: + + ``` + import("//build/ohos.gni") + ohos_shared_library("module1") { + ... + part_name = "part1" # (Mandatory) Name of the component to which the module belongs. + ... + } + ``` + +- **bundle.json** file of the component to which module 1 belongs + + ``` + { + "name": "@ohos/", # 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. + "subsystem": "", # Subsystem to which the component belongs. + "syscap": [], # System capabilities provided by the component for applications. + "features": [], # List of the component's configurable features. Generally, this parameter corresponds to sub_component in build and can be configured. + "adapted_system_type": [], # Adapted system types, which can be mini, small, and standard. Multiple values are allowed. + "rom": "xxxKB" # ROM baseline. If there is no baseline, enter the current value. + "ram": "xxxKB", # RAM baseline. If there is no baseline, enter the current value. + "deps": { + "components": [], # Other components on which this component depends. + "third_party": [] # Third-party open-source software on which this component depends. + }, + "build": { # Build-related configurations. + "sub_component": ["part1"], # Component build entry. All modules of the component are listed here. + "inner_kits": [], # APIs between components. + { + "header": { + "header_base": "Header file directory", # Directory of the header files. + "header_files": [ + "Header file name" + ] # List of header file names. + }, + "name": "GN target of module 1" + }, + ], + "test": [] # Entry for building the component's test cases. + } + } + } + ``` + + ``` + import("//build/ohos.gni") + ohos_shared_library("module2") { + ... + external_deps = [ + "part1:module1", + ... + ] # Inter-component dependency. The dependent module must be declared in **inner_kits** by the dependent component. + part_name = "part2" # (Mandatory) Name of the component to which the module belongs. + } + + ``` + +> ![icon-caution.gif](../public_sys-resources/icon-caution.gif) **CAUTION**
+> 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/, # 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. + "subsystem": "", # Subsystem to which the component belongs. + "syscap": [], # System capabilities provided by the component for applications. + "features": [], # List of the component's configurable features. Generally, this parameter corresponds to sub_component in build and can be configured. + "adapted_system_type": [], # Adapted system types, which can be mini, small, and standard. Multiple values are allowed. + "rom": "xxxKB" # ROM baseline. If there is no baseline, enter the current value. + "ram": "xxxKB", # RAM baseline. If there is no baseline, enter the current value. + "deps": { + "components": [], # Other components on which this component depends. + "third_party": [] # Third-party open-source software on which this component depends. + }, + + "build": { # Build-related configurations + "sub_component": [ + "//foundation/arkui/napi:napi_packages", # Existing module 1 + "//foundation/arkui/napi:napi_packages_ndk" # Existing module 2 + "//foundation/arkui/napi:new" # Module to add + ], # Component build entry. Configure the module here. + "inner_kits": [], # APIs between components + "test": [] # Entry for building the component's test cases. + } + } + } + ``` + + Note that the **bundle.json** file must be in the folder of the corresponding subsystem. + +#### Creating a Component and Adding a Module + +1. Configure the **BUILD.gn** file in the module directory and select the corresponding template. Note that **part_name** in the **BUILD.gn** file is the name of the newly added component. + +2. Create a **bundle.json** file in the folder of the corresponding subsystem. + + The **bundle.json** file consists of two parts: **subsystem** and **parts**. Add the component information to **parts**. When adding a component, you need to specify the **sub_component** of the component. If there are APIs provided for other components, add them in **inner_kits**. If there are test cases, add them in **test**. + +3. Add the new component to the end of existing components in **//vendor/{product_company}/{product-name}/config.json**. + + ``` + "subsystems": [ + { + "subsystem": "Name of the subsystem to which the component belongs", + "components": [ + {"component": "Component 1 name", "features":[]}, # Existing component 1 in the subsystem + { "component": "Component 2 name", "features":[] }, # Existing component 2 in the subsystem + {"component": "New component name", "features":[]} # New component in the subsystem + ] + }, + ... + ] + ``` + +#### Creating a Subsystem and Adding a Module + +1. Configure the **BUILD.gn** file in the module directory and select the corresponding template. + + Note that **part_name** in the **BUILD.gn** file is the name of the newly added component. + +2. Create a **bundle.json** file in the folder of the component of the subsystem. + + This step is the same as the step in "Creating a Component and Adding a Module." + +3. Modify the **subsystem_config.json** file in the **build** directory. + + ``` + { + "Subsystem 1 name": { # Existing subsystem 1 + "path": "Subsystem 1 directory", + "name": "Subsystem 1 name" + }, + "Subsystem 2 name": { # Existing subsystem 2 + "path": "Subsystem 2 directory", + "name": "Subsystem 2 name" + }, + "Subsystem name new": { # Subsystem to add + "path": "New subsystem directory", + "name": "New subsystem name" + }, + ... + } + ``` + + This file defines the subsystems and their paths. To add a subsystem, specify **path** and **name** for the subsystem. + +4. If **product-name** in the **//vendor/{product_company}/{product-name}** directory is **hispark_taurus_standard**, add the new component information to the end of existing components in the **config.json** file. + + ``` + "subsystems": [ + { + "subsystem": "arkui", # Name of the existing subsystem + "components": [ # All components of the subsystem + { + "component": "ace_engine_standard", # Name of the existing component + "features": [] + }, + { + "component": "napi", # Name of the existing component + "features": [] + } + { + "component": "component_new1", # Name of the new component added to the existing subsystem + "features": [] + } + ] + }, + { + "subsystem": "subsystem_new", # Name of the new subsystem to add + "components": [ + { + "component": "component_new2", # Name of the component added to the new subsystem + "features": [] + } + ] + }, + ... + ] + ``` + Verification: + - Check that **module_list** in the **BUILD.gn** file in the component directory under the corresponding subsystem directory contains the target defined in the **BUILD.gn** file of the new module. + - Check the .so file or binary file generated in the image created. + +#### Configuration Files + +There are four OpenHarmony configuration files. + +1. **vendor\Product vendor\Product name\config.json** + + ``` + { + "product_name": "MyProduct", + "version": "3.0", + "type": "standard", + "target_cpu": "arm", + "ohos_version": "OpenHarmony 1.0", + "device_company": "MyProductVendor", + "board": "MySOC", + "enable_ramdisk": true, + "subsystems": [ + { + "subsystem": "ace", + "components": [ + { "component": "ace_engine_lite", "features":[""] } + ] + }, + ... ] - public_configs = [ ":helloworld_lib_config" ] - part_name = "partA" + } + + ``` + This file specifies the name, manufacturer, device, version, type of system to be built, and subsystems of the product. + +2. **subsystem_config.json** in the **build** directory + + ``` + { + "arkui": { + "path": "foundation/arkui", + "name": "arkui" + }, + "ai": { + "path": "foundation/ai", + "name": "ai" + }, + ...... } - ``` + ``` + This file contains subsystem information. You need to configure **name** and **path** for each subsystem. + +3. **bundle.json** of a subsystem + + ``` + { + "name": "@ohos/, # 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. + "subsystem": "", # Subsystem to which the component belongs. + "syscap": [], # System capabilities provided by the component for applications. + "features": [], # List of the component's configurable features. Generally, this parameter corresponds to sub_component in build and can be configured. + "adapted_system_type": [], # Adapted system types, which can be mini, small, and standard. Multiple values are allowed. + "rom": "xxxKB" # ROM baseline. If there is no baseline, enter the current value. + "ram": "xxxKB", # RAM baseline. If there is no baseline, enter the current value. + "deps": { + "components": [], # Other components on which this component depends. + "third_party": [] # Third-party open-source software on which this component depends. + }, + "build": { # Build-related configurations. + "sub_component": ["gn target of the module"], # Component build entry + "inner_kits": [], # APIs between components. + "test": [] # Entry for building the component's test cases. + } + } + } + ``` + The **bundle.json** file defines the components of a subsystem. + + Each component contains the module's target **component.build.sub_component**, **component.build.inner_kits** for interaction between components, and test cases **component.build.test_list**. The **component.build.sub_component** is mandatory. + +4. **BUILD.gn** of each module + + You can create **BUILD.gn** from a template or using the GN syntax. + +### How Do I Build a HAP? + +#### **HAP Description** + +An OpenHarmony Ability Package (HAP) includes resources, raw assets, JS assets, native libraries, and **config.json**. + +#### **Templates** - Example 2: GN script \(**test/examples/partA/feature2/BUILD.gn**\) for building an executable file +The compilation and build subsystem provides four templates for building HAPs. The templates are integrated in **ohos.gni**. Before using the templates, import **build/ohos.gni**. + +1. **ohos_resources** + + This template declares resource targets. After a target is built by restool, an index file is generated. The resource source file and index file are both packaged into the HAP. + + A **ResourceTable.h** file is also generated after resource building. This header file can be referenced if the resource target is relied on. + + The resource target name must end with **resources**, **resource**, or **res**. Otherwise, a build error may occur. + + The following variables are supported: + + - **sources**: a list of resource paths. + - **hap_profile**: **config.json** of the HAP required for resource building. + - **deps**: (optional) dependency of the current target. + +2. **ohos_assets** + + This template declares asset targets. + + Beware that the spelling is "assets" as opposed to "assert". + + The asset target name must end with **assets** or **asset**. + + The following variables are supported: + + - **sources**: a list for raw asset paths. + - **deps**: (optional) dependency of the current target. + +3. **ohos_js_assets** + + This template declares a JS resource target. The JS resource is the executable part of an L2 HAP. + + The JS asset target name must end with **assets** or **asset**. + + The following variables are supported: + + - **source_dir**: JS resource path, which is of the string type. + - **deps**: (optional) dependency of the current target. + +4. **ohos_hap** + + This template declares a HAP target. A HAP that will be generated and packaged into the system image. + + The following variables are supported: + + - **hap_profile**: **config.json** of the HAP. + - **deps**: dependency of the current target. + - **shared_libraries**: native libraries on which the current target depends. + - **hap_name**: (optional) name of the HAP. The default value is the target name. + - **final_hap_path**: (optional) destination path of the HAP. It takes precedence over **hap_name**. + - **subsystem_name**: name of the subsystem to which the HAP belongs. The value must be the same as that in **bundle.json**. Otherwise, the HAP will fail to be installed in the system image. + - **part_name**: name of the component to which the HAP belongs. The value must be the same as that in **bundle.json**. + - **js2abc**: whether to convert the HAP into ARK bytecode. + - **certificate_profile**: certificate profile of the HAP, which is used for signature. For details about signatures, see [Configuring Signature Information](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-debugging-and-running-0000001263040487#section17660437768). + - **certificate_file**: Certificate file. You must apply for the certificate and its profile from the official OpenHarmony website. + - **keystore_path**: keystore file, which is used for signature. + - **keystore_password**: keystore password, which is used for signature. + - **key_alias**: key alias. + - **module_install_name**: name of the HAP used during installation. + - **module_install_dir**: installation path. The default path is **system/app**. + +**HAP Example** ``` - ohos_executable("helloworld_bin") { - sources = [ - "src/helloworld2.cpp" + import("//build/ohos.gni") # Import **ohos.gni**. + ohos_hap("clock") { + hap_profile = "./src/main/config.json" # config.json + deps = [ + ":clock_js_assets", # JS assets + ":clock_resources", # Resources ] - include_dirs = [ "include" ] - deps = [ # Dependent submodule - "../feature1:helloworld_lib" + shared_libraries = [ + "//third_party/libpng:libpng", # Native library ] - external_deps = [ "partB:module1" ] # (Optional) If there is a cross-module dependency, the format is "module name: submodule name" - install_enable = true # By default, the executable file is not installed. You need to set this parameter to true for installation. - part_name = "partA" + certificate_profile = "../signature/systemui.p7b" # Certificate profile + hap_name = "SystemUI-NavigationBar" # HAP name + part_name = "prebuilt_hap" + subsystem_name = "applications" + } + ohos_js_assets("clock_js_assets") { + source_dir = "./src/main/js/default" + } + ohos_resources("clock_resources") { + sources = [ "./src/main/resources" ] + hap_profile = "./src/main/config.json" } ``` - Example 3: GN script \(**test/examples/partA/feature3/BUILD.gn**\) for building the etc configuration file \(submodule\). +### What Does an Open-Source Software Notice Collect? - ``` - ohos_prebuilt_etc("feature3_etc") { - source = "src/config.conf" - relative_install_dir = "init" # (Optional) Directory for installing the submodule, which is relative to the default installation directory (/system/etc) - part_name = "partA" - } - ``` +#### Information to Collect - Example 4: Adding the module configuration file **test/examples/ohos.build** to the **ohos.build** file of this subsystem. Each subsystem has an **ohos.build** file in its root directory. Example: +The notice collects only the licenses of the modules packaged in the image. For example, the licenses of the tools (such as Clang, Python, and Ninja) used during the build process are not collected. - ``` - "partA": { - "module_list": [ - "//test/examples/partA/feature1:helloworld_lib", - "//test/examples/partA/feature2:helloworld_bin", - "//test/examples/partA/feature3:feature3_etc", - ], - "inner_kits": [ - - ], - "system_kits": [ - - ], - "test_list": [ - - ] - } - ``` +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 declaration of a module contains the following parts: +The final **Notice.txt** file must include all licenses used by the files in the image and the mapping between modules and licenses. - - **module\_list**: submodule list of the module - - **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 +The **Notice.txt** file is located in the **/system/etc/** directory. -2. Add the module to the product configuration file. +#### Rules for Collecting Information - Add the module to the product configuration file **//vendor/{product_company}/{product-name}/config.json**. +Licenses are collected by priority. - Add "subsystem\_examples:partA" to the product configuration file. **partA** will be built and packaged into the distribution. +1. Licenses that are directly declared in a module's **BUILD.gn** are given the top priority. The following is an example: -3. Build the module. + ``` + ohos_shared_library("example") { + ... + license_file = "path-to-license-file" + ... + } + ``` - For example, run the following command to build hispark_taurus_standard: +2. If there is no explicitly declared license, the build script searches for the **Readme.OpenSource** file in the directory of **BUILD.gn**, parses the file, and collects the obtained licenses. + If the **Readme.OpenSource** file does not contain license information, an error will be reported. - ``` - ./build.sh --product-name hispark_taurus_standard --ccache - ``` +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. -4. Obtain the build result. +Check items: - Files generated during the build process are stored in the **out/hispark_taurus/** directory, and the generated image is stored in the **out/hispark_taurus/packages/phone/images/** directory. +1. For third-party open-source software, such as OpenSSL and ICU, **Readme.OpenSource** must be configured in the source code directory. Check whether **Readme.OpenSource** is in the same directory as **BUILD.gn** and whether the license configured in **Readme.OpenSource** is valid. +2. If the source code is not licensed under the Apache License 2.0, the corresponding license file must be provided in the source code directory or declared by **license_file** for the module. +3. If the source code file added to **BUILD.gn** is not from the current directory, check whether the license in the repository where the source code file is located is the same as that in the repository of **BUILD.gn**. License inconsistency entails follow-up operations. diff --git a/en/device-dev/subsystems/subsys-dfx-hisysevent-logging.md b/en/device-dev/subsystems/subsys-dfx-hisysevent-logging.md index 06033bd48bdd941aa104a3997a323b9359576c62..aad574b94e51306a4130173f8ea8a4a7304b0b39 100644 --- a/en/device-dev/subsystems/subsys-dfx-hisysevent-logging.md +++ b/en/device-dev/subsystems/subsys-dfx-hisysevent-logging.md @@ -1,99 +1,233 @@ -# HiSysEvent Logging - -## Overview - -### Introduction - -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. - -### Constraints - -Before logging system events, you need to configure HiSysEvent logging. For details, see [HiSysEvent Logging Configuration](subsys-dfx-hisysevent-logging-config.md). - -## Development Guidelines - -### Available APIs - -The following table lists the C++ APIs provided by the HiSysEvent class. - -For details about the HiSysEvent class, see the API reference. - -**Table 1** C++ APIs provided by HiSysEvent - -| API| Description| -| -------- | --------- | -| template<typename... Types> static int Write(const std::string &domain, const std::string &eventName, EventType type, Types... keyValues) | Logs system events.

Input arguments:
  • **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.
  • **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.
  • **type**: Indicates the event type. For details, see EventType.
  • **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.
Return value:
  • **0**: The logging is successful.
  • Negative value: The logging has failed.
| - -**Table 2** Description of HiSysEvent::Domain APIs - -| API| Description| -| -------- | --------- | -| static const std::string AAFWK | Atomic ability subsystem| -| static const std::string APPEXECFWK | User program framework subsystem| -| static const std::string ACCOUNT | Account subsystem| -| static const std::string ARKUI | ARKUI subsystem| -| static const std::string AI | AI subsystem| -| static const std::string BARRIER_FREE | Accessibility subsystem| -| static const std::string BIOMETRICS | Biometric recognition subsystem| -| static const std::string CCRUNTIME |C/C++ operating environment subsystem| -| static const std::string COMMUNICATION | Public communication subsystem| -| static const std::string DEVELOPTOOLS | Development toolchain subsystem| -| static const std::string DISTRIBUTED_DATAMGR | Distributed data management subsystem| -| static const std::string DISTRIBUTED_SCHEDULE | Distributed Scheduler subsystem| -| static const std::string GLOBAL | Globalization subsystem| -| static const std::string GRAPHIC | Graphics subsystem| -| static const std::string HIVIEWDFX | DFX subsystem| -| static const std::string IAWARE | Scheduling and resource management subsystem| -| static const std::string INTELLI_ACCESSORIES | Smart accessory subsystem| -| static const std::string INTELLI_TV | Smart TV subsystem| -| static const std::string IVI_HARDWARE | IVI-dedicated hardware subsystem| -| static const std::string LOCATION | LBS subsystem| -| static const std::string MSDP | MSDP subsystem| -| static const std::string MULTI_MEDIA | Media subsystem| -| static const std::string MULTI_MODAL_INPUT | Multimode input subsystem| -| static const std::string NOTIFICATION | Common event and notification subsystem| -| static const std::string POWERMGR | Power management subsystem| -| static const std::string ROUTER | Router subsystem| -| static const std::string SECURITY | Security subsystem| -| static const std::string SENSORS | Pan-sensor subsystem| -| static const std::string SOURCE_CODE_TRANSFORMER | Application porting subsystem| -| static const std::string STARTUP | Startup subsystem| -| static const std::string TELEPHONY | Telephony subsystem| -| static const std::string UPDATE | Update subsystem| -| static const std::string USB | USB subsystem| -| static const std::string WEARABLE_HARDWARE | Wearable-dedicated hardware subsystem| -| static const std::string WEARABLE_HARDWARE | Wearable-dedicated service subsystem| -| static const std::string OTHERS | Others| - -**Table 3** Description of HiSysEvent::EventType - -| Name| Description| -| -------- | --------- | -| FAULT | Fault event| +# HiSysEvent Logging + +## Overview + +### Introduction + +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. + +### Working Principles + +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 + +### When to Use + +Use HiSysEvent logging to flush logged event data to disks. + +### Available APIs + +#### C++ Event Logging APIs + +HiSysEvent logging is implemented using the API provided by the **HiSysEvent** class. For details, see the API Reference. + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> 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 1** C++ event logging API (deprecated) + +| API | Description | +| ------------------------------------------------------------ | ---------------------- | +| template<typename... Types> 
static int Write(const std::string &domain, const std::string &eventName, EventType type, Types... keyValues) | Flushes logged event data to disks.| + +**Table 2** C++ event logging API (in use) +| API | Description | +| ------------------------------------------------------------ | ---------------------- | +| HiSysEventWrite(domain, eventName, type, ...) | Flushes logged event data to disks.| + + **Table 3** Event types + +| Event | Description | +| --------- | ------------ | +| FAULT | Fault event| +| STATISTIC | Statistical event| +| SECURITY | Security event| +| BEHAVIOR | Behavior event| + +#### Kernel Event Logging APIs + +The following table describes the kernel event logging APIs. + +**Table 4** Description of kernel event logging APIs + +| API | Description | +| ------------------------------------------------------------ | ------------------------------------ | +| struct hiview_hisysevent *hisysevent_create(const char *domain, const char *name, enum hisysevent_type type); | Creates a **hisysevent** object. | +| void hisysevent_destroy(struct hiview_hisysevent *event); | Destroys a **hisysevent** object. | +| 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.| +| int hisysevent_write(struct hiview_hisysevent *event); | Flushes **hisysevent** object data to disks. | + +Table 5 Kernel event types + +| Event | Description | +| --------- | ------------ | +| FAULT | Fault event| | STATISTIC | Statistical event| -| SECURITY | Security event| -| BEHAVIOR | System behavior event| +| SECURITY | Security event| +| BEHAVIOR | Behavior event| + +### How to Develop + +#### C++ Event Logging + +1. Call the event logging API wherever needed, with required event parameters passed to the API. + + ```c++ + HiSysEventWrite(HiSysEvent::Domain::AAFWK, "START_APP", HiSysEvent::EventType::BEHAVIOR, "APP_NAME", "com.ohos.demo"); + ``` + +#### Kernel Event Logging + +1. Create a **hisysevent** object based on the specified event domain, event name, and event type. + + ```c + struct hiview_hisysevent *event = hisysevent_create("KERNEL", "BOOT", BEHAVIOR); + ``` + +2. Pass the customized event parameters to the **hisysevent** object. -### Development Example + ```c + // Add a parameter of the integer type. + hisysevent_put_integer(event, "BOOT_TIME", 100); -C++ + // Add a parameter of the string type. + hisysevent_put_string(event, "MSG", "This is a test message"); + ``` -1. Develop the source code. +3. Trigger reporting of the **hisysevent** event. - Include the HiSysEvent header file in the class definition header file or class implementation source file. For example: + ```c + hisysevent_write(event); + ``` +4. Manually destroy the **hisysevent** object. + + ```c + hisysevent_destroy(&event); + ``` + +#### 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. + ```c++ + #define DOMAIN_MASKS "DOMAIN_NAME_1|DOMAIN_NAME_2|...|DOMAIN_NAME_n" + #include "hisysevent.h" + ``` + +- Shielding event logging for event domains of the entire module: Define the **DOMAIN_MASKS** macro in the **BUILD.gn** file of the module. + ```gn + config("module_a"){ + cflags_cc += ["-DDOMAIN_MASKS=\"DOMAIN_NAME_1|DOMAIN_NAME_2|...|DOMAIN_NAME_n\""] + } + ``` + +- Shielding event logging for event domains globally: Define the **DOMAIN_MASKS** macro in **/build/config/compiler/BUILD.gn**. + ```gn + cflags_cc += ["-DDOMAIN_MASKS=\"DOMAIN_NAME_1|DOMAIN_NAME_2|...|DOMAIN_NAME_n\""] + ``` + +2. Perform event logging by using the **HiSysEventWrite** API. + ```c++ + constexpr char DOMAIN[] = "DOMAIN_NAME_1"; + const std::string eventName = "EVENT_NAME1"; + OHOS:HiviewDFX::HiSysEvent::EventType eventType = OHOS:HiviewDFX::HiSysEvent::EventType::FAULT; + 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" ] + ``` + +2. In the application startup function **StartAbility()** of the service module, call the event logging API with the event parameters passed in. + + ```c++ + #include "hisysevent.h" + + int StartAbility() + { + ... // Other service logic + int ret = HiSysEventWrite(HiSysEvent::Domain::AAFWK, "START_APP", HiSysEvent::EventType::BEHAVIOR, "APP_NAME", "com.ohos.demo"); + ... // Other service logic + } + ``` + +#### Kernel Event Logging + +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. + + ```c + #include + + #include + #include + + int device_boot() + { + ... // Other service logic + struct hiview_hisysevent *event = NULL; + int ret = 0; + + event = hisysevent_create("KERNEL", "BOOT", BEHAVIOR); + if (!event) { + pr_err("failed to create event"); + return -EINVAL; + } + 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. - 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: + ``` +- 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\""] + } ``` - HiSysEvent::Write(HiSysEvent::Domain::AAFWK, "start_app", HiSysEvent::EventType::FAULT, "app_name", "com.demo"); + +- 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\""] ``` -2. Configure compilation information. Specifically, add the subsystem SDK dependency to **BUILD.gn**. +# Reference - ``` - external_deps = [ "hisysevent_native:libhisysevent" ] - ``` +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). diff --git a/en/device-dev/subsystems/subsys-dfx-hisysevent-tool.md b/en/device-dev/subsystems/subsys-dfx-hisysevent-tool.md index 7e6b3a45e72d58f6f0b1847b38dc817ef82a8ae3..15fd6220152829b8e8ca6f62551caa25d8a9e088 100644 --- a/en/device-dev/subsystems/subsys-dfx-hisysevent-tool.md +++ b/en/device-dev/subsystems/subsys-dfx-hisysevent-tool.md @@ -1,12 +1,13 @@ -# HiSysEvent Tool Usage +# HiSysEvent Tool Usage -## Overview + +## Overview 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 +## Subscribing to Real-Time System Events -- Command for subscribing to real-time system events: +- Command for subscribing to real-time system events: ``` hisysevent -r @@ -15,10 +16,10 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** Description of command options: | 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: ``` hisysevent -r -d @@ -27,10 +28,10 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** Description of command options: | 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: ``` hisysevent -r -t [-c [WHOLE_WORD|PREFIX|REGULAR]] @@ -39,24 +40,22 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** Description of command options: | Option| Description| - | -------- | --------- | - | -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**.| + | -------- | -------- | + | -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**.| Example: ``` - # hisysevent -r -t "TAG" -c PREFIX - {"domain_":"ARKUI","name_":"UI_BLOCK_6S","type_":1,"time_":1501940269812,"tz_":"+0000","tag_":"TAG1","pid_":1428,"tid_":1452,"uid_":10001,"level_":"CRITICAL","info_":""} - # hisysevent -r -t "TA\w{0,1}" -c REGULAR - {"domain_":"WINDOWMANAGER","name_":"NO_FOCUS_WINDOW","type_":1,"time_":1501940269802,"tz_":"+0000","tag_":"TAG","pid_":1428,"tid_":1433,"uid_":10001,"level_":"CRITICAL","info_":""} - {"domain_":"ARKUI","name_":"UI_BLOCK_6S","type_":1,"time_":1501940269812,"tz_":"+0000","tag_":"TAG1","pid_":1428,"tid_":1452,"uid_":10001,"level_":"CRITICAL","info_":""} - # hisysevent -r -t "TA\w+" -c REGULAR - {"domain_":"WINDOWMANAGER","name_":"NO_FOCUS_WINDOW","type_":1,"time_":1501940269802,"tz_":"+0000","tag_":"TAG","pid_":1428,"tid_":1433,"uid_":10001,"level_":"CRITICAL","info_":""} - {"domain_":"ARKUI","name_":"UI_BLOCK_6S","type_":1,"time_":1501940269812,"tz_":"+0000","tag_":"TAG1","pid_":1428,"tid_":1452,"uid_":10001,"level_":"CRITICAL","info_":""} + # hisysevent -r -t "STA" -c PREFIX + {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963670809,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805200750","HAPPEN_TIME":1501963670809,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"4973863135535405472","info_":""} + # hisysevent -r -t "STAw{0,6}" -c REGULAR + {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963793206,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805200953","HAPPEN_TIME":1501963793206,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"16367997008075110557","info_":""} + # hisysevent -r -t "STA\w+" -c REGULAR + {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963863393,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201103","HAPPEN_TIME":1501963863393,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"5522352691813553392","info_":""} ``` -- Command for subscribing to real-time system events by event domain and event name: +- Command for subscribing to real-time system events by event domain and event name: ``` hisysevent -r -o -n [-c [WHOLE_WORD|PREFIX|REGULAR]] @@ -65,31 +64,29 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** Description of command options: | Option| Description| - | -------- | --------- | - | -o | Event domain used to filter subscribed real-time system events.| - | -n | Event name used to filter subscribed real-time system events.| - | -c | Matching rule for event domains and event names. The options can be **WHOLE_WORD**, **PREFIX**, or **REGULAR**.| + | -------- | -------- | + | -o | Event domain used to filter subscribed real-time system events.| + | -n | Event name used to filter subscribed real-time system events.| + | -c | Matching rule for event domains and event names. The options can be **WHOLE_WORD**, PREFIX, or **REGULAR**.| Example: ``` - # hisysevent -r -o "DOMAINA" -n "EVENTNAMEA" - {"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":1501940269802,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""} - # hisysevent -r -o "DOMA\w{0,10}" -n "EVENT\w+" -c REULAR - {"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":1501940269802,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""} - {"domain_":"DOMAINABC","name_":"EVENTNAMEABC","type_":1,"time_":1501940269938,"tz_":"+0000","pid_":1428,"tid_":1336,"uid_":10002,"level_":"CRITICAL","info_":""} - # hisysevent -r -o "DOMA\w{0,10}" -c REGULAR - {"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":1501940269802,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""} - {"domain_":"DOMAINABC","name_":"EVENTNAMEABC","type_":1,"time_":1501940269938,"tz_":"+0000","pid_":1428,"tid_":1336,"uid_":10002,"level_":"CRITICAL","info_":""} - {"domain_":"DOMAINABC","name_":"EVENTNAMEB","type_":1,"time_":1501940279938,"tz_":"+0000","pid_":1428,"tid_":1344,"uid_":10002,"level_":"CRITICAL","info_":""} + # hisysevent -r -o "RELIABILITY" -n "APP_FREEZE" + {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963989773,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201309","HAPPEN_TIME":1501963989773,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"16367997008075110557","info_":""} + # hisysevent -r -o "RELIABI\w{0,8}" -n "APP_FREEZE" -c REGULAR + {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501964144383,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201544","HAPPEN_TIME":1501964144383,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"13456525196455104060","info_":""} + # hisysevent -r -o "RELIABI\w+" -c REGULAR + {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501964193466,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201633","HAPPEN_TIME":1501964193466,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"12675246910904037271","info_":""} ``` - >![](../public_sys-resources/icon-note.gif) **NOTE:** - >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. + > **NOTE** + > 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 +## Querying Historical System Events -- Command for querying historical system events: +- Command for querying historical system events: ``` hisysevent -l @@ -98,10 +95,10 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** Description of command options: | 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: ``` hisysevent -l -s -e @@ -110,21 +107,20 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** Description of command options: | Option| Description| - | -------- | --------- | - | -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.| + | -------- | -------- | + | -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.| Example: ``` - # hisysevent -l -s 20207388633 -e 20207389000 - {"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":20207388633,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""} - {"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":20207388634,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""} - {"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":20207388900,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""} - {"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":20207389000,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""} + # hisysevent -l -s 1501964222980 -e 1501964222996 + {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501964222980,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201702","HAPPEN_TIME":1501964222980,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"10435592800188571430","info_":""} + {"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: ``` hisysevent -l -m @@ -133,18 +129,36 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** Description of command options: | 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.| Example: ``` - # hisysevent -l -s 20207388633 -e 20207389000 -m 3 - {"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":20207388634,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""} - {"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":20207388900,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""} - {"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":20207389000,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""} - # hisysevent -l -m 2 - {"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":20207388633,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""} - {"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":20207388634,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""} + # hisysevent -l -s 1501964222980 -e 1501964222996 -m 1 + {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501964222980,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201702","HAPPEN_TIME":1501964222980,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"10435592800188571430","info_":""} + ``` + +## System Event Validity Check + +- Enabling system event validity check + + ``` + hisysevent -v ``` + + Description of command options: + + | Option| Description| + | -------- | -------- | + | -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.| + Example: + + ``` + # hisysevent -v -l -s 1501964222980 -e 1501964222996 + # 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. + {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501964222980,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201702","HAPPEN_TIME":1501964222980,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"10435592800188571430","info_":""} + # hisysevent -v -r -o "RELIABILITY" -n "APP_FREEZE" + {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501964644584,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805202404","HAPPEN_TIME":1501964644584,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"11097868872446282676","info_":""} + ``` diff --git a/en/device-dev/subsystems/subsys-dfx-hisysevent.md b/en/device-dev/subsystems/subsys-dfx-hisysevent.md index aba11496ba72484a72f37b2c3f424156e52085c5..86ceb227152ca26ec2c50a9be11d7c15b9be6adf 100644 --- a/en/device-dev/subsystems/subsys-dfx-hisysevent.md +++ b/en/device-dev/subsystems/subsys-dfx-hisysevent.md @@ -1,5 +1,7 @@ # HiSysEvent Development +- **[HiSysEvent Overview](subsys-dfx-hisysevent-overview.md)** + - **[HiSysEvent Logging Configuration](subsys-dfx-hisysevent-logging-config.md)** - **[HiSysEvent Logging](subsys-dfx-hisysevent-logging.md)** diff --git a/en/device-dev/subsystems/subsys-dfx-hiview.md b/en/device-dev/subsystems/subsys-dfx-hiview.md new file mode 100644 index 0000000000000000000000000000000000000000..34751c841a6857d8cacfc438a22abf4a7273f7ec --- /dev/null +++ b/en/device-dev/subsystems/subsys-dfx-hiview.md @@ -0,0 +1,197 @@ +# Hiview Development Guide + + +## Introduction + + +### Function Overview + +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 + +![Hiview_module_data_interaction](figure/Hiview_module_data_interaction.png) + +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. + - FreezeDetectorPlugin processes screen freezing events. + - HiCollieCollector processes suspension events. + +### Basic Concepts + +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. + +| Mode | Description | +| ------------------ | ------------------------------------------------------------ | +| 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. + +Table 1 Description of Plugin APIs + +| API | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| 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) | 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) | 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. | + +**Table 2** Description of Event APIs + +| API | Description | +| ---------------------- | ---------------------------- | +| domain_ | Event domain. | +| eventName_ | Event name. | +| happenTime_ | Time when an event occurs. | +| jsonExtraInfo_ | Event data in JSON format. | +| bool IsPipelineEvent() | Whether an event is a pipeline event. | +| bool HasFinish() | Whether an event can continue to traverse backward.| + +### How to Develop + +1. Define a service plugin class, namely, **PluginExample**, which inherits from the **Plugin** class. + + ```c++ + #include "event.h" + #include "plugin.h" + + class PluginExample : public Plugin { + public: + bool OnEvent(std::shared_ptr& event) override; + void OnLoad() override; + void OnUnload() override; + }; + ``` + +2. In the plugin class implementation code, register the plugin and overwrite the corresponding functions based on the service requirements. + + ```c++ + #include "plugin_factory.h" + + // Register the plugin in static registration mode. + REGISTER(PluginExample); + + void PluginExample::OnLoad() + { + ... // Initialize plugin resources while the plugin is loaded. + printf("PluginExample OnLoad \n"); + } + + void PluginExample::OnUnload() + { + ... // Release plugin resources while the plugin is unloaded. + printf("PluginExample OnUnload \n"); + } + + bool PluginExample::OnEvent(std::shared_ptr& event) + { + ... // Perform specific service processing on the event using the event processing function. + printf("PluginExample OnEvent \n"); + + // If the plugin focuses only on events of a certain domain, log only the events of this domain. + if (event->domain_ == "TEST_DOMAIN") { + printf("The event data received is %s \n", event->jsonExtraInfo_); + return true; + } + + return false; + } + ``` + +3. Configure the plugin in the **plugin_build.json** file and compile the plugin with the Hiview binary file. + + ```json + { + "plugins": { + "PluginExample": { + "path": "plugins/PluginExample", + "name": "PluginExample" + } + }, + "rules": [ + { + "info": { + "loadorder": { + "PluginExample": { + "loadtime": 0 + } + }, + "pipelines": { + "SysEventPipeline": [ + PluginExample + ] + } + } + } + ] + } + ``` + + +## Reference + +For more information about the source code and usage of HiSysEvent, access the Hiview code repository(https://gitee.com/openharmony/hiviewdfx_hiview). diff --git a/en/device-dev/subsystems/subsys-dfx-overview.md b/en/device-dev/subsystems/subsys-dfx-overview.md index 10d57285496c2534e1f78ea3eecac6bc40449fd9..17f65f4ffd4ef6a59f363fcf80419e6fc2cf9cbe 100644 --- a/en/device-dev/subsystems/subsys-dfx-overview.md +++ b/en/device-dev/subsystems/subsys-dfx-overview.md @@ -12,6 +12,7 @@ The DFX subsystem provides the following functions: - HiChecker: implements defect scanning. It is applicable to standard-system devices \(reference memory ≥ 128 MiB\). - HiDumper: exports system information. It is applicable to standard-system devices \(reference memory ≥ 128 MiB\). - FaultLogger: implements crash detection. It is applicable to standard-system devices \(reference memory ≥ 128 MiB\). +- Hiview: implements device maintenance across different platforms. It is applicable to standard-system devices \(reference memory ≥ 128 MiB\). ## Basic Concepts diff --git a/en/device-dev/subsystems/subsys-dfx.md b/en/device-dev/subsystems/subsys-dfx.md index 6ede18fca604394d71e5663f631568a7a911561b..f01cb1eb3be14fb4a3519012fdbaf94599b82a0a 100644 --- a/en/device-dev/subsystems/subsys-dfx.md +++ b/en/device-dev/subsystems/subsys-dfx.md @@ -8,3 +8,4 @@ - **[HiSysEvent Development](subsys-dfx-hisysevent.md)** - **[HiDumper Development](subsys-dfx-hidumper.md)** - **[HiChecker Development](subsys-dfx-hichecker.md)** +- **[Hiview Development](subsys-dfx-hiview.md)** diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/resource-usage.md b/zh-cn/application-dev/key-features/multi-device-app-dev/resource-usage.md index 4915ade834a8f61eb902b015f1cd090a7122e6a4..20129df52a83ba41e72039ef1ee3320624da9b66 100644 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/resource-usage.md +++ b/zh-cn/application-dev/key-features/multi-device-app-dev/resource-usage.md @@ -38,7 +38,7 @@ 在工程中,通过 "$r('app.type.name')" 的形式引用应用资源。app代表是应用内resources目录中定义的资源;type 代表资源类型(或资源的存放位置),可以取 color、float、string、plural和media,name代表资源命名,由开发者定义资源时确定。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** -> - 可以查看[声明式开发范式资源访问](../../ui/ts-application-resource-access.md),了解资源访问的更多细节。 +> - 可以查看[声明式开发范式资源访问](../../ui/ts-resource-access.md),了解资源访问的更多细节。 > > - 类Web开发范式的资源文件路径及资源限定词的使用与声明式范式不同,详情请参考[类Web开发范式资源限定与访问](../../ui/js-framework-resource-restriction.md)及[类Web开发范式文件组织](../../ui/js-framework-file.md)。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md b/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md index af042fbd6f43103babce2fea8e620354d3fb547a..122835b12e2fece6d2d17e30fba9b8d06cc93ef8 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md +++ b/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md @@ -104,7 +104,7 @@ grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFl 授予应用user grant权限,使用Promise方式异步返回结果。 -此接口为系统接口,三方应用不支持调用。 +此接口为系统接口。 **需要权限:** ohos.permission.GRANT_SENSITIVE_PERMISSIONS @@ -142,7 +142,7 @@ grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFl 授予应用user grant权限,使用callback回调异步返回结果。 -此接口为系统接口,三方应用不支持调用。 +此接口为系统接口。 **需要权限:** ohos.permission.GRANT_SENSITIVE_PERMISSIONS @@ -178,7 +178,7 @@ revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionF 撤销应用user grant权限,使用Promise方式异步返回结果。 -此接口为系统接口,三方应用不支持调用。 +此接口为系统接口。 **需要权限:** ohos.permission.REVOKE_SENSITIVE_PERMISSIONS @@ -216,7 +216,7 @@ revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionF 撤销应用user grant权限,使用callback回调异步返回结果。 -此接口为系统接口,三方应用不支持调用。 +此接口为系统接口。 **需要权限:** ohos.permission.REVOKE_SENSITIVE_PERMISSIONS @@ -252,7 +252,7 @@ getPermissionFlags(tokenID: number, permissionName: string): Promise<number&g 获取指定应用的指定权限的flag,使用Promise方式异步返回结果。 -此接口为系统接口,三方应用不支持调用。 +此接口为系统接口。 **需要权限:** ohos.permission.GET_SENSITIVE_PERMISSIONS or ohos.permission.GRANT_SENSITIVE_PERMISSIONS or ohos.permission.REVOKE_SENSITIVE_PERMISSIONS diff --git a/zh-cn/application-dev/reference/apis/js-apis-abilityrunninginfo.md b/zh-cn/application-dev/reference/apis/js-apis-abilityrunninginfo.md index 33b9ff847ac76c6f00d67e2734547894aa287344..5f9195932a5a290805d973bc0780bd30947c057b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-abilityrunninginfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-abilityrunninginfo.md @@ -25,9 +25,9 @@ abilitymanager.getAbilityRunningInfos((err,data) => { | 名称 | 参数类型 | 可读 | 可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | -| ability | ElementName | 是 | 否 | Ability匹配信息 | -| pid | number | 是 | 否 | 进程ID。 | -| uid | number | 是 | 否 | 用户ID。 | -| processName | string | 是 | 否 | 进程名称。 | -| startTime | number | 是 | 否 | Ability启动时间。 | -| abilityState | [abilityManager.AbilityState](js-apis-abilityManager.md#abilityState) | 是 | 否 | Ability状态。 | \ No newline at end of file +| ability | ElementName | 是 | 否 | Ability匹配信息 | +| pid | number | 是 | 否 | 进程ID。 | +| uid | number | 是 | 否 | 用户ID。 | +| processName | string | 是 | 否 | 进程名称。 | +| startTime | number | 是 | 否 | Ability启动时间。 | +| abilityState | [abilityManager.AbilityState](js-apis-application-abilityManager.md#abilitystate) | 是 | 否 | Ability状态。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-appAccount.md b/zh-cn/application-dev/reference/apis/js-apis-appAccount.md index da43ecfd8c1f9e62325002ce505da8d7ad4ce35b..7b8267ffc31efde4a2b1ee2f8a6182c61fce1301 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-appAccount.md +++ b/zh-cn/application-dev/reference/apis/js-apis-appAccount.md @@ -1952,11 +1952,11 @@ setAuthenticatorProperties(owner: string, options: SetPropertiesOptions, callbac **系统能力:** 以下各项对应的系统能力均为SystemCapability.Account.AppAccount。 -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------- | ---- | ----------------- | -| authType | string | 是 | 令牌的鉴权类型。 | -| token | string | 是 | 令牌的取值。 | -| account | AppAccountInfo | 否 | 令牌所属的帐号信息。| +| 参数名 | 类型 | 必填 | 说明 | +| -------------------- | -------------- | ----- | ---------------- | +| authType | string | 是 | 令牌的鉴权类型。 | +| token | string | 是 | 令牌的取值。 | +| account9+ | AppAccountInfo | 否 | 令牌所属的帐号信息。| ## AuthenticatorInfo8+ diff --git a/zh-cn/application-dev/reference/apis/js-apis-audio.md b/zh-cn/application-dev/reference/apis/js-apis-audio.md index 2019664c6337a0ec16e9c1b1e159e99c3ab84418..b79b92ed7f706806dcffd1c70e0a88cf8ec5502c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-audio.md +++ b/zh-cn/application-dev/reference/apis/js-apis-audio.md @@ -74,31 +74,30 @@ createAudioRenderer(options: AudioRendererOptions, callback: AsyncCallback\ { - if (err) { - console.error(`AudioRenderer Created : Error: ${err.message}`); - } - else { - console.info('AudioRenderer Created : Success : SUCCESS'); - let audioRenderer = data; - } + if (err) { + console.error(`AudioRenderer Created: Error: ${err.message}`); + } else { + console.info('AudioRenderer Created: Success: SUCCESS'); + let audioRenderer = data; + } }); ``` @@ -128,29 +127,29 @@ createAudioRenderer(options: AudioRendererOptions): Promise import audio from '@ohos.multimedia.audio'; var audioStreamInfo = { - samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, - channels: audio.AudioChannel.CHANNEL_1, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, - encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, + channels: audio.AudioChannel.CHANNEL_1, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW } var audioRendererInfo = { - content: audio.ContentType.CONTENT_TYPE_SPEECH, - usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, - rendererFlags: 1 + content: audio.ContentType.CONTENT_TYPE_SPEECH, + usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, + rendererFlags: 0 } var audioRendererOptions = { - streamInfo: audioStreamInfo, - rendererInfo: audioRendererInfo + streamInfo: audioStreamInfo, + rendererInfo: audioRendererInfo } var audioRenderer; audio.createAudioRenderer(audioRendererOptions).then((data) => { - audioRenderer = data; - console.info('AudioFrameworkRenderLog: AudioRenderer Created : Success : Stream Type: SUCCESS'); + audioRenderer = data; + console.info('AudioFrameworkRenderLog: AudioRenderer Created : Success : Stream Type: SUCCESS'); }).catch((err) => { - console.info('AudioFrameworkRenderLog: AudioRenderer Created : ERROR : '+err.message); + console.info('AudioFrameworkRenderLog: AudioRenderer Created : ERROR : ' + err.message); }); ``` @@ -174,30 +173,29 @@ createAudioCapturer(options: AudioCapturerOptions, callback: AsyncCallback