kmalloc_tracer.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // SPDX-License-Identifier: GPL-2.0+
  2. #include "kmalloc_tracer.h"
  3. #include <linux/gfp.h>
  4. #include <linux/slab.h>
  5. static int kmalloc_entry_handler(struct kretprobe_instance *instance,
  6. struct pt_regs *regs)
  7. {
  8. struct hlist_head *head_proc;
  9. struct hlist_node *i;
  10. struct tracer_data *data_proc;
  11. struct addr_data *data_addr;
  12. pid_t tgid;
  13. tgid = current->tgid;
  14. head_proc = &procs_table[hash_min(tgid, HASH_BITS(procs_table))];
  15. if (head_proc->first == NULL)
  16. return HANDLER_STOP;
  17. hlist_for_each_entry_safe(data_proc, i, head_proc, node) {
  18. if (data_proc->tgid == tgid) {
  19. arch_atomic_inc(&data_proc->kmalloc_data.calls);
  20. data_addr =
  21. kmalloc(sizeof(struct addr_data), GFP_NOWAIT);
  22. if (data_addr == NULL)
  23. return -ENOMEM;
  24. data_addr->tgid = tgid;
  25. data_addr->size = (ssize_t)regs->ax;
  26. data_addr->addr = 0;
  27. hash_add(addr_table, &data_addr->node, tgid);
  28. return HANDLER_CONTINUE;
  29. }
  30. }
  31. return HANDLER_STOP;
  32. }
  33. static int kmalloc_handler(struct kretprobe_instance *instance,
  34. struct pt_regs *regs)
  35. {
  36. struct hlist_head *head_proc;
  37. struct hlist_head *head_addr;
  38. struct hlist_node *i, *j;
  39. struct tracer_data *data_proc;
  40. struct addr_data *data_addr;
  41. unsigned long addr;
  42. pid_t tgid;
  43. addr = regs->ax;
  44. tgid = current->tgid;
  45. if (addr == 0)
  46. return HANDLER_STOP;
  47. head_proc = &procs_table[hash_min(tgid, HASH_BITS(procs_table))];
  48. if (head_proc->first == NULL)
  49. return HANDLER_STOP;
  50. hlist_for_each_entry_safe(data_proc, i, head_proc, node) {
  51. if (data_proc->tgid == tgid) {
  52. head_addr = &addr_table[hash_min(
  53. tgid, HASH_BITS(addr_table))];
  54. if (head_addr->first == NULL)
  55. return HANDLER_STOP;
  56. hlist_for_each_entry_safe(data_addr, j, head_addr, node) {
  57. if (data_addr->tgid == tgid) {
  58. data_addr->addr = addr;
  59. arch_atomic_add(
  60. data_addr->size,
  61. &data_proc->kmalloc_data.mem);
  62. return HANDLER_CONTINUE;
  63. }
  64. }
  65. }
  66. }
  67. return HANDLER_STOP;
  68. }
  69. struct kretprobe kmalloc_probe = { .handler = kmalloc_handler,
  70. .entry_handler = kmalloc_entry_handler,
  71. .kp.symbol_name = KMALLOC_TRACER_SYMBOL_NAME,
  72. .maxactive = MAX_ACTIVE };