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

!19282 翻译已完成18415+18771+18868+18878+18885+18947+18955+18988+19030+19076

Merge pull request !19282 from shawn_he/18868-d
......@@ -78,6 +78,8 @@ httpRequest.request(
// data.header carries the HTTP response header. Parse the content based on service requirements.
console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
// Call the destroy() method to release resources after HttpRequest is complete.
httpRequest.destroy();
} else {
console.info('error:' + JSON.stringify(err));
// Unsubscribe from HTTP Response Header events.
......@@ -158,4 +160,11 @@ httpRequest.request2(
httpRequest.destroy();
}
);
```
\ No newline at end of file
```
## Samples
The following sample is provided to help you better understand how to develop the HTTP data request feature:
- [`Http`: Data Request (ArkTS) (API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Connectivity/Http)
- [HTTP Communication (ArkTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/SmartChatEtsOH)
......@@ -21,7 +21,7 @@ Due to the asynchronous I/O feature of JS, the hiTraceMeter module provides only
## Available APIs
The performance tracing APIs are provided by the **hiTraceMeter** module. For details, see [API Reference]( ../reference/apis/js-apis-hitracemeter.md).
The performance tracing APIs are provided by the **hiTraceMeter** module. For details, see [API Reference](../reference/apis/js-apis-hitracemeter.md).
**APIs for performance tracing**
......
......@@ -4,17 +4,13 @@
Applicable to: OpenHarmony 3.2 Beta (API version 9)
**Symptom**
How do I flush HiLog information to disks?
**Solution**
Run the **hilog -w start -f ckTest -l 1M -n 5 -m zlib -j 11** command.
The log file is saved in the **/data/log/hilog/** directory.
Parameter description:
**Parameters:**
```
-**-w**: Starts a log flushing task. **start** means to start the task, and **stop** means to stop the task.
......@@ -25,3 +21,129 @@ Parameter description:
-**-j**: Specifies the task ID. The value ranges from **10** to **0xffffffffff**.
For more details about parameters, run the **hilog --help** command.
```
## How do I print only HiLog information of the current application?
Applicable to: OpenHarmony 3.2 Beta (API version 9)
**Solution**
Use the hilog command line tool to filter the logs of the current application.
**hilog -T xxx**: filtering logs by tag.
**hilog –D xxx**: filtering logs by domain.
**hilog -e**: matching log content based on the tag, domain, and pid by using regular expressions. Multi-layered filtering, combination filtering, and reverse filtering are supported.
## How do I locate the fault when the application crashes?
Applicable to: OpenHarmony 3.2 Beta (API version 9)
**Solution**
Method 1: Locate the crash-related code based on the service log.
Method 2: View the error information in the crash file. The crash file is located at **/data/log/faultlog/faultlogger/**.
## Is HiLog or console recommended for log printing? How do I set the domain if HiLog is used?
Applicable to: OpenHarmony 3.2 Beta (API version 9)
The console encapsulates the HiLog system with the default parameter configuration. It is mainly used in the application development and debugging phase.
HiLog is recommended because it supports log classification and processing in a unified manner. For details, see [@ohos.hilog (HiLog)](../reference/apis/js-apis-hilog.md#hilogisloggable).
The value of the **domain** parameter in the HiLog API ranges from **0x0** to **0xFFFF**. You are advised to customize the value as required.
## What is the maximum length of a log record when HiLog is used? Is it configurable?
Applicable to: OpenHarmony 3.2 Beta (API version 9)
The maximum length of a log record is 1,024 characters, and it is not changeable.
## What is the purpose of using private in printing of formatted logs?
Applicable to: OpenHarmony 3.2 Beta (API version 9)
**Symptom**
**private** is displayed in HiLog information when format parameters are of the %d or %s type in C++.
**Solution**
When format parameters such as **%d** and **%s** are directly used, the standard system uses **private** to replace the actual data for printing by default to prevent data leakage. To print the actual data, replace **%d** with **%{public}d** or replace **%s** with **%{public}s**.
## What should I do if the hilog.debug log cannot be printed?
Applicable to: OpenHarmony 3.2 Beta (API version 9)
**Solution**
Run **hdc std shell hilog -b D** to turn on the debugging switch.
## Can I separate multiple strings by spaces in the tag parameter of the HiLog API?
Applicable to: OpenHarmony 3.2 Beta (API version 9)
Yes.
## How does HiLog print the log information marked with the \{private\} tag?
Applicable to: OpenHarmony 3.2 Beta (API version 9)
**Solution**
To print the log information marked with the \{private\} tag, run the command to disable the privacy mode: hdc shell hilog -p off
## What are the cash log collection and performance troubleshooting functions provided by the HiLog system?
Applicable to: OpenHarmony 3.2 Beta (API version 9)
**Symptom**
What are the cash log collection and performance troubleshooting functions provided by the HiLog system?
**Solution**
FaultLogger: collects crash logs. For details, see [FaultLogger](../reference/apis/js-apis-faultLogger.md).
HiChecker: detects potential faults. For details, see [HiChecker](../reference/apis/js-apis-hichecker.md).
hiTraceMeter: implements performance tracing. For details, see [hiTraceMeter](../reference/apis/js-apis-hitracemeter.md).
## How do I control log output?
Applicable to: OpenHarmony 3.2 Beta (API version 9)
**Symptom**
The output log varies according to environment requirements.
**Solution**
You can run the following command to adjust the log level to print the desired logs:
hdc shell hilog -L <D/I/W/E/F\>
## Is there a limit on the tag length of HiLog?
Applicable to: OpenHarmony 3.2 Beta (API version 9)
The length of the entire tag is 32.
## How do I view the appfreeze information in the logs?
Applicable to: OpenHarmony 3.2 Beta (API version 9)
Try the following procedure:
1. Check the reason for the event. Fault location methods and examples are provided specifically to different reasons.
2. Check the MSG information.
3. Check the application stack information in OpenStacktraceCatcher as well as the HiLog information for the operation that leads to the event.
4. Check the PeerBinderCatcher process to see if the current process is suspended by the peer binder. If there is a synchronous wait related to the current process, the corresponding PeerBinder Stacktrace information will be logged. It contains the stack information of the peer process that leads to suspension of the current process.
5. Check the CPU usage of system processes and the memory usage of the current process.
......@@ -2,13 +2,13 @@
## How do I read an XML file in rawfile and convert the data in it to the string type?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
Applicable to: OpenHarmony 3.2 Beta5 (API version 9)
**Solution**
Call **getRawFileContent** of the **ResourceManager** module to obtain the data in the XML file, and then use **String.fromCharCode** to convert the data to the string type.
**Sample Code**
**Example**
```
resourceManager.getRawFileContent('test.xml', (error, value) => {
......@@ -21,7 +21,7 @@ resourceManager.getRawFileContent('test.xml', (error, value) => {
});
```
**Reference**
**Reference Link**
[Resource Manager](../reference/apis/js-apis-resource-manager.md)
......@@ -33,7 +33,7 @@ Applicable to: OpenHarmony 3.1 Beta 5 (API version 9)
The stage model allows an application to obtain a **ResourceManager** object based on **context** and call its resource management APIs without first importing the required bundle. This mode does not apply to the FA model.
**Sample Code**
**Example**
```
const context = getContext(this) as any
......@@ -63,13 +63,13 @@ To obtain the path of the **resource** directory, try either of the following wa
2. Use **ResourceManager** for access. This method applies to dynamic access, during which the **resource** directory dynamically changes when the application is running.
**Reference**
**Reference Link**
[Resource Categories and Access](../quick-start/resource-categories-and-access.md) and [Resource Manager](../reference/apis/js-apis-resource-manager.md)
## Why does getPluralString return an incorrect value?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
Applicable to: OpenHarmony 3.2 Beta5 (API version 9)
**Symptom**
......@@ -81,19 +81,19 @@ The **getPluralString** API is effective only when the system language is Englis
## How do I obtain the customized string fields in the resources directory?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
Applicable to: OpenHarmony 3.2 Beta5 (API version 9)
**Solution**
Use **getStringValue** of the **ResourceManager** module.
**Reference**
**Reference Link**
[Resource Manager](../reference/apis/js-apis-resource-manager.md#getstringvalue9)
## How do I reference resources such as images and text in AppScope?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
Applicable to: OpenHarmony 3.2 Beta5 (API version 9)
**Solution**
......@@ -101,18 +101,50 @@ Reference resources in the **\$r\('app.type.name'\)** format. Wherein, **type**
## How do I convert resources to strings?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
Applicable to: OpenHarmony 3.2 Beta5 (API version 9)
**Solution**
For a qualifier directory, use **this.context.resourceManager.getStringSync\(\$r\('app.string.test'\).id\)** to covert resources to strings synchronously. Note that the **\$r\('app.string.test', 2\)** mode is not supported.
**Reference**
**Reference Link**
[Resource Manager](../reference/apis/js-apis-resource-manager.md#getstringsync9)
## Can $ be used to reference constants in the form\_config.json file?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
Applicable to: OpenHarmony 3.2 Beta5 (API version 9)
**\$** cannot be used to reference constants in the **form\_config.json** file.
## How does ArkTS parse XML files?
Applicable to: OpenHarmony 3.2 Beta5 (API version 9)
**Solution**
1. Create the following XML file in the **rawfile** directory:
```
<?xml version="1.0" encoding="utf-8"?>
<user>
<name>Jacky</name>
<age>18</age>
</user>
```
2. Use **resourceManager.getRawFileContent** to obtain the byte arrays of the XML file.
```
import resourceManager from '@ohos.resourceManager';
resourceManager.getRawFileContent("test.xml", (error, value) => {
if (error != null) {
console.log("error is " + error);
return
}
let arrayBuffer = value.buffer; // unit8Array
var xmpParser = new xml.XmlPullParser(arrayBuffer);
var tagName = ""
//do something
}
```
......@@ -3,6 +3,7 @@
The **hiSysEvent** module provides the system event logging functions, such as configuring trace points, subscribing to system events, and querying system events written to the event file.
> **NOTE**
>
> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - The APIs provided by this module are system APIs.
......@@ -312,6 +313,8 @@ Defines arguments for an event query.
| beginTime | number | Yes| Start time (13-digit timestamp) for the event query.|
| endTime | number | Yes| End time (13-digit timestamp) for the event query.|
| maxEvents | number | Yes| Maximum number of events that can be queried.|
| fromSeq<sup>10+</sup> | number | No | Start SN of the events to be queried. The default value is **-1**.|
| toSeq<sup>10+</sup> | number | No | End SN of the system events to be queried. The default value is **-1**.|
## QueryRule
......@@ -323,6 +326,7 @@ Defines event query rules.
| -------- | -------- | -------- | -------- |
| domain | string | Yes| Event domain.|
| names | string[] | Yes| Array of event names. A **QueryRule** object contains multiple system event names.|
| condition<sup>10+</sup> | string | No| Additional event conditions. The value of this parameter is in the format of {"version":"V1","condition":{"and":[{"param":"*Parameter*","op":"*Operator*","value":"*Comparison value*"}]}}.|
## Querier
......@@ -403,3 +407,197 @@ try {
console.error(`error code: ${error.code}, error msg: ${error.message}`);
}
```
## hiSysEvent.exportSysEvents<sup>10+</sup>
exportSysEvents(queryArg: QueryArg, rules: QueryRule[]): number
Exports system events in batches and writes them as a file to the fixed directory of the application sandbox (that is, **/data/storage/el2/base/cache/hiview/event/**).
**Required permission**: ohos.permission.READ_DFX_SYSEVENT
**System capability**: SystemCapability.HiviewDFX.HiSysEvent
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ------------------------------------------ |
| queryArg | [QueryArg](#queryarg) | Yes | Event query parameters for the export. |
| rules | [QueryRule](#queryrule)[] | Yes | Array of event query rules for the export.|
**Return value**
| Type | Description |
| ------ | ---------------- |
| number | API call timestamp.|
**Error codes**
For details about the error codes, see [HiSysEvent Error Codes](../errorcodes/errorcode-hisysevent.md).
| ID| Error Message |
| -------- | ----------------------------------- |
| 11200301 | Count of query rules is over limit. |
| 11200302 | Invalid query rule. |
| 11200304 | Export frequency is over limit. |
**Example**
```
import hiSysEvent from '@ohos.hiSysEvent';
import fs from '@ohos.file.fs';
try {
hiSysEvent.write({
domain: "RELIABILITY",
name: "STACK",
eventType: hiSysEvent.EventType.FAULT,
params: {
PID: 487,
UID: 103,
PACKAGE_NAME: "com.ohos.hisysevent.test",
PROCESS_NAME: "syseventservice",
MSG: "no msg."
}
}, (err, val) => {
// do something here.
})
let time = hiSysEvent.exportSysEvents({
beginTime: -1,
endTime: -1,
maxEvents: 1,
}, [{
domain: "RELIABILITY",
names: ["STACK"],
}])
console.log(`receive export task time is : ${time}`);
// Postpone reading of exported events.
setTimeout(function() {
let eventDir = '/data/storage/el2/base/cache/hiview/event';
let filenames = fs.listFileSync(eventDir);
for (let i = 0; i < filenames.length; i++) {
if (filenames[i].indexOf(time.toString()) != -1) {
let res = fs.readTextSync(eventDir + '/' + filenames[i]);
let events = JSON.parse('[' + res.slice(0, res.length - 1) + ']');
console.log("read file end, events is :" + JSON.stringify(events));
}
}
}, 10000)
} catch (error) {
console.error(`error code: ${error.code}, error msg: ${error.message}`);
}
```
## hiSysEvent.subscribe<sup>10+</sup>
subscribe(rules: QueryRule[]): number
Subscribes to real-time system events that occur occasionally or occur in a low frequency. These events are written as a file to the fixed directory of the application sandbox (that is, **/data/storage/el2/base/cache/hiview/event/**).
**Required permission**: ohos.permission.READ_DFX_SYSEVENT
**System capability**: SystemCapability.HiviewDFX.HiSysEvent
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------------------------- | ---- | ------------------------------------------ |
| rules | [QueryRule](#queryrule)[] | Yes | Array of event query rules for the subscription.|
**Return value**
| Type | Description |
| ------ | ---------------- |
| number | API call timestamp.|
**Error codes**
For details about the error codes, see [HiSysEvent Error Codes](../errorcodes/errorcode-hisysevent.md).
| ID| Error Message |
| -------- | ----------------------------------- |
| 11200301 | Count of query rules is over limit. |
| 11200302 | Invalid query rule. |
**Example**
```
import hiSysEvent from '@ohos.hiSysEvent';
import fs from '@ohos.file.fs';
try {
hiSysEvent.subscribe([{
domain: "RELIABILITY",
names: ["STACK"],
},{
domain: "BUNDLE_MANAGER",
names: ["BUNDLE_UNINSTALL"],
}])
hiSysEvent.write({
domain: "RELIABILITY",
name: "STACK",
eventType: hiSysEvent.EventType.FAULT,
params: {
PID: 487,
UID: 103,
PACKAGE_NAME: "com.ohos.hisysevent.test",
PROCESS_NAME: "syseventservice",
MSG: "no msg."
}
}, (err, val) => {
// do something here.
})
// Postpone reading of subscribed events.
setTimeout(function() {
let eventDir = '/data/storage/el2/base/cache/hiview/event';
let filenames = fs.listFileSync(eventDir);
for (let i = 0; i < filenames.length; i++) {
let res = fs.readTextSync(eventDir + '/' + filenames[i]);
let events = JSON.parse('[' + res.slice(0, res.length - 1) + ']');
console.log("read file end, events is :" + JSON.stringify(events));
}
}, 10000)
} catch (error) {
console.error(`error code: ${error.code}, error msg: ${error.message}`);
}
```
## hiSysEvent.unsubscribe<sup>10+</sup>
unsubscribe(): void
Unsubscribes from system events.
**Required permission**: ohos.permission.READ_DFX_SYSEVENT
**System capability**: SystemCapability.HiviewDFX.HiSysEvent
**Error codes**
For details about the error codes, see [HiSysEvent Error Codes](../errorcodes/errorcode-hisysevent.md).
| ID| Error Message |
| -------- | ------------------- |
| 11200305 | Unsubscribe failed. |
**Example**
```
import hiSysEvent from '@ohos.hiSysEvent';
try {
hiSysEvent.subscribe([{
domain: "RELIABILITY",
names: ["STACK"],
},{
domain: "BUNDLE_MANAGER",
names: ["BUNDLE_UNINSTALL","BUNDLE_INSTALL"],
}])
hiSysEvent.unsubscribe();
} catch (error) {
console.error(`error code: ${error.code}, error msg: ${error.message}`);
}
```
......@@ -16,7 +16,7 @@ import http from '@ohos.net.http';
## Examples
```js
// Import the http namespace.
// Import the HTTP namespace.
import http from '@ohos.net.http';
// Each httpRequest corresponds to an HTTP request task and cannot be reused.
......@@ -35,17 +35,17 @@ httpRequest.request(
header: {
'Content-Type': 'application/json'
},
// This parameter is used to transfer data when the POST request is used.
// This field is used to transfer data when the POST request is used.
extraData: {
"data": "data to send",
},
expectDataType: http.HttpDataType.STRING, // Optional. This parameter specifies the type of the return data.
expectDataType: http.HttpDataType.STRING, // Optional. This field specifies the type of the return data.
usingCache: true, // Optional. The default value is true.
priority: 1, // Optional. The default value is 1.
connectTimeout: 60000 // Optional. The default value is 60000, in ms.
readTimeout: 60000, // Optional. The default value is 60000, in ms.
usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system.
usingProxy: false, // Optional. By default, network proxy is not used. This field is supported since API version 10.
usingProxy: false, // Optional. By default, network proxy is not used. This field is supported since API 10.
caPath: "", // Optional. The preset CA certificate is used by default. This field is supported since API version 10.
}, (err, data) => {
if (!err) {
......@@ -55,6 +55,8 @@ httpRequest.request(
// data.header carries the HTTP response header. Parse the content based on service requirements.
console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
// Call the destroy() method to release resources after HttpRequest is complete.
httpRequest.destroy();
} else {
console.info('error:' + JSON.stringify(err));
// Unsubscribe from HTTP Response Header events.
......@@ -73,7 +75,7 @@ httpRequest.request(
createHttp(): HttpRequest
Creates an HTTP request. You can use this API to initiate or destroy an HTTP request, or enable or disable listening for HTTP Response Header events. An **HttpRequest** object corresponds to an HTTP request. To initiate multiple HTTP requests, you must create an **HttpRequest** object for each HTTP request.
Creates an HTTP request. You can use this API to initiate or destroy an HTTP request, or enable or disable listening for HTTP Response Header events. An HttpRequest object corresponds to an HTTP request. To initiate multiple HTTP requests, you must create an **HttpRequest** object for each HTTP request.
**System capability**: SystemCapability.Communication.NetStack
......@@ -432,7 +434,7 @@ httpRequest.request2("EXAMPLE_URL", (err, data) => {
request2(url: string, options: HttpRequestOptions, callback: AsyncCallback\<number\>): void
Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result, which is a streaming response.
Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result, which is a streaming response.
**Required permissions**: ohos.permission.INTERNET
......@@ -567,7 +569,7 @@ Initiates an HTTP request containing specified options to a given URL. This API
> **NOTE**
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html).
> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see:
**Example**
......@@ -594,7 +596,7 @@ on(type: 'headerReceive', callback: AsyncCallback\<Object\>): void
Registers an observer for HTTP Response Header events.
> **NOTE**
> This API has been deprecated. You are advised to use [on('headersReceive')<sup>8+</sup>](#onheadersreceive8).
> This API has been deprecated. You are advised to use [on('headersReceive')<sup>8+</sup>](#onheadersreceive8) instead.
**System capability**: SystemCapability.Communication.NetStack
......@@ -621,7 +623,7 @@ Unregisters the observer for HTTP Response Header events.
> **NOTE**
>
>1. This API has been deprecated. You are advised to use [off('headersReceive')<sup>8+</sup>](#offheadersreceive8).
>1. This API has been deprecated. You are advised to use [off('headersReceive')<sup>8+</sup>](#offheadersreceive8) instead.
>
>2. 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.
......@@ -817,7 +819,7 @@ Registers an observer for events indicating progress of receiving HTTP streaming
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | --------------------------------- |
| type | string | Yes | Event type. The value is **dataProgress**.|
| callback | AsyncCallback\<{ receiveSize: number, totalSize: number }\> | Yes | Callback used to return the result.<br>- **receiveSize**: number of received bytes.<br>- **totalSize**: total number of bytes to be received.|
| callback | AsyncCallback\<{ receiveSize: number, totalSize: number }\> | Yes | Callback used to return the result.<br>**receiveSize**: number of received bytes.<br>**totalSize**: total number of bytes to be received.|
**Example**
......@@ -860,7 +862,7 @@ Specifies the type and value range of the optional parameters in the HTTP reques
| Name | Type | Mandatory| Description |
| -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
| method | [RequestMethod](#requestmethod) | No | Request method. The default value is **GET**. |
| extraData | string<sup>6+</sup> \| Object<sup>6+</sup> \| ArrayBuffer<sup>8+</sup> | No | Additional data for sending a request. This parameter is not used by default.<br>- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request and is encoded in UTF-8 format. If **'Content-Type'** is **'application/x-www-form-urlencoded'**, the data in the request body must be encoded in the format of **key1=value1&key2=value2&key3=value3** after URL transcoding.<sup>6+</sup><br>- If the HTTP request uses the GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter serves as a supplement to HTTP request parameters. Parameters of the string type need to be encoded before being passed to the HTTP request. Parameters of the object type do not need to be precoded and will be directly concatenated to the URL. Parameters of the ArrayBuffer type will not be concatenated to the URL.<sup>6+</sup> |
| extraData | string<sup>6+</sup> \| Object<sup>6+</sup> \| ArrayBuffer<sup>8+</sup> | No | Additional data for sending a request. This parameter is not used by default.<br>- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request and is encoded in UTF-8 format. If **'Content-Type'** is **'application/x-www-form-urlencoded'**, the data in the request body must be encoded in the format of **key1=value1&key2=value2&key3=value3** after URL transcoding.<br>- If the HTTP request uses the GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter serves as a supplement to HTTP request parameters. Parameters of the string type need to be encoded before being passed to the HTTP request. Parameters of the object type do not need to be precoded and will be directly concatenated to the URL. Parameters of the ArrayBuffer type will not be concatenated to the URL.|
| expectDataType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | No | Type of the returned data. This parameter is not used by default. If this parameter is set, the system returns the specified type of data preferentially.|
| usingCache<sup>9+</sup> | boolean | No | Whether to use the cache. The default value is **true**. |
| priority<sup>9+</sup> | number | No | Priority. The value range is [1,1000]. The default value is **1**. |
......@@ -896,7 +898,7 @@ Enumerates the response codes for an HTTP request.
| Name | Value | Description |
| ----------------- | ---- | ------------------------------------------------------------ |
| OK | 200 | The request is successful. The request has been processed successfully. This return code is generally used for GET and POST requests. |
| OK | 200 | "OK." 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. |
| NOT_AUTHORITATIVE | 203 | "Non-Authoritative Information." The request is successful. |
......
......@@ -19,9 +19,10 @@ Prints debugging information in formatted output mode.
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----------- |
| message | string | Yes | Text to be printed.|
| arguments | any | No | Arguments in the message or other information to be printed.|
| arguments | any[] | No | Arguments in the message or other information to be printed.|
**Example**
```js
const number = 5;
console.debug('count: %d', number); // Print the debugging information with arguments in the message replaced.
......@@ -45,9 +46,10 @@ Prints log information in formatted output mode.
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----------- |
| message | string | Yes | Text to be printed.|
| arguments | any | No |Arguments in the message or other information to be printed.|
| arguments | any[] | No |Arguments in the message or other information to be printed.|
**Example**
```js
const number = 5;
console.log('count: %d', number); // Print the log information with arguments in the message replaced.
......@@ -71,9 +73,10 @@ Prints log information in formatted output mode. This API is the alias of **cons
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----------- |
| message | string | Yes | Text to be printed.|
| arguments | any | No | Arguments in the message or other information to be printed.|
| arguments | any[] | No | Arguments in the message or other information to be printed.|
**Example**
```js
const number = 5;
console.info('count: %d', number); // Print the log information with arguments in the message replaced.
......@@ -97,9 +100,10 @@ Prints warning information in formatted output mode.
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----------- |
| message | string | Yes | Warning information to be printed.|
| arguments | any | No | Arguments in the message or other information to be printed.|
| arguments | any[] | No | Arguments in the message or other information to be printed.|
**Example**
```js
const str = "name should be string";
console.warn('warn: %d', str); // Print the warning information with arguments in the message replaced.
......@@ -123,10 +127,11 @@ Prints error information in formatted output mode.
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----------- |
| message | string | Yes | Error information to be printed.|
| arguments | any | No | Arguments in the message or other information to be printed.|
| arguments | any[] | No | Arguments in the message or other information to be printed.|
**Example**
```js
const str = "value is not defined";
console.error('error: %d', str); // Print the error information with arguments in the message replaced.
......@@ -153,6 +158,7 @@ Prints assertion information.
| arguments | Object | No | Other information to be printed when **value** is **false**. If this parameter is left blank, other information is not printed.|
**Example**
```js
console.assert(true, 'does nothing'); // Do not print error information as value is true.
console.assert(2% 1 == 0,'does nothing'); // Do not print error information as value is true.
......@@ -180,6 +186,7 @@ Maintains an internal counter. When this counter is invoked, its label name and
**Example**
```js
console.count()
// default: 1
......@@ -210,6 +217,7 @@ Resets a counter based on the specified label name.
| label | string | No | Counter label name. The default value is **default**.|
**Example**
```js
console.count('abc');
// abc: 1
......@@ -234,6 +242,7 @@ Prints content of the specified object.
**Example**
```js
let a = { foo: { bar: { baz: true } }};
console.dir(a);
......@@ -258,6 +267,7 @@ Displays an interactive tree of the descendant elements of the specified XML ele
| arguments | Object | Yes | Information to be printed.|
**Example**
```js
const number = 5;
console.dirxml('count: %d', number);
......@@ -284,6 +294,7 @@ If the information to be printed is provided, the information is printed without
| arguments | Object | No | Information to be printed.|
**Example**
```js
console.log("outter");
// outter
......@@ -313,6 +324,7 @@ Creates a new inline group in collapsed mode. The usage and function of this API
**Example**
```js
console.groupCollapsed("outter");
// outter
......@@ -335,6 +347,7 @@ Reduces the indentation of subsequent lines by two spaces.
**Example**
```js
console.log("outter");
// outter
......@@ -362,6 +375,7 @@ Prints data in a table.
| tableData | Object | No | Data to be printed in a table. If this parameter is left blank, no information is printed.|
**Example**
```js
console.table([1, 2, 3]);
// ┌─────────┬────────┐
......@@ -382,6 +396,7 @@ console.table({ a: [1, 2, 3, 4, 5], b: 5, c: { e: 5 } });
// │ c │ │ │ │ │ │ 5 │ │
// └─────────┴───┴───┴───┴───┴───┴───┴────────┘
```
## console.time<sup>10+</sup>
time(label?: string): void
......@@ -397,6 +412,7 @@ Starts a timer to track the duration of an operation. You can use **console.time
| label | string | No | Timer label. The default value is **default**.|
**Example**
```js
console.time('abc');
```
......@@ -416,6 +432,7 @@ Stops the timer started by calling **console.time()** and prints the elapsed tim
| label | string | No | Timer label. The default value is **default**.|
**Example**
```js
console.time('abc');
console.timeEnd('abc');
......@@ -438,6 +455,7 @@ Prints the elapsed time and other data parameters for the timer started by **con
| arguments | Object | No | Logs to be printed.|
**Example**
```js
console.time('timer1');
console.timeLog('timer1', 17);
......@@ -461,6 +479,7 @@ Creates a stack trace.
| arguments | Object | No | Logs to be printed. If this parameter is left blank, only stack information is printed.|
**Example**
```js
console.trace();
// Trace:
......
# Seccomp Policy Development
## Overview
### Introduction
Secure computing mode (Seccomp) is a security mechanism provided by the Linux kernel. In the Linux system, a large number of system calls can be opened to user-mode programs without any restrictions. However, not all of these system calls are necessarily needed for user-mode programs. In this case, abuse of system calls can lead to system threats. For example, if a process has a security vulnerability, an attacker can run a shellcode segment to trigger system calls that are not triggered during normal execution, resulting in privilege escalation or private information leakage. To prevent such security risks, Seccomp limits the scope of system calls that can be used by programs, so as to reduce system exposure and improve security.
### Operating Mechanism
1. Basic mechanism
Seccomp policies exist in the form of policy files. During compilation and building, a policy file is parsed to generate a source file that contains the BPF instruction policies, and then the source file is compiled into a dynamic policy library. During startup of a user-mode process, Seccomp system calls are invoked to load the BPF instruction policies into the kernel through the dynamic policy library.
......@@ -15,6 +19,7 @@ Secure computing mode (Seccomp) is a security mechanism provided by the Linux ke
### Constraints
- System restrictions<br>The system used must be a standard system, and the options listed below must be enabled in the kernel. You can find the kernel option configuration file of the product in **//kernel/linux/config/{linux_version}/arch/{target_cpu}/configs/**.
```shell
CONFIG_HAVE_ARCH_SECCOMP=y
......@@ -31,9 +36,13 @@ Secure computing mode (Seccomp) is a security mechanism provided by the Linux ke
- Personalized Seccomp policies can be enabled for the native service processes incubated by the init process.
## Enabling Seccomp
### When to Use
To meet product security requirements, you can enable Seccomp to limit the scope of system calls that can be invoked by processes. The development procedure below describes how to enable the basic functions and policies of Seccomp. Note that the basic functions must meet the feature restrictions described in [Constraints](#constraints). For details about the basic policy file, see [Policy File Overview](#policy-file-overview).
### How to Develop
1. Add the following field to **vendor/Product vendor/Product name/config.json**:
```c
"build_seccomp": true
......@@ -68,6 +77,7 @@ To meet product security requirements, you can enable Seccomp to limit the scope
3. Burn the image into the device.
### Debugging and Verification
Check whether Seccomp is enabled for application processes and system service processes.
1. Run the shell command to obtain the process ID (that is, **target pid**) of the target process.
```
......@@ -95,9 +105,13 @@ Check whether Seccomp is enabled for application processes and system service pr
| Seccomp_filters | Number of Seccomp policies set for a process. |
## Customizing Seccomp Policies for a Process
### When to Use
If the basic Seccomp policy has been enabled for a product, you can customize Seccomp policies for native service processes incubated by the init process to adapt to diversified security requirements. In this case, the Seccomp policies of other native service processes remain unchanged.
### How to Develop
1. Collect statistics on the system calls required by the 32-bit and 64-bit systems by using the static analysis and Strace statistics methods described in [System Call Statistic Methods](#system-call-statistic-methods). In this way, you will obtain the initial Seccomp policy.
2. Write a policy file. For details, see [How to Write a Common Policy File](#how-to-write-a-common-policy-file).
3. Write and build the **BUILD.gn** file.
......@@ -166,12 +180,15 @@ If the basic Seccomp policy has been enabled for a product, you can customize Se
6. Use the [audit statistics](#audit-statistics) method to check and supplement the Seccomp policies. Repeat steps 4 to 6 until the process can run properly.
### Debugging and Verification
1. If Seccomp is not enabled for the target process, [check the Seccomp status](#debugging-and-verification) of the target process.
2. If the process is terminated and audit log information is present in the kernel logs, the Seccomp policy is enabled but the policy list is incomplete. You can find an example audit log in [Audit Statistics](#audit-statistics).
3. If the process is not terminated, comment out the system calls (for example, **setuid**) related to the specified uid in the Seccomp policy file. Rebuild the dynamic policy library, push the library to the image, and restart the process. Then, check whether the process is terminated by Seccomp. If the process is terminated, Seccomp has been enabled.
## FAQs
### How do I determine whether a process termination is caused by Seccomp?
**Symptom**
If a process is terminated under certain conditions, how do I determine whether the issue is caused by Seccomp?
......@@ -207,6 +224,7 @@ Use either of the following methods:
```
## Reference
### Seccomp source code directory
```
base/startup/init/services/modules/seccomp
......@@ -229,6 +247,7 @@ base/startup/init/services/modules/seccomp
```
### Policy File Overview
- Location<br>Basic policy files are stored in **//base/startup/init/services/modules/seccomp/seccomp_policy**.
- Basic policy files
......@@ -244,6 +263,7 @@ base/startup/init/services/modules/seccomp
| privileged_process.seccomp.policy | Privileged process policy file. If certain processes need to use the system calls on the baseline blocklist, you need to declare the corresponding process identifiers and baseline blocklists in this file.|
### How to Write a Common Policy File
- To declare a configuration item, write **@** followed by the configuration item, for example, **@returnValue**.
- Add the content of a configuration item from the next line of this configuration item to the beginning of the next configuration item.
- To comment out a line, add a pound sign (#) at the beginning of this line.
......@@ -298,6 +318,7 @@ swapon;all
```
### How to Write a Privileged Process Policy File
- To declare a configuration item, write **@** followed by the configuration item, for example, **@allowBlockList**.
- Add the content of a configuration item from the next line of this configuration item to the beginning of the next configuration item.
- To comment out a line, add a pound sign (#) at the beginning of this line.
......@@ -326,6 +347,7 @@ swapon;all
```
### System Call Statistic Methods
**Table 6** Comparison of statistic methods
| Statistic Method | Description | Advantage | Disadvantage |
| --- | --- | --- | --- |
......@@ -334,6 +356,7 @@ swapon;all
| Audit statistics | After the Seccomp policy is enabled for a process, Seccomp intercepts invalid system calls and records audit log information containing the system call numbers into kernel logs. Collect the logs after the trace is complete, and use a script to parse the logs and generate a Seccomp policy file.| This method can be used as a supplement to the preceding methods. | Logs may be lost.<br>System calls can be completely collected only when all code branches are traversed. |
#### Static Analysis
1. Prepare the environment.
1. Prepare a Linux environment.
2. Download the cross compilers arm-linux-musleabi and aarch64-linux-musl.
......@@ -433,10 +456,13 @@ swapon;all
```
#### Strace Statistics
1. Use the cross compilers arm-linux-musleabi and aarch64-linux-musl to build the Strace tool for the 32-bit and 64-bit architectures, respectively.
2. [Trace the service process](#tracing-the-service-process) to obtain the Strace logs.
3. [Parse Strace logs](#parsing-strace-logs) by using scripts to obtain the Seccomp policy file.
##### Tracing the Service Process
1. Modify the embedded code in the init repository. Specifically, add the following content to **//base/startup/init/services/init/init_common_service.c** before executing the **SetSystemseccompPolicy** function to set the Seccomp policy. If the line starts with a plus sign (+), the line is added; if the line starts with a hyphen (-), the line is deleted. **xxxx** must be the same as the value of **Services name** in the [boot configuration file](subsys-boot-init-cfg.md) of the process.
```c
--- a/services/init/init_common_service.c
......@@ -485,6 +511,7 @@ swapon;all
```
##### Parsing Strace Logs
1. Copy the dependency files to the Strace log folder for later use. The dependency files are those generated in step 2 in [Static Analysis](#static-analysis).
```shell
cp out/*product name* /gen/base/startup/init/services/modules/seccomp/gen_system_filter/libsyscall_to_nr_arm* base/startup/init/services/modules/seccomp/scripts/tools/strace/
......@@ -521,6 +548,7 @@ swapon;all
```
#### Audit Statistics
1. Enable the initial Seccomp policy. For details, see [Customizing Seccomp Policies for a Process](#customizing-seccomp-policies-for-a-process).
2. Obtain logs.
1. Create a folder for storing logs.
......@@ -586,6 +614,7 @@ swapon;all
```
### Combining Multiple Policy Files
During [colltatistics on system calls](#system-call-statistic-methods), multiple policy files may be generated. In these policy files, system calls may be repeated or disordered. To solve these problems, you can combine policy files to sort system calls by arm64/arm and by system call number in ascending order.
**Table 11** Parameters in the merge_policy.py script file
......
# HiTraceMeter Development
# HiTraceMeter
## Introduction
......@@ -279,6 +279,7 @@ The hitrace CLI tool is an executable binary program. On an OpenHarmony-powered
| --trace_begin | Starts capturing trace data. |
| --trace_dump | Dumps trace data to the specified position. The default position is the console. |
| --trace_finish | Stops capturing trace data and dumps trace data to the specified position. The default position is the console. |
| --trace_finish_nodump | Stops capturing trace packets and dumping trace data. |
| -l, --list_categories | Lists the trace categories supported by the device. |
| --overwrite | Sets the action to take when the buffer is full. If this option is used, the latest trace data is discarded. If this option is not used, the earliest trace data is discarded (default). |
| -o *filename*, --output *filename*| Outputs trace data to the specified file. |
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册