maint: make update-copyright handle more cases
[coreutils.git] / src / dd.c
blob0028b53e4e1b7a1c12c8408601962df7084b0970
1 /* dd -- convert a file while copying it.
2 Copyright (C) 85, 90, 91, 1995-2009 Free Software Foundation, Inc.
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.
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.
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/>. */
17 /* Written by Paul Rubin, David MacKenzie, and Stuart Kemp. */
19 #include <config.h>
21 #define SWAB_ALIGN_OFFSET 2
23 #include <sys/types.h>
24 #include <signal.h>
25 #include <getopt.h>
27 #include "system.h"
28 #include "error.h"
29 #include "fd-reopen.h"
30 #include "gethrxtime.h"
31 #include "human.h"
32 #include "long-options.h"
33 #include "quote.h"
34 #include "quotearg.h"
35 #include "xstrtol.h"
36 #include "xtime.h"
38 static void process_signals (void);
40 /* The official name of this program (e.g., no `g' prefix). */
41 #define PROGRAM_NAME "dd"
43 #define AUTHORS \
44 proper_name ("Paul Rubin"), \
45 proper_name ("David MacKenzie"), \
46 proper_name ("Stuart Kemp")
48 /* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is
49 present. SA_NODEFER and SA_RESETHAND are XSI extensions. */
50 #ifndef SA_NOCLDSTOP
51 # define SA_NOCLDSTOP 0
52 # define sigprocmask(How, Set, Oset) /* empty */
53 # define sigset_t int
54 # if ! HAVE_SIGINTERRUPT
55 # define siginterrupt(sig, flag) /* empty */
56 # endif
57 #endif
58 #ifndef SA_NODEFER
59 # define SA_NODEFER 0
60 #endif
61 #ifndef SA_RESETHAND
62 # define SA_RESETHAND 0
63 #endif
65 #ifndef SIGINFO
66 # define SIGINFO SIGUSR1
67 #endif
69 /* This may belong in GNULIB's fcntl module instead.
70 Define O_CIO to 0 if it is not supported by this OS. */
71 #ifndef O_CIO
72 # define O_CIO 0
73 #endif
75 #if ! HAVE_FDATASYNC
76 # define fdatasync(fd) (errno = ENOSYS, -1)
77 #endif
79 #define output_char(c) \
80 do \
81 { \
82 obuf[oc++] = (c); \
83 if (oc >= output_blocksize) \
84 write_output (); \
85 } \
86 while (0)
88 /* Default input and output blocksize. */
89 #define DEFAULT_BLOCKSIZE 512
91 /* How many bytes to add to the input and output block sizes before invoking
92 malloc. See dd_copy for details. INPUT_BLOCK_SLOP must be no less than
93 OUTPUT_BLOCK_SLOP. */
94 #define INPUT_BLOCK_SLOP (2 * SWAB_ALIGN_OFFSET + 2 * page_size - 1)
95 #define OUTPUT_BLOCK_SLOP (page_size - 1)
97 /* Maximum blocksize for the given SLOP.
98 Keep it smaller than SIZE_MAX - SLOP, so that we can
99 allocate buffers that size. Keep it smaller than SSIZE_MAX, for
100 the benefit of system calls like "read". And keep it smaller than
101 OFF_T_MAX, for the benefit of the large-offset seek code. */
102 #define MAX_BLOCKSIZE(slop) MIN (SIZE_MAX - (slop), MIN (SSIZE_MAX, OFF_T_MAX))
104 /* Conversions bit masks. */
105 enum
107 C_ASCII = 01,
109 C_EBCDIC = 02,
110 C_IBM = 04,
111 C_BLOCK = 010,
112 C_UNBLOCK = 020,
113 C_LCASE = 040,
114 C_UCASE = 0100,
115 C_SWAB = 0200,
116 C_NOERROR = 0400,
117 C_NOTRUNC = 01000,
118 C_SYNC = 02000,
120 /* Use separate input and output buffers, and combine partial
121 input blocks. */
122 C_TWOBUFS = 04000,
124 C_NOCREAT = 010000,
125 C_EXCL = 020000,
126 C_FDATASYNC = 040000,
127 C_FSYNC = 0100000
130 /* Status bit masks. */
131 enum
133 STATUS_NOXFER = 01
136 /* The name of the input file, or NULL for the standard input. */
137 static char const *input_file = NULL;
139 /* The name of the output file, or NULL for the standard output. */
140 static char const *output_file = NULL;
142 /* The page size on this host. */
143 static size_t page_size;
145 /* The number of bytes in which atomic reads are done. */
146 static size_t input_blocksize = 0;
148 /* The number of bytes in which atomic writes are done. */
149 static size_t output_blocksize = 0;
151 /* Conversion buffer size, in bytes. 0 prevents conversions. */
152 static size_t conversion_blocksize = 0;
154 /* Skip this many records of `input_blocksize' bytes before input. */
155 static uintmax_t skip_records = 0;
157 /* Skip this many records of `output_blocksize' bytes before output. */
158 static uintmax_t seek_records = 0;
160 /* Copy only this many records. The default is effectively infinity. */
161 static uintmax_t max_records = (uintmax_t) -1;
163 /* Bit vector of conversions to apply. */
164 static int conversions_mask = 0;
166 /* Open flags for the input and output files. */
167 static int input_flags = 0;
168 static int output_flags = 0;
170 /* Status flags for what is printed to stderr. */
171 static int status_flags = 0;
173 /* If nonzero, filter characters through the translation table. */
174 static bool translation_needed = false;
176 /* Number of partial blocks written. */
177 static uintmax_t w_partial = 0;
179 /* Number of full blocks written. */
180 static uintmax_t w_full = 0;
182 /* Number of partial blocks read. */
183 static uintmax_t r_partial = 0;
185 /* Number of full blocks read. */
186 static uintmax_t r_full = 0;
188 /* Number of bytes written. */
189 static uintmax_t w_bytes = 0;
191 /* Time that dd started. */
192 static xtime_t start_time;
194 /* True if input is seekable. */
195 static bool input_seekable;
197 /* Error number corresponding to initial attempt to lseek input.
198 If ESPIPE, do not issue any more diagnostics about it. */
199 static int input_seek_errno;
201 /* File offset of the input, in bytes, along with a flag recording
202 whether it overflowed. */
203 static uintmax_t input_offset;
204 static bool input_offset_overflow;
206 /* Records truncated by conv=block. */
207 static uintmax_t r_truncate = 0;
209 /* Output representation of newline and space characters.
210 They change if we're converting to EBCDIC. */
211 static char newline_character = '\n';
212 static char space_character = ' ';
214 /* Output buffer. */
215 static char *obuf;
217 /* Current index into `obuf'. */
218 static size_t oc = 0;
220 /* Index into current line, for `conv=block' and `conv=unblock'. */
221 static size_t col = 0;
223 /* The set of signals that are caught. */
224 static sigset_t caught_signals;
226 /* If nonzero, the value of the pending fatal signal. */
227 static sig_atomic_t volatile interrupt_signal;
229 /* A count of the number of pending info signals that have been received. */
230 static sig_atomic_t volatile info_signal_count;
232 /* Function used for read (to handle iflag=fullblock parameter). */
233 static ssize_t (*iread_fnc) (int fd, char *buf, size_t size);
235 /* A longest symbol in the struct symbol_values tables below. */
236 #define LONGEST_SYMBOL "fdatasync"
238 /* A symbol and the corresponding integer value. */
239 struct symbol_value
241 char symbol[sizeof LONGEST_SYMBOL];
242 int value;
245 /* Conversion symbols, for conv="...". */
246 static struct symbol_value const conversions[] =
248 {"ascii", C_ASCII | C_TWOBUFS}, /* EBCDIC to ASCII. */
249 {"ebcdic", C_EBCDIC | C_TWOBUFS}, /* ASCII to EBCDIC. */
250 {"ibm", C_IBM | C_TWOBUFS}, /* Slightly different ASCII to EBCDIC. */
251 {"block", C_BLOCK | C_TWOBUFS}, /* Variable to fixed length records. */
252 {"unblock", C_UNBLOCK | C_TWOBUFS}, /* Fixed to variable length records. */
253 {"lcase", C_LCASE | C_TWOBUFS}, /* Translate upper to lower case. */
254 {"ucase", C_UCASE | C_TWOBUFS}, /* Translate lower to upper case. */
255 {"swab", C_SWAB | C_TWOBUFS}, /* Swap bytes of input. */
256 {"noerror", C_NOERROR}, /* Ignore i/o errors. */
257 {"nocreat", C_NOCREAT}, /* Do not create output file. */
258 {"excl", C_EXCL}, /* Fail if the output file already exists. */
259 {"notrunc", C_NOTRUNC}, /* Do not truncate output file. */
260 {"sync", C_SYNC}, /* Pad input records to ibs with NULs. */
261 {"fdatasync", C_FDATASYNC}, /* Synchronize output data before finishing. */
262 {"fsync", C_FSYNC}, /* Also synchronize output metadata. */
263 {"", 0}
266 enum
268 /* Compute a value that's bitwise disjoint from the union
269 of all O_ values. */
270 v = ~(0
271 | O_APPEND
272 | O_BINARY
273 | O_CIO
274 | O_DIRECT
275 | O_DIRECTORY
276 | O_DSYNC
277 | O_NOATIME
278 | O_NOCTTY
279 | O_NOFOLLOW
280 | O_NOLINKS
281 | O_NONBLOCK
282 | O_SYNC
283 | O_TEXT
285 /* Use its lowest bit. */
286 O_FULLBLOCK = v ^ (v & (v - 1))
289 /* Ensure that we got something. */
290 verify (O_FULLBLOCK != 0);
292 #define MULTIPLE_BITS_SET(i) (((i) & ((i) - 1)) != 0)
294 /* Ensure that this is a single-bit value. */
295 verify ( ! MULTIPLE_BITS_SET (O_FULLBLOCK));
297 /* Flags, for iflag="..." and oflag="...". */
298 static struct symbol_value const flags[] =
300 {"append", O_APPEND},
301 {"binary", O_BINARY},
302 {"cio", O_CIO},
303 {"direct", O_DIRECT},
304 {"directory", O_DIRECTORY},
305 {"dsync", O_DSYNC},
306 {"noatime", O_NOATIME},
307 {"noctty", O_NOCTTY},
308 {"nofollow", HAVE_WORKING_O_NOFOLLOW ? O_NOFOLLOW : 0},
309 {"nolinks", O_NOLINKS},
310 {"nonblock", O_NONBLOCK},
311 {"sync", O_SYNC},
312 {"text", O_TEXT},
313 {"fullblock", O_FULLBLOCK}, /* Accumulate full blocks from input. */
314 {"", 0}
317 /* Status, for status="...". */
318 static struct symbol_value const statuses[] =
320 {"noxfer", STATUS_NOXFER},
321 {"", 0}
324 /* Translation table formed by applying successive transformations. */
325 static unsigned char trans_table[256];
327 static char const ascii_to_ebcdic[] =
329 '\000', '\001', '\002', '\003', '\067', '\055', '\056', '\057',
330 '\026', '\005', '\045', '\013', '\014', '\015', '\016', '\017',
331 '\020', '\021', '\022', '\023', '\074', '\075', '\062', '\046',
332 '\030', '\031', '\077', '\047', '\034', '\035', '\036', '\037',
333 '\100', '\117', '\177', '\173', '\133', '\154', '\120', '\175',
334 '\115', '\135', '\134', '\116', '\153', '\140', '\113', '\141',
335 '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367',
336 '\370', '\371', '\172', '\136', '\114', '\176', '\156', '\157',
337 '\174', '\301', '\302', '\303', '\304', '\305', '\306', '\307',
338 '\310', '\311', '\321', '\322', '\323', '\324', '\325', '\326',
339 '\327', '\330', '\331', '\342', '\343', '\344', '\345', '\346',
340 '\347', '\350', '\351', '\112', '\340', '\132', '\137', '\155',
341 '\171', '\201', '\202', '\203', '\204', '\205', '\206', '\207',
342 '\210', '\211', '\221', '\222', '\223', '\224', '\225', '\226',
343 '\227', '\230', '\231', '\242', '\243', '\244', '\245', '\246',
344 '\247', '\250', '\251', '\300', '\152', '\320', '\241', '\007',
345 '\040', '\041', '\042', '\043', '\044', '\025', '\006', '\027',
346 '\050', '\051', '\052', '\053', '\054', '\011', '\012', '\033',
347 '\060', '\061', '\032', '\063', '\064', '\065', '\066', '\010',
348 '\070', '\071', '\072', '\073', '\004', '\024', '\076', '\341',
349 '\101', '\102', '\103', '\104', '\105', '\106', '\107', '\110',
350 '\111', '\121', '\122', '\123', '\124', '\125', '\126', '\127',
351 '\130', '\131', '\142', '\143', '\144', '\145', '\146', '\147',
352 '\150', '\151', '\160', '\161', '\162', '\163', '\164', '\165',
353 '\166', '\167', '\170', '\200', '\212', '\213', '\214', '\215',
354 '\216', '\217', '\220', '\232', '\233', '\234', '\235', '\236',
355 '\237', '\240', '\252', '\253', '\254', '\255', '\256', '\257',
356 '\260', '\261', '\262', '\263', '\264', '\265', '\266', '\267',
357 '\270', '\271', '\272', '\273', '\274', '\275', '\276', '\277',
358 '\312', '\313', '\314', '\315', '\316', '\317', '\332', '\333',
359 '\334', '\335', '\336', '\337', '\352', '\353', '\354', '\355',
360 '\356', '\357', '\372', '\373', '\374', '\375', '\376', '\377'
363 static char const ascii_to_ibm[] =
365 '\000', '\001', '\002', '\003', '\067', '\055', '\056', '\057',
366 '\026', '\005', '\045', '\013', '\014', '\015', '\016', '\017',
367 '\020', '\021', '\022', '\023', '\074', '\075', '\062', '\046',
368 '\030', '\031', '\077', '\047', '\034', '\035', '\036', '\037',
369 '\100', '\132', '\177', '\173', '\133', '\154', '\120', '\175',
370 '\115', '\135', '\134', '\116', '\153', '\140', '\113', '\141',
371 '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367',
372 '\370', '\371', '\172', '\136', '\114', '\176', '\156', '\157',
373 '\174', '\301', '\302', '\303', '\304', '\305', '\306', '\307',
374 '\310', '\311', '\321', '\322', '\323', '\324', '\325', '\326',
375 '\327', '\330', '\331', '\342', '\343', '\344', '\345', '\346',
376 '\347', '\350', '\351', '\255', '\340', '\275', '\137', '\155',
377 '\171', '\201', '\202', '\203', '\204', '\205', '\206', '\207',
378 '\210', '\211', '\221', '\222', '\223', '\224', '\225', '\226',
379 '\227', '\230', '\231', '\242', '\243', '\244', '\245', '\246',
380 '\247', '\250', '\251', '\300', '\117', '\320', '\241', '\007',
381 '\040', '\041', '\042', '\043', '\044', '\025', '\006', '\027',
382 '\050', '\051', '\052', '\053', '\054', '\011', '\012', '\033',
383 '\060', '\061', '\032', '\063', '\064', '\065', '\066', '\010',
384 '\070', '\071', '\072', '\073', '\004', '\024', '\076', '\341',
385 '\101', '\102', '\103', '\104', '\105', '\106', '\107', '\110',
386 '\111', '\121', '\122', '\123', '\124', '\125', '\126', '\127',
387 '\130', '\131', '\142', '\143', '\144', '\145', '\146', '\147',
388 '\150', '\151', '\160', '\161', '\162', '\163', '\164', '\165',
389 '\166', '\167', '\170', '\200', '\212', '\213', '\214', '\215',
390 '\216', '\217', '\220', '\232', '\233', '\234', '\235', '\236',
391 '\237', '\240', '\252', '\253', '\254', '\255', '\256', '\257',
392 '\260', '\261', '\262', '\263', '\264', '\265', '\266', '\267',
393 '\270', '\271', '\272', '\273', '\274', '\275', '\276', '\277',
394 '\312', '\313', '\314', '\315', '\316', '\317', '\332', '\333',
395 '\334', '\335', '\336', '\337', '\352', '\353', '\354', '\355',
396 '\356', '\357', '\372', '\373', '\374', '\375', '\376', '\377'
399 static char const ebcdic_to_ascii[] =
401 '\000', '\001', '\002', '\003', '\234', '\011', '\206', '\177',
402 '\227', '\215', '\216', '\013', '\014', '\015', '\016', '\017',
403 '\020', '\021', '\022', '\023', '\235', '\205', '\010', '\207',
404 '\030', '\031', '\222', '\217', '\034', '\035', '\036', '\037',
405 '\200', '\201', '\202', '\203', '\204', '\012', '\027', '\033',
406 '\210', '\211', '\212', '\213', '\214', '\005', '\006', '\007',
407 '\220', '\221', '\026', '\223', '\224', '\225', '\226', '\004',
408 '\230', '\231', '\232', '\233', '\024', '\025', '\236', '\032',
409 '\040', '\240', '\241', '\242', '\243', '\244', '\245', '\246',
410 '\247', '\250', '\133', '\056', '\074', '\050', '\053', '\041',
411 '\046', '\251', '\252', '\253', '\254', '\255', '\256', '\257',
412 '\260', '\261', '\135', '\044', '\052', '\051', '\073', '\136',
413 '\055', '\057', '\262', '\263', '\264', '\265', '\266', '\267',
414 '\270', '\271', '\174', '\054', '\045', '\137', '\076', '\077',
415 '\272', '\273', '\274', '\275', '\276', '\277', '\300', '\301',
416 '\302', '\140', '\072', '\043', '\100', '\047', '\075', '\042',
417 '\303', '\141', '\142', '\143', '\144', '\145', '\146', '\147',
418 '\150', '\151', '\304', '\305', '\306', '\307', '\310', '\311',
419 '\312', '\152', '\153', '\154', '\155', '\156', '\157', '\160',
420 '\161', '\162', '\313', '\314', '\315', '\316', '\317', '\320',
421 '\321', '\176', '\163', '\164', '\165', '\166', '\167', '\170',
422 '\171', '\172', '\322', '\323', '\324', '\325', '\326', '\327',
423 '\330', '\331', '\332', '\333', '\334', '\335', '\336', '\337',
424 '\340', '\341', '\342', '\343', '\344', '\345', '\346', '\347',
425 '\173', '\101', '\102', '\103', '\104', '\105', '\106', '\107',
426 '\110', '\111', '\350', '\351', '\352', '\353', '\354', '\355',
427 '\175', '\112', '\113', '\114', '\115', '\116', '\117', '\120',
428 '\121', '\122', '\356', '\357', '\360', '\361', '\362', '\363',
429 '\134', '\237', '\123', '\124', '\125', '\126', '\127', '\130',
430 '\131', '\132', '\364', '\365', '\366', '\367', '\370', '\371',
431 '\060', '\061', '\062', '\063', '\064', '\065', '\066', '\067',
432 '\070', '\071', '\372', '\373', '\374', '\375', '\376', '\377'
435 /* True if we need to close the standard output *stream*. */
436 static bool close_stdout_required = true;
438 /* The only reason to close the standard output *stream* is if
439 parse_long_options fails (as it does for --help or --version).
440 In any other case, dd uses only the STDOUT_FILENO file descriptor,
441 and the "cleanup" function calls "close (STDOUT_FILENO)".
442 Closing the file descriptor and then letting the usual atexit-run
443 close_stdout function call "fclose (stdout)" would result in a
444 harmless failure of the close syscall (with errno EBADF).
445 This function serves solely to avoid the unnecessary close_stdout
446 call, once parse_long_options has succeeded. */
447 static void
448 maybe_close_stdout (void)
450 if (close_stdout_required)
451 close_stdout ();
454 void
455 usage (int status)
457 if (status != EXIT_SUCCESS)
458 fprintf (stderr, _("Try `%s --help' for more information.\n"),
459 program_name);
460 else
462 printf (_("\
463 Usage: %s [OPERAND]...\n\
464 or: %s OPTION\n\
466 program_name, program_name);
467 fputs (_("\
468 Copy a file, converting and formatting according to the operands.\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 (_("\
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\
492 Each CONV symbol may be:\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 (_("\
519 Each FLAG symbol may be:\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);
552 char const *siginfo_name = (SIGINFO == SIGUSR1 ? "USR1" : "INFO");
553 printf (_("\
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\
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\
564 Options are:\n\
567 siginfo_name, siginfo_name);
570 fputs (HELP_OPTION_DESCRIPTION, stdout);
571 fputs (VERSION_OPTION_DESCRIPTION, stdout);
572 emit_bug_reporting_address ();
574 exit (status);
577 static void
578 translate_charset (char const *new_trans)
580 int i;
582 for (i = 0; i < 256; i++)
583 trans_table[i] = new_trans[trans_table[i]];
584 translation_needed = true;
587 /* Return true if I has more than one bit set. I must be nonnegative. */
589 static inline bool
590 multiple_bits_set (int i)
592 return MULTIPLE_BITS_SET (i);
595 /* Print transfer statistics. */
597 static void
598 print_stats (void)
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;
608 fprintf (stderr,
609 _("%"PRIuMAX"+%"PRIuMAX" records in\n"
610 "%"PRIuMAX"+%"PRIuMAX" records out\n"),
611 r_full, r_partial, w_full, w_partial);
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);
620 if (status_flags & STATUS_NOXFER)
621 return;
623 /* Use integer arithmetic to compute the transfer rate,
624 since that makes it easy to use SI abbreviations. */
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));
633 if (start_time < now)
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);
642 else
644 delta_s = 0;
645 bytes_per_second = _("Infinity B");
648 /* TRANSLATORS: The two instances of "s" in this string are the SI
649 symbol "s" (meaning second), and should not be translated.
651 This format used to be:
653 ngettext (", %g second, %s/s\n", ", %g seconds, %s/s\n", delta_s == 1)
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);
661 static void
662 cleanup (void)
664 if (close (STDIN_FILENO) < 0)
665 error (EXIT_FAILURE, errno,
666 _("closing input file %s"), quote (input_file));
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));
676 static void ATTRIBUTE_NORETURN
677 quit (int code)
679 cleanup ();
680 print_stats ();
681 process_signals ();
682 exit (code);
685 /* An ordinary signal was received; arrange for the program to exit. */
687 static void
688 interrupt_handler (int sig)
690 if (! SA_RESETHAND)
691 signal (sig, SIG_DFL);
692 interrupt_signal = sig;
695 /* An info signal was received; arrange for the program to print status. */
697 static void
698 siginfo_handler (int sig)
700 if (! SA_NOCLDSTOP)
701 signal (sig, siginfo_handler);
702 info_signal_count++;
705 /* Install the signal handlers. */
707 static void
708 install_signal_handlers (void)
710 bool catch_siginfo = ! (SIGINFO == SIGUSR1 && getenv ("POSIXLY_CORRECT"));
712 #if SA_NOCLDSTOP
714 struct sigaction act;
715 sigemptyset (&caught_signals);
716 if (catch_siginfo)
718 sigaction (SIGINFO, NULL, &act);
719 if (act.sa_handler != SIG_IGN)
720 sigaddset (&caught_signals, SIGINFO);
722 sigaction (SIGINT, NULL, &act);
723 if (act.sa_handler != SIG_IGN)
724 sigaddset (&caught_signals, SIGINT);
725 act.sa_mask = caught_signals;
727 if (sigismember (&caught_signals, SIGINFO))
729 act.sa_handler = siginfo_handler;
730 act.sa_flags = 0;
731 sigaction (SIGINFO, &act, NULL);
734 if (sigismember (&caught_signals, SIGINT))
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);
744 #else
746 if (catch_siginfo && signal (SIGINFO, SIG_IGN) != SIG_IGN)
748 signal (SIGINFO, siginfo_handler);
749 siginterrupt (SIGINFO, 1);
751 if (signal (SIGINT, SIG_IGN) != SIG_IGN)
753 signal (SIGINT, interrupt_handler);
754 siginterrupt (SIGINT, 1);
756 #endif
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. */
763 static void
764 process_signals (void)
766 while (interrupt_signal | info_signal_count)
768 int interrupt;
769 int infos;
770 sigset_t oldset;
772 sigprocmask (SIG_BLOCK, &caught_signals, &oldset);
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;
779 if (infos)
780 info_signal_count = infos - 1;
782 sigprocmask (SIG_SETMASK, &oldset, NULL);
784 if (interrupt)
785 cleanup ();
786 print_stats ();
787 if (interrupt)
788 raise (interrupt);
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. */
796 static ssize_t
797 iread (int fd, char *buf, size_t size)
799 for (;;)
801 ssize_t nread;
802 process_signals ();
803 nread = read (fd, buf, size);
804 if (! (nread < 0 && errno == EINTR))
805 return nread;
809 /* Wrapper around iread function to accumulate full blocks. */
810 static ssize_t
811 iread_fullblock (int fd, char *buf, size_t size)
813 ssize_t nread = 0;
815 while (0 < size)
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;
827 return nread;
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. */
835 static size_t
836 iwrite (int fd, char const *buf, size_t size)
838 size_t total_written = 0;
840 while (total_written < size)
842 ssize_t nwritten;
843 process_signals ();
844 nwritten = write (fd, buf + total_written, size - total_written);
845 if (nwritten < 0)
847 if (errno != EINTR)
848 break;
850 else if (nwritten == 0)
852 /* Some buggy drivers return 0 when one tries to write beyond
853 a device's end. (Example: Linux kernel 1.2.13 on /dev/fd0.)
854 Set errno to ENOSPC so they get a sensible diagnostic. */
855 errno = ENOSPC;
856 break;
858 else
859 total_written += nwritten;
862 return total_written;
865 /* Write, then empty, the output buffer `obuf'. */
867 static void
868 write_output (void)
870 size_t nwritten = iwrite (STDOUT_FILENO, obuf, output_blocksize);
871 w_bytes += nwritten;
872 if (nwritten != output_blocksize)
874 error (0, errno, _("writing to %s"), quote (output_file));
875 if (nwritten != 0)
876 w_partial++;
877 quit (EXIT_FAILURE);
879 else
880 w_full++;
881 oc = 0;
884 /* Return true if STR is of the form "PATTERN" or "PATTERNDELIM...". */
886 static bool
887 operand_matches (char const *str, char const *pattern, char delim)
889 while (*pattern)
890 if (*str++ != *pattern++)
891 return false;
892 return !*str || *str == delim;
895 /* Interpret one "conv=..." or similar operand STR according to the
896 symbols in TABLE, returning the flags specified. If the operand
897 cannot be parsed, use ERROR_MSGID to generate a diagnostic. */
899 static int
900 parse_symbols (char const *str, struct symbol_value const *table,
901 char const *error_msgid)
903 int value = 0;
905 for (;;)
907 char const *strcomma = strchr (str, ',');
908 struct symbol_value const *entry;
910 for (entry = table;
911 ! (operand_matches (str, entry->symbol, ',') && entry->value);
912 entry++)
914 if (! entry->symbol[0])
916 size_t slen = strcomma ? strcomma - str : strlen (str);
917 error (0, 0, "%s: %s", _(error_msgid),
918 quotearg_n_style_mem (0, locale_quoting_style, str, slen));
919 usage (EXIT_FAILURE);
923 value |= entry->value;
924 if (!strcomma)
925 break;
926 str = strcomma + 1;
929 return value;
932 /* Return the value of STR, interpreted as a non-negative decimal integer,
933 optionally multiplied by various values.
934 Set *INVALID if STR does not represent a number in this format. */
936 static uintmax_t
937 parse_integer (const char *str, bool *invalid)
939 uintmax_t n;
940 char *suffix;
941 enum strtol_error e = xstrtoumax (str, &suffix, 10, &n, "bcEGkKMPTwYZ0");
943 if (e == LONGINT_INVALID_SUFFIX_CHAR && *suffix == 'x')
945 uintmax_t multiplier = parse_integer (suffix + 1, invalid);
947 if (multiplier != 0 && n * multiplier / multiplier != n)
949 *invalid = true;
950 return 0;
953 n *= multiplier;
955 else if (e != LONGINT_OK)
957 *invalid = true;
958 return 0;
961 return n;
964 /* OPERAND is of the form "X=...". Return true if X is NAME. */
966 static bool
967 operand_is (char const *operand, char const *name)
969 return operand_matches (operand, name, '=');
972 static void
973 scanargs (int argc, char *const *argv)
975 int i;
976 size_t blocksize = 0;
978 for (i = optind; i < argc; i++)
980 char const *name = argv[i];
981 char const *val = strchr (name, '=');
983 if (val == NULL)
985 error (0, 0, _("unrecognized operand %s"), quote (name));
986 usage (EXIT_FAILURE);
988 val++;
990 if (operand_is (name, "if"))
991 input_file = val;
992 else if (operand_is (name, "of"))
993 output_file = val;
994 else if (operand_is (name, "conv"))
995 conversions_mask |= parse_symbols (val, conversions,
996 N_("invalid conversion"));
997 else if (operand_is (name, "iflag"))
998 input_flags |= parse_symbols (val, flags,
999 N_("invalid input flag"));
1000 else if (operand_is (name, "oflag"))
1001 output_flags |= parse_symbols (val, flags,
1002 N_("invalid output flag"));
1003 else if (operand_is (name, "status"))
1004 status_flags |= parse_symbols (val, statuses,
1005 N_("invalid status flag"));
1006 else
1008 bool invalid = false;
1009 uintmax_t n = parse_integer (val, &invalid);
1011 if (operand_is (name, "ibs"))
1013 invalid |= ! (0 < n && n <= MAX_BLOCKSIZE (INPUT_BLOCK_SLOP));
1014 input_blocksize = n;
1016 else if (operand_is (name, "obs"))
1018 invalid |= ! (0 < n && n <= MAX_BLOCKSIZE (OUTPUT_BLOCK_SLOP));
1019 output_blocksize = n;
1021 else if (operand_is (name, "bs"))
1023 invalid |= ! (0 < n && n <= MAX_BLOCKSIZE (INPUT_BLOCK_SLOP));
1024 blocksize = n;
1026 else if (operand_is (name, "cbs"))
1028 invalid |= ! (0 < n && n <= SIZE_MAX);
1029 conversion_blocksize = n;
1031 else if (operand_is (name, "skip"))
1032 skip_records = n;
1033 else if (operand_is (name, "seek"))
1034 seek_records = n;
1035 else if (operand_is (name, "count"))
1036 max_records = n;
1037 else
1039 error (0, 0, _("unrecognized operand %s"), quote (name));
1040 usage (EXIT_FAILURE);
1043 if (invalid)
1044 error (EXIT_FAILURE, 0, _("invalid number %s"), quote (val));
1048 if (blocksize)
1049 input_blocksize = output_blocksize = blocksize;
1050 else
1052 /* POSIX says dd aggregates short reads into
1053 output_blocksize if bs= is not specified. */
1054 conversions_mask |= C_TWOBUFS;
1057 if (input_blocksize == 0)
1058 input_blocksize = DEFAULT_BLOCKSIZE;
1059 if (output_blocksize == 0)
1060 output_blocksize = DEFAULT_BLOCKSIZE;
1061 if (conversion_blocksize == 0)
1062 conversions_mask &= ~(C_BLOCK | C_UNBLOCK);
1064 if (input_flags & (O_DSYNC | O_SYNC))
1065 input_flags |= O_RSYNC;
1067 if (output_flags & O_FULLBLOCK)
1069 error (0, 0, "%s: %s", _("invalid output flag"), "'fullblock'");
1070 usage (EXIT_FAILURE);
1072 iread_fnc = ((input_flags & O_FULLBLOCK)
1073 ? iread_fullblock
1074 : iread);
1075 input_flags &= ~O_FULLBLOCK;
1077 if (multiple_bits_set (conversions_mask & (C_ASCII | C_EBCDIC | C_IBM)))
1078 error (EXIT_FAILURE, 0, _("cannot combine any two of {ascii,ebcdic,ibm}"));
1079 if (multiple_bits_set (conversions_mask & (C_BLOCK | C_UNBLOCK)))
1080 error (EXIT_FAILURE, 0, _("cannot combine block and unblock"));
1081 if (multiple_bits_set (conversions_mask & (C_LCASE | C_UCASE)))
1082 error (EXIT_FAILURE, 0, _("cannot combine lcase and ucase"));
1083 if (multiple_bits_set (conversions_mask & (C_EXCL | C_NOCREAT)))
1084 error (EXIT_FAILURE, 0, _("cannot combine excl and nocreat"));
1087 /* Fix up translation table. */
1089 static void
1090 apply_translations (void)
1092 int i;
1094 if (conversions_mask & C_ASCII)
1095 translate_charset (ebcdic_to_ascii);
1097 if (conversions_mask & C_UCASE)
1099 for (i = 0; i < 256; i++)
1100 trans_table[i] = toupper (trans_table[i]);
1101 translation_needed = true;
1103 else if (conversions_mask & C_LCASE)
1105 for (i = 0; i < 256; i++)
1106 trans_table[i] = tolower (trans_table[i]);
1107 translation_needed = true;
1110 if (conversions_mask & C_EBCDIC)
1112 translate_charset (ascii_to_ebcdic);
1113 newline_character = ascii_to_ebcdic['\n'];
1114 space_character = ascii_to_ebcdic[' '];
1116 else if (conversions_mask & C_IBM)
1118 translate_charset (ascii_to_ibm);
1119 newline_character = ascii_to_ibm['\n'];
1120 space_character = ascii_to_ibm[' '];
1124 /* Apply the character-set translations specified by the user
1125 to the NREAD bytes in BUF. */
1127 static void
1128 translate_buffer (char *buf, size_t nread)
1130 char *cp;
1131 size_t i;
1133 for (i = nread, cp = buf; i; i--, cp++)
1134 *cp = trans_table[to_uchar (*cp)];
1137 /* If true, the last char from the previous call to `swab_buffer'
1138 is saved in `saved_char'. */
1139 static bool char_is_saved = false;
1141 /* Odd char from previous call. */
1142 static char saved_char;
1144 /* Swap NREAD bytes in BUF, plus possibly an initial char from the
1145 previous call. If NREAD is odd, save the last char for the
1146 next call. Return the new start of the BUF buffer. */
1148 static char *
1149 swab_buffer (char *buf, size_t *nread)
1151 char *bufstart = buf;
1152 char *cp;
1153 size_t i;
1155 /* Is a char left from last time? */
1156 if (char_is_saved)
1158 *--bufstart = saved_char;
1159 (*nread)++;
1160 char_is_saved = false;
1163 if (*nread & 1)
1165 /* An odd number of chars are in the buffer. */
1166 saved_char = bufstart[--*nread];
1167 char_is_saved = true;
1170 /* Do the byte-swapping by moving every second character two
1171 positions toward the end, working from the end of the buffer
1172 toward the beginning. This way we only move half of the data. */
1174 cp = bufstart + *nread; /* Start one char past the last. */
1175 for (i = *nread / 2; i; i--, cp -= 2)
1176 *cp = *(cp - 2);
1178 return ++bufstart;
1181 /* Add OFFSET to the input offset, setting the overflow flag if
1182 necessary. */
1184 static void
1185 advance_input_offset (uintmax_t offset)
1187 input_offset += offset;
1188 if (input_offset < offset)
1189 input_offset_overflow = true;
1192 /* This is a wrapper for lseek. It detects and warns about a kernel
1193 bug that makes lseek a no-op for tape devices, even though the kernel
1194 lseek return value suggests that the function succeeded.
1196 The parameters are the same as those of the lseek function, but
1197 with the addition of FILENAME, the name of the file associated with
1198 descriptor FDESC. The file name is used solely in the warning that's
1199 printed when the bug is detected. Return the same value that lseek
1200 would have returned, but when the lseek bug is detected, return -1
1201 to indicate that lseek failed.
1203 The offending behavior has been confirmed with an Exabyte SCSI tape
1204 drive accessed via /dev/nst0 on both Linux 2.2.17 and 2.4.16 kernels. */
1206 #ifdef __linux__
1208 # include <sys/mtio.h>
1210 # define MT_SAME_POSITION(P, Q) \
1211 ((P).mt_resid == (Q).mt_resid \
1212 && (P).mt_fileno == (Q).mt_fileno \
1213 && (P).mt_blkno == (Q).mt_blkno)
1215 static off_t
1216 skip_via_lseek (char const *filename, int fdesc, off_t offset, int whence)
1218 struct mtget s1;
1219 struct mtget s2;
1220 bool got_original_tape_position = (ioctl (fdesc, MTIOCGET, &s1) == 0);
1221 /* known bad device type */
1222 /* && s.mt_type == MT_ISSCSI2 */
1224 off_t new_position = lseek (fdesc, offset, whence);
1225 if (0 <= new_position
1226 && got_original_tape_position
1227 && ioctl (fdesc, MTIOCGET, &s2) == 0
1228 && MT_SAME_POSITION (s1, s2))
1230 error (0, 0, _("warning: working around lseek kernel bug for file (%s)\n\
1231 of mt_type=0x%0lx -- see <sys/mtio.h> for the list of types"),
1232 filename, s2.mt_type);
1233 errno = 0;
1234 new_position = -1;
1237 return new_position;
1239 #else
1240 # define skip_via_lseek(Filename, Fd, Offset, Whence) lseek (Fd, Offset, Whence)
1241 #endif
1243 /* Throw away RECORDS blocks of BLOCKSIZE bytes on file descriptor FDESC,
1244 which is open with read permission for FILE. Store up to BLOCKSIZE
1245 bytes of the data at a time in BUF, if necessary. RECORDS must be
1246 nonzero. If fdesc is STDIN_FILENO, advance the input offset.
1247 Return the number of records remaining, i.e., that were not skipped
1248 because EOF was reached. */
1250 static uintmax_t
1251 skip (int fdesc, char const *file, uintmax_t records, size_t blocksize,
1252 char *buf)
1254 uintmax_t offset = records * blocksize;
1256 /* Try lseek and if an error indicates it was an inappropriate operation --
1257 or if the file offset is not representable as an off_t --
1258 fall back on using read. */
1260 errno = 0;
1261 if (records <= OFF_T_MAX / blocksize
1262 && 0 <= skip_via_lseek (file, fdesc, offset, SEEK_CUR))
1264 if (fdesc == STDIN_FILENO)
1266 struct stat st;
1267 if (fstat (STDIN_FILENO, &st) != 0)
1268 error (EXIT_FAILURE, errno, _("cannot fstat %s"), quote (file));
1269 if (S_ISREG (st.st_mode) && st.st_size < (input_offset + offset))
1271 /* When skipping past EOF, return the number of _full_ blocks
1272 * that are not skipped, and set offset to EOF, so the caller
1273 * can determine the requested skip was not satisfied. */
1274 records = ( offset - st.st_size ) / blocksize;
1275 offset = st.st_size - input_offset;
1277 else
1278 records = 0;
1279 advance_input_offset (offset);
1281 else
1282 records = 0;
1283 return records;
1285 else
1287 int lseek_errno = errno;
1288 off_t soffset;
1290 /* The seek request may have failed above if it was too big
1291 (> device size, > max file size, etc.)
1292 Or it may not have been done at all (> OFF_T_MAX).
1293 Therefore try to seek to the end of the file,
1294 to avoid redundant reading. */
1295 if ((soffset = skip_via_lseek (file, fdesc, 0, SEEK_END)) >= 0)
1297 /* File is seekable, and we're at the end of it, and
1298 size <= OFF_T_MAX. So there's no point using read to advance. */
1300 if (!lseek_errno)
1302 /* The original seek was not attempted as offset > OFF_T_MAX.
1303 We should error for write as can't get to the desired
1304 location, even if OFF_T_MAX < max file size.
1305 For read we're not going to read any data anyway,
1306 so we should error for consistency.
1307 It would be nice to not error for /dev/{zero,null}
1308 for any offset, but that's not a significant issue. */
1309 lseek_errno = EOVERFLOW;
1312 if (fdesc == STDIN_FILENO)
1313 error (0, lseek_errno, _("%s: cannot skip"), quote (file));
1314 else
1315 error (0, lseek_errno, _("%s: cannot seek"), quote (file));
1316 /* If the file has a specific size and we've asked
1317 to skip/seek beyond the max allowable, then quit. */
1318 quit (EXIT_FAILURE);
1320 /* else file_size && offset > OFF_T_MAX or file ! seekable */
1324 ssize_t nread = iread_fnc (fdesc, buf, blocksize);
1325 if (nread < 0)
1327 if (fdesc == STDIN_FILENO)
1329 error (0, errno, _("reading %s"), quote (file));
1330 if (conversions_mask & C_NOERROR)
1332 print_stats ();
1333 continue;
1336 else
1337 error (0, lseek_errno, _("%s: cannot seek"), quote (file));
1338 quit (EXIT_FAILURE);
1341 if (nread == 0)
1342 break;
1343 if (fdesc == STDIN_FILENO)
1344 advance_input_offset (nread);
1346 while (--records != 0);
1348 return records;
1352 /* Advance the input by NBYTES if possible, after a read error.
1353 The input file offset may or may not have advanced after the failed
1354 read; adjust it to point just after the bad record regardless.
1355 Return true if successful, or if the input is already known to not
1356 be seekable. */
1358 static bool
1359 advance_input_after_read_error (size_t nbytes)
1361 if (! input_seekable)
1363 if (input_seek_errno == ESPIPE)
1364 return true;
1365 errno = input_seek_errno;
1367 else
1369 off_t offset;
1370 advance_input_offset (nbytes);
1371 input_offset_overflow |= (OFF_T_MAX < input_offset);
1372 if (input_offset_overflow)
1374 error (0, 0, _("offset overflow while reading file %s"),
1375 quote (input_file));
1376 return false;
1378 offset = lseek (STDIN_FILENO, 0, SEEK_CUR);
1379 if (0 <= offset)
1381 off_t diff;
1382 if (offset == input_offset)
1383 return true;
1384 diff = input_offset - offset;
1385 if (! (0 <= diff && diff <= nbytes))
1386 error (0, 0, _("warning: invalid file offset after failed read"));
1387 if (0 <= skip_via_lseek (input_file, STDIN_FILENO, diff, SEEK_CUR))
1388 return true;
1389 if (errno == 0)
1390 error (0, 0, _("cannot work around kernel bug after all"));
1394 error (0, errno, _("%s: cannot seek"), quote (input_file));
1395 return false;
1398 /* Copy NREAD bytes of BUF, with no conversions. */
1400 static void
1401 copy_simple (char const *buf, size_t nread)
1403 const char *start = buf; /* First uncopied char in BUF. */
1407 size_t nfree = MIN (nread, output_blocksize - oc);
1409 memcpy (obuf + oc, start, nfree);
1411 nread -= nfree; /* Update the number of bytes left to copy. */
1412 start += nfree;
1413 oc += nfree;
1414 if (oc >= output_blocksize)
1415 write_output ();
1417 while (nread != 0);
1420 /* Copy NREAD bytes of BUF, doing conv=block
1421 (pad newline-terminated records to `conversion_blocksize',
1422 replacing the newline with trailing spaces). */
1424 static void
1425 copy_with_block (char const *buf, size_t nread)
1427 size_t i;
1429 for (i = nread; i; i--, buf++)
1431 if (*buf == newline_character)
1433 if (col < conversion_blocksize)
1435 size_t j;
1436 for (j = col; j < conversion_blocksize; j++)
1437 output_char (space_character);
1439 col = 0;
1441 else
1443 if (col == conversion_blocksize)
1444 r_truncate++;
1445 else if (col < conversion_blocksize)
1446 output_char (*buf);
1447 col++;
1452 /* Copy NREAD bytes of BUF, doing conv=unblock
1453 (replace trailing spaces in `conversion_blocksize'-sized records
1454 with a newline). */
1456 static void
1457 copy_with_unblock (char const *buf, size_t nread)
1459 size_t i;
1460 char c;
1461 static size_t pending_spaces = 0;
1463 for (i = 0; i < nread; i++)
1465 c = buf[i];
1467 if (col++ >= conversion_blocksize)
1469 col = pending_spaces = 0; /* Wipe out any pending spaces. */
1470 i--; /* Push the char back; get it later. */
1471 output_char (newline_character);
1473 else if (c == space_character)
1474 pending_spaces++;
1475 else
1477 /* `c' is the character after a run of spaces that were not
1478 at the end of the conversion buffer. Output them. */
1479 while (pending_spaces)
1481 output_char (space_character);
1482 --pending_spaces;
1484 output_char (c);
1489 /* Set the file descriptor flags for FD that correspond to the nonzero bits
1490 in ADD_FLAGS. The file's name is NAME. */
1492 static void
1493 set_fd_flags (int fd, int add_flags, char const *name)
1495 /* Ignore file creation flags that are no-ops on file descriptors. */
1496 add_flags &= ~ (O_NOCTTY | O_NOFOLLOW);
1498 if (add_flags)
1500 int old_flags = fcntl (fd, F_GETFL);
1501 int new_flags = old_flags | add_flags;
1502 bool ok = true;
1503 if (old_flags < 0)
1504 ok = false;
1505 else if (old_flags != new_flags)
1507 if (new_flags & (O_DIRECTORY | O_NOLINKS))
1509 /* NEW_FLAGS contains at least one file creation flag that
1510 requires some checking of the open file descriptor. */
1511 struct stat st;
1512 if (fstat (fd, &st) != 0)
1513 ok = false;
1514 else if ((new_flags & O_DIRECTORY) && ! S_ISDIR (st.st_mode))
1516 errno = ENOTDIR;
1517 ok = false;
1519 else if ((new_flags & O_NOLINKS) && 1 < st.st_nlink)
1521 errno = EMLINK;
1522 ok = false;
1524 new_flags &= ~ (O_DIRECTORY | O_NOLINKS);
1527 if (ok && old_flags != new_flags
1528 && fcntl (fd, F_SETFL, new_flags) == -1)
1529 ok = false;
1532 if (!ok)
1533 error (EXIT_FAILURE, errno, _("setting flags for %s"), quote (name));
1537 /* The main loop. */
1539 static int
1540 dd_copy (void)
1542 char *ibuf, *bufstart; /* Input buffer. */
1543 /* These are declared static so that even though we don't free the
1544 buffers, valgrind will recognize that there is no "real" leak. */
1545 static char *real_buf; /* real buffer address before alignment */
1546 static char *real_obuf;
1547 ssize_t nread; /* Bytes read in the current block. */
1549 /* If nonzero, then the previously read block was partial and
1550 PARTREAD was its size. */
1551 size_t partread = 0;
1553 int exit_status = EXIT_SUCCESS;
1554 size_t n_bytes_read;
1556 /* Leave at least one extra byte at the beginning and end of `ibuf'
1557 for conv=swab, but keep the buffer address even. But some peculiar
1558 device drivers work only with word-aligned buffers, so leave an
1559 extra two bytes. */
1561 /* Some devices require alignment on a sector or page boundary
1562 (e.g. character disk devices). Align the input buffer to a
1563 page boundary to cover all bases. Note that due to the swab
1564 algorithm, we must have at least one byte in the page before
1565 the input buffer; thus we allocate 2 pages of slop in the
1566 real buffer. 8k above the blocksize shouldn't bother anyone.
1568 The page alignment is necessary on any Linux kernel that supports
1569 either the SGI raw I/O patch or Steven Tweedies raw I/O patch.
1570 It is necessary when accessing raw (i.e. character special) disk
1571 devices on Unixware or other SVR4-derived system. */
1573 real_buf = xmalloc (input_blocksize + INPUT_BLOCK_SLOP);
1574 ibuf = real_buf;
1575 ibuf += SWAB_ALIGN_OFFSET; /* allow space for swab */
1577 ibuf = ptr_align (ibuf, page_size);
1579 if (conversions_mask & C_TWOBUFS)
1581 /* Page-align the output buffer, too. */
1582 real_obuf = xmalloc (output_blocksize + OUTPUT_BLOCK_SLOP);
1583 obuf = ptr_align (real_obuf, page_size);
1585 else
1587 real_obuf = NULL;
1588 obuf = ibuf;
1591 if (skip_records != 0)
1593 uintmax_t us_bytes = input_offset + (skip_records * input_blocksize);
1594 uintmax_t us_blocks = skip (STDIN_FILENO, input_file,
1595 skip_records, input_blocksize, ibuf);
1596 us_bytes -= input_offset;
1598 /* POSIX doesn't say what to do when dd detects it has been
1599 asked to skip past EOF, so I assume it's non-fatal.
1600 There are 3 reasons why there might be unskipped blocks/bytes:
1601 1. file is too small
1602 2. pipe has not enough data
1603 3. short reads */
1604 if (us_blocks || (!input_offset_overflow && us_bytes))
1606 error (0, 0,
1607 _("%s: cannot skip to specified offset"), quote (input_file));
1611 if (seek_records != 0)
1613 uintmax_t write_records = skip (STDOUT_FILENO, output_file,
1614 seek_records, output_blocksize, obuf);
1616 if (write_records != 0)
1618 memset (obuf, 0, output_blocksize);
1621 if (iwrite (STDOUT_FILENO, obuf, output_blocksize)
1622 != output_blocksize)
1624 error (0, errno, _("writing to %s"), quote (output_file));
1625 quit (EXIT_FAILURE);
1627 while (--write_records != 0);
1631 if (max_records == 0)
1632 return exit_status;
1634 while (1)
1636 if (r_partial + r_full >= max_records)
1637 break;
1639 /* Zero the buffer before reading, so that if we get a read error,
1640 whatever data we are able to read is followed by zeros.
1641 This minimizes data loss. */
1642 if ((conversions_mask & C_SYNC) && (conversions_mask & C_NOERROR))
1643 memset (ibuf,
1644 (conversions_mask & (C_BLOCK | C_UNBLOCK)) ? ' ' : '\0',
1645 input_blocksize);
1647 nread = iread_fnc (STDIN_FILENO, ibuf, input_blocksize);
1649 if (nread == 0)
1650 break; /* EOF. */
1652 if (nread < 0)
1654 error (0, errno, _("reading %s"), quote (input_file));
1655 if (conversions_mask & C_NOERROR)
1657 print_stats ();
1658 /* Seek past the bad block if possible. */
1659 if (!advance_input_after_read_error (input_blocksize - partread))
1661 exit_status = EXIT_FAILURE;
1663 /* Suppress duplicate diagnostics. */
1664 input_seekable = false;
1665 input_seek_errno = ESPIPE;
1667 if ((conversions_mask & C_SYNC) && !partread)
1668 /* Replace the missing input with null bytes and
1669 proceed normally. */
1670 nread = 0;
1671 else
1672 continue;
1674 else
1676 /* Write any partial block. */
1677 exit_status = EXIT_FAILURE;
1678 break;
1682 n_bytes_read = nread;
1683 advance_input_offset (nread);
1685 if (n_bytes_read < input_blocksize)
1687 r_partial++;
1688 partread = n_bytes_read;
1689 if (conversions_mask & C_SYNC)
1691 if (!(conversions_mask & C_NOERROR))
1692 /* If C_NOERROR, we zeroed the block before reading. */
1693 memset (ibuf + n_bytes_read,
1694 (conversions_mask & (C_BLOCK | C_UNBLOCK)) ? ' ' : '\0',
1695 input_blocksize - n_bytes_read);
1696 n_bytes_read = input_blocksize;
1699 else
1701 r_full++;
1702 partread = 0;
1705 if (ibuf == obuf) /* If not C_TWOBUFS. */
1707 size_t nwritten = iwrite (STDOUT_FILENO, obuf, n_bytes_read);
1708 w_bytes += nwritten;
1709 if (nwritten != n_bytes_read)
1711 error (0, errno, _("writing %s"), quote (output_file));
1712 return EXIT_FAILURE;
1714 else if (n_bytes_read == input_blocksize)
1715 w_full++;
1716 else
1717 w_partial++;
1718 continue;
1721 /* Do any translations on the whole buffer at once. */
1723 if (translation_needed)
1724 translate_buffer (ibuf, n_bytes_read);
1726 if (conversions_mask & C_SWAB)
1727 bufstart = swab_buffer (ibuf, &n_bytes_read);
1728 else
1729 bufstart = ibuf;
1731 if (conversions_mask & C_BLOCK)
1732 copy_with_block (bufstart, n_bytes_read);
1733 else if (conversions_mask & C_UNBLOCK)
1734 copy_with_unblock (bufstart, n_bytes_read);
1735 else
1736 copy_simple (bufstart, n_bytes_read);
1739 /* If we have a char left as a result of conv=swab, output it. */
1740 if (char_is_saved)
1742 if (conversions_mask & C_BLOCK)
1743 copy_with_block (&saved_char, 1);
1744 else if (conversions_mask & C_UNBLOCK)
1745 copy_with_unblock (&saved_char, 1);
1746 else
1747 output_char (saved_char);
1750 if ((conversions_mask & C_BLOCK) && col > 0)
1752 /* If the final input line didn't end with a '\n', pad
1753 the output block to `conversion_blocksize' chars. */
1754 size_t i;
1755 for (i = col; i < conversion_blocksize; i++)
1756 output_char (space_character);
1759 if ((conversions_mask & C_UNBLOCK) && col == conversion_blocksize)
1760 /* Add a final '\n' if there are exactly `conversion_blocksize'
1761 characters in the final record. */
1762 output_char (newline_character);
1764 /* Write out the last block. */
1765 if (oc != 0)
1767 size_t nwritten = iwrite (STDOUT_FILENO, obuf, oc);
1768 w_bytes += nwritten;
1769 if (nwritten != 0)
1770 w_partial++;
1771 if (nwritten != oc)
1773 error (0, errno, _("writing %s"), quote (output_file));
1774 return EXIT_FAILURE;
1778 if ((conversions_mask & C_FDATASYNC) && fdatasync (STDOUT_FILENO) != 0)
1780 if (errno != ENOSYS && errno != EINVAL)
1782 error (0, errno, _("fdatasync failed for %s"), quote (output_file));
1783 exit_status = EXIT_FAILURE;
1785 conversions_mask |= C_FSYNC;
1788 if (conversions_mask & C_FSYNC)
1789 while (fsync (STDOUT_FILENO) != 0)
1790 if (errno != EINTR)
1792 error (0, errno, _("fsync failed for %s"), quote (output_file));
1793 return EXIT_FAILURE;
1796 return exit_status;
1800 main (int argc, char **argv)
1802 int i;
1803 int exit_status;
1804 off_t offset;
1806 initialize_main (&argc, &argv);
1807 set_program_name (argv[0]);
1808 setlocale (LC_ALL, "");
1809 bindtextdomain (PACKAGE, LOCALEDIR);
1810 textdomain (PACKAGE);
1812 /* Arrange to close stdout if parse_long_options exits. */
1813 atexit (maybe_close_stdout);
1815 page_size = getpagesize ();
1817 parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE, Version,
1818 usage, AUTHORS, (char const *) NULL);
1819 close_stdout_required = false;
1821 if (getopt_long (argc, argv, "", NULL, NULL) != -1)
1822 usage (EXIT_FAILURE);
1824 /* Initialize translation table to identity translation. */
1825 for (i = 0; i < 256; i++)
1826 trans_table[i] = i;
1828 /* Decode arguments. */
1829 scanargs (argc, argv);
1831 apply_translations ();
1833 if (input_file == NULL)
1835 input_file = _("standard input");
1836 set_fd_flags (STDIN_FILENO, input_flags, input_file);
1838 else
1840 if (fd_reopen (STDIN_FILENO, input_file, O_RDONLY | input_flags, 0) < 0)
1841 error (EXIT_FAILURE, errno, _("opening %s"), quote (input_file));
1844 offset = lseek (STDIN_FILENO, 0, SEEK_CUR);
1845 input_seekable = (0 <= offset);
1846 input_offset = MAX(0, offset);
1847 input_seek_errno = errno;
1849 if (output_file == NULL)
1851 output_file = _("standard output");
1852 set_fd_flags (STDOUT_FILENO, output_flags, output_file);
1854 else
1856 mode_t perms = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
1857 int opts
1858 = (output_flags
1859 | (conversions_mask & C_NOCREAT ? 0 : O_CREAT)
1860 | (conversions_mask & C_EXCL ? O_EXCL : 0)
1861 | (seek_records || (conversions_mask & C_NOTRUNC) ? 0 : O_TRUNC));
1863 /* Open the output file with *read* access only if we might
1864 need to read to satisfy a `seek=' request. If we can't read
1865 the file, go ahead with write-only access; it might work. */
1866 if ((! seek_records
1867 || fd_reopen (STDOUT_FILENO, output_file, O_RDWR | opts, perms) < 0)
1868 && (fd_reopen (STDOUT_FILENO, output_file, O_WRONLY | opts, perms)
1869 < 0))
1870 error (EXIT_FAILURE, errno, _("opening %s"), quote (output_file));
1872 #if HAVE_FTRUNCATE
1873 if (seek_records != 0 && !(conversions_mask & C_NOTRUNC))
1875 uintmax_t size = seek_records * output_blocksize;
1876 unsigned long int obs = output_blocksize;
1878 if (OFF_T_MAX / output_blocksize < seek_records)
1879 error (EXIT_FAILURE, 0,
1880 _("offset too large: "
1881 "cannot truncate to a length of seek=%"PRIuMAX""
1882 " (%lu-byte) blocks"),
1883 seek_records, obs);
1885 if (ftruncate (STDOUT_FILENO, size) != 0)
1887 /* Complain only when ftruncate fails on a regular file, a
1888 directory, or a shared memory object, as POSIX 1003.1-2004
1889 specifies ftruncate's behavior only for these file types.
1890 For example, do not complain when Linux kernel 2.4 ftruncate
1891 fails on /dev/fd0. */
1892 int ftruncate_errno = errno;
1893 struct stat stdout_stat;
1894 if (fstat (STDOUT_FILENO, &stdout_stat) != 0)
1895 error (EXIT_FAILURE, errno, _("cannot fstat %s"),
1896 quote (output_file));
1897 if (S_ISREG (stdout_stat.st_mode)
1898 || S_ISDIR (stdout_stat.st_mode)
1899 || S_TYPEISSHM (&stdout_stat))
1900 error (EXIT_FAILURE, ftruncate_errno,
1901 _("truncating at %"PRIuMAX" bytes in output file %s"),
1902 size, quote (output_file));
1905 #endif
1908 install_signal_handlers ();
1910 start_time = gethrxtime ();
1912 exit_status = dd_copy ();
1914 quit (exit_status);