1 /* 2 * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved. 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 "test_common.h" 17 #include "token_setproc.h" 18 #include "accesstoken_kit.h" 19 #include <string> 20 #include <iostream> 21 #include <mutex> 22 #include <sstream> 23 using namespace OHOS::Security::AccessToken; 24 25 namespace TEST_COMMON { 26 std::mutex g_lockSetToken; 27 uint64_t g_shellTokenId = 0; 28 GetShellTokenId()29uint64_t GetShellTokenId() 30 { 31 std::lock_guard<std::mutex> lock(g_lockSetToken); 32 return g_shellTokenId; 33 } 34 SetTestEvironment(uint64_t shellTokenId)35void SetTestEvironment(uint64_t shellTokenId) 36 { 37 std::lock_guard<std::mutex> lock(g_lockSetToken); 38 g_shellTokenId = shellTokenId; 39 } 40 ResetTestEvironment()41void ResetTestEvironment() 42 { 43 std::lock_guard<std::mutex> lock(g_lockSetToken); 44 g_shellTokenId = 0; 45 } 46 GetNativeTokenIdFromProcess(const std::string & process)47static AccessTokenID GetNativeTokenIdFromProcess(const std::string &process) 48 { 49 uint64_t selfTokenId = GetSelfTokenID(); 50 if (SetSelfTokenID(GetShellTokenId()) != 0) { 51 return 0; 52 } 53 54 std::string dumpInfo; 55 AtmToolsParamInfo info; 56 info.processName = process; 57 AccessTokenKit::DumpTokenInfo(info, dumpInfo); 58 size_t pos = dumpInfo.find("\"tokenID\": "); 59 if (pos == std::string::npos) { 60 return 0; 61 } 62 pos += std::string("\"tokenID\": ").length(); 63 std::string numStr; 64 while (pos < dumpInfo.length() && std::isdigit(dumpInfo[pos])) { 65 numStr += dumpInfo[pos]; 66 ++pos; 67 } 68 // restore 69 if (SetSelfTokenID(selfTokenId) != 0) { 70 return 0; 71 } 72 73 std::istringstream iss(numStr); 74 AccessTokenID tokenID; 75 iss >> tokenID; 76 return tokenID; 77 } 78 MockNativeToken(const std::string & process)79MockNativeToken::MockNativeToken(const std::string& process) 80 { 81 selfToken_ = GetSelfTokenID(); 82 uint32_t tokenId = GetNativeTokenIdFromProcess(process); 83 SetSelfTokenID(tokenId); 84 } 85 ~MockNativeToken()86MockNativeToken::~MockNativeToken() 87 { 88 SetSelfTokenID(selfToken_); 89 } 90 }