(extract_regexp): Set re_syntax_options to a
[platform/upstream/coreutils.git] / src / csplit.c
1 /* csplit - split a file into sections determined by context lines
2    Copyright (C) 91, 1995-2006 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 Foundation,
16    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
17
18 /* Written by Stuart Kemp, cpsrk@groper.jcu.edu.au.
19    Modified by David MacKenzie, djm@gnu.ai.mit.edu. */
20
21 #include <config.h>
22
23 #include <getopt.h>
24 #include <sys/types.h>
25 #include <signal.h>
26
27 #include "system.h"
28
29 #include <regex.h>
30
31 #include "error.h"
32 #include "fd-reopen.h"
33 #include "inttostr.h"
34 #include "quote.h"
35 #include "safe-read.h"
36 #include "stdio--.h"
37 #include "xstrtol.h"
38
39 /* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is
40    present.  */
41 #ifndef SA_NOCLDSTOP
42 # define SA_NOCLDSTOP 0
43 # define sigprocmask(How, Set, Oset) /* empty */
44 # define sigset_t int
45 # if ! HAVE_SIGINTERRUPT
46 #  define siginterrupt(sig, flag) /* empty */
47 # endif
48 #endif
49
50 /* The official name of this program (e.g., no `g' prefix).  */
51 #define PROGRAM_NAME "csplit"
52
53 #define AUTHORS "Stuart Kemp", "David MacKenzie"
54
55 /* Increment size of area for control records. */
56 #define ALLOC_SIZE 20
57
58 /* The default prefix for output file names. */
59 #define DEFAULT_PREFIX  "xx"
60
61 /* A compiled pattern arg. */
62 struct control
63 {
64   intmax_t offset;              /* Offset from regexp to split at. */
65   uintmax_t lines_required;     /* Number of lines required. */
66   uintmax_t repeat;             /* Repeat count. */
67   int argnum;                   /* ARGV index. */
68   bool repeat_forever;          /* True if `*' used as a repeat count. */
69   bool ignore;                  /* If true, produce no output (for regexp). */
70   bool regexpr;                 /* True if regular expression was used. */
71   struct re_pattern_buffer re_compiled; /* Compiled regular expression. */
72   char fastmap[UCHAR_MAX + 1];  /* Fastmap for RE_COMPILED.  */
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 /* The name this program was run with. */
132 char *program_name;
133
134 /* Start of buffer list. */
135 static struct buffer_record *head = NULL;
136
137 /* Partially read line. */
138 static char *hold_area = NULL;
139
140 /* Number of bytes in `hold_area'. */
141 static size_t hold_count = 0;
142
143 /* Number of the last line in the buffers. */
144 static uintmax_t last_line_number = 0;
145
146 /* Number of the line currently being examined. */
147 static uintmax_t current_line = 0;
148
149 /* If true, we have read EOF. */
150 static bool have_read_eof = false;
151
152 /* Name of output files. */
153 static char * volatile filename_space = NULL;
154
155 /* Prefix part of output file names. */
156 static char * volatile prefix = NULL;
157
158 /* Suffix part of output file names. */
159 static char * volatile suffix = NULL;
160
161 /* Number of digits to use in output file names. */
162 static int volatile digits = 2;
163
164 /* Number of files created so far. */
165 static unsigned int volatile files_created = 0;
166
167 /* Number of bytes written to current file. */
168 static uintmax_t bytes_written;
169
170 /* Output file pointer. */
171 static FILE *output_stream = NULL;
172
173 /* Output file name. */
174 static char *output_filename = NULL;
175
176 /* Perhaps it would be cleaner to pass arg values instead of indexes. */
177 static char **global_argv;
178
179 /* If true, do not print the count of bytes in each output file. */
180 static bool suppress_count;
181
182 /* If true, remove output files on error. */
183 static bool volatile remove_files;
184
185 /* If true, remove all output files which have a zero length. */
186 static bool elide_empty_files;
187
188 /* The compiled pattern arguments, which determine how to split
189    the input file. */
190 static struct control *controls;
191
192 /* Number of elements in `controls'. */
193 static size_t control_used;
194
195 /* The set of signals that are caught.  */
196 static sigset_t caught_signals;
197
198 static struct option const longopts[] =
199 {
200   {"digits", required_argument, NULL, 'n'},
201   {"quiet", no_argument, NULL, 'q'},
202   {"silent", no_argument, NULL, 's'},
203   {"keep-files", no_argument, NULL, 'k'},
204   {"elide-empty-files", no_argument, NULL, 'z'},
205   {"prefix", required_argument, NULL, 'f'},
206   {"suffix-format", required_argument, NULL, 'b'},
207   {GETOPT_HELP_OPTION_DECL},
208   {GETOPT_VERSION_OPTION_DECL},
209   {NULL, 0, NULL, 0}
210 };
211
212 /* Optionally remove files created so far; then exit.
213    Called when an error detected. */
214
215 static void
216 cleanup (void)
217 {
218   sigset_t oldset;
219
220   close_output_file ();
221
222   sigprocmask (SIG_BLOCK, &caught_signals, &oldset);
223   delete_all_files (false);
224   sigprocmask (SIG_SETMASK, &oldset, NULL);
225 }
226
227 static void cleanup_fatal (void) ATTRIBUTE_NORETURN;
228 static void
229 cleanup_fatal (void)
230 {
231   cleanup ();
232   exit (EXIT_FAILURE);
233 }
234
235 extern void
236 xalloc_die (void)
237 {
238   error (0, 0, "%s", _("memory exhausted"));
239   cleanup_fatal ();
240 }
241
242 static void
243 interrupt_handler (int sig)
244 {
245   if (! SA_NOCLDSTOP)
246     signal (sig, SIG_IGN);
247
248   delete_all_files (true);
249
250   signal (sig, SIG_DFL);
251   raise (sig);
252 }
253
254 /* Keep track of NUM bytes of a partial line in buffer START.
255    These bytes will be retrieved later when another large buffer is read.  */
256
257 static void
258 save_to_hold_area (char *start, size_t num)
259 {
260   free (hold_area);
261   hold_area = start;
262   hold_count = num;
263 }
264
265 /* Read up to MAX_N_BYTES bytes from the input stream into DEST.
266    Return the number of bytes read. */
267
268 static size_t
269 read_input (char *dest, size_t max_n_bytes)
270 {
271   size_t bytes_read;
272
273   if (max_n_bytes == 0)
274     return 0;
275
276   bytes_read = safe_read (STDIN_FILENO, dest, max_n_bytes);
277
278   if (bytes_read == 0)
279     have_read_eof = true;
280
281   if (bytes_read == SAFE_READ_ERROR)
282     {
283       error (0, errno, _("read error"));
284       cleanup_fatal ();
285     }
286
287   return bytes_read;
288 }
289
290 /* Initialize existing line record P. */
291
292 static void
293 clear_line_control (struct line *p)
294 {
295   p->used = 0;
296   p->insert_index = 0;
297   p->retrieve_index = 0;
298 }
299
300 /* Return a new, initialized line record. */
301
302 static struct line *
303 new_line_control (void)
304 {
305   struct line *p = xmalloc (sizeof *p);
306
307   p->next = NULL;
308   clear_line_control (p);
309
310   return p;
311 }
312
313 /* Record LINE_START, which is the address of the start of a line
314    of length LINE_LEN in the large buffer, in the lines buffer of B. */
315
316 static void
317 keep_new_line (struct buffer_record *b, char *line_start, size_t line_len)
318 {
319   struct line *l;
320
321   /* If there is no existing area to keep line info, get some. */
322   if (b->line_start == NULL)
323     b->line_start = b->curr_line = new_line_control ();
324
325   /* If existing area for lines is full, get more. */
326   if (b->curr_line->used == CTRL_SIZE)
327     {
328       b->curr_line->next = new_line_control ();
329       b->curr_line = b->curr_line->next;
330     }
331
332   l = b->curr_line;
333
334   /* Record the start of the line, and update counters. */
335   l->starts[l->insert_index].str = line_start;
336   l->starts[l->insert_index].len = line_len;
337   l->used++;
338   l->insert_index++;
339 }
340
341 /* Scan the buffer in B for newline characters
342    and record the line start locations and lengths in B.
343    Return the number of lines found in this buffer.
344
345    There may be an incomplete line at the end of the buffer;
346    a pointer is kept to this area, which will be used when
347    the next buffer is filled. */
348
349 static size_t
350 record_line_starts (struct buffer_record *b)
351 {
352   char *line_start;             /* Start of current line. */
353   char *line_end;               /* End of each line found. */
354   size_t bytes_left;            /* Length of incomplete last line. */
355   size_t lines;                 /* Number of lines found. */
356   size_t line_length;           /* Length of each line found. */
357
358   if (b->bytes_used == 0)
359     return 0;
360
361   lines = 0;
362   line_start = b->buffer;
363   bytes_left = b->bytes_used;
364
365   for (;;)
366     {
367       line_end = memchr (line_start, '\n', bytes_left);
368       if (line_end == NULL)
369         break;
370       line_length = line_end - line_start + 1;
371       keep_new_line (b, line_start, line_length);
372       bytes_left -= line_length;
373       line_start = line_end + 1;
374       lines++;
375     }
376
377   /* Check for an incomplete last line. */
378   if (bytes_left)
379     {
380       if (have_read_eof)
381         {
382           keep_new_line (b, line_start, bytes_left);
383           lines++;
384         }
385       else
386         save_to_hold_area (xmemdup (line_start, bytes_left), bytes_left);
387     }
388
389   b->num_lines = lines;
390   b->first_available = b->start_line = last_line_number + 1;
391   last_line_number += lines;
392
393   return lines;
394 }
395
396 /* Return a new buffer with room to store SIZE bytes, plus
397    an extra byte for safety. */
398
399 static struct buffer_record *
400 create_new_buffer (size_t size)
401 {
402   struct buffer_record *new_buffer = xmalloc (sizeof *new_buffer);
403
404   new_buffer->buffer = xmalloc (size + 1);
405
406   new_buffer->bytes_alloc = size;
407   new_buffer->line_start = new_buffer->curr_line = NULL;
408
409   return new_buffer;
410 }
411
412 /* Return a new buffer of at least MINSIZE bytes.  If a buffer of at
413    least that size is currently free, use it, otherwise create a new one. */
414
415 static struct buffer_record *
416 get_new_buffer (size_t min_size)
417 {
418   struct buffer_record *new_buffer; /* Buffer to return. */
419   size_t alloc_size;    /* Actual size that will be requested. */
420
421   alloc_size = START_SIZE;
422   if (alloc_size < min_size)
423     {
424       size_t s = min_size - alloc_size + INCR_SIZE - 1;
425       alloc_size += s - s % INCR_SIZE;
426     }
427
428   new_buffer = create_new_buffer (alloc_size);
429
430   new_buffer->num_lines = 0;
431   new_buffer->bytes_used = 0;
432   new_buffer->start_line = new_buffer->first_available = last_line_number + 1;
433   new_buffer->next = NULL;
434
435   return new_buffer;
436 }
437
438 static void
439 free_buffer (struct buffer_record *buf)
440 {
441   free (buf->buffer);
442   buf->buffer = NULL;
443 }
444
445 /* Append buffer BUF to the linked list of buffers that contain
446    some data yet to be processed. */
447
448 static void
449 save_buffer (struct buffer_record *buf)
450 {
451   struct buffer_record *p;
452
453   buf->next = NULL;
454   buf->curr_line = buf->line_start;
455
456   if (head == NULL)
457     head = buf;
458   else
459     {
460       for (p = head; p->next; p = p->next)
461         /* Do nothing. */ ;
462       p->next = buf;
463     }
464 }
465
466 /* Fill a buffer of input.
467
468    Set the initial size of the buffer to a default.
469    Fill the buffer (from the hold area and input stream)
470    and find the individual lines.
471    If no lines are found (the buffer is too small to hold the next line),
472    release the current buffer (whose contents would have been put in the
473    hold area) and repeat the process with another large buffer until at least
474    one entire line has been read.
475
476    Return true if a new buffer was obtained, otherwise false
477    (in which case end-of-file must have been encountered). */
478
479 static bool
480 load_buffer (void)
481 {
482   struct buffer_record *b;
483   size_t bytes_wanted = START_SIZE; /* Minimum buffer size. */
484   size_t bytes_avail;           /* Size of new buffer created. */
485   size_t lines_found;           /* Number of lines in this new buffer. */
486   char *p;                      /* Place to load into buffer. */
487
488   if (have_read_eof)
489     return false;
490
491   /* We must make the buffer at least as large as the amount of data
492      in the partial line left over from the last call. */
493   if (bytes_wanted < hold_count)
494     bytes_wanted = hold_count;
495
496   while (1)
497     {
498       b = get_new_buffer (bytes_wanted);
499       bytes_avail = b->bytes_alloc; /* Size of buffer returned. */
500       p = b->buffer;
501
502       /* First check the `holding' area for a partial line. */
503       if (hold_count)
504         {
505           memcpy (p, hold_area, hold_count);
506           p += hold_count;
507           b->bytes_used += hold_count;
508           bytes_avail -= hold_count;
509           hold_count = 0;
510         }
511
512       b->bytes_used += read_input (p, bytes_avail);
513
514       lines_found = record_line_starts (b);
515       if (!lines_found)
516         free_buffer (b);
517
518       if (lines_found || have_read_eof)
519         break;
520
521       if (xalloc_oversized (2, b->bytes_alloc))
522         xalloc_die ();
523       bytes_wanted = 2 * b->bytes_alloc;
524       free_buffer (b);
525       free (b);
526     }
527
528   if (lines_found)
529     save_buffer (b);
530
531   return lines_found != 0;
532 }
533
534 /* Return the line number of the first line that has not yet been retrieved. */
535
536 static uintmax_t
537 get_first_line_in_buffer (void)
538 {
539   if (head == NULL && !load_buffer ())
540     error (EXIT_FAILURE, errno, _("input disappeared"));
541
542   return head->first_available;
543 }
544
545 /* Return a pointer to the logical first line in the buffer and make the
546    next line the logical first line.
547    Return NULL if there is no more input. */
548
549 static struct cstring *
550 remove_line (void)
551 {
552   /* If non-NULL, this is the buffer for which the previous call
553      returned the final line.  So now, presuming that line has been
554      processed, we can free the buffer and reset this pointer.  */
555   static struct buffer_record *prev_buf = NULL;
556
557   struct cstring *line;         /* Return value. */
558   struct line *l;               /* For convenience. */
559
560   if (prev_buf)
561     {
562       free_buffer (prev_buf);
563       prev_buf = NULL;
564     }
565
566   if (head == NULL && !load_buffer ())
567     return NULL;
568
569   if (current_line < head->first_available)
570     current_line = head->first_available;
571
572   ++(head->first_available);
573
574   l = head->curr_line;
575
576   line = &l->starts[l->retrieve_index];
577
578   /* Advance index to next line. */
579   if (++l->retrieve_index == l->used)
580     {
581       /* Go on to the next line record. */
582       head->curr_line = l->next;
583       if (head->curr_line == NULL || head->curr_line->used == 0)
584         {
585           /* Go on to the next data block.
586              but first record the current one so we can free it
587              once the line we're returning has been processed.  */
588           prev_buf = head;
589           head = head->next;
590         }
591     }
592
593   return line;
594 }
595
596 /* Search the buffers for line LINENUM, reading more input if necessary.
597    Return a pointer to the line, or NULL if it is not found in the file. */
598
599 static struct cstring *
600 find_line (uintmax_t linenum)
601 {
602   struct buffer_record *b;
603
604   if (head == NULL && !load_buffer ())
605     return NULL;
606
607   if (linenum < head->start_line)
608     return NULL;
609
610   for (b = head;;)
611     {
612       if (linenum < b->start_line + b->num_lines)
613         {
614           /* The line is in this buffer. */
615           struct line *l;
616           size_t offset;        /* How far into the buffer the line is. */
617
618           l = b->line_start;
619           offset = linenum - b->start_line;
620           /* Find the control record. */
621           while (offset >= CTRL_SIZE)
622             {
623               l = l->next;
624               offset -= CTRL_SIZE;
625             }
626           return &l->starts[offset];
627         }
628       if (b->next == NULL && !load_buffer ())
629         return NULL;
630       b = b->next;              /* Try the next data block. */
631     }
632 }
633
634 /* Return true if at least one more line is available for input. */
635
636 static bool
637 no_more_lines (void)
638 {
639   return find_line (current_line + 1) == NULL;
640 }
641
642 /* Open NAME as standard input.  */
643
644 static void
645 set_input_file (const char *name)
646 {
647   if (! STREQ (name, "-") && fd_reopen (STDIN_FILENO, name, O_RDONLY, 0) < 0)
648     error (EXIT_FAILURE, errno, _("cannot open %s for reading"), quote (name));
649 }
650
651 /* Write all lines from the beginning of the buffer up to, but
652    not including, line LAST_LINE, to the current output file.
653    If IGNORE is true, do not output lines selected here.
654    ARGNUM is the index in ARGV of the current pattern. */
655
656 static void
657 write_to_file (uintmax_t last_line, bool ignore, int argnum)
658 {
659   struct cstring *line;
660   uintmax_t first_line;         /* First available input line. */
661   uintmax_t lines;              /* Number of lines to output. */
662   uintmax_t i;
663
664   first_line = get_first_line_in_buffer ();
665
666   if (first_line > last_line)
667     {
668       error (0, 0, _("%s: line number out of range"), global_argv[argnum]);
669       cleanup_fatal ();
670     }
671
672   lines = last_line - first_line;
673
674   for (i = 0; i < lines; i++)
675     {
676       line = remove_line ();
677       if (line == NULL)
678         {
679           error (0, 0, _("%s: line number out of range"), global_argv[argnum]);
680           cleanup_fatal ();
681         }
682       if (!ignore)
683         save_line_to_file (line);
684     }
685 }
686
687 /* Output any lines left after all regexps have been processed. */
688
689 static void
690 dump_rest_of_file (void)
691 {
692   struct cstring *line;
693
694   while ((line = remove_line ()) != NULL)
695     save_line_to_file (line);
696 }
697
698 /* Handle an attempt to read beyond EOF under the control of record P,
699    on iteration REPETITION if nonzero. */
700
701 static void handle_line_error (const struct control *, uintmax_t)
702      ATTRIBUTE_NORETURN;
703 static void
704 handle_line_error (const struct control *p, uintmax_t repetition)
705 {
706   char buf[INT_BUFSIZE_BOUND (uintmax_t)];
707
708   fprintf (stderr, _("%s: %s: line number out of range"),
709            program_name, quote (umaxtostr (p->lines_required, buf)));
710   if (repetition)
711     fprintf (stderr, _(" on repetition %s\n"), umaxtostr (repetition, buf));
712   else
713     fprintf (stderr, "\n");
714
715   cleanup_fatal ();
716 }
717
718 /* Determine the line number that marks the end of this file,
719    then get those lines and save them to the output file.
720    P is the control record.
721    REPETITION is the repetition number. */
722
723 static void
724 process_line_count (const struct control *p, uintmax_t repetition)
725 {
726   uintmax_t linenum;
727   uintmax_t last_line_to_save = p->lines_required * (repetition + 1);
728   struct cstring *line;
729
730   create_output_file ();
731
732   linenum = get_first_line_in_buffer ();
733
734   while (linenum++ < last_line_to_save)
735     {
736       line = remove_line ();
737       if (line == NULL)
738         handle_line_error (p, repetition);
739       save_line_to_file (line);
740     }
741
742   close_output_file ();
743
744   /* Ensure that the line number specified is not 1 greater than
745      the number of lines in the file. */
746   if (no_more_lines ())
747     handle_line_error (p, repetition);
748 }
749
750 static void regexp_error (struct control *, uintmax_t, bool) ATTRIBUTE_NORETURN;
751 static void
752 regexp_error (struct control *p, uintmax_t repetition, bool ignore)
753 {
754   fprintf (stderr, _("%s: %s: match not found"),
755            program_name, quote (global_argv[p->argnum]));
756
757   if (repetition)
758     {
759       char buf[INT_BUFSIZE_BOUND (uintmax_t)];
760       fprintf (stderr, _(" on repetition %s\n"), umaxtostr (repetition, buf));
761     }
762   else
763     fprintf (stderr, "\n");
764
765   if (!ignore)
766     {
767       dump_rest_of_file ();
768       close_output_file ();
769     }
770   cleanup_fatal ();
771 }
772
773 /* Read the input until a line matches the regexp in P, outputting
774    it unless P->IGNORE is true.
775    REPETITION is this repeat-count; 0 means the first time. */
776
777 static void
778 process_regexp (struct control *p, uintmax_t repetition)
779 {
780   struct cstring *line;         /* From input file. */
781   size_t line_len;              /* To make "$" in regexps work. */
782   uintmax_t break_line;         /* First line number of next file. */
783   bool ignore = p->ignore;      /* If true, skip this section. */
784   regoff_t ret;
785
786   if (!ignore)
787     create_output_file ();
788
789   /* If there is no offset for the regular expression, or
790      it is positive, then it is not necessary to buffer the lines. */
791
792   if (p->offset >= 0)
793     {
794       for (;;)
795         {
796           line = find_line (++current_line);
797           if (line == NULL)
798             {
799               if (p->repeat_forever)
800                 {
801                   if (!ignore)
802                     {
803                       dump_rest_of_file ();
804                       close_output_file ();
805                     }
806                   exit (EXIT_SUCCESS);
807                 }
808               else
809                 regexp_error (p, repetition, ignore);
810             }
811           line_len = line->len;
812           if (line->str[line_len - 1] == '\n')
813             line_len--;
814           ret = re_search (&p->re_compiled, line->str, line_len,
815                            0, line_len, NULL);
816           if (ret == -2)
817             {
818               error (0, 0, _("error in regular expression search"));
819               cleanup_fatal ();
820             }
821           if (ret == -1)
822             {
823               line = remove_line ();
824               if (!ignore)
825                 save_line_to_file (line);
826             }
827           else
828             break;
829         }
830     }
831   else
832     {
833       /* Buffer the lines. */
834       for (;;)
835         {
836           line = find_line (++current_line);
837           if (line == NULL)
838             {
839               if (p->repeat_forever)
840                 {
841                   if (!ignore)
842                     {
843                       dump_rest_of_file ();
844                       close_output_file ();
845                     }
846                   exit (EXIT_SUCCESS);
847                 }
848               else
849                 regexp_error (p, repetition, ignore);
850             }
851           line_len = line->len;
852           if (line->str[line_len - 1] == '\n')
853             line_len--;
854           ret = re_search (&p->re_compiled, line->str, line_len,
855                            0, line_len, NULL);
856           if (ret == -2)
857             {
858               error (0, 0, _("error in regular expression search"));
859               cleanup_fatal ();
860             }
861           if (ret != -1)
862             break;
863         }
864     }
865
866   /* Account for any offset from this regexp. */
867   break_line = current_line + p->offset;
868
869   write_to_file (break_line, ignore, p->argnum);
870
871   if (!ignore)
872     close_output_file ();
873
874   if (p->offset > 0)
875     current_line = break_line;
876 }
877
878 /* Split the input file according to the control records we have built. */
879
880 static void
881 split_file (void)
882 {
883   size_t i;
884
885   for (i = 0; i < control_used; i++)
886     {
887       uintmax_t j;
888       if (controls[i].regexpr)
889         {
890           for (j = 0; (controls[i].repeat_forever
891                        || j <= controls[i].repeat); j++)
892             process_regexp (&controls[i], j);
893         }
894       else
895         {
896           for (j = 0; (controls[i].repeat_forever
897                        || j <= controls[i].repeat); j++)
898             process_line_count (&controls[i], j);
899         }
900     }
901
902   create_output_file ();
903   dump_rest_of_file ();
904   close_output_file ();
905 }
906
907 /* Return the name of output file number NUM.
908
909    This function is called from a signal handler, so it should invoke
910    only reentrant functions that are async-signal-safe.  POSIX does
911    not guarantee this for the functions called below, but we don't
912    know of any hosts where this implementation isn't safe.  */
913
914 static char *
915 make_filename (unsigned int num)
916 {
917   strcpy (filename_space, prefix);
918   if (suffix)
919     sprintf (filename_space + strlen (prefix), suffix, num);
920   else
921     sprintf (filename_space + strlen (prefix), "%0*u", digits, num);
922   return filename_space;
923 }
924
925 /* Create the next output file. */
926
927 static void
928 create_output_file (void)
929 {
930   sigset_t oldset;
931   bool fopen_ok;
932   int fopen_errno;
933
934   output_filename = make_filename (files_created);
935
936   /* Create the output file in a critical section, to avoid races.  */
937   sigprocmask (SIG_BLOCK, &caught_signals, &oldset);
938   output_stream = fopen (output_filename, "w");
939   fopen_ok = (output_stream != NULL);
940   fopen_errno = errno;
941   files_created += fopen_ok;
942   sigprocmask (SIG_SETMASK, &oldset, NULL);
943
944   if (! fopen_ok)
945     {
946       error (0, fopen_errno, "%s", output_filename);
947       cleanup_fatal ();
948     }
949   bytes_written = 0;
950 }
951
952 /* If requested, delete all the files we have created.  This function
953    must be called only from critical sections.  */
954
955 static void
956 delete_all_files (bool in_signal_handler)
957 {
958   unsigned int i;
959
960   if (! remove_files)
961     return;
962
963   for (i = 0; i < files_created; i++)
964     {
965       const char *name = make_filename (i);
966       if (unlink (name) != 0 && !in_signal_handler)
967         error (0, errno, "%s", name);
968     }
969
970   files_created = 0;
971 }
972
973 /* Close the current output file and print the count
974    of characters in this file. */
975
976 static void
977 close_output_file (void)
978 {
979   if (output_stream)
980     {
981       if (ferror (output_stream))
982         {
983           error (0, 0, _("write error for %s"), quote (output_filename));
984           output_stream = NULL;
985           cleanup_fatal ();
986         }
987       if (fclose (output_stream) != 0)
988         {
989           error (0, errno, "%s", output_filename);
990           output_stream = NULL;
991           cleanup_fatal ();
992         }
993       if (bytes_written == 0 && elide_empty_files)
994         {
995           sigset_t oldset;
996           bool unlink_ok;
997           int unlink_errno;
998
999           /* Remove the output file in a critical section, to avoid races.  */
1000           sigprocmask (SIG_BLOCK, &caught_signals, &oldset);
1001           unlink_ok = (unlink (output_filename) == 0);
1002           unlink_errno = errno;
1003           files_created -= unlink_ok;
1004           sigprocmask (SIG_SETMASK, &oldset, NULL);
1005
1006           if (! unlink_ok)
1007             error (0, unlink_errno, "%s", output_filename);
1008         }
1009       else
1010         {
1011           if (!suppress_count)
1012             {
1013               char buf[INT_BUFSIZE_BOUND (uintmax_t)];
1014               fprintf (stdout, "%s\n", umaxtostr (bytes_written, buf));
1015             }
1016         }
1017       output_stream = NULL;
1018     }
1019 }
1020
1021 /* Save line LINE to the output file and
1022    increment the character count for the current file. */
1023
1024 static void
1025 save_line_to_file (const struct cstring *line)
1026 {
1027   fwrite (line->str, sizeof (char), line->len, output_stream);
1028   bytes_written += line->len;
1029 }
1030
1031 /* Return a new, initialized control record. */
1032
1033 static struct control *
1034 new_control_record (void)
1035 {
1036   static size_t control_allocated = 0; /* Total space allocated. */
1037   struct control *p;
1038
1039   if (control_used == control_allocated)
1040     controls = X2NREALLOC (controls, &control_allocated);
1041   p = &controls[control_used++];
1042   p->regexpr = false;
1043   p->repeat = 0;
1044   p->repeat_forever = false;
1045   p->lines_required = 0;
1046   p->offset = 0;
1047   return p;
1048 }
1049
1050 /* Check if there is a numeric offset after a regular expression.
1051    STR is the entire command line argument.
1052    P is the control record for this regular expression.
1053    NUM is the numeric part of STR. */
1054
1055 static void
1056 check_for_offset (struct control *p, const char *str, const char *num)
1057 {
1058   if (xstrtoimax (num, NULL, 10, &p->offset, "") != LONGINT_OK)
1059     error (EXIT_FAILURE, 0, _("%s: integer expected after delimiter"), str);
1060 }
1061
1062 /* Given that the first character of command line arg STR is '{',
1063    make sure that the rest of the string is a valid repeat count
1064    and store its value in P.
1065    ARGNUM is the ARGV index of STR. */
1066
1067 static void
1068 parse_repeat_count (int argnum, struct control *p, char *str)
1069 {
1070   uintmax_t val;
1071   char *end;
1072
1073   end = str + strlen (str) - 1;
1074   if (*end != '}')
1075     error (EXIT_FAILURE, 0, _("%s: `}' is required in repeat count"), str);
1076   *end = '\0';
1077
1078   if (str+1 == end-1 && *(str+1) == '*')
1079     p->repeat_forever = true;
1080   else
1081     {
1082       if (xstrtoumax (str + 1, NULL, 10, &val, "") != LONGINT_OK)
1083         {
1084           error (EXIT_FAILURE, 0,
1085                  _("%s}: integer required between `{' and `}'"),
1086                  global_argv[argnum]);
1087         }
1088       p->repeat = val;
1089     }
1090
1091   *end = '}';
1092 }
1093
1094 /* Extract the regular expression from STR and check for a numeric offset.
1095    STR should start with the regexp delimiter character.
1096    Return a new control record for the regular expression.
1097    ARGNUM is the ARGV index of STR.
1098    Unless IGNORE is true, mark these lines for output. */
1099
1100 static struct control *
1101 extract_regexp (int argnum, bool ignore, char const *str)
1102 {
1103   size_t len;                   /* Number of bytes in this regexp. */
1104   char delim = *str;
1105   char const *closing_delim;
1106   struct control *p;
1107   const char *err;
1108
1109   closing_delim = strrchr (str + 1, delim);
1110   if (closing_delim == NULL)
1111     error (EXIT_FAILURE, 0,
1112            _("%s: closing delimiter `%c' missing"), str, delim);
1113
1114   len = closing_delim - str - 1;
1115   p = new_control_record ();
1116   p->argnum = argnum;
1117   p->ignore = ignore;
1118
1119   p->regexpr = true;
1120   p->re_compiled.buffer = NULL;
1121   p->re_compiled.allocated = 0;
1122   p->re_compiled.fastmap = p->fastmap;
1123   p->re_compiled.translate = NULL;
1124   re_syntax_options = RE_SYNTAX_POSIX_BASIC & ~RE_CONTEXT_INVALID_DUP;
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   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[] = { SIGHUP, SIGINT, SIGQUIT, SIGTERM };
1404     enum { nsigs = sizeof sig / sizeof sig[0] };
1405
1406 #if SA_NOCLDSTOP
1407     struct sigaction act;
1408
1409     sigemptyset (&caught_signals);
1410     for (i = 0; i < nsigs; i++)
1411       {
1412         sigaction (sig[i], NULL, &act);
1413         if (act.sa_handler != SIG_IGN)
1414           sigaddset (&caught_signals, sig[i]);
1415       }
1416
1417     act.sa_handler = interrupt_handler;
1418     act.sa_mask = caught_signals;
1419     act.sa_flags = 0;
1420
1421     for (i = 0; i < nsigs; i++)
1422       if (sigismember (&caught_signals, sig[i]))
1423         sigaction (sig[i], &act, NULL);
1424 #else
1425     for (i = 0; i < nsigs; i++)
1426       if (signal (sig[i], SIG_IGN) != SIG_IGN)
1427         {
1428           signal (sig[i], interrupt_handler);
1429           siginterrupt (sig[i], 1);
1430         }
1431 #endif
1432   }
1433
1434   split_file ();
1435
1436   if (close (STDIN_FILENO) != 0)
1437     {
1438       error (0, errno, _("read error"));
1439       cleanup_fatal ();
1440     }
1441
1442   exit (EXIT_SUCCESS);
1443 }
1444
1445 void
1446 usage (int status)
1447 {
1448   if (status != EXIT_SUCCESS)
1449     fprintf (stderr, _("Try `%s --help' for more information.\n"),
1450              program_name);
1451   else
1452     {
1453       printf (_("\
1454 Usage: %s [OPTION]... FILE PATTERN...\n\
1455 "),
1456               program_name);
1457       fputs (_("\
1458 Output pieces of FILE separated by PATTERN(s) to files `xx00', `xx01', ...,\n\
1459 and output byte counts of each piece to standard output.\n\
1460 \n\
1461 "), stdout);
1462       fputs (_("\
1463 Mandatory arguments to long options are mandatory for short options too.\n\
1464 "), stdout);
1465       fputs (_("\
1466   -b, --suffix-format=FORMAT use sprintf FORMAT instead of %02d\n\
1467   -f, --prefix=PREFIX        use PREFIX instead of `xx'\n\
1468   -k, --keep-files           do not remove output files on errors\n\
1469 "), stdout);
1470       fputs (_("\
1471   -n, --digits=DIGITS        use specified number of digits instead of 2\n\
1472   -s, --quiet, --silent      do not print counts of output file sizes\n\
1473   -z, --elide-empty-files    remove empty output files\n\
1474 "), stdout);
1475       fputs (HELP_OPTION_DESCRIPTION, stdout);
1476       fputs (VERSION_OPTION_DESCRIPTION, stdout);
1477       fputs (_("\
1478 \n\
1479 Read standard input if FILE is -.  Each PATTERN may be:\n\
1480 "), stdout);
1481       fputs (_("\
1482 \n\
1483   INTEGER            copy up to but not including specified line number\n\
1484   /REGEXP/[OFFSET]   copy up to but not including a matching line\n\
1485   %REGEXP%[OFFSET]   skip to, but not including a matching line\n\
1486   {INTEGER}          repeat the previous pattern specified number of times\n\
1487   {*}                repeat the previous pattern as many times as possible\n\
1488 \n\
1489 A line OFFSET is a required `+' or `-' followed by a positive integer.\n\
1490 "), stdout);
1491       printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
1492     }
1493   exit (status);
1494 }