lkmc.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /* https://cirosantilli.com/linux-kernel-module-cheat#lkmc-c
  2. *
  3. * This toplevel header includes all the lkmc/ *.h headers.
  4. */
  5. #ifndef LKMC_H
  6. #define LKMC_H
  7. #if !defined(__ASSEMBLER__)
  8. #include <errno.h>
  9. #include <inttypes.h>
  10. #include <stdbool.h>
  11. #include <stdint.h>
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #define LKMC_ASSERT_EQ_DECLARE(bits) \
  15. void lkmc_assert_eq_ ## bits( \
  16. uint ## bits ## _t val1, \
  17. uint ## bits ## _t val2, \
  18. uint32_t line \
  19. )
  20. LKMC_ASSERT_EQ_DECLARE(32);
  21. LKMC_ASSERT_EQ_DECLARE(64);
  22. void lkmc_assert_fail(uint32_t line);
  23. void lkmc_assert_memcmp(const void *s1, const void *s2, size_t n, uint32_t line);
  24. #define LKMC_ARRAY_SIZE(array) (sizeof(array)/sizeof(array[0]))
  25. /* Standard action to take in case of a file IO error. */
  26. #define LKMC_IO_ERROR(function, path) \
  27. fprintf(stderr, "error: %s errno = %d, path = %s\n", function, errno, path); \
  28. exit(EXIT_FAILURE);
  29. #define LKMC_TMP_EXT ".tmp"
  30. /* Temporary per C source file name that our examples can safely create. */
  31. #define LKMC_TMP_FILE __FILE__ LKMC_TMP_EXT
  32. #define LKMC_TMP_FILE_NAMED(name) __FILE__ "__" name LKMC_TMP_EXT
  33. /* https://cirosantilli.com/linux-kernel-module-cheat#c-busy-loop */
  34. void __attribute__ ((noinline)) lkmc_busy_loop(
  35. unsigned long long max,
  36. unsigned long long max2
  37. );
  38. #endif
  39. /* Assert that the given branch instruction is taken. */
  40. #define LKMC_ASSERT(branch_if_pass) \
  41. branch_if_pass 1f; \
  42. LKMC_ASSERT_FAIL; \
  43. 1: \
  44. ;
  45. /* https://stackoverflow.com/questions/1489932/how-to-concatenate-twice-with-the-c-preprocessor-and-expand-a-macro-as-in-arg */
  46. #define LKMC_CONCAT_EVAL(a,b) a ## b
  47. #define LKMC_CONCAT(a,b) LKMC_CONCAT_EVAL(a, b)
  48. #define LKMC_STRINGIFY_DO(x) #x
  49. #define LKMC_STRINGIFY(x) LKMC_STRINGIFY_DO(x)
  50. #define LKMC_GLOBAL(name) \
  51. .global name; \
  52. name:
  53. /* Common C definitions. */
  54. #define LKMC_UNUSED(x) (void)x
  55. /* Weak means that if any other file defines it as a non-weak global,
  56. * that one will take precedence:
  57. * https://stackoverflow.com/questions/274753/how-to-make-weak-linking-work-with-gcc/54601464#54601464
  58. */
  59. #define LKMC_WEAK(name) \
  60. .weak name; \
  61. name:
  62. #if defined(__x86_64__)
  63. #include <lkmc/x86_64.h>
  64. #elif defined(__arm__)
  65. #include <lkmc/arm.h>
  66. #elif defined(__aarch64__)
  67. #include <lkmc/aarch64.h>
  68. #else
  69. #error
  70. #endif
  71. #include <lkmc/m5ops.h>
  72. #endif