• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2025 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef OHOS_ABILITY_RUNTIME_APP_SCHEDULER_H
17 #define OHOS_ABILITY_RUNTIME_APP_SCHEDULER_H
18 
19 #include <memory>
20 #include <unordered_set>
21 
22 #include "ability_debug_response_interface.h"
23 #include "ability_info.h"
24 #include "ability_manager_client.h"
25 #include "app_debug_listener_interface.h"
26 #include "application_info.h"
27 #include "appmgr/app_mgr_client.h"
28 #include "appmgr/app_state_callback_host.h"
29 #include "appmgr/start_specified_ability_response_stub.h"
30 #include "bundle_info.h"
31 #include "fault_data.h"
32 #include "iremote_object.h"
33 #include "refbase.h"
34 #include "running_process_info.h"
35 #include "singleton.h"
36 #include "system_memory_attr.h"
37 #include "want.h"
38 
39 namespace OHOS {
40 namespace AppExecFwk {
41 class Configuration;
42 }
43 namespace AbilityRuntime {
44 struct LoadParam;
45 }
46 namespace AAFwk {
47 /**
48  * @enum AppAbilityState
49  * AppAbilityState defines the life cycle state of app ability.
50  */
51 enum class AppAbilityState {
52     ABILITY_STATE_UNDEFINED = 0,
53     ABILITY_STATE_FOREGROUND,
54     ABILITY_STATE_BACKGROUND,
55     ABILITY_STATE_END,
56 };
57 
58 enum class AppState {
59     BEGIN = 0,
60     READY,
61     FOREGROUND,
62     FOCUS,
63     BACKGROUND,
64     TERMINATED,
65     END,
66     SUSPENDED,
67     COLD_START = 99,
68 };
69 
70 struct AppData {
71     std::string appName;
72     int32_t uid;
73 };
74 
75 struct AppInfo {
76     std::vector<AppData> appData;
77     std::string processName;
78     AppState state;
79     pid_t pid = 0;
80     int32_t appIndex = 0;
81     std::string instanceKey = "";
82     std::string bundleName = "";
83 };
84 /**
85  * @class AppStateCallback
86  * AppStateCallback.
87  */
88 class AppStateCallback {
89 public:
AppStateCallback()90     AppStateCallback()
91     {}
~AppStateCallback()92     virtual ~AppStateCallback()
93     {}
94 
95     virtual void OnAbilityRequestDone(const sptr<IRemoteObject> &token, const int32_t state) = 0;
96 
97     virtual void OnAppStateChanged(const AppInfo &info) = 0;
98 
NotifyConfigurationChange(const AppExecFwk::Configuration & config,int32_t userId)99     virtual void NotifyConfigurationChange(const AppExecFwk::Configuration &config, int32_t userId) {}
100 
NotifyStartResidentProcess(std::vector<AppExecFwk::BundleInfo> & bundleInfos)101     virtual void NotifyStartResidentProcess(std::vector<AppExecFwk::BundleInfo> &bundleInfos) {}
102 
NotifyStartKeepAliveProcess(std::vector<AppExecFwk::BundleInfo> & bundleInfos)103     virtual void NotifyStartKeepAliveProcess(std::vector<AppExecFwk::BundleInfo> &bundleInfos) {}
104 
105     /**
106      * @brief Notify abilityms app process pre cache
107      * @param pid process pid.
108      * @param userId userId Designation User ID.
109      */
NotifyAppPreCache(int32_t pid,int32_t userId)110     virtual void NotifyAppPreCache(int32_t pid, int32_t userId) {}
111 
112     /**
113      * @brief Notify abilityms app process OnRemoteDied
114      * @param abilityTokens abilities in died process.
115      */
OnAppRemoteDied(const std::vector<sptr<IRemoteObject>> & abilityTokens)116     virtual void OnAppRemoteDied(const std::vector<sptr<IRemoteObject>> &abilityTokens) {}
117 
OnStartProcessFailed(sptr<IRemoteObject> token)118     virtual void OnStartProcessFailed(sptr<IRemoteObject> token) {}
119 
OnCacheExitInfo(uint32_t accessTokenId,const AAFwk::LastExitDetailInfo & exitInfo,const std::string & bundleName,const std::vector<std::string> & abilityNames,const std::vector<std::string> & uiExtensionNames)120     virtual void OnCacheExitInfo(uint32_t accessTokenId, const AAFwk::LastExitDetailInfo &exitInfo,
121         const std::string &bundleName, const std::vector<std::string> &abilityNames,
122         const std::vector<std::string> &uiExtensionNames) {}
123 };
124 
125 class StartSpecifiedAbilityResponse : public AppExecFwk::StartSpecifiedAbilityResponseStub {
126 public:
127     StartSpecifiedAbilityResponse() = default;
128     virtual ~StartSpecifiedAbilityResponse() = default;
129 
130     virtual void OnAcceptWantResponse(const AAFwk::Want &want, const std::string &flag,
131         int32_t requestId) override;
132     virtual void OnTimeoutResponse(const AAFwk::Want &want, int32_t requestId) override;
133 
134     virtual void OnNewProcessRequestResponse(const AAFwk::Want &want, const std::string &flag,
135         int32_t requestId) override;
136     virtual void OnNewProcessRequestTimeoutResponse(const AAFwk::Want &want, int32_t requestId) override;
137 
138     virtual void OnStartSpecifiedFailed(int32_t requestId) override;
139 };
140 
141 /**
142  * @class AppScheduler
143  * AppScheduler , access app manager service.
144  */
145 class AppScheduler : virtual RefBase, public AppExecFwk::AppStateCallbackHost {
146     DECLARE_DELAYED_SINGLETON(AppScheduler)
147 public:
148     /**
149      * init app scheduler.
150      * @param callback, app state call back.
151      * @return true on success ,false on failure.
152      */
153     bool Init(const std::weak_ptr<AppStateCallback> &callback);
154 
155     /**
156      * load ability with token, ability info and application info.
157      *
158      * @param loadParam, the loadParam of ability.
159      * @param abilityInfo, ability info.
160      * @param applicationInfo, application info.
161      * @param want ability want
162      * @return true on success ,false on failure.
163      */
164     int LoadAbility(const AbilityRuntime::LoadParam &loadParam, const AppExecFwk::AbilityInfo &abilityInfo,
165         const AppExecFwk::ApplicationInfo &applicationInfo, const Want &want);
166 
167     /**
168      * terminate ability with token.
169      *
170      * @param token, the token of ability.
171      * @param clearMissionFlag, indicates whether terminate the ability when clearMission.
172      * @return true on success ,false on failure.
173      */
174     int TerminateAbility(const sptr<IRemoteObject> &token, bool clearMissionFlag);
175 
176     /**
177      * Prepare terminate application
178      *
179      * @param pid Process ID
180      * @param moduleName Module name
181      */
182     void PrepareTerminateApp(const pid_t pid, const std::string &moduleName);
183 
184     /**
185      * move ability to foreground.
186      *
187      * @param token, the token of ability.
188      */
189     void MoveToForeground(const sptr<IRemoteObject> &token);
190 
191     /**
192      * move ability to background.
193      *
194      * @param token, the token of ability.
195      */
196     void MoveToBackground(const sptr<IRemoteObject> &token);
197 
198     /**
199      * Update ability state.
200      *
201      * @param token, the token of ability.
202      * @param state, ability state.
203      */
204     void UpdateAbilityState(const sptr<IRemoteObject> &token, const AppExecFwk::AbilityState state);
205 
206     /**
207      * UpdateExtensionState, call UpdateExtensionState() through the proxy object, update the extension status.
208      *
209      * @param token, the unique identification to update the extension.
210      * @param state, extension status that needs to be updated.
211      * @return
212      */
213     void UpdateExtensionState(const sptr<IRemoteObject> &token, const AppExecFwk::ExtensionState state);
214 
215     /**
216      * KillProcessByAbilityToken, call KillProcessByAbilityToken() through proxy object,
217      * kill the process by ability token.
218      *
219      * @param token, the unique identification to the ability.
220      */
221     void KillProcessByAbilityToken(const sptr<IRemoteObject> &token);
222 
223     /**
224      * KillProcessesByUserId, call KillProcessesByUserId() through proxy object,
225      * kill the process by user id.
226      * Send appSpawn uninstall debug hap message.
227      *
228      * @param userId, the user id.
229      * @param isNeedSendAppSpawnMsg, true send appSpawn message otherwise not send.
230      */
231     void KillProcessesByUserId(int32_t userId, bool isNeedSendAppSpawnMsg = false,
232         sptr<AAFwk::IUserCallback> callback = nullptr);
233 
234     /**
235      * KillProcessesByPids, only in process call is allowed,
236      * kill the processes by pid list given.
237      *
238      * @param pids, the pid list of processes are going to be killed.
239      * @param reason, the reason to kill the processes.
240      */
241     void KillProcessesByPids(const std::vector<int32_t> &pids,
242         const std::string &reason = "KillProcessesByPids");
243 
244     /**
245      * Set child and parent relationship
246      * @param token child process
247      * @param callerToken parent process
248      */
249     void AttachPidToParent(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &callerToken);
250 
251     /**
252      * convert ability state to app ability state.
253      *
254      * @param state, the state of ability.
255      */
256     AppAbilityState ConvertToAppAbilityState(const int32_t state);
257 
258     /**
259      * get ability state.
260      *
261      * @return state, the state of app ability.
262      */
263     AppAbilityState GetAbilityState() const;
264 
265     /**
266      * kill the application
267      *
268      * @param bundleName.
269      */
270     int KillApplication(const std::string &bundleName, bool clearPageStack = false, int32_t appIndex = 0);
271 
272     /**
273      * ForceKillApplication, force kill the application.
274      *
275      * @param  bundleName, bundle name in Application record.
276      * @param  userId, userId.
277      * @param  appIndex, appIndex.
278      * @return ERR_OK, return back success, others fail.
279      */
280     int ForceKillApplication(const std::string &bundleName, const int userId = -1,
281         const int appIndex = 0);
282 
283     /**
284      * KillProcessesByAccessTokenId.
285      *
286      * @param  accessTokenId, accessTokenId.
287      * @return ERR_OK, return back success, others fail.
288      */
289     int KillProcessesByAccessTokenId(const uint32_t accessTokenId);
290 
291     /**
292      * kill the application by uid
293      *
294      * @param bundleName name of bundle.
295      * @param uid uid of bundle.
296      * @param  reason, caller function name.
297      * @return 0 if success.
298      */
299     int KillApplicationByUid(const std::string &bundleName, int32_t uid,
300         const std::string& reason = "KillApplicationByUid");
301 
302      /**
303      * update the application info after new module installed.
304      *
305      * @param bundleName, bundle name in Application record.
306      * @param  uid, uid.
307      * @return 0 if success.
308      */
309     int UpdateApplicationInfoInstalled(const std::string &bundleName, const int32_t uid, const std::string &moduleName);
310 
311     /**
312      * Ability attach timeout. If start ability encounter failure, attach timeout to terminate.
313      *
314      * @param token Ability identify.
315      */
316     void AttachTimeOut(const sptr<IRemoteObject> &token);
317 
318     /**
319      * Prepare terminate.
320      *
321      * @param token Ability identify.
322      * @param clearMissionFlag Clear mission flag.
323      */
324     void PrepareTerminate(const sptr<IRemoteObject> &token, bool clearMissionFlag = false);
325 
326     /**
327      * Get running process information by ability token.
328      *
329      * @param token Ability identify.
330      * @param info Running process info.
331      */
332     void GetRunningProcessInfoByToken(const sptr<IRemoteObject> &token, AppExecFwk::RunningProcessInfo &info);
333 
334     /**
335      * Get running process information by pid.
336      *
337      * @param pid process id.
338      * @param info Output parameters, return runningProcessInfo.
339      * @return Returns ERR_OK on success, others on failure.
340      */
341     void GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExecFwk::RunningProcessInfo &info) const;
342 
343     /**
344      * Get running process information by child process pid.
345      *
346      * @param childPid child process id.
347      * @param info Output parameters, return runningProcessInfo.
348      * @return Returns ERR_OK on success, others on failure.
349      */
350     void GetRunningProcessInfoByChildProcessPid(const pid_t childPid,
351         OHOS::AppExecFwk::RunningProcessInfo &info) const;
352 
353     /**
354      * Set AbilityForegroundingFlag of an app-record to true.
355      *
356      * @param pid, pid.
357      *
358      */
359     void SetAbilityForegroundingFlagToAppRecord(const pid_t pid) const;
360 
361     /**
362      * Start a resident process
363      */
364     void StartupResidentProcess(const std::vector<AppExecFwk::BundleInfo> &bundleInfos);
365 
366     /**
367      * Start specified ability.
368      *
369      * @param want Want contains information of the ability to start.
370      * @param abilityInfo Ability information.
371      * @param requestId request id to callback
372      */
373     void StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo,
374         int32_t requestId = 0);
375 
376     /**
377      * @brief Get running process information.
378      *
379      * @param info Running process information.
380      * @return Returns ERR_OK on success, others on failure.
381      */
382     int GetProcessRunningInfos(std::vector<AppExecFwk::RunningProcessInfo> &info);
383 
384     /**
385      * Start specified process.
386      *
387      * @param want Want contains information wish to start.
388      * @param abilityInfo Ability information.
389      * @param requestId for callback
390      */
391     void StartSpecifiedProcess(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo,
392         int32_t requestId = 0);
393 
394     /**
395      * Start a user test
396      */
397     int StartUserTest(const Want &want, const sptr<IRemoteObject> &observer, const AppExecFwk::BundleInfo &bundleInfo,
398         int32_t userId);
399 
400     /**
401      * @brief Finish user test.
402      * @param msg user test message.
403      * @param resultCode user test result Code.
404      * @param bundleName user test bundleName.
405      *
406      * @return Returns ERR_OK on success, others on failure.
407      */
408     int FinishUserTest(const std::string &msg, const int64_t &resultCode, const std::string &bundleName);
409 
410     /**
411      * GetProcessRunningInfosByUserId, call GetProcessRunningInfosByUserId() through proxy project.
412      * Obtains information about application processes that are running on the device.
413      *
414      * @param info, app name in Application record.
415      * @param userId, user Id in Application record.
416      * @return ERR_OK ,return back success,others fail.
417      */
418     int GetProcessRunningInfosByUserId(std::vector<AppExecFwk::RunningProcessInfo> &info, int32_t userId);
419     std::string ConvertAppState(const AppState &state);
420 
421     /**
422      *  ANotify application update system environment changes.
423      *
424      * @param config System environment change parameters.
425      * @return Returns ERR_OK on success, others on failure.
426      */
427     int UpdateConfiguration(const AppExecFwk::Configuration &config);
428 
429     /**
430      * GetConfiguration
431      *
432      * @param info to retrieve configuration data.
433      * @return ERR_OK ,return back success,others fail.
434      */
435     int GetConfiguration(AppExecFwk::Configuration &config);
436 
437     /**
438      *  Get the token of ability records by process ID.
439      *
440      * @param pid The process id.
441      * @param tokens The token of ability records.
442      * @return Returns ERR_OK on success, others on failure.
443      */
444     int GetAbilityRecordsByProcessID(const int pid, std::vector<sptr<IRemoteObject>> &tokens);
445 
446     /**
447      *  Get the application info by process ID.
448      *
449      * @param pid The process id.
450      * @param application The application info.
451      * @param debug The app is or not debug.
452      * @return Returns ERR_OK on success, others on failure.
453      */
454     int GetApplicationInfoByProcessID(const int pid, AppExecFwk::ApplicationInfo &application, bool &debug);
455 
456     /**
457      *  Set the process cache status by process ID.
458      *
459      * @param pid The process id.
460      * @param isSupport The process is support cache.
461      * @return Returns ERR_OK on success, others on failure.
462      */
463     void SetProcessCacheStatus(int32_t pid, bool isSupport);
464 
465     /**
466      * Record process exit reason to appRunningRecord
467      * @param pid pid
468      * @param reason reason enum
469      * @param exitMsg exitMsg
470      * @return Returns ERR_OK on success, others on failure.
471      */
472     virtual int32_t NotifyAppMgrRecordExitReason(int32_t pid, int32_t reason, const std::string &exitMsg);
473 
474     /**
475      * Set the current userId of appMgr, only used by abilityMgr.
476      *
477      * @param userId the user id.
478      *
479      * @return
480      */
481     void SetCurrentUserId(int32_t userId);
482 
483     /**
484      * Set enable start process flag by userId
485      * @param userId the user id.
486      * @param enableStartProcess enable start process.
487      * @return
488      */
489     void SetEnableStartProcessFlagByUserId(int32_t userId, bool enableStartProcess);
490 
491     /**
492      * Get bundleName by pid.
493      *
494      * @param pid process id.
495      * @param bundleName Output parameters, return bundleName.
496      * @param uid Output parameters, return userId.
497      * @return Returns ERR_OK on success, others on failure.
498      */
499     int32_t GetBundleNameByPid(const int pid, std::string &bundleName, int32_t &uid);
500 
501     /**
502      * Notify Fault Data
503      *
504      * @param faultData the fault data.
505      * @return Returns ERR_OK on success, others on failure.
506      */
507     int32_t NotifyFault(const AppExecFwk::FaultData &faultData);
508 
509     /**
510      * @brief Register app debug listener.
511      * @param listener App debug listener.
512      * @return Returns ERR_OK on success, others on failure.
513      */
514     int32_t RegisterAppDebugListener(const sptr<AppExecFwk::IAppDebugListener> &listener);
515 
516     /**
517      * @brief Unregister app debug listener.
518      * @param listener App debug listener.
519      * @return Returns ERR_OK on success, others on failure.
520      */
521     int32_t UnregisterAppDebugListener(const sptr<AppExecFwk::IAppDebugListener> &listener);
522 
523     /**
524      * @brief Attach app debug.
525      * @param bundleName The application bundle name.
526      * @return Returns ERR_OK on success, others on failure.
527      */
528     int32_t AttachAppDebug(const std::string &bundleName, bool isDebugFromLocal);
529 
530     /**
531      * @brief Detach app debug.
532      * @param bundleName The application bundle name.
533      * @return Returns ERR_OK on success, others on failure.
534      */
535     int32_t DetachAppDebug(const std::string &bundleName);
536 
537     /**
538      * @brief Register ability debug response to set debug mode.
539      * @param bundleName The application bundle name.
540      * @return Returns ERR_OK on success, others on failure.
541      */
542     int32_t RegisterAbilityDebugResponse(const sptr<AppExecFwk::IAbilityDebugResponse> &response);
543 
544     /**
545      * @brief Determine whether it is an attachment debug application based on the bundle name.
546      * @param bundleName The application bundle name.
547      * @return Returns true if it is an attach debug application, otherwise it returns false.
548      */
549     bool IsAttachDebug(const std::string &bundleName);
550 
551     /**
552      * To clear the process by ability token.
553      *
554      * @param token the unique identification to the ability.
555      */
556     void ClearProcessByToken(sptr<IRemoteObject> token) const;
557 
558     /**
559      * whether memory size is sufficient.
560      * @return Returns true is sufficient memory size, others return false.
561      */
562     virtual bool IsMemorySizeSufficent() const;
563 
564     /**
565      * Notifies that one ability is attached to status bar.
566      *
567      * @param token the token of the abilityRecord that is attached to status bar.
568      */
569     void AttachedToStatusBar(const sptr<IRemoteObject> &token);
570 
571      /**
572      * Temporarily block the process cache feature.
573      *
574      * @param pids the pids of the processes that should be blocked.
575      */
576     void BlockProcessCacheByPids(const std::vector<int32_t>& pids);
577 
578     /**
579      * Request to clean uiability from user.
580      *
581      * @param token the token of ability.
582      * @return Returns true if clean success, others return false.
583      */
584     bool CleanAbilityByUserRequest(const sptr<IRemoteObject> &token);
585 
586     /**
587      * whether killed for upgrade web.
588      *
589      * @param bundleName the bundle name is killed for upgrade web.
590      * @return Returns true is killed for upgrade web, others return false.
591      */
592     bool IsKilledForUpgradeWeb(const std::string &bundleName);
593 
594     /**
595      * whether the abilities of process specified by pid type only UIAbility.
596      * @return Returns true is only UIAbility, otherwise return false
597      */
598     bool IsProcessContainsOnlyUIAbility(const pid_t pid);
599 
600     bool IsProcessAttached(sptr<IRemoteObject> token) const;
601 
602     bool IsCallerKilling(const std::string& callerKey) const;
603 
604 protected:
605     /**
606      * OnAbilityRequestDone, app manager service call this interface after ability request done.
607      *
608      * @param token,ability's token.
609      * @param state,the state of ability lift cycle.
610      */
611     virtual void OnAbilityRequestDone(const sptr<IRemoteObject> &token, const AppExecFwk::AbilityState state) override;
612 
613     /**
614      * Application state changed callback.
615      *
616      * @param appProcessData Process data
617      */
618     virtual void OnAppStateChanged(const AppExecFwk::AppProcessData &appData) override;
619 
620     /**
621      * @brief Notify application update system environment changes.
622      * @param config System environment change parameters.
623      * @param userId userId Designation User ID.
624      */
625     virtual void NotifyConfigurationChange(const AppExecFwk::Configuration &config, int32_t userId) override;
626 
627     /**
628      * @brief Notify abilityms start resident process.
629      * @param bundleInfos resident process bundle infos.
630      */
631     virtual void NotifyStartResidentProcess(std::vector<AppExecFwk::BundleInfo> &bundleInfos) override;
632 
633     /**
634      * @brief Notify abilityms start keep-alive process.
635      * @param bundleInfos resident process bundle infos.
636      */
637     virtual void NotifyStartKeepAliveProcess(std::vector<AppExecFwk::BundleInfo> &bundleInfos) override;
638 
639     /**
640      * @brief Notify abilityms app process OnRemoteDied
641      * @param abilityTokens abilities in died process.
642      */
643     virtual void OnAppRemoteDied(const std::vector<sptr<IRemoteObject>> &abilityTokens) override;
644 
645     virtual void OnStartProcessFailed(sptr<IRemoteObject> token) override;
646 
647     /**
648      * @brief Notify abilityms app process pre cache
649      * @param pid process pid.
650      * @param userId userId Designation User ID.
651      */
652     virtual void NotifyAppPreCache(int32_t pid, int32_t userId) override;
653 
654     /**
655      * @brief Notify abilityms exit info
656      * @param accessTokenId accessTokenId.
657      * @param exitInfo exit info before app died.
658      * @param bundleName app bundleName.
659      * @param abilityNames abilityNames in app.
660      * @param uiExtensionNames uiExtensionNames in app.
661      */
662     virtual void OnCacheExitInfo(uint32_t accessTokenId, const AAFwk::LastExitDetailInfo &exitInfo,
663         const std::string &bundleName, const std::vector<std::string> &abilityNames,
664         const std::vector<std::string> &uiExtensionNames) override;
665 
666 private:
667     bool isInit_  {false};
668     AppAbilityState appAbilityState_ = AppAbilityState::ABILITY_STATE_UNDEFINED;
669     std::weak_ptr<AppStateCallback> callback_;
670     std::unique_ptr<AppExecFwk::AppMgrClient> appMgrClient_;
671     sptr<StartSpecifiedAbilityResponse> startSpecifiedAbilityResponse_;
672     std::mutex lock_;
673 };
674 }  // namespace AAFwk
675 }  // namespace OHOS
676 #endif  // OHOS_ABILITY_RUNTIME_APP_SCHEDULER_H
677