zoukankan      html  css  js  c++  java
  • linux内核模块Makefile的解析

    Linux内核是一种单体内核,但是通过动态加载模块的方式,使它的开发非常灵活 方便。那么,它是如何编译内核的呢?我们可以通过分析它的Makefile入手。以下是 一个简单的hello内核模块的Makefile. 

    ifneq ($(KERNELRELEASE),)
    obj-m:=hello.o
    else
    KERNELDIR:=/lib/modules/$(shell uname -r)/build
    PWD:=$(shell pwd)
    default:
            $(MAKE) -C $(KERNELDIR)  M=$(PWD) modules
    clean:
            rm -rf *.o *.mod.c *.mod.o *.ko
    endif

    当我们写完一个hello模块,只要使用以上的makefile。然后make一下就行。

    假设我们把hello模块的源代码放在/home/study/prog/mod/hello/下。

    当我们在这个目录运行make时,make是怎么执行的呢?

     LDD3第二章第四节“编译和装载”中只是简略地说到该Makefile被执行了两次,但是具体过程是如何的呢?


    首先,由于make 后面没有目标,所以make会在Makefile中的第一个不是以.开头的目标作为默认的目标执行。于是default成为make的目标。make会执行 $(MAKE) -C $(KERNELDIR) M=$(PWD) modules shell是make内部的函数,

    假设当前内核版本是2.6.13-study,所以$(shell uname -r)的结果是 2.6.13-study 这里,实际运行的是 
    make -C /lib/modules/2.6.13-study/build M=/home/study/prog/mod/hello/ modules
    /lib /modules/2.6.13-study/build是一个指向内核源代码/usr/src/linux的符号链接。

    可见,make执行了两次。

    第一次执行时是读hello模块的源代码所在目录/home/s tudy/prog/mod/hello/下的Makefile。

    第二次执行时是执行/usr/src/linux/下的Makefile时. 
    但是还是有不少令人困惑的问题: 1.这个KERNELRELEASE也很令人困惑,它是什么呢?在/home/study/prog/mod/he llo/Makefile中是没有定义这个变量的,所以起作用的是else…endif这一段。

       不过,如果把hello模块移动到内核源代码中。例如放到/usr/src/linux/driver/中, KERNELRELEASE就有定义了。在/usr/src/linux/Makefile中有 162 KERNELRELEASE=$(VERSION).$(PATCHLEVEL).$(SUBLEVEL)$(EXTRAVERSION)$(LOCALVERSION) 这时候,hello模块也不再是单独用make编译,而是在内核中用make modules进行 编译。用这种方式,该Makefile在单独编译和作为内核一部分编译时都能正常工作。

     
    2.这个obj-m := hello.o什么时候会执行到呢? 在执行: 
    make -C /lib/modules/2.6.13-study/build M=/home/study/prog/mod/hello/ modules
    时,make 去/usr/src/linux/Makefile中寻找目标modules: 862 .PHONY: modules 863 modules: $(vmlinux-dirs) $(if $(KBUILD_BUILTIN),vmlinux) 864 @echo ' Building modules, stage 2.'; 865 $(Q)$(MAKE) -rR -f $(srctree)/scripts/Makefile.modpost


    可以看出,分两个stage:

    1.编译出hello.o文件。

    2.生成hello.mod.o hello.ko

    在这过程中,会调用 make -f scripts/Makefile.build

    obj=/home/study/prog/mod/hello

    而在 scripts/Makefile.build会包含很多文件: 011 -include .config 012 013 include $(if $(wildcard $(obj)/Kbuild), $(obj)/Kbuild, $(obj)/Makefile) 其中就有/home/study/prog/mod/hello/Makefile 这时 KERNELRELEASE已经存在。

    所以执行的是: obj-m:=hello.o 
    关于make modules的更详细的过程可以在scripts/Makefile.modpost文件的注释 中找到。如果想查看make的整个执行过程,

    可以运行make -n。

  • 相关阅读:
    Hystrix熔断原理
    FeignClient Hystrix超时重试降级
    Windows上Docker Toolbox修改镜像源
    Windows10家庭版安装docker
    Class类文件结构--访问标志
    MySQL常见的七种锁详细介绍()
    maven setting.xml 阿里云镜像 没有一句废话
    mysql 批量操作,已存在则修改,不存在则insert,同时判断空选择性写入字段
    hdu5730
    3月部分题目简要题解
  • 原文地址:https://www.cnblogs.com/Cysan/p/4384158.html
Copyright © 2011-2022 走看看