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