util.c (1461B)
1 #include <signal.h> 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <string.h> 5 #include <unistd.h> 6 7 #define allocztn(type, n) allocz(sizeof(type) * n) 8 #define alloczt(type) allocz(sizeof(type)) 9 10 typedef struct mctx { 11 int ptrc; 12 void **ptrs; 13 } mctx; 14 15 mctx *gctx; 16 17 void * 18 alloczctx(mctx *ctx, const size_t size) { 19 ctx->ptrs = realloc(ctx->ptrs, sizeof(void *) * (ctx->ptrc + 1)); 20 ctx->ptrs[ctx->ptrc] = malloc(size); 21 memset(ctx->ptrs[ctx->ptrc], 0, size); 22 return ctx->ptrs[ctx->ptrc++]; 23 } 24 25 void * 26 realloczctx(mctx *ctx, void *ptr, const size_t size) { 27 if (!ptr) 28 return alloczctx(ctx, size); 29 30 for (int i = 0; i < ctx->ptrc; i++) { 31 if (ctx->ptrs[i] == ptr) { 32 ctx->ptrs[i] = realloc(ctx->ptrs[i], size); 33 //memset(ctx->ptrs[i], 0, size); 34 return ctx->ptrs[i]; 35 } 36 } 37 kill(getpid(), SIGSEGV); 38 } 39 40 void * 41 reallocz(void *ptr, const size_t size) { 42 return realloczctx(gctx, ptr, size); 43 } 44 45 void * 46 allocz(const size_t size) { 47 return alloczctx(gctx, size); 48 } 49 50 mctx * 51 newctx() { 52 mctx *ctx = malloc(sizeof(mctx)); 53 memset(ctx, 0, sizeof(mctx)); 54 return ctx; 55 } 56 57 void 58 freectx(mctx *ctx) { 59 for (int i = 0; i < ctx->ptrc; i++) 60 free(ctx->ptrs[i]); 61 free(ctx->ptrs); 62 free(ctx); 63 } 64 65 char * 66 strslice(char *s, int len) { 67 char *slice = allocz(len + 1); 68 memcpy(slice, s, len); 69 return slice; 70 } 71 72 char * 73 drainfile(FILE *f) { 74 int l; 75 char *file; 76 77 fseek(f, 0, SEEK_END); 78 l = ftell(f); 79 rewind(f); 80 81 file = malloc(l + 1); 82 fread(file, 1, l, f); 83 84 return file; 85 }