
??想了解更多關(guān)于開源的內(nèi)容,請訪問:??
??51CTO 開源基礎(chǔ)軟件社區(qū)??
??https://ost.51cto.com??
1、預(yù)備知識
Linux中主要的IPC機制有:管道(pipe)、信號(signal)、信號量(semophore)、消息隊列(Message)、共享內(nèi)存(Share Memory)、套接字(Socket)等。Openharmony基于binder驅(qū)動封裝了一套ipc機制(foundation\communication\ipc)用于實現(xiàn)設(shè)備內(nèi)的跨進程通信。
Binder機制通常采用客戶端-服務(wù)器(Client-Server)模型,服務(wù)請求方(Client)可獲取服務(wù)提供方(Server)的代理 (Proxy),并通過此代理讀寫數(shù)據(jù)來實現(xiàn)進程間的數(shù)據(jù)通信。通常,系統(tǒng)能力(SystemAbility)Server側(cè)會先注冊到系統(tǒng)能力管理者(System Ability Manager,縮寫SAMgr)中,SAMgr負責管理這些SA并向Client提供相關(guān)的接口(添加,查詢,獲取,刪除等)。Client要和某個具體的SA通信,必須先從SAMgr中獲取該SA的代理,然后使用代理和SA通信。
注:SAMgr本身也是IPC的Server端,Client通過SAMgr的代理,調(diào)用SAMgr的接口。
(1)binder機制架構(gòu)圖

說明:
SAMgr中保存了一個map,key為saId, value為SAInfo。SAInfo結(jié)構(gòu)體定義如下:
struct SAInfo {
sptr<IRemoteObject> remoteObj;
bool isDistributed = false;
std::u16string capability;
std::string permission;
};
(2)實現(xiàn)IPC的基本步驟
- 定義接口類
接口類繼承IRemoteBroker,定義描述符、業(yè)務(wù)函數(shù)和消息碼。 - 實現(xiàn)服務(wù)提供端(Stub)
Stub繼承IRemoteStub,除了接口類中未實現(xiàn)方法外,還需要實現(xiàn)OnRemoteRequest方法。 - 實現(xiàn)服務(wù)請求端(Proxy)
Proxy繼承IRemoteProxy,封裝業(yè)務(wù)函數(shù),調(diào)用SendRequest將請求發(fā)送到Stub。 - 服務(wù)端進程注冊SA
服務(wù)提供方所在進程啟動后,申請SA的唯一標識,將Stub注冊到SAMgr。 - 客戶端進程通過SA的標識(saId),從SAMgr獲取Proxy,通過Proxy實現(xiàn)與Stub的跨進程通信。
ohos中的SystemAbility可以運行在獨立的進程中,也可以多個SystemAbility同時依附在某個進程內(nèi)(如 foundation進程),通過這個進程對外提供服務(wù)。其他進程通過IPC(binder機制)使用這些服務(wù)提供的接口。
2、系統(tǒng)服務(wù)管理子系統(tǒng)簡介
系統(tǒng)服務(wù)管理子系統(tǒng)由兩部分構(gòu)成。
系統(tǒng)服務(wù)框架組件(safwk):定義了SystemAbility的實現(xiàn)方法,并提供啟動、發(fā)布等接口實現(xiàn)。
系統(tǒng)服務(wù)管理組件(samgr): 提供系統(tǒng)服務(wù)注冊、查詢等功能。
架構(gòu)圖如下:

代碼目錄:
/foundation/systemabilitymgr
│── safwk # 組件目錄
│ ├── bundle.json # 組件描述及編譯腳本
│ ├── etc # 配置文件
│ ├── interfaces # 對外接口目錄
│ ├── services # 框架實現(xiàn)
│ ├── test # 測試用例
├── samgr
│ ├── bundle.json # 部件描述及編譯文件
│ ├── frameworks # 框架實現(xiàn)存在目錄
│ ├── interfaces # 接口目錄
│ ├── services # 組件服務(wù)端目錄
│ ├── test # 測試代碼存放目錄
│ ├── utils # 工具類目錄
3、系統(tǒng)服務(wù)框架組件
SystemAbility實現(xiàn)一般采用XXX.cfg + saId.xml + libXXX.z.so的方式由init進程解析對應(yīng)的XXX.cfg文件拉起SystemAbility所依賴的進程。(注:多個系統(tǒng)服務(wù)可能跑在同一個進程里。比如AbilityManagerService、BatteryService、WindowManagerService都在foundation進程,MMIService在獨立的進程multimodalinput中。)
SystemAbility類圖如下:

說明:
SystemAbility子類需要重寫OnStart()和OnStop()方法,并且在OnStart()方法中調(diào)用Publish(sptr<IRemoteObject> systemAbility)方法把系統(tǒng)服務(wù)發(fā)布出去。
(1)系統(tǒng)服務(wù)實現(xiàn)步驟
下面以AbilityManagerService為例說明SystemAbility的實現(xiàn)。
定義IPC對外接口IXXX
定義該服務(wù)對外提供的能力集合函數(shù),統(tǒng)一繼承IPC接口類IRemoteBroker;同時聲明該IPC對外接口唯一標識符DECLARE_INTERFACE_DESCRIPTOR(XXX);該標識符用于IPC通信的校驗等目的。
foundation\ability\ability_runtime\interfaces\inner_api\ability_manager\include\ability_manager_interface.h。
class IAbilityManager : public OHOS::IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.aafwk.AbilityManager")
/**
* StartAbility with want, send want to ability manager service.
*
* @param want, the want of the ability to start.
* @param userId, Designation User ID.
* @param requestCode, Ability request code.
* @return Returns ERR_OK on success, others on failure.
*/
virtual int StartAbility(
const Want &want,
int32_t userId = DEFAULT_INVAL_VALUE,
int requestCode = DEFAULT_INVAL_VALUE) = 0;
//...此處省略若干行
}
定義客戶端代碼XXXProxy
foundation\ability\ability_runtime\services\abilitymgr\include\ability_manager_proxy.h。
class AbilityManagerProxy : public IRemoteProxy<IAbilityManager> {
public:
explicit AbilityManagerProxy(const sptr<IRemoteObject> &impl) : IRemoteProxy<IAbilityManager>(impl)
{}
virtual ~AbilityManagerProxy()
{}
/**
* StartAbility with want, send want to ability manager service.
*
* @param want, the want of the ability to start.
* @param requestCode, Ability request code.
* @param userId, Designation User ID.
* @return Returns ERR_OK on success, others on failure.
*/
virtual int StartAbility(
const Want &want,
int32_t userId = DEFAULT_INVAL_VALUE,
int requestCode = DEFAULT_INVAL_VALUE) override;
//...此處省略若干行
private:
static inline BrokerDelegator<AbilityManagerProxy> delegator_;
};
foundation\ability\ability_runtime\services\abilitymgr\src\ability_manager_proxy.cpp。
int AbilityManagerProxy::StartAbility(const Want &want, int32_t userId, int requestCode)
{
int error;
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!WriteInterfaceToken(data)) {
return INNER_ERR;
}
if (!data.WriteParcelable(&want)) {
HILOG_ERROR("want write failed.");
return INNER_ERR;
}
if (!data.WriteInt32(userId)) {
HILOG_ERROR("userId write failed.");
return INNER_ERR;
}
if (!data.WriteInt32(requestCode)) {
HILOG_ERROR("requestCode write failed.");
return INNER_ERR;
}
error = Remote()->SendRequest(IAbilityManager::START_ABILITY, data, reply, option);
if (error != NO_ERROR) {
HILOG_ERROR("Send request error: %{public}d", error);
return error;
}
return reply.ReadInt32();
}
AbilityManagerProxy::StartAbility()實現(xiàn)代碼中會調(diào)用Remote()->SendRequest(IAbilityManager::START_ABILITY, data, reply, option);把消息碼和數(shù)據(jù)發(fā)送給服務(wù)端。
定義服務(wù)端代碼XXXStub
foundation\ability\ability_runtime\services\abilitymgr\include\ability_manager_stub.h。
class AbilityManagerStub : public IRemoteStub<IAbilityManager> {
public:
AbilityManagerStub();
~AbilityManagerStub();
virtual int OnRemoteRequest(
uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
//...此處省略若干行
};
foundation\ability\ability_runtime\services\abilitymgr\src\ability_manager_stub.cpp。
int AbilityManagerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
{
std::u16string descriptor = AbilityManagerStub::GetDescriptor();
std::u16string remoteDescriptor = data.ReadInterfaceToken();
if (descriptor != remoteDescriptor) {
HILOG_INFO("local descriptor is not equal to remote");
return ERR_INVALID_STATE;
}
auto itFunc = requestFuncMap_.find(code);
if (itFunc != requestFuncMap_.end()) {
auto requestFunc = itFunc->second;
if (requestFunc != nullptr) {
return (this->*requestFunc)(data, reply);
}
}
HILOG_WARN("default case, need check.");
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
requestFuncMap_[START_ABILITY] = &AbilityManagerStub::StartAbilityInner。
消息碼START_ABILITY對應(yīng)的函數(shù)為AbilityManagerStub::StartAbilityInner。
int AbilityManagerStub::StartAbilityInner(MessageParcel &data, MessageParcel &reply)
{
Want *want = data.ReadParcelable<Want>();
if (want == nullptr) {
HILOG_ERROR("want is nullptr");
return ERR_INVALID_VALUE;
}
int32_t userId = data.ReadInt32();
int requestCode = data.ReadInt32();
int32_t result = StartAbility(*want, userId, requestCode);
reply.WriteInt32(result);
delete want;
return NO_ERROR;
}
StartAbility()的實現(xiàn)在AbilityManagerStub的實現(xiàn)類AbilityManagerService中。
SystemAbility的實現(xiàn)類
foundation\ability\ability_runtime\services\abilitymgr\include\ability_manager_service.h。
class AbilityManagerService : public SystemAbility,
public AbilityManagerStub,
public AppStateCallback,
public std::enable_shared_from_this<AbilityManagerService> {
DECLARE_DELAYED_SINGLETON(AbilityManagerService)
DECLEAR_SYSTEM_ABILITY(AbilityManagerService)
public:
void OnStart() override;
void OnStop() override;
ServiceRunningState QueryServiceState() const;
/**
* StartAbility with want, send want to ability manager service.
*
* @param want, the want of the ability to start.
* @param requestCode, Ability request code.
* @param userId, Designation User ID.
* @return Returns ERR_OK on success, others on failure.
*/
virtual int StartAbility(
const Want &want, int32_t userId = DEFAULT_INVAL_VALUE, int requestCode = DEFAULT_INVAL_VALUE) override;
// ...此處省略若干行
}
AbilityManagerService同時繼承了SystemAbility和AbilityManagerStub。
在重寫的SystemAbility的接口函數(shù)OnStart()中,調(diào)用Publish(instance_)把自己發(fā)布出去。
void AbilityManagerService::OnStart()
{
//...此處省略若干行
/* Publish service maybe failed, so we need call this function at the last,
* so it can't affect the TDD test program */
instance_ = DelayedSingleton<AbilityManagerService>::GetInstance().get();
if (instance_ == nullptr) {
HILOG_ERROR("AMS enter OnStart, but instance_ is nullptr!");
return;
}
bool ret = Publish(instance_);
if (!ret) {
HILOG_ERROR("Publish AMS failed!");
return;
}
//...此處省略若干行
}
注:在實現(xiàn)SystemAbility的時候,必須調(diào)用宏REGISTER_SYSTEM_ABILITY_BY_ID或者SystemAbility::MakeAndRegisterAbility()把SystemAbility注冊到LocalAbilityManager中。
可參考如下代碼:
const bool REGISTER_RESULT =
SystemAbility::MakeAndRegisterAbility(DelayedSingleton<AbilityManagerService>::GetInstance().get());
或者:
REGISTER_SYSTEM_ABILITY_BY_ID(AppMgrService, APP_MGR_SERVICE_ID, true);
SystemAbility配置
以c++實現(xiàn)的SA必須配置相關(guān)SystemAbility的profile配置文件才會完成SA的自動加載注冊邏輯,否則沒有編寫配置文件的SystemAbility不會完成自動加載注冊。配置方法如下:
在子系統(tǒng)的根目錄新建一個以sa_profile為名的文件夾,然后在此文件夾中新建兩個文件:一個以saId為前綴的xml文件,另外一個為BUILD.gn文件。
比如AbilityManagerService,saId為ABILITY_MGR_SERVICE_ID(即180),對應(yīng)的配置文件為180.xml。內(nèi)容如下:
<info>
<process>foundation</process>
<systemability>
<name>180</name>
<libpath>libabilityms.z.so</libpath>
<run-on-create>true</run-on-create>
<distributed>false</distributed>
<dump-level>1</dump-level>
</systemability>
</info>
BUILD.gn內(nèi)容如下:
ohos_sa_profile("ams_sa_profile") {
sources = [
"180.xml",
"182.xml",
"183.xml",
"184.xml",
"501.xml",
]
part_name = "ability_runtime"
}
說明:
- 進程名字即該SystemAbility要運行的進程空間,此字段是必填選項。上例中,AbilityManagerService跑在foundation進程中。
- 一個SystemAbility配置文件只能配置一個SystemAbility節(jié)點,配置多個會導(dǎo)致編譯失敗。
- SystemAbility的name為對應(yīng)的saId必須與代碼中注冊的saId保持一致,必配項。
- libpath為SystemAbility的加載路徑,必配項。
- run-on-create:true表示進程啟動后即向samgr組件注冊該SystemAbility;false表示按需啟動,即在其他模塊訪問到該SystemAbility時啟動,必配項。
- distributed:true表示該SystemAbility為分布式SystemAbility,支持跨設(shè)備訪問;false表示只有本地跨進程訪問。
- bootphase:可不設(shè)置;可以設(shè)置的值有三種:BootStartPhase、CoreStartPhase、OtherStartPhase(默認類型),三種優(yōu)先級依次降低,在同一個進程中,會優(yōu)先拉起注冊配置BootStartPhase的SystemAbility,然后是配置了CoreStartPhase的SystemAbility,最后是OtherStartPhase;當高優(yōu)先級的SystemAbility全部啟動注冊完畢才會啟動下一級的SystemAbility的注冊啟動。
- dump-level:表示systemdumper支持的level等級,默認配置1。
- BUILD.gn中part_name為相應(yīng)部件名稱;sources表示當前子系統(tǒng)需要配置的SystemAbility列表,可支持配置多個SystemAbility。
以上步驟完成后,全量編譯代碼后會在out路徑下生成一個以進程名為前綴的xml文件(比如foundation.xml),路徑為:out\…\system\profile\foundation.xml。該文件整合了所有需要在該進程中運行的SA的saId.xml文件內(nèi)容。(比如AbilityManagerService,WindowManagerService,PowerManagerService等SA的配置文件都會被集成到foundation.xml中)。
Cfg配置文件
cfg配置文件為linux提供的native進程拉起策略,開機啟動階段由init進程解析cfg文件把目標進程拉起(動態(tài)加載的除外)。
foundation進程的配置文件在systemabilitymgr子系統(tǒng)中。
foundation\systemabilitymgr\safwk\etc\profile\foundation.cfg。
"services" : [{
"name" : "foundation",
"path" : ["/system/bin/sa_main", "/system/profile/foundation.xml"],
"importance" : -20,
"uid" : "foundation",
//...此處省略若干行
}
]
(2)SystemAbility所在進程啟動時序圖

時序圖1
該流程即為/system/bin/sa_main可執(zhí)行文件的啟動流程,main()函數(shù)(代碼路徑foundation\systemabilitymgr\safwk\services\safwk\src\main.cpp)在調(diào)用LocalAbilityManager::GetInstance().DoStartSAProcess(profilePath, saId)之前會把進程改名為saId.xml配置文件中指定的進程名。
3、系統(tǒng)服務(wù)管理組件
SystemAbilityManager本身是IPC接口ISystemAbilityManager的服務(wù)端。提供了添加、刪除、查詢系統(tǒng)服務(wù),以及訂閱系統(tǒng)服務(wù)狀態(tài)等接口。IPCSkeleton::SetContextObject()通過該方法告訴binder我是服務(wù)管理器,我是0號選手。
constexpr int REGISTRY_HANDLE = 0。
foundation\systemabilitymgr\samgr\services\samgr\native\source\main.cpp。
int main(int argc, char *argv[])
{
HILOGI("%{public}s called, enter System Ability Manager ", __func__);
OHOS::sptr<OHOS::SystemAbilityManager> manager = OHOS::SystemAbilityManager::GetInstance();
manager->Init();
OHOS::sptr<OHOS::IRemoteObject> serv = manager->AsObject();
if (!IPCSkeleton::SetContextObject(serv)) {
HILOGE("set context fail!"); // add log for dfx
}
int result = SetParameter("bootevent.samgr.ready", "true");
HILOGI("set samgr ready ret : %{public}s", result == 0 ? "succeed" : "failed");
manager->StartDfxTimer();
OHOS::IPCSkeleton::JoinWorkThread();
return -1;
}

標紅的方法LoadSystemAbility適用于動態(tài)加載系統(tǒng)服務(wù)進程的場景。
前面章節(jié)講的AbilityManagerService所在的foundation進程,開機即被init進程拉起。
有些系統(tǒng)服務(wù)進程需要動態(tài)加載,比如QuickFixManagerService所在的quick_fix進程。
foundation\ability\ability_runtime\services\quickfixmgr\quick_fix.cfg。
{
"services" : [{
"name" : "quick_fix",
"path" : ["/system/bin/sa_main", "/system/profile/quick_fix.xml"],
"ondemand" : true,
"uid" : "quickfixserver",
"gid" : ["system"],
"secon" : "u:r:quick_fix:s0"
}
]
}
cfg文件指定了"ondemand"為 true,說明quick_fix進程要按需啟動。拉起quick_fix進程的關(guān)鍵在于SystemAbilityManager::LoadSystemAbility方法。
foundation\ability\ability_runtime\interfaces\inner_api\quick_fix\src\quick_fix_manager_client.cpp。
bool QuickFixManagerClient::LoadQuickFixMgrService()
{
// ...此處省略若干行
sptr<QuickFixLoadCallback> loadCallback = new (std::nothrow) QuickFixLoadCallback();
if (loadCallback == nullptr) {
HILOG_ERROR("Create load callback failed.");
return false;
}
auto ret = systemAbilityMgr->LoadSystemAbility(QUICK_FIX_MGR_SERVICE_ID, loadCallback);
if (ret != 0) {
HILOG_ERROR("Load system ability %{public}d failed with %{public}d.", QUICK_FIX_MGR_SERVICE_ID, ret);
return false;
}
{
std::unique_lock<std::mutex> lock(loadSaMutex_);
auto waitStatus = loadSaCondation_.wait_for(lock, std::chrono::milliseconds(LOAD_SA_TIMEOUT_MS),
[this]() {
return loadSaFinished_;
});
if (!waitStatus) {
HILOG_ERROR("Wait for load sa timeout.");
return false;
}
}
return true;
}
SystemAbilityManager::LoadSystemAbility()中,會先判斷目標SA是否已存在,如不存在,則調(diào)用StartDynamicSystemProcess()函數(shù)把目標SA所在進程拉起。(SystemAbilityManager在初始化的時候會遍歷/system/profile/目錄下的文件并解析,把所有SA的配置信息保存到saProfileMap_中。所以目標SA所在的進程名,SystemAbilityManager都有保存。)
int32_t SystemAbilityManager::StartDynamicSystemProcess(const std::u16string& name, int32_t systemAbilityId)
{
std::string strExtra = std::to_string(systemAbilityId);
auto extraArgv = strExtra.c_str();
auto result = ServiceControlWithExtra(Str16ToStr8(name).c_str(), ServiceAction::START, &extraArgv, 1);
HILOGI("StartDynamicSystemProcess call ServiceControlWithExtra result:%{public}d!", result);
return (result == 0) ? ERR_OK : ERR_INVALID_VALUE;
}
ServiceControlWithExtra()函數(shù)的實現(xiàn)在base\startup\init\interfaces\innerkits\service_control\service_control.c文件中,實際就是通知init進程把目標進程拉起。目標進程被拉起之后會再走一遍時序圖1的流程。跟開機啟動的系統(tǒng)服務(wù)進程的不同點在于,動態(tài)加載的系統(tǒng)服務(wù)進程main()函數(shù)參數(shù)多了目標saId。
4、系統(tǒng)服務(wù)接口使用方法
foundation\systemabilitymgr\samgr\interfaces\innerkits\samgr_proxy\include\system_ability_definition.h 定義了所有系統(tǒng)服務(wù)的saId。
比如要使用AbilityManagerService的StartAbility()接口。
#include "ability_manager_interface.h"
#include "if_system_ability_manager.h"
#include "ipc_skeleton.h"
#include "iservice_registry.h"
#include "system_ability_definition.h"
- 獲取系統(tǒng)服務(wù),調(diào)用接口
OHOS::sptr<OHOS::ISystemAbilityManager> systemAbilityManager =
OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
OHOS::sptr<OHOS::IRemoteObject> abilityObject =
systemAbilityManager->GetSystemAbility(OHOS::ABILITY_MGR_SERVICE_ID);
auto abms = OHOS::iface_cast<OHOS::AAFwk::IAbilityManager>(abilityObject);
abms->StartAbility(want, userId, requestCode);
5、系統(tǒng)服務(wù)不配置saId.xml,不走自動加載注冊流程行不行?
答案是可以的。
參考SysEventServiceOhos,是SystemAbility,但沒有配置saId.xml,直接在hiview進程中初始化并注冊。
SysEventService::OnLoad() => (hiview進程加載SysEventService插件)
SysEventServiceAdapter::StartService() =>
OHOS::HiviewDFX::SysEventServiceOhos::StartService() =>
samgr->AddSystemAbility(DFX_SYS_EVENT_SERVICE_ABILITY_ID, instance)
6、總結(jié)
本文詳細講解了系統(tǒng)服務(wù)的實現(xiàn)方法和注意事項。通過這篇文章相信大家對系統(tǒng)服務(wù)管理子系統(tǒng)有了一定的了解。
??想了解更多關(guān)于開源的內(nèi)容,請訪問:??
??51CTO 開源基礎(chǔ)軟件社區(qū)??
??https://ost.51cto.com??