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	default:
33		usage();
34	} ARGEND;
35
36	if (argc < 1)
37		usage();
38
39	fd = open(argv[0], O_RDONLY);
40	if (fd < 0)
41		eprintf("open %s:", argv[0]);
42	if (fstat(fd, &sb) < 0)
43		eprintf("stat %s:", argv[0]);
44	blen = sb.st_size;
45	buf = emalloc(blen);
46
47	n = read(fd, buf, blen);
48	if (n < 0 || (size_t)n != blen)
49		eprintf("read:");
50
51	argc--;
52	argv++;
53
54	for (i = 0; i < argc; i++)
55		plen += strlen(argv[i]);
56	if (plen > 0) {
57		plen += argc;
58		opts = ecalloc(1, plen);
59		for (i = 0; i < argc; i++) {
60			strcat(opts, argv[i]);
61			if (i + 1 < argc)
62				strcat(opts, " ");
63		}
64	}
65
66	if (syscall(__NR_init_module, buf, blen, !opts ? "" : opts) < 0)
67		eprintf("init_module:");
68
69	free(opts);
70	free(buf);
71	return 0;
72}