myinsmod.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /* https://cirosantilli.com/linux-kernel-module-cheat#myinsmod */
  2. #define _GNU_SOURCE
  3. #include <fcntl.h>
  4. #include <stdio.h>
  5. #include <sys/stat.h>
  6. #include <sys/syscall.h>
  7. #include <sys/types.h>
  8. #include <unistd.h>
  9. #include <stdlib.h>
  10. #define init_module(module_image, len, param_values) syscall(__NR_init_module, module_image, len, param_values)
  11. #define finit_module(fd, param_values, flags) syscall(__NR_finit_module, fd, param_values, flags)
  12. int main(int argc, char **argv) {
  13. const char *params;
  14. int fd, use_finit;
  15. size_t image_size;
  16. struct stat st;
  17. void *image;
  18. /* CLI handling. */
  19. if (argc < 2) {
  20. puts("Usage ./prog mymodule.ko [args="" [use_finit=0]");
  21. return EXIT_FAILURE;
  22. }
  23. if (argc < 3) {
  24. params = "";
  25. } else {
  26. params = argv[2];
  27. }
  28. if (argc < 4) {
  29. use_finit = 0;
  30. } else {
  31. use_finit = (argv[3][0] != '0');
  32. }
  33. /* Action. */
  34. fd = open(argv[1], O_RDONLY);
  35. if (use_finit) {
  36. puts("finit");
  37. if (finit_module(fd, params, 0) != 0) {
  38. perror("finit_module");
  39. return EXIT_FAILURE;
  40. }
  41. close(fd);
  42. } else {
  43. puts("init");
  44. fstat(fd, &st);
  45. image_size = st.st_size;
  46. image = malloc(image_size);
  47. read(fd, image, image_size);
  48. close(fd);
  49. if (init_module(image, image_size, params) != 0) {
  50. perror("init_module");
  51. return EXIT_FAILURE;
  52. }
  53. free(image);
  54. }
  55. return EXIT_SUCCESS;
  56. }