Question

Experimenting with some FreeBSD kernel hacking and I ran into an error on a simple hook example. The code is as follows

*NOTE - I have added #include <sys/stat.h> as many have suggested, but continue to get the same error.

#include <sys/types.h>
#include <sys/param.h>
#include <sys/proc.h>
#include <sys/module.h>
#include <sys/sysent.h>
#include <sys/kernel.h>
#include <sys/systm.h>
#include <sys/syscall.h>
#include <sys/sysproto.h>
#include <sys/stat.h>

static int mkdir_hook(struct thread *td, void *syscall_args) {

  struct mkdir_args *uap;
  uap = (struct mkdir_args *)syscall_args;
  char path[255];
  size_t done;
  int error;
  error = copyinstr(uap->path, path, 255, &done);
  if(error != 0)
    return (error);

  uprintf("hooked it\n");
  return (mkdir(td, syscall_args));
}

static int load(struct module *module, int cmd, void *arg) {
  int error = 0;
  switch(cmd){
  case MOD_LOAD:
    sysent[SYS_mkdir].sy_call = (sy_call_t *)mkdir_hook;
    break;
  case MOD_UNLOAD:
    sysent[SYS_mkdir].sy_call = (sy_call_t *)mkdir;
    break;
  default:
    error = EOPNOTSUPP;
    break;
  }
  return(error);
}

static moduledata_t mkdir_hook_mod = {
  "mkdir_hook",
  load,
  NULL
};

DECLARE_MODULE(mkdir_hook, mkdir_hook_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE);

The compiler error is

    mkdirhook.c:23:11: error: implicit declaration of function 'mkdir' is invalid in C99 [-Werror,-Wimplicit-function-declaration]
  return (mkdir(td, syscall_args));
          ^
1 error generated.
*** Error code 1

My guess is this is a simple problem and the code sample I'm using is out of date.

Was it helpful?

Solution

You cannot use mkdir in a kernel module.

The mkdir function is part of the standard C library (libc) which can only be used in user-space programs, not in kernel or module code!

So the definition of mkdir in sys/stat.h is in an #ifndef _KERNEL/#endif block and won't be "seen" if you are compiling a kernel module.

In 2011, all system calls were all given a sys_ prefix. (See also the answer to this question) So you should use sys_mkdir instead.

OTHER TIPS

mkdir() is defined in sys/stat.h on FreeBSD. The code need to:

  #include <sys/stat.h>

You need to include sys/stat.h to use the mkdir function.

#include <sys/stat.h>

implicit declaration of function 'mkdir' is the give-away... you're trying to use a function (mkdir()) that has not been prototyped. Prototype it: #include <sys/stat.h>

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top