如何动态的把kernel config配置编译到kernel中

有了前面一篇博客的基础,《如何在把主机及版本信息编译进内核中?》现在我们可以进阶一下,任务是如何把kernel的config配置编译到内核中,这样在每个运行中的kernel环境,我们都可以查看它配置了哪些功能。

我们把实现代码放置于kernel-4.4/fs/proc/info/目录中,共有三个文件:Makefile/config_info.c/mkconfiginfo

其中mkconfiginfo是用来生成config_info.h的一个shell脚本。

话不多说,直接上代码:

##Makefile:

#Delete obj file first
#OBJFILE=$(objtree)/fs/proc/info/config_info.o
#$(shell rm $(OBJFILE) -f)
#FORCE will make sure this obj be compiled every time
obj-y += config_info.o
$(obj)/config_info.o: FORCE fs/proc/info/config_info.h
fs/proc/info/config_info.h: FORCE
    $(Q)$(CONFIG_SHELL) fs/proc/info/mkconfiginfo $(objtree) $@

注意这里的FORCE,这是kbuild中的一个伪目标,主要目的就是确保每次编译都强制重现编译config_info.c和config_info.h这两个文件。为什么呢?

因为每次编译我们可能都会修改到对应的kernel config配置,所以要确保每次编译都重新刷新一下其中的内容,保证内容是最新的。

##mkconfiginfo:
用来根据kernel .config配置文件生成对应的config_info.h头文件

 #!/bin/bash
 
 #THIS MAYBE KBUILD_OUTPUT
 ROOTDIR=$1
 TARGET=$2
 
 CONFIG=${ROOTDIR}/.config
 NUM=`cat $CONFIG | grep CONFIG | grep -v '\#' | wc -l`
 echo $NUM
 
 cat $CONFIG | grep CONFIG | grep -v '\#' > ${TARGET}
 sed -i 's/\"/\\\"/g' ${TARGET}
 sed -i 's/^/\t\"&/g' ${TARGET}
 sed -i 's/$/&\",/g' ${TARGET}
 sed -i '1i\static char *config[] = {'  ${TARGET}
 sed -i '$a\};' ${TARGET}

##config_info.c:
用来创建对应的proc节点

#include <linux/fs.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <asm/uaccess.h>
#include "config_info.h"
static int config_info_proc_show(struct seq_file *m, void *v)
{
    int num = ARRAY_SIZE(config);
    int i;
    for (i = 0; i < num; i++)
        seq_printf(m, "%s\n", config[i]);
    return 0;
}
static int config_info_proc_open(struct inode *inode, struct file *file)
{
    return single_open(file, config_info_proc_show, NULL);
}
static const struct file_operations config_info_proc_fops = {
    .open       = config_info_proc_open,
    .read       = seq_read,
    .llseek     = seq_lseek,
    .release    = single_release,
};
static int __init proc_config_info_init(void)
{
    proc_create("config_info", 0, NULL, &config_info_proc_fops);
    return 0;
}
fs_initcall(proc_config_info_init);

完整的项目代码已经传到github,可以作为大家的参考:https://github.com/rikeyone/proc_config_info

发布了236 篇原创文章 · 获赞 78 · 访问量 24万+

猜你喜欢

转载自blog.csdn.net/rikeyone/article/details/80083517
今日推荐