update OpenHarmony 2.0 Canary

This commit is contained in:
mamingshuai
2021-06-02 00:05:56 +08:00
parent fc38d4d56e
commit 1d6c38ae9c
37 changed files with 3599 additions and 61 deletions
View File
Executable
+177
View File
@@ -0,0 +1,177 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
-36
View File
@@ -1,36 +0,0 @@
# distributedschedule_safwk
#### Description
System ability framework | 系统服务框架定义
#### Software Architecture
Software architecture description
#### Installation
1. xxxx
2. xxxx
3. xxxx
#### Instructions
1. xxxx
2. xxxx
3. xxxx
#### Contribution
1. Fork the repository
2. Create Feat_xxx branch
3. Commit your code
4. Create Pull Request
#### Gitee Feature
1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md
2. Gitee blog [blog.gitee.com](https://blog.gitee.com)
3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore)
4. The most valuable open source project [GVP](https://gitee.com/gvp)
5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help)
6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)
Regular → Executable
+248 -25
View File
@@ -1,37 +1,260 @@
# distributedschedule_safwk
# safwk<a name="EN-US_TOPIC_0000001115588558"></a>
#### 介绍
System ability framework | 系统服务框架定义
- [Introduction](#section11660541593)
- [Directory Structure](#section161941989596)
- [Usage](#section1312121216216)
- [Available APIs](#section1551164914237)
- [Usage Guidelines](#section129654513264)
#### 软件架构
软件架构说明
- [Repositories Involved](#section1371113476307)
## Introduction<a name="section11660541593"></a>
#### 安装教程
The **safwk** module of the Distributed Scheduler subsystem defines how to implement a **SystemAbility** in OpenHarmony and provides APIs for system ability startup and registration.
1. xxxx
2. xxxx
3. xxxx
## Directory Structure<a name="section161941989596"></a>
#### 使用说明
```
/foundation/distributedschedule
│── safwk # Directory for the safwk module
│ ├── ohos.build # Compilation script for safwk
│ ├── interfaces # APIs exposed externally
│ ├── services # Service implementation
```
1. xxxx
2. xxxx
3. xxxx
## Usage<a name="section1312121216216"></a>
#### 参与贡献
### Available APIs<a name="section1551164914237"></a>
1. Fork 本仓库
2. 新建 Feat_xxx 分支
3. 提交代码
4. 新建 Pull Request
<a name="table775715438253"></a>
<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>API</p>
</th>
<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>Description</p>
</th>
</tr>
</thead>
<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>
</td>
<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>Obtains the remote procedure call (RPC) object of a specified system ability.</p>
</td>
</tr>
<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>
</td>
<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>Publishes a specified system ability.</p>
</td>
</tr>
<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>
</td>
<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>Enables a system ability based on the SA profile information.</p>
</td>
</tr>
<tr id="row159634125718"><td class="cellrowborder" valign="top" width="43.19%" headers="mcps1.1.3.1.1 "><p id="p10596134105710"><a name="p10596134105710"></a><a name="p10596134105710"></a>void OnConnectedSystemAbility(const sptr&lt;IRemoteObject&gt;&amp; connectionCallback);</p>
</td>
<td class="cellrowborder" valign="top" width="56.81%" headers="mcps1.1.3.1.2 "><p id="p105961241125713"><a name="p105961241125713"></a><a name="p105961241125713"></a>Called when a system ability is connected.</p>
</td>
</tr>
<tr id="row611715428577"><td class="cellrowborder" valign="top" width="43.19%" headers="mcps1.1.3.1.1 "><p id="p10118242155716"><a name="p10118242155716"></a><a name="p10118242155716"></a>void OnDisConnectedSystemAbility(int32_t systemAbilityId);</p>
</td>
<td class="cellrowborder" valign="top" width="56.81%" headers="mcps1.1.3.1.2 "><p id="p81189429578"><a name="p81189429578"></a><a name="p81189429578"></a>Called when a system ability is disconnected.</p>
</td>
</tr>
</tbody>
</table>
### Usage Guidelines<a name="section129654513264"></a>
#### 特技
System abilities can be implemented in both C++ and Java languages. In C++, you must define the _XXX_**.rc**, **profile.xml**, and **lib**_XXX_**.z.so** files to declare the system ability, and the init process executes the specified _XXX_**.rc** file to start the process of the particular system ability. Similar to the implementation in C++, the system ability process is started by [the foundationserver module](en-us_topic_0000001078878484.md) in Java.
**Implementing a System Ability in C++**
- **Define the _IXXX_ class for IPC.**
This _IXXX_ class is used to define the functions for the system ability to provide specific capabilities. To define this class, implement the **IRemoteBroker** interface provided by OpenHarmony for inter-process communication \(IPC\). In addition, implement the **DECLARE\_INTERFACE\_DESCRIPTOR\(_XXX_\)** that uniquely identifies this class. The identifier is used for purposes such as IPC communication verification.
The following example shows how to define the **IListenAbility** class for testing in the Distributed Scheduler subsystem:
```
namespace OHOS {
class IListenAbility : public IRemoteBroker {
public:
virtual int AddVolume(int volume) = 0;
public:
enum {
ADD_VOLUME = 1,
};
public:
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.test.IListenAbility");
};
}
```
- **Define the _XXX_Proxy class for client communication.**
```
namespace OHOS {
class ListenAbilityProxy : public IRemoteProxy<IListenAbility> {
public:
int AddVolume(int volume);
explicit ListenAbilityProxy(const sptr<IRemoteObject>& impl)
: IRemoteProxy<IListenAbility>(impl)
{
}
private:
static inline BrokerDelegator<ListenAbilityProxy> delegator_;
};
} // namespace OHOS
```
- **Define the _XXX_Stub class for server communication.**
```
namespace OHOS {
int32_t ListenAbilityStub::OnRemoteRequest(uint32_t code,
MessageParcel& data, MessageParcel &reply, MessageOption &option)
{
switch (code) {
case ADD_VOLUME: {
return reply.WriteInt32(AddVolume(data.ReadInt32()));
}
default:
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
}
}
```
- **Implement a system ability.**
```
namespace {
constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, 0xD001800, "SA_TST"};
}
REGISTER_SYSTEM_ABILITY_BY_ID(ListenAbility, DISTRIBUTED_SCHED_TEST_LISTEN_ID, true);
ListenAbility::ListenAbility(int32_t saId, bool runOnCreate) : SystemAbility(saId, runOnCreate)
{
HiLog::Info(LABEL, ":%s called", __func__);
HiLog::Info(LABEL, "ListenAbility()");
}
ListenAbility::~ListenAbility()
{
HiLog::Info(LABEL, "~ListenAbility()");
}
int ListenAbility::AddVolume(int volume)
{
pid_t current = getpid();
HiLog::Info(LABEL, "ListenAbility::AddVolume volume = %d, pid = %d.", volume, current);
return (volume + 1);
}
void ListenAbility::OnDump()
{
}
void ListenAbility::OnStart()
{
HiLog::Info(LABEL, "ListenAbility::OnStart()");
HiLog::Info(LABEL, "ListenAbility:%s called:-----Publish------", __func__);
bool res = Publish(this);
if (res) {
HiLog::Error(LABEL, "ListenAbility: res == false");
}
HiLog::Info(LABEL, "ListenAbility:%s called:AddAbilityListener_OS_TST----beg-----", __func__);
AddSystemAbilityListener(DISTRIBUTED_SCHED_TEST_OS_ID);
HiLog::Info(LABEL, "ListenAbility:%s called:AddAbilityListener_OS_TST----end-----", __func__);
HiLog::Info(LABEL, "ListenAbility:%s called:StopAbility_OS_TST----beg-----", __func__);
StopAbility(DISTRIBUTED_SCHED_TEST_OS_ID);
HiLog::Info(LABEL, "ListenAbility:%s called:StopAbility_OS_TST----end-----", __func__);
return;
}
void ListenAbility::OnStop()
{
}
```
- **Configure the system ability.**
If the system ability is implemented in C++, you must define a profile for it so that it can be loaded and registered. The configuration procedure is as follows:
Create a folder named **sa\_profile** in the root directory of the subsystem. Then, create two files in this folder, including an XML file prefixed with the service ID of the system ability and a **BUILD.gn** file.
Sample _serviceid_**.xml** file:
```
<?xml version="1.0" encoding="UTF-8"?>
<info>
<process>listen_test</process>
<systemability>
<name>serviceid</name>
<libpath>/system/lib64/liblistentest.z.so</libpath>
<run-on-create>true</run-on-create>
<distributed>false</distributed>
<dump-level>1</dump-level>
</systemability>
</info>
```
Sample **BUILD.gn** file:
```
import("//build/ohos/sa_profile/sa_profile.gni")
ohos_sa_profile("xxx_sa_profile") {
sources = [
"serviceid.xml"
]
subsystem_name = "distributedschedule"
}
```
>![](public_sys-resources/icon-note.gif) **NOTE:**
>1. Set the **process** tag to the name of the process where the system ability will run. This tag is mandatory.
>2. Add only one **systemability** node in the profile of a system ability. If multiple **systemability** nodes are added, the building fails.
>3. Set the **name** tag to the service ID registered in the code for the system ability. This tag is mandatory.
>4. Set the **libpath** tag to the path for loading the system ability. This tag is mandatory.
>5. Set the **run-on-create** tag to **true** if you want to register this system ability with the **samgr** module immediately after the process is started. Set this tag to **false** if you want the system ability to start only when other modules access the system ability. This tag is mandatory.
>6. Set the **distributed** tag to **true** if this system ability allows cross-device access; set it to **false** if it allows IPC only on the local device.
>7. Set the **def-permission** tag to define the permissions, if any, required for the process on another device to access this system ability during cross-device RPC communication when **distributed** is set to **true**. This tag is optional.
>8. Set the **bootphase** tag to define the startup priority of the system ability, which \(from high to low\) can be **BootStartPhase**, **CoreStartPhase**, or **OtherStartPhase** \(default value\). In the same process, the system ability of the **BootStartPhase** priority will be started first, then that of the **CoreStartPhase** priority, and finally the **OtherStartPhase** priority. System abilities of a lower priority can be started and registered only after those of a high priority have all been started and registered. This tag is optional.
>9. Set **dump-level** to **1**, which indicates that the level is supported by the system dumper.
>10. In the **BUILD.gn** file, set **subsystem\_name** to the name of the corresponding subsystem, and add the list of system abilities that need to be configured for the specified subsystem in **sources**. Multiple system abilities can be configured.
After the preceding files are configured and full code building is complete, a **listen\_test.xml** prefixed with the process name will be generated in the **out** directory. The path is **out\\phone-release\\system\\profile\\listen\_test.xml** in this example.
- **Configure the _XXX_.rc file.**
The **_XXX_.rc** configuration file defines the native process startup policy provided by Linux. The **init** process parses the configured **_XXX_.rc** file during device startup.
```
service listen_test /system/bin/sa_main /system/profile/listen_test.xml
class z_core
user system
group system shell
seclabel u:r:xxxx:s0
```
>![](public_sys-resources/icon-note.gif) **NOTE:**
>For details about the implementation of **listen\_ability**, see the code in **test/unittest/common/listen\_ability**.
## Repositories Involved<a name="section1371113476307"></a>
[Distributed Scheduler subsystem](en-us_topic_0000001115719369.md)
[dmsadapter](en-us_topic_0000001124134145.md)
[dmsfwk](en-us_topic_0000001078718754.md)
[foundationserver](en-us_topic_0000001078878484.md)
**[safwk](safwk.md)**
[samgr](en-us_topic_0000001124076649.md)
1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md
2. Gitee 官方博客 [blog.gitee.com](https://blog.gitee.com)
3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解 Gitee 上的优秀开源项目
4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目
5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help)
6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)
Executable
+252
View File
@@ -0,0 +1,252 @@
# safwk组件<a name="ZH-CN_TOPIC_0000001115588558"></a>
- [简介](#section11660541593)
- [目录](#section161941989596)
- [说明](#section1312121216216)
- [接口说明](#section1551164914237)
- [使用说明](#section129654513264)
- [相关仓](#section1371113476307)
## 简介<a name="section11660541593"></a>
在分布式任务调度子系统中safwk组件定义OpenHarmony中SystemAbility的实现方法,并提供启动、注册等接口实现。
## 目录<a name="section161941989596"></a>
```
/foundation/distributedschedule
│── safwk # 组件目录
│ ├── ohos.build # 组件编译脚本
│ ├── interfaces # 对外接口目录
│ ├── services # 组件服务实现
```
## 说明<a name="section1312121216216"></a>
### 接口说明<a name="section1551164914237"></a>
<a name="table775715438253"></a>
<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>
</th>
<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>
</th>
</tr>
</thead>
<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>
</td>
<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>
</td>
</tr>
<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>
</td>
<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>
</td>
</tr>
<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>
</td>
<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>
</td>
</tr>
</tbody>
</table>
### 使用说明<a name="section129654513264"></a>
SystemAbility实现一般采用XXX.rc + profile.xml + libXXX.z.so的方式由init进程执行对应的XXX.rc文件拉起相关SystemAbility进程;
**C++实现SystemAbility**
- **1.1 定义IPC对外接口IXXX**
定义该服务对外提供的能力集合函数,统一继承HOSP提供IPC接口类IRemoteBroker;同时实现该IPC对外接口唯一标识符DECLARE\_INTERFACE\_DESCRIPTOR\(XXX\);该标识符用于IPC通信的校验等目的。
以分布式调度子系统的测试程序IListenAbility服务为例接口定义如下:
```
namespace OHOS {
class IListenAbility : public IRemoteBroker {
public:
virtual int AddVolume(int volume) = 0;
public:
enum {
ADD_VOLUME = 1,
};
public:
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.test.IListenAbility");
};
}
```
- **1.2 定义客户端通信代码XXXProxy**
```
namespace OHOS {
class ListenAbilityProxy : public IRemoteProxy<IListenAbility> {
public:
int AddVolume(int volume);
explicit ListenAbilityProxy(const sptr<IRemoteObject>& impl)
: IRemoteProxy<IListenAbility>(impl)
{
}
private:
static inline BrokerDelegator<ListenAbilityProxy> delegator_;
};
} // namespace OHOS
```
- **1.3** **定义服务端通信代码XXXStub**
```
namespace OHOS {
int32_t ListenAbilityStub::OnRemoteRequest(uint32_t code,
MessageParcel& data, MessageParcel &reply, MessageOption &option)
{
switch (code) {
case ADD_VOLUME: {
return reply.WriteInt32(AddVolume(data.ReadInt32()));
}
default:
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
}
}
```
- **1.4 SystemAbility的实现类**
```
namespace {
constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, 0xD001800, "SA_TST"};
}
REGISTER_SYSTEM_ABILITY_BY_ID(ListenAbility, DISTRIBUTED_SCHED_TEST_LISTEN_ID, true);
ListenAbility::ListenAbility(int32_t saId, bool runOnCreate) : SystemAbility(saId, runOnCreate)
{
HiLog::Info(LABEL, ":%s called", __func__);
HiLog::Info(LABEL, "ListenAbility()");
}
ListenAbility::~ListenAbility()
{
HiLog::Info(LABEL, "~ListenAbility()");
}
int ListenAbility::AddVolume(int volume)
{
pid_t current = getpid();
HiLog::Info(LABEL, "ListenAbility::AddVolume volume = %d, pid = %d.", volume, current);
return (volume + 1);
}
void ListenAbility::OnDump()
{
}
void ListenAbility::OnStart()
{
HiLog::Info(LABEL, "ListenAbility::OnStart()");
HiLog::Info(LABEL, "ListenAbility:%s called:-----Publish------", __func__);
bool res = Publish(this);
if (res) {
HiLog::Error(LABEL, "ListenAbility: res == false");
}
HiLog::Info(LABEL, "ListenAbility:%s called:AddAbilityListener_OS_TST----beg-----", __func__);
AddSystemAbilityListener(DISTRIBUTED_SCHED_TEST_OS_ID);
HiLog::Info(LABEL, "ListenAbility:%s called:AddAbilityListener_OS_TST----end-----", __func__);
HiLog::Info(LABEL, "ListenAbility:%s called:StopAbility_OS_TST----beg-----", __func__);
StopAbility(DISTRIBUTED_SCHED_TEST_OS_ID);
HiLog::Info(LABEL, "ListenAbility:%s called:StopAbility_OS_TST----end-----", __func__);
return;
}
void ListenAbility::OnStop()
{
}
```
- **1.5 SystemAbility配置**
以c++实现的SA必须配置相关System Ability的profile配置文件才会完成SA的加载注册逻辑,否则没有编写profile配置的System Ability不会完成注册。配置方法如下:
在子系统的根目录新建一个以sa\_profile为名的文件夹;然后在此文件夹中新建两个文件:一个以serviceId为前缀的xml文件;另外一个为BUILD.gn文件
serviceid.xml
```
<?xml version="1.0" encoding="UTF-8"?>
<info>
<process>listen_test</process>
<systemability>
<name>serviceid</name>
<libpath>/system/lib64/liblistentest.z.so</libpath>
<run-on-create>true</run-on-create>
<distributed>false</distributed>
<dump-level>1</dump-level>
</systemability>
</info>
```
BUILD.gn
```
import("//build/ohos/sa_profile/sa_profile.gni")
ohos_sa_profile("xxx_sa_profile") {
sources = [
"serviceid.xml"
]
subsystem_name = "distributedschedule"
}
```
>![](public_sys-resources/icon-note.gif) **说明:**
>1. 进程名字即该SystemAbility要运行的进程空间,此字段是必填选项;
>2. 一个SystemAbility配置文件只能配置一个SystemAbility节点;配置多个会导致编译失败,切记
>3. SystemAbility的name为对应的serviceId必须与代码中注册的serviceId保持一致;必配项
>4. libpath为SystemAbility的加载路径,必配项;
>5. run-on-createtrue表示进程启动后即向samgr组件注册该SystemAbility;false表示按需启动,即在其他模块访问到该SystemAbility时启动;必配项;
>6. distributedtrue表示该SystemAbility为分布式SystemAbility,支持跨设备访问;false表示只有本地跨IPC访问;
>7. def-permission:可不设置,含义为当distributed为true时(即支持分布式访问方式时);设备A进程想与设备B进程的该SystemAbility进行跨RPC通信时必须申请的权限,才能正常进行通信
>8. bootphase:可不设置;可以设置的值有三种:BootStartPhase、CoreStartPhase、OtherStartPhase(默认类型),三种优先级依次降低,当同一个进程中,会优先拉起注册配置BootStartPhase的SystemAbility,然后是配置了CoreStartPhase的SystemAbility,最后是OtherStartPhase;当高优先级的SystemAbility全部启动注册完毕才会启动下一级的SystemAbility的注册启动;
>9. dump-level:表示systemdumper支持的level等级,默认配置1就OK;
>10. BUILD.gn中subsystem\_name为相应部件名称;sources表示当前子系统需要配置的SystemAbility列表,可支持配置多个SystemAbility
以上步骤完成后,全量编译代码后会在out路径向生成一个以进程名为前缀的xml文件listen\_test.xml;路径为:out\\phone-release\\system\\profile\\listen\_test.xml
- **1.6 rc配置文件**
rc配置文件为linux提供的native进程拉起策略,为手机在开机启动阶段由init进程解析配置的rc文件进行拉起
```
service listen_test /system/bin/sa_main /system/profile/listen_test.xml
class z_core
user system
group system shell
seclabel u:r:xxxx:s0
```
>![](public_sys-resources/icon-note.gif) **说明:**
>listen\_ability的实现可以参考:test/unittest/common/listen\_ability
## 相关仓<a name="section1371113476307"></a>
分布式任务调度子系统
distributedschedule\_dms\_fwk
**distributedschedule\_safwk**
distributedschedule\_samgr
distributedschedule\_safwk\_lite
hdistributedschedule\_samgr\_lite
distributedschedule\_dms\_fwk\_lite
+60
View File
@@ -0,0 +1,60 @@
# Copyright (c) 2021 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//build/ohos.gni")
import("//build/ohos_var.gni")
################################################################################
config("system_ability_config") {
visibility = [ ":*" ]
include_dirs = [
"//utils/native/base/include",
"//utils/system/safwk/native/include",
"//developtools/liblog",
"../../../services/safwk/include",
"//foundation/distributedschedule/samgr/services/lsamgr/include",
"//foundation/distributedschedule/dmsfwk/utils/native/include",
]
}
ohos_shared_library("system_ability_fwk") {
sources = [
"../../../services/safwk/src/if_system_ability_connection_callback.cpp",
"../../../services/safwk/src/ilocal_ability_manager.cpp",
"../../../services/safwk/src/local_ability_manager.cpp",
"../../../services/safwk/src/local_ability_manager_stub.cpp",
"../../../services/safwk/src/sa_profile_parser.cpp",
"../../../services/safwk/src/samgr_death_recipient.cpp",
"../../../services/safwk/src/system_ability.cpp",
"../../../services/safwk/src/system_ability_connection_callback.cpp",
"../../../services/safwk/src/system_ability_connection_callback_proxy.cpp",
"../../../services/safwk/src/system_ability_connection_callback_stub.cpp",
]
public_configs = [ ":system_ability_config" ]
deps = [ "//utils/native/base:utils" ]
if (is_standard_system) {
external_deps = [
"ipc:ipc_core",
"hiviewdfx_hilog_native:libhilog",
"samgr_L2:samgr_proxy",
]
public_deps = [ "//third_party/libxml2:libxml2" ]
}
part_name = "safwk"
subsystem_name = "distributedschedule"
}
################################################################################
+1
View File
@@ -0,0 +1 @@
../../../services/safwk/include/connection_handler.h
+1
View File
@@ -0,0 +1 @@
../../../services/safwk/include/ilocal_ability_manager.h
+1
View File
@@ -0,0 +1 @@
../../../services/safwk/include/system_ability.h
@@ -0,0 +1 @@
../../../services/safwk/include/system_ability_connection_callback.h
@@ -0,0 +1 @@
../../../services/safwk/include/system_ability_connection_callback_proxy.h
+25
View File
@@ -0,0 +1,25 @@
{
"parts": {
"safwk": {
"variants": ["phone", "wearable"],
"inner_kits": [
{
"header": {
"header_base": "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk",
"header_files": [
"system_ability.h",
"connection_handler.h",
"system_ability_connection_callback.h",
"ilocal_ability_manager.h"
]
},
"name": "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk"
}
],
"module_list": [
"//foundation/distributedschedule/safwk/services/safwk:sa_main"
]
}
},
"subsystem": "distributedschedule"
}
+53
View File
@@ -0,0 +1,53 @@
# Copyright (c) 2021 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//build/ohos.gni")
################################################################################
config("config_safwk") {
visibility = [ ":*" ]
include_dirs = [
"//developtools/liblog",
"//foundation/distributedschedule/safwk/services/safwk/include",
"//utils/native/base/include",
"//utils/system/safwk/native/include",
"//third_party/libxml2/include",
]
}
ohos_executable("sa_main") {
install_enable = true
sources = [ "src/main.cpp" ]
configs = [ ":config_safwk" ]
ldflags = [ "-rdynamic" ]
deps = [
"../../interfaces/innerkits/safwk:system_ability_fwk",
"//utils/native/base:utils",
]
if (is_standard_system) {
external_deps = [
"ipc:ipc_core",
"hiviewdfx_hilog_native:libhilog",
"samgr_L2:samgr_proxy",
]
public_deps = [ "//third_party/libxml2:libxml2" ]
}
part_name = "safwk"
subsystem_name = "distributedschedule"
}
################################################################################
+30
View File
@@ -0,0 +1,30 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SYSTEM_ABILITY_CONNECTION_HANDLER_H_
#define SYSTEM_ABILITY_CONNECTION_HANDLER_H_
#include "iremote_object.h"
namespace OHOS {
class ConnectionHandler {
public:
virtual ~ConnectionHandler() = default;
virtual void OnConnectedSystemAbility(const sptr<IRemoteObject>& connectionCallback) = 0;
virtual void OnDisConnectedSystemAbility(const std::u16string& name) = 0;
};
} // namespace OHOS
#endif // SYSTEM_ABILITY_CONNECTION_HANDLER_H_
+43
View File
@@ -0,0 +1,43 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SAFWK_ILOCAL_ABILITY_MANAGER_H
#define SAFWK_ILOCAL_ABILITY_MANAGER_H
#include <string>
namespace OHOS {
class ILocalAbilityManagerKit {
public:
/**
* Abstract class, all functions implement in the derived class.
*
* @return Returns the only one derived class object.
*/
static ILocalAbilityManagerKit& GetInstance();
/**
* Start System Ability.
*
* @param profilePath xml parh of the SAProcess.
*/
virtual void DoStartSAProcess(const std::string& profilePath) = 0;
protected:
ILocalAbilityManagerKit() = default;
virtual ~ILocalAbilityManagerKit() = default;
};
} // namespace OHOS
#endif // SAFWK_ILOCAL_ABILITY_MANAGER_H
+115
View File
@@ -0,0 +1,115 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef LOCAL_ABILITY_MANAGER_H
#define LOCAL_ABILITY_MANAGER_H
#include <string>
#include <map>
#include <list>
#include <unistd.h>
#include <condition_variable>
#include <shared_mutex>
#include "local_ability_manager_stub.h"
#include "system_ability.h"
#include "thread_pool.h"
#include "sa_profile_parser.h"
#include "ilocal_ability_manager.h"
#include "single_instance.h"
namespace OHOS {
// Check all dependencies's availability before the timeout period ended, [200, 60000].
const int32_t MIN_DEPENDENCY_TIMEOUT = 200;
const int32_t MAX_DEPENDENCY_TIMEOUT = 60000;
const int32_t DEFAULT_DEPENDENCY_TIMEOUT = 6000;
class LocalAbilityManager : public LocalAbilityManagerStub, public ILocalAbilityManagerKit {
DECLARE_SINGLE_INSTANCE_BASE(LocalAbilityManager);
public:
bool Run();
public:
bool InitializeSaProfiles();
bool AddAbility(SystemAbility* ability);
bool RemoveAbility(int32_t systemAbilityId);
SystemAbility* GetAbility(int32_t systemAbilityId);
bool GetRunningStatus(int32_t systemAbilityId);
bool SaveAbilityListener(int32_t systemAbilityId, int32_t listenerSaId);
bool DeleteAbilityListener(int32_t systemAbilityId, int32_t listenerSaId);
bool StartAllAddAbilityListener();
bool NotifyAbilityListener(int32_t systemAbilityId, int32_t listenerSaId, int32_t code);
bool NotifyAbilityListener(int32_t systemAbilityId, int32_t listenerSaId,
const std::string& deviceId, int32_t code);
bool InitAddSystemAbilityListener(int32_t systemAbilityId, int32_t listenerSaId);
bool AddSystemAbilityListener(int32_t systemAbilityId, int32_t listenerSaId);
bool RemoveSystemAbilityListener(int32_t systemAbilityId, int32_t listenerSaId);
bool FindAndNotifyAbilityListeners(int32_t systemAbilityId, const std::string& deviceId, int32_t code);
std::vector<std::u16string> CheckDependencyStatus(const std::vector<std::u16string>& dependSas);
void StartSystemAbilityTask(SystemAbility* sa);
bool CheckSystemAbilityManagerReady();
bool InitSystemAbilityProfiles(const std::string& profilePath);
void ClearResource();
void StartOndemandSystemAbility(int32_t systemAbilityId);
bool HandoffAbilityAfter(const std::u16string& begin, const std::u16string& after) override;
bool HandoffAbilityBegin(int32_t systemAbilityId) override;
bool StartAbility(int32_t systemAbilityId) override;
bool StopAbility(int32_t systemAbilityId) override;
bool OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId = "") override;
bool OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId = "") override;
bool Debug(int32_t systemAbilityId) override;
bool Test(int32_t systemAbilityId) override;
bool SADump(int32_t systemAbilityId) override;
void StartAbilityAsyn(int32_t systemAbilityId) override;
bool RecycleOndemandSystemAbility(int32_t systemAbilityId) override;
void DoStartSAProcess(const std::string& profilePath) override;
bool ReRegisterSA();
private:
LocalAbilityManager();
~LocalAbilityManager();
bool AddLocalAbilityManager(const std::string& localAbilityMgrName);
void RegisterOnDemandSystemAbility();
void FindAndStartPhaseTasks();
void CreateDirectories();
void AddSamgrDeathRecipient();
void StartPhaseTasks(const std::list<SystemAbility*>& startTasks);
std::map<int32_t, SystemAbility*> abilityMap_;
std::map<uint32_t, std::list<SystemAbility*>> abilityPhaseMap_;
std::shared_mutex abilityMapLock_;
sptr<LocalAbilityManager> localAbilityManager_;
// Thread pool used to start system abilities in parallel.
ThreadPool pool_;
// Thread pool used to start ondemand system abilities in parallel.
ThreadPool ondemandPool_;
// Max task number in pool is 20.
const int32_t MAX_TASK_NUMBER = 20;
// Check dependent sa status every 50 ms, it equals 50000us.
const int32_t CHECK_DEPENDENT_SA_PERIOD = 50000;
pid_t currentPid_ = 0;
std::map<int32_t, std::vector<int32_t>> listenerMap_;
std::shared_ptr<SaProfileParser> profileParser_;
std::condition_variable startPhaseCV_;
std::mutex startPhaseLock_;
int32_t startTaskNum_ = 0;
};
}
#endif
+53
View File
@@ -0,0 +1,53 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef LOCAL_ABILITY_MANAGER_STUB_H_
#define LOCAL_ABILITY_MANAGER_STUB_H_
#include <map>
#include "if_local_ability_manager.h"
namespace OHOS {
class LocalAbilityManagerStub : public IRemoteStub<ILocalAbilityManager> {
public:
LocalAbilityManagerStub();
~LocalAbilityManagerStub() = default;
int32_t OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override;
protected:
static bool CheckInputSysAbilityId(int32_t systemAbilityId);
private:
int32_t DebugInner(MessageParcel& data, MessageParcel& reply);
int32_t TestInner(MessageParcel& data, MessageParcel& reply);
int32_t DumpInner(MessageParcel& data, MessageParcel& reply);
int32_t HandOffAbilityAfterInner(MessageParcel& data, MessageParcel& reply);
int32_t HandOffAbilityBeginInner(MessageParcel& data, MessageParcel& reply);
int32_t StartAbilityInner(MessageParcel& data, MessageParcel& reply);
int32_t StopAbilityInner(MessageParcel& data, MessageParcel& reply);
int32_t OnAddSystemAbilityInner(MessageParcel& data, MessageParcel& reply);
int32_t OnRemoveSystemAbilityInner(MessageParcel& data, MessageParcel& reply);
int32_t StartAbilityAsyncInner(MessageParcel& data, MessageParcel& reply);
int32_t RecycleOndemandAbilityInner(MessageParcel& data, MessageParcel& reply);
static bool CanRequest();
static bool EnforceInterceToken(MessageParcel& data);
using LocalAbilityManagerStubFunc =
int32_t (LocalAbilityManagerStub::*)(MessageParcel& data, MessageParcel& reply);
std::map<uint32_t, LocalAbilityManagerStubFunc> memberFuncMap_;
};
}
#endif
+47
View File
@@ -0,0 +1,47 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_SA_PROFILE_PARSER_H_
#define OHOS_SA_PROFILE_PARSER_H_
#include <list>
#include <string>
#include "sa_profiles.h"
#include "libxml/parser.h"
#include "libxml/xpath.h"
namespace OHOS {
class SaProfileParser {
public:
~SaProfileParser();
bool ParseSaProfiles(const std::string& profilePath);
const std::list<SaProfile>& GetAllSaProfiles() const;
void ClearResource();
void OpenSo();
void CloseSo(int32_t systemAbilityId);
bool LoadSaLib(int32_t systemAbilityId);
private:
void CloseSo();
void OpenSo(SaProfile& saProfile);
void CloseHandle(SaProfile& saProfile);
bool ParseSystemAbility(const xmlNode& rootNode);
void ParseSAProp(const std::string& nodeName, const std::string& nodeContent, SaProfile& saProfile);
std::list<SaProfile> saProfiles_;
};
} // namespace OHOS
#endif // OHOS_SA_PROFILE_PARSER_H_
+39
View File
@@ -0,0 +1,39 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_SA_PROFILE_H_
#define OHOS_SA_PROFILE_H_
#include <string>
#include <vector>
namespace OHOS {
using DlHandle = void*;
struct SaProfile {
int32_t saId = 0;
std::u16string libPath;
std::vector<std::u16string> dependSa;
int32_t dependTimeout = 0;
bool runOnCreate = false;
bool distributed = false;
int32_t dumpLevel = 0;
std::u16string capability;
std::u16string permission;
std::u16string bootPhase;
DlHandle handle = nullptr;
};
}
#endif
+58
View File
@@ -0,0 +1,58 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SERVICES_SAFWK_NATIVE_INCLUDE_SAM_LOG_H_
#define SERVICES_SAFWK_NATIVE_INCLUDE_SAM_LOG_H_
#include "hilog/log.h"
namespace OHOS {
static constexpr OHOS::HiviewDFX::HiLogLabel SAFWK_LABEL = {
LOG_CORE,
0xD001800,
"SAFWK"
};
#ifdef HILOGF
#undef HILOGF
#endif
#ifdef HILOGE
#undef HILOGE
#endif
#ifdef HILOGW
#undef HILOGW
#endif
#ifdef HILOGI
#undef HILOGI
#endif
#ifdef HILOGD
#undef HILOGD
#endif
#define SAFWK_LOG(level, TAG, fmt, ...) \
HiviewDFX::HiLog::level(SAFWK_LABEL, "%{public}s::%{public}s " fmt, TAG.c_str(), __FUNCTION__, ##__VA_ARGS__)
#define HILOGF(TAG, fmt, ...) SAFWK_LOG(Fatal, TAG, fmt, ##__VA_ARGS__)
#define HILOGE(TAG, fmt, ...) SAFWK_LOG(Error, TAG, fmt, ##__VA_ARGS__)
#define HILOGW(TAG, fmt, ...) SAFWK_LOG(Warn, TAG, fmt, ##__VA_ARGS__)
#define HILOGI(TAG, fmt, ...) SAFWK_LOG(Info, TAG, fmt, ##__VA_ARGS__)
#define HILOGD(TAG, fmt, ...) SAFWK_LOG(Debug, TAG, fmt, ##__VA_ARGS__)
}
#endif
@@ -0,0 +1,30 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_SAMHR_DEATH_RECIPENT_H_
#define OHOS_SAMHR_DEATH_RECIPENT_H_
#include "iremote_object.h"
namespace OHOS {
class SamgrDeathRecipient : public IRemoteObject::DeathRecipient {
public:
void OnRemoteDied(const wptr<IRemoteObject> &remote) override;
SamgrDeathRecipient() = default;
~SamgrDeathRecipient() override = default;
};
} // namespace OHOS
#endif // !defined(OHOS_SAMHR_DEATH_RECIPENT_H_)
+141
View File
@@ -0,0 +1,141 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SYSTEM_ABILITY_H_
#define SYSTEM_ABILITY_H_
#include <string>
#include <map>
#include <vector>
#include <chrono>
#include "iremote_object.h"
namespace OHOS {
#define REGISTER_SYSTEM_ABILITY_BY_ID(abilityClassName, systemAbilityId, runOnCreate) \
const bool abilityClassName##_##RegisterResult = \
SystemAbility::MakeAndRegisterAbility(new abilityClassName(systemAbilityId, runOnCreate));
#define INIT_LISTEN_SYSTEM_ABILITY_BY_ID(abilityClassName, \
abilityClassNameListenerName, systemAbilityId, listenerName) \
const bool abilityClassName##_##abilityClassNameListenerName##_##RegisterResult = \
SystemAbility::InitAddSystemAbilityListener(systemAbilityId, listenerName);
#define DECLEAR_SYSTEM_ABILITY(className) \
public: \
virtual std::string GetClassName() override { \
return #className; \
}
#define DECLEAR_BASE_SYSTEM_ABILITY(className) \
public: \
virtual std::string GetClassName() = 0;
#define DECLARE_SYSTEM_ABILITY(className) \
public: \
virtual std::string GetClassName() override { \
return #className; \
}
#define DECLARE_BASE_SYSTEM_ABILITY(className) \
public: \
virtual std::string GetClassName() = 0;
#define DECLARE_SYSTEM_ABILITY(className) \
public: \
virtual std::string GetClassName() override { \
return #className; \
}
#define DECLARE_BASE_SYSTEM_ABILITY(className) \
public: \
virtual std::string GetClassName() = 0;
class SystemAbility {
DECLARE_BASE_SYSTEM_ABILITY(SystemAbility);
public:
static bool MakeAndRegisterAbility(SystemAbility* systemAbility);
// IntToString adapter interface
static bool InitAddSystemAbilityListener(int32_t systemAbilityId, int32_t listenerSaId);
bool AddSystemAbilityListener(int32_t systemAbilityId, int32_t listenerSaId);
bool AddSystemAbilityListener(int32_t systemAbilityId);
bool RemoveSystemAbilityListener(int32_t systemAbilityId, int32_t listenerSaId);
bool RemoveSystemAbilityListener(int32_t systemAbilityId);
protected:
virtual void OnDump();
virtual void OnDebug();
virtual void OnTest();
virtual void OnStart();
virtual void OnStop();
virtual void OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId,
const sptr<IRemoteObject>& ability);
virtual void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId);
sptr<IRemoteObject> GetSystemAbility(int32_t systemAbilityId);
bool Publish(sptr<IRemoteObject> systemAbility);
void StopAbility(int32_t systemAbilityId);
SystemAbility(bool runOnCreate = false);
SystemAbility(int32_t systemAbilityId, bool runOnCreate = false);
virtual ~SystemAbility();
private:
void Start();
void Stop();
void SADump();
void Debug();
void Test();
int32_t GetSystemAbilitId() const;
void SetLibPath(const std::u16string& libPath);
const std::u16string& GetLibPath() const;
void SetDependSa(const std::vector<std::u16string>& dependSa);
const std::vector<std::u16string>& GetDependSa() const;
void SetRunOnCreate(bool isRunOnCreate);
bool IsRunOnCreate() const;
void SetDistributed(bool isDistributed);
bool GetDistributed() const;
void SetDumpLevel(unsigned int dumpLevel);
unsigned int GetDumpLevel() const;
void SetDependTimeout(int dependTimeout);
int GetDependTimeout() const;
bool GetRunningStatus() const;
void AddToLocal() const;
void DeleteFromLocal() const;
void SetCapability(const std::u16string& capability);
const std::u16string& GetCapability() const;
void SetPermission(const std::u16string& defPerm);
bool RePublish();
friend class LocalAbilityManager;
private:
int32_t saId_ = 0;
std::u16string libPath_;
std::vector<std::u16string> dependSa_;
bool isRunOnCreate_;
bool isDistributed_;
unsigned int dumpLevel_;
int dependTimeout_;
bool isRunning_;
std::u16string capability_;
sptr<IRemoteObject> publishObj_;
std::u16string permission_;
};
}
#endif
@@ -0,0 +1,38 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SYSTEM_ABILITY_CONNECTION_CALLBACK_H_
#define SYSTEM_ABILITY_CONNECTION_CALLBACK_H_
#include "system_ability_connection_callback_stub.h"
#include "connection_handler.h"
namespace OHOS {
class SystemAbilityConnectionCallback : public SystemAbilityConnectionCallbackStub {
public:
explicit SystemAbilityConnectionCallback(std::shared_ptr<ConnectionHandler> handler)
: handler_(handler) {}
~SystemAbilityConnectionCallback() = default;
public:
void OnConnectedSystemAbility(const sptr<IRemoteObject>& connectionCallback);
void OnDisConnectedSystemAbility(int32_t systemAbilityId);
private:
std::shared_ptr<ConnectionHandler> handler_;
};
} // namespace OHOS
#endif // SYSTEM_ABILITY_CONNECTION_CALLBACK_H_
@@ -0,0 +1,39 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SYSTEM_ABILITY_CONNECTION_CALLBACK_PROXY_H_
#define SYSTEM_ABILITY_CONNECTION_CALLBACK_PROXY_H_
#include "if_system_ability_connection_callback.h"
#include "iremote_proxy.h"
#include "ipc_skeleton.h"
namespace OHOS {
class SystemAbilityConnectionCallbackProxy : public IRemoteProxy<ISystemAbilityConnectionCallback> {
public:
explicit SystemAbilityConnectionCallbackProxy(const sptr<IRemoteObject>& impl)
: IRemoteProxy<ISystemAbilityConnectionCallback>(impl) {}
~SystemAbilityConnectionCallbackProxy() = default;
virtual void OnConnectedSystemAbility(const sptr<IRemoteObject>& connectionCallback);
virtual void OnDisConnectedSystemAbility(int32_t systemAbilityId);
private:
static inline BrokerDelegator<SystemAbilityConnectionCallbackProxy> delegator_;
};
} // namespace OHOS
#endif // !defined(SYSTEM_ABILITY_CONNECTION_CALLBACK_PROXY_H_)
@@ -0,0 +1,30 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SYSTEM_ABILITY_CONNECTION_CALLBACK_STUB_H_
#define SYSTEM_ABILITY_CONNECTION_CALLBACK_STUB_H_
#include "if_system_ability_connection_callback.h"
#include "iremote_object.h"
#include "iremote_stub.h"
namespace OHOS {
class SystemAbilityConnectionCallbackStub : public IRemoteStub<ISystemAbilityConnectionCallback> {
public:
int32_t OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override;
};
} // namespace OHOS
#endif // !defined(SYSTEM_ABILITY_CONNECTION_CALLBACK_STUB_H_ )
+34
View File
@@ -0,0 +1,34 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef INTERFACES_INNERKITS_SYSTEM_READY_CALLBACK_H
#define INTERFACES_INNERKITS_SYSTEM_READY_CALLBACK_H
#include "iremote_broker.h"
#include "iremote_object.h"
namespace OHOS {
class SystemReadyCallback : public IRemoteBroker {
public:
virtual void OnSystemReadyNotify() const = 0;
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.SystemReadyCallback");
enum {
ON_SYSTEM_READY_EVENT = 1,
};
};
} // namespace OHOS
#endif // !defined(INTERFACES_INNERKITS_SYSTEM_READY_CALLBACK_H )
@@ -0,0 +1,20 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "if_system_ability_connection_callback.h"
#include "system_ability_connection_callback_proxy.h"
namespace OHOS {
} // namespace OHOS
@@ -0,0 +1,24 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ilocal_ability_manager.h"
#include "local_ability_manager.h"
namespace OHOS {
ILocalAbilityManagerKit& ILocalAbilityManagerKit::GetInstance()
{
return LocalAbilityManager::GetInstance();
}
}; // namespace OHOS
+819
View File
@@ -0,0 +1,819 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "local_ability_manager.h"
#include <chrono>
#include <cinttypes>
#include <iostream>
#include <string>
#include <sys/types.h>
#include <unistd.h>
#include "datetime_ex.h"
#include "errors.h"
#include "ipc_skeleton.h"
#include "iservice_registry.h"
#include "safwk_log.h"
#include "samgr_death_recipient.h"
#include "string_ex.h"
#include "system_ability.h"
namespace OHOS {
using std::u16string;
using std::string;
using std::vector;
namespace {
const string TAG = "LocalAbilityManager";
constexpr int32_t RETRY_TIMES_FOR_ONDEMAND = 10;
constexpr int32_t RETRY_TIMES_FOR_SAMGR = 50;
constexpr std::chrono::milliseconds MILLISECONDS_WAITING_SAMGR_ONE_TIME(200);
constexpr std::chrono::milliseconds MILLISECONDS_WAITING_ONDEMAND_ONE_TIME(100);
const u16string BOOT_START_PHASE = u"BootStartPhase";
const u16string CORE_START_PHASE = u"CoreStartPhase";
constexpr int32_t MAX_SA_STARTUP_TIME = 100;
const string PROFILES_DIR = "/system/profile/";
const string DEFAULT_DIR = "/system/usr/";
enum {
BOOT_START = 1,
CORE_START = 2,
OTHER_START = 3,
};
}
IMPLEMENT_SINGLE_INSTANCE(LocalAbilityManager);
LocalAbilityManager::LocalAbilityManager()
{
currentPid_ = getpid();
profileParser_ = std::make_shared<SaProfileParser>();
ondemandPool_.Start(std::thread::hardware_concurrency());
ondemandPool_.SetMaxTaskNum(MAX_TASK_NUMBER);
}
LocalAbilityManager::~LocalAbilityManager()
{
ondemandPool_.Stop();
}
void LocalAbilityManager::DoStartSAProcess(const std::string& profilePath)
{
if (profilePath.length() > PATH_MAX) {
HILOGE(TAG, "profilePath length too long!");
return;
}
char realProfilePath[PATH_MAX] = {'\0'};
if (realpath(profilePath.c_str(), realProfilePath) == nullptr) {
HILOGE(TAG, "xmlDocName path does not exist!");
return;
}
// pathString must begin with "/system/profile/" or begin with "/system/usr/"
string pathString(realProfilePath);
if (pathString.find(PROFILES_DIR) != 0 && pathString.find(DEFAULT_DIR) != 0) {
HILOGE(TAG, "xmlDoc dir is not matched");
return;
}
bool ret = InitSystemAbilityProfiles(pathString);
if (!ret) {
HILOGW(TAG, "InitSystemAbilityProfiles failed!");
return;
}
ret = CheckSystemAbilityManagerReady();
if (!ret) {
HILOGW(TAG, "CheckSystemAbilityManagerReady failed!");
return;
}
ret = InitializeSaProfiles();
if (!ret) {
HILOGW(TAG, "InitializeSaProfiles failed!");
return;
}
ret = Run();
if (!ret) {
HILOGW(TAG, "Run failed!");
return;
}
IPCSkeleton::JoinWorkThread();
ClearResource();
}
bool LocalAbilityManager::CheckSystemAbilityManagerReady()
{
sptr<ISystemAbilityManager> samgrProxy;
int32_t timeout = RETRY_TIMES_FOR_SAMGR;
constexpr int32_t duration = std::chrono::microseconds(MILLISECONDS_WAITING_SAMGR_ONE_TIME).count();
while (samgrProxy == nullptr) {
HILOGI(TAG, "waiting for samgr...");
if (timeout > 0) {
samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
usleep(duration);
} else {
HILOGE(TAG, "wait for samgr time out (10s)");
return false;
}
timeout--;
}
return true;
}
bool LocalAbilityManager::InitSystemAbilityProfiles(const std::string& profilePath)
{
bool ret = profileParser_->ParseSaProfiles(profilePath);
if (!ret) {
HILOGW(TAG, "ParseSaProfiles failed!");
return false;
}
profileParser_->OpenSo();
return true;
}
void LocalAbilityManager::ClearResource()
{
profileParser_->ClearResource();
}
bool LocalAbilityManager::RecycleOndemandSystemAbility(int32_t systemAbilityId)
{
std::unique_lock<std::shared_mutex> writeLock(abilityMapLock_);
auto iter = abilityMap_.find(systemAbilityId);
if (iter == abilityMap_.end()) {
HILOGW(TAG, "SA:%{public}d not found", systemAbilityId);
return false;
}
auto abilityInstance = iter->second;
if (abilityInstance == nullptr) {
HILOGW(TAG, "SA:%{public}d instance not exist", systemAbilityId);
return false;
}
if (!abilityInstance->isRunning_) {
delete abilityInstance;
abilityInstance = nullptr;
(void)abilityMap_.erase(iter);
}
profileParser_->CloseSo(systemAbilityId);
return true;
}
bool LocalAbilityManager::AddAbility(SystemAbility* ability)
{
if (ability == nullptr) {
HILOGW(TAG, "try to add null ability!");
return false;
}
int32_t saId = ability->GetSystemAbilitId();
std::unique_lock<std::shared_mutex> writeLock(abilityMapLock_);
auto iter = abilityMap_.find(saId);
if (iter != abilityMap_.end()) {
HILOGI(TAG, "try to add exsited ability:%{public}d!", saId);
return false;
}
HILOGI(TAG, "adding SA:%{public}d", saId);
abilityMap_.emplace(saId, ability);
return true;
}
bool LocalAbilityManager::RemoveAbility(int32_t systemAbilityId)
{
if (systemAbilityId <= 0) {
HILOGW(TAG, "invalid systemAbilityId");
return false;
}
std::unique_lock<std::shared_mutex> writeLock(abilityMapLock_);
(void)abilityMap_.erase(systemAbilityId);
return true;
}
bool LocalAbilityManager::SaveAbilityListener(int32_t systemAbilityId, int32_t listenerSaId)
{
HILOGD(TAG, "SA:%{public}d, listenerSA:%{public}d", systemAbilityId, listenerSaId);
if (!CheckInputSysAbilityId(systemAbilityId) || !CheckInputSysAbilityId(listenerSaId)) {
HILOGW(TAG, "SA:%{public}d or listenerSA:%{public}d invalid!", systemAbilityId, listenerSaId);
return false;
}
auto& listenerSaIdList = listenerMap_[systemAbilityId];
auto iter = std::find_if(listenerSaIdList.begin(), listenerSaIdList.end(), [listenerSaId](auto SaId) {
return SaId == listenerSaId;
});
if (iter == listenerSaIdList.end()) {
listenerSaIdList.emplace_back(listenerSaId);
return true;
}
HILOGI(TAG, "SA:%{public}d already exist, listener SA is %{public}d", systemAbilityId, listenerSaId);
return false;
}
bool LocalAbilityManager::DeleteAbilityListener(int32_t systemAbilityId, int32_t listenerSaId)
{
HILOGD(TAG, "SA:%{public}d, listenerSA:%{public}d", systemAbilityId, listenerSaId);
if (!CheckInputSysAbilityId(systemAbilityId) || !CheckInputSysAbilityId(listenerSaId)) {
HILOGW(TAG, "SA:%{public}d or listenerSA:%{public}d invalid!",
systemAbilityId, listenerSaId);
return false;
}
if (listenerMap_.count(systemAbilityId) == 0) {
return false;
}
auto& listenerSaIdList = listenerMap_[systemAbilityId];
for (auto iter = listenerSaIdList.begin(); iter != listenerSaIdList.end();) {
if (*iter == listenerSaId) {
iter = listenerSaIdList.erase(iter);
return true;
} else {
++iter;
}
}
return false;
}
bool LocalAbilityManager::InitAddSystemAbilityListener(int32_t systemAbilityId, int32_t listenerSaId)
{
return SaveAbilityListener(systemAbilityId, listenerSaId);
}
bool LocalAbilityManager::StartAllAddAbilityListener()
{
std::string localAbilityManagerName = "localabilitymanager" + std::to_string(currentPid_);
auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (samgrProxy == nullptr) {
HILOGE(TAG, "failed to get samgrProxy");
return false;
}
HILOGD(TAG, "localAbilityManagerName:%{public}s", localAbilityManagerName.c_str());
for (const auto& [saId, listenerSaIdList] : listenerMap_) {
if (samgrProxy->CheckSystemAbility(saId) != nullptr) {
HILOGI(TAG, "SA:%{public}d already started, localabilitymanager = %{public}s",
saId, localAbilityManagerName.c_str());
std::string deviceId;
if (!samgrProxy->GetDeviceId(deviceId)) {
HILOGE(TAG, "failed to get deviceId");
return false;
}
FindAndNotifyAbilityListeners(saId, deviceId, ON_ADD_SYSTEM_ABILITY_TRANSACTION);
}
int32_t ret = samgrProxy->SubscribeSystemAbility(saId, OHOS::to_utf16(localAbilityManagerName));
if (ret != ERR_NONE) {
HILOGE(TAG, "failed to subscribe SA:%{public}d, localabilitymanager:%{public}s",
saId, localAbilityManagerName.c_str());
}
}
return true;
}
bool LocalAbilityManager::AddSystemAbilityListener(int32_t systemAbilityId, int32_t listenerSaId)
{
HILOGD(TAG, "SA:%{public}d, listenerSA:%{public}d", systemAbilityId, listenerSaId);
if (!CheckInputSysAbilityId(systemAbilityId) || !CheckInputSysAbilityId(listenerSaId)) {
HILOGW(TAG, "SA:%{public}d or listenerSA:%{public}d invalid!",
systemAbilityId, listenerSaId);
return false;
}
auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (samgrProxy == nullptr) {
HILOGE(TAG, "failed to get samgrProxy");
return false;
}
std::string localAbilityManagerName = "localabilitymanager" + std::to_string(currentPid_);
if (!SaveAbilityListener(systemAbilityId, listenerSaId)) {
HILOGE(TAG, "failed to save ability listener");
return false;
}
if (samgrProxy->CheckSystemAbility(systemAbilityId) != nullptr) {
HILOGE(TAG, "SA:%{public}d already start, localabilitymanager:%{public}s", systemAbilityId,
localAbilityManagerName.c_str());
std::string deviceId;
if (!samgrProxy->GetDeviceId(deviceId)) {
HILOGE(TAG, "failed to get deviceId");
return false;
}
NotifyAbilityListener(systemAbilityId, listenerSaId, deviceId, ON_ADD_SYSTEM_ABILITY_TRANSACTION);
}
int32_t ret = samgrProxy->SubscribeSystemAbility(systemAbilityId, OHOS::to_utf16(localAbilityManagerName));
if (ret) {
HILOGE(TAG, "failed to subscribe sa:%{public}d, localabilitymanager:%{public}s", systemAbilityId,
localAbilityManagerName.c_str());
return false;
}
return true;
}
bool LocalAbilityManager::RemoveSystemAbilityListener(int32_t systemAbilityId, int32_t listenerSaId)
{
HILOGD(TAG, "SA:%{public}d, listenerSA:%{public}d", systemAbilityId, listenerSaId);
if (!CheckInputSysAbilityId(systemAbilityId) || !CheckInputSysAbilityId(listenerSaId)) {
HILOGW(TAG, "SA:%{public}d or listenerSA:%{public}d invalid!",
systemAbilityId, listenerSaId);
return false;
}
auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (samgrProxy == nullptr) {
HILOGE(TAG, "failed to get samgrProxy");
return false;
}
std::string localAbilityManagerName = "localabilitymanager" + std::to_string(currentPid_);
if (!DeleteAbilityListener(systemAbilityId, listenerSaId)) {
HILOGE(TAG, "failed to delete ability listener");
return false;
}
int32_t ret = samgrProxy->UnSubscribeSystemAbility(systemAbilityId, to_utf16(localAbilityManagerName));
if (ret) {
HILOGE(TAG, "failed to unsubscribe SA:%{public}d, localAbilityManager:%{public}s",
systemAbilityId, localAbilityManagerName.c_str());
return false;
}
return true;
}
bool LocalAbilityManager::NotifyAbilityListener(int32_t systemAbilityId, int32_t listenerSaId, int32_t code)
{
auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (samgrProxy == nullptr) {
HILOGE(TAG, "failed to get samgrProxy");
return false;
}
std::string deviceId;
if (!samgrProxy->GetDeviceId(deviceId)) {
HILOGE(TAG, "failed to get deviceId");
return false;
}
return NotifyAbilityListener(systemAbilityId, listenerSaId, deviceId, code);
}
bool LocalAbilityManager::NotifyAbilityListener(int32_t systemAbilityId, int32_t listenerSaId,
const std::string& deviceId, int32_t code)
{
HILOGD(TAG, "SA:%{public}d, listenerSA:%{public}d, code:%{public}d", systemAbilityId, listenerSaId, code);
auto ability = GetAbility(listenerSaId);
if (ability == nullptr) {
HILOGE(TAG, "failed to get listener SA:%{public}d", listenerSaId);
return false;
}
auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (samgrProxy == nullptr) {
HILOGE(TAG, "failed to get samgrProxy");
return false;
}
switch (code) {
case ON_ADD_SYSTEM_ABILITY_TRANSACTION: {
HILOGD(TAG, "OnAddSystemAbility, SA:%{public}d", listenerSaId);
sptr<IRemoteObject> saObject = samgrProxy->GetSystemAbility(systemAbilityId);
ability->OnAddSystemAbility(systemAbilityId, deviceId, saObject);
break;
}
case ON_REMOVE_SYSTEM_ABILITY_TRANSACTION: {
HILOGD(TAG, "OnRemoveSystemAbility, SA:%{public}d", listenerSaId);
ability->OnRemoveSystemAbility(systemAbilityId, deviceId);
break;
}
default:
break;
}
return true;
}
bool LocalAbilityManager::FindAndNotifyAbilityListeners(int32_t systemAbilityId,
const std::string& deviceId, int32_t code)
{
HILOGD(TAG, "SA:%{public}d, code:%{public}d", systemAbilityId, code);
auto iter = listenerMap_.find(systemAbilityId);
if (iter != listenerMap_.end()) {
auto& listenerSaIdList = iter->second;
for (auto listenerSaId : listenerSaIdList) {
NotifyAbilityListener(systemAbilityId, listenerSaId, deviceId, code);
}
} else {
HILOGW(TAG, "SA:%{public}d not found", systemAbilityId);
}
return true;
}
bool LocalAbilityManager::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
{
HILOGD(TAG, "SA:%{public}d added", systemAbilityId);
if (!CheckInputSysAbilityId(systemAbilityId)) {
HILOGW(TAG, "SA:%{public}d is invalid!", systemAbilityId);
return false;
}
return FindAndNotifyAbilityListeners(systemAbilityId, deviceId, ON_ADD_SYSTEM_ABILITY_TRANSACTION);
}
bool LocalAbilityManager::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
{
HILOGD(TAG, "SA:%{public}d removed", systemAbilityId);
if (!CheckInputSysAbilityId(systemAbilityId)) {
HILOGW(TAG, "SA:%{public}d is invalid!", systemAbilityId);
return false;
}
return FindAndNotifyAbilityListeners(systemAbilityId, deviceId, ON_REMOVE_SYSTEM_ABILITY_TRANSACTION);
}
bool LocalAbilityManager::StartAbility(int32_t systemAbilityId)
{
HILOGD(TAG, "try to start SA:%{public}d", systemAbilityId);
auto ability = GetAbility(systemAbilityId);
if (ability == nullptr) {
return false;
}
ability->Start();
return true;
}
bool LocalAbilityManager::StopAbility(int32_t systemAbilityId)
{
HILOGD(TAG, "try to stop SA:%{public}d", systemAbilityId);
auto ability = GetAbility(systemAbilityId);
if (ability == nullptr) {
return false;
}
ability->Stop();
return true;
}
bool LocalAbilityManager::HandoffAbilityAfter(const u16string& begin, const u16string& after)
{
return true;
}
bool LocalAbilityManager::HandoffAbilityBegin(int32_t systemAbilityId)
{
return true;
}
SystemAbility* LocalAbilityManager::GetAbility(int32_t systemAbilityId)
{
std::shared_lock<std::shared_mutex> readLock(abilityMapLock_);
auto it = abilityMap_.find(systemAbilityId);
if (it == abilityMap_.end()) {
return nullptr;
}
return it->second;
}
bool LocalAbilityManager::GetRunningStatus(int32_t systemAbilityId)
{
auto ability = GetAbility(systemAbilityId);
if (ability == nullptr) {
return false;
}
return ability->GetRunningStatus();
}
bool LocalAbilityManager::Debug(int32_t systemAbilityId)
{
auto ability = GetAbility(systemAbilityId);
if (ability == nullptr) {
return false;
}
ability->Debug();
return true;
}
bool LocalAbilityManager::Test(int32_t systemAbilityId)
{
auto ability = GetAbility(systemAbilityId);
if (ability == nullptr) {
return false;
}
ability->Test();
return true;
}
bool LocalAbilityManager::SADump(int32_t systemAbilityId)
{
auto ability = GetAbility(systemAbilityId);
if (ability == nullptr) {
return false;
}
ability->SADump();
return true;
}
void LocalAbilityManager::StartOndemandSystemAbility(int32_t systemAbilityId)
{
HILOGI(TAG, "systemAbilityId is %{public}d", systemAbilityId);
bool isExist = profileParser_->LoadSaLib(systemAbilityId);
if (isExist) {
int32_t timeout = RETRY_TIMES_FOR_ONDEMAND;
constexpr int32_t duration = std::chrono::microseconds(MILLISECONDS_WAITING_ONDEMAND_ONE_TIME).count();
{
std::shared_lock<std::shared_mutex> readLock(abilityMapLock_);
auto it = abilityMap_.find(systemAbilityId);
while (it == abilityMap_.end()) {
HILOGI(TAG, "waiting for SA:%{public}d...", systemAbilityId);
if (timeout > 0) {
usleep(duration);
it = abilityMap_.find(systemAbilityId);
} else {
HILOGE(TAG, "waiting for SA:%{public}d time out (1s)", systemAbilityId);
return;
}
timeout--;
}
}
if (!StartAbility(systemAbilityId)) {
HILOGE(TAG, "failed to start ability:%{public}d", systemAbilityId);
}
} else {
HILOGW(TAG, "SA:%{public}d not found", systemAbilityId);
}
}
void LocalAbilityManager::StartAbilityAsyn(int32_t systemAbilityId)
{
auto task = std::bind(&LocalAbilityManager::StartOndemandSystemAbility, this, systemAbilityId);
ondemandPool_.AddTask(task);
}
bool LocalAbilityManager::InitializeSaProfiles()
{
HILOGD(TAG, "initializing sa profiles...");
auto& saProfileList = profileParser_->GetAllSaProfiles();
if (saProfileList.empty()) {
HILOGW(TAG, "sa profile is empty");
return false;
}
std::unique_lock<std::shared_mutex> writeLock(abilityMapLock_);
for (const auto& saProfile : saProfileList) {
auto iterProfile = abilityMap_.find(saProfile.saId);
if (iterProfile == abilityMap_.end()) {
HILOGW(TAG, "SA:%{public}d not found", saProfile.saId);
continue;
}
auto systemAbility = iterProfile->second;
if (systemAbility == nullptr) {
HILOGW(TAG, "SA:%{public}d is null", saProfile.saId);
continue;
}
HILOGI(TAG, "set profile attributes for SA:%{public}d", saProfile.saId);
systemAbility->SetLibPath(saProfile.libPath);
systemAbility->SetRunOnCreate(saProfile.runOnCreate);
systemAbility->SetDependSa(saProfile.dependSa);
systemAbility->SetDependTimeout(saProfile.dependTimeout);
systemAbility->SetDistributed(saProfile.distributed);
systemAbility->SetDumpLevel(saProfile.dumpLevel);
systemAbility->SetCapability(saProfile.capability);
systemAbility->SetPermission(saProfile.permission);
uint32_t phase = OTHER_START;
if (saProfile.bootPhase == BOOT_START_PHASE) {
phase = BOOT_START;
} else if (saProfile.bootPhase == CORE_START_PHASE) {
phase = CORE_START;
}
auto& saList = abilityPhaseMap_[phase];
saList.emplace_back(systemAbility);
}
return true;
}
vector<u16string> LocalAbilityManager::CheckDependencyStatus(const vector<u16string>& dependSa)
{
auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (samgrProxy == nullptr) {
HILOGW(TAG, "failed to get samgrProxy");
return dependSa;
}
vector<u16string> checkSaStatusResult;
for (const auto& saName : dependSa) {
int32_t systemAbilityId = atoi(Str16ToStr8(saName).c_str());
if (CheckInputSysAbilityId(systemAbilityId)) {
sptr<IRemoteObject> saObject = samgrProxy->CheckSystemAbility(systemAbilityId);
if (saObject == nullptr) {
checkSaStatusResult.emplace_back(saName);
}
} else {
HILOGW(TAG, "dependency's id:%{public}s is invalid", Str16ToStr8(saName).c_str());
}
}
return checkSaStatusResult;
}
void LocalAbilityManager::StartSystemAbilityTask(SystemAbility* ability)
{
if (ability != nullptr) {
HILOGD(TAG, "StartSystemAbility is called for %{public}d", ability->GetSystemAbilitId());
if (ability->GetDependSa().empty()) {
ability->Start();
} else {
int64_t start = GetTickCount();
int64_t dependTimeout = ability->GetDependTimeout();
while (!CheckDependencyStatus(ability->GetDependSa()).empty()) {
int64_t end = GetTickCount();
int64_t duration = ((end >= start) ? (end - start) : (INT64_MAX - end + start));
if (duration < dependTimeout) {
usleep(CHECK_DEPENDENT_SA_PERIOD);
} else {
break;
}
}
vector<u16string> unpreparedDeps = CheckDependencyStatus(ability->GetDependSa());
if (unpreparedDeps.empty()) {
ability->Start();
} else {
for (const auto& unpreparedDep : unpreparedDeps) {
HILOGI(TAG, "%{public}d's dependency:%{public}s not started in %{public}d ms",
ability->GetSystemAbilitId(), Str16ToStr8(unpreparedDep).c_str(), ability->GetDependTimeout());
}
}
}
}
std::lock_guard<std::mutex> lock(startPhaseLock_);
if (startTaskNum_ > 0) {
--startTaskNum_;
}
startPhaseCV_.notify_one();
}
void LocalAbilityManager::RegisterOnDemandSystemAbility()
{
auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (samgrProxy == nullptr) {
HILOGI(TAG, "failed to get samgrProxy");
return;
}
std::string localAbilityManagerName = "localabilitymanager" + std::to_string(currentPid_);
auto& saProfileList = profileParser_->GetAllSaProfiles();
for (const auto& saProfile : saProfileList) {
HILOGD(TAG, "register ondemand ability:%{public}d to samgr", saProfile.saId);
if (!saProfile.runOnCreate) {
int32_t ret = samgrProxy->AddOnDemandSystemAbilityInfo(saProfile.saId,
OHOS::to_utf16(localAbilityManagerName));
if (ret != ERR_OK) {
HILOGI(TAG, "failed to add ability info for on-demand SA:%{public}d", saProfile.saId);
}
}
}
}
void LocalAbilityManager::AddSamgrDeathRecipient()
{
sptr<IRemoteObject> registryObject = SystemAbilityManagerClient::GetInstance().GetRegistryRemoteObject();
if (registryObject == nullptr) {
HILOGD(TAG, "failed to get registry object");
return;
}
auto recipient = sptr<IRemoteObject::DeathRecipient>(new SamgrDeathRecipient());
bool result = registryObject->AddDeathRecipient(recipient);
HILOGD(TAG, "%{public}s to add death recipient", result ? "success" : "failed");
}
void LocalAbilityManager::StartPhaseTasks(const std::list<SystemAbility*>& systemAbilityList)
{
if (systemAbilityList.empty()) {
return;
}
for (auto systemAbility : systemAbilityList) {
if (systemAbility != nullptr && systemAbility->IsRunOnCreate()) {
HILOGD(TAG, "add phase task for SA:%{public}d", systemAbility->GetSystemAbilitId());
std::lock_guard<std::mutex> autoLock(startPhaseLock_);
++startTaskNum_;
auto task = std::bind(&LocalAbilityManager::StartSystemAbilityTask, this, systemAbility);
pool_.AddTask(task);
}
}
int64_t begin = GetTickCount();
HILOGI(TAG, "start waiting for all tasks!");
std::unique_lock<std::mutex> lck(startPhaseLock_);
auto now = std::chrono::system_clock::now();
if (!startPhaseCV_.wait_until(lck, now + std::chrono::seconds(MAX_SA_STARTUP_TIME),
[this] () { return startTaskNum_ == 0; })) {
HILOGW(TAG, "start timeout!");
}
startTaskNum_ = 0;
int64_t end = GetTickCount();
HILOGI(TAG, "start tasks finished and spend %{public}" PRId64 " ms", (end - begin));
}
void LocalAbilityManager::FindAndStartPhaseTasks()
{
std::shared_lock<std::shared_mutex> readLock(abilityMapLock_);
for (uint32_t startType = BOOT_START; startType <= OTHER_START; ++startType) {
auto iter = abilityPhaseMap_.find(startType);
if (iter != abilityPhaseMap_.end()) {
StartPhaseTasks(iter->second);
}
}
}
bool LocalAbilityManager::Run()
{
HILOGD(TAG, "local ability manager is running...");
std::string localAbilityManagerName = "localabilitymanager" + std::to_string(currentPid_);
bool addResult = AddLocalAbilityManager(localAbilityManagerName);
if (!addResult) {
HILOGE(TAG, "failed to add local abilitymanager");
return false;
}
HILOGI(TAG, "success to add local ability manager:%{public}s", localAbilityManagerName.c_str());
AddSamgrDeathRecipient();
bool startResult = StartAllAddAbilityListener();
HILOGI(TAG, "%{public}s to start all Listeners for ability add", startResult ? "success" : "failed");
uint32_t concurrentThreads = std::thread::hardware_concurrency();
HILOGD(TAG, "concurrentThreads is %{public}d", concurrentThreads);
pool_.Start(concurrentThreads);
pool_.SetMaxTaskNum(MAX_TASK_NUMBER);
FindAndStartPhaseTasks();
RegisterOnDemandSystemAbility();
pool_.Stop();
return true;
}
bool LocalAbilityManager::AddLocalAbilityManager(const std::string& localAbilityMgrName)
{
auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (samgrProxy == nullptr) {
HILOGE(TAG, "failed to get samgrProxy");
return false;
}
if (localAbilityManager_ == nullptr) {
localAbilityManager_ = this;
}
int32_t ret = samgrProxy->AddLocalAbilityManager(OHOS::to_utf16(localAbilityMgrName), localAbilityManager_);
return ret == ERR_OK;
}
bool LocalAbilityManager::ReRegisterSA()
{
HILOGI(TAG, "try to register SA again...");
auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (samgrProxy == nullptr) {
HILOGE(TAG, "failed to get samgrProxy");
return false;
}
std::string localAbilityManagerName = "localabilitymanager" + std::to_string(currentPid_);
int32_t ret = samgrProxy->AddLocalAbilityManager(OHOS::to_utf16(localAbilityManagerName), this);
HILOGD(TAG, "%{public}s to add local ability manager", (ret == ERR_OK) ? "success" : "failed");
std::shared_lock<std::shared_mutex> readLock(abilityMapLock_);
for (const auto& [abilityId, ability] : abilityMap_) {
if (ability != nullptr) {
HILOGD(TAG, "%{public}s to republish ability:%{public}d", ability->RePublish() ? "success" : "failed",
abilityId);
}
}
return true;
}
}
+315
View File
@@ -0,0 +1,315 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "local_ability_manager_stub.h"
#include "errors.h"
#include "ipc_skeleton.h"
#include "ipc_types.h"
#include "safwk_log.h"
#include "system_ability_definition.h"
using namespace std;
using namespace OHOS::HiviewDFX;
namespace OHOS {
namespace {
const std::string TAG = "LocalAbilityManagerStub";
constexpr int32_t UID_ROOT = 0;
constexpr int32_t UID_SYSTEM = 1000;
const std::u16string LOCAL_ABILITY_MANAGER_INTERFACE_TOKEN = u"ohos.localabilitymanager.accessToken";
}
LocalAbilityManagerStub::LocalAbilityManagerStub()
{
memberFuncMap_[DEBUG_TRANSACTION] =
&LocalAbilityManagerStub::DebugInner;
memberFuncMap_[TEST_TRANSACTION] =
&LocalAbilityManagerStub::TestInner;
memberFuncMap_[DUMP_TRANSACTION] =
&LocalAbilityManagerStub::DumpInner;
memberFuncMap_[HAND_OFF_ABILITY_AFTER_TRANSACTION] =
&LocalAbilityManagerStub::HandOffAbilityAfterInner;
memberFuncMap_[HAND_OFF_ABILITY_BEGIN_TRANSACTION] =
&LocalAbilityManagerStub::HandOffAbilityBeginInner;
memberFuncMap_[START_ABILITY_TRANSACTION] =
&LocalAbilityManagerStub::StartAbilityInner;
memberFuncMap_[STOP_ABILITY_TRANSACTION] =
&LocalAbilityManagerStub::StopAbilityInner;
memberFuncMap_[ON_ADD_SYSTEM_ABILITY_TRANSACTION] =
&LocalAbilityManagerStub::OnAddSystemAbilityInner;
memberFuncMap_[ON_REMOVE_SYSTEM_ABILITY_TRANSACTION] =
&LocalAbilityManagerStub::OnRemoveSystemAbilityInner;
memberFuncMap_[START_ABILITY_ASYN_TRANSACTION] =
&LocalAbilityManagerStub::StartAbilityAsyncInner;
memberFuncMap_[RECYCLE_SYSTEM_ABILITY_TRANSACTION] =
&LocalAbilityManagerStub::RecycleOndemandAbilityInner;
}
int32_t LocalAbilityManagerStub::OnRemoteRequest(uint32_t code,
MessageParcel& data, MessageParcel& reply, MessageOption& option)
{
HILOGI(TAG, "code:%{public}d, flags:%{public}d", code, option.GetFlags());
if (!CanRequest()) {
HILOGW(TAG, "permission denied!");
return ERR_PERMISSION_DENIED;
}
if (!EnforceInterceToken(data)) {
HILOGW(TAG, "check interface token failed!");
return ERR_PERMISSION_DENIED;
}
auto iter = memberFuncMap_.find(code);
if (iter != memberFuncMap_.end()) {
auto memberFunc = iter->second;
if (memberFunc != nullptr) {
return (this->*memberFunc)(data, reply);
}
}
HILOGW(TAG, "unknown request code!");
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
int32_t LocalAbilityManagerStub::DebugInner(MessageParcel& data, MessageParcel& reply)
{
int32_t saId = data.ReadInt32();
if (!CheckInputSysAbilityId(saId)) {
HILOGW(TAG, "read saId failed!");
return ERR_NULL_OBJECT;
}
bool result = Debug(saId);
HILOGI(TAG, "%{public}s to debug", result ? "success" : "failed");
bool ret = reply.WriteBool(result);
if (!ret) {
HILOGW(TAG, "write reply failed!");
return ERR_FLATTEN_OBJECT;
}
return ERR_NONE;
}
int32_t LocalAbilityManagerStub::TestInner(MessageParcel& data, MessageParcel& reply)
{
int32_t saId = data.ReadInt32();
if (!CheckInputSysAbilityId(saId)) {
HILOGW(TAG, "read saId failed!");
return ERR_NULL_OBJECT;
}
bool result = Test(saId);
HILOGI(TAG, "%{public}s to test", result ? "success" : "failed");
bool ret = reply.WriteBool(result);
if (!ret) {
HILOGW(TAG, "write reply failed!");
return ERR_FLATTEN_OBJECT;
}
return ERR_NONE;
}
int32_t LocalAbilityManagerStub::DumpInner(MessageParcel& data, MessageParcel& reply)
{
int32_t saId = data.ReadInt32();
if (!CheckInputSysAbilityId(saId)) {
HILOGW(TAG, "read saId failed!");
return ERR_NULL_OBJECT;
}
bool result = SADump(saId);
HILOGI(TAG, "%{public}s to dump", result ? "success" : "failed");
bool ret = reply.WriteBool(result);
if (!ret) {
HILOGW(TAG, "write reply failed!");
return ERR_FLATTEN_OBJECT;
}
return ERR_NONE;
}
int32_t LocalAbilityManagerStub::HandOffAbilityAfterInner(MessageParcel& data, MessageParcel& reply)
{
std::u16string begin = data.ReadString16();
if (begin.empty()) {
HILOGW(TAG, "read begin failed!");
return ERR_NULL_OBJECT;
}
std::u16string after = data.ReadString16();
if (after.empty()) {
HILOGW(TAG, "read after failed!");
return ERR_NULL_OBJECT;
}
bool result = HandoffAbilityAfter(begin, after);
HILOGI(TAG, "%{public}s to handoff ability after", result ? "success" : "failed");
bool ret = reply.WriteBool(result);
if (!ret) {
HILOGW(TAG, "write reply failed!");
return ERR_FLATTEN_OBJECT;
}
return ERR_NONE;
}
int32_t LocalAbilityManagerStub::HandOffAbilityBeginInner(MessageParcel& data, MessageParcel& reply)
{
int32_t saId = data.ReadInt32();
if (!CheckInputSysAbilityId(saId)) {
HILOGW(TAG, "read saId failed!");
return ERR_NULL_OBJECT;
}
bool result = HandoffAbilityBegin(saId);
HILOGI(TAG, "%{public}s to handoff ability begin", result ? "success" : "failed");
bool ret = reply.WriteBool(result);
if (!ret) {
HILOGW(TAG, "write reply failed!");
return ERR_FLATTEN_OBJECT;
}
return ERR_NONE;
}
int32_t LocalAbilityManagerStub::StartAbilityInner(MessageParcel& data, MessageParcel& reply)
{
int32_t saId = data.ReadInt32();
if (!CheckInputSysAbilityId(saId)) {
HILOGW(TAG, "read saId failed!");
return ERR_NULL_OBJECT;
}
bool result = StartAbility(saId);
HILOGI(TAG, "%{public}s to start ability", result ? "success" : "failed");
bool ret = reply.WriteBool(result);
if (!ret) {
HILOGW(TAG, "write reply failed!");
return ERR_FLATTEN_OBJECT;
}
return ERR_NONE;
}
int32_t LocalAbilityManagerStub::StopAbilityInner(MessageParcel& data, MessageParcel& reply)
{
int32_t saId = data.ReadInt32();
if (!CheckInputSysAbilityId(saId)) {
HILOGW(TAG, "read saId failed!");
return ERR_NULL_OBJECT;
}
bool result = StopAbility(saId);
HILOGI(TAG, "%{public}s to stop ability", result ? "success" : "failed");
bool ret = reply.WriteBool(result);
if (!ret) {
HILOGW(TAG, "write reply failed!");
return ERR_FLATTEN_OBJECT;
}
return ERR_NONE;
}
int32_t LocalAbilityManagerStub::OnAddSystemAbilityInner(MessageParcel& data, MessageParcel& reply)
{
int32_t saId = data.ReadInt32();
if (!CheckInputSysAbilityId(saId)) {
HILOGW(TAG, "read saId failed!");
return ERR_NULL_OBJECT;
}
const std::string& deviceId = data.ReadString();
if (deviceId.empty()) {
HILOGW(TAG, "read deviceId failed!");
return ERR_NULL_OBJECT;
}
bool result = OnAddSystemAbility(saId, deviceId);
HILOGI(TAG, "%{public}s to notify SA add", result ? "success" : "failed");
bool ret = reply.WriteBool(result);
if (!ret) {
HILOGW(TAG, "write reply failed!");
return ERR_FLATTEN_OBJECT;
}
return ERR_NONE;
}
int32_t LocalAbilityManagerStub::OnRemoveSystemAbilityInner(MessageParcel& data, MessageParcel& reply)
{
int32_t saId = data.ReadInt32();
if (!CheckInputSysAbilityId(saId)) {
HILOGW(TAG, "read saId failed!");
return ERR_NULL_OBJECT;
}
const std::string& deviceId = data.ReadString();
if (deviceId.empty()) {
HILOGW(TAG, "read deviceId failed!");
return ERR_NULL_OBJECT;
}
bool result = OnRemoveSystemAbility(saId, deviceId);
HILOGI(TAG, "%{public}s to notify SA add", result ? "success" : "failed");
bool ret = reply.WriteBool(result);
if (!ret) {
HILOGW(TAG, "write reply failed!");
return ERR_FLATTEN_OBJECT;
}
return ERR_NONE;
}
int32_t LocalAbilityManagerStub::StartAbilityAsyncInner(MessageParcel& data, MessageParcel& reply)
{
int32_t saId = data.ReadInt32();
if (!CheckInputSysAbilityId(saId)) {
HILOGW(TAG, "read saId failed!");
return ERR_NULL_OBJECT;
}
StartAbilityAsyn(saId);
return ERR_NONE;
}
int32_t LocalAbilityManagerStub::RecycleOndemandAbilityInner(MessageParcel& data, MessageParcel& reply)
{
int32_t saId = data.ReadInt32();
if (!CheckInputSysAbilityId(saId)) {
HILOGW(TAG, "read saId failed!");
return ERR_NULL_OBJECT;
}
bool result = RecycleOndemandSystemAbility(saId);
HILOGI(TAG, "%{public}s to recycle on-demand SA", result ? "success" : "failed");
bool ret = reply.WriteBool(result);
if (!ret) {
HILOGW(TAG, "write reply failed!");
return ERR_FLATTEN_OBJECT;
}
return ERR_NONE;
}
bool LocalAbilityManagerStub::CheckInputSysAbilityId(int32_t systemAbilityId)
{
return (systemAbilityId >= FIRST_SYS_ABILITY_ID) && (systemAbilityId <= LAST_SYS_ABILITY_ID);
}
bool LocalAbilityManagerStub::CanRequest()
{
auto callingUid = IPCSkeleton::GetCallingUid();
return (callingUid == UID_ROOT) || (callingUid == UID_SYSTEM);
}
bool LocalAbilityManagerStub::EnforceInterceToken(MessageParcel& data)
{
std::u16string interfaceToken = data.ReadInterfaceToken();
return interfaceToken == LOCAL_ABILITY_MANAGER_INTERFACE_TOKEN;
}
}
+96
View File
@@ -0,0 +1,96 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <sys/prctl.h>
#include "ipc_skeleton.h"
#include "local_ability_manager.h"
#include "safwk_log.h"
#include "securec.h"
#include "string_ex.h"
using namespace OHOS;
using std::string;
namespace {
const string TAG = "SaMain";
using ProcessNameSetFunc = std::function<void(const string&)>;
constexpr auto DEFAULT_XML = "/system/usr/default.xml";
// The pid name can be up to 16 bytes long, including the terminating null byte.
// So need to set the max length of pid name to 15 bytes.
constexpr size_t MAX_LEN_PID_NAME = 15;
}
static void SetProcName(const string& filePath, const ProcessNameSetFunc& setProcessName)
{
std::vector<string> strVector;
SplitStr(filePath, "/", strVector);
auto vectorSize = strVector.size();
if (vectorSize > 0) {
auto& fileName = strVector[vectorSize - 1];
auto dotPos = fileName.find(".");
if (dotPos == string::npos) {
return;
}
if (dotPos > MAX_LEN_PID_NAME) {
dotPos = MAX_LEN_PID_NAME;
}
string profileName = fileName.substr(0, dotPos);
int32_t ret = prctl(PR_SET_NAME, profileName.c_str());
if (ret != 0) {
HILOGI(TAG, "call the system API prctl failed!");
}
setProcessName(profileName);
}
}
int main(int argc, char *argv[])
{
HILOGI(TAG, "safwk main entry");
auto setProcessName = [argc, argv](const string& name) -> void {
uintptr_t start = reinterpret_cast<uintptr_t>(argv[0]);
uintptr_t end = reinterpret_cast<uintptr_t>(strchr(argv[argc - 1], 0));
uintptr_t argvSize = end - start;
if (memset_s(argv[0], argvSize, 0, argvSize) != EOK) {
HILOGW(TAG, "failed to clear argv:%s", strerror(errno));
return;
}
if (strcpy_s(argv[0], argvSize, name.c_str()) != EOK) {
HILOGW(TAG, "failed to set process name:%s", strerror(errno));
return;
}
HILOGI(TAG, "Set process name to %s", argv[0]);
};
// Load system abilities related shared libraries from specific xml-format profile,
// when this process starts.
string profilePath(DEFAULT_XML);
if (argc > 1) {
string filePath(argv[1]);
if (filePath.empty() || filePath.find(".xml") == string::npos) {
HILOGE(TAG, "profile file path is invalid!");
return 0;
}
SetProcName(filePath, setProcessName);
profilePath = std::move(filePath);
}
LocalAbilityManager::GetInstance().DoStartSAProcess(profilePath);
return 0;
}
+226
View File
@@ -0,0 +1,226 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "sa_profile_parser.h"
#include <dlfcn.h>
#include <fstream>
#include <sstream>
#include "safwk_log.h"
#include "string_ex.h"
namespace OHOS {
using std::string;
namespace {
const string TAG = "SaProfileParser";
const auto XML_TAG_PROFILE = "profile";
const auto XML_TAG_INFO = "info";
const auto XML_TAG_SYSTEM_ABILITY = "systemability";
const auto XML_TAG_LIB_PATH = "libpath";
const auto XML_TAG_NAME = "name";
const auto XML_TAG_DEPEND = "depend";
const auto XML_TAG_DEPEND_TIMEOUT = "depend-time-out";
const auto XML_TAG_RUN_ON_CREATE = "run-on-create";
const auto XML_TAG_DISTRIBUTED = "distributed";
const auto XML_TAG_DUMP_LEVEL = "dump-level";
const auto XML_TAG_CAPABILITY = "capability";
const auto XML_TAG_DEF_PERMISSION = "def-permission";
const auto XML_TAG_PERMISSION = "permission";
const auto XML_TAG_BOOT_PHASE = "bootphase";
}
SaProfileParser::~SaProfileParser()
{
ClearResource();
}
void SaProfileParser::CloseHandle(SaProfile& saProfile)
{
if (saProfile.handle == nullptr) {
return;
}
int32_t ret = dlclose(saProfile.handle);
if (ret) {
HILOGW(TAG, "close handle failed with errno:%{public}d!", errno);
}
saProfile.handle = nullptr;
}
void SaProfileParser::CloseSo()
{
for (auto& saProfile : saProfiles_) {
CloseHandle(saProfile);
}
}
void SaProfileParser::CloseSo(int32_t systemAbilityId)
{
for (auto& saProfile : saProfiles_) {
if (saProfile.saId == systemAbilityId) {
CloseHandle(saProfile);
break;
}
}
}
void SaProfileParser::ClearResource()
{
CloseSo();
saProfiles_.clear();
}
void SaProfileParser::OpenSo()
{
for (auto& saProfile : saProfiles_) {
if (saProfile.runOnCreate) {
OpenSo(saProfile);
}
}
}
void SaProfileParser::OpenSo(SaProfile& saProfile)
{
if (saProfile.handle == nullptr) {
DlHandle handle = dlopen(Str16ToStr8(saProfile.libPath).c_str(), RTLD_NOW);
if (handle == nullptr) {
std::vector<string> libPathVec;
string fileName = "";
SplitStr(Str16ToStr8(saProfile.libPath), "/", libPathVec);
if ((libPathVec.size() > 0)) {
fileName = libPathVec[libPathVec.size() - 1];
}
HILOGE(TAG, "dlopen %{public}s failed with errno:%{public}d!", fileName.c_str(), errno);
return;
}
saProfile.handle = handle;
} else {
HILOGI(TAG, "SA:%{public}d handle is not null", saProfile.saId);
}
}
bool SaProfileParser::LoadSaLib(int32_t systemAbilityId)
{
for (auto& saProfile : saProfiles_) {
if (saProfile.saId == systemAbilityId) {
OpenSo(saProfile);
return true;
}
}
return false;
}
const std::list<SaProfile>& SaProfileParser::GetAllSaProfiles() const
{
return saProfiles_;
}
void SaProfileParser::ParseSAProp(const string& nodeName, const string& nodeContent, SaProfile& saProfile)
{
if (nodeName == XML_TAG_NAME) {
saProfile.saId = atoi(nodeContent.c_str());
} else if (nodeName == XML_TAG_LIB_PATH) {
saProfile.libPath = Str8ToStr16(nodeContent);
} else if (nodeName == XML_TAG_DEPEND) {
saProfile.dependSa.emplace_back(Str8ToStr16(nodeContent));
} else if (nodeName == XML_TAG_DEPEND_TIMEOUT) {
saProfile.dependTimeout = atoi(nodeContent.c_str());
} else if (nodeName == XML_TAG_RUN_ON_CREATE) {
std::istringstream(nodeContent) >> std::boolalpha >> saProfile.runOnCreate;
} else if (nodeName == XML_TAG_DISTRIBUTED) {
std::istringstream(nodeContent) >> std::boolalpha >> saProfile.distributed;
} else if (nodeName == XML_TAG_DUMP_LEVEL) {
std::stringstream ss(nodeContent);
ss >> saProfile.dumpLevel;
} else if (nodeName == XML_TAG_CAPABILITY) {
saProfile.capability = Str8ToStr16(nodeContent);
} else if ((nodeName == XML_TAG_DEF_PERMISSION) || (nodeName == XML_TAG_PERMISSION)) {
saProfile.permission = Str8ToStr16(nodeContent);
} else if (nodeName == XML_TAG_BOOT_PHASE) {
saProfile.bootPhase = Str8ToStr16(nodeContent);
}
}
bool SaProfileParser::ParseSystemAbility(const xmlNode& rootNode)
{
auto currNodePtr = rootNode.xmlChildrenNode;
if (currNodePtr == nullptr) {
return false;
}
SaProfile saProfile;
for (; currNodePtr != nullptr; currNodePtr = currNodePtr->next) {
if (currNodePtr->name == nullptr || currNodePtr->type == XML_COMMENT_NODE) {
continue;
}
auto contentPtr = xmlNodeGetContent(currNodePtr);
if (contentPtr == nullptr) {
continue;
}
string nodeName(reinterpret_cast<const char*>(currNodePtr->name));
string nodeContent(reinterpret_cast<char*>(contentPtr));
ParseSAProp(nodeName, nodeContent, saProfile);
xmlFree(contentPtr);
}
saProfiles_.emplace_back(saProfile);
return true;
}
bool SaProfileParser::ParseSaProfiles(const string& profilePath)
{
HILOGI(TAG, "xmlFile:%{private}s", profilePath.c_str());
std::ifstream profileStream(profilePath.c_str());
if (!profileStream.good()) {
HILOGE(TAG, "bad profile path!");
return false;
}
xmlDocPtr ptrDoc = xmlReadFile(profilePath.c_str(), nullptr, XML_PARSE_NOBLANKS);
if (ptrDoc == nullptr) {
HILOGE(TAG, "xmlReadFile error!");
return false;
}
xmlNodePtr rootNodePtr = xmlDocGetRootElement(ptrDoc);
if (rootNodePtr == nullptr || rootNodePtr->name == nullptr ||
(xmlStrcmp(rootNodePtr->name, reinterpret_cast<const xmlChar*>(XML_TAG_PROFILE)) != 0 &&
xmlStrcmp(rootNodePtr->name, reinterpret_cast<const xmlChar*>(XML_TAG_INFO)) != 0)) {
HILOGW(TAG, "wrong root element tag!");
xmlFreeDoc(ptrDoc);
return false;
}
bool isParseCorrect = false;
xmlNodePtr currNodePtr = rootNodePtr->xmlChildrenNode;
for (; currNodePtr != nullptr; currNodePtr = currNodePtr->next) {
if (currNodePtr->name == nullptr || currNodePtr->type == XML_COMMENT_NODE) {
continue;
}
string nodeName(reinterpret_cast<const char*>(currNodePtr->name));
HILOGI(TAG, "profile nodeName:%{public}s", nodeName.c_str());
if (nodeName == XML_TAG_SYSTEM_ABILITY) {
bool ret = ParseSystemAbility(*currNodePtr);
if (!ret) {
HILOGW(TAG, "profile %{public}s wrong tag!", currNodePtr->name);
xmlFreeDoc(ptrDoc);
return false;
}
isParseCorrect = true;
}
}
xmlFreeDoc(ptrDoc);
return isParseCorrect;
}
} // namespace OHOS
+68
View File
@@ -0,0 +1,68 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "samgr_death_recipient.h"
#include <chrono>
#include "iremote_proxy.h"
#include "iservice_registry.h"
#include "local_ability_manager.h"
#include "safwk_log.h"
namespace OHOS {
namespace {
const std::string TAG = "SamgrDeathRecipient";
constexpr std::chrono::seconds SECONDS_TRY_WAITING_SAMGR_ONE_TIME(1);
constexpr int32_t RETRY_TIMES = 30;
}
void SamgrDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& remote)
{
if (remote == nullptr) {
return;
}
HILOGI(TAG, "remote samgr died!");
SystemAbilityManagerClient::GetInstance().DestroySystemAbilityManagerObject();
int32_t retryTimeout = RETRY_TIMES;
constexpr int32_t duration = std::chrono::microseconds(SECONDS_TRY_WAITING_SAMGR_ONE_TIME).count();
sptr<ISystemAbilityManager> samgrProxy;
while (samgrProxy == nullptr) {
HILOGD(TAG, "waiting for samgr...");
if (retryTimeout > 0) {
usleep(duration);
samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
} else {
HILOGE(TAG, "wait for samgr timeout (30s)");
return;
}
retryTimeout--;
}
if (samgrProxy != nullptr && samgrProxy->AsObject() != nullptr) {
auto recipient = sptr<IRemoteObject::DeathRecipient>(new SamgrDeathRecipient());
bool ret = samgrProxy->AsObject()->AddDeathRecipient(recipient);
if (!ret) {
HILOGW(TAG, "failed to add death recipient for samgr");
}
}
LocalAbilityManager::GetInstance().ReRegisterSA();
HILOGI(TAG, "receive samgr death notification success");
}
} // namespace OHOS
+323
View File
@@ -0,0 +1,323 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "system_ability.h"
#include "errors.h"
#include "if_system_ability_manager.h"
#include "ipc_skeleton.h"
#include "iservice_registry.h"
#include "local_ability_manager.h"
#include "safwk_log.h"
#include "string_ex.h"
namespace OHOS {
namespace {
const std::string TAG = "SystemAbility";
}
SystemAbility::SystemAbility(bool runOnCreate)
{
isRunning_ = false;
isRunOnCreate_ = runOnCreate;
isDistributed_ = false;
dumpLevel_ = 0;
// timeout for waiting dependency ready, which configed in xml, with DEFAULT_DEPENDENCY_TIMEOUT(6s) by default
dependTimeout_ = DEFAULT_DEPENDENCY_TIMEOUT;
capability_ = u"";
}
SystemAbility::SystemAbility(int32_t systemAbilityId, bool runOnCreate) : SystemAbility(runOnCreate)
{
saId_ = systemAbilityId;
}
SystemAbility::~SystemAbility()
{
HILOGI(TAG, "SA:%{public}d destroyed", saId_);
}
bool SystemAbility::MakeAndRegisterAbility(SystemAbility* systemAbility)
{
HILOGD(TAG, "registering system ability...");
return LocalAbilityManager::GetInstance().AddAbility(systemAbility);
}
bool SystemAbility::AddSystemAbilityListener(int32_t systemAbilityId, int32_t listenerSaId)
{
HILOGD(TAG, "SA:%{public}d, listenerSA:%{public}d", systemAbilityId, listenerSaId);
return LocalAbilityManager::GetInstance().AddSystemAbilityListener(systemAbilityId, listenerSaId);
}
bool SystemAbility::AddSystemAbilityListener(int32_t systemAbilityId)
{
HILOGD(TAG, "SA:%{public}d, listenerSA:%{public}d", systemAbilityId, saId_);
return LocalAbilityManager::GetInstance().AddSystemAbilityListener(systemAbilityId, saId_);
}
bool SystemAbility::InitAddSystemAbilityListener(int32_t systemAbilityId, int32_t listenerSaId)
{
HILOGD(TAG, "SA:%{public}d, listenerSA:%{public}d", systemAbilityId, listenerSaId);
return LocalAbilityManager::GetInstance().InitAddSystemAbilityListener(systemAbilityId,
listenerSaId);
}
bool SystemAbility::RemoveSystemAbilityListener(int32_t systemAbilityId, int32_t listenerSaId)
{
HILOGD(TAG, "SA:%{public}d, listenerSA:%{public}d", systemAbilityId, listenerSaId);
return LocalAbilityManager::GetInstance().RemoveSystemAbilityListener(systemAbilityId, listenerSaId);
}
bool SystemAbility::RemoveSystemAbilityListener(int32_t systemAbilityId)
{
HILOGD(TAG, "SA:%{public}d, listenerSA:%{public}d", systemAbilityId, saId_);
return LocalAbilityManager::GetInstance().RemoveSystemAbilityListener(systemAbilityId, saId_);
}
bool SystemAbility::Publish(sptr<IRemoteObject> systemAbility)
{
if (systemAbility == nullptr) {
HILOGE(TAG, "systemAbility is nullptr");
return false;
}
sptr<ISystemAbilityManager> samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (samgrProxy == nullptr) {
HILOGE(TAG, "failed to get samgrProxy");
return false;
}
publishObj_ = systemAbility;
HILOGD(TAG, "SA:%{public}d", saId_);
ISystemAbilityManager::SAExtraProp saExtra(GetDistributed(), GetDumpLevel(), capability_, permission_);
int32_t result = samgrProxy->AddSystemAbility(saId_, publishObj_, saExtra);
HILOGI(TAG, "AddSystemAbility result:%{public}d", result);
return result == ERR_OK;
}
bool SystemAbility::RePublish()
{
if (publishObj_ == nullptr) {
return true;
}
return Publish(publishObj_);
}
void SystemAbility::StopAbility(int32_t systemAbilityId)
{
HILOGD(TAG, "SA:%{public}d", systemAbilityId);
sptr<ISystemAbilityManager> samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (samgrProxy == nullptr) {
HILOGE(TAG, "failed to get samgrProxy");
return;
}
int32_t ret = samgrProxy->RemoveSystemAbility(systemAbilityId);
HILOGI(TAG, "%{public}s to remove ability", (ret == ERR_OK) ? "success" : "failed");
}
void SystemAbility::Start()
{
HILOGD(TAG, "starting system ability...");
if (isRunning_) {
return;
}
OnStart();
isRunning_ = true;
}
void SystemAbility::Stop()
{
HILOGD(TAG, "stoping system ability...");
if (!isRunning_) {
return;
}
OnStop();
isRunning_ = false;
sptr<ISystemAbilityManager> samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (samgrProxy == nullptr) {
HILOGE(TAG, "failed to get samgrProxy");
return;
}
int32_t ret = samgrProxy->RemoveSystemAbility(saId_);
HILOGI(TAG, "%{public}s to remove ability", (ret == ERR_OK) ? "success" : "failed");
}
void SystemAbility::SADump()
{
OnDump();
}
void SystemAbility::Test()
{
OnTest();
}
void SystemAbility::Debug()
{
OnDebug();
}
int32_t SystemAbility::GetSystemAbilitId() const
{
return saId_;
}
void SystemAbility::SetLibPath(const std::u16string& libPath)
{
libPath_ = libPath;
}
const std::u16string& SystemAbility::GetLibPath() const
{
return libPath_;
}
void SystemAbility::SetDependSa(const std::vector<std::u16string>& dependSa)
{
dependSa_ = dependSa;
}
const std::vector<std::u16string>& SystemAbility::GetDependSa() const
{
return dependSa_;
}
void SystemAbility::SetRunOnCreate(bool isRunOnCreate)
{
isRunOnCreate_ = isRunOnCreate;
}
bool SystemAbility::IsRunOnCreate() const
{
return isRunOnCreate_;
}
void SystemAbility::SetDistributed(bool isDistributed)
{
isDistributed_ = isDistributed;
}
bool SystemAbility::GetDistributed() const
{
return isDistributed_;
}
bool SystemAbility::GetRunningStatus() const
{
return isRunning_;
}
void SystemAbility::SetDumpLevel(uint32_t dumpLevel)
{
dumpLevel_ = dumpLevel;
}
uint32_t SystemAbility::GetDumpLevel() const
{
return dumpLevel_;
}
void SystemAbility::SetDependTimeout(int32_t dependTimeout)
{
if (dependTimeout >= MIN_DEPENDENCY_TIMEOUT && dependTimeout <= MAX_DEPENDENCY_TIMEOUT) {
dependTimeout_ = dependTimeout;
}
HILOGD(TAG, "new dependTimeout:%{public}d, orignal dependTimeout:%{public}d", dependTimeout, dependTimeout_);
}
int32_t SystemAbility::GetDependTimeout() const
{
return dependTimeout_;
}
// The details should be implemented by subclass
void SystemAbility::OnDump()
{
}
// The details should be implemented by subclass
void SystemAbility::OnDebug()
{
}
// The details should be implemented by subclass
void SystemAbility::OnTest()
{
}
// The details should be implemented by subclass
void SystemAbility::OnStart()
{
}
// The details should be implemented by subclass
void SystemAbility::OnStop()
{
}
// The details should be implemented by subclass
void SystemAbility::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId,
const sptr<IRemoteObject>& ability)
{
}
// The details should be implemented by subclass
void SystemAbility::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
{
}
sptr<IRemoteObject> SystemAbility::GetSystemAbility(int32_t systemAbilityId)
{
sptr<ISystemAbilityManager> samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (samgrProxy == nullptr) {
HILOGE(TAG, "failed to get samgrProxy");
return nullptr;
}
return samgrProxy->GetSystemAbility(systemAbilityId);
}
// Reserved for future usage
void SystemAbility::AddToLocal() const
{
}
// Reserved for future usage
void SystemAbility::DeleteFromLocal() const
{
}
void SystemAbility::SetCapability(const std::u16string& capability)
{
capability_ = capability;
}
const std::u16string& SystemAbility::GetCapability() const
{
return capability_;
}
void SystemAbility::SetPermission(const std::u16string& permission)
{
permission_ = permission;
}
}
+41
View File
@@ -0,0 +1,41 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "system_ability_connection_callback.h"
#include "safwk_log.h"
#include "string_ex.h"
namespace OHOS {
namespace {
const std::string TAG = "SystemAbilityConnectionCallback";
}
void SystemAbilityConnectionCallback::OnConnectedSystemAbility(const sptr<IRemoteObject>& connectionCallback)
{
HILOGI(TAG, "system ability connected");
if (handler_ != nullptr) {
handler_->OnConnectedSystemAbility(connectionCallback);
}
}
void SystemAbilityConnectionCallback::OnDisConnectedSystemAbility(int32_t systemAbilityId)
{
HILOGI(TAG, "SA:%{public}d", systemAbilityId);
if (handler_ != nullptr) {
handler_->OnDisConnectedSystemAbility(Str8ToStr16(std::to_string(systemAbilityId)));
}
}
} // namespace OHOS
@@ -0,0 +1,86 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "system_ability_connection_callback_proxy.h"
#include "errors.h"
#include "ipc_skeleton.h"
#include "iremote_proxy.h"
#include "safwk_log.h"
#include "string_ex.h"
namespace OHOS {
namespace {
const std::string TAG = "SystemAbilityConnectionCallbackProxy";
const std::u16string SA_CONNECTION_CALLBACK_INTERFACE_TOKEN = u"ohos.distributedschedule.saconnectAccessToken";
}
void SystemAbilityConnectionCallbackProxy::OnConnectedSystemAbility(const sptr<IRemoteObject>& connectionCallback)
{
HILOGI(TAG, "system ability connected");
if (connectionCallback == nullptr) {
HILOGW(TAG, "connectionCallback is null!");
return;
}
auto remote = Remote();
if (remote == nullptr) {
HILOGW(TAG, "remote is nullptr!");
return;
}
MessageParcel data;
if (!data.WriteInterfaceToken(SA_CONNECTION_CALLBACK_INTERFACE_TOKEN)) {
HILOGW(TAG, "write interface token failed!");
return;
}
if (!data.WriteRemoteObject(connectionCallback)) {
HILOGW(TAG, "write connectionCallback failed!");
return;
}
MessageParcel reply;
MessageOption option;
int32_t ret = remote->SendRequest(ON_CONNECTED_SYSTEM_ABILITY, data, reply, option);
HILOGI(TAG, "SendRequest ret:%{public}d", ret);
}
void SystemAbilityConnectionCallbackProxy::OnDisConnectedSystemAbility(int32_t systemAbilityId)
{
HILOGI(TAG, "systemAbilityId:%{public}d", systemAbilityId);
auto remote = Remote();
if (remote == nullptr) {
HILOGW(TAG, "remote is nullptr!");
return;
}
MessageParcel data;
if (!data.WriteInterfaceToken(SA_CONNECTION_CALLBACK_INTERFACE_TOKEN)) {
return;
}
if (!data.WriteInt32(systemAbilityId)) {
HILOGW(TAG, "write systemAbilityId failed!");
return;
}
MessageParcel reply;
MessageOption option;
int32_t ret = remote->SendRequest(ON_DISCONNECTED_SYSTEM_ABILITY, data, reply, option);
HILOGI(TAG, "SendRequest ret:%{public}d", ret);
}
} // namespace OHOS
@@ -0,0 +1,64 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "system_ability_connection_callback_stub.h"
#include "errors.h"
#include "ipc_skeleton.h"
#include "ipc_types.h"
#include "safwk_log.h"
namespace OHOS {
namespace {
const std::string TAG = "SystemAbilityConnectionCallbackStub";
const std::u16string SA_CONNECTION_CALLBACK_INTERFACE_TOKEN = u"ohos.distributedschedule.saconnectAccessToken";
}
int32_t SystemAbilityConnectionCallbackStub::OnRemoteRequest(uint32_t code,
MessageParcel& data, MessageParcel& reply, MessageOption& option)
{
HILOGI(TAG, "code:%{public}d, flags:%{public}d", code, option.GetFlags());
if (data.ReadInterfaceToken() != SA_CONNECTION_CALLBACK_INTERFACE_TOKEN) {
return ERR_PERMISSION_DENIED;
}
switch (code) {
case ON_CONNECTED_SYSTEM_ABILITY: {
auto object = data.ReadRemoteObject();
if (object == nullptr) {
HILOGW(TAG, "ReadRemoteObject failed!");
return ERR_NULL_OBJECT;
}
OnConnectedSystemAbility(object);
return ERR_OK;
}
case ON_DISCONNECTED_SYSTEM_ABILITY: {
int32_t systemAbilityId = data.ReadInt32();
if (systemAbilityId <= 0) {
HILOGW(TAG, "read saId failed!");
return ERR_NULL_OBJECT;
}
OnDisConnectedSystemAbility(systemAbilityId);
return ERR_OK;
}
default:
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
}
} // namespace OHOS