Added a memusage tool

This commit is contained in:
2023-01-25 15:11:22 +00:00
parent 9b21bfb53b
commit b2c3dd894c
2 changed files with 114 additions and 0 deletions

72
tools/memusage/main.c Normal file
View File

@@ -0,0 +1,72 @@
#include "repl_tools.h"
#include "toy_memory.h"
#include "toy_console_colors.h"
#include "lib_runner.h"
#include <stdio.h>
#include <stdlib.h>
//tracker allocator
int currentMemoryUsed = 0;
int maxMemoryUsed = 0;
int memoryAllocCalls = 0;
static void* trackerAllocator(void* pointer, size_t oldSize, size_t newSize) {
if (newSize == 0 && oldSize == 0) {
//causes issues, so just skip out with a NO-OP
return NULL;
}
memoryAllocCalls++;
//track the changes
currentMemoryUsed = currentMemoryUsed - oldSize + newSize;
maxMemoryUsed = currentMemoryUsed > maxMemoryUsed ? currentMemoryUsed : maxMemoryUsed;
if (newSize == 0) {
free(pointer);
return NULL;
}
void* mem = realloc(pointer, newSize);
if (mem == NULL) {
fprintf(stderr, TOY_CC_ERROR "[tracker] Memory allocation error (requested %d for %ld, replacing %d)\n" TOY_CC_RESET, (int)newSize, (long int)pointer, (int)oldSize);
exit(-1);
}
return mem;
}
int main(int argc, char* argv[]) {
if (argc <= 1) {
return -1;
}
//setup for runner
Toy_initDriveDictionary();
Toy_Literal driveLiteral = TOY_TO_STRING_LITERAL(Toy_createRefString("scripts"));
Toy_Literal pathLiteral = TOY_TO_STRING_LITERAL(Toy_createRefString("scripts"));
Toy_setLiteralDictionary(Toy_getDriveDictionary(), driveLiteral, pathLiteral);
Toy_freeLiteral(driveLiteral);
Toy_freeLiteral(pathLiteral);
Toy_setMemoryAllocator(trackerAllocator);
//run memory tests
for (int fileCounter = 1; fileCounter < argc; fileCounter++) {
Toy_runSourceFile(argv[fileCounter]);
}
//lib cleanup
Toy_freeDriveDictionary();
//report output
printf("Memory report: %d max bytes, %d calls\n", maxMemoryUsed, memoryAllocCalls);
return 0;
}

42
tools/memusage/makefile Normal file
View File

@@ -0,0 +1,42 @@
CC=gcc
TOY_OUTDIR=out
IDIR+=. ../../source
CFLAGS+=$(addprefix -I,$(IDIR)) -g -Wall -W -Wno-unused-parameter -Wno-unused-function -Wno-unused-variable
LIBS+=-ltoy
ODIR = obj
SRC = $(wildcard *.c)
OBJ = $(addprefix $(ODIR)/,$(SRC:.c=.o))
OUTNAME=toy
OUT=../../$(TOY_OUTDIR)/memusage
all:
cp $(shell find ../../repl/repl_tools*) .
cp $(shell find ../../repl/lib*) .
$(MAKE) build
build: $(OBJ)
echo $(OBJ)
ifeq ($(shell uname),Darwin)
cp $(PWD)/$(TOY_OUTDIR)/lib$(OUTNAME).dylib /usr/local/lib/
$(CC) -DTOY_IMPORT $(CFLAGS) -o $(OUT) $(OBJ) $(LIBS)
else
$(CC) -DTOY_IMPORT $(CFLAGS) -o $(OUT) $(OBJ) -Wl,-rpath,. -L$(realpath $(shell pwd)/../../$(TOY_OUTDIR)) $(LIBS)
endif
$(OBJ): | $(ODIR)
$(ODIR):
mkdir $(ODIR)
$(ODIR)/%.o: %.c
$(CC) -c -o $@ $< $(CFLAGS)
.PHONY: clean
clean:
$(RM) -r $(ODIR)
$(RM) $(shell find ./repl_tools*)
$(RM) $(shell find ./lib*)