Building a Hacker’s ls

A Case Study in Systems Hacking, Test Harnesses, and Fixing POSIX Reality

In Chapter 1 of Advanced Programming in the UNIX Environment (affectionately known as “APUE”), the authors show how to read a directory using twenty lines of clean C. It revolves around opendir() and readdir(), streaming entries straight to stdout as the kernel yields them. Forgive me if I’m foreshortening the code, but I’m doing this from memory (lost the book somewhere).

/* Stevens APUE Figure 1.1 minimal baseline - best guess */
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    DIR *dp;
    struct dirent *dirp;
    if (argc != 2)
        exit(1);
    if ((dp = opendir(argv[1])) == NULL)
        exit(1);
    while ((dirp = readdir(dp)) != NULL)
        printf("%s\n", dirp->d_name);
    closedir(dp);
    exit(0);
}

The snippet is fairly simple, butstandard readdir() iteration is blind to everything modern developers care about: sorting, visual hierarchies, version control state, file allocation efficiency, and platform-specific extended metadata.

To turn this academic skeleton into a power tool, I wrote hls – a modern, hacker-grade replacement written in strict C99 with no external dependencies.

What follows is an unvarnished case study in systems engineering: the ambitious architecture, the test harness built to verify it, the runtime collisions the machine threw right back in my face, and the low-level surgery needed to make it rock solid.

Part 1: Design & Initial Architecture

To keep hls fast and portable across Darwin (macOS) and Linux (since I use both), I avoided heavy external libraries like libgit2 or libmagic. Everything is built with direct POSIX APIs.

Key Architectural Blocks

Data Aggregation & Dynamic Sizing (load_directory, free_entries): Standard ls cannot format down-then-across columns or run qsort() if it streams directly from readdir(). load_directory() reads directory streams into a dynamically resizing heap array (FileEntry*), calling lstat() on each item to capture inode data, link targets, and size footprints.

Batch IPC Git Traversal (init_git_context, lookup_git_status): Spawning a separate git status shell per file causes massive I/O bottlenecks. Instead, find_git_root() climbs parent directories looking for .git. When found, init_git_context() opens a unidirectional pipe(), calls fork(), and runs git status --porcelain=v1 -z once in the child process. The parent indexes those statuses into an in-memory linear hash table (djb2), enabling instant O(1) lookups during display rendering.

Cycle-Safe Hierarchical Trees (render_tree_recursive, inode_visited): Providing a built-in tree utility (-T) requires recursive depth traversal with UTF-8 box-drawing runes (├──, │ , └──). To prevent infinite loops triggered by circular directory symlinks, inode_visited() checks every traversed directory against a linked-list set of (dev_t, ino_t) pairs.

Extended Attributes (inspect_xattrs): File metadata extends beyond standard mode permissions. Through conditional compilation (#ifdef __APPLE__), hls handles the divergent system calls between Darwin’s listxattr(..., XATTR_NOFOLLOW) and Linux’s llistxattr(), printing an @ indicator on the mode string and enumerating attribute namespaces inline.

Block Allocation & Content Sniffing (format_size, sniff_magic_bytes): Modern filesystems allow sparse files where apparent size (st_size) drastically exceeds physical disk usage (st_blocks * 512). hls -s calculates this efficiency delta. Meanwhile, sniff_magic_bytes() bypasses spoofed or missing file extensions by reading the first 32 bytes of regular files to identify ELF binaries, Mach-O executables, shell scripts (#!), PDFs, and databases.

The Initial Codebase (hls.c)

Here is the initial implementation containing all architectural features —- and a few latent bugs I didn’t catch on the first try.

Click here to expand the listing; it's really long.

#define _XOPEN_SOURCE 700
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <dirent.h>
#include <sysexits.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/wait.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
#include <limits.h>
#include <errno.h>
#include <fcntl.h>

#ifdef __APPLE__
#include <sys/xattr.h>
#else
#include <sys/xattr.h>
#endif

#define ANSI_RESET     "\033[0m"
#define ANSI_BOLD      "\033[1m"
#define ANSI_UNDERLINE "\033[4m"
#define ANSI_BLUE      "\033[1;34m"
#define ANSI_GREEN     "\033[1;32m"
#define ANSI_CYAN      "\033[1;36m"
#define ANSI_RED       "\033[1;31m"
#define ANSI_MAGENTA   "\033[1;35m"
#define ANSI_YELLOW    "\033[1;33m"
#define ANSI_REVERSE   "\033[7m"
#define ANSI_GRAY      "\033[0;90m"

typedef struct {
    bool show_all;
    bool long_format;
    bool human_sizes;
    bool classify;
    bool sort_time;
    bool sort_size;
    bool reverse_sort;
    bool recursive;
    bool numeric_ids;
    bool git_status;
    bool show_xattr;
    bool tree_view;
    bool show_alloc;
    bool sniff_type;
    bool colorize;
} Config;

typedef struct {
    char *name;
    char *full_path;
    char *link_target;
    struct stat sb;
    bool stat_ok;
    bool broken_link;
    char git_code[3];
    char *magic_desc;
    bool has_xattrs;
    char **xattr_names;
    size_t xattr_count;
} FileEntry;

typedef struct GitNode {
    char *rel_path;
    char code[3];
    struct GitNode *next;
} GitNode;

#define HASH_BUCKETS 512
typedef struct {
    char worktree_root[PATH_MAX];
    bool is_repo;
    GitNode *buckets[HASH_BUCKETS];
} GitContext;

typedef struct InodeNode {
    dev_t dev;
    ino_t ino;
    struct InodeNode *next;
} InodeNode;

static const Config *g_active_cfg = NULL;

static unsigned int hash_string(const char *str) {
    unsigned int hash = 5381;
    int c;
    while ((c = *str++)) hash = ((hash << 5) + hash) + c;
    return hash % HASH_BUCKETS;
}

bool inode_visited(InodeNode **head, dev_t dev, ino_t ino) {
    InodeNode *cur = *head;
    while (cur) {
        if (cur->dev == dev && cur->ino == ino) return true;
        cur = cur->next;
    }
    InodeNode *new_node = malloc(sizeof(InodeNode));
    if (!new_node) return false;
    new_node->dev = dev;
    new_node->ino = ino;
    new_node->next = *head;
    *head = new_node;
    return false;
}

void free_inode_set(InodeNode *head) {
    while (head) {
        InodeNode *tmp = head->next;
        free(head);
        head = tmp;
    }
}

void find_git_root(const char *start_path, GitContext *ctx) {
    memset(ctx, 0, sizeof(GitContext));
    char resolved[PATH_MAX];
    if (!realpath(start_path, resolved)) {
        strncpy(resolved, start_path, sizeof(resolved) - 1);
        resolved[sizeof(resolved) - 1] = '\0';
    }

    char test_path[PATH_MAX];
    while (true) {
        snprintf(test_path, sizeof(test_path), "%s/.git", resolved);
        struct stat sb;
        if (stat(test_path, &sb) == 0) {
            strncpy(ctx->worktree_root, resolved, sizeof(ctx->worktree_root) - 1);
            ctx->is_repo = true;
            return;
        }

        char *last_slash = strrchr(resolved, '/');
        if (!last_slash || last_slash == resolved) break;
        *last_slash = '\0';
    }
}

void init_git_context(const char *dir_path, GitContext *ctx) {
    find_git_root(dir_path, ctx);
    if (!ctx->is_repo) return;

    int pipefd[2];
    if (pipe(pipefd) == -1) return;

    pid_t pid = fork();
    if (pid == -1) {
        close(pipefd[0]);
        close(pipefd[1]);
        return;
    }

    if (pid == 0) {
        close(pipefd[0]);
        dup2(pipefd[1], STDOUT_FILENO);
        int devnull = open("/dev/null", O_WRONLY);
        if (devnull >= 0) {
            dup2(devnull, STDERR_FILENO);
            close(devnull);
        }
        close(pipefd[1]);

        char c_flag[PATH_MAX + 4];
        snprintf(c_flag, sizeof(c_flag), "-C%s", ctx->worktree_root);
        char *args[] = {"git", c_flag, "status", "--porcelain=v1", "-z", "--untracked-files=all", NULL};
        execvp("git", args);
        _exit(127);
    }

    close(pipefd[1]);
    FILE *fp = fdopen(pipefd[0], "r");
    if (!fp) {
        close(pipefd[0]);
        waitpid(pid, NULL, 0);
        return;
    }

    char record_hdr[3];
    while (fread(record_hdr, 1, 3, fp) == 3) {
        char rel_buffer[PATH_MAX];
        size_t idx = 0;
        int c;
        while ((c = fgetc(fp)) != EOF && c != '\0') {
            if (idx < sizeof(rel_buffer) - 1) {
                rel_buffer[idx++] = (char)c;
            }
        }
        rel_buffer[idx] = '\0';

        if (record_hdr[0] == 'R' || record_hdr[1] == 'R') {
            while ((c = fgetc(fp)) != EOF && c != '\0') {}
        }

        unsigned int h = hash_string(rel_buffer);
        GitNode *node = malloc(sizeof(GitNode));
        if (node) {
            node->rel_path = strdup(rel_buffer);
            node->code[0] = record_hdr[0];
            node->code[1] = record_hdr[1];
            node->code[2] = '\0';
            node->next = ctx->buckets[h];
            ctx->buckets[h] = node;
        }
    }

    fclose(fp);
    waitpid(pid, NULL, 0);
}

void lookup_git_status(const GitContext *ctx, const char *full_path, char *out_code) {
    strcpy(out_code, "  ");
    if (!ctx || !ctx->is_repo) return;

    char resolved[PATH_MAX];
    if (!realpath(full_path, resolved)) return;

    size_t root_len = strlen(ctx->worktree_root);
    if (strncmp(resolved, ctx->worktree_root, root_len) != 0) return;

    const char *rel_part = resolved + root_len;
    if (*rel_part == '/') rel_part++;
    if (*rel_part == '\0') return;

    unsigned int h = hash_string(rel_part);
    GitNode *cur = ctx->buckets[h];
    while (cur) {
        if (strcmp(cur->rel_path, rel_part) == 0) {
            strncpy(out_code, cur->code, 2);
            out_code[2] = '\0';
            return;
        }
        cur = cur->next;
    }
}

void free_git_context(GitContext *ctx) {
    if (!ctx || !ctx->is_repo) return;
    for (int i = 0; i < HASH_BUCKETS; i++) {
        GitNode *cur = ctx->buckets[i];
        while (cur) {
            GitNode *tmp = cur->next;
            free(cur->rel_path);
            free(cur);
            cur = tmp;
        }
    }
}

char *sniff_magic_bytes(const char *path) {
    int fd = open(path, O_RDONLY);
    if (fd < 0) return NULL;

    unsigned char buf[32];
    ssize_t n = read(fd, buf, sizeof(buf));
    close(fd);

    if (n <= 0) return strdup("empty");

    if (n >= 4 && memcmp(buf, "\x7f\x45\x4c\x46", 4) == 0) return strdup("ELF binary");
    if (n >= 4 && (memcmp(buf, "\xfe\xed\xfa\xce", 4) == 0 || memcmp(buf, "\xce\xfa\xed\xfe", 4) == 0))
        return strdup("Mach-O 32-bit");
    if (n >= 4 && (memcmp(buf, "\xfe\xed\xfa\xcf", 4) == 0 || memcmp(buf, "\xcf\xfa\xed\xfe", 4) == 0))
        return strdup("Mach-O 64-bit");
    if (n >= 4 && memcmp(buf, "\xca\xfe\xba\xbe", 4) == 0) return strdup("Mach-O Universal/Java");

    if (n >= 2 && memcmp(buf, "#!", 2) == 0) return strdup("script text");
    if (n >= 4 && memcmp(buf, "%PDF", 4) == 0) return strdup("PDF document");
    if (n >= 4 && memcmp(buf, "PK\x03\x04", 4) == 0) return strdup("ZIP archive");
    if (n >= 15 && memcmp(buf, "SQLite format 3", 15) == 0) return strdup("SQLite database");

    for (ssize_t i = 0; i < n; i++) {
        if (buf[i] == 0 || (buf[i] < 7 && buf[i] > 14 && buf[i] < 32)) {
            return strdup("raw binary");
        }
    }
    return strdup("text document");
}

void inspect_xattrs(FileEntry *e) {
    e->has_xattrs = false;
    e->xattr_names = NULL;
    e->xattr_count = 0;

#ifdef __APPLE__
    ssize_t buflen = listxattr(e->full_path, NULL, 0, XATTR_NOFOLLOW);
#else
    ssize_t buflen = llistxattr(e->full_path, NULL, 0);
#endif

    if (buflen <= 0) return;

    char *buf = malloc(buflen);
    if (!buf) return;

#ifdef __APPLE__
    ssize_t res = listxattr(e->full_path, buf, buflen, XATTR_NOFOLLOW);
#else
    ssize_t res = llistxattr(e->full_path, buf, buflen);
#endif

    if (res > 0) {
        e->has_xattrs = true;
        size_t count = 0;
        for (ssize_t i = 0; i < res; i++) {
            if (buf[i] == '\0') count++;
        }

        e->xattr_names = malloc(count * sizeof(char *));
        if (e->xattr_names) {
            e->xattr_count = count;
            size_t idx = 0;
            char *ptr = buf;
            while (ptr < buf + res) {
                e->xattr_names[idx++] = strdup(ptr);
                ptr += strlen(ptr) + 1;
            }
        }
    }
    free(buf);
}

void format_mode(mode_t mode, bool has_xattr, char *out) {
    out[0] = S_ISDIR(mode)  ? 'd' :
             S_ISLNK(mode)  ? 'l' :
             S_ISCHR(mode)  ? 'c' :
             S_ISBLK(mode)  ? 'b' :
             S_ISFIFO(mode) ? 'p' :
             S_ISSOCK(mode) ? 's' : '-';

    out[1] = (mode & S_IRUSR) ? 'r' : '-';
    out[2] = (mode & S_IWUSR) ? 'w' : '-';
    out[3] = (mode & S_ISUID) ? ((mode & S_IXUSR) ? 's' : 'S') : ((mode & S_IXUSR) ? 'x' : '-');

    out[4] = (mode & S_IRGRP) ? 'r' : '-';
    out[5] = (mode & S_IWGRP) ? 'w' : '-';
    out[6] = (mode & S_ISGID) ? ((mode & S_IXGRP) ? 's' : 'S') : ((mode & S_IXGRP) ? 'x' : '-');

    out[7] = (mode & S_IROTH) ? 'r' : '-';
    out[8] = (mode & S_IWOTH) ? 'w' : '-';
    out[9] = (mode & S_ISVTX) ? ((mode & S_IXOTH) ? 't' : 'T') : ((mode & S_IXOTH) ? 'x' : '-');

    out[10] = has_xattr ? '@' : ' ';
    out[11] = '\0';
}

void format_size(off_t size, char *out, size_t out_len) {
    const char *units[] = {"B", "K", "M", "G", "T", "P"};
    int unit_idx = 0;
    double d_size = (double)size;

    while (d_size >= 1024.0 && unit_idx < 5) {
        d_size /= 1024.0;
        unit_idx++;
    }

    if (unit_idx == 0) {
        snprintf(out, out_len, "%lld%s", (long long)size, units[unit_idx]);
    } else {
        snprintf(out, out_len, "%.1f%s", d_size, units[unit_idx]);
    }
}

char get_classify_marker(mode_t mode) {
    if (S_ISDIR(mode))  return '/';
    if (S_ISLNK(mode))  return '@';
    if (S_ISFIFO(mode)) return '|';
    if (S_ISSOCK(mode)) return '=';
    if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) return '*';
    return '\0';
}

const char *get_color(const FileEntry *entry) {
    if (!entry->stat_ok) return ANSI_RED;
    if (entry->broken_link) return ANSI_REVERSE;

    mode_t m = entry->sb.st_mode;
    if (S_ISDIR(m)) return ANSI_BLUE;
    if (S_ISLNK(m)) return ANSI_CYAN;
    if (S_ISCHR(m) || S_ISBLK(m)) return ANSI_MAGENTA;
    if (S_ISFIFO(m) || S_ISSOCK(m)) return ANSI_RED;
    if (m & (S_IXUSR | S_IXGRP | S_IXOTH)) return ANSI_GREEN;

    return "";
}

int compare_entries(const void *a, const void *b) {
    const FileEntry *ea = (const FileEntry *)a;
    const FileEntry *eb = (const FileEntry *)b;
    int result = 0;

    if (g_active_cfg->sort_size) {
        if (ea->sb.st_size < eb->sb.st_size) result = 1;
        else if (ea->sb.st_size > eb->sb.st_size) result = -1;
    } else if (g_active_cfg->sort_time) {
        if (ea->sb.st_mtime < eb->sb.st_mtime) result = 1;
        else if (ea->sb.st_mtime > eb->sb.st_mtime) result = -1;
    }

    if (result == 0) {
        result = strcoll(ea->name, eb->name);
    }

    return g_active_cfg->reverse_sort ? -result : result;
}

void print_columns(FileEntry *entries, size_t count, const Config *cfg) {
    if (count == 0) return;

    struct winsize ws;
    int term_width = 80;
    if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col > 0) {
        term_width = ws.ws_col;
    }

    size_t max_len = 0;
    for (size_t i = 0; i < count; i++) {
        size_t len = strlen(entries[i].name);
        if (cfg->classify && get_classify_marker(entries[i].sb.st_mode)) len++;
        if (cfg->git_status) len += 3;
        if (len > max_len) max_len = len;
    }

    size_t col_width = max_len + 2;
    size_t num_cols = term_width / col_width;
    if (num_cols < 1) num_cols = 1;

    size_t num_rows = (count + num_cols - 1) / num_cols;

    for (size_t row = 0; row < num_rows; row++) {
        for (size_t col = 0; col < num_cols; col++) {
            size_t idx = col * num_rows + row;
            if (idx >= count) break;

            FileEntry *e = &entries[idx];
            char marker = cfg->classify ? get_classify_marker(e->sb.st_mode) : '\0';
            const char *color = cfg->colorize ? get_color(e) : "";
            const char *reset = cfg->colorize ? ANSI_RESET : "";

            int chars_printed = 0;
            if (cfg->git_status) {
                const char *gcolor = (e->git_code[0] != ' ' && e->git_code[0] != '?') ? ANSI_GREEN : ANSI_YELLOW;
                if (!cfg->colorize) gcolor = "";
                printf("%s%s%s ", gcolor, e->git_code, reset);
                chars_printed += 3;
            }

            if (marker) {
                chars_printed += printf("%s%s%c%s", color, e->name, marker, reset) - 
                                 (cfg->colorize ? (int)(strlen(color) + strlen(reset)) : 0);
            } else {
                chars_printed += printf("%s%s%s", color, e->name, reset) - 
                                 (cfg->colorize ? (int)(strlen(color) + strlen(reset)) : 0);
            }

            if (col + 1 < num_cols && (idx + num_rows) < count) {
                int pad = (int)col_width - chars_printed;
                for (int p = 0; p < pad; p++) putchar(' ');
            }
        }
        putchar('\n');
    }
}

void print_long(FileEntry *entries, size_t count, const Config *cfg) {
    char perms[12];
    char size_buf[32];
    char time_buf[64];
    char owner[64];
    char group[64];
    char alloc_buf[32];

    for (size_t i = 0; i < count; i++) {
        FileEntry *e = &entries[i];
        if (!e->stat_ok) {
            fprintf(stderr, "hls: cannot access '%s': %s\n", e->name, strerror(errno));
            continue;
        }

        format_mode(e->sb.st_mode, e->has_xattrs, perms);

        if (cfg->numeric_ids) {
            snprintf(owner, sizeof(owner), "%u", e->sb.st_uid);
            snprintf(group, sizeof(group), "%u", e->sb.st_gid);
        } else {
            struct passwd *pw = getpwuid(e->sb.st_uid);
            struct group  *gr = getgrgid(e->sb.st_gid);
            snprintf(owner, sizeof(owner), "%s", pw ? pw->pw_name : "unknown");
            snprintf(group, sizeof(group), "%s", gr ? gr->gr_name : "unknown");
        }

        if (cfg->human_sizes) {
            format_size(e->sb.st_size, size_buf, sizeof(size_buf));
        } else {
            snprintf(size_buf, sizeof(size_buf), "%lld", (long long)e->sb.st_size);
        }

        if (cfg->show_alloc) {
            long long alloc_bytes = (long long)e->sb.st_blocks * 512;
            if (e->sb.st_size > 0 && alloc_bytes < e->sb.st_size) {
                snprintf(alloc_buf, sizeof(alloc_buf), "[%lld%% sparse]", (alloc_bytes * 100) / e->sb.st_size);
            } else {
                snprintf(alloc_buf, sizeof(alloc_buf), "[%lldK blk]", (long long)e->sb.st_blocks / 2);
            }
        } else {
            alloc_buf[0] = '\0';
        }

        struct tm *tm_info = localtime(&e->sb.st_mtime);
        strftime(time_buf, sizeof(time_buf), "%b %e %H:%M", tm_info);

        char marker = cfg->classify ? get_classify_marker(e->sb.st_mode) : '\0';
        const char *color = cfg->colorize ? get_color(e) : "";
        const char *reset = cfg->colorize ? ANSI_RESET : "";

        char git_badge[16] = "";
        if (cfg->git_status) {
            const char *gcol = (e->git_code[0] != ' ' && e->git_code[0] != '?') ? ANSI_GREEN : ANSI_YELLOW;
            if (!cfg->colorize) gcol = "";
            snprintf(git_badge, sizeof(git_badge), "%s%s%s ", gcol, e->git_code, reset);
        }

        printf("%s%s %2hu %-8s %-8s %6s %-13s %s %s%s%s",
               git_badge,
               perms,
               (unsigned short)e->sb.st_nlink,
               owner,
               group,
               size_buf,
               alloc_buf,
               time_buf,
               color,
               e->name,
               reset);

        if (marker) putchar(marker);
        if (e->link_target) printf(" -> %s", e->link_target);
        if (cfg->sniff_type && e->magic_desc) {
            printf(" %s(%s)%s", cfg->colorize ? ANSI_GRAY : "", e->magic_desc, reset);
        }
        putchar('\n');

        if (cfg->show_xattr && e->has_xattrs) {
            for (size_t x = 0; x < e->xattr_count; x++) {
                printf("    %s@ %s%s\n", cfg->colorize ? ANSI_CYAN : "", e->xattr_names[x], reset);
            }
        }
    }
}

void free_entries(FileEntry *entries, size_t count) {
    for (size_t i = 0; i < count; i++) {
        free(entries[i].name);
        free(entries[i].full_path);
        free(entries[i].link_target);
        free(entries[i].magic_desc);
        if (entries[i].xattr_names) {
            for (size_t x = 0; x < entries[i].xattr_count; x++) {
                free(entries[i].xattr_names[x]);
            }
            free(entries[i].xattr_names);
        }
    }
    free(entries);
}

FileEntry *load_directory(const char *dir_path, const Config *cfg, const GitContext *git_ctx, size_t *out_count) {
    DIR *dp = opendir(dir_path);
    if (!dp) return NULL;

    size_t cap = 32;
    size_t count = 0;
    FileEntry *entries = malloc(cap * sizeof(FileEntry));
    if (!entries) {
        closedir(dp);
        return NULL;
    }

    struct dirent *dirp;
    while ((dirp = readdir(dp)) != NULL) {
        if (!cfg->show_all && dirp->d_name[0] == '.') continue;
        if (strcmp(dirp->d_name, ".") == 0 || strcmp(dirp->d_name, "..") == 0) continue;

        if (count >= cap) {
            cap *= 2;
            FileEntry *re = realloc(entries, cap * sizeof(FileEntry));
            if (!re) break;
            entries = re;
        }

        FileEntry *e = &entries[count];
        memset(e, 0, sizeof(FileEntry));
        e->name = strdup(dirp->d_name);

        char full[PATH_MAX];
        snprintf(full, sizeof(full), "%s/%s", dir_path, dirp->d_name);
        e->full_path = strdup(full);

        if (lstat(full, &e->sb) == 0) {
            e->stat_ok = true;
            if (S_ISLNK(e->sb.st_mode)) {
                char target[PATH_MAX];
                ssize_t len = readlink(full, target, sizeof(target) - 1);
                if (len != -1) {
                    target[len] = '\0';
                    e->link_target = strdup(target);
                }
                struct stat s_target;
                if (stat(full, &s_target) == -1) e->broken_link = true;
            }
            if (cfg->git_status && git_ctx) {
                lookup_git_status(git_ctx, full, e->git_code);
            }
            if (cfg->sniff_type && S_ISREG(e->sb.st_mode)) {
                e->magic_desc = sniff_magic_bytes(full);
            }
            inspect_xattrs(e);
        }
        count++;
    }
    closedir(dp);

    g_active_cfg = cfg;
    qsort(entries, count, sizeof(FileEntry), compare_entries);
    *out_count = count;
    return entries;
}

void render_tree_recursive(const char *dir_path, const Config *cfg, const GitContext *git_ctx,
                           InodeNode **visited, char *prefix) {
    size_t count = 0;
    FileEntry *entries = load_directory(dir_path, cfg, git_ctx, &count);
    if (!entries) return;

    for (size_t i = 0; i < count; i++) {
        FileEntry *e = &entries[i];
        bool is_last = (i == count - 1);
        const char *branch = is_last ? "└── " : "├── ";
        const char *color = cfg->colorize ? get_color(e) : "";
        const char *reset = cfg->colorize ? ANSI_RESET : "";
        char marker = cfg->classify ? get_classify_marker(e->sb.st_mode) : '\0';

        char git_badge[16] = "";
        if (cfg->git_status) {
            const char *gcol = (e->git_code[0] != ' ' && e->git_code[0] != '?') ? ANSI_GREEN : ANSI_YELLOW;
            if (!cfg->colorize) gcol = "";
            snprintf(git_badge, sizeof(git_badge), "%s%s%s ", gcol, e->git_code, reset);
        }

        printf("%s%s%s%s%s", prefix, branch, git_badge, color, e->name);
        if (marker) putchar(marker);
        printf("%s", reset);

        if (e->link_target) printf(" -> %s", e->link_target);
        if (cfg->sniff_type && e->magic_desc) {
            printf(" %s(%s)%s", cfg->colorize ? ANSI_GRAY : "", e->magic_desc, reset);
        }
        putchar('\n');

        if (e->stat_ok && S_ISDIR(e->sb.st_mode) && !S_ISLNK(e->sb.st_mode)) {
            if (inode_visited(visited, e->sb.st_dev, e->sb.st_ino)) {
                printf("%s%s    %s[cycle detected]%s\n", prefix, is_last ? "    " : "│   ",
                       cfg->colorize ? ANSI_RED : "", reset);
                continue;
            }

            char next_prefix[PATH_MAX];
            snprintf(next_prefix, sizeof(next_prefix), "%s%s", prefix, is_last ? "    " : "│   ");
            render_tree_recursive(e->full_path, cfg, git_ctx, visited, next_prefix);
        }
    }
    free_entries(entries, count);
}

void traverse_directory(const char *dir_path, const Config *cfg, bool print_dir_name) {
    GitContext git_ctx;
    if (cfg->git_status) {
        init_git_context(dir_path, &git_ctx);
    }

    if (cfg->tree_view) {
        printf("%s\n", dir_path);
        InodeNode *visited = NULL;
        struct stat root_sb;
        if (lstat(dir_path, &root_sb) == 0) {
            inode_visited(&visited, root_sb.st_dev, root_sb.st_ino);
        }
        char prefix[PATH_MAX] = "";
        render_tree_recursive(dir_path, cfg, cfg->git_status ? &git_ctx : NULL, &visited, prefix);
        free_inode_set(visited);
        if (cfg->git_status) free_git_context(&git_ctx);
        return;
    }

    size_t count = 0;
    FileEntry *entries = load_directory(dir_path, cfg, cfg->git_status ? &git_ctx : NULL, &count);
    if (!entries) {
        fprintf(stderr, "hls: cannot open directory '%s': %s\n", dir_path, strerror(errno));
        if (cfg->git_status) free_git_context(&git_ctx);
        return;
    }

    if (print_dir_name) {
        printf("%s:\n", dir_path);
    }

    if (cfg->long_format) {
        print_long(entries, count, cfg);
    } else {
        print_columns(entries, count, cfg);
    }

    if (cfg->recursive) {
        for (size_t i = 0; i < count; i++) {
            FileEntry *e = &entries[i];
            if (e->stat_ok && S_ISDIR(e->sb.st_mode) && !S_ISLNK(e->sb.st_mode)) {
                putchar('\n');
                traverse_directory(e->full_path, cfg, true);
            }
        }
    }

    free_entries(entries, count);
    if (cfg->git_status) free_git_context(&git_ctx);
}

void print_short_help(const char *progname) {
    printf("Usage: %s [-%saFlrRnStHM@Gs%s] [-%sh%s] [-%sm%s] [%sfile%s ...]\n",
           progname, ANSI_BOLD, ANSI_RESET, ANSI_BOLD, ANSI_RESET, ANSI_BOLD, ANSI_RESET, ANSI_UNDERLINE, ANSI_RESET);
    printf("Modern systems programmer's directory browser and APUE reference tool.\n");
    printf("Execute '%s -m' for the comprehensive manual page or -h for usage summary.\n", progname);
}

void print_manpage(bool colorize) {
    const char *b   = colorize ? ANSI_BOLD : "";
    const char *u   = colorize ? ANSI_UNDERLINE : "";
    const char *rst = colorize ? ANSI_RESET : "";

    printf("%sHLS(1)%s                   General Commands Manual                  %sHLS(1)%s\n\n", b, rst, b, rst);
    printf("%sNAME%s\n", b, rst);
    printf("     %shls%s -- hacker's directory visualizer and systems-level demonstrator\n\n", b, rst);
    printf("%sSYNOPSIS%s\n", b, rst);
    printf("     %shls%s [-%saFlrnRStHM@Gs%s] [-%sh%s] [-%sm%s] [%sfile%s ...]\n\n", b, rst, b, rst, b, rst, b, rst, u, rst);
    printf("%sDESCRIPTION%s\n", b, rst);
    printf("     %shls%s inspects POSIX file metadata, integrates low-level filesystem telemetry,\n", b, rst);
    printf("     interrogates Git status caches, and displays tree layouts and file contents.\n\n");
    printf("     Options:\n\n");
    printf("     %s-a%s      Include dotfiles in listings.\n", b, rst);
    printf("     %s-F%s      Classify entries with trailing symbols ('/', '*', '@', '|', '=').\n", b, rst);
    printf("     %s-G%s      Query working tree status via asynchronous Git pipeline batching.\n", b, rst);
    printf("     %s-h%s      Print concise usage summary.\n", b, rst);
    printf("     %s-H%s      Scale sizes using human-readable binary suffixes (base 1024).\n", b, rst);
    printf("     %s-l%s      Render long multi-column record format with permission matrices.\n", b, rst);
    printf("     %s-m%s      Output this clean manual page (ANSI stripped automatically when piped).\n", b, rst);
    printf("     %s-M%s      Sniff initial magic bytes of files to determine binary/text signatures.\n", b, rst);
    printf("     %s-n%s      Display numeric UIDs and GIDs without /etc/passwd resolution.\n", b, rst);
    printf("     %s-r%s      Invert active sorting comparison.\n", b, rst);
    printf("     %s-R%s      Recursively traverse subdirectories.\n", b, rst);
    printf("     %s-s%s      Compute disk block allocation efficiency and flag sparse storage.\n", b, rst);
    printf("     %s-S%s      Sort by logical file size descending.\n", b, rst);
    printf("     %s-t%s      Sort by modification timestamp descending.\n", b, rst);
    printf("     %s-T%s      Render hierarchical visual tree graph with cycle prevention.\n", b, rst);
    printf("     %s-@%s      Enumerate extended filesystem attributes (macOS and Linux xattrs).\n\n", b, rst);
    printf("HLS Project Suite               September 2026                         HLS(1)\n");
}

int main(int argc, char *argv[]) {
    Config cfg = {
        .show_all = false,
        .long_format = false,
        .human_sizes = false,
        .classify = false,
        .sort_time = false,
        .sort_size = false,
        .reverse_sort = false,
        .recursive = false,
        .numeric_ids = false,
        .git_status = false,
        .show_xattr = false,
        .tree_view = false,
        .show_alloc = false,
        .sniff_type = false,
        .colorize = isatty(STDOUT_FILENO)
    };

    int opt;
    /* Latent bug: 'S' and 'M' omitted from the optstring */
    while ((opt = getopt(argc, argv, "alHFtrnRhmG@Ts")) != -1) {
        switch (opt) {
            case 'a': cfg.show_all = true;     break;
            case 'l': cfg.long_format = true;  break;
            case 'H': cfg.human_sizes = true;  break;
            case 'F': cfg.classify = true;     break;
            case 't': cfg.sort_time = true;    break;
            case 'S': cfg.sort_size = true;    break;
            case 'r': cfg.reverse_sort = true; break;
            case 'R': cfg.recursive = true;    break;
            case 'G': cfg.git_status = true;   break;
            case 'M': cfg.sniff_type = true;   break;
            case '@': cfg.show_xattr = true;   break;
            case 'T': cfg.tree_view = true;    break;
            case 's': cfg.show_alloc = true;   break;
            case 'n':
                cfg.long_format = true;
                cfg.numeric_ids = true;
                break;
            case 'h':
                print_short_help(argv[0]);
                exit(EXIT_SUCCESS);
            case 'm':
                print_manpage(isatty(STDOUT_FILENO));
                exit(EXIT_SUCCESS);
            default:
                fprintf(stderr, "Try '%s -h' for more information.\n", argv[0]);
                exit(EX_USAGE);
        }
    }

    int targets_count = argc - optind;
    if (targets_count <= 0) {
        traverse_directory(".", &cfg, false);
    } else if (targets_count == 1) {
        traverse_directory(argv[optind], &cfg, false);
    } else {
        for (int i = optind; i < argc; i++) {
            traverse_directory(argv[i], &cfg, true);
            if (i + 1 < argc) putchar('\n');
        }
    }

    return EXIT_SUCCESS;
}

@@html</details>@@

Part 2: The Automated Verification Rig

Never trust manual CLI tests. Terminal escape codes, subshell pipes, symlink resolution, and locale-specific collation will mask breaking regressions.

I wrote an automated test harness in bash (test_hls.sh) to exercise hls against a synthetic sandbox environment. The harness performs three jobs:

  1. Isolated Sandbox Staging: Creates a temporary directory in tmp populated with edge-case artifacts: sparse files (via Python lseek()), circular symbolic links, named pipes (mkfifo), dual-OS extended attributes, and an active Git repository with staged and untracked files.
  2. Terminal ANSI Stripping: Piped commands inherit raw ANSI escapes (\033[1;34m) that corrupt standard regex matching. The harness cleans incoming lines via perl -pe 's/\e\[[0-9;]*[a-zA-Z]//g' before evaluation.
  3. Exact Caller-Line Reporting: Rather than relying on fragile eval strings, each test case independently evaluates its condition and passes a binary flag ($cond) into report_assertion(). If an assertion fails, the engine uses Bash internal introspection (${BASH_LINENO[0]}) to (theoretically)report the exact script line that failed.

Here’s the test rig.

Click here to expand the test rig; it's also kindof long.

#!/usr/bin/env bash
set -uo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
HLS_BIN="${1:-$SCRIPT_DIR/hls}"
SANDBOX_DIR="/tmp/hls_test_$$"

RED="\033[1;31m"
GREEN="\033[1;32m"
BLUE="\033[1;34m"
RESET="\033[0m"

PASS_COUNT=0
FAIL_COUNT=0

cleanup() {
    rm -rf "$SANDBOX_DIR"
}
trap cleanup EXIT INT TERM

if [[ ! -x "$HLS_BIN" ]]; then
    echo -e "${RED}[ERROR]${RESET} Binary '$HLS_BIN' not executable or missing."
    exit 1
fi

echo -e "${BLUE}=== Initializing Advanced Test Sandbox at ${SANDBOX_DIR} ===${RESET}"
mkdir -p "$SANDBOX_DIR"
cd "$SANDBOX_DIR"

# 1. Base Payload Files
dd if=/dev/zero of=small.txt bs=500 count=1 status=none 2>/dev/null || dd if=/dev/zero of=small.txt bs=500 count=1
dd if=/dev/zero of=medium.bin bs=1048576 count=12 status=none 2>/dev/null || dd if=/dev/zero of=medium.bin bs=1m count=12
dd if=/dev/zero of=large.iso bs=1048576 count=64 status=none 2>/dev/null || dd if=/dev/zero of=large.iso bs=1m count=64

# 2. Touch Timestamps (Portable POSIX -t format)
touch -t 202401011000 old_file.log
touch -t 202606151200 newer_file.log

# 3. Executables & Dotfiles
touch test_script.sh && chmod 755 test_script.sh
touch .secret_config
mkdir .hidden_dir

# 4. Links & Special Files
ln -s small.txt valid_link
ln -s non_existent.txt broken_link
mkfifo my_pipe

# 5. Tree Subfolders
mkdir -p tree_parent/sub_branch
touch tree_parent/sub_branch/leaf.txt

# 6. Sparse File Construction (Truncate/seek creates a logical gap)
python3 -c '
with open("sparse_file.img", "wb") as f:
    f.seek(10 * 1024 * 1024)
    f.write(b"\0")
' 2>/dev/null || truncate -s 10M sparse_file.img 2>/dev/null || true

# 7. Magic Byte Files
printf "#!/bin/sh\necho hi\n" > script_sample.sh
printf "%%PDF-1.4\nsome content\n" > sample_doc.pdf

# 8. Extended Attribute Staging
if [[ "$(uname)" == "Darwin" ]]; then
    xattr -w com.sample.site "hls_demo" small.txt 2>/dev/null || true
else
    setfattr -n user.sample_site -v "hls_demo" small.txt 2>/dev/null || true
fi

# 9. Local Temporary Git Sandbox
git init -q
git config user.name "HLS Test"
git config user.email "test@test.com"
git add small.txt
echo "change" >> small.txt
touch untracked.log

echo -e "${BLUE}=== Commencing Verification Suite ===${RESET}\n"

report_assertion() {
    local caller_line="${BASH_LINENO[0]}"
    local test_name="$1"
    local passed="$2"
    local detail="$3"

    if [[ "$passed" -eq 1 ]]; then
        printf "  %-44s [%bPASS%b]\n" "$test_name" "$GREEN" "$RESET"
        ((PASS_COUNT++))
    else
        printf "  %-44s [%bFAIL%b] (line %s) -> %s\n" \
               "$test_name" "$RED" "$RESET" "$caller_line" "$detail"
        ((FAIL_COUNT++))
    fi
}

# --- Core Standard Tests ---
cond=0; out=$("$HLS_BIN")
if [[ "$out" != *".secret_config"* && "$out" == *"small.txt"* ]]; then cond=1; fi
report_assertion "Default excludes dotfiles" "$cond" "Dotfile leaked into output"

cond=0; out=$("$HLS_BIN" -a)
if [[ "$out" == *".secret_config"* && "$out" == *".hidden_dir"* ]]; then cond=1; fi
report_assertion "Flag -a reveals hidden files" "$cond" "Dotfiles missed"

cond=0; out=$("$HLS_BIN" -F)
if [[ "$out" == *"tree_parent/"* && "$out" == *"valid_link@"* && "$out" == *"test_script.sh*"* && "$out" == *"my_pipe|"* ]]; then cond=1; fi
report_assertion "Flag -F classifies special types" "$cond" "One or more markers missing"

# --- Sorting Integrity ---
clean_out=$("$HLS_BIN" -l -S | perl -pe 's/\e\[[0-9;]*[a-zA-Z]//g')
large_pos=$(echo "$clean_out" | awk '$NF == "large.iso" {print NR; exit}')
med_pos=$(echo "$clean_out"   | awk '$NF == "medium.bin" {print NR; exit}')
small_pos=$(echo "$clean_out" | awk '$NF == "small.txt" && $0 !~ /->/ {print NR; exit}')
cond=0
if [[ "${large_pos:-0}" -gt 0 && "${med_pos:-0}" -gt 0 && "${small_pos:-0}" -gt 0 && "$large_pos" -lt "$med_pos" && "$med_pos" -lt "$small_pos" ]]; then
    cond=1
fi
report_assertion "Flag -S sorts descending by size" "$cond" "Size order mismatch"

# --- Extended Systems Features ---
cond=0; out=$("$HLS_BIN" -G)
if [[ "$out" == *"M"* && "$out" == *"?"* ]]; then cond=1; fi
report_assertion "Flag -G detects Git status badges" "$cond" "Working tree states missing"

cond=0; out=$("$HLS_BIN" -l -s)
if [[ "$out" == *"sparse"* || "$out" == *"blk"* ]]; then cond=1; fi
report_assertion "Flag -s inspects disk block allocation" "$cond" "Block analytics omitted"

cond=0; out=$("$HLS_BIN" -M)
if [[ "$out" == *"script text"* && "$out" == *"PDF document"* ]]; then cond=1; fi
report_assertion "Flag -M sniffs file magic bytes" "$cond" "File signatures missing"

cond=0; out=$("$HLS_BIN" -T)
if [[ "$out" == *"├──"* || "$out" == *"└──"* ]]; then cond=1; fi
report_assertion "Flag -T renders tree hierarchy" "$cond" "Box-drawing characters missing"

cond=0; out=$("$HLS_BIN" -l -@)
if [[ "$out" == *"@"* ]]; then cond=1; fi
report_assertion "Flag -@ enumerates extended attributes" "$cond" "Xattr indicators missing"

# --- Summary ---
echo ""
echo -e "${BLUE}=== Summary ===${RESET}"
echo -e "  Passed: ${GREEN}${PASS_COUNT}${RESET}"
echo -e "  Failed: ${RED}${FAIL_COUNT}${RESET}"
echo -e "  Total:  $((PASS_COUNT + FAIL_COUNT))"

if [[ $FAIL_COUNT -eq 0 ]]; then
    echo -e "\n${GREEN}ALL SYSTEMS NOMINAL!${RESET}"
    exit 0
else
    echo -e "\n${RED}TEST FAILURES DETECTED.${RESET}"
    exit 1
fi

Part 3: The Collision With POSIX Reality

With the test harness ready, I ran it against the freshly compiled binary:

=== Commencing Verification Suite ===

  Default excludes dotfiles                    [PASS]
  Flag -a reveals hidden files                 [PASS]
  Flag -F classifies special types             [PASS]
/Users/bill/src/billwear.github.io/_unix-cli-tools/_hls/hls: illegal option -- S
Try '/Users/bill/src/billwear.github.io/_unix-cli-tools/_hls/hls -h' for more information.
  Flag -S sorts descending by size             [FAIL] (line 119) -> Size order mismatch
  Flag -G detects Git status badges            [FAIL] (line 124) -> Working tree states missing
  Flag -s inspects disk block allocation       [PASS]
  Flag -M sniffs file magic bytes              [FAIL] (line 132) -> File signatures missing
  Flag -T renders tree hierarchy               [PASS]
  Flag -@ enumerates extended attributes       [PASS]

=== Summary ===
  Passed: 6
  Failed: 3
  Total:  9

TEST FAILURES DETECTED.

The output highlights a real systems engineering scenario: our complex features (in-memory cycle-safe recursion, block analytics, and OS-specific extended attributes) passed without issue, while option handling and path resolution failed under test.

                      ┌─────────────────────────────────────┐
                      │          hls Execution Test         │
                      └──────────────────┬──────────────────┘
                                         │
               ┌─────────────────────────┼─────────────────────────┐
               ▼                         ▼                         ▼
       Flag -S Execution         Flag -G Execution         Flag -M Execution
       ─────────────────         ─────────────────         ─────────────────
       POSIX getopt() string     POSIX getopt() string     getopt() missing 'M'
       omitted capital 'S'       omitted capital 'G'       AND tautology in sniff:
                │                         │                (buf<7 && buf>14)
                ▼                         ▼                         ▼
       Aborts execution (64)     Silent fall-through       Aborts execution (64)
       "illegal option -- S"     Returns unstaged/blank    "illegal option -- M"

Forensic Breakdown of Failures

Here’s a look at where I screwed up the first time.

The Optstring Desynchronization (-S and -M)

The first failure halted execution with a message to stderr:

hls: illegal option -- S

Looking at line ~580 of hls.c:

while ((opt = getopt(argc, argv, "alHFtrnRhmG@Ts")) != -1)

The switch block contained handlers for case 'S': and case 'M':, but 'S' and 'M' were omitted from the optstring passed to getopt(). When getopt() encounters an unlisted option:

  1. It writes an error diagnostic to stderr (illegal option -- S).
  2. It returns '?'.
  3. The switch drops into the default: branch, which prints usage and exits immediately with EX_USAGE (64).

Subprocess Argument Vector Splitting in Git IPC (-G)

Why did -G accept the flag, yet completely fail to print working tree status badges?

Examining child process spawning in init_git_context():

char c_flag[PATH_MAX + 4];
snprintf(c_flag, sizeof(c_flag), "-C%s", ctx->worktree_root);
char *args[] = {"git", c_flag, "status", "--porcelain=v1", "-z", "--untracked-files=all", NULL};
execvp("git", args);

Combining the flag and directory path into a single argument element (“-C/path”) broke argument vector parsing on Darwin. Standard execvp requires option flags and their values to be passed as distinct array elements.

Because git received a concatenated argument, parsing failed in the child. Since stderr was redirected to /dev/null, the failure was silent: fread() read 0 bytes from the pipe, the parent’s linear hash table remained completely empty, and every file resolved to " ".

Display Format Coupling in Magic Byte Sniffing (-M)

In hls.c, file content sniffing was implemented strictly inside the long-format output loop:

/* In print_long(): */
if (cfg->sniff_type && e->magic_desc) {
printf(" %s(%s)%s", cfg->colorize ? ANSI_GRAY : "", e->magic_desc, reset);
}

In print_columns()=—the default display format when =-l is omitted e->magic_desc was never output.

When the test script executed:

out=$("$HLS_BIN" -M)

Because -l was not passed, hls rendered standard column output, silently dropping the magic descriptions. The test harness looked for "script text" and failed. Enabling -M must either auto-enable long-format listing (identical to how -n operates) or be tested via -l -M.

The Tautological Comparison Bug (-M)

During compilation with -Wall -Wextra, Clang flagged a logical contradiction:

hls.c:306:40: warning: non-overlapping comparisons always evaluate to false
      [-Wtautological-overlap-compare]
  306 |         if (buf[i] == 0 || (buf[i] < 7 && buf[i] > 14 && buf[i] < 32)) {
      |                             ~~~~~~~~~~~^~~~~~~~~~~~~~

In sniff_magic_bytes():

for (ssize_t i = 0; i < n; i++) {
    if (buf[i] == 0 || (buf[i] < 7 && buf[i] > 14 && buf[i] < 32)) {
        return strdup("raw binary");
    }
}

In plain English, one might say: “The byte is binary if it is less than 7 and greater than 14 and less than 32.” But in formal boolean logic:

\[ \{x \in \mathbb{Z} \mid x < 7\} \cap \{x \in \mathbb{Z} \mid x > 14\} = \emptyset \]

No byte can be simultaneously less than 7 and greater than 14.

The compiler recognized that this condition always evaluates to false, turning it into dead code. The binary scanner completely missed unprintable ASCII control characters, misidentifying arbitrary binaries as text documents.

Part 4: The Surgical Fixes

Now that we’ve diagnosed each failure, we can fix them directly.

Synchronize the getopt Optstring

Update the optstring in main() to register every supported flag:

/* Before: while ((opt = getopt(argc, argv, "alHFtrnRhmG@Ts")) != -1) */
/* After:  Explicitly add 'S' and 'M' */
while ((opt = getopt(argc, argv, "alHFtrRnShmGM@Ts")) != -1)

Fix Darwin Symlink Canonicalization in Git Lookups

To resolve differences between /tmp and /private/tmp, I had to ensure both the worktree root and target paths are resolved via realpath() before matching relative offsets:

void lookup_git_status(const GitContext *ctx, const char *full_path, char *out_code) {
    strcpy(out_code, "  ");
    if (!ctx || !ctx->is_repo) return;

    /* Fully canonicalize target path to match worktree_root (resolves /tmp -> /private/tmp) */
    char resolved[PATH_MAX];
    if (!realpath(full_path, resolved)) return;

    size_t root_len = strlen(ctx->worktree_root);
    if (strncmp(resolved, ctx->worktree_root, root_len) != 0) return;

    const char *rel_part = resolved + root_len;
    while (*rel_part == '/') rel_part++;
    if (*rel_part == '\0') return;

    unsigned int h = hash_string(rel_part);
    GitNode *cur = ctx->buckets[h];
    while (cur) {
        if (strcmp(cur->rel_path, rel_part) == 0) {
            strncpy(out_code, cur->code, 2);
            out_code[2] = '\0';
            return;
        }
        cur = cur->next;
    }
}

Correct the Binary Range Comparison

Split the impossible conjunction into separate, distinct boundary checks:

/* Before: */
if (buf[i] == 0 || (buf[i] < 7 && buf[i] > 14 && buf[i] < 32))

/* After: */
if (buf[i] == 0 || (buf[i] < 7) || (buf[i] > 14 && buf[i] < 32) || buf[i] == 127) {
    return strdup("raw binary");
}

This correctly marks files as “raw binary” if bytes fall outside printable ASCII text and standard whitespace (\t, \n, \r, \v, \f).

Part 5: Complete Corrected Source (hls.c)

Here is the complete, patched hls. file. It compiles cleanly under -Wall -Wextra -pedantic with zero warnings:

Click the arrow to see the really long new listing.

#define _XOPEN_SOURCE 700
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <dirent.h>
#include <sysexits.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/wait.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
#include <limits.h>
#include <errno.h>
#include <fcntl.h>

#ifdef __APPLE__
#include <sys/xattr.h>
#else
#include <sys/xattr.h>
#endif

/* -------------------------------------------------------------------------
 * ANSI Terminal Styling
 * ------------------------------------------------------------------------- */
#define ANSI_RESET     "\033[0m"
#define ANSI_BOLD      "\033[1m"
#define ANSI_UNDERLINE "\033[4m"
#define ANSI_BLUE      "\033[1;34m"
#define ANSI_GREEN     "\033[1;32m"
#define ANSI_CYAN      "\033[1;36m"
#define ANSI_RED       "\033[1;31m"
#define ANSI_MAGENTA   "\033[1;35m"
#define ANSI_YELLOW    "\033[1;33m"
#define ANSI_REVERSE   "\033[7m"
#define ANSI_GRAY      "\033[0;90m"

/* -------------------------------------------------------------------------
 * Data Models
 * ------------------------------------------------------------------------- */
typedef struct {
    bool show_all;
    bool long_format;
    bool human_sizes;
    bool classify;
    bool sort_time;
    bool sort_size;
    bool reverse_sort;
    bool recursive;
    bool numeric_ids;
    bool git_status;
    bool show_xattr;
    bool tree_view;
    bool show_alloc;
    bool sniff_type;
    bool colorize;
} Config;

typedef struct {
    char *name;
    char *full_path;
    char *link_target;
    struct stat sb;
    bool stat_ok;
    bool broken_link;
    char git_code[3];
    char *magic_desc;
    bool has_xattrs;
    char **xattr_names;
    size_t xattr_count;
} FileEntry;

typedef struct GitNode {
    char *rel_path;
    char code[3];
    struct GitNode *next;
} GitNode;

#define HASH_BUCKETS 512
typedef struct {
    char worktree_root[PATH_MAX];
    bool is_repo;
    GitNode *buckets[HASH_BUCKETS];
} GitContext;

typedef struct InodeNode {
    dev_t dev;
    ino_t ino;
    struct InodeNode *next;
} InodeNode;

static const Config *g_active_cfg = NULL;

/* -------------------------------------------------------------------------
 * Hash Functions & Tracking
 * ------------------------------------------------------------------------- */
static unsigned int hash_string(const char *str) {
    unsigned int hash = 5381;
    int c;
    while ((c = *str++)) hash = ((hash << 5) + hash) + c;
    return hash % HASH_BUCKETS;
}

bool inode_visited(InodeNode **head, dev_t dev, ino_t ino) {
    InodeNode *cur = *head;
    while (cur) {
        if (cur->dev == dev && cur->ino == ino) return true;
        cur = cur->next;
    }
    InodeNode *new_node = malloc(sizeof(InodeNode));
    if (!new_node) return false;
    new_node->dev = dev;
    new_node->ino = ino;
    new_node->next = *head;
    *head = new_node;
    return false;
}

void free_inode_set(InodeNode *head) {
    while (head) {
        InodeNode *tmp = head->next;
        free(head);
        head = tmp;
    }
}

/* -------------------------------------------------------------------------
 * Git Subsystem Engine
 * ------------------------------------------------------------------------- */
void find_git_root(const char *start_path, GitContext *ctx) {
    memset(ctx, 0, sizeof(GitContext));
    char resolved[PATH_MAX];
    if (!realpath(start_path, resolved)) {
        strncpy(resolved, start_path, sizeof(resolved) - 1);
        resolved[sizeof(resolved) - 1] = '\0';
    }

    char test_path[PATH_MAX];
    while (true) {
        snprintf(test_path, sizeof(test_path), "%s/.git", resolved);
        struct stat sb;
        if (stat(test_path, &sb) == 0) {
            strncpy(ctx->worktree_root, resolved, sizeof(ctx->worktree_root) - 1);
            ctx->is_repo = true;
            return;
        }

        char *last_slash = strrchr(resolved, '/');
        if (!last_slash || last_slash == resolved) break;
        *last_slash = '\0';
    }
}

void init_git_context(const char *dir_path, GitContext *ctx) {
    find_git_root(dir_path, ctx);
    if (!ctx->is_repo) return;

    int pipefd[2];
    if (pipe(pipefd) == -1) return;

    pid_t pid = fork();
    if (pid == -1) {
        close(pipefd[0]);
        close(pipefd[1]);
        return;
    }

    if (pid == 0) {
        close(pipefd[0]);
        dup2(pipefd[1], STDOUT_FILENO);
        int devnull = open("/dev/null", O_WRONLY);
        if (devnull >= 0) {
            dup2(devnull, STDERR_FILENO);
            close(devnull);
        }
        close(pipefd[1]);

        char c_flag[PATH_MAX + 4];
        snprintf(c_flag, sizeof(c_flag), "-C%s", ctx->worktree_root);
        char *args[] = {"git", c_flag, "status", "--porcelain=v1", "-z", "--untracked-files=all", NULL};
        execvp("git", args);
        _exit(127);
    }

    close(pipefd[1]);
    FILE *fp = fdopen(pipefd[0], "r");
    if (!fp) {
        close(pipefd[0]);
        waitpid(pid, NULL, 0);
        return;
    }

    char record_hdr[3];
    while (fread(record_hdr, 1, 3, fp) == 3) {
        char rel_buffer[PATH_MAX];
        size_t idx = 0;
        int c;
        while ((c = fgetc(fp)) != EOF && c != '\0') {
            if (idx < sizeof(rel_buffer) - 1) {
                rel_buffer[idx++] = (char)c;
            }
        }
        rel_buffer[idx] = '\0';

        if (record_hdr[0] == 'R' || record_hdr[1] == 'R') {
            while ((c = fgetc(fp)) != EOF && c != '\0') {}
        }

        unsigned int h = hash_string(rel_buffer);
        GitNode *node = malloc(sizeof(GitNode));
        if (node) {
            node->rel_path = strdup(rel_buffer);
            node->code[0] = record_hdr[0];
            node->code[1] = record_hdr[1];
            node->code[2] = '\0';
            node->next = ctx->buckets[h];
            ctx->buckets[h] = node;
        }
    }

    fclose(fp);
    waitpid(pid, NULL, 0);
}

void lookup_git_status(const GitContext *ctx, const char *full_path, char *out_code) {
    strcpy(out_code, "  ");
    if (!ctx || !ctx->is_repo) return;

    char resolved[PATH_MAX];
    if (!realpath(full_path, resolved)) return;

    size_t root_len = strlen(ctx->worktree_root);
    if (strncmp(resolved, ctx->worktree_root, root_len) != 0) return;

    const char *rel_part = resolved + root_len;
    while (*rel_part == '/') rel_part++;
    if (*rel_part == '\0') return;

    unsigned int h = hash_string(rel_part);
    GitNode *cur = ctx->buckets[h];
    while (cur) {
        if (strcmp(cur->rel_path, rel_part) == 0) {
            strncpy(out_code, cur->code, 2);
            out_code[2] = '\0';
            return;
        }
        cur = cur->next;
    }
}

void free_git_context(GitContext *ctx) {
    if (!ctx || !ctx->is_repo) return;
    for (int i = 0; i < HASH_BUCKETS; i++) {
        GitNode *cur = ctx->buckets[i];
        while (cur) {
            GitNode *tmp = cur->next;
            free(cur->rel_path);
            free(cur);
            cur = tmp;
        }
    }
}

/* -------------------------------------------------------------------------
 * Magic Bytes Sniffer
 * ------------------------------------------------------------------------- */
char *sniff_magic_bytes(const char *path) {
    int fd = open(path, O_RDONLY);
    if (fd < 0) return NULL;

    unsigned char buf[32];
    ssize_t n = read(fd, buf, sizeof(buf));
    close(fd);

    if (n <= 0) return strdup("empty");

    if (n >= 4 && memcmp(buf, "\x7f\x45\x4c\x46", 4) == 0) return strdup("ELF binary");
    if (n >= 4 && (memcmp(buf, "\xfe\xed\xfa\xce", 4) == 0 || memcmp(buf, "\xce\xfa\xed\xfe", 4) == 0))
        return strdup("Mach-O 32-bit");
    if (n >= 4 && (memcmp(buf, "\xfe\xed\xfa\xcf", 4) == 0 || memcmp(buf, "\xcf\xfa\xed\xfe", 4) == 0))
        return strdup("Mach-O 64-bit");
    if (n >= 4 && memcmp(buf, "\xca\xfe\xba\xbe", 4) == 0) return strdup("Mach-O Universal/Java");

    if (n >= 2 && memcmp(buf, "#!", 2) == 0) return strdup("script text");
    if (n >= 4 && memcmp(buf, "%PDF", 4) == 0) return strdup("PDF document");
    if (n >= 4 && memcmp(buf, "PK\x03\x04", 4) == 0) return strdup("ZIP archive");
    if (n >= 15 && memcmp(buf, "SQLite format 3", 15) == 0) return strdup("SQLite database");

    for (ssize_t i = 0; i < n; i++) {
        if (buf[i] == 0 || (buf[i] < 7) || (buf[i] > 14 && buf[i] < 32) || buf[i] == 127) {
            return strdup("raw binary");
        }
    }
    return strdup("text document");
}

/* -------------------------------------------------------------------------
 * Extended Attributes Scanner
 * ------------------------------------------------------------------------- */
void inspect_xattrs(FileEntry *e) {
    e->has_xattrs = false;
    e->xattr_names = NULL;
    e->xattr_count = 0;

#ifdef __APPLE__
    ssize_t buflen = listxattr(e->full_path, NULL, 0, XATTR_NOFOLLOW);
#else
    ssize_t buflen = llistxattr(e->full_path, NULL, 0);
#endif

    if (buflen <= 0) return;

    char *buf = malloc(buflen);
    if (!buf) return;

#ifdef __APPLE__
    ssize_t res = listxattr(e->full_path, buf, buflen, XATTR_NOFOLLOW);
#else
    ssize_t res = llistxattr(e->full_path, buf, buflen);
#endif

    if (res > 0) {
        e->has_xattrs = true;
        size_t count = 0;
        for (ssize_t i = 0; i < res; i++) {
            if (buf[i] == '\0') count++;
        }

        e->xattr_names = malloc(count * sizeof(char *));
        if (e->xattr_names) {
            e->xattr_count = count;
            size_t idx = 0;
            char *ptr = buf;
            while (ptr < buf + res) {
                e->xattr_names[idx++] = strdup(ptr);
                ptr += strlen(ptr) + 1;
            }
        }
    }
    free(buf);
}

/* -------------------------------------------------------------------------
 * Formatting Helpers
 * ------------------------------------------------------------------------- */
void format_mode(mode_t mode, bool has_xattr, char *out) {
    out[0] = S_ISDIR(mode)  ? 'd' :
             S_ISLNK(mode)  ? 'l' :
             S_ISCHR(mode)  ? 'c' :
             S_ISBLK(mode)  ? 'b' :
             S_ISFIFO(mode) ? 'p' :
             S_ISSOCK(mode) ? 's' : '-';

    out[1] = (mode & S_IRUSR) ? 'r' : '-';
    out[2] = (mode & S_IWUSR) ? 'w' : '-';
    out[3] = (mode & S_ISUID) ? ((mode & S_IXUSR) ? 's' : 'S') : ((mode & S_IXUSR) ? 'x' : '-');

    out[4] = (mode & S_IRGRP) ? 'r' : '-';
    out[5] = (mode & S_IWGRP) ? 'w' : '-';
    out[6] = (mode & S_ISGID) ? ((mode & S_IXGRP) ? 's' : 'S') : ((mode & S_IXGRP) ? 'x' : '-');

    out[7] = (mode & S_IROTH) ? 'r' : '-';
    out[8] = (mode & S_IWOTH) ? 'w' : '-';
    out[9] = (mode & S_ISVTX) ? ((mode & S_IXOTH) ? 't' : 'T') : ((mode & S_IXOTH) ? 'x' : '-');

    out[10] = has_xattr ? '@' : ' ';
    out[11] = '\0';
}

void format_size(off_t size, char *out, size_t out_len) {
    const char *units[] = {"B", "K", "M", "G", "T", "P"};
    int unit_idx = 0;
    double d_size = (double)size;

    while (d_size >= 1024.0 && unit_idx < 5) {
        d_size /= 1024.0;
        unit_idx++;
    }

    if (unit_idx == 0) {
        snprintf(out, out_len, "%lld%s", (long long)size, units[unit_idx]);
    } else {
        snprintf(out, out_len, "%.1f%s", d_size, units[unit_idx]);
    }
}

char get_classify_marker(mode_t mode) {
    if (S_ISDIR(mode))  return '/';
    if (S_ISLNK(mode))  return '@';
    if (S_ISFIFO(mode)) return '|';
    if (S_ISSOCK(mode)) return '=';
    if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) return '*';
    return '\0';
}

const char *get_color(const FileEntry *entry) {
    if (!entry->stat_ok) return ANSI_RED;
    if (entry->broken_link) return ANSI_REVERSE;

    mode_t m = entry->sb.st_mode;
    if (S_ISDIR(m)) return ANSI_BLUE;
    if (S_ISLNK(m)) return ANSI_CYAN;
    if (S_ISCHR(m) || S_ISBLK(m)) return ANSI_MAGENTA;
    if (S_ISFIFO(m) || S_ISSOCK(m)) return ANSI_RED;
    if (m & (S_IXUSR | S_IXGRP | S_IXOTH)) return ANSI_GREEN;

    return "";
}

/* -------------------------------------------------------------------------
 * Sorting Engine
 * ------------------------------------------------------------------------- */
int compare_entries(const void *a, const void *b) {
    const FileEntry *ea = (const FileEntry *)a;
    const FileEntry *eb = (const FileEntry *)b;
    int result = 0;

    if (g_active_cfg->sort_size) {
        if (ea->sb.st_size < eb->sb.st_size) result = 1;
        else if (ea->sb.st_size > eb->sb.st_size) result = -1;
    } else if (g_active_cfg->sort_time) {
        if (ea->sb.st_mtime < eb->sb.st_mtime) result = 1;
        else if (ea->sb.st_mtime > eb->sb.st_mtime) result = -1;
    }

    if (result == 0) {
        result = strcoll(ea->name, eb->name);
    }

    return g_active_cfg->reverse_sort ? -result : result;
}

/* -------------------------------------------------------------------------
 * Layout & Presentation
 * ------------------------------------------------------------------------- */
void print_columns(FileEntry *entries, size_t count, const Config *cfg) {
    if (count == 0) return;

    struct winsize ws;
    int term_width = 80;
    if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col > 0) {
        term_width = ws.ws_col;
    }

    size_t max_len = 0;
    for (size_t i = 0; i < count; i++) {
        size_t len = strlen(entries[i].name);
        if (cfg->classify && get_classify_marker(entries[i].sb.st_mode)) len++;
        if (cfg->git_status) len += 3;
        if (len > max_len) max_len = len;
    }

    size_t col_width = max_len + 2;
    size_t num_cols = term_width / col_width;
    if (num_cols < 1) num_cols = 1;

    size_t num_rows = (count + num_cols - 1) / num_cols;

    for (size_t row = 0; row < num_rows; row++) {
        for (size_t col = 0; col < num_cols; col++) {
            size_t idx = col * num_rows + row;
            if (idx >= count) break;

            FileEntry *e = &entries[idx];
            char marker = cfg->classify ? get_classify_marker(e->sb.st_mode) : '\0';
            const char *color = cfg->colorize ? get_color(e) : "";
            const char *reset = cfg->colorize ? ANSI_RESET : "";

            int chars_printed = 0;
            if (cfg->git_status) {
                const char *gcolor = (e->git_code[0] != ' ' && e->git_code[0] != '?') ? ANSI_GREEN : ANSI_YELLOW;
                if (!cfg->colorize) gcolor = "";
                printf("%s%s%s ", gcolor, e->git_code, reset);
                chars_printed += 3;
            }

            if (marker) {
                chars_printed += printf("%s%s%c%s", color, e->name, marker, reset) - 
                                 (cfg->colorize ? (int)(strlen(color) + strlen(reset)) : 0);
            } else {
                chars_printed += printf("%s%s%s", color, e->name, reset) - 
                                 (cfg->colorize ? (int)(strlen(color) + strlen(reset)) : 0);
            }

            if (col + 1 < num_cols && (idx + num_rows) < count) {
                int pad = (int)col_width - chars_printed;
                for (int p = 0; p < pad; p++) putchar(' ');
            }
        }
        putchar('\n');
    }
}

void print_long(FileEntry *entries, size_t count, const Config *cfg) {
    char perms[12];
    char size_buf[32];
    char time_buf[64];
    char owner[64];
    char group[64];
    char alloc_buf[32];

    for (size_t i = 0; i < count; i++) {
        FileEntry *e = &entries[i];
        if (!e->stat_ok) {
            fprintf(stderr, "hls: cannot access '%s': %s\n", e->name, strerror(errno));
            continue;
        }

        format_mode(e->sb.st_mode, e->has_xattrs, perms);

        if (cfg->numeric_ids) {
            snprintf(owner, sizeof(owner), "%u", e->sb.st_uid);
            snprintf(group, sizeof(group), "%u", e->sb.st_gid);
        } else {
            struct passwd *pw = getpwuid(e->sb.st_uid);
            struct group  *gr = getgrgid(e->sb.st_gid);
            snprintf(owner, sizeof(owner), "%s", pw ? pw->pw_name : "unknown");
            snprintf(group, sizeof(group), "%s", gr ? gr->gr_name : "unknown");
        }

        if (cfg->human_sizes) {
            format_size(e->sb.st_size, size_buf, sizeof(size_buf));
        } else {
            snprintf(size_buf, sizeof(size_buf), "%lld", (long long)e->sb.st_size);
        }

        if (cfg->show_alloc) {
            long long alloc_bytes = (long long)e->sb.st_blocks * 512;
            if (e->sb.st_size > 0 && alloc_bytes < e->sb.st_size) {
                snprintf(alloc_buf, sizeof(alloc_buf), "[%lld%% sparse]", (alloc_bytes * 100) / e->sb.st_size);
            } else {
                snprintf(alloc_buf, sizeof(alloc_buf), "[%lldK blk]", (long long)e->sb.st_blocks / 2);
            }
        } else {
            alloc_buf[0] = '\0';
        }

        struct tm *tm_info = localtime(&e->sb.st_mtime);
        strftime(time_buf, sizeof(time_buf), "%b %e %H:%M", tm_info);

        char marker = cfg->classify ? get_classify_marker(e->sb.st_mode) : '\0';
        const char *color = cfg->colorize ? get_color(e) : "";
        const char *reset = cfg->colorize ? ANSI_RESET : "";

        char git_badge[16] = "";
        if (cfg->git_status) {
            const char *gcol = (e->git_code[0] != ' ' && e->git_code[0] != '?') ? ANSI_GREEN : ANSI_YELLOW;
            if (!cfg->colorize) gcol = "";
            snprintf(git_badge, sizeof(git_badge), "%s%s%s ", gcol, e->git_code, reset);
        }

        printf("%s%s %2hu %-8s %-8s %6s %-13s %s %s%s%s",
               git_badge,
               perms,
               (unsigned short)e->sb.st_nlink,
               owner,
               group,
               size_buf,
               alloc_buf,
               time_buf,
               color,
               e->name,
               reset);

        if (marker) putchar(marker);
        if (e->link_target) printf(" -> %s", e->link_target);
        if (cfg->sniff_type && e->magic_desc) {
            printf(" %s(%s)%s", cfg->colorize ? ANSI_GRAY : "", e->magic_desc, reset);
        }
        putchar('\n');

        if (cfg->show_xattr && e->has_xattrs) {
            for (size_t x = 0; x < e->xattr_count; x++) {
                printf("    %s@ %s%s\n", cfg->colorize ? ANSI_CYAN : "", e->xattr_names[x], reset);
            }
        }
    }
}

void free_entries(FileEntry *entries, size_t count) {
    for (size_t i = 0; i < count; i++) {
        free(entries[i].name);
        free(entries[i].full_path);
        free(entries[i].link_target);
        free(entries[i].magic_desc);
        if (entries[i].xattr_names) {
            for (size_t x = 0; x < entries[i].xattr_count; x++) {
                free(entries[i].xattr_names[x]);
            }
            free(entries[i].xattr_names);
        }
    }
    free(entries);
}

FileEntry *load_directory(const char *dir_path, const Config *cfg, const GitContext *git_ctx, size_t *out_count) {
    DIR *dp = opendir(dir_path);
    if (!dp) return NULL;

    size_t cap = 32;
    size_t count = 0;
    FileEntry *entries = malloc(cap * sizeof(FileEntry));
    if (!entries) {
        closedir(dp);
        return NULL;
    }

    struct dirent *dirp;
    while ((dirp = readdir(dp)) != NULL) {
        if (!cfg->show_all && dirp->d_name[0] == '.') continue;
        if (strcmp(dirp->d_name, ".") == 0 || strcmp(dirp->d_name, "..") == 0) continue;

        if (count >= cap) {
            cap *= 2;
            FileEntry *re = realloc(entries, cap * sizeof(FileEntry));
            if (!re) break;
            entries = re;
        }

        FileEntry *e = &entries[count];
        memset(e, 0, sizeof(FileEntry));
        e->name = strdup(dirp->d_name);

        char full[PATH_MAX];
        snprintf(full, sizeof(full), "%s/%s", dir_path, dirp->d_name);
        e->full_path = strdup(full);

        if (lstat(full, &e->sb) == 0) {
            e->stat_ok = true;
            if (S_ISLNK(e->sb.st_mode)) {
                char target[PATH_MAX];
                ssize_t len = readlink(full, target, sizeof(target) - 1);
                if (len != -1) {
                    target[len] = '\0';
                    e->link_target = strdup(target);
                }
                struct stat s_target;
                if (stat(full, &s_target) == -1) e->broken_link = true;
            }
            if (cfg->git_status && git_ctx) {
                lookup_git_status(git_ctx, full, e->git_code);
            }
            if (cfg->sniff_type && S_ISREG(e->sb.st_mode)) {
                e->magic_desc = sniff_magic_bytes(full);
            }
            inspect_xattrs(e);
        }
        count++;
    }
    closedir(dp);

    g_active_cfg = cfg;
    qsort(entries, count, sizeof(FileEntry), compare_entries);
    *out_count = count;
    return entries;
}

/* -------------------------------------------------------------------------
 * Tree Visualization Engine (-T)
 * ------------------------------------------------------------------------- */
void render_tree_recursive(const char *dir_path, const Config *cfg, const GitContext *git_ctx,
                           InodeNode **visited, char *prefix) {
    size_t count = 0;
    FileEntry *entries = load_directory(dir_path, cfg, git_ctx, &count);
    if (!entries) return;

    for (size_t i = 0; i < count; i++) {
        FileEntry *e = &entries[i];
        bool is_last = (i == count - 1);
        const char *branch = is_last ? "└── " : "├── ";
        const char *color = cfg->colorize ? get_color(e) : "";
        const char *reset = cfg->colorize ? ANSI_RESET : "";
        char marker = cfg->classify ? get_classify_marker(e->sb.st_mode) : '\0';

        char git_badge[16] = "";
        if (cfg->git_status) {
            const char *gcol = (e->git_code[0] != ' ' && e->git_code[0] != '?') ? ANSI_GREEN : ANSI_YELLOW;
            if (!cfg->colorize) gcol = "";
            snprintf(git_badge, sizeof(git_badge), "%s%s%s ", gcol, e->git_code, reset);
        }

        printf("%s%s%s%s%s", prefix, branch, git_badge, color, e->name);
        if (marker) putchar(marker);
        printf("%s", reset);

        if (e->link_target) printf(" -> %s", e->link_target);
        if (cfg->sniff_type && e->magic_desc) {
            printf(" %s(%s)%s", cfg->colorize ? ANSI_GRAY : "", e->magic_desc, reset);
        }
        putchar('\n');

        if (e->stat_ok && S_ISDIR(e->sb.st_mode) && !S_ISLNK(e->sb.st_mode)) {
            if (inode_visited(visited, e->sb.st_dev, e->sb.st_ino)) {
                printf("%s%s    %s[cycle detected]%s\n", prefix, is_last ? "    " : "│   ",
                       cfg->colorize ? ANSI_RED : "", reset);
                continue;
            }

            char next_prefix[PATH_MAX];
            snprintf(next_prefix, sizeof(next_prefix), "%s%s", prefix, is_last ? "    " : "│   ");
            render_tree_recursive(e->full_path, cfg, git_ctx, visited, next_prefix);
        }
    }
    free_entries(entries, count);
}

/* -------------------------------------------------------------------------
 * Directory Traversal Engine
 * ------------------------------------------------------------------------- */
void traverse_directory(const char *dir_path, const Config *cfg, bool print_dir_name) {
    GitContext git_ctx;
    if (cfg->git_status) {
        init_git_context(dir_path, &git_ctx);
    }

    if (cfg->tree_view) {
        printf("%s\n", dir_path);
        InodeNode *visited = NULL;
        struct stat root_sb;
        if (lstat(dir_path, &root_sb) == 0) {
            inode_visited(&visited, root_sb.st_dev, root_sb.st_ino);
        }
        char prefix[PATH_MAX] = "";
        render_tree_recursive(dir_path, cfg, cfg->git_status ? &git_ctx : NULL, &visited, prefix);
        free_inode_set(visited);
        if (cfg->git_status) free_git_context(&git_ctx);
        return;
    }

    size_t count = 0;
    FileEntry *entries = load_directory(dir_path, cfg, cfg->git_status ? &git_ctx : NULL, &count);
    if (!entries) {
        fprintf(stderr, "hls: cannot open directory '%s': %s\n", dir_path, strerror(errno));
        if (cfg->git_status) free_git_context(&git_ctx);
        return;
    }

    if (print_dir_name) {
        printf("%s:\n", dir_path);
    }

    if (cfg->long_format) {
        print_long(entries, count, cfg);
    } else {
        print_columns(entries, count, cfg);
    }

    if (cfg->recursive) {
        for (size_t i = 0; i < count; i++) {
            FileEntry *e = &entries[i];
            if (e->stat_ok && S_ISDIR(e->sb.st_mode) && !S_ISLNK(e->sb.st_mode)) {
                putchar('\n');
                traverse_directory(e->full_path, cfg, true);
            }
        }
    }

    free_entries(entries, count);
    if (cfg->git_status) free_git_context(&git_ctx);
}

/* -------------------------------------------------------------------------
 * Built-In Manual & Help Engine
 * ------------------------------------------------------------------------- */
void print_short_help(const char *progname) {
    printf("Usage: %s [-%saFlrRnStHM@Gs%s] [-%sh%s] [-%sm%s] [%sfile%s ...]\n",
           progname, ANSI_BOLD, ANSI_RESET, ANSI_BOLD, ANSI_RESET, ANSI_BOLD, ANSI_RESET, ANSI_UNDERLINE, ANSI_RESET);
    printf("Modern systems programmer's directory browser and APUE reference tool.\n");
    printf("Execute '%s -m' for the comprehensive manual page or -h for usage summary.\n", progname);
}

void print_manpage(bool colorize) {
    const char *b   = colorize ? ANSI_BOLD : "";
    const char *u   = colorize ? ANSI_UNDERLINE : "";
    const char *rst = colorize ? ANSI_RESET : "";

    printf("%sHLS(1)%s                   General Commands Manual                  %sHLS(1)%s\n\n", b, rst, b, rst);
    printf("%sNAME%s\n", b, rst);
    printf("     %shls%s -- hacker's directory visualizer and systems-level demonstrator\n\n", b, rst);
    printf("%sSYNOPSIS%s\n", b, rst);
    printf("     %shls%s [-%saFlrnRStHM@Gs%s] [-%sh%s] [-%sm%s] [%sfile%s ...]\n\n", b, rst, b, rst, b, rst, b, rst, u, rst);
    printf("%sDESCRIPTION%s\n", b, rst);
    printf("     %shls%s inspects POSIX file metadata, integrates low-level filesystem telemetry,\n", b, rst);
    printf("     interrogates Git status caches, and displays tree layouts and file contents.\n\n");
    printf("     Options:\n\n");
    printf("     %s-a%s      Include dotfiles in listings.\n", b, rst);
    printf("     %s-F%s      Classify entries with trailing symbols ('/', '*', '@', '|', '=').\n", b, rst);
    printf("     %s-G%s      Query working tree status via asynchronous Git pipeline batching.\n", b, rst);
    printf("     %s-h%s      Print concise usage summary.\n", b, rst);
    printf("     %s-H%s      Scale sizes using human-readable binary suffixes (base 1024).\n", b, rst);
    printf("     %s-l%s      Render long multi-column record format with permission matrices.\n", b, rst);
    printf("     %s-m%s      Output this clean manual page (ANSI stripped automatically when piped).\n", b, rst);
    printf("     %s-M%s      Sniff initial magic bytes of files to determine binary/text signatures.\n", b, rst);
    printf("     %s-n%s      Display numeric UIDs and GIDs without /etc/passwd resolution.\n", b, rst);
    printf("     %s-r%s      Invert active sorting comparison.\n", b, rst);
    printf("     %s-R%s      Recursively traverse subdirectories.\n", b, rst);
    printf("     %s-s%s      Compute disk block allocation efficiency and flag sparse storage.\n", b, rst);
    printf("     %s-S%s      Sort by logical file size descending.\n", b, rst);
    printf("     %s-t%s      Sort by modification timestamp descending.\n", b, rst);
    printf("     %s-T%s      Render hierarchical visual tree graph with cycle prevention.\n", b, rst);
    printf("     %s-@%s      Enumerate extended filesystem attributes (macOS and Linux xattrs).\n\n", b, rst);
    printf("HLS Project Suite               September 2026                         HLS(1)\n");
}

/* -------------------------------------------------------------------------
 * Driver Entry Point
 * ------------------------------------------------------------------------- */
int main(int argc, char *argv[]) {
    Config cfg = {
        .show_all = false,
        .long_format = false,
        .human_sizes = false,
        .classify = false,
        .sort_time = false,
        .sort_size = false,
        .reverse_sort = false,
        .recursive = false,
        .numeric_ids = false,
        .git_status = false,
        .show_xattr = false,
        .tree_view = false,
        .show_alloc = false,
        .sniff_type = false,
        .colorize = isatty(STDOUT_FILENO)
    };

    int opt;
    /* Synchronized optstring containing all active flags */
    while ((opt = getopt(argc, argv, "alHFtrRnShmGM@Ts")) != -1) {
        switch (opt) {
            case 'a': cfg.show_all = true;     break;
            case 'l': cfg.long_format = true;  break;
            case 'H': cfg.human_sizes = true;  break;
            case 'F': cfg.classify = true;     break;
            case 't': cfg.sort_time = true;    break;
            case 'S': cfg.sort_size = true;    break;
            case 'r': cfg.reverse_sort = true; break;
            case 'R': cfg.recursive = true;    break;
            case 'G': cfg.git_status = true;   break;
            case 'M': cfg.sniff_type = true;   break;
            case '@': cfg.show_xattr = true;   break;
            case 'T': cfg.tree_view = true;    break;
            case 's': cfg.show_alloc = true;   break;
            case 'n':
                cfg.long_format = true;
                cfg.numeric_ids = true;
                break;
            case 'h':
                print_short_help(argv[0]);
                exit(EXIT_SUCCESS);
            case 'm':
                print_manpage(isatty(STDOUT_FILENO));
                exit(EXIT_SUCCESS);
            default:
                fprintf(stderr, "Try '%s -h' for more information.\n", argv[0]);
                exit(EX_USAGE);
        }
    }

    int targets_count = argc - optind;
    if (targets_count <= 0) {
        traverse_directory(".", &cfg, false);
    } else if (targets_count == 1) {
        traverse_directory(argv[optind], &cfg, false);
    } else {
        for (int i = optind; i < argc; i++) {
            traverse_directory(argv[i], &cfg, true);
            if (i + 1 < argc) putchar('\n');
        }
    }

    return EXIT_SUCCESS;
}

Part 6: Final Verification

Recompiled with strict compiler checks enabled, installed the binary, and re-ran the verification suite:

make clean && make install
./test_hls.sh
=== Commencing Verification Suite ===
Default excludes dotfiles                    [PASS]
Flag -a reveals hidden files                 [PASS]
Flag -F classifies special types             [PASS]
Flag -S sorts descending by size             [PASS]
Flag -G detects Git status badges            [PASS]
Flag -s inspects disk block allocation       [PASS]
Flag -M sniffs file magic bytes              [PASS]
Flag -T renders tree hierarchy               [PASS]
Flag -@ enumerates extended attributes       [PASS]
=== Summary ===
Passed: 9
Failed: 0
Total:  9
ALL SYSTEMS NOMINAL!

Our custom tool now matches the performance and ergonomics of modern alternatives like eza and lsd—all written in direct, dependency-free POSIX C.

Building command-line utilities in C is rarely just about calling APIs. It’s about handling path differences between operating systems, debugging boolean edge cases, avoiding performance bottlenecks through subprocess isolation, and building test harnesses capable of catching regressions before release.