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