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