From ffe2af37fef7139d35a6a7c1a5ec620f529fdcbc Mon Sep 17 00:00:00 2001 From: Randy Jordan Date: Thu, 3 Jul 2025 19:04:47 -0500 Subject: [PATCH] Initial commit --- LICENSE | 21 +++++++++++++ Makefile | 76 ++++++++++++++++++++++++++++++++++++++++++++ README.md | 40 ++++++++++++++++++++++++ include/except.h | 80 +++++++++++++++++++++++++++++++++++++++++++++++ include/mem.h | 24 ++++++++++++++ src/except.c | 30 ++++++++++++++++++ src/mem.c | 54 ++++++++++++++++++++++++++++++++ tests/01_alloc.c | 29 +++++++++++++++++ tests/02_new.c | 29 +++++++++++++++++ tests/03_calloc.c | 29 +++++++++++++++++ tests/04_new0.c | 29 +++++++++++++++++ 11 files changed, 441 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_alloc.c create mode 100644 tests/02_new.c create mode 100644 tests/03_calloc.c create mode 100644 tests/04_new0.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..62673fc --- /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 + +# 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 -n "\033[0;32m$$TEST_NAME: EXIT CODE: $$EXIT_CODE (SUCCESS)\033[0m"\\n; \ + SUCCESS_COUNT=$$((SUCCESS_COUNT + 1)); \ + else \ + echo -n "\033[0;31m$$TEST_NAME: EXIT CODE: $$EXIT_CODE (FAILURE)\033[0m"\\n; \ + 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..43dc452 --- /dev/null +++ b/README.md @@ -0,0 +1,40 @@ +# mem + +## Description +Simple memory allocator library written in C.
+Depends on [except](https://myrepos.dev/Randy-Jordan/except) + +## Table of Contents + +- [Description](#description) +- [Features](#features) +- [Installation](#installation) +- [Usage](#usage) +- [Credits / Resources](#credits--resources) +- [License](#license) + +## Features + +- [x] Exceptions +- [x] Free +- [x] Malloc +- [x] Calloc +- [x] Realloc +- [x] Macros +- [ ] Arenas + +## Usage + +`make test` to build and test project.
+`make` to build the project. + + +## Credits / Resources +I found these resources extremely helpful.
+ +[C Interfaces and Implementations - David Hanson](https://github.com/drh/cii) + + +## 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..3ccbf3a --- /dev/null +++ b/include/except.h @@ -0,0 +1,80 @@ +#ifndef EXCEPT_INCLUDED +#define EXCEPT_INCLUDED + +#include + +struct Exception { + const char *reason; +}; +typedef struct Exception Exception; + +struct ExceptFrame { + struct ExceptFrame *prev; // Exception Stack + jmp_buf env; // Enviroment Buffer + const char *file; // Exception File + int line; // Exception Line + const Exception *exception; // Exception Reason +}; +typedef struct ExceptFrame ExceptFrame; + +// Exception States +enum { EXCEPT_ENTERED=0, EXCEPT_RAISED, EXCEPT_HANDLED, EXCEPT_FINALIZED}; + +void except_raise(const Exception *e, const char *file,int line); // Raise exceptions + +// External declarations +extern ExceptFrame *except_stack; // Global exception stack +extern const Exception assert_failed; // Forward declaration for assert. +extern void asserted(int e); + +#ifdef NDEBUG +#define ASSERTED(e) ((void)0) +#else +#define ASSERTED(e) ((void)((e)||(RAISE(assert_failed),0))) +#endif + +// Raise an Exception. +#define RAISE(e) except_raise(&(e), __FILE__, __LINE__) + +// Reraise the currect exception. +#define RERAISE except_raise(except_frame.exception, \ + except_frame.file, except_frame.line) + +// Switch to the previous exception frame and return. +#define RETURN switch (except_stack = except_stack->prev,0) default: return + +// Start a try block. +#define TRY do { \ + volatile int except_flag; \ + ExceptFrame except_frame; \ + except_frame.prev = except_stack; \ + except_stack = &except_frame; \ + except_flag = setjmp(except_frame.env); \ + if (except_flag == EXCEPT_ENTERED) { + +// Handle specific example. +#define EXCEPT(e) \ + if (except_flag == EXCEPT_ENTERED) except_stack = except_stack->prev; \ + } else if (except_frame.exception == &(e)) { \ + except_flag = EXCEPT_HANDLED; + +// Catch all other exceptions. +#define ELSE \ + if (except_flag == EXCEPT_ENTERED) except_stack = except_stack->prev; \ + } else { \ + except_flag = EXCEPT_HANDLED; + +// Execute finalization code. +#define FINALLY \ + if (except_flag == EXCEPT_ENTERED) except_stack = except_stack->prev; \ + } { \ + if (except_flag == EXCEPT_ENTERED) \ + except_flag = EXCEPT_FINALIZED; + +// End Try block. +#define END_TRY \ + if (except_flag == EXCEPT_ENTERED) except_stack = except_stack->prev; \ + } if (except_flag == EXCEPT_RAISED) RERAISE; \ +} while (0) + +#endif diff --git a/include/mem.h b/include/mem.h new file mode 100644 index 0000000..d1ec329 --- /dev/null +++ b/include/mem.h @@ -0,0 +1,24 @@ +#ifndef MEM_INCLUDED +#define MEM_INCLUDED + +#include "except.h" +#include + +#define SIZEOF(x) (ptrdiff_t)sizeof(x) +#define NELEMS(a) (sizeof(a) / sizeof(*(a))) +#define LEN(s) (NELEMS(s) - 1) + +extern const Exception out_of_memory; // OOM Exception +extern void *mem_alloc (size_t nbytes,const char *file, int line); +extern void *mem_calloc(size_t count, size_t nbytes,const char *file, int line); +extern void mem_free(void *ptr, const char *file, int line); +extern void *mem_realloc(void *ptr, size_t nbytes, const char *file, int line); + +#define ALLOC(nbytes) mem_alloc((nbytes), __FILE__, __LINE__) +#define CALLOC(count, nbytes) mem_calloc((count), (nbytes), __FILE__, __LINE__) +#define NEW(p) ((p) = ALLOC((size_t)sizeof *(p))) +#define NEW0(p) ((p) = CALLOC(1, (size_t)sizeof *(p))) +#define FREE(ptr) ((void)(mem_free((ptr), __FILE__, __LINE__), (ptr) = 0)) +#define REALLOC(ptr, nbytes) ((ptr) = mem_realloc((ptr), (nbytes), __FILE__, __LINE__)) + +#endif diff --git a/src/except.c b/src/except.c new file mode 100644 index 0000000..6d3c652 --- /dev/null +++ b/src/except.c @@ -0,0 +1,30 @@ +#include "../include/except.h" +#include +#include + +ExceptFrame *except_stack = NULL; // Global exception stack. +const Exception assert_failed = { "Assertion Failure!" }; // If ASSERT fails. + +void except_raise(const Exception *e, const char *file,int line) { + // An exception was raised, grab the exception stack. + ExceptFrame *p = except_stack; + asserted(e != NULL); // Ensure exception pointer is not NULL + if (p == NULL) { // Uncaught Exception + const char *msg = e->reason ? e->reason : "Uncaught Exception!"; + fprintf(stderr,"\033[31m%s | Address: 0x%p | Raised at %s@%d \033[0m" ,msg,(void *)e,file,line); + fflush(stderr); + abort(); + } + // Set the exception details to the current frame. + p->exception = e; // Exception reason + p->file = file; + p->line = line; + // Move to the previous frame in the stack. + except_stack = except_stack->prev; + // Jump to the saved context environment. + longjmp(p->env, EXCEPT_RAISED); +} +void asserted(int e) { + ASSERTED(e); + (void)e; +} diff --git a/src/mem.c b/src/mem.c new file mode 100644 index 0000000..270587e --- /dev/null +++ b/src/mem.c @@ -0,0 +1,54 @@ +#include "../include/except.h" +#include "../include/mem.h" +#include + +const Exception out_of_memory = { "Out Of Memory" }; // OOM Exception. + +void *mem_alloc(size_t nbytes, const char *file, int line){ + void *ptr; // Memory to allocate. + ASSERTED(nbytes > 0); + ptr = malloc(nbytes); // Attempt allocation. + if (ptr == NULL){ // Out of memory, raise exception . + if (file == NULL) // Wasn't called by macro. + RAISE(out_of_memory); + else // Called by macro. + except_raise(&out_of_memory, file, line); + } + // Success, return allocated memory. + return ptr; +} +void *mem_calloc(size_t count, size_t nbytes,const char *file, int line) { + void *ptr; // Memory to allocate. + ASSERTED(count > 0); + ASSERTED(nbytes > 0); + ptr = calloc(count, nbytes);// Attempt allocation and zero out memory. + if (ptr == NULL){ // Out of memory raise exception. + if (file == NULL) // Wasn't called by macro. + RAISE(out_of_memory); + else // Was called by macro. + except_raise(&out_of_memory, file, line); + } + // Success, return allocated and zeroed memory. + return ptr; +} +void mem_free(void *ptr, const char *file, int line) { + (void) file; + (void) line; + if (ptr){// If we have valid pointer, free and null. + free(ptr); + ptr = NULL; + } +} +void *mem_realloc(void *ptr, size_t nbytes, const char *file, int line) { + ASSERTED(ptr); + ASSERTED(nbytes > 0); + ptr = realloc(ptr, nbytes); // Attempt reallocation. + if (ptr == NULL){ // Out of memory, raise exception. + if (file == NULL) // Wasn't called by macro. + RAISE(out_of_memory); + else // Called by macro. + except_raise(&out_of_memory, file, line); + } + // Success, return reallocated memory. + return ptr; +} diff --git a/tests/01_alloc.c b/tests/01_alloc.c new file mode 100644 index 0000000..302c28d --- /dev/null +++ b/tests/01_alloc.c @@ -0,0 +1,29 @@ +#define DEBUG +#include "../include/except.h" +#include "../include/mem.h" +#include +#include +#include +#include + +#define BUFSZ 100 + +static bool isZeroed(void *memory, unsigned int size) +{ + unsigned char *mm = (unsigned char*)memory; + + // early out for empty size + if (size == 0) return true; + + return (*mm == 0) && memcmp(mm, mm + 1, size - 1) == 0; +} + +int main(void){ + + char *buf = ALLOC(BUFSZ); + ASSERTED(buf != NULL); + ASSERTED(isZeroed(buf, BUFSZ) == false); + FREE(buf); + ASSERTED(buf == NULL); + return EXIT_SUCCESS; +} diff --git a/tests/02_new.c b/tests/02_new.c new file mode 100644 index 0000000..5e630a0 --- /dev/null +++ b/tests/02_new.c @@ -0,0 +1,29 @@ +#define DEBUG +#include "../include/except.h" +#include "../include/mem.h" +#include +#include +#include +#include + +#define BUFSZ 100 + +static bool isZeroed(void *memory, unsigned int size) +{ + unsigned char *mm = (unsigned char*)memory; + + // early out for empty size + if (size == 0) return true; + + return (*mm == 0) && memcmp(mm, mm + 1, size - 1) == 0; +} + +int main(void){ + + char *buf = NEW(buf); + ASSERTED(buf != NULL); + ASSERTED(isZeroed(buf, BUFSZ) == false); + FREE(buf); + ASSERTED(buf == NULL); + return EXIT_SUCCESS; +} diff --git a/tests/03_calloc.c b/tests/03_calloc.c new file mode 100644 index 0000000..177c06d --- /dev/null +++ b/tests/03_calloc.c @@ -0,0 +1,29 @@ +#define DEBUG +#include "../include/except.h" +#include "../include/mem.h" +#include +#include +#include +#include + +#define BUFSZ 100 + +static bool isZeroed(void *memory, unsigned int size) +{ + unsigned char *mm = (unsigned char*)memory; + + // early out for empty size + if (size == 0) return true; + + return (*mm == 0) && memcmp(mm, mm + 1, size - 1) == 0; +} + +int main(void){ + + char *buf = CALLOC(BUFSZ, SIZEOF(char *)); + ASSERTED(buf != NULL); + ASSERTED(isZeroed(buf, BUFSZ) == true); + FREE(buf); + ASSERTED(buf == NULL); + return EXIT_SUCCESS; +} diff --git a/tests/04_new0.c b/tests/04_new0.c new file mode 100644 index 0000000..cff82f7 --- /dev/null +++ b/tests/04_new0.c @@ -0,0 +1,29 @@ +#define DEBUG +#include "../include/except.h" +#include "../include/mem.h" +#include +#include +#include +#include + +#define BUFSZ 100 + +static bool isZeroed(void *memory, unsigned int size) +{ + unsigned char *mm = (unsigned char*)memory; + + // early out for empty size + if (size == 0) return true; + + return (*mm == 0) && memcmp(mm, mm + 1, size - 1) == 0; +} + +int main(void){ + + char *buf = NEW0(buf); + ASSERTED(buf != NULL); + ASSERTED(isZeroed(buf,SIZEOF(char)) == true); + FREE(buf); + ASSERTED(buf == NULL); + return EXIT_SUCCESS; +}