系统相关
首页 > 系统相关> > 《内核kernel:VMA内存模块编写》

《内核kernel:VMA内存模块编写》

作者:互联网

一、模块编写

#include <linux/module.h>
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/sched.h>

static int pid;
module_param(pid, int, 0644);

static void printit(struct task_struct *tsk)
{
	struct mm_struct *mm;
	struct vm_area_struct *vma;
	int j = 0;
	unsigned long start, end, length;

	mm = tsk->mm;
	pr_info("mm_struct addr = 0x%p\n", mm);
	vma = mm->mmap;

	/* protect from simultaneous modification */
	down_read(&mm->mmap_sem);
	pr_info("vmas:                vma        start          end        length\n");

	while (vma) {
		j++;
		start = vma->vm_start;
		end = vma->vm_end;
		length = end - start;
		pr_info("%6d: %16p %12lx %12lx   %8ld\n",
			j, vma, start, end, length);
		vma = vma->vm_next;
	}
	up_read(&mm->mmap_sem);
}

static int __init my_init(void)
{
	struct task_struct *tsk;
	/* if don't pass the pid over insmod, then use the current process */
	if (pid == 0) {
		tsk = current;
		pid = current->pid;
		pr_info("using current process\n");
	} else {
		tsk = pid_task(find_vpid(pid), PIDTYPE_PID);
	}
	if (!tsk)
		return -1;
	pr_info(" Examining vma's for pid=%d, command=%s\n", pid, tsk->comm);
	printit(tsk);
	return 0;
}

static void __exit my_exit(void)
{
	pr_info("Module exit\n");
}

module_init(my_init);
module_exit(my_exit);

MODULE_LICENSE("GPL v2");

二、Makefile

BASEINCLUDE ?= /home/yexiang/work/running_kernel/runninglinuxkernel_4.0
#BASEINCLUDE ?= /lib/modules/`uname -r`/build

vma_test-objs := vma.o

obj-m   := vma_test.o
all :
        $(MAKE) -C $(BASEINCLUDE) M=$(PWD) modules;

clean:
        $(MAKE) -C $(BASEINCLUDE) SUBDIRS=$(PWD) clean;
        rm -f *.ko;

编译:make

运行:

/ # insmod /mnt/vma_test.ko 
[16719.728784] using current process
[16719.729100]  Examining vma's for pid=793, command=insmod
[16719.729655] mm_struct addr = 0xc4b50240
[16719.729863] vmas:                vma        start          end        length
[16719.730536]      1:         c4dc1bd8        10000       207000    2060288
[16719.730747]      2:         c4dc1398       216000       219000      12288
[16719.730914]      3:         c4dc0c60       219000       23d000     147456
[16719.736574]      4:         c4dc0528     bec9f000     becc1000     139264
[16719.740987]      5:         c4dc14a0     bedd0000     bedd1000       4096

 

标签:kernel,struct,mm,pid,tsk,vma,start,VMA,内存模块
来源: https://blog.csdn.net/yexiangCSDN/article/details/96136414