blob: ace9fd710c4c970074b81634e9ada8bfafc08317 [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
Nick Kralevich5db8d6a2016-01-16 16:19:17 -080030 if (level > klog_get_level()) return;
31
Elliott Hughese5ce30f2015-05-06 19:19:24 -070032 // The kernel's printk buffer is only 1024 bytes.
33 // TODO: should we automatically break up long lines into multiple lines?
34 // Or we could log but with something like "..." at the end?
35 char buf[1024];
36 size_t prefix_size = snprintf(buf, sizeof(buf), "<%d>%s: ", level, tag);
37 size_t msg_size = vsnprintf(buf + prefix_size, sizeof(buf) - prefix_size, fmt, ap);
38 if (msg_size >= sizeof(buf) - prefix_size) {
39 msg_size = snprintf(buf + prefix_size, sizeof(buf) - prefix_size,
40 "(%zu-byte message too long for printk)\n", msg_size);
41 }
Elliott Hughesda40c002015-03-27 23:20:44 -070042
Elliott Hughese5ce30f2015-05-06 19:19:24 -070043 iovec iov[1];
44 iov[0].iov_base = buf;
45 iov[0].iov_len = prefix_size + msg_size;
Elliott Hughesda40c002015-03-27 23:20:44 -070046
Elliott Hughese5ce30f2015-05-06 19:19:24 -070047 klog_writev(level, iov, 1);
Elliott Hughesda40c002015-03-27 23:20:44 -070048}
49
50void init_klog_write(int level, const char* fmt, ...) {
51 va_list ap;
52 va_start(ap, fmt);
53 init_klog_vwrite(level, fmt, ap);
54 va_end(ap);
55}
56
57int selinux_klog_callback(int type, const char *fmt, ...) {
58 int level = KLOG_ERROR_LEVEL;
59 if (type == SELINUX_WARNING) {
60 level = KLOG_WARNING_LEVEL;
61 } else if (type == SELINUX_INFO) {
62 level = KLOG_INFO_LEVEL;
63 }
64 va_list ap;
65 va_start(ap, fmt);
66 init_klog_vwrite(level, fmt, ap);
67 va_end(ap);
68 return 0;
69}