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_RUNNING_MANAGER_H
17 #define OHOS_ABILITY_RUNTIME_APP_RUNNING_MANAGER_H
18 
19 #include <map>
20 #include <mutex>
21 #include <regex>
22 #include <set>
23 
24 #include "ability_info.h"
25 #include "app_debug_listener_interface.h"
26 #include "app_jsheap_mem_info.h"
27 #include "app_malloc_info.h"
28 #include "app_mem_info.h"
29 #include "app_running_record.h"
30 #include "app_state_data.h"
31 #include "application_info.h"
32 #include "bundle_info.h"
33 #include "configuration.h"
34 #include "iremote_object.h"
35 #include "record_query_result.h"
36 #include "refbase.h"
37 #include "running_process_info.h"
38 
39 namespace OHOS {
40 namespace Rosen {
41 class WindowVisibilityInfo;
42 }
43 namespace AppExecFwk {
44 
45 class AppRunningManager : public std::enable_shared_from_this<AppRunningManager> {
46 public:
47     AppRunningManager();
48     virtual ~AppRunningManager();
49     /**
50      * CreateAppRunningRecord, Get or create application record information.
51      *
52      * @param token, the unique identification to start the ability.
53      * @param abilityInfo, ability information.
54      * @param appInfo, app information.
55      * @param processName, app process name.
56      * @param uid, app uid in Application record.
57      * @param result, If error occurs, error code is in |result|.
58      *
59      * @return AppRunningRecord pointer if success get or create.
60      */
61     std::shared_ptr<AppRunningRecord> CreateAppRunningRecord(
62         const std::shared_ptr<ApplicationInfo> &appInfo, const std::string &processName, const BundleInfo &bundleInfo);
63 
64     /**
65      * CheckAppRunningRecordIsExist, Get process record by application name and process Name.
66      *
67      * @param appName, the application name.
68      * @param processName, the process name.
69      * @param uid, the process uid.
70      *
71      * @return process record.
72      */
73     std::shared_ptr<AppRunningRecord> CheckAppRunningRecordIsExist(const std::string &appName,
74         const std::string &processName, const int uid, const BundleInfo &bundleInfo,
75         const std::string &specifiedProcessFlag = "");
76 
77 #ifdef APP_NO_RESPONSE_DIALOG
78     /**
79      * CheckAppRunningRecordIsExist, Check whether the process of the app exists by bundle name and process Name.
80      *
81      * @param bundleName, Indicates the bundle name of the bundle..
82      * @param ablityName, ablity name.
83      *
84      * @return true if exist.
85      */
86     bool CheckAppRunningRecordIsExist(const std::string &bundleName, const std::string &ablityName);
87 #endif
88 
89     /**
90      * CheckAppRunningRecordIsExistByBundleName, Check whether the process of the application exists.
91      *
92      * @param bundleName, the bundle name.
93      *
94      * @return, Return true if exist.
95      */
96     bool CheckAppRunningRecordIsExistByBundleName(const std::string &bundleName);
97 
98     /**
99      * CheckAppRunningRecordIsExistByUid, check app exist when concurrent.
100      *
101      * @param uid, the process uid.
102      * @return, Return true if exist.
103      */
104     bool CheckAppRunningRecordIsExistByUid(int32_t uid);
105 
106     /**
107      * CheckAppRunningRecordIsExistByBundleName, Check whether the process of the application exists.
108      *
109      * @param bundleName Indicates the bundle name of the bundle.
110      * @param appCloneIndex the appindex of the bundle.
111      * @param isRunning Obtain the running status of the application, the result is true if running, false otherwise.
112      * @return, Return ERR_OK if success, others fail.
113      */
114     int32_t CheckAppCloneRunningRecordIsExistByBundleName(const std::string &bundleName,
115         int32_t appCloneIndex, bool &isRunning);
116 
117     /**
118      * GetAppRunningRecordByPid, Get process record by application pid.
119      *
120      * @param pid, the application pid.
121      *
122      * @return process record.
123      */
124     std::shared_ptr<AppRunningRecord> GetAppRunningRecordByPid(const pid_t pid);
125 
126     /**
127      * GetAppRunningRecordByAbilityToken, Get process record by ability token.
128      *
129      * @param abilityToken, the ability token.
130      *
131      * @return process record.
132      */
133     std::shared_ptr<AppRunningRecord> GetAppRunningRecordByAbilityToken(const sptr<IRemoteObject> &abilityToken);
134 
135     /**
136      * OnRemoteDied, Equipment death notification.
137      *
138      * @param remote, Death client.
139      * @param appMgrServiceInner, Application manager service inner instance.
140      * @return
141      */
142     std::shared_ptr<AppRunningRecord> OnRemoteDied(const wptr<IRemoteObject> &remote,
143         std::shared_ptr<AppMgrServiceInner> appMgrServiceInner);
144 
145     /**
146      * GetAppRunningRecordMap, Get application record list.
147      *
148      * @return the application record list.
149      */
150     std::map<const int32_t, const std::shared_ptr<AppRunningRecord>> GetAppRunningRecordMap();
151 
152     /**
153      * RemoveAppRunningRecordById, Remove application information through application id.
154      *
155      * @param recordId, the application id.
156      * @return
157      */
158     void RemoveAppRunningRecordById(const int32_t recordId);
159 
160     /**
161      * ClearAppRunningRecordMap, Clear application record list.
162      *
163      * @return
164      */
165     void ClearAppRunningRecordMap();
166 
167     /**
168      * Get the pid of a non-resident process.
169      *
170      * @return Return true if found, otherwise return false.
171      */
172     bool ProcessExitByBundleName(
173         const std::string &bundleName, std::list<pid_t> &pids, const bool clearPageStack = true);
174     /**
175      * Get Foreground Applications.
176      *
177      * @return Foreground Applications.
178      */
179     void GetForegroundApplications(std::vector<AppStateData> &list);
180 
181     /*
182     *  ANotify application update system environment changes.
183     *
184     * @param config System environment change parameters.
185     * @return Returns ERR_OK on success, others on failure.
186     */
187     int32_t UpdateConfiguration(const Configuration &config, const int32_t userId = -1);
188 
189     /**
190      *  Update config by sa.
191      *
192      * @param config Application enviroment change parameters.
193      * @param name Application bundle name.
194      * @return Returns ERR_OK on success, others on failure.
195      */
196     int32_t UpdateConfigurationByBundleName(const Configuration &config, const std::string &name);
197 
198     /*
199     *  Notify application background of current memory level.
200     *
201     * @param level current memory level.
202     * @return Returns ERR_OK on success, others on failure.
203     */
204     int32_t NotifyMemoryLevel(int32_t level);
205 
206     /**
207      * Notify applications the current memory level.
208      *
209      * @param  procLevelMap , <pid_t, MemoryLevel>.
210      * @return Returns ERR_OK on success, others on failure.
211      */
212     int32_t NotifyProcMemoryLevel(const std::map<pid_t, MemoryLevel> &procLevelMap);
213 
214     /*
215     * Get the application's memory allocation info.
216     *
217     * @param pid, pid input.
218     * @param mallocInfo, dynamic storage information output.
219     *
220     * @return Returns ERR_OK on success, others on failure.
221     */
222     int32_t DumpHeapMemory(const int32_t pid, OHOS::AppExecFwk::MallocInfo &mallocInfo);
223 
224     /**
225      * DumpJsHeapMemory, call DumpJsHeapMemory() through proxy project.
226      * triggerGC and dump the application's jsheap memory info.
227      *
228      * @param info, pid, tid, needGc, needSnapshot
229      * @return Returns ERR_OK on success, others on failure.
230      */
231     int32_t DumpJsHeapMemory(OHOS::AppExecFwk::JsHeapDumpInfo &info);
232 
233     /**
234      * Set AbilityForegroundingFlag of an app-record to true.
235      *
236      * @param pid, pid.
237      *
238      */
239     void SetAbilityForegroundingFlagToAppRecord(const pid_t pid);
240 
241     void HandleTerminateTimeOut(int64_t eventId);
242     void HandleAbilityAttachTimeOut(const sptr<IRemoteObject> &token, std::shared_ptr<AppMgrServiceInner> serviceInner);
243     std::shared_ptr<AppRunningRecord> GetAppRunningRecord(const int64_t eventId);
244     void TerminateAbility(const sptr<IRemoteObject> &token, bool clearMissionFlag,
245         std::shared_ptr<AppMgrServiceInner> appMgrServiceInner);
246 
247     /**
248      *
249      * @brief update the application info after new module installed.
250      *
251      * @param appInfo The latest application info obtained from bms for update abilityRuntimeContext.
252      *
253      */
254     int32_t ProcessUpdateApplicationInfoInstalled(const ApplicationInfo &appInfo);
255 
256     bool ProcessExitByBundleNameAndUid(
257         const std::string &bundleName, const int uid, std::list<pid_t> &pids, const bool clearPageStack = true);
258     bool GetPidsByUserId(int32_t userId, std::list<pid_t> &pids);
259 
260     void PrepareTerminate(const sptr<IRemoteObject> &token, bool clearMissionFlag = false);
261 
262     std::shared_ptr<AppRunningRecord> GetTerminatingAppRunningRecord(const sptr<IRemoteObject> &abilityToken);
263 
264     void GetRunningProcessInfoByToken(const sptr<IRemoteObject> &token, AppExecFwk::RunningProcessInfo &info);
265     int32_t GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExecFwk::RunningProcessInfo &info);
266 
267     void initConfig(const Configuration &config);
268     void ClipStringContent(const std::regex &re, const std::string &source, std::string &afterCutStr);
269     std::shared_ptr<AppRunningRecord> GetAppRunningRecordByRenderPid(const pid_t pid);
270     std::shared_ptr<RenderRecord> OnRemoteRenderDied(const wptr<IRemoteObject> &remote);
271     bool GetAppRunningStateByBundleName(const std::string &bundleName);
272     int32_t NotifyLoadRepairPatch(const std::string &bundleName, const sptr<IQuickFixCallback> &callback);
273     int32_t NotifyHotReloadPage(const std::string &bundleName, const sptr<IQuickFixCallback> &callback);
274     int32_t NotifyUnLoadRepairPatch(const std::string &bundleName, const sptr<IQuickFixCallback> &callback);
275     bool IsApplicationFirstForeground(const AppRunningRecord &foregroundingRecord);
276     bool IsApplicationBackground(const AppRunningRecord &backgroundingRecord);
277     bool IsApplicationFirstFocused(const AppRunningRecord &foregroundingRecord);
278     bool IsApplicationUnfocused(const std::string &bundleName);
279     void OnWindowVisibilityChanged(const std::vector<sptr<OHOS::Rosen::WindowVisibilityInfo>> &windowVisibilityInfos);
280 
281     /**
282      * @brief Set attach app debug mode.
283      * @param bundleName The application bundle name.
284      * @param isAttachDebug Determine if it is in attach debug mode.
285      */
286     void SetAttachAppDebug(const std::string &bundleName, const bool &isAttachDebug);
287 
288     /**
289      * @brief Obtain app debug infos through bundleName.
290      * @param bundleName The application bundle name.
291      * @param isDetachDebug Determine if it is a Detach.
292      * @return Specify the stored app informations based on bundle name output.
293      */
294     std::vector<AppDebugInfo> GetAppDebugInfosByBundleName(const std::string &bundleName, const bool &isDetachDebug);
295 
296     /**
297      * @brief Obtain ability tokens through bundleName.
298      * @param bundleName The application bundle name.
299      * @param abilityTokens Specify the stored ability token based on bundle name output.
300      */
301     void GetAbilityTokensByBundleName(const std::string &bundleName, std::vector<sptr<IRemoteObject>> &abilityTokens);
302 
303     std::shared_ptr<AppRunningRecord> GetAppRunningRecordByChildProcessPid(const pid_t pid);
304     std::shared_ptr<ChildProcessRecord> OnChildProcessRemoteDied(const wptr<IRemoteObject> &remote);
305     bool IsChildProcessReachLimit(uint32_t accessTokenId);
306 
307     /**
308      * @brief Obtain number of app through bundlename.
309      * @param bundleName The application bundle name.
310      * @return Returns the number of queries.
311      */
312     int32_t GetAllAppRunningRecordCountByBundleName(const std::string &bundleName);
313 
314     int32_t SignRestartAppFlag(int32_t uid);
315 
316     int32_t GetAppRunningUniqueIdByPid(pid_t pid, std::string &appRunningUniqueId);
317 
318     int32_t GetAllUIExtensionRootHostPid(pid_t pid, std::vector<pid_t> &hostPids);
319 
320     int32_t GetAllUIExtensionProviderPid(pid_t hostPid, std::vector<pid_t> &providerPids);
321 
322     int32_t AddUIExtensionLauncherItem(int32_t uiExtensionAbilityId, pid_t hostPid, pid_t providerPid);
323     int32_t RemoveUIExtensionLauncherItem(pid_t pid);
324     int32_t RemoveUIExtensionLauncherItemById(int32_t uiExtensionAbilityId);
325 
326     int DumpIpcAllStart(std::string& result);
327 
328     int DumpIpcAllStop(std::string& result);
329 
330     int DumpIpcAllStat(std::string& result);
331 
332     int DumpIpcStart(const int32_t pid, std::string& result);
333 
334     int DumpIpcStop(const int32_t pid, std::string& result);
335 
336     int DumpIpcStat(const int32_t pid, std::string& result);
337 
338     int DumpFfrt(const std::vector<int32_t>& pids, std::string& result);
339 
340     bool IsAppProcessesAllCached(const std::string &bundleName, int32_t uid,
341         const std::set<std::shared_ptr<AppRunningRecord>> &cachedSet);
342 
343     int32_t UpdateConfigurationDelayed(const std::shared_ptr<AppRunningRecord> &appRecord);
344 
345     bool GetPidsByBundleNameUserIdAndAppIndex(const std::string &bundleName,
346         const int userId, const int appIndex, std::list<pid_t> &pids);
347 
348     bool HandleUserRequestClean(const sptr<IRemoteObject> &abilityToken, pid_t &pid, int32_t &uid);
349 
350     void SetMultiUserConfigurationMgr(const std::shared_ptr<MultiUserConfigurationMgr>& multiUserConfigurationMgr);
351 
352     bool CheckAppRunningRecordIsLast(const std::shared_ptr<AppRunningRecord> &appRecord);
353 
354 private:
355     std::shared_ptr<AbilityRunningRecord> GetAbilityRunningRecord(const int64_t eventId);
356     int32_t AssignRunningProcessInfoByAppRecord(
357         std::shared_ptr<AppRunningRecord> appRecord, AppExecFwk::RunningProcessInfo &info) const;
358     bool isCollaboratorReserveType(const std::shared_ptr<AppRunningRecord> &appRecord);
359 
360     void NotifyAppPreCache(const std::shared_ptr<AppRunningRecord>& appRecord,
361         const std::shared_ptr<AppMgrServiceInner>& appMgrServiceInner);
362 
363 private:
364     std::mutex runningRecordMapMutex_;
365     std::map<const int32_t, const std::shared_ptr<AppRunningRecord>> appRunningRecordMap_;
366 
367     std::mutex uiExtensionMapLock_;
368     std::map<int32_t, std::pair<pid_t, pid_t>> uiExtensionLauncherMap_;
369 
370     std::shared_ptr<Configuration> configuration_;
371     std::mutex updateConfigurationDelayedLock_;
372     std::map<const int32_t, bool> updateConfigurationDelayedMap_;
373     std::shared_ptr<MultiUserConfigurationMgr> multiUserConfigurationMgr_;
374 };
375 }  // namespace AppExecFwk
376 }  // namespace OHOS
377 
378 #endif  // OHOS_ABILITY_RUNTIME_APP_RUNNING_MANAGER_H
379