OpenHarmony——应用程序管理(AppManager)模块源码解析 原创 精华

深开鸿
发布于 2022-5-7 14:21
浏览
5收藏

作者:成飞

简介

应用程序管理模块提供了应用程序的启动及其进程的生命周期管理的功能。属于Ability管理的上一级管理目录。一下内容以v3.1-Release版进行分析。

代码目录

foundation/
└──foundation/aafwk/standard
   ├── common                       #线程管理的核心代码
   ├── frameworks/kits
   │   └── appkit                   # 框架层
   ├── interfaces
   │    ├── innerkits
   │    |    └── app_manager		# 内部接口
   │    └──  kits/napi/aafwk
   │         └── app                # NAPI接口 
   └──— services
        └──  appmgr					# 服务管理层        

类间关系及关键类介绍

类图

OpenHarmony——应用程序管理(AppManager)模块源码解析-鸿蒙开发者社区

AppMgrServiceInner及AppRuningRecord是应用管理服务核心类。应用管理服务进程内的各类事件及任务通过AMSEventHandler投递到主线程,并调用AppMgrServiceInner的方法执行。

AppMgrServiceInner中含有AppRunningManager的实例,AppRunningManager中以map表的形式包含所有的AppRunningRecord。每一个AppRunningRecord对应着一个应用进程(即上述类图中MainThread所在的进程),AppRunningRecord通过AppLifeCycleDeal管理所对应的应用进程的生命周期。

MainThread及OHOSApplication是应用进程的核心类。应用进程内的各类事件及任务通过MainThread中mainHandler_投递到主线程并调用MainThread中的方法执行。OHOSApplication中包含应用进程的上下文,可以通过abilityRecordMgr中的AbilityThread对进程内的各Ability线程进行调用。

应用进程与服务管理进程之间,通过IDL实现进程间调用。IAppSchedule, IAppMgr, IAmsMgr是进程间调用的接口类。

服务管理进程还可以通过socket与AppSpawanServer通信。AppSpawanServer内可进行系统调用。

关键类介绍
类名 功能简介
MainThread 应用程序主线程类,负责进程内各类事件及任务的执行,并实现了IPC调用的各接口。
OHOSApplication 包含应用进程的上下文环境,负责管理及调用该进程下的各Ability。
abilityRecordMgr 包含属于这个应用进程的所有AbilityLocalRecord的集合,其中AbilityLocalRecord中又封装了AbilityThread。由此实现应用进程对各Ability线程的调用
IAppSchedule 应用进程提供的进程间的调用接口。可通过此接口实现对应用进程生命周期的调用。
AppMgrService 应用管理服务主线程类。实现了IPC调用的IAppMgr接口。并通过AMSEventHandler将进程内各类事件及任务投递到主线程。
AppMgrServiceInner 应用管理服务内部的主线程类,通过AMSEventHandler投递到主线程的各事件及任务,基本上都是调用AppMgrServiceInner的方法进行执行。
AmsMgrScheduler 实现了IPC调用的IAmsMgr接口。并通过AMSEventHandler将各类事件及任务投递到主线程。
AppRunningManager 所有应用进程的AppRunningRecord的合集,以Map表的形式存在于该类
AppRuningRecord 存储了应用进程的各种信息,可对应用进程进行调度管理。
AppLifeCycleDeal 对应用进程的生命周期进行调度
ModuleRunningRecord 对应用进程的Ability进行管理调度
IAppMgr 应用管理服务提供的进程间的调用接口。可通过此接口实现对管理进程的调用。
IAmsMgr 应用管理服务提供的进程间的调用接口。可通过此接口实现对管理进程的调用。主要的调用方是Ability模块。

应用程序启动的时序图

当加载某个Ability时,会启动该Ability所属的应用进程。以此为例分析应用进程的启动过程。

时序图

OpenHarmony——应用程序管理(AppManager)模块源码解析-鸿蒙开发者社区

源码分析

限于篇幅,每个调用函数只摘抄关键语句。

1. ability模块通过 IAmsMgr的接口调用 AmsMgrScheduler的LoadAbility

foundation\aafwk\standard\services\appmgr\src\ams_mgr_scheduler.cpp

void AmsMgrScheduler::LoadAbility(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &preToken,
    const std::shared_ptr<AbilityInfo> &abilityInfo, const std::shared_ptr<ApplicationInfo> &appInfo,
    const std::shared_ptr<AAFwk::Want> &want)
{
  
    std::function<void()> loadAbilityFunc =
        std::bind(&AppMgrServiceInner::LoadAbility, amsMgrServiceInner_, token, preToken, abilityInfo, appInfo, want);

    amsHandler_->PostTask(loadAbilityFunc, TASK_LOAD_ABILITY);    // 通过amsHandler发送loadAbilityFunc任务给AppMgrService的主线程
}
2. AppMgrService的主线程调用 app_mgr_service_inner.cpp中的 LoadAbility

foundation\aafwk\standard\services\appmgr\src\app_mgr_service_inner.cpp

void AppMgrServiceInner::LoadAbility(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &preToken,
    const std::shared_ptr<AbilityInfo> &abilityInfo, const std::shared_ptr<ApplicationInfo> &appInfo,
    const std::shared_ptr<AAFwk::Want> &want)
{
   
    std::string processName;
    MakeProcessName(processName, abilityInfo, appInfo, hapModuleInfo);     //根据ability及hap包信息构建应用程序进程名
    HILOG_INFO("processName = [%{public}s]", processName.c_str());

    auto appRecord =
        appRunningManager_->CheckAppRunningRecordIsExist(appInfo->name, processName, appInfo->uid, bundleInfo); //根据应用程序进程名检查该appRecord是否存在,如果appRecord已经存在,说明该应该程序是启动中的。
    if (!appRecord) {
        appRecord =
            CreateAppRunningRecord(token, preToken, appInfo, abilityInfo,
                processName, bundleInfo, hapModuleInfo, want); //该appRecord不存在的情况下,创建appRecord
        if (!appRecord) {
            HILOG_ERROR("CreateAppRunningRecord failed, appRecord is nullptr");
            return;
        }
        bool isColdStart = want == nullptr ? false : want->GetBoolParam("coldStart", false);
        StartProcess(abilityInfo->applicationName, processName, isColdStart, appRecord,
            appInfo->uid, appInfo->bundleName);  //调用同文件中的StartProcess启动该应用程序进程。
    } else {
        StartAbility(token, preToken, abilityInfo, appRecord, hapModuleInfo, want); 
    }
    PerfProfile::GetInstance().SetAbilityLoadEndTime(GetTickCount());
    PerfProfile::GetInstance().Dump();
    PerfProfile::GetInstance().Reset();
}
void AppMgrServiceInner::StartProcess(const std::string &appName, const std::string &processName, bool coldStart,
    const std::shared_ptr<AppRunningRecord> &appRecord, const int uid, const std::string &bundleName)
{
 
    PerfProfile::GetInstance().SetAppForkStartTime(GetTickCount());
    pid_t pid = 0;
    ErrCode errCode = remoteClientManager_->GetSpawnClient()->StartProcess(startMsg, pid); //通过appSpawanSocket与AppSpwanSever进行socket通信,发送启动进程的消息给AppSpawnServer, AppSpawnServer启动后的进程信息等会通过startMsg,pid返回。
    if (FAILED(errCode)) {
        HILOG_ERROR("failed to spawn new app process, errCode %{public}08x", errCode);
        appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
        return;
    }
    HILOG_INFO("newPid:%{public}d uid:%{public}d", pid, startMsg.uid);
    appRecord->GetPriorityObject()->SetPid(pid);  // 设置appRecord关联的应用进程的pid
    appRecord->SetUid(startMsg.uid);              // 设置appRecord关联的Uid
    appRecord->SetStartMsg(startMsg);
    appRecord->SetAppMgrServiceInner(weak_from_this());
    OnAppStateChanged(appRecord, ApplicationState::APP_STATE_CREATE);
    AddAppToRecentList(appName, appRecord->GetProcessName(), pid, appRecord->GetRecordId());
    OnProcessCreated(appRecord);
    PerfProfile::GetInstance().SetAppForkEndTime(GetTickCount());
}
3. appSpawanServer通过消息队列的方式处理接收到的消息,并启动相应的应用进程。

base\startup\appspawn_standard\src\appspawn_serrver.cpp

bool AppSpawnServer::ServerMain(char *longProcName, int64_t longProcNameLen)
{
   
    while (isRunning_) {
      
        std::unique_ptr<AppSpawnMsgPeer> msg = std::move(appQueue_.front());
        appQueue_.pop();                                                    //按照先进先出的原则弹出一条消息  
        int connectFd = msg->GetConnectFd();                                
        ClientSocket::AppProperty *appProperty = msg->GetMsg();             
        pid_t pid = 0;
        int ret = StartApp(longProcName, longProcNameLen, appProperty, connectFd, pid);    //启动相应的进程
       
    QuickExitMain();
    return false;
}
int AppSpawnServer::StartApp(char *longProcName, int64_t longProcNameLen,
    ClientSocket::AppProperty *appProperty, int connectFd, pid_t &pid)
{
    if (!CheckAppProperty(appProperty)) {
        return -EINVAL;
    }
    int32_t fd[FDLEN2] = {FD_INIT_VALUE, FD_INIT_VALUE};
    int32_t buff = 0;
    if (pipe(fd) == -1) {
        HiLog::Error(LABEL, "create pipe fail, errno = %{public}d", errno);
        return ERR_PIPE_FAIL;
    }

    InstallSigHandler();
    pid = fork();                   //通过系统调用创建新进程
    if (pid < 0) {
        HiLog::Error(LABEL, "AppSpawnServer::Failed to fork new process, errno = %{public}d", errno);
        close(fd[0]);
        close(fd[1]);
        return -errno;
    } else if (pid == 0) {
        SpecialHandle(appProperty);
        // close socket connection and peer socket in child process
        if (socket_ != NULL) {
            socket_->CloseConnection(connectFd);
            socket_->CloseServerMonitor();
        }
        close(fd[0]); // close read fd
        ClearEnvironment();
        UninstallSigHandler();
        SetAppAccessToken(appProperty);       
        if ((appProperty->flags == ClientSocket::APPSPAWN_COLD_BOOT) &&
            OHOS::system::GetBoolParameter("appspawn.cold.boot", false)) {
            DoColdStartApp(appProperty, fd[1]);
        } else {
            SetAppProcProperty(appProperty, longProcName, longProcNameLen, fd[1]);  //在新进程执行相应的应用程序逻辑
        }
        _exit(0);
    }
    read(fd[0], &buff, sizeof(buff)); // wait child process resutl
    close(fd[0]);
    close(fd[1]);

    HiLog::Info(LABEL, "child process init %{public}s", (buff == ERR_OK) ? "success" : "fail");
    return (buff == ERR_OK) ? 0 : buff;
}
bool AppSpawnServer::SetAppProcProperty(const ClientSocket::AppProperty *appProperty, char *longProcName,
    int64_t longProcNameLen, const int32_t fd)
{
   
#ifdef NWEB_SPAWN
    using FuncType = void (*)(const char *cmd);
    FuncType funcNWebRenderMain = reinterpret_cast<FuncType>(dlsym(nwebHandle, "NWebRenderMain"));
    if (funcNWebRenderMain == nullptr) {
        HiLog::Error(LABEL, "nwebspawn dlsym ERROR=%{public}s", dlerror());
        return false;
    }
    funcNWebRenderMain(appProperty->renderCmd);
#else
    AppExecFwk::MainThread::Start();                                   //启动应用程序主线程
#endif

    HiLog::Error(LABEL, "Failed to start process, pid = %{public}d", getpid());
    return false;
}
4. 应用程序主线程(FrameWork层)

foundation\aafwk\standard\frameworks\kits\appkit\native\app\src\main_thread.cpp

void MainThread::Start()
{
    BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__);
    HILOG_INFO("MainThread::main called start");
    std::shared_ptr<EventRunner> runner = EventRunner::GetMainEventRunner();               //应用程序主线程
    if (runner == nullptr) {
        HILOG_ERROR("MainThread::main failed, runner is nullptr");
        return;
    }
    std::shared_ptr<EventRunner> runnerWatchDog = EventRunner::Create("WatchDogRunner");   //应用程序看门狗线程
    if (runnerWatchDog == nullptr) {
        HILOG_ERROR("MainThread::Start runnerWatchDog is nullptr");
        return;
    }
    sptr<MainThread> thread = sptr<MainThread>(new (std::nothrow) MainThread());
    if (thread == nullptr) {
        HILOG_ERROR("MainThread::static failed. new MainThread failed");
        return;
    }

    HILOG_INFO("MainThread::main called start Init");
    thread->Init(runner, runnerWatchDog);                                                 //主线程及看门狗线程初始化
    HILOG_INFO("MainThread::main called end Init");

    HILOG_INFO("MainThread::main called start Attach");
    thread->Attach();                                                                    //将主线程Attach到AppMgr
    HILOG_INFO("MainThread::main called end Attach");

    int ret = runner->Run();
    if (ret != ERR_OK) {
        HILOG_ERROR("MainThread::main failed. runner->Run failed ret = %{public}d", ret);
    }

    thread->RemoveAppMgrDeathRecipient();
    HILOG_INFO("MainThread::main runner stopped");
}
/**
 *
 * @brief Attach the mainthread to the AppMgr.
 *
 */
void MainThread::Attach()
{
    BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__);
    HILOG_INFO("MainThread::attach called");
    if (!ConnectToAppMgr()) {                            //获取AppMgrService的代理
        HILOG_ERROR("attachApplication failed");
        return;
    }
    mainThreadState_ = MainThreadState::ATTACH;
    HILOG_INFO("MainThread::attach mainThreadState: %{public}d", mainThreadState_);
}
/**
 *
 * @brief Connect the mainthread to the AppMgr.
 *
 */
bool MainThread::ConnectToAppMgr()
{
    BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__);
    HILOG_INFO("MainThread::ConnectToAppMgr start");
    auto object = OHOS::DelayedSingleton<SysMrgClient>::GetInstance()->GetSystemAbility(APP_MGR_SERVICE_ID);   //获取Service侧代理
  
    appMgr_ = iface_cast<IAppMgr>(object);     //保存Service侧的代理,用于调用Service的接口
    if (appMgr_ == nullptr) {
        HILOG_ERROR("failed to iface_cast object to appMgr_");
        return false;
    }
    HILOG_INFO("MainThread::connectToAppMgr before AttachApplication");
    appMgr_->AttachApplication(this);          // 将自身信息注册到 Application Service                                  
    HILOG_INFO("MainThread::connectToAppMgr after AttachApplication");
    return true;
}

foundation\aafwk\standard\interfaces\innerkits\app_manager\src\appmgr\app_mgr_proxy.cpp

/**
     * AttachApplication, call AttachApplication() through proxy object,
     * get all the information needed to start the Application (data related to the Application ).
     *
     * @param app, information needed to start the Application.
     * @return
 */

void AppMgrProxy::AttachApplication(const sptr<IRemoteObject> &obj)
{
    HILOG_DEBUG("AppMgrProxy::AttachApplication start");
    MessageParcel data;
    MessageParcel reply;
    MessageOption option(MessageOption::TF_SYNC);
    if (!WriteInterfaceToken(data)) {
        return;
    }
    data.WriteParcelable(obj.GetRefPtr());
    sptr<IRemoteObject> remote = Remote();
    if (remote == nullptr) {
        HILOG_ERROR("Remote() is NULL");
        return;
    }
    int32_t ret =
        remote->SendRequest(static_cast<uint32_t>(IAppMgr::Message::APP_ATTACH_APPLICATION), data, reply, option);  //发送attach信息给service层
    if (ret != NO_ERROR) {
        HILOG_WARN("SendRequest is failed, error code: %{public}d", ret);
    }
    HILOG_DEBUG("end");
}

5. service层处理APP_ATTACH_APPLICATION消息

foundation\aafwk\standard\interfaces\innerkits\app_manager\src\appmgr\app_mgr_stub.cpp

int32_t AppMgrStub::HandleAttachApplication(MessageParcel &data, MessageParcel &reply)
{
    BYTRACE(BYTRACE_TAG_APP);
    sptr<IRemoteObject> client = data.ReadParcelable<IRemoteObject>();   //接收attachApplication信息
    AttachApplication(client);   //调用AttachApplication的实现
    return NO_ERROR;
}

foundation\aafwk\standard\services\appmgr\src\app_mgr_service.cpp

void AppMgrService::AttachApplication(const sptr<IRemoteObject> &app)
{
    if (!IsReady()) {
        HILOG_ERROR("AttachApplication failed, not ready.");
        return;
    }

    pid_t pid = IPCSkeleton::GetCallingPid();
    AddAppDeathRecipient(pid);
    std::function<void()> attachApplicationFunc =
        std::bind(&AppMgrServiceInner::AttachApplication, appMgrServiceInner_, pid, iface_cast<IAppScheduler>(app));  //调用AppMgrServiceInner的AttachAppliction
    handler_->PostTask(attachApplicationFunc, TASK_ATTACH_APPLICATION);
}

foundation\aafwk\standard\services\appmgr\src\app_mgr_service_inner.cpp

void AppMgrServiceInner::AttachApplication(const pid_t pid, const sptr<IAppScheduler> &app)
{
    BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__);
    if (pid <= 0) {
        HILOG_ERROR("invalid pid:%{public}d", pid);
        return;
    }
    if (!app) {
        HILOG_ERROR("app client is null");
        return;
    }
    HILOG_INFO("attach application pid:%{public}d", pid);
    auto appRecord = GetAppRunningRecordByPid(pid);
    if (!appRecord) {
        HILOG_ERROR("no such appRecord");
        return;
    }
    appRecord->SetApplicationClient(app);
    if (appRecord->GetState() == ApplicationState::APP_STATE_CREATE) {
        LaunchApplication(appRecord); //通知应用程序,以启动应用程序
    }
    appRecord->RegisterAppDeathRecipient();
}
 /**
     * LaunchApplication, Notify application to launch application.
     *
     * @param appRecord, the application record.
     *
     * @return
     */
    void AppMgrServiceInner::LaunchApplication(const std::shared_ptr<AppRunningRecord> &appRecord)
{
    BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__);
    if (!appRecord) {
        HILOG_ERROR("appRecord is null");
        return;
    }

    if (!configuration_) {
        HILOG_ERROR("configuration_ is null");
        return;
    }

    if (appRecord->GetState() != ApplicationState::APP_STATE_CREATE) {
        HILOG_ERROR("wrong app state:%{public}d", appRecord->GetState());
        return;
    }
    appRecord->LaunchApplication(*configuration_);   //通过appRecord启动Application
    appRecord->SetState(ApplicationState::APP_STATE_READY);

    // There is no ability when the resident process starts         
    // The status of all resident processes is ready
    // There is no process of switching the foreground, waiting for his first ability to start
    if (appRecord->IsKeepAliveApp()) {
        appRecord->AddAbilityStage();
        return;
    }

    if (appRecord->IsStartSpecifiedAbility()) {
        appRecord->AddAbilityStageBySpecifiedAbility(appRecord->GetBundleName());
        return;
    }
    appRecord->LaunchPendingAbilities();
}

foundation\aafwk\standard\services\appmgr\src\app_running_record.cpp

/**
     * LaunchApplication, Notify application to launch application.
     *
     * @return
     */
    void AppRunningRecord::LaunchApplication(const Configuration &config)
{
    BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__);
    if (appLifeCycleDeal_ == nullptr) {
        HILOG_ERROR("appLifeCycleDeal_ is null");
        return;
    }
    if (!appLifeCycleDeal_->GetApplicationClient()) {
        HILOG_ERROR("appThread is null");
        return;
    }
    AppLaunchData launchData;
    auto moduleRecords = appInfos_.find(mainBundleName_);
    if (moduleRecords != appInfos_.end()) {
        launchData.SetApplicationInfo(*(moduleRecords->second));
    }
    ProcessInfo processInfo(processName_, GetPriorityObject()->GetPid());
    launchData.SetProcessInfo(processInfo);
    launchData.SetRecordId(appRecordId_);
    launchData.SetUId(mainUid_);
    launchData.SetUserTestInfo(userTestRecord_);
    HILOG_INFO("ScheduleLaunchApplication app:%{public}s", GetName().c_str());
    appLifeCycleDeal_->LaunchApplication(launchData, config);   //通过appLifeCycleDeal启动application
}
    
    

foundation\aafwk\standard\services\appmgr\src\app_lifecycle_deal.cpp

 /**
     * LaunchApplication, call ScheduleLaunchApplication() through proxy project,
     * Notify application to launch application.                                      
     *
     * @param The app data value.
     *
     * @return
     */
   void AppLifeCycleDeal::LaunchApplication(const AppLaunchData &launchData_, const Configuration &config)
{
    BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__);
    HILOG_INFO("AppLifeCycleDeal ScheduleLaunchApplication");
    if (appThread_) {
        appThread_->ScheduleLaunchApplication(launchData_, config);    //通知APP启动应用程序
    }
}

foundation\aafwk\standard\interfaces\innerkits\app_manager\src\appmgr\app_scheduler_proxy.cpp

/**
     * ScheduleLaunchApplication, call ScheduleLaunchApplication() through proxy project,
     * Notify application to launch application.
     *
     * @param The app data value.
     *
     * @return
*/

void AppSchedulerProxy::ScheduleLaunchApplication(const AppLaunchData &launchData, const Configuration &config)
{
    HILOG_INFO("AppSchedulerProxy ScheduleLaunchApplication start");
    MessageParcel data;
    MessageParcel reply;
    MessageOption option(MessageOption::TF_SYNC);
    if (!WriteInterfaceToken(data)) {
        return;
    }

    if (!data.WriteParcelable(&launchData)) {
        HILOG_ERROR("WriteParcelable launchData failed");
        return ;
    }

    if (!data.WriteParcelable(&config)) {
        HILOG_ERROR("WriteParcelable config failed");
        return ;
    }

    sptr<IRemoteObject> remote = Remote();
    if (remote == nullptr) {
        HILOG_ERROR("Remote() is NULL");
        return;
    }
    int32_t ret = remote->SendRequest(
        static_cast<uint32_t>(IAppScheduler::Message::SCHEDULE_LAUNCH_APPLICATION_TRANSACTION), data, reply, option);
    if (ret != NO_ERROR) {              //通知框架层启动应用程序
        HILOG_WARN("SendRequest is failed, error code: %{public}d", ret);
    }

    HILOG_INFO("AppSchedulerProxy ScheduleLaunchApplication end");
}
6. 应用进程(FrameWork层)生命周期处理

foundation\aafwk\standard\interfaces\innerkits\app_manager\src\appmgr\app_scheduler_host.cpp

 memberFuncMap_[static_cast<uint32_t>(IAppScheduler::Message::SCHEDULE_LAUNCH_APPLICATION_TRANSACTION)] =
        &AppSchedulerHost::HandleScheduleLaunchApplication;   //SCHEDULE_LAUNCH_APPLICATION_TRANSACTION消息对应HandleScheduleLaunchApplication函数
        
        
 int AppSchedulerHost::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
{
  
    auto itFunc = memberFuncMap_.find(code);
    if (itFunc != memberFuncMap_.end()) {
        auto memberFunc = itFunc->second;
        if (memberFunc != nullptr) {
            return (this->*memberFunc)(data, reply);  //SCHEDULE_LAUNCH_APPLICATION_TRANSACTION消息对应HandleScheduleLaunchApplication函数
        }
    }
    return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}


/**
 *
 * @brief Launch the application.
 *
 * @param appLaunchData The launchdata of the application witch launced.
 *
 */

int32_t AppSchedulerHost::HandleScheduleLaunchApplication(MessageParcel &data, MessageParcel &reply)
{
    BYTRACE(BYTRACE_TAG_APP);
    std::unique_ptr<AppLaunchData> launchData(data.ReadParcelable<AppLaunchData>());
    std::unique_ptr<Configuration> config(data.ReadParcelable<Configuration>());
    if (!launchData) {
        HILOG_ERROR("ReadParcelable<launchData> failed");
        return ERR_APPEXECFWK_PARCEL_ERROR;
    }
    if (!config) {
        HILOG_ERROR("ReadParcelable<Configuration> failed");
        return ERR_APPEXECFWK_PARCEL_ERROR;
    }

    ScheduleLaunchApplication(*launchData, *config);
    return NO_ERROR;
}

foundation\aafwk\standard\frameworks\kits\appkit\native\app\src\main_thread.cpp

/**
 *
 * @brief Launch the application.
 *
 * @param data The launchdata of the application witch launced.
 *
 */
void MainThread::ScheduleLaunchApplication(const AppLaunchData &data, const Configuration &config)
{
    BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__);
    HILOG_INFO("MainThread::scheduleLaunchApplication start");
    wptr<MainThread> weak = this;
    auto task = [weak, data, config]() {
        auto appThread = weak.promote();
        if (appThread == nullptr) {
            HILOG_ERROR("appThread is nullptr, HandleLaunchApplication failed.");
            return;
        }
        appThread->HandleLaunchApplication(data, config);
    };
    if (!mainHandler_->PostTask(task)) {
        HILOG_ERROR("MainThread::ScheduleLaunchApplication PostTask task failed");
    }
    HILOG_INFO("MainThread::scheduleLaunchApplication end.");
}



/**
 *
 * @brief Launch the application.
 *
 * @param appLaunchData The launchdata of the application witch launced.
 *
 */
void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, const Configuration &config)
{
   
    std::shared_ptr<ContextDeal> contextDeal = nullptr;
    if (!InitCreate(contextDeal, appInfo, processInfo, appProfile)) {  // 新规abilityRecordMgr_ / applicationImpl_/ contextDeal并设置contextDeal<
        HILOG_ERROR("MainThread::handleLaunchApplication InitCreate failed");
        return;
    }

    // get application shared point
    application_ = std::shared_ptr<OHOSApplication>(ApplicationLoader::GetInstance().GetApplicationByName());
    if (application_ == nullptr) {
        HILOG_ERROR("HandleLaunchApplication::application launch failed");
        return;
    }
    applicationForAnr_ = application_;

    // init resourceManager.
    std::shared_ptr<Global::Resource::ResourceManager> resourceManager(Global::Resource::CreateResourceManager());
    if (resourceManager == nullptr) {
        HILOG_ERROR("MainThread::handleLaunchApplication create resourceManager failed");
        return;
    }

    HILOG_INFO("MainThread::handleLaunchApplication. Start calling GetBundleManager.");
    sptr<IBundleMgr> bundleMgr = contextDeal->GetBundleManager();
    if (bundleMgr == nullptr) {
        HILOG_ERROR("MainThread::handleLaunchApplication GetBundleManager is nullptr");
        return;
    }
    HILOG_INFO("MainThread::handleLaunchApplication. End calling GetBundleManager.");

    BundleInfo bundleInfo;
    HILOG_INFO("MainThread::handleLaunchApplication length: %{public}zu, bundleName: %{public}s",
        appInfo.bundleName.length(), appInfo.bundleName.c_str());
    if (!bundleMgr->GetBundleInfo(appInfo.bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, UNSPECIFIED_USERID)) {
        HILOG_DEBUG("MainThread::handleLaunchApplication GetBundleInfo fail.");
    }

    if (!InitResourceManager(resourceManager, contextDeal, appInfo, bundleInfo, config)) {
        HILOG_ERROR("MainThread::handleLaunchApplication InitResourceManager failed");
        return;
    }

    // create contextImpl
    std::shared_ptr<AbilityRuntime::ContextImpl> contextImpl = std::make_shared<AbilityRuntime::ContextImpl>();
    contextImpl->SetResourceManager(resourceManager);
    contextImpl->SetApplicationInfo(std::make_shared<ApplicationInfo>(appInfo));
    contextImpl->InitAppContext();
    application_->SetApplicationContext(contextImpl);

    bool moduelJson = false;
    bool isStageBased = false;
    if (!bundleInfo.hapModuleInfos.empty()) {
        moduelJson = bundleInfo.hapModuleInfos.back().isModuleJson;
        isStageBased = bundleInfo.hapModuleInfos.back().isStageBasedModel;
    }
    HILOG_INFO("stageBased:%{public}d moduleJson:%{public}d size:%{public}d",
        isStageBased, moduelJson, (int32_t)bundleInfo.hapModuleInfos.size());

    if (isStageBased) {
        // Create runtime
        AbilityRuntime::Runtime::Options options;
        options.codePath = LOCAL_CODE_PATH;
        options.eventRunner = mainHandler_->GetEventRunner();
        options.loadAce = true;
        std::string nativeLibraryPath = appInfo.nativeLibraryPath;
        if (!nativeLibraryPath.empty()) {
            if (nativeLibraryPath.back() == '/') {
                nativeLibraryPath.pop_back();
            }
            std::string libPath = LOCAL_CODE_PATH;
            libPath += (libPath.back() == '/') ? nativeLibraryPath : "/" + nativeLibraryPath;
            HILOG_INFO("napi lib path = %{private}s", libPath.c_str());
            options.packagePath = libPath;
        } 
        auto runtime = AbilityRuntime::Runtime::Create(options);                 //创建ability的线程
        if (!runtime) {
            HILOG_ERROR("OHOSApplication::OHOSApplication: Failed to create runtime");
            return;
        }
        auto& jsEngine = (static_cast<AbilityRuntime::JsRuntime&>(*runtime)).GetNativeEngine();
        auto bundleName = appInfo.bundleName;
        auto uid = appInfo.uid;
        auto processName = processInfo.GetProcessName();
        auto processPid = processInfo.GetPid();
        wptr<MainThread> weak = this;
        auto uncaughtTask = [weak, uid, processPid, bundleName, processName](NativeValue* v) {
            HILOG_INFO("RegisterUncaughtExceptionHandler Begin");
            NativeObject* obj = AbilityRuntime::ConvertNativeValueTo<NativeObject>(v);
            NativeValue* message = obj->GetProperty("message");
            NativeString* messageStr = AbilityRuntime::ConvertNativeValueTo<NativeString>(message);
            if (messageStr == nullptr) {
                HILOG_ERROR("messageStr Convert failed");
                return;
            }
            size_t messagebufferLen = messageStr->GetLength();
            size_t messagestrLen = 0;
            char* messagecap = new char[messagebufferLen + 1];
            messageStr->GetCString(messagecap, messagebufferLen + 1, &messagestrLen);
            HILOG_INFO("messagecap = %{public}s", messagecap);
            NativeValue* stack = obj->GetProperty("stack");
            NativeString* stackStr = AbilityRuntime::ConvertNativeValueTo<NativeString>(stack);
            if (stackStr == nullptr) {
                HILOG_ERROR("stackStr Convert failed");
                return;
            }
            size_t stackbufferLen = stackStr->GetLength();
            size_t stackstrLen = 0;
            char* stackcap = new char[stackbufferLen + 1];
            stackStr->GetCString(stackcap, stackbufferLen + 1, &stackstrLen);
            HILOG_INFO("stackcap = %{public}s", stackcap);
            auto appThread = weak.promote();
            if (appThread == nullptr) {
                HILOG_ERROR("appThread is nullptr, HandleLaunchApplication failed.");
                return;
            }
            std::string eventType = "JS_EXCEPTION";
            std::string msgContent;
            std::string tempMessageStr(messagecap);
            std::string tempStackStr(stackcap);
            if (messagecap != nullptr) {
                delete [] messagecap;
            }
            if (stackcap != nullptr) {
                delete [] stackcap;
            }
            msgContent = "  message:" + tempMessageStr + "  Stack:" + tempStackStr;
            auto ret = OHOS::HiviewDFX::HiSysEvent::Write(OHOS::HiviewDFX::HiSysEvent::Domain::AAFWK, eventType,
                OHOS::HiviewDFX::HiSysEvent::EventType::FAULT,
                EVENT_KEY_UID, std::to_string(uid),
                EVENT_KEY_PID, std::to_string(processPid),
                EVENT_KEY_PACKAGE_NAME, bundleName,
                EVENT_KEY_PROCESS_NAME, processName,
                EVENT_KEY_MESSAGE, msgContent);
            appThread->ScheduleProcessSecurityExit();                           
            HILOG_INFO("RegisterUncaughtExceptionHandler End ret = %{public}d", ret);
        };
        jsEngine.RegisterUncaughtExceptionHandler(uncaughtTask);
        application_->SetRuntime(std::move(runtime));

        AbilityLoader::GetInstance().RegisterAbility("Ability", [application = application_]() {
            return Ability::Create(application->GetRuntime());
        });
#ifdef SUPPORT_GRAPHICS
        AbilityLoader::GetInstance().RegisterExtension("FormExtension", [application = application_]() {
            return AbilityRuntime::FormExtension::Create(application->GetRuntime());
        });
#endif
        AbilityLoader::GetInstance().RegisterExtension("StaticSubscriberExtension", [application = application_]() {
            return AbilityRuntime::StaticSubscriberExtension::Create(application->GetRuntime());
        });
        LoadAndRegisterExtension("system/lib/libservice_extension_module.z.so", "ServiceExtension",
            application_->GetRuntime());
        LoadAndRegisterExtension("system/lib/libdatashare_ext_ability_module.z.so", "DataShareExtAbility",
            application_->GetRuntime());
        LoadAndRegisterExtension("system/lib/libworkschedextension.z.so", "WorkSchedulerExtension",
            application_->GetRuntime());
        LoadAndRegisterExtension("system/lib/libaccessibility_extension_module.z.so", "AccessibilityExtension",
            application_->GetRuntime());
        LoadAndRegisterExtension("system/lib/libwallpaper_extension_module.z.so", "WallpaperExtension",
            application_->GetRuntime());
    }

    auto usertestInfo = appLaunchData.GetUserTestInfo();
    if (usertestInfo) {
        if (!PrepareAbilityDelegator(usertestInfo)) {
            HILOG_ERROR("Failed to prepare ability delegator");
            return;
        }
    }

    contextDeal->initResourceManager(resourceManager);
    contextDeal->SetApplicationContext(application_);
    application_->AttachBaseContext(contextDeal);               //为container设置成员变量,contextDeal
    application_->SetAbilityRecordMgr(abilityRecordMgr_);
    application_->SetConfiguration(config);
    contextImpl->SetConfiguration(application_->GetConfiguration());

    applicationImpl_->SetRecordId(appLaunchData.GetRecordId());
    applicationImpl_->SetApplication(application_);
    mainThreadState_ = MainThreadState::READY; //设为ready状态
    HILOG_INFO("MainThread::handleLaunchApplication before PerformAppReady.");
    if (!applicationImpl_->PerformAppReady()) {
        HILOG_ERROR("HandleLaunchApplication::application applicationImpl_->PerformAppReady failed");
        return;
    }
    HILOG_INFO("MainThread::handleLaunchApplication after PerformAppReady.");
    // L1 needs to add corresponding interface
    ApplicationEnvImpl *pAppEvnIml = ApplicationEnvImpl::GetInstance();

    if (pAppEvnIml) {
        pAppEvnIml->SetAppInfo(*applicationInfo_.get());
    } else {
        HILOG_ERROR("HandleLaunchApplication::application pAppEvnIml is null");
    }

    HILOG_INFO("MainThread::handleLaunchApplication called end.");
}

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
分类
已于2022-5-7 14:47:12修改
5
收藏 5
回复
举报
5条回复
按时间正序
/
按时间倒序
红叶亦知秋
红叶亦知秋

赞!大佬类图有点糊能传附件一份吗?

1
回复
2022-5-7 14:52:23
鸿蒙坚果派
鸿蒙坚果派

三个赞

1
回复
2022-5-10 12:24:33
wangccsy爱鸿蒙
wangccsy爱鸿蒙

底层都是C++,不懂了的。

回复
2022-5-11 14:13:36
cheerfully
cheerfully

类图及时序图的高清图

类图和时序图.zip 372.47K 65次下载
回复
2022-5-12 14:25:17
cheerfully
cheerfully 回复了 红叶亦知秋
赞!大佬类图有点糊能传附件一份吗?

已上传

回复
2022-5-12 14:25:36
回复
    相关推荐