From 7c4f56c7177cec952d036ca72858488263615323 Mon Sep 17 00:00:00 2001 From: Randy Jordan Date: Sun, 15 Feb 2026 11:54:20 -0600 Subject: [PATCH] Initial commit --- LICENSE | 21 ++++++++ Makefile | 76 ++++++++++++++++++++++++++ README.md | 24 +++++++++ include/except.h | 103 ++++++++++++++++++++++++++++++++++++ include/mem.h | 33 ++++++++++++ src/except.c | 71 +++++++++++++++++++++++++ src/mem.c | 51 ++++++++++++++++++ tests/01_malloc.c | 28 ++++++++++ tests/02_calloc.c | 30 +++++++++++ tests/03_malloc_softfail.c | 13 +++++ tests/04_malloc_exception.c | 28 ++++++++++ 11 files changed, 478 insertions(+) create mode 100644 LICENSE create mode 100644 Makefile create mode 100644 README.md create mode 100644 include/except.h create mode 100644 include/mem.h create mode 100644 src/except.c create mode 100644 src/mem.c create mode 100644 tests/01_malloc.c create mode 100644 tests/02_calloc.c create mode 100644 tests/03_malloc_softfail.c create mode 100644 tests/04_malloc_exception.c diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..8aa2645 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) [year] [fullname] + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..3b8792f --- /dev/null +++ b/Makefile @@ -0,0 +1,76 @@ +# Compiler Flags +CC := gcc +CFLAGS := -g -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined -fno-omit-frame-pointer +export ASAN_OPTIONS = allocator_may_return_null=1 +# Directory variables +LIBDIR := lib +OBJ := obj +INC := include +SRC := src +TEST := tests + +# Filepath Pattern Matching +LIB := $(LIBDIR)/lib.a +SRCS := $(wildcard $(SRC)/*.c) +OBJS := $(patsubst $(SRC)/%.c, $(OBJ)/%.o, $(SRCS)) +TESTS := $(wildcard $(TEST)/*.c) +TESTBINS := $(patsubst $(TEST)/%.c, $(TEST)/bin/%, $(TESTS)) + +# Commands must be labeled PHONY +.PHONY: all release clean test + +# Compiler Release Flags +release: CFLAGS := -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined -fno-omit-frame-pointer -O2 -DNDEBUG +release: clean $(LIB) + +# Target for compilation. +all: $(LIB) + +# Target / Dependencies +$(LIB): $(OBJS) | $(LIBDIR) + $(RM) $(LIB) + ar -cvrs $@ $^ + +$(OBJ)/%.o: $(SRC)/%.c $(SRC)/%.h | $(OBJ) + $(CC) $(CFLAGS) -c $< -o $@ + +$(OBJ)/%.o: $(SRC)/%.c | $(OBJ) + $(CC) $(CFLAGS) -c $< -o $@ + +$(TEST)/bin/%: $(TEST)/%.c $(LIB) | $(TEST)/bin + $(CC) $(CFLAGS) $< $(LIB) -o $@ + +# Make directories if none. +$(LIBDIR): + mkdir $@ + +$(INC): + mkdir $@ + +$(OBJ): + mkdir $@ + +$(TEST)/bin: + mkdir $@ + +# Run the tests in the bin folder and track results +test: $(LIB) $(TEST)/bin $(TESTBINS) + @SUCCESS_COUNT=0; FAILURE_COUNT=0; \ + for test in $(TESTBINS); do \ + ./$$test; \ + EXIT_CODE=$$?; \ + TEST_NAME=$(notdir $$test); \ + if [ $$EXIT_CODE -eq 0 ]; then \ + echo "\033[0;32m$$TEST_NAME: EXIT CODE: $$EXIT_CODE (SUCCESS)\033[0m"; \ + SUCCESS_COUNT=$$((SUCCESS_COUNT + 1)); \ + else \ + echo "\033[0;31m$$TEST_NAME: EXIT CODE: $$EXIT_CODE (FAILURE)\033[0m"; \ + FAILURE_COUNT=$$((FAILURE_COUNT + 1)); \ + fi; \ + done; \ + echo "\n\nTests completed"; \ + echo "SUCCESS: $$SUCCESS_COUNT"; \ + echo "FAILURE: $$FAILURE_COUNT"; + +clean: + $(RM) -r $(LIBDIR) $(OBJ) $(TEST)/bin/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..ded0f25 --- /dev/null +++ b/README.md @@ -0,0 +1,24 @@ +# mem + +## Description +Simple memory allocator written in C. + +## Table of Contents + +- [Description](#description) +- [Features](#features) +- [Usage](#usage) +- [Credits / Resources](#credits--resources) +- [License](#license) + +## Features / TODOS + +## Usage + +## Credits / Resources +[Tom Preston-Werner README Driven Development](https://tom.preston-werner.com/2010/08/23/readme-driven-development)
+[Make a README](https://www.makeareadme.com/)
+[Choose a LICENSE](https://choosealicense.com/)
+ +## License +This project is licensed under MIT - see the [LICENSE](LICENSE) file for details. diff --git a/include/except.h b/include/except.h new file mode 100644 index 0000000..28813bc --- /dev/null +++ b/include/except.h @@ -0,0 +1,103 @@ +#ifndef EXCEPT_INCLUDED +#define EXCEPT_INCLUDED + +#include +struct Exception { + const char *reason; +}; +typedef struct Exception Exception; + +struct Except_Frame { + struct Except_Frame *prev; + jmp_buf env; + const char *file; + int line; + const struct Exception *exception; +}; +typedef struct Except_Frame Except_Frame; + +enum { + EXCEPT_STATE_ENTERED=0, + EXCEPT_STATE_RAISED, + EXCEPT_STATE_HANDLED, + EXCEPT_STATE_FINALIZED, + EXCEPT_STATE_COUNT }; + +extern struct Except_Frame *except_stack; +extern const struct Exception assert_failed; +void except_raise(const struct Exception *e, const char *file, int line); + +// Try Catch MACROS - LINUX +#define RAISE(e) except_raise(&(e), __FILE__, __LINE__) +#define RERAISE except_raise(except_frame.exception, \ + except_frame.file, except_frame.line) +#define RETURN switch (except_stack = except_stack->prev,0) default: return +#define TRY do { \ + volatile int except_flag; \ + Except_Frame except_frame; \ + except_frame.prev = except_stack; \ + except_stack = &except_frame; \ + except_flag = setjmp(except_frame.env); \ + if (except_flag == EXCEPT_STATE_ENTERED) { +#define EXCEPT(e) \ + if (except_flag == EXCEPT_STATE_ENTERED) except_stack = except_stack->prev; \ + } else if (except_frame.exception == &(e)) { \ + except_flag = EXCEPT_STATE_HANDLED; +#define ELSE \ + if (except_flag == EXCEPT_STATE_ENTERED) except_stack = except_stack->prev; \ + } else { \ + except_flag = EXCEPT_STATE_HANDLED; +#define FINALLY \ + if (except_flag == EXCEPT_STATE_ENTERED) except_stack = except_stack->prev; \ + } { \ + if (except_flag == EXCEPT_STATE_ENTERED) \ + except_flag = EXCEPT_STATE_FINALIZED; +#define END_TRY \ + if (except_flag == EXCEPT_STATE_ENTERED) except_stack = except_stack->prev; \ + } if (except_flag == EXCEPT_STATE_RAISED) RERAISE; \ +} while (0) + + +// Try Catch MACROS - WIN32 +#ifdef WIN32 +#include + +extern int except_index; +extern void except_init(void); +extern void except_push(Except_Frame *fp); +extern void except_pop(void); + +#define RAISE(e) except_raise(&(e), __FILE__, __LINE__) +#define RERAISE except_raise(except_frame.exception, \ + except_frame.file, except_frame.line) +#define RETURN switch (except_pop(),0) default: return +#define TRY do { \ + volatile int except_flag; \ + Except_Frame except_frame; \ + if (except_index == -1) \ + except_init(); \ + except_push(&except_frame); \ + except_flag = setjmp(except_frame.env); \ + if (except_flag == EXCEPT_STATE_ENTERED) { +#define EXCEPT(e) \ + if (except_flag == EXCEPT_STATE_ENTERED) except_pop(); \ + } else if (except_frame.exception == &(e)) { \ + except_flag = EXCEPT_STATE_HANDLED; +#define ELSE \ + if (except_flag == EXCEPT_STATE_ENTERED) except_pop(); \ + } else { \ + except_flag = EXCEPT_STATE_HANDLED; +#define FINALLY \ + if (except_flag == EXCEPT_STATE_ENTERED) except_pop(); \ + } { \ + if (except_flag == EXCEPT_STATE_ENTERED) \ + except_flag = EXCEPT_STATE_FINALIZED; +#define END_TRY \ + if (except_flag == EXCEPT_STATE_ENTERED) except_pop(); \ + } if (except_flag == EXCEPT_STATE_RAISED) RERAISE; \ +} while (0) +#endif + + + +#endif // except.h diff --git a/include/mem.h b/include/mem.h new file mode 100644 index 0000000..6c4dbef --- /dev/null +++ b/include/mem.h @@ -0,0 +1,33 @@ +#ifndef MEM_INCLUDED +#define MEM_INCLUDED + +#include "except.h" // Exceptions +#include // size_t + +/* General Macros*/ +#define MEM_KB(x) ((size_t)(x) * 1024ULL) +#define MEM_MB(x) ((size_t)(x) * 1024ULL * 1024ULL) +#define MEM_GB(x) ((size_t)(x) * 1024ULL * 1024ULL * 1024ULL) +#define MEM_SIZE(x) (ptrdiff_t)sizeof(x) +#define MEM_COUNT(a) (MEM_SIZE(a) / MEM_SIZE(*(a))) +#define MEM_LEN(s) (MEM_COUNT(s) - 1) + +/* Default behavior is to throw exceptions and zero out memory*/ +enum MemFlags { + NOZERO = 1 << 0, /* 0001 */ + SOFT_FAIL = 1 << 1, /* 0010 */ + HARD_FAIL = 1 << 2, /* 0100 */ +}; + +extern const Exception OOM; // Out of memory + +extern void *mem_alloc (int flags, size_t nbytes, const char *file, int line); +extern void mem_free(void *ptr, const char *file, int line); +extern void *mem_resize(int flags, void *ptr, size_t nbytes, const char *file, int line); + +#define ALLOC(flags, nbytes) mem_alloc((flags), (nbytes), __FILE__, __LINE__) +#define FREE(ptr) ((void)(mem_free((ptr), __FILE__, __LINE__), (ptr) = 0)) +#define RESIZE(flags, ptr, nbytes) ((ptr) = mem_resize((flags), (ptr), \ + (nbytes), __FILE__, __LINE__)) + +#endif diff --git a/src/except.c b/src/except.c new file mode 100644 index 0000000..088da65 --- /dev/null +++ b/src/except.c @@ -0,0 +1,71 @@ +#include +#include +#include // for now +#include "../include/except.h" + +struct Except_Frame *except_stack = NULL; +void except_raise(const struct Exception *e, const char *file,int line) +{ +#ifdef WIN32 + struct Except_Frame *p; + + if (except_index == -1) + except_init(); + p = TlsGetValue(except_index); +#else + struct Except_Frame *p = except_stack; +#endif + assert(e); + if (p == NULL) { + fprintf(stderr, "Uncaught exception"); + if (e->reason) + fprintf(stderr, " %s", e->reason); + else + fprintf(stderr, " at 0x%p", (void*)e); + if (file && line > 0) + fprintf(stderr, " raised at %s:%d\n", file, line); + fprintf(stderr, "aborting...\n"); + fflush(stderr); + abort(); + } + p->exception = e; + p->file = file; + p->line = line; +#ifdef WIN32 + except_pop(); +#else + except_stack = except_stack->prev; +#endif + longjmp(p->env, EXCEPT_STATE_RAISED); +} +#ifdef WIN32 +_CRTIMP void __cdecl _assert(void *, void *, unsigned); +#undef assert +#define assert(e) ((e) || (_assert(#e, __FILE__, __LINE__), 0)) + +int except_index = -1; +void except_init(void) { + BOOL cond; + + except_index = TlsAlloc(); + assert(except_index != TLS_OUT_OF_INDEXES); + cond = TlsSetValue(except_index, NULL); + assert(cond == TRUE); +} + +void Except_push(Except_Frame *fp) { + BOOL cond; + + fp->prev = TlsGetValue(except_index); + cond = TlsSetValue(except_index, fp); + assert(cond == TRUE); +} + +void Except_pop(void) { + BOOL cond; + Except_Frame *tos = TlsGetValue(Except_index); + + cond = TlsSetValue(except_index, tos->prev); + assert(cond == TRUE); +} +#endif diff --git a/src/mem.c b/src/mem.c new file mode 100644 index 0000000..00a84fd --- /dev/null +++ b/src/mem.c @@ -0,0 +1,51 @@ +#include +#include +#include + +#include "../include/except.h" +#include "../include/mem.h" +#include // for now + +const Exception OOM = { "Out of Memory" }; +#define MEM_ENOMEM 12 + +void *mem_alloc(int flags, size_t nbytes, const char *file, int line){ + void *ptr; + assert(nbytes > 0); + ptr = malloc(nbytes); + if (ptr == NULL){ // OOM check flags for how to handle. + if (flags & SOFT_FAIL) return 0; + if (flags & HARD_FAIL) exit(MEM_ENOMEM); + + if (file == NULL) // Wasn't called by macro + RAISE(OOM); // Out of Memory Exception + else // Called by macro + except_raise(&OOM, file, line); + } + return flags&NOZERO ? ptr : memset(ptr, 0, nbytes); +} + +void mem_free(void *ptr, const char *file, int line) { + (void) file; + (void) line; + if (ptr){ + free(ptr); + } +} + +void *mem_resize(int flags, void *ptr, size_t nbytes,const char *file, int line) { + void *p = realloc(ptr, nbytes); + + if (p == NULL){ // OOM check flags for how to handle. + if(flags & SOFT_FAIL) return 0; + if(flags & HARD_FAIL) exit(MEM_ENOMEM); + + if (file == NULL) // Wasn't called by macro + RAISE(OOM); // Out of memory exception + else // Called by macro + except_raise(&OOM, file, line); + } + ptr = p; + return ptr; +} + diff --git a/tests/01_malloc.c b/tests/01_malloc.c new file mode 100644 index 0000000..11ec0db --- /dev/null +++ b/tests/01_malloc.c @@ -0,0 +1,28 @@ +#define DEBUG +#include +#include +#include +#include "../include/mem.h" + +int mem_is_zero(const void *ptr, size_t nbytes) { + assert(ptr); + assert(nbytes > 0); + static const unsigned char zero_block[1024] = {0}; + while (nbytes >= sizeof(zero_block)) { + if (memcmp(ptr, zero_block, sizeof(zero_block)) != 0) + return 0; + ptr = (const unsigned char *)ptr + sizeof(zero_block); + nbytes -= sizeof(zero_block); + } + if (nbytes > 0 && memcmp(ptr, zero_block, nbytes) != 0) + return 0; + return 1; +} + +int main(void){ + size_t nbytes = 20; + void *ptr = ALLOC(0, nbytes); + assert(ptr != NULL); + assert( mem_is_zero(ptr, nbytes)); + return EXIT_SUCCESS; +} diff --git a/tests/02_calloc.c b/tests/02_calloc.c new file mode 100644 index 0000000..4eb5a92 --- /dev/null +++ b/tests/02_calloc.c @@ -0,0 +1,30 @@ +#define DEBUG +#include +#include +#include + +#include "../include/mem.h" + +int mem_is_zero(const void *ptr, size_t nbytes) { + assert(ptr); + assert(nbytes > 0); + static const unsigned char zero_block[1024] = {0}; + while (nbytes >= sizeof(zero_block)) { + if (memcmp(ptr, zero_block, sizeof(zero_block)) != 0) + return 0; + ptr = (const unsigned char *)ptr + sizeof(zero_block); + nbytes -= sizeof(zero_block); + } + if (nbytes > 0 && memcmp(ptr, zero_block, nbytes) != 0) + return 0; + return 1; +} + + +int main(void){ + size_t nbytes = 20; + void *ptr = ALLOC(NOZERO, nbytes); + assert(ptr != NULL); + assert( !mem_is_zero(ptr, nbytes)); + return EXIT_SUCCESS; +} diff --git a/tests/03_malloc_softfail.c b/tests/03_malloc_softfail.c new file mode 100644 index 0000000..9365335 --- /dev/null +++ b/tests/03_malloc_softfail.c @@ -0,0 +1,13 @@ +#define DEBUG +#include +#include +#include +#include "../include/mem.h" + + +int main(void){ + size_t nbytes = MEM_GB(1024); + void *ptr = ALLOC(SOFT_FAIL, nbytes); + assert(ptr == NULL); + return EXIT_SUCCESS; +} diff --git a/tests/04_malloc_exception.c b/tests/04_malloc_exception.c new file mode 100644 index 0000000..7d0bb71 --- /dev/null +++ b/tests/04_malloc_exception.c @@ -0,0 +1,28 @@ +#define DEBUG +#include +#include +#include +#include "../include/mem.h" + +int main(void){ + size_t nbytes = MEM_GB(1024); + void *buf; + TRY { + buf = ALLOC(0,nbytes); /* try 1GB */ + if (!buf) + RAISE(OOM); + free(buf); + } + EXCEPT(OOM) { + /* handle memory failure gracefully */ + fprintf(stderr, "Caught: %s\n", OOM.reason); + return EXIT_SUCCESS; /* requested behavior */ + } + FINALLY { + /* cleanup if needed, runs always */ + if (buf) free(buf); + } + END_TRY; + + return EXIT_FAILURE; /* shouldn't reach here for this example */ + }