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_ABILITY_RECORD_H
17 #define OHOS_ABILITY_RUNTIME_ABILITY_RECORD_H
18 
19 #include <ctime>
20 #include <functional>
21 #include <list>
22 #include <memory>
23 #include <vector>
24 #include <utility>
25 #include <set>
26 #include "cpp/mutex.h"
27 #include "cpp/condition_variable.h"
28 
29 #include "ability_connect_callback_interface.h"
30 #include "ability_info.h"
31 #include "ability_start_setting.h"
32 #include "ability_state.h"
33 #include "ability_token_stub.h"
34 #include "app_scheduler.h"
35 #include "application_info.h"
36 #include "bundlemgr/bundle_mgr_interface.h"
37 #include "call_container.h"
38 #include "exit_reason.h"
39 #include "ipc_skeleton.h"
40 #include "lifecycle_deal.h"
41 #include "lifecycle_state_info.h"
42 #include "session_info.h"
43 #include "ui_extension_window_command.h"
44 #include "uri.h"
45 #include "want.h"
46 #include "window_config.h"
47 #ifdef SUPPORT_GRAPHICS
48 #include "ability_window_configuration.h"
49 #include "resource_manager.h"
50 #include "start_options.h"
51 #include "window_manager_service_handler.h"
52 #endif
53 
54 namespace OHOS {
55 namespace AAFwk {
56 using Closure = std::function<void()>;
57 
58 class AbilityRecord;
59 class ConnectionRecord;
60 class CallContainer;
61 
62 constexpr const char* ABILITY_TOKEN_NAME = "AbilityToken";
63 constexpr const char* LAUNCHER_BUNDLE_NAME = "com.ohos.launcher";
64 
65 /**
66  * @class Token
67  * Token is identification of ability and used to interact with kit and wms.
68  */
69 class Token : public AbilityTokenStub {
70 public:
71     explicit Token(std::weak_ptr<AbilityRecord> abilityRecord);
72     virtual ~Token();
73 
74     std::shared_ptr<AbilityRecord> GetAbilityRecord() const;
75     static std::shared_ptr<AbilityRecord> GetAbilityRecordByToken(const sptr<IRemoteObject> &token);
76 
77 private:
78     std::weak_ptr<AbilityRecord> abilityRecord_;  // ability of this token
79 };
80 
81 /**
82  * @class AbilityResult
83  * Record requestCode of for-result start mode and result.
84  */
85 class AbilityResult {
86 public:
87     AbilityResult() = default;
AbilityResult(int requestCode,int resultCode,const Want & resultWant)88     AbilityResult(int requestCode, int resultCode, const Want &resultWant)
89         : requestCode_(requestCode), resultCode_(resultCode), resultWant_(resultWant)
90     {}
~AbilityResult()91     virtual ~AbilityResult()
92     {}
93 
94     int requestCode_ = -1;  // requestCode of for-result start mode
95     int resultCode_ = -1;   // resultCode of for-result start mode
96     Want resultWant_;       // for-result start mode ability will send the result to caller
97 };
98 
99 /**
100  * @class SystemAbilityCallerRecord
101  * Record system caller ability of for-result start mode and result.
102  */
103 class SystemAbilityCallerRecord {
104 public:
SystemAbilityCallerRecord(std::string & srcAbilityId,const sptr<IRemoteObject> & callerToken)105     SystemAbilityCallerRecord(std::string &srcAbilityId, const sptr<IRemoteObject> &callerToken)
106         : srcAbilityId_(srcAbilityId), callerToken_(callerToken)
107     {}
~SystemAbilityCallerRecord()108     virtual ~SystemAbilityCallerRecord()
109     {}
110 
GetSrcAbilityId()111     std::string GetSrcAbilityId()
112     {
113         return srcAbilityId_;
114     }
GetCallerToken()115     const sptr<IRemoteObject> GetCallerToken()
116     {
117         return callerToken_;
118     }
SetResult(Want & want,int resultCode)119     void SetResult(Want &want, int resultCode)
120     {
121         resultWant_ = want;
122         resultCode_ = resultCode;
123     }
GetResultWant()124     Want &GetResultWant()
125     {
126         return resultWant_;
127     }
GetResultCode()128     int &GetResultCode()
129     {
130         return resultCode_;
131     }
132     /**
133      * Set result to system ability.
134      *
135      */
136     void SetResultToSystemAbility(std::shared_ptr<SystemAbilityCallerRecord> callerSystemAbilityRecord,
137         Want &resultWant, int resultCode);
138     /**
139      * Send result to system ability.
140      *
141      */
142     void SendResultToSystemAbility(int requestCode,
143         const std::shared_ptr<SystemAbilityCallerRecord> callerSystemAbilityRecord,
144         int32_t callerUid, uint32_t accessToken, bool schedulerdied);
145 
146 private:
147     std::string srcAbilityId_;
148     sptr<IRemoteObject> callerToken_;
149     Want resultWant_;
150     int resultCode_ = -1;
151 };
152 
153 /**
154  * @struct CallerAbilityInfo
155  * caller ability info.
156  */
157 struct CallerAbilityInfo {
158 public:
159     std::string callerBundleName;
160     std::string callerAbilityName;
161     int32_t callerTokenId = 0;
162     int32_t callerUid = 0;
163     int32_t callerPid = 0;
164     std::string callerNativeName;
165     int32_t callerAppCloneIndex = 0;
166 };
167 
168 /**
169  * @class CallerRecord
170  * Record caller ability of for-result start mode and result.
171  */
172 class CallerRecord {
173 public:
174     CallerRecord() = default;
175     CallerRecord(int requestCode, std::weak_ptr<AbilityRecord> caller);
CallerRecord(int requestCode,std::shared_ptr<SystemAbilityCallerRecord> saCaller)176     CallerRecord(int requestCode, std::shared_ptr<SystemAbilityCallerRecord> saCaller) : requestCode_(requestCode),
177         saCaller_(saCaller)
178     {}
~CallerRecord()179     virtual ~CallerRecord()
180     {}
181 
GetRequestCode()182     int GetRequestCode()
183     {
184         return requestCode_;
185     }
GetCaller()186     std::shared_ptr<AbilityRecord> GetCaller()
187     {
188         return caller_.lock();
189     }
GetSaCaller()190     std::shared_ptr<SystemAbilityCallerRecord> GetSaCaller()
191     {
192         return saCaller_;
193     }
GetCallerInfo()194     std::shared_ptr<CallerAbilityInfo> GetCallerInfo()
195     {
196         return callerInfo_;
197     }
IsHistoryRequestCode(int32_t requestCode)198     bool IsHistoryRequestCode(int32_t requestCode)
199     {
200         return requestCodeSet_.count(requestCode) > 0;
201     }
RemoveHistoryRequestCode(int32_t requestCode)202     void RemoveHistoryRequestCode(int32_t requestCode)
203     {
204         requestCodeSet_.erase(requestCode);
205     }
AddHistoryRequestCode(int32_t requestCode)206     void AddHistoryRequestCode(int32_t requestCode)
207     {
208         requestCodeSet_.insert(requestCode);
209     }
SetRequestCodeSet(const std::set<int32_t> & requestCodeSet)210     void SetRequestCodeSet(const std::set<int32_t> &requestCodeSet)
211     {
212         requestCodeSet_ = requestCodeSet;
213     }
GetRequestCodeSet()214     std::set<int32_t> GetRequestCodeSet()
215     {
216         return requestCodeSet_;
217     }
218 
219 private:
220     int requestCode_ = -1;  // requestCode of for-result start mode
221     std::weak_ptr<AbilityRecord> caller_;
222     std::shared_ptr<SystemAbilityCallerRecord> saCaller_ = nullptr;
223     std::shared_ptr<CallerAbilityInfo> callerInfo_ = nullptr;
224     std::set<int32_t> requestCodeSet_;
225 };
226 
227 /**
228  * @class AbilityRequest
229  * Wrap parameters of starting ability.
230  */
231 enum AbilityCallType {
232     INVALID_TYPE = 0,
233     CALL_REQUEST_TYPE,
234     START_OPTIONS_TYPE,
235     START_SETTINGS_TYPE,
236     START_EXTENSION_TYPE,
237 };
238 
239 enum CollaboratorType {
240     DEFAULT_TYPE = 0,
241     RESERVE_TYPE,
242     OTHERS_TYPE
243 };
244 
245 struct AbilityRequest {
246     Want want;
247     AppExecFwk::AbilityInfo abilityInfo;
248     AppExecFwk::ApplicationInfo appInfo;
249     int32_t uid = 0;
250     int requestCode = -1;
251     bool restart = false;
252     int32_t restartCount = -1;
253     int64_t restartTime = 0;
254     bool startRecent = false;
255     int32_t collaboratorType = CollaboratorType::DEFAULT_TYPE;
256 
257     // call ability
258     int callerUid = -1;
259     AbilityCallType callType = AbilityCallType::INVALID_TYPE;
260     sptr<IRemoteObject> callerToken = nullptr;
261     sptr<IRemoteObject> asCallerSourceToken = nullptr;
262     uint32_t callerAccessTokenId = -1;
263     sptr<IAbilityConnection> connect = nullptr;
264 
265     std::vector<AppExecFwk::SupportWindowMode> supportWindowModes;
266     std::shared_ptr<AbilityStartSetting> startSetting = nullptr;
267     std::shared_ptr<ProcessOptions> processOptions = nullptr;
268     std::shared_ptr<StartWindowOption> startWindowOption = nullptr;
269     std::string specifiedFlag;
270     int32_t userId = -1;
271     bool callSpecifiedFlagTimeout = false;
272     sptr<IRemoteObject> abilityInfoCallback = nullptr;
273 
274     AppExecFwk::ExtensionAbilityType extensionType = AppExecFwk::ExtensionAbilityType::UNSPECIFIED;
275     AppExecFwk::ExtensionProcessMode extensionProcessMode = AppExecFwk::ExtensionProcessMode::UNDEFINED;
276 
277     sptr<SessionInfo> sessionInfo;
278     uint32_t specifyTokenId = 0;
279     bool uriReservedFlag = false;
280     std::string reservedBundleName;
281     bool isFromIcon = false;
282     bool isShellCall = false;
IsContinuationAbilityRequest283     std::pair<bool, LaunchReason> IsContinuation() const
284     {
285         auto flags = want.GetFlags();
286         if ((flags & Want::FLAG_ABILITY_CONTINUATION) == Want::FLAG_ABILITY_CONTINUATION) {
287             return {true, LaunchReason::LAUNCHREASON_CONTINUATION};
288         }
289         if ((flags & Want::FLAG_ABILITY_PREPARE_CONTINUATION) == Want::FLAG_ABILITY_PREPARE_CONTINUATION) {
290             return {true, LaunchReason::LAUNCHREASON_PREPARE_CONTINUATION};
291         }
292         return {false, LaunchReason::LAUNCHREASON_UNKNOWN};
293     }
294 
IsAcquireShareDataAbilityRequest295     bool IsAcquireShareData() const
296     {
297         return want.GetBoolParam(Want::PARAM_ABILITY_ACQUIRE_SHARE_DATA, false);
298     }
299 
IsAppRecoveryAbilityRequest300     bool IsAppRecovery() const
301     {
302         return want.GetBoolParam(Want::PARAM_ABILITY_RECOVERY_RESTART, false);
303     }
304 
IsCallTypeAbilityRequest305     bool IsCallType(const AbilityCallType & type) const
306     {
307         return (callType == type);
308     }
309 
DumpAbilityRequest310     void Dump(std::vector<std::string> &state)
311     {
312         std::string dumpInfo = "      want [" + want.ToUri() + "]";
313         state.push_back(dumpInfo);
314         dumpInfo = "      app name [" + abilityInfo.applicationName + "]";
315         state.push_back(dumpInfo);
316         dumpInfo = "      main name [" + abilityInfo.name + "]";
317         state.push_back(dumpInfo);
318         dumpInfo = "      request code [" + std::to_string(requestCode) + "]";
319         state.push_back(dumpInfo);
320     }
321 
322     void Voluation(const Want &srcWant, int srcRequestCode,
323         const sptr<IRemoteObject> &srcCallerToken, const std::shared_ptr<AbilityStartSetting> srcStartSetting = nullptr,
324         int srcCallerUid = -1)
325     {
326         want = srcWant;
327         requestCode = srcRequestCode;
328         callerToken = srcCallerToken;
329         startSetting = srcStartSetting;
330         callerUid = srcCallerUid == -1 ? IPCSkeleton::GetCallingUid() : srcCallerUid;
331     }
332 };
333 
334 // new version
335 enum ResolveResultType {
336     OK_NO_REMOTE_OBJ = 0,
337     OK_HAS_REMOTE_OBJ,
338     NG_INNER_ERROR,
339 };
340 
341 enum class AbilityWindowState {
342     FOREGROUND = 0,
343     BACKGROUND,
344     TERMINATE,
345     FOREGROUNDING,
346     BACKGROUNDING,
347     TERMINATING
348 };
349 
350 enum class AbilityVisibilityState {
351     INITIAL = 0,
352     FOREGROUND_HIDE,
353     FOREGROUND_SHOW,
354     UNSPECIFIED,
355 };
356 
357 struct LaunchDebugInfo {
358 public:
359     void Update(const Want &want);
360 
361     bool isDebugAppSet = false;
362     bool isNativeDebugSet = false;
363     bool isPerfCmdSet = false;
364     bool debugApp = false;
365     bool nativeDebug = false;
366     std::string perfCmd;
367 };
368 
369 /**
370  * @class AbilityRecord
371  * AbilityRecord records ability info and states and used to schedule ability life.
372  */
373 class AbilityRecord : public std::enable_shared_from_this<AbilityRecord> {
374 public:
375     AbilityRecord(const Want &want, const AppExecFwk::AbilityInfo &abilityInfo,
376         const AppExecFwk::ApplicationInfo &applicationInfo, int requestCode = -1);
377 
378     virtual ~AbilityRecord();
379 
380     /**
381      * CreateAbilityRecord.
382      *
383      * @param abilityRequest,create ability record.
384      * @return Returns ability record ptr.
385      */
386     static std::shared_ptr<AbilityRecord> CreateAbilityRecord(const AbilityRequest &abilityRequest);
387 
388     /**
389      * Init ability record.
390      *
391      * @return Returns true on success, others on failure.
392      */
393     bool Init();
394 
395     /**
396      * load UI ability.
397      *
398      */
399     void LoadUIAbility();
400 
401     /**
402      * load ability.
403      *
404      * @return Returns ERR_OK on success, others on failure.
405      */
406     int LoadAbility(bool isShellCall = false);
407 
408     /**
409      * foreground the ability.
410      *
411      */
412     void ForegroundAbility(uint32_t sceneFlag = 0);
413     void ForegroundUIExtensionAbility(uint32_t sceneFlag = 0);
414 
415     /**
416      * process request of foregrounding the ability.
417      *
418      */
419     void ProcessForegroundAbility(uint32_t tokenId, uint32_t sceneFlag = 0, bool isShellCall = false);
420 
421      /**
422      * post foreground timeout task for ui ability.
423      *
424      */
425     void PostForegroundTimeoutTask();
426 
427     void PostUIExtensionAbilityTimeoutTask(uint32_t messageId);
428 
429     /**
430      * move the ability to back ground.
431      *
432      * @param task timeout task.
433      */
434     void BackgroundAbility(const Closure &task);
435 
436     /**
437      * prepare terminate ability.
438      *
439      * @return Returns true on stop terminating; returns false on terminate.
440      */
441     bool PrepareTerminateAbility();
442 
443     /**
444      * terminate ability.
445      *
446      * @return Returns ERR_OK on success, others on failure.
447      */
448     int TerminateAbility();
449 
450     /**
451      * get ability's info.
452      *
453      * @return ability info.
454      */
455     const AppExecFwk::AbilityInfo &GetAbilityInfo() const;
456 
457     /**
458      * get application's info.
459      *
460      * @return application info.
461      */
462     const AppExecFwk::ApplicationInfo &GetApplicationInfo() const;
463 
464     /**
465      * set ability's state.
466      *
467      * @param state, ability's state.
468      */
469     void SetAbilityState(AbilityState state);
470 
471     bool GetAbilityForegroundingFlag() const;
472 
473     void SetAbilityForegroundingFlag();
474 
475     /**
476      * get ability's state.
477      *
478      * @return ability state.
479      */
480     AbilityState GetAbilityState() const;
481 
482     /**
483      * get ability's windowconfig.
484      *
485      * @return ability windowconfig.
486      */
487     WindowConfig GetAbilityWindowConfig() const;
488 
489     bool IsForeground() const;
490 
491     AbilityVisibilityState GetAbilityVisibilityState() const;
492     void SetAbilityVisibilityState(AbilityVisibilityState state);
493 
494     void UpdateAbilityVisibilityState();
495 
496     /**
497      * set ability scheduler for accessing ability thread.
498      *
499      * @param scheduler , ability scheduler.
500      */
501     void SetScheduler(const sptr<IAbilityScheduler> &scheduler);
502 
GetScheduler()503     inline sptr<IAbilityScheduler> GetScheduler() const
504     {
505         return scheduler_;
506     }
507 
508     sptr<SessionInfo> GetSessionInfo() const;
509 
510     /**
511      * get ability's token.
512      *
513      * @return ability's token.
514      */
515     sptr<Token> GetToken() const;
516 
517     /**
518      * set ability's previous ability record.
519      *
520      * @param abilityRecord , previous ability record
521      */
522     void SetPreAbilityRecord(const std::shared_ptr<AbilityRecord> &abilityRecord);
523 
524     /**
525      * get ability's previous ability record.
526      *
527      * @return previous ability record
528      */
529     std::shared_ptr<AbilityRecord> GetPreAbilityRecord() const;
530 
531     /**
532      * set ability's next ability record.
533      *
534      * @param abilityRecord , next ability record
535      */
536     void SetNextAbilityRecord(const std::shared_ptr<AbilityRecord> &abilityRecord);
537 
538     /**
539      * get ability's previous ability record.
540      *
541      * @return previous ability record
542      */
543     std::shared_ptr<AbilityRecord> GetNextAbilityRecord() const;
544 
545     /**
546      * check whether the ability is ready.
547      *
548      * @return true : ready ,false: not ready
549      */
550     bool IsReady() const;
551 
552     void UpdateRecoveryInfo(bool hasRecoverInfo);
553 
554     bool GetRecoveryInfo();
555 
556 #ifdef SUPPORT_GRAPHICS
557     /**
558      * check whether the ability 's window is attached.
559      *
560      * @return true : attached ,false: not attached
561      */
562     bool IsWindowAttached() const;
563 
IsStartingWindow()564     inline bool IsStartingWindow() const
565     {
566         return isStartingWindow_;
567     }
568 
SetStartingWindow(bool isStartingWindow)569     inline void SetStartingWindow(bool isStartingWindow)
570     {
571         isStartingWindow_ = isStartingWindow;
572     }
573 
574     void PostCancelStartingWindowHotTask();
575 
576     /**
577      * process request of foregrounding the ability.
578      *
579      */
580     void ProcessForegroundAbility(bool isRecent, const AbilityRequest &abilityRequest,
581         std::shared_ptr<StartOptions> &startOptions, const std::shared_ptr<AbilityRecord> &callerAbility,
582         uint32_t sceneFlag = 0);
583 
584     void ProcessForegroundAbility(const std::shared_ptr<AbilityRecord> &callerAbility, bool needExit = true,
585         uint32_t sceneFlag = 0);
586     void NotifyAnimationFromTerminatingAbility() const;
587     void NotifyAnimationFromMinimizeAbility(bool& animaEnabled);
588 
589     bool ReportAtomicServiceDrawnCompleteEvent();
590     void SetCompleteFirstFrameDrawing(const bool flag);
591     bool IsCompleteFirstFrameDrawing() const;
592     bool GetColdStartFlag();
593     void SetColdStartFlag(bool isColdStart);
594 #endif
595 
596     bool GrantUriPermissionForServiceExtension();
597 
598     bool GrantUriPermissionForUIExtension();
599 
600     /**
601      * check whether the ability is launcher.
602      *
603      * @return true : lanucher ,false: not lanucher
604      */
605     bool IsLauncherAbility() const;
606 
607     /**
608      * check whether the ability is terminating.
609      *
610      * @return true : yes ,false: not
611      */
612     bool IsTerminating() const;
613 
614     /**
615      * set the ability is terminating.
616      *
617      */
618     void SetTerminatingState();
619 
620     /**
621      * set the ability is new want flag.
622      *
623      * @return isNewWant
624      */
625     void SetIsNewWant(bool isNewWant);
626 
627     /**
628      * check whether the ability is new want flag.
629      *
630      * @return true : yes ,false: not
631      */
632     bool IsNewWant() const;
633 
634     /**
635      * check whether the ability is created by connect ability mode.
636      *
637      * @return true : yes ,false: not
638      */
639     bool IsCreateByConnect() const;
640 
641     /**
642      * set the ability is created by connect ability mode.
643      *
644      */
645     void SetCreateByConnectMode(bool isCreatedByConnect = true);
646 
647     /**
648      * active the ability.
649      *
650      */
651     virtual void Activate();
652 
653     /**
654      * inactive the ability.
655      *
656      */
657     virtual void Inactivate();
658 
659     /**
660      * terminate the ability.
661      *
662      */
663     void Terminate(const Closure &task);
664 
665     /**
666      * connect the ability.
667      *
668      */
669     void ConnectAbility();
670 
671     /**
672      * connect the ability with want.
673      *
674      */
675     void ConnectAbilityWithWant(const Want &want);
676 
677     /**
678      * disconnect the ability.
679      *
680      */
681     void DisconnectAbility();
682 
683     /**
684      * disconnect the ability with want
685      *
686      */
687     void DisconnectAbilityWithWant(const Want &want);
688 
689     /**
690      * Command the ability.
691      *
692      */
693     void CommandAbility();
694 
695     void CommandAbilityWindow(const sptr<SessionInfo> &sessionInfo, WindowCommand winCmd);
696 
697     /**
698      * save ability state.
699      *
700      */
701     void SaveAbilityState();
702     void SaveAbilityState(const PacMap &inState);
703     void SaveAbilityWindowConfig(const WindowConfig &windowConfig);
704 
705     /**
706      * restore ability state.
707      *
708      */
709     void RestoreAbilityState();
710 
711     /**
712      * notify top active ability updated.
713      *
714      */
715     void TopActiveAbilityChanged(bool flag);
716 
717     /**
718      * set the want for start ability.
719      *
720      */
721     void SetWant(const Want &want);
722 
723     /**
724      * get the want for start ability.
725      *
726      */
727     Want GetWant() const;
728 
729     /**
730      * remove signature info of want.
731      *
732      */
733     void RemoveSignatureInfo();
734 
735     /**
736      * remove specified wantParam for start ability.
737      *
738      */
739     void RemoveSpecifiedWantParam(const std::string &key);
740 
741     /**
742      * get request code of the ability to start.
743      *
744      */
745     int GetRequestCode() const;
746 
747     /**
748      * set the result object of the ability which one need to be terminated.
749      *
750      */
751     void SetResult(const std::shared_ptr<AbilityResult> &result);
752 
753     /**
754      * get the result object of the ability which one need to be terminated.
755      *
756      */
757     std::shared_ptr<AbilityResult> GetResult() const;
758 
759     /**
760      * send result object to caller ability thread.
761      *
762      */
763     void SendResult(bool isSandboxApp, uint32_t tokeId);
764 
765     /**
766      * send result object to caller ability thread.
767      *
768      */
769     void SendResultByBackToCaller(const std::shared_ptr<AbilityResult> &result);
770 
771     /**
772      * send result object to caller ability thread for sandbox app file saving.
773      */
774     void SendSandboxSavefileResult(const Want &want, int resultCode, int requestCode);
775 
776     /**
777      * send result object to caller ability.
778      *
779      */
780     void SendResultToCallers(bool schedulerdied = false);
781 
782     /**
783      * save result object to caller ability.
784      *
785      */
786     void SaveResultToCallers(const int resultCode, const Want *resultWant);
787 
788     std::shared_ptr<AbilityRecord> GetCallerByRequestCode(int32_t requestCode, int32_t pid);
789 
790     /**
791      * save result to caller ability.
792      *
793      */
794     void SaveResult(int resultCode, const Want *resultWant, std::shared_ptr<CallerRecord> caller);
795 
796     bool NeedConnectAfterCommand();
797 
798     /**
799      * add connect record to the list.
800      *
801      */
802     void AddConnectRecordToList(const std::shared_ptr<ConnectionRecord> &connRecord);
803 
804     /**
805      * get the list of connect record.
806      *
807      */
808     std::list<std::shared_ptr<ConnectionRecord>> GetConnectRecordList() const;
809 
810     /**
811      * get the list of connect record.
812      *
813      */
814     std::list<std::shared_ptr<ConnectionRecord>> GetConnectingRecordList();
815 
816     /**
817      * get the count of In Progress record.
818      *
819      */
820     uint32_t GetInProgressRecordCount();
821     /**
822      * remove the connect record from list.
823      *
824      */
825     void RemoveConnectRecordFromList(const std::shared_ptr<ConnectionRecord> &connRecord);
826 
827     /**
828      * check whether connect list is empty.
829      *
830      */
831     bool IsConnectListEmpty();
832 
833     size_t GetConnectedListSize();
834 
835     size_t GetConnectingListSize();
836 
837     void RemoveCallerRequestCode(std::shared_ptr<AbilityRecord> callerAbilityRecord, int32_t requestCode);
838 
839     /**
840      * add caller record
841      *
842      */
843     void AddCallerRecord(const sptr<IRemoteObject> &callerToken, int requestCode, const Want &want,
844         std::string srcAbilityId = "", uint32_t callingTokenId = 0);
845 
846     /**
847      * get caller record to list.
848      *
849      */
850     std::list<std::shared_ptr<CallerRecord>> GetCallerRecordList() const;
851     std::shared_ptr<AbilityRecord> GetCallerRecord() const;
852 
853     std::shared_ptr<CallerAbilityInfo> GetCallerInfo() const;
854 
855     /**
856      * get connecting record from list.
857      *
858      */
859     std::shared_ptr<ConnectionRecord> GetConnectingRecord() const;
860 
861     /**
862      * get disconnecting record from list.
863      *
864      */
865     std::shared_ptr<ConnectionRecord> GetDisconnectingRecord() const;
866 
867     /**
868      * convert ability state (enum type to string type).
869      *
870      */
871     static std::string ConvertAbilityState(const AbilityState &state);
872 
873     static std::string ConvertAppState(const AppState &state);
874 
875     /**
876      * convert life cycle state to ability state .
877      *
878      */
879     static int ConvertLifeCycleToAbilityState(const AbilityLifeCycleState &state);
880 
881     /**
882      * get the ability record id.
883      *
884      */
GetRecordId()885     inline int GetRecordId() const
886     {
887         return recordId_;
888     }
889 
890     /**
891      * dump ability info.
892      *
893      */
894     void Dump(std::vector<std::string> &info);
895 
896     void DumpClientInfo(std::vector<std::string> &info, const std::vector<std::string> &params,
897         bool isClient = false, bool dumpConfig = true) const;
898 
899     /**
900      * Called when client complete dump.
901      *
902      * @param infos The dump info.
903      */
904     void DumpAbilityInfoDone(std::vector<std::string> &infos);
905 
906     /**
907      * dump ability state info.
908      *
909      */
910     void DumpAbilityState(std::vector<std::string> &info, bool isClient, const std::vector<std::string> &params);
911 
912     void SetStartTime();
913 
914     int64_t GetStartTime() const;
915 
916     /**
917      * dump service info.
918      *
919      */
920     void DumpService(std::vector<std::string> &info, bool isClient = false) const;
921 
922     /**
923      * dump service info.
924      *
925      */
926     void DumpService(std::vector<std::string> &info, std::vector<std::string> &params, bool isClient = false) const;
927 
928     /**
929      * set aconnect remote object.
930      *
931      */
932     void SetConnRemoteObject(const sptr<IRemoteObject> &remoteObject);
933 
934     /**
935      * get connect remote object.
936      *
937      */
938     sptr<IRemoteObject> GetConnRemoteObject() const;
939 
940     /**
941      * check whether the ability is never started.
942      */
943     bool IsNeverStarted() const;
944 
945     void AddStartId();
946     int GetStartId() const;
947 
948     void SetIsUninstallAbility();
949     /**
950      * Determine whether ability is uninstalled
951      *
952      * @return true: uninstalled false: installed
953      */
954     bool IsUninstallAbility() const;
955     void ShareData(const int32_t &uniqueId);
956     void SetLauncherRoot();
957     bool IsLauncherRoot() const;
958     bool IsAbilityState(const AbilityState &state) const;
959     bool IsActiveState() const;
960 
961     void SetStartSetting(const std::shared_ptr<AbilityStartSetting> &setting);
962     std::shared_ptr<AbilityStartSetting> GetStartSetting() const;
963 
964     void SetRestarting(const bool isRestart);
965     void SetRestarting(const bool isRestart, int32_t canReStartCount);
966     int32_t GetRestartCount() const;
967     void SetRestartCount(int32_t restartCount);
968     bool GetKeepAlive() const;
SetKeepAliveBundle(bool value)969     void SetKeepAliveBundle(bool value)
970     {
971         keepAliveBundle_ = value;
972     }
IsKeepAliveBundle()973     bool IsKeepAliveBundle() const
974     {
975         return keepAliveBundle_;
976     }
977     void SetLoading(bool status);
978     bool IsLoading() const;
979     int64_t GetRestartTime();
980     void SetRestartTime(const int64_t restartTime);
981     void SetAppIndex(const int32_t appIndex);
982     int32_t GetAppIndex() const;
983     bool IsRestarting() const;
984     void SetAppState(const AppState &state);
985     AppState GetAppState() const;
986 
987     void SetLaunchReason(const LaunchReason &reason);
988     void SetLastExitReason(const ExitReason &exitReason);
989     void ContinueAbility(const std::string &deviceId, uint32_t versionCode);
990     void NotifyContinuationResult(int32_t result);
991 
992     void SetMissionId(int32_t missionId);
993     int32_t GetMissionId() const;
994 
995     void SetUid(int32_t uid);
996     int32_t GetUid();
997     int32_t GetPid();
998     void SetSwitchingPause(bool state);
999     bool IsSwitchingPause();
1000     void SetOwnerMissionUserId(int32_t userId);
1001     int32_t GetOwnerMissionUserId();
1002 
1003     // new version
1004     ResolveResultType Resolve(const AbilityRequest &abilityRequest);
1005     bool ReleaseCall(const sptr<IAbilityConnection> &connect);
1006     bool IsNeedToCallRequest() const;
1007     bool IsStartedByCall() const;
1008     void SetStartedByCall(const bool isFlag);
1009     void CallRequest();
1010     bool CallRequestDone(const sptr<IRemoteObject> &callStub) const;
1011     bool IsStartToBackground() const;
1012     void SetStartToBackground(const bool flag);
1013     bool IsStartToForeground() const;
1014     void SetStartToForeground(const bool flag);
1015     void SetSessionInfo(sptr<SessionInfo> sessionInfo);
1016     void UpdateSessionInfo(sptr<IRemoteObject> sessionToken);
1017     void SetMinimizeReason(bool fromUser);
1018     void SetSceneFlag(uint32_t sceneFlag);
1019     bool IsMinimizeFromUser() const;
1020     void SetClearMissionFlag(bool clearMissionFlag);
1021     bool IsClearMissionFlag();
1022 
1023     void SetSpecifiedFlag(const std::string &flag);
1024     std::string GetSpecifiedFlag() const;
1025     void SetWindowMode(int32_t windowMode);
1026     void RemoveWindowMode();
1027     LifeCycleStateInfo lifeCycleStateInfo_;                // target life state info
1028 
1029     bool CanRestartRootLauncher();
1030 
1031     bool CanRestartResident();
1032 
1033     std::string GetLabel();
GetAbilityRecordId()1034     inline int64_t GetAbilityRecordId() const
1035     {
1036         return recordId_;
1037     }
1038 
1039     void SetPendingState(AbilityState state);
1040     AbilityState GetPendingState() const;
1041 
1042     bool IsNeedBackToOtherMissionStack();
1043     void SetNeedBackToOtherMissionStack(bool isNeedBackToOtherMissionStack);
1044     std::shared_ptr<AbilityRecord> GetOtherMissionStackAbilityRecord() const;
1045     void SetOtherMissionStackAbilityRecord(const std::shared_ptr<AbilityRecord> &abilityRecord);
1046     void RevokeUriPermission();
1047     void RemoveAbilityDeathRecipient() const;
1048     bool IsExistConnection(const sptr<IAbilityConnection> &connect);
1049 
1050     int32_t GetCollaboratorType() const;
1051 
1052     std::string GetMissionAffinity() const;
1053 
1054     void SetLockedState(bool lockedState);
1055     bool GetLockedState();
1056 
1057     void SetAttachDebug(const bool isAttachDebug);
1058     void SetAssertDebug(bool isAssertDebug);
1059     int32_t CreateModalUIExtension(const Want &want);
1060 
1061     AppExecFwk::ElementName GetElementName() const;
1062     bool IsDebugApp() const;
1063     bool IsDebug() const;
1064 
1065     void AddAbilityWindowStateMap(uint64_t uiExtensionComponentId,
1066         AbilityWindowState abilityWindowState);
1067 
1068     void RemoveAbilityWindowStateMap(uint64_t uiExtensionComponentId);
1069 
1070     bool IsAbilityWindowReady();
1071 
1072     void SetAbilityWindowState(const sptr<SessionInfo> &sessionInfo,
1073         WindowCommand winCmd, bool isFinished);
1074 
1075     void SetUIExtensionAbilityId(const int32_t uiExtensionAbilityId);
1076     int32_t GetUIExtensionAbilityId() const;
1077 
1078     void OnProcessDied();
1079 
1080     void SetProcessName(const std::string &process);
1081 
1082     std::string GetProcessName() const;
1083 
1084     void SetURI(const std::string &uri);
1085     std::string GetURI() const;
1086 
1087     void DoBackgroundAbilityWindowDelayed(bool needBackground);
1088     bool BackgroundAbilityWindowDelayed();
1089 
1090     bool IsSceneBoard() const;
1091 
1092     void SetRestartAppFlag(bool isRestartApp);
1093     bool GetRestartAppFlag() const;
1094 
1095     void SetSpecifyTokenId(const uint32_t specifyTokenId);
1096     void UpdateUIExtensionInfo(const WantParams &wantParams);
1097 
1098     void SaveConnectWant(const Want &want);
1099 
1100     void UpdateConnectWant();
1101 
1102     void RemoveConnectWant();
1103 
1104     void UpdateDmsCallerInfo(Want &want);
1105 
SetSecurityFlag(bool securityFlag)1106     void SetSecurityFlag(bool securityFlag)
1107     {
1108         securityFlag_ = securityFlag;
1109     }
1110 
GetSecurityFlag()1111     bool GetSecurityFlag() const
1112     {
1113         return securityFlag_;
1114     }
1115 
1116 protected:
1117     void SendEvent(uint32_t msg, uint32_t timeOut, int32_t param = -1, bool isExtension = false);
1118 
1119     sptr<Token> token_ = {};                               // used to interact with kit and wms
1120     std::unique_ptr<LifecycleDeal> lifecycleDeal_ = {};    // life manager used to schedule life
1121     AbilityState currentState_ = AbilityState::INITIAL;    // current life state
1122     Want want_ = {};                                       // want to start this ability
1123 
1124 private:
1125     /**
1126      * get the type of ability.
1127      *
1128      */
1129     void GetAbilityTypeString(std::string &typeStr);
1130     void OnSchedulerDied(const wptr<IRemoteObject> &remote);
1131     void GrantUriPermission(Want &want, std::string targetBundleName, bool isSandboxApp, uint32_t tokenId);
1132     void GrantDmsUriPermission(Want &want, std::string targetBundleName);
1133     bool IsDmsCall(Want &want);
1134     int32_t GetCurrentAccountId() const;
1135 
1136     /**
1137      * add system ability caller record
1138      *
1139      */
1140     void AddSystemAbilityCallerRecord(const sptr<IRemoteObject> &callerToken, int requestCode,
1141         std::string srcAbilityId);
1142 
1143     bool IsSystemAbilityCall(const sptr<IRemoteObject> &callerToken, uint32_t callingTokenId = 0);
1144 
1145     void RecordSaCallerInfo(const Want &want);
1146 
1147 #ifdef WITH_DLP
1148     void HandleDlpAttached();
1149     void HandleDlpClosed();
1150 #endif // WITH_DLP
1151     void NotifyRemoveShellProcess(int32_t type);
1152     void NotifyAnimationAbilityDied();
SetCallerAccessTokenId(uint32_t callerAccessTokenId)1153     inline void SetCallerAccessTokenId(uint32_t callerAccessTokenId)
1154     {
1155         callerAccessTokenId_ = callerAccessTokenId;
1156     }
1157 
1158     bool GrantPermissionToShell(const std::vector<std::string> &uriVec, uint32_t flag, std::string targetPkg);
1159 
1160     void GrantUriPermissionInner(Want &want, std::vector<std::string> &uriVec, const std::string &targetBundleName,
1161          uint32_t tokenId);
1162     void GrantUriPermissionFor2In1Inner(
1163         Want &want, std::vector<std::string> &uriVec, const std::string &targetBundleName, uint32_t tokenId);
1164 
1165     LastExitReason CovertAppExitReasonToLastReason(const Reason exitReason);
1166 
1167     void NotifyMissionBindPid();
1168 
1169     void DumpUIExtensionRootHostInfo(std::vector<std::string> &info) const;
1170 
1171     void DumpUIExtensionPid(std::vector<std::string> &info, bool isUIExtension) const;
1172 
1173     void PublishFileOpenEvent(const Want &want);
1174 
1175     void SetDebugAppByWaitingDebugFlag();
1176     void AfterLoaded();
1177 
1178 #ifdef SUPPORT_GRAPHICS
1179     std::shared_ptr<Want> GetWantFromMission() const;
1180     void SetShowWhenLocked(const AppExecFwk::AbilityInfo &abilityInfo, sptr<AbilityTransitionInfo> &info) const;
1181     void SetAbilityTransitionInfo(const AppExecFwk::AbilityInfo &abilityInfo,
1182         sptr<AbilityTransitionInfo> &info) const;
1183     void SetAbilityTransitionInfo(sptr<AbilityTransitionInfo>& info) const;
1184     sptr<IWindowManagerServiceHandler> GetWMSHandler() const;
1185     void SetWindowModeAndDisplayId(sptr<AbilityTransitionInfo> &info, const std::shared_ptr<Want> &want) const;
1186     sptr<AbilityTransitionInfo> CreateAbilityTransitionInfo();
1187     sptr<AbilityTransitionInfo> CreateAbilityTransitionInfo(const std::shared_ptr<StartOptions> &startOptions,
1188         const std::shared_ptr<Want> &want) const;
1189     sptr<AbilityTransitionInfo> CreateAbilityTransitionInfo(const AbilityRequest &abilityRequest) const;
1190     sptr<AbilityTransitionInfo> CreateAbilityTransitionInfo(const std::shared_ptr<StartOptions> &startOptions,
1191         const std::shared_ptr<Want> &want, const AbilityRequest &abilityRequest);
1192     std::shared_ptr<Global::Resource::ResourceManager> CreateResourceManager() const;
1193     std::shared_ptr<Media::PixelMap> GetPixelMap(const uint32_t windowIconId,
1194         std::shared_ptr<Global::Resource::ResourceManager> resourceMgr) const;
1195 
1196     void AnimationTask(bool isRecent, const AbilityRequest &abilityRequest,
1197         const std::shared_ptr<StartOptions> &startOptions, const std::shared_ptr<AbilityRecord> &callerAbility);
1198     void NotifyAnimationFromStartingAbility(const std::shared_ptr<AbilityRecord> &callerAbility,
1199         const AbilityRequest &abilityRequest) const;
1200     void NotifyAnimationFromRecentTask(const std::shared_ptr<StartOptions> &startOptions,
1201         const std::shared_ptr<Want> &want) const;
1202     void NotifyAnimationFromTerminatingAbility(const std::shared_ptr<AbilityRecord> &callerAbility, bool needExit,
1203         bool flag);
1204 
1205     void StartingWindowTask(bool isRecent, bool isCold, const AbilityRequest &abilityRequest,
1206         std::shared_ptr<StartOptions> &startOptions);
1207     void StartingWindowColdTask(bool isRecnet, const AbilityRequest &abilityRequest,
1208         std::shared_ptr<StartOptions> &startOptions);
1209     void PostCancelStartingWindowColdTask();
1210     void StartingWindowHot(const std::shared_ptr<StartOptions> &startOptions, const std::shared_ptr<Want> &want,
1211         const AbilityRequest &abilityRequest);
1212     void StartingWindowHot();
1213     void StartingWindowCold(const std::shared_ptr<StartOptions> &startOptions, const std::shared_ptr<Want> &want,
1214         const AbilityRequest &abilityRequest);
1215     void InitColdStartingWindowResource(const std::shared_ptr<Global::Resource::ResourceManager> &resourceMgr);
1216     void GetColdStartingWindowResource(std::shared_ptr<Media::PixelMap> &bg, uint32_t &bgColor);
1217     void SetAbilityStateInner(AbilityState state);
1218 #endif
1219 
1220     static int64_t abilityRecordId;
1221     int recordId_ = 0;                                // record id
1222     int32_t uiExtensionAbilityId_ = 0;                // uiextension ability id
1223     AppExecFwk::AbilityInfo abilityInfo_ = {};             // the ability info get from BMS
1224     AppExecFwk::ApplicationInfo applicationInfo_ = {};     // the ability info get from BMS
1225     std::weak_ptr<AbilityRecord> preAbilityRecord_ = {};   // who starts this ability record
1226     std::weak_ptr<AbilityRecord> nextAbilityRecord_ = {};  // ability that started by this ability
1227     int64_t startTime_ = 0;                           // records first time of ability start
1228     int64_t restartTime_ = 0;                         // the time of last trying restart
1229     bool isReady_ = false;                            // is ability thread attached?
1230     bool isWindowStarted_ = false;                     // is window hotstart or coldstart?
1231     bool isWindowAttached_ = false;                   // Is window of this ability attached?
1232     bool isLauncherAbility_ = false;                  // is launcher?
1233 
1234     sptr<IAbilityScheduler> scheduler_ = {};       // kit scheduler
1235     bool isLoading_ = false;        // is loading?
1236     bool isTerminating_ = false;              // is terminating ?
1237     bool isCreateByConnect_ = false;          // is created by connect ability mode?
1238 
1239     int requestCode_ = -1;  // requestCode_: >= 0 for-result start mode; <0 for normal start mode in default.
1240     sptr<IRemoteObject::DeathRecipient> schedulerDeathRecipient_ = {};  // scheduler binderDied Recipient
1241 
1242     /**
1243      * result_: ability starts with for-result mode will send result before being terminated.
1244      * Its caller will receive results before active.
1245      * Now we assume only one result generate when terminate.
1246      */
1247     std::shared_ptr<AbilityResult> result_ = {};
1248 
1249     /**
1250      * When this ability startAbilityForResult another ability, if another ability is terminated,
1251      * this ability will move to foreground, during this time, isAbilityForegrounding_ is true,
1252      * isAbilityForegrounding_ will be set to false when this ability is background
1253      */
1254     bool isAbilityForegrounding_ = false;
1255 
1256     // service(ability) can be connected by multi-pages(abilites), so need to store this service's connections
1257     mutable ffrt::mutex connRecordListMutex_;
1258     std::list<std::shared_ptr<ConnectionRecord>> connRecordList_ = {};
1259     // service(ability) onConnect() return proxy of service ability
1260     sptr<IRemoteObject> connRemoteObject_ = {};
1261     int startId_ = 0;  // service(ability) start id
1262 
1263     // page(ability) can be started by multi-pages(abilites), so need to store this ability's caller
1264     std::list<std::shared_ptr<CallerRecord>> callerList_ = {};
1265 
1266     bool isUninstall_ = false;
1267 
1268     bool isLauncherRoot_ = false;
1269 
1270     PacMap stateDatas_;             // ability saved ability state data
1271     WindowConfig windowConfig_;
1272     bool isRestarting_ = false;     // is restarting ?
1273     AppState appState_ = AppState::BEGIN;
1274 
1275     int32_t uid_ = 0;
1276     int32_t pid_ = 0;
1277     int32_t missionId_ = -1;
1278     int32_t ownerMissionUserId_ = -1;
1279     bool isSwitchingPause_ = false;
1280 
1281     // new version
1282     std::shared_ptr<CallContainer> callContainer_ = nullptr;
1283     bool isStartedByCall_ = false;
1284     bool isStartToBackground_ = false;
1285     bool isStartToForeground_ = false;
1286     int32_t appIndex_ = 0;
1287     bool minimizeReason_ = false;
1288 
1289     bool clearMissionFlag_ = false;
1290     bool keepAliveBundle_ = false;
1291     int32_t restartCount_ = -1;
1292     int32_t restartMax_ = -1;
1293     std::string specifiedFlag_;
1294     std::string uri_;
1295     ffrt::mutex lock_;
1296     mutable ffrt::mutex dumpInfoLock_;
1297     mutable ffrt::mutex dumpLock_;
1298     mutable ffrt::mutex resultLock_;
1299     mutable ffrt::mutex wantLock_;
1300     mutable ffrt::condition_variable dumpCondition_;
1301     mutable bool isDumpTimeout_ = false;
1302     std::vector<std::string> dumpInfos_;
1303     std::atomic<AbilityState> pendingState_ = AbilityState::INITIAL;    // pending life state
1304     std::atomic<AbilityVisibilityState> abilityVisibilityState_ = AbilityVisibilityState::INITIAL;
1305 
1306     // scene session
1307     sptr<SessionInfo> sessionInfo_ = nullptr;
1308     mutable ffrt::mutex sessionLock_;
1309     std::map<uint64_t, AbilityWindowState> abilityWindowStateMap_;
1310 
1311 #ifdef SUPPORT_GRAPHICS
1312     bool isStartingWindow_ = false;
1313     uint32_t bgColor_ = 0;
1314     std::shared_ptr<Media::PixelMap> startingWindowBg_ = nullptr;
1315 
1316     bool isCompleteFirstFrameDrawing_ = false;
1317     bool coldStart_ = false;
1318 #endif
1319 
1320     bool isGrantedUriPermission_ = false;
1321     uint32_t callerAccessTokenId_ = -1;
1322     bool isNeedBackToOtherMissionStack_ = false;
1323     std::weak_ptr<AbilityRecord> otherMissionStackAbilityRecord_; // who starts this ability record by SA
1324     int32_t collaboratorType_ = 0;
1325     std::string missionAffinity_ = "";
1326     bool lockedState_ = false;
1327     bool isAttachDebug_ = false;
1328     bool isAssertDebug_ = false;
1329     bool isAppAutoStartup_ = false;
1330     bool isConnected = false;
1331     std::atomic_bool backgroundAbilityWindowDelayed_ = false;
1332 
1333     bool isRestartApp_ = false; // Only app calling RestartApp can be set to true
1334     uint32_t specifyTokenId_ = 0;
1335 
1336     std::shared_ptr<Want> connectWant_ = nullptr;
1337     std::shared_ptr<CallerAbilityInfo> saCallerInfo_ = nullptr;
1338     ffrt::mutex connectWantLock_;
1339     bool isLaunching_ = true;
1340     LaunchDebugInfo launchDebugInfo_;
1341     bool securityFlag_ = false;
1342 };
1343 }  // namespace AAFwk
1344 }  // namespace OHOS
1345 #endif  // OHOS_ABILITY_RUNTIME_ABILITY_RECORD_H
1346