master xplshn/aruu / cmd / linux / insmod.c
 1
 2#include <sys/stat.h>
 3#include <sys/syscall.h>
 4
 5#include <fcntl.h>
 6#include <stdio.h>
 7#include <stdlib.h>
 8#include <string.h>
 9#include <unistd.h>
10
11#include "util.h"
12
13static void
14usage(void)
15{
16  eprintf("usage: %s filename [args...]\n", argv0);
17}
18
19// ?man insmod: insert a module into the Linux kernel
20// ?man arguments: filename [args ...]
21// ?man insmod inserts a kernel module from filename into the running kernel
22int
23main(int argc, char *argv[])
24{
25  char       *buf = NULL, *opts = NULL;
26  size_t      blen, plen        = 0;
27  int         i, fd;
28  ssize_t     n;
29  struct stat sb;
30
31  ARGBEGIN
32  {
33    default:
34      usage();
35  }
36  ARGEND;
37
38  if (argc < 1)
39    usage();
40
41  fd = open(argv[0], O_RDONLY);
42  if (fd < 0)
43    eprintf("open %s:", argv[0]);
44  if (fstat(fd, &sb) < 0)
45    eprintf("stat %s:", argv[0]);
46  blen = sb.st_size;
47  buf  = emalloc(blen);
48
49  n = read(fd, buf, blen);
50  if (n < 0 || (size_t)n != blen)
51    eprintf("read:");
52
53  argc--;
54  argv++;
55
56  for (i = 0; i < argc; i++)
57    plen += strlen(argv[i]);
58  if (plen > 0) {
59    plen += argc;
60    opts = ecalloc(1, plen);
61    for (i = 0; i < argc; i++) {
62      strcat(opts, argv[i]);
63      if (i + 1 < argc)
64        strcat(opts, " ");
65    }
66  }
67
68  if (syscall(__NR_init_module, buf, blen, !opts ? "" : opts) < 0)
69    eprintf("init_module:");
70
71  free(opts);
72  free(buf);
73  return 0;
74}