* src/dd.c (flags): noatime and nofollow now depend on
[platform/upstream/coreutils.git] / src / dd.c
1 /* dd -- convert a file while copying it.
2    Copyright (C) 85, 90, 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 Paul Rubin, David MacKenzie, and Stuart Kemp. */
19
20 #include <config.h>
21
22 #define SWAB_ALIGN_OFFSET 2
23
24 #include <sys/types.h>
25 #include <signal.h>
26 #include <getopt.h>
27
28 #include "system.h"
29 #include "error.h"
30 #include "fd-reopen.h"
31 #include "gethrxtime.h"
32 #include "getpagesize.h"
33 #include "human.h"
34 #include "long-options.h"
35 #include "quote.h"
36 #include "xstrtol.h"
37 #include "xtime.h"
38
39 static void process_signals (void);
40
41 /* The official name of this program (e.g., no `g' prefix).  */
42 #define PROGRAM_NAME "dd"
43
44 #define AUTHORS "Paul Rubin", "David MacKenzie", "Stuart Kemp"
45
46 /* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is
47    present.  SA_NODEFER and SA_RESETHAND are XSI extensions.  */
48 #ifndef SA_NOCLDSTOP
49 # define SA_NOCLDSTOP 0
50 # define sigprocmask(How, Set, Oset) /* empty */
51 # define sigset_t int
52 # if ! HAVE_SIGINTERRUPT
53 #  define siginterrupt(sig, flag) /* empty */
54 # endif
55 #endif
56 #ifndef SA_NODEFER
57 # define SA_NODEFER 0
58 #endif
59 #ifndef SA_RESETHAND
60 # define SA_RESETHAND 0
61 #endif
62
63 #ifndef SIGINFO
64 # define SIGINFO SIGUSR1
65 #endif
66
67 #if ! HAVE_FDATASYNC
68 # define fdatasync(fd) (errno = ENOSYS, -1)
69 #endif
70
71 #define max(a, b) ((a) > (b) ? (a) : (b))
72 #define output_char(c)                          \
73   do                                            \
74     {                                           \
75       obuf[oc++] = (c);                         \
76       if (oc >= output_blocksize)               \
77         write_output ();                        \
78     }                                           \
79   while (0)
80
81 /* Default input and output blocksize. */
82 #define DEFAULT_BLOCKSIZE 512
83
84 /* How many bytes to add to the input and output block sizes before invoking
85    malloc.  See dd_copy for details.  INPUT_BLOCK_SLOP must be no less than
86    OUTPUT_BLOCK_SLOP.  */
87 #define INPUT_BLOCK_SLOP (2 * SWAB_ALIGN_OFFSET + 2 * page_size - 1)
88 #define OUTPUT_BLOCK_SLOP (page_size - 1)
89
90 /* Maximum blocksize for the given SLOP.
91    Keep it smaller than SIZE_MAX - SLOP, so that we can
92    allocate buffers that size.  Keep it smaller than SSIZE_MAX, for
93    the benefit of system calls like "read".  And keep it smaller than
94    OFF_T_MAX, for the benefit of the large-offset seek code.  */
95 #define MAX_BLOCKSIZE(slop) MIN (SIZE_MAX - (slop), MIN (SSIZE_MAX, OFF_T_MAX))
96
97 /* Conversions bit masks. */
98 enum
99   {
100     C_ASCII = 01,
101
102     C_EBCDIC = 02,
103     C_IBM = 04,
104     C_BLOCK = 010,
105     C_UNBLOCK = 020,
106     C_LCASE = 040,
107     C_UCASE = 0100,
108     C_SWAB = 0200,
109     C_NOERROR = 0400,
110     C_NOTRUNC = 01000,
111     C_SYNC = 02000,
112
113     /* Use separate input and output buffers, and combine partial
114        input blocks. */
115     C_TWOBUFS = 04000,
116
117     C_NOCREAT = 010000,
118     C_EXCL = 020000,
119     C_FDATASYNC = 040000,
120     C_FSYNC = 0100000
121   };
122
123 /* Status bit masks.  */
124 enum
125   {
126     STATUS_NOXFER = 01
127   };
128
129 /* The name this program was run with. */
130 char *program_name;
131
132 /* The name of the input file, or NULL for the standard input. */
133 static char const *input_file = NULL;
134
135 /* The name of the output file, or NULL for the standard output. */
136 static char const *output_file = NULL;
137
138 /* The page size on this host.  */
139 static size_t page_size;
140
141 /* The number of bytes in which atomic reads are done. */
142 static size_t input_blocksize = 0;
143
144 /* The number of bytes in which atomic writes are done. */
145 static size_t output_blocksize = 0;
146
147 /* Conversion buffer size, in bytes.  0 prevents conversions. */
148 static size_t conversion_blocksize = 0;
149
150 /* Skip this many records of `input_blocksize' bytes before input. */
151 static uintmax_t skip_records = 0;
152
153 /* Skip this many records of `output_blocksize' bytes before output. */
154 static uintmax_t seek_records = 0;
155
156 /* Copy only this many records.  The default is effectively infinity.  */
157 static uintmax_t max_records = (uintmax_t) -1;
158
159 /* Bit vector of conversions to apply. */
160 static int conversions_mask = 0;
161
162 /* Open flags for the input and output files.  */
163 static int input_flags = 0;
164 static int output_flags = 0;
165
166 /* Status flags for what is printed to stderr.  */
167 static int status_flags = 0;
168
169 /* If nonzero, filter characters through the translation table.  */
170 static bool translation_needed = false;
171
172 /* Number of partial blocks written. */
173 static uintmax_t w_partial = 0;
174
175 /* Number of full blocks written. */
176 static uintmax_t w_full = 0;
177
178 /* Number of partial blocks read. */
179 static uintmax_t r_partial = 0;
180
181 /* Number of full blocks read. */
182 static uintmax_t r_full = 0;
183
184 /* Number of bytes written.  */
185 static uintmax_t w_bytes = 0;
186
187 /* Time that dd started.  */
188 static xtime_t start_time;
189
190 /* True if input is seekable.  */
191 static bool input_seekable;
192
193 /* Error number corresponding to initial attempt to lseek input.
194    If ESPIPE, do not issue any more diagnostics about it.  */
195 static int input_seek_errno;
196
197 /* File offset of the input, in bytes, along with a flag recording
198    whether it overflowed.  The offset is valid only if the input is
199    seekable and if the offset has not overflowed.  */
200 static uintmax_t input_offset;
201 static bool input_offset_overflow;
202
203 /* Records truncated by conv=block. */
204 static uintmax_t r_truncate = 0;
205
206 /* Output representation of newline and space characters.
207    They change if we're converting to EBCDIC.  */
208 static char newline_character = '\n';
209 static char space_character = ' ';
210
211 /* Output buffer. */
212 static char *obuf;
213
214 /* Current index into `obuf'. */
215 static size_t oc = 0;
216
217 /* Index into current line, for `conv=block' and `conv=unblock'.  */
218 static size_t col = 0;
219
220 /* The set of signals that are caught.  */
221 static sigset_t caught_signals;
222
223 /* If nonzero, the value of the pending fatal signal.  */
224 static sig_atomic_t volatile interrupt_signal;
225
226 /* A count of the number of pending info signals that have been received.  */
227 static sig_atomic_t volatile info_signal_count;
228
229 /* A longest symbol in the struct symbol_values tables below.  */
230 #define LONGEST_SYMBOL "fdatasync"
231
232 /* A symbol and the corresponding integer value.  */
233 struct symbol_value
234 {
235   char symbol[sizeof LONGEST_SYMBOL];
236   int value;
237 };
238
239 /* Conversion symbols, for conv="...".  */
240 static struct symbol_value const conversions[] =
241 {
242   {"ascii", C_ASCII | C_TWOBUFS},       /* EBCDIC to ASCII. */
243   {"ebcdic", C_EBCDIC | C_TWOBUFS},     /* ASCII to EBCDIC. */
244   {"ibm", C_IBM | C_TWOBUFS},   /* Slightly different ASCII to EBCDIC. */
245   {"block", C_BLOCK | C_TWOBUFS},       /* Variable to fixed length records. */
246   {"unblock", C_UNBLOCK | C_TWOBUFS},   /* Fixed to variable length records. */
247   {"lcase", C_LCASE | C_TWOBUFS},       /* Translate upper to lower case. */
248   {"ucase", C_UCASE | C_TWOBUFS},       /* Translate lower to upper case. */
249   {"swab", C_SWAB | C_TWOBUFS}, /* Swap bytes of input. */
250   {"noerror", C_NOERROR},       /* Ignore i/o errors. */
251   {"nocreat", C_NOCREAT},       /* Do not create output file.  */
252   {"excl", C_EXCL},             /* Fail if the output file already exists.  */
253   {"notrunc", C_NOTRUNC},       /* Do not truncate output file. */
254   {"sync", C_SYNC},             /* Pad input records to ibs with NULs. */
255   {"fdatasync", C_FDATASYNC},   /* Synchronize output data before finishing.  */
256   {"fsync", C_FSYNC},           /* Also synchronize output metadata.  */
257   {"", 0}
258 };
259
260 /* Flags, for iflag="..." and oflag="...".  */
261 static struct symbol_value const flags[] =
262 {
263   {"append",    O_APPEND},
264   {"binary",    O_BINARY},
265   {"direct",    O_DIRECT},
266   {"directory", O_DIRECTORY},
267   {"dsync",     O_DSYNC},
268   {"noatime",   HAVE_WORKING_O_NOATIME ? O_NOATIME : 0},
269   {"noctty",    O_NOCTTY},
270   {"nofollow",  HAVE_WORKING_O_NOFOLLOW ? O_NOFOLLOW : 0},
271   {"nolinks",   O_NOLINKS},
272   {"nonblock",  O_NONBLOCK},
273   {"sync",      O_SYNC},
274   {"text",      O_TEXT},
275   {"",          0}
276 };
277
278 /* Status, for status="...".  */
279 static struct symbol_value const statuses[] =
280 {
281   {"noxfer",    STATUS_NOXFER},
282   {"",          0}
283 };
284
285 /* Translation table formed by applying successive transformations. */
286 static unsigned char trans_table[256];
287
288 static char const ascii_to_ebcdic[] =
289 {
290   '\000', '\001', '\002', '\003', '\067', '\055', '\056', '\057',
291   '\026', '\005', '\045', '\013', '\014', '\015', '\016', '\017',
292   '\020', '\021', '\022', '\023', '\074', '\075', '\062', '\046',
293   '\030', '\031', '\077', '\047', '\034', '\035', '\036', '\037',
294   '\100', '\117', '\177', '\173', '\133', '\154', '\120', '\175',
295   '\115', '\135', '\134', '\116', '\153', '\140', '\113', '\141',
296   '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367',
297   '\370', '\371', '\172', '\136', '\114', '\176', '\156', '\157',
298   '\174', '\301', '\302', '\303', '\304', '\305', '\306', '\307',
299   '\310', '\311', '\321', '\322', '\323', '\324', '\325', '\326',
300   '\327', '\330', '\331', '\342', '\343', '\344', '\345', '\346',
301   '\347', '\350', '\351', '\112', '\340', '\132', '\137', '\155',
302   '\171', '\201', '\202', '\203', '\204', '\205', '\206', '\207',
303   '\210', '\211', '\221', '\222', '\223', '\224', '\225', '\226',
304   '\227', '\230', '\231', '\242', '\243', '\244', '\245', '\246',
305   '\247', '\250', '\251', '\300', '\152', '\320', '\241', '\007',
306   '\040', '\041', '\042', '\043', '\044', '\025', '\006', '\027',
307   '\050', '\051', '\052', '\053', '\054', '\011', '\012', '\033',
308   '\060', '\061', '\032', '\063', '\064', '\065', '\066', '\010',
309   '\070', '\071', '\072', '\073', '\004', '\024', '\076', '\341',
310   '\101', '\102', '\103', '\104', '\105', '\106', '\107', '\110',
311   '\111', '\121', '\122', '\123', '\124', '\125', '\126', '\127',
312   '\130', '\131', '\142', '\143', '\144', '\145', '\146', '\147',
313   '\150', '\151', '\160', '\161', '\162', '\163', '\164', '\165',
314   '\166', '\167', '\170', '\200', '\212', '\213', '\214', '\215',
315   '\216', '\217', '\220', '\232', '\233', '\234', '\235', '\236',
316   '\237', '\240', '\252', '\253', '\254', '\255', '\256', '\257',
317   '\260', '\261', '\262', '\263', '\264', '\265', '\266', '\267',
318   '\270', '\271', '\272', '\273', '\274', '\275', '\276', '\277',
319   '\312', '\313', '\314', '\315', '\316', '\317', '\332', '\333',
320   '\334', '\335', '\336', '\337', '\352', '\353', '\354', '\355',
321   '\356', '\357', '\372', '\373', '\374', '\375', '\376', '\377'
322 };
323
324 static char const ascii_to_ibm[] =
325 {
326   '\000', '\001', '\002', '\003', '\067', '\055', '\056', '\057',
327   '\026', '\005', '\045', '\013', '\014', '\015', '\016', '\017',
328   '\020', '\021', '\022', '\023', '\074', '\075', '\062', '\046',
329   '\030', '\031', '\077', '\047', '\034', '\035', '\036', '\037',
330   '\100', '\132', '\177', '\173', '\133', '\154', '\120', '\175',
331   '\115', '\135', '\134', '\116', '\153', '\140', '\113', '\141',
332   '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367',
333   '\370', '\371', '\172', '\136', '\114', '\176', '\156', '\157',
334   '\174', '\301', '\302', '\303', '\304', '\305', '\306', '\307',
335   '\310', '\311', '\321', '\322', '\323', '\324', '\325', '\326',
336   '\327', '\330', '\331', '\342', '\343', '\344', '\345', '\346',
337   '\347', '\350', '\351', '\255', '\340', '\275', '\137', '\155',
338   '\171', '\201', '\202', '\203', '\204', '\205', '\206', '\207',
339   '\210', '\211', '\221', '\222', '\223', '\224', '\225', '\226',
340   '\227', '\230', '\231', '\242', '\243', '\244', '\245', '\246',
341   '\247', '\250', '\251', '\300', '\117', '\320', '\241', '\007',
342   '\040', '\041', '\042', '\043', '\044', '\025', '\006', '\027',
343   '\050', '\051', '\052', '\053', '\054', '\011', '\012', '\033',
344   '\060', '\061', '\032', '\063', '\064', '\065', '\066', '\010',
345   '\070', '\071', '\072', '\073', '\004', '\024', '\076', '\341',
346   '\101', '\102', '\103', '\104', '\105', '\106', '\107', '\110',
347   '\111', '\121', '\122', '\123', '\124', '\125', '\126', '\127',
348   '\130', '\131', '\142', '\143', '\144', '\145', '\146', '\147',
349   '\150', '\151', '\160', '\161', '\162', '\163', '\164', '\165',
350   '\166', '\167', '\170', '\200', '\212', '\213', '\214', '\215',
351   '\216', '\217', '\220', '\232', '\233', '\234', '\235', '\236',
352   '\237', '\240', '\252', '\253', '\254', '\255', '\256', '\257',
353   '\260', '\261', '\262', '\263', '\264', '\265', '\266', '\267',
354   '\270', '\271', '\272', '\273', '\274', '\275', '\276', '\277',
355   '\312', '\313', '\314', '\315', '\316', '\317', '\332', '\333',
356   '\334', '\335', '\336', '\337', '\352', '\353', '\354', '\355',
357   '\356', '\357', '\372', '\373', '\374', '\375', '\376', '\377'
358 };
359
360 static char const ebcdic_to_ascii[] =
361 {
362   '\000', '\001', '\002', '\003', '\234', '\011', '\206', '\177',
363   '\227', '\215', '\216', '\013', '\014', '\015', '\016', '\017',
364   '\020', '\021', '\022', '\023', '\235', '\205', '\010', '\207',
365   '\030', '\031', '\222', '\217', '\034', '\035', '\036', '\037',
366   '\200', '\201', '\202', '\203', '\204', '\012', '\027', '\033',
367   '\210', '\211', '\212', '\213', '\214', '\005', '\006', '\007',
368   '\220', '\221', '\026', '\223', '\224', '\225', '\226', '\004',
369   '\230', '\231', '\232', '\233', '\024', '\025', '\236', '\032',
370   '\040', '\240', '\241', '\242', '\243', '\244', '\245', '\246',
371   '\247', '\250', '\133', '\056', '\074', '\050', '\053', '\041',
372   '\046', '\251', '\252', '\253', '\254', '\255', '\256', '\257',
373   '\260', '\261', '\135', '\044', '\052', '\051', '\073', '\136',
374   '\055', '\057', '\262', '\263', '\264', '\265', '\266', '\267',
375   '\270', '\271', '\174', '\054', '\045', '\137', '\076', '\077',
376   '\272', '\273', '\274', '\275', '\276', '\277', '\300', '\301',
377   '\302', '\140', '\072', '\043', '\100', '\047', '\075', '\042',
378   '\303', '\141', '\142', '\143', '\144', '\145', '\146', '\147',
379   '\150', '\151', '\304', '\305', '\306', '\307', '\310', '\311',
380   '\312', '\152', '\153', '\154', '\155', '\156', '\157', '\160',
381   '\161', '\162', '\313', '\314', '\315', '\316', '\317', '\320',
382   '\321', '\176', '\163', '\164', '\165', '\166', '\167', '\170',
383   '\171', '\172', '\322', '\323', '\324', '\325', '\326', '\327',
384   '\330', '\331', '\332', '\333', '\334', '\335', '\336', '\337',
385   '\340', '\341', '\342', '\343', '\344', '\345', '\346', '\347',
386   '\173', '\101', '\102', '\103', '\104', '\105', '\106', '\107',
387   '\110', '\111', '\350', '\351', '\352', '\353', '\354', '\355',
388   '\175', '\112', '\113', '\114', '\115', '\116', '\117', '\120',
389   '\121', '\122', '\356', '\357', '\360', '\361', '\362', '\363',
390   '\134', '\237', '\123', '\124', '\125', '\126', '\127', '\130',
391   '\131', '\132', '\364', '\365', '\366', '\367', '\370', '\371',
392   '\060', '\061', '\062', '\063', '\064', '\065', '\066', '\067',
393   '\070', '\071', '\372', '\373', '\374', '\375', '\376', '\377'
394 };
395
396 void
397 usage (int status)
398 {
399   if (status != EXIT_SUCCESS)
400     fprintf (stderr, _("Try `%s --help' for more information.\n"),
401              program_name);
402   else
403     {
404       printf (_("\
405 Usage: %s [OPERAND]...\n\
406   or:  %s OPTION\n\
407 "),
408               program_name, program_name);
409       fputs (_("\
410 Copy a file, converting and formatting according to the operands.\n\
411 \n\
412   bs=BYTES        force ibs=BYTES and obs=BYTES\n\
413   cbs=BYTES       convert BYTES bytes at a time\n\
414   conv=CONVS      convert the file as per the comma separated symbol list\n\
415   count=BLOCKS    copy only BLOCKS input blocks\n\
416   ibs=BYTES       read BYTES bytes at a time\n\
417 "), stdout);
418       fputs (_("\
419   if=FILE         read from FILE instead of stdin\n\
420   iflag=FLAGS     read as per the comma separated symbol list\n\
421   obs=BYTES       write BYTES bytes at a time\n\
422   of=FILE         write to FILE instead of stdout\n\
423   oflag=FLAGS     write as per the comma separated symbol list\n\
424   seek=BLOCKS     skip BLOCKS obs-sized blocks at start of output\n\
425   skip=BLOCKS     skip BLOCKS ibs-sized blocks at start of input\n\
426   status=noxfer   suppress transfer statistics\n\
427 "), stdout);
428       fputs (_("\
429 \n\
430 BLOCKS and BYTES may be followed by the following multiplicative suffixes:\n\
431 xM M, c 1, w 2, b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024,\n\
432 GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y.\n\
433 \n\
434 Each CONV symbol may be:\n\
435 \n\
436 "), stdout);
437       fputs (_("\
438   ascii     from EBCDIC to ASCII\n\
439   ebcdic    from ASCII to EBCDIC\n\
440   ibm       from ASCII to alternate EBCDIC\n\
441   block     pad newline-terminated records with spaces to cbs-size\n\
442   unblock   replace trailing spaces in cbs-size records with newline\n\
443   lcase     change upper case to lower case\n\
444 "), stdout);
445       fputs (_("\
446   nocreat   do not create the output file\n\
447   excl      fail if the output file already exists\n\
448   notrunc   do not truncate the output file\n\
449   ucase     change lower case to upper case\n\
450   swab      swap every pair of input bytes\n\
451   noerror   continue after read errors\n\
452   sync      pad every input block with NULs to ibs-size; when used\n\
453               with block or unblock, pad with spaces rather than NULs\n\
454   fdatasync physically write output file data before finishing\n\
455   fsync     likewise, but also write metadata\n\
456 "), stdout);
457       fputs (_("\
458 \n\
459 Each FLAG symbol may be:\n\
460 \n\
461   append    append mode (makes sense only for output; conv=notrunc suggested)\n\
462 "), stdout);
463       if (O_DIRECT)
464         fputs (_("  direct    use direct I/O for data\n"), stdout);
465       if (O_DIRECTORY)
466         fputs (_("  directory fail unless a directory\n"), stdout);
467       if (O_DSYNC)
468         fputs (_("  dsync     use synchronized I/O for data\n"), stdout);
469       if (O_SYNC)
470         fputs (_("  sync      likewise, but also for metadata\n"), stdout);
471       if (O_NONBLOCK)
472         fputs (_("  nonblock  use non-blocking I/O\n"), stdout);
473       if (HAVE_WORKING_O_NOATIME)
474         fputs (_("  noatime   do not update access time\n"), stdout);
475       if (O_NOCTTY)
476         fputs (_("  noctty    do not assign controlling terminal from file\n"),
477                stdout);
478       if (HAVE_WORKING_O_NOFOLLOW)
479         fputs (_("  nofollow  do not follow symlinks\n"), stdout);
480       if (O_NOLINKS)
481         fputs (_("  nolinks   fail if multiply-linked\n"), stdout);
482       if (O_BINARY)
483         fputs (_("  binary    use binary I/O for data\n"), stdout);
484       if (O_TEXT)
485         fputs (_("  text      use text I/O for data\n"), stdout);
486
487       {
488         char const *siginfo_name = (SIGINFO == SIGUSR1 ? "USR1" : "INFO");
489         printf (_("\
490 \n\
491 Sending a %s signal to a running `dd' process makes it\n\
492 print I/O statistics to standard error and then resume copying.\n\
493 \n\
494   $ dd if=/dev/zero of=/dev/null& pid=$!\n\
495   $ kill -%s $pid; sleep 1; kill $pid\n\
496   18335302+0 records in\n\
497   18335302+0 records out\n\
498   9387674624 bytes (9.4 GB) copied, 34.6279 seconds, 271 MB/s\n\
499 \n\
500 Options are:\n\
501 \n\
502 "),
503                 siginfo_name, siginfo_name);
504       }
505
506       fputs (HELP_OPTION_DESCRIPTION, stdout);
507       fputs (VERSION_OPTION_DESCRIPTION, stdout);
508       printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
509     }
510   exit (status);
511 }
512
513 static void
514 translate_charset (char const *new_trans)
515 {
516   int i;
517
518   for (i = 0; i < 256; i++)
519     trans_table[i] = new_trans[trans_table[i]];
520   translation_needed = true;
521 }
522
523 /* Return true if I has more than one bit set.  I must be nonnegative.  */
524
525 static inline bool
526 multiple_bits_set (int i)
527 {
528   return (i & (i - 1)) != 0;
529 }
530
531 /* Print transfer statistics.  */
532
533 static void
534 print_stats (void)
535 {
536   xtime_t now = gethrxtime ();
537   char hbuf[LONGEST_HUMAN_READABLE + 1];
538   int human_opts =
539     (human_autoscale | human_round_to_nearest
540      | human_space_before_unit | human_SI | human_B);
541   double delta_s;
542   char const *bytes_per_second;
543
544   fprintf (stderr,
545            _("%"PRIuMAX"+%"PRIuMAX" records in\n"
546              "%"PRIuMAX"+%"PRIuMAX" records out\n"),
547            r_full, r_partial, w_full, w_partial);
548
549   if (r_truncate != 0)
550     fprintf (stderr,
551              ngettext ("%"PRIuMAX" truncated record\n",
552                        "%"PRIuMAX" truncated records\n",
553                        select_plural (r_truncate)),
554              r_truncate);
555
556   if (status_flags & STATUS_NOXFER)
557     return;
558
559   /* Use integer arithmetic to compute the transfer rate,
560      since that makes it easy to use SI abbreviations.  */
561
562   fprintf (stderr,
563            ngettext ("%"PRIuMAX" byte (%s) copied",
564                      "%"PRIuMAX" bytes (%s) copied",
565                      select_plural (w_bytes)),
566            w_bytes,
567            human_readable (w_bytes, hbuf, human_opts, 1, 1));
568
569   if (start_time < now)
570     {
571       double XTIME_PRECISIONe0 = XTIME_PRECISION;
572       uintmax_t delta_xtime = now;
573       delta_xtime -= start_time;
574       delta_s = delta_xtime / XTIME_PRECISIONe0;
575       bytes_per_second = human_readable (w_bytes, hbuf, human_opts,
576                                          XTIME_PRECISION, delta_xtime);
577     }
578   else
579     {
580       delta_s = 0;
581       bytes_per_second = _("Infinity B");
582     }
583
584   /* TRANSLATORS: The two instances of "s" in this string are the SI
585      symbol "s" (meaning second), and should not be translated.
586
587      This format used to be:
588
589      ngettext (", %g second, %s/s\n", ", %g seconds, %s/s\n", delta_s == 1)
590
591      but that was incorrect for languages like Polish.  To fix this
592      bug we now use SI symbols even though they're a bit more
593      confusing in English.  */
594   fprintf (stderr, _(", %g s, %s/s\n"), delta_s, bytes_per_second);
595 }
596
597 static void
598 cleanup (void)
599 {
600   if (close (STDIN_FILENO) < 0)
601     error (EXIT_FAILURE, errno,
602            _("closing input file %s"), quote (input_file));
603
604   /* Don't remove this call to close, even though close_stdout
605      closes standard output.  This close is necessary when cleanup
606      is called as part of a signal handler.  */
607   if (close (STDOUT_FILENO) < 0)
608     error (EXIT_FAILURE, errno,
609            _("closing output file %s"), quote (output_file));
610 }
611
612 static inline void ATTRIBUTE_NORETURN
613 quit (int code)
614 {
615   cleanup ();
616   print_stats ();
617   process_signals ();
618   exit (code);
619 }
620
621 /* An ordinary signal was received; arrange for the program to exit.  */
622
623 static void
624 interrupt_handler (int sig)
625 {
626   if (! SA_RESETHAND)
627     signal (sig, SIG_DFL);
628   interrupt_signal = sig;
629 }
630
631 /* An info signal was received; arrange for the program to print status.  */
632
633 static void
634 siginfo_handler (int sig)
635 {
636   if (! SA_NOCLDSTOP)
637     signal (sig, siginfo_handler);
638   info_signal_count++;
639 }
640
641 /* Install the signal handlers.  */
642
643 static void
644 install_signal_handlers (void)
645 {
646   bool catch_siginfo = ! (SIGINFO == SIGUSR1 && getenv ("POSIXLY_CORRECT"));
647
648 #if SA_NOCLDSTOP
649
650   struct sigaction act;
651   sigemptyset (&caught_signals);
652   if (catch_siginfo)
653     {
654       sigaction (SIGINFO, NULL, &act);
655       if (act.sa_handler != SIG_IGN)
656         sigaddset (&caught_signals, SIGINFO);
657     }
658   sigaction (SIGINT, NULL, &act);
659   if (act.sa_handler != SIG_IGN)
660     sigaddset (&caught_signals, SIGINT);
661   act.sa_mask = caught_signals;
662
663   if (sigismember (&caught_signals, SIGINFO))
664     {
665       act.sa_handler = siginfo_handler;
666       act.sa_flags = 0;
667       sigaction (SIGINFO, &act, NULL);
668     }
669
670   if (sigismember (&caught_signals, SIGINT))
671     {
672       /* POSIX 1003.1-2001 says SA_RESETHAND implies SA_NODEFER,
673          but this is not true on Solaris 8 at least.  It doesn't
674          hurt to use SA_NODEFER here, so leave it in.  */
675       act.sa_handler = interrupt_handler;
676       act.sa_flags = SA_NODEFER | SA_RESETHAND;
677       sigaction (SIGINT, &act, NULL);
678     }
679
680 #else
681
682   if (catch_siginfo && signal (SIGINFO, SIG_IGN) != SIG_IGN)
683     {
684       signal (SIGINFO, siginfo_handler);
685       siginterrupt (SIGINFO, 1);
686     }
687   if (signal (SIGINT, SIG_IGN) != SIG_IGN)
688     {
689       signal (SIGINT, interrupt_handler);
690       siginterrupt (SIGINT, 1);
691     }
692 #endif
693 }
694
695 /* Process any pending signals.  If signals are caught, this function
696    should be called periodically.  Ideally there should never be an
697    unbounded amount of time when signals are not being processed.  */
698
699 static void
700 process_signals (void)
701 {
702   while (interrupt_signal | info_signal_count)
703     {
704       int interrupt;
705       int infos;
706       sigset_t oldset;
707
708       sigprocmask (SIG_BLOCK, &caught_signals, &oldset);
709
710       /* Reload interrupt_signal and info_signal_count, in case a new
711          signal was handled before sigprocmask took effect.  */
712       interrupt = interrupt_signal;
713       infos = info_signal_count;
714
715       if (infos)
716         info_signal_count = infos - 1;
717
718       sigprocmask (SIG_SETMASK, &oldset, NULL);
719
720       if (interrupt)
721         cleanup ();
722       print_stats ();
723       if (interrupt)
724         raise (interrupt);
725     }
726 }
727
728 /* Read from FD into the buffer BUF of size SIZE, processing any
729    signals that arrive before bytes are read.  Return the number of
730    bytes read if successful, -1 (setting errno) on failure.  */
731
732 static ssize_t
733 iread (int fd, char *buf, size_t size)
734 {
735   for (;;)
736     {
737       ssize_t nread;
738       process_signals ();
739       nread = read (fd, buf, size);
740       if (! (nread < 0 && errno == EINTR))
741         return nread;
742     }
743 }
744
745 /* Write to FD the buffer BUF of size SIZE, processing any signals
746    that arrive.  Return the number of bytes written, setting errno if
747    this is less than SIZE.  Keep trying if there are partial
748    writes.  */
749
750 static size_t
751 iwrite (int fd, char const *buf, size_t size)
752 {
753   size_t total_written = 0;
754
755   while (total_written < size)
756     {
757       ssize_t nwritten;
758       process_signals ();
759       nwritten = write (fd, buf + total_written, size - total_written);
760       if (nwritten < 0)
761         {
762           if (errno != EINTR)
763             break;
764         }
765       else if (nwritten == 0)
766         {
767           /* Some buggy drivers return 0 when one tries to write beyond
768              a device's end.  (Example: Linux 1.2.13 on /dev/fd0.)
769              Set errno to ENOSPC so they get a sensible diagnostic.  */
770           errno = ENOSPC;
771           break;
772         }
773       else
774         total_written += nwritten;
775     }
776
777   return total_written;
778 }
779
780 /* Write, then empty, the output buffer `obuf'. */
781
782 static void
783 write_output (void)
784 {
785   size_t nwritten = iwrite (STDOUT_FILENO, obuf, output_blocksize);
786   w_bytes += nwritten;
787   if (nwritten != output_blocksize)
788     {
789       error (0, errno, _("writing to %s"), quote (output_file));
790       if (nwritten != 0)
791         w_partial++;
792       quit (EXIT_FAILURE);
793     }
794   else
795     w_full++;
796   oc = 0;
797 }
798
799 /* Interpret one "conv=..." or similar operand STR according to the
800    symbols in TABLE, returning the flags specified.  If the operand
801    cannot be parsed, use ERROR_MSGID to generate a diagnostic.
802    As a by product, this function replaces each `,' in STR with a NUL byte.  */
803
804 static int
805 parse_symbols (char *str, struct symbol_value const *table,
806                char const *error_msgid)
807 {
808   int value = 0;
809
810   do
811     {
812       struct symbol_value const *entry;
813       char *new = strchr (str, ',');
814       if (new != NULL)
815         *new++ = '\0';
816       for (entry = table; ; entry++)
817         {
818           if (! entry->symbol[0])
819             {
820               error (0, 0, _(error_msgid), quote (str));
821               usage (EXIT_FAILURE);
822             }
823           if (STREQ (entry->symbol, str))
824             {
825               if (! entry->value)
826                 error (EXIT_FAILURE, 0, _(error_msgid), quote (str));
827               value |= entry->value;
828               break;
829             }
830         }
831       str = new;
832     }
833   while (str);
834
835   return value;
836 }
837
838 /* Return the value of STR, interpreted as a non-negative decimal integer,
839    optionally multiplied by various values.
840    Set *INVALID if STR does not represent a number in this format.  */
841
842 static uintmax_t
843 parse_integer (const char *str, bool *invalid)
844 {
845   uintmax_t n;
846   char *suffix;
847   enum strtol_error e = xstrtoumax (str, &suffix, 10, &n, "bcEGkKMPTwYZ0");
848
849   if (e == LONGINT_INVALID_SUFFIX_CHAR && *suffix == 'x')
850     {
851       uintmax_t multiplier = parse_integer (suffix + 1, invalid);
852
853       if (multiplier != 0 && n * multiplier / multiplier != n)
854         {
855           *invalid = true;
856           return 0;
857         }
858
859       n *= multiplier;
860     }
861   else if (e != LONGINT_OK)
862     {
863       *invalid = true;
864       return 0;
865     }
866
867   return n;
868 }
869
870 static void
871 scanargs (int argc, char **argv)
872 {
873   int i;
874
875   for (i = optind; i < argc; i++)
876     {
877       char *name, *val;
878
879       name = argv[i];
880       val = strchr (name, '=');
881       if (val == NULL)
882         {
883           error (0, 0, _("unrecognized operand %s"), quote (name));
884           usage (EXIT_FAILURE);
885         }
886       *val++ = '\0';
887
888       if (STREQ (name, "if"))
889         input_file = val;
890       else if (STREQ (name, "of"))
891         output_file = val;
892       else if (STREQ (name, "conv"))
893         conversions_mask |= parse_symbols (val, conversions,
894                                            N_("invalid conversion: %s"));
895       else if (STREQ (name, "iflag"))
896         input_flags |= parse_symbols (val, flags,
897                                       N_("invalid input flag: %s"));
898       else if (STREQ (name, "oflag"))
899         output_flags |= parse_symbols (val, flags,
900                                        N_("invalid output flag: %s"));
901       else if (STREQ (name, "status"))
902         status_flags |= parse_symbols (val, statuses,
903                                        N_("invalid status flag: %s"));
904       else
905         {
906           bool invalid = false;
907           uintmax_t n = parse_integer (val, &invalid);
908
909           if (STREQ (name, "ibs"))
910             {
911               invalid |= ! (0 < n && n <= MAX_BLOCKSIZE (INPUT_BLOCK_SLOP));
912               input_blocksize = n;
913               conversions_mask |= C_TWOBUFS;
914             }
915           else if (STREQ (name, "obs"))
916             {
917               invalid |= ! (0 < n && n <= MAX_BLOCKSIZE (OUTPUT_BLOCK_SLOP));
918               output_blocksize = n;
919               conversions_mask |= C_TWOBUFS;
920             }
921           else if (STREQ (name, "bs"))
922             {
923               invalid |= ! (0 < n && n <= MAX_BLOCKSIZE (INPUT_BLOCK_SLOP));
924               output_blocksize = input_blocksize = n;
925             }
926           else if (STREQ (name, "cbs"))
927             {
928               invalid |= ! (0 < n && n <= SIZE_MAX);
929               conversion_blocksize = n;
930             }
931           else if (STREQ (name, "skip"))
932             skip_records = n;
933           else if (STREQ (name, "seek"))
934             seek_records = n;
935           else if (STREQ (name, "count"))
936             max_records = n;
937           else
938             {
939               error (0, 0, _("unrecognized operand %s=%s"),
940                      quote_n (0, name), quote_n (1, val));
941               usage (EXIT_FAILURE);
942             }
943
944           if (invalid)
945             error (EXIT_FAILURE, 0, _("invalid number %s"), quote (val));
946         }
947     }
948
949   /* If bs= was given, both `input_blocksize' and `output_blocksize' will
950      have been set to positive values.  If either has not been set,
951      bs= was not given, so make sure two buffers are used. */
952   if (input_blocksize == 0 || output_blocksize == 0)
953     conversions_mask |= C_TWOBUFS;
954   if (input_blocksize == 0)
955     input_blocksize = DEFAULT_BLOCKSIZE;
956   if (output_blocksize == 0)
957     output_blocksize = DEFAULT_BLOCKSIZE;
958   if (conversion_blocksize == 0)
959     conversions_mask &= ~(C_BLOCK | C_UNBLOCK);
960
961   if (input_flags & (O_DSYNC | O_SYNC))
962     input_flags |= O_RSYNC;
963
964   if (multiple_bits_set (conversions_mask & (C_ASCII | C_EBCDIC | C_IBM)))
965     error (EXIT_FAILURE, 0, _("cannot combine any two of {ascii,ebcdic,ibm}"));
966   if (multiple_bits_set (conversions_mask & (C_BLOCK | C_UNBLOCK)))
967     error (EXIT_FAILURE, 0, _("cannot combine block and unblock"));
968   if (multiple_bits_set (conversions_mask & (C_LCASE | C_UCASE)))
969     error (EXIT_FAILURE, 0, _("cannot combine lcase and ucase"));
970   if (multiple_bits_set (conversions_mask & (C_EXCL | C_NOCREAT)))
971     error (EXIT_FAILURE, 0, _("cannot combine excl and nocreat"));
972 }
973
974 /* Fix up translation table. */
975
976 static void
977 apply_translations (void)
978 {
979   int i;
980
981   if (conversions_mask & C_ASCII)
982     translate_charset (ebcdic_to_ascii);
983
984   if (conversions_mask & C_UCASE)
985     {
986       for (i = 0; i < 256; i++)
987         trans_table[i] = toupper (trans_table[i]);
988       translation_needed = true;
989     }
990   else if (conversions_mask & C_LCASE)
991     {
992       for (i = 0; i < 256; i++)
993         trans_table[i] = tolower (trans_table[i]);
994       translation_needed = true;
995     }
996
997   if (conversions_mask & C_EBCDIC)
998     {
999       translate_charset (ascii_to_ebcdic);
1000       newline_character = ascii_to_ebcdic['\n'];
1001       space_character = ascii_to_ebcdic[' '];
1002     }
1003   else if (conversions_mask & C_IBM)
1004     {
1005       translate_charset (ascii_to_ibm);
1006       newline_character = ascii_to_ibm['\n'];
1007       space_character = ascii_to_ibm[' '];
1008     }
1009 }
1010
1011 /* Apply the character-set translations specified by the user
1012    to the NREAD bytes in BUF.  */
1013
1014 static void
1015 translate_buffer (char *buf, size_t nread)
1016 {
1017   char *cp;
1018   size_t i;
1019
1020   for (i = nread, cp = buf; i; i--, cp++)
1021     *cp = trans_table[to_uchar (*cp)];
1022 }
1023
1024 /* If true, the last char from the previous call to `swab_buffer'
1025    is saved in `saved_char'.  */
1026 static bool char_is_saved = false;
1027
1028 /* Odd char from previous call.  */
1029 static char saved_char;
1030
1031 /* Swap NREAD bytes in BUF, plus possibly an initial char from the
1032    previous call.  If NREAD is odd, save the last char for the
1033    next call.   Return the new start of the BUF buffer.  */
1034
1035 static char *
1036 swab_buffer (char *buf, size_t *nread)
1037 {
1038   char *bufstart = buf;
1039   char *cp;
1040   size_t i;
1041
1042   /* Is a char left from last time?  */
1043   if (char_is_saved)
1044     {
1045       *--bufstart = saved_char;
1046       (*nread)++;
1047       char_is_saved = false;
1048     }
1049
1050   if (*nread & 1)
1051     {
1052       /* An odd number of chars are in the buffer.  */
1053       saved_char = bufstart[--*nread];
1054       char_is_saved = true;
1055     }
1056
1057   /* Do the byte-swapping by moving every second character two
1058      positions toward the end, working from the end of the buffer
1059      toward the beginning.  This way we only move half of the data.  */
1060
1061   cp = bufstart + *nread;       /* Start one char past the last.  */
1062   for (i = *nread / 2; i; i--, cp -= 2)
1063     *cp = *(cp - 2);
1064
1065   return ++bufstart;
1066 }
1067
1068 /* Add OFFSET to the input offset, setting the overflow flag if
1069    necessary.  */
1070
1071 static void
1072 advance_input_offset (uintmax_t offset)
1073 {
1074   input_offset += offset;
1075   if (input_offset < offset)
1076     input_offset_overflow = true;
1077 }
1078
1079 /* This is a wrapper for lseek.  It detects and warns about a kernel
1080    bug that makes lseek a no-op for tape devices, even though the kernel
1081    lseek return value suggests that the function succeeded.
1082
1083    The parameters are the same as those of the lseek function, but
1084    with the addition of FILENAME, the name of the file associated with
1085    descriptor FDESC.  The file name is used solely in the warning that's
1086    printed when the bug is detected.  Return the same value that lseek
1087    would have returned, but when the lseek bug is detected, return -1
1088    to indicate that lseek failed.
1089
1090    The offending behavior has been confirmed with an Exabyte SCSI tape
1091    drive accessed via /dev/nst0 on both Linux-2.2.17 and Linux-2.4.16.  */
1092
1093 #ifdef __linux__
1094
1095 # include <sys/mtio.h>
1096
1097 # define MT_SAME_POSITION(P, Q) \
1098    ((P).mt_resid == (Q).mt_resid \
1099     && (P).mt_fileno == (Q).mt_fileno \
1100     && (P).mt_blkno == (Q).mt_blkno)
1101
1102 static off_t
1103 skip_via_lseek (char const *filename, int fdesc, off_t offset, int whence)
1104 {
1105   struct mtget s1;
1106   struct mtget s2;
1107   bool got_original_tape_position = (ioctl (fdesc, MTIOCGET, &s1) == 0);
1108   /* known bad device type */
1109   /* && s.mt_type == MT_ISSCSI2 */
1110
1111   off_t new_position = lseek (fdesc, offset, whence);
1112   if (0 <= new_position
1113       && got_original_tape_position
1114       && ioctl (fdesc, MTIOCGET, &s2) == 0
1115       && MT_SAME_POSITION (s1, s2))
1116     {
1117       error (0, 0, _("warning: working around lseek kernel bug for file (%s)\n\
1118   of mt_type=0x%0lx -- see <sys/mtio.h> for the list of types"),
1119              filename, s2.mt_type);
1120       errno = 0;
1121       new_position = -1;
1122     }
1123
1124   return new_position;
1125 }
1126 #else
1127 # define skip_via_lseek(Filename, Fd, Offset, Whence) lseek (Fd, Offset, Whence)
1128 #endif
1129
1130 /* Throw away RECORDS blocks of BLOCKSIZE bytes on file descriptor FDESC,
1131    which is open with read permission for FILE.  Store up to BLOCKSIZE
1132    bytes of the data at a time in BUF, if necessary.  RECORDS must be
1133    nonzero.  If fdesc is STDIN_FILENO, advance the input offset.
1134    Return the number of records remaining, i.e., that were not skipped
1135    because EOF was reached.  */
1136
1137 static uintmax_t
1138 skip (int fdesc, char const *file, uintmax_t records, size_t blocksize,
1139       char *buf)
1140 {
1141   uintmax_t offset = records * blocksize;
1142
1143   /* Try lseek and if an error indicates it was an inappropriate operation --
1144      or if the file offset is not representable as an off_t --
1145      fall back on using read.  */
1146
1147   errno = 0;
1148   if (records <= OFF_T_MAX / blocksize
1149       && 0 <= skip_via_lseek (file, fdesc, offset, SEEK_CUR))
1150     {
1151       if (fdesc == STDIN_FILENO)
1152         advance_input_offset (offset);
1153       return 0;
1154     }
1155   else
1156     {
1157       int lseek_errno = errno;
1158
1159       do
1160         {
1161           ssize_t nread = iread (fdesc, buf, blocksize);
1162           if (nread < 0)
1163             {
1164               if (fdesc == STDIN_FILENO)
1165                 {
1166                   error (0, errno, _("reading %s"), quote (file));
1167                   if (conversions_mask & C_NOERROR)
1168                     {
1169                       print_stats ();
1170                       continue;
1171                     }
1172                 }
1173               else
1174                 error (0, lseek_errno, _("%s: cannot seek"), quote (file));
1175               quit (EXIT_FAILURE);
1176             }
1177
1178           if (nread == 0)
1179             break;
1180           if (fdesc == STDIN_FILENO)
1181             advance_input_offset (nread);
1182         }
1183       while (--records != 0);
1184
1185       return records;
1186     }
1187 }
1188
1189 /* Advance the input by NBYTES if possible, after a read error.
1190    The input file offset may or may not have advanced after the failed
1191    read; adjust it to point just after the bad record regardless.
1192    Return true if successful, or if the input is already known to not
1193    be seekable.  */
1194
1195 static bool
1196 advance_input_after_read_error (size_t nbytes)
1197 {
1198   if (! input_seekable)
1199     {
1200       if (input_seek_errno == ESPIPE)
1201         return true;
1202       errno = input_seek_errno;
1203     }
1204   else
1205     {
1206       off_t offset;
1207       advance_input_offset (nbytes);
1208       input_offset_overflow |= (OFF_T_MAX < input_offset);
1209       if (input_offset_overflow)
1210         {
1211           error (0, 0, _("offset overflow while reading file %s"),
1212                  quote (input_file));
1213           return false;
1214         }
1215       offset = lseek (STDIN_FILENO, 0, SEEK_CUR);
1216       if (0 <= offset)
1217         {
1218           off_t diff;
1219           if (offset == input_offset)
1220             return true;
1221           diff = input_offset - offset;
1222           if (! (0 <= diff && diff <= nbytes))
1223             error (0, 0, _("warning: screwy file offset after failed read"));
1224           if (0 <= skip_via_lseek (input_file, STDIN_FILENO, diff, SEEK_CUR))
1225             return true;
1226           if (errno == 0)
1227             error (0, 0, _("cannot work around kernel bug after all"));
1228         }
1229     }
1230
1231   error (0, errno, _("%s: cannot seek"), quote (input_file));
1232   return false;
1233 }
1234
1235 /* Copy NREAD bytes of BUF, with no conversions.  */
1236
1237 static void
1238 copy_simple (char const *buf, size_t nread)
1239 {
1240   const char *start = buf;      /* First uncopied char in BUF.  */
1241
1242   do
1243     {
1244       size_t nfree = MIN (nread, output_blocksize - oc);
1245
1246       memcpy (obuf + oc, start, nfree);
1247
1248       nread -= nfree;           /* Update the number of bytes left to copy. */
1249       start += nfree;
1250       oc += nfree;
1251       if (oc >= output_blocksize)
1252         write_output ();
1253     }
1254   while (nread != 0);
1255 }
1256
1257 /* Copy NREAD bytes of BUF, doing conv=block
1258    (pad newline-terminated records to `conversion_blocksize',
1259    replacing the newline with trailing spaces).  */
1260
1261 static void
1262 copy_with_block (char const *buf, size_t nread)
1263 {
1264   size_t i;
1265
1266   for (i = nread; i; i--, buf++)
1267     {
1268       if (*buf == newline_character)
1269         {
1270           if (col < conversion_blocksize)
1271             {
1272               size_t j;
1273               for (j = col; j < conversion_blocksize; j++)
1274                 output_char (space_character);
1275             }
1276           col = 0;
1277         }
1278       else
1279         {
1280           if (col == conversion_blocksize)
1281             r_truncate++;
1282           else if (col < conversion_blocksize)
1283             output_char (*buf);
1284           col++;
1285         }
1286     }
1287 }
1288
1289 /* Copy NREAD bytes of BUF, doing conv=unblock
1290    (replace trailing spaces in `conversion_blocksize'-sized records
1291    with a newline).  */
1292
1293 static void
1294 copy_with_unblock (char const *buf, size_t nread)
1295 {
1296   size_t i;
1297   char c;
1298   static size_t pending_spaces = 0;
1299
1300   for (i = 0; i < nread; i++)
1301     {
1302       c = buf[i];
1303
1304       if (col++ >= conversion_blocksize)
1305         {
1306           col = pending_spaces = 0; /* Wipe out any pending spaces.  */
1307           i--;                  /* Push the char back; get it later. */
1308           output_char (newline_character);
1309         }
1310       else if (c == space_character)
1311         pending_spaces++;
1312       else
1313         {
1314           /* `c' is the character after a run of spaces that were not
1315              at the end of the conversion buffer.  Output them.  */
1316           while (pending_spaces)
1317             {
1318               output_char (space_character);
1319               --pending_spaces;
1320             }
1321           output_char (c);
1322         }
1323     }
1324 }
1325
1326 /* Set the file descriptor flags for FD that correspond to the nonzero bits
1327    in ADD_FLAGS.  The file's name is NAME.  */
1328
1329 static void
1330 set_fd_flags (int fd, int add_flags, char const *name)
1331 {
1332   /* Ignore file creation flags that are no-ops on file descriptors.  */
1333   add_flags &= ~ (O_NOCTTY | O_NOFOLLOW);
1334
1335   if (add_flags)
1336     {
1337       int old_flags = fcntl (fd, F_GETFL);
1338       int new_flags = old_flags | add_flags;
1339       bool ok = true;
1340       if (old_flags < 0)
1341         ok = false;
1342       else if (old_flags != new_flags)
1343         {
1344           if (new_flags & (O_DIRECTORY | O_NOLINKS))
1345             {
1346               /* NEW_FLAGS contains at least one file creation flag that
1347                  requires some checking of the open file descriptor.  */
1348               struct stat st;
1349               if (fstat (fd, &st) != 0)
1350                 ok = false;
1351               else if ((new_flags & O_DIRECTORY) && ! S_ISDIR (st.st_mode))
1352                 {
1353                   errno = ENOTDIR;
1354                   ok = false;
1355                 }
1356               else if ((new_flags & O_NOLINKS) && 1 < st.st_nlink)
1357                 {
1358                   errno = EMLINK;
1359                   ok = false;
1360                 }
1361               new_flags &= ~ (O_DIRECTORY | O_NOLINKS);
1362             }
1363
1364           if (ok && old_flags != new_flags
1365               && fcntl (fd, F_SETFL, new_flags) == -1)
1366             ok = false;
1367         }
1368
1369       if (!ok)
1370         error (EXIT_FAILURE, errno, _("setting flags for %s"), quote (name));
1371     }
1372 }
1373
1374 /* The main loop.  */
1375
1376 static int
1377 dd_copy (void)
1378 {
1379   char *ibuf, *bufstart;        /* Input buffer. */
1380   char *real_buf;               /* real buffer address before alignment */
1381   char *real_obuf;
1382   ssize_t nread;                /* Bytes read in the current block.  */
1383
1384   /* If nonzero, then the previously read block was partial and
1385      PARTREAD was its size.  */
1386   size_t partread = 0;
1387
1388   int exit_status = EXIT_SUCCESS;
1389   size_t n_bytes_read;
1390
1391   /* Leave at least one extra byte at the beginning and end of `ibuf'
1392      for conv=swab, but keep the buffer address even.  But some peculiar
1393      device drivers work only with word-aligned buffers, so leave an
1394      extra two bytes.  */
1395
1396   /* Some devices require alignment on a sector or page boundary
1397      (e.g. character disk devices).  Align the input buffer to a
1398      page boundary to cover all bases.  Note that due to the swab
1399      algorithm, we must have at least one byte in the page before
1400      the input buffer;  thus we allocate 2 pages of slop in the
1401      real buffer.  8k above the blocksize shouldn't bother anyone.
1402
1403      The page alignment is necessary on any linux system that supports
1404      either the SGI raw I/O patch or Steven Tweedies raw I/O patch.
1405      It is necessary when accessing raw (i.e. character special) disk
1406      devices on Unixware or other SVR4-derived system.  */
1407
1408   real_buf = xmalloc (input_blocksize + INPUT_BLOCK_SLOP);
1409   ibuf = real_buf;
1410   ibuf += SWAB_ALIGN_OFFSET;    /* allow space for swab */
1411
1412   ibuf = ptr_align (ibuf, page_size);
1413
1414   if (conversions_mask & C_TWOBUFS)
1415     {
1416       /* Page-align the output buffer, too.  */
1417       real_obuf = xmalloc (output_blocksize + OUTPUT_BLOCK_SLOP);
1418       obuf = ptr_align (real_obuf, page_size);
1419     }
1420   else
1421     {
1422       real_obuf = NULL;
1423       obuf = ibuf;
1424     }
1425
1426   if (skip_records != 0)
1427     {
1428       skip (STDIN_FILENO, input_file, skip_records, input_blocksize, ibuf);
1429       /* POSIX doesn't say what to do when dd detects it has been
1430          asked to skip past EOF, so I assume it's non-fatal if the
1431          call to 'skip' returns nonzero.  FIXME: maybe give a warning.  */
1432     }
1433
1434   if (seek_records != 0)
1435     {
1436       uintmax_t write_records = skip (STDOUT_FILENO, output_file,
1437                                       seek_records, output_blocksize, obuf);
1438
1439       if (write_records != 0)
1440         {
1441           memset (obuf, 0, output_blocksize);
1442
1443           do
1444             if (iwrite (STDOUT_FILENO, obuf, output_blocksize)
1445                 != output_blocksize)
1446               {
1447                 error (0, errno, _("writing to %s"), quote (output_file));
1448                 quit (EXIT_FAILURE);
1449               }
1450           while (--write_records != 0);
1451         }
1452     }
1453
1454   if (max_records == 0)
1455     return exit_status;
1456
1457   while (1)
1458     {
1459       if (r_partial + r_full >= max_records)
1460         break;
1461
1462       /* Zero the buffer before reading, so that if we get a read error,
1463          whatever data we are able to read is followed by zeros.
1464          This minimizes data loss. */
1465       if ((conversions_mask & C_SYNC) && (conversions_mask & C_NOERROR))
1466         memset (ibuf,
1467                 (conversions_mask & (C_BLOCK | C_UNBLOCK)) ? ' ' : '\0',
1468                 input_blocksize);
1469
1470       nread = iread (STDIN_FILENO, ibuf, input_blocksize);
1471
1472       if (nread == 0)
1473         break;                  /* EOF.  */
1474
1475       if (nread < 0)
1476         {
1477           error (0, errno, _("reading %s"), quote (input_file));
1478           if (conversions_mask & C_NOERROR)
1479             {
1480               print_stats ();
1481               /* Seek past the bad block if possible. */
1482               if (!advance_input_after_read_error (input_blocksize - partread))
1483                 {
1484                   exit_status = EXIT_FAILURE;
1485
1486                   /* Suppress duplicate diagnostics.  */
1487                   input_seekable = false;
1488                   input_seek_errno = ESPIPE;
1489                 }
1490               if ((conversions_mask & C_SYNC) && !partread)
1491                 /* Replace the missing input with null bytes and
1492                    proceed normally.  */
1493                 nread = 0;
1494               else
1495                 continue;
1496             }
1497           else
1498             {
1499               /* Write any partial block. */
1500               exit_status = EXIT_FAILURE;
1501               break;
1502             }
1503         }
1504
1505       n_bytes_read = nread;
1506       advance_input_offset (nread);
1507
1508       if (n_bytes_read < input_blocksize)
1509         {
1510           r_partial++;
1511           partread = n_bytes_read;
1512           if (conversions_mask & C_SYNC)
1513             {
1514               if (!(conversions_mask & C_NOERROR))
1515                 /* If C_NOERROR, we zeroed the block before reading. */
1516                 memset (ibuf + n_bytes_read,
1517                         (conversions_mask & (C_BLOCK | C_UNBLOCK)) ? ' ' : '\0',
1518                         input_blocksize - n_bytes_read);
1519               n_bytes_read = input_blocksize;
1520             }
1521         }
1522       else
1523         {
1524           r_full++;
1525           partread = 0;
1526         }
1527
1528       if (ibuf == obuf)         /* If not C_TWOBUFS. */
1529         {
1530           size_t nwritten = iwrite (STDOUT_FILENO, obuf, n_bytes_read);
1531           w_bytes += nwritten;
1532           if (nwritten != n_bytes_read)
1533             {
1534               error (0, errno, _("writing %s"), quote (output_file));
1535               return EXIT_FAILURE;
1536             }
1537           else if (n_bytes_read == input_blocksize)
1538             w_full++;
1539           else
1540             w_partial++;
1541           continue;
1542         }
1543
1544       /* Do any translations on the whole buffer at once.  */
1545
1546       if (translation_needed)
1547         translate_buffer (ibuf, n_bytes_read);
1548
1549       if (conversions_mask & C_SWAB)
1550         bufstart = swab_buffer (ibuf, &n_bytes_read);
1551       else
1552         bufstart = ibuf;
1553
1554       if (conversions_mask & C_BLOCK)
1555         copy_with_block (bufstart, n_bytes_read);
1556       else if (conversions_mask & C_UNBLOCK)
1557         copy_with_unblock (bufstart, n_bytes_read);
1558       else
1559         copy_simple (bufstart, n_bytes_read);
1560     }
1561
1562   /* If we have a char left as a result of conv=swab, output it.  */
1563   if (char_is_saved)
1564     {
1565       if (conversions_mask & C_BLOCK)
1566         copy_with_block (&saved_char, 1);
1567       else if (conversions_mask & C_UNBLOCK)
1568         copy_with_unblock (&saved_char, 1);
1569       else
1570         output_char (saved_char);
1571     }
1572
1573   if ((conversions_mask & C_BLOCK) && col > 0)
1574     {
1575       /* If the final input line didn't end with a '\n', pad
1576          the output block to `conversion_blocksize' chars.  */
1577       size_t i;
1578       for (i = col; i < conversion_blocksize; i++)
1579         output_char (space_character);
1580     }
1581
1582   if ((conversions_mask & C_UNBLOCK) && col == conversion_blocksize)
1583     /* Add a final '\n' if there are exactly `conversion_blocksize'
1584        characters in the final record. */
1585     output_char (newline_character);
1586
1587   /* Write out the last block. */
1588   if (oc != 0)
1589     {
1590       size_t nwritten = iwrite (STDOUT_FILENO, obuf, oc);
1591       w_bytes += nwritten;
1592       if (nwritten != 0)
1593         w_partial++;
1594       if (nwritten != oc)
1595         {
1596           error (0, errno, _("writing %s"), quote (output_file));
1597           return EXIT_FAILURE;
1598         }
1599     }
1600
1601   free (real_buf);
1602   free (real_obuf);
1603
1604   if ((conversions_mask & C_FDATASYNC) && fdatasync (STDOUT_FILENO) != 0)
1605     {
1606       if (errno != ENOSYS && errno != EINVAL)
1607         {
1608           error (0, errno, _("fdatasync failed for %s"), quote (output_file));
1609           exit_status = EXIT_FAILURE;
1610         }
1611       conversions_mask |= C_FSYNC;
1612     }
1613
1614   if (conversions_mask & C_FSYNC)
1615     while (fsync (STDOUT_FILENO) != 0)
1616       if (errno != EINTR)
1617         {
1618           error (0, errno, _("fsync failed for %s"), quote (output_file));
1619           return EXIT_FAILURE;
1620         }
1621
1622   return exit_status;
1623 }
1624
1625 int
1626 main (int argc, char **argv)
1627 {
1628   int i;
1629   int exit_status;
1630   off_t offset;
1631
1632   initialize_main (&argc, &argv);
1633   program_name = argv[0];
1634   setlocale (LC_ALL, "");
1635   bindtextdomain (PACKAGE, LOCALEDIR);
1636   textdomain (PACKAGE);
1637
1638   /* Arrange to close stdout if parse_long_options exits.  */
1639   atexit (close_stdout);
1640
1641   page_size = getpagesize ();
1642
1643   parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE, VERSION,
1644                       usage, AUTHORS, (char const *) NULL);
1645   if (getopt_long (argc, argv, "", NULL, NULL) != -1)
1646     usage (EXIT_FAILURE);
1647
1648   /* Initialize translation table to identity translation. */
1649   for (i = 0; i < 256; i++)
1650     trans_table[i] = i;
1651
1652   /* Decode arguments. */
1653   scanargs (argc, argv);
1654
1655   apply_translations ();
1656
1657   if (input_file == NULL)
1658     {
1659       input_file = _("standard input");
1660       set_fd_flags (STDIN_FILENO, input_flags, input_file);
1661     }
1662   else
1663     {
1664       if (fd_reopen (STDIN_FILENO, input_file, O_RDONLY | input_flags, 0) < 0)
1665         error (EXIT_FAILURE, errno, _("opening %s"), quote (input_file));
1666     }
1667
1668   offset = lseek (STDIN_FILENO, 0, SEEK_CUR);
1669   input_seekable = (0 <= offset);
1670   input_offset = offset;
1671   input_seek_errno = errno;
1672
1673   if (output_file == NULL)
1674     {
1675       output_file = _("standard output");
1676       set_fd_flags (STDOUT_FILENO, output_flags, output_file);
1677     }
1678   else
1679     {
1680       mode_t perms = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
1681       int opts
1682         = (output_flags
1683            | (conversions_mask & C_NOCREAT ? 0 : O_CREAT)
1684            | (conversions_mask & C_EXCL ? O_EXCL : 0)
1685            | (seek_records || (conversions_mask & C_NOTRUNC) ? 0 : O_TRUNC));
1686
1687       /* Open the output file with *read* access only if we might
1688          need to read to satisfy a `seek=' request.  If we can't read
1689          the file, go ahead with write-only access; it might work.  */
1690       if ((! seek_records
1691            || fd_reopen (STDOUT_FILENO, output_file, O_RDWR | opts, perms) < 0)
1692           && (fd_reopen (STDOUT_FILENO, output_file, O_WRONLY | opts, perms)
1693               < 0))
1694         error (EXIT_FAILURE, errno, _("opening %s"), quote (output_file));
1695
1696 #if HAVE_FTRUNCATE
1697       if (seek_records != 0 && !(conversions_mask & C_NOTRUNC))
1698         {
1699           uintmax_t size = seek_records * output_blocksize;
1700           unsigned long int obs = output_blocksize;
1701
1702           if (OFF_T_MAX / output_blocksize < seek_records)
1703             error (EXIT_FAILURE, 0,
1704                    _("offset too large: "
1705                      "cannot truncate to a length of seek=%"PRIuMAX""
1706                      " (%lu-byte) blocks"),
1707                    seek_records, obs);
1708
1709           if (ftruncate (STDOUT_FILENO, size) != 0)
1710             {
1711               /* Complain only when ftruncate fails on a regular file, a
1712                  directory, or a shared memory object, as POSIX 1003.1-2004
1713                  specifies ftruncate's behavior only for these file types.
1714                  For example, do not complain when Linux 2.4 ftruncate
1715                  fails on /dev/fd0.  */
1716               int ftruncate_errno = errno;
1717               struct stat stdout_stat;
1718               if (fstat (STDOUT_FILENO, &stdout_stat) != 0)
1719                 error (EXIT_FAILURE, errno, _("cannot fstat %s"),
1720                        quote (output_file));
1721               if (S_ISREG (stdout_stat.st_mode)
1722                   || S_ISDIR (stdout_stat.st_mode)
1723                   || S_TYPEISSHM (&stdout_stat))
1724                 error (EXIT_FAILURE, ftruncate_errno,
1725                        _("truncating at %"PRIuMAX" bytes in output file %s"),
1726                        size, quote (output_file));
1727             }
1728         }
1729 #endif
1730     }
1731
1732   install_signal_handlers ();
1733
1734   start_time = gethrxtime ();
1735
1736   exit_status = dd_copy ();
1737
1738   quit (exit_status);
1739 }