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. */
21 #define SWAB_ALIGN_OFFSET 2
23 #include <sys/types.h>
29 #include "fd-reopen.h"
30 #include "gethrxtime.h"
32 #include "ignore-value.h"
33 #include "long-options.h"
39 static void process_signals (void);
41 /* The official name of this program (e.g., no `g' prefix). */
42 #define PROGRAM_NAME "dd"
45 proper_name ("Paul Rubin"), \
46 proper_name ("David MacKenzie"), \
47 proper_name ("Stuart Kemp")
49 /* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is
50 present. SA_NODEFER and SA_RESETHAND are XSI extensions. */
52 # define SA_NOCLDSTOP 0
53 # define sigprocmask(How, Set, Oset) /* empty */
55 # if ! HAVE_SIGINTERRUPT
56 # define siginterrupt(sig, flag) /* empty */
63 # define SA_RESETHAND 0
67 # define SIGINFO SIGUSR1
70 /* This may belong in GNULIB's fcntl module instead.
71 Define O_CIO to 0 if it is not supported by this OS. */
77 # define fdatasync(fd) (errno = ENOSYS, -1)
80 #define output_char(c) \
84 if (oc >= output_blocksize) \
89 /* Default input and output blocksize. */
90 #define DEFAULT_BLOCKSIZE 512
92 /* How many bytes to add to the input and output block sizes before invoking
93 malloc. See dd_copy for details. INPUT_BLOCK_SLOP must be no less than
95 #define INPUT_BLOCK_SLOP (2 * SWAB_ALIGN_OFFSET + 2 * page_size - 1)
96 #define OUTPUT_BLOCK_SLOP (page_size - 1)
98 /* Maximum blocksize for the given SLOP.
99 Keep it smaller than SIZE_MAX - SLOP, so that we can
100 allocate buffers that size. Keep it smaller than SSIZE_MAX, for
101 the benefit of system calls like "read". And keep it smaller than
102 OFF_T_MAX, for the benefit of the large-offset seek code. */
103 #define MAX_BLOCKSIZE(slop) MIN (SIZE_MAX - (slop), MIN (SSIZE_MAX, OFF_T_MAX))
105 /* Conversions bit masks. */
121 /* Use separate input and output buffers, and combine partial
127 C_FDATASYNC
= 040000,
131 /* Status bit masks. */
137 /* The name of the input file, or NULL for the standard input. */
138 static char const *input_file
= NULL
;
140 /* The name of the output file, or NULL for the standard output. */
141 static char const *output_file
= NULL
;
143 /* The page size on this host. */
144 static size_t page_size
;
146 /* The number of bytes in which atomic reads are done. */
147 static size_t input_blocksize
= 0;
149 /* The number of bytes in which atomic writes are done. */
150 static size_t output_blocksize
= 0;
152 /* Conversion buffer size, in bytes. 0 prevents conversions. */
153 static size_t conversion_blocksize
= 0;
155 /* Skip this many records of `input_blocksize' bytes before input. */
156 static uintmax_t skip_records
= 0;
158 /* Skip this many records of `output_blocksize' bytes before output. */
159 static uintmax_t seek_records
= 0;
161 /* Copy only this many records. The default is effectively infinity. */
162 static uintmax_t max_records
= (uintmax_t) -1;
164 /* Bit vector of conversions to apply. */
165 static int conversions_mask
= 0;
167 /* Open flags for the input and output files. */
168 static int input_flags
= 0;
169 static int output_flags
= 0;
171 /* Status flags for what is printed to stderr. */
172 static int status_flags
= 0;
174 /* If nonzero, filter characters through the translation table. */
175 static bool translation_needed
= false;
177 /* Number of partial blocks written. */
178 static uintmax_t w_partial
= 0;
180 /* Number of full blocks written. */
181 static uintmax_t w_full
= 0;
183 /* Number of partial blocks read. */
184 static uintmax_t r_partial
= 0;
186 /* Number of full blocks read. */
187 static uintmax_t r_full
= 0;
189 /* Number of bytes written. */
190 static uintmax_t w_bytes
= 0;
192 /* Time that dd started. */
193 static xtime_t start_time
;
195 /* True if input is seekable. */
196 static bool input_seekable
;
198 /* Error number corresponding to initial attempt to lseek input.
199 If ESPIPE, do not issue any more diagnostics about it. */
200 static int input_seek_errno
;
202 /* File offset of the input, in bytes, along with a flag recording
203 whether it overflowed. */
204 static uintmax_t input_offset
;
205 static bool input_offset_overflow
;
207 /* Records truncated by conv=block. */
208 static uintmax_t r_truncate
= 0;
210 /* Output representation of newline and space characters.
211 They change if we're converting to EBCDIC. */
212 static char newline_character
= '\n';
213 static char space_character
= ' ';
218 /* Current index into `obuf'. */
219 static size_t oc
= 0;
221 /* Index into current line, for `conv=block' and `conv=unblock'. */
222 static size_t col
= 0;
224 /* The set of signals that are caught. */
225 static sigset_t caught_signals
;
227 /* If nonzero, the value of the pending fatal signal. */
228 static sig_atomic_t volatile interrupt_signal
;
230 /* A count of the number of pending info signals that have been received. */
231 static sig_atomic_t volatile info_signal_count
;
233 /* Function used for read (to handle iflag=fullblock parameter). */
234 static ssize_t (*iread_fnc
) (int fd
, char *buf
, size_t size
);
236 /* A longest symbol in the struct symbol_values tables below. */
237 #define LONGEST_SYMBOL "fdatasync"
239 /* A symbol and the corresponding integer value. */
242 char symbol
[sizeof LONGEST_SYMBOL
];
246 /* Conversion symbols, for conv="...". */
247 static struct symbol_value
const conversions
[] =
249 {"ascii", C_ASCII
| C_TWOBUFS
}, /* EBCDIC to ASCII. */
250 {"ebcdic", C_EBCDIC
| C_TWOBUFS
}, /* ASCII to EBCDIC. */
251 {"ibm", C_IBM
| C_TWOBUFS
}, /* Slightly different ASCII to EBCDIC. */
252 {"block", C_BLOCK
| C_TWOBUFS
}, /* Variable to fixed length records. */
253 {"unblock", C_UNBLOCK
| C_TWOBUFS
}, /* Fixed to variable length records. */
254 {"lcase", C_LCASE
| C_TWOBUFS
}, /* Translate upper to lower case. */
255 {"ucase", C_UCASE
| C_TWOBUFS
}, /* Translate lower to upper case. */
256 {"swab", C_SWAB
| C_TWOBUFS
}, /* Swap bytes of input. */
257 {"noerror", C_NOERROR
}, /* Ignore i/o errors. */
258 {"nocreat", C_NOCREAT
}, /* Do not create output file. */
259 {"excl", C_EXCL
}, /* Fail if the output file already exists. */
260 {"notrunc", C_NOTRUNC
}, /* Do not truncate output file. */
261 {"sync", C_SYNC
}, /* Pad input records to ibs with NULs. */
262 {"fdatasync", C_FDATASYNC
}, /* Synchronize output data before finishing. */
263 {"fsync", C_FSYNC
}, /* Also synchronize output metadata. */
269 /* Compute a value that's bitwise disjoint from the union
286 /* Use its lowest bit. */
287 O_FULLBLOCK
= v
^ (v
& (v
- 1))
290 /* Ensure that we got something. */
291 verify (O_FULLBLOCK
!= 0);
293 #define MULTIPLE_BITS_SET(i) (((i) & ((i) - 1)) != 0)
295 /* Ensure that this is a single-bit value. */
296 verify ( ! MULTIPLE_BITS_SET (O_FULLBLOCK
));
298 /* Flags, for iflag="..." and oflag="...". */
299 static struct symbol_value
const flags
[] =
301 {"append", O_APPEND
},
302 {"binary", O_BINARY
},
304 {"direct", O_DIRECT
},
305 {"directory", O_DIRECTORY
},
307 {"noatime", O_NOATIME
},
308 {"noctty", O_NOCTTY
},
309 {"nofollow", HAVE_WORKING_O_NOFOLLOW
? O_NOFOLLOW
: 0},
310 {"nolinks", O_NOLINKS
},
311 {"nonblock", O_NONBLOCK
},
314 {"fullblock", O_FULLBLOCK
}, /* Accumulate full blocks from input. */
318 /* Status, for status="...". */
319 static struct symbol_value
const statuses
[] =
321 {"noxfer", STATUS_NOXFER
},
325 /* Translation table formed by applying successive transformations. */
326 static unsigned char trans_table
[256];
328 static char const ascii_to_ebcdic
[] =
330 '\000', '\001', '\002', '\003', '\067', '\055', '\056', '\057',
331 '\026', '\005', '\045', '\013', '\014', '\015', '\016', '\017',
332 '\020', '\021', '\022', '\023', '\074', '\075', '\062', '\046',
333 '\030', '\031', '\077', '\047', '\034', '\035', '\036', '\037',
334 '\100', '\117', '\177', '\173', '\133', '\154', '\120', '\175',
335 '\115', '\135', '\134', '\116', '\153', '\140', '\113', '\141',
336 '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367',
337 '\370', '\371', '\172', '\136', '\114', '\176', '\156', '\157',
338 '\174', '\301', '\302', '\303', '\304', '\305', '\306', '\307',
339 '\310', '\311', '\321', '\322', '\323', '\324', '\325', '\326',
340 '\327', '\330', '\331', '\342', '\343', '\344', '\345', '\346',
341 '\347', '\350', '\351', '\112', '\340', '\132', '\137', '\155',
342 '\171', '\201', '\202', '\203', '\204', '\205', '\206', '\207',
343 '\210', '\211', '\221', '\222', '\223', '\224', '\225', '\226',
344 '\227', '\230', '\231', '\242', '\243', '\244', '\245', '\246',
345 '\247', '\250', '\251', '\300', '\152', '\320', '\241', '\007',
346 '\040', '\041', '\042', '\043', '\044', '\025', '\006', '\027',
347 '\050', '\051', '\052', '\053', '\054', '\011', '\012', '\033',
348 '\060', '\061', '\032', '\063', '\064', '\065', '\066', '\010',
349 '\070', '\071', '\072', '\073', '\004', '\024', '\076', '\341',
350 '\101', '\102', '\103', '\104', '\105', '\106', '\107', '\110',
351 '\111', '\121', '\122', '\123', '\124', '\125', '\126', '\127',
352 '\130', '\131', '\142', '\143', '\144', '\145', '\146', '\147',
353 '\150', '\151', '\160', '\161', '\162', '\163', '\164', '\165',
354 '\166', '\167', '\170', '\200', '\212', '\213', '\214', '\215',
355 '\216', '\217', '\220', '\232', '\233', '\234', '\235', '\236',
356 '\237', '\240', '\252', '\253', '\254', '\255', '\256', '\257',
357 '\260', '\261', '\262', '\263', '\264', '\265', '\266', '\267',
358 '\270', '\271', '\272', '\273', '\274', '\275', '\276', '\277',
359 '\312', '\313', '\314', '\315', '\316', '\317', '\332', '\333',
360 '\334', '\335', '\336', '\337', '\352', '\353', '\354', '\355',
361 '\356', '\357', '\372', '\373', '\374', '\375', '\376', '\377'
364 static char const ascii_to_ibm
[] =
366 '\000', '\001', '\002', '\003', '\067', '\055', '\056', '\057',
367 '\026', '\005', '\045', '\013', '\014', '\015', '\016', '\017',
368 '\020', '\021', '\022', '\023', '\074', '\075', '\062', '\046',
369 '\030', '\031', '\077', '\047', '\034', '\035', '\036', '\037',
370 '\100', '\132', '\177', '\173', '\133', '\154', '\120', '\175',
371 '\115', '\135', '\134', '\116', '\153', '\140', '\113', '\141',
372 '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367',
373 '\370', '\371', '\172', '\136', '\114', '\176', '\156', '\157',
374 '\174', '\301', '\302', '\303', '\304', '\305', '\306', '\307',
375 '\310', '\311', '\321', '\322', '\323', '\324', '\325', '\326',
376 '\327', '\330', '\331', '\342', '\343', '\344', '\345', '\346',
377 '\347', '\350', '\351', '\255', '\340', '\275', '\137', '\155',
378 '\171', '\201', '\202', '\203', '\204', '\205', '\206', '\207',
379 '\210', '\211', '\221', '\222', '\223', '\224', '\225', '\226',
380 '\227', '\230', '\231', '\242', '\243', '\244', '\245', '\246',
381 '\247', '\250', '\251', '\300', '\117', '\320', '\241', '\007',
382 '\040', '\041', '\042', '\043', '\044', '\025', '\006', '\027',
383 '\050', '\051', '\052', '\053', '\054', '\011', '\012', '\033',
384 '\060', '\061', '\032', '\063', '\064', '\065', '\066', '\010',
385 '\070', '\071', '\072', '\073', '\004', '\024', '\076', '\341',
386 '\101', '\102', '\103', '\104', '\105', '\106', '\107', '\110',
387 '\111', '\121', '\122', '\123', '\124', '\125', '\126', '\127',
388 '\130', '\131', '\142', '\143', '\144', '\145', '\146', '\147',
389 '\150', '\151', '\160', '\161', '\162', '\163', '\164', '\165',
390 '\166', '\167', '\170', '\200', '\212', '\213', '\214', '\215',
391 '\216', '\217', '\220', '\232', '\233', '\234', '\235', '\236',
392 '\237', '\240', '\252', '\253', '\254', '\255', '\256', '\257',
393 '\260', '\261', '\262', '\263', '\264', '\265', '\266', '\267',
394 '\270', '\271', '\272', '\273', '\274', '\275', '\276', '\277',
395 '\312', '\313', '\314', '\315', '\316', '\317', '\332', '\333',
396 '\334', '\335', '\336', '\337', '\352', '\353', '\354', '\355',
397 '\356', '\357', '\372', '\373', '\374', '\375', '\376', '\377'
400 static char const ebcdic_to_ascii
[] =
402 '\000', '\001', '\002', '\003', '\234', '\011', '\206', '\177',
403 '\227', '\215', '\216', '\013', '\014', '\015', '\016', '\017',
404 '\020', '\021', '\022', '\023', '\235', '\205', '\010', '\207',
405 '\030', '\031', '\222', '\217', '\034', '\035', '\036', '\037',
406 '\200', '\201', '\202', '\203', '\204', '\012', '\027', '\033',
407 '\210', '\211', '\212', '\213', '\214', '\005', '\006', '\007',
408 '\220', '\221', '\026', '\223', '\224', '\225', '\226', '\004',
409 '\230', '\231', '\232', '\233', '\024', '\025', '\236', '\032',
410 '\040', '\240', '\241', '\242', '\243', '\244', '\245', '\246',
411 '\247', '\250', '\133', '\056', '\074', '\050', '\053', '\041',
412 '\046', '\251', '\252', '\253', '\254', '\255', '\256', '\257',
413 '\260', '\261', '\135', '\044', '\052', '\051', '\073', '\136',
414 '\055', '\057', '\262', '\263', '\264', '\265', '\266', '\267',
415 '\270', '\271', '\174', '\054', '\045', '\137', '\076', '\077',
416 '\272', '\273', '\274', '\275', '\276', '\277', '\300', '\301',
417 '\302', '\140', '\072', '\043', '\100', '\047', '\075', '\042',
418 '\303', '\141', '\142', '\143', '\144', '\145', '\146', '\147',
419 '\150', '\151', '\304', '\305', '\306', '\307', '\310', '\311',
420 '\312', '\152', '\153', '\154', '\155', '\156', '\157', '\160',
421 '\161', '\162', '\313', '\314', '\315', '\316', '\317', '\320',
422 '\321', '\176', '\163', '\164', '\165', '\166', '\167', '\170',
423 '\171', '\172', '\322', '\323', '\324', '\325', '\326', '\327',
424 '\330', '\331', '\332', '\333', '\334', '\335', '\336', '\337',
425 '\340', '\341', '\342', '\343', '\344', '\345', '\346', '\347',
426 '\173', '\101', '\102', '\103', '\104', '\105', '\106', '\107',
427 '\110', '\111', '\350', '\351', '\352', '\353', '\354', '\355',
428 '\175', '\112', '\113', '\114', '\115', '\116', '\117', '\120',
429 '\121', '\122', '\356', '\357', '\360', '\361', '\362', '\363',
430 '\134', '\237', '\123', '\124', '\125', '\126', '\127', '\130',
431 '\131', '\132', '\364', '\365', '\366', '\367', '\370', '\371',
432 '\060', '\061', '\062', '\063', '\064', '\065', '\066', '\067',
433 '\070', '\071', '\372', '\373', '\374', '\375', '\376', '\377'
436 /* True if we need to close the standard output *stream*. */
437 static bool close_stdout_required
= true;
439 /* The only reason to close the standard output *stream* is if
440 parse_long_options fails (as it does for --help or --version).
441 In any other case, dd uses only the STDOUT_FILENO file descriptor,
442 and the "cleanup" function calls "close (STDOUT_FILENO)".
443 Closing the file descriptor and then letting the usual atexit-run
444 close_stdout function call "fclose (stdout)" would result in a
445 harmless failure of the close syscall (with errno EBADF).
446 This function serves solely to avoid the unnecessary close_stdout
447 call, once parse_long_options has succeeded. */
449 maybe_close_stdout (void)
451 if (close_stdout_required
)
458 if (status
!= EXIT_SUCCESS
)
459 fprintf (stderr
, _("Try `%s --help' for more information.\n"),
464 Usage: %s [OPERAND]...\n\
467 program_name
, program_name
);
469 Copy a file, converting and formatting according to the operands.\n\
471 bs=BYTES read and write BYTES bytes at a time (also see ibs=,obs=)\n\
472 cbs=BYTES convert BYTES bytes at a time\n\
473 conv=CONVS convert the file as per the comma separated symbol list\n\
474 count=BLOCKS copy only BLOCKS input blocks\n\
475 ibs=BYTES read BYTES bytes at a time (default: 512)\n\
478 if=FILE read from FILE instead of stdin\n\
479 iflag=FLAGS read as per the comma separated symbol list\n\
480 obs=BYTES write BYTES bytes at a time (default: 512)\n\
481 of=FILE write to FILE instead of stdout\n\
482 oflag=FLAGS write as per the comma separated symbol list\n\
483 seek=BLOCKS skip BLOCKS obs-sized blocks at start of output\n\
484 skip=BLOCKS skip BLOCKS ibs-sized blocks at start of input\n\
485 status=noxfer suppress transfer statistics\n\
489 BLOCKS and BYTES may be followed by the following multiplicative suffixes:\n\
490 c =1, w =2, b =512, kB =1000, K =1024, MB =1000*1000, M =1024*1024, xM =M\n\
491 GB =1000*1000*1000, G =1024*1024*1024, and so on for T, P, E, Z, Y.\n\
493 Each CONV symbol may be:\n\
497 ascii from EBCDIC to ASCII\n\
498 ebcdic from ASCII to EBCDIC\n\
499 ibm from ASCII to alternate EBCDIC\n\
500 block pad newline-terminated records with spaces to cbs-size\n\
501 unblock replace trailing spaces in cbs-size records with newline\n\
502 lcase change upper case to lower case\n\
505 nocreat do not create the output file\n\
506 excl fail if the output file already exists\n\
507 notrunc do not truncate the output file\n\
508 ucase change lower case to upper case\n\
509 swab swap every pair of input bytes\n\
512 noerror continue after read errors\n\
513 sync pad every input block with NULs to ibs-size; when used\n\
514 with block or unblock, pad with spaces rather than NULs\n\
515 fdatasync physically write output file data before finishing\n\
516 fsync likewise, but also write metadata\n\
520 Each FLAG symbol may be:\n\
522 append append mode (makes sense only for output; conv=notrunc suggested)\n\
525 fputs (_(" cio use concurrent I/O for data\n"), stdout
);
527 fputs (_(" direct use direct I/O for data\n"), stdout
);
529 fputs (_(" directory fail unless a directory\n"), stdout
);
531 fputs (_(" dsync use synchronized I/O for data\n"), stdout
);
533 fputs (_(" sync likewise, but also for metadata\n"), stdout
);
534 fputs (_(" fullblock accumulate full blocks of input (iflag only)\n"),
537 fputs (_(" nonblock use non-blocking I/O\n"), stdout
);
539 fputs (_(" noatime do not update access time\n"), stdout
);
541 fputs (_(" noctty do not assign controlling terminal from file\n"),
543 if (HAVE_WORKING_O_NOFOLLOW
)
544 fputs (_(" nofollow do not follow symlinks\n"), stdout
);
546 fputs (_(" nolinks fail if multiply-linked\n"), stdout
);
548 fputs (_(" binary use binary I/O for data\n"), stdout
);
550 fputs (_(" text use text I/O for data\n"), stdout
);
553 char const *siginfo_name
= (SIGINFO
== SIGUSR1
? "USR1" : "INFO");
556 Sending a %s signal to a running `dd' process makes it\n\
557 print I/O statistics to standard error and then resume copying.\n\
559 $ dd if=/dev/zero of=/dev/null& pid=$!\n\
560 $ kill -%s $pid; sleep 1; kill $pid\n\
561 18335302+0 records in\n\
562 18335302+0 records out\n\
563 9387674624 bytes (9.4 GB) copied, 34.6279 seconds, 271 MB/s\n\
568 siginfo_name
, siginfo_name
);
571 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
572 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
573 emit_bug_reporting_address ();
579 translate_charset (char const *new_trans
)
583 for (i
= 0; i
< 256; i
++)
584 trans_table
[i
] = new_trans
[trans_table
[i
]];
585 translation_needed
= true;
588 /* Return true if I has more than one bit set. I must be nonnegative. */
591 multiple_bits_set (int i
)
593 return MULTIPLE_BITS_SET (i
);
596 /* Print transfer statistics. */
601 xtime_t now
= gethrxtime ();
602 char hbuf
[LONGEST_HUMAN_READABLE
+ 1];
604 (human_autoscale
| human_round_to_nearest
605 | human_space_before_unit
| human_SI
| human_B
);
607 char const *bytes_per_second
;
610 _("%"PRIuMAX
"+%"PRIuMAX
" records in\n"
611 "%"PRIuMAX
"+%"PRIuMAX
" records out\n"),
612 r_full
, r_partial
, w_full
, w_partial
);
616 ngettext ("%"PRIuMAX
" truncated record\n",
617 "%"PRIuMAX
" truncated records\n",
618 select_plural (r_truncate
)),
621 if (status_flags
& STATUS_NOXFER
)
624 /* Use integer arithmetic to compute the transfer rate,
625 since that makes it easy to use SI abbreviations. */
628 ngettext ("%"PRIuMAX
" byte (%s) copied",
629 "%"PRIuMAX
" bytes (%s) copied",
630 select_plural (w_bytes
)),
632 human_readable (w_bytes
, hbuf
, human_opts
, 1, 1));
634 if (start_time
< now
)
636 double XTIME_PRECISIONe0
= XTIME_PRECISION
;
637 uintmax_t delta_xtime
= now
;
638 delta_xtime
-= start_time
;
639 delta_s
= delta_xtime
/ XTIME_PRECISIONe0
;
640 bytes_per_second
= human_readable (w_bytes
, hbuf
, human_opts
,
641 XTIME_PRECISION
, delta_xtime
);
646 bytes_per_second
= _("Infinity B");
649 /* TRANSLATORS: The two instances of "s" in this string are the SI
650 symbol "s" (meaning second), and should not be translated.
652 This format used to be:
654 ngettext (", %g second, %s/s\n", ", %g seconds, %s/s\n", delta_s == 1)
656 but that was incorrect for languages like Polish. To fix this
657 bug we now use SI symbols even though they're a bit more
658 confusing in English. */
659 fprintf (stderr
, _(", %g s, %s/s\n"), delta_s
, bytes_per_second
);
665 if (close (STDIN_FILENO
) < 0)
666 error (EXIT_FAILURE
, errno
,
667 _("closing input file %s"), quote (input_file
));
669 /* Don't remove this call to close, even though close_stdout
670 closes standard output. This close is necessary when cleanup
671 is called as part of a signal handler. */
672 if (close (STDOUT_FILENO
) < 0)
673 error (EXIT_FAILURE
, errno
,
674 _("closing output file %s"), quote (output_file
));
677 static void ATTRIBUTE_NORETURN
686 /* An ordinary signal was received; arrange for the program to exit. */
689 interrupt_handler (int sig
)
692 signal (sig
, SIG_DFL
);
693 interrupt_signal
= sig
;
696 /* An info signal was received; arrange for the program to print status. */
699 siginfo_handler (int sig
)
702 signal (sig
, siginfo_handler
);
706 /* Install the signal handlers. */
709 install_signal_handlers (void)
711 bool catch_siginfo
= ! (SIGINFO
== SIGUSR1
&& getenv ("POSIXLY_CORRECT"));
715 struct sigaction act
;
716 sigemptyset (&caught_signals
);
719 sigaction (SIGINFO
, NULL
, &act
);
720 if (act
.sa_handler
!= SIG_IGN
)
721 sigaddset (&caught_signals
, SIGINFO
);
723 sigaction (SIGINT
, NULL
, &act
);
724 if (act
.sa_handler
!= SIG_IGN
)
725 sigaddset (&caught_signals
, SIGINT
);
726 act
.sa_mask
= caught_signals
;
728 if (sigismember (&caught_signals
, SIGINFO
))
730 act
.sa_handler
= siginfo_handler
;
732 sigaction (SIGINFO
, &act
, NULL
);
735 if (sigismember (&caught_signals
, SIGINT
))
737 /* POSIX 1003.1-2001 says SA_RESETHAND implies SA_NODEFER,
738 but this is not true on Solaris 8 at least. It doesn't
739 hurt to use SA_NODEFER here, so leave it in. */
740 act
.sa_handler
= interrupt_handler
;
741 act
.sa_flags
= SA_NODEFER
| SA_RESETHAND
;
742 sigaction (SIGINT
, &act
, NULL
);
747 if (catch_siginfo
&& signal (SIGINFO
, SIG_IGN
) != SIG_IGN
)
749 signal (SIGINFO
, siginfo_handler
);
750 siginterrupt (SIGINFO
, 1);
752 if (signal (SIGINT
, SIG_IGN
) != SIG_IGN
)
754 signal (SIGINT
, interrupt_handler
);
755 siginterrupt (SIGINT
, 1);
760 /* Process any pending signals. If signals are caught, this function
761 should be called periodically. Ideally there should never be an
762 unbounded amount of time when signals are not being processed. */
765 process_signals (void)
767 while (interrupt_signal
| info_signal_count
)
773 sigprocmask (SIG_BLOCK
, &caught_signals
, &oldset
);
775 /* Reload interrupt_signal and info_signal_count, in case a new
776 signal was handled before sigprocmask took effect. */
777 interrupt
= interrupt_signal
;
778 infos
= info_signal_count
;
781 info_signal_count
= infos
- 1;
783 sigprocmask (SIG_SETMASK
, &oldset
, NULL
);
793 /* Read from FD into the buffer BUF of size SIZE, processing any
794 signals that arrive before bytes are read. Return the number of
795 bytes read if successful, -1 (setting errno) on failure. */
798 iread (int fd
, char *buf
, size_t size
)
804 nread
= read (fd
, buf
, size
);
805 if (! (nread
< 0 && errno
== EINTR
))
810 /* Wrapper around iread function to accumulate full blocks. */
812 iread_fullblock (int fd
, char *buf
, size_t size
)
818 ssize_t ncurr
= iread (fd
, buf
, size
);
831 /* Write to FD the buffer BUF of size SIZE, processing any signals
832 that arrive. Return the number of bytes written, setting errno if
833 this is less than SIZE. Keep trying if there are partial
837 iwrite (int fd
, char const *buf
, size_t size
)
839 size_t total_written
= 0;
841 if ((output_flags
& O_DIRECT
) && size
< output_blocksize
)
843 int old_flags
= fcntl (STDOUT_FILENO
, F_GETFL
);
844 if (fcntl (STDOUT_FILENO
, F_SETFL
, old_flags
& ~O_DIRECT
) != 0)
845 error (0, errno
, _("failed to turn off O_DIRECT: %s"),
846 quote (output_file
));
848 /* Since we have just turned off O_DIRECT for the final write,
849 here we try to preserve some of its semantics. First, use
850 posix_fadvise to tell the system not to pollute the buffer
851 cache with this data. Don't bother to diagnose lseek or
852 posix_fadvise failure. */
853 #ifdef POSIX_FADV_DONTNEED
854 off_t off
= lseek (STDOUT_FILENO
, 0, SEEK_CUR
);
856 ignore_value (posix_fadvise (STDOUT_FILENO
,
857 off
, 0, POSIX_FADV_DONTNEED
));
860 /* Attempt to ensure that that final block is committed
861 to disk as quickly as possible. */
862 conversions_mask
|= C_FSYNC
;
865 while (total_written
< size
)
869 nwritten
= write (fd
, buf
+ total_written
, size
- total_written
);
875 else if (nwritten
== 0)
877 /* Some buggy drivers return 0 when one tries to write beyond
878 a device's end. (Example: Linux kernel 1.2.13 on /dev/fd0.)
879 Set errno to ENOSPC so they get a sensible diagnostic. */
884 total_written
+= nwritten
;
887 return total_written
;
890 /* Write, then empty, the output buffer `obuf'. */
895 size_t nwritten
= iwrite (STDOUT_FILENO
, obuf
, output_blocksize
);
897 if (nwritten
!= output_blocksize
)
899 error (0, errno
, _("writing to %s"), quote (output_file
));
909 /* Return true if STR is of the form "PATTERN" or "PATTERNDELIM...". */
912 operand_matches (char const *str
, char const *pattern
, char delim
)
915 if (*str
++ != *pattern
++)
917 return !*str
|| *str
== delim
;
920 /* Interpret one "conv=..." or similar operand STR according to the
921 symbols in TABLE, returning the flags specified. If the operand
922 cannot be parsed, use ERROR_MSGID to generate a diagnostic. */
925 parse_symbols (char const *str
, struct symbol_value
const *table
,
926 char const *error_msgid
)
932 char const *strcomma
= strchr (str
, ',');
933 struct symbol_value
const *entry
;
936 ! (operand_matches (str
, entry
->symbol
, ',') && entry
->value
);
939 if (! entry
->symbol
[0])
941 size_t slen
= strcomma
? strcomma
- str
: strlen (str
);
942 error (0, 0, "%s: %s", _(error_msgid
),
943 quotearg_n_style_mem (0, locale_quoting_style
, str
, slen
));
944 usage (EXIT_FAILURE
);
948 value
|= entry
->value
;
957 /* Return the value of STR, interpreted as a non-negative decimal integer,
958 optionally multiplied by various values.
959 Set *INVALID if STR does not represent a number in this format. */
962 parse_integer (const char *str
, bool *invalid
)
966 enum strtol_error e
= xstrtoumax (str
, &suffix
, 10, &n
, "bcEGkKMPTwYZ0");
968 if (e
== LONGINT_INVALID_SUFFIX_CHAR
&& *suffix
== 'x')
970 uintmax_t multiplier
= parse_integer (suffix
+ 1, invalid
);
972 if (multiplier
!= 0 && n
* multiplier
/ multiplier
!= n
)
980 else if (e
!= LONGINT_OK
)
989 /* OPERAND is of the form "X=...". Return true if X is NAME. */
992 operand_is (char const *operand
, char const *name
)
994 return operand_matches (operand
, name
, '=');
998 scanargs (int argc
, char *const *argv
)
1001 size_t blocksize
= 0;
1003 for (i
= optind
; i
< argc
; i
++)
1005 char const *name
= argv
[i
];
1006 char const *val
= strchr (name
, '=');
1010 error (0, 0, _("unrecognized operand %s"), quote (name
));
1011 usage (EXIT_FAILURE
);
1015 if (operand_is (name
, "if"))
1017 else if (operand_is (name
, "of"))
1019 else if (operand_is (name
, "conv"))
1020 conversions_mask
|= parse_symbols (val
, conversions
,
1021 N_("invalid conversion"));
1022 else if (operand_is (name
, "iflag"))
1023 input_flags
|= parse_symbols (val
, flags
,
1024 N_("invalid input flag"));
1025 else if (operand_is (name
, "oflag"))
1026 output_flags
|= parse_symbols (val
, flags
,
1027 N_("invalid output flag"));
1028 else if (operand_is (name
, "status"))
1029 status_flags
|= parse_symbols (val
, statuses
,
1030 N_("invalid status flag"));
1033 bool invalid
= false;
1034 uintmax_t n
= parse_integer (val
, &invalid
);
1036 if (operand_is (name
, "ibs"))
1038 invalid
|= ! (0 < n
&& n
<= MAX_BLOCKSIZE (INPUT_BLOCK_SLOP
));
1039 input_blocksize
= n
;
1041 else if (operand_is (name
, "obs"))
1043 invalid
|= ! (0 < n
&& n
<= MAX_BLOCKSIZE (OUTPUT_BLOCK_SLOP
));
1044 output_blocksize
= n
;
1046 else if (operand_is (name
, "bs"))
1048 invalid
|= ! (0 < n
&& n
<= MAX_BLOCKSIZE (INPUT_BLOCK_SLOP
));
1051 else if (operand_is (name
, "cbs"))
1053 invalid
|= ! (0 < n
&& n
<= SIZE_MAX
);
1054 conversion_blocksize
= n
;
1056 else if (operand_is (name
, "skip"))
1058 else if (operand_is (name
, "seek"))
1060 else if (operand_is (name
, "count"))
1064 error (0, 0, _("unrecognized operand %s"), quote (name
));
1065 usage (EXIT_FAILURE
);
1069 error (EXIT_FAILURE
, 0, _("invalid number %s"), quote (val
));
1074 input_blocksize
= output_blocksize
= blocksize
;
1077 /* POSIX says dd aggregates short reads into
1078 output_blocksize if bs= is not specified. */
1079 conversions_mask
|= C_TWOBUFS
;
1082 if (input_blocksize
== 0)
1083 input_blocksize
= DEFAULT_BLOCKSIZE
;
1084 if (output_blocksize
== 0)
1085 output_blocksize
= DEFAULT_BLOCKSIZE
;
1086 if (conversion_blocksize
== 0)
1087 conversions_mask
&= ~(C_BLOCK
| C_UNBLOCK
);
1089 if (input_flags
& (O_DSYNC
| O_SYNC
))
1090 input_flags
|= O_RSYNC
;
1092 if (output_flags
& O_FULLBLOCK
)
1094 error (0, 0, "%s: %s", _("invalid output flag"), "'fullblock'");
1095 usage (EXIT_FAILURE
);
1097 iread_fnc
= ((input_flags
& O_FULLBLOCK
)
1100 input_flags
&= ~O_FULLBLOCK
;
1102 if (multiple_bits_set (conversions_mask
& (C_ASCII
| C_EBCDIC
| C_IBM
)))
1103 error (EXIT_FAILURE
, 0, _("cannot combine any two of {ascii,ebcdic,ibm}"));
1104 if (multiple_bits_set (conversions_mask
& (C_BLOCK
| C_UNBLOCK
)))
1105 error (EXIT_FAILURE
, 0, _("cannot combine block and unblock"));
1106 if (multiple_bits_set (conversions_mask
& (C_LCASE
| C_UCASE
)))
1107 error (EXIT_FAILURE
, 0, _("cannot combine lcase and ucase"));
1108 if (multiple_bits_set (conversions_mask
& (C_EXCL
| C_NOCREAT
)))
1109 error (EXIT_FAILURE
, 0, _("cannot combine excl and nocreat"));
1112 /* Fix up translation table. */
1115 apply_translations (void)
1119 if (conversions_mask
& C_ASCII
)
1120 translate_charset (ebcdic_to_ascii
);
1122 if (conversions_mask
& C_UCASE
)
1124 for (i
= 0; i
< 256; i
++)
1125 trans_table
[i
] = toupper (trans_table
[i
]);
1126 translation_needed
= true;
1128 else if (conversions_mask
& C_LCASE
)
1130 for (i
= 0; i
< 256; i
++)
1131 trans_table
[i
] = tolower (trans_table
[i
]);
1132 translation_needed
= true;
1135 if (conversions_mask
& C_EBCDIC
)
1137 translate_charset (ascii_to_ebcdic
);
1138 newline_character
= ascii_to_ebcdic
['\n'];
1139 space_character
= ascii_to_ebcdic
[' '];
1141 else if (conversions_mask
& C_IBM
)
1143 translate_charset (ascii_to_ibm
);
1144 newline_character
= ascii_to_ibm
['\n'];
1145 space_character
= ascii_to_ibm
[' '];
1149 /* Apply the character-set translations specified by the user
1150 to the NREAD bytes in BUF. */
1153 translate_buffer (char *buf
, size_t nread
)
1158 for (i
= nread
, cp
= buf
; i
; i
--, cp
++)
1159 *cp
= trans_table
[to_uchar (*cp
)];
1162 /* If true, the last char from the previous call to `swab_buffer'
1163 is saved in `saved_char'. */
1164 static bool char_is_saved
= false;
1166 /* Odd char from previous call. */
1167 static char saved_char
;
1169 /* Swap NREAD bytes in BUF, plus possibly an initial char from the
1170 previous call. If NREAD is odd, save the last char for the
1171 next call. Return the new start of the BUF buffer. */
1174 swab_buffer (char *buf
, size_t *nread
)
1176 char *bufstart
= buf
;
1180 /* Is a char left from last time? */
1183 *--bufstart
= saved_char
;
1185 char_is_saved
= false;
1190 /* An odd number of chars are in the buffer. */
1191 saved_char
= bufstart
[--*nread
];
1192 char_is_saved
= true;
1195 /* Do the byte-swapping by moving every second character two
1196 positions toward the end, working from the end of the buffer
1197 toward the beginning. This way we only move half of the data. */
1199 cp
= bufstart
+ *nread
; /* Start one char past the last. */
1200 for (i
= *nread
/ 2; i
; i
--, cp
-= 2)
1206 /* Add OFFSET to the input offset, setting the overflow flag if
1210 advance_input_offset (uintmax_t offset
)
1212 input_offset
+= offset
;
1213 if (input_offset
< offset
)
1214 input_offset_overflow
= true;
1217 /* This is a wrapper for lseek. It detects and warns about a kernel
1218 bug that makes lseek a no-op for tape devices, even though the kernel
1219 lseek return value suggests that the function succeeded.
1221 The parameters are the same as those of the lseek function, but
1222 with the addition of FILENAME, the name of the file associated with
1223 descriptor FDESC. The file name is used solely in the warning that's
1224 printed when the bug is detected. Return the same value that lseek
1225 would have returned, but when the lseek bug is detected, return -1
1226 to indicate that lseek failed.
1228 The offending behavior has been confirmed with an Exabyte SCSI tape
1229 drive accessed via /dev/nst0 on both Linux 2.2.17 and 2.4.16 kernels. */
1233 # include <sys/mtio.h>
1235 # define MT_SAME_POSITION(P, Q) \
1236 ((P).mt_resid == (Q).mt_resid \
1237 && (P).mt_fileno == (Q).mt_fileno \
1238 && (P).mt_blkno == (Q).mt_blkno)
1241 skip_via_lseek (char const *filename
, int fdesc
, off_t offset
, int whence
)
1245 bool got_original_tape_position
= (ioctl (fdesc
, MTIOCGET
, &s1
) == 0);
1246 /* known bad device type */
1247 /* && s.mt_type == MT_ISSCSI2 */
1249 off_t new_position
= lseek (fdesc
, offset
, whence
);
1250 if (0 <= new_position
1251 && got_original_tape_position
1252 && ioctl (fdesc
, MTIOCGET
, &s2
) == 0
1253 && MT_SAME_POSITION (s1
, s2
))
1255 error (0, 0, _("warning: working around lseek kernel bug for file (%s)\n\
1256 of mt_type=0x%0lx -- see <sys/mtio.h> for the list of types"),
1257 filename
, s2
.mt_type
);
1262 return new_position
;
1265 # define skip_via_lseek(Filename, Fd, Offset, Whence) lseek (Fd, Offset, Whence)
1268 /* Throw away RECORDS blocks of BLOCKSIZE bytes on file descriptor FDESC,
1269 which is open with read permission for FILE. Store up to BLOCKSIZE
1270 bytes of the data at a time in BUF, if necessary. RECORDS must be
1271 nonzero. If fdesc is STDIN_FILENO, advance the input offset.
1272 Return the number of records remaining, i.e., that were not skipped
1273 because EOF was reached. */
1276 skip (int fdesc
, char const *file
, uintmax_t records
, size_t blocksize
,
1279 uintmax_t offset
= records
* blocksize
;
1281 /* Try lseek and if an error indicates it was an inappropriate operation --
1282 or if the file offset is not representable as an off_t --
1283 fall back on using read. */
1286 if (records
<= OFF_T_MAX
/ blocksize
1287 && 0 <= skip_via_lseek (file
, fdesc
, offset
, SEEK_CUR
))
1289 if (fdesc
== STDIN_FILENO
)
1292 if (fstat (STDIN_FILENO
, &st
) != 0)
1293 error (EXIT_FAILURE
, errno
, _("cannot fstat %s"), quote (file
));
1294 if (S_ISREG (st
.st_mode
) && st
.st_size
< (input_offset
+ offset
))
1296 /* When skipping past EOF, return the number of _full_ blocks
1297 * that are not skipped, and set offset to EOF, so the caller
1298 * can determine the requested skip was not satisfied. */
1299 records
= ( offset
- st
.st_size
) / blocksize
;
1300 offset
= st
.st_size
- input_offset
;
1304 advance_input_offset (offset
);
1312 int lseek_errno
= errno
;
1315 /* The seek request may have failed above if it was too big
1316 (> device size, > max file size, etc.)
1317 Or it may not have been done at all (> OFF_T_MAX).
1318 Therefore try to seek to the end of the file,
1319 to avoid redundant reading. */
1320 if ((soffset
= skip_via_lseek (file
, fdesc
, 0, SEEK_END
)) >= 0)
1322 /* File is seekable, and we're at the end of it, and
1323 size <= OFF_T_MAX. So there's no point using read to advance. */
1327 /* The original seek was not attempted as offset > OFF_T_MAX.
1328 We should error for write as can't get to the desired
1329 location, even if OFF_T_MAX < max file size.
1330 For read we're not going to read any data anyway,
1331 so we should error for consistency.
1332 It would be nice to not error for /dev/{zero,null}
1333 for any offset, but that's not a significant issue. */
1334 lseek_errno
= EOVERFLOW
;
1337 if (fdesc
== STDIN_FILENO
)
1338 error (0, lseek_errno
, _("%s: cannot skip"), quote (file
));
1340 error (0, lseek_errno
, _("%s: cannot seek"), quote (file
));
1341 /* If the file has a specific size and we've asked
1342 to skip/seek beyond the max allowable, then quit. */
1343 quit (EXIT_FAILURE
);
1345 /* else file_size && offset > OFF_T_MAX or file ! seekable */
1349 ssize_t nread
= iread_fnc (fdesc
, buf
, blocksize
);
1352 if (fdesc
== STDIN_FILENO
)
1354 error (0, errno
, _("reading %s"), quote (file
));
1355 if (conversions_mask
& C_NOERROR
)
1362 error (0, lseek_errno
, _("%s: cannot seek"), quote (file
));
1363 quit (EXIT_FAILURE
);
1368 if (fdesc
== STDIN_FILENO
)
1369 advance_input_offset (nread
);
1371 while (--records
!= 0);
1377 /* Advance the input by NBYTES if possible, after a read error.
1378 The input file offset may or may not have advanced after the failed
1379 read; adjust it to point just after the bad record regardless.
1380 Return true if successful, or if the input is already known to not
1384 advance_input_after_read_error (size_t nbytes
)
1386 if (! input_seekable
)
1388 if (input_seek_errno
== ESPIPE
)
1390 errno
= input_seek_errno
;
1395 advance_input_offset (nbytes
);
1396 input_offset_overflow
|= (OFF_T_MAX
< input_offset
);
1397 if (input_offset_overflow
)
1399 error (0, 0, _("offset overflow while reading file %s"),
1400 quote (input_file
));
1403 offset
= lseek (STDIN_FILENO
, 0, SEEK_CUR
);
1407 if (offset
== input_offset
)
1409 diff
= input_offset
- offset
;
1410 if (! (0 <= diff
&& diff
<= nbytes
))
1411 error (0, 0, _("warning: invalid file offset after failed read"));
1412 if (0 <= skip_via_lseek (input_file
, STDIN_FILENO
, diff
, SEEK_CUR
))
1415 error (0, 0, _("cannot work around kernel bug after all"));
1419 error (0, errno
, _("%s: cannot seek"), quote (input_file
));
1423 /* Copy NREAD bytes of BUF, with no conversions. */
1426 copy_simple (char const *buf
, size_t nread
)
1428 const char *start
= buf
; /* First uncopied char in BUF. */
1432 size_t nfree
= MIN (nread
, output_blocksize
- oc
);
1434 memcpy (obuf
+ oc
, start
, nfree
);
1436 nread
-= nfree
; /* Update the number of bytes left to copy. */
1439 if (oc
>= output_blocksize
)
1445 /* Copy NREAD bytes of BUF, doing conv=block
1446 (pad newline-terminated records to `conversion_blocksize',
1447 replacing the newline with trailing spaces). */
1450 copy_with_block (char const *buf
, size_t nread
)
1454 for (i
= nread
; i
; i
--, buf
++)
1456 if (*buf
== newline_character
)
1458 if (col
< conversion_blocksize
)
1461 for (j
= col
; j
< conversion_blocksize
; j
++)
1462 output_char (space_character
);
1468 if (col
== conversion_blocksize
)
1470 else if (col
< conversion_blocksize
)
1477 /* Copy NREAD bytes of BUF, doing conv=unblock
1478 (replace trailing spaces in `conversion_blocksize'-sized records
1482 copy_with_unblock (char const *buf
, size_t nread
)
1486 static size_t pending_spaces
= 0;
1488 for (i
= 0; i
< nread
; i
++)
1492 if (col
++ >= conversion_blocksize
)
1494 col
= pending_spaces
= 0; /* Wipe out any pending spaces. */
1495 i
--; /* Push the char back; get it later. */
1496 output_char (newline_character
);
1498 else if (c
== space_character
)
1502 /* `c' is the character after a run of spaces that were not
1503 at the end of the conversion buffer. Output them. */
1504 while (pending_spaces
)
1506 output_char (space_character
);
1514 /* Set the file descriptor flags for FD that correspond to the nonzero bits
1515 in ADD_FLAGS. The file's name is NAME. */
1518 set_fd_flags (int fd
, int add_flags
, char const *name
)
1520 /* Ignore file creation flags that are no-ops on file descriptors. */
1521 add_flags
&= ~ (O_NOCTTY
| O_NOFOLLOW
);
1525 int old_flags
= fcntl (fd
, F_GETFL
);
1526 int new_flags
= old_flags
| add_flags
;
1530 else if (old_flags
!= new_flags
)
1532 if (new_flags
& (O_DIRECTORY
| O_NOLINKS
))
1534 /* NEW_FLAGS contains at least one file creation flag that
1535 requires some checking of the open file descriptor. */
1537 if (fstat (fd
, &st
) != 0)
1539 else if ((new_flags
& O_DIRECTORY
) && ! S_ISDIR (st
.st_mode
))
1544 else if ((new_flags
& O_NOLINKS
) && 1 < st
.st_nlink
)
1549 new_flags
&= ~ (O_DIRECTORY
| O_NOLINKS
);
1552 if (ok
&& old_flags
!= new_flags
1553 && fcntl (fd
, F_SETFL
, new_flags
) == -1)
1558 error (EXIT_FAILURE
, errno
, _("setting flags for %s"), quote (name
));
1562 /* The main loop. */
1567 char *ibuf
, *bufstart
; /* Input buffer. */
1568 /* These are declared static so that even though we don't free the
1569 buffers, valgrind will recognize that there is no "real" leak. */
1570 static char *real_buf
; /* real buffer address before alignment */
1571 static char *real_obuf
;
1572 ssize_t nread
; /* Bytes read in the current block. */
1574 /* If nonzero, then the previously read block was partial and
1575 PARTREAD was its size. */
1576 size_t partread
= 0;
1578 int exit_status
= EXIT_SUCCESS
;
1579 size_t n_bytes_read
;
1581 /* Leave at least one extra byte at the beginning and end of `ibuf'
1582 for conv=swab, but keep the buffer address even. But some peculiar
1583 device drivers work only with word-aligned buffers, so leave an
1586 /* Some devices require alignment on a sector or page boundary
1587 (e.g. character disk devices). Align the input buffer to a
1588 page boundary to cover all bases. Note that due to the swab
1589 algorithm, we must have at least one byte in the page before
1590 the input buffer; thus we allocate 2 pages of slop in the
1591 real buffer. 8k above the blocksize shouldn't bother anyone.
1593 The page alignment is necessary on any Linux kernel that supports
1594 either the SGI raw I/O patch or Steven Tweedies raw I/O patch.
1595 It is necessary when accessing raw (i.e. character special) disk
1596 devices on Unixware or other SVR4-derived system. */
1598 real_buf
= xmalloc (input_blocksize
+ INPUT_BLOCK_SLOP
);
1600 ibuf
+= SWAB_ALIGN_OFFSET
; /* allow space for swab */
1602 ibuf
= ptr_align (ibuf
, page_size
);
1604 if (conversions_mask
& C_TWOBUFS
)
1606 /* Page-align the output buffer, too. */
1607 real_obuf
= xmalloc (output_blocksize
+ OUTPUT_BLOCK_SLOP
);
1608 obuf
= ptr_align (real_obuf
, page_size
);
1616 if (skip_records
!= 0)
1618 uintmax_t us_bytes
= input_offset
+ (skip_records
* input_blocksize
);
1619 uintmax_t us_blocks
= skip (STDIN_FILENO
, input_file
,
1620 skip_records
, input_blocksize
, ibuf
);
1621 us_bytes
-= input_offset
;
1623 /* POSIX doesn't say what to do when dd detects it has been
1624 asked to skip past EOF, so I assume it's non-fatal.
1625 There are 3 reasons why there might be unskipped blocks/bytes:
1626 1. file is too small
1627 2. pipe has not enough data
1629 if (us_blocks
|| (!input_offset_overflow
&& us_bytes
))
1632 _("%s: cannot skip to specified offset"), quote (input_file
));
1636 if (seek_records
!= 0)
1638 uintmax_t write_records
= skip (STDOUT_FILENO
, output_file
,
1639 seek_records
, output_blocksize
, obuf
);
1641 if (write_records
!= 0)
1643 memset (obuf
, 0, output_blocksize
);
1646 if (iwrite (STDOUT_FILENO
, obuf
, output_blocksize
)
1647 != output_blocksize
)
1649 error (0, errno
, _("writing to %s"), quote (output_file
));
1650 quit (EXIT_FAILURE
);
1652 while (--write_records
!= 0);
1656 if (max_records
== 0)
1661 if (r_partial
+ r_full
>= max_records
)
1664 /* Zero the buffer before reading, so that if we get a read error,
1665 whatever data we are able to read is followed by zeros.
1666 This minimizes data loss. */
1667 if ((conversions_mask
& C_SYNC
) && (conversions_mask
& C_NOERROR
))
1669 (conversions_mask
& (C_BLOCK
| C_UNBLOCK
)) ? ' ' : '\0',
1672 nread
= iread_fnc (STDIN_FILENO
, ibuf
, input_blocksize
);
1679 error (0, errno
, _("reading %s"), quote (input_file
));
1680 if (conversions_mask
& C_NOERROR
)
1683 /* Seek past the bad block if possible. */
1684 if (!advance_input_after_read_error (input_blocksize
- partread
))
1686 exit_status
= EXIT_FAILURE
;
1688 /* Suppress duplicate diagnostics. */
1689 input_seekable
= false;
1690 input_seek_errno
= ESPIPE
;
1692 if ((conversions_mask
& C_SYNC
) && !partread
)
1693 /* Replace the missing input with null bytes and
1694 proceed normally. */
1701 /* Write any partial block. */
1702 exit_status
= EXIT_FAILURE
;
1707 n_bytes_read
= nread
;
1708 advance_input_offset (nread
);
1710 if (n_bytes_read
< input_blocksize
)
1713 partread
= n_bytes_read
;
1714 if (conversions_mask
& C_SYNC
)
1716 if (!(conversions_mask
& C_NOERROR
))
1717 /* If C_NOERROR, we zeroed the block before reading. */
1718 memset (ibuf
+ n_bytes_read
,
1719 (conversions_mask
& (C_BLOCK
| C_UNBLOCK
)) ? ' ' : '\0',
1720 input_blocksize
- n_bytes_read
);
1721 n_bytes_read
= input_blocksize
;
1730 if (ibuf
== obuf
) /* If not C_TWOBUFS. */
1732 size_t nwritten
= iwrite (STDOUT_FILENO
, obuf
, n_bytes_read
);
1733 w_bytes
+= nwritten
;
1734 if (nwritten
!= n_bytes_read
)
1736 error (0, errno
, _("writing %s"), quote (output_file
));
1737 return EXIT_FAILURE
;
1739 else if (n_bytes_read
== input_blocksize
)
1746 /* Do any translations on the whole buffer at once. */
1748 if (translation_needed
)
1749 translate_buffer (ibuf
, n_bytes_read
);
1751 if (conversions_mask
& C_SWAB
)
1752 bufstart
= swab_buffer (ibuf
, &n_bytes_read
);
1756 if (conversions_mask
& C_BLOCK
)
1757 copy_with_block (bufstart
, n_bytes_read
);
1758 else if (conversions_mask
& C_UNBLOCK
)
1759 copy_with_unblock (bufstart
, n_bytes_read
);
1761 copy_simple (bufstart
, n_bytes_read
);
1764 /* If we have a char left as a result of conv=swab, output it. */
1767 if (conversions_mask
& C_BLOCK
)
1768 copy_with_block (&saved_char
, 1);
1769 else if (conversions_mask
& C_UNBLOCK
)
1770 copy_with_unblock (&saved_char
, 1);
1772 output_char (saved_char
);
1775 if ((conversions_mask
& C_BLOCK
) && col
> 0)
1777 /* If the final input line didn't end with a '\n', pad
1778 the output block to `conversion_blocksize' chars. */
1780 for (i
= col
; i
< conversion_blocksize
; i
++)
1781 output_char (space_character
);
1784 if ((conversions_mask
& C_UNBLOCK
) && col
== conversion_blocksize
)
1785 /* Add a final '\n' if there are exactly `conversion_blocksize'
1786 characters in the final record. */
1787 output_char (newline_character
);
1789 /* Write out the last block. */
1792 size_t nwritten
= iwrite (STDOUT_FILENO
, obuf
, oc
);
1793 w_bytes
+= nwritten
;
1798 error (0, errno
, _("writing %s"), quote (output_file
));
1799 return EXIT_FAILURE
;
1803 if ((conversions_mask
& C_FDATASYNC
) && fdatasync (STDOUT_FILENO
) != 0)
1805 if (errno
!= ENOSYS
&& errno
!= EINVAL
)
1807 error (0, errno
, _("fdatasync failed for %s"), quote (output_file
));
1808 exit_status
= EXIT_FAILURE
;
1810 conversions_mask
|= C_FSYNC
;
1813 if (conversions_mask
& C_FSYNC
)
1814 while (fsync (STDOUT_FILENO
) != 0)
1817 error (0, errno
, _("fsync failed for %s"), quote (output_file
));
1818 return EXIT_FAILURE
;
1825 main (int argc
, char **argv
)
1831 install_signal_handlers ();
1833 initialize_main (&argc
, &argv
);
1834 set_program_name (argv
[0]);
1835 setlocale (LC_ALL
, "");
1836 bindtextdomain (PACKAGE
, LOCALEDIR
);
1837 textdomain (PACKAGE
);
1839 /* Arrange to close stdout if parse_long_options exits. */
1840 atexit (maybe_close_stdout
);
1842 page_size
= getpagesize ();
1844 parse_long_options (argc
, argv
, PROGRAM_NAME
, PACKAGE
, Version
,
1845 usage
, AUTHORS
, (char const *) NULL
);
1846 close_stdout_required
= false;
1848 if (getopt_long (argc
, argv
, "", NULL
, NULL
) != -1)
1849 usage (EXIT_FAILURE
);
1851 /* Initialize translation table to identity translation. */
1852 for (i
= 0; i
< 256; i
++)
1855 /* Decode arguments. */
1856 scanargs (argc
, argv
);
1858 apply_translations ();
1860 if (input_file
== NULL
)
1862 input_file
= _("standard input");
1863 set_fd_flags (STDIN_FILENO
, input_flags
, input_file
);
1867 if (fd_reopen (STDIN_FILENO
, input_file
, O_RDONLY
| input_flags
, 0) < 0)
1868 error (EXIT_FAILURE
, errno
, _("opening %s"), quote (input_file
));
1871 offset
= lseek (STDIN_FILENO
, 0, SEEK_CUR
);
1872 input_seekable
= (0 <= offset
);
1873 input_offset
= MAX(0, offset
);
1874 input_seek_errno
= errno
;
1876 if (output_file
== NULL
)
1878 output_file
= _("standard output");
1879 set_fd_flags (STDOUT_FILENO
, output_flags
, output_file
);
1883 mode_t perms
= S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
| S_IROTH
| S_IWOTH
;
1886 | (conversions_mask
& C_NOCREAT
? 0 : O_CREAT
)
1887 | (conversions_mask
& C_EXCL
? O_EXCL
: 0)
1888 | (seek_records
|| (conversions_mask
& C_NOTRUNC
) ? 0 : O_TRUNC
));
1890 /* Open the output file with *read* access only if we might
1891 need to read to satisfy a `seek=' request. If we can't read
1892 the file, go ahead with write-only access; it might work. */
1894 || fd_reopen (STDOUT_FILENO
, output_file
, O_RDWR
| opts
, perms
) < 0)
1895 && (fd_reopen (STDOUT_FILENO
, output_file
, O_WRONLY
| opts
, perms
)
1897 error (EXIT_FAILURE
, errno
, _("opening %s"), quote (output_file
));
1899 if (seek_records
!= 0 && !(conversions_mask
& C_NOTRUNC
))
1901 uintmax_t size
= seek_records
* output_blocksize
;
1902 unsigned long int obs
= output_blocksize
;
1904 if (OFF_T_MAX
/ output_blocksize
< seek_records
)
1905 error (EXIT_FAILURE
, 0,
1906 _("offset too large: "
1907 "cannot truncate to a length of seek=%"PRIuMAX
""
1908 " (%lu-byte) blocks"),
1911 if (ftruncate (STDOUT_FILENO
, size
) != 0)
1913 /* Complain only when ftruncate fails on a regular file, a
1914 directory, or a shared memory object, as POSIX 1003.1-2004
1915 specifies ftruncate's behavior only for these file types.
1916 For example, do not complain when Linux kernel 2.4 ftruncate
1917 fails on /dev/fd0. */
1918 int ftruncate_errno
= errno
;
1919 struct stat stdout_stat
;
1920 if (fstat (STDOUT_FILENO
, &stdout_stat
) != 0)
1921 error (EXIT_FAILURE
, errno
, _("cannot fstat %s"),
1922 quote (output_file
));
1923 if (S_ISREG (stdout_stat
.st_mode
)
1924 || S_ISDIR (stdout_stat
.st_mode
)
1925 || S_TYPEISSHM (&stdout_stat
))
1926 error (EXIT_FAILURE
, ftruncate_errno
,
1927 _("failed to truncate to %"PRIuMAX
" bytes in output file %s"),
1928 size
, quote (output_file
));
1933 start_time
= gethrxtime ();
1935 exit_status
= dd_copy ();