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 #ifdef OHOS_STANDARD_SYSTEM
17 #include "faultloggerd_client.h"
18 #endif
19 #include <cstring>
20 #include <iostream>
21 #include <fstream>
22 #include <sstream>
23 #include <atomic>
24 #include "ffrt_log_api.h"
25 #include "internal_inc/osal.h"
26 static int g_ffrtLogLevel = FFRT_LOG_DEBUG;
27 static std::atomic<unsigned int> g_ffrtLogId(0);
28 static bool g_whiteListFlag = false;
29 namespace {
30     constexpr int PROCESS_NAME_BUFFER_LENGTH = 1024;
31     constexpr char CONF_FILEPATH[] = "/etc/ffrt/log_ctr_whitelist.conf";
32 }
33 
GetLogId(void)34 unsigned int GetLogId(void)
35 {
36     return ++g_ffrtLogId;
37 }
38 
IsInWhitelist(void)39 bool IsInWhitelist(void)
40 {
41     return g_whiteListFlag;
42 }
43 
GetFFRTLogLevel(void)44 int GetFFRTLogLevel(void)
45 {
46     return g_ffrtLogLevel;
47 }
48 
SetLogLevel(void)49 static void SetLogLevel(void)
50 {
51     std::string envLogStr = GetEnv("FFRT_LOG_LEVEL");
52     if (envLogStr.size() != 0) {
53         int level = std::stoi(envLogStr);
54         if (level < FFRT_LOG_LEVEL_MAX && level >= FFRT_LOG_ERROR) {
55             g_ffrtLogLevel = level;
56             return;
57         }
58     }
59 }
60 
InitWhiteListFlag(void)61 void InitWhiteListFlag(void)
62 {
63     // 获取当前进程名称
64     char processName[PROCESS_NAME_BUFFER_LENGTH] = "";
65     GetProcessName(processName, PROCESS_NAME_BUFFER_LENGTH);
66     if (strlen(processName) == 0) {
67             g_whiteListFlag = true;
68             return;
69     }
70 
71     // 从配置文件读取白名单比对
72     std::string whiteProcess;
73     std::ifstream file(CONF_FILEPATH);
74     if (file.is_open()) {
75         while (std::getline(file, whiteProcess)) {
76             if (strstr(processName, whiteProcess.c_str()) != nullptr) {
77                 g_whiteListFlag = true;
78                 return;
79             }
80         }
81     } else {
82         // 当文件不存在或者无权限时默认都开
83         g_whiteListFlag = true;
84     }
85 }
86 
LogInit(void)87 static __attribute__((constructor)) void LogInit(void)
88 {
89     SetLogLevel();
90     InitWhiteListFlag();
91 }