]> git.refcnt.org Git - colorize.git/blob - colorize.c
Rearrange debugging macros
[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-2014 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 _BSD_SOURCE
23 #define _XOPEN_SOURCE 700
24 #include <assert.h>
25 #include <ctype.h>
26 #include <errno.h>
27 #include <getopt.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <sys/time.h>
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <time.h>
36 #include <unistd.h>
37
38 #ifndef DEBUG
39 # define DEBUG 0
40 #endif
41
42 #define str(arg) #arg
43 #define to_str(arg) str(arg)
44
45 #define streq(s1, s2) (strcmp (s1, s2) == 0)
46
47 #if !DEBUG
48 # define xmalloc(size) malloc_wrap(size)
49 # define xcalloc(nmemb, size) calloc_wrap(nmemb, size)
50 # define xrealloc(ptr, size) realloc_wrap(ptr, size)
51 #else
52 # define xmalloc(size) malloc_wrap_debug(size, __FILE__, __LINE__)
53 # define xcalloc(nmemb, size) calloc_wrap_debug(nmemb, size, __FILE__, __LINE__)
54 # define xrealloc(ptr, size) realloc_wrap_debug(ptr, size, __FILE__, __LINE__)
55 #endif
56
57 #define free_null(ptr) free_wrap((void **)&ptr)
58 #define xstrdup(str) strdup_wrap(str)
59
60 #if BUF_SIZE <= 0
61 # undef BUF_SIZE
62 #endif
63 #ifndef BUF_SIZE
64 # define BUF_SIZE 4096
65 #endif
66
67 #define LF 0x01
68 #define CR 0x02
69
70 #define SKIP_LINE_ENDINGS(flags) (((flags) & CR) && ((flags) & LF) ? 2 : 1)
71
72 #define VALID_FILE_TYPE(mode) (S_ISREG (mode) || S_ISLNK (mode) || S_ISFIFO (mode))
73
74 #define STACK_VAR(ptr) do { \
75 stack_var (&vars_list, &stacked_vars, stacked_vars, ptr); \
76 } while (false)
77
78 #define RELEASE_VAR(ptr) do { \
79 release_var (vars_list, stacked_vars, (void **)&ptr); \
80 } while (false)
81
82 #if !DEBUG
83 # define MEM_ALLOC_FAIL() do { \
84 fprintf (stderr, "%s: memory allocation failure\n", program_name); \
85 exit (2); \
86 } while (false)
87 #else
88 # define MEM_ALLOC_FAIL_DEBUG(file, line) do { \
89 fprintf (stderr, "Memory allocation failure in source file %s, line %u\n", file, line); \
90 exit (2); \
91 } while (false)
92 #endif
93
94 #define ABORT_TRACE() \
95 fprintf (stderr, "Aborting in source file %s, line %u\n", __FILE__, __LINE__); \
96 abort (); \
97
98 #define CHECK_COLORS_RANDOM(color1, color2) \
99 streq (color_names[color1]->name, "random") \
100 && (streq (color_names[color2]->name, "none") \
101 || streq (color_names[color2]->name, "default")) \
102
103 #define COLOR_SEP_CHAR '/'
104
105 #define VERSION "0.53"
106
107 typedef enum { false, true } bool;
108
109 struct color_name {
110 char *name;
111 char *orig;
112 };
113
114 static struct color_name *color_names[3] = { NULL, NULL, NULL };
115
116 struct color {
117 const char *name;
118 const char *code;
119 };
120
121 static const struct color fg_colors[] = {
122 { "none", NULL },
123 { "black", "30m" },
124 { "red", "31m" },
125 { "green", "32m" },
126 { "yellow", "33m" },
127 { "blue", "34m" },
128 { "magenta", "35m" },
129 { "cyan", "36m" },
130 { "white", "37m" },
131 { "default", "39m" },
132 };
133 static const struct color bg_colors[] = {
134 { "none", NULL },
135 { "black", "40m" },
136 { "red", "41m" },
137 { "green", "42m" },
138 { "yellow", "43m" },
139 { "blue", "44m" },
140 { "magenta", "45m" },
141 { "cyan", "46m" },
142 { "white", "47m" },
143 { "default", "49m" },
144 };
145
146 enum fmts {
147 FMT_GENERIC,
148 FMT_STRING,
149 FMT_QUOTE,
150 FMT_COLOR,
151 FMT_RANDOM,
152 FMT_ERROR,
153 FMT_FILE,
154 FMT_TYPE
155 };
156 static const char *formats[] = {
157 "%s", /* generic */
158 "%s '%s'", /* string */
159 "%s `%s' %s", /* quote */
160 "%s color '%s' %s", /* color */
161 "%s color '%s' %s '%s'", /* random */
162 "less than %u bytes %s", /* error */
163 "%s: %s", /* file */
164 "%s: %s: %s", /* type */
165 };
166
167 enum { FOREGROUND, BACKGROUND };
168
169 static const struct {
170 struct color const *entries;
171 unsigned int count;
172 const char *desc;
173 } tables[] = {
174 { fg_colors, sizeof (fg_colors) / sizeof (struct color), "foreground" },
175 { bg_colors, sizeof (bg_colors) / sizeof (struct color), "background" },
176 };
177
178 static FILE *stream = NULL;
179
180 static unsigned int stacked_vars = 0;
181 static void **vars_list = NULL;
182
183 static bool clean = false;
184 static bool clean_all = false;
185
186 static char *exclude = NULL;
187
188 static const char *program_name;
189
190 static void print_hint (void);
191 static void print_help (void);
192 static void print_version (void);
193 static void cleanup (void);
194 static void free_color_names (struct color_name **);
195 static void process_args (unsigned int, char **, bool *, const struct color **, const char **, FILE **);
196 static void process_file_arg (const char *, const char **, FILE **);
197 static void read_print_stream (bool, const struct color **, const char *, FILE *);
198 static void find_color_entries (struct color_name **, const struct color **);
199 static void find_color_entry (const struct color_name *, unsigned int, const struct color **);
200 static void print_line (bool, const struct color **, const char * const, unsigned int);
201 static void print_clean (const char *);
202 static void print_free_offsets (const char *, char ***, unsigned int);
203 #if !DEBUG
204 static void *malloc_wrap (size_t);
205 static void *calloc_wrap (size_t, size_t);
206 static void *realloc_wrap (void *, size_t);
207 #else
208 static void *malloc_wrap_debug (size_t, const char *, unsigned int);
209 static void *calloc_wrap_debug (size_t, size_t, const char *, unsigned int);
210 static void *realloc_wrap_debug (void *, size_t, const char *, unsigned int);
211 #endif
212 static void free_wrap (void **);
213 static char *strdup_wrap (const char *);
214 static char *str_concat (const char *, const char *);
215 static char *get_file_type (mode_t);
216 static bool has_color_name (const char *, const char *);
217 static void vfprintf_diag (const char *, ...);
218 static void vfprintf_fail (const char *, ...);
219 static void stack_var (void ***, unsigned int *, unsigned int, void *);
220 static void release_var (void **, unsigned int, void **);
221
222 #define SET_OPT_TYPE(type) \
223 opt_type = type; \
224 opt = 0; \
225 goto PARSE_OPT; \
226
227 extern char *optarg;
228 extern int optind;
229
230 static int opt_type = 0;
231
232 int
233 main (int argc, char **argv)
234 {
235 unsigned int arg_cnt = 0;
236
237 enum {
238 OPT_CLEAN = 1,
239 OPT_CLEAN_ALL,
240 OPT_EXCLUDE_RANDOM,
241 OPT_HELP,
242 OPT_VERSION
243 };
244
245 int opt;
246 struct option long_opts[] = {
247 { "clean", no_argument, &opt_type, OPT_CLEAN },
248 { "clean-all", no_argument, &opt_type, OPT_CLEAN_ALL },
249 { "exclude-random", required_argument, &opt_type, OPT_EXCLUDE_RANDOM },
250 { "help", no_argument, &opt_type, OPT_HELP },
251 { "version", no_argument, &opt_type, OPT_VERSION },
252 { NULL, 0, NULL, 0 },
253 };
254
255 bool bold = false;
256
257 const struct color *colors[2] = {
258 NULL, /* foreground */
259 NULL, /* background */
260 };
261
262 const char *file = NULL;
263
264 program_name = argv[0];
265 atexit (cleanup);
266
267 setvbuf (stdout, NULL, _IOLBF, 0);
268
269 while ((opt = getopt_long (argc, argv, "hv", long_opts, NULL)) != -1)
270 {
271 PARSE_OPT:
272 switch (opt)
273 {
274 case 0: /* long opts */
275 switch (opt_type)
276 {
277 case OPT_CLEAN:
278 clean = true;
279 break;
280 case OPT_CLEAN_ALL:
281 clean_all = true;
282 break;
283 case OPT_EXCLUDE_RANDOM: {
284 bool valid = false;
285 unsigned int i;
286 exclude = xstrdup (optarg);
287 STACK_VAR (exclude);
288 for (i = 1; i < tables[FOREGROUND].count - 1; i++) /* skip color none and default */
289 {
290 const struct color *entry = &tables[FOREGROUND].entries[i];
291 if (streq (exclude, entry->name))
292 {
293 valid = true;
294 break;
295 }
296 }
297 if (!valid)
298 vfprintf_fail (formats[FMT_GENERIC], "--exclude-random switch must be provided a plain color");
299 break;
300 }
301 case OPT_HELP:
302 print_help ();
303 exit (EXIT_SUCCESS);
304 case OPT_VERSION:
305 print_version ();
306 exit (EXIT_SUCCESS);
307 default: /* never reached */
308 ABORT_TRACE ();
309 }
310 break;
311 case 'h':
312 SET_OPT_TYPE (OPT_HELP);
313 case 'v':
314 SET_OPT_TYPE (OPT_VERSION);
315 case '?':
316 print_hint ();
317 exit (EXIT_FAILURE);
318 default: /* never reached */
319 ABORT_TRACE ();
320 }
321 }
322
323 arg_cnt = argc - optind;
324
325 if (clean || clean_all)
326 {
327 if (clean && clean_all)
328 vfprintf_fail (formats[FMT_GENERIC], "--clean and --clean-all switch are mutually exclusive");
329 if (arg_cnt > 1)
330 {
331 const char *format = "%s %s";
332 const char *message = "switch cannot be used with more than one file";
333 if (clean)
334 vfprintf_fail (format, "--clean", message);
335 else if (clean_all)
336 vfprintf_fail (format, "--clean-all", message);
337 }
338 }
339 else
340 {
341 if (arg_cnt == 0 || arg_cnt > 2)
342 {
343 vfprintf_diag ("%u arguments provided, expected 1-2 arguments or clean option", arg_cnt);
344 print_hint ();
345 exit (EXIT_FAILURE);
346 }
347 }
348
349 if (clean || clean_all)
350 process_file_arg (argv[optind], &file, &stream);
351 else
352 process_args (arg_cnt, &argv[optind], &bold, colors, &file, &stream);
353 read_print_stream (bold, colors, file, stream);
354
355 RELEASE_VAR (exclude);
356
357 exit (EXIT_SUCCESS);
358 }
359
360 static void
361 print_hint (void)
362 {
363 fprintf (stderr, "Type `%s --help' for help screen.\n", program_name);
364 }
365
366 static void
367 print_help (void)
368 {
369 unsigned int i;
370
371 printf ("Usage: %s (foreground) OR (foreground)%c(background) OR --clean[-all] [-|file]\n\n", program_name, COLOR_SEP_CHAR);
372 printf ("\tColors (foreground) (background)\n");
373 for (i = 0; i < tables[FOREGROUND].count; i++)
374 {
375 const struct color *entry = &tables[FOREGROUND].entries[i];
376 const char *name = entry->name;
377 const char *code = entry->code;
378 if (code)
379 printf ("\t\t{\033[%s#\033[0m} [%c%c]%s%*s%s\n",
380 code, toupper (*name), *name, name + 1, 10 - (int)strlen (name), " ", name);
381 else
382 printf ("\t\t{-} %s%*s%s\n", name, 13 - (int)strlen (name), " ", name);
383 }
384 printf ("\t\t{*} [Rr]%s%*s%s [--exclude-random=<foreground color>]\n", "andom", 10 - (int)strlen ("random"), " ", "random");
385
386 printf ("\n\tFirst character of color name in upper case denotes increased intensity,\n");
387 printf ("\twhereas for lower case colors will be of normal intensity.\n");
388
389 printf ("\n\tOptions\n");
390 printf ("\t\t --clean\n");
391 printf ("\t\t --clean-all\n");
392 printf ("\t\t --exclude-random\n");
393 printf ("\t\t-h, --help\n");
394 printf ("\t\t-v, --version\n\n");
395 }
396
397 static void
398 print_version (void)
399 {
400 const char *c_flags;
401 bool debug;
402 #ifdef CFLAGS
403 c_flags = to_str (CFLAGS);
404 #else
405 c_flags = "unknown";
406 #endif
407 #if DEBUG
408 debug = true;
409 #else
410 debug = false;
411 #endif
412 printf ("%s v%s (compiled at %s, %s)\n", "colorize", VERSION, __DATE__, __TIME__);
413 printf ("Compiler flags: %s\n", c_flags);
414 printf ("Buffer size: %u bytes\n", BUF_SIZE);
415 printf ("Debugging: %s\n", debug ? "yes" : "no");
416 }
417
418 static void
419 cleanup (void)
420 {
421 free_color_names (color_names);
422
423 if (stream && fileno (stream) != STDIN_FILENO)
424 fclose (stream);
425
426 if (vars_list)
427 {
428 unsigned int i;
429 for (i = 0; i < stacked_vars; i++)
430 if (vars_list[i])
431 free_null (vars_list[i]);
432
433 free_null (vars_list);
434 }
435 }
436
437 static void
438 free_color_names (struct color_name **color_names)
439 {
440 unsigned int i;
441 for (i = 0; color_names[i]; i++)
442 {
443 free_null (color_names[i]->name);
444 free_null (color_names[i]->orig);
445 free_null (color_names[i]);
446 }
447 }
448
449 static void
450 process_args (unsigned int arg_cnt, char **arg_strings, bool *bold, const struct color **colors, const char **file, FILE **stream)
451 {
452 int ret;
453 unsigned int index;
454 char *color, *p, *str;
455 struct stat sb;
456
457 const char *color_string = arg_cnt >= 1 ? arg_strings[0] : NULL;
458 const char *file_string = arg_cnt == 2 ? arg_strings[1] : NULL;
459
460 assert (color_string);
461
462 if (streq (color_string, "-"))
463 {
464 if (file_string)
465 vfprintf_fail (formats[FMT_GENERIC], "hyphen cannot be used as color string");
466 else
467 vfprintf_fail (formats[FMT_GENERIC], "hyphen must be preceeded by color string");
468 }
469
470 ret = lstat (color_string, &sb);
471
472 /* Ensure that we don't fail if there's a file with one or more
473 color names in its path. */
474 if (ret != -1)
475 {
476 bool have_file;
477 unsigned int c;
478 const char *color = color_string;
479 const mode_t mode = sb.st_mode;
480
481 for (c = 1; c <= 2 && *color; c++)
482 {
483 bool matched = false;
484 unsigned int i;
485 for (i = 0; i < tables[FOREGROUND].count; i++)
486 {
487 const struct color *entry = &tables[FOREGROUND].entries[i];
488 if (has_color_name (color, entry->name))
489 {
490 color += strlen (entry->name);
491 matched = true;
492 break;
493 }
494 }
495 if (!matched && has_color_name (color, "random"))
496 {
497 color += strlen ("random");
498 matched = true;
499 }
500 if (matched && *color == COLOR_SEP_CHAR && *(color + 1))
501 color++;
502 else
503 break;
504 }
505
506 have_file = (*color != '\0');
507
508 if (have_file)
509 {
510 if (file_string)
511 vfprintf_fail (formats[FMT_QUOTE], get_file_type (mode), color_string, "cannot be used as color string");
512 else
513 {
514 if (VALID_FILE_TYPE (mode))
515 vfprintf_fail (formats[FMT_QUOTE], get_file_type (mode), color_string, "must be preceeded by color string");
516 else
517 vfprintf_fail (formats[FMT_QUOTE], get_file_type (mode), color_string, "is not a valid file type");
518 }
519 }
520 }
521
522 if ((p = strchr (color_string, COLOR_SEP_CHAR)))
523 {
524 if (p == color_string)
525 vfprintf_fail (formats[FMT_STRING], "foreground color missing in string", color_string);
526 else if (p == color_string + strlen (color_string) - 1)
527 vfprintf_fail (formats[FMT_STRING], "background color missing in string", color_string);
528 else if (strchr (++p, COLOR_SEP_CHAR))
529 vfprintf_fail (formats[FMT_STRING], "one color pair allowed only for string", color_string);
530 }
531
532 str = xstrdup (color_string);
533 STACK_VAR (str);
534
535 for (index = 0, color = str; *color; index++, color = p)
536 {
537 char *ch, *sep;
538
539 p = NULL;
540 if ((sep = strchr (color, COLOR_SEP_CHAR)))
541 {
542 *sep = '\0';
543 p = sep + 1;
544 }
545 else
546 p = color + strlen (color);
547 assert (p);
548
549 for (ch = color; *ch; ch++)
550 if (!isalpha (*ch))
551 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be made of non-alphabetic characters");
552
553 for (ch = color + 1; *ch; ch++)
554 if (!islower (*ch))
555 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be in mixed lower/upper case");
556
557 if (streq (color, "None"))
558 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be bold");
559
560 if (isupper (*color))
561 {
562 switch (index)
563 {
564 case FOREGROUND:
565 *bold = true;
566 break;
567 case BACKGROUND:
568 vfprintf_fail (formats[FMT_COLOR], tables[BACKGROUND].desc, color, "cannot be bold");
569 break;
570 default: /* never reached */
571 ABORT_TRACE ();
572 }
573 }
574
575 color_names[index] = xcalloc (1, sizeof (struct color_name));
576
577 color_names[index]->orig = xstrdup (color);
578
579 for (ch = color; *ch; ch++)
580 *ch = tolower (*ch);
581
582 color_names[index]->name = xstrdup (color);
583 }
584
585 RELEASE_VAR (str);
586
587 assert (color_names[FOREGROUND]);
588
589 if (color_names[BACKGROUND])
590 {
591 unsigned int i;
592 unsigned int color_sets[2][2] = { { FOREGROUND, BACKGROUND }, { BACKGROUND, FOREGROUND } };
593 for (i = 0; i < 2; i++)
594 {
595 unsigned int color1 = color_sets[i][0];
596 unsigned int color2 = color_sets[i][1];
597 if (CHECK_COLORS_RANDOM (color1, color2))
598 vfprintf_fail (formats[FMT_RANDOM], tables[color1].desc, color_names[color1]->orig, "cannot be combined with", color_names[color2]->orig);
599 }
600 }
601
602 find_color_entries (color_names, colors);
603 free_color_names (color_names);
604
605 if (!colors[FOREGROUND]->code && colors[BACKGROUND] && colors[BACKGROUND]->code)
606 {
607 struct color_name color_name;
608 color_name.name = color_name.orig = "default";
609
610 find_color_entry (&color_name, FOREGROUND, colors);
611 }
612
613 process_file_arg (file_string, file, stream);
614 }
615
616 static void
617 process_file_arg (const char *file_string, const char **file, FILE **stream)
618 {
619 if (file_string)
620 {
621 if (streq (file_string, "-"))
622 *stream = stdin;
623 else
624 {
625 FILE *s;
626 const char *file = file_string;
627 struct stat sb;
628 int errno, ret;
629
630 errno = 0;
631 ret = lstat (file, &sb);
632
633 if (ret == -1)
634 vfprintf_fail (formats[FMT_FILE], file, strerror (errno));
635
636 if (!VALID_FILE_TYPE (sb.st_mode))
637 vfprintf_fail (formats[FMT_TYPE], file, "unrecognized type", get_file_type (sb.st_mode));
638
639 errno = 0;
640
641 s = fopen (file, "r");
642 if (!s)
643 vfprintf_fail (formats[FMT_FILE], file, strerror (errno));
644 *stream = s;
645 }
646 *file = file_string;
647 }
648 else
649 {
650 *stream = stdin;
651 *file = "stdin";
652 }
653
654 assert (*stream);
655 assert (*file);
656 }
657
658 #define MERGE_PRINT_LINE(part_line, line, flags, check_eof) do { \
659 char *current_line, *merged_line = NULL; \
660 if (part_line) \
661 { \
662 merged_line = str_concat (part_line, line); \
663 free_null (part_line); \
664 } \
665 current_line = merged_line ? merged_line : (char *)line; \
666 if (!check_eof || *current_line != '\0') \
667 print_line (bold, colors, current_line, flags); \
668 free (merged_line); \
669 } while (false)
670
671 static void
672 read_print_stream (bool bold, const struct color **colors, const char *file, FILE *stream)
673 {
674 char buf[BUF_SIZE + 1], *part_line = NULL;
675 unsigned int flags = 0;
676
677 while (!feof (stream))
678 {
679 size_t bytes_read;
680 char *eol;
681 const char *line;
682 memset (buf, '\0', BUF_SIZE + 1);
683 bytes_read = fread (buf, 1, BUF_SIZE, stream);
684 if (bytes_read != BUF_SIZE && ferror (stream))
685 vfprintf_fail (formats[FMT_ERROR], BUF_SIZE, "read");
686 line = buf;
687 while ((eol = strpbrk (line, "\n\r")))
688 {
689 char *p;
690 flags &= ~(CR|LF);
691 if (*eol == '\r')
692 {
693 flags |= CR;
694 if (*(eol + 1) == '\n')
695 flags |= LF;
696 }
697 else if (*eol == '\n')
698 flags |= LF;
699 else
700 vfprintf_fail (formats[FMT_FILE], file, "unrecognized line ending");
701 p = eol + SKIP_LINE_ENDINGS (flags);
702 *eol = '\0';
703 MERGE_PRINT_LINE (part_line, line, flags, false);
704 line = p;
705 }
706 if (feof (stream)) {
707 MERGE_PRINT_LINE (part_line, line, 0, true);
708 }
709 else if (*line != '\0')
710 {
711 if (!clean && !clean_all) /* efficiency */
712 print_line (bold, colors, line, 0);
713 else if (!part_line)
714 part_line = xstrdup (line);
715 else
716 {
717 char *merged_line = str_concat (part_line, line);
718 free (part_line);
719 part_line = merged_line;
720 }
721 }
722 }
723 }
724
725 static void
726 find_color_entries (struct color_name **color_names, const struct color **colors)
727 {
728 struct timeval tv;
729 unsigned int index;
730
731 /* randomness */
732 gettimeofday (&tv, NULL);
733 srand (tv.tv_usec * tv.tv_sec);
734
735 for (index = 0; color_names[index]; index++)
736 {
737 const char *color_name = color_names[index]->name;
738
739 const unsigned int count = tables[index].count;
740 const struct color *const color_entries = tables[index].entries;
741
742 if (streq (color_name, "random"))
743 {
744 bool excludable;
745 unsigned int i;
746 do {
747 excludable = false;
748 i = rand() % (count - 2) + 1; /* omit color none and default */
749 switch (index)
750 {
751 case FOREGROUND:
752 /* --exclude-random */
753 if (exclude && streq (exclude, color_entries[i].name))
754 excludable = true;
755 else if (color_names[BACKGROUND] && streq (color_names[BACKGROUND]->name, color_entries[i].name))
756 excludable = true;
757 break;
758 case BACKGROUND:
759 if (streq (colors[FOREGROUND]->name, color_entries[i].name))
760 excludable = true;
761 break;
762 default: /* never reached */
763 ABORT_TRACE ();
764 }
765 } while (excludable);
766 colors[index] = (struct color *)&color_entries[i];
767 }
768 else
769 find_color_entry (color_names[index], index, colors);
770 }
771 }
772
773 static void
774 find_color_entry (const struct color_name *color_name, unsigned int index, const struct color **colors)
775 {
776 bool found = false;
777 unsigned int i;
778
779 const unsigned int count = tables[index].count;
780 const struct color *const color_entries = tables[index].entries;
781
782 for (i = 0; i < count; i++)
783 if (streq (color_name->name, color_entries[i].name))
784 {
785 colors[index] = (struct color *)&color_entries[i];
786 found = true;
787 break;
788 }
789 if (!found)
790 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color_name->orig, "not recognized");
791 }
792
793 static void
794 print_line (bool bold, const struct color **colors, const char *const line, unsigned int flags)
795 {
796 /* --clean[-all] */
797 if (clean || clean_all)
798 print_clean (line);
799 else
800 {
801 /* Foreground color code is guaranteed to be set when background color code is present. */
802 if (colors[BACKGROUND] && colors[BACKGROUND]->code)
803 printf ("\033[%s", colors[BACKGROUND]->code);
804 if (colors[FOREGROUND]->code)
805 printf ("\033[%s%s%s\033[0m", bold ? "1;" : "", colors[FOREGROUND]->code, line);
806 else
807 printf (formats[FMT_GENERIC], line);
808 }
809 if (flags & CR)
810 putchar ('\r');
811 if (flags & LF)
812 putchar ('\n');
813 }
814
815 static void
816 print_clean (const char *line)
817 {
818 const char *p;
819 char ***offsets = NULL;
820 unsigned int count = 0, i = 0;
821
822 for (p = line; *p;)
823 {
824 /* ESC[ */
825 if (*p == 27 && *(p + 1) == '[')
826 {
827 const char *begin = p;
828 p += 2;
829 if (clean_all)
830 {
831 while (isdigit (*p) || *p == ';')
832 p++;
833 }
834 else if (clean)
835 {
836 bool check_values;
837 unsigned int iter = 0;
838 const char *digit;
839 do {
840 check_values = false;
841 iter++;
842 if (!isdigit (*p))
843 goto DISCARD;
844 digit = p;
845 while (isdigit (*p))
846 p++;
847 if (p - digit > 2)
848 goto DISCARD;
849 else /* check range */
850 {
851 char val[3];
852 int value;
853 unsigned int i;
854 const unsigned int digits = p - digit;
855 for (i = 0; i < digits; i++)
856 val[i] = *digit++;
857 val[i] = '\0';
858 value = atoi (val);
859 if (value == 0) /* reset */
860 {
861 if (iter > 1)
862 goto DISCARD;
863 goto END;
864 }
865 else if (value == 1) /* bold */
866 {
867 bool discard = false;
868 if (iter > 1)
869 discard = true;
870 else if (*p != ';')
871 discard = true;
872 if (discard)
873 goto DISCARD;
874 p++;
875 check_values = true;
876 }
877 else if ((value >= 30 && value <= 37) || value == 39) /* foreground colors */
878 goto END;
879 else if ((value >= 40 && value <= 47) || value == 49) /* background colors */
880 {
881 if (iter > 1)
882 goto DISCARD;
883 goto END;
884 }
885 else
886 goto DISCARD;
887 }
888 } while (iter == 1 && check_values);
889 }
890 END: if (*p == 'm')
891 {
892 const char *end = p++;
893 if (!offsets)
894 offsets = xmalloc (++count * sizeof (char **));
895 else
896 offsets = xrealloc (offsets, ++count * sizeof (char **));
897 offsets[i] = xmalloc (2 * sizeof (char *));
898 offsets[i][0] = (char *)begin; /* ESC */
899 offsets[i][1] = (char *)end; /* m */
900 i++;
901 continue;
902 }
903 DISCARD:
904 continue;
905 }
906 p++;
907 }
908
909 if (offsets)
910 print_free_offsets (line, offsets, count);
911 else
912 printf (formats[FMT_GENERIC], line);
913 }
914
915 #define SET_CHAR(offset, new, old) \
916 *old = *offset; \
917 *offset = new; \
918
919 #define RESTORE_CHAR(offset, old) \
920 *offset = old; \
921
922 static void
923 print_free_offsets (const char *line, char ***offsets, unsigned int count)
924 {
925 char ch;
926 unsigned int i;
927
928 SET_CHAR (offsets[0][0], '\0', &ch);
929 printf (formats[FMT_GENERIC], line);
930 RESTORE_CHAR (offsets[0][0], ch);
931
932 for (i = 0; i < count; i++)
933 {
934 char ch;
935 bool next_offset = false;
936 if (i + 1 < count)
937 {
938 SET_CHAR (offsets[i + 1][0], '\0', &ch);
939 next_offset = true;
940 }
941 printf (formats[FMT_GENERIC], offsets[i][1] + 1);
942 if (next_offset)
943 RESTORE_CHAR (offsets[i + 1][0], ch);
944 }
945 for (i = 0; i < count; i++)
946 free_null (offsets[i]);
947 free_null (offsets);
948 }
949
950 #if !DEBUG
951 static void *
952 malloc_wrap (size_t size)
953 {
954 void *p = malloc (size);
955 if (!p)
956 MEM_ALLOC_FAIL ();
957 return p;
958 }
959
960 static void *
961 calloc_wrap (size_t nmemb, size_t size)
962 {
963 void *p = calloc (nmemb, size);
964 if (!p)
965 MEM_ALLOC_FAIL ();
966 return p;
967 }
968
969 static void *
970 realloc_wrap (void *ptr, size_t size)
971 {
972 void *p = realloc (ptr, size);
973 if (!p)
974 MEM_ALLOC_FAIL ();
975 return p;
976 }
977 #else
978 static void *
979 malloc_wrap_debug (size_t size, const char *file, unsigned int line)
980 {
981 void *p = malloc (size);
982 if (!p)
983 MEM_ALLOC_FAIL_DEBUG (file, line);
984 return p;
985 }
986
987 static void *
988 calloc_wrap_debug (size_t nmemb, size_t size, const char *file, unsigned int line)
989 {
990 void *p = calloc (nmemb, size);
991 if (!p)
992 MEM_ALLOC_FAIL_DEBUG (file, line);
993 return p;
994 }
995
996 static void *
997 realloc_wrap_debug (void *ptr, size_t size, const char *file, unsigned int line)
998 {
999 void *p = realloc (ptr, size);
1000 if (!p)
1001 MEM_ALLOC_FAIL_DEBUG (file, line);
1002 return p;
1003 }
1004 #endif
1005
1006 static void
1007 free_wrap (void **ptr)
1008 {
1009 free (*ptr);
1010 *ptr = NULL;
1011 }
1012
1013 static char *
1014 strdup_wrap (const char *str)
1015 {
1016 const size_t len = strlen (str) + 1;
1017 char *p = xmalloc (len);
1018 strncpy (p, str, len);
1019 return p;
1020 }
1021
1022 static char *
1023 str_concat (const char *str1, const char *str2)
1024 {
1025 const size_t len = strlen (str1) + strlen (str2) + 1;
1026 char *p, *str;
1027
1028 p = str = xmalloc (len);
1029 strncpy (p, str1, strlen (str1));
1030 p += strlen (str1);
1031 strncpy (p, str2, strlen (str2));
1032 p += strlen (str2);
1033 *p = '\0';
1034
1035 return str;
1036 }
1037
1038 static char *
1039 get_file_type (mode_t mode)
1040 {
1041 if (S_ISREG (mode))
1042 return "file";
1043 else if (S_ISDIR (mode))
1044 return "directory";
1045 else if (S_ISCHR (mode))
1046 return "character device";
1047 else if (S_ISBLK (mode))
1048 return "block device";
1049 else if (S_ISFIFO (mode))
1050 return "named pipe";
1051 else if (S_ISLNK (mode))
1052 return "symbolic link";
1053 else if (S_ISSOCK (mode))
1054 return "socket";
1055 else
1056 return "file";
1057 }
1058
1059 static bool
1060 has_color_name (const char *str, const char *name)
1061 {
1062 char *p;
1063
1064 assert (strlen (str));
1065 assert (strlen (name));
1066
1067 if (!(*str == *name || *str == toupper (*name)))
1068 return false;
1069 else if (*(name + 1) != '\0'
1070 && !((p = strstr (str + 1, name + 1)) && p == str + 1))
1071 return false;
1072
1073 return true;
1074 }
1075
1076 #define DO_VFPRINTF(fmt) \
1077 va_list ap; \
1078 fprintf (stderr, "%s: ", program_name); \
1079 va_start (ap, fmt); \
1080 vfprintf (stderr, fmt, ap); \
1081 va_end (ap); \
1082 fprintf (stderr, "\n"); \
1083
1084 static void
1085 vfprintf_diag (const char *fmt, ...)
1086 {
1087 DO_VFPRINTF (fmt);
1088 }
1089
1090 static void
1091 vfprintf_fail (const char *fmt, ...)
1092 {
1093 DO_VFPRINTF (fmt);
1094 exit (EXIT_FAILURE);
1095 }
1096
1097 static void
1098 stack_var (void ***list, unsigned int *stacked, unsigned int index, void *ptr)
1099 {
1100 /* nothing to stack */
1101 if (ptr == NULL)
1102 return;
1103 if (!*list)
1104 *list = xmalloc (sizeof (void *));
1105 else
1106 {
1107 unsigned int i;
1108 for (i = 0; i < *stacked; i++)
1109 if (!(*list)[i])
1110 {
1111 (*list)[i] = ptr;
1112 return; /* reused */
1113 }
1114 *list = xrealloc (*list, (*stacked + 1) * sizeof (void *));
1115 }
1116 (*list)[index] = ptr;
1117 (*stacked)++;
1118 }
1119
1120 static void
1121 release_var (void **list, unsigned int stacked, void **ptr)
1122 {
1123 unsigned int i;
1124 /* nothing to release */
1125 if (*ptr == NULL)
1126 return;
1127 for (i = 0; i < stacked; i++)
1128 if (list[i] == *ptr)
1129 {
1130 free (*ptr);
1131 *ptr = NULL;
1132 list[i] = NULL;
1133 return;
1134 }
1135 }