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_MGR_SERVICE_INNER_H
17 #define OHOS_ABILITY_RUNTIME_APP_MGR_SERVICE_INNER_H
18 
19 #include <list>
20 #include <map>
21 #include <mutex>
22 #include <regex>
23 #include <unordered_map>
24 #include <unordered_set>
25 #include <vector>
26 
27 #include "ability_debug_response_interface.h"
28 #include "ability_foreground_state_observer_interface.h"
29 #include "ability_info.h"
30 #include "advanced_security_mode_manager.h"
31 #include "app_death_recipient.h"
32 #include "app_debug_listener_interface.h"
33 #include "app_debug_manager.h"
34 #include "app_foreground_state_observer_interface.h"
35 #include "app_malloc_info.h"
36 #include "app_mgr_constants.h"
37 #include "app_mgr_event.h"
38 #include "app_preloader.h"
39 #include "app_record_id.h"
40 #include "app_running_manager.h"
41 #include "app_running_record.h"
42 #include "app_running_status_listener_interface.h"
43 #include "app_running_status_module.h"
44 #include "app_scheduler_interface.h"
45 #include "app_spawn_client.h"
46 #include "appexecfwk_errors.h"
47 #include "bundle_info.h"
48 #include "bundle_mgr_helper.h"
49 #include "child_process_info.h"
50 #include "child_process_request.h"
51 #include "cpp/mutex.h"
52 #include "event_report.h"
53 #include "fault_data.h"
54 #include "hisysevent.h"
55 #include "iapp_state_callback.h"
56 #include "iapplication_state_observer.h"
57 #include "iconfiguration_observer.h"
58 #include "iremote_object.h"
59 #include "irender_state_observer.h"
60 #include "istart_specified_ability_response.h"
61 #include "record_query_result.h"
62 #include "refbase.h"
63 #include "remote_client_manager.h"
64 #include "render_process_info.h"
65 #include "running_process_info.h"
66 #include "shared/base_shared_bundle_info.h"
67 #include "task_handler_wrap.h"
68 #include "want.h"
69 #include "app_jsheap_mem_info.h"
70 #include "running_multi_info.h"
71 
72 namespace OHOS {
73 namespace AbilityRuntime {
74 struct LoadParam;
75 }
76 namespace Rosen {
77 class WindowVisibilityInfo;
78 class FocusChangeInfo;
79 }
80 namespace AppExecFwk {
81 using OHOS::AAFwk::Want;
82 class WindowFocusChangedListener;
83 class WindowVisibilityChangedListener;
84 using LoadAbilityTaskFunc = std::function<void()>;
85 constexpr int32_t BASE_USER_RANGE = 200000;
86 
87 class AppMgrServiceInner : public std::enable_shared_from_this<AppMgrServiceInner> {
88 public:
89     struct ConfigurationObserverWithUserId {
90         sptr<IConfigurationObserver> observer;
91         int32_t userId = -1;
92     };
93     struct AppStateCallbackWithUserId {
94         sptr<IAppStateCallback> callback;
95         int32_t userId = -1;
96     };
97 
98     AppMgrServiceInner();
99     virtual ~AppMgrServiceInner();
100 
101     /**
102      * Initialize the object.
103      */
104     void Init();
105     /**
106      * LoadAbility, load the ability that needed to be started.
107      *
108      * @param token, the unique identification to start the ability.
109      * @param preToken, the unique identification to call the ability.
110      * @param abilityInfo, the ability information.
111      * @param appInfo, the app information.
112      * @param want the ability want.
113      *
114      * @return
115      */
116     virtual void LoadAbility(std::shared_ptr<AbilityInfo> abilityInfo, std::shared_ptr<ApplicationInfo> appInfo,
117         std::shared_ptr<AAFwk::Want> want, std::shared_ptr<AbilityRuntime::LoadParam> loadParam);
118 
119     /**
120      * TerminateAbility, terminate the token ability.
121      *
122      * @param token, he unique identification to terminate the ability.
123      * @param clearMissionFlag, indicates whether terminate the ability when clearMission.
124      * @return
125      */
126     virtual void TerminateAbility(const sptr<IRemoteObject> &token, bool clearMissionFlag);
127 
128     /**
129      * UpdateAbilityState, update the ability status.
130      *
131      * @param token, the unique identification to update the ability.
132      * @param state, ability status that needs to be updated.
133      *
134      * @return
135      */
136     virtual void UpdateAbilityState(const sptr<IRemoteObject> &token, const AbilityState state);
137 
138     /**
139      * UpdateExtensionState, call UpdateExtensionState() through the proxy object, update the extension status.
140      *
141      * @param token, the unique identification to update the extension.
142      * @param state, extension status that needs to be updated.
143      */
144     virtual void UpdateExtensionState(const sptr<IRemoteObject> &token, const ExtensionState state);
145 
146     /**
147      * StateChangedNotifyObserver, Call ability state change.
148      *
149      * @param ability, the ability info.
150      * @param state, the ability state.
151      *
152      * @return
153      */
154     void StateChangedNotifyObserver(
155         const AbilityStateData abilityStateData, bool isAbility, bool isFromWindowFocusChanged);
156 
157     /**
158      * RegisterAppStateCallback, register the callback.
159      *
160      * @param callback, Ams register the callback.
161      *
162      * @return
163      */
164     virtual void RegisterAppStateCallback(const sptr<IAppStateCallback> &callback);
165     void RemoveDeadAppStateCallback(const wptr<IRemoteObject> &remote);
166 
167     /**
168      * AbilityBehaviorAnalysis, ability behavior analysis assistant process optimization.
169      *
170      * @param token, the unique identification to start the ability.
171      * @param preToken, the unique identification to call the ability.
172      * @param visibility, the visibility information about windows info.
173      * @param perceptibility, the Perceptibility information about windows info.
174      * @param connectionState, the service ability connection state.
175      * @return
176      */
177     virtual void AbilityBehaviorAnalysis(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &preToken,
178         const int32_t visibility, const int32_t perceptibility, const int32_t connectionState);
179 
180     /**
181      * KillProcessByAbilityToken, kill the process by ability token.
182      *
183      * @param token, the unique identification to the ability.
184      * @return
185      */
186     virtual void KillProcessByAbilityToken(const sptr<IRemoteObject> &token);
187 
188     /**
189      * KillProcessesByUserId, kill the processes by userId.
190      *
191      * @param userId, the user id.
192      * @return
193      */
194     virtual void KillProcessesByUserId(int32_t userId);
195 
196     virtual void KillProcessesByPids(std::vector<int32_t> &pids);
197 
198     /**
199      * KillProcessesInBatch, kill processes in batch;
200      * the killed bundle won't be started by the watcher.
201      *
202      * @param pids, the pid list of processes are going to be killed.
203      * @return ERR_OK, return back success, others fail.
204      */
205     virtual int32_t KillProcessesInBatch(const std::vector<int32_t> &pids);
206 
207     virtual void AttachPidToParent(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &callerToken);
208 
209     /**
210      * AttachApplication, get all the information needed to start the Application
211      * (data related to the Application ).
212      *
213      * @param appScheduler, information needed to start the Application.
214      *
215      * @return
216      */
217     virtual void AttachApplication(const pid_t pid, const sptr<IAppScheduler> &appScheduler);
218 
219     /**
220      * Preload application.
221      *
222      * @param bundleName The bundle name of the application to preload.
223      * @param userId Indicates the user identification.
224      * @param preloadMode Preload application mode.
225      * @param appIndex The index of application clone.
226      * @return Returns ERR_OK on success, others on failure.
227      */
228     virtual int32_t PreloadApplication(const std::string &bundleName, int32_t userId,
229         AppExecFwk::PreloadMode preloadMode, int32_t appIndex);
230 
231     /**
232      * ApplicationForegrounded, set the application to Foreground State.
233      *
234      * @param recordId, a unique record that identifies this Application from others.
235      *
236      * @return
237      */
238     virtual void ApplicationForegrounded(const int32_t recordId);
239 
240     /**
241      * ApplicationBackgrounded, set the application to Backgrounded State.
242      *
243      * @param recordId, a unique record that identifies this Application from others.
244      *
245      * @return
246      */
247     virtual void ApplicationBackgrounded(const int32_t recordId);
248 
249     /**
250      * ApplicationTerminated, terminate the application.
251      *
252      * @param recordId, a unique record that identifies this Application from others.
253      *
254      * @return
255      */
256     virtual void ApplicationTerminated(const int32_t recordId);
257 
258     /**
259      * AbilityTerminated, terminate the ability.
260      *
261      * @param token, the unique identification to terminated the ability.
262      *
263      * @return
264      */
265     virtual void AbilityTerminated(const sptr<IRemoteObject> &token);
266 
267      /**
268      * UpdateApplicationInfoInstalled, update the application info after new module installed.
269      *
270      * @param bundleName, bundle name in Application record.
271      * @param  uid, uid.
272      * @return ERR_OK, return back success, others fail.
273      */
274     virtual int32_t UpdateApplicationInfoInstalled(const std::string &bundleName, const int uid);
275 
276     /**
277      * KillApplication, kill the application.
278      *
279      * @param  bundleName, bundle name in Application record.
280      *
281      * @return ERR_OK, return back success, others fail.
282      */
283     virtual int32_t KillApplication(const std::string &bundleName, const bool clearPageStack = true);
284 
285     /**
286      * ForceKillApplication, force kill the application.
287      *
288      * @param  bundleName, bundle name in Application record.
289      * @param  userId, userId.
290      * @param  appIndex, appIndex.
291      * @return ERR_OK, return back success, others fail.
292      */
293     virtual int32_t ForceKillApplication(const std::string &bundleName, const int userId = -1,
294         const int appIndex = 0);
295 
296     /**
297      * KillProcessesByAccessTokenId.
298      *
299      * @param  accessTokenId, accessTokenId.
300      * @return ERR_OK, return back success, others fail.
301      */
302     virtual int32_t KillProcessesByAccessTokenId(const uint32_t accessTokenId);
303 
304     /**
305      * KillApplicationByUid, call KillApplicationByUid() through proxy object, kill the application.
306      *
307      * @param  bundleName, bundle name in Application record.
308      * @param  uid, uid.
309      * @param  reason, caller function name.
310      * @return ERR_OK, return back success, others fail.
311      */
312     virtual int32_t KillApplicationByUid(const std::string &bundleName, const int uid,
313         const std::string& reason = "KillApplicationByUid");
314 
315     virtual int32_t KillApplicationSelf(const bool clearPageStack = false,
316         const std::string& reason = "KillApplicationSelf");
317 
318     /**
319      * KillApplicationByUserId, kill the application by user ID.
320      *
321      * @param bundleName, bundle name in Application record.
322      * @param appCloneIndex the app clone id.
323      * @param userId, user ID.
324      * @param  reason, caller function name.
325      *
326      * @return ERR_OK, return back success, others fail.
327      */
328     virtual int32_t KillApplicationByUserId(
329         const std::string &bundleName, int32_t appCloneIndex, int userId, const bool clearPageStack = false,
330         const std::string& reason = "KillApplicationByUserId");
331 
332     /**
333      * ClearUpApplicationData, clear the application data.
334      *
335      * @param bundleName, bundle name in Application record.
336      * @param callerUid, app uid in Application record.
337      * @param callerPid, app pid in Application record.
338      * @param appCloneIndex the app clone id.
339      * @param userId the user id
340      * @return ERR_OK, return back success, others fail.
341      */
342     virtual int32_t ClearUpApplicationData(const std::string &bundleName,
343         int32_t callerUid, pid_t callerPid, int32_t appCloneIndex, int32_t userId = -1);
344 
345     /**
346      * ClearUpApplicationDataBySelf, clear the application data.
347      *
348      * @param callerUid, app uid in Application record.
349      * @param callerPid, app pid in Application record.
350      * @param userId, user ID.
351      *
352      * @return ERR_OK, return back success, others fail.
353      */
354     virtual int32_t ClearUpApplicationDataBySelf(int32_t callerUid, pid_t callerPid,  int32_t userId = -1);
355 
356     /**
357      * GetAllRunningProcesses, Obtains information about application processes that are running on the device.
358      *
359      * @param info, app name in Application record.
360      *
361      * @return ERR_OK ,return back success,others fail.
362      */
363     virtual int32_t GetAllRunningProcesses(std::vector<RunningProcessInfo> &info);
364 
365     /**
366      * GetRunningMultiAppInfoByBundleName, call GetRunningMultiAppInfoByBundleName through proxy project.
367      * Obtains information about TwinApp that are running on the device.
368      *
369      * @param bundleName, input.
370      * @param info, output multiapp information.
371      * @return void.
372      */
373     virtual int32_t GetRunningMultiAppInfoByBundleName(const std::string &bundleName,
374         RunningMultiAppInfo &info);
375 
376     /**
377      * GetAllRunningInstanceKeysBySelf, call GetAllRunningInstanceKeysBySelf() through proxy project.
378      * Obtains running instance keys of multi-instance app that are running on the device.
379      *
380      * @param instanceKeys, output instance keys of the multi-instance app.
381      * @return ERR_OK ,return back success,others fail.
382      */
383     virtual int32_t GetAllRunningInstanceKeysBySelf(std::vector<std::string> &instanceKeys);
384 
385     /**
386      * GetAllRunningInstanceKeysByBundleName, call GetAllRunningInstanceKeysByBundleName() through proxy project.
387      * Obtains running isntance keys of multi-instance app that are running on the device.
388      *
389      * @param bundlename, bundle name in Application record.
390      * @param instanceKeys, output instance keys of the multi-insatnce app.
391      * @param userId, user id.
392      * @return ERR_OK ,return back success,others fail.
393      */
394     virtual int32_t GetAllRunningInstanceKeysByBundleName(const std::string &bundleName,
395         std::vector<std::string> &instanceKeys, int32_t userId = -1);
396 
397     /**
398      * GetRunningProcessesByBundleType, Obtains information about application processes by bundle type.
399      *
400      * @param bundleType, the bundle type of the application process
401      * @param info, app name in Application record.
402      *
403      * @return ERR_OK ,return back success,others fail.
404      */
405     virtual int32_t GetRunningProcessesByBundleType(BundleType bundleType, std::vector<RunningProcessInfo> &info);
406 
407     /**
408      * GetProcessRunningInfosByUserId, Obtains information about application processes that are running on the device.
409      *
410      * @param info, app name in Application record.
411      * @param userId, userId.
412      *
413      * @return ERR_OK ,return back success,others fail.
414      */
415     virtual int32_t GetProcessRunningInfosByUserId(std::vector<RunningProcessInfo> &info, int32_t userId);
416 
417     /**
418      * GetProcessRunningInformation, Obtains information about current application process
419      * which is running on the device.
420      * @param info, app name in Application record.
421      *
422      * @return ERR_OK ,return back success,others fail.
423      */
424     virtual int32_t GetProcessRunningInformation(RunningProcessInfo &info);
425 
426     /**
427      * GetAllRenderProcesses, Obtains information about render processes that are running on the device.
428      *
429      * @param info, render process record.
430      *
431      * @return ERR_OK, return back success, others fail.
432      */
433     virtual int32_t GetAllRenderProcesses(std::vector<RenderProcessInfo> &info);
434 
435     /**
436      * GetAllChildrenProcesses, call GetAllChildrenProcesses() through proxy project.
437      * Obtains information about children processes that are running on the device.
438      *
439      * @param info, child process info.
440      * @return ERR_OK, return back success, others fail.
441      */
442     virtual int GetAllChildrenProcesses(std::vector<ChildProcessInfo> &info);
443 
444     /**
445      * NotifyMemoryLevel, Notify applications background the current memory level.
446      *
447      * @param level, current memory level.
448      *
449      * @return ERR_OK ,return back success,others fail.
450      */
451     virtual int32_t NotifyMemoryLevel(int32_t level);
452 
453     /**
454      * NotifyProcMemoryLevel, Notify applications background the current memory level.
455      *
456      * @param procLevelMap , <pid_t, MemoryLevel>.
457      *
458      * @return ERR_OK ,return back success,others fail.
459      */
460     virtual int32_t NotifyProcMemoryLevel(const std::map<pid_t, MemoryLevel> &procLevelMap);
461 
462     /**
463      * DumpHeapMemory, get the application's memory info.
464      * Get the application's memory allocation info.
465      *
466      * @param pid, pid input.
467      * @param mallocInfo, dynamic storage information output.
468      *
469      * @return ERR_OK, return back success,others fail.
470      */
471     virtual int32_t DumpHeapMemory(const int32_t pid, OHOS::AppExecFwk::MallocInfo &mallocInfo);
472 
473     /**
474      * DumpJsHeapMemory, call DumpJsHeapMemory() through proxy project.
475      * triggerGC and dump the application's jsheap memory info.
476      *
477      * @param info, pid, tid, needGc, needSnapshot
478      * @return Returns ERR_OK on success, others on failure.
479      */
480     virtual int32_t DumpJsHeapMemory(OHOS::AppExecFwk::JsHeapDumpInfo &info);
481 
482     /**
483      * @brief Check whether the shared bundle is running.
484      *
485      * @param bundleName Shared bundle name.
486      * @param versionCode Shared bundle version code.
487      * @return Returns the shared bundle running result. The result is true if running, false otherwise.
488      */
489     virtual bool IsSharedBundleRunning(const std::string &bundleName, uint32_t versionCode);
490 
491     /**
492      * Check whether the bundle is running.
493      *
494      * @param bundleName Indicates the bundle name of the bundle.
495      * @param isRunning Obtain the running status of the application, the result is true if running, false otherwise.
496      * @return Return ERR_OK if success, others fail.
497      */
498     int32_t IsApplicationRunning(const std::string &bundleName, bool &isRunning);
499 
500     /**
501      * Check whether the bundle is running.
502      *
503      * @param bundleName Indicates the bundle name of the bundle.
504      * @param appCloneIndex the appindex of the bundle.
505      * @param isRunning Obtain the running status of the application, the result is true if running, false otherwise.
506      * @return Return ERR_OK if success, others fail.
507      */
508     int32_t IsAppRunning(const std::string &bundleName, int32_t appCloneIndex, bool &isRunning);
509 
510     int32_t StartNativeProcessForDebugger(const AAFwk::Want &want);
511 
512     std::shared_ptr<AppRunningRecord> CreateAppRunningRecord(
513         sptr<IRemoteObject> token,
514         sptr<IRemoteObject> preToken,
515         std::shared_ptr<ApplicationInfo> appInfo,
516         std::shared_ptr<AbilityInfo> abilityInfo,
517         const std::string &processName,
518         const BundleInfo &bundleInfo,
519         const HapModuleInfo &hapModuleInfo,
520         std::shared_ptr<AAFwk::Want> want,
521         int32_t abilityRecordId);
522 
523     /**
524      * OnStop, Application management service stopped.
525      *
526      * @return
527      */
528     void OnStop();
529 
530     /**
531      * OpenAppSpawnConnection, Open connection with appspawn.
532      *
533      * @return ERR_OK ,return back success,others fail.
534      */
535     virtual ErrCode OpenAppSpawnConnection();
536 
537     /**
538      * CloseAppSpawnConnection, Close connection with appspawn.
539      *
540      * @return
541      */
542     virtual void CloseAppSpawnConnection() const;
543 
544     /**
545      * QueryAppSpawnConnectionState, Query the connection status with appspawn.
546      *
547      * @return Returns the connection status with appspawn.
548      */
549     virtual SpawnConnectionState QueryAppSpawnConnectionState() const;
550 
551     /**
552      * SetAppSpawnClient, Setting the client to connect with appspawn.
553      *
554      * @param spawnClient, the client to connect with appspawn.
555      *
556      * @return
557      */
558     void SetAppSpawnClient(std::shared_ptr<AppSpawnClient> spawnClient);
559 
560     // Schedule launch application with specified |appRecord|
561 
562     /**
563      * LaunchApplication, Notify application to launch application.
564      *
565      * @param appRecord, the application record.
566      *
567      * @return
568      */
569     void LaunchApplication(const std::shared_ptr<AppRunningRecord> &appRecord);
570 
571     /**
572      * LaunchApplicationExt, to solve the nbnc of method over 50.
573      *
574      * @param appRecord, the application record.
575      *
576      * @return
577      */
578     void LaunchApplicationExt(const std::shared_ptr<AppRunningRecord> &appRecord);
579 
580     /**
581      * Notice of AddAbilityStageInfo()
582      *
583      * @param recordId, the application record.
584      */
585     virtual void AddAbilityStageDone(const int32_t recordId);
586 
587     /**
588      * GetAppRunningRecordByPid, Get process record by application pid.
589      *
590      * @param pid, the application pid.
591      *
592      * @return process record.
593      */
594     std::shared_ptr<AppRunningRecord> GetAppRunningRecordByPid(const pid_t pid) const;
595 
596     /**
597      * GetAppRunningRecordByAbilityToken, Get process record by ability token.
598      *
599      * @param abilityToken, the ability token.
600      *
601      * @return process record.
602      */
603     std::shared_ptr<AppRunningRecord> GetAppRunningRecordByAbilityToken(const sptr<IRemoteObject> &abilityToken) const;
604 
605     /**
606      * GetTerminatingAppRunningRecord, Get process record by ability token.
607      *
608      * @param abilityToken, the ability token.
609      *
610      * @return process record.
611      */
612     std::shared_ptr<AppRunningRecord> GetTerminatingAppRunningRecord(const sptr<IRemoteObject> &token) const;
613 
614     /**
615      * GetAppRunningRecordByAppRecordId, Get process record by application id.
616      *
617      * @param recordId, the application id.
618      *
619      * @return process record.
620      */
621     std::shared_ptr<AppRunningRecord> GetAppRunningRecordByAppRecordId(const int32_t recordId) const;
622 
623     /**
624      * OnAbilityStateChanged, Call ability state change.
625      *
626      * @param ability, the ability info.
627      * @param state, the ability state.
628      *
629      * @return
630      */
631     void OnAbilityStateChanged(const std::shared_ptr<AbilityRunningRecord> &ability, const AbilityState state);
632 
633     /**
634      * OnRemoteDied, Equipment death notification.
635      *
636      * @param remote, Death client.
637      * @param isRenderProcess is render process died.
638      * @param isChildProcess is child process died.
639      * @return
640      */
641     void OnRemoteDied(const wptr<IRemoteObject> &remote, bool isRenderProcess = false, bool isChildProcess = false);
642 
643     void HandleTimeOut(const AAFwk::EventWrap &event);
644 
DecreaseWillKillPidsNum()645     void DecreaseWillKillPidsNum()
646     {
647         willKillPidsNum_ -= 1;
648     }
649 
SetTaskHandler(std::shared_ptr<AAFwk::TaskHandlerWrap> taskHandler)650     void SetTaskHandler(std::shared_ptr<AAFwk::TaskHandlerWrap> taskHandler)
651     {
652         taskHandler_ = taskHandler;
653     }
654 
SetEventHandler(const std::shared_ptr<AMSEventHandler> & eventHandler)655     void SetEventHandler(const std::shared_ptr<AMSEventHandler> &eventHandler)
656     {
657         eventHandler_ = eventHandler;
658     }
659 
660     void HandleAbilityAttachTimeOut(const sptr<IRemoteObject> &token);
661 
662     void PrepareTerminate(const sptr<IRemoteObject> &token, bool clearMissionFlag = false);
663 
664     void OnAppStateChanged(const std::shared_ptr<AppRunningRecord> &appRecord, const ApplicationState state,
665         bool needNotifyApp, bool isFromWindowFocusChanged);
666 
667     void OnAppStarted(const std::shared_ptr<AppRunningRecord> &appRecord);
668 
669     void OnAppStopped(const std::shared_ptr<AppRunningRecord> &appRecord);
670 
671     void GetRunningProcessInfoByToken(const sptr<IRemoteObject> &token, AppExecFwk::RunningProcessInfo &info);
672 
673     int32_t GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExecFwk::RunningProcessInfo &info) const;
674 
675     /**
676      * Set AbilityForegroundingFlag of an app-record to true.
677      *
678      * @param pid, pid.
679      *
680      */
681     void SetAbilityForegroundingFlagToAppRecord(const pid_t pid) const;
682 
683      /**
684      * UpdateConfiguration, ANotify application update system environment changes.
685      *
686      * @param config, System environment change parameters.
687      * @return Returns ERR_OK on success, others on failure.
688      */
689     int32_t UpdateConfiguration(const Configuration &config, const int32_t userId = -1);
690 
691     int32_t UpdateConfigurationByBundleName(const Configuration &config, const std::string &name);
692 
693     std::shared_ptr<AppExecFwk::Configuration> GetConfiguration();
694 
695     int32_t RegisterConfigurationObserver(const sptr<IConfigurationObserver>& observer);
696 
697     int32_t UnregisterConfigurationObserver(const sptr<IConfigurationObserver>& observer);
698 
699     /**
700      * Start empty process
701      */
702     void LoadResidentProcess(const std::vector<BundleInfo> &infos);
703 
704     void StartResidentProcess(const std::vector<BundleInfo> &infos,  int restartCount, bool isEmptyKeepAliveApp);
705 
706     bool CheckRemoteClient();
707 
708     /**
709      * Register application or process state observer.
710      * @param observer, ability token.
711      * @return Returns ERR_OK on success, others on failure.
712      */
713     int32_t RegisterApplicationStateObserver(const sptr<IApplicationStateObserver> &observer,
714         const std::vector<std::string> &bundleNameList = {});
715 
716     /**
717      * Unregister application or process state observer.
718      * @param observer, ability token.
719      * @return Returns ERR_OK on success, others on failure.
720      */
721     int32_t UnregisterApplicationStateObserver(const sptr<IApplicationStateObserver> &observer);
722 
723     /**
724      * Register application or process state observer.
725      * @param observer, Is ability foreground state observer
726      * @return Returns ERR_OK on success, others on failure.
727      */
728     int32_t RegisterAbilityForegroundStateObserver(const sptr<IAbilityForegroundStateObserver> &observer);
729 
730     /**
731      * Unregister application or process state observer.
732      * @param observer, Is ability foreground state observer
733      * @return Returns ERR_OK on success, others on failure.
734      */
735     int32_t UnregisterAbilityForegroundStateObserver(const sptr<IAbilityForegroundStateObserver> &observer);
736 
737     /**
738      * Get Foreground Applications.
739      *
740      * @return Foreground Applications.
741      */
742     int32_t GetForegroundApplications(std::vector<AppStateData> &list);
743 
744     /**
745      * Start user test process.
746      * @param want, want object.
747      * @param observer, test observer remote object.
748      * @param bundleInfo, bundle info.
749      * @param userId the user id.
750      * @return Returns ERR_OK on success, others on failure.
751      */
752     int StartUserTestProcess(const AAFwk::Want &want, const sptr<IRemoteObject> &observer,
753         const AppExecFwk::BundleInfo &bundleInfo, int32_t userId);
754 
755     /**
756      * @brief Finish user test.
757      * @param msg user test message.
758      * @param resultCode user test result Code.
759      * @param bundleName user test bundleName.
760      * @param pid the user test process id.
761      *
762      * @return Returns ERR_OK on success, others on failure.
763      */
764     int FinishUserTest(
765         const std::string &msg, const int64_t &resultCode, const std::string &bundleName, const pid_t &pid);
766 
767     void StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo,
768         int32_t requestId = 0);
769 
770     void StartSpecifiedProcess(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo,
771         int32_t requestId = 0);
772 
773     void RegisterStartSpecifiedAbilityResponse(const sptr<IStartSpecifiedAbilityResponse> &response);
774 
775     void ScheduleAcceptWantDone(const int32_t recordId, const AAFwk::Want &want, const std::string &flag);
776 
777     void ScheduleNewProcessRequestDone(const int32_t recordId, const AAFwk::Want &want, const std::string &flag);
778 
779     /**
780      *  Get the token of ability records by process ID.
781      *
782      * @param pid The process id.
783      * @param tokens The token of ability records.
784      * @return Returns true on success, others on failure.
785      */
786     int GetAbilityRecordsByProcessID(const int pid, std::vector<sptr<IRemoteObject>> &tokens);
787 
788     virtual int32_t PreStartNWebSpawnProcess(const pid_t hostPid);
789 
790     virtual int32_t StartRenderProcess(const pid_t hostPid,
791                                        const std::string &renderParam,
792                                        int32_t ipcFd, int32_t sharedFd,
793                                        int32_t crashFd, pid_t &renderPid, bool isGPU = false);
794 
795     virtual void AttachRenderProcess(const pid_t pid, const sptr<IRenderScheduler> &scheduler);
796 
797     virtual int GetRenderProcessTerminationStatus(pid_t renderPid, int &status);
798 
799     int VerifyKillProcessPermission(const sptr<IRemoteObject> &token) const;
800 
801     int VerifyAccountPermission(const std::string &permissionName, const int userId) const;
802 
803     int VerifyRequestPermission() const;
804 
805     void ClearAppRunningData(const std::shared_ptr<AppRunningRecord> &appRecord, bool containsApp);
806 
807     void TerminateApplication(const std::shared_ptr<AppRunningRecord> &appRecord);
808 
809     int GetApplicationInfoByProcessID(const int pid, AppExecFwk::ApplicationInfo &application, bool &debug);
810 
811     int32_t NotifyAppMgrRecordExitReason(int32_t pid, int32_t reason, const std::string &exitMsg);
812 
813     /**
814      * Notify application status.
815      *
816      * @param bundleName Indicates the name of the bundle.
817      * @param eventData Indicates the event defined by CommonEventSupport
818      *
819      * @return
820      */
821     void NotifyAppStatus(const std::string &bundleName, const std::string &eventData);
822 
823     int32_t KillProcessByPid(const pid_t pid, const std::string& reason = "foundation");
824 
825     bool GetAppRunningStateByBundleName(const std::string &bundleName);
826 
827     int32_t NotifyLoadRepairPatch(const std::string &bundleName, const sptr<IQuickFixCallback> &callback);
828 
829     int32_t NotifyHotReloadPage(const std::string &bundleName, const sptr<IQuickFixCallback> &callback);
830 
831     int32_t NotifyUnLoadRepairPatch(const std::string &bundleName, const sptr<IQuickFixCallback> &callback);
832 
833     void HandleFocused(const sptr<OHOS::Rosen::FocusChangeInfo> &focusChangeInfo);
834     void HandleUnfocused(const sptr<OHOS::Rosen::FocusChangeInfo> &focusChangeInfo);
835 
836     /**
837      * Handle window visibility changed.
838      */
839     void HandleWindowVisibilityChanged(
840             const std::vector<sptr<OHOS::Rosen::WindowVisibilityInfo>> &windowVisibilityInfos);
841 
842     /**
843      * Set the current userId, only used by abilityMgr.
844      *
845      * @param userId the user id.
846      *
847      * @return
848      */
849     void SetCurrentUserId(const int32_t userId);
850 
851     /**
852      * Set enable start process flag by userId
853      * @param userId the user id.
854      * @param enableStartProcess enable start process.
855      * @return
856      */
857     void SetEnableStartProcessFlagByUserId(int32_t userId, bool enableStartProcess);
858 
859 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
860     int32_t SetContinuousTaskProcess(int32_t pid, bool isContinuousTask);
861 #endif
862 
863     /**
864      * Get bundleName by pid.
865      *
866      * @param pid process id.
867      * @param bundleName Output parameters, return bundleName.
868      * @param uid Output parameters, return userId.
869      * @return Returns ERR_OK on success, others on failure.
870      */
871     int32_t GetBundleNameByPid(const int32_t pid, std::string &bundleName, int32_t &uid);
872 
873     /**
874      * Notify Fault Data
875      *
876      * @param faultData the fault data.
877      * @return Returns ERR_OK on success, others on failure.
878      */
879     int32_t NotifyAppFault(const FaultData &faultData);
880 
881     /**
882      * Transformed Notify Fault Data
883      *
884      * @param faultData Transformed the fault data.
885      * @return Returns ERR_OK on success, others on failure.
886      */
887 
888     int32_t TransformedNotifyAppFault(const AppFaultDataBySA &faultData);
889 
890     /**
891      * Notify Fault Data By SA
892      *
893      * @param faultData the fault data notified by SA.
894      * @return Returns ERR_OK on success, others on failure.
895      */
896     int32_t NotifyAppFaultBySA(const AppFaultDataBySA &faultData);
897 
898     /**
899      * Set Appfreeze Detect Filter
900      *
901      * @param pid the process pid.
902      * @return Returns true on success, others on failure.
903      */
904     bool SetAppFreezeFilter(int32_t pid);
905 
906     /**
907      * get memorySize by pid.
908      *
909      * @param pid process id.
910      * @param memorySize Output parameters, return memorySize in KB.
911      * @return Returns ERR_OK on success, others on failure.
912      */
913     virtual int32_t GetProcessMemoryByPid(const int32_t pid, int32_t &memorySize);
914 
915     /**
916      * get application processes information list by bundleName.
917      *
918      * @param bundleName Bundle name.
919      * @param userId user Id in Application record.
920      * @param info Output parameters, return running process info list.
921      * @return Returns ERR_OK on success, others on failure.
922      */
923     virtual int32_t GetRunningProcessInformation(
924         const std::string &bundleName, int32_t userId, std::vector<RunningProcessInfo> &info);
925 
926     /**
927      * init focusListener.
928      *
929      * @return
930      */
931     void InitFocusListener();
932 
933     /**
934      * free focusListener.
935      *
936      * @return
937      */
938     void FreeFocusListener();
939 
940     /**
941      * Init window visibility changed listener.
942      */
943     void InitWindowVisibilityChangedListener();
944 
945     /**
946      * Free window visibility changed listener.
947      */
948     void FreeWindowVisibilityChangedListener();
949 
950     /*
951      * @brief Notify NativeEngine GC of status change.
952      *
953      * @param state GC state
954      * @param pid pid
955      *
956      * @return Is the status change completed.
957      */
958     int32_t ChangeAppGcState(pid_t pid, int32_t state);
959 
960     /**
961      * @brief Register app debug listener.
962      * @param listener App debug listener.
963      * @return Returns ERR_OK on success, others on failure.
964      */
965     int32_t RegisterAppDebugListener(const sptr<IAppDebugListener> &listener);
966 
967     /**
968      * @brief Unregister app debug listener.
969      * @param listener App debug listener.
970      * @return Returns ERR_OK on success, others on failure.
971      */
972     int32_t UnregisterAppDebugListener(const sptr<IAppDebugListener> &listener);
973 
974     /**
975      * @brief Attach app debug.
976      * @param bundleName The application bundle name.
977      * @return Returns ERR_OK on success, others on failure.
978      */
979     int32_t AttachAppDebug(const std::string &bundleName);
980 
981     /**
982      * @brief Detach app debug.
983      * @param bundleName The application bundle name.
984      * @return Returns ERR_OK on success, others on failure.
985      */
986     int32_t DetachAppDebug(const std::string &bundleName);
987 
988     /**
989      * @brief Set app waiting debug mode.
990      * @param bundleName The application bundle name.
991      * @param isPersist The persist flag.
992      * @return Returns ERR_OK on success, others on failure.
993      */
994     int32_t SetAppWaitingDebug(const std::string &bundleName, bool isPersist);
995 
996     /**
997      * @brief Cancel app waiting debug mode.
998      * @return Returns ERR_OK on success, others on failure.
999      */
1000     int32_t CancelAppWaitingDebug();
1001 
1002     /**
1003      * @brief Get waiting debug mode application.
1004      * @param bundleNameList The application bundle name list.
1005      * @return Returns ERR_OK on success, others on failure.
1006      */
1007     int32_t GetWaitingDebugApp(std::vector<std::string> &bundleNameList);
1008 
1009     /**
1010      * @brief Determine whether it is a waiting debug application based on the bundle name.
1011      * @return Returns true if it is a waiting debug application, otherwise it returns false.
1012      */
1013     bool IsWaitingDebugApp(const std::string &bundleName);
1014 
1015     /**
1016      * @brief Clear non persist waiting debug flag.
1017      */
1018     void ClearNonPersistWaitingDebugFlag();
1019 
1020     /**
1021      * @brief Registering ability debug mode response.
1022      * @param response Response for ability debug object.
1023      * @return Returns ERR_OK on success, others on failure.
1024      */
1025     int32_t RegisterAbilityDebugResponse(const sptr<IAbilityDebugResponse> &response);
1026 
1027     /**
1028      * @brief Determine whether it is an attachment debug application based on the bundle name.
1029      * @param bundleName The application bundle name.
1030      * @return Returns true if it is an attach debug application, otherwise it returns false.
1031      */
1032     bool IsAttachDebug(const std::string &bundleName);
1033 
1034     /**
1035      * @brief Notify AbilityManagerService the page show.
1036      * @param token Ability identify.
1037      * @param pageStateData The data of ability's page state.
1038      * @return Returns ERR_OK on success, others on failure.
1039      */
1040     virtual int32_t NotifyPageShow(const sptr<IRemoteObject> &token, const PageStateData &pageStateData);
1041 
1042     /**
1043      * @brief Notify AbilityManagerService the page hide.
1044      * @param token Ability identify.
1045      * @param pageStateData The data of ability's page state.
1046      * @return Returns ERR_OK on success, others on failure.
1047      */
1048     virtual int32_t NotifyPageHide(const sptr<IRemoteObject> &token, const PageStateData &pageStateData);
1049 
1050     /**
1051      * Register appRunning status listener.
1052      *
1053      * @param listener Running status listener.
1054      * @return Returns ERR_OK on success, others on failure.
1055      */
1056     int32_t RegisterAppRunningStatusListener(const sptr<IRemoteObject> &listener);
1057 
1058     /**
1059      * Unregister appRunning status listener.
1060      *
1061      * @param listener Running status listener.
1062      * @return Returns ERR_OK on success, others on failure.
1063      */
1064     int32_t UnregisterAppRunningStatusListener(const sptr<IRemoteObject> &listener);
1065 
1066     /**
1067      * Register application foreground state observer.
1068      * @param observer Is app foreground statue observer
1069      * @return Returns ERR_OK on success, others on failure.
1070      */
1071     int32_t RegisterAppForegroundStateObserver(const sptr<IAppForegroundStateObserver> &observer);
1072 
1073     /**
1074      * Unregister application foreground state observer.
1075      * @param observer Is app foreground statue observer
1076      * @return Returns ERR_OK on success, others on failure.
1077      */
1078     int32_t UnregisterAppForegroundStateObserver(const sptr<IAppForegroundStateObserver> &observer);
1079 
1080     /**
1081      * Start child process, called by ChildProcessManager.
1082      *
1083      * @param callingPid Calling process pid.
1084      * @param childPid Created child process pid.
1085      * @param request Child process start request params.
1086      * @return Returns ERR_OK on success, others on failure.
1087      */
1088     virtual int32_t StartChildProcess(const pid_t callingPid, pid_t &childPid, const ChildProcessRequest &request);
1089 
1090     /**
1091      * Get child process record for self.
1092      *
1093      * @return child process record.
1094      */
1095     virtual int32_t GetChildProcessInfoForSelf(ChildProcessInfo &info);
1096 
1097     /**
1098      * Attach child process scheduler to app manager service.
1099      *
1100      * @param pid the child process pid to exit.
1101      * @param childScheduler scheduler of child process.
1102      */
1103     virtual void AttachChildProcess(const pid_t pid, const sptr<IChildScheduler> &childScheduler);
1104 
1105     /**
1106      * Exit child process safely by child process pid.
1107      *
1108      * @param pid child process pid.
1109      */
1110     virtual void ExitChildProcessSafelyByChildPid(const pid_t pid);
1111 
1112     /**
1113      * Start native child process, callde by ChildProcessManager.
1114      * @param hostPid Host process pid.
1115      * @param childProcessCount current started child process count
1116      * @param libName lib file name to be load in child process
1117      * @param callback callback for notify start result
1118      * @return Returns ERR_OK on success, others on failure.
1119      */
1120     virtual int32_t StartNativeChildProcess(const pid_t hostPid,
1121         const std::string &libName, int32_t childProcessCount, const sptr<IRemoteObject> &callback);
1122 
1123     /**
1124      * To clear the process by ability token.
1125      *
1126      * @param token the unique identification to the ability.
1127      */
1128     void ClearProcessByToken(sptr<IRemoteObject> token);
1129 
1130     /**
1131      * Whether the current application process is the last surviving process.
1132      * @param bundleName To query the bundle name of a process.
1133      * @return Returns true is final application process, others return false.
1134      */
1135     bool IsFinalAppProcessByBundleName(const std::string &bundleName);
1136 
1137     /**
1138      * @brief Notify memory size state changed to sufficient or insufficent.
1139      * @param isMemorySizeSufficent Indicates the memory size state.
1140      * @return Returns ERR_OK on success, others on failure.
1141      */
1142     int32_t NotifyMemorySizeStateChanged(bool isMemorySizeSufficent);
1143 
1144     /**
1145      * whether memory size is sufficent.
1146      * @return Returns true is sufficent memory size, others return false.
1147      */
1148     bool IsMemorySizeSufficent();
1149 
1150     int32_t RegisterRenderStateObserver(const sptr<IRenderStateObserver> &observer);
1151 
1152     int32_t UnregisterRenderStateObserver(const sptr<IRenderStateObserver> &observer);
1153 
1154     int32_t UpdateRenderState(pid_t renderPid, int32_t state);
1155 
1156     int32_t SignRestartAppFlag(int32_t uid);
1157 
1158     int32_t GetAppIndexByPid(pid_t pid, int32_t &appIndex) const;
1159 
1160     void SetAppAssertionPauseState(bool flag);
1161 
1162     void SetKeepAliveEnableState(const std::string &bundleName, bool enable, int32_t uid);
1163 
1164     int32_t GetAppRunningUniqueIdByPid(pid_t pid, std::string &appRunningUniqueId);
1165 
1166     int32_t GetAllUIExtensionRootHostPid(pid_t pid, std::vector<pid_t> &hostPids);
1167 
1168     int32_t GetAllUIExtensionProviderPid(pid_t hostPid, std::vector<pid_t> &providerPids);
1169 
1170     virtual int DumpIpcAllStart(std::string& result);
1171 
1172     virtual int DumpIpcAllStop(std::string& result);
1173 
1174     virtual int DumpIpcAllStat(std::string& result);
1175 
1176     virtual int DumpIpcStart(const int32_t pid, std::string& result);
1177 
1178     virtual int DumpIpcStop(const int32_t pid, std::string& result);
1179 
1180     virtual int DumpIpcStat(const int32_t pid, std::string& result);
1181 
1182     virtual int DumpFfrt(const std::vector<int32_t>& pids, std::string& result);
1183 
1184     int32_t SetSupportedProcessCacheSelf(bool isSupport);
1185 
1186     int32_t SetSupportedProcessCache(int32_t pid, bool isSupport);
1187 
1188     void OnAppCacheStateChanged(const std::shared_ptr<AppRunningRecord> &appRecord, ApplicationState state);
1189 
1190     virtual void SaveBrowserChannel(const pid_t hostPid, sptr<IRemoteObject> browser);
1191 
1192     bool IsAppProcessesAllCached(const std::string &bundleName, int32_t uid,
1193         const std::set<std::shared_ptr<AppRunningRecord>> &cachedSet);
1194 
1195     /**
1196      * Check caller is test ability
1197      *
1198      * @param pid, the pid of ability.
1199      * @return Returns ERR_OK is test ability, others is not test ability.
1200      */
1201     int32_t CheckCallingIsUserTestModeInner(const pid_t pid, bool &isUserTest);
1202 
1203     bool GetSceneBoardAttachFlag() const;
1204 
1205     void SetSceneBoardAttachFlag(bool flag);
1206 
1207     void CacheLoadAbilityTask(const LoadAbilityTaskFunc& func);
1208 
1209     void SubmitCacheLoadAbilityTask();
1210     /**
1211      * Notifies that one ability is attached to status bar.
1212      *
1213      * @param token the token of the abilityRecord that is attached to status bar.
1214      */
1215     void AttachedToStatusBar(const sptr<IRemoteObject> &token);
1216     void KillApplicationByRecord(const std::shared_ptr<AppRunningRecord> &appRecord);
1217 
1218     int32_t NotifyProcessDependedOnWeb();
1219 
1220     void KillProcessDependedOnWeb();
1221 
1222     void RestartResidentProcessDependedOnWeb();
1223 
1224     void BlockProcessCacheByPids(const std::vector<int32_t>& pids);
1225 
1226     bool IsKilledForUpgradeWeb(const std::string &bundleName) const;
1227 
1228     bool CleanAbilityByUserRequest(const sptr<IRemoteObject> &token);
1229 
1230     bool IsProcessContainsOnlyUIAbility(const pid_t pid);
1231 
1232     bool IsProcessAttached(sptr<IRemoteObject> token) const;
1233 
1234     void NotifyAppPreCache(int32_t pid, int32_t userId);
1235 
1236     /**
1237      * Get pids of processes which belong to specific bundle name and support process cache feature.
1238      *
1239      * @param bundleName bundle name.
1240      * @param pidList pid list of processes that support process cache.
1241      * @return Returns ERR_OK on success, others on failure.
1242      */
1243     virtual int32_t GetSupportedProcessCachePids(const std::string &bundleName, std::vector<int32_t> &pidList);
1244 
1245 private:
1246     int32_t ForceKillApplicationInner(const std::string &bundleName, const int userId = -1,
1247         const int appIndex = 0);
1248 
1249     std::string FaultTypeToString(FaultDataType type);
1250 
1251     FaultData ConvertDataTypes(const AppFaultDataBySA &faultData);
1252 
1253     void StartEmptyResidentProcess(const BundleInfo &info, const std::string &processName, int restartCount,
1254         bool isEmptyKeepAliveApp);
1255 
1256     void RestartResidentProcess(std::shared_ptr<AppRunningRecord> appRecord);
1257 
1258     bool CheckLoadAbilityConditions(const sptr<IRemoteObject> &token,
1259         const std::shared_ptr<AbilityInfo> &abilityInfo, const std::shared_ptr<ApplicationInfo> &appInfo);
1260 
1261     bool GetBundleInfo(const std::string &bundleName, BundleInfo &bundleInfo);
1262 
1263     bool GenerateRenderUid(int32_t &renderUid);
1264 
1265     void MakeServiceExtProcessName(const std::shared_ptr<AbilityInfo> &abilityInfo,
1266         const std::shared_ptr<ApplicationInfo> &appInfo, std::string &processName) const;
1267 
1268     void MakeProcessName(const std::shared_ptr<AbilityInfo> &abilityInfo,
1269         const std::shared_ptr<ApplicationInfo> &appInfo, const HapModuleInfo &hapModuleInfo, int32_t appIndex,
1270         const std::string &specifiedProcessFlag, std::string &processName) const;
1271 
1272     void MakeProcessName(const std::shared_ptr<ApplicationInfo> &appInfo, const HapModuleInfo &hapModuleInfo,
1273         std::string &processName) const;
1274 
1275     bool CheckIsolationMode(const HapModuleInfo &hapModuleInfo) const;
1276 
1277     bool IsMainProcess(const std::shared_ptr<ApplicationInfo> &appInfo, const std::string &processName) const;
1278 
1279     /**
1280      * StartAbility, load the ability that needed to be started(Start on the basis of the original process).
1281      *  Start on a new boot process
1282      * @param token, the unique identification to start the ability.
1283      * @param preToken, the unique identification to call the ability.
1284      * @param abilityInfo, the ability information.
1285      * @param appInfo, the app information.
1286      *
1287      * @return
1288      */
1289     void StartAbility(sptr<IRemoteObject> token, sptr<IRemoteObject> preToken,
1290         std::shared_ptr<AbilityInfo> abilityInfo, std::shared_ptr<AppRunningRecord> appRecord,
1291         const HapModuleInfo &hapModuleInfo, std::shared_ptr<AAFwk::Want> want, int32_t abilityRecordId);
1292 
1293     int32_t StartPerfProcess(const std::shared_ptr<AppRunningRecord> &appRecord, const std::string& perfCmd,
1294         const std::string& debugCmd, bool isSandboxApp);
1295 
1296     void StartProcessVerifyPermission(const BundleInfo &bundleInfo, bool &hasAccessBundleDirReq,
1297         uint8_t &setAllowInternet, uint8_t &allowInternet, std::vector<int32_t> &gids);
1298 
1299     void AddMountPermission(uint32_t accessTokenId, std::set<std::string> &permissions);
1300 
1301     /**
1302      * StartProcess, load the ability that needed to be started(Start on a new boot process).
1303      *
1304      * @param appName, the app name.
1305      * @param processName, the process name.
1306      * @param appRecord, the app information.
1307      * @param uid, the process uid.
1308      * @param bundleName, the app bundleName.
1309      *
1310      * @return
1311      */
1312     void StartProcess(const std::string &appName, const std::string &processName, uint32_t startFlags,
1313                       std::shared_ptr<AppRunningRecord> appRecord, const int uid, const BundleInfo &bundleInfo,
1314                       const std::string &bundleName, const int32_t bundleIndex, bool appExistFlag = true,
1315                       bool isPreload = false,  AppExecFwk::PreloadMode preloadMode = AppExecFwk::PreloadMode::PRE_MAKE,
1316                       const std::string &moduleName = "", const std::string &abilityName = "",
1317                       bool strictMode = false, int32_t maxChildProcess = 0, sptr<IRemoteObject> token = nullptr,
1318                       std::shared_ptr<AAFwk::Want> want = nullptr,
1319                       ExtensionAbilityType ExtensionAbilityType = ExtensionAbilityType::UNSPECIFIED);
1320 
1321     /**
1322      * KillApplicationByUserId, kill the application by user ID.
1323      *
1324      * @param bundleName, bundle name in Application record.
1325      * @param appCloneIndex the app clone id.
1326      * @param userId, user ID.
1327      * @param  reason, caller function name.
1328      *
1329      * @return ERR_OK, return back success, others fail.
1330      */
1331     int32_t KillApplicationByUserIdLocked(const std::string &bundleName, int32_t appCloneIndex, int32_t userId,
1332         const bool clearPageStack = false, const std::string& reason = "KillApplicationByUserIdLocked");
1333 
1334     /**
1335      * WaitForRemoteProcessExit, Wait for the process to exit normally.
1336      *
1337      * @param pids, process number collection to exit.
1338      * @param startTime, execution process security exit start time.
1339      *
1340      * @return true, return back success,others fail.
1341      */
1342     bool WaitForRemoteProcessExit(std::list<pid_t> &pids, const int64_t startTime);
1343 
1344     /**
1345      * ProcessExist, Judge whether the process exists.
1346      *
1347      * @param pids, process number collection to exit.
1348      *
1349      * @return true, return back existed,others non-existent.
1350      */
1351     bool ProcessExist(pid_t pid);
1352 
1353     /**
1354      * CheckAllProcessExist, Determine whether all processes exist .
1355      *
1356      * @param pids, process number collection to exit.
1357      *
1358      * @return true, Returns that a process exists and all other processes do not exist.
1359      */
1360     bool CheckAllProcessExist(std::list<pid_t> &pids);
1361 
1362     /**
1363      * SystemTimeMillisecond, Get system time.
1364      *
1365      * @return the system time.
1366      */
1367     int64_t SystemTimeMillisecond();
1368 
1369     // Test add the bundle manager instance.
1370     void SetBundleManagerHelper(const std::shared_ptr<BundleMgrHelper> &bundleMgrHelper);
1371 
1372     void HandleTerminateApplicationTimeOut(const int64_t eventId);
1373 
1374     void HandleAddAbilityStageTimeOut(const int64_t eventId);
1375 
1376     void ClipStringContent(const std::regex &re, const std::string &source, std::string &afterCutStr);
1377 
1378     bool GetBundleAndHapInfo(const AbilityInfo &abilityInfo, const std::shared_ptr<ApplicationInfo> &appInfo,
1379         BundleInfo &bundleInfo, HapModuleInfo &hapModuleInfo, int32_t appIndex = 0) const;
1380     AppProcessData WrapAppProcessData(const std::shared_ptr<AppRunningRecord> &appRecord,
1381         const ApplicationState state);
1382 
1383     int UserTestAbnormalFinish(const sptr<IRemoteObject> &observer, const std::string &msg);
1384     int GetHapModuleInfoForTestRunner(const AAFwk::Want &want, const sptr<IRemoteObject> &observer,
1385         const BundleInfo &bundleInfo, HapModuleInfo &hapModuleInfo);
1386     int StartEmptyProcess(const AAFwk::Want &want, const sptr<IRemoteObject> &observer, const BundleInfo &info,
1387         const std::string &processName, const int userId);
1388 
1389     void HandleStartSpecifiedAbilityTimeOut(const int64_t eventId);
1390 
1391     void HandleStartSpecifiedProcessTimeout(const int64_t eventId);
1392 
1393     void InitGlobalConfiguration();
1394 
1395     void GetRunningProcesses(const std::shared_ptr<AppRunningRecord> &appRecord, std::vector<RunningProcessInfo> &info);
1396     void GetRunningProcess(const std::shared_ptr<AppRunningRecord> &appRecord, RunningProcessInfo &info);
1397 
1398     void GetRenderProcesses(const std::shared_ptr<AppRunningRecord> &appRecord, std::vector<RenderProcessInfo> &info);
1399 
1400     void GetChildrenProcesses(const std::shared_ptr<AppRunningRecord> &appRecord, std::vector<ChildProcessInfo> &info);
1401 
1402     int StartRenderProcessImpl(const std::shared_ptr<RenderRecord> &renderRecord,
1403         const std::shared_ptr<AppRunningRecord> appRecord, pid_t &renderPid, bool isGPU = false);
1404 
1405     void SetRenderStartMsg(AppSpawnStartMsg &startMsg, std::shared_ptr<RenderRecord> renderRecord,
1406         const int32_t renderUid, const bool isGPU);
1407 
1408     void OnRenderRemoteDied(const wptr<IRemoteObject> &remote);
1409 
1410     void AddWatchParameter();
1411 
1412     bool VerifyAPL() const;
1413 
1414     void RegisterFocusListener();
1415 
1416     static void PointerDeviceEventCallback(const char *key, const char *value, void *context);
1417 
1418     int VerifyKillProcessPermission(const std::string &bundleName) const;
1419 
1420     int32_t VerifyKillProcessPermissionCommon() const;
1421 
1422     bool CheckCallerIsAppGallery();
1423 
1424     void ApplicationTerminatedSendProcessEvent(const std::shared_ptr<AppRunningRecord> &appRecord);
1425     void ClearAppRunningDataForKeepAlive(const std::shared_ptr<AppRunningRecord> &appRecord);
1426 
1427     int32_t StartChildProcessPreCheck(pid_t callingPid, int32_t childProcessType);
1428 
1429     int32_t StartChildProcessImpl(const std::shared_ptr<ChildProcessRecord> childProcessRecord,
1430         const std::shared_ptr<AppRunningRecord> appRecord, pid_t &childPid, const ChildProcessArgs &args,
1431         const ChildProcessOptions &options);
1432 
1433     int32_t GetChildProcessInfo(const std::shared_ptr<ChildProcessRecord> childProcessRecord,
1434         const std::shared_ptr<AppRunningRecord> appRecord, ChildProcessInfo &info,
1435         bool isCallFromGetChildrenProcesses = false);
1436 
1437     void OnChildProcessRemoteDied(const wptr<IRemoteObject> &remote);
1438 
1439     void KillChildProcess(const std::shared_ptr<AppRunningRecord> &appRecord);
1440 
1441     void KillAttachedChildProcess(const std::shared_ptr<AppRunningRecord> &appRecord);
1442 
1443     void PresetMaxChildProcess(const std::shared_ptr<AbilityInfo> &abilityInfo, int32_t &maxChildProcess);
1444 
1445     void AfterLoadAbility(std::shared_ptr<AppRunningRecord> appRecord, std::shared_ptr<AbilityInfo> abilityInfo,
1446         std::shared_ptr<AbilityRuntime::LoadParam> loadParam);
1447 
1448     void RemoveRenderRecordNoAttach(const std::shared_ptr<AppRunningRecord> &hostRecord, int32_t renderPid);
1449 
1450 private:
1451     /**
1452      * ClearUpApplicationData, clear the application data.
1453      *
1454      * @param bundleName, bundle name in Application record.
1455      * @param uid, app uid in Application record.
1456      * @param pid, app pid in Application record.
1457      * @param appCloneIndex the app clone id.
1458      * @param userId, userId.
1459      * @param isBySelf, clear data by application self.
1460      * @param reason, caller function.
1461      *
1462      * @return Returns ERR_OK on success, others on failure.
1463      */
1464     int32_t ClearUpApplicationDataByUserId(const std::string &bundleName,
1465         int32_t callerUid, pid_t callerPid, int32_t appCloneIndex, int32_t userId, bool isBySelf = false,
1466         const std::string& reason = "ClearUpApplicationDataByUserId");
1467 
1468     bool CheckGetRunningInfoPermission() const;
1469 
1470     /**
1471      * kill all processes of a bundleName
1472      * @param bundleName bundleName of which to be killed
1473      * @param clearPageStack clear Page Stack
1474      * @param reason caller function name
1475      */
1476     int32_t KillApplicationByBundleName(const std::string &bundleName, const bool clearPageStack = false,
1477         const std::string& reason = "KillApplicationByBundleName");
1478 
1479     bool SendProcessStartEvent(const std::shared_ptr<AppRunningRecord> &appRecord, bool isPreload,
1480         AppExecFwk::PreloadMode preloadMode);
1481 
1482     bool SendProcessStartFailedEvent(std::shared_ptr<AppRunningRecord> appRecord, ProcessStartFailedReason reason,
1483         int32_t subReason);
1484 
1485     void SendAppStartupTypeEvent(const std::shared_ptr<AppRunningRecord> &appRecord,
1486         const std::shared_ptr<AbilityInfo> &abilityInfo, const AppStartType startType);
1487 
1488     bool SendCreateAtomicServiceProcessEvent(const std::shared_ptr<AppRunningRecord> &appRecord,
1489         const BundleType &bundleType, const std::string &moduleName = "", const std::string &abilityName = "");
1490 
1491     void SendProcessExitEvent(const std::shared_ptr<AppRunningRecord> &appRecord);
1492 
1493     void SendProcessExitEventTask(const std::shared_ptr<AppRunningRecord> &appRecord, time_t exitTime, int32_t count);
1494 
1495     void SetRunningSharedBundleList(const std::string &bundleName,
1496         const std::vector<BaseSharedBundleInfo> baseSharedBundleInfoList);
1497 
1498     void RemoveRunningSharedBundleList(const std::string &bundleName);
1499 
1500     void KillRenderProcess(const std::shared_ptr<AppRunningRecord> &appRecord);
1501 
1502     void SetOverlayInfo(const std::string& bundleName, const int32_t userId, AppSpawnStartMsg& startMsg);
1503     void SetAppEnvInfo(const BundleInfo &bundleInfo, AppSpawnStartMsg& startMsg);
1504 
1505     void TimeoutNotifyApp(int32_t pid, int32_t uid, const std::string& bundleName, const std::string& processName,
1506         const FaultData &faultData);
1507 
1508     void AppRecoveryNotifyApp(int32_t pid, const std::string& bundleName,
1509         FaultDataType faultType, const std::string& markers);
1510 
1511     void ProcessAppDebug(const std::shared_ptr<AppRunningRecord> &appRecord, const bool &isDebugStart);
1512     AppDebugInfo MakeAppDebugInfo(const std::shared_ptr<AppRunningRecord> &appRecord, const bool &isDebugStart);
1513     int32_t NotifyAbilitysDebugChange(const std::string &bundleName, const bool &isAppDebug);
1514     int32_t NotifyAbilitysAssertDebugChange(const std::shared_ptr<AppRunningRecord> &appRecord, bool isAssertDebug);
1515 
1516     void SetProcessJITState(const std::shared_ptr<AppRunningRecord> appRecord);
1517 
1518     bool JudgeSelfCalledByToken(const sptr<IRemoteObject> &token, const PageStateData &pageStateData);
1519 
1520     void ParseServiceExtMultiProcessWhiteList();
1521     void ClearData(std::shared_ptr<AppRunningRecord> appRecord);
1522 
1523     /**
1524      * Notify the app running status.
1525      *
1526      * @param bundle Bundle name in application record.
1527      * @param uid Uid of bundle.
1528      * @param runningStatus The app running status.
1529      *
1530      * @return
1531      */
1532     void NotifyAppRunningStatusEvent(
1533         const std::string &bundle, int32_t uid, AbilityRuntime::RunningStatus runningStatus);
1534 
1535     void GetRunningCloneAppInfo(const std::shared_ptr<AppRunningRecord> &appRecord,
1536         RunningMultiAppInfo &info);
1537 
1538     void GetRunningMultiInstanceKeys(const std::shared_ptr<AppRunningRecord> &appRecord,
1539         std::vector<std::string> &instanceKeys);
1540     /**
1541      * To Prevent process being killed when ability is starting in an existing process,
1542      * we need notify memmgr to increase process priority.
1543      *
1544      * @param appRecord Current app running record.
1545      *
1546      * @return Whether improve priority succeed.
1547      */
1548     bool NotifyMemMgrPriorityChanged(const std::shared_ptr<AppRunningRecord> appRecord);
1549 
1550     void HandlePreloadApplication(const PreloadRequest &request);
1551 
1552     void reportpreLoadTask(const std::shared_ptr<AppRunningRecord> appRecord);
1553 
1554     std::string GetSpecifiedProcessFlag(std::shared_ptr<AbilityInfo> abilityInfo, std::shared_ptr<AAFwk::Want> want);
1555 
1556     void LoadAbilityNoAppRecord(const std::shared_ptr<AppRunningRecord> appRecord,
1557         bool isShellCall, std::shared_ptr<ApplicationInfo> appInfo,
1558         std::shared_ptr<AbilityInfo> abilityInfo, const std::string &processName,
1559         const std::string &specifiedProcessFlag, const BundleInfo &bundleInfo,
1560         const HapModuleInfo &hapModuleInfo, std::shared_ptr<AAFwk::Want> want,
1561         bool appExistFlag, bool isPreload, AppExecFwk::PreloadMode preloadMode,
1562         sptr<IRemoteObject> token = nullptr);
1563 
1564     int32_t CreatNewStartMsg(const Want &want, const AbilityInfo &abilityInfo,
1565         const std::shared_ptr<ApplicationInfo> &appInfo, const std::string &processName,
1566         AppSpawnStartMsg &startMsg);
1567 
1568     int32_t CreateStartMsg(const std::string &processName, uint32_t startFlags, const int uid,
1569         const BundleInfo &bundleInfo, const int32_t bundleIndex, BundleType bundleType, AppSpawnStartMsg &startMsg,
1570         std::shared_ptr<AAFwk::Want> want, const std::string &moduleName = "", const std::string &abilityName = "",
1571         bool strictMode = false);
1572 
1573     void QueryExtensionSandBox(const std::string &moduleName, const std::string &abilityName,
1574         const BundleInfo &bundleInfo, AppSpawnStartMsg &startMsg, DataGroupInfoList& dataGroupInfoList,
1575         bool strictMode, std::shared_ptr<AAFwk::Want> want);
1576 
1577     int32_t StartPerfProcessByStartMsg(AppSpawnStartMsg &startMsg, const std::string& perfCmd,
1578         const std::string& debugCmd, bool isSandboxApp);
1579 
1580     void SetAtomicServiceInfo(BundleType bundleType, AppSpawnStartMsg &startMsg);
1581 
1582     void SetAppInfo(const BundleInfo &bundleInfo, AppSpawnStartMsg &startMsg);
1583 
1584     bool CreateAbilityInfo(const AAFwk::Want &want, AbilityInfo &abilityInfo);
1585 
1586     AAFwk::EventInfo BuildEventInfo(std::shared_ptr<AppRunningRecord> appRecord) const;
1587 
1588     void NotifyAppAttachFailed(std::shared_ptr<AppRunningRecord> appRecord);
1589 private:
1590     /**
1591      * Notify application status.
1592      *
1593      * @param bundleName Indicates the name of the bundle.
1594      * @param bundleName Indicates the name of the bundle.
1595      * @param eventData Indicates the event defined by CommonEventSupport
1596      *
1597      * @return
1598      */
1599     void NotifyAppStatusByCallerUid(const std::string &bundleName, const int32_t tokenId, const int32_t userId,
1600         const int32_t callerUid, const int32_t targetUid, const std::string &eventData);
1601     void SendHiSysEvent(const int32_t innerEventId, const int64_t eventId);
1602     int FinishUserTestLocked(
1603         const std::string &msg, const int64_t &resultCode, const std::shared_ptr<AppRunningRecord> &appRecord);
1604     int32_t GetCurrentAccountId() const;
1605     void SendReStartProcessEvent(AAFwk::EventInfo &eventInfo, int32_t appUid);
1606     void SendAppLaunchEvent(const std::shared_ptr<AppRunningRecord> &appRecord);
1607     void InitAppWaitingDebugList();
1608     void HandleConfigurationChange(const Configuration &config, const int32_t userId = -1);
1609     bool CheckIsThreadInFoundation(pid_t pid);
1610     bool CheckAppFault(const std::shared_ptr<AppRunningRecord> &appRecord, const FaultData &faultData);
1611     int32_t KillFaultApp(int32_t pid, const std::string &bundleName, const FaultData &faultData,
1612         bool isNeedExit = false);
1613     void AddUIExtensionLauncherItem(std::shared_ptr<AAFwk::Want> want, std::shared_ptr<AppRunningRecord> appRecord,
1614         sptr<IRemoteObject> token);
1615     void NotifyStartResidentProcess(std::vector<AppExecFwk::BundleInfo> &bundleInfos);
1616     void RemoveUIExtensionLauncherItem(std::shared_ptr<AppRunningRecord> appRecord, sptr<IRemoteObject> token);
1617     bool IsSceneBoardCall();
1618     void CheckCleanAbilityByUserRequest(const std::shared_ptr<AppRunningRecord> &appRecord,
1619         const std::shared_ptr<AbilityRunningRecord> &abilityRecord, const AbilityState state);
1620     void GetPidsByAccessTokenId(const uint32_t accessTokenId, std::vector<pid_t> &pids);
1621     void DealMultiUserConfig(const Configuration &config, const int32_t userId);
1622     int32_t KillProcessByPidInner(const pid_t pid, const std::string& reason,
1623         const std::string& killReason, std::shared_ptr<AppRunningRecord> appRecord);
1624     bool IsAllowedNWebPreload(const std::string &processName);
1625     bool CheckAppRecordAndPriorityObject(const std::shared_ptr<AppRunningRecord> &appRecord);
1626     void GetAppCloneInfo(const std::shared_ptr<AppRunningRecord> &appRecord,
1627         RunningMultiAppInfo &info);
1628     void GetMultiInstanceInfo(const std::shared_ptr<AppRunningRecord> &appRecord,
1629         RunningMultiAppInfo &info);
1630     int32_t GetAllRunningInstanceKeysByBundleNameInner(const std::string &bundleName,
1631         std::vector<std::string> &instanceKeys, int32_t userId);
1632     const std::string TASK_ON_CALLBACK_DIED = "OnCallbackDiedTask";
1633     std::vector<AppStateCallbackWithUserId> appStateCallbacks_;
1634     std::shared_ptr<RemoteClientManager> remoteClientManager_;
1635     std::shared_ptr<AppRunningManager> appRunningManager_;
1636     std::shared_ptr<AAFwk::TaskHandlerWrap> taskHandler_;
1637     std::shared_ptr<AMSEventHandler> eventHandler_;
1638     std::shared_ptr<Configuration> configuration_;
1639     ffrt::mutex userTestLock_;
1640     ffrt::mutex appStateCallbacksLock_;
1641     ffrt::mutex renderUidSetLock_;
1642     ffrt::mutex exceptionLock_;
1643     ffrt::mutex browserHostLock_;
1644     sptr<IStartSpecifiedAbilityResponse> startSpecifiedAbilityResponse_;
1645     ffrt::mutex configurationObserverLock_;
1646     std::vector<ConfigurationObserverWithUserId> configurationObservers_;
1647     sptr<WindowFocusChangedListener> focusListener_;
1648     sptr<WindowVisibilityChangedListener> windowVisibilityChangedListener_;
1649     std::vector<std::shared_ptr<AppRunningRecord>> restartResedentTaskList_;
1650     std::map<std::string, std::vector<BaseSharedBundleInfo>> runningSharedBundleList_;
1651     std::map<std::string, bool> waitingDebugBundleList_;
1652     ffrt::mutex waitingDebugLock_;
1653     bool isInitAppWaitingDebugListExecuted_ = false;
1654     std::unordered_set<int32_t> renderUidSet_;
1655     std::string supportIsolationMode_ {"false"};
1656     std::string supportServiceExtMultiProcess_ {"false"};
1657     int32_t currentUserId_ = 0;
1658     int32_t lastRenderUid_ = Constants::START_UID_FOR_RENDER_PROCESS;
1659     sptr<IAbilityDebugResponse> abilityDebugResponse_;
1660     std::shared_ptr<AppDebugManager> appDebugManager_;
1661     ffrt::mutex killpedProcessMapLock_;
1662     mutable std::map<int64_t, std::string> killedProcessMap_;
1663     ffrt::mutex startChildProcessLock_;
1664     std::vector<std::string> serviceExtensionWhiteList_;
1665     std::shared_ptr<AbilityRuntime::AppRunningStatusModule> appRunningStatusModule_;
1666     std::shared_ptr<AdvancedSecurityModeManager> securityModeManager_;
1667     std::shared_ptr<AAFwk::TaskHandlerWrap> dfxTaskHandler_;
1668     std::shared_ptr<AAFwk::TaskHandlerWrap> otherTaskHandler_;
1669     std::shared_ptr<AppPreloader> appPreloader_;
1670     std::atomic<bool> sceneBoardAttachFlag_ = true;
1671 
1672     std::mutex loadTaskListMutex_;
1673     std::vector<LoadAbilityTaskFunc> loadAbilityTaskFuncList_;
1674     std::atomic<int32_t> willKillPidsNum_ = 0;
1675     std::shared_ptr<AAFwk::TaskHandlerWrap> delayKillTaskHandler_;
1676 
1677     std::shared_ptr<MultiUserConfigurationMgr> multiUserConfigurationMgr_;
1678     std::unordered_set<std::string> nwebPreloadSet_ {};
1679     ffrt::mutex killedBundleSetMutex_;
1680     std::set<std::string> killedBundleSet_;
1681 };
1682 }  // namespace AppExecFwk
1683 }  // namespace OHOS
1684 #endif  // OHOS_ABILITY_RUNTIME_APP_MGR_SERVICE_INNER_H
1685