Kernel crash when dereferencing a null pointer

2019-09-01 10:20发布

问题:

I have a simple module like this:

#define MODULE

#include <linux/kernel.h> 
#include <linux/module.h> 
#include <linux/init.h> 

int init_module(void) {
    struct inode {
        int i_ino;
    };
    struct dentry {
        struct inode *d_inode;
    }; 
    struct dentry *f_dentry;
    f_dentry = NULL;
    struct inode * p = f_dentry->d_inode;
    return 0; 
}

void cleanup_module(void) { 
        printk("Goodbye world\n"); 
}

And my Makefile is like this:

obj-m += oops.o 

all: 
        make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

clean:
        make -C /lib/modules$(shell uname -r)/build M=$(PWD) clean

I expect that the kernel will crash because struct inode * p = f_dentry->d_inode; has dereferenced a null pointer, right? But it does not. Anything wrong with my idea? All right, now I'll have one more try. If my module is like this:

#define MODULE

#include <linux/kernel.h> 
#include <linux/module.h> 
#include <linux/init.h> 

int init_module(void) {
    *(int *)0 = 0; 
    return 0; 
}

void cleanup_module(void) { 
        printk("Goodbye world\n"); 
}

My computer really crashes. Or anything wrong with my former example? It doesn't dereference a null pointer?

回答1:

If you look at the assembly code(via e.g. objdump -D oops.ko), all of your init_module() is optimized away, presumably because it doesn't do anything.

If you e.g. do p->i_ino = 1; , you'll likely see different results(Albeit this is undefined behavior, so it's not straight forward to reason about what the code is going to do - better check the assembly in this case too).