• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023 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 #include "mock_session_manager_service.h"
17 
18 #include <cstdint>
19 #include <fcntl.h>
20 #include <securec.h>
21 #include <unistd.h>
22 
23 #include <bundle_mgr_interface.h>
24 #include <system_ability_definition.h>
25 #include <cinttypes>
26 #include <csignal>
27 #include <iomanip>
28 #include <ipc_skeleton.h>
29 #include <iservice_registry.h>
30 #include <map>
31 #include <sstream>
32 
33 #include "window_manager_hilog.h"
34 #include "unique_fd.h"
35 #include "parameters.h"
36 #include "root_scene.h"
37 #include "string_ex.h"
38 #include "wm_common.h"
39 #include "ws_common.h"
40 #include "session_manager_service_interface.h"
41 #include "scene_session_manager_interface.h"
42 #include "screen_session_manager_lite.h"
43 #include "common/include/session_permission.h"
44 
45 #define PATH_LEN 1024
46 #define O_RDWR   02
47 
48 namespace OHOS {
49 namespace Rosen {
50 namespace {
51 constexpr HiviewDFX::HiLogLabel LABEL = { LOG_CORE, HILOG_DOMAIN_WINDOW, "MockSessionManagerService" };
52 
53 const std::u16string DEFAULT_USTRING = u"error";
54 const char DEFAULT_STRING[] = "error";
55 const std::string ARG_DUMP_HELP = "-h";
56 const std::string ARG_DUMP_ALL = "-a";
57 const std::string ARG_DUMP_WINDOW = "-w";
58 const std::string KEY_SCENE_BOARD_TEST_ENABLE = "persist.scb.testmode.enable";
59 const std::string SCENE_BOARD_BUNDLE_NAME = "com.ohos.sceneboard";
60 const std::string TEST_MODULE_NAME_SUFFIX = "_test";
61 const std::string BOOTEVENT_WMS_READY = "bootevent.wms.ready";
62 
GetUserIdByCallingUid()63 inline int32_t GetUserIdByCallingUid()
64 {
65     int32_t uid = IPCSkeleton::GetCallingUid();
66     TLOGD(WmsLogTag::WMS_MULTI_USER, "get calling uid(%{public}d)", uid);
67     if (uid <= INVALID_UID) {
68         TLOGE(WmsLogTag::WMS_MULTI_USER, "uid is illegal: %{public}d", uid);
69         return INVALID_USER_ID;
70     }
71     return GetUserIdByUid(uid);
72 }
73 } // namespace
74 
75 
76 class ClientListenerDeathRecipient : public IRemoteObject::DeathRecipient {
77 public:
ClientListenerDeathRecipient(int32_t userId,int32_t pid,bool isLite)78     explicit ClientListenerDeathRecipient(int32_t userId, int32_t pid, bool isLite)
79         : userId_(userId), pid_(pid), isLite_(isLite)
80     {}
81 
OnRemoteDied(const wptr<IRemoteObject> & wptrDeath)82     void OnRemoteDied(const wptr<IRemoteObject>& wptrDeath) override
83     {
84         TLOGD(WmsLogTag::WMS_RECOVER, "Client died, pid = %{public}d, isLite = %{public}d", pid_, isLite_);
85         if (isLite_) {
86             MockSessionManagerService::GetInstance().UnregisterSMSLiteRecoverListener(userId_, pid_);
87         } else {
88             MockSessionManagerService::GetInstance().UnregisterSMSRecoverListener(userId_, pid_);
89         }
90     }
91 
92 private:
93     int32_t userId_;
94     int32_t pid_;
95     bool isLite_;
96 };
97 
WM_IMPLEMENT_SINGLE_INSTANCE(MockSessionManagerService)98 WM_IMPLEMENT_SINGLE_INSTANCE(MockSessionManagerService)
99 MockSessionManagerService::SMSDeathRecipient::SMSDeathRecipient(int32_t userId)
100     : userId_(userId), screenId_(DEFAULT_SCREEN_ID)
101 {}
102 
OnRemoteDied(const wptr<IRemoteObject> & object)103 void MockSessionManagerService::SMSDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& object)
104 {
105     TLOGI(WmsLogTag::WMS_MULTI_USER, "Scb died with userId_=%{public}d, screenId_=%{public}d", userId_, screenId_);
106     MockSessionManagerService::GetInstance().NotifyWMSConnectionChanged(userId_, screenId_, false);
107     MockSessionManagerService::GetInstance().RemoveSMSDeathRecipientByUserId(userId_);
108     MockSessionManagerService::GetInstance().RemoveSessionManagerServiceByUserId(userId_);
109     auto sessionManagerService = object.promote();
110     if (!sessionManagerService) {
111         TLOGE(WmsLogTag::WMS_MULTI_USER, "sessionManagerService is null");
112         return;
113     }
114 
115     if (IsSceneBoardTestMode()) {
116         TLOGI(WmsLogTag::WMS_MULTI_USER, "SceneBoard is testing, do not kill foundation.");
117         return;
118     }
119     TLOGW(WmsLogTag::WMS_MULTI_USER, "SessionManagerService died!");
120 }
121 
SetScreenId(int32_t screenId)122 void MockSessionManagerService::SMSDeathRecipient::SetScreenId(int32_t screenId)
123 {
124     TLOGI(WmsLogTag::WMS_MULTI_USER, "screenId=%{public}d", screenId);
125     screenId_ = screenId;
126 }
127 
MockSessionManagerService()128 MockSessionManagerService::MockSessionManagerService()
129     : SystemAbility(WINDOW_MANAGER_SERVICE_ID, true), currentWMSUserId_(INVALID_USER_ID),
130       currentScreenId_(DEFAULT_SCREEN_ID)
131 {}
132 
RegisterMockSessionManagerService()133 bool MockSessionManagerService::RegisterMockSessionManagerService()
134 {
135     bool res = SystemAbility::MakeAndRegisterAbility(this);
136     if (!res) {
137         WLOGFE("register failed");
138     }
139     if (!Publish(this)) {
140         WLOGFE("Publish failed");
141     }
142     WLOGFI("Publish mock session manager service success");
143     return true;
144 }
145 
OnStart()146 void MockSessionManagerService::OnStart()
147 {
148     WLOGFD("OnStart begin");
149 }
150 
Str16ToStr8(const std::u16string & str)151 static std::string Str16ToStr8(const std::u16string& str)
152 {
153     if (str == DEFAULT_USTRING) {
154         return DEFAULT_STRING;
155     }
156     std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert(DEFAULT_STRING);
157     std::string result = convert.to_bytes(str);
158     return result == DEFAULT_STRING ? "" : result;
159 }
160 
Dump(int fd,const std::vector<std::u16string> & args)161 int MockSessionManagerService::Dump(int fd, const std::vector<std::u16string> &args)
162 {
163     WLOGI("dump begin fd: %{public}d", fd);
164     if (fd < 0) {
165         return -1;
166     }
167     (void) signal(SIGPIPE, SIG_IGN); // ignore SIGPIPE crash
168     std::vector<std::string> params;
169     for (auto& arg : args) {
170         params.emplace_back(Str16ToStr8(arg));
171     }
172 
173     std::string dumpInfo;
174     if (params.empty()) {
175         ShowHelpInfo(dumpInfo);
176     } else if (params.size() == 1 && params[0] == ARG_DUMP_HELP) { // 1: params num
177         ShowHelpInfo(dumpInfo);
178     } else {
179         int errCode = DumpSessionInfo(params, dumpInfo);
180         if (errCode != 0) {
181             ShowIllegalArgsInfo(dumpInfo);
182         }
183     }
184     int ret = dprintf(fd, "%s\n", dumpInfo.c_str());
185     if (ret < 0) {
186         WLOGFE("dprintf error");
187         return -1; // WMError::WM_ERROR_INVALID_OPERATION;
188     }
189     WLOGI("dump end");
190     return 0;
191 }
192 
SetSessionManagerService(const sptr<IRemoteObject> & sessionManagerService)193 bool MockSessionManagerService::SetSessionManagerService(const sptr<IRemoteObject>& sessionManagerService)
194 {
195     if (!sessionManagerService) {
196         WLOGFE("sessionManagerService is nullptr");
197         return false;
198     }
199     currentWMSUserId_ = GetUserIdByCallingUid();
200     if (currentWMSUserId_ <= INVALID_USER_ID) {
201         TLOGE(WmsLogTag::WMS_MULTI_USER, "userId is illegal: %{public}d", currentWMSUserId_);
202         return false;
203     }
204     {
205         std::unique_lock<std::shared_mutex> lock(sessionManagerServiceMapLock_);
206         sessionManagerServiceMap_[currentWMSUserId_] = sessionManagerService;
207     }
208     auto smsDeathRecipient = GetSMSDeathRecipientByUserId(currentWMSUserId_);
209     if (!smsDeathRecipient) {
210         smsDeathRecipient = new SMSDeathRecipient(currentWMSUserId_);
211         std::unique_lock<std::shared_mutex> lock(smsDeathRecipientMapLock_);
212         if (!smsDeathRecipient) {
213             TLOGE(WmsLogTag::WMS_MULTI_USER, "Failed to create death Recipient ptr smsDeathRecipient");
214             return false;
215         }
216         smsDeathRecipientMap_[currentWMSUserId_] = smsDeathRecipient;
217     }
218     if (sessionManagerService->IsProxyObject() && !sessionManagerService->AddDeathRecipient(smsDeathRecipient)) {
219         TLOGE(WmsLogTag::WMS_MULTI_USER, "Failed to add death recipient");
220         return false;
221     }
222     RegisterMockSessionManagerService();
223     TLOGI(WmsLogTag::WMS_MULTI_USER, "sessionManagerService set success!");
224     system::SetParameter(BOOTEVENT_WMS_READY.c_str(), "true");
225     GetSceneSessionManager();
226 
227     return true;
228 }
229 
GetSMSDeathRecipientByUserId(int32_t userId)230 sptr<MockSessionManagerService::SMSDeathRecipient> MockSessionManagerService::GetSMSDeathRecipientByUserId(
231     int32_t userId)
232 {
233     std::shared_lock<std::shared_mutex> lock(smsDeathRecipientMapLock_);
234     auto iter = smsDeathRecipientMap_.find(userId);
235     if (iter != smsDeathRecipientMap_.end()) {
236         TLOGI(WmsLogTag::WMS_MULTI_USER, "Get SMS death recipient with userId=%{public}d", userId);
237         return iter->second;
238     } else {
239         TLOGW(WmsLogTag::WMS_MULTI_USER, "Get SMS death recipient failed with userId=%{public}d", userId);
240         return nullptr;
241     }
242 }
243 
RemoveSMSDeathRecipientByUserId(int32_t userId)244 void MockSessionManagerService::RemoveSMSDeathRecipientByUserId(int32_t userId)
245 {
246     TLOGI(WmsLogTag::WMS_MULTI_USER, "userId: %{public}d", userId);
247     auto sessionManagerService = GetSessionManagerServiceByUserId(userId);
248     std::unique_lock<std::shared_mutex> lock(smsDeathRecipientMapLock_);
249     auto iter = smsDeathRecipientMap_.find(userId);
250     if (iter != smsDeathRecipientMap_.end() && iter->second) {
251         if (sessionManagerService != nullptr) {
252             sessionManagerService->RemoveDeathRecipient(iter->second);
253         }
254     }
255 }
256 
GetSessionManagerService()257 sptr<IRemoteObject> MockSessionManagerService::GetSessionManagerService()
258 {
259     int32_t clientUserId = GetUserIdByCallingUid();
260     if (clientUserId <= INVALID_USER_ID) {
261         TLOGE(WmsLogTag::WMS_MULTI_USER, "userId is illegal: %{public}d", clientUserId);
262         return nullptr;
263     }
264     if (clientUserId == SYSTEM_USERID) {
265         TLOGI(WmsLogTag::WMS_MULTI_USER, "System user, return current sessionManagerService with %{public}d",
266             currentWMSUserId_);
267         clientUserId = currentWMSUserId_;
268     }
269     return GetSessionManagerServiceByUserId(clientUserId);
270 }
271 
GetSessionManagerServiceByUserId(int32_t userId)272 sptr<IRemoteObject> MockSessionManagerService::GetSessionManagerServiceByUserId(int32_t userId)
273 {
274     std::shared_lock<std::shared_mutex> lock(sessionManagerServiceMapLock_);
275     auto iter = sessionManagerServiceMap_.find(userId);
276     if (iter != sessionManagerServiceMap_.end()) {
277         TLOGD(WmsLogTag::WMS_MULTI_USER, "Get session manager service success with userId=%{public}d", userId);
278         return iter->second;
279     } else {
280         TLOGE(WmsLogTag::WMS_MULTI_USER, "Get session manager service failed with userId=%{public}d", userId);
281         return nullptr;
282     }
283 }
284 
RemoveSessionManagerServiceByUserId(int32_t userId)285 void MockSessionManagerService::RemoveSessionManagerServiceByUserId(int32_t userId)
286 {
287     TLOGI(WmsLogTag::WMS_MULTI_USER, "userId: %{public}d", userId);
288     std::unique_lock<std::shared_mutex> lock(sessionManagerServiceMapLock_);
289     auto iter = sessionManagerServiceMap_.find(userId);
290     if (iter != sessionManagerServiceMap_.end()) {
291         sessionManagerServiceMap_.erase(iter);
292     }
293 }
294 
NotifySceneBoardAvailable()295 void MockSessionManagerService::NotifySceneBoardAvailable()
296 {
297     if (!SessionPermission::IsSystemCalling()) {
298         TLOGE(WmsLogTag::WMS_RECOVER, "permission denied");
299         return;
300     }
301     int32_t userId = GetUserIdByCallingUid();
302     if (userId <= INVALID_USER_ID) {
303         TLOGE(WmsLogTag::WMS_RECOVER, "userId is illegal: %{public}d", userId);
304         return;
305     }
306     TLOGI(WmsLogTag::WMS_RECOVER, "scene board is available with userId=%{public}d", userId);
307 
308     NotifySceneBoardAvailableToLiteClient(SYSTEM_USERID);
309     NotifySceneBoardAvailableToLiteClient(userId);
310 
311     NotifySceneBoardAvailableToClient(SYSTEM_USERID);
312     NotifySceneBoardAvailableToClient(userId);
313 }
314 
RegisterSMSRecoverListener(const sptr<IRemoteObject> & listener)315 void MockSessionManagerService::RegisterSMSRecoverListener(const sptr<IRemoteObject>& listener)
316 {
317     if (listener == nullptr) {
318         TLOGE(WmsLogTag::WMS_RECOVER, "listener is nullptr");
319         return;
320     }
321 
322     int32_t clientUserId = GetUserIdByCallingUid();
323     if (clientUserId <= INVALID_USER_ID) {
324         TLOGE(WmsLogTag::WMS_RECOVER, "userId is illegal: %{public}d", clientUserId);
325         return;
326     }
327     int32_t pid = IPCSkeleton::GetCallingRealPid();
328     TLOGI(WmsLogTag::WMS_RECOVER, "clientUserId = %{public}d, pid = %{public}d", clientUserId, pid);
329     sptr<ClientListenerDeathRecipient> clientDeathListener = new ClientListenerDeathRecipient(clientUserId, pid, false);
330     listener->AddDeathRecipient(clientDeathListener);
331     sptr<ISessionManagerServiceRecoverListener> smsListener;
332     {
333         std::unique_lock<std::shared_mutex> lock(smsRecoverListenerLock_);
334         smsListener = iface_cast<ISessionManagerServiceRecoverListener>(listener);
335         smsRecoverListenerMap_[clientUserId][pid] = smsListener;
336     }
337     if (clientUserId != SYSTEM_USERID) {
338         return;
339     }
340     bool isWMSConnected = false;
341     {
342         std::lock_guard<std::mutex> lock(wmsConnectionStatusLock_);
343         if (wmsConnectionStatusMap_.find(currentWMSUserId_) != wmsConnectionStatusMap_.end()) {
344             isWMSConnected = wmsConnectionStatusMap_[currentWMSUserId_];
345         }
346     }
347     if (smsListener && isWMSConnected) {
348         auto sessionManagerService = GetSessionManagerServiceByUserId(currentWMSUserId_);
349         if (sessionManagerService == nullptr) {
350             TLOGE(WmsLogTag::WMS_RECOVER, "SessionManagerService is null");
351             return;
352         }
353         TLOGI(WmsLogTag::WMS_RECOVER, "WMS is already connected, notify client");
354         smsListener->OnWMSConnectionChanged(currentWMSUserId_, currentScreenId_, true, sessionManagerService);
355     }
356 }
357 
GetSMSRecoverListenerMap(int32_t userId)358 std::map<int32_t, sptr<ISessionManagerServiceRecoverListener>>* MockSessionManagerService::GetSMSRecoverListenerMap(
359     int32_t userId)
360 {
361     auto iter = smsRecoverListenerMap_.find(userId);
362     if (iter != smsRecoverListenerMap_.end()) {
363         return &iter->second;
364     }
365     return nullptr;
366 }
367 
UnregisterSMSRecoverListener()368 void MockSessionManagerService::UnregisterSMSRecoverListener()
369 {
370     int32_t clientUserId = GetUserIdByCallingUid();
371     if (clientUserId <= INVALID_USER_ID) {
372         TLOGE(WmsLogTag::WMS_RECOVER, "userId is illegal: %{public}d", clientUserId);
373         return;
374     }
375     int32_t pid = IPCSkeleton::GetCallingRealPid();
376     TLOGD(WmsLogTag::WMS_RECOVER, "clientUserId = %{public}d, pid = %{public}d", clientUserId, pid);
377     UnregisterSMSRecoverListener(clientUserId, pid);
378 }
379 
UnregisterSMSRecoverListener(int32_t userId,int32_t pid)380 void MockSessionManagerService::UnregisterSMSRecoverListener(int32_t userId, int32_t pid)
381 {
382     TLOGD(WmsLogTag::WMS_RECOVER, "userId = %{public}d, pid = %{public}d", userId, pid);
383     std::unique_lock<std::shared_mutex> lock(smsRecoverListenerLock_);
384     std::map<int32_t, sptr<ISessionManagerServiceRecoverListener>>* smsRecoverListenerMap =
385         GetSMSRecoverListenerMap(userId);
386     if (!smsRecoverListenerMap) {
387         TLOGW(WmsLogTag::WMS_RECOVER, "smsRecoverListenerMap is null");
388         return;
389     }
390     auto iter = smsRecoverListenerMap->find(pid);
391     if (iter != smsRecoverListenerMap->end()) {
392         smsRecoverListenerMap->erase(iter);
393     }
394 }
395 
NotifySceneBoardAvailableToClient(int32_t userId)396 void MockSessionManagerService::NotifySceneBoardAvailableToClient(int32_t userId)
397 {
398     std::shared_lock<std::shared_mutex> lock(smsRecoverListenerLock_);
399     std::map<int32_t, sptr<ISessionManagerServiceRecoverListener>>* smsRecoverListenerMap =
400         GetSMSRecoverListenerMap(userId);
401     if (!smsRecoverListenerMap) {
402         TLOGW(WmsLogTag::WMS_RECOVER, "smsRecoverListenerMap is null");
403         return;
404     }
405     TLOGI(WmsLogTag::WMS_RECOVER, "userId=%{public}d, Remote process count = %{public}" PRIu64, userId,
406         static_cast<uint64_t>(smsRecoverListenerMap->size()));
407     auto sessionManagerService = GetSessionManagerServiceByUserId(currentWMSUserId_);
408     if (sessionManagerService == nullptr) {
409         TLOGE(WmsLogTag::WMS_RECOVER, "SessionManagerService is null");
410         return;
411     }
412     for (auto& iter : *smsRecoverListenerMap) {
413         if (iter.second != nullptr) {
414             TLOGI(WmsLogTag::WMS_RECOVER, "Call OnSessionManagerServiceRecover pid = %{public}d", iter.first);
415             iter.second->OnSessionManagerServiceRecover(sessionManagerService);
416         }
417     }
418 }
419 
RegisterSMSLiteRecoverListener(const sptr<IRemoteObject> & listener)420 void MockSessionManagerService::RegisterSMSLiteRecoverListener(const sptr<IRemoteObject>& listener)
421 {
422     if (listener == nullptr) {
423         TLOGE(WmsLogTag::WMS_RECOVER, "Lite listener is nullptr");
424         return;
425     }
426     int32_t clientUserId = GetUserIdByCallingUid();
427     if (clientUserId <= INVALID_USER_ID) {
428         TLOGE(WmsLogTag::WMS_RECOVER, "userId is illegal: %{public}d", clientUserId);
429         return;
430     }
431     int32_t pid = IPCSkeleton::GetCallingRealPid();
432     TLOGI(WmsLogTag::WMS_RECOVER, "clientUserId = %{public}d, pid = %{public}d", clientUserId, pid);
433     sptr<ClientListenerDeathRecipient> clientDeathListener = new ClientListenerDeathRecipient(clientUserId, pid, true);
434     listener->AddDeathRecipient(clientDeathListener);
435     sptr<ISessionManagerServiceRecoverListener> smsListener;
436     {
437         std::unique_lock<std::shared_mutex> lock(smsLiteRecoverListenerLock_);
438         smsListener = iface_cast<ISessionManagerServiceRecoverListener>(listener);
439         smsLiteRecoverListenerMap_[clientUserId][pid] = smsListener;
440     }
441     if (clientUserId != SYSTEM_USERID) {
442         return;
443     }
444     bool isWMSConnected = false;
445     {
446         std::lock_guard<std::mutex> lock(wmsConnectionStatusLock_);
447         if (wmsConnectionStatusMap_.find(currentWMSUserId_) != wmsConnectionStatusMap_.end()) {
448             isWMSConnected = wmsConnectionStatusMap_[currentWMSUserId_];
449         }
450     }
451     if (smsListener && isWMSConnected) {
452         auto sessionManagerService = GetSessionManagerServiceByUserId(currentWMSUserId_);
453         if (sessionManagerService == nullptr) {
454             TLOGE(WmsLogTag::WMS_RECOVER, "SessionManagerService is null");
455             return;
456         }
457         TLOGI(WmsLogTag::WMS_MULTI_USER, "Lite wms is already connected, notify client");
458         smsListener->OnWMSConnectionChanged(currentWMSUserId_, currentScreenId_, true, sessionManagerService);
459     }
460 }
461 
GetSMSLiteRecoverListenerMap(int32_t userId)462 std::map<int32_t, sptr<ISessionManagerServiceRecoverListener>>* MockSessionManagerService::GetSMSLiteRecoverListenerMap(
463     int32_t userId)
464 {
465     auto iter = smsLiteRecoverListenerMap_.find(userId);
466     if (iter != smsLiteRecoverListenerMap_.end()) {
467         return &iter->second;
468     }
469     return nullptr;
470 }
471 
UnregisterSMSLiteRecoverListener()472 void MockSessionManagerService::UnregisterSMSLiteRecoverListener()
473 {
474     int32_t clientUserId = GetUserIdByCallingUid();
475     if (clientUserId <= INVALID_USER_ID) {
476         TLOGE(WmsLogTag::WMS_RECOVER, "userId is illegal: %{public}d", clientUserId);
477         return;
478     }
479     int32_t pid = IPCSkeleton::GetCallingRealPid();
480     TLOGD(WmsLogTag::WMS_RECOVER, "clientUserId = %{public}d, pid = %{public}d", clientUserId, pid);
481     UnregisterSMSLiteRecoverListener(clientUserId, pid);
482 }
483 
UnregisterSMSLiteRecoverListener(int32_t userId,int32_t pid)484 void MockSessionManagerService::UnregisterSMSLiteRecoverListener(int32_t userId, int32_t pid)
485 {
486     TLOGD(WmsLogTag::WMS_RECOVER, "userId = %{public}d, pid = %{public}d", userId, pid);
487     std::unique_lock<std::shared_mutex> lock(smsLiteRecoverListenerLock_);
488     std::map<int32_t, sptr<ISessionManagerServiceRecoverListener>>* smsLiteRecoverListenerMap =
489         GetSMSLiteRecoverListenerMap(userId);
490     if (!smsLiteRecoverListenerMap) {
491         return;
492     }
493     auto iter = smsLiteRecoverListenerMap->find(pid);
494     if (iter != smsLiteRecoverListenerMap->end()) {
495         smsLiteRecoverListenerMap->erase(iter);
496     }
497 }
498 
NotifySceneBoardAvailableToLiteClient(int32_t userId)499 void MockSessionManagerService::NotifySceneBoardAvailableToLiteClient(int32_t userId)
500 {
501     std::shared_lock<std::shared_mutex> lock(smsLiteRecoverListenerLock_);
502     std::map<int32_t, sptr<ISessionManagerServiceRecoverListener>>* smsLiteRecoverListenerMap =
503         GetSMSLiteRecoverListenerMap(userId);
504     if (!smsLiteRecoverListenerMap) {
505         return;
506     }
507     TLOGI(WmsLogTag::WMS_RECOVER, "userId=%{public}d, Remote process count = %{public}" PRIu64, userId,
508         static_cast<uint64_t>(smsLiteRecoverListenerMap->size()));
509     auto sessionManagerService = GetSessionManagerServiceByUserId(currentWMSUserId_);
510     if (sessionManagerService == nullptr) {
511         TLOGE(WmsLogTag::WMS_RECOVER, "SessionManagerService is null");
512         return;
513     }
514     for (auto& iter : *smsLiteRecoverListenerMap) {
515         if (iter.second != nullptr) {
516             TLOGI(WmsLogTag::WMS_RECOVER,
517                 "Call OnSessionManagerServiceRecover Lite pid = %{public}d, ref count = %{public}" PRId32, iter.first,
518                 iter.second->GetSptrRefCount());
519             iter.second->OnSessionManagerServiceRecover(sessionManagerService);
520         }
521     }
522 }
523 
NotifyWMSConnected(int32_t userId,int32_t screenId,bool isColdStart)524 void MockSessionManagerService::NotifyWMSConnected(int32_t userId, int32_t screenId, bool isColdStart)
525 {
526     TLOGI(WmsLogTag::WMS_MULTI_USER, "userId = %{public}d, screenId = %{public}d, isColdStart = %{public}d", userId,
527         screenId, isColdStart);
528     currentScreenId_ = screenId;
529     currentWMSUserId_ = userId;
530     auto smsDeathRecipient = GetSMSDeathRecipientByUserId(currentWMSUserId_);
531     if (smsDeathRecipient != nullptr) {
532         smsDeathRecipient->SetScreenId(screenId);
533     }
534     if (!isColdStart) {
535         TLOGI(WmsLogTag::WMS_MULTI_USER, "User switched");
536         GetSceneSessionManager();
537     }
538     NotifyWMSConnectionChanged(userId, screenId, true);
539 }
540 
NotifyWMSConnectionChanged(int32_t wmsUserId,int32_t screenId,bool isConnected)541 void MockSessionManagerService::NotifyWMSConnectionChanged(int32_t wmsUserId, int32_t screenId, bool isConnected)
542 {
543     TLOGI(WmsLogTag::WMS_MULTI_USER, "wmsUserId = %{public}d, isConnected = %{public}d", wmsUserId, isConnected);
544     {
545         std::lock_guard<std::mutex> lock(wmsConnectionStatusLock_);
546         wmsConnectionStatusMap_[wmsUserId] = isConnected;
547     }
548     NotifyWMSConnectionChangedToLiteClient(wmsUserId, screenId, isConnected);
549     NotifyWMSConnectionChangedToClient(wmsUserId, screenId, isConnected);
550 }
551 
NotifyWMSConnectionChangedToClient(int32_t wmsUserId,int32_t screenId,bool isConnected)552 void MockSessionManagerService::NotifyWMSConnectionChangedToClient(
553     int32_t wmsUserId, int32_t screenId, bool isConnected)
554 {
555     std::shared_lock<std::shared_mutex> lock(smsRecoverListenerLock_);
556     std::map<int32_t, sptr<ISessionManagerServiceRecoverListener>>* smsRecoverListenerMap =
557         GetSMSRecoverListenerMap(SYSTEM_USERID);
558     if (!smsRecoverListenerMap) {
559         TLOGW(WmsLogTag::WMS_MULTI_USER, "smsRecoverListenerMap is null");
560         return;
561     }
562     TLOGD(WmsLogTag::WMS_MULTI_USER,
563         "wmsUserId = %{public}d, isConnected = %{public}d, remote process count = "
564         "%{public}" PRIu64,
565         wmsUserId, isConnected, static_cast<uint64_t>(smsRecoverListenerMap->size()));
566     auto sessionManagerService = GetSessionManagerServiceByUserId(currentWMSUserId_);
567     if (sessionManagerService == nullptr) {
568         TLOGE(WmsLogTag::WMS_RECOVER, "SessionManagerService is null");
569         return;
570     }
571     for (auto& iter : *smsRecoverListenerMap) {
572         if (iter.second != nullptr) {
573             TLOGI(WmsLogTag::WMS_MULTI_USER, "Call OnWMSConnectionChanged pid = %{public}d", iter.first);
574             iter.second->OnWMSConnectionChanged(wmsUserId, screenId, isConnected, sessionManagerService);
575         }
576     }
577 }
578 
NotifyWMSConnectionChangedToLiteClient(int32_t wmsUserId,int32_t screenId,bool isConnected)579 void MockSessionManagerService::NotifyWMSConnectionChangedToLiteClient(
580     int32_t wmsUserId, int32_t screenId, bool isConnected)
581 {
582     std::shared_lock<std::shared_mutex> lock(smsLiteRecoverListenerLock_);
583     std::map<int32_t, sptr<ISessionManagerServiceRecoverListener>>* smsLiteRecoverListenerMap =
584         GetSMSLiteRecoverListenerMap(SYSTEM_USERID);
585     if (!smsLiteRecoverListenerMap) {
586         return;
587     }
588     TLOGD(WmsLogTag::WMS_MULTI_USER, "wmsUserId = %{public}d, isConnected = %{public}d", wmsUserId, isConnected);
589     auto sessionManagerService = GetSessionManagerServiceByUserId(currentWMSUserId_);
590     if (sessionManagerService == nullptr) {
591         TLOGE(WmsLogTag::WMS_RECOVER, "SessionManagerService is null");
592         return;
593     }
594     for (auto& iter : *smsLiteRecoverListenerMap) {
595         if (iter.second != nullptr) {
596             TLOGI(WmsLogTag::WMS_MULTI_USER,
597                 "Call OnWMSConnectionChanged Lite pid = %{public}d, ref count = %{public}d", iter.first,
598                 iter.second->GetSptrRefCount());
599             iter.second->OnWMSConnectionChanged(wmsUserId, screenId, isConnected, sessionManagerService);
600         }
601     }
602 }
603 
GetScreenSessionManagerLite()604 sptr<IRemoteObject> MockSessionManagerService::GetScreenSessionManagerLite()
605 {
606     if (screenSessionManager_) {
607         return screenSessionManager_;
608     }
609     screenSessionManager_ = ScreenSessionManagerLite::GetInstance().AsObject();
610     return screenSessionManager_;
611 }
612 
ShowIllegalArgsInfo(std::string & dumpInfo)613 void MockSessionManagerService::ShowIllegalArgsInfo(std::string& dumpInfo)
614 {
615     dumpInfo.append("The arguments are illegal and you can enter '-h' for help.");
616 }
617 
GetSceneSessionManager()618 sptr<IRemoteObject> MockSessionManagerService::GetSceneSessionManager()
619 {
620     auto sessionManagerService = GetSessionManagerServiceByUserId(currentWMSUserId_);
621     if (sessionManagerService == nullptr) {
622         WLOGFE("SessionManagerService is null");
623         return nullptr;
624     }
625     sptr<ISessionManagerService> sessionManagerServiceProxy = iface_cast<ISessionManagerService>(sessionManagerService);
626     if (!sessionManagerServiceProxy) {
627         WLOGFE("sessionManagerServiceProxy is nullptr");
628         return nullptr;
629     }
630     sptr<IRemoteObject> remoteObject = sessionManagerServiceProxy->GetSceneSessionManager();
631     if (!remoteObject) {
632         WLOGFW("Get scene session manager proxy failed, scene session manager service is null");
633         return sptr<IRemoteObject>(nullptr);
634     }
635     sceneSessionManager_ = remoteObject;
636     return sceneSessionManager_;
637 }
638 
DumpSessionInfo(const std::vector<std::string> & args,std::string & dumpInfo)639 int MockSessionManagerService::DumpSessionInfo(const std::vector<std::string>& args, std::string& dumpInfo)
640 {
641     if (args.empty()) {
642         return -1;  // WMError::WM_ERROR_INVALID_PARAM;
643     }
644     auto sessionManagerService = GetSessionManagerServiceByUserId(currentWMSUserId_);
645     if (sessionManagerService == nullptr) {
646         WLOGFE("sessionManagerService is nullptr");
647         return -1;
648     }
649     if (!sceneSessionManager_) {
650         WLOGFW("Get scene session manager ...");
651         GetSceneSessionManager();
652         if (!sceneSessionManager_) {
653             WLOGFW("Get scene session manager proxy failed, nullptr");
654             return -1;
655         }
656     }
657     sptr<ISceneSessionManager> sceneSessionManagerProxy = iface_cast<ISceneSessionManager>(sceneSessionManager_);
658     WSError ret = sceneSessionManagerProxy->GetSessionDumpInfo(args, dumpInfo);
659     if (ret != WSError::WS_OK) {
660         WLOGFD("sessionManagerService set success!");
661         return -1;
662     }
663     return 0; // WMError::WM_OK;
664 }
665 
ShowHelpInfo(std::string & dumpInfo)666 void MockSessionManagerService::ShowHelpInfo(std::string& dumpInfo)
667 {
668     dumpInfo.append("Usage:\n")
669         .append(" -h                             ")
670         .append("|help text for the tool\n")
671         .append(" -a                             ")
672         .append("|dump all window information in the system\n")
673         .append(" -w {window id} [ArkUI Option]  ")
674         .append("|dump specified window information\n")
675         .append(" ------------------------------------[ArkUI Option]------------------------------------ \n");
676     ShowAceDumpHelp(dumpInfo);
677 }
678 
ShowAceDumpHelp(std::string & dumpInfo)679 void MockSessionManagerService::ShowAceDumpHelp(std::string& dumpInfo)
680 {
681 }
682 
IsSceneBoardTestMode()683 bool MockSessionManagerService::SMSDeathRecipient::IsSceneBoardTestMode()
684 {
685     if (!OHOS::system::GetBoolParameter(KEY_SCENE_BOARD_TEST_ENABLE, false)) {
686         WLOGFD("SceneBoard testmode is disabled.");
687         return false;
688     }
689     auto systemAbilityMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
690     if (systemAbilityMgr == nullptr) {
691         WLOGFE("Failed to get SystemAbilityManager.");
692         return false;
693     }
694 
695     auto bmsObj = systemAbilityMgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
696     if (bmsObj == nullptr) {
697         WLOGFE("Failed to get BundleManagerService.");
698         return false;
699     }
700     sptr<AppExecFwk::IBundleMgr> bundleMgr_ = iface_cast<AppExecFwk::IBundleMgr>(bmsObj);
701     AppExecFwk::BundleInfo bundleInfo;
702     int uid = IPCSkeleton::GetCallingUid();
703     int userId = uid / 200000;
704     bool result = bundleMgr_->GetBundleInfo(SCENE_BOARD_BUNDLE_NAME,
705         AppExecFwk::BundleFlag::GET_BUNDLE_WITH_EXTENSION_INFO, bundleInfo, userId);
706     if (!result) {
707         WLOGFE("Failed to query bundleInfo, userId:%{public}d", userId);
708         return true;
709     }
710     auto hapModulesList = bundleInfo.hapModuleInfos;
711     if (hapModulesList.empty()) {
712         WLOGFE("hapModulesList is empty");
713         return false;
714     }
715     std::string suffix = TEST_MODULE_NAME_SUFFIX;
716     for (auto hapModule: hapModulesList) {
717         std::string moduleName = hapModule.moduleName;
718         if (moduleName.length() < suffix.length()) {
719             continue;
720         }
721         if (moduleName.compare(moduleName.length() - suffix.length(), suffix.length(), suffix) == 0) {
722             WLOGFI("Found test module name: %{public}s", moduleName.c_str());
723             return true;
724         }
725     }
726     return false;
727 }
728 
WriteStringToFile(int32_t pid,const char * str)729 void MockSessionManagerService::WriteStringToFile(int32_t pid, const char* str)
730 {
731     char file[PATH_LEN] = {0};
732     if (snprintf_s(file, PATH_LEN, PATH_LEN - 1, "/proc/%d/unexpected_die_catch", pid) == -1) {
733         WLOGFI("failed to build path for %d.", pid);
734     }
735     int fd = open(file, O_RDWR);
736     if (fd == -1) {
737         return;
738     }
739     if (write(fd, str, strlen(str)) < 0) {
740         WLOGFI("failed to write 0 for %s", file);
741         close(fd);
742         return;
743     }
744     close(fd);
745 }
746 
GetProcessSurfaceNodeIdByPersistentId(const int32_t pid,const std::vector<uint64_t> & windowIdList,std::vector<uint64_t> & surfaceNodeIds)747 void MockSessionManagerService::GetProcessSurfaceNodeIdByPersistentId(const int32_t pid,
748     const std::vector<uint64_t>& windowIdList, std::vector<uint64_t>& surfaceNodeIds)
749 {
750     auto sessionManagerService = GetSessionManagerServiceByUserId(currentWMSUserId_);
751     if (sessionManagerService == nullptr) {
752         WLOGFE("sessionManagerService is nullptr");
753         return;
754     }
755     if (!sceneSessionManager_) {
756         WLOGFW("Get scene session manager ...");
757         GetSceneSessionManager();
758         if (!sceneSessionManager_) {
759             WLOGFW("Get scene session manager proxy failed, nullptr");
760             return;
761         }
762     }
763     if (windowIdList.empty()) {
764         TLOGE(WmsLogTag::DEFAULT, "windowIdList is null, no need to get surfaceNodeId");
765         return;
766     }
767     std::vector<int32_t> persistentIds(windowIdList.size());
768     std::transform(windowIdList.begin(), windowIdList.end(),
769         persistentIds.begin(), [](uint64_t id) { return static_cast<int32_t>(id); });
770     sptr<ISceneSessionManager> sceneSessionManagerProxy = iface_cast<ISceneSessionManager>(sceneSessionManager_);
771     WMError ret = sceneSessionManagerProxy->GetProcessSurfaceNodeIdByPersistentId(
772         pid, persistentIds, surfaceNodeIds);
773     if (ret != WMError::WM_OK) {
774         TLOGE(WmsLogTag::DEFAULT, "Get process surfaceNodeId by persistentId failed!");
775     }
776 }
777 } // namespace Rosen
778 } // namespace OHOS