看板 LinuxDev 關於我們 聯絡資訊
我自己解決了 ^^ ================ 我昨天在閱讀現在新版的 lkmpg ,在其中一個章節有 character device 的 example code : https://sysprog21.github.io/lkmpg/#chardevc 前面 6.4 有提過: Note that you don't have to check the counter within cleanup_module because the check will be performed for you by the system call sys_delete_module, defined in include/linux/syscall.h . You should not use this counter directly but there are functions defined in include/linux/module.h which that you increase, decrease and display the counter: try_module_get(THIS_MODULE) : ......... module_put(THIS_MODULE) : ......... module_refcount(THIS_MODULE): ......... 但是在 chardev.c 裡面卻在 device_open 裡面用 try_module_get(THIS_MODULE) 去增 加 refcount ,在 device_release 裡面用 module_put(THIS_MODULE) 說好的不推薦直接使用呢??? 目前看過的 kernel module 的 code 好像也沒有人呼叫過這些 function , kernel 應 該會幫忙 handle 這些 lkm 的 refcount ,不明白加這些的用意在幹嘛.... -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.229.149.207 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/LinuxDev/M.1655094115.A.C5B.html ※ 編輯: b0920075 (36.229.149.207 臺灣), 06/13/2022 12:24:01
admon: 黃字說不要用變數,要用函式。你英文不好。 06/13 12:40
他意思不是說不要去改 refcount 但真的手賤想改的話仍然有些 function 可以更改 re fcoutn 的意思嗎? 就算不要用變數好了,那他用這些函數意義在哪? kernel 不是應該要幫忙管理 refcount 嗎 然後我有找到一篇 stackoverflow 也說不要用 try_module_get 這種 函數 https://stackoverflow.com/questions/1741415/linux-kernel-modules-when-to-use-try-module-get-module-put 看起來跟直接用變數還是函數控制沒關係啊? ※ 編輯: b0920075 (36.229.149.207 臺灣), 06/13/2022 16:37:59 我剛剛自己做了一下實驗看移除 try_module_get 和 module_put 會怎樣 移除後 lsmod 看到的 used by 都會是 0 ,看起來 kernel 沒有因為我開啟 / dev/chardev 就幫我增加 refcount ,如果此時我直接 mmod 後關閉 /dev/chardev 會 發生 kernel panic unhandle page fault ,但是這跟我之前接觸到的 kernel module 行為有些出入.... 於是我又嘗試加載另一份 lkm 取自 https://github.com/yuawn/Linux-Kernel-Exploitation 簡單的在 msg_msg.c 開啟 /dev/demo 後印出 lsmod 發現他的 Used 真的有加 1 但是 demo 裡面卻沒看到 try_module_get 或是 module_put ,不確定是差在哪 QQ ※ 編輯: b0920075 (36.229.149.207 臺灣), 06/13/2022 17:35:14 ※ 編輯: b0920075 (36.229.149.207 臺灣), 06/13/2022 17:36:03 剛剛嘗試對 file_operations 的 owner 給 THIS_MODULE 後 Used 的數字就正常了, 應該是 .owner = THIS_MODULE 對 refcount 生效了!? 根據這篇 stackoverflow 也說如果有設定 .owner 的話在 device_open 前就會 try_module_get https://stackoverflow.com/questions/48478978/regarding-owner-field-of-struct-file-operations 因為我的 device 是 chardev ,猜測應該是在 char_dev.c 中的 cdev_get 裡面的: static struct kobject *cdev_get(struct cdev *p) { struct module *owner = p->owner; struct kobject *kobj; if (owner && !try_module_get(owner)) return NULL; kobj = kobject_get(&p->kobj); if (!kobj) module_put(owner); return kobj; } 如果有 owner 就嘗試去 try_module_get 幫忙 handle ※ 編輯: b0920075 (36.229.149.207 臺灣), 06/13/2022 17:50:37 ※ 編輯: b0920075 (36.229.149.207 臺灣), 06/13/2022 17:51:01
dragon121985: softdep可能是更好的選擇? 06/16 20:58