]> git.refcnt.org Git - colorize.git/blob - colorize.c
Include print_tstamp() under DEBUG only
[colorize.git] / colorize.c
1 /*
2 * colorize - Read text from standard input stream or file and print
3 * it colorized through use of ANSI escape sequences
4 *
5 * Copyright (c) 2011-2018 Steven Schubiger
6 *
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 *
20 */
21
22 #define _DEFAULT_SOURCE
23 #define _BSD_SOURCE
24 #define _XOPEN_SOURCE 700
25 #define _FILE_OFFSET_BITS 64
26 #include <assert.h>
27 #include <ctype.h>
28 #include <errno.h>
29 #include <getopt.h>
30 #include <stdarg.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <sys/time.h>
35 #include <sys/types.h>
36 #include <sys/stat.h>
37 #include <time.h>
38 #include <unistd.h>
39
40 #ifndef DEBUG
41 # define DEBUG 0
42 #endif
43
44 #define str(arg) #arg
45 #define to_str(arg) str(arg)
46
47 #define streq(s1, s2) (strcmp (s1, s2) == 0)
48 #define strneq(s1, s2, n) (strncmp (s1, s2, n) == 0)
49
50 #if !DEBUG
51 # define xmalloc(size) malloc_wrap(size)
52 # define xcalloc(nmemb, size) calloc_wrap(nmemb, size)
53 # define xrealloc(ptr, size) realloc_wrap(ptr, size)
54 # define xstrdup(str) strdup_wrap(str, NULL, 0)
55 # define str_concat(str1, str2) str_concat_wrap(str1, str2, NULL, 0)
56 #else
57 # define xmalloc(size) malloc_wrap_debug(size, __FILE__, __LINE__)
58 # define xcalloc(nmemb, size) calloc_wrap_debug(nmemb, size, __FILE__, __LINE__)
59 # define xrealloc(ptr, size) realloc_wrap_debug(ptr, size, __FILE__, __LINE__)
60 # define xstrdup(str) strdup_wrap(str, __FILE__, __LINE__)
61 # define str_concat(str1, str2) str_concat_wrap(str1, str2, __FILE__, __LINE__)
62 #endif
63
64 #define free_null(ptr) free_wrap((void **)&ptr)
65
66 #if defined(BUF_SIZE) && (BUF_SIZE <= 0 || BUF_SIZE > 65536)
67 # undef BUF_SIZE
68 #endif
69 #ifndef BUF_SIZE
70 # define BUF_SIZE 4096
71 #endif
72
73 #define LF 0x01
74 #define CR 0x02
75
76 #define COUNT_OF(obj, type) (sizeof (obj) / sizeof (type))
77
78 #define SKIP_LINE_ENDINGS(flags) ((flags) == (CR|LF) ? 2 : 1)
79
80 #define VALID_FILE_TYPE(mode) (S_ISREG (mode) || S_ISLNK (mode) || S_ISFIFO (mode))
81
82 #define STACK_VAR(ptr) do { \
83 stack_var (&vars_list, &stacked_vars, stacked_vars, ptr); \
84 } while (false)
85
86 #define RELEASE_VAR(ptr) do { \
87 release_var (vars_list, stacked_vars, (void **)&ptr); \
88 } while (false)
89
90 #if !DEBUG
91 # define MEM_ALLOC_FAIL() do { \
92 fprintf (stderr, "%s: memory allocation failure\n", program_name); \
93 exit (EXIT_FAILURE); \
94 } while (false)
95 #else
96 # define MEM_ALLOC_FAIL_DEBUG(file, line) do { \
97 fprintf (stderr, "Memory allocation failure in source file %s, line %u\n", file, line); \
98 exit (EXIT_FAILURE); \
99 } while (false)
100 #endif
101
102 #define ABORT_TRACE() \
103 fprintf (stderr, "Aborting in source file %s, line %u\n", __FILE__, __LINE__); \
104 abort ();
105
106 #define CHECK_COLORS_RANDOM(color1, color2) \
107 streq (color_names[color1]->name, "random") \
108 && (streq (color_names[color2]->name, "none") \
109 || streq (color_names[color2]->name, "default"))
110
111 #define ALLOC_COMPLETE_PART_LINE 8
112
113 #if defined(COLOR_SEP_CHAR_COLON)
114 # define COLOR_SEP_CHAR ':'
115 #elif defined(COLOR_SEP_CHAR_SLASH)
116 # define COLOR_SEP_CHAR '/'
117 #else
118 # define COLOR_SEP_CHAR '/'
119 #endif
120
121 #if DEBUG
122 # define DEBUG_FILE "debug.txt"
123 #endif
124
125 #define MAX_ATTRIBUTE_CHARS (6 * 2)
126
127 #define PROGRAM_NAME "colorize"
128
129 #define VERSION "0.64"
130
131 typedef enum { false, true } bool;
132
133 struct color_name {
134 char *name;
135 char *orig;
136 };
137
138 struct color {
139 const char *name;
140 const char *code;
141 };
142
143 static const struct color fg_colors[] = {
144 { "none", NULL },
145 { "black", "30m" },
146 { "red", "31m" },
147 { "green", "32m" },
148 { "yellow", "33m" },
149 { "blue", "34m" },
150 { "magenta", "35m" },
151 { "cyan", "36m" },
152 { "white", "37m" },
153 { "default", "39m" },
154 };
155 static const struct color bg_colors[] = {
156 { "none", NULL },
157 { "black", "40m" },
158 { "red", "41m" },
159 { "green", "42m" },
160 { "yellow", "43m" },
161 { "blue", "44m" },
162 { "magenta", "45m" },
163 { "cyan", "46m" },
164 { "white", "47m" },
165 { "default", "49m" },
166 };
167
168 struct bytes_size {
169 unsigned int size;
170 char unit;
171 };
172
173 enum {
174 FMT_GENERIC,
175 FMT_STRING,
176 FMT_QUOTE,
177 FMT_COLOR,
178 FMT_RANDOM,
179 FMT_ERROR,
180 FMT_FILE,
181 FMT_TYPE
182 };
183 static const char *formats[] = {
184 "%s", /* generic */
185 "%s '%s'", /* string */
186 "%s `%s' %s", /* quote */
187 "%s color '%s' %s", /* color */
188 "%s color '%s' %s '%s'", /* random */
189 "less than %lu bytes %s", /* error */
190 "%s: %s", /* file */
191 "%s: %s: %s", /* type */
192 };
193
194 enum { GENERIC, FOREGROUND = 0, BACKGROUND };
195
196 static const struct {
197 const struct color *entries;
198 unsigned int count;
199 const char *desc;
200 } tables[] = {
201 { fg_colors, COUNT_OF (fg_colors, struct color), "foreground" },
202 { bg_colors, COUNT_OF (bg_colors, struct color), "background" },
203 };
204
205 enum {
206 OPT_ATTR = 1,
207 OPT_CLEAN,
208 OPT_CLEAN_ALL,
209 OPT_EXCLUDE_RANDOM,
210 OPT_OMIT_COLOR_EMPTY,
211 OPT_HELP,
212 OPT_VERSION
213 };
214 static int opt_type;
215 static const struct option long_opts[] = {
216 { "attr", required_argument, &opt_type, OPT_ATTR },
217 { "clean", no_argument, &opt_type, OPT_CLEAN },
218 { "clean-all", no_argument, &opt_type, OPT_CLEAN_ALL },
219 { "exclude-random", required_argument, &opt_type, OPT_EXCLUDE_RANDOM },
220 { "omit-color-empty", no_argument, &opt_type, OPT_OMIT_COLOR_EMPTY },
221 { "help", no_argument, &opt_type, OPT_HELP },
222 { "version", no_argument, &opt_type, OPT_VERSION },
223 { NULL, 0, NULL, 0 },
224 };
225
226 enum attr_type {
227 ATTR_BOLD = 0x01,
228 ATTR_UNDERSCORE = 0x02,
229 ATTR_BLINK = 0x04,
230 ATTR_REVERSE = 0x08,
231 ATTR_CONCEALED = 0x10
232 };
233 struct attr {
234 const char *name;
235 unsigned int val;
236 enum attr_type type;
237 };
238
239 static FILE *stream;
240 #if DEBUG
241 static FILE *log;
242 #endif
243
244 static unsigned int stacked_vars;
245 static void **vars_list;
246
247 static bool clean;
248 static bool clean_all;
249 static bool omit_color_empty;
250
251 static char attr[MAX_ATTRIBUTE_CHARS + 1];
252 static char *exclude;
253
254 static const char *program_name;
255
256 #if DEBUG
257 static void print_tstamp (FILE *);
258 #endif
259 static void process_opts (int, char **);
260 static void process_opt_attr (const char *);
261 static void write_attr (const struct attr *, unsigned int *);
262 static void print_hint (void);
263 static void print_help (void);
264 static void print_version (void);
265 static void cleanup (void);
266 static void free_color_names (struct color_name **);
267 static void process_args (unsigned int, char **, char *, const struct color **, const char **, FILE **);
268 static void process_file_arg (const char *, const char **, FILE **);
269 static void skip_path_colors (const char *, const char *, const struct stat *);
270 static void gather_color_names (const char *, char *, struct color_name **);
271 static void read_print_stream (const char *, const struct color **, const char *, FILE *);
272 static void merge_print_line (const char *, const char *, FILE *);
273 static void complete_part_line (const char *, char **, FILE *);
274 static bool get_next_char (char *, const char **, FILE *, bool *);
275 static void save_char (char, char **, size_t *, size_t *);
276 static void find_color_entries (struct color_name **, const struct color **);
277 static void find_color_entry (const struct color_name *, unsigned int, const struct color **);
278 static void print_line (const char *, const struct color **, const char * const, unsigned int, bool);
279 static void print_clean (const char *);
280 static bool is_esc (const char *);
281 static const char *get_end_of_esc (const char *);
282 static const char *get_end_of_text (const char *);
283 static void print_text (const char *, size_t);
284 static bool gather_esc_offsets (const char *, const char **, const char **);
285 static bool validate_esc_clean_all (const char **);
286 static bool validate_esc_clean (int, unsigned int, unsigned int *, const char **, bool *);
287 static bool is_reset (int, unsigned int, const char **);
288 static bool is_attr (int, unsigned int, unsigned int, const char **);
289 static bool is_fg_color (int, const char **);
290 static bool is_bg_color (int, unsigned int, const char **);
291 #if !DEBUG
292 static void *malloc_wrap (size_t);
293 static void *calloc_wrap (size_t, size_t);
294 static void *realloc_wrap (void *, size_t);
295 #else
296 static void *malloc_wrap_debug (size_t, const char *, unsigned int);
297 static void *calloc_wrap_debug (size_t, size_t, const char *, unsigned int);
298 static void *realloc_wrap_debug (void *, size_t, const char *, unsigned int);
299 #endif
300 static void free_wrap (void **);
301 static char *strdup_wrap (const char *, const char *, unsigned int);
302 static char *str_concat_wrap (const char *, const char *, const char *, unsigned int);
303 static bool get_bytes_size (unsigned long, struct bytes_size *);
304 static char *get_file_type (mode_t);
305 static bool has_color_name (const char *, const char *);
306 static FILE *open_file (const char *, const char *);
307 static void vfprintf_diag (const char *, ...);
308 static void vfprintf_fail (const char *, ...);
309 static void stack_var (void ***, unsigned int *, unsigned int, void *);
310 static void release_var (void **, unsigned int, void **);
311
312 extern int optind;
313
314 int
315 main (int argc, char **argv)
316 {
317 unsigned int arg_cnt;
318
319 const struct color *colors[2] = {
320 NULL, /* foreground */
321 NULL, /* background */
322 };
323
324 const char *file = NULL;
325
326 program_name = argv[0];
327 atexit (cleanup);
328
329 setvbuf (stdout, NULL, _IOLBF, 0);
330
331 #if DEBUG
332 log = open_file (DEBUG_FILE, "w");
333 print_tstamp (log);
334 #endif
335
336 attr[0] = '\0';
337
338 process_opts (argc, argv);
339
340 arg_cnt = argc - optind;
341
342 if (clean || clean_all)
343 {
344 if (clean && clean_all)
345 vfprintf_fail (formats[FMT_GENERIC], "--clean and --clean-all switch are mutually exclusive");
346 if (arg_cnt > 1)
347 {
348 const char *const format = "%s %s";
349 const char *const message = "switch cannot be used with more than one file";
350 if (clean)
351 vfprintf_fail (format, "--clean", message);
352 else if (clean_all)
353 vfprintf_fail (format, "--clean-all", message);
354 }
355 }
356 else
357 {
358 if (arg_cnt == 0 || arg_cnt > 2)
359 {
360 vfprintf_diag ("%u arguments provided, expected 1-2 arguments or clean option", arg_cnt);
361 print_hint ();
362 exit (EXIT_FAILURE);
363 }
364 }
365
366 if (clean || clean_all)
367 process_file_arg (argv[optind], &file, &stream);
368 else
369 process_args (arg_cnt, &argv[optind], &attr[0], colors, &file, &stream);
370 read_print_stream (&attr[0], colors, file, stream);
371
372 RELEASE_VAR (exclude);
373
374 exit (EXIT_SUCCESS);
375 }
376
377 #if DEBUG
378 static void
379 print_tstamp (FILE *log)
380 {
381 time_t t;
382 struct tm *tm;
383 char str[128];
384 size_t written;
385
386 t = time (NULL);
387 tm = localtime (&t);
388 if (tm == NULL)
389 {
390 perror ("localtime");
391 exit (EXIT_FAILURE);
392 }
393 written = strftime (str, sizeof (str), "%Y-%m-%d %H:%M:%S %Z", tm);
394 if (written == 0)
395 vfprintf_fail (formats[FMT_GENERIC], "strftime: 0 returned");
396
397 fprintf (log, "%s\n", str);
398 while (written--)
399 fprintf (log, "=");
400 fprintf (log, "\n");
401 }
402 #endif
403
404 #define PRINT_HELP_EXIT() \
405 print_help (); \
406 exit (EXIT_SUCCESS);
407
408 #define PRINT_VERSION_EXIT() \
409 print_version (); \
410 exit (EXIT_SUCCESS);
411
412 extern char *optarg;
413
414 static void
415 process_opts (int argc, char **argv)
416 {
417 int opt;
418 while ((opt = getopt_long (argc, argv, "hV", long_opts, NULL)) != -1)
419 {
420 switch (opt)
421 {
422 case 0: /* long opts */
423 switch (opt_type)
424 {
425 case OPT_ATTR:
426 process_opt_attr (optarg);
427 break;
428 case OPT_CLEAN:
429 clean = true;
430 break;
431 case OPT_CLEAN_ALL:
432 clean_all = true;
433 break;
434 case OPT_EXCLUDE_RANDOM: {
435 bool valid = false;
436 unsigned int i;
437 exclude = xstrdup (optarg);
438 STACK_VAR (exclude);
439 for (i = 1; i < tables[GENERIC].count - 1; i++) /* skip color none and default */
440 {
441 const struct color *entry = &tables[GENERIC].entries[i];
442 if (streq (exclude, entry->name))
443 {
444 valid = true;
445 break;
446 }
447 }
448 if (!valid)
449 vfprintf_fail (formats[FMT_GENERIC], "--exclude-random switch must be provided a plain color");
450 break;
451 }
452 case OPT_OMIT_COLOR_EMPTY:
453 omit_color_empty = true;
454 break;
455 case OPT_HELP:
456 PRINT_HELP_EXIT ();
457 case OPT_VERSION:
458 PRINT_VERSION_EXIT ();
459 default: /* never reached */
460 ABORT_TRACE ();
461 }
462 break;
463 case 'h':
464 PRINT_HELP_EXIT ();
465 case 'V':
466 PRINT_VERSION_EXIT ();
467 case '?':
468 print_hint ();
469 exit (EXIT_FAILURE);
470 default: /* never reached */
471 ABORT_TRACE ();
472 }
473 }
474 }
475
476 static void
477 process_opt_attr (const char *p)
478 {
479 /* If attributes are added to this "list", also increase MAX_ATTRIBUTE_CHARS! */
480 const struct attr attrs[] = {
481 { "bold", 1, ATTR_BOLD },
482 { "underscore", 4, ATTR_UNDERSCORE },
483 { "blink", 5, ATTR_BLINK },
484 { "reverse", 7, ATTR_REVERSE },
485 { "concealed", 8, ATTR_CONCEALED },
486 };
487 unsigned int attr_types = 0;
488
489 while (*p)
490 {
491 const char *s;
492 if (!isalnum (*p))
493 vfprintf_fail (formats[FMT_GENERIC], "--attr switch must be provided a string");
494 s = p;
495 while (isalnum (*p))
496 p++;
497 if (*p != '\0' && *p != ',')
498 vfprintf_fail (formats[FMT_GENERIC], "--attr switch must have strings separated by ,");
499 else
500 {
501 bool valid_attr = false;
502 unsigned int i;
503 for (i = 0; i < COUNT_OF (attrs, struct attr); i++)
504 {
505 const size_t name_len = strlen (attrs[i].name);
506 if ((size_t)(p - s) == name_len && strneq (s, attrs[i].name, name_len))
507 {
508 write_attr (&attrs[i], &attr_types);
509 valid_attr = true;
510 break;
511 }
512 }
513 if (!valid_attr)
514 {
515 char *attr_invalid = xmalloc ((p - s) + 1);
516 STACK_VAR (attr_invalid);
517 strncpy (attr_invalid, s, p - s);
518 attr_invalid[p - s] = '\0';
519 vfprintf_fail ("--attr switch attribute '%s' is not valid", attr_invalid);
520 RELEASE_VAR (attr_invalid); /* never reached */
521 }
522 }
523 if (*p)
524 p++;
525 }
526 }
527
528 static void
529 write_attr (const struct attr *attr_i, unsigned int *attr_types)
530 {
531 const unsigned int val = attr_i->val;
532 const enum attr_type attr_type = attr_i->type;
533 const char *attr_name = attr_i->name;
534
535 if (*attr_types & attr_type)
536 vfprintf_fail ("--attr switch has attribute '%s' twice or more", attr_name);
537 snprintf (attr + strlen (attr), 3, "%u;", val);
538 *attr_types |= attr_type;
539 }
540
541 static void
542 print_hint (void)
543 {
544 fprintf (stderr, "Type `%s --help' for help screen.\n", program_name);
545 }
546
547 static void
548 print_help (void)
549 {
550 struct opt_data {
551 const char *name;
552 const char *short_opt;
553 const char *arg;
554 };
555 const struct opt_data opts_data[] = {
556 { "attr", NULL, "=ATTR1,ATTR2,..." },
557 { "exclude-random", NULL, "=COLOR" },
558 { "help", "h", NULL },
559 { "version", "V", NULL },
560 };
561 const struct option *opt = long_opts;
562 unsigned int i;
563
564 printf ("Usage: %s (foreground) OR (foreground)%c(background) OR --clean[-all] [-|file]\n\n", program_name, COLOR_SEP_CHAR);
565 printf ("\tColors (foreground) (background)\n");
566 for (i = 0; i < tables[FOREGROUND].count; i++)
567 {
568 const struct color *entry = &tables[FOREGROUND].entries[i];
569 const char *name = entry->name;
570 const char *code = entry->code;
571 if (code)
572 printf ("\t\t{\033[%s#\033[0m} [%c%c]%s%*s%s\n",
573 code, toupper (*name), *name, name + 1, 10 - (int)strlen (name), " ", name);
574 else
575 printf ("\t\t{-} %s%*s%s\n", name, 13 - (int)strlen (name), " ", name);
576 }
577 printf ("\t\t{*} [Rr]%s%*s%s [--exclude-random=<foreground color>]\n", "andom", 10 - (int)strlen ("random"), " ", "random");
578
579 printf ("\n\tFirst character of color name in upper case denotes increased intensity,\n");
580 printf ("\twhereas for lower case colors will be of normal intensity.\n");
581
582 printf ("\n\tOptions\n");
583 for (; opt->name; opt++)
584 {
585 const struct opt_data *opt_data = NULL;
586 unsigned int i;
587 for (i = 0; i < COUNT_OF (opts_data, struct opt_data); i++)
588 if (streq (opt->name, opts_data[i].name))
589 {
590 opt_data = &opts_data[i];
591 break;
592 }
593 if (opt_data)
594 {
595 if (opt_data->short_opt)
596 printf ("\t\t-%s, --%s\n", opt_data->short_opt, opt->name);
597 else
598 printf ("\t\t --%s%s\n", opt->name, opt_data->arg);
599 }
600 else
601 printf ("\t\t --%s\n", opt->name);
602 }
603 printf ("\n");
604 }
605
606 static void
607 print_version (void)
608 {
609 #ifdef HAVE_VERSION
610 # include "version.h"
611 #else
612 const char *const version = NULL;
613 #endif
614 const char *version_prefix, *version_string;
615 const char *c_flags, *ld_flags, *cpp_flags;
616 const char *const desc_flags_unknown = "unknown";
617 struct bytes_size bytes_size;
618 bool debug;
619 #ifdef CFLAGS
620 c_flags = to_str (CFLAGS);
621 #else
622 c_flags = desc_flags_unknown;
623 #endif
624 #ifdef LDFLAGS
625 ld_flags = to_str (LDFLAGS);
626 #else
627 ld_flags = desc_flags_unknown;
628 #endif
629 #ifdef CPPFLAGS
630 cpp_flags = to_str (CPPFLAGS);
631 #else
632 cpp_flags = desc_flags_unknown;
633 #endif
634 #if DEBUG
635 debug = true;
636 #else
637 debug = false;
638 #endif
639 version_prefix = version ? "" : "v";
640 version_string = version ? version : VERSION;
641 printf ("%s %s%s (compiled at %s, %s)\n", PROGRAM_NAME, version_prefix, version_string, __DATE__, __TIME__);
642
643 printf ("Compiler flags: %s\n", c_flags);
644 printf ("Linker flags: %s\n", ld_flags);
645 printf ("Preprocessor flags: %s\n", cpp_flags);
646 if (get_bytes_size (BUF_SIZE, &bytes_size))
647 {
648 if (BUF_SIZE % 1024 == 0)
649 printf ("Buffer size: %u%c\n", bytes_size.size, bytes_size.unit);
650 else
651 printf ("Buffer size: %u%c, %u byte%s\n", bytes_size.size, bytes_size.unit,
652 BUF_SIZE % 1024, BUF_SIZE % 1024 > 1 ? "s" : "");
653 }
654 else
655 printf ("Buffer size: %lu byte%s\n", (unsigned long)BUF_SIZE, BUF_SIZE > 1 ? "s" : "");
656 printf ("Color separator: '%c'\n", COLOR_SEP_CHAR);
657 printf ("Debugging: %s\n", debug ? "yes" : "no");
658 }
659
660 static void
661 cleanup (void)
662 {
663 if (stream && fileno (stream) != STDIN_FILENO)
664 fclose (stream);
665 #if DEBUG
666 if (log)
667 fclose (log);
668 #endif
669
670 if (vars_list)
671 {
672 unsigned int i;
673 for (i = 0; i < stacked_vars; i++)
674 free (vars_list[i]);
675 free_null (vars_list);
676 }
677 }
678
679 static void
680 free_color_names (struct color_name **color_names)
681 {
682 unsigned int i;
683 for (i = 0; color_names[i]; i++)
684 {
685 RELEASE_VAR (color_names[i]->name);
686 RELEASE_VAR (color_names[i]->orig);
687 RELEASE_VAR (color_names[i]);
688 }
689 }
690
691 static void
692 process_args (unsigned int arg_cnt, char **arg_strings, char *attr, const struct color **colors, const char **file, FILE **stream)
693 {
694 int ret;
695 char *p;
696 struct stat sb;
697 struct color_name *color_names[3] = {
698 NULL, /* foreground */
699 NULL, /* background */
700 NULL, /* sentinel value */
701 };
702
703 const char *color_string = arg_cnt >= 1 ? arg_strings[0] : NULL;
704 const char *file_string = arg_cnt == 2 ? arg_strings[1] : NULL;
705
706 assert (color_string != NULL);
707
708 if (streq (color_string, "-"))
709 {
710 if (file_string)
711 vfprintf_fail (formats[FMT_GENERIC], "hyphen cannot be used as color string");
712 else
713 vfprintf_fail (formats[FMT_GENERIC], "hyphen must be preceded by color string");
714 }
715
716 ret = lstat (color_string, &sb);
717
718 /* Ensure that we don't fail if there's a file with one or more
719 color names in its path. */
720 if (ret == 0) /* success */
721 skip_path_colors (color_string, file_string, &sb);
722
723 if ((p = strchr (color_string, COLOR_SEP_CHAR)))
724 {
725 if (p == color_string)
726 vfprintf_fail (formats[FMT_STRING], "foreground color missing in string", color_string);
727 else if (p == color_string + strlen (color_string) - 1)
728 vfprintf_fail (formats[FMT_STRING], "background color missing in string", color_string);
729 else if (strchr (++p, COLOR_SEP_CHAR))
730 vfprintf_fail (formats[FMT_STRING], "one color pair allowed only for string", color_string);
731 }
732
733 gather_color_names (color_string, attr, color_names);
734
735 assert (color_names[FOREGROUND] != NULL);
736
737 if (color_names[BACKGROUND])
738 {
739 unsigned int i;
740 const unsigned int color_sets[2][2] = { { FOREGROUND, BACKGROUND }, { BACKGROUND, FOREGROUND } };
741 for (i = 0; i < 2; i++)
742 {
743 const unsigned int color1 = color_sets[i][0];
744 const unsigned int color2 = color_sets[i][1];
745 if (CHECK_COLORS_RANDOM (color1, color2))
746 vfprintf_fail (formats[FMT_RANDOM], tables[color1].desc, color_names[color1]->orig, "cannot be combined with", color_names[color2]->orig);
747 }
748 }
749
750 find_color_entries (color_names, colors);
751 assert (colors[FOREGROUND] != NULL);
752 free_color_names (color_names);
753
754 if (!colors[FOREGROUND]->code && colors[BACKGROUND] && colors[BACKGROUND]->code)
755 {
756 struct color_name color_name;
757 color_name.name = color_name.orig = "default";
758
759 find_color_entry (&color_name, FOREGROUND, colors);
760 assert (colors[FOREGROUND]->code != NULL);
761 }
762
763 process_file_arg (file_string, file, stream);
764 }
765
766 static void
767 process_file_arg (const char *file_string, const char **file, FILE **stream)
768 {
769 if (file_string)
770 {
771 if (streq (file_string, "-"))
772 *stream = stdin;
773 else
774 {
775 const char *file = file_string;
776 struct stat sb;
777 int ret;
778
779 errno = 0;
780 ret = stat (file, &sb);
781
782 if (ret == -1)
783 vfprintf_fail (formats[FMT_FILE], file, strerror (errno));
784
785 if (!VALID_FILE_TYPE (sb.st_mode))
786 vfprintf_fail (formats[FMT_TYPE], file, "unrecognized type", get_file_type (sb.st_mode));
787
788 *stream = open_file (file, "r");
789 }
790 *file = file_string;
791 }
792 else
793 {
794 *stream = stdin;
795 *file = "stdin";
796 }
797
798 assert (*stream != NULL);
799 assert (*file != NULL);
800 }
801
802 static void
803 skip_path_colors (const char *color_string, const char *file_string, const struct stat *sb)
804 {
805 bool have_file;
806 unsigned int c;
807 const char *color = color_string;
808 const mode_t mode = sb->st_mode;
809
810 for (c = 1; c <= 2 && *color; c++)
811 {
812 bool matched = false;
813 unsigned int i;
814 for (i = 0; i < tables[GENERIC].count; i++)
815 {
816 const struct color *entry = &tables[GENERIC].entries[i];
817 if (has_color_name (color, entry->name))
818 {
819 color += strlen (entry->name);
820 matched = true;
821 break;
822 }
823 }
824 if (!matched && has_color_name (color, "random"))
825 {
826 color += strlen ("random");
827 matched = true;
828 }
829 if (matched && *color == COLOR_SEP_CHAR && *(color + 1))
830 color++;
831 else
832 break;
833 }
834
835 have_file = (*color != '\0');
836
837 if (have_file)
838 {
839 const char *file_existing = color_string;
840 if (file_string)
841 vfprintf_fail (formats[FMT_QUOTE], get_file_type (mode), file_existing, "cannot be used as color string");
842 else
843 {
844 if (VALID_FILE_TYPE (mode))
845 vfprintf_fail (formats[FMT_QUOTE], get_file_type (mode), file_existing, "must be preceded by color string");
846 else
847 vfprintf_fail (formats[FMT_QUOTE], get_file_type (mode), file_existing, "is not a valid file type");
848 }
849 }
850 }
851
852 static void
853 gather_color_names (const char *color_string, char *attr, struct color_name **color_names)
854 {
855 unsigned int index;
856 char *color, *p, *str;
857
858 str = xstrdup (color_string);
859 STACK_VAR (str);
860
861 for (index = 0, color = str; *color; index++, color = p)
862 {
863 char *ch, *sep;
864
865 p = NULL;
866 if ((sep = strchr (color, COLOR_SEP_CHAR)))
867 {
868 *sep = '\0';
869 p = sep + 1;
870 }
871 else
872 p = color + strlen (color);
873 assert (p != NULL);
874
875 for (ch = color; *ch; ch++)
876 if (!isalpha (*ch))
877 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be made of non-alphabetic characters");
878
879 for (ch = color + 1; *ch; ch++)
880 if (!islower (*ch))
881 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be in mixed lower/upper case");
882
883 if (streq (color, "None"))
884 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be bold");
885
886 if (isupper (*color))
887 {
888 switch (index)
889 {
890 case FOREGROUND:
891 snprintf (attr + strlen (attr), 3, "1;");
892 break;
893 case BACKGROUND:
894 vfprintf_fail (formats[FMT_COLOR], tables[BACKGROUND].desc, color, "cannot be bold");
895 default: /* never reached */
896 ABORT_TRACE ();
897 }
898 }
899
900 color_names[index] = xcalloc (1, sizeof (struct color_name));
901 STACK_VAR (color_names[index]);
902
903 color_names[index]->orig = xstrdup (color);
904 STACK_VAR (color_names[index]->orig);
905
906 for (ch = color; *ch; ch++)
907 *ch = tolower (*ch);
908
909 color_names[index]->name = xstrdup (color);
910 STACK_VAR (color_names[index]->name);
911 }
912
913 RELEASE_VAR (str);
914 }
915
916 static void
917 read_print_stream (const char *attr, const struct color **colors, const char *file, FILE *stream)
918 {
919 char buf[BUF_SIZE + 1];
920 unsigned int flags = 0;
921
922 while (!feof (stream))
923 {
924 size_t bytes_read;
925 char *eol;
926 const char *line;
927 bytes_read = fread (buf, 1, BUF_SIZE, stream);
928 if (bytes_read != BUF_SIZE && ferror (stream))
929 vfprintf_fail (formats[FMT_ERROR], BUF_SIZE, "read");
930 buf[bytes_read] = '\0';
931 line = buf;
932 while ((eol = strpbrk (line, "\n\r")))
933 {
934 const bool has_text = (eol > line);
935 const char *p;
936 flags &= ~(CR|LF);
937 if (*eol == '\r')
938 {
939 flags |= CR;
940 if (*(eol + 1) == '\n')
941 flags |= LF;
942 }
943 else if (*eol == '\n')
944 flags |= LF;
945 else /* never reached */
946 vfprintf_fail (formats[FMT_FILE], file, "unrecognized line ending");
947 p = eol + SKIP_LINE_ENDINGS (flags);
948 *eol = '\0';
949 print_line (attr, colors, line, flags,
950 omit_color_empty ? has_text : true);
951 line = p;
952 }
953 if (feof (stream))
954 {
955 if (*line != '\0')
956 print_line (attr, colors, line, 0, true);
957 }
958 else if (*line != '\0')
959 {
960 char *p;
961 if ((clean || clean_all) && (p = strrchr (line, '\033')))
962 merge_print_line (line, p, stream);
963 else
964 print_line (attr, colors, line, 0, true);
965 }
966 }
967 }
968
969 static void
970 merge_print_line (const char *line, const char *p, FILE *stream)
971 {
972 char *buf = NULL;
973 char *merged_esc = NULL;
974 const char *esc = "";
975 const char char_restore = *p;
976
977 complete_part_line (p + 1, &buf, stream);
978
979 if (buf)
980 {
981 /* form escape sequence */
982 esc = merged_esc = str_concat (p, buf);
983 /* shorten partial line accordingly */
984 *(char *)p = '\0';
985 free (buf);
986 }
987
988 #ifdef TEST_MERGE_PART_LINE
989 printf ("%s%s", line, esc);
990 fflush (stdout);
991 _exit (EXIT_SUCCESS);
992 #else
993 print_clean (line);
994 *(char *)p = char_restore;
995 print_clean (esc);
996 free (merged_esc);
997 #endif
998 }
999
1000 static void
1001 complete_part_line (const char *p, char **buf, FILE *stream)
1002 {
1003 bool got_next_char = false, read_from_stream;
1004 char ch;
1005 size_t i = 0, size;
1006
1007 if (get_next_char (&ch, &p, stream, &read_from_stream))
1008 {
1009 if (ch == '[')
1010 {
1011 if (read_from_stream)
1012 save_char (ch, buf, &i, &size);
1013 }
1014 else
1015 {
1016 if (read_from_stream)
1017 ungetc ((int)ch, stream);
1018 return; /* cancel */
1019 }
1020 }
1021 else
1022 return; /* cancel */
1023
1024 while (get_next_char (&ch, &p, stream, &read_from_stream))
1025 {
1026 if (isdigit (ch) || ch == ';')
1027 {
1028 if (read_from_stream)
1029 save_char (ch, buf, &i, &size);
1030 }
1031 else /* got next character */
1032 {
1033 got_next_char = true;
1034 break;
1035 }
1036 }
1037
1038 if (got_next_char)
1039 {
1040 if (ch == 'm')
1041 {
1042 if (read_from_stream)
1043 save_char (ch, buf, &i, &size);
1044 }
1045 else
1046 {
1047 if (read_from_stream)
1048 ungetc ((int)ch, stream);
1049 return; /* cancel */
1050 }
1051 }
1052 else
1053 return; /* cancel */
1054 }
1055
1056 static bool
1057 get_next_char (char *ch, const char **p, FILE *stream, bool *read_from_stream)
1058 {
1059 if (**p == '\0')
1060 {
1061 int c;
1062 if ((c = fgetc (stream)) != EOF)
1063 {
1064 *ch = (char)c;
1065 *read_from_stream = true;
1066 return true;
1067 }
1068 else
1069 {
1070 *read_from_stream = false;
1071 return false;
1072 }
1073 }
1074 else
1075 {
1076 *ch = **p;
1077 (*p)++;
1078 *read_from_stream = false;
1079 return true;
1080 }
1081 }
1082
1083 static void
1084 save_char (char ch, char **buf, size_t *i, size_t *size)
1085 {
1086 if (!*buf)
1087 {
1088 *size = ALLOC_COMPLETE_PART_LINE;
1089 *buf = xmalloc (*size);
1090 }
1091 /* +1: effective occupied size of buffer */
1092 else if ((*i + 1) == *size)
1093 {
1094 *size *= 2;
1095 *buf = xrealloc (*buf, *size);
1096 }
1097 (*buf)[*i] = ch;
1098 (*buf)[*i + 1] = '\0';
1099 (*i)++;
1100 }
1101
1102 static void
1103 find_color_entries (struct color_name **color_names, const struct color **colors)
1104 {
1105 struct timeval tv;
1106 unsigned int index;
1107
1108 /* randomness */
1109 gettimeofday (&tv, NULL);
1110 srand (tv.tv_usec * tv.tv_sec);
1111
1112 for (index = 0; color_names[index]; index++)
1113 {
1114 const char *color_name = color_names[index]->name;
1115
1116 const unsigned int count = tables[index].count;
1117 const struct color *const color_entries = tables[index].entries;
1118
1119 if (streq (color_name, "random"))
1120 {
1121 bool excludable;
1122 unsigned int i;
1123 do {
1124 excludable = false;
1125 i = rand() % (count - 2) + 1; /* omit color none and default */
1126 switch (index)
1127 {
1128 case FOREGROUND:
1129 /* --exclude-random */
1130 if (exclude && streq (exclude, color_entries[i].name))
1131 excludable = true;
1132 else if (color_names[BACKGROUND] && streq (color_names[BACKGROUND]->name, color_entries[i].name))
1133 excludable = true;
1134 break;
1135 case BACKGROUND:
1136 if (streq (colors[FOREGROUND]->name, color_entries[i].name))
1137 excludable = true;
1138 break;
1139 default: /* never reached */
1140 ABORT_TRACE ();
1141 }
1142 } while (excludable);
1143 colors[index] = (struct color *)&color_entries[i];
1144 }
1145 else
1146 find_color_entry (color_names[index], index, colors);
1147 }
1148 }
1149
1150 static void
1151 find_color_entry (const struct color_name *color_name, unsigned int index, const struct color **colors)
1152 {
1153 bool found = false;
1154 unsigned int i;
1155
1156 const unsigned int count = tables[index].count;
1157 const struct color *const color_entries = tables[index].entries;
1158
1159 for (i = 0; i < count; i++)
1160 if (streq (color_name->name, color_entries[i].name))
1161 {
1162 colors[index] = (struct color *)&color_entries[i];
1163 found = true;
1164 break;
1165 }
1166 if (!found)
1167 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color_name->orig, "not recognized");
1168 }
1169
1170 static void
1171 print_line (const char *attr, const struct color **colors, const char *const line, unsigned int flags, bool emit_colors)
1172 {
1173 /* --clean[-all] */
1174 if (clean || clean_all)
1175 print_clean (line);
1176 /* skip for --omit-color-empty? */
1177 else if (emit_colors)
1178 {
1179 /* Foreground color code is guaranteed to be set when background color code is present. */
1180 if (colors[BACKGROUND] && colors[BACKGROUND]->code)
1181 printf ("\033[%s", colors[BACKGROUND]->code);
1182 if (colors[FOREGROUND]->code)
1183 printf ("\033[%s%s%s\033[0m", attr, colors[FOREGROUND]->code, line);
1184 else
1185 printf (formats[FMT_GENERIC], line);
1186 }
1187 if (flags & CR)
1188 putchar ('\r');
1189 if (flags & LF)
1190 putchar ('\n');
1191 }
1192
1193 static void
1194 print_clean (const char *line)
1195 {
1196 const char *p = line;
1197
1198 if (is_esc (p))
1199 p = get_end_of_esc (p);
1200
1201 while (*p != '\0')
1202 {
1203 const char *text_start = p;
1204 const char *text_end = get_end_of_text (p);
1205 print_text (text_start, text_end - text_start);
1206 p = get_end_of_esc (text_end);
1207 }
1208 }
1209
1210 static bool
1211 is_esc (const char *p)
1212 {
1213 return gather_esc_offsets (p, NULL, NULL);
1214 }
1215
1216 static const char *
1217 get_end_of_esc (const char *p)
1218 {
1219 const char *esc;
1220 const char *end = NULL;
1221 while ((esc = strchr (p, '\033')))
1222 {
1223 if (gather_esc_offsets (esc, NULL, &end))
1224 break;
1225 p = esc + 1;
1226 }
1227 return end ? end + 1 : p + strlen (p);
1228 }
1229
1230 static const char *
1231 get_end_of_text (const char *p)
1232 {
1233 const char *esc;
1234 const char *start = NULL;
1235 while ((esc = strchr (p, '\033')))
1236 {
1237 if (gather_esc_offsets (esc, &start, NULL))
1238 break;
1239 p = esc + 1;
1240 }
1241 return start ? start : p + strlen (p);
1242 }
1243
1244 static void
1245 print_text (const char *p, size_t len)
1246 {
1247 size_t bytes_written;
1248 bytes_written = fwrite (p, 1, len, stdout);
1249 if (bytes_written != len)
1250 vfprintf_fail (formats[FMT_ERROR], (unsigned long)len, "written");
1251 }
1252
1253 static bool
1254 gather_esc_offsets (const char *p, const char **start, const char **end)
1255 {
1256 /* ESC[ */
1257 if (*p == 27 && *(p + 1) == '[')
1258 {
1259 bool valid = false;
1260 const char *const begin = p;
1261 p += 2;
1262 if (clean_all)
1263 valid = validate_esc_clean_all (&p);
1264 else if (clean)
1265 {
1266 bool check_values;
1267 unsigned int prev_iter, iter;
1268 const char *digit;
1269 prev_iter = iter = 0;
1270 do {
1271 check_values = false;
1272 iter++;
1273 if (!isdigit (*p))
1274 break;
1275 digit = p;
1276 while (isdigit (*p))
1277 p++;
1278 if (p - digit > 2)
1279 break;
1280 else /* check range */
1281 {
1282 char val[3];
1283 int value;
1284 unsigned int i;
1285 const unsigned int digits = p - digit;
1286 for (i = 0; i < digits; i++)
1287 val[i] = *digit++;
1288 val[i] = '\0';
1289 value = atoi (val);
1290 valid = validate_esc_clean (value, iter, &prev_iter, &p, &check_values);
1291 }
1292 } while (check_values);
1293 }
1294 if (valid)
1295 {
1296 if (start)
1297 *start = begin;
1298 if (end)
1299 *end = p;
1300 return true;
1301 }
1302 }
1303 return false;
1304 }
1305
1306 static bool
1307 validate_esc_clean_all (const char **p)
1308 {
1309 while (isdigit (**p) || **p == ';')
1310 (*p)++;
1311 return (**p == 'm');
1312 }
1313
1314 static bool
1315 validate_esc_clean (int value, unsigned int iter, unsigned int *prev_iter, const char **p, bool *check_values)
1316 {
1317 if (is_reset (value, iter, p))
1318 return true;
1319 else if (is_attr (value, iter, *prev_iter, p))
1320 {
1321 (*p)++;
1322 *check_values = true;
1323 *prev_iter = iter;
1324 return false; /* partial escape sequence, need another valid value */
1325 }
1326 else if (is_fg_color (value, p))
1327 return true;
1328 else if (is_bg_color (value, iter, p))
1329 return true;
1330 else
1331 return false;
1332 }
1333
1334 static bool
1335 is_reset (int value, unsigned int iter, const char **p)
1336 {
1337 return (value == 0 && iter == 1 && **p == 'm');
1338 }
1339
1340 static bool
1341 is_attr (int value, unsigned int iter, unsigned int prev_iter, const char **p)
1342 {
1343 return ((value > 0 && value < 10) && (iter - prev_iter == 1) && **p == ';');
1344 }
1345
1346 static bool
1347 is_fg_color (int value, const char **p)
1348 {
1349 return (((value >= 30 && value <= 37) || value == 39) && **p == 'm');
1350 }
1351
1352 static bool
1353 is_bg_color (int value, unsigned int iter, const char **p)
1354 {
1355 return (((value >= 40 && value <= 47) || value == 49) && iter == 1 && **p == 'm');
1356 }
1357
1358 #if !DEBUG
1359 static void *
1360 malloc_wrap (size_t size)
1361 {
1362 void *p = malloc (size);
1363 if (!p)
1364 MEM_ALLOC_FAIL ();
1365 return p;
1366 }
1367
1368 static void *
1369 calloc_wrap (size_t nmemb, size_t size)
1370 {
1371 void *p = calloc (nmemb, size);
1372 if (!p)
1373 MEM_ALLOC_FAIL ();
1374 return p;
1375 }
1376
1377 static void *
1378 realloc_wrap (void *ptr, size_t size)
1379 {
1380 void *p = realloc (ptr, size);
1381 if (!p)
1382 MEM_ALLOC_FAIL ();
1383 return p;
1384 }
1385 #else
1386 static const char *const format_debug = "%s: %10s %7lu bytes [source file %s, line %5u]\n";
1387 static void *
1388 malloc_wrap_debug (size_t size, const char *file, unsigned int line)
1389 {
1390 void *p = malloc (size);
1391 if (!p)
1392 MEM_ALLOC_FAIL_DEBUG (file, line);
1393 fprintf (log, format_debug, program_name, "malloc'ed", (unsigned long)size, file, line);
1394 return p;
1395 }
1396
1397 static void *
1398 calloc_wrap_debug (size_t nmemb, size_t size, const char *file, unsigned int line)
1399 {
1400 void *p = calloc (nmemb, size);
1401 if (!p)
1402 MEM_ALLOC_FAIL_DEBUG (file, line);
1403 fprintf (log, format_debug, program_name, "calloc'ed", (unsigned long)(nmemb * size), file, line);
1404 return p;
1405 }
1406
1407 static void *
1408 realloc_wrap_debug (void *ptr, size_t size, const char *file, unsigned int line)
1409 {
1410 void *p = realloc (ptr, size);
1411 if (!p)
1412 MEM_ALLOC_FAIL_DEBUG (file, line);
1413 fprintf (log, format_debug, program_name, "realloc'ed", (unsigned long)size, file, line);
1414 return p;
1415 }
1416 #endif /* !DEBUG */
1417
1418 static void
1419 free_wrap (void **ptr)
1420 {
1421 free (*ptr);
1422 *ptr = NULL;
1423 }
1424
1425 #if !DEBUG
1426 # define do_malloc(len, file, line) malloc_wrap(len)
1427 #else
1428 # define do_malloc(len, file, line) malloc_wrap_debug(len, file, line)
1429 #endif
1430
1431 static char *
1432 strdup_wrap (const char *str, const char *file, unsigned int line)
1433 {
1434 const size_t len = strlen (str) + 1;
1435 char *p = do_malloc (len, file, line);
1436 strncpy (p, str, len);
1437 return p;
1438 }
1439
1440 static char *
1441 str_concat_wrap (const char *str1, const char *str2, const char *file, unsigned int line)
1442 {
1443 const size_t len = strlen (str1) + strlen (str2) + 1;
1444 char *p, *str;
1445
1446 p = str = do_malloc (len, file, line);
1447 strncpy (p, str1, strlen (str1));
1448 p += strlen (str1);
1449 strncpy (p, str2, strlen (str2));
1450 p += strlen (str2);
1451 *p = '\0';
1452
1453 return str;
1454 }
1455
1456 static bool
1457 get_bytes_size (unsigned long bytes, struct bytes_size *bytes_size)
1458 {
1459 const char *unit, units[] = { '0', 'K', 'M', 'G', '\0' };
1460 unsigned long size = bytes;
1461 if (bytes < 1024)
1462 return false;
1463 unit = units;
1464 while (size >= 1024 && *(unit + 1))
1465 {
1466 size /= 1024;
1467 unit++;
1468 }
1469 bytes_size->size = (unsigned int)size;
1470 bytes_size->unit = *unit;
1471 return true;
1472 }
1473
1474 static char *
1475 get_file_type (mode_t mode)
1476 {
1477 if (S_ISREG (mode))
1478 return "file";
1479 else if (S_ISDIR (mode))
1480 return "directory";
1481 else if (S_ISCHR (mode))
1482 return "character device";
1483 else if (S_ISBLK (mode))
1484 return "block device";
1485 else if (S_ISFIFO (mode))
1486 return "named pipe";
1487 else if (S_ISLNK (mode))
1488 return "symbolic link";
1489 else if (S_ISSOCK (mode))
1490 return "socket";
1491 else
1492 return "file";
1493 }
1494
1495 static bool
1496 has_color_name (const char *str, const char *name)
1497 {
1498 char *p;
1499
1500 assert (strlen (str) > 0);
1501 assert (strlen (name) > 0);
1502
1503 if (!(*str == *name || *str == toupper (*name)))
1504 return false;
1505 else if (*(name + 1) != '\0'
1506 && !((p = strstr (str + 1, name + 1)) && p == str + 1))
1507 return false;
1508 else
1509 return true;
1510 }
1511
1512 static FILE *
1513 open_file (const char *file, const char *mode)
1514 {
1515 FILE *stream;
1516
1517 errno = 0;
1518 stream = fopen (file, mode);
1519 if (!stream)
1520 vfprintf_fail (formats[FMT_FILE], file, strerror (errno));
1521
1522 return stream;
1523 }
1524
1525 #define DO_VFPRINTF(fmt) \
1526 va_list ap; \
1527 fprintf (stderr, "%s: ", program_name); \
1528 va_start (ap, fmt); \
1529 vfprintf (stderr, fmt, ap); \
1530 va_end (ap); \
1531 fprintf (stderr, "\n");
1532
1533 static void
1534 vfprintf_diag (const char *fmt, ...)
1535 {
1536 DO_VFPRINTF (fmt);
1537 }
1538
1539 static void
1540 vfprintf_fail (const char *fmt, ...)
1541 {
1542 DO_VFPRINTF (fmt);
1543 exit (EXIT_FAILURE);
1544 }
1545
1546 static void
1547 stack_var (void ***list, unsigned int *stacked, unsigned int index, void *ptr)
1548 {
1549 /* nothing to stack */
1550 if (ptr == NULL)
1551 return;
1552 if (!*list)
1553 *list = xmalloc (sizeof (void *));
1554 else
1555 {
1556 unsigned int i;
1557 for (i = 0; i < *stacked; i++)
1558 if (!(*list)[i])
1559 {
1560 (*list)[i] = ptr;
1561 return; /* reused */
1562 }
1563 *list = xrealloc (*list, (*stacked + 1) * sizeof (void *));
1564 }
1565 (*list)[index] = ptr;
1566 (*stacked)++;
1567 }
1568
1569 static void
1570 release_var (void **list, unsigned int stacked, void **ptr)
1571 {
1572 unsigned int i;
1573 /* nothing to release */
1574 if (*ptr == NULL)
1575 return;
1576 for (i = 0; i < stacked; i++)
1577 if (list[i] == *ptr)
1578 {
1579 free (*ptr);
1580 *ptr = NULL;
1581 list[i] = NULL;
1582 return;
1583 }
1584 }