Tizen 2.0 Release
[external/tizen-coreutils.git] / src / dd.c
1 /* dd -- convert a file while copying it.
2    Copyright (C) 85, 90, 91, 1995-2007 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",   O_NOATIME},
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 "), stdout);
452       fputs (_("\
453   noerror   continue after read errors\n\
454   sync      pad every input block with NULs to ibs-size; when used\n\
455             with block or unblock, pad with spaces rather than NULs\n\
456   fdatasync  physically write output file data before finishing\n\
457   fsync     likewise, but also write metadata\n\
458 "), stdout);
459       fputs (_("\
460 \n\
461 Each FLAG symbol may be:\n\
462 \n\
463   append    append mode (makes sense only for output; conv=notrunc suggested)\n\
464 "), stdout);
465       if (O_DIRECT)
466         fputs (_("  direct    use direct I/O for data\n"), stdout);
467       if (O_DIRECTORY)
468         fputs (_("  directory fail unless a directory\n"), stdout);
469       if (O_DSYNC)
470         fputs (_("  dsync     use synchronized I/O for data\n"), stdout);
471       if (O_SYNC)
472         fputs (_("  sync      likewise, but also for metadata\n"), stdout);
473       if (O_NONBLOCK)
474         fputs (_("  nonblock  use non-blocking I/O\n"), stdout);
475       if (O_NOATIME)
476         fputs (_("  noatime   do not update access time\n"), stdout);
477       if (O_NOCTTY)
478         fputs (_("  noctty    do not assign controlling terminal from file\n"),
479                stdout);
480       if (HAVE_WORKING_O_NOFOLLOW)
481         fputs (_("  nofollow  do not follow symlinks\n"), stdout);
482       if (O_NOLINKS)
483         fputs (_("  nolinks   fail if multiply-linked\n"), stdout);
484       if (O_BINARY)
485         fputs (_("  binary    use binary I/O for data\n"), stdout);
486       if (O_TEXT)
487         fputs (_("  text      use text I/O for data\n"), stdout);
488
489       {
490         char const *siginfo_name = (SIGINFO == SIGUSR1 ? "USR1" : "INFO");
491         printf (_("\
492 \n\
493 Sending a %s signal to a running `dd' process makes it\n\
494 print I/O statistics to standard error and then resume copying.\n\
495 \n\
496   $ dd if=/dev/zero of=/dev/null& pid=$!\n\
497   $ kill -%s $pid; sleep 1; kill $pid\n\
498   18335302+0 records in\n\
499   18335302+0 records out\n\
500   9387674624 bytes (9.4 GB) copied, 34.6279 seconds, 271 MB/s\n\
501 \n\
502 Options are:\n\
503 \n\
504 "),
505                 siginfo_name, siginfo_name);
506       }
507
508       fputs (HELP_OPTION_DESCRIPTION, stdout);
509       fputs (VERSION_OPTION_DESCRIPTION, stdout);
510       printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
511     }
512   exit (status);
513 }
514
515 static void
516 translate_charset (char const *new_trans)
517 {
518   int i;
519
520   for (i = 0; i < 256; i++)
521     trans_table[i] = new_trans[trans_table[i]];
522   translation_needed = true;
523 }
524
525 /* Return true if I has more than one bit set.  I must be nonnegative.  */
526
527 static inline bool
528 multiple_bits_set (int i)
529 {
530   return (i & (i - 1)) != 0;
531 }
532
533 /* Print transfer statistics.  */
534
535 static void
536 print_stats (void)
537 {
538   xtime_t now = gethrxtime ();
539   char hbuf[LONGEST_HUMAN_READABLE + 1];
540   int human_opts =
541     (human_autoscale | human_round_to_nearest
542      | human_space_before_unit | human_SI | human_B);
543   double delta_s;
544   char const *bytes_per_second;
545
546   fprintf (stderr,
547            _("%"PRIuMAX"+%"PRIuMAX" records in\n"
548              "%"PRIuMAX"+%"PRIuMAX" records out\n"),
549            r_full, r_partial, w_full, w_partial);
550
551   if (r_truncate != 0)
552     fprintf (stderr,
553              ngettext ("%"PRIuMAX" truncated record\n",
554                        "%"PRIuMAX" truncated records\n",
555                        select_plural (r_truncate)),
556              r_truncate);
557
558   if (status_flags & STATUS_NOXFER)
559     return;
560
561   /* Use integer arithmetic to compute the transfer rate,
562      since that makes it easy to use SI abbreviations.  */
563
564   fprintf (stderr,
565            ngettext ("%"PRIuMAX" byte (%s) copied",
566                      "%"PRIuMAX" bytes (%s) copied",
567                      select_plural (w_bytes)),
568            w_bytes,
569            human_readable (w_bytes, hbuf, human_opts, 1, 1));
570
571   if (start_time < now)
572     {
573       double XTIME_PRECISIONe0 = XTIME_PRECISION;
574       uintmax_t delta_xtime = now;
575       delta_xtime -= start_time;
576       delta_s = delta_xtime / XTIME_PRECISIONe0;
577       bytes_per_second = human_readable (w_bytes, hbuf, human_opts,
578                                          XTIME_PRECISION, delta_xtime);
579     }
580   else
581     {
582       delta_s = 0;
583       bytes_per_second = _("Infinity B");
584     }
585
586   /* TRANSLATORS: The two instances of "s" in this string are the SI
587      symbol "s" (meaning second), and should not be translated.
588
589      This format used to be:
590
591      ngettext (", %g second, %s/s\n", ", %g seconds, %s/s\n", delta_s == 1)
592
593      but that was incorrect for languages like Polish.  To fix this
594      bug we now use SI symbols even though they're a bit more
595      confusing in English.  */
596   fprintf (stderr, _(", %g s, %s/s\n"), delta_s, bytes_per_second);
597 }
598
599 static void
600 cleanup (void)
601 {
602   if (close (STDIN_FILENO) < 0)
603     error (EXIT_FAILURE, errno,
604            _("closing input file %s"), quote (input_file));
605
606   /* Don't remove this call to close, even though close_stdout
607      closes standard output.  This close is necessary when cleanup
608      is called as part of a signal handler.  */
609   if (close (STDOUT_FILENO) < 0)
610     error (EXIT_FAILURE, errno,
611            _("closing output file %s"), quote (output_file));
612 }
613
614 static inline void ATTRIBUTE_NORETURN
615 quit (int code)
616 {
617   cleanup ();
618   print_stats ();
619   process_signals ();
620   exit (code);
621 }
622
623 /* An ordinary signal was received; arrange for the program to exit.  */
624
625 static void
626 interrupt_handler (int sig)
627 {
628   if (! SA_RESETHAND)
629     signal (sig, SIG_DFL);
630   interrupt_signal = sig;
631 }
632
633 /* An info signal was received; arrange for the program to print status.  */
634
635 static void
636 siginfo_handler (int sig)
637 {
638   if (! SA_NOCLDSTOP)
639     signal (sig, siginfo_handler);
640   info_signal_count++;
641 }
642
643 /* Install the signal handlers.  */
644
645 static void
646 install_signal_handlers (void)
647 {
648   bool catch_siginfo = ! (SIGINFO == SIGUSR1 && getenv ("POSIXLY_CORRECT"));
649
650 #if SA_NOCLDSTOP
651
652   struct sigaction act;
653   sigemptyset (&caught_signals);
654   if (catch_siginfo)
655     {
656       sigaction (SIGINFO, NULL, &act);
657       if (act.sa_handler != SIG_IGN)
658         sigaddset (&caught_signals, SIGINFO);
659     }
660   sigaction (SIGINT, NULL, &act);
661   if (act.sa_handler != SIG_IGN)
662     sigaddset (&caught_signals, SIGINT);
663   act.sa_mask = caught_signals;
664
665   if (sigismember (&caught_signals, SIGINFO))
666     {
667       act.sa_handler = siginfo_handler;
668       act.sa_flags = 0;
669       sigaction (SIGINFO, &act, NULL);
670     }
671
672   if (sigismember (&caught_signals, SIGINT))
673     {
674       /* POSIX 1003.1-2001 says SA_RESETHAND implies SA_NODEFER,
675          but this is not true on Solaris 8 at least.  It doesn't
676          hurt to use SA_NODEFER here, so leave it in.  */
677       act.sa_handler = interrupt_handler;
678       act.sa_flags = SA_NODEFER | SA_RESETHAND;
679       sigaction (SIGINT, &act, NULL);
680     }
681
682 #else
683
684   if (catch_siginfo && signal (SIGINFO, SIG_IGN) != SIG_IGN)
685     {
686       signal (SIGINFO, siginfo_handler);
687       siginterrupt (SIGINFO, 1);
688     }
689   if (signal (SIGINT, SIG_IGN) != SIG_IGN)
690     {
691       signal (SIGINT, interrupt_handler);
692       siginterrupt (SIGINT, 1);
693     }
694 #endif
695 }
696
697 /* Process any pending signals.  If signals are caught, this function
698    should be called periodically.  Ideally there should never be an
699    unbounded amount of time when signals are not being processed.  */
700
701 static void
702 process_signals (void)
703 {
704   while (interrupt_signal | info_signal_count)
705     {
706       int interrupt;
707       int infos;
708       sigset_t oldset;
709
710       sigprocmask (SIG_BLOCK, &caught_signals, &oldset);
711
712       /* Reload interrupt_signal and info_signal_count, in case a new
713          signal was handled before sigprocmask took effect.  */
714       interrupt = interrupt_signal;
715       infos = info_signal_count;
716
717       if (infos)
718         info_signal_count = infos - 1;
719
720       sigprocmask (SIG_SETMASK, &oldset, NULL);
721
722       if (interrupt)
723         cleanup ();
724       print_stats ();
725       if (interrupt)
726         raise (interrupt);
727     }
728 }
729
730 /* Read from FD into the buffer BUF of size SIZE, processing any
731    signals that arrive before bytes are read.  Return the number of
732    bytes read if successful, -1 (setting errno) on failure.  */
733
734 static ssize_t
735 iread (int fd, char *buf, size_t size)
736 {
737   for (;;)
738     {
739       ssize_t nread;
740       process_signals ();
741       nread = read (fd, buf, size);
742       if (! (nread < 0 && errno == EINTR))
743         return nread;
744     }
745 }
746
747 /* Write to FD the buffer BUF of size SIZE, processing any signals
748    that arrive.  Return the number of bytes written, setting errno if
749    this is less than SIZE.  Keep trying if there are partial
750    writes.  */
751
752 static size_t
753 iwrite (int fd, char const *buf, size_t size)
754 {
755   size_t total_written = 0;
756
757   while (total_written < size)
758     {
759       ssize_t nwritten;
760       process_signals ();
761       nwritten = write (fd, buf + total_written, size - total_written);
762       if (nwritten < 0)
763         {
764           if (errno != EINTR)
765             break;
766         }
767       else if (nwritten == 0)
768         {
769           /* Some buggy drivers return 0 when one tries to write beyond
770              a device's end.  (Example: Linux 1.2.13 on /dev/fd0.)
771              Set errno to ENOSPC so they get a sensible diagnostic.  */
772           errno = ENOSPC;
773           break;
774         }
775       else
776         total_written += nwritten;
777     }
778
779   return total_written;
780 }
781
782 /* Write, then empty, the output buffer `obuf'. */
783
784 static void
785 write_output (void)
786 {
787   size_t nwritten = iwrite (STDOUT_FILENO, obuf, output_blocksize);
788   w_bytes += nwritten;
789   if (nwritten != output_blocksize)
790     {
791       error (0, errno, _("writing to %s"), quote (output_file));
792       if (nwritten != 0)
793         w_partial++;
794       quit (EXIT_FAILURE);
795     }
796   else
797     w_full++;
798   oc = 0;
799 }
800
801 /* Interpret one "conv=..." or similar operand STR according to the
802    symbols in TABLE, returning the flags specified.  If the operand
803    cannot be parsed, use ERROR_MSGID to generate a diagnostic.
804    As a by product, this function replaces each `,' in STR with a NUL byte.  */
805
806 static int
807 parse_symbols (char *str, struct symbol_value const *table,
808                char const *error_msgid)
809 {
810   int value = 0;
811
812   do
813     {
814       struct symbol_value const *entry;
815       char *new = strchr (str, ',');
816       if (new != NULL)
817         *new++ = '\0';
818       for (entry = table; ; entry++)
819         {
820           if (! entry->symbol[0])
821             {
822               error (0, 0, _(error_msgid), quote (str));
823               usage (EXIT_FAILURE);
824             }
825           if (STREQ (entry->symbol, str))
826             {
827               if (! entry->value)
828                 error (EXIT_FAILURE, 0, _(error_msgid), quote (str));
829               value |= entry->value;
830               break;
831             }
832         }
833       str = new;
834     }
835   while (str);
836
837   return value;
838 }
839
840 /* Return the value of STR, interpreted as a non-negative decimal integer,
841    optionally multiplied by various values.
842    Set *INVALID if STR does not represent a number in this format.  */
843
844 static uintmax_t
845 parse_integer (const char *str, bool *invalid)
846 {
847   uintmax_t n;
848   char *suffix;
849   enum strtol_error e = xstrtoumax (str, &suffix, 10, &n, "bcEGkKMPTwYZ0");
850
851   if (e == LONGINT_INVALID_SUFFIX_CHAR && *suffix == 'x')
852     {
853       uintmax_t multiplier = parse_integer (suffix + 1, invalid);
854
855       if (multiplier != 0 && n * multiplier / multiplier != n)
856         {
857           *invalid = true;
858           return 0;
859         }
860
861       n *= multiplier;
862     }
863   else if (e != LONGINT_OK)
864     {
865       *invalid = true;
866       return 0;
867     }
868
869   return n;
870 }
871
872 static void
873 scanargs (int argc, char **argv)
874 {
875   int i;
876   size_t blocksize = 0;
877
878   for (i = optind; i < argc; i++)
879     {
880       char *name, *val;
881
882       name = argv[i];
883       val = strchr (name, '=');
884       if (val == NULL)
885         {
886           error (0, 0, _("unrecognized operand %s"), quote (name));
887           usage (EXIT_FAILURE);
888         }
889       *val++ = '\0';
890
891       if (STREQ (name, "if"))
892         input_file = val;
893       else if (STREQ (name, "of"))
894         output_file = val;
895       else if (STREQ (name, "conv"))
896         conversions_mask |= parse_symbols (val, conversions,
897                                            N_("invalid conversion: %s"));
898       else if (STREQ (name, "iflag"))
899         input_flags |= parse_symbols (val, flags,
900                                       N_("invalid input flag: %s"));
901       else if (STREQ (name, "oflag"))
902         output_flags |= parse_symbols (val, flags,
903                                        N_("invalid output flag: %s"));
904       else if (STREQ (name, "status"))
905         status_flags |= parse_symbols (val, statuses,
906                                        N_("invalid status flag: %s"));
907       else
908         {
909           bool invalid = false;
910           uintmax_t n = parse_integer (val, &invalid);
911
912           if (STREQ (name, "ibs"))
913             {
914               invalid |= ! (0 < n && n <= MAX_BLOCKSIZE (INPUT_BLOCK_SLOP));
915               input_blocksize = n;
916               conversions_mask |= C_TWOBUFS;
917             }
918           else if (STREQ (name, "obs"))
919             {
920               invalid |= ! (0 < n && n <= MAX_BLOCKSIZE (OUTPUT_BLOCK_SLOP));
921               output_blocksize = n;
922               conversions_mask |= C_TWOBUFS;
923             }
924           else if (STREQ (name, "bs"))
925             {
926               invalid |= ! (0 < n && n <= MAX_BLOCKSIZE (INPUT_BLOCK_SLOP));
927               blocksize = n;
928             }
929           else if (STREQ (name, "cbs"))
930             {
931               invalid |= ! (0 < n && n <= SIZE_MAX);
932               conversion_blocksize = n;
933             }
934           else if (STREQ (name, "skip"))
935             skip_records = n;
936           else if (STREQ (name, "seek"))
937             seek_records = n;
938           else if (STREQ (name, "count"))
939             max_records = n;
940           else
941             {
942               error (0, 0, _("unrecognized operand %s=%s"),
943                      quote_n (0, name), quote_n (1, val));
944               usage (EXIT_FAILURE);
945             }
946
947           if (invalid)
948             error (EXIT_FAILURE, 0, _("invalid number %s"), quote (val));
949         }
950     }
951
952   if (blocksize)
953     input_blocksize = output_blocksize = blocksize;
954
955   /* If bs= was given, both `input_blocksize' and `output_blocksize' will
956      have been set to positive values.  If either has not been set,
957      bs= was not given, so make sure two buffers are used. */
958   if (input_blocksize == 0 || output_blocksize == 0)
959     conversions_mask |= C_TWOBUFS;
960   if (input_blocksize == 0)
961     input_blocksize = DEFAULT_BLOCKSIZE;
962   if (output_blocksize == 0)
963     output_blocksize = DEFAULT_BLOCKSIZE;
964   if (conversion_blocksize == 0)
965     conversions_mask &= ~(C_BLOCK | C_UNBLOCK);
966
967   if (input_flags & (O_DSYNC | O_SYNC))
968     input_flags |= O_RSYNC;
969
970   if (multiple_bits_set (conversions_mask & (C_ASCII | C_EBCDIC | C_IBM)))
971     error (EXIT_FAILURE, 0, _("cannot combine any two of {ascii,ebcdic,ibm}"));
972   if (multiple_bits_set (conversions_mask & (C_BLOCK | C_UNBLOCK)))
973     error (EXIT_FAILURE, 0, _("cannot combine block and unblock"));
974   if (multiple_bits_set (conversions_mask & (C_LCASE | C_UCASE)))
975     error (EXIT_FAILURE, 0, _("cannot combine lcase and ucase"));
976   if (multiple_bits_set (conversions_mask & (C_EXCL | C_NOCREAT)))
977     error (EXIT_FAILURE, 0, _("cannot combine excl and nocreat"));
978 }
979
980 /* Fix up translation table. */
981
982 static void
983 apply_translations (void)
984 {
985   int i;
986
987   if (conversions_mask & C_ASCII)
988     translate_charset (ebcdic_to_ascii);
989
990   if (conversions_mask & C_UCASE)
991     {
992       for (i = 0; i < 256; i++)
993         trans_table[i] = toupper (trans_table[i]);
994       translation_needed = true;
995     }
996   else if (conversions_mask & C_LCASE)
997     {
998       for (i = 0; i < 256; i++)
999         trans_table[i] = tolower (trans_table[i]);
1000       translation_needed = true;
1001     }
1002
1003   if (conversions_mask & C_EBCDIC)
1004     {
1005       translate_charset (ascii_to_ebcdic);
1006       newline_character = ascii_to_ebcdic['\n'];
1007       space_character = ascii_to_ebcdic[' '];
1008     }
1009   else if (conversions_mask & C_IBM)
1010     {
1011       translate_charset (ascii_to_ibm);
1012       newline_character = ascii_to_ibm['\n'];
1013       space_character = ascii_to_ibm[' '];
1014     }
1015 }
1016
1017 /* Apply the character-set translations specified by the user
1018    to the NREAD bytes in BUF.  */
1019
1020 static void
1021 translate_buffer (char *buf, size_t nread)
1022 {
1023   char *cp;
1024   size_t i;
1025
1026   for (i = nread, cp = buf; i; i--, cp++)
1027     *cp = trans_table[to_uchar (*cp)];
1028 }
1029
1030 /* If true, the last char from the previous call to `swab_buffer'
1031    is saved in `saved_char'.  */
1032 static bool char_is_saved = false;
1033
1034 /* Odd char from previous call.  */
1035 static char saved_char;
1036
1037 /* Swap NREAD bytes in BUF, plus possibly an initial char from the
1038    previous call.  If NREAD is odd, save the last char for the
1039    next call.   Return the new start of the BUF buffer.  */
1040
1041 static char *
1042 swab_buffer (char *buf, size_t *nread)
1043 {
1044   char *bufstart = buf;
1045   char *cp;
1046   size_t i;
1047
1048   /* Is a char left from last time?  */
1049   if (char_is_saved)
1050     {
1051       *--bufstart = saved_char;
1052       (*nread)++;
1053       char_is_saved = false;
1054     }
1055
1056   if (*nread & 1)
1057     {
1058       /* An odd number of chars are in the buffer.  */
1059       saved_char = bufstart[--*nread];
1060       char_is_saved = true;
1061     }
1062
1063   /* Do the byte-swapping by moving every second character two
1064      positions toward the end, working from the end of the buffer
1065      toward the beginning.  This way we only move half of the data.  */
1066
1067   cp = bufstart + *nread;       /* Start one char past the last.  */
1068   for (i = *nread / 2; i; i--, cp -= 2)
1069     *cp = *(cp - 2);
1070
1071   return ++bufstart;
1072 }
1073
1074 /* Add OFFSET to the input offset, setting the overflow flag if
1075    necessary.  */
1076
1077 static void
1078 advance_input_offset (uintmax_t offset)
1079 {
1080   input_offset += offset;
1081   if (input_offset < offset)
1082     input_offset_overflow = true;
1083 }
1084
1085 /* This is a wrapper for lseek.  It detects and warns about a kernel
1086    bug that makes lseek a no-op for tape devices, even though the kernel
1087    lseek return value suggests that the function succeeded.
1088
1089    The parameters are the same as those of the lseek function, but
1090    with the addition of FILENAME, the name of the file associated with
1091    descriptor FDESC.  The file name is used solely in the warning that's
1092    printed when the bug is detected.  Return the same value that lseek
1093    would have returned, but when the lseek bug is detected, return -1
1094    to indicate that lseek failed.
1095
1096    The offending behavior has been confirmed with an Exabyte SCSI tape
1097    drive accessed via /dev/nst0 on both Linux-2.2.17 and Linux-2.4.16.  */
1098
1099 #ifdef __linux__
1100
1101 # include <sys/mtio.h>
1102
1103 # define MT_SAME_POSITION(P, Q) \
1104    ((P).mt_resid == (Q).mt_resid \
1105     && (P).mt_fileno == (Q).mt_fileno \
1106     && (P).mt_blkno == (Q).mt_blkno)
1107
1108 static off_t
1109 skip_via_lseek (char const *filename, int fdesc, off_t offset, int whence)
1110 {
1111   struct mtget s1;
1112   struct mtget s2;
1113   bool got_original_tape_position = (ioctl (fdesc, MTIOCGET, &s1) == 0);
1114   /* known bad device type */
1115   /* && s.mt_type == MT_ISSCSI2 */
1116
1117   off_t new_position = lseek (fdesc, offset, whence);
1118   if (0 <= new_position
1119       && got_original_tape_position
1120       && ioctl (fdesc, MTIOCGET, &s2) == 0
1121       && MT_SAME_POSITION (s1, s2))
1122     {
1123       error (0, 0, _("warning: working around lseek kernel bug for file (%s)\n\
1124   of mt_type=0x%0lx -- see <sys/mtio.h> for the list of types"),
1125              filename, s2.mt_type);
1126       errno = 0;
1127       new_position = -1;
1128     }
1129
1130   return new_position;
1131 }
1132 #else
1133 # define skip_via_lseek(Filename, Fd, Offset, Whence) lseek (Fd, Offset, Whence)
1134 #endif
1135
1136 /* Throw away RECORDS blocks of BLOCKSIZE bytes on file descriptor FDESC,
1137    which is open with read permission for FILE.  Store up to BLOCKSIZE
1138    bytes of the data at a time in BUF, if necessary.  RECORDS must be
1139    nonzero.  If fdesc is STDIN_FILENO, advance the input offset.
1140    Return the number of records remaining, i.e., that were not skipped
1141    because EOF was reached.  */
1142
1143 static uintmax_t
1144 skip (int fdesc, char const *file, uintmax_t records, size_t blocksize,
1145       char *buf)
1146 {
1147   uintmax_t offset = records * blocksize;
1148
1149   /* Try lseek and if an error indicates it was an inappropriate operation --
1150      or if the file offset is not representable as an off_t --
1151      fall back on using read.  */
1152
1153   errno = 0;
1154   if (records <= OFF_T_MAX / blocksize
1155       && 0 <= skip_via_lseek (file, fdesc, offset, SEEK_CUR))
1156     {
1157       if (fdesc == STDIN_FILENO)
1158         advance_input_offset (offset);
1159       return 0;
1160     }
1161   else
1162     {
1163       int lseek_errno = errno;
1164
1165       do
1166         {
1167           ssize_t nread = iread (fdesc, buf, blocksize);
1168           if (nread < 0)
1169             {
1170               if (fdesc == STDIN_FILENO)
1171                 {
1172                   error (0, errno, _("reading %s"), quote (file));
1173                   if (conversions_mask & C_NOERROR)
1174                     {
1175                       print_stats ();
1176                       continue;
1177                     }
1178                 }
1179               else
1180                 error (0, lseek_errno, _("%s: cannot seek"), quote (file));
1181               quit (EXIT_FAILURE);
1182             }
1183
1184           if (nread == 0)
1185             break;
1186           if (fdesc == STDIN_FILENO)
1187             advance_input_offset (nread);
1188         }
1189       while (--records != 0);
1190
1191       return records;
1192     }
1193 }
1194
1195 /* Advance the input by NBYTES if possible, after a read error.
1196    The input file offset may or may not have advanced after the failed
1197    read; adjust it to point just after the bad record regardless.
1198    Return true if successful, or if the input is already known to not
1199    be seekable.  */
1200
1201 static bool
1202 advance_input_after_read_error (size_t nbytes)
1203 {
1204   if (! input_seekable)
1205     {
1206       if (input_seek_errno == ESPIPE)
1207         return true;
1208       errno = input_seek_errno;
1209     }
1210   else
1211     {
1212       off_t offset;
1213       advance_input_offset (nbytes);
1214       input_offset_overflow |= (OFF_T_MAX < input_offset);
1215       if (input_offset_overflow)
1216         {
1217           error (0, 0, _("offset overflow while reading file %s"),
1218                  quote (input_file));
1219           return false;
1220         }
1221       offset = lseek (STDIN_FILENO, 0, SEEK_CUR);
1222       if (0 <= offset)
1223         {
1224           off_t diff;
1225           if (offset == input_offset)
1226             return true;
1227           diff = input_offset - offset;
1228           if (! (0 <= diff && diff <= nbytes))
1229             error (0, 0, _("warning: invalid file offset after failed read"));
1230           if (0 <= skip_via_lseek (input_file, STDIN_FILENO, diff, SEEK_CUR))
1231             return true;
1232           if (errno == 0)
1233             error (0, 0, _("cannot work around kernel bug after all"));
1234         }
1235     }
1236
1237   error (0, errno, _("%s: cannot seek"), quote (input_file));
1238   return false;
1239 }
1240
1241 /* Copy NREAD bytes of BUF, with no conversions.  */
1242
1243 static void
1244 copy_simple (char const *buf, size_t nread)
1245 {
1246   const char *start = buf;      /* First uncopied char in BUF.  */
1247
1248   do
1249     {
1250       size_t nfree = MIN (nread, output_blocksize - oc);
1251
1252       memcpy (obuf + oc, start, nfree);
1253
1254       nread -= nfree;           /* Update the number of bytes left to copy. */
1255       start += nfree;
1256       oc += nfree;
1257       if (oc >= output_blocksize)
1258         write_output ();
1259     }
1260   while (nread != 0);
1261 }
1262
1263 /* Copy NREAD bytes of BUF, doing conv=block
1264    (pad newline-terminated records to `conversion_blocksize',
1265    replacing the newline with trailing spaces).  */
1266
1267 static void
1268 copy_with_block (char const *buf, size_t nread)
1269 {
1270   size_t i;
1271
1272   for (i = nread; i; i--, buf++)
1273     {
1274       if (*buf == newline_character)
1275         {
1276           if (col < conversion_blocksize)
1277             {
1278               size_t j;
1279               for (j = col; j < conversion_blocksize; j++)
1280                 output_char (space_character);
1281             }
1282           col = 0;
1283         }
1284       else
1285         {
1286           if (col == conversion_blocksize)
1287             r_truncate++;
1288           else if (col < conversion_blocksize)
1289             output_char (*buf);
1290           col++;
1291         }
1292     }
1293 }
1294
1295 /* Copy NREAD bytes of BUF, doing conv=unblock
1296    (replace trailing spaces in `conversion_blocksize'-sized records
1297    with a newline).  */
1298
1299 static void
1300 copy_with_unblock (char const *buf, size_t nread)
1301 {
1302   size_t i;
1303   char c;
1304   static size_t pending_spaces = 0;
1305
1306   for (i = 0; i < nread; i++)
1307     {
1308       c = buf[i];
1309
1310       if (col++ >= conversion_blocksize)
1311         {
1312           col = pending_spaces = 0; /* Wipe out any pending spaces.  */
1313           i--;                  /* Push the char back; get it later. */
1314           output_char (newline_character);
1315         }
1316       else if (c == space_character)
1317         pending_spaces++;
1318       else
1319         {
1320           /* `c' is the character after a run of spaces that were not
1321              at the end of the conversion buffer.  Output them.  */
1322           while (pending_spaces)
1323             {
1324               output_char (space_character);
1325               --pending_spaces;
1326             }
1327           output_char (c);
1328         }
1329     }
1330 }
1331
1332 /* Set the file descriptor flags for FD that correspond to the nonzero bits
1333    in ADD_FLAGS.  The file's name is NAME.  */
1334
1335 static void
1336 set_fd_flags (int fd, int add_flags, char const *name)
1337 {
1338   /* Ignore file creation flags that are no-ops on file descriptors.  */
1339   add_flags &= ~ (O_NOCTTY | O_NOFOLLOW);
1340
1341   if (add_flags)
1342     {
1343       int old_flags = fcntl (fd, F_GETFL);
1344       int new_flags = old_flags | add_flags;
1345       bool ok = true;
1346       if (old_flags < 0)
1347         ok = false;
1348       else if (old_flags != new_flags)
1349         {
1350           if (new_flags & (O_DIRECTORY | O_NOLINKS))
1351             {
1352               /* NEW_FLAGS contains at least one file creation flag that
1353                  requires some checking of the open file descriptor.  */
1354               struct stat st;
1355               if (fstat (fd, &st) != 0)
1356                 ok = false;
1357               else if ((new_flags & O_DIRECTORY) && ! S_ISDIR (st.st_mode))
1358                 {
1359                   errno = ENOTDIR;
1360                   ok = false;
1361                 }
1362               else if ((new_flags & O_NOLINKS) && 1 < st.st_nlink)
1363                 {
1364                   errno = EMLINK;
1365                   ok = false;
1366                 }
1367               new_flags &= ~ (O_DIRECTORY | O_NOLINKS);
1368             }
1369
1370           if (ok && old_flags != new_flags
1371               && fcntl (fd, F_SETFL, new_flags) == -1)
1372             ok = false;
1373         }
1374
1375       if (!ok)
1376         error (EXIT_FAILURE, errno, _("setting flags for %s"), quote (name));
1377     }
1378 }
1379
1380 /* The main loop.  */
1381
1382 static int
1383 dd_copy (void)
1384 {
1385   char *ibuf, *bufstart;        /* Input buffer. */
1386   /* These are declared static so that even though we don't free the
1387      buffers, valgrind will recognize that there is no "real" leak.  */
1388   static char *real_buf;        /* real buffer address before alignment */
1389   static char *real_obuf;
1390   ssize_t nread;                /* Bytes read in the current block.  */
1391
1392   /* If nonzero, then the previously read block was partial and
1393      PARTREAD was its size.  */
1394   size_t partread = 0;
1395
1396   int exit_status = EXIT_SUCCESS;
1397   size_t n_bytes_read;
1398
1399   /* Leave at least one extra byte at the beginning and end of `ibuf'
1400      for conv=swab, but keep the buffer address even.  But some peculiar
1401      device drivers work only with word-aligned buffers, so leave an
1402      extra two bytes.  */
1403
1404   /* Some devices require alignment on a sector or page boundary
1405      (e.g. character disk devices).  Align the input buffer to a
1406      page boundary to cover all bases.  Note that due to the swab
1407      algorithm, we must have at least one byte in the page before
1408      the input buffer;  thus we allocate 2 pages of slop in the
1409      real buffer.  8k above the blocksize shouldn't bother anyone.
1410
1411      The page alignment is necessary on any linux system that supports
1412      either the SGI raw I/O patch or Steven Tweedies raw I/O patch.
1413      It is necessary when accessing raw (i.e. character special) disk
1414      devices on Unixware or other SVR4-derived system.  */
1415
1416   real_buf = xmalloc (input_blocksize + INPUT_BLOCK_SLOP);
1417   ibuf = real_buf;
1418   ibuf += SWAB_ALIGN_OFFSET;    /* allow space for swab */
1419
1420   ibuf = ptr_align (ibuf, page_size);
1421
1422   if (conversions_mask & C_TWOBUFS)
1423     {
1424       /* Page-align the output buffer, too.  */
1425       real_obuf = xmalloc (output_blocksize + OUTPUT_BLOCK_SLOP);
1426       obuf = ptr_align (real_obuf, page_size);
1427     }
1428   else
1429     {
1430       real_obuf = NULL;
1431       obuf = ibuf;
1432     }
1433
1434   if (skip_records != 0)
1435     {
1436       skip (STDIN_FILENO, input_file, skip_records, input_blocksize, ibuf);
1437       /* POSIX doesn't say what to do when dd detects it has been
1438          asked to skip past EOF, so I assume it's non-fatal if the
1439          call to 'skip' returns nonzero.  FIXME: maybe give a warning.  */
1440     }
1441
1442   if (seek_records != 0)
1443     {
1444       uintmax_t write_records = skip (STDOUT_FILENO, output_file,
1445                                       seek_records, output_blocksize, obuf);
1446
1447       if (write_records != 0)
1448         {
1449           memset (obuf, 0, output_blocksize);
1450
1451           do
1452             if (iwrite (STDOUT_FILENO, obuf, output_blocksize)
1453                 != output_blocksize)
1454               {
1455                 error (0, errno, _("writing to %s"), quote (output_file));
1456                 quit (EXIT_FAILURE);
1457               }
1458           while (--write_records != 0);
1459         }
1460     }
1461
1462   if (max_records == 0)
1463     return exit_status;
1464
1465   while (1)
1466     {
1467       if (r_partial + r_full >= max_records)
1468         break;
1469
1470       /* Zero the buffer before reading, so that if we get a read error,
1471          whatever data we are able to read is followed by zeros.
1472          This minimizes data loss. */
1473       if ((conversions_mask & C_SYNC) && (conversions_mask & C_NOERROR))
1474         memset (ibuf,
1475                 (conversions_mask & (C_BLOCK | C_UNBLOCK)) ? ' ' : '\0',
1476                 input_blocksize);
1477
1478       nread = iread (STDIN_FILENO, ibuf, input_blocksize);
1479
1480       if (nread == 0)
1481         break;                  /* EOF.  */
1482
1483       if (nread < 0)
1484         {
1485           error (0, errno, _("reading %s"), quote (input_file));
1486           if (conversions_mask & C_NOERROR)
1487             {
1488               print_stats ();
1489               /* Seek past the bad block if possible. */
1490               if (!advance_input_after_read_error (input_blocksize - partread))
1491                 {
1492                   exit_status = EXIT_FAILURE;
1493
1494                   /* Suppress duplicate diagnostics.  */
1495                   input_seekable = false;
1496                   input_seek_errno = ESPIPE;
1497                 }
1498               if ((conversions_mask & C_SYNC) && !partread)
1499                 /* Replace the missing input with null bytes and
1500                    proceed normally.  */
1501                 nread = 0;
1502               else
1503                 continue;
1504             }
1505           else
1506             {
1507               /* Write any partial block. */
1508               exit_status = EXIT_FAILURE;
1509               break;
1510             }
1511         }
1512
1513       n_bytes_read = nread;
1514       advance_input_offset (nread);
1515
1516       if (n_bytes_read < input_blocksize)
1517         {
1518           r_partial++;
1519           partread = n_bytes_read;
1520           if (conversions_mask & C_SYNC)
1521             {
1522               if (!(conversions_mask & C_NOERROR))
1523                 /* If C_NOERROR, we zeroed the block before reading. */
1524                 memset (ibuf + n_bytes_read,
1525                         (conversions_mask & (C_BLOCK | C_UNBLOCK)) ? ' ' : '\0',
1526                         input_blocksize - n_bytes_read);
1527               n_bytes_read = input_blocksize;
1528             }
1529         }
1530       else
1531         {
1532           r_full++;
1533           partread = 0;
1534         }
1535
1536       if (ibuf == obuf)         /* If not C_TWOBUFS. */
1537         {
1538           size_t nwritten = iwrite (STDOUT_FILENO, obuf, n_bytes_read);
1539           w_bytes += nwritten;
1540           if (nwritten != n_bytes_read)
1541             {
1542               error (0, errno, _("writing %s"), quote (output_file));
1543               return EXIT_FAILURE;
1544             }
1545           else if (n_bytes_read == input_blocksize)
1546             w_full++;
1547           else
1548             w_partial++;
1549           continue;
1550         }
1551
1552       /* Do any translations on the whole buffer at once.  */
1553
1554       if (translation_needed)
1555         translate_buffer (ibuf, n_bytes_read);
1556
1557       if (conversions_mask & C_SWAB)
1558         bufstart = swab_buffer (ibuf, &n_bytes_read);
1559       else
1560         bufstart = ibuf;
1561
1562       if (conversions_mask & C_BLOCK)
1563         copy_with_block (bufstart, n_bytes_read);
1564       else if (conversions_mask & C_UNBLOCK)
1565         copy_with_unblock (bufstart, n_bytes_read);
1566       else
1567         copy_simple (bufstart, n_bytes_read);
1568     }
1569
1570   /* If we have a char left as a result of conv=swab, output it.  */
1571   if (char_is_saved)
1572     {
1573       if (conversions_mask & C_BLOCK)
1574         copy_with_block (&saved_char, 1);
1575       else if (conversions_mask & C_UNBLOCK)
1576         copy_with_unblock (&saved_char, 1);
1577       else
1578         output_char (saved_char);
1579     }
1580
1581   if ((conversions_mask & C_BLOCK) && col > 0)
1582     {
1583       /* If the final input line didn't end with a '\n', pad
1584          the output block to `conversion_blocksize' chars.  */
1585       size_t i;
1586       for (i = col; i < conversion_blocksize; i++)
1587         output_char (space_character);
1588     }
1589
1590   if ((conversions_mask & C_UNBLOCK) && col == conversion_blocksize)
1591     /* Add a final '\n' if there are exactly `conversion_blocksize'
1592        characters in the final record. */
1593     output_char (newline_character);
1594
1595   /* Write out the last block. */
1596   if (oc != 0)
1597     {
1598       size_t nwritten = iwrite (STDOUT_FILENO, obuf, oc);
1599       w_bytes += nwritten;
1600       if (nwritten != 0)
1601         w_partial++;
1602       if (nwritten != oc)
1603         {
1604           error (0, errno, _("writing %s"), quote (output_file));
1605           return EXIT_FAILURE;
1606         }
1607     }
1608
1609   if ((conversions_mask & C_FDATASYNC) && fdatasync (STDOUT_FILENO) != 0)
1610     {
1611       if (errno != ENOSYS && errno != EINVAL)
1612         {
1613           error (0, errno, _("fdatasync failed for %s"), quote (output_file));
1614           exit_status = EXIT_FAILURE;
1615         }
1616       conversions_mask |= C_FSYNC;
1617     }
1618
1619   if (conversions_mask & C_FSYNC)
1620     while (fsync (STDOUT_FILENO) != 0)
1621       if (errno != EINTR)
1622         {
1623           error (0, errno, _("fsync failed for %s"), quote (output_file));
1624           return EXIT_FAILURE;
1625         }
1626
1627   return exit_status;
1628 }
1629
1630 int
1631 main (int argc, char **argv)
1632 {
1633   int i;
1634   int exit_status;
1635   off_t offset;
1636
1637   initialize_main (&argc, &argv);
1638   program_name = argv[0];
1639   setlocale (LC_ALL, "");
1640   bindtextdomain (PACKAGE, LOCALEDIR);
1641   textdomain (PACKAGE);
1642
1643   /* Arrange to close stdout if parse_long_options exits.  */
1644   atexit (close_stdout);
1645
1646   page_size = getpagesize ();
1647
1648   parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE, VERSION,
1649                       usage, AUTHORS, (char const *) NULL);
1650   if (getopt_long (argc, argv, "", NULL, NULL) != -1)
1651     usage (EXIT_FAILURE);
1652
1653   /* Initialize translation table to identity translation. */
1654   for (i = 0; i < 256; i++)
1655     trans_table[i] = i;
1656
1657   /* Decode arguments. */
1658   scanargs (argc, argv);
1659
1660   apply_translations ();
1661
1662   if (input_file == NULL)
1663     {
1664       input_file = _("standard input");
1665       set_fd_flags (STDIN_FILENO, input_flags, input_file);
1666     }
1667   else
1668     {
1669       if (fd_reopen (STDIN_FILENO, input_file, O_RDONLY | input_flags, 0) < 0)
1670         error (EXIT_FAILURE, errno, _("opening %s"), quote (input_file));
1671     }
1672
1673   offset = lseek (STDIN_FILENO, 0, SEEK_CUR);
1674   input_seekable = (0 <= offset);
1675   input_offset = offset;
1676   input_seek_errno = errno;
1677
1678   if (output_file == NULL)
1679     {
1680       output_file = _("standard output");
1681       set_fd_flags (STDOUT_FILENO, output_flags, output_file);
1682     }
1683   else
1684     {
1685       mode_t perms = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
1686       int opts
1687         = (output_flags
1688            | (conversions_mask & C_NOCREAT ? 0 : O_CREAT)
1689            | (conversions_mask & C_EXCL ? O_EXCL : 0)
1690            | (seek_records || (conversions_mask & C_NOTRUNC) ? 0 : O_TRUNC));
1691
1692       /* Open the output file with *read* access only if we might
1693          need to read to satisfy a `seek=' request.  If we can't read
1694          the file, go ahead with write-only access; it might work.  */
1695       if ((! seek_records
1696            || fd_reopen (STDOUT_FILENO, output_file, O_RDWR | opts, perms) < 0)
1697           && (fd_reopen (STDOUT_FILENO, output_file, O_WRONLY | opts, perms)
1698               < 0))
1699         error (EXIT_FAILURE, errno, _("opening %s"), quote (output_file));
1700
1701 #if HAVE_FTRUNCATE
1702       if (seek_records != 0 && !(conversions_mask & C_NOTRUNC))
1703         {
1704           uintmax_t size = seek_records * output_blocksize;
1705           unsigned long int obs = output_blocksize;
1706
1707           if (OFF_T_MAX / output_blocksize < seek_records)
1708             error (EXIT_FAILURE, 0,
1709                    _("offset too large: "
1710                      "cannot truncate to a length of seek=%"PRIuMAX""
1711                      " (%lu-byte) blocks"),
1712                    seek_records, obs);
1713
1714           if (ftruncate (STDOUT_FILENO, size) != 0)
1715             {
1716               /* Complain only when ftruncate fails on a regular file, a
1717                  directory, or a shared memory object, as POSIX 1003.1-2004
1718                  specifies ftruncate's behavior only for these file types.
1719                  For example, do not complain when Linux 2.4 ftruncate
1720                  fails on /dev/fd0.  */
1721               int ftruncate_errno = errno;
1722               struct stat stdout_stat;
1723               if (fstat (STDOUT_FILENO, &stdout_stat) != 0)
1724                 error (EXIT_FAILURE, errno, _("cannot fstat %s"),
1725                        quote (output_file));
1726               if (S_ISREG (stdout_stat.st_mode)
1727                   || S_ISDIR (stdout_stat.st_mode)
1728                   || S_TYPEISSHM (&stdout_stat))
1729                 error (EXIT_FAILURE, ftruncate_errno,
1730                        _("truncating at %"PRIuMAX" bytes in output file %s"),
1731                        size, quote (output_file));
1732             }
1733         }
1734 #endif
1735     }
1736
1737   install_signal_handlers ();
1738
1739   start_time = gethrxtime ();
1740
1741   exit_status = dd_copy ();
1742
1743   quit (exit_status);
1744 }