1 /*
2 * Copyright (c) 2022 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 "accesstoken_klog.h"
17 #include <cstdio>
18 #include <fcntl.h>
19 #include <unistd.h>
20 #include "securec.h"
21
22 #define MAX_LOG_SIZE 1024
23 #define MAX_LEVEL_SIZE 3
24
25 static const char* g_logLevelStr[] = {"ERROR", "WARNING", "INFO"};
26
27 #ifndef UNLIKELY
28 #define UNLIKELY(x) __builtin_expect(!!(x), 0)
29 #endif
30
31 static int g_fd = -1;
32 const uint64_t g_nativeKmsgFdTag = 0xD005A01;
33
NativeTokenOpenLogDevice(void)34 static void NativeTokenOpenLogDevice(void)
35 {
36 int fd = open("/dev/kmsg", O_WRONLY | O_CLOEXEC);
37 if (fd >= 0) {
38 g_fd = fd;
39 }
40 fdsan_exchange_owner_tag(g_fd, 0, g_nativeKmsgFdTag);
41 return;
42 }
43
NativeTokenKmsg(int logLevel,const char * fmt,...)44 int NativeTokenKmsg(int logLevel, const char* fmt, ...)
45 {
46 if ((logLevel < 0) || (logLevel >= MAX_LEVEL_SIZE)) {
47 return -1;
48 }
49 if (UNLIKELY(g_fd < 0)) {
50 NativeTokenOpenLogDevice();
51 if (g_fd < 0) {
52 return -1;
53 }
54 }
55 va_list vargs;
56 va_start(vargs, fmt);
57 char tmpFmt[MAX_LOG_SIZE];
58 if (vsnprintf_s(tmpFmt, MAX_LOG_SIZE, MAX_LOG_SIZE - 1, fmt, vargs) == -1) {
59 (void)fdsan_close_with_tag(g_fd, g_nativeKmsgFdTag);
60 g_fd = -1;
61 va_end(vargs);
62 return -1;
63 }
64
65 char logInfo[MAX_LOG_SIZE];
66 int res = snprintf_s(logInfo, MAX_LOG_SIZE, MAX_LOG_SIZE - 1, "[pid=%d][%s][%s] %s",
67 getpid(), "access_token", g_logLevelStr[logLevel], tmpFmt);
68 if (res == -1) {
69 (void)fdsan_close_with_tag(g_fd, g_nativeKmsgFdTag);
70 g_fd = -1;
71 va_end(vargs);
72 return -1;
73 }
74 va_end(vargs);
75
76 if (write(g_fd, logInfo, strlen(logInfo)) < 0) {
77 (void)fdsan_close_with_tag(g_fd, g_nativeKmsgFdTag);
78 g_fd = -1;
79 }
80 return 0;
81 }
82