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