blob: a72906b4ec9f8755db39cb3b03213c6c14681b3e [file] [log] [blame]
Elliott Hughesda40c002015-03-27 23:20:44 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Elliott Hughese5ce30f2015-05-06 19:19:24 -070017#include "log.h"
18
Elliott Hughesda40c002015-03-27 23:20:44 -070019#include <stdlib.h>
20#include <string.h>
21#include <sys/uio.h>
22
23#include <selinux/selinux.h>
24
Elliott Hughes4f713192015-12-04 22:00:26 -080025#include <android-base/stringprintf.h>
Elliott Hughesda40c002015-03-27 23:20:44 -070026
27static void init_klog_vwrite(int level, const char* fmt, va_list ap) {
28 static const char* tag = basename(getprogname());
29
Elliott Hughese5ce30f2015-05-06 19:19:24 -070030 // The kernel's printk buffer is only 1024 bytes.
31 // TODO: should we automatically break up long lines into multiple lines?
32 // Or we could log but with something like "..." at the end?
33 char buf[1024];
34 size_t prefix_size = snprintf(buf, sizeof(buf), "<%d>%s: ", level, tag);
35 size_t msg_size = vsnprintf(buf + prefix_size, sizeof(buf) - prefix_size, fmt, ap);
36 if (msg_size >= sizeof(buf) - prefix_size) {
37 msg_size = snprintf(buf + prefix_size, sizeof(buf) - prefix_size,
38 "(%zu-byte message too long for printk)\n", msg_size);
39 }
Elliott Hughesda40c002015-03-27 23:20:44 -070040
Elliott Hughese5ce30f2015-05-06 19:19:24 -070041 iovec iov[1];
42 iov[0].iov_base = buf;
43 iov[0].iov_len = prefix_size + msg_size;
Elliott Hughesda40c002015-03-27 23:20:44 -070044
Elliott Hughese5ce30f2015-05-06 19:19:24 -070045 klog_writev(level, iov, 1);
Elliott Hughesda40c002015-03-27 23:20:44 -070046}
47
48void init_klog_write(int level, const char* fmt, ...) {
49 va_list ap;
50 va_start(ap, fmt);
51 init_klog_vwrite(level, fmt, ap);
52 va_end(ap);
53}
54
55int selinux_klog_callback(int type, const char *fmt, ...) {
56 int level = KLOG_ERROR_LEVEL;
57 if (type == SELINUX_WARNING) {
58 level = KLOG_WARNING_LEVEL;
59 } else if (type == SELINUX_INFO) {
60 level = KLOG_INFO_LEVEL;
61 }
62 va_list ap;
63 va_start(ap, fmt);
64 init_klog_vwrite(level, fmt, ap);
65 va_end(ap);
66 return 0;
67}