1 /* dd -- convert a file while copying it.
2 Copyright (C) 85, 90, 91, 1995-2008 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 "long-options.h"
38 static void process_signals (void);
40 /* The official name of this program (e.g., no `g' prefix). */
41 #define PROGRAM_NAME "dd"
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. */
51 # define SA_NOCLDSTOP 0
52 # define sigprocmask(How, Set, Oset) /* empty */
54 # if ! HAVE_SIGINTERRUPT
55 # define siginterrupt(sig, flag) /* empty */
62 # define SA_RESETHAND 0
66 # define SIGINFO SIGUSR1
70 # define fdatasync(fd) (errno = ENOSYS, -1)
73 #define max(a, b) ((a) > (b) ? (a) : (b))
74 #define output_char(c) \
78 if (oc >= output_blocksize) \
83 /* Default input and output blocksize. */
84 #define DEFAULT_BLOCKSIZE 512
86 /* How many bytes to add to the input and output block sizes before invoking
87 malloc. See dd_copy for details. INPUT_BLOCK_SLOP must be no less than
89 #define INPUT_BLOCK_SLOP (2 * SWAB_ALIGN_OFFSET + 2 * page_size - 1)
90 #define OUTPUT_BLOCK_SLOP (page_size - 1)
92 /* Maximum blocksize for the given SLOP.
93 Keep it smaller than SIZE_MAX - SLOP, so that we can
94 allocate buffers that size. Keep it smaller than SSIZE_MAX, for
95 the benefit of system calls like "read". And keep it smaller than
96 OFF_T_MAX, for the benefit of the large-offset seek code. */
97 #define MAX_BLOCKSIZE(slop) MIN (SIZE_MAX - (slop), MIN (SSIZE_MAX, OFF_T_MAX))
99 /* Conversions bit masks. */
115 /* Use separate input and output buffers, and combine partial
121 C_FDATASYNC = 040000,
125 /* Status bit masks. */
131 /* The name of the input file, or NULL for the standard input. */
132 static char const *input_file = NULL;
134 /* The name of the output file, or NULL for the standard output. */
135 static char const *output_file = NULL;
137 /* The page size on this host. */
138 static size_t page_size;
140 /* The number of bytes in which atomic reads are done. */
141 static size_t input_blocksize = 0;
143 /* The number of bytes in which atomic writes are done. */
144 static size_t output_blocksize = 0;
146 /* Conversion buffer size, in bytes. 0 prevents conversions. */
147 static size_t conversion_blocksize = 0;
149 /* Skip this many records of `input_blocksize' bytes before input. */
150 static uintmax_t skip_records = 0;
152 /* Skip this many records of `output_blocksize' bytes before output. */
153 static uintmax_t seek_records = 0;
155 /* Copy only this many records. The default is effectively infinity. */
156 static uintmax_t max_records = (uintmax_t) -1;
158 /* Bit vector of conversions to apply. */
159 static int conversions_mask = 0;
161 /* Open flags for the input and output files. */
162 static int input_flags = 0;
163 static int output_flags = 0;
165 /* Status flags for what is printed to stderr. */
166 static int status_flags = 0;
168 /* If nonzero, filter characters through the translation table. */
169 static bool translation_needed = false;
171 /* Number of partial blocks written. */
172 static uintmax_t w_partial = 0;
174 /* Number of full blocks written. */
175 static uintmax_t w_full = 0;
177 /* Number of partial blocks read. */
178 static uintmax_t r_partial = 0;
180 /* Number of full blocks read. */
181 static uintmax_t r_full = 0;
183 /* Number of bytes written. */
184 static uintmax_t w_bytes = 0;
186 /* Time that dd started. */
187 static xtime_t start_time;
189 /* True if input is seekable. */
190 static bool input_seekable;
192 /* Error number corresponding to initial attempt to lseek input.
193 If ESPIPE, do not issue any more diagnostics about it. */
194 static int input_seek_errno;
196 /* File offset of the input, in bytes, along with a flag recording
197 whether it overflowed. The offset is valid only if the input is
198 seekable and if the offset has not overflowed. */
199 static uintmax_t input_offset;
200 static bool input_offset_overflow;
202 /* Records truncated by conv=block. */
203 static uintmax_t r_truncate = 0;
205 /* Output representation of newline and space characters.
206 They change if we're converting to EBCDIC. */
207 static char newline_character = '\n';
208 static char space_character = ' ';
213 /* Current index into `obuf'. */
214 static size_t oc = 0;
216 /* Index into current line, for `conv=block' and `conv=unblock'. */
217 static size_t col = 0;
219 /* The set of signals that are caught. */
220 static sigset_t caught_signals;
222 /* If nonzero, the value of the pending fatal signal. */
223 static sig_atomic_t volatile interrupt_signal;
225 /* A count of the number of pending info signals that have been received. */
226 static sig_atomic_t volatile info_signal_count;
228 /* A longest symbol in the struct symbol_values tables below. */
229 #define LONGEST_SYMBOL "fdatasync"
231 /* A symbol and the corresponding integer value. */
234 char symbol[sizeof LONGEST_SYMBOL];
238 /* Conversion symbols, for conv="...". */
239 static struct symbol_value const conversions[] =
241 {"ascii", C_ASCII | C_TWOBUFS}, /* EBCDIC to ASCII. */
242 {"ebcdic", C_EBCDIC | C_TWOBUFS}, /* ASCII to EBCDIC. */
243 {"ibm", C_IBM | C_TWOBUFS}, /* Slightly different ASCII to EBCDIC. */
244 {"block", C_BLOCK | C_TWOBUFS}, /* Variable to fixed length records. */
245 {"unblock", C_UNBLOCK | C_TWOBUFS}, /* Fixed to variable length records. */
246 {"lcase", C_LCASE | C_TWOBUFS}, /* Translate upper to lower case. */
247 {"ucase", C_UCASE | C_TWOBUFS}, /* Translate lower to upper case. */
248 {"swab", C_SWAB | C_TWOBUFS}, /* Swap bytes of input. */
249 {"noerror", C_NOERROR}, /* Ignore i/o errors. */
250 {"nocreat", C_NOCREAT}, /* Do not create output file. */
251 {"excl", C_EXCL}, /* Fail if the output file already exists. */
252 {"notrunc", C_NOTRUNC}, /* Do not truncate output file. */
253 {"sync", C_SYNC}, /* Pad input records to ibs with NULs. */
254 {"fdatasync", C_FDATASYNC}, /* Synchronize output data before finishing. */
255 {"fsync", C_FSYNC}, /* Also synchronize output metadata. */
259 /* Flags, for iflag="..." and oflag="...". */
260 static struct symbol_value const flags[] =
262 {"append", O_APPEND},
263 {"binary", O_BINARY},
264 {"direct", O_DIRECT},
265 {"directory", O_DIRECTORY},
267 {"noatime", O_NOATIME},
268 {"noctty", O_NOCTTY},
269 {"nofollow", HAVE_WORKING_O_NOFOLLOW ? O_NOFOLLOW : 0},
270 {"nolinks", O_NOLINKS},
271 {"nonblock", O_NONBLOCK},
277 /* Status, for status="...". */
278 static struct symbol_value const statuses[] =
280 {"noxfer", STATUS_NOXFER},
284 /* Translation table formed by applying successive transformations. */
285 static unsigned char trans_table[256];
287 static char const ascii_to_ebcdic[] =
289 '\000', '\001', '\002', '\003', '\067', '\055', '\056', '\057',
290 '\026', '\005', '\045', '\013', '\014', '\015', '\016', '\017',
291 '\020', '\021', '\022', '\023', '\074', '\075', '\062', '\046',
292 '\030', '\031', '\077', '\047', '\034', '\035', '\036', '\037',
293 '\100', '\117', '\177', '\173', '\133', '\154', '\120', '\175',
294 '\115', '\135', '\134', '\116', '\153', '\140', '\113', '\141',
295 '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367',
296 '\370', '\371', '\172', '\136', '\114', '\176', '\156', '\157',
297 '\174', '\301', '\302', '\303', '\304', '\305', '\306', '\307',
298 '\310', '\311', '\321', '\322', '\323', '\324', '\325', '\326',
299 '\327', '\330', '\331', '\342', '\343', '\344', '\345', '\346',
300 '\347', '\350', '\351', '\112', '\340', '\132', '\137', '\155',
301 '\171', '\201', '\202', '\203', '\204', '\205', '\206', '\207',
302 '\210', '\211', '\221', '\222', '\223', '\224', '\225', '\226',
303 '\227', '\230', '\231', '\242', '\243', '\244', '\245', '\246',
304 '\247', '\250', '\251', '\300', '\152', '\320', '\241', '\007',
305 '\040', '\041', '\042', '\043', '\044', '\025', '\006', '\027',
306 '\050', '\051', '\052', '\053', '\054', '\011', '\012', '\033',
307 '\060', '\061', '\032', '\063', '\064', '\065', '\066', '\010',
308 '\070', '\071', '\072', '\073', '\004', '\024', '\076', '\341',
309 '\101', '\102', '\103', '\104', '\105', '\106', '\107', '\110',
310 '\111', '\121', '\122', '\123', '\124', '\125', '\126', '\127',
311 '\130', '\131', '\142', '\143', '\144', '\145', '\146', '\147',
312 '\150', '\151', '\160', '\161', '\162', '\163', '\164', '\165',
313 '\166', '\167', '\170', '\200', '\212', '\213', '\214', '\215',
314 '\216', '\217', '\220', '\232', '\233', '\234', '\235', '\236',
315 '\237', '\240', '\252', '\253', '\254', '\255', '\256', '\257',
316 '\260', '\261', '\262', '\263', '\264', '\265', '\266', '\267',
317 '\270', '\271', '\272', '\273', '\274', '\275', '\276', '\277',
318 '\312', '\313', '\314', '\315', '\316', '\317', '\332', '\333',
319 '\334', '\335', '\336', '\337', '\352', '\353', '\354', '\355',
320 '\356', '\357', '\372', '\373', '\374', '\375', '\376', '\377'
323 static char const ascii_to_ibm[] =
325 '\000', '\001', '\002', '\003', '\067', '\055', '\056', '\057',
326 '\026', '\005', '\045', '\013', '\014', '\015', '\016', '\017',
327 '\020', '\021', '\022', '\023', '\074', '\075', '\062', '\046',
328 '\030', '\031', '\077', '\047', '\034', '\035', '\036', '\037',
329 '\100', '\132', '\177', '\173', '\133', '\154', '\120', '\175',
330 '\115', '\135', '\134', '\116', '\153', '\140', '\113', '\141',
331 '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367',
332 '\370', '\371', '\172', '\136', '\114', '\176', '\156', '\157',
333 '\174', '\301', '\302', '\303', '\304', '\305', '\306', '\307',
334 '\310', '\311', '\321', '\322', '\323', '\324', '\325', '\326',
335 '\327', '\330', '\331', '\342', '\343', '\344', '\345', '\346',
336 '\347', '\350', '\351', '\255', '\340', '\275', '\137', '\155',
337 '\171', '\201', '\202', '\203', '\204', '\205', '\206', '\207',
338 '\210', '\211', '\221', '\222', '\223', '\224', '\225', '\226',
339 '\227', '\230', '\231', '\242', '\243', '\244', '\245', '\246',
340 '\247', '\250', '\251', '\300', '\117', '\320', '\241', '\007',
341 '\040', '\041', '\042', '\043', '\044', '\025', '\006', '\027',
342 '\050', '\051', '\052', '\053', '\054', '\011', '\012', '\033',
343 '\060', '\061', '\032', '\063', '\064', '\065', '\066', '\010',
344 '\070', '\071', '\072', '\073', '\004', '\024', '\076', '\341',
345 '\101', '\102', '\103', '\104', '\105', '\106', '\107', '\110',
346 '\111', '\121', '\122', '\123', '\124', '\125', '\126', '\127',
347 '\130', '\131', '\142', '\143', '\144', '\145', '\146', '\147',
348 '\150', '\151', '\160', '\161', '\162', '\163', '\164', '\165',
349 '\166', '\167', '\170', '\200', '\212', '\213', '\214', '\215',
350 '\216', '\217', '\220', '\232', '\233', '\234', '\235', '\236',
351 '\237', '\240', '\252', '\253', '\254', '\255', '\256', '\257',
352 '\260', '\261', '\262', '\263', '\264', '\265', '\266', '\267',
353 '\270', '\271', '\272', '\273', '\274', '\275', '\276', '\277',
354 '\312', '\313', '\314', '\315', '\316', '\317', '\332', '\333',
355 '\334', '\335', '\336', '\337', '\352', '\353', '\354', '\355',
356 '\356', '\357', '\372', '\373', '\374', '\375', '\376', '\377'
359 static char const ebcdic_to_ascii[] =
361 '\000', '\001', '\002', '\003', '\234', '\011', '\206', '\177',
362 '\227', '\215', '\216', '\013', '\014', '\015', '\016', '\017',
363 '\020', '\021', '\022', '\023', '\235', '\205', '\010', '\207',
364 '\030', '\031', '\222', '\217', '\034', '\035', '\036', '\037',
365 '\200', '\201', '\202', '\203', '\204', '\012', '\027', '\033',
366 '\210', '\211', '\212', '\213', '\214', '\005', '\006', '\007',
367 '\220', '\221', '\026', '\223', '\224', '\225', '\226', '\004',
368 '\230', '\231', '\232', '\233', '\024', '\025', '\236', '\032',
369 '\040', '\240', '\241', '\242', '\243', '\244', '\245', '\246',
370 '\247', '\250', '\133', '\056', '\074', '\050', '\053', '\041',
371 '\046', '\251', '\252', '\253', '\254', '\255', '\256', '\257',
372 '\260', '\261', '\135', '\044', '\052', '\051', '\073', '\136',
373 '\055', '\057', '\262', '\263', '\264', '\265', '\266', '\267',
374 '\270', '\271', '\174', '\054', '\045', '\137', '\076', '\077',
375 '\272', '\273', '\274', '\275', '\276', '\277', '\300', '\301',
376 '\302', '\140', '\072', '\043', '\100', '\047', '\075', '\042',
377 '\303', '\141', '\142', '\143', '\144', '\145', '\146', '\147',
378 '\150', '\151', '\304', '\305', '\306', '\307', '\310', '\311',
379 '\312', '\152', '\153', '\154', '\155', '\156', '\157', '\160',
380 '\161', '\162', '\313', '\314', '\315', '\316', '\317', '\320',
381 '\321', '\176', '\163', '\164', '\165', '\166', '\167', '\170',
382 '\171', '\172', '\322', '\323', '\324', '\325', '\326', '\327',
383 '\330', '\331', '\332', '\333', '\334', '\335', '\336', '\337',
384 '\340', '\341', '\342', '\343', '\344', '\345', '\346', '\347',
385 '\173', '\101', '\102', '\103', '\104', '\105', '\106', '\107',
386 '\110', '\111', '\350', '\351', '\352', '\353', '\354', '\355',
387 '\175', '\112', '\113', '\114', '\115', '\116', '\117', '\120',
388 '\121', '\122', '\356', '\357', '\360', '\361', '\362', '\363',
389 '\134', '\237', '\123', '\124', '\125', '\126', '\127', '\130',
390 '\131', '\132', '\364', '\365', '\366', '\367', '\370', '\371',
391 '\060', '\061', '\062', '\063', '\064', '\065', '\066', '\067',
392 '\070', '\071', '\372', '\373', '\374', '\375', '\376', '\377'
395 /* True if we need to close the standard output *stream*. */
396 static bool close_stdout_required = true;
398 /* The only reason to close the standard output *stream* is if
399 parse_long_options fails (as it does for --help or --version).
400 In any other case, dd uses only the STDOUT_FILENO file descriptor,
401 and the "cleanup" function calls "close (STDOUT_FILENO)".
402 Closing the file descriptor and then letting the usual atexit-run
403 close_stdout function call "fclose (stdout)" would result in a
404 harmless failure of the close syscall (with errno EBADF).
405 This function serves solely to avoid the unnecessary close_stdout
406 call, once parse_long_options has succeeded. */
408 maybe_close_stdout (void)
410 if (close_stdout_required)
417 if (status != EXIT_SUCCESS)
418 fprintf (stderr, _("Try `%s --help' for more information.\n"),
423 Usage: %s [OPERAND]...\n\
426 program_name, program_name);
428 Copy a file, converting and formatting according to the operands.\n\
430 bs=BYTES force ibs=BYTES and obs=BYTES\n\
431 cbs=BYTES convert BYTES bytes at a time\n\
432 conv=CONVS convert the file as per the comma separated symbol list\n\
433 count=BLOCKS copy only BLOCKS input blocks\n\
434 ibs=BYTES read BYTES bytes at a time\n\
437 if=FILE read from FILE instead of stdin\n\
438 iflag=FLAGS read as per the comma separated symbol list\n\
439 obs=BYTES write BYTES bytes at a time\n\
440 of=FILE write to FILE instead of stdout\n\
441 oflag=FLAGS write as per the comma separated symbol list\n\
442 seek=BLOCKS skip BLOCKS obs-sized blocks at start of output\n\
443 skip=BLOCKS skip BLOCKS ibs-sized blocks at start of input\n\
444 status=noxfer suppress transfer statistics\n\
448 BLOCKS and BYTES may be followed by the following multiplicative suffixes:\n\
449 xM M, c 1, w 2, b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024,\n\
450 GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y.\n\
452 Each CONV symbol may be:\n\
456 ascii from EBCDIC to ASCII\n\
457 ebcdic from ASCII to EBCDIC\n\
458 ibm from ASCII to alternate EBCDIC\n\
459 block pad newline-terminated records with spaces to cbs-size\n\
460 unblock replace trailing spaces in cbs-size records with newline\n\
461 lcase change upper case to lower case\n\
464 nocreat do not create the output file\n\
465 excl fail if the output file already exists\n\
466 notrunc do not truncate the output file\n\
467 ucase change lower case to upper case\n\
468 swab swap every pair of input bytes\n\
471 noerror continue after read errors\n\
472 sync pad every input block with NULs to ibs-size; when used\n\
473 with block or unblock, pad with spaces rather than NULs\n\
474 fdatasync physically write output file data before finishing\n\
475 fsync likewise, but also write metadata\n\
479 Each FLAG symbol may be:\n\
481 append append mode (makes sense only for output; conv=notrunc suggested)\n\
484 fputs (_(" direct use direct I/O for data\n"), stdout);
486 fputs (_(" directory fail unless a directory\n"), stdout);
488 fputs (_(" dsync use synchronized I/O for data\n"), stdout);
490 fputs (_(" sync likewise, but also for metadata\n"), stdout);
492 fputs (_(" nonblock use non-blocking I/O\n"), stdout);
494 fputs (_(" noatime do not update access time\n"), stdout);
496 fputs (_(" noctty do not assign controlling terminal from file\n"),
498 if (HAVE_WORKING_O_NOFOLLOW)
499 fputs (_(" nofollow do not follow symlinks\n"), stdout);
501 fputs (_(" nolinks fail if multiply-linked\n"), stdout);
503 fputs (_(" binary use binary I/O for data\n"), stdout);
505 fputs (_(" text use text I/O for data\n"), stdout);
508 char const *siginfo_name = (SIGINFO == SIGUSR1 ? "USR1" : "INFO");
511 Sending a %s signal to a running `dd' process makes it\n\
512 print I/O statistics to standard error and then resume copying.\n\
514 $ dd if=/dev/zero of=/dev/null& pid=$!\n\
515 $ kill -%s $pid; sleep 1; kill $pid\n\
516 18335302+0 records in\n\
517 18335302+0 records out\n\
518 9387674624 bytes (9.4 GB) copied, 34.6279 seconds, 271 MB/s\n\
523 siginfo_name, siginfo_name);
526 fputs (HELP_OPTION_DESCRIPTION, stdout);
527 fputs (VERSION_OPTION_DESCRIPTION, stdout);
528 emit_bug_reporting_address ();
534 translate_charset (char const *new_trans)
538 for (i = 0; i < 256; i++)
539 trans_table[i] = new_trans[trans_table[i]];
540 translation_needed = true;
543 /* Return true if I has more than one bit set. I must be nonnegative. */
546 multiple_bits_set (int i)
548 return (i & (i - 1)) != 0;
551 /* Print transfer statistics. */
556 xtime_t now = gethrxtime ();
557 char hbuf[LONGEST_HUMAN_READABLE + 1];
559 (human_autoscale | human_round_to_nearest
560 | human_space_before_unit | human_SI | human_B);
562 char const *bytes_per_second;
565 _("%"PRIuMAX"+%"PRIuMAX" records in\n"
566 "%"PRIuMAX"+%"PRIuMAX" records out\n"),
567 r_full, r_partial, w_full, w_partial);
571 ngettext ("%"PRIuMAX" truncated record\n",
572 "%"PRIuMAX" truncated records\n",
573 select_plural (r_truncate)),
576 if (status_flags & STATUS_NOXFER)
579 /* Use integer arithmetic to compute the transfer rate,
580 since that makes it easy to use SI abbreviations. */
583 ngettext ("%"PRIuMAX" byte (%s) copied",
584 "%"PRIuMAX" bytes (%s) copied",
585 select_plural (w_bytes)),
587 human_readable (w_bytes, hbuf, human_opts, 1, 1));
589 if (start_time < now)
591 double XTIME_PRECISIONe0 = XTIME_PRECISION;
592 uintmax_t delta_xtime = now;
593 delta_xtime -= start_time;
594 delta_s = delta_xtime / XTIME_PRECISIONe0;
595 bytes_per_second = human_readable (w_bytes, hbuf, human_opts,
596 XTIME_PRECISION, delta_xtime);
601 bytes_per_second = _("Infinity B");
604 /* TRANSLATORS: The two instances of "s" in this string are the SI
605 symbol "s" (meaning second), and should not be translated.
607 This format used to be:
609 ngettext (", %g second, %s/s\n", ", %g seconds, %s/s\n", delta_s == 1)
611 but that was incorrect for languages like Polish. To fix this
612 bug we now use SI symbols even though they're a bit more
613 confusing in English. */
614 fprintf (stderr, _(", %g s, %s/s\n"), delta_s, bytes_per_second);
620 if (close (STDIN_FILENO) < 0)
621 error (EXIT_FAILURE, errno,
622 _("closing input file %s"), quote (input_file));
624 /* Don't remove this call to close, even though close_stdout
625 closes standard output. This close is necessary when cleanup
626 is called as part of a signal handler. */
627 if (close (STDOUT_FILENO) < 0)
628 error (EXIT_FAILURE, errno,
629 _("closing output file %s"), quote (output_file));
632 static inline void ATTRIBUTE_NORETURN
641 /* An ordinary signal was received; arrange for the program to exit. */
644 interrupt_handler (int sig)
647 signal (sig, SIG_DFL);
648 interrupt_signal = sig;
651 /* An info signal was received; arrange for the program to print status. */
654 siginfo_handler (int sig)
657 signal (sig, siginfo_handler);
661 /* Install the signal handlers. */
664 install_signal_handlers (void)
666 bool catch_siginfo = ! (SIGINFO == SIGUSR1 && getenv ("POSIXLY_CORRECT"));
670 struct sigaction act;
671 sigemptyset (&caught_signals);
674 sigaction (SIGINFO, NULL, &act);
675 if (act.sa_handler != SIG_IGN)
676 sigaddset (&caught_signals, SIGINFO);
678 sigaction (SIGINT, NULL, &act);
679 if (act.sa_handler != SIG_IGN)
680 sigaddset (&caught_signals, SIGINT);
681 act.sa_mask = caught_signals;
683 if (sigismember (&caught_signals, SIGINFO))
685 act.sa_handler = siginfo_handler;
687 sigaction (SIGINFO, &act, NULL);
690 if (sigismember (&caught_signals, SIGINT))
692 /* POSIX 1003.1-2001 says SA_RESETHAND implies SA_NODEFER,
693 but this is not true on Solaris 8 at least. It doesn't
694 hurt to use SA_NODEFER here, so leave it in. */
695 act.sa_handler = interrupt_handler;
696 act.sa_flags = SA_NODEFER | SA_RESETHAND;
697 sigaction (SIGINT, &act, NULL);
702 if (catch_siginfo && signal (SIGINFO, SIG_IGN) != SIG_IGN)
704 signal (SIGINFO, siginfo_handler);
705 siginterrupt (SIGINFO, 1);
707 if (signal (SIGINT, SIG_IGN) != SIG_IGN)
709 signal (SIGINT, interrupt_handler);
710 siginterrupt (SIGINT, 1);
715 /* Process any pending signals. If signals are caught, this function
716 should be called periodically. Ideally there should never be an
717 unbounded amount of time when signals are not being processed. */
720 process_signals (void)
722 while (interrupt_signal | info_signal_count)
728 sigprocmask (SIG_BLOCK, &caught_signals, &oldset);
730 /* Reload interrupt_signal and info_signal_count, in case a new
731 signal was handled before sigprocmask took effect. */
732 interrupt = interrupt_signal;
733 infos = info_signal_count;
736 info_signal_count = infos - 1;
738 sigprocmask (SIG_SETMASK, &oldset, NULL);
748 /* Read from FD into the buffer BUF of size SIZE, processing any
749 signals that arrive before bytes are read. Return the number of
750 bytes read if successful, -1 (setting errno) on failure. */
753 iread (int fd, char *buf, size_t size)
759 nread = read (fd, buf, size);
760 if (! (nread < 0 && errno == EINTR))
765 /* Write to FD the buffer BUF of size SIZE, processing any signals
766 that arrive. Return the number of bytes written, setting errno if
767 this is less than SIZE. Keep trying if there are partial
771 iwrite (int fd, char const *buf, size_t size)
773 size_t total_written = 0;
775 while (total_written < size)
779 nwritten = write (fd, buf + total_written, size - total_written);
785 else if (nwritten == 0)
787 /* Some buggy drivers return 0 when one tries to write beyond
788 a device's end. (Example: Linux 1.2.13 on /dev/fd0.)
789 Set errno to ENOSPC so they get a sensible diagnostic. */
794 total_written += nwritten;
797 return total_written;
800 /* Write, then empty, the output buffer `obuf'. */
805 size_t nwritten = iwrite (STDOUT_FILENO, obuf, output_blocksize);
807 if (nwritten != output_blocksize)
809 error (0, errno, _("writing to %s"), quote (output_file));
819 /* Return true if STR is of the form "PATTERN" or "PATTERNDELIM...". */
822 operand_matches (char const *str, char const *pattern, char delim)
825 if (*str++ != *pattern++)
827 return !*str || *str == delim;
830 /* Interpret one "conv=..." or similar operand STR according to the
831 symbols in TABLE, returning the flags specified. If the operand
832 cannot be parsed, use ERROR_MSGID to generate a diagnostic. */
835 parse_symbols (char const *str, struct symbol_value const *table,
836 char const *error_msgid)
842 char const *strcomma = strchr (str, ',');
843 struct symbol_value const *entry;
846 ! (operand_matches (str, entry->symbol, ',') && entry->value);
849 if (! entry->symbol[0])
851 size_t slen = strcomma ? strcomma - str : strlen (str);
852 error (0, 0, "%s: %s", _(error_msgid),
853 quotearg_n_style_mem (0, locale_quoting_style, str, slen));
854 usage (EXIT_FAILURE);
858 value |= entry->value;
867 /* Return the value of STR, interpreted as a non-negative decimal integer,
868 optionally multiplied by various values.
869 Set *INVALID if STR does not represent a number in this format. */
872 parse_integer (const char *str, bool *invalid)
876 enum strtol_error e = xstrtoumax (str, &suffix, 10, &n, "bcEGkKMPTwYZ0");
878 if (e == LONGINT_INVALID_SUFFIX_CHAR && *suffix == 'x')
880 uintmax_t multiplier = parse_integer (suffix + 1, invalid);
882 if (multiplier != 0 && n * multiplier / multiplier != n)
890 else if (e != LONGINT_OK)
899 /* OPERAND is of the form "X=...". Return true if X is NAME. */
902 operand_is (char const *operand, char const *name)
904 return operand_matches (operand, name, '=');
908 scanargs (int argc, char *const *argv)
911 size_t blocksize = 0;
913 for (i = optind; i < argc; i++)
915 char const *name = argv[i];
916 char const *val = strchr (name, '=');
920 error (0, 0, _("unrecognized operand %s"), quote (name));
921 usage (EXIT_FAILURE);
925 if (operand_is (name, "if"))
927 else if (operand_is (name, "of"))
929 else if (operand_is (name, "conv"))
930 conversions_mask |= parse_symbols (val, conversions,
931 N_("invalid conversion"));
932 else if (operand_is (name, "iflag"))
933 input_flags |= parse_symbols (val, flags,
934 N_("invalid input flag"));
935 else if (operand_is (name, "oflag"))
936 output_flags |= parse_symbols (val, flags,
937 N_("invalid output flag"));
938 else if (operand_is (name, "status"))
939 status_flags |= parse_symbols (val, statuses,
940 N_("invalid status flag"));
943 bool invalid = false;
944 uintmax_t n = parse_integer (val, &invalid);
946 if (operand_is (name, "ibs"))
948 invalid |= ! (0 < n && n <= MAX_BLOCKSIZE (INPUT_BLOCK_SLOP));
950 conversions_mask |= C_TWOBUFS;
952 else if (operand_is (name, "obs"))
954 invalid |= ! (0 < n && n <= MAX_BLOCKSIZE (OUTPUT_BLOCK_SLOP));
955 output_blocksize = n;
956 conversions_mask |= C_TWOBUFS;
958 else if (operand_is (name, "bs"))
960 invalid |= ! (0 < n && n <= MAX_BLOCKSIZE (INPUT_BLOCK_SLOP));
963 else if (operand_is (name, "cbs"))
965 invalid |= ! (0 < n && n <= SIZE_MAX);
966 conversion_blocksize = n;
968 else if (operand_is (name, "skip"))
970 else if (operand_is (name, "seek"))
972 else if (operand_is (name, "count"))
976 error (0, 0, _("unrecognized operand %s"), quote (name));
977 usage (EXIT_FAILURE);
981 error (EXIT_FAILURE, 0, _("invalid number %s"), quote (val));
986 input_blocksize = output_blocksize = blocksize;
988 /* If bs= was given, both `input_blocksize' and `output_blocksize' will
989 have been set to positive values. If either has not been set,
990 bs= was not given, so make sure two buffers are used. */
991 if (input_blocksize == 0 || output_blocksize == 0)
992 conversions_mask |= C_TWOBUFS;
993 if (input_blocksize == 0)
994 input_blocksize = DEFAULT_BLOCKSIZE;
995 if (output_blocksize == 0)
996 output_blocksize = DEFAULT_BLOCKSIZE;
997 if (conversion_blocksize == 0)
998 conversions_mask &= ~(C_BLOCK | C_UNBLOCK);
1000 if (input_flags & (O_DSYNC | O_SYNC))
1001 input_flags |= O_RSYNC;
1003 if (multiple_bits_set (conversions_mask & (C_ASCII | C_EBCDIC | C_IBM)))
1004 error (EXIT_FAILURE, 0, _("cannot combine any two of {ascii,ebcdic,ibm}"));
1005 if (multiple_bits_set (conversions_mask & (C_BLOCK | C_UNBLOCK)))
1006 error (EXIT_FAILURE, 0, _("cannot combine block and unblock"));
1007 if (multiple_bits_set (conversions_mask & (C_LCASE | C_UCASE)))
1008 error (EXIT_FAILURE, 0, _("cannot combine lcase and ucase"));
1009 if (multiple_bits_set (conversions_mask & (C_EXCL | C_NOCREAT)))
1010 error (EXIT_FAILURE, 0, _("cannot combine excl and nocreat"));
1013 /* Fix up translation table. */
1016 apply_translations (void)
1020 if (conversions_mask & C_ASCII)
1021 translate_charset (ebcdic_to_ascii);
1023 if (conversions_mask & C_UCASE)
1025 for (i = 0; i < 256; i++)
1026 trans_table[i] = toupper (trans_table[i]);
1027 translation_needed = true;
1029 else if (conversions_mask & C_LCASE)
1031 for (i = 0; i < 256; i++)
1032 trans_table[i] = tolower (trans_table[i]);
1033 translation_needed = true;
1036 if (conversions_mask & C_EBCDIC)
1038 translate_charset (ascii_to_ebcdic);
1039 newline_character = ascii_to_ebcdic['\n'];
1040 space_character = ascii_to_ebcdic[' '];
1042 else if (conversions_mask & C_IBM)
1044 translate_charset (ascii_to_ibm);
1045 newline_character = ascii_to_ibm['\n'];
1046 space_character = ascii_to_ibm[' '];
1050 /* Apply the character-set translations specified by the user
1051 to the NREAD bytes in BUF. */
1054 translate_buffer (char *buf, size_t nread)
1059 for (i = nread, cp = buf; i; i--, cp++)
1060 *cp = trans_table[to_uchar (*cp)];
1063 /* If true, the last char from the previous call to `swab_buffer'
1064 is saved in `saved_char'. */
1065 static bool char_is_saved = false;
1067 /* Odd char from previous call. */
1068 static char saved_char;
1070 /* Swap NREAD bytes in BUF, plus possibly an initial char from the
1071 previous call. If NREAD is odd, save the last char for the
1072 next call. Return the new start of the BUF buffer. */
1075 swab_buffer (char *buf, size_t *nread)
1077 char *bufstart = buf;
1081 /* Is a char left from last time? */
1084 *--bufstart = saved_char;
1086 char_is_saved = false;
1091 /* An odd number of chars are in the buffer. */
1092 saved_char = bufstart[--*nread];
1093 char_is_saved = true;
1096 /* Do the byte-swapping by moving every second character two
1097 positions toward the end, working from the end of the buffer
1098 toward the beginning. This way we only move half of the data. */
1100 cp = bufstart + *nread; /* Start one char past the last. */
1101 for (i = *nread / 2; i; i--, cp -= 2)
1107 /* Add OFFSET to the input offset, setting the overflow flag if
1111 advance_input_offset (uintmax_t offset)
1113 input_offset += offset;
1114 if (input_offset < offset)
1115 input_offset_overflow = true;
1118 /* This is a wrapper for lseek. It detects and warns about a kernel
1119 bug that makes lseek a no-op for tape devices, even though the kernel
1120 lseek return value suggests that the function succeeded.
1122 The parameters are the same as those of the lseek function, but
1123 with the addition of FILENAME, the name of the file associated with
1124 descriptor FDESC. The file name is used solely in the warning that's
1125 printed when the bug is detected. Return the same value that lseek
1126 would have returned, but when the lseek bug is detected, return -1
1127 to indicate that lseek failed.
1129 The offending behavior has been confirmed with an Exabyte SCSI tape
1130 drive accessed via /dev/nst0 on both Linux-2.2.17 and Linux-2.4.16. */
1134 # include <sys/mtio.h>
1136 # define MT_SAME_POSITION(P, Q) \
1137 ((P).mt_resid == (Q).mt_resid \
1138 && (P).mt_fileno == (Q).mt_fileno \
1139 && (P).mt_blkno == (Q).mt_blkno)
1142 skip_via_lseek (char const *filename, int fdesc, off_t offset, int whence)
1146 bool got_original_tape_position = (ioctl (fdesc, MTIOCGET, &s1) == 0);
1147 /* known bad device type */
1148 /* && s.mt_type == MT_ISSCSI2 */
1150 off_t new_position = lseek (fdesc, offset, whence);
1151 if (0 <= new_position
1152 && got_original_tape_position
1153 && ioctl (fdesc, MTIOCGET, &s2) == 0
1154 && MT_SAME_POSITION (s1, s2))
1156 error (0, 0, _("warning: working around lseek kernel bug for file (%s)\n\
1157 of mt_type=0x%0lx -- see <sys/mtio.h> for the list of types"),
1158 filename, s2.mt_type);
1163 return new_position;
1166 # define skip_via_lseek(Filename, Fd, Offset, Whence) lseek (Fd, Offset, Whence)
1169 /* Throw away RECORDS blocks of BLOCKSIZE bytes on file descriptor FDESC,
1170 which is open with read permission for FILE. Store up to BLOCKSIZE
1171 bytes of the data at a time in BUF, if necessary. RECORDS must be
1172 nonzero. If fdesc is STDIN_FILENO, advance the input offset.
1173 Return the number of records remaining, i.e., that were not skipped
1174 because EOF was reached. */
1177 skip (int fdesc, char const *file, uintmax_t records, size_t blocksize,
1180 uintmax_t offset = records * blocksize;
1182 /* Try lseek and if an error indicates it was an inappropriate operation --
1183 or if the file offset is not representable as an off_t --
1184 fall back on using read. */
1187 if (records <= OFF_T_MAX / blocksize
1188 && 0 <= skip_via_lseek (file, fdesc, offset, SEEK_CUR))
1190 if (fdesc == STDIN_FILENO)
1191 advance_input_offset (offset);
1196 int lseek_errno = errno;
1200 ssize_t nread = iread (fdesc, buf, blocksize);
1203 if (fdesc == STDIN_FILENO)
1205 error (0, errno, _("reading %s"), quote (file));
1206 if (conversions_mask & C_NOERROR)
1213 error (0, lseek_errno, _("%s: cannot seek"), quote (file));
1214 quit (EXIT_FAILURE);
1219 if (fdesc == STDIN_FILENO)
1220 advance_input_offset (nread);
1222 while (--records != 0);
1228 /* Advance the input by NBYTES if possible, after a read error.
1229 The input file offset may or may not have advanced after the failed
1230 read; adjust it to point just after the bad record regardless.
1231 Return true if successful, or if the input is already known to not
1235 advance_input_after_read_error (size_t nbytes)
1237 if (! input_seekable)
1239 if (input_seek_errno == ESPIPE)
1241 errno = input_seek_errno;
1246 advance_input_offset (nbytes);
1247 input_offset_overflow |= (OFF_T_MAX < input_offset);
1248 if (input_offset_overflow)
1250 error (0, 0, _("offset overflow while reading file %s"),
1251 quote (input_file));
1254 offset = lseek (STDIN_FILENO, 0, SEEK_CUR);
1258 if (offset == input_offset)
1260 diff = input_offset - offset;
1261 if (! (0 <= diff && diff <= nbytes))
1262 error (0, 0, _("warning: invalid file offset after failed read"));
1263 if (0 <= skip_via_lseek (input_file, STDIN_FILENO, diff, SEEK_CUR))
1266 error (0, 0, _("cannot work around kernel bug after all"));
1270 error (0, errno, _("%s: cannot seek"), quote (input_file));
1274 /* Copy NREAD bytes of BUF, with no conversions. */
1277 copy_simple (char const *buf, size_t nread)
1279 const char *start = buf; /* First uncopied char in BUF. */
1283 size_t nfree = MIN (nread, output_blocksize - oc);
1285 memcpy (obuf + oc, start, nfree);
1287 nread -= nfree; /* Update the number of bytes left to copy. */
1290 if (oc >= output_blocksize)
1296 /* Copy NREAD bytes of BUF, doing conv=block
1297 (pad newline-terminated records to `conversion_blocksize',
1298 replacing the newline with trailing spaces). */
1301 copy_with_block (char const *buf, size_t nread)
1305 for (i = nread; i; i--, buf++)
1307 if (*buf == newline_character)
1309 if (col < conversion_blocksize)
1312 for (j = col; j < conversion_blocksize; j++)
1313 output_char (space_character);
1319 if (col == conversion_blocksize)
1321 else if (col < conversion_blocksize)
1328 /* Copy NREAD bytes of BUF, doing conv=unblock
1329 (replace trailing spaces in `conversion_blocksize'-sized records
1333 copy_with_unblock (char const *buf, size_t nread)
1337 static size_t pending_spaces = 0;
1339 for (i = 0; i < nread; i++)
1343 if (col++ >= conversion_blocksize)
1345 col = pending_spaces = 0; /* Wipe out any pending spaces. */
1346 i--; /* Push the char back; get it later. */
1347 output_char (newline_character);
1349 else if (c == space_character)
1353 /* `c' is the character after a run of spaces that were not
1354 at the end of the conversion buffer. Output them. */
1355 while (pending_spaces)
1357 output_char (space_character);
1365 /* Set the file descriptor flags for FD that correspond to the nonzero bits
1366 in ADD_FLAGS. The file's name is NAME. */
1369 set_fd_flags (int fd, int add_flags, char const *name)
1371 /* Ignore file creation flags that are no-ops on file descriptors. */
1372 add_flags &= ~ (O_NOCTTY | O_NOFOLLOW);
1376 int old_flags = fcntl (fd, F_GETFL);
1377 int new_flags = old_flags | add_flags;
1381 else if (old_flags != new_flags)
1383 if (new_flags & (O_DIRECTORY | O_NOLINKS))
1385 /* NEW_FLAGS contains at least one file creation flag that
1386 requires some checking of the open file descriptor. */
1388 if (fstat (fd, &st) != 0)
1390 else if ((new_flags & O_DIRECTORY) && ! S_ISDIR (st.st_mode))
1395 else if ((new_flags & O_NOLINKS) && 1 < st.st_nlink)
1400 new_flags &= ~ (O_DIRECTORY | O_NOLINKS);
1403 if (ok && old_flags != new_flags
1404 && fcntl (fd, F_SETFL, new_flags) == -1)
1409 error (EXIT_FAILURE, errno, _("setting flags for %s"), quote (name));
1413 /* The main loop. */
1418 char *ibuf, *bufstart; /* Input buffer. */
1419 /* These are declared static so that even though we don't free the
1420 buffers, valgrind will recognize that there is no "real" leak. */
1421 static char *real_buf; /* real buffer address before alignment */
1422 static char *real_obuf;
1423 ssize_t nread; /* Bytes read in the current block. */
1425 /* If nonzero, then the previously read block was partial and
1426 PARTREAD was its size. */
1427 size_t partread = 0;
1429 int exit_status = EXIT_SUCCESS;
1430 size_t n_bytes_read;
1432 /* Leave at least one extra byte at the beginning and end of `ibuf'
1433 for conv=swab, but keep the buffer address even. But some peculiar
1434 device drivers work only with word-aligned buffers, so leave an
1437 /* Some devices require alignment on a sector or page boundary
1438 (e.g. character disk devices). Align the input buffer to a
1439 page boundary to cover all bases. Note that due to the swab
1440 algorithm, we must have at least one byte in the page before
1441 the input buffer; thus we allocate 2 pages of slop in the
1442 real buffer. 8k above the blocksize shouldn't bother anyone.
1444 The page alignment is necessary on any linux system that supports
1445 either the SGI raw I/O patch or Steven Tweedies raw I/O patch.
1446 It is necessary when accessing raw (i.e. character special) disk
1447 devices on Unixware or other SVR4-derived system. */
1449 real_buf = xmalloc (input_blocksize + INPUT_BLOCK_SLOP);
1451 ibuf += SWAB_ALIGN_OFFSET; /* allow space for swab */
1453 ibuf = ptr_align (ibuf, page_size);
1455 if (conversions_mask & C_TWOBUFS)
1457 /* Page-align the output buffer, too. */
1458 real_obuf = xmalloc (output_blocksize + OUTPUT_BLOCK_SLOP);
1459 obuf = ptr_align (real_obuf, page_size);
1467 if (skip_records != 0)
1469 skip (STDIN_FILENO, input_file, skip_records, input_blocksize, ibuf);
1470 /* POSIX doesn't say what to do when dd detects it has been
1471 asked to skip past EOF, so I assume it's non-fatal if the
1472 call to 'skip' returns nonzero. FIXME: maybe give a warning. */
1475 if (seek_records != 0)
1477 uintmax_t write_records = skip (STDOUT_FILENO, output_file,
1478 seek_records, output_blocksize, obuf);
1480 if (write_records != 0)
1482 memset (obuf, 0, output_blocksize);
1485 if (iwrite (STDOUT_FILENO, obuf, output_blocksize)
1486 != output_blocksize)
1488 error (0, errno, _("writing to %s"), quote (output_file));
1489 quit (EXIT_FAILURE);
1491 while (--write_records != 0);
1495 if (max_records == 0)
1500 if (r_partial + r_full >= max_records)
1503 /* Zero the buffer before reading, so that if we get a read error,
1504 whatever data we are able to read is followed by zeros.
1505 This minimizes data loss. */
1506 if ((conversions_mask & C_SYNC) && (conversions_mask & C_NOERROR))
1508 (conversions_mask & (C_BLOCK | C_UNBLOCK)) ? ' ' : '\0',
1511 nread = iread (STDIN_FILENO, ibuf, input_blocksize);
1518 error (0, errno, _("reading %s"), quote (input_file));
1519 if (conversions_mask & C_NOERROR)
1522 /* Seek past the bad block if possible. */
1523 if (!advance_input_after_read_error (input_blocksize - partread))
1525 exit_status = EXIT_FAILURE;
1527 /* Suppress duplicate diagnostics. */
1528 input_seekable = false;
1529 input_seek_errno = ESPIPE;
1531 if ((conversions_mask & C_SYNC) && !partread)
1532 /* Replace the missing input with null bytes and
1533 proceed normally. */
1540 /* Write any partial block. */
1541 exit_status = EXIT_FAILURE;
1546 n_bytes_read = nread;
1547 advance_input_offset (nread);
1549 if (n_bytes_read < input_blocksize)
1552 partread = n_bytes_read;
1553 if (conversions_mask & C_SYNC)
1555 if (!(conversions_mask & C_NOERROR))
1556 /* If C_NOERROR, we zeroed the block before reading. */
1557 memset (ibuf + n_bytes_read,
1558 (conversions_mask & (C_BLOCK | C_UNBLOCK)) ? ' ' : '\0',
1559 input_blocksize - n_bytes_read);
1560 n_bytes_read = input_blocksize;
1569 if (ibuf == obuf) /* If not C_TWOBUFS. */
1571 size_t nwritten = iwrite (STDOUT_FILENO, obuf, n_bytes_read);
1572 w_bytes += nwritten;
1573 if (nwritten != n_bytes_read)
1575 error (0, errno, _("writing %s"), quote (output_file));
1576 return EXIT_FAILURE;
1578 else if (n_bytes_read == input_blocksize)
1585 /* Do any translations on the whole buffer at once. */
1587 if (translation_needed)
1588 translate_buffer (ibuf, n_bytes_read);
1590 if (conversions_mask & C_SWAB)
1591 bufstart = swab_buffer (ibuf, &n_bytes_read);
1595 if (conversions_mask & C_BLOCK)
1596 copy_with_block (bufstart, n_bytes_read);
1597 else if (conversions_mask & C_UNBLOCK)
1598 copy_with_unblock (bufstart, n_bytes_read);
1600 copy_simple (bufstart, n_bytes_read);
1603 /* If we have a char left as a result of conv=swab, output it. */
1606 if (conversions_mask & C_BLOCK)
1607 copy_with_block (&saved_char, 1);
1608 else if (conversions_mask & C_UNBLOCK)
1609 copy_with_unblock (&saved_char, 1);
1611 output_char (saved_char);
1614 if ((conversions_mask & C_BLOCK) && col > 0)
1616 /* If the final input line didn't end with a '\n', pad
1617 the output block to `conversion_blocksize' chars. */
1619 for (i = col; i < conversion_blocksize; i++)
1620 output_char (space_character);
1623 if ((conversions_mask & C_UNBLOCK) && col == conversion_blocksize)
1624 /* Add a final '\n' if there are exactly `conversion_blocksize'
1625 characters in the final record. */
1626 output_char (newline_character);
1628 /* Write out the last block. */
1631 size_t nwritten = iwrite (STDOUT_FILENO, obuf, oc);
1632 w_bytes += nwritten;
1637 error (0, errno, _("writing %s"), quote (output_file));
1638 return EXIT_FAILURE;
1642 if ((conversions_mask & C_FDATASYNC) && fdatasync (STDOUT_FILENO) != 0)
1644 if (errno != ENOSYS && errno != EINVAL)
1646 error (0, errno, _("fdatasync failed for %s"), quote (output_file));
1647 exit_status = EXIT_FAILURE;
1649 conversions_mask |= C_FSYNC;
1652 if (conversions_mask & C_FSYNC)
1653 while (fsync (STDOUT_FILENO) != 0)
1656 error (0, errno, _("fsync failed for %s"), quote (output_file));
1657 return EXIT_FAILURE;
1664 main (int argc, char **argv)
1670 initialize_main (&argc, &argv);
1671 set_program_name (argv[0]);
1672 setlocale (LC_ALL, "");
1673 bindtextdomain (PACKAGE, LOCALEDIR);
1674 textdomain (PACKAGE);
1676 /* Arrange to close stdout if parse_long_options exits. */
1677 atexit (maybe_close_stdout);
1679 page_size = getpagesize ();
1681 parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE, VERSION,
1682 usage, AUTHORS, (char const *) NULL);
1683 close_stdout_required = false;
1685 if (getopt_long (argc, argv, "", NULL, NULL) != -1)
1686 usage (EXIT_FAILURE);
1688 /* Initialize translation table to identity translation. */
1689 for (i = 0; i < 256; i++)
1692 /* Decode arguments. */
1693 scanargs (argc, argv);
1695 apply_translations ();
1697 if (input_file == NULL)
1699 input_file = _("standard input");
1700 set_fd_flags (STDIN_FILENO, input_flags, input_file);
1704 if (fd_reopen (STDIN_FILENO, input_file, O_RDONLY | input_flags, 0) < 0)
1705 error (EXIT_FAILURE, errno, _("opening %s"), quote (input_file));
1708 offset = lseek (STDIN_FILENO, 0, SEEK_CUR);
1709 input_seekable = (0 <= offset);
1710 input_offset = offset;
1711 input_seek_errno = errno;
1713 if (output_file == NULL)
1715 output_file = _("standard output");
1716 set_fd_flags (STDOUT_FILENO, output_flags, output_file);
1720 mode_t perms = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
1723 | (conversions_mask & C_NOCREAT ? 0 : O_CREAT)
1724 | (conversions_mask & C_EXCL ? O_EXCL : 0)
1725 | (seek_records || (conversions_mask & C_NOTRUNC) ? 0 : O_TRUNC));
1727 /* Open the output file with *read* access only if we might
1728 need to read to satisfy a `seek=' request. If we can't read
1729 the file, go ahead with write-only access; it might work. */
1731 || fd_reopen (STDOUT_FILENO, output_file, O_RDWR | opts, perms) < 0)
1732 && (fd_reopen (STDOUT_FILENO, output_file, O_WRONLY | opts, perms)
1734 error (EXIT_FAILURE, errno, _("opening %s"), quote (output_file));
1737 if (seek_records != 0 && !(conversions_mask & C_NOTRUNC))
1739 uintmax_t size = seek_records * output_blocksize;
1740 unsigned long int obs = output_blocksize;
1742 if (OFF_T_MAX / output_blocksize < seek_records)
1743 error (EXIT_FAILURE, 0,
1744 _("offset too large: "
1745 "cannot truncate to a length of seek=%"PRIuMAX""
1746 " (%lu-byte) blocks"),
1749 if (ftruncate (STDOUT_FILENO, size) != 0)
1751 /* Complain only when ftruncate fails on a regular file, a
1752 directory, or a shared memory object, as POSIX 1003.1-2004
1753 specifies ftruncate's behavior only for these file types.
1754 For example, do not complain when Linux 2.4 ftruncate
1755 fails on /dev/fd0. */
1756 int ftruncate_errno = errno;
1757 struct stat stdout_stat;
1758 if (fstat (STDOUT_FILENO, &stdout_stat) != 0)
1759 error (EXIT_FAILURE, errno, _("cannot fstat %s"),
1760 quote (output_file));
1761 if (S_ISREG (stdout_stat.st_mode)
1762 || S_ISDIR (stdout_stat.st_mode)
1763 || S_TYPEISSHM (&stdout_stat))
1764 error (EXIT_FAILURE, ftruncate_errno,
1765 _("truncating at %"PRIuMAX" bytes in output file %s"),
1766 size, quote (output_file));
1772 install_signal_handlers ();
1774 start_time = gethrxtime ();
1776 exit_status = dd_copy ();