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