大家好,想請問kernel module的function中array of struct與struct的記憶體配置方式
是不是不一樣(變數為函數中直接宣告,未使用kmalloc)?會這樣問是因為最近在寫作業時
遇到使用copy_to_user複製一段記憶體內容到userspace時只要複製的內容是array of
struct就會panic,log如下:
usercopy: kernel memory exposure attempt detected from 00000000e7ee16e5
(<process stack>) (16 bytes)
但只要把原本要複製的內容放到同個資料結構的struct中就可以正常copy...,以下是複
時用到的資料結構:
struct U64 {
unsigned long long msl;
unsigned long long lsl;
};
然後餵給copy_to_user的arg(size)都一樣是16 bytes。目前推測array of struct配置的
成員記憶體是不連續的,可是kernelspace的virtual address讓我在debug時看到的記憶
體都是不連續的(array of struct與struct),所以不確定這樣推測是否正確。
不知道各位前輩有什麼看法,謝謝大家!
**更新**(補上程式碼),以下為可以正常運作的程式碼,原本有問題的版本是使用fib(ar
ra
of struct)做複製(copy_to_user(buf, &fib[g - 1], size)),另外,size一直都是16
bytes:
static long long fib_sequence(long long g, char *buf, size_t size)
{
unsigned long long a;
a = 10000000000000000000;
struct U64 fib[g + 1], tmp = {0};
memset(fib, 0, sizeof(struct U64) * (g + 1));
int k;
fib[0].lsl = 1;
fib[1].lsl = 1;
for (k = 2; k <= g; k++) {
fib[k].lsl = fib[k - 1].lsl + fib[k - 2].lsl;
fib[k].msl = fib[k - 1].msl + fib[k - 2].msl;
if (fib[k].lsl > a) {
fib[k].lsl = fib[k].lsl - a;
fib[k].msl = fib[k].msl + 1;
}
}
tmp = fib[g - 1];
copy_to_user(buf, &tmp, size);
return 1;
}