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