• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..17-Mar-2025-

etc/profile/H17-Mar-2025-560553

figures/H17-Mar-2025-

interfaces/innerkits/safwk/H17-Mar-2025-2,5681,752

services/safwk/H17-Mar-2025-3,1692,491

test/H17-Mar-2025-9,0996,049

.gitattributesH A D17-Mar-2025631 1615

.gitignoreH A D17-Mar-202517 22

Cargo.tomlH A D17-Mar-2025795 2119

LICENSEH A D17-Mar-202510.1 KiB177150

OAT.xmlH A D17-Mar-20256.3 KiB8937

README.mdH A D17-Mar-20258.2 KiB241186

README_zh.mdH A D17-Mar-20259.2 KiB258204

bundle.jsonH A D17-Mar-20252.9 KiB8079

cfi_blocklist.txtH A D17-Mar-2025777 1716

rustfmt.tomlH A D17-Mar-2025774 2018

README.md

1# safwk
2## Introduction
3
4The System Ability Framework (safwk) component defines how to implement system abilities in OpenHarmony and provides APIs to start and register system abilities.
5
6## System Architecture
7
8**Figure 1** Architecture of safwk
9
10
11![](figures/en-us_image_0000001115820566.png)
12
13## Directory Structure
14
15```
16/foundation/systemabilitymgr
17│── safwk                # Directory of safwk
18│  ├── bundle.json      # Description and build file of safwk
19│  ├── etc              # Configuration files
20│  ├── interfaces       # APIs exposed externally
21│  ├── services         # Service implementation
22│  ├── test             # Test cases
23```
24
25## Usage
26
27### Available APIs
28
29| API                                                      | Description                              |
30| ------------------------------------------------------------ | -------------------------------------- |
31| sptr\<IRemoteObject> GetSystemAbility(int32_t systemAbilityId); | Obtains the remote procedure call (RPC) object of a system ability.           |
32| bool Publish(sptr\<IRemoteObject> systemAbility);            | Publishes a system ability.                        |
33| virtual void DoStartSAProcess(const std::string& profilePath) = 0; | Enables a system ability based on its profile.|
34
35### How to Use
36
37A system ability is implemented by using a XXX.cfg, a profile.json, and a libXXX.z.so. The init process starts the SystemAbility process by executing the corresponding XXX.cfg file.
38
39**Implementing a System Ability in C++**
40
41The sample code is as follows:
42
43**1. Define the *IXXX* class for IPC.**
44
45The *IXXX* class is used to define the functions for the system ability to provide specific capabilities. To define this class, inherit from the **IRemoteBroker** class provided by OpenHarmony for Inter-Process Communication (IPC) and implement the **DECLARE\_INTERFACE\_DESCRIPTOR\(*XXX*)** that uniquely identifies this class. The identifier is used for IPC verification.
46
47```
48namespace OHOS {
49class IListenAbility : public IRemoteBroker {
50public:
51    virtual int AddVolume(int volume) = 0;
52
53public:
54    enum {
55        ADD_VOLUME = 1,
56    };
57public:
58    DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.test.IListenAbility");
59};
60}
61```
62
63**2. Define the *XXX*Proxy class for client communication.**
64
65```
66namespace OHOS {
67class ListenAbilityProxy : public IRemoteProxy<IListenAbility> {
68public:
69    int AddVolume(int volume);
70
71    explicit ListenAbilityProxy(const sptr<IRemoteObject>& impl)
72        : IRemoteProxy<IListenAbility>(impl)
73    {
74    }
75
76private:
77    static inline BrokerDelegator<ListenAbilityProxy> delegator_;
78};
79} // namespace OHOS
80```
81
82**3. Define the *XXX*Stub class for server communication.**
83
84```
85namespace OHOS {
86int32_t ListenAbilityStub::OnRemoteRequest(uint32_t code,
87    MessageParcel& data, MessageParcel &reply, MessageOption &option)
88{
89    switch (code) {
90        case ADD_VOLUME: {
91            return reply.WriteInt32(AddVolume(data.ReadInt32()));
92        }
93
94        default:
95            return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
96    }
97}
98}
99```
100
101**4. Implement a system ability.**
102
103```
104namespace {
105constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, 0xD001800, "SA_TST"};
106}
107
108REGISTER_SYSTEM_ABILITY_BY_ID(ListenAbility, DISTRIBUTED_SCHED_TEST_LISTEN_ID, true);
109
110ListenAbility::ListenAbility(int32_t saId, bool runOnCreate) : SystemAbility(saId, runOnCreate)
111{
112    HiLog::Info(LABEL, ":%s called", __func__);
113    HiLog::Info(LABEL, "ListenAbility()");
114}
115
116ListenAbility::~ListenAbility()
117{
118    HiLog::Info(LABEL, "~ListenAbility()");
119}
120
121int ListenAbility::AddVolume(int volume)
122{
123    pid_t current = getpid();
124    HiLog::Info(LABEL, "ListenAbility::AddVolume volume = %d, pid = %d.", volume, current);
125    return (volume + 1);
126}
127
128void ListenAbility::OnDump()
129{
130}
131
132void ListenAbility::OnStart()
133{
134    HiLog::Info(LABEL, "ListenAbility::OnStart()");
135    HiLog::Info(LABEL, "ListenAbility:%s called:-----Publish------", __func__);
136    bool res = Publish(this);
137    if (res) {
138        HiLog::Error(LABEL, "ListenAbility: res == false");
139    }
140    HiLog::Info(LABEL, "ListenAbility:%s called:AddAbilityListener_OS_TST----beg-----", __func__);
141    AddSystemAbilityListener(DISTRIBUTED_SCHED_TEST_OS_ID);
142    HiLog::Info(LABEL, "ListenAbility:%s called:AddAbilityListener_OS_TST----end-----", __func__);
143
144    HiLog::Info(LABEL, "ListenAbility:%s called:StopAbility_OS_TST----beg-----", __func__);
145    StopAbility(DISTRIBUTED_SCHED_TEST_OS_ID);
146    HiLog::Info(LABEL, "ListenAbility:%s called:StopAbility_OS_TST----end-----", __func__);
147    return;
148}
149
150void ListenAbility::OnStop()
151{
152}
153```
154
155**5. Configure the system ability.**
156
157Configure the profile of the system ability so that the system ability can be loaded and registered. The configuration procedure is as follows:
158
159Create a folder named **sa_profile** in the root directory of the subsystem. Then, create two files in this folder, including an json file prefixed with the service ID of the system ability and a **BUILD.gn** file.
160
161Sample *serviceid*.json file:
162
163```
164{
165    "process": "listen_test",
166    "systemability": [
167        {
168            "name": serviceid,
169            "libpath": "liblisten_test.z.so",
170            "run-on-create": true,
171            "distributed": true,
172            "dump_level": 1
173        }
174    ]
175}
176```
177
178Sample **BUILD.gn** file:
179
180```
181import("//build/ohos/sa_profile/sa_profile.gni")
182ohos_sa_profile("xxx_sa_profile") {
183    sources = [
184        "serviceid.json"
185    ]
186    subsystem_name = "systemabilitymgr"
187}
188```
189
190>**NOTE**
191>1.  Set **process** to the name of the process where the system ability will run. This parameter is mandatory.
192>2.  The *serviceid*.json file can contain only one **systemability** node. Multiple **systemability** nodes will cause a build failure.
193>3.  Set **name** to the service ID registered in the code for the system ability. This parameter is mandatory.
194>4.  Set **libpath** to the path for loading the system ability. This parameter is mandatory.
195>5.  Set **run-on-create** to **true** if you want to register this system ability with the Samgr component immediately after the process is started. Set it to **false** if you want the system ability to start only when it is accessed. This parameter is mandatory.
196>6.  Set **distributed** to **true** if this system ability allows cross-device access. Set it to **false** if it allows IPC only on the local device.
197>7.  **bootphase** specifies the startup priority of the system ability. The value can be **BootStartPhase** (highest), **CoreStartPhase**, or **OtherStartPhase** (lowest). In the same process, system abilities of a lower priority can be started and registered only after those of a higher priority have all been started and registered. This parameter is optional. The default value is **OtherStartPhase**.
198>8.  **dump-level** specifies the level supported by the system dumper. The default value is **1**.
199>9. In the **BUILD.gn** file, set **subsystem_name** to the subsystem name, and add the list of system abilities to be configured for the subsystem in **sources**. Multiple system abilities can be configured.
200
201After the preceding steps are complete, an json file named by the process will be generated in the **out**, for example, **out\...\system\profile\listen_test.json**.
202
203**6. Configure the .cfg file.**
204
205The .cfg file contains the native process startup policy provided by Linux. During the system startup process, the init process parses the .cfg file to start the native process.
206
207```
208{
209    "jobs" : [{
210            "name" : "post-fs-data",
211            "cmds" : [
212                "start listen_test"
213            ]
214        }
215    ],
216	"services" : [{
217            "name" : "listen_test",
218            "path" : ["/system/bin/sa_main", "/system/profile/listen_test.json"],
219            "uid" : "system",
220            "gid" : ["system", "shell"]
221        }
222    ]
223}
224```
225
226>**NOTE**
227>
228>For details about the implementation of listen_ability, see **test/services/safwk/unittest/common/listen_ability**.
229
230## Repositories Involved
231
232Samgr
233
234[**systemabilitymgr\_safwk**](https://gitee.com/openharmony/systemabilitymgr_safwk)
235
236[systemabilitymgr\_samgr](https://gitee.com/openharmony/systemabilitymgr_samgr)
237
238[systemabilitymgr\_safwk\_lite](https://gitee.com/openharmony/systemabilitymgr_safwk_lite)
239
240[systemabilitymgr\_samgr\_lite](https://gitee.com/openharmony/systemabilitymgr_samgr_lite)
241

README_zh.md

1# 系统服务框架部件<a name="ZH-CN_TOPIC_0000001115588558"></a>
2## 简介<a name="section11660541593"></a>
3
4在系统服务管理子系统中safwk组件定义OpenHarmony中SystemAbility的实现方法,并提供启动、注册等接口实现。
5
6## 系统架构<a name="section342962219551"></a>
7
8**图 1**  系统服务框架图
9
10
11![](figures/zh-cn_image_0000001115820566.png)
12
13## 目录<a name="section161941989596"></a>
14
15```
16/foundation/systemabilitymgr
17│── safwk               # 组件目录
18│  ├── bundle.json      # 组件描述及编译脚本
19│  ├── etc              # 配置文件
20│  ├── interfaces       # 对外接口目录
21│  ├── services         # 组件服务实现
22│  ├── test             # 测试用例
23```
24
25## 说明<a name="section1312121216216"></a>
26
27### 接口说明<a name="section1551164914237"></a>
28
29<a name="table775715438253"></a>
30<table><thead align="left"><tr id="row12757154342519"><th class="cellrowborder" valign="top" width="43.19%" id="mcps1.1.3.1.1"><p id="p1075794372512"><a name="p1075794372512"></a><a name="p1075794372512"></a>接口名</p>
31</th>
32<th class="cellrowborder" valign="top" width="56.81%" id="mcps1.1.3.1.2"><p id="p375844342518"><a name="p375844342518"></a><a name="p375844342518"></a>接口描述</p>
33</th>
34</tr>
35</thead>
36<tbody><tr id="row1975804332517"><td class="cellrowborder" valign="top" width="43.19%" headers="mcps1.1.3.1.1 "><p id="p5758174313255"><a name="p5758174313255"></a><a name="p5758174313255"></a>sptr&lt;IRemoteObject&gt; GetSystemAbility(int32_t systemAbilityId);</p>
37</td>
38<td class="cellrowborder" valign="top" width="56.81%" headers="mcps1.1.3.1.2 "><p id="p14758743192519"><a name="p14758743192519"></a><a name="p14758743192519"></a>获取指定系统服务的RPC对象。</p>
39</td>
40</tr>
41<tr id="row2758943102514"><td class="cellrowborder" valign="top" width="43.19%" headers="mcps1.1.3.1.1 "><p id="p107581438250"><a name="p107581438250"></a><a name="p107581438250"></a>bool Publish(sptr&lt;IRemoteObject&gt; systemAbility);</p>
42</td>
43<td class="cellrowborder" valign="top" width="56.81%" headers="mcps1.1.3.1.2 "><p id="p8758743202512"><a name="p8758743202512"></a><a name="p8758743202512"></a>发布系统服务。</p>
44</td>
45</tr>
46<tr id="row09311240175710"><td class="cellrowborder" valign="top" width="43.19%" headers="mcps1.1.3.1.1 "><p id="p159328405571"><a name="p159328405571"></a><a name="p159328405571"></a>virtual void DoStartSAProcess(const std::string&amp; profilePath) = 0;</p>
47</td>
48<td class="cellrowborder" valign="top" width="56.81%" headers="mcps1.1.3.1.2 "><p id="p493294018574"><a name="p493294018574"></a><a name="p493294018574"></a>根据SA profile配置启动System Ability。</p>
49</td>
50</tr>
51</tbody>
52</table>
53
54### 使用说明<a name="section129654513264"></a>
55
56SystemAbility实现一般采用XXX.cfg + profile.json + libXXX.z.so的方式由init进程执行对应的XXX.cfg文件拉起相关SystemAbility进程。
57
58**C++实现SystemAbility**
59
60示例代码如下:
61
62-   **1. 定义IPC对外接口IXXX**
63
64定义该服务对外提供的能力集合函数,统一继承IPC接口类IRemoteBroker;同时实现该IPC对外接口唯一标识符DECLARE\_INTERFACE\_DESCRIPTOR\(XXX\);该标识符用于IPC通信的校验等目的。
65
66```
67namespace OHOS {
68class IListenAbility : public IRemoteBroker {
69public:
70    virtual int AddVolume(int volume) = 0;
71
72public:
73    enum {
74        ADD_VOLUME = 1,
75    };
76public:
77    DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.test.IListenAbility");
78};
79}
80```
81
82-   **2. 定义客户端通信代码XXXProxy**
83
84```
85namespace OHOS {
86class ListenAbilityProxy : public IRemoteProxy<IListenAbility> {
87public:
88    int AddVolume(int volume);
89
90    explicit ListenAbilityProxy(const sptr<IRemoteObject>& impl)
91        : IRemoteProxy<IListenAbility>(impl)
92    {
93    }
94
95private:
96    static inline BrokerDelegator<ListenAbilityProxy> delegator_;
97};
98} // namespace OHOS
99```
100
101-   **3. 定义服务端通信代码XXXStub**
102
103```
104namespace OHOS {
105int32_t ListenAbilityStub::OnRemoteRequest(uint32_t code,
106    MessageParcel& data, MessageParcel &reply, MessageOption &option)
107{
108    switch (code) {
109        case ADD_VOLUME: {
110            return reply.WriteInt32(AddVolume(data.ReadInt32()));
111        }
112
113        default:
114            return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
115    }
116}
117}
118```
119
120-   **4. SystemAbility的实现类**
121
122```
123namespace {
124constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, 0xD001800, "SA_TST"};
125}
126
127REGISTER_SYSTEM_ABILITY_BY_ID(ListenAbility, DISTRIBUTED_SCHED_TEST_LISTEN_ID, true);
128
129ListenAbility::ListenAbility(int32_t saId, bool runOnCreate) : SystemAbility(saId, runOnCreate)
130{
131    HiLog::Info(LABEL, ":%s called", __func__);
132    HiLog::Info(LABEL, "ListenAbility()");
133}
134
135ListenAbility::~ListenAbility()
136{
137    HiLog::Info(LABEL, "~ListenAbility()");
138}
139
140int ListenAbility::AddVolume(int volume)
141{
142    pid_t current = getpid();
143    HiLog::Info(LABEL, "ListenAbility::AddVolume volume = %d, pid = %d.", volume, current);
144    return (volume + 1);
145}
146
147void ListenAbility::OnDump()
148{
149}
150
151void ListenAbility::OnStart()
152{
153    HiLog::Info(LABEL, "ListenAbility::OnStart()");
154    HiLog::Info(LABEL, "ListenAbility:%s called:-----Publish------", __func__);
155    bool res = Publish(this);
156    if (res) {
157        HiLog::Error(LABEL, "ListenAbility: res == false");
158    }
159    HiLog::Info(LABEL, "ListenAbility:%s called:AddAbilityListener_OS_TST----beg-----", __func__);
160    AddSystemAbilityListener(DISTRIBUTED_SCHED_TEST_OS_ID);
161    HiLog::Info(LABEL, "ListenAbility:%s called:AddAbilityListener_OS_TST----end-----", __func__);
162
163    HiLog::Info(LABEL, "ListenAbility:%s called:StopAbility_OS_TST----beg-----", __func__);
164    StopAbility(DISTRIBUTED_SCHED_TEST_OS_ID);
165    HiLog::Info(LABEL, "ListenAbility:%s called:StopAbility_OS_TST----end-----", __func__);
166    return;
167}
168
169void ListenAbility::OnStop()
170{
171}
172```
173
174-   **5. SystemAbility配置**
175
176以c++实现的SA必须配置相关System Ability的profile配置文件才会完成SA的加载注册逻辑,否则没有编写profile配置的System Ability不会完成注册。配置方法如下:
177
178在子系统的根目录新建一个以sa\_profile为名的文件夹,然后在此文件夹中新建两个文件:一个以serviceId为前缀的json文件,另外一个为BUILD.gn文件。
179
180serviceid.json181
182```
183{
184    "process": "listen_test",
185    "systemability": [
186        {
187            "name": serviceid,
188            "libpath": "liblisten_test.z.so",
189            "run-on-create": true,
190            "distributed": true,
191            "dump_level": 1
192        }
193    ]
194}
195```
196
197BUILD.gn198
199```
200import("//build/ohos/sa_profile/sa_profile.gni")
201ohos_sa_profile("xxx_sa_profile") {
202    sources = [
203        "serviceid.json"
204    ]
205    subsystem_name = "systemabilitymgr"
206}
207```
208
209>**说明:**
210>1.  进程名字即该SystemAbility要运行的进程空间,此字段是必填选项。
211>2.  一个SystemAbility配置文件只能配置一个SystemAbility节点,配置多个会导致编译失败。
212>3.  SystemAbility的name为对应的serviceId必须与代码中注册的serviceId保持一致,必配项。
213>4.  libpath为SystemAbility的加载路径,必配项。
214>5.  run-on-create:true表示进程启动后即向samgr组件注册该SystemAbility;false表示按需启动,即在其他模块访问到该SystemAbility时启动,必配项。
215>6.  distributed:true表示该SystemAbility为分布式SystemAbility,支持跨设备访问;false表示只有本地跨IPC访问。
216>7.  bootphase:可不设置;可以设置的值有三种:BootStartPhase、CoreStartPhase、OtherStartPhase(默认类型),三种优先级依次降低,当同一个进程中,会优先拉起注册配置BootStartPhase的SystemAbility,然后是配置了CoreStartPhase的SystemAbility,最后是OtherStartPhase;当高优先级的SystemAbility全部启动注册完毕才会启动下一级的SystemAbility的注册启动。
217>8.  dump-level:表示systemdumper支持的level等级,默认配置1。
218>9. BUILD.gn中subsystem\_name为相应部件名称;sources表示当前子系统需要配置的SystemAbility列表,可支持配置多个SystemAbility。
219
220以上步骤完成后,全量编译代码后会在out路径向生成一个以进程名为前缀的json文件listen\_test.json;路径为:out\\...\\system\\profile\\listen\_test.json221
222-   **6. cfg配置文件**
223
224cfg配置文件为linux提供的native进程拉起策略,开机启动阶段由init进程解析配置的cfg文件进行拉起。
225
226```
227{
228    "jobs" : [{
229            "name" : "post-fs-data",
230            "cmds" : [
231                "start listen_test"
232            ]
233        }
234    ],
235	"services" : [{
236            "name" : "listen_test",
237            "path" : ["/system/bin/sa_main", "/system/profile/listen_test.json"],
238            "uid" : "system",
239            "gid" : ["system", "shell"]
240        }
241    ]
242}
243```
244
245>**说明:**
246>listen\_ability的实现可以参考:test/services/safwk/unittest/common/listen\_ability。
247
248## 相关仓<a name="section1371113476307"></a>
249
250系统服务管理子系统
251
252[**systemabilitymgr\_safwk**](https://gitee.com/openharmony/systemabilitymgr_safwk)
253
254[systemabilitymgr\_samgr](https://gitee.com/openharmony/systemabilitymgr_samgr)
255
256[systemabilitymgr\_safwk\_lite](https://gitee.com/openharmony/systemabilitymgr_safwk_lite)
257
258[systemabilitymgr\_samgr\_lite](https://gitee.com/openharmony/systemabilitymgr_samgr_lite)