3

I'm trying to load a kernel module from C using kmod, but it's not working at all. Here's what I have:

#include <stdio.h>
#include <stddef.h>
#include <unistd.h>
#include <stdlib.h>

#include <libkmod.h>

int main(int argc, char **argv){

    struct kmod_ctx *ctx;
    struct kmod_module *mod;
    const char *null_config = NULL;
    int err;

    ctx = kmod_new(NULL, &null_config);
    if(ctx == NULL)
        exit(EXIT_FAILURE);

    err = kmod_module_new_from_path(ctx, "./my_module.ko", &mod); // <-- module is in same dir as this binary
    if(err != 0)
        printf("Error creating module from path\n");

    err = kmod_module_insert_module(mod, 0, NULL);
    if(err != 0)
        printf("Error inserting module\n");
    kmod_unref(ctx);

}

I'm getting both printfs, so kmod is failing at creating the module from the path, but why?

PS: I'm running the binary as root, from the same dir as the module.

0x90
  • 39,472
  • 36
  • 165
  • 245
alexandernst
  • 14,352
  • 22
  • 97
  • 197
  • You say the module is in the same directory as the executable, but from where do you run the executable? – Carl Norum Apr 25 '13 at 22:10
  • From the same dir, ofc. – alexandernst Apr 25 '13 at 22:10
  • What error is returned? – Carl Norum Apr 25 '13 at 22:12
  • The only output I get are both printfs's messages. – alexandernst Apr 25 '13 at 22:14
  • 1
    That's because you don't check what the error value is, just that the return value is nonzero. If you do check it (`strerror` or `perror`, maybe?), it will probably have useful information. – Carl Norum Apr 25 '13 at 22:20
  • err is equal to -2, which doesn't mean anything at all as it could be almost anything according to docs: Returns: 0 on success or < 0 otherwise. It fails if file does not exist, if * it's not a valid file for a kmod_module or if memory allocation failed. – alexandernst Apr 25 '13 at 22:26
  • 1
    What about `errno`? Check out this example: https://github.com/profusion/kmod/blob/master/test/test-elf.c – Carl Norum Apr 25 '13 at 22:30
  • The error is "Unknown error -2" (strerror(-errno)); – alexandernst Apr 25 '13 at 22:32
  • 1
    Try without the `-`? I'm not actually familiar with the referenced code, it just turned up in a google search. On my machine `2` is `ENOENT`, meaning "no such file or directory". Sounds like you have a permissions or working-directory problem. – Carl Norum Apr 25 '13 at 22:37
  • Ok, I just rebooted my pc and it started working. Maybe I upgraded my kernel a few days/weeks ago and didn't rebooted since then (?). Thank you for the help anyways :) – alexandernst Apr 25 '13 at 22:38
  • with `System ("insmod a.ko")` it works? can someone get all the comment and write an answer? – 0x90 Apr 26 '13 at 08:15
  • The code works fine. The problem was (?) that I didn't reboot my pc since the last kernel update and something weird was going on. – alexandernst Apr 26 '13 at 08:19

0 Answers0