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