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 /* Function used for read (to handle iflag=fullblock parameter) */
229 static ssize_t (*iread_fnc) (int fd, char *buf, size_t size);
231 /* A longest symbol in the struct symbol_values tables below. */
232 #define LONGEST_SYMBOL "fdatasync"
234 /* A symbol and the corresponding integer value. */
237 char symbol[sizeof LONGEST_SYMBOL];
241 /* Conversion symbols, for conv="...". */
242 static struct symbol_value const conversions[] =
244 {"ascii", C_ASCII | C_TWOBUFS}, /* EBCDIC to ASCII. */
245 {"ebcdic", C_EBCDIC | C_TWOBUFS}, /* ASCII to EBCDIC. */
246 {"ibm", C_IBM | C_TWOBUFS}, /* Slightly different ASCII to EBCDIC. */
247 {"block", C_BLOCK | C_TWOBUFS}, /* Variable to fixed length records. */
248 {"unblock", C_UNBLOCK | C_TWOBUFS}, /* Fixed to variable length records. */
249 {"lcase", C_LCASE | C_TWOBUFS}, /* Translate upper to lower case. */
250 {"ucase", C_UCASE | C_TWOBUFS}, /* Translate lower to upper case. */
251 {"swab", C_SWAB | C_TWOBUFS}, /* Swap bytes of input. */
252 {"noerror", C_NOERROR}, /* Ignore i/o errors. */
253 {"nocreat", C_NOCREAT}, /* Do not create output file. */
254 {"excl", C_EXCL}, /* Fail if the output file already exists. */
255 {"notrunc", C_NOTRUNC}, /* Do not truncate output file. */
256 {"sync", C_SYNC}, /* Pad input records to ibs with NULs. */
257 {"fdatasync", C_FDATASYNC}, /* Synchronize output data before finishing. */
258 {"fsync", C_FSYNC}, /* Also synchronize output metadata. */
262 /* Flags, for iflag="..." and oflag="...". */
263 #define O_FULLBLOCK 010000000 /* Read only full blocks from input */
264 static struct symbol_value const flags[] =
266 {"append", O_APPEND},
267 {"binary", O_BINARY},
268 {"direct", O_DIRECT},
269 {"directory", O_DIRECTORY},
271 {"noatime", O_NOATIME},
272 {"noctty", O_NOCTTY},
273 {"nofollow", HAVE_WORKING_O_NOFOLLOW ? O_NOFOLLOW : 0},
274 {"nolinks", O_NOLINKS},
275 {"nonblock", O_NONBLOCK},
278 {"fullblock", O_FULLBLOCK}, /* Read only full blocks from input */
282 /* Status, for status="...". */
283 static struct symbol_value const statuses[] =
285 {"noxfer", STATUS_NOXFER},
289 /* Translation table formed by applying successive transformations. */
290 static unsigned char trans_table[256];
292 static char const ascii_to_ebcdic[] =
294 '\000', '\001', '\002', '\003', '\067', '\055', '\056', '\057',
295 '\026', '\005', '\045', '\013', '\014', '\015', '\016', '\017',
296 '\020', '\021', '\022', '\023', '\074', '\075', '\062', '\046',
297 '\030', '\031', '\077', '\047', '\034', '\035', '\036', '\037',
298 '\100', '\117', '\177', '\173', '\133', '\154', '\120', '\175',
299 '\115', '\135', '\134', '\116', '\153', '\140', '\113', '\141',
300 '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367',
301 '\370', '\371', '\172', '\136', '\114', '\176', '\156', '\157',
302 '\174', '\301', '\302', '\303', '\304', '\305', '\306', '\307',
303 '\310', '\311', '\321', '\322', '\323', '\324', '\325', '\326',
304 '\327', '\330', '\331', '\342', '\343', '\344', '\345', '\346',
305 '\347', '\350', '\351', '\112', '\340', '\132', '\137', '\155',
306 '\171', '\201', '\202', '\203', '\204', '\205', '\206', '\207',
307 '\210', '\211', '\221', '\222', '\223', '\224', '\225', '\226',
308 '\227', '\230', '\231', '\242', '\243', '\244', '\245', '\246',
309 '\247', '\250', '\251', '\300', '\152', '\320', '\241', '\007',
310 '\040', '\041', '\042', '\043', '\044', '\025', '\006', '\027',
311 '\050', '\051', '\052', '\053', '\054', '\011', '\012', '\033',
312 '\060', '\061', '\032', '\063', '\064', '\065', '\066', '\010',
313 '\070', '\071', '\072', '\073', '\004', '\024', '\076', '\341',
314 '\101', '\102', '\103', '\104', '\105', '\106', '\107', '\110',
315 '\111', '\121', '\122', '\123', '\124', '\125', '\126', '\127',
316 '\130', '\131', '\142', '\143', '\144', '\145', '\146', '\147',
317 '\150', '\151', '\160', '\161', '\162', '\163', '\164', '\165',
318 '\166', '\167', '\170', '\200', '\212', '\213', '\214', '\215',
319 '\216', '\217', '\220', '\232', '\233', '\234', '\235', '\236',
320 '\237', '\240', '\252', '\253', '\254', '\255', '\256', '\257',
321 '\260', '\261', '\262', '\263', '\264', '\265', '\266', '\267',
322 '\270', '\271', '\272', '\273', '\274', '\275', '\276', '\277',
323 '\312', '\313', '\314', '\315', '\316', '\317', '\332', '\333',
324 '\334', '\335', '\336', '\337', '\352', '\353', '\354', '\355',
325 '\356', '\357', '\372', '\373', '\374', '\375', '\376', '\377'
328 static char const ascii_to_ibm[] =
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', '\132', '\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', '\255', '\340', '\275', '\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', '\117', '\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 ebcdic_to_ascii[] =
366 '\000', '\001', '\002', '\003', '\234', '\011', '\206', '\177',
367 '\227', '\215', '\216', '\013', '\014', '\015', '\016', '\017',
368 '\020', '\021', '\022', '\023', '\235', '\205', '\010', '\207',
369 '\030', '\031', '\222', '\217', '\034', '\035', '\036', '\037',
370 '\200', '\201', '\202', '\203', '\204', '\012', '\027', '\033',
371 '\210', '\211', '\212', '\213', '\214', '\005', '\006', '\007',
372 '\220', '\221', '\026', '\223', '\224', '\225', '\226', '\004',
373 '\230', '\231', '\232', '\233', '\024', '\025', '\236', '\032',
374 '\040', '\240', '\241', '\242', '\243', '\244', '\245', '\246',
375 '\247', '\250', '\133', '\056', '\074', '\050', '\053', '\041',
376 '\046', '\251', '\252', '\253', '\254', '\255', '\256', '\257',
377 '\260', '\261', '\135', '\044', '\052', '\051', '\073', '\136',
378 '\055', '\057', '\262', '\263', '\264', '\265', '\266', '\267',
379 '\270', '\271', '\174', '\054', '\045', '\137', '\076', '\077',
380 '\272', '\273', '\274', '\275', '\276', '\277', '\300', '\301',
381 '\302', '\140', '\072', '\043', '\100', '\047', '\075', '\042',
382 '\303', '\141', '\142', '\143', '\144', '\145', '\146', '\147',
383 '\150', '\151', '\304', '\305', '\306', '\307', '\310', '\311',
384 '\312', '\152', '\153', '\154', '\155', '\156', '\157', '\160',
385 '\161', '\162', '\313', '\314', '\315', '\316', '\317', '\320',
386 '\321', '\176', '\163', '\164', '\165', '\166', '\167', '\170',
387 '\171', '\172', '\322', '\323', '\324', '\325', '\326', '\327',
388 '\330', '\331', '\332', '\333', '\334', '\335', '\336', '\337',
389 '\340', '\341', '\342', '\343', '\344', '\345', '\346', '\347',
390 '\173', '\101', '\102', '\103', '\104', '\105', '\106', '\107',
391 '\110', '\111', '\350', '\351', '\352', '\353', '\354', '\355',
392 '\175', '\112', '\113', '\114', '\115', '\116', '\117', '\120',
393 '\121', '\122', '\356', '\357', '\360', '\361', '\362', '\363',
394 '\134', '\237', '\123', '\124', '\125', '\126', '\127', '\130',
395 '\131', '\132', '\364', '\365', '\366', '\367', '\370', '\371',
396 '\060', '\061', '\062', '\063', '\064', '\065', '\066', '\067',
397 '\070', '\071', '\372', '\373', '\374', '\375', '\376', '\377'
400 /* True if we need to close the standard output *stream*. */
401 static bool close_stdout_required = true;
403 /* The only reason to close the standard output *stream* is if
404 parse_long_options fails (as it does for --help or --version).
405 In any other case, dd uses only the STDOUT_FILENO file descriptor,
406 and the "cleanup" function calls "close (STDOUT_FILENO)".
407 Closing the file descriptor and then letting the usual atexit-run
408 close_stdout function call "fclose (stdout)" would result in a
409 harmless failure of the close syscall (with errno EBADF).
410 This function serves solely to avoid the unnecessary close_stdout
411 call, once parse_long_options has succeeded. */
413 maybe_close_stdout (void)
415 if (close_stdout_required)
422 if (status != EXIT_SUCCESS)
423 fprintf (stderr, _("Try `%s --help' for more information.\n"),
428 Usage: %s [OPERAND]...\n\
431 program_name, program_name);
433 Copy a file, converting and formatting according to the operands.\n\
435 bs=BYTES force ibs=BYTES and obs=BYTES\n\
436 cbs=BYTES convert BYTES bytes at a time\n\
437 conv=CONVS convert the file as per the comma separated symbol list\n\
438 count=BLOCKS copy only BLOCKS input blocks\n\
439 ibs=BYTES read BYTES bytes at a time\n\
442 if=FILE read from FILE instead of stdin\n\
443 iflag=FLAGS read as per the comma separated symbol list\n\
444 obs=BYTES write BYTES bytes at a time\n\
445 of=FILE write to FILE instead of stdout\n\
446 oflag=FLAGS write as per the comma separated symbol list\n\
447 seek=BLOCKS skip BLOCKS obs-sized blocks at start of output\n\
448 skip=BLOCKS skip BLOCKS ibs-sized blocks at start of input\n\
449 status=noxfer suppress transfer statistics\n\
453 BLOCKS and BYTES may be followed by the following multiplicative suffixes:\n\
454 xM M, c 1, w 2, b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024,\n\
455 GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y.\n\
457 Each CONV symbol may be:\n\
461 ascii from EBCDIC to ASCII\n\
462 ebcdic from ASCII to EBCDIC\n\
463 ibm from ASCII to alternate EBCDIC\n\
464 block pad newline-terminated records with spaces to cbs-size\n\
465 unblock replace trailing spaces in cbs-size records with newline\n\
466 lcase change upper case to lower case\n\
469 nocreat do not create the output file\n\
470 excl fail if the output file already exists\n\
471 notrunc do not truncate the output file\n\
472 ucase change lower case to upper case\n\
473 swab swap every pair of input bytes\n\
476 noerror continue after read errors\n\
477 sync pad every input block with NULs to ibs-size; when used\n\
478 with block or unblock, pad with spaces rather than NULs\n\
479 fdatasync physically write output file data before finishing\n\
480 fsync likewise, but also write metadata\n\
484 Each FLAG symbol may be:\n\
486 append append mode (makes sense only for output; conv=notrunc suggested)\n\
489 fputs (_(" direct use direct I/O for data\n"), stdout);
491 fputs (_(" directory fail unless a directory\n"), stdout);
493 fputs (_(" dsync use synchronized I/O for data\n"), stdout);
495 fputs (_(" sync likewise, but also for metadata\n"), stdout);
497 fputs (_(" nonblock use non-blocking I/O\n"), stdout);
499 fputs (_(" noatime do not update access time\n"), stdout);
501 fputs (_(" noctty do not assign controlling terminal from file\n"),
503 if (HAVE_WORKING_O_NOFOLLOW)
504 fputs (_(" nofollow do not follow symlinks\n"), stdout);
506 fputs (_(" nolinks fail if multiply-linked\n"), stdout);
508 fputs (_(" binary use binary I/O for data\n"), stdout);
510 fputs (_(" text use text I/O for data\n"), stdout);
513 char const *siginfo_name = (SIGINFO == SIGUSR1 ? "USR1" : "INFO");
516 Sending a %s signal to a running `dd' process makes it\n\
517 print I/O statistics to standard error and then resume copying.\n\
519 $ dd if=/dev/zero of=/dev/null& pid=$!\n\
520 $ kill -%s $pid; sleep 1; kill $pid\n\
521 18335302+0 records in\n\
522 18335302+0 records out\n\
523 9387674624 bytes (9.4 GB) copied, 34.6279 seconds, 271 MB/s\n\
528 siginfo_name, siginfo_name);
531 fputs (HELP_OPTION_DESCRIPTION, stdout);
532 fputs (VERSION_OPTION_DESCRIPTION, stdout);
533 emit_bug_reporting_address ();
539 translate_charset (char const *new_trans)
543 for (i = 0; i < 256; i++)
544 trans_table[i] = new_trans[trans_table[i]];
545 translation_needed = true;
548 /* Return true if I has more than one bit set. I must be nonnegative. */
551 multiple_bits_set (int i)
553 return (i & (i - 1)) != 0;
556 /* Print transfer statistics. */
561 xtime_t now = gethrxtime ();
562 char hbuf[LONGEST_HUMAN_READABLE + 1];
564 (human_autoscale | human_round_to_nearest
565 | human_space_before_unit | human_SI | human_B);
567 char const *bytes_per_second;
570 _("%"PRIuMAX"+%"PRIuMAX" records in\n"
571 "%"PRIuMAX"+%"PRIuMAX" records out\n"),
572 r_full, r_partial, w_full, w_partial);
576 ngettext ("%"PRIuMAX" truncated record\n",
577 "%"PRIuMAX" truncated records\n",
578 select_plural (r_truncate)),
581 if (status_flags & STATUS_NOXFER)
584 /* Use integer arithmetic to compute the transfer rate,
585 since that makes it easy to use SI abbreviations. */
588 ngettext ("%"PRIuMAX" byte (%s) copied",
589 "%"PRIuMAX" bytes (%s) copied",
590 select_plural (w_bytes)),
592 human_readable (w_bytes, hbuf, human_opts, 1, 1));
594 if (start_time < now)
596 double XTIME_PRECISIONe0 = XTIME_PRECISION;
597 uintmax_t delta_xtime = now;
598 delta_xtime -= start_time;
599 delta_s = delta_xtime / XTIME_PRECISIONe0;
600 bytes_per_second = human_readable (w_bytes, hbuf, human_opts,
601 XTIME_PRECISION, delta_xtime);
606 bytes_per_second = _("Infinity B");
609 /* TRANSLATORS: The two instances of "s" in this string are the SI
610 symbol "s" (meaning second), and should not be translated.
612 This format used to be:
614 ngettext (", %g second, %s/s\n", ", %g seconds, %s/s\n", delta_s == 1)
616 but that was incorrect for languages like Polish. To fix this
617 bug we now use SI symbols even though they're a bit more
618 confusing in English. */
619 fprintf (stderr, _(", %g s, %s/s\n"), delta_s, bytes_per_second);
625 if (close (STDIN_FILENO) < 0)
626 error (EXIT_FAILURE, errno,
627 _("closing input file %s"), quote (input_file));
629 /* Don't remove this call to close, even though close_stdout
630 closes standard output. This close is necessary when cleanup
631 is called as part of a signal handler. */
632 if (close (STDOUT_FILENO) < 0)
633 error (EXIT_FAILURE, errno,
634 _("closing output file %s"), quote (output_file));
637 static inline void ATTRIBUTE_NORETURN
646 /* An ordinary signal was received; arrange for the program to exit. */
649 interrupt_handler (int sig)
652 signal (sig, SIG_DFL);
653 interrupt_signal = sig;
656 /* An info signal was received; arrange for the program to print status. */
659 siginfo_handler (int sig)
662 signal (sig, siginfo_handler);
666 /* Install the signal handlers. */
669 install_signal_handlers (void)
671 bool catch_siginfo = ! (SIGINFO == SIGUSR1 && getenv ("POSIXLY_CORRECT"));
675 struct sigaction act;
676 sigemptyset (&caught_signals);
679 sigaction (SIGINFO, NULL, &act);
680 if (act.sa_handler != SIG_IGN)
681 sigaddset (&caught_signals, SIGINFO);
683 sigaction (SIGINT, NULL, &act);
684 if (act.sa_handler != SIG_IGN)
685 sigaddset (&caught_signals, SIGINT);
686 act.sa_mask = caught_signals;
688 if (sigismember (&caught_signals, SIGINFO))
690 act.sa_handler = siginfo_handler;
692 sigaction (SIGINFO, &act, NULL);
695 if (sigismember (&caught_signals, SIGINT))
697 /* POSIX 1003.1-2001 says SA_RESETHAND implies SA_NODEFER,
698 but this is not true on Solaris 8 at least. It doesn't
699 hurt to use SA_NODEFER here, so leave it in. */
700 act.sa_handler = interrupt_handler;
701 act.sa_flags = SA_NODEFER | SA_RESETHAND;
702 sigaction (SIGINT, &act, NULL);
707 if (catch_siginfo && signal (SIGINFO, SIG_IGN) != SIG_IGN)
709 signal (SIGINFO, siginfo_handler);
710 siginterrupt (SIGINFO, 1);
712 if (signal (SIGINT, SIG_IGN) != SIG_IGN)
714 signal (SIGINT, interrupt_handler);
715 siginterrupt (SIGINT, 1);
720 /* Process any pending signals. If signals are caught, this function
721 should be called periodically. Ideally there should never be an
722 unbounded amount of time when signals are not being processed. */
725 process_signals (void)
727 while (interrupt_signal | info_signal_count)
733 sigprocmask (SIG_BLOCK, &caught_signals, &oldset);
735 /* Reload interrupt_signal and info_signal_count, in case a new
736 signal was handled before sigprocmask took effect. */
737 interrupt = interrupt_signal;
738 infos = info_signal_count;
741 info_signal_count = infos - 1;
743 sigprocmask (SIG_SETMASK, &oldset, NULL);
753 /* Read from FD into the buffer BUF of size SIZE, processing any
754 signals that arrive before bytes are read. Return the number of
755 bytes read if successful, -1 (setting errno) on failure. */
758 iread (int fd, char *buf, size_t size)
764 nread = read (fd, buf, size);
765 if (! (nread < 0 && errno == EINTR))
770 /* Wrapper around iread function which reads full blocks if possible */
772 iread_fullblock (int fd, char *buf, size_t size)
778 ssize_t ncurr = iread(fd, buf, size);
791 /* Write to FD the buffer BUF of size SIZE, processing any signals
792 that arrive. Return the number of bytes written, setting errno if
793 this is less than SIZE. Keep trying if there are partial
797 iwrite (int fd, char const *buf, size_t size)
799 size_t total_written = 0;
801 while (total_written < size)
805 nwritten = write (fd, buf + total_written, size - total_written);
811 else if (nwritten == 0)
813 /* Some buggy drivers return 0 when one tries to write beyond
814 a device's end. (Example: Linux 1.2.13 on /dev/fd0.)
815 Set errno to ENOSPC so they get a sensible diagnostic. */
820 total_written += nwritten;
823 return total_written;
826 /* Write, then empty, the output buffer `obuf'. */
831 size_t nwritten = iwrite (STDOUT_FILENO, obuf, output_blocksize);
833 if (nwritten != output_blocksize)
835 error (0, errno, _("writing to %s"), quote (output_file));
845 /* Return true if STR is of the form "PATTERN" or "PATTERNDELIM...". */
848 operand_matches (char const *str, char const *pattern, char delim)
851 if (*str++ != *pattern++)
853 return !*str || *str == delim;
856 /* Interpret one "conv=..." or similar operand STR according to the
857 symbols in TABLE, returning the flags specified. If the operand
858 cannot be parsed, use ERROR_MSGID to generate a diagnostic. */
861 parse_symbols (char const *str, struct symbol_value const *table,
862 char const *error_msgid)
868 char const *strcomma = strchr (str, ',');
869 struct symbol_value const *entry;
872 ! (operand_matches (str, entry->symbol, ',') && entry->value);
875 if (! entry->symbol[0])
877 size_t slen = strcomma ? strcomma - str : strlen (str);
878 error (0, 0, "%s: %s", _(error_msgid),
879 quotearg_n_style_mem (0, locale_quoting_style, str, slen));
880 usage (EXIT_FAILURE);
884 value |= entry->value;
893 /* Return the value of STR, interpreted as a non-negative decimal integer,
894 optionally multiplied by various values.
895 Set *INVALID if STR does not represent a number in this format. */
898 parse_integer (const char *str, bool *invalid)
902 enum strtol_error e = xstrtoumax (str, &suffix, 10, &n, "bcEGkKMPTwYZ0");
904 if (e == LONGINT_INVALID_SUFFIX_CHAR && *suffix == 'x')
906 uintmax_t multiplier = parse_integer (suffix + 1, invalid);
908 if (multiplier != 0 && n * multiplier / multiplier != n)
916 else if (e != LONGINT_OK)
925 /* OPERAND is of the form "X=...". Return true if X is NAME. */
928 operand_is (char const *operand, char const *name)
930 return operand_matches (operand, name, '=');
934 scanargs (int argc, char *const *argv)
937 size_t blocksize = 0;
939 for (i = optind; i < argc; i++)
941 char const *name = argv[i];
942 char const *val = strchr (name, '=');
946 error (0, 0, _("unrecognized operand %s"), quote (name));
947 usage (EXIT_FAILURE);
951 if (operand_is (name, "if"))
953 else if (operand_is (name, "of"))
955 else if (operand_is (name, "conv"))
956 conversions_mask |= parse_symbols (val, conversions,
957 N_("invalid conversion"));
958 else if (operand_is (name, "iflag"))
959 input_flags |= parse_symbols (val, flags,
960 N_("invalid input flag"));
961 else if (operand_is (name, "oflag"))
962 output_flags |= parse_symbols (val, flags,
963 N_("invalid output flag"));
964 else if (operand_is (name, "status"))
965 status_flags |= parse_symbols (val, statuses,
966 N_("invalid status flag"));
969 bool invalid = false;
970 uintmax_t n = parse_integer (val, &invalid);
972 if (operand_is (name, "ibs"))
974 invalid |= ! (0 < n && n <= MAX_BLOCKSIZE (INPUT_BLOCK_SLOP));
976 conversions_mask |= C_TWOBUFS;
978 else if (operand_is (name, "obs"))
980 invalid |= ! (0 < n && n <= MAX_BLOCKSIZE (OUTPUT_BLOCK_SLOP));
981 output_blocksize = n;
982 conversions_mask |= C_TWOBUFS;
984 else if (operand_is (name, "bs"))
986 invalid |= ! (0 < n && n <= MAX_BLOCKSIZE (INPUT_BLOCK_SLOP));
989 else if (operand_is (name, "cbs"))
991 invalid |= ! (0 < n && n <= SIZE_MAX);
992 conversion_blocksize = n;
994 else if (operand_is (name, "skip"))
996 else if (operand_is (name, "seek"))
998 else if (operand_is (name, "count"))
1002 error (0, 0, _("unrecognized operand %s"), quote (name));
1003 usage (EXIT_FAILURE);
1007 error (EXIT_FAILURE, 0, _("invalid number %s"), quote (val));
1012 input_blocksize = output_blocksize = blocksize;
1014 /* If bs= was given, both `input_blocksize' and `output_blocksize' will
1015 have been set to positive values. If either has not been set,
1016 bs= was not given, so make sure two buffers are used. */
1017 if (input_blocksize == 0 || output_blocksize == 0)
1018 conversions_mask |= C_TWOBUFS;
1019 if (input_blocksize == 0)
1020 input_blocksize = DEFAULT_BLOCKSIZE;
1021 if (output_blocksize == 0)
1022 output_blocksize = DEFAULT_BLOCKSIZE;
1023 if (conversion_blocksize == 0)
1024 conversions_mask &= ~(C_BLOCK | C_UNBLOCK);
1026 if (input_flags & (O_DSYNC | O_SYNC))
1027 input_flags |= O_RSYNC;
1029 if (output_flags & O_FULLBLOCK)
1031 error (0, 0, "%s: %s", _("invalid output flag"), "'fullblock'");
1032 usage (EXIT_FAILURE);
1034 iread_fnc = (input_flags & O_FULLBLOCK)?
1038 if (multiple_bits_set (conversions_mask & (C_ASCII | C_EBCDIC | C_IBM)))
1039 error (EXIT_FAILURE, 0, _("cannot combine any two of {ascii,ebcdic,ibm}"));
1040 if (multiple_bits_set (conversions_mask & (C_BLOCK | C_UNBLOCK)))
1041 error (EXIT_FAILURE, 0, _("cannot combine block and unblock"));
1042 if (multiple_bits_set (conversions_mask & (C_LCASE | C_UCASE)))
1043 error (EXIT_FAILURE, 0, _("cannot combine lcase and ucase"));
1044 if (multiple_bits_set (conversions_mask & (C_EXCL | C_NOCREAT)))
1045 error (EXIT_FAILURE, 0, _("cannot combine excl and nocreat"));
1048 /* Fix up translation table. */
1051 apply_translations (void)
1055 if (conversions_mask & C_ASCII)
1056 translate_charset (ebcdic_to_ascii);
1058 if (conversions_mask & C_UCASE)
1060 for (i = 0; i < 256; i++)
1061 trans_table[i] = toupper (trans_table[i]);
1062 translation_needed = true;
1064 else if (conversions_mask & C_LCASE)
1066 for (i = 0; i < 256; i++)
1067 trans_table[i] = tolower (trans_table[i]);
1068 translation_needed = true;
1071 if (conversions_mask & C_EBCDIC)
1073 translate_charset (ascii_to_ebcdic);
1074 newline_character = ascii_to_ebcdic['\n'];
1075 space_character = ascii_to_ebcdic[' '];
1077 else if (conversions_mask & C_IBM)
1079 translate_charset (ascii_to_ibm);
1080 newline_character = ascii_to_ibm['\n'];
1081 space_character = ascii_to_ibm[' '];
1085 /* Apply the character-set translations specified by the user
1086 to the NREAD bytes in BUF. */
1089 translate_buffer (char *buf, size_t nread)
1094 for (i = nread, cp = buf; i; i--, cp++)
1095 *cp = trans_table[to_uchar (*cp)];
1098 /* If true, the last char from the previous call to `swab_buffer'
1099 is saved in `saved_char'. */
1100 static bool char_is_saved = false;
1102 /* Odd char from previous call. */
1103 static char saved_char;
1105 /* Swap NREAD bytes in BUF, plus possibly an initial char from the
1106 previous call. If NREAD is odd, save the last char for the
1107 next call. Return the new start of the BUF buffer. */
1110 swab_buffer (char *buf, size_t *nread)
1112 char *bufstart = buf;
1116 /* Is a char left from last time? */
1119 *--bufstart = saved_char;
1121 char_is_saved = false;
1126 /* An odd number of chars are in the buffer. */
1127 saved_char = bufstart[--*nread];
1128 char_is_saved = true;
1131 /* Do the byte-swapping by moving every second character two
1132 positions toward the end, working from the end of the buffer
1133 toward the beginning. This way we only move half of the data. */
1135 cp = bufstart + *nread; /* Start one char past the last. */
1136 for (i = *nread / 2; i; i--, cp -= 2)
1142 /* Add OFFSET to the input offset, setting the overflow flag if
1146 advance_input_offset (uintmax_t offset)
1148 input_offset += offset;
1149 if (input_offset < offset)
1150 input_offset_overflow = true;
1153 /* This is a wrapper for lseek. It detects and warns about a kernel
1154 bug that makes lseek a no-op for tape devices, even though the kernel
1155 lseek return value suggests that the function succeeded.
1157 The parameters are the same as those of the lseek function, but
1158 with the addition of FILENAME, the name of the file associated with
1159 descriptor FDESC. The file name is used solely in the warning that's
1160 printed when the bug is detected. Return the same value that lseek
1161 would have returned, but when the lseek bug is detected, return -1
1162 to indicate that lseek failed.
1164 The offending behavior has been confirmed with an Exabyte SCSI tape
1165 drive accessed via /dev/nst0 on both Linux-2.2.17 and Linux-2.4.16. */
1169 # include <sys/mtio.h>
1171 # define MT_SAME_POSITION(P, Q) \
1172 ((P).mt_resid == (Q).mt_resid \
1173 && (P).mt_fileno == (Q).mt_fileno \
1174 && (P).mt_blkno == (Q).mt_blkno)
1177 skip_via_lseek (char const *filename, int fdesc, off_t offset, int whence)
1181 bool got_original_tape_position = (ioctl (fdesc, MTIOCGET, &s1) == 0);
1182 /* known bad device type */
1183 /* && s.mt_type == MT_ISSCSI2 */
1185 off_t new_position = lseek (fdesc, offset, whence);
1186 if (0 <= new_position
1187 && got_original_tape_position
1188 && ioctl (fdesc, MTIOCGET, &s2) == 0
1189 && MT_SAME_POSITION (s1, s2))
1191 error (0, 0, _("warning: working around lseek kernel bug for file (%s)\n\
1192 of mt_type=0x%0lx -- see <sys/mtio.h> for the list of types"),
1193 filename, s2.mt_type);
1198 return new_position;
1201 # define skip_via_lseek(Filename, Fd, Offset, Whence) lseek (Fd, Offset, Whence)
1204 /* Throw away RECORDS blocks of BLOCKSIZE bytes on file descriptor FDESC,
1205 which is open with read permission for FILE. Store up to BLOCKSIZE
1206 bytes of the data at a time in BUF, if necessary. RECORDS must be
1207 nonzero. If fdesc is STDIN_FILENO, advance the input offset.
1208 Return the number of records remaining, i.e., that were not skipped
1209 because EOF was reached. */
1212 skip (int fdesc, char const *file, uintmax_t records, size_t blocksize,
1215 uintmax_t offset = records * blocksize;
1217 /* Try lseek and if an error indicates it was an inappropriate operation --
1218 or if the file offset is not representable as an off_t --
1219 fall back on using read. */
1222 if (records <= OFF_T_MAX / blocksize
1223 && 0 <= skip_via_lseek (file, fdesc, offset, SEEK_CUR))
1225 if (fdesc == STDIN_FILENO)
1226 advance_input_offset (offset);
1231 int lseek_errno = errno;
1235 ssize_t nread = iread_fnc (fdesc, buf, blocksize);
1238 if (fdesc == STDIN_FILENO)
1240 error (0, errno, _("reading %s"), quote (file));
1241 if (conversions_mask & C_NOERROR)
1248 error (0, lseek_errno, _("%s: cannot seek"), quote (file));
1249 quit (EXIT_FAILURE);
1254 if (fdesc == STDIN_FILENO)
1255 advance_input_offset (nread);
1257 while (--records != 0);
1263 /* Advance the input by NBYTES if possible, after a read error.
1264 The input file offset may or may not have advanced after the failed
1265 read; adjust it to point just after the bad record regardless.
1266 Return true if successful, or if the input is already known to not
1270 advance_input_after_read_error (size_t nbytes)
1272 if (! input_seekable)
1274 if (input_seek_errno == ESPIPE)
1276 errno = input_seek_errno;
1281 advance_input_offset (nbytes);
1282 input_offset_overflow |= (OFF_T_MAX < input_offset);
1283 if (input_offset_overflow)
1285 error (0, 0, _("offset overflow while reading file %s"),
1286 quote (input_file));
1289 offset = lseek (STDIN_FILENO, 0, SEEK_CUR);
1293 if (offset == input_offset)
1295 diff = input_offset - offset;
1296 if (! (0 <= diff && diff <= nbytes))
1297 error (0, 0, _("warning: invalid file offset after failed read"));
1298 if (0 <= skip_via_lseek (input_file, STDIN_FILENO, diff, SEEK_CUR))
1301 error (0, 0, _("cannot work around kernel bug after all"));
1305 error (0, errno, _("%s: cannot seek"), quote (input_file));
1309 /* Copy NREAD bytes of BUF, with no conversions. */
1312 copy_simple (char const *buf, size_t nread)
1314 const char *start = buf; /* First uncopied char in BUF. */
1318 size_t nfree = MIN (nread, output_blocksize - oc);
1320 memcpy (obuf + oc, start, nfree);
1322 nread -= nfree; /* Update the number of bytes left to copy. */
1325 if (oc >= output_blocksize)
1331 /* Copy NREAD bytes of BUF, doing conv=block
1332 (pad newline-terminated records to `conversion_blocksize',
1333 replacing the newline with trailing spaces). */
1336 copy_with_block (char const *buf, size_t nread)
1340 for (i = nread; i; i--, buf++)
1342 if (*buf == newline_character)
1344 if (col < conversion_blocksize)
1347 for (j = col; j < conversion_blocksize; j++)
1348 output_char (space_character);
1354 if (col == conversion_blocksize)
1356 else if (col < conversion_blocksize)
1363 /* Copy NREAD bytes of BUF, doing conv=unblock
1364 (replace trailing spaces in `conversion_blocksize'-sized records
1368 copy_with_unblock (char const *buf, size_t nread)
1372 static size_t pending_spaces = 0;
1374 for (i = 0; i < nread; i++)
1378 if (col++ >= conversion_blocksize)
1380 col = pending_spaces = 0; /* Wipe out any pending spaces. */
1381 i--; /* Push the char back; get it later. */
1382 output_char (newline_character);
1384 else if (c == space_character)
1388 /* `c' is the character after a run of spaces that were not
1389 at the end of the conversion buffer. Output them. */
1390 while (pending_spaces)
1392 output_char (space_character);
1400 /* Set the file descriptor flags for FD that correspond to the nonzero bits
1401 in ADD_FLAGS. The file's name is NAME. */
1404 set_fd_flags (int fd, int add_flags, char const *name)
1406 /* Ignore file creation flags that are no-ops on file descriptors. */
1407 add_flags &= ~ (O_NOCTTY | O_NOFOLLOW);
1411 int old_flags = fcntl (fd, F_GETFL);
1412 int new_flags = old_flags | add_flags;
1416 else if (old_flags != new_flags)
1418 if (new_flags & (O_DIRECTORY | O_NOLINKS))
1420 /* NEW_FLAGS contains at least one file creation flag that
1421 requires some checking of the open file descriptor. */
1423 if (fstat (fd, &st) != 0)
1425 else if ((new_flags & O_DIRECTORY) && ! S_ISDIR (st.st_mode))
1430 else if ((new_flags & O_NOLINKS) && 1 < st.st_nlink)
1435 new_flags &= ~ (O_DIRECTORY | O_NOLINKS);
1438 if (ok && old_flags != new_flags
1439 && fcntl (fd, F_SETFL, new_flags) == -1)
1444 error (EXIT_FAILURE, errno, _("setting flags for %s"), quote (name));
1448 /* The main loop. */
1453 char *ibuf, *bufstart; /* Input buffer. */
1454 /* These are declared static so that even though we don't free the
1455 buffers, valgrind will recognize that there is no "real" leak. */
1456 static char *real_buf; /* real buffer address before alignment */
1457 static char *real_obuf;
1458 ssize_t nread; /* Bytes read in the current block. */
1460 /* If nonzero, then the previously read block was partial and
1461 PARTREAD was its size. */
1462 size_t partread = 0;
1464 int exit_status = EXIT_SUCCESS;
1465 size_t n_bytes_read;
1467 /* Leave at least one extra byte at the beginning and end of `ibuf'
1468 for conv=swab, but keep the buffer address even. But some peculiar
1469 device drivers work only with word-aligned buffers, so leave an
1472 /* Some devices require alignment on a sector or page boundary
1473 (e.g. character disk devices). Align the input buffer to a
1474 page boundary to cover all bases. Note that due to the swab
1475 algorithm, we must have at least one byte in the page before
1476 the input buffer; thus we allocate 2 pages of slop in the
1477 real buffer. 8k above the blocksize shouldn't bother anyone.
1479 The page alignment is necessary on any linux system that supports
1480 either the SGI raw I/O patch or Steven Tweedies raw I/O patch.
1481 It is necessary when accessing raw (i.e. character special) disk
1482 devices on Unixware or other SVR4-derived system. */
1484 real_buf = xmalloc (input_blocksize + INPUT_BLOCK_SLOP);
1486 ibuf += SWAB_ALIGN_OFFSET; /* allow space for swab */
1488 ibuf = ptr_align (ibuf, page_size);
1490 if (conversions_mask & C_TWOBUFS)
1492 /* Page-align the output buffer, too. */
1493 real_obuf = xmalloc (output_blocksize + OUTPUT_BLOCK_SLOP);
1494 obuf = ptr_align (real_obuf, page_size);
1502 if (skip_records != 0)
1504 skip (STDIN_FILENO, input_file, skip_records, input_blocksize, ibuf);
1505 /* POSIX doesn't say what to do when dd detects it has been
1506 asked to skip past EOF, so I assume it's non-fatal if the
1507 call to 'skip' returns nonzero. FIXME: maybe give a warning. */
1510 if (seek_records != 0)
1512 uintmax_t write_records = skip (STDOUT_FILENO, output_file,
1513 seek_records, output_blocksize, obuf);
1515 if (write_records != 0)
1517 memset (obuf, 0, output_blocksize);
1520 if (iwrite (STDOUT_FILENO, obuf, output_blocksize)
1521 != output_blocksize)
1523 error (0, errno, _("writing to %s"), quote (output_file));
1524 quit (EXIT_FAILURE);
1526 while (--write_records != 0);
1530 if (max_records == 0)
1535 if (r_partial + r_full >= max_records)
1538 /* Zero the buffer before reading, so that if we get a read error,
1539 whatever data we are able to read is followed by zeros.
1540 This minimizes data loss. */
1541 if ((conversions_mask & C_SYNC) && (conversions_mask & C_NOERROR))
1543 (conversions_mask & (C_BLOCK | C_UNBLOCK)) ? ' ' : '\0',
1546 nread = iread_fnc (STDIN_FILENO, ibuf, input_blocksize);
1553 error (0, errno, _("reading %s"), quote (input_file));
1554 if (conversions_mask & C_NOERROR)
1557 /* Seek past the bad block if possible. */
1558 if (!advance_input_after_read_error (input_blocksize - partread))
1560 exit_status = EXIT_FAILURE;
1562 /* Suppress duplicate diagnostics. */
1563 input_seekable = false;
1564 input_seek_errno = ESPIPE;
1566 if ((conversions_mask & C_SYNC) && !partread)
1567 /* Replace the missing input with null bytes and
1568 proceed normally. */
1575 /* Write any partial block. */
1576 exit_status = EXIT_FAILURE;
1581 n_bytes_read = nread;
1582 advance_input_offset (nread);
1584 if (n_bytes_read < input_blocksize)
1587 partread = n_bytes_read;
1588 if (conversions_mask & C_SYNC)
1590 if (!(conversions_mask & C_NOERROR))
1591 /* If C_NOERROR, we zeroed the block before reading. */
1592 memset (ibuf + n_bytes_read,
1593 (conversions_mask & (C_BLOCK | C_UNBLOCK)) ? ' ' : '\0',
1594 input_blocksize - n_bytes_read);
1595 n_bytes_read = input_blocksize;
1604 if (ibuf == obuf) /* If not C_TWOBUFS. */
1606 size_t nwritten = iwrite (STDOUT_FILENO, obuf, n_bytes_read);
1607 w_bytes += nwritten;
1608 if (nwritten != n_bytes_read)
1610 error (0, errno, _("writing %s"), quote (output_file));
1611 return EXIT_FAILURE;
1613 else if (n_bytes_read == input_blocksize)
1620 /* Do any translations on the whole buffer at once. */
1622 if (translation_needed)
1623 translate_buffer (ibuf, n_bytes_read);
1625 if (conversions_mask & C_SWAB)
1626 bufstart = swab_buffer (ibuf, &n_bytes_read);
1630 if (conversions_mask & C_BLOCK)
1631 copy_with_block (bufstart, n_bytes_read);
1632 else if (conversions_mask & C_UNBLOCK)
1633 copy_with_unblock (bufstart, n_bytes_read);
1635 copy_simple (bufstart, n_bytes_read);
1638 /* If we have a char left as a result of conv=swab, output it. */
1641 if (conversions_mask & C_BLOCK)
1642 copy_with_block (&saved_char, 1);
1643 else if (conversions_mask & C_UNBLOCK)
1644 copy_with_unblock (&saved_char, 1);
1646 output_char (saved_char);
1649 if ((conversions_mask & C_BLOCK) && col > 0)
1651 /* If the final input line didn't end with a '\n', pad
1652 the output block to `conversion_blocksize' chars. */
1654 for (i = col; i < conversion_blocksize; i++)
1655 output_char (space_character);
1658 if ((conversions_mask & C_UNBLOCK) && col == conversion_blocksize)
1659 /* Add a final '\n' if there are exactly `conversion_blocksize'
1660 characters in the final record. */
1661 output_char (newline_character);
1663 /* Write out the last block. */
1666 size_t nwritten = iwrite (STDOUT_FILENO, obuf, oc);
1667 w_bytes += nwritten;
1672 error (0, errno, _("writing %s"), quote (output_file));
1673 return EXIT_FAILURE;
1677 if ((conversions_mask & C_FDATASYNC) && fdatasync (STDOUT_FILENO) != 0)
1679 if (errno != ENOSYS && errno != EINVAL)
1681 error (0, errno, _("fdatasync failed for %s"), quote (output_file));
1682 exit_status = EXIT_FAILURE;
1684 conversions_mask |= C_FSYNC;
1687 if (conversions_mask & C_FSYNC)
1688 while (fsync (STDOUT_FILENO) != 0)
1691 error (0, errno, _("fsync failed for %s"), quote (output_file));
1692 return EXIT_FAILURE;
1699 main (int argc, char **argv)
1705 initialize_main (&argc, &argv);
1706 set_program_name (argv[0]);
1707 setlocale (LC_ALL, "");
1708 bindtextdomain (PACKAGE, LOCALEDIR);
1709 textdomain (PACKAGE);
1711 /* Arrange to close stdout if parse_long_options exits. */
1712 atexit (maybe_close_stdout);
1714 page_size = getpagesize ();
1716 parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE, VERSION,
1717 usage, AUTHORS, (char const *) NULL);
1718 close_stdout_required = false;
1720 if (getopt_long (argc, argv, "", NULL, NULL) != -1)
1721 usage (EXIT_FAILURE);
1723 /* Initialize translation table to identity translation. */
1724 for (i = 0; i < 256; i++)
1727 /* Decode arguments. */
1728 scanargs (argc, argv);
1730 apply_translations ();
1732 if (input_file == NULL)
1734 input_file = _("standard input");
1735 set_fd_flags (STDIN_FILENO, input_flags, input_file);
1739 if (fd_reopen (STDIN_FILENO, input_file, O_RDONLY | input_flags, 0) < 0)
1740 error (EXIT_FAILURE, errno, _("opening %s"), quote (input_file));
1743 offset = lseek (STDIN_FILENO, 0, SEEK_CUR);
1744 input_seekable = (0 <= offset);
1745 input_offset = offset;
1746 input_seek_errno = errno;
1748 if (output_file == NULL)
1750 output_file = _("standard output");
1751 set_fd_flags (STDOUT_FILENO, output_flags, output_file);
1755 mode_t perms = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
1758 | (conversions_mask & C_NOCREAT ? 0 : O_CREAT)
1759 | (conversions_mask & C_EXCL ? O_EXCL : 0)
1760 | (seek_records || (conversions_mask & C_NOTRUNC) ? 0 : O_TRUNC));
1762 /* Open the output file with *read* access only if we might
1763 need to read to satisfy a `seek=' request. If we can't read
1764 the file, go ahead with write-only access; it might work. */
1766 || fd_reopen (STDOUT_FILENO, output_file, O_RDWR | opts, perms) < 0)
1767 && (fd_reopen (STDOUT_FILENO, output_file, O_WRONLY | opts, perms)
1769 error (EXIT_FAILURE, errno, _("opening %s"), quote (output_file));
1772 if (seek_records != 0 && !(conversions_mask & C_NOTRUNC))
1774 uintmax_t size = seek_records * output_blocksize;
1775 unsigned long int obs = output_blocksize;
1777 if (OFF_T_MAX / output_blocksize < seek_records)
1778 error (EXIT_FAILURE, 0,
1779 _("offset too large: "
1780 "cannot truncate to a length of seek=%"PRIuMAX""
1781 " (%lu-byte) blocks"),
1784 if (ftruncate (STDOUT_FILENO, size) != 0)
1786 /* Complain only when ftruncate fails on a regular file, a
1787 directory, or a shared memory object, as POSIX 1003.1-2004
1788 specifies ftruncate's behavior only for these file types.
1789 For example, do not complain when Linux 2.4 ftruncate
1790 fails on /dev/fd0. */
1791 int ftruncate_errno = errno;
1792 struct stat stdout_stat;
1793 if (fstat (STDOUT_FILENO, &stdout_stat) != 0)
1794 error (EXIT_FAILURE, errno, _("cannot fstat %s"),
1795 quote (output_file));
1796 if (S_ISREG (stdout_stat.st_mode)
1797 || S_ISDIR (stdout_stat.st_mode)
1798 || S_TYPEISSHM (&stdout_stat))
1799 error (EXIT_FAILURE, ftruncate_errno,
1800 _("truncating at %"PRIuMAX" bytes in output file %s"),
1801 size, quote (output_file));
1807 install_signal_handlers ();
1809 start_time = gethrxtime ();
1811 exit_status = dd_copy ();