[英]Can kmalloc() return invalid memory?
我正在寫一個Linux內核模塊,在其中實現了一個鏈表。 我知道Linux內核中有一個列表API,但是當我實現它時,我不知道實現了如何使用kmalloc()處理原始指針。 運行幾個小時后,內核崩潰,並且在崩潰日志中顯示“常規保護錯誤”。 日志還顯示它是從我搜索鏈接列表的函數中發生的。 顯然,搜索功能如下所示,沒有邏輯錯誤。
/*
* Searches in a certain index of hash table for a data
* returns NULL if not found else returns pointer of that element in the table
*/
struct queue_data * search_table(unsigned int hash_index, struct queue_data *new_data)
{
/* Taking a new queue pointer. Which will be pointing to the queue represented
* by new_data at last. */
struct queue_data *ret;
/* First initializing it with first queue on the list */
ret = table[hash_index].next;
/* Iterating through the list to find the desired queue */
while(ret != NULL) {
/* Checking if current queue matches our criteria */
if(ret->saddr == new_data->saddr &&
ret->daddr == new_data->daddr &&
ret->dest == new_data->dest &&
ret->ssrc == new_data->ssrc) {
/* It matched. So I can return it */
return ret;
}
/* It didn't match so I need to go to next queue */
ret = ret->next;
}
/* No queue matched out criteria. Because if it matched it would have not
* come this far. It would have returned before.
* So I need to return a NULL. Now value of 'ret' is NULL.
* I can return 'ret'
*/
return ret;
}
從邏輯的角度來看,插入函數也很完美。 由於一般保護錯誤通常發生在發生無效的內存訪問並且我從未使用kmalloc()
以外的內存分配時。 現在我的問題是,如果我使用由kmalloc分配的內存,那么是否有可能使用無效的內存,在使用前應該檢查嗎?
崩潰日志的分數在這里:
[ffff8804130cb690] general_protection at ffffffff81661c85
[exception RIP: search_table+52]
RIP: ffffffffa00bc854 RSP: ffff8804130cb748 RFLAGS: 00010286
RAX: d6d4575455d55555 RBX: ffff88040f46db00 RCX: 0000000000000018
RDX: 02b53202ab706c17 RSI: ffff8803fccaaa00 RDI: 00000000000c2568
RBP: ffff8804130cb748 R8: ffffffff8180cb80 R9: 000000000000016d
R10: a3d70a3d70a3d70b R11: ffff8803fccaab58 R12: ffffc9001262cc38
R13: 000000000000079f R14: ffff8803fccaaa00 R15: ffffffffa00cbee8
ORIG_RAX: ffffffffffffffff CS: 0010 SS: 0018
插入時,我用kmalloc檢查了分配的內存:
/* Allocating and initializing a new queue.
* If a queue corresponding to it already exists then it's data will
* copied and this queue will be dropped.
* Else this queue will be inserted to the hash table that manages the queues.
*/
new_data = (struct queue_data *)kmalloc(sizeof(struct queue_data), GFP_ATOMIC);
if (!new_data) {
//printk(KERN_ALERT "pkt_queue EXCEPTION: new_data\n");
return NULL;
}
查看您發布的代碼,我看到的“ 一般保護錯誤”的唯一可能來源是以下行:
ret = table[hash_index].next;
您沒有檢查table
的大小,所以也許您正在訪問越界內存? 如果不知道table
的聲明方式,位置和形式以及如何初始化table
,就無法確定。
在查看您的評論后,說hash_index
,一個unsigned int
,是HASH_PRIME
宏的模數的結果, 可能是在某個時候,您遇到了可能的有符號無符號算術問題,因此盡管HASH_PRIME
,你實際上會出界。 也許加上:
if (hash_index >= HASH_PRIME) hash_index = HASH_PRIME-1;//or error
出於完整性考慮:正如我在評論中所指出的那樣,您正在使用的所有功能均使用內核的u32
類型。 事實證明,這就是您的代碼仍然訪問錯誤內存的原因。 (在手機上鍵入此更新...討厭)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.