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