add "const" attribute, where possible
[platform/upstream/coreutils.git] / src / csplit.c
1 /* csplit - split a file into sections determined by context lines
2    Copyright (C) 91, 1995-2008 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 3 of the License, or
7    (at your option) 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, see <http://www.gnu.org/licenses/>.  */
16
17 /* Written by Stuart Kemp, cpsrk@groper.jcu.edu.au.
18    Modified by David MacKenzie, djm@gnu.ai.mit.edu. */
19
20 #include <config.h>
21
22 #include <getopt.h>
23 #include <sys/types.h>
24 #include <signal.h>
25
26 #include "system.h"
27
28 #include <regex.h>
29
30 #include "error.h"
31 #include "fd-reopen.h"
32 #include "inttostr.h"
33 #include "quote.h"
34 #include "safe-read.h"
35 #include "stdio--.h"
36 #include "xstrtol.h"
37
38 /* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is
39    present.  */
40 #ifndef SA_NOCLDSTOP
41 # define SA_NOCLDSTOP 0
42 # define sigprocmask(How, Set, Oset) /* empty */
43 # define sigset_t int
44 # if ! HAVE_SIGINTERRUPT
45 #  define siginterrupt(sig, flag) /* empty */
46 # endif
47 #endif
48
49 /* The official name of this program (e.g., no `g' prefix).  */
50 #define PROGRAM_NAME "csplit"
51
52 #define AUTHORS \
53   proper_name ("Stuart Kemp"), \
54   proper_name ("David MacKenzie")
55
56 /* Increment size of area for control records. */
57 #define ALLOC_SIZE 20
58
59 /* The default prefix for output file names. */
60 #define DEFAULT_PREFIX  "xx"
61
62 /* A compiled pattern arg. */
63 struct control
64 {
65   intmax_t offset;              /* Offset from regexp to split at. */
66   uintmax_t lines_required;     /* Number of lines required. */
67   uintmax_t repeat;             /* Repeat count. */
68   int argnum;                   /* ARGV index. */
69   bool repeat_forever;          /* True if `*' used as a repeat count. */
70   bool ignore;                  /* If true, produce no output (for regexp). */
71   bool regexpr;                 /* True if regular expression was used. */
72   struct re_pattern_buffer re_compiled; /* Compiled regular expression. */
73 };
74
75 /* Initial size of data area in buffers. */
76 #define START_SIZE      8191
77
78 /* Increment size for data area. */
79 #define INCR_SIZE       2048
80
81 /* Number of lines kept in each node in line list. */
82 #define CTRL_SIZE       80
83
84 #ifdef DEBUG
85 /* Some small values to test the algorithms. */
86 # define START_SIZE     200
87 # define INCR_SIZE      10
88 # define CTRL_SIZE      1
89 #endif
90
91 /* A string with a length count. */
92 struct cstring
93 {
94   size_t len;
95   char *str;
96 };
97
98 /* Pointers to the beginnings of lines in the buffer area.
99    These structures are linked together if needed. */
100 struct line
101 {
102   size_t used;                  /* Number of offsets used in this struct. */
103   size_t insert_index;          /* Next offset to use when inserting line. */
104   size_t retrieve_index;        /* Next index to use when retrieving line. */
105   struct cstring starts[CTRL_SIZE]; /* Lines in the data area. */
106   struct line *next;            /* Next in linked list. */
107 };
108
109 /* The structure to hold the input lines.
110    Contains a pointer to the data area and a list containing
111    pointers to the individual lines. */
112 struct buffer_record
113 {
114   size_t bytes_alloc;           /* Size of the buffer area. */
115   size_t bytes_used;            /* Bytes used in the buffer area. */
116   uintmax_t start_line;         /* First line number in this buffer. */
117   uintmax_t first_available;    /* First line that can be retrieved. */
118   size_t num_lines;             /* Number of complete lines in this buffer. */
119   char *buffer;                 /* Data area. */
120   struct line *line_start;      /* Head of list of pointers to lines. */
121   struct line *curr_line;       /* The line start record currently in use. */
122   struct buffer_record *next;
123 };
124
125 static void close_output_file (void);
126 static void create_output_file (void);
127 static void delete_all_files (bool);
128 static void save_line_to_file (const struct cstring *line);
129 void usage (int status);
130
131 /* Start of buffer list. */
132 static struct buffer_record *head = NULL;
133
134 /* Partially read line. */
135 static char *hold_area = NULL;
136
137 /* Number of bytes in `hold_area'. */
138 static size_t hold_count = 0;
139
140 /* Number of the last line in the buffers. */
141 static uintmax_t last_line_number = 0;
142
143 /* Number of the line currently being examined. */
144 static uintmax_t current_line = 0;
145
146 /* If true, we have read EOF. */
147 static bool have_read_eof = false;
148
149 /* Name of output files. */
150 static char *volatile filename_space = NULL;
151
152 /* Prefix part of output file names. */
153 static char const *volatile prefix = NULL;
154
155 /* Suffix part of output file names. */
156 static char *volatile suffix = NULL;
157
158 /* Number of digits to use in output file names. */
159 static int volatile digits = 2;
160
161 /* Number of files created so far. */
162 static unsigned int volatile files_created = 0;
163
164 /* Number of bytes written to current file. */
165 static uintmax_t bytes_written;
166
167 /* Output file pointer. */
168 static FILE *output_stream = NULL;
169
170 /* Output file name. */
171 static char *output_filename = NULL;
172
173 /* Perhaps it would be cleaner to pass arg values instead of indexes. */
174 static char **global_argv;
175
176 /* If true, do not print the count of bytes in each output file. */
177 static bool suppress_count;
178
179 /* If true, remove output files on error. */
180 static bool volatile remove_files;
181
182 /* If true, remove all output files which have a zero length. */
183 static bool elide_empty_files;
184
185 /* The compiled pattern arguments, which determine how to split
186    the input file. */
187 static struct control *controls;
188
189 /* Number of elements in `controls'. */
190 static size_t control_used;
191
192 /* The set of signals that are caught.  */
193 static sigset_t caught_signals;
194
195 static const struct option const longopts[] =
196 {
197   {"digits", required_argument, NULL, 'n'},
198   {"quiet", no_argument, NULL, 'q'},
199   {"silent", no_argument, NULL, 's'},
200   {"keep-files", no_argument, NULL, 'k'},
201   {"elide-empty-files", no_argument, NULL, 'z'},
202   {"prefix", required_argument, NULL, 'f'},
203   {"suffix-format", required_argument, NULL, 'b'},
204   {GETOPT_HELP_OPTION_DECL},
205   {GETOPT_VERSION_OPTION_DECL},
206   {NULL, 0, NULL, 0}
207 };
208
209 /* Optionally remove files created so far; then exit.
210    Called when an error detected. */
211
212 static void
213 cleanup (void)
214 {
215   sigset_t oldset;
216
217   close_output_file ();
218
219   sigprocmask (SIG_BLOCK, &caught_signals, &oldset);
220   delete_all_files (false);
221   sigprocmask (SIG_SETMASK, &oldset, NULL);
222 }
223
224 static void cleanup_fatal (void) ATTRIBUTE_NORETURN;
225 static void
226 cleanup_fatal (void)
227 {
228   cleanup ();
229   exit (EXIT_FAILURE);
230 }
231
232 extern void
233 xalloc_die (void)
234 {
235   error (0, 0, "%s", _("memory exhausted"));
236   cleanup_fatal ();
237 }
238
239 static void
240 interrupt_handler (int sig)
241 {
242   if (! SA_NOCLDSTOP)
243     signal (sig, SIG_IGN);
244
245   delete_all_files (true);
246
247   signal (sig, SIG_DFL);
248   raise (sig);
249 }
250
251 /* Keep track of NUM bytes of a partial line in buffer START.
252    These bytes will be retrieved later when another large buffer is read.  */
253
254 static void
255 save_to_hold_area (char *start, size_t num)
256 {
257   free (hold_area);
258   hold_area = start;
259   hold_count = num;
260 }
261
262 /* Read up to MAX_N_BYTES bytes from the input stream into DEST.
263    Return the number of bytes read. */
264
265 static size_t
266 read_input (char *dest, size_t max_n_bytes)
267 {
268   size_t bytes_read;
269
270   if (max_n_bytes == 0)
271     return 0;
272
273   bytes_read = safe_read (STDIN_FILENO, dest, max_n_bytes);
274
275   if (bytes_read == 0)
276     have_read_eof = true;
277
278   if (bytes_read == SAFE_READ_ERROR)
279     {
280       error (0, errno, _("read error"));
281       cleanup_fatal ();
282     }
283
284   return bytes_read;
285 }
286
287 /* Initialize existing line record P. */
288
289 static void
290 clear_line_control (struct line *p)
291 {
292   p->used = 0;
293   p->insert_index = 0;
294   p->retrieve_index = 0;
295 }
296
297 /* Return a new, initialized line record. */
298
299 static struct line *
300 new_line_control (void)
301 {
302   struct line *p = xmalloc (sizeof *p);
303
304   p->next = NULL;
305   clear_line_control (p);
306
307   return p;
308 }
309
310 /* Record LINE_START, which is the address of the start of a line
311    of length LINE_LEN in the large buffer, in the lines buffer of B. */
312
313 static void
314 keep_new_line (struct buffer_record *b, char *line_start, size_t line_len)
315 {
316   struct line *l;
317
318   /* If there is no existing area to keep line info, get some. */
319   if (b->line_start == NULL)
320     b->line_start = b->curr_line = new_line_control ();
321
322   /* If existing area for lines is full, get more. */
323   if (b->curr_line->used == CTRL_SIZE)
324     {
325       b->curr_line->next = new_line_control ();
326       b->curr_line = b->curr_line->next;
327     }
328
329   l = b->curr_line;
330
331   /* Record the start of the line, and update counters. */
332   l->starts[l->insert_index].str = line_start;
333   l->starts[l->insert_index].len = line_len;
334   l->used++;
335   l->insert_index++;
336 }
337
338 /* Scan the buffer in B for newline characters
339    and record the line start locations and lengths in B.
340    Return the number of lines found in this buffer.
341
342    There may be an incomplete line at the end of the buffer;
343    a pointer is kept to this area, which will be used when
344    the next buffer is filled. */
345
346 static size_t
347 record_line_starts (struct buffer_record *b)
348 {
349   char *line_start;             /* Start of current line. */
350   char *line_end;               /* End of each line found. */
351   size_t bytes_left;            /* Length of incomplete last line. */
352   size_t lines;                 /* Number of lines found. */
353   size_t line_length;           /* Length of each line found. */
354
355   if (b->bytes_used == 0)
356     return 0;
357
358   lines = 0;
359   line_start = b->buffer;
360   bytes_left = b->bytes_used;
361
362   for (;;)
363     {
364       line_end = memchr (line_start, '\n', bytes_left);
365       if (line_end == NULL)
366         break;
367       line_length = line_end - line_start + 1;
368       keep_new_line (b, line_start, line_length);
369       bytes_left -= line_length;
370       line_start = line_end + 1;
371       lines++;
372     }
373
374   /* Check for an incomplete last line. */
375   if (bytes_left)
376     {
377       if (have_read_eof)
378         {
379           keep_new_line (b, line_start, bytes_left);
380           lines++;
381         }
382       else
383         save_to_hold_area (xmemdup (line_start, bytes_left), bytes_left);
384     }
385
386   b->num_lines = lines;
387   b->first_available = b->start_line = last_line_number + 1;
388   last_line_number += lines;
389
390   return lines;
391 }
392
393 /* Return a new buffer with room to store SIZE bytes, plus
394    an extra byte for safety. */
395
396 static struct buffer_record *
397 create_new_buffer (size_t size)
398 {
399   struct buffer_record *new_buffer = xmalloc (sizeof *new_buffer);
400
401   new_buffer->buffer = xmalloc (size + 1);
402
403   new_buffer->bytes_alloc = size;
404   new_buffer->line_start = new_buffer->curr_line = NULL;
405
406   return new_buffer;
407 }
408
409 /* Return a new buffer of at least MINSIZE bytes.  If a buffer of at
410    least that size is currently free, use it, otherwise create a new one. */
411
412 static struct buffer_record *
413 get_new_buffer (size_t min_size)
414 {
415   struct buffer_record *new_buffer; /* Buffer to return. */
416   size_t alloc_size;    /* Actual size that will be requested. */
417
418   alloc_size = START_SIZE;
419   if (alloc_size < min_size)
420     {
421       size_t s = min_size - alloc_size + INCR_SIZE - 1;
422       alloc_size += s - s % INCR_SIZE;
423     }
424
425   new_buffer = create_new_buffer (alloc_size);
426
427   new_buffer->num_lines = 0;
428   new_buffer->bytes_used = 0;
429   new_buffer->start_line = new_buffer->first_available = last_line_number + 1;
430   new_buffer->next = NULL;
431
432   return new_buffer;
433 }
434
435 static void
436 free_buffer (struct buffer_record *buf)
437 {
438   free (buf->buffer);
439   buf->buffer = NULL;
440 }
441
442 /* Append buffer BUF to the linked list of buffers that contain
443    some data yet to be processed. */
444
445 static void
446 save_buffer (struct buffer_record *buf)
447 {
448   struct buffer_record *p;
449
450   buf->next = NULL;
451   buf->curr_line = buf->line_start;
452
453   if (head == NULL)
454     head = buf;
455   else
456     {
457       for (p = head; p->next; p = p->next)
458         /* Do nothing. */ ;
459       p->next = buf;
460     }
461 }
462
463 /* Fill a buffer of input.
464
465    Set the initial size of the buffer to a default.
466    Fill the buffer (from the hold area and input stream)
467    and find the individual lines.
468    If no lines are found (the buffer is too small to hold the next line),
469    release the current buffer (whose contents would have been put in the
470    hold area) and repeat the process with another large buffer until at least
471    one entire line has been read.
472
473    Return true if a new buffer was obtained, otherwise false
474    (in which case end-of-file must have been encountered). */
475
476 static bool
477 load_buffer (void)
478 {
479   struct buffer_record *b;
480   size_t bytes_wanted = START_SIZE; /* Minimum buffer size. */
481   size_t bytes_avail;           /* Size of new buffer created. */
482   size_t lines_found;           /* Number of lines in this new buffer. */
483   char *p;                      /* Place to load into buffer. */
484
485   if (have_read_eof)
486     return false;
487
488   /* We must make the buffer at least as large as the amount of data
489      in the partial line left over from the last call. */
490   if (bytes_wanted < hold_count)
491     bytes_wanted = hold_count;
492
493   while (1)
494     {
495       b = get_new_buffer (bytes_wanted);
496       bytes_avail = b->bytes_alloc; /* Size of buffer returned. */
497       p = b->buffer;
498
499       /* First check the `holding' area for a partial line. */
500       if (hold_count)
501         {
502           memcpy (p, hold_area, hold_count);
503           p += hold_count;
504           b->bytes_used += hold_count;
505           bytes_avail -= hold_count;
506           hold_count = 0;
507         }
508
509       b->bytes_used += read_input (p, bytes_avail);
510
511       lines_found = record_line_starts (b);
512       if (!lines_found)
513         free_buffer (b);
514
515       if (lines_found || have_read_eof)
516         break;
517
518       if (xalloc_oversized (2, b->bytes_alloc))
519         xalloc_die ();
520       bytes_wanted = 2 * b->bytes_alloc;
521       free_buffer (b);
522       free (b);
523     }
524
525   if (lines_found)
526     save_buffer (b);
527   else
528     free (b);
529
530   return lines_found != 0;
531 }
532
533 /* Return the line number of the first line that has not yet been retrieved. */
534
535 static uintmax_t
536 get_first_line_in_buffer (void)
537 {
538   if (head == NULL && !load_buffer ())
539     error (EXIT_FAILURE, errno, _("input disappeared"));
540
541   return head->first_available;
542 }
543
544 /* Return a pointer to the logical first line in the buffer and make the
545    next line the logical first line.
546    Return NULL if there is no more input. */
547
548 static struct cstring *
549 remove_line (void)
550 {
551   /* If non-NULL, this is the buffer for which the previous call
552      returned the final line.  So now, presuming that line has been
553      processed, we can free the buffer and reset this pointer.  */
554   static struct buffer_record *prev_buf = NULL;
555
556   struct cstring *line;         /* Return value. */
557   struct line *l;               /* For convenience. */
558
559   if (prev_buf)
560     {
561       free_buffer (prev_buf);
562       prev_buf = NULL;
563     }
564
565   if (head == NULL && !load_buffer ())
566     return NULL;
567
568   if (current_line < head->first_available)
569     current_line = head->first_available;
570
571   ++(head->first_available);
572
573   l = head->curr_line;
574
575   line = &l->starts[l->retrieve_index];
576
577   /* Advance index to next line. */
578   if (++l->retrieve_index == l->used)
579     {
580       /* Go on to the next line record. */
581       head->curr_line = l->next;
582       if (head->curr_line == NULL || head->curr_line->used == 0)
583         {
584           /* Go on to the next data block.
585              but first record the current one so we can free it
586              once the line we're returning has been processed.  */
587           prev_buf = head;
588           head = head->next;
589         }
590     }
591
592   return line;
593 }
594
595 /* Search the buffers for line LINENUM, reading more input if necessary.
596    Return a pointer to the line, or NULL if it is not found in the file. */
597
598 static struct cstring *
599 find_line (uintmax_t linenum)
600 {
601   struct buffer_record *b;
602
603   if (head == NULL && !load_buffer ())
604     return NULL;
605
606   if (linenum < head->start_line)
607     return NULL;
608
609   for (b = head;;)
610     {
611       if (linenum < b->start_line + b->num_lines)
612         {
613           /* The line is in this buffer. */
614           struct line *l;
615           size_t offset;        /* How far into the buffer the line is. */
616
617           l = b->line_start;
618           offset = linenum - b->start_line;
619           /* Find the control record. */
620           while (offset >= CTRL_SIZE)
621             {
622               l = l->next;
623               offset -= CTRL_SIZE;
624             }
625           return &l->starts[offset];
626         }
627       if (b->next == NULL && !load_buffer ())
628         return NULL;
629       b = b->next;              /* Try the next data block. */
630     }
631 }
632
633 /* Return true if at least one more line is available for input. */
634
635 static bool
636 no_more_lines (void)
637 {
638   return find_line (current_line + 1) == NULL;
639 }
640
641 /* Open NAME as standard input.  */
642
643 static void
644 set_input_file (const char *name)
645 {
646   if (! STREQ (name, "-") && fd_reopen (STDIN_FILENO, name, O_RDONLY, 0) < 0)
647     error (EXIT_FAILURE, errno, _("cannot open %s for reading"), quote (name));
648 }
649
650 /* Write all lines from the beginning of the buffer up to, but
651    not including, line LAST_LINE, to the current output file.
652    If IGNORE is true, do not output lines selected here.
653    ARGNUM is the index in ARGV of the current pattern. */
654
655 static void
656 write_to_file (uintmax_t last_line, bool ignore, int argnum)
657 {
658   struct cstring *line;
659   uintmax_t first_line;         /* First available input line. */
660   uintmax_t lines;              /* Number of lines to output. */
661   uintmax_t i;
662
663   first_line = get_first_line_in_buffer ();
664
665   if (first_line > last_line)
666     {
667       error (0, 0, _("%s: line number out of range"), global_argv[argnum]);
668       cleanup_fatal ();
669     }
670
671   lines = last_line - first_line;
672
673   for (i = 0; i < lines; i++)
674     {
675       line = remove_line ();
676       if (line == NULL)
677         {
678           error (0, 0, _("%s: line number out of range"), global_argv[argnum]);
679           cleanup_fatal ();
680         }
681       if (!ignore)
682         save_line_to_file (line);
683     }
684 }
685
686 /* Output any lines left after all regexps have been processed. */
687
688 static void
689 dump_rest_of_file (void)
690 {
691   struct cstring *line;
692
693   while ((line = remove_line ()) != NULL)
694     save_line_to_file (line);
695 }
696
697 /* Handle an attempt to read beyond EOF under the control of record P,
698    on iteration REPETITION if nonzero. */
699
700 static void handle_line_error (const struct control *, uintmax_t)
701      ATTRIBUTE_NORETURN;
702 static void
703 handle_line_error (const struct control *p, uintmax_t repetition)
704 {
705   char buf[INT_BUFSIZE_BOUND (uintmax_t)];
706
707   fprintf (stderr, _("%s: %s: line number out of range"),
708            program_name, quote (umaxtostr (p->lines_required, buf)));
709   if (repetition)
710     fprintf (stderr, _(" on repetition %s\n"), umaxtostr (repetition, buf));
711   else
712     fprintf (stderr, "\n");
713
714   cleanup_fatal ();
715 }
716
717 /* Determine the line number that marks the end of this file,
718    then get those lines and save them to the output file.
719    P is the control record.
720    REPETITION is the repetition number. */
721
722 static void
723 process_line_count (const struct control *p, uintmax_t repetition)
724 {
725   uintmax_t linenum;
726   uintmax_t last_line_to_save = p->lines_required * (repetition + 1);
727   struct cstring *line;
728
729   create_output_file ();
730
731   linenum = get_first_line_in_buffer ();
732
733   while (linenum++ < last_line_to_save)
734     {
735       line = remove_line ();
736       if (line == NULL)
737         handle_line_error (p, repetition);
738       save_line_to_file (line);
739     }
740
741   close_output_file ();
742
743   /* Ensure that the line number specified is not 1 greater than
744      the number of lines in the file. */
745   if (no_more_lines ())
746     handle_line_error (p, repetition);
747 }
748
749 static void regexp_error (struct control *, uintmax_t, bool) ATTRIBUTE_NORETURN;
750 static void
751 regexp_error (struct control *p, uintmax_t repetition, bool ignore)
752 {
753   fprintf (stderr, _("%s: %s: match not found"),
754            program_name, quote (global_argv[p->argnum]));
755
756   if (repetition)
757     {
758       char buf[INT_BUFSIZE_BOUND (uintmax_t)];
759       fprintf (stderr, _(" on repetition %s\n"), umaxtostr (repetition, buf));
760     }
761   else
762     fprintf (stderr, "\n");
763
764   if (!ignore)
765     {
766       dump_rest_of_file ();
767       close_output_file ();
768     }
769   cleanup_fatal ();
770 }
771
772 /* Read the input until a line matches the regexp in P, outputting
773    it unless P->IGNORE is true.
774    REPETITION is this repeat-count; 0 means the first time. */
775
776 static void
777 process_regexp (struct control *p, uintmax_t repetition)
778 {
779   struct cstring *line;         /* From input file. */
780   size_t line_len;              /* To make "$" in regexps work. */
781   uintmax_t break_line;         /* First line number of next file. */
782   bool ignore = p->ignore;      /* If true, skip this section. */
783   regoff_t ret;
784
785   if (!ignore)
786     create_output_file ();
787
788   /* If there is no offset for the regular expression, or
789      it is positive, then it is not necessary to buffer the lines. */
790
791   if (p->offset >= 0)
792     {
793       for (;;)
794         {
795           line = find_line (++current_line);
796           if (line == NULL)
797             {
798               if (p->repeat_forever)
799                 {
800                   if (!ignore)
801                     {
802                       dump_rest_of_file ();
803                       close_output_file ();
804                     }
805                   exit (EXIT_SUCCESS);
806                 }
807               else
808                 regexp_error (p, repetition, ignore);
809             }
810           line_len = line->len;
811           if (line->str[line_len - 1] == '\n')
812             line_len--;
813           ret = re_search (&p->re_compiled, line->str, line_len,
814                            0, line_len, NULL);
815           if (ret == -2)
816             {
817               error (0, 0, _("error in regular expression search"));
818               cleanup_fatal ();
819             }
820           if (ret == -1)
821             {
822               line = remove_line ();
823               if (!ignore)
824                 save_line_to_file (line);
825             }
826           else
827             break;
828         }
829     }
830   else
831     {
832       /* Buffer the lines. */
833       for (;;)
834         {
835           line = find_line (++current_line);
836           if (line == NULL)
837             {
838               if (p->repeat_forever)
839                 {
840                   if (!ignore)
841                     {
842                       dump_rest_of_file ();
843                       close_output_file ();
844                     }
845                   exit (EXIT_SUCCESS);
846                 }
847               else
848                 regexp_error (p, repetition, ignore);
849             }
850           line_len = line->len;
851           if (line->str[line_len - 1] == '\n')
852             line_len--;
853           ret = re_search (&p->re_compiled, line->str, line_len,
854                            0, line_len, NULL);
855           if (ret == -2)
856             {
857               error (0, 0, _("error in regular expression search"));
858               cleanup_fatal ();
859             }
860           if (ret != -1)
861             break;
862         }
863     }
864
865   /* Account for any offset from this regexp. */
866   break_line = current_line + p->offset;
867
868   write_to_file (break_line, ignore, p->argnum);
869
870   if (!ignore)
871     close_output_file ();
872
873   if (p->offset > 0)
874     current_line = break_line;
875 }
876
877 /* Split the input file according to the control records we have built. */
878
879 static void
880 split_file (void)
881 {
882   size_t i;
883
884   for (i = 0; i < control_used; i++)
885     {
886       uintmax_t j;
887       if (controls[i].regexpr)
888         {
889           for (j = 0; (controls[i].repeat_forever
890                        || j <= controls[i].repeat); j++)
891             process_regexp (&controls[i], j);
892         }
893       else
894         {
895           for (j = 0; (controls[i].repeat_forever
896                        || j <= controls[i].repeat); j++)
897             process_line_count (&controls[i], j);
898         }
899     }
900
901   create_output_file ();
902   dump_rest_of_file ();
903   close_output_file ();
904 }
905
906 /* Return the name of output file number NUM.
907
908    This function is called from a signal handler, so it should invoke
909    only reentrant functions that are async-signal-safe.  POSIX does
910    not guarantee this for the functions called below, but we don't
911    know of any hosts where this implementation isn't safe.  */
912
913 static char *
914 make_filename (unsigned int num)
915 {
916   strcpy (filename_space, prefix);
917   if (suffix)
918     sprintf (filename_space + strlen (prefix), suffix, num);
919   else
920     sprintf (filename_space + strlen (prefix), "%0*u", digits, num);
921   return filename_space;
922 }
923
924 /* Create the next output file. */
925
926 static void
927 create_output_file (void)
928 {
929   sigset_t oldset;
930   bool fopen_ok;
931   int fopen_errno;
932
933   output_filename = make_filename (files_created);
934
935   /* Create the output file in a critical section, to avoid races.  */
936   sigprocmask (SIG_BLOCK, &caught_signals, &oldset);
937   output_stream = fopen (output_filename, "w");
938   fopen_ok = (output_stream != NULL);
939   fopen_errno = errno;
940   files_created += fopen_ok;
941   sigprocmask (SIG_SETMASK, &oldset, NULL);
942
943   if (! fopen_ok)
944     {
945       error (0, fopen_errno, "%s", output_filename);
946       cleanup_fatal ();
947     }
948   bytes_written = 0;
949 }
950
951 /* If requested, delete all the files we have created.  This function
952    must be called only from critical sections.  */
953
954 static void
955 delete_all_files (bool in_signal_handler)
956 {
957   unsigned int i;
958
959   if (! remove_files)
960     return;
961
962   for (i = 0; i < files_created; i++)
963     {
964       const char *name = make_filename (i);
965       if (unlink (name) != 0 && !in_signal_handler)
966         error (0, errno, "%s", name);
967     }
968
969   files_created = 0;
970 }
971
972 /* Close the current output file and print the count
973    of characters in this file. */
974
975 static void
976 close_output_file (void)
977 {
978   if (output_stream)
979     {
980       if (ferror (output_stream))
981         {
982           error (0, 0, _("write error for %s"), quote (output_filename));
983           output_stream = NULL;
984           cleanup_fatal ();
985         }
986       if (fclose (output_stream) != 0)
987         {
988           error (0, errno, "%s", output_filename);
989           output_stream = NULL;
990           cleanup_fatal ();
991         }
992       if (bytes_written == 0 && elide_empty_files)
993         {
994           sigset_t oldset;
995           bool unlink_ok;
996           int unlink_errno;
997
998           /* Remove the output file in a critical section, to avoid races.  */
999           sigprocmask (SIG_BLOCK, &caught_signals, &oldset);
1000           unlink_ok = (unlink (output_filename) == 0);
1001           unlink_errno = errno;
1002           files_created -= unlink_ok;
1003           sigprocmask (SIG_SETMASK, &oldset, NULL);
1004
1005           if (! unlink_ok)
1006             error (0, unlink_errno, "%s", output_filename);
1007         }
1008       else
1009         {
1010           if (!suppress_count)
1011             {
1012               char buf[INT_BUFSIZE_BOUND (uintmax_t)];
1013               fprintf (stdout, "%s\n", umaxtostr (bytes_written, buf));
1014             }
1015         }
1016       output_stream = NULL;
1017     }
1018 }
1019
1020 /* Save line LINE to the output file and
1021    increment the character count for the current file. */
1022
1023 static void
1024 save_line_to_file (const struct cstring *line)
1025 {
1026   fwrite (line->str, sizeof (char), line->len, output_stream);
1027   bytes_written += line->len;
1028 }
1029
1030 /* Return a new, initialized control record. */
1031
1032 static struct control *
1033 new_control_record (void)
1034 {
1035   static size_t control_allocated = 0; /* Total space allocated. */
1036   struct control *p;
1037
1038   if (control_used == control_allocated)
1039     controls = X2NREALLOC (controls, &control_allocated);
1040   p = &controls[control_used++];
1041   p->regexpr = false;
1042   p->repeat = 0;
1043   p->repeat_forever = false;
1044   p->lines_required = 0;
1045   p->offset = 0;
1046   return p;
1047 }
1048
1049 /* Check if there is a numeric offset after a regular expression.
1050    STR is the entire command line argument.
1051    P is the control record for this regular expression.
1052    NUM is the numeric part of STR. */
1053
1054 static void
1055 check_for_offset (struct control *p, const char *str, const char *num)
1056 {
1057   if (xstrtoimax (num, NULL, 10, &p->offset, "") != LONGINT_OK)
1058     error (EXIT_FAILURE, 0, _("%s: integer expected after delimiter"), str);
1059 }
1060
1061 /* Given that the first character of command line arg STR is '{',
1062    make sure that the rest of the string is a valid repeat count
1063    and store its value in P.
1064    ARGNUM is the ARGV index of STR. */
1065
1066 static void
1067 parse_repeat_count (int argnum, struct control *p, char *str)
1068 {
1069   uintmax_t val;
1070   char *end;
1071
1072   end = str + strlen (str) - 1;
1073   if (*end != '}')
1074     error (EXIT_FAILURE, 0, _("%s: `}' is required in repeat count"), str);
1075   *end = '\0';
1076
1077   if (str+1 == end-1 && *(str+1) == '*')
1078     p->repeat_forever = true;
1079   else
1080     {
1081       if (xstrtoumax (str + 1, NULL, 10, &val, "") != LONGINT_OK)
1082         {
1083           error (EXIT_FAILURE, 0,
1084                  _("%s}: integer required between `{' and `}'"),
1085                  global_argv[argnum]);
1086         }
1087       p->repeat = val;
1088     }
1089
1090   *end = '}';
1091 }
1092
1093 /* Extract the regular expression from STR and check for a numeric offset.
1094    STR should start with the regexp delimiter character.
1095    Return a new control record for the regular expression.
1096    ARGNUM is the ARGV index of STR.
1097    Unless IGNORE is true, mark these lines for output. */
1098
1099 static struct control *
1100 extract_regexp (int argnum, bool ignore, char const *str)
1101 {
1102   size_t len;                   /* Number of bytes in this regexp. */
1103   char delim = *str;
1104   char const *closing_delim;
1105   struct control *p;
1106   const char *err;
1107
1108   closing_delim = strrchr (str + 1, delim);
1109   if (closing_delim == NULL)
1110     error (EXIT_FAILURE, 0,
1111            _("%s: closing delimiter `%c' missing"), str, delim);
1112
1113   len = closing_delim - str - 1;
1114   p = new_control_record ();
1115   p->argnum = argnum;
1116   p->ignore = ignore;
1117
1118   p->regexpr = true;
1119   p->re_compiled.buffer = NULL;
1120   p->re_compiled.allocated = 0;
1121   p->re_compiled.fastmap = xmalloc (UCHAR_MAX + 1);
1122   p->re_compiled.translate = NULL;
1123   re_syntax_options =
1124     RE_SYNTAX_POSIX_BASIC & ~RE_CONTEXT_INVALID_DUP & ~RE_NO_EMPTY_RANGES;
1125   err = re_compile_pattern (str + 1, len, &p->re_compiled);
1126   if (err)
1127     {
1128       error (0, 0, _("%s: invalid regular expression: %s"), str, err);
1129       cleanup_fatal ();
1130     }
1131
1132   if (closing_delim[1])
1133     check_for_offset (p, str, closing_delim + 1);
1134
1135   return p;
1136 }
1137
1138 /* Extract the break patterns from args START through ARGC - 1 of ARGV.
1139    After each pattern, check if the next argument is a repeat count. */
1140
1141 static void
1142 parse_patterns (int argc, int start, char **argv)
1143 {
1144   int i;                        /* Index into ARGV. */
1145   struct control *p;            /* New control record created. */
1146   uintmax_t val;
1147   static uintmax_t last_val = 0;
1148
1149   for (i = start; i < argc; i++)
1150     {
1151       if (*argv[i] == '/' || *argv[i] == '%')
1152         {
1153           p = extract_regexp (i, *argv[i] == '%', argv[i]);
1154         }
1155       else
1156         {
1157           p = new_control_record ();
1158           p->argnum = i;
1159
1160           if (xstrtoumax (argv[i], NULL, 10, &val, "") != LONGINT_OK)
1161             error (EXIT_FAILURE, 0, _("%s: invalid pattern"), argv[i]);
1162           if (val == 0)
1163             error (EXIT_FAILURE, 0,
1164                    _("%s: line number must be greater than zero"),
1165                    argv[i]);
1166           if (val < last_val)
1167             {
1168               char buf[INT_BUFSIZE_BOUND (uintmax_t)];
1169               error (EXIT_FAILURE, 0,
1170                _("line number %s is smaller than preceding line number, %s"),
1171                      quote (argv[i]), umaxtostr (last_val, buf));
1172             }
1173
1174           if (val == last_val)
1175             error (0, 0,
1176            _("warning: line number %s is the same as preceding line number"),
1177                    quote (argv[i]));
1178
1179           last_val = val;
1180
1181           p->lines_required = val;
1182         }
1183
1184       if (i + 1 < argc && *argv[i + 1] == '{')
1185         {
1186           /* We have a repeat count. */
1187           i++;
1188           parse_repeat_count (i, p, argv[i]);
1189         }
1190     }
1191 }
1192
1193 static unsigned int
1194 get_format_flags (char **format_ptr)
1195 {
1196   unsigned int count = 0;
1197
1198   for (; **format_ptr; (*format_ptr)++)
1199     {
1200       switch (**format_ptr)
1201         {
1202         case '-':
1203           break;
1204
1205         case '+':
1206         case ' ':
1207           count |= 1;
1208           break;
1209
1210         case '#':
1211           count |= 2;   /* Allow for 0x prefix preceding an `x' conversion.  */
1212           break;
1213
1214         default:
1215           return count;
1216         }
1217     }
1218   return count;
1219 }
1220
1221 static size_t
1222 get_format_width (char **format_ptr)
1223 {
1224   unsigned long int val = 0;
1225
1226   if (ISDIGIT (**format_ptr)
1227       && (xstrtoul (*format_ptr, format_ptr, 10, &val, NULL) != LONGINT_OK
1228           || SIZE_MAX < val))
1229     error (EXIT_FAILURE, 0, _("invalid format width"));
1230
1231   /* Allow for enough octal digits to represent the value of UINT_MAX,
1232      even if the field width is less than that.  */
1233   return MAX (val, (sizeof (unsigned int) * CHAR_BIT + 2) / 3);
1234 }
1235
1236 static size_t
1237 get_format_prec (char **format_ptr)
1238 {
1239   if (**format_ptr != '.')
1240     return 0;
1241   (*format_ptr)++;
1242
1243   if (! ISDIGIT (**format_ptr))
1244     return 0;
1245   else
1246     {
1247       unsigned long int val;
1248       if (xstrtoul (*format_ptr, format_ptr, 10, &val, NULL) != LONGINT_OK
1249           || SIZE_MAX < val)
1250         error (EXIT_FAILURE, 0, _("invalid format precision"));
1251       return val;
1252     }
1253 }
1254
1255 static void
1256 get_format_conv_type (char **format_ptr)
1257 {
1258   unsigned char ch = *(*format_ptr)++;
1259
1260   switch (ch)
1261     {
1262     case 'd':
1263     case 'i':
1264     case 'o':
1265     case 'u':
1266     case 'x':
1267     case 'X':
1268       break;
1269
1270     case 0:
1271       error (EXIT_FAILURE, 0, _("missing conversion specifier in suffix"));
1272       break;
1273
1274     default:
1275       if (isprint (ch))
1276         error (EXIT_FAILURE, 0,
1277                _("invalid conversion specifier in suffix: %c"), ch);
1278       else
1279         error (EXIT_FAILURE, 0,
1280                _("invalid conversion specifier in suffix: \\%.3o"), ch);
1281     }
1282 }
1283
1284 static size_t
1285 max_out (char *format)
1286 {
1287   size_t out_count = 0;
1288   bool percent = false;
1289
1290   while (*format)
1291     {
1292       if (*format++ != '%')
1293         out_count++;
1294       else if (*format == '%')
1295         {
1296           format++;
1297           out_count++;
1298         }
1299       else
1300         {
1301           if (percent)
1302             error (EXIT_FAILURE, 0,
1303                    _("too many %% conversion specifications in suffix"));
1304           percent = true;
1305           out_count += get_format_flags (&format);
1306           {
1307             size_t width = get_format_width (&format);
1308             size_t prec = get_format_prec (&format);
1309
1310             out_count += MAX (width, prec);
1311           }
1312           get_format_conv_type (&format);
1313         }
1314     }
1315
1316   if (! percent)
1317     error (EXIT_FAILURE, 0,
1318            _("missing %% conversion specification in suffix"));
1319
1320   return out_count;
1321 }
1322
1323 int
1324 main (int argc, char **argv)
1325 {
1326   int optc;
1327   unsigned long int val;
1328
1329   initialize_main (&argc, &argv);
1330   set_program_name (argv[0]);
1331   setlocale (LC_ALL, "");
1332   bindtextdomain (PACKAGE, LOCALEDIR);
1333   textdomain (PACKAGE);
1334
1335   atexit (close_stdout);
1336
1337   global_argv = argv;
1338   controls = NULL;
1339   control_used = 0;
1340   suppress_count = false;
1341   remove_files = true;
1342   prefix = DEFAULT_PREFIX;
1343
1344   while ((optc = getopt_long (argc, argv, "f:b:kn:sqz", longopts, NULL)) != -1)
1345     switch (optc)
1346       {
1347       case 'f':
1348         prefix = optarg;
1349         break;
1350
1351       case 'b':
1352         suffix = optarg;
1353         break;
1354
1355       case 'k':
1356         remove_files = false;
1357         break;
1358
1359       case 'n':
1360         if (xstrtoul (optarg, NULL, 10, &val, "") != LONGINT_OK
1361             || val > INT_MAX)
1362           error (EXIT_FAILURE, 0, _("%s: invalid number"), optarg);
1363         digits = val;
1364         break;
1365
1366       case 's':
1367       case 'q':
1368         suppress_count = true;
1369         break;
1370
1371       case 'z':
1372         elide_empty_files = true;
1373         break;
1374
1375       case_GETOPT_HELP_CHAR;
1376
1377       case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1378
1379       default:
1380         usage (EXIT_FAILURE);
1381       }
1382
1383   if (argc - optind < 2)
1384     {
1385       if (argc <= optind)
1386         error (0, 0, _("missing operand"));
1387       else
1388         error (0, 0, _("missing operand after %s"), quote (argv[argc - 1]));
1389       usage (EXIT_FAILURE);
1390     }
1391
1392   if (suffix)
1393     filename_space = xmalloc (strlen (prefix) + max_out (suffix) + 2);
1394   else
1395     filename_space = xmalloc (strlen (prefix) + digits + 2);
1396
1397   set_input_file (argv[optind++]);
1398
1399   parse_patterns (argc, optind, argv);
1400
1401   {
1402     int i;
1403     static int const sig[] =
1404       {
1405         /* The usual suspects.  */
1406         SIGALRM, SIGHUP, SIGINT, SIGPIPE, SIGQUIT, SIGTERM,
1407 #ifdef SIGPOLL
1408         SIGPOLL,
1409 #endif
1410 #ifdef SIGPROF
1411         SIGPROF,
1412 #endif
1413 #ifdef SIGVTALRM
1414         SIGVTALRM,
1415 #endif
1416 #ifdef SIGXCPU
1417         SIGXCPU,
1418 #endif
1419 #ifdef SIGXFSZ
1420         SIGXFSZ,
1421 #endif
1422       };
1423     enum { nsigs = sizeof sig / sizeof sig[0] };
1424
1425 #if SA_NOCLDSTOP
1426     struct sigaction act;
1427
1428     sigemptyset (&caught_signals);
1429     for (i = 0; i < nsigs; i++)
1430       {
1431         sigaction (sig[i], NULL, &act);
1432         if (act.sa_handler != SIG_IGN)
1433           sigaddset (&caught_signals, sig[i]);
1434       }
1435
1436     act.sa_handler = interrupt_handler;
1437     act.sa_mask = caught_signals;
1438     act.sa_flags = 0;
1439
1440     for (i = 0; i < nsigs; i++)
1441       if (sigismember (&caught_signals, sig[i]))
1442         sigaction (sig[i], &act, NULL);
1443 #else
1444     for (i = 0; i < nsigs; i++)
1445       if (signal (sig[i], SIG_IGN) != SIG_IGN)
1446         {
1447           signal (sig[i], interrupt_handler);
1448           siginterrupt (sig[i], 1);
1449         }
1450 #endif
1451   }
1452
1453   split_file ();
1454
1455   if (close (STDIN_FILENO) != 0)
1456     {
1457       error (0, errno, _("read error"));
1458       cleanup_fatal ();
1459     }
1460
1461   exit (EXIT_SUCCESS);
1462 }
1463
1464 void
1465 usage (int status)
1466 {
1467   if (status != EXIT_SUCCESS)
1468     fprintf (stderr, _("Try `%s --help' for more information.\n"),
1469              program_name);
1470   else
1471     {
1472       printf (_("\
1473 Usage: %s [OPTION]... FILE PATTERN...\n\
1474 "),
1475               program_name);
1476       fputs (_("\
1477 Output pieces of FILE separated by PATTERN(s) to files `xx00', `xx01', ...,\n\
1478 and output byte counts of each piece to standard output.\n\
1479 \n\
1480 "), stdout);
1481       fputs (_("\
1482 Mandatory arguments to long options are mandatory for short options too.\n\
1483 "), stdout);
1484       fputs (_("\
1485   -b, --suffix-format=FORMAT  use sprintf FORMAT instead of %02d\n\
1486   -f, --prefix=PREFIX        use PREFIX instead of `xx'\n\
1487   -k, --keep-files           do not remove output files on errors\n\
1488 "), stdout);
1489       fputs (_("\
1490   -n, --digits=DIGITS        use specified number of digits instead of 2\n\
1491   -s, --quiet, --silent      do not print counts of output file sizes\n\
1492   -z, --elide-empty-files    remove empty output files\n\
1493 "), stdout);
1494       fputs (HELP_OPTION_DESCRIPTION, stdout);
1495       fputs (VERSION_OPTION_DESCRIPTION, stdout);
1496       fputs (_("\
1497 \n\
1498 Read standard input if FILE is -.  Each PATTERN may be:\n\
1499 "), stdout);
1500       fputs (_("\
1501 \n\
1502   INTEGER            copy up to but not including specified line number\n\
1503   /REGEXP/[OFFSET]   copy up to but not including a matching line\n\
1504   %REGEXP%[OFFSET]   skip to, but not including a matching line\n\
1505   {INTEGER}          repeat the previous pattern specified number of times\n\
1506   {*}                repeat the previous pattern as many times as possible\n\
1507 \n\
1508 A line OFFSET is a required `+' or `-' followed by a positive integer.\n\
1509 "), stdout);
1510       emit_bug_reporting_address ();
1511     }
1512   exit (status);
1513 }