1 /*
2  * Copyright (c) 2021-2024 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 };
81 /**
82  * @class AppStateCallback
83  * AppStateCallback.
84  */
85 class AppStateCallback {
86 public:
AppStateCallback()87     AppStateCallback()
88     {}
~AppStateCallback()89     virtual ~AppStateCallback()
90     {}
91 
92     virtual void OnAbilityRequestDone(const sptr<IRemoteObject> &token, const int32_t state) = 0;
93 
94     virtual void OnAppStateChanged(const AppInfo &info) = 0;
95 
NotifyConfigurationChange(const AppExecFwk::Configuration & config,int32_t userId)96     virtual void NotifyConfigurationChange(const AppExecFwk::Configuration &config, int32_t userId) {}
97 
NotifyStartResidentProcess(std::vector<AppExecFwk::BundleInfo> & bundleInfos)98     virtual void NotifyStartResidentProcess(std::vector<AppExecFwk::BundleInfo> &bundleInfos) {}
99 
NotifyAppPreCache(int32_t pid,int32_t userId)100     virtual void NotifyAppPreCache(int32_t pid, int32_t userId) {}
101 
OnAppRemoteDied(const std::vector<sptr<IRemoteObject>> & abilityTokens)102     virtual void OnAppRemoteDied(const std::vector<sptr<IRemoteObject>> &abilityTokens) {}
103 };
104 
105 class StartSpecifiedAbilityResponse : public AppExecFwk::StartSpecifiedAbilityResponseStub {
106 public:
107     StartSpecifiedAbilityResponse() = default;
108     virtual ~StartSpecifiedAbilityResponse() = default;
109 
110     virtual void OnAcceptWantResponse(const AAFwk::Want &want, const std::string &flag,
111         int32_t requestId) override;
112     virtual void OnTimeoutResponse(const AAFwk::Want &want, int32_t requestId) override;
113 
114     virtual void OnNewProcessRequestResponse(const AAFwk::Want &want, const std::string &flag,
115         int32_t requestId) override;
116     virtual void OnNewProcessRequestTimeoutResponse(const AAFwk::Want &want, int32_t requestId) override;
117 };
118 
119 /**
120  * @class AppScheduler
121  * AppScheduler , access app manager service.
122  */
123 class AppScheduler : virtual RefBase, public AppExecFwk::AppStateCallbackHost {
124     DECLARE_DELAYED_SINGLETON(AppScheduler)
125 public:
126     /**
127      * init app scheduler.
128      * @param callback, app state call back.
129      * @return true on success ,false on failure.
130      */
131     bool Init(const std::weak_ptr<AppStateCallback> &callback);
132 
133     /**
134      * load ability with token, ability info and application info.
135      *
136      * @param loadParam, the loadParam of ability.
137      * @param abilityInfo, ability info.
138      * @param applicationInfo, application info.
139      * @param want ability want
140      * @return true on success ,false on failure.
141      */
142     int LoadAbility(const AbilityRuntime::LoadParam &loadParam, const AppExecFwk::AbilityInfo &abilityInfo,
143         const AppExecFwk::ApplicationInfo &applicationInfo, const Want &want);
144 
145     /**
146      * terminate ability with token.
147      *
148      * @param token, the token of ability.
149      * @param clearMissionFlag, indicates whether terminate the ability when clearMission.
150      * @return true on success ,false on failure.
151      */
152     int TerminateAbility(const sptr<IRemoteObject> &token, bool clearMissionFlag);
153 
154     /**
155      * move ability to foreground.
156      *
157      * @param token, the token of ability.
158      */
159     void MoveToForeground(const sptr<IRemoteObject> &token);
160 
161     /**
162      * move ability to background.
163      *
164      * @param token, the token of ability.
165      */
166     void MoveToBackground(const sptr<IRemoteObject> &token);
167 
168     /**
169      * Update ability state.
170      *
171      * @param token, the token of ability.
172      * @param state, ability state.
173      */
174     void UpdateAbilityState(const sptr<IRemoteObject> &token, const AppExecFwk::AbilityState state);
175 
176     /**
177      * UpdateExtensionState, call UpdateExtensionState() through the proxy object, update the extension status.
178      *
179      * @param token, the unique identification to update the extension.
180      * @param state, extension status that needs to be updated.
181      * @return
182      */
183     void UpdateExtensionState(const sptr<IRemoteObject> &token, const AppExecFwk::ExtensionState state);
184 
185     /**
186      * AbilityBehaviorAnalysis, ability behavior analysis assistant process optimization.
187      *
188      * @param token, the unique identification to start the ability.
189      * @param preToken, the unique identification to call the ability.
190      * @param visibility, the visibility information about windows info.
191      * @param perceptibility, the Perceptibility information about windows info.
192      * @param connectionState, the service ability connection state.
193      * @return Returns RESULT_OK on success, others on failure.
194      */
195     void AbilityBehaviorAnalysis(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &preToken,
196         const int32_t visibility, const int32_t perceptibility, const int32_t connectionState);
197 
198     /**
199      * KillProcessByAbilityToken, call KillProcessByAbilityToken() through proxy object,
200      * kill the process by ability token.
201      *
202      * @param token, the unique identification to the ability.
203      */
204     void KillProcessByAbilityToken(const sptr<IRemoteObject> &token);
205 
206     /**
207      * KillProcessesByUserId, call KillProcessesByUserId() through proxy object,
208      * kill the process by user id.
209      *
210      * @param userId, the user id.
211      */
212     void KillProcessesByUserId(int32_t userId);
213 
214     void KillProcessesByPids(std::vector<int32_t> &pids);
215 
216     void AttachPidToParent(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &callerToken);
217 
218     /**
219      * convert ability state to app ability state.
220      *
221      * @param state, the state of ability.
222      */
223     AppAbilityState ConvertToAppAbilityState(const int32_t state);
224 
225     /**
226      * get ability state.
227      *
228      * @return state, the state of app ability.
229      */
230     AppAbilityState GetAbilityState() const;
231 
232     /**
233      * kill the application
234      *
235      * @param bundleName.
236      */
237     int KillApplication(const std::string &bundleName, const bool clearPageStack = true);
238 
239     /**
240      * ForceKillApplication, force kill the application.
241      *
242      * @param  bundleName, bundle name in Application record.
243      * @param  userId, userId.
244      * @param  appIndex, appIndex.
245      * @return ERR_OK, return back success, others fail.
246      */
247     int ForceKillApplication(const std::string &bundleName, const int userId = -1,
248         const int appIndex = 0);
249 
250     /**
251      * KillProcessesByAccessTokenId.
252      *
253      * @param  accessTokenId, accessTokenId.
254      * @return ERR_OK, return back success, others fail.
255      */
256     int KillProcessesByAccessTokenId(const uint32_t accessTokenId);
257 
258     /**
259      * kill the application by uid
260      *
261      * @param bundleName name of bundle.
262      * @param uid uid of bundle.
263      * @param  reason, caller function name.
264      * @return 0 if success.
265      */
266     int KillApplicationByUid(const std::string &bundleName, int32_t uid,
267         const std::string& reason = "KillApplicationByUid");
268 
269      /**
270      * update the application info after new module installed.
271      *
272      * @param bundleName, bundle name in Application record.
273      * @param  uid, uid.
274      * @return 0 if success.
275      */
276     int UpdateApplicationInfoInstalled(const std::string &bundleName, const int32_t uid);
277 
278     void AttachTimeOut(const sptr<IRemoteObject> &token);
279 
280     void PrepareTerminate(const sptr<IRemoteObject> &token, bool clearMissionFlag = false);
281 
282     void GetRunningProcessInfoByToken(const sptr<IRemoteObject> &token, AppExecFwk::RunningProcessInfo &info);
283 
284     void GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExecFwk::RunningProcessInfo &info) const;
285 
286     /**
287      * Set AbilityForegroundingFlag of an app-record to true.
288      *
289      * @param pid, pid.
290      *
291      */
292     void SetAbilityForegroundingFlagToAppRecord(const pid_t pid) const;
293 
294     /**
295      * Start a resident process
296      */
297     void StartupResidentProcess(const std::vector<AppExecFwk::BundleInfo> &bundleInfos);
298 
299     void StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo,
300         int32_t requestId = 0);
301     int GetProcessRunningInfos(std::vector<AppExecFwk::RunningProcessInfo> &info);
302 
303     void StartSpecifiedProcess(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo,
304         int32_t requestId = 0);
305 
306     /**
307      * Start a user test
308      */
309     int StartUserTest(const Want &want, const sptr<IRemoteObject> &observer, const AppExecFwk::BundleInfo &bundleInfo,
310         int32_t userId);
311 
312     /**
313      * @brief Finish user test.
314      * @param msg user test message.
315      * @param resultCode user test result Code.
316      * @param bundleName user test bundleName.
317      *
318      * @return Returns ERR_OK on success, others on failure.
319      */
320     int FinishUserTest(const std::string &msg, const int64_t &resultCode, const std::string &bundleName);
321 
322     int GetProcessRunningInfosByUserId(std::vector<AppExecFwk::RunningProcessInfo> &info, int32_t userId);
323     std::string ConvertAppState(const AppState &state);
324 
325     /**
326      *  ANotify application update system environment changes.
327      *
328      * @param config System environment change parameters.
329      * @return Returns ERR_OK on success, others on failure.
330      */
331     int UpdateConfiguration(const AppExecFwk::Configuration &config);
332 
333     int GetConfiguration(AppExecFwk::Configuration &config);
334 
335     /**
336      *  Get the token of ability records by process ID.
337      *
338      * @param pid The process id.
339      * @param tokens The token of ability records.
340      * @return Returns ERR_OK on success, others on failure.
341      */
342     int GetAbilityRecordsByProcessID(const int pid, std::vector<sptr<IRemoteObject>> &tokens);
343 
344     /**
345      *  Get the application info by process ID.
346      *
347      * @param pid The process id.
348      * @param application The application info.
349      * @param debug The app is or not debug.
350      * @return Returns ERR_OK on success, others on failure.
351      */
352     int GetApplicationInfoByProcessID(const int pid, AppExecFwk::ApplicationInfo &application, bool &debug);
353 
354     /**
355      *  Set the process cache status by process ID.
356      *
357      * @param pid The process id.
358      * @param isSupport The process is support cache.
359      * @return Returns ERR_OK on success, others on failure.
360      */
361     void SetProcessCacheStatus(int32_t pid, bool isSupport);
362 
363     /**
364      * Record process exit reason to appRunningRecord
365      * @param pid pid
366      * @param reason reason enum
367      * @param exitMsg exitMsg
368      * @return Returns ERR_OK on success, others on failure.
369      */
370     virtual int32_t NotifyAppMgrRecordExitReason(int32_t pid, int32_t reason, const std::string &exitMsg);
371 
372     /**
373      * Set the current userId of appMgr, only used by abilityMgr.
374      *
375      * @param userId the user id.
376      *
377      * @return
378      */
379     void SetCurrentUserId(int32_t userId);
380 
381     /**
382      * Set enable start process flag by userId
383      * @param userId the user id.
384      * @param enableStartProcess enable start process.
385      * @return
386      */
387     void SetEnableStartProcessFlagByUserId(int32_t userId, bool enableStartProcess);
388 
389     /**
390      * Get bundleName by pid.
391      *
392      * @param pid process id.
393      * @param bundleName Output parameters, return bundleName.
394      * @param uid Output parameters, return userId.
395      * @return Returns ERR_OK on success, others on failure.
396      */
397     int32_t GetBundleNameByPid(const int pid, std::string &bundleName, int32_t &uid);
398 
399     /**
400      * Notify Fault Data
401      *
402      * @param faultData the fault data.
403      * @return Returns ERR_OK on success, others on failure.
404      */
405     int32_t NotifyFault(const AppExecFwk::FaultData &faultData);
406 
407     /**
408      * @brief Register app debug listener.
409      * @param listener App debug listener.
410      * @return Returns ERR_OK on success, others on failure.
411      */
412     int32_t RegisterAppDebugListener(const sptr<AppExecFwk::IAppDebugListener> &listener);
413 
414     /**
415      * @brief Unregister app debug listener.
416      * @param listener App debug listener.
417      * @return Returns ERR_OK on success, others on failure.
418      */
419     int32_t UnregisterAppDebugListener(const sptr<AppExecFwk::IAppDebugListener> &listener);
420 
421     /**
422      * @brief Attach app debug.
423      * @param bundleName The application bundle name.
424      * @return Returns ERR_OK on success, others on failure.
425      */
426     int32_t AttachAppDebug(const std::string &bundleName);
427 
428     /**
429      * @brief Detach app debug.
430      * @param bundleName The application bundle name.
431      * @return Returns ERR_OK on success, others on failure.
432      */
433     int32_t DetachAppDebug(const std::string &bundleName);
434 
435     /**
436      * @brief Register ability debug response to set debug mode.
437      * @param bundleName The application bundle name.
438      * @return Returns ERR_OK on success, others on failure.
439      */
440     int32_t RegisterAbilityDebugResponse(const sptr<AppExecFwk::IAbilityDebugResponse> &response);
441 
442     /**
443      * @brief Determine whether it is an attachment debug application based on the bundle name.
444      * @param bundleName The application bundle name.
445      * @return Returns true if it is an attach debug application, otherwise it returns false.
446      */
447     bool IsAttachDebug(const std::string &bundleName);
448 
449     /**
450      * To clear the process by ability token.
451      *
452      * @param token the unique identification to the ability.
453      */
454     void ClearProcessByToken(sptr<IRemoteObject> token) const;
455 
456     /**
457      * whether memory size is sufficent.
458      * @return Returns true is sufficent memory size, others return false.
459      */
460     virtual bool IsMemorySizeSufficent() const;
461 
462     /**
463      * Notifies that one ability is attached to status bar.
464      *
465      * @param token the token of the abilityRecord that is attached to status bar.
466      */
467     void AttachedToStatusBar(const sptr<IRemoteObject> &token);
468 
469     void BlockProcessCacheByPids(const std::vector<int32_t>& pids);
470 
471     bool IsKilledForUpgradeWeb(const std::string &bundleName);
472 
473     /**
474      * Request to clean uiability from user.
475      *
476      * @param token the token of ability.
477      * @return Returns true if clean success, others return false.
478      */
479     bool CleanAbilityByUserRequest(const sptr<IRemoteObject> &token);
480 
481     /**
482      * whether the abilities of process specified by pid type only UIAbility.
483      * @return Returns true is only UIAbility, otherwise return false
484      */
485     bool IsProcessContainsOnlyUIAbility(const pid_t pid);
486 
487     bool IsProcessAttached(sptr<IRemoteObject> token) const;
488 
489 protected:
490     /**
491      * OnAbilityRequestDone, app manager service call this interface after ability request done.
492      *
493      * @param token,ability's token.
494      * @param state,the state of ability lift cycle.
495      */
496     virtual void OnAbilityRequestDone(const sptr<IRemoteObject> &token, const AppExecFwk::AbilityState state) override;
497 
498     /**
499      * Application state changed callback.
500      *
501      * @param appProcessData Process data
502      */
503     virtual void OnAppStateChanged(const AppExecFwk::AppProcessData &appData) override;
504 
505     /**
506      * @brief Notify application update system environment changes.
507      * @param config System environment change parameters.
508      * @param userId userId Designation User ID.
509      */
510     virtual void NotifyConfigurationChange(const AppExecFwk::Configuration &config, int32_t userId) override;
511 
512     /**
513      * @brief Notify abilityms start resident process.
514      * @param bundleInfos resident process bundle infos.
515      */
516     virtual void NotifyStartResidentProcess(std::vector<AppExecFwk::BundleInfo> &bundleInfos) override;
517 
518     virtual void OnAppRemoteDied(const std::vector<sptr<IRemoteObject>> &abilityTokens) override;
519 
520 
521     virtual void NotifyAppPreCache(int32_t pid, int32_t userId) override;
522 
523 private:
524     std::mutex lock_;
525     bool isInit_  {false};
526     std::weak_ptr<AppStateCallback> callback_;
527     std::unique_ptr<AppExecFwk::AppMgrClient> appMgrClient_;
528     AppAbilityState appAbilityState_ = AppAbilityState::ABILITY_STATE_UNDEFINED;
529     sptr<StartSpecifiedAbilityResponse> startSpecifiedAbilityResponse_;
530 };
531 }  // namespace AAFwk
532 }  // namespace OHOS
533 #endif  // OHOS_ABILITY_RUNTIME_APP_SCHEDULER_H
534