Skip to content
Myr

inject_errors.c

This file

Path

src/inject_errors.c

110 lines · 2.8 KiB · C

Last changed by

Not known.

History of this file

Take it

The walk stopped after 200 commits: lines older than 19453a6 point at it.

ci.yml: use sysctl -n hw.logicalcpu instead of nproc on macosEmanuele Torrebefore adoption19453a6

lines 1–110why, one step back
1#include <assert.h>
2#include <dlfcn.h>3#include <errno.h>4#include <stdio.h>5#include <string.h>6#include <unistd.h>78static FILE *fail;9static FILE *fail_read;10static FILE *fail_write;11static FILE *fail_close;12static int error;1314static FILE * (*real_fopen)(const char *, const char *);15static int (*real_fclose)(FILE *);16static int (*real_ferror)(FILE *);17static void (*real_clearerr)(FILE *);18static char * (*real_fgets)(char *, int, FILE *);19static size_t (*real_fread)(void *, size_t, size_t, FILE *);20static size_t (*real_fwrite)(const void *, size_t, size_t, FILE *);2122#define GET_REAL(sym) \23 do { \24 if (real_ ## sym == 0) { \25 real_ ## sym = dlsym(RTLD_NEXT, #sym); \26 assert(real_ ## sym != 0); \27 } \28 } while (0)2930#define dbg_write(msg) (void)write(2, msg, sizeof(msg) - 1)3132#define dbg() \33 do { \34 dbg_write("here: "); \35 dbg_write(__func__); \36 dbg_write("!\n"); \37 } while (0)3839FILE *fopen(const char *path, const char *mode) {40 GET_REAL(fopen);41 fail = fail_read = fail_write = fail_close = 0;42 FILE *f = real_fopen(path, mode);43 error = EIO;44 if (strcmp(path, "fail_read") == 0) {45 fail = fail_read = f;46 } else if (strncmp(path, "fail_write", sizeof("fail_write") - 1) == 0) {47 // Not that jq opens files for write anyways...48 fail = fail_write = f;49 if (strcmp(path, "fail_write_enospc") == 0)50 error = ENOSPC;51 } else if (strncmp(path, "fail_close", sizeof("fail_close") - 1) == 0) {52 fail = fail_close = f;53 if (strcmp(path, "fail_close_enospc") == 0)54 error = ENOSPC;55 }56 return f;57}5859int fclose(FILE *f) {60 GET_REAL(fclose);61 int res = real_fclose(f);62 if (fail_close == f) {63 fail = fail_read = fail_write = fail_close = 0;64 return EOF;65 }66 return res;67}6869char * fgets(char *buf, int len, FILE *f) {70 GET_REAL(fgets);71 char *res = real_fgets(buf, len, f);72 if (fail_read == f)73 return 0;74 return res;75}7677size_t fread(void *buf, size_t sz, size_t nemb, FILE *f) {78 GET_REAL(fread);79 size_t res = real_fread(buf, sz, nemb, f);80 if (fail_read == f)81 return 0;82 return res;83}8485size_t fwrite(const void *buf, size_t sz, size_t nemb, FILE *f) {86 GET_REAL(fwrite);87 size_t res = real_fwrite(buf, sz, nemb, f);88 if (fail_write == f)89 return 0;90 return res;91}9293int ferror(FILE *f) {94 GET_REAL(ferror);95 int res = real_ferror(f);96 if (fail == f) {97 errno = error;98 return 1;99 }100 return res;101}102103void clearerr(FILE *f) {104 GET_REAL(clearerr);105 real_clearerr(f);106 if (fail == f) {107 fail = fail_read = fail_write = fail_close = 0;108 error = 0;109 }110}