diff --git a/Makefile b/Makefile index 60d3a9760..d9540d963 100644 --- a/Makefile +++ b/Makefile @@ -157,6 +157,10 @@ ifeq ($(ARCH),faulty) DUMMY_EXTRA+=test/pico_faulty.o endif +ifdef CHECK_MEM + CFLAGS+=-DCHECK_MEM -rdynamic +endif + ifeq ($(ARCH),msp430) CFLAGS+=-DMSP430 endif diff --git a/include/pico_config.h b/include/pico_config.h index b37ba63c0..60f2af946 100644 --- a/include/pico_config.h +++ b/include/pico_config.h @@ -9,10 +9,15 @@ #ifndef __KERNEL__ #include #include +#include #include #else #include #endif +#ifdef __linux__ +#include +#endif + #if defined __IAR_SYSTEMS_ICC__ || defined ATOP # define PACKED_STRUCT_DEF __packed struct @@ -51,6 +56,8 @@ #define long_be(x) (x) #define long_long_be(x) (x) + + static inline uint16_t short_from(void *_p) { unsigned char *p = (unsigned char *)_p; @@ -163,7 +170,6 @@ static inline uint64_t long_long_be(uint64_t le) # endif /* BYTESWAP_GCC */ #endif - /* Mockables */ #if defined UNIT_TEST # define MOCKABLE __attribute__((weak)) @@ -229,7 +235,43 @@ static inline uint64_t long_long_be(uint64_t le) # include "arch/pico_posix.h" #endif -#ifdef PICO_SUPPORT_MM + +#ifdef CHECK_MEM +extern int start_failing_mallocs; + +static inline void log_malloc(const char* filename, const char* message) +{ + FILE * file; + file = fopen(filename, "a"); + fprintf(file, message); + fclose(file); +} + +static inline void append_backtrace(const char* filename) +{ + void *array[10]; + size_t size; + int fd; + FILE * file; + file = fopen(filename, "a"); + fd = fileno(file); + + fprintf(file, "Backtrace:\n"); + fseek(file, 0, SEEK_END); + + size = backtrace(array, 10); + backtrace_symbols_fd(array, size, fd); + fprintf(file, "\n"); + + fclose(file); +} + +#define PICO_ZALLOC(x) \ +((start_failing_mallocs && (((double)(rand())/(double)RAND_MAX) < 0.4)) \ +? (log_malloc("mem_test.log", "Malloc FAILED\n"), append_backtrace("mem_test.log"), NULL) \ +: (log_malloc("mem_test.log", "Malloc Succeeded\n"), append_backtrace("mem_test.log"), pico_zalloc(x))) +#define PICO_FREE(x) pico_free(x) +#elif defined PICO_SUPPORT_MM #define PICO_ZALLOC(x) pico_mem_zalloc(x) #define PICO_FREE(x) pico_mem_free(x) #else diff --git a/stack/pico_stack.c b/stack/pico_stack.c index 9d86d1379..bbca72f98 100644 --- a/stack/pico_stack.c +++ b/stack/pico_stack.c @@ -38,7 +38,6 @@ # define MOCKABLE #endif - volatile pico_time pico_tick; volatile pico_err_t pico_err; @@ -857,6 +856,20 @@ uint32_t pico_timer_add_hashed(pico_time expire, void (*timer)(pico_time, void * int MOCKABLE pico_stack_init(void) { + +#ifdef CHECK_MEM + //New log for malloc information + fopen("mem_test.log", "w"); + + //Set rand seed + char *buf = getenv("MEM_TEST_SEED"); + if(buf!=NULL){ + srand(atoi(buf)); + } + else + srand(1); +#endif + #ifdef PICO_SUPPORT_ETH pico_protocol_init(&pico_proto_ethernet); #endif @@ -917,9 +930,11 @@ int MOCKABLE pico_stack_init(void) pico_aodv_init(); #endif + pico_stack_tick(); pico_stack_tick(); pico_stack_tick(); + return 0; }