リンクリストを実装した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;
}
また、挿入機能も論理的な観点から完璧であることは明らかです。General Protection Fault は通常、無効なメモリ アクセスが発生した場合に発生し、 以外によって割り当てられたメモリを使用したことがないため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;
}