Home | History | Annotate | Download | only in init
      1 /*
      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 
     17 #include "log.h"
     18 
     19 #include <stdlib.h>
     20 #include <string.h>
     21 #include <sys/uio.h>
     22 
     23 #include <selinux/selinux.h>
     24 
     25 #include <android-base/stringprintf.h>
     26 
     27 static void init_klog_vwrite(int level, const char* fmt, va_list ap) {
     28     static const char* tag = basename(getprogname());
     29 
     30     if (level > klog_get_level()) return;
     31 
     32     // 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     }
     42 
     43     iovec iov[1];
     44     iov[0].iov_base = buf;
     45     iov[0].iov_len = prefix_size + msg_size;
     46 
     47     klog_writev(level, iov, 1);
     48 }
     49 
     50 void 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 
     57 int 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 }
     70