ubase

suckless linux base utils
git clone git://git.2f30.org/ubase
Log | Files | Refs | README | LICENSE

insmod.c (1141B)


      1 /* See LICENSE file for copyright and license details. */
      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 
     13 static void
     14 usage(void)
     15 {
     16 	eprintf("usage: %s filename [args...]\n", argv0);
     17 }
     18 
     19 int
     20 main(int argc, char *argv[])
     21 {
     22 	char *buf = NULL, *opts = NULL;
     23 	size_t blen, plen = 0;
     24 	int i, fd;
     25 	ssize_t n;
     26 	struct stat sb;
     27 
     28 	ARGBEGIN {
     29 	default:
     30 		usage();
     31 	} ARGEND;
     32 
     33 	if (argc < 1)
     34 		usage();
     35 
     36 	fd = open(argv[0], O_RDONLY);
     37 	if (fd < 0)
     38 		eprintf("open %s:", argv[0]);
     39 	if (fstat(fd, &sb) < 0)
     40 		eprintf("stat %s:", argv[0]);
     41 	blen = sb.st_size;
     42 	buf = emalloc(blen);
     43 
     44 	n = read(fd, buf, blen);
     45 	if (n < 0 || (size_t)n != blen)
     46 		eprintf("read:");
     47 
     48 	argc--;
     49 	argv++;
     50 
     51 	for (i = 0; i < argc; i++)
     52 		plen += strlen(argv[i]);
     53 	if (plen > 0) {
     54 		plen += argc;
     55 		opts = ecalloc(1, plen);
     56 		for (i = 0; i < argc; i++) {
     57 			strcat(opts, argv[i]);
     58 			if (i + 1 < argc)
     59 				strcat(opts, " ");
     60 		}
     61 	}
     62 
     63 	if (syscall(__NR_init_module, buf, blen, !opts ? "" : opts) < 0)
     64 		eprintf("init_module:");
     65 
     66 	free(opts);
     67 	free(buf);
     68 	return 0;
     69 }