From 67ec4accb9ca59780944fa015983379651a63961 Mon Sep 17 00:00:00 2001 From: Michal Moskal Date: Wed, 13 Dec 2017 15:28:52 +0000 Subject: [PATCH] Monitor memory usage and panic on over 8MB used --- libs/core/linux.cpp | 25 +++++++++++++++++++++++-- libs/core/png.cpp | 2 +- libs/core/pxt.h | 2 ++ 3 files changed, 26 insertions(+), 3 deletions(-) diff --git a/libs/core/linux.cpp b/libs/core/linux.cpp index 68caa628..5e7bcfa4 100644 --- a/libs/core/linux.cpp +++ b/libs/core/linux.cpp @@ -13,14 +13,35 @@ #include #include #include +#include #define THREAD_DBG(...) +#define MALLOC_LIMIT (8 * 1024 * 1024) +#define MALLOC_CHECK_PERIOD (1024 * 1024) + +void *xmalloc(size_t sz) { + static size_t allocBytes = 0; + allocBytes += sz; + if (allocBytes >= MALLOC_CHECK_PERIOD) { + allocBytes = 0; + auto info = mallinfo(); + DMESG("malloc used: %d kb", info.uordblks / 1024); + if (info.uordblks > MALLOC_LIMIT) { + target_panic(904); + } + } + auto r = malloc(sz); + if (r == NULL) + target_panic(905); // shouldn't happen + return r; +} + void *operator new(size_t size) { - return malloc(size); + return xmalloc(size); } void *operator new[](size_t size) { - return malloc(size); + return xmalloc(size); } void operator delete(void *p) { diff --git a/libs/core/png.cpp b/libs/core/png.cpp index 90674728..9932a6bc 100644 --- a/libs/core/png.cpp +++ b/libs/core/png.cpp @@ -88,7 +88,7 @@ Image unpackPNG(Buffer png) { uint32_t byteW = (hd.width + 7) >> 3; uint32_t expSize = (byteW + 1) * hd.height; unsigned long sz = expSize; - uint8_t *tmp = (uint8_t *)malloc(sz); + uint8_t *tmp = (uint8_t *)xmalloc(sz); int code = uncompress(tmp, &sz, png->data + sizeof(hd), hd.lenIDAT); if (code != 0) { DMESG("PNG: zlib failed: %d", code); diff --git a/libs/core/pxt.h b/libs/core/pxt.h index 0c62ad43..8bd3b92c 100644 --- a/libs/core/pxt.h +++ b/libs/core/pxt.h @@ -3,6 +3,8 @@ #include "pxtbase.h" +void *xmalloc(size_t sz); + namespace pxt { void raiseEvent(int id, int event); int allocateNotifyEvent();