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