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