From ca2d1f278cf0d30bbcf938e02c173f44fa3b9e05 Mon Sep 17 00:00:00 2001 From: Sadeep Madurange Date: Thu, 5 Mar 2026 21:31:40 +0800 Subject: Define _xmalloc and _xrealloc. --- .gitignore | 1 + main.c | 45 +++++++++++++++++++++++++++++++-------------- 2 files changed, 32 insertions(+), 14 deletions(-) diff --git a/.gitignore b/.gitignore index b398ecb..d6c576f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ cvn .cvn/ +top_dir/ **/*.o **/*.out diff --git a/main.c b/main.c index 97083ba..a8e02b7 100644 --- a/main.c +++ b/main.c @@ -6,16 +6,21 @@ #include #include #include - #include #include #define REPO ".cvn" #define INDEX "index" +#define MALLOC(s) _xmalloc((s), __FILE__, __LINE__) +#define REALLOC(p, s) _xrealloc((p), (s), __FILE__, __LINE__) + static inline void init(int argc, char *argv[]); static inline void status(int argc, char *argv[]); +static inline void *_xmalloc(size_t s, const char *file, int line); +static inline void *_xrealloc(void *ptr, size_t s, const char *file, int line); + static inline void traverse(void); static inline uint8_t ignore(const char *path); @@ -49,6 +54,24 @@ int main(int argc, char *argv[]) return 0; } + +static inline void *_xmalloc(size_t s, const char *file, int line) +{ + void *p = malloc(s); + if (!p) + err(1, "%s:%d: malloc", file, line); + return p; +} + +static inline void *_xrealloc(void *ptr, size_t s, + const char *file, int line) +{ + void *p = realloc(ptr, s); + if (!p) + err(1, "%s:%d: realloc", file, line); + return p; +} + static inline void init(int argc, char *argv[]) { char *branch; @@ -79,7 +102,8 @@ static inline void init(int argc, char *argv[]) return; } - if ((idx_fd = openat(repo_fd, INDEX, O_WRONLY | O_CREAT | O_EXCL, 0644)) == -1) { + if ((idx_fd = openat(repo_fd, INDEX, + O_WRONLY | O_CREAT | O_EXCL, 0644)) == -1) { if (errno != EEXIST) { close(repo_fd); perror("Failed to create index"); @@ -110,17 +134,12 @@ static inline void traverse(void) char *path, *rel_path; struct stat st; struct dirent *entry; - int i, subdirs_len; - char **subdirs; + char **subdirs, levels; + int i, subdirs_len, levels_len; i = 0; - // On 64-bit systems: 512 * 8 (ptr size) = 4096 - typical page size / 64 cache lines - // Page-aligned buffers that fit in CPU cache lines reduce mmu overhead (play well - // with the CPU's TLB (Tranlation Lookaside Buffer). - subdirs_len = 512; - subdirs = malloc(sizeof(subdirs[0]) * subdirs_len); - if (!subdirs) - err(1, "malloc() failed"); + subdirs_len = 512, levels_len = 512; + subdirs = MALLOC(sizeof(subdirs[0]) * subdirs_len); subdirs[i++] = strdup("."); while (i > 0) { @@ -144,9 +163,7 @@ static inline void traverse(void) if (S_ISDIR(st.st_mode)) { if (i >= subdirs_len) { subdirs_len <<= 1; - subdirs = realloc(subdirs, sizeof(subdirs[0]) * subdirs_len); - if (!subdirs) - err(1, "realloc() failed"); + subdirs = REALLOC(subdirs, sizeof(subdirs[0]) * subdirs_len); } subdirs[i++] = rel_path; } else { -- cgit v1.2.3