stack_trace.inc 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright (C) 2012 Zeex
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining a
  4. // copy of this software and associated documentation files (the "Software"),
  5. // to deal in the Software without restriction, including without limitation
  6. // the rights to use, copy, modify, merge, publish, distribute, sublicense,
  7. // and/or sell copies of the Software, and to permit persons to whom the
  8. // Software is furnished to do so, subject to the following conditions:
  9. //
  10. // The above copyright notice and this permission notice shall be included in
  11. // all copies or substantial portions of the Software.
  12. //
  13. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  14. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  18. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  19. // DEALINGS IN THE SOFTWARE.
  20. #if defined STACK_TRACE_INC
  21. #endinput
  22. #endif
  23. #define STACK_TRACE_INC
  24. #include "amx_base"
  25. #include "amx_header"
  26. #include "frame_info"
  27. stock GetFunctionFromReturnAddress(ret_addr) {
  28. new addr = ret_addr - 4;
  29. #emit load.s.alt addr
  30. #emit lctrl 0
  31. #emit add
  32. #emit move.alt
  33. #emit lctrl 1
  34. #emit sub.alt
  35. #emit stor.s.pri addr
  36. #emit lref.s.alt addr
  37. #emit lctrl 0
  38. #emit sub.alt
  39. #emit stor.s.pri addr
  40. return addr - GetAmxBaseAddress();
  41. }
  42. stock GetStackTrace(trace[], skip = 0, max = sizeof(trace)) {
  43. new frm_addr;
  44. #emit lctrl 5
  45. #emit stor.s.pri frm_addr
  46. new length = 0;
  47. while (length < max) {
  48. new ret_addr = GetFrameReturn(frm_addr);
  49. if (length >= skip) {
  50. trace[length] = ret_addr;
  51. }
  52. if (ret_addr == 0) {
  53. break;
  54. }
  55. frm_addr = GetFramePreviousFrame(frm_addr);
  56. if (frm_addr == 0) {
  57. break;
  58. }
  59. length++;
  60. }
  61. return length;
  62. }
  63. stock PrintStackTrace(trace[], max = sizeof(trace)) {
  64. print("Stack trace:");
  65. new i = 0;
  66. for (; trace[i] != 0 && i < max - 1; i++) {
  67. new name[32];
  68. new address = GetFunctionFromReturnAddress(trace[i + 1]);
  69. if (GetPublicNameFromAddress(address, name)) {
  70. printf(" %s[%08x]", name, trace[i]);
  71. } else {
  72. printf(" ??[%08x]", trace[i]);
  73. }
  74. }
  75. printf(" ??[%08x]", trace[i]);
  76. }