Skip to content

Instantly share code, notes, and snippets.

@yhnu
Created September 25, 2018 08:25
Show Gist options
  • Save yhnu/b092ef02c0307ece810e5279aaab8c9c to your computer and use it in GitHub Desktop.
Save yhnu/b092ef02c0307ece810e5279aaab8c9c to your computer and use it in GitHub Desktop.
slua 自定义luaalloc分析内存
static void *my_alloc(void *ud, void *ptr, size_t osize, size_t nsize) {
(void)ud; (void)osize; /* not used */
if (nsize == 0) {
if (ptr != NULL) {
fprintf(stderr, "lua free %u\n", osize);
}
free(ptr);
return NULL;
}
else
{
// Get Lua Stack
lua_State* L = g_lua_state;
lua_Debug ld, *ar = &ld; stBuf_Init(&g_StackBuf);
stBuf_Push(&g_StackBuf, "[LuaStack]");
if (L != NULL) {
if (lua_getstack(L, 0, ar) == 1) {
for (int i = 0; lua_getstack(L, i, ar); i++)
{
if (!lua_getinfo(L, "nSl", ar))
{
stBuf_Push(&g_StackBuf, "??? |");
continue;
}
if (ar->namewhat[0])
{
stBuf_Push(&g_StackBuf, "<%s> ", ar->namewhat);
}
if ((ar->name) && (ar->name[0]))
{
stBuf_Push(&g_StackBuf, "function %s() ", ar->name);
}
else
{
if (strcmp(ar->what, "main") == 0)
{
stBuf_Push(&g_StackBuf, "mainline of chunk ");
}
else if (strcmp(ar->what, "tail") == 0)
{
stBuf_Push(&g_StackBuf, "tail call ");
}
else
{
stBuf_Push(&g_StackBuf, "unidentifiable function ");
}
}
if (strcmp(ar->what, "C") == 0)
{
stBuf_Push(&g_StackBuf, "in native code ");
}
else if (strcmp(ar->what, "tail") == 0)
{
stBuf_Push(&g_StackBuf, "in Lua code ");
}
else if ((strcmp(ar->source, "=?") == 0) && (ar->currentline == 0))
{
stBuf_Push(&g_StackBuf, "in Lua code (debug info stripped) ");
}
else
{
//stBuf_Push(&g_StackBuf, "in Lua code at %s ", ar->source);
if (ar->currentline != -1)
{
stBuf_Push(&g_StackBuf, ":%d ", ar->currentline);
}
stBuf_Push(&g_StackBuf, "%s() ", ar->name);
}
stBuf_Push(&g_StackBuf, "|");
}
}
else {
stBuf_Push(&g_StackBuf, "lua_getstack ERROR");
}
}
else {
stBuf_Push(&g_StackBuf, "lua_State is NULL");
}
if (osize) {
if (osize < nsize)
{
fprintf(stderr, "lua alloc %u * %s * ", nsize - osize, g_StackBuf.dat);
if(L) luv_lua_debug_stackdump(L, "XStackWalk", '|');
fprintf(stderr, "\n");
}
else
{
fprintf(stderr, "lua free %u\n", osize - nsize);
}
}
else {
fprintf(stderr, "lua alloc %u * %s * ", nsize, g_StackBuf.dat);
if (L) luv_lua_debug_stackdump(L, "[XStack]", '|');
fprintf(stderr, "\n");
}
return realloc(ptr, nsize);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment