kstrto.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /* https://github.com/cirosantilli/linux-kernel-module-cheat#kstrto */
  2. #include <linux/debugfs.h>
  3. #include <linux/kernel.h>
  4. #include <linux/module.h>
  5. #include <linux/seq_file.h>
  6. #include <linux/uaccess.h> /* copy_from_user, copy_to_user */
  7. #include <uapi/linux/stat.h> /* S_IWUSR */
  8. static struct dentry *toplevel_file;
  9. static char read_buf[1024];
  10. static int show(struct seq_file *m, void *v)
  11. {
  12. seq_printf(m, read_buf);
  13. return 0;
  14. }
  15. static int open(struct inode *inode, struct file *file)
  16. {
  17. return single_open(file, show, NULL);
  18. }
  19. static ssize_t write(struct file *filp, const char __user *buf, size_t len, loff_t *off)
  20. {
  21. ssize_t ret;
  22. int kstrto_return;
  23. unsigned long long kstrto_result;
  24. kstrto_return = kstrtoull_from_user(buf, len, 10, &kstrto_result);
  25. if (kstrto_return) {
  26. /* Negative error code. */
  27. ret = kstrto_return;
  28. } else {
  29. ret = len;
  30. }
  31. snprintf(read_buf, sizeof(read_buf), "%llu", kstrto_result + 1);
  32. return ret;
  33. }
  34. static const struct file_operations fops = {
  35. .llseek = seq_lseek,
  36. .open = open,
  37. .owner = THIS_MODULE,
  38. .read = seq_read,
  39. .release = single_release,
  40. .write = write,
  41. };
  42. static int myinit(void)
  43. {
  44. toplevel_file = debugfs_create_file("lkmc_kstrto", S_IWUSR, NULL, NULL, &fops);
  45. if (!toplevel_file) {
  46. return -1;
  47. }
  48. return 0;
  49. }
  50. static void myexit(void)
  51. {
  52. debugfs_remove(toplevel_file);
  53. }
  54. module_init(myinit)
  55. module_exit(myexit)
  56. MODULE_LICENSE("GPL");