stacktrace.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Stack trace management functions
  4. *
  5. * Copyright (C) 2022 Loongson Technology Corporation Limited
  6. */
  7. #include <linux/sched.h>
  8. #include <linux/stacktrace.h>
  9. #include <linux/uaccess.h>
  10. #include <asm/stacktrace.h>
  11. #include <asm/unwind.h>
  12. void arch_stack_walk(stack_trace_consume_fn consume_entry, void *cookie,
  13. struct task_struct *task, struct pt_regs *regs)
  14. {
  15. unsigned long addr;
  16. struct pt_regs dummyregs;
  17. struct unwind_state state;
  18. regs = &dummyregs;
  19. if (task == current) {
  20. regs->regs[3] = (unsigned long)__builtin_frame_address(0);
  21. regs->csr_era = (unsigned long)__builtin_return_address(0);
  22. } else {
  23. regs->regs[3] = thread_saved_fp(task);
  24. regs->csr_era = thread_saved_ra(task);
  25. }
  26. regs->regs[1] = 0;
  27. for (unwind_start(&state, task, regs);
  28. !unwind_done(&state); unwind_next_frame(&state)) {
  29. addr = unwind_get_return_address(&state);
  30. if (!addr || !consume_entry(cookie, addr))
  31. break;
  32. }
  33. }
  34. static int
  35. copy_stack_frame(unsigned long fp, struct stack_frame *frame)
  36. {
  37. int ret = 1;
  38. unsigned long err;
  39. unsigned long __user *user_frame_tail;
  40. user_frame_tail = (unsigned long *)(fp - sizeof(struct stack_frame));
  41. if (!access_ok(user_frame_tail, sizeof(*frame)))
  42. return 0;
  43. pagefault_disable();
  44. err = (__copy_from_user_inatomic(frame, user_frame_tail, sizeof(*frame)));
  45. if (err || (unsigned long)user_frame_tail >= frame->fp)
  46. ret = 0;
  47. pagefault_enable();
  48. return ret;
  49. }
  50. void arch_stack_walk_user(stack_trace_consume_fn consume_entry, void *cookie,
  51. const struct pt_regs *regs)
  52. {
  53. unsigned long fp = regs->regs[22];
  54. while (fp && !((unsigned long)fp & 0xf)) {
  55. struct stack_frame frame;
  56. frame.fp = 0;
  57. frame.ra = 0;
  58. if (!copy_stack_frame(fp, &frame))
  59. break;
  60. if (!frame.ra)
  61. break;
  62. if (!consume_entry(cookie, frame.ra))
  63. break;
  64. fp = frame.fp;
  65. }
  66. }