1 /* dd -- convert a file while copying it.
2 Copyright (C) 85, 90, 91, 1995-2007 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 2, or (at your option)
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, write to the Free Software Foundation,
16 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
18 /* Written by Paul Rubin, David MacKenzie, and Stuart Kemp. */
22 #define SWAB_ALIGN_OFFSET 2
24 #include <sys/types.h>
30 #include "fd-reopen.h"
31 #include "gethrxtime.h"
32 #include "getpagesize.h"
34 #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"
44 #define AUTHORS "Paul Rubin", "David MacKenzie", "Stuart Kemp"
46 /* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is
47 present. SA_NODEFER and SA_RESETHAND are XSI extensions. */
49 # define SA_NOCLDSTOP 0
50 # define sigprocmask(How, Set, Oset) /* empty */
52 # if ! HAVE_SIGINTERRUPT
53 # define siginterrupt(sig, flag) /* empty */
60 # define SA_RESETHAND 0
64 # define SIGINFO SIGUSR1
68 # define fdatasync(fd) (errno = ENOSYS, -1)
71 #define max(a, b) ((a) > (b) ? (a) : (b))
72 #define output_char(c) \
76 if (oc >= output_blocksize) \
81 /* Default input and output blocksize. */
82 #define DEFAULT_BLOCKSIZE 512
84 /* How many bytes to add to the input and output block sizes before invoking
85 malloc. See dd_copy for details. INPUT_BLOCK_SLOP must be no less than
87 #define INPUT_BLOCK_SLOP (2 * SWAB_ALIGN_OFFSET + 2 * page_size - 1)
88 #define OUTPUT_BLOCK_SLOP (page_size - 1)
90 /* Maximum blocksize for the given SLOP.
91 Keep it smaller than SIZE_MAX - SLOP, so that we can
92 allocate buffers that size. Keep it smaller than SSIZE_MAX, for
93 the benefit of system calls like "read". And keep it smaller than
94 OFF_T_MAX, for the benefit of the large-offset seek code. */
95 #define MAX_BLOCKSIZE(slop) MIN (SIZE_MAX - (slop), MIN (SSIZE_MAX, OFF_T_MAX))
97 /* Conversions bit masks. */
113 /* Use separate input and output buffers, and combine partial
119 C_FDATASYNC = 040000,
123 /* Status bit masks. */
129 /* The name this program was run with. */
132 /* The name of the input file, or NULL for the standard input. */
133 static char const *input_file = NULL;
135 /* The name of the output file, or NULL for the standard output. */
136 static char const *output_file = NULL;
138 /* The page size on this host. */
139 static size_t page_size;
141 /* The number of bytes in which atomic reads are done. */
142 static size_t input_blocksize = 0;
144 /* The number of bytes in which atomic writes are done. */
145 static size_t output_blocksize = 0;
147 /* Conversion buffer size, in bytes. 0 prevents conversions. */
148 static size_t conversion_blocksize = 0;
150 /* Skip this many records of `input_blocksize' bytes before input. */
151 static uintmax_t skip_records = 0;
153 /* Skip this many records of `output_blocksize' bytes before output. */
154 static uintmax_t seek_records = 0;
156 /* Copy only this many records. The default is effectively infinity. */
157 static uintmax_t max_records = (uintmax_t) -1;
159 /* Bit vector of conversions to apply. */
160 static int conversions_mask = 0;
162 /* Open flags for the input and output files. */
163 static int input_flags = 0;
164 static int output_flags = 0;
166 /* Status flags for what is printed to stderr. */
167 static int status_flags = 0;
169 /* If nonzero, filter characters through the translation table. */
170 static bool translation_needed = false;
172 /* Number of partial blocks written. */
173 static uintmax_t w_partial = 0;
175 /* Number of full blocks written. */
176 static uintmax_t w_full = 0;
178 /* Number of partial blocks read. */
179 static uintmax_t r_partial = 0;
181 /* Number of full blocks read. */
182 static uintmax_t r_full = 0;
184 /* Number of bytes written. */
185 static uintmax_t w_bytes = 0;
187 /* Time that dd started. */
188 static xtime_t start_time;
190 /* True if input is seekable. */
191 static bool input_seekable;
193 /* Error number corresponding to initial attempt to lseek input.
194 If ESPIPE, do not issue any more diagnostics about it. */
195 static int input_seek_errno;
197 /* File offset of the input, in bytes, along with a flag recording
198 whether it overflowed. The offset is valid only if the input is
199 seekable and if the offset has not overflowed. */
200 static uintmax_t input_offset;
201 static bool input_offset_overflow;
203 /* Records truncated by conv=block. */
204 static uintmax_t r_truncate = 0;
206 /* Output representation of newline and space characters.
207 They change if we're converting to EBCDIC. */
208 static char newline_character = '\n';
209 static char space_character = ' ';
214 /* Current index into `obuf'. */
215 static size_t oc = 0;
217 /* Index into current line, for `conv=block' and `conv=unblock'. */
218 static size_t col = 0;
220 /* The set of signals that are caught. */
221 static sigset_t caught_signals;
223 /* If nonzero, the value of the pending fatal signal. */
224 static sig_atomic_t volatile interrupt_signal;
226 /* A count of the number of pending info signals that have been received. */
227 static sig_atomic_t volatile info_signal_count;
229 /* A longest symbol in the struct symbol_values tables below. */
230 #define LONGEST_SYMBOL "fdatasync"
232 /* A symbol and the corresponding integer value. */
235 char symbol[sizeof LONGEST_SYMBOL];
239 /* Conversion symbols, for conv="...". */
240 static struct symbol_value const conversions[] =
242 {"ascii", C_ASCII | C_TWOBUFS}, /* EBCDIC to ASCII. */
243 {"ebcdic", C_EBCDIC | C_TWOBUFS}, /* ASCII to EBCDIC. */
244 {"ibm", C_IBM | C_TWOBUFS}, /* Slightly different ASCII to EBCDIC. */
245 {"block", C_BLOCK | C_TWOBUFS}, /* Variable to fixed length records. */
246 {"unblock", C_UNBLOCK | C_TWOBUFS}, /* Fixed to variable length records. */
247 {"lcase", C_LCASE | C_TWOBUFS}, /* Translate upper to lower case. */
248 {"ucase", C_UCASE | C_TWOBUFS}, /* Translate lower to upper case. */
249 {"swab", C_SWAB | C_TWOBUFS}, /* Swap bytes of input. */
250 {"noerror", C_NOERROR}, /* Ignore i/o errors. */
251 {"nocreat", C_NOCREAT}, /* Do not create output file. */
252 {"excl", C_EXCL}, /* Fail if the output file already exists. */
253 {"notrunc", C_NOTRUNC}, /* Do not truncate output file. */
254 {"sync", C_SYNC}, /* Pad input records to ibs with NULs. */
255 {"fdatasync", C_FDATASYNC}, /* Synchronize output data before finishing. */
256 {"fsync", C_FSYNC}, /* Also synchronize output metadata. */
260 /* Flags, for iflag="..." and oflag="...". */
261 static struct symbol_value const flags[] =
263 {"append", O_APPEND},
264 {"binary", O_BINARY},
265 {"direct", O_DIRECT},
266 {"directory", O_DIRECTORY},
268 {"noatime", O_NOATIME},
269 {"noctty", O_NOCTTY},
270 {"nofollow", HAVE_WORKING_O_NOFOLLOW ? O_NOFOLLOW : 0},
271 {"nolinks", O_NOLINKS},
272 {"nonblock", O_NONBLOCK},
278 /* Status, for status="...". */
279 static struct symbol_value const statuses[] =
281 {"noxfer", STATUS_NOXFER},
285 /* Translation table formed by applying successive transformations. */
286 static unsigned char trans_table[256];
288 static char const ascii_to_ebcdic[] =
290 '\000', '\001', '\002', '\003', '\067', '\055', '\056', '\057',
291 '\026', '\005', '\045', '\013', '\014', '\015', '\016', '\017',
292 '\020', '\021', '\022', '\023', '\074', '\075', '\062', '\046',
293 '\030', '\031', '\077', '\047', '\034', '\035', '\036', '\037',
294 '\100', '\117', '\177', '\173', '\133', '\154', '\120', '\175',
295 '\115', '\135', '\134', '\116', '\153', '\140', '\113', '\141',
296 '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367',
297 '\370', '\371', '\172', '\136', '\114', '\176', '\156', '\157',
298 '\174', '\301', '\302', '\303', '\304', '\305', '\306', '\307',
299 '\310', '\311', '\321', '\322', '\323', '\324', '\325', '\326',
300 '\327', '\330', '\331', '\342', '\343', '\344', '\345', '\346',
301 '\347', '\350', '\351', '\112', '\340', '\132', '\137', '\155',
302 '\171', '\201', '\202', '\203', '\204', '\205', '\206', '\207',
303 '\210', '\211', '\221', '\222', '\223', '\224', '\225', '\226',
304 '\227', '\230', '\231', '\242', '\243', '\244', '\245', '\246',
305 '\247', '\250', '\251', '\300', '\152', '\320', '\241', '\007',
306 '\040', '\041', '\042', '\043', '\044', '\025', '\006', '\027',
307 '\050', '\051', '\052', '\053', '\054', '\011', '\012', '\033',
308 '\060', '\061', '\032', '\063', '\064', '\065', '\066', '\010',
309 '\070', '\071', '\072', '\073', '\004', '\024', '\076', '\341',
310 '\101', '\102', '\103', '\104', '\105', '\106', '\107', '\110',
311 '\111', '\121', '\122', '\123', '\124', '\125', '\126', '\127',
312 '\130', '\131', '\142', '\143', '\144', '\145', '\146', '\147',
313 '\150', '\151', '\160', '\161', '\162', '\163', '\164', '\165',
314 '\166', '\167', '\170', '\200', '\212', '\213', '\214', '\215',
315 '\216', '\217', '\220', '\232', '\233', '\234', '\235', '\236',
316 '\237', '\240', '\252', '\253', '\254', '\255', '\256', '\257',
317 '\260', '\261', '\262', '\263', '\264', '\265', '\266', '\267',
318 '\270', '\271', '\272', '\273', '\274', '\275', '\276', '\277',
319 '\312', '\313', '\314', '\315', '\316', '\317', '\332', '\333',
320 '\334', '\335', '\336', '\337', '\352', '\353', '\354', '\355',
321 '\356', '\357', '\372', '\373', '\374', '\375', '\376', '\377'
324 static char const ascii_to_ibm[] =
326 '\000', '\001', '\002', '\003', '\067', '\055', '\056', '\057',
327 '\026', '\005', '\045', '\013', '\014', '\015', '\016', '\017',
328 '\020', '\021', '\022', '\023', '\074', '\075', '\062', '\046',
329 '\030', '\031', '\077', '\047', '\034', '\035', '\036', '\037',
330 '\100', '\132', '\177', '\173', '\133', '\154', '\120', '\175',
331 '\115', '\135', '\134', '\116', '\153', '\140', '\113', '\141',
332 '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367',
333 '\370', '\371', '\172', '\136', '\114', '\176', '\156', '\157',
334 '\174', '\301', '\302', '\303', '\304', '\305', '\306', '\307',
335 '\310', '\311', '\321', '\322', '\323', '\324', '\325', '\326',
336 '\327', '\330', '\331', '\342', '\343', '\344', '\345', '\346',
337 '\347', '\350', '\351', '\255', '\340', '\275', '\137', '\155',
338 '\171', '\201', '\202', '\203', '\204', '\205', '\206', '\207',
339 '\210', '\211', '\221', '\222', '\223', '\224', '\225', '\226',
340 '\227', '\230', '\231', '\242', '\243', '\244', '\245', '\246',
341 '\247', '\250', '\251', '\300', '\117', '\320', '\241', '\007',
342 '\040', '\041', '\042', '\043', '\044', '\025', '\006', '\027',
343 '\050', '\051', '\052', '\053', '\054', '\011', '\012', '\033',
344 '\060', '\061', '\032', '\063', '\064', '\065', '\066', '\010',
345 '\070', '\071', '\072', '\073', '\004', '\024', '\076', '\341',
346 '\101', '\102', '\103', '\104', '\105', '\106', '\107', '\110',
347 '\111', '\121', '\122', '\123', '\124', '\125', '\126', '\127',
348 '\130', '\131', '\142', '\143', '\144', '\145', '\146', '\147',
349 '\150', '\151', '\160', '\161', '\162', '\163', '\164', '\165',
350 '\166', '\167', '\170', '\200', '\212', '\213', '\214', '\215',
351 '\216', '\217', '\220', '\232', '\233', '\234', '\235', '\236',
352 '\237', '\240', '\252', '\253', '\254', '\255', '\256', '\257',
353 '\260', '\261', '\262', '\263', '\264', '\265', '\266', '\267',
354 '\270', '\271', '\272', '\273', '\274', '\275', '\276', '\277',
355 '\312', '\313', '\314', '\315', '\316', '\317', '\332', '\333',
356 '\334', '\335', '\336', '\337', '\352', '\353', '\354', '\355',
357 '\356', '\357', '\372', '\373', '\374', '\375', '\376', '\377'
360 static char const ebcdic_to_ascii[] =
362 '\000', '\001', '\002', '\003', '\234', '\011', '\206', '\177',
363 '\227', '\215', '\216', '\013', '\014', '\015', '\016', '\017',
364 '\020', '\021', '\022', '\023', '\235', '\205', '\010', '\207',
365 '\030', '\031', '\222', '\217', '\034', '\035', '\036', '\037',
366 '\200', '\201', '\202', '\203', '\204', '\012', '\027', '\033',
367 '\210', '\211', '\212', '\213', '\214', '\005', '\006', '\007',
368 '\220', '\221', '\026', '\223', '\224', '\225', '\226', '\004',
369 '\230', '\231', '\232', '\233', '\024', '\025', '\236', '\032',
370 '\040', '\240', '\241', '\242', '\243', '\244', '\245', '\246',
371 '\247', '\250', '\133', '\056', '\074', '\050', '\053', '\041',
372 '\046', '\251', '\252', '\253', '\254', '\255', '\256', '\257',
373 '\260', '\261', '\135', '\044', '\052', '\051', '\073', '\136',
374 '\055', '\057', '\262', '\263', '\264', '\265', '\266', '\267',
375 '\270', '\271', '\174', '\054', '\045', '\137', '\076', '\077',
376 '\272', '\273', '\274', '\275', '\276', '\277', '\300', '\301',
377 '\302', '\140', '\072', '\043', '\100', '\047', '\075', '\042',
378 '\303', '\141', '\142', '\143', '\144', '\145', '\146', '\147',
379 '\150', '\151', '\304', '\305', '\306', '\307', '\310', '\311',
380 '\312', '\152', '\153', '\154', '\155', '\156', '\157', '\160',
381 '\161', '\162', '\313', '\314', '\315', '\316', '\317', '\320',
382 '\321', '\176', '\163', '\164', '\165', '\166', '\167', '\170',
383 '\171', '\172', '\322', '\323', '\324', '\325', '\326', '\327',
384 '\330', '\331', '\332', '\333', '\334', '\335', '\336', '\337',
385 '\340', '\341', '\342', '\343', '\344', '\345', '\346', '\347',
386 '\173', '\101', '\102', '\103', '\104', '\105', '\106', '\107',
387 '\110', '\111', '\350', '\351', '\352', '\353', '\354', '\355',
388 '\175', '\112', '\113', '\114', '\115', '\116', '\117', '\120',
389 '\121', '\122', '\356', '\357', '\360', '\361', '\362', '\363',
390 '\134', '\237', '\123', '\124', '\125', '\126', '\127', '\130',
391 '\131', '\132', '\364', '\365', '\366', '\367', '\370', '\371',
392 '\060', '\061', '\062', '\063', '\064', '\065', '\066', '\067',
393 '\070', '\071', '\372', '\373', '\374', '\375', '\376', '\377'
399 if (status != EXIT_SUCCESS)
400 fprintf (stderr, _("Try `%s --help' for more information.\n"),
405 Usage: %s [OPERAND]...\n\
408 program_name, program_name);
410 Copy a file, converting and formatting according to the operands.\n\
412 bs=BYTES force ibs=BYTES and obs=BYTES\n\
413 cbs=BYTES convert BYTES bytes at a time\n\
414 conv=CONVS convert the file as per the comma separated symbol list\n\
415 count=BLOCKS copy only BLOCKS input blocks\n\
416 ibs=BYTES read BYTES bytes at a time\n\
419 if=FILE read from FILE instead of stdin\n\
420 iflag=FLAGS read as per the comma separated symbol list\n\
421 obs=BYTES write BYTES bytes at a time\n\
422 of=FILE write to FILE instead of stdout\n\
423 oflag=FLAGS write as per the comma separated symbol list\n\
424 seek=BLOCKS skip BLOCKS obs-sized blocks at start of output\n\
425 skip=BLOCKS skip BLOCKS ibs-sized blocks at start of input\n\
426 status=noxfer suppress transfer statistics\n\
430 BLOCKS and BYTES may be followed by the following multiplicative suffixes:\n\
431 xM M, c 1, w 2, b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024,\n\
432 GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y.\n\
434 Each CONV symbol may be:\n\
438 ascii from EBCDIC to ASCII\n\
439 ebcdic from ASCII to EBCDIC\n\
440 ibm from ASCII to alternate EBCDIC\n\
441 block pad newline-terminated records with spaces to cbs-size\n\
442 unblock replace trailing spaces in cbs-size records with newline\n\
443 lcase change upper case to lower case\n\
446 nocreat do not create the output file\n\
447 excl fail if the output file already exists\n\
448 notrunc do not truncate the output file\n\
449 ucase change lower case to upper case\n\
450 swab swap every pair of input bytes\n\
453 noerror continue after read errors\n\
454 sync pad every input block with NULs to ibs-size; when used\n\
455 with block or unblock, pad with spaces rather than NULs\n\
456 fdatasync physically write output file data before finishing\n\
457 fsync likewise, but also write metadata\n\
461 Each FLAG symbol may be:\n\
463 append append mode (makes sense only for output; conv=notrunc suggested)\n\
466 fputs (_(" direct use direct I/O for data\n"), stdout);
468 fputs (_(" directory fail unless a directory\n"), stdout);
470 fputs (_(" dsync use synchronized I/O for data\n"), stdout);
472 fputs (_(" sync likewise, but also for metadata\n"), stdout);
474 fputs (_(" nonblock use non-blocking I/O\n"), stdout);
476 fputs (_(" noatime do not update access time\n"), stdout);
478 fputs (_(" noctty do not assign controlling terminal from file\n"),
480 if (HAVE_WORKING_O_NOFOLLOW)
481 fputs (_(" nofollow do not follow symlinks\n"), stdout);
483 fputs (_(" nolinks fail if multiply-linked\n"), stdout);
485 fputs (_(" binary use binary I/O for data\n"), stdout);
487 fputs (_(" text use text I/O for data\n"), stdout);
490 char const *siginfo_name = (SIGINFO == SIGUSR1 ? "USR1" : "INFO");
493 Sending a %s signal to a running `dd' process makes it\n\
494 print I/O statistics to standard error and then resume copying.\n\
496 $ dd if=/dev/zero of=/dev/null& pid=$!\n\
497 $ kill -%s $pid; sleep 1; kill $pid\n\
498 18335302+0 records in\n\
499 18335302+0 records out\n\
500 9387674624 bytes (9.4 GB) copied, 34.6279 seconds, 271 MB/s\n\
505 siginfo_name, siginfo_name);
508 fputs (HELP_OPTION_DESCRIPTION, stdout);
509 fputs (VERSION_OPTION_DESCRIPTION, stdout);
510 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
516 translate_charset (char const *new_trans)
520 for (i = 0; i < 256; i++)
521 trans_table[i] = new_trans[trans_table[i]];
522 translation_needed = true;
525 /* Return true if I has more than one bit set. I must be nonnegative. */
528 multiple_bits_set (int i)
530 return (i & (i - 1)) != 0;
533 /* Print transfer statistics. */
538 xtime_t now = gethrxtime ();
539 char hbuf[LONGEST_HUMAN_READABLE + 1];
541 (human_autoscale | human_round_to_nearest
542 | human_space_before_unit | human_SI | human_B);
544 char const *bytes_per_second;
547 _("%"PRIuMAX"+%"PRIuMAX" records in\n"
548 "%"PRIuMAX"+%"PRIuMAX" records out\n"),
549 r_full, r_partial, w_full, w_partial);
553 ngettext ("%"PRIuMAX" truncated record\n",
554 "%"PRIuMAX" truncated records\n",
555 select_plural (r_truncate)),
558 if (status_flags & STATUS_NOXFER)
561 /* Use integer arithmetic to compute the transfer rate,
562 since that makes it easy to use SI abbreviations. */
565 ngettext ("%"PRIuMAX" byte (%s) copied",
566 "%"PRIuMAX" bytes (%s) copied",
567 select_plural (w_bytes)),
569 human_readable (w_bytes, hbuf, human_opts, 1, 1));
571 if (start_time < now)
573 double XTIME_PRECISIONe0 = XTIME_PRECISION;
574 uintmax_t delta_xtime = now;
575 delta_xtime -= start_time;
576 delta_s = delta_xtime / XTIME_PRECISIONe0;
577 bytes_per_second = human_readable (w_bytes, hbuf, human_opts,
578 XTIME_PRECISION, delta_xtime);
583 bytes_per_second = _("Infinity B");
586 /* TRANSLATORS: The two instances of "s" in this string are the SI
587 symbol "s" (meaning second), and should not be translated.
589 This format used to be:
591 ngettext (", %g second, %s/s\n", ", %g seconds, %s/s\n", delta_s == 1)
593 but that was incorrect for languages like Polish. To fix this
594 bug we now use SI symbols even though they're a bit more
595 confusing in English. */
596 fprintf (stderr, _(", %g s, %s/s\n"), delta_s, bytes_per_second);
602 if (close (STDIN_FILENO) < 0)
603 error (EXIT_FAILURE, errno,
604 _("closing input file %s"), quote (input_file));
606 /* Don't remove this call to close, even though close_stdout
607 closes standard output. This close is necessary when cleanup
608 is called as part of a signal handler. */
609 if (close (STDOUT_FILENO) < 0)
610 error (EXIT_FAILURE, errno,
611 _("closing output file %s"), quote (output_file));
614 static inline void ATTRIBUTE_NORETURN
623 /* An ordinary signal was received; arrange for the program to exit. */
626 interrupt_handler (int sig)
629 signal (sig, SIG_DFL);
630 interrupt_signal = sig;
633 /* An info signal was received; arrange for the program to print status. */
636 siginfo_handler (int sig)
639 signal (sig, siginfo_handler);
643 /* Install the signal handlers. */
646 install_signal_handlers (void)
648 bool catch_siginfo = ! (SIGINFO == SIGUSR1 && getenv ("POSIXLY_CORRECT"));
652 struct sigaction act;
653 sigemptyset (&caught_signals);
656 sigaction (SIGINFO, NULL, &act);
657 if (act.sa_handler != SIG_IGN)
658 sigaddset (&caught_signals, SIGINFO);
660 sigaction (SIGINT, NULL, &act);
661 if (act.sa_handler != SIG_IGN)
662 sigaddset (&caught_signals, SIGINT);
663 act.sa_mask = caught_signals;
665 if (sigismember (&caught_signals, SIGINFO))
667 act.sa_handler = siginfo_handler;
669 sigaction (SIGINFO, &act, NULL);
672 if (sigismember (&caught_signals, SIGINT))
674 /* POSIX 1003.1-2001 says SA_RESETHAND implies SA_NODEFER,
675 but this is not true on Solaris 8 at least. It doesn't
676 hurt to use SA_NODEFER here, so leave it in. */
677 act.sa_handler = interrupt_handler;
678 act.sa_flags = SA_NODEFER | SA_RESETHAND;
679 sigaction (SIGINT, &act, NULL);
684 if (catch_siginfo && signal (SIGINFO, SIG_IGN) != SIG_IGN)
686 signal (SIGINFO, siginfo_handler);
687 siginterrupt (SIGINFO, 1);
689 if (signal (SIGINT, SIG_IGN) != SIG_IGN)
691 signal (SIGINT, interrupt_handler);
692 siginterrupt (SIGINT, 1);
697 /* Process any pending signals. If signals are caught, this function
698 should be called periodically. Ideally there should never be an
699 unbounded amount of time when signals are not being processed. */
702 process_signals (void)
704 while (interrupt_signal | info_signal_count)
710 sigprocmask (SIG_BLOCK, &caught_signals, &oldset);
712 /* Reload interrupt_signal and info_signal_count, in case a new
713 signal was handled before sigprocmask took effect. */
714 interrupt = interrupt_signal;
715 infos = info_signal_count;
718 info_signal_count = infos - 1;
720 sigprocmask (SIG_SETMASK, &oldset, NULL);
730 /* Read from FD into the buffer BUF of size SIZE, processing any
731 signals that arrive before bytes are read. Return the number of
732 bytes read if successful, -1 (setting errno) on failure. */
735 iread (int fd, char *buf, size_t size)
741 nread = read (fd, buf, size);
742 if (! (nread < 0 && errno == EINTR))
747 /* Write to FD the buffer BUF of size SIZE, processing any signals
748 that arrive. Return the number of bytes written, setting errno if
749 this is less than SIZE. Keep trying if there are partial
753 iwrite (int fd, char const *buf, size_t size)
755 size_t total_written = 0;
757 while (total_written < size)
761 nwritten = write (fd, buf + total_written, size - total_written);
767 else if (nwritten == 0)
769 /* Some buggy drivers return 0 when one tries to write beyond
770 a device's end. (Example: Linux 1.2.13 on /dev/fd0.)
771 Set errno to ENOSPC so they get a sensible diagnostic. */
776 total_written += nwritten;
779 return total_written;
782 /* Write, then empty, the output buffer `obuf'. */
787 size_t nwritten = iwrite (STDOUT_FILENO, obuf, output_blocksize);
789 if (nwritten != output_blocksize)
791 error (0, errno, _("writing to %s"), quote (output_file));
801 /* Interpret one "conv=..." or similar operand STR according to the
802 symbols in TABLE, returning the flags specified. If the operand
803 cannot be parsed, use ERROR_MSGID to generate a diagnostic.
804 As a by product, this function replaces each `,' in STR with a NUL byte. */
807 parse_symbols (char *str, struct symbol_value const *table,
808 char const *error_msgid)
814 struct symbol_value const *entry;
815 char *new = strchr (str, ',');
818 for (entry = table; ; entry++)
820 if (! entry->symbol[0])
822 error (0, 0, _(error_msgid), quote (str));
823 usage (EXIT_FAILURE);
825 if (STREQ (entry->symbol, str))
828 error (EXIT_FAILURE, 0, _(error_msgid), quote (str));
829 value |= entry->value;
840 /* Return the value of STR, interpreted as a non-negative decimal integer,
841 optionally multiplied by various values.
842 Set *INVALID if STR does not represent a number in this format. */
845 parse_integer (const char *str, bool *invalid)
849 enum strtol_error e = xstrtoumax (str, &suffix, 10, &n, "bcEGkKMPTwYZ0");
851 if (e == LONGINT_INVALID_SUFFIX_CHAR && *suffix == 'x')
853 uintmax_t multiplier = parse_integer (suffix + 1, invalid);
855 if (multiplier != 0 && n * multiplier / multiplier != n)
863 else if (e != LONGINT_OK)
873 scanargs (int argc, char **argv)
876 size_t blocksize = 0;
878 for (i = optind; i < argc; i++)
883 val = strchr (name, '=');
886 error (0, 0, _("unrecognized operand %s"), quote (name));
887 usage (EXIT_FAILURE);
891 if (STREQ (name, "if"))
893 else if (STREQ (name, "of"))
895 else if (STREQ (name, "conv"))
896 conversions_mask |= parse_symbols (val, conversions,
897 N_("invalid conversion: %s"));
898 else if (STREQ (name, "iflag"))
899 input_flags |= parse_symbols (val, flags,
900 N_("invalid input flag: %s"));
901 else if (STREQ (name, "oflag"))
902 output_flags |= parse_symbols (val, flags,
903 N_("invalid output flag: %s"));
904 else if (STREQ (name, "status"))
905 status_flags |= parse_symbols (val, statuses,
906 N_("invalid status flag: %s"));
909 bool invalid = false;
910 uintmax_t n = parse_integer (val, &invalid);
912 if (STREQ (name, "ibs"))
914 invalid |= ! (0 < n && n <= MAX_BLOCKSIZE (INPUT_BLOCK_SLOP));
916 conversions_mask |= C_TWOBUFS;
918 else if (STREQ (name, "obs"))
920 invalid |= ! (0 < n && n <= MAX_BLOCKSIZE (OUTPUT_BLOCK_SLOP));
921 output_blocksize = n;
922 conversions_mask |= C_TWOBUFS;
924 else if (STREQ (name, "bs"))
926 invalid |= ! (0 < n && n <= MAX_BLOCKSIZE (INPUT_BLOCK_SLOP));
929 else if (STREQ (name, "cbs"))
931 invalid |= ! (0 < n && n <= SIZE_MAX);
932 conversion_blocksize = n;
934 else if (STREQ (name, "skip"))
936 else if (STREQ (name, "seek"))
938 else if (STREQ (name, "count"))
942 error (0, 0, _("unrecognized operand %s=%s"),
943 quote_n (0, name), quote_n (1, val));
944 usage (EXIT_FAILURE);
948 error (EXIT_FAILURE, 0, _("invalid number %s"), quote (val));
953 input_blocksize = output_blocksize = blocksize;
955 /* If bs= was given, both `input_blocksize' and `output_blocksize' will
956 have been set to positive values. If either has not been set,
957 bs= was not given, so make sure two buffers are used. */
958 if (input_blocksize == 0 || output_blocksize == 0)
959 conversions_mask |= C_TWOBUFS;
960 if (input_blocksize == 0)
961 input_blocksize = DEFAULT_BLOCKSIZE;
962 if (output_blocksize == 0)
963 output_blocksize = DEFAULT_BLOCKSIZE;
964 if (conversion_blocksize == 0)
965 conversions_mask &= ~(C_BLOCK | C_UNBLOCK);
967 if (input_flags & (O_DSYNC | O_SYNC))
968 input_flags |= O_RSYNC;
970 if (multiple_bits_set (conversions_mask & (C_ASCII | C_EBCDIC | C_IBM)))
971 error (EXIT_FAILURE, 0, _("cannot combine any two of {ascii,ebcdic,ibm}"));
972 if (multiple_bits_set (conversions_mask & (C_BLOCK | C_UNBLOCK)))
973 error (EXIT_FAILURE, 0, _("cannot combine block and unblock"));
974 if (multiple_bits_set (conversions_mask & (C_LCASE | C_UCASE)))
975 error (EXIT_FAILURE, 0, _("cannot combine lcase and ucase"));
976 if (multiple_bits_set (conversions_mask & (C_EXCL | C_NOCREAT)))
977 error (EXIT_FAILURE, 0, _("cannot combine excl and nocreat"));
980 /* Fix up translation table. */
983 apply_translations (void)
987 if (conversions_mask & C_ASCII)
988 translate_charset (ebcdic_to_ascii);
990 if (conversions_mask & C_UCASE)
992 for (i = 0; i < 256; i++)
993 trans_table[i] = toupper (trans_table[i]);
994 translation_needed = true;
996 else if (conversions_mask & C_LCASE)
998 for (i = 0; i < 256; i++)
999 trans_table[i] = tolower (trans_table[i]);
1000 translation_needed = true;
1003 if (conversions_mask & C_EBCDIC)
1005 translate_charset (ascii_to_ebcdic);
1006 newline_character = ascii_to_ebcdic['\n'];
1007 space_character = ascii_to_ebcdic[' '];
1009 else if (conversions_mask & C_IBM)
1011 translate_charset (ascii_to_ibm);
1012 newline_character = ascii_to_ibm['\n'];
1013 space_character = ascii_to_ibm[' '];
1017 /* Apply the character-set translations specified by the user
1018 to the NREAD bytes in BUF. */
1021 translate_buffer (char *buf, size_t nread)
1026 for (i = nread, cp = buf; i; i--, cp++)
1027 *cp = trans_table[to_uchar (*cp)];
1030 /* If true, the last char from the previous call to `swab_buffer'
1031 is saved in `saved_char'. */
1032 static bool char_is_saved = false;
1034 /* Odd char from previous call. */
1035 static char saved_char;
1037 /* Swap NREAD bytes in BUF, plus possibly an initial char from the
1038 previous call. If NREAD is odd, save the last char for the
1039 next call. Return the new start of the BUF buffer. */
1042 swab_buffer (char *buf, size_t *nread)
1044 char *bufstart = buf;
1048 /* Is a char left from last time? */
1051 *--bufstart = saved_char;
1053 char_is_saved = false;
1058 /* An odd number of chars are in the buffer. */
1059 saved_char = bufstart[--*nread];
1060 char_is_saved = true;
1063 /* Do the byte-swapping by moving every second character two
1064 positions toward the end, working from the end of the buffer
1065 toward the beginning. This way we only move half of the data. */
1067 cp = bufstart + *nread; /* Start one char past the last. */
1068 for (i = *nread / 2; i; i--, cp -= 2)
1074 /* Add OFFSET to the input offset, setting the overflow flag if
1078 advance_input_offset (uintmax_t offset)
1080 input_offset += offset;
1081 if (input_offset < offset)
1082 input_offset_overflow = true;
1085 /* This is a wrapper for lseek. It detects and warns about a kernel
1086 bug that makes lseek a no-op for tape devices, even though the kernel
1087 lseek return value suggests that the function succeeded.
1089 The parameters are the same as those of the lseek function, but
1090 with the addition of FILENAME, the name of the file associated with
1091 descriptor FDESC. The file name is used solely in the warning that's
1092 printed when the bug is detected. Return the same value that lseek
1093 would have returned, but when the lseek bug is detected, return -1
1094 to indicate that lseek failed.
1096 The offending behavior has been confirmed with an Exabyte SCSI tape
1097 drive accessed via /dev/nst0 on both Linux-2.2.17 and Linux-2.4.16. */
1101 # include <sys/mtio.h>
1103 # define MT_SAME_POSITION(P, Q) \
1104 ((P).mt_resid == (Q).mt_resid \
1105 && (P).mt_fileno == (Q).mt_fileno \
1106 && (P).mt_blkno == (Q).mt_blkno)
1109 skip_via_lseek (char const *filename, int fdesc, off_t offset, int whence)
1113 bool got_original_tape_position = (ioctl (fdesc, MTIOCGET, &s1) == 0);
1114 /* known bad device type */
1115 /* && s.mt_type == MT_ISSCSI2 */
1117 off_t new_position = lseek (fdesc, offset, whence);
1118 if (0 <= new_position
1119 && got_original_tape_position
1120 && ioctl (fdesc, MTIOCGET, &s2) == 0
1121 && MT_SAME_POSITION (s1, s2))
1123 error (0, 0, _("warning: working around lseek kernel bug for file (%s)\n\
1124 of mt_type=0x%0lx -- see <sys/mtio.h> for the list of types"),
1125 filename, s2.mt_type);
1130 return new_position;
1133 # define skip_via_lseek(Filename, Fd, Offset, Whence) lseek (Fd, Offset, Whence)
1136 /* Throw away RECORDS blocks of BLOCKSIZE bytes on file descriptor FDESC,
1137 which is open with read permission for FILE. Store up to BLOCKSIZE
1138 bytes of the data at a time in BUF, if necessary. RECORDS must be
1139 nonzero. If fdesc is STDIN_FILENO, advance the input offset.
1140 Return the number of records remaining, i.e., that were not skipped
1141 because EOF was reached. */
1144 skip (int fdesc, char const *file, uintmax_t records, size_t blocksize,
1147 uintmax_t offset = records * blocksize;
1149 /* Try lseek and if an error indicates it was an inappropriate operation --
1150 or if the file offset is not representable as an off_t --
1151 fall back on using read. */
1154 if (records <= OFF_T_MAX / blocksize
1155 && 0 <= skip_via_lseek (file, fdesc, offset, SEEK_CUR))
1157 if (fdesc == STDIN_FILENO)
1158 advance_input_offset (offset);
1163 int lseek_errno = errno;
1167 ssize_t nread = iread (fdesc, buf, blocksize);
1170 if (fdesc == STDIN_FILENO)
1172 error (0, errno, _("reading %s"), quote (file));
1173 if (conversions_mask & C_NOERROR)
1180 error (0, lseek_errno, _("%s: cannot seek"), quote (file));
1181 quit (EXIT_FAILURE);
1186 if (fdesc == STDIN_FILENO)
1187 advance_input_offset (nread);
1189 while (--records != 0);
1195 /* Advance the input by NBYTES if possible, after a read error.
1196 The input file offset may or may not have advanced after the failed
1197 read; adjust it to point just after the bad record regardless.
1198 Return true if successful, or if the input is already known to not
1202 advance_input_after_read_error (size_t nbytes)
1204 if (! input_seekable)
1206 if (input_seek_errno == ESPIPE)
1208 errno = input_seek_errno;
1213 advance_input_offset (nbytes);
1214 input_offset_overflow |= (OFF_T_MAX < input_offset);
1215 if (input_offset_overflow)
1217 error (0, 0, _("offset overflow while reading file %s"),
1218 quote (input_file));
1221 offset = lseek (STDIN_FILENO, 0, SEEK_CUR);
1225 if (offset == input_offset)
1227 diff = input_offset - offset;
1228 if (! (0 <= diff && diff <= nbytes))
1229 error (0, 0, _("warning: invalid file offset after failed read"));
1230 if (0 <= skip_via_lseek (input_file, STDIN_FILENO, diff, SEEK_CUR))
1233 error (0, 0, _("cannot work around kernel bug after all"));
1237 error (0, errno, _("%s: cannot seek"), quote (input_file));
1241 /* Copy NREAD bytes of BUF, with no conversions. */
1244 copy_simple (char const *buf, size_t nread)
1246 const char *start = buf; /* First uncopied char in BUF. */
1250 size_t nfree = MIN (nread, output_blocksize - oc);
1252 memcpy (obuf + oc, start, nfree);
1254 nread -= nfree; /* Update the number of bytes left to copy. */
1257 if (oc >= output_blocksize)
1263 /* Copy NREAD bytes of BUF, doing conv=block
1264 (pad newline-terminated records to `conversion_blocksize',
1265 replacing the newline with trailing spaces). */
1268 copy_with_block (char const *buf, size_t nread)
1272 for (i = nread; i; i--, buf++)
1274 if (*buf == newline_character)
1276 if (col < conversion_blocksize)
1279 for (j = col; j < conversion_blocksize; j++)
1280 output_char (space_character);
1286 if (col == conversion_blocksize)
1288 else if (col < conversion_blocksize)
1295 /* Copy NREAD bytes of BUF, doing conv=unblock
1296 (replace trailing spaces in `conversion_blocksize'-sized records
1300 copy_with_unblock (char const *buf, size_t nread)
1304 static size_t pending_spaces = 0;
1306 for (i = 0; i < nread; i++)
1310 if (col++ >= conversion_blocksize)
1312 col = pending_spaces = 0; /* Wipe out any pending spaces. */
1313 i--; /* Push the char back; get it later. */
1314 output_char (newline_character);
1316 else if (c == space_character)
1320 /* `c' is the character after a run of spaces that were not
1321 at the end of the conversion buffer. Output them. */
1322 while (pending_spaces)
1324 output_char (space_character);
1332 /* Set the file descriptor flags for FD that correspond to the nonzero bits
1333 in ADD_FLAGS. The file's name is NAME. */
1336 set_fd_flags (int fd, int add_flags, char const *name)
1338 /* Ignore file creation flags that are no-ops on file descriptors. */
1339 add_flags &= ~ (O_NOCTTY | O_NOFOLLOW);
1343 int old_flags = fcntl (fd, F_GETFL);
1344 int new_flags = old_flags | add_flags;
1348 else if (old_flags != new_flags)
1350 if (new_flags & (O_DIRECTORY | O_NOLINKS))
1352 /* NEW_FLAGS contains at least one file creation flag that
1353 requires some checking of the open file descriptor. */
1355 if (fstat (fd, &st) != 0)
1357 else if ((new_flags & O_DIRECTORY) && ! S_ISDIR (st.st_mode))
1362 else if ((new_flags & O_NOLINKS) && 1 < st.st_nlink)
1367 new_flags &= ~ (O_DIRECTORY | O_NOLINKS);
1370 if (ok && old_flags != new_flags
1371 && fcntl (fd, F_SETFL, new_flags) == -1)
1376 error (EXIT_FAILURE, errno, _("setting flags for %s"), quote (name));
1380 /* The main loop. */
1385 char *ibuf, *bufstart; /* Input buffer. */
1386 /* These are declared static so that even though we don't free the
1387 buffers, valgrind will recognize that there is no "real" leak. */
1388 static char *real_buf; /* real buffer address before alignment */
1389 static char *real_obuf;
1390 ssize_t nread; /* Bytes read in the current block. */
1392 /* If nonzero, then the previously read block was partial and
1393 PARTREAD was its size. */
1394 size_t partread = 0;
1396 int exit_status = EXIT_SUCCESS;
1397 size_t n_bytes_read;
1399 /* Leave at least one extra byte at the beginning and end of `ibuf'
1400 for conv=swab, but keep the buffer address even. But some peculiar
1401 device drivers work only with word-aligned buffers, so leave an
1404 /* Some devices require alignment on a sector or page boundary
1405 (e.g. character disk devices). Align the input buffer to a
1406 page boundary to cover all bases. Note that due to the swab
1407 algorithm, we must have at least one byte in the page before
1408 the input buffer; thus we allocate 2 pages of slop in the
1409 real buffer. 8k above the blocksize shouldn't bother anyone.
1411 The page alignment is necessary on any linux system that supports
1412 either the SGI raw I/O patch or Steven Tweedies raw I/O patch.
1413 It is necessary when accessing raw (i.e. character special) disk
1414 devices on Unixware or other SVR4-derived system. */
1416 real_buf = xmalloc (input_blocksize + INPUT_BLOCK_SLOP);
1418 ibuf += SWAB_ALIGN_OFFSET; /* allow space for swab */
1420 ibuf = ptr_align (ibuf, page_size);
1422 if (conversions_mask & C_TWOBUFS)
1424 /* Page-align the output buffer, too. */
1425 real_obuf = xmalloc (output_blocksize + OUTPUT_BLOCK_SLOP);
1426 obuf = ptr_align (real_obuf, page_size);
1434 if (skip_records != 0)
1436 skip (STDIN_FILENO, input_file, skip_records, input_blocksize, ibuf);
1437 /* POSIX doesn't say what to do when dd detects it has been
1438 asked to skip past EOF, so I assume it's non-fatal if the
1439 call to 'skip' returns nonzero. FIXME: maybe give a warning. */
1442 if (seek_records != 0)
1444 uintmax_t write_records = skip (STDOUT_FILENO, output_file,
1445 seek_records, output_blocksize, obuf);
1447 if (write_records != 0)
1449 memset (obuf, 0, output_blocksize);
1452 if (iwrite (STDOUT_FILENO, obuf, output_blocksize)
1453 != output_blocksize)
1455 error (0, errno, _("writing to %s"), quote (output_file));
1456 quit (EXIT_FAILURE);
1458 while (--write_records != 0);
1462 if (max_records == 0)
1467 if (r_partial + r_full >= max_records)
1470 /* Zero the buffer before reading, so that if we get a read error,
1471 whatever data we are able to read is followed by zeros.
1472 This minimizes data loss. */
1473 if ((conversions_mask & C_SYNC) && (conversions_mask & C_NOERROR))
1475 (conversions_mask & (C_BLOCK | C_UNBLOCK)) ? ' ' : '\0',
1478 nread = iread (STDIN_FILENO, ibuf, input_blocksize);
1485 error (0, errno, _("reading %s"), quote (input_file));
1486 if (conversions_mask & C_NOERROR)
1489 /* Seek past the bad block if possible. */
1490 if (!advance_input_after_read_error (input_blocksize - partread))
1492 exit_status = EXIT_FAILURE;
1494 /* Suppress duplicate diagnostics. */
1495 input_seekable = false;
1496 input_seek_errno = ESPIPE;
1498 if ((conversions_mask & C_SYNC) && !partread)
1499 /* Replace the missing input with null bytes and
1500 proceed normally. */
1507 /* Write any partial block. */
1508 exit_status = EXIT_FAILURE;
1513 n_bytes_read = nread;
1514 advance_input_offset (nread);
1516 if (n_bytes_read < input_blocksize)
1519 partread = n_bytes_read;
1520 if (conversions_mask & C_SYNC)
1522 if (!(conversions_mask & C_NOERROR))
1523 /* If C_NOERROR, we zeroed the block before reading. */
1524 memset (ibuf + n_bytes_read,
1525 (conversions_mask & (C_BLOCK | C_UNBLOCK)) ? ' ' : '\0',
1526 input_blocksize - n_bytes_read);
1527 n_bytes_read = input_blocksize;
1536 if (ibuf == obuf) /* If not C_TWOBUFS. */
1538 size_t nwritten = iwrite (STDOUT_FILENO, obuf, n_bytes_read);
1539 w_bytes += nwritten;
1540 if (nwritten != n_bytes_read)
1542 error (0, errno, _("writing %s"), quote (output_file));
1543 return EXIT_FAILURE;
1545 else if (n_bytes_read == input_blocksize)
1552 /* Do any translations on the whole buffer at once. */
1554 if (translation_needed)
1555 translate_buffer (ibuf, n_bytes_read);
1557 if (conversions_mask & C_SWAB)
1558 bufstart = swab_buffer (ibuf, &n_bytes_read);
1562 if (conversions_mask & C_BLOCK)
1563 copy_with_block (bufstart, n_bytes_read);
1564 else if (conversions_mask & C_UNBLOCK)
1565 copy_with_unblock (bufstart, n_bytes_read);
1567 copy_simple (bufstart, n_bytes_read);
1570 /* If we have a char left as a result of conv=swab, output it. */
1573 if (conversions_mask & C_BLOCK)
1574 copy_with_block (&saved_char, 1);
1575 else if (conversions_mask & C_UNBLOCK)
1576 copy_with_unblock (&saved_char, 1);
1578 output_char (saved_char);
1581 if ((conversions_mask & C_BLOCK) && col > 0)
1583 /* If the final input line didn't end with a '\n', pad
1584 the output block to `conversion_blocksize' chars. */
1586 for (i = col; i < conversion_blocksize; i++)
1587 output_char (space_character);
1590 if ((conversions_mask & C_UNBLOCK) && col == conversion_blocksize)
1591 /* Add a final '\n' if there are exactly `conversion_blocksize'
1592 characters in the final record. */
1593 output_char (newline_character);
1595 /* Write out the last block. */
1598 size_t nwritten = iwrite (STDOUT_FILENO, obuf, oc);
1599 w_bytes += nwritten;
1604 error (0, errno, _("writing %s"), quote (output_file));
1605 return EXIT_FAILURE;
1609 if ((conversions_mask & C_FDATASYNC) && fdatasync (STDOUT_FILENO) != 0)
1611 if (errno != ENOSYS && errno != EINVAL)
1613 error (0, errno, _("fdatasync failed for %s"), quote (output_file));
1614 exit_status = EXIT_FAILURE;
1616 conversions_mask |= C_FSYNC;
1619 if (conversions_mask & C_FSYNC)
1620 while (fsync (STDOUT_FILENO) != 0)
1623 error (0, errno, _("fsync failed for %s"), quote (output_file));
1624 return EXIT_FAILURE;
1631 main (int argc, char **argv)
1637 initialize_main (&argc, &argv);
1638 program_name = argv[0];
1639 setlocale (LC_ALL, "");
1640 bindtextdomain (PACKAGE, LOCALEDIR);
1641 textdomain (PACKAGE);
1643 /* Arrange to close stdout if parse_long_options exits. */
1644 atexit (close_stdout);
1646 page_size = getpagesize ();
1648 parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE, VERSION,
1649 usage, AUTHORS, (char const *) NULL);
1650 if (getopt_long (argc, argv, "", NULL, NULL) != -1)
1651 usage (EXIT_FAILURE);
1653 /* Initialize translation table to identity translation. */
1654 for (i = 0; i < 256; i++)
1657 /* Decode arguments. */
1658 scanargs (argc, argv);
1660 apply_translations ();
1662 if (input_file == NULL)
1664 input_file = _("standard input");
1665 set_fd_flags (STDIN_FILENO, input_flags, input_file);
1669 if (fd_reopen (STDIN_FILENO, input_file, O_RDONLY | input_flags, 0) < 0)
1670 error (EXIT_FAILURE, errno, _("opening %s"), quote (input_file));
1673 offset = lseek (STDIN_FILENO, 0, SEEK_CUR);
1674 input_seekable = (0 <= offset);
1675 input_offset = offset;
1676 input_seek_errno = errno;
1678 if (output_file == NULL)
1680 output_file = _("standard output");
1681 set_fd_flags (STDOUT_FILENO, output_flags, output_file);
1685 mode_t perms = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
1688 | (conversions_mask & C_NOCREAT ? 0 : O_CREAT)
1689 | (conversions_mask & C_EXCL ? O_EXCL : 0)
1690 | (seek_records || (conversions_mask & C_NOTRUNC) ? 0 : O_TRUNC));
1692 /* Open the output file with *read* access only if we might
1693 need to read to satisfy a `seek=' request. If we can't read
1694 the file, go ahead with write-only access; it might work. */
1696 || fd_reopen (STDOUT_FILENO, output_file, O_RDWR | opts, perms) < 0)
1697 && (fd_reopen (STDOUT_FILENO, output_file, O_WRONLY | opts, perms)
1699 error (EXIT_FAILURE, errno, _("opening %s"), quote (output_file));
1702 if (seek_records != 0 && !(conversions_mask & C_NOTRUNC))
1704 uintmax_t size = seek_records * output_blocksize;
1705 unsigned long int obs = output_blocksize;
1707 if (OFF_T_MAX / output_blocksize < seek_records)
1708 error (EXIT_FAILURE, 0,
1709 _("offset too large: "
1710 "cannot truncate to a length of seek=%"PRIuMAX""
1711 " (%lu-byte) blocks"),
1714 if (ftruncate (STDOUT_FILENO, size) != 0)
1716 /* Complain only when ftruncate fails on a regular file, a
1717 directory, or a shared memory object, as POSIX 1003.1-2004
1718 specifies ftruncate's behavior only for these file types.
1719 For example, do not complain when Linux 2.4 ftruncate
1720 fails on /dev/fd0. */
1721 int ftruncate_errno = errno;
1722 struct stat stdout_stat;
1723 if (fstat (STDOUT_FILENO, &stdout_stat) != 0)
1724 error (EXIT_FAILURE, errno, _("cannot fstat %s"),
1725 quote (output_file));
1726 if (S_ISREG (stdout_stat.st_mode)
1727 || S_ISDIR (stdout_stat.st_mode)
1728 || S_TYPEISSHM (&stdout_stat))
1729 error (EXIT_FAILURE, ftruncate_errno,
1730 _("truncating at %"PRIuMAX" bytes in output file %s"),
1731 size, quote (output_file));
1737 install_signal_handlers ();
1739 start_time = gethrxtime ();
1741 exit_status = dd_copy ();