lua-memory.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. #define LUA_LIB
  2. #include <lua.h>
  3. #include <lauxlib.h>
  4. #include "malloc_hook.h"
  5. static int
  6. ltotal(lua_State *L) {
  7. size_t t = malloc_used_memory();
  8. lua_pushinteger(L, (lua_Integer)t);
  9. return 1;
  10. }
  11. static int
  12. lblock(lua_State *L) {
  13. size_t t = malloc_memory_block();
  14. lua_pushinteger(L, (lua_Integer)t);
  15. return 1;
  16. }
  17. static int
  18. ldumpinfo(lua_State *L) {
  19. const char *opts = NULL;
  20. if (lua_isstring(L, 1)) {
  21. opts = luaL_checkstring(L,1);
  22. }
  23. memory_info_dump(opts);
  24. return 0;
  25. }
  26. static int
  27. ljestat(lua_State *L) {
  28. static const char* names[] = {
  29. "stats.allocated",
  30. "stats.resident",
  31. "stats.retained",
  32. "stats.mapped",
  33. "stats.active" };
  34. static size_t flush = 1;
  35. mallctl_int64("epoch", &flush); // refresh je.stats.cache
  36. lua_newtable(L);
  37. int i;
  38. for (i = 0; i < (sizeof(names)/sizeof(names[0])); i++) {
  39. lua_pushstring(L, names[i]);
  40. lua_pushinteger(L, (lua_Integer) mallctl_int64(names[i], NULL));
  41. lua_settable(L, -3);
  42. }
  43. return 1;
  44. }
  45. static int
  46. lmallctl(lua_State *L) {
  47. const char *name = luaL_checkstring(L,1);
  48. lua_pushinteger(L, (lua_Integer) mallctl_int64(name, NULL));
  49. return 1;
  50. }
  51. static int
  52. ldump(lua_State *L) {
  53. dump_c_mem();
  54. return 0;
  55. }
  56. static int
  57. lcurrent(lua_State *L) {
  58. lua_pushinteger(L, malloc_current_memory());
  59. return 1;
  60. }
  61. static int
  62. ldumpheap(lua_State *L) {
  63. mallctl_cmd("prof.dump");
  64. return 0;
  65. }
  66. static int
  67. lprofactive(lua_State *L) {
  68. bool *pval, active;
  69. if (lua_isnone(L, 1)) {
  70. pval = NULL;
  71. } else {
  72. active = lua_toboolean(L, 1) ? true : false;
  73. pval = &active;
  74. }
  75. bool ret = mallctl_bool("prof.active", pval);
  76. lua_pushboolean(L, ret);
  77. return 1;
  78. }
  79. LUAMOD_API int
  80. luaopen_skynet_memory(lua_State *L) {
  81. luaL_checkversion(L);
  82. luaL_Reg l[] = {
  83. { "total", ltotal },
  84. { "block", lblock },
  85. { "dumpinfo", ldumpinfo },
  86. { "jestat", ljestat },
  87. { "mallctl", lmallctl },
  88. { "dump", ldump },
  89. { "info", dump_mem_lua },
  90. { "current", lcurrent },
  91. { "dumpheap", ldumpheap },
  92. { "profactive", lprofactive },
  93. { NULL, NULL },
  94. };
  95. luaL_newlib(L,l);
  96. return 1;
  97. }