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