commit 9ae2287dc72c57a768e7a28507cda3c3a954387f
parent f6ae146cd891240813f4d609dfddc1f0d84f81f1
Author: Allis IO <0xa111510@gmail.com>
Date: Thu, 23 Apr 2020 22:46:11 -0400
Handle cache misses gracefully
If the user changes their config to cache a new value, recompiles, and
then runs paleofetch without `--recache`, we segfault when we go looking
for the new key in the now-stale cache.
This patch fixes that by checking whether `strstr()` found something
and bails if it didn't, guiding the user in the direction of the fix.
Because this seemed like a good use case for a formatted exit message,
`halt_and_catch_fire()` was refactored to behave like `fprintf(stderr, ...)`.
Token-pasting `__VA_ARGS__` is a widely adopted extension (at least, GCC
and Clang have supported it for ages) that I made us of so that I didn't
have to touch any of the other calls to `halt_and_catch_fire()`.
Without the `##`, they'd leave a trailing comma in the expansion and
result in invalid syntax.
Diffstat:
1 file changed, 11 insertions(+), 7 deletions(-)
diff --git a/paleofetch.c b/paleofetch.c
@@ -4,6 +4,7 @@
#include <stdbool.h>
#include <string.h>
#include <dirent.h>
+#include <errno.h>
#include <sys/utsname.h>
#include <sys/sysinfo.h>
@@ -29,12 +30,11 @@ struct sysinfo my_sysinfo;
int title_length;
int status;
-void halt_and_catch_fire(const char *message) {
- if(status != 0) {
- printf("paleofetch: %s\n", message);
- exit(status);
+#define halt_and_catch_fire(fmt, ...) \
+ if(status != 0) { \
+ fprintf(stderr, "paleofetch: " fmt "\n", ##__VA_ARGS__); \
+ exit(status); \
}
-}
/*
* Replaces the first newline character with null terminator
@@ -505,9 +505,13 @@ char *get_cache_file() {
* we might get in trouble would be if the user decided not to have any
* sort of sigil (like ':') after their labels. */
char *search_cache(char *cache_data, char *label) {
- char *start = strstr(cache_data, label) + strlen(label);
+ char *start = strstr(cache_data, label);
+ if(start == NULL) {
+ status = ENODATA;
+ halt_and_catch_fire("cache miss on key '%s'; need to --recache?", label);
+ }
+ start += strlen(label);
char *end = strchr(start, ';');
-
char *buf = calloc(1, BUF_SIZE);
// skip past the '=' and stop just before the ';'
strncpy(buf, start + 1, end - start - 1);