The Android Open Source Project | dd7bc33 | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1 | #include <stdio.h> |
| 2 | #include <string.h> |
| 3 | #include <fcntl.h> |
| 4 | #include <unistd.h> |
| 5 | #include <malloc.h> |
| 6 | #include <errno.h> |
| 7 | #include <sys/types.h> |
| 8 | #include <sys/stat.h> |
| 9 | #include <unistd.h> |
| 10 | |
| 11 | extern int init_module(void *, unsigned long, const char *); |
| 12 | |
| 13 | static void *read_file(const char *filename, ssize_t *_size) |
| 14 | { |
| 15 | int ret, fd; |
| 16 | struct stat sb; |
| 17 | ssize_t size; |
| 18 | void *buffer = NULL; |
| 19 | |
| 20 | /* open the file */ |
| 21 | fd = open(filename, O_RDONLY); |
| 22 | if (fd < 0) |
| 23 | return NULL; |
| 24 | |
| 25 | /* find out how big it is */ |
| 26 | if (fstat(fd, &sb) < 0) |
| 27 | goto bail; |
| 28 | size = sb.st_size; |
| 29 | |
| 30 | /* allocate memory for it to be read into */ |
| 31 | buffer = malloc(size); |
| 32 | if (!buffer) |
| 33 | goto bail; |
| 34 | |
| 35 | /* slurp it into our buffer */ |
| 36 | ret = read(fd, buffer, size); |
| 37 | if (ret != size) |
| 38 | goto bail; |
| 39 | |
| 40 | /* let the caller know how big it is */ |
| 41 | *_size = size; |
| 42 | |
| 43 | bail: |
| 44 | close(fd); |
| 45 | return buffer; |
| 46 | } |
| 47 | |
| 48 | #define min(x,y) ((x) < (y) ? (x) : (y)) |
| 49 | int insmod_main(int argc, char **argv) |
| 50 | { |
| 51 | void *file; |
| 52 | ssize_t size = 0; |
| 53 | char opts[1024]; |
| 54 | int ret; |
| 55 | |
| 56 | /* make sure we've got an argument */ |
| 57 | if (argc < 2) { |
| 58 | fprintf(stderr, "usage: insmod <module.o>\n"); |
| 59 | return -1; |
| 60 | } |
| 61 | |
| 62 | /* read the file into memory */ |
| 63 | file = read_file(argv[1], &size); |
| 64 | if (!file) { |
| 65 | fprintf(stderr, "insmod: can't open '%s'\n", argv[1]); |
| 66 | return -1; |
| 67 | } |
| 68 | |
| 69 | opts[0] = '\0'; |
| 70 | if (argc > 2) { |
| 71 | int i, len; |
| 72 | char *end = opts + sizeof(opts) - 1; |
| 73 | char *ptr = opts; |
| 74 | |
| 75 | for (i = 2; (i < argc) && (ptr < end); i++) { |
| 76 | len = min(strlen(argv[i]), end - ptr); |
| 77 | memcpy(ptr, argv[i], len); |
| 78 | ptr += len; |
| 79 | *ptr++ = ' '; |
| 80 | *ptr++ = '\0'; |
| 81 | } |
| 82 | *(ptr - 1) = '\0'; |
| 83 | } |
| 84 | |
| 85 | /* pass it to the kernel */ |
| 86 | ret = init_module(file, size, opts); |
| 87 | if (ret != 0) { |
| 88 | fprintf(stderr, |
| 89 | "insmod: init_module '%s' failed (%s)\n", |
| 90 | argv[1], strerror(errno)); |
| 91 | } |
| 92 | |
| 93 | /* free the file buffer */ |
| 94 | free(file); |
| 95 | |
| 96 | return ret; |
| 97 | } |
| 98 | |