add --version and --help
[platform/upstream/coreutils.git] / src / tac.c
1 /* tac - concatenate and print files in reverse
2    Copyright (C) 1988, 1989, 1990, 1991 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2, or (at your option)
7    any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software
16    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
17
18 /* Written by Jay Lepreau (lepreau@cs.utah.edu).
19    GNU enhancements by David MacKenzie (djm@gnu.ai.mit.edu). */
20
21 /* Copy each FILE, or the standard input if none are given or when a
22    FILE name of "-" is encountered, to the standard output with the
23    order of the records reversed.  The records are separated by
24    instances of a string, or a newline if none is given.  By default, the
25    separator string is attached to the end of the record that it
26    follows in the file.
27
28    Options:
29    -b, --before                 The separator is attached to the beginning
30                                 of the record that it precedes in the file.
31    -r, --regex                  The separator is a regular expression.
32    -s, --separator=separator    Use SEPARATOR as the record separator.
33
34    To reverse a file byte by byte, use (in bash, ksh, or sh):
35 tac -r -s '.\|
36 ' file */
37
38 #include <stdio.h>
39 #include <getopt.h>
40 #include <sys/types.h>
41 #include <signal.h>
42 #include <regex.h>
43 #include "system.h"
44 #include "version.h"
45
46 #ifndef STDC_HEADERS
47 char *malloc ();
48 char *realloc ();
49 #endif
50
51 /* The number of bytes per atomic read. */
52 #define INITIAL_READSIZE 8192
53
54 /* The number of bytes per atomic write. */
55 #define WRITESIZE 8192
56
57 char *mktemp ();
58
59 static RETSIGTYPE cleanup ();
60 static int tac ();
61 static int tac_file ();
62 static int tac_stdin ();
63 static char *xmalloc ();
64 static char *xrealloc ();
65 static void output ();
66 static void save_stdin ();
67 static void xwrite ();
68
69 void error ();
70
71 /* The name this program was run with. */
72 char *program_name;
73
74 /* The string that separates the records of the file. */
75 static char *separator;
76
77 /* If nonzero, print `separator' along with the record preceding it
78    in the file; otherwise with the record following it. */
79 static int separator_ends_record;
80
81 /* 0 if `separator' is to be matched as a regular expression;
82    otherwise, the length of `separator', used as a sentinel to
83    stop the search. */
84 static int sentinel_length;
85
86 /* The length of a match with `separator'.  If `sentinel_length' is 0,
87    `match_length' is computed every time a match succeeds;
88    otherwise, it is simply the length of `separator'. */
89 static int match_length;
90
91 /* The input buffer. */
92 static char *buffer;
93
94 /* The number of bytes to read at once into `buffer'. */
95 static unsigned read_size;
96
97 /* The size of `buffer'.  This is read_size * 2 + sentinel_length + 2.
98    The extra 2 bytes allow `past_end' to have a value beyond the
99    end of `buffer' and `match_start' to run off the front of `buffer'. */
100 static unsigned buffer_size;
101
102 /* The compiled regular expression representing `separator'. */
103 static struct re_pattern_buffer compiled_separator;
104
105 /* If non-zero, display usage information and exit.  */
106 static int flag_help;
107
108 /* If non-zero, print the version on standard error.  */
109 static int flag_version;
110
111 static struct option const longopts[] =
112 {
113   {"before", no_argument, &separator_ends_record, 0},
114   {"regex", no_argument, &sentinel_length, 0},
115   {"separator", required_argument, NULL, 's'},
116   {"help", no_argument, &flag_help, 1},
117   {"version", no_argument, &flag_version, 1},
118   {NULL, 0, NULL, 0}
119 };
120
121 static void
122 usage ()
123 {
124   fprintf (stderr, "\
125 Usage: %s [-br] [-s separator] [--before] [--regex] [--separator=separator]\n\
126       [--help] [--version] [file...]\n",
127            program_name);
128   exit (1);
129 }
130
131 void
132 main (argc, argv)
133      int argc;
134      char **argv;
135 {
136   const char *error_message;    /* Return value from re_compile_pattern. */
137   int optc, errors;
138   int have_read_stdin = 0;
139
140   program_name = argv[0];
141   errors = 0;
142   separator = "\n";
143   sentinel_length = 1;
144   separator_ends_record = 1;
145
146   while ((optc = getopt_long (argc, argv, "brs:", longopts, (int *) 0))
147          != EOF)
148     {
149       switch (optc)
150         {
151         case 0:
152           break;
153         case 'b':
154           separator_ends_record = 0;
155           break;
156         case 'r':
157           sentinel_length = 0;
158           break;
159         case 's':
160           separator = optarg;
161           if (*separator == 0)
162             error (1, 0, "separator cannot be empty");
163           break;
164         default:
165           usage ();
166         }
167     }
168
169   if (flag_version)
170     fprintf (stderr, "%s\n", version_string);
171
172   if (flag_help)
173     usage ();
174
175   if (sentinel_length == 0)
176     {
177       compiled_separator.allocated = 100;
178       compiled_separator.buffer = (unsigned char *)
179         xmalloc (compiled_separator.allocated);
180       compiled_separator.fastmap = xmalloc (256);
181       compiled_separator.translate = 0;
182       error_message = re_compile_pattern (separator, strlen (separator),
183                                           &compiled_separator);
184       if (error_message)
185         error (1, 0, "%s", error_message);
186     }
187   else
188     match_length = sentinel_length = strlen (separator);
189
190   read_size = INITIAL_READSIZE;
191   /* A precaution that will probably never be needed. */
192   while (sentinel_length * 2 >= read_size)
193     read_size *= 2;
194   buffer_size = read_size * 2 + sentinel_length + 2;
195   buffer = xmalloc (buffer_size);
196   if (sentinel_length)
197     {
198       strcpy (buffer, separator);
199       buffer += sentinel_length;
200     }
201   else
202     ++buffer;
203
204   if (optind == argc)
205     {
206       have_read_stdin = 1;
207       errors = tac_stdin ();
208     }
209   else
210     for (; optind < argc; ++optind)
211       {
212         if (strcmp (argv[optind], "-") == 0)
213           {
214             have_read_stdin = 1;
215             errors |= tac_stdin ();
216           }
217         else
218           errors |= tac_file (argv[optind]);
219       }
220
221   /* Flush the output buffer. */
222   output ((char *) NULL, (char *) NULL);
223
224   if (have_read_stdin && close (0) < 0)
225     error (1, errno, "-");
226   if (close (1) < 0)
227     error (1, errno, "write error");
228   exit (errors);
229 }
230
231 /* The name of a temporary file containing a copy of pipe input. */
232 char *tempfile;
233
234 /* Print the standard input in reverse, saving it to temporary
235    file `tempfile' first if it is a pipe.
236    Return 0 if ok, 1 if an error occurs. */
237
238 static int
239 tac_stdin ()
240 {
241   /* Previous values of signal handlers. */
242   RETSIGTYPE (*sigint) (), (*sighup) (), (*sigpipe) (), (*sigterm) ();
243   int errors;
244   struct stat stats;
245 #ifdef _POSIX_VERSION
246     struct sigaction oldact, newact;
247 #endif                          /* _POSIX_VERSION */
248
249   /* No tempfile is needed for "tac < file".
250      Use fstat instead of checking for errno == ESPIPE because
251      lseek doesn't work on some special files but doesn't return an
252      error, either. */
253   if (fstat (0, &stats))
254     {
255       error (0, errno, "standard input");
256       return 1;
257     }
258   if (S_ISREG (stats.st_mode))
259     return tac (0, "standard input");
260
261 #ifdef _POSIX_VERSION
262   newact.sa_handler = cleanup;
263   sigemptyset (&newact.sa_mask);
264   newact.sa_flags = 0;
265
266   sigaction (SIGINT, NULL, &oldact);
267   sigint = oldact.sa_handler;
268   if (sigint != SIG_IGN)
269     sigaction (SIGINT, &newact, NULL);
270
271   sigaction (SIGHUP, NULL, &oldact);
272   sighup = oldact.sa_handler;
273   if (sighup != SIG_IGN)
274     sigaction (SIGHUP, &newact, NULL);
275
276   sigaction (SIGPIPE, NULL, &oldact);
277   sigpipe = oldact.sa_handler;
278   if (sigpipe != SIG_IGN)
279     sigaction (SIGPIPE, &newact, NULL);
280
281   sigaction (SIGTERM, NULL, &oldact);
282   sigterm = oldact.sa_handler;
283   if (sigterm != SIG_IGN)
284     sigaction (SIGTERM, &newact, NULL);
285 #else                           /* !_POSIX_VERSION */
286   sigint = signal (SIGINT, SIG_IGN);
287   if (sigint != SIG_IGN)
288     signal (SIGINT, cleanup);
289
290   sighup = signal (SIGHUP, SIG_IGN);
291   if (sighup != SIG_IGN)
292     signal (SIGHUP, cleanup);
293
294   sigpipe = signal (SIGPIPE, SIG_IGN);
295   if (sigpipe != SIG_IGN)
296     signal (SIGPIPE, cleanup);
297
298   sigterm = signal (SIGTERM, SIG_IGN);
299   if (sigterm != SIG_IGN)
300     signal (SIGTERM, cleanup);
301 #endif                          /* _POSIX_VERSION */
302
303   save_stdin ();
304
305   errors = tac_file (tempfile);
306
307   unlink (tempfile);
308
309 #ifdef _POSIX_VERSION
310   newact.sa_handler = sigint;
311   sigaction (SIGINT, &newact, NULL);
312   newact.sa_handler = sighup;
313   sigaction (SIGHUP, &newact, NULL);
314   newact.sa_handler = sigterm;
315   sigaction (SIGTERM, &newact, NULL);
316   newact.sa_handler = sigpipe;
317   sigaction (SIGPIPE, &newact, NULL);
318 #else                           /* !_POSIX_VERSION */
319   signal (SIGINT, sigint);
320   signal (SIGHUP, sighup);
321   signal (SIGTERM, sigterm);
322   signal (SIGPIPE, sigpipe);
323 #endif                          /* _POSIX_VERSION */
324
325   return errors;
326 }
327
328 /* Make a copy of the standard input in `tempfile'. */
329
330 static void
331 save_stdin ()
332 {
333   static char *template = NULL;
334   static char *tempdir;
335   int fd;
336   int bytes_read;
337
338   if (template == NULL)
339     {
340       tempdir = getenv ("TMPDIR");
341       if (tempdir == NULL)
342         tempdir = "/tmp";
343       template = xmalloc (strlen (tempdir) + 11);
344     }
345   sprintf (template, "%s/tacXXXXXX", tempdir);
346   tempfile = mktemp (template);
347
348   fd = creat (tempfile, 0600);
349   if (fd == -1)
350     {
351       error (0, errno, "%s", tempfile);
352       cleanup ();
353     }
354   while ((bytes_read = read (0, buffer, read_size)) > 0)
355     if (write (fd, buffer, bytes_read) != bytes_read)
356       {
357         error (0, errno, "%s", tempfile);
358         cleanup ();
359       }
360   if (close (fd) < 0)
361     {
362       error (0, errno, "%s", tempfile);
363       cleanup ();
364     }
365   if (bytes_read == -1)
366     {
367       error (0, errno, "read error");
368       cleanup ();
369     }
370 }
371
372 /* Print FILE in reverse.
373    Return 0 if ok, 1 if an error occurs. */
374
375 static int
376 tac_file (file)
377      char *file;
378 {
379   int fd, errors;
380
381   fd = open (file, 0);
382   if (fd == -1)
383     {
384       error (0, errno, "%s", file);
385       return 1;
386     }
387   errors = tac (fd, file);
388   if (close (fd) < 0)
389     {
390       error (0, errno, "%s", file);
391       return 1;
392     }
393   return errors;
394 }
395
396 /* Print in reverse the file open on descriptor FD for reading FILE.
397    Return 0 if ok, 1 if an error occurs. */
398
399 static int
400 tac (fd, file)
401      int fd;
402      char *file;
403 {
404   /* Pointer to the location in `buffer' where the search for
405      the next separator will begin. */
406   char *match_start;
407   /* Pointer to one past the rightmost character in `buffer' that
408      has not been printed yet. */
409   char *past_end;
410   unsigned saved_record_size;   /* Length of the record growing in `buffer'. */
411   off_t file_pos;               /* Offset in the file of the next read. */
412   /* Nonzero if `output' has not been called yet for any file.
413      Only used when the separator is attached to the preceding record. */
414   int first_time = 1;
415   char first_char = *separator; /* Speed optimization, non-regexp. */
416   char *separator1 = separator + 1; /* Speed optimization, non-regexp. */
417   int match_length1 = match_length - 1; /* Speed optimization, non-regexp. */
418   struct re_registers regs;
419
420   /* Find the size of the input file. */
421   file_pos = lseek (fd, (off_t) 0, SEEK_END);
422   if (file_pos < 1)
423     return 0;                   /* It's an empty file. */
424
425   /* Arrange for the first read to lop off enough to leave the rest of the
426      file a multiple of `read_size'.  Since `read_size' can change, this may
427      not always hold during the program run, but since it usually will, leave
428      it here for i/o efficiency (page/sector boundaries and all that).
429      Note: the efficiency gain has not been verified. */
430   saved_record_size = file_pos % read_size;
431   if (saved_record_size == 0)
432     saved_record_size = read_size;
433   file_pos -= saved_record_size;
434   /* `file_pos' now points to the start of the last (probably partial) block
435      in the input file. */
436
437   lseek (fd, file_pos, SEEK_SET);
438   if (read (fd, buffer, saved_record_size) != saved_record_size)
439     {
440       error (0, 1, "%s", file);
441       return 1;
442     }
443
444   match_start = past_end = buffer + saved_record_size;
445   /* For non-regexp search, move past impossible positions for a match. */
446   if (sentinel_length)
447     match_start -= match_length1;
448
449   for (;;)
450     {
451       /* Search backward from `match_start' - 1 to `buffer' for a match
452          with `separator'; for speed, use strncmp if `separator' contains no
453          metacharacters.
454          If the match succeeds, set `match_start' to point to the start of
455          the match and `match_length' to the length of the match.
456          Otherwise, make `match_start' < `buffer'. */
457       if (sentinel_length == 0)
458         {
459           int i = match_start - buffer;
460           int ret;
461
462           ret = re_search (&compiled_separator, buffer, i, i - 1, -i, &regs);
463           if (ret == -1)
464             match_start = buffer - 1;
465           else if (ret == -2)
466             {
467               error (0, 0, "error in regular expression search");
468               cleanup ();
469             }
470           else
471             {
472               match_start = buffer + regs.start[0];
473               match_length = regs.end[0] - regs.start[0];
474             }
475         }
476       else
477         {
478           /* `match_length' is constant for non-regexp boundaries. */
479           while (*--match_start != first_char
480                  || (match_length1 && strncmp (match_start + 1, separator1,
481                                                match_length1)))
482             /* Do nothing. */ ;
483         }
484
485       /* Check whether we backed off the front of `buffer' without finding
486          a match for `separator'. */
487       if (match_start < buffer)
488         {
489           if (file_pos == 0)
490             {
491               /* Hit the beginning of the file; print the remaining record. */
492               output (buffer, past_end);
493               return 0;
494             }
495
496           saved_record_size = past_end - buffer;
497           if (saved_record_size > read_size)
498             {
499               /* `buffer_size' is about twice `read_size', so since
500                  we want to read in another `read_size' bytes before
501                  the data already in `buffer', we need to increase
502                  `buffer_size'. */
503               char *newbuffer;
504               int offset = sentinel_length ? sentinel_length : 1;
505
506               read_size *= 2;
507               buffer_size = read_size * 2 + sentinel_length + 2;
508               newbuffer = xrealloc (buffer - offset, buffer_size) + offset;
509               /* Adjust the pointers for the new buffer location.  */
510               match_start += newbuffer - buffer;
511               past_end += newbuffer - buffer;
512               buffer = newbuffer;
513             }
514
515           /* Back up to the start of the next bufferfull of the file.  */
516           if (file_pos >= read_size)
517             file_pos -= read_size;
518           else
519             {
520               read_size = file_pos;
521               file_pos = 0;
522             }
523           lseek (fd, file_pos, SEEK_SET);
524
525           /* Shift the pending record data right to make room for the new. */
526           bcopy (buffer, buffer + read_size, saved_record_size);
527           past_end = buffer + read_size + saved_record_size;
528           /* For non-regexp searches, avoid unneccessary scanning. */
529           if (sentinel_length)
530             match_start = buffer + read_size;
531           else
532             match_start = past_end;
533
534           if (read (fd, buffer, read_size) != read_size)
535             {
536               error (0, errno, "%s", file);
537               return 1;
538             }
539         }
540       else
541         {
542           /* Found a match of `separator'. */
543           if (separator_ends_record)
544             {
545               char *match_end = match_start + match_length;
546
547               /* If this match of `separator' isn't at the end of the
548                  file, print the record. */
549               if (first_time == 0 || match_end != past_end)
550                 output (match_end, past_end);
551               past_end = match_end;
552               first_time = 0;
553             }
554           else
555             {
556               output (match_start, past_end);
557               past_end = match_start;
558             }
559           match_start -= match_length - 1;
560         }
561     }
562 }
563
564 /* Print the characters from START to PAST_END - 1.
565    If START is NULL, just flush the buffer. */
566
567 static void
568 output (start, past_end)
569      char *start;
570      char *past_end;
571 {
572   static char buffer[WRITESIZE];
573   static int bytes_in_buffer = 0;
574   int bytes_to_add = past_end - start;
575   int bytes_available = WRITESIZE - bytes_in_buffer;
576
577   if (start == 0)
578     {
579       xwrite (1, buffer, bytes_in_buffer);
580       bytes_in_buffer = 0;
581       return;
582     }
583   
584   /* Write out as many full buffers as possible. */
585   while (bytes_to_add >= bytes_available)
586     {
587       bcopy (start, buffer + bytes_in_buffer, bytes_available);
588       bytes_to_add -= bytes_available;
589       start += bytes_available;
590       xwrite (1, buffer, WRITESIZE);
591       bytes_in_buffer = 0;
592       bytes_available = WRITESIZE;
593     }
594
595   bcopy (start, buffer + bytes_in_buffer, bytes_to_add);
596   bytes_in_buffer += bytes_to_add;
597 }
598
599 static RETSIGTYPE
600 cleanup ()
601 {
602   unlink (tempfile);
603   exit (1);
604 }
605
606 static void
607 xwrite (desc, buffer, size)
608      int desc;
609      char *buffer;
610      int size;
611 {
612   if (write (desc, buffer, size) != size)
613     {
614       error (0, errno, "write error");
615       cleanup ();
616     }
617 }
618
619 /* Allocate N bytes of memory dynamically, with error checking.  */
620
621 static char *
622 xmalloc (n)
623      unsigned n;
624 {
625   char *p;
626
627   p = malloc (n);
628   if (p == 0)
629     {
630       error (0, 0, "virtual memory exhausted");
631       cleanup ();
632     }
633   return p;
634 }
635
636 /* Change the size of memory area P to N bytes, with error checking. */
637
638 static char *
639 xrealloc (p, n)
640      char *p;
641      unsigned n;
642 {
643   p = realloc (p, n);
644   if (p == 0)
645     {
646       error (0, 0, "virtual memory exhausted");
647       cleanup ();
648     }
649   return p;
650 }