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