• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-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 "sandbox_utils.h"
17 #include <cstdlib>
18 #include <cstring>
19 
20 #ifdef _WIN32
21 #include <windows.h>
22 #endif
23 
24 namespace OHOS {
25 #if !defined(OHOS_LITE) && !defined(_WIN32) && !defined(__APPLE__) && !defined(__gnu_linux__)
26 static pid_t g_appSandboxPid_ = -1;
27 
28 const int PID_STR_SIZE = 5;
29 const int STATUS_LINE_SIZE = 1024;
30 const int PID_MAX_LEN = 11;
31 
FindAndConvertPid(char * buf,int len)32 static int FindAndConvertPid(char *buf, int len)
33 {
34     int count = 0;
35     char pidBuf[PID_MAX_LEN] = {0};
36     char *str = buf;
37 
38     if (len <= PID_STR_SIZE) {
39         return -1;
40     }
41 
42     while (*str != '\0') {
43         if ((*str >= '0') && (*str <= '9') && (count < PID_MAX_LEN)) {
44             pidBuf[count] = *str;
45             count++;
46             str++;
47             continue;
48         }
49 
50         if (count > 0) {
51             break;
52         }
53         str++;
54     }
55     return atoi(pidBuf);
56 }
57 
ParseRealPid(void)58 static pid_t ParseRealPid(void)
59 {
60     const char *path = "/proc/self/status";
61     char buf[STATUS_LINE_SIZE] = {0};
62     FILE *fp = fopen(path, "r");
63     if (fp == nullptr) {
64         return -1;
65     }
66 
67     while (!feof(fp)) {
68         if (fgets(buf, STATUS_LINE_SIZE, fp) == nullptr) {
69             fclose(fp);
70             return -1;
71         }
72         if (strncmp(buf, "Tgid:", PID_STR_SIZE) == 0) {
73             break;
74         }
75     }
76     (void)fclose(fp);
77 
78     return static_cast<pid_t>(FindAndConvertPid(buf, strlen(buf)));
79 }
80 #endif
81 
GetRealPid(void)82 pid_t GetRealPid(void)
83 {
84 #ifdef _WIN32
85     return GetCurrentProcessId();
86 #elif defined(OHOS_LITE) || defined(__APPLE__) || defined(__gnu_linux__)
87     return getpid();
88 #else
89     if (g_appSandboxPid_ < 0) {
90         g_appSandboxPid_ = ParseRealPid();
91     }
92     return g_appSandboxPid_;
93 #endif
94 }
95 } // namespace OHOS
96