123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164 |
- #include "config.h"
- #include <stdlib.h>
- #include <string.h>
- #include "memory_mosq.h"
- #ifdef REAL_WITH_MEMORY_TRACKING
- # if defined(__APPLE__)
- # include <malloc/malloc.h>
- # define malloc_usable_size malloc_size
- # elif defined(__FreeBSD__)
- # include <malloc_np.h>
- # else
- # include <malloc.h>
- # endif
- #endif
- #ifdef REAL_WITH_MEMORY_TRACKING
- static unsigned long memcount = 0;
- static unsigned long max_memcount = 0;
- #endif
- #ifdef WITH_BROKER
- static size_t mem_limit = 0;
- void memory__set_limit(size_t lim)
- {
- mem_limit = lim;
- }
- #endif
- void *mosquitto__calloc(size_t nmemb, size_t size)
- {
- void *mem;
- #ifdef REAL_WITH_MEMORY_TRACKING
- if(mem_limit && memcount + size > mem_limit){
- return NULL;
- }
- #endif
- mem = calloc(nmemb, size);
- #ifdef REAL_WITH_MEMORY_TRACKING
- if(mem){
- memcount += malloc_usable_size(mem);
- if(memcount > max_memcount){
- max_memcount = memcount;
- }
- }
- #endif
- return mem;
- }
- void mosquitto__free(void *mem)
- {
- #ifdef REAL_WITH_MEMORY_TRACKING
- if(!mem){
- return;
- }
- memcount -= malloc_usable_size(mem);
- #endif
- free(mem);
- }
- void *mosquitto__malloc(size_t size)
- {
- void *mem;
- #ifdef REAL_WITH_MEMORY_TRACKING
- if(mem_limit && memcount + size > mem_limit){
- return NULL;
- }
- #endif
- mem = malloc(size);
- #ifdef REAL_WITH_MEMORY_TRACKING
- if(mem){
- memcount += malloc_usable_size(mem);
- if(memcount > max_memcount){
- max_memcount = memcount;
- }
- }
- #endif
- return mem;
- }
- #ifdef REAL_WITH_MEMORY_TRACKING
- unsigned long mosquitto__memory_used(void)
- {
- return memcount;
- }
- unsigned long mosquitto__max_memory_used(void)
- {
- return max_memcount;
- }
- #endif
- void *mosquitto__realloc(void *ptr, size_t size)
- {
- void *mem;
- #ifdef REAL_WITH_MEMORY_TRACKING
- if(mem_limit && memcount + size > mem_limit){
- return NULL;
- }
- if(ptr){
- memcount -= malloc_usable_size(ptr);
- }
- #endif
- mem = realloc(ptr, size);
- #ifdef REAL_WITH_MEMORY_TRACKING
- if(mem){
- memcount += malloc_usable_size(mem);
- if(memcount > max_memcount){
- max_memcount = memcount;
- }
- }
- #endif
- return mem;
- }
- char *mosquitto__strdup(const char *s)
- {
- char *str;
- #ifdef REAL_WITH_MEMORY_TRACKING
- if(mem_limit && memcount + strlen(s) > mem_limit){
- return NULL;
- }
- #endif
- str = strdup(s);
- #ifdef REAL_WITH_MEMORY_TRACKING
- if(str){
- memcount += malloc_usable_size(str);
- if(memcount > max_memcount){
- max_memcount = memcount;
- }
- }
- #endif
- return str;
- }
|