都是指针惹的祸?(一)
一月 7th, 2009
1: /* slightly modified, for 32-bit platform */
2: 3: #define MAX_INDEX 0x8
4: #define IOCTL_GET_FOO_STRUCT 0x20081018
5: 6: struct foo_s {
7: int bla;
8: int blabla;
9: /* .... */
10: }; 11: 12: struct foo_s foo_structs[MAX_INDEX];
13: 14: /*
15: * 获取内核指定数组中索引为index的元素,用户层传入的缓冲区结构如下:
16: *
17: * ,--------------------,
18: * | u32 index | sizeof(u32), 0-based
19: * |--------------------|
20: * | struct foo_s |
21: * | ... |
22: * `--------------------`
23: *
24: */
25: 26: static int foo_ioctl(struct inode *inode, struct file *file,
27: unsigned int cmd, unsigned long arg)
28: {29: /* .... */
30: 31: switch (cmd) {
32: /* .... */
33: 34: case IOCTL_GET_FOO_STRUCT:
35: {36: unsigned long not = 0;
37: u32 *ip = (u32 *)arg; 38: 39: printk(KERN_INFO "get index %d\n", *ip);
40: if (*ip >= MAX_INDEX) {
41: return -EINVAL;
42: }43: check_foo_present(*ip); /* check if the struct valid */
44: *ip = IOCTL_GET_FOO_STRUCT; /* take it as magic */
45: not = copy_to_user((void *)(arg + sizeof(u32)), /* offset! */
46: &foo_structs[*ip], sizeof(struct foo_s));
47: 48: break;
49: } 50: 51: /* .... */
52: 53: } /* switch */
54: 55: return 0;
56: } 57: 注意44~46行。