Re: About THIS_MODULE
John Garry <[email protected]> Wed, 29 Jul 2026 13:46:25 +0100
| Newsgroups | org.kernel.vger.linux-modules |
|---|---|
| Organization | Oracle Corporation |
| Message-ID | <[email protected]> |
On 09/07/2026 15:31, Petr Pavlu wrote:
> On 7/3/26 5:33 PM, John Garry wrote:
Hi Petr,
Apologies for the very slow response. I only noticed your message now.
>> Hi all,
>>
>> I have a query which I hope someone can advise on.
>>
>> I am adding a library API which requires a driver to pass the driver module pointer to the API.
>>
>> So we use THIS_MODULE for that purpose.
>>
>> However, adding a sanity check in the library to ensure that pointer is set is a challenge. Normally we would check that the module pointer is non-NULL. However, for a built-in driver module, THIS_MODULE is NULL, so rely on the non-NULL check.
>>
>> Any idea how to deal with this?
> Right, a NULL module pointer is ambiguous if you want to distinguish
> between these two cases. I can't think of a neat way to handle this in
> a library API.
>
> One option would be to rework THIS_MODULE and introduce a reduced module
> struct also for vmlinux and built-in modules.
I was thinking of something like this:
init.h
extern struct module builtin_this_module;
#ifdef MODULE
extern struct module __this_module;
#define THIS_MODULE (&__this_module)
#else
#define THIS_MODULE (&builtin_this_module)
#endif
main.c
struct module builtin_this_module;
bool try_module_get(struct module *module)
{
bool ret = true;
if (module == &builtin_this_module)
return true;
if (module) {
/* Note: here, we can fail to get a reference */
if (likely(module_is_live(module) &&
atomic_inc_not_zero(&module->refcnt) != 0))
trace_module_get(module, _RET_IP_);
else
ret = false;
} else {
pr_warn("cannot take reference to NULL module\n");
ret = false;
}
return ret;
}
EXPORT_SYMBOL(try_module_get);
All the module APIs would be need to be able to handle builtin_this_module.
The issue I then see is that other kernel code just relies on
THIS_MODULE == NULL for builtin or forget to set, like:
static inline int netlink_dump_start(struct sock *ssk, struct sk_buff *skb,
const struct nlmsghdr *nlh,
struct netlink_dump_control *control)
{
if (!control->module)
control->module = THIS_MODULE;
return __netlink_dump_start(ssk, skb, nlh, control);
}
Cleaning this up would be too difficult.
> However, this isn't
> a trivial change and I can't recall a case in the last few years where
> this has caused a specific issue. Additionally, if someone forgets to
> pass a module pointer somewhere, I would expect it to be fairly easy to
> detect and fix.
Removing modules test coverage is not generally great and that is where
we use things like try_module_get() to protect - but it only does the
proper job if the module is properly set.
Thanks,
John