Fork Me on GitHub

源码开放学ARM

LASO - Learn ARM with Source Open

首页         目录索引         资料下载         代码下载         联系作者        
下载PDF打印版本

Linux 内核模块

用户空间编写驱动程序

错误写法

/* main.c */

#define UTXH	*(volatile unsigned int *)0xe2900020

int main(void)
{
	while (1)
		UTXH = 'a';

	return 0;
}

Makefile

limingth@ubuntu:~/led-drv-on-linux$ cat Makefile

all: 
	arm-linux-gcc main.c -o main
	
clean: 
	-rm *.obj *.o app

执行会出段错误

$ ./main 
$ Segmentation Fault

正确写法

/* main.c */

#include <stdio.h>	
#include <sys/mman.h>		// mmap()
#include <fcntl.h>		// O_RDWR

int global = 100;

int main(void)
{
	int * vmem = (int *)0x0;
	int uart = 0xe2900000;	// 0x20 offset
	int fd;
	
	fd = open("/dev/mem", O_RDWR);

	printf("fd = %d\n", fd);
	
	vmem = mmap(0, 1, PROT_READ|PROT_WRITE, MAP_SHARED, fd, uart);

	printf("vmem = %p\n", vmem);

	printf(".text = %p\n", main);
	printf(".data = %p\n", &global);
	printf(".stack = %p\n", &uart);

	sleep(1);

	while (1)
		*(vmem + 0x20/4) = 'a';

	close(fd);

	return 0;
}

输出结果

[root@FriendlyARM /home]# ./main
fd = 3                                                                 
vmem = 0x40020000                                                      
.text = 0x8440                                                         
.data = 0x11034                                                        
.stack = 0xbe9fbce4   
aaaaa....

如何链接

arm-linux-ld -verbose

查看 Section 地址

arm-linux-readelf -a main

上一节 | 目录索引 | 下一节

blog comments powered by Disqus