1 /*
2  * Copyright (c) 2021-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 "klog.h"
17 
18 #include <cerrno>
19 #include <cstdarg>
20 #include <cstdio>
21 #include <cstdlib>
22 #include <cstring>
23 #include <ctime>
24 
25 #include <fcntl.h>
26 #include <pthread.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <sys/wait.h>
30 #include <unistd.h>
31 
32 #include "hilog/log.h"
33 #include "securec.h"
34 
35 namespace OHOS {
36 namespace MMI {
37 #define UNUSED(x) \
38     do { \
39         (void)(x) \
40     } while (0)
41 
42 #define UNLIKELY(x)    __builtin_expect(!!(x), 0)
43 
44 static int g_fd = -1;
45 
46 constexpr int32_t MAX_LOG_SIZE = 1024;
47 
KLogOpenLogDevice(void)48 void KLogOpenLogDevice(void)
49 {
50 #ifdef _CLOEXEC_
51     int fd = open("/dev/kmsg", O_WRONLY | O_CLOEXEC, S_IRUSR | S_IWUSR | S_IRGRP | S_IRGRP);
52 #else
53     int fd = open("/dev/kmsg", O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IRGRP);
54 #endif
55     if (fd >= 0) {
56         g_fd = fd;
57     }
58     return;
59 }
60 
kMsgLog(const char * fileName,int line,const char * kLevel,const char * fmt,...)61 void kMsgLog(const char* fileName, int line, const char* kLevel,
62     const char* fmt, ...)
63 {
64     if (UNLIKELY(g_fd < 0)) {
65         KLogOpenLogDevice();
66         if (g_fd < 0) {
67             return;
68         }
69     }
70     va_list vargs;
71     va_start(vargs, fmt);
72     char tmpFmt[MAX_LOG_SIZE];
73     if (vsnprintf_s(tmpFmt, MAX_LOG_SIZE, MAX_LOG_SIZE - 1, fmt, vargs) == -1) {
74         va_end(vargs);
75         close(g_fd);
76         g_fd = -1;
77         return;
78     }
79 
80     char logInfo[MAX_LOG_SIZE];
81     if (snprintf_s(logInfo, MAX_LOG_SIZE, MAX_LOG_SIZE - 1,
82         "%s[dm=%08X][pid=%d][%s:%d][%s][%s] %s",
83         kLevel, 0x0D002800, getpid(), fileName, line, "klog", "info", tmpFmt) == -1) {
84         va_end(vargs);
85         close(g_fd);
86         g_fd = -1;
87         return;
88     }
89     va_end(vargs);
90 
91     if (write(g_fd, logInfo, strlen(logInfo)) < 0) {
92         close(g_fd);
93         g_fd = -1;
94     }
95     return;
96 }
97 } // namespace MMI
98 } // namespace OHOS
99