]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - bin/dd/dd.c
MFC r328427:
[FreeBSD/FreeBSD.git] / bin / dd / dd.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1991, 1993, 1994
5  *      The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Keith Muller of the University of California, San Diego and Lance
9  * Visser of Convex Computer Corporation.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35
36 #if 0
37 #ifndef lint
38 static char const copyright[] =
39 "@(#) Copyright (c) 1991, 1993, 1994\n\
40         The Regents of the University of California.  All rights reserved.\n";
41 #endif /* not lint */
42
43 #ifndef lint
44 static char sccsid[] = "@(#)dd.c        8.5 (Berkeley) 4/2/94";
45 #endif /* not lint */
46 #endif
47 #include <sys/cdefs.h>
48 __FBSDID("$FreeBSD$");
49
50 #include <sys/param.h>
51 #include <sys/stat.h>
52 #include <sys/conf.h>
53 #include <sys/disklabel.h>
54 #include <sys/filio.h>
55
56 #include <assert.h>
57 #include <ctype.h>
58 #include <err.h>
59 #include <errno.h>
60 #include <fcntl.h>
61 #include <inttypes.h>
62 #include <locale.h>
63 #include <stdio.h>
64 #include <stdlib.h>
65 #include <string.h>
66 #include <time.h>
67 #include <unistd.h>
68
69 #include "dd.h"
70 #include "extern.h"
71
72 static void dd_close(void);
73 static void dd_in(void);
74 static void getfdtype(IO *);
75 static void setup(void);
76
77 IO      in, out;                /* input/output state */
78 STAT    st;                     /* statistics */
79 void    (*cfunc)(void);         /* conversion function */
80 uintmax_t cpy_cnt;              /* # of blocks to copy */
81 static off_t    pending = 0;    /* pending seek if sparse */
82 u_int   ddflags = 0;            /* conversion options */
83 size_t  cbsz;                   /* conversion block size */
84 uintmax_t files_cnt = 1;        /* # of files to copy */
85 const   u_char *ctab;           /* conversion table */
86 char    fill_char;              /* Character to fill with if defined */
87 size_t  speed = 0;              /* maximum speed, in bytes per second */
88 volatile sig_atomic_t need_summary;
89
90 int
91 main(int argc __unused, char *argv[])
92 {
93         (void)setlocale(LC_CTYPE, "");
94         jcl(argv);
95         setup();
96
97         (void)signal(SIGINFO, siginfo_handler);
98         (void)signal(SIGINT, terminate);
99
100         atexit(summary);
101
102         while (files_cnt--)
103                 dd_in();
104
105         dd_close();
106         /*
107          * Some devices such as cfi(4) may perform significant amounts
108          * of work when a write descriptor is closed.  Close the out
109          * descriptor explicitly so that the summary handler (called
110          * from an atexit() hook) includes this work.
111          */
112         close(out.fd);
113         exit(0);
114 }
115
116 static int
117 parity(u_char c)
118 {
119         int i;
120
121         i = c ^ (c >> 1) ^ (c >> 2) ^ (c >> 3) ^ 
122             (c >> 4) ^ (c >> 5) ^ (c >> 6) ^ (c >> 7);
123         return (i & 1);
124 }
125
126 static void
127 setup(void)
128 {
129         u_int cnt;
130
131         if (in.name == NULL) {
132                 in.name = "stdin";
133                 in.fd = STDIN_FILENO;
134         } else {
135                 in.fd = open(in.name, O_RDONLY, 0);
136                 if (in.fd == -1)
137                         err(1, "%s", in.name);
138         }
139
140         getfdtype(&in);
141
142         if (files_cnt > 1 && !(in.flags & ISTAPE))
143                 errx(1, "files is not supported for non-tape devices");
144
145         if (out.name == NULL) {
146                 /* No way to check for read access here. */
147                 out.fd = STDOUT_FILENO;
148                 out.name = "stdout";
149         } else {
150 #define OFLAGS \
151     (O_CREAT | (ddflags & (C_SEEK | C_NOTRUNC) ? 0 : O_TRUNC))
152                 out.fd = open(out.name, O_RDWR | OFLAGS, DEFFILEMODE);
153                 /*
154                  * May not have read access, so try again with write only.
155                  * Without read we may have a problem if output also does
156                  * not support seeks.
157                  */
158                 if (out.fd == -1) {
159                         out.fd = open(out.name, O_WRONLY | OFLAGS, DEFFILEMODE);
160                         out.flags |= NOREAD;
161                 }
162                 if (out.fd == -1)
163                         err(1, "%s", out.name);
164         }
165
166         getfdtype(&out);
167
168         /*
169          * Allocate space for the input and output buffers.  If not doing
170          * record oriented I/O, only need a single buffer.
171          */
172         if (!(ddflags & (C_BLOCK | C_UNBLOCK))) {
173                 if ((in.db = malloc(out.dbsz + in.dbsz - 1)) == NULL)
174                         err(1, "input buffer");
175                 out.db = in.db;
176         } else if ((in.db = malloc(MAX(in.dbsz, cbsz) + cbsz)) == NULL ||
177             (out.db = malloc(out.dbsz + cbsz)) == NULL)
178                 err(1, "output buffer");
179
180         /* dbp is the first free position in each buffer. */
181         in.dbp = in.db;
182         out.dbp = out.db;
183
184         /* Position the input/output streams. */
185         if (in.offset)
186                 pos_in();
187         if (out.offset)
188                 pos_out();
189
190         /*
191          * Truncate the output file.  If it fails on a type of output file
192          * that it should _not_ fail on, error out.
193          */
194         if ((ddflags & (C_OF | C_SEEK | C_NOTRUNC)) == (C_OF | C_SEEK) &&
195             out.flags & ISTRUNC)
196                 if (ftruncate(out.fd, out.offset * out.dbsz) == -1)
197                         err(1, "truncating %s", out.name);
198
199         if (ddflags & (C_LCASE  | C_UCASE | C_ASCII | C_EBCDIC | C_PARITY)) {
200                 if (ctab != NULL) {
201                         for (cnt = 0; cnt <= 0377; ++cnt)
202                                 casetab[cnt] = ctab[cnt];
203                 } else {
204                         for (cnt = 0; cnt <= 0377; ++cnt)
205                                 casetab[cnt] = cnt;
206                 }
207                 if ((ddflags & C_PARITY) && !(ddflags & C_ASCII)) {
208                         /*
209                          * If the input is not EBCDIC, and we do parity
210                          * processing, strip input parity.
211                          */
212                         for (cnt = 200; cnt <= 0377; ++cnt)
213                                 casetab[cnt] = casetab[cnt & 0x7f];
214                 }
215                 if (ddflags & C_LCASE) {
216                         for (cnt = 0; cnt <= 0377; ++cnt)
217                                 casetab[cnt] = tolower(casetab[cnt]);
218                 } else if (ddflags & C_UCASE) {
219                         for (cnt = 0; cnt <= 0377; ++cnt)
220                                 casetab[cnt] = toupper(casetab[cnt]);
221                 }
222                 if ((ddflags & C_PARITY)) {
223                         /*
224                          * This should strictly speaking be a no-op, but I
225                          * wonder what funny LANG settings could get us.
226                          */
227                         for (cnt = 0; cnt <= 0377; ++cnt)
228                                 casetab[cnt] = casetab[cnt] & 0x7f;
229                 }
230                 if ((ddflags & C_PARSET)) {
231                         for (cnt = 0; cnt <= 0377; ++cnt)
232                                 casetab[cnt] = casetab[cnt] | 0x80;
233                 }
234                 if ((ddflags & C_PAREVEN)) {
235                         for (cnt = 0; cnt <= 0377; ++cnt)
236                                 if (parity(casetab[cnt]))
237                                         casetab[cnt] = casetab[cnt] | 0x80;
238                 }
239                 if ((ddflags & C_PARODD)) {
240                         for (cnt = 0; cnt <= 0377; ++cnt)
241                                 if (!parity(casetab[cnt]))
242                                         casetab[cnt] = casetab[cnt] | 0x80;
243                 }
244
245                 ctab = casetab;
246         }
247
248         if (clock_gettime(CLOCK_MONOTONIC, &st.start))
249                 err(1, "clock_gettime");
250 }
251
252 static void
253 getfdtype(IO *io)
254 {
255         struct stat sb;
256         int type;
257
258         if (fstat(io->fd, &sb) == -1)
259                 err(1, "%s", io->name);
260         if (S_ISREG(sb.st_mode))
261                 io->flags |= ISTRUNC;
262         if (S_ISCHR(sb.st_mode) || S_ISBLK(sb.st_mode)) { 
263                 if (ioctl(io->fd, FIODTYPE, &type) == -1) {
264                         err(1, "%s", io->name);
265                 } else {
266                         if (type & D_TAPE)
267                                 io->flags |= ISTAPE;
268                         else if (type & (D_DISK | D_MEM))
269                                 io->flags |= ISSEEK;
270                         if (S_ISCHR(sb.st_mode) && (type & D_TAPE) == 0)
271                                 io->flags |= ISCHR;
272                 }
273                 return;
274         }
275         errno = 0;
276         if (lseek(io->fd, (off_t)0, SEEK_CUR) == -1 && errno == ESPIPE)
277                 io->flags |= ISPIPE;
278         else
279                 io->flags |= ISSEEK;
280 }
281
282 /*
283  * Limit the speed by adding a delay before every block read.
284  * The delay (t_usleep) is equal to the time computed from block
285  * size and the specified speed limit (t_target) minus the time
286  * spent on actual read and write operations (t_io).
287  */
288 static void
289 speed_limit(void)
290 {
291         static double t_prev, t_usleep;
292         double t_now, t_io, t_target;
293
294         t_now = secs_elapsed();
295         t_io = t_now - t_prev - t_usleep;
296         t_target = (double)in.dbsz / (double)speed;
297         t_usleep = t_target - t_io;
298         if (t_usleep > 0)
299                 usleep(t_usleep * 1000000);
300         else
301                 t_usleep = 0;
302         t_prev = t_now;
303 }
304
305 static void
306 swapbytes(void *v, size_t len)
307 {
308         unsigned char *p = v;
309         unsigned char t;
310
311         while (len > 1) {
312                 t = p[0];
313                 p[0] = p[1];
314                 p[1] = t;
315                 p += 2;
316                 len -= 2;
317         }
318 }
319
320 static void
321 dd_in(void)
322 {
323         ssize_t n;
324
325         for (;;) {
326                 switch (cpy_cnt) {
327                 case -1:                        /* count=0 was specified */
328                         return;
329                 case 0:
330                         break;
331                 default:
332                         if (st.in_full + st.in_part >= (uintmax_t)cpy_cnt)
333                                 return;
334                         break;
335                 }
336
337                 if (speed > 0)
338                         speed_limit();
339
340                 /*
341                  * Zero the buffer first if sync; if doing block operations,
342                  * use spaces.
343                  */
344                 if (ddflags & C_SYNC) {
345                         if (ddflags & C_FILL)
346                                 memset(in.dbp, fill_char, in.dbsz);
347                         else if (ddflags & (C_BLOCK | C_UNBLOCK))
348                                 memset(in.dbp, ' ', in.dbsz);
349                         else
350                                 memset(in.dbp, 0, in.dbsz);
351                 }
352
353                 n = read(in.fd, in.dbp, in.dbsz);
354                 if (n == 0) {
355                         in.dbrcnt = 0;
356                         return;
357                 }
358
359                 /* Read error. */
360                 if (n == -1) {
361                         /*
362                          * If noerror not specified, die.  POSIX requires that
363                          * the warning message be followed by an I/O display.
364                          */
365                         if (!(ddflags & C_NOERROR))
366                                 err(1, "%s", in.name);
367                         warn("%s", in.name);
368                         summary();
369
370                         /*
371                          * If it's a seekable file descriptor, seek past the
372                          * error.  If your OS doesn't do the right thing for
373                          * raw disks this section should be modified to re-read
374                          * in sector size chunks.
375                          */
376                         if (in.flags & ISSEEK &&
377                             lseek(in.fd, (off_t)in.dbsz, SEEK_CUR))
378                                 warn("%s", in.name);
379
380                         /* If sync not specified, omit block and continue. */
381                         if (!(ddflags & C_SYNC))
382                                 continue;
383
384                         /* Read errors count as full blocks. */
385                         in.dbcnt += in.dbrcnt = in.dbsz;
386                         ++st.in_full;
387
388                 /* Handle full input blocks. */
389                 } else if ((size_t)n == in.dbsz) {
390                         in.dbcnt += in.dbrcnt = n;
391                         ++st.in_full;
392
393                 /* Handle partial input blocks. */
394                 } else {
395                         /* If sync, use the entire block. */
396                         if (ddflags & C_SYNC)
397                                 in.dbcnt += in.dbrcnt = in.dbsz;
398                         else
399                                 in.dbcnt += in.dbrcnt = n;
400                         ++st.in_part;
401                 }
402
403                 /*
404                  * POSIX states that if bs is set and no other conversions
405                  * than noerror, notrunc or sync are specified, the block
406                  * is output without buffering as it is read.
407                  */
408                 if ((ddflags & ~(C_NOERROR | C_NOTRUNC | C_SYNC)) == C_BS) {
409                         out.dbcnt = in.dbcnt;
410                         dd_out(1);
411                         in.dbcnt = 0;
412                         continue;
413                 }
414
415                 if (ddflags & C_SWAB) {
416                         if ((n = in.dbrcnt) & 1) {
417                                 ++st.swab;
418                                 --n;
419                         }
420                         swapbytes(in.dbp, (size_t)n);
421                 }
422
423                 in.dbp += in.dbrcnt;
424                 (*cfunc)();
425                 if (need_summary) {
426                         summary();
427                 }
428         }
429 }
430
431 /*
432  * Clean up any remaining I/O and flush output.  If necessary, the output file
433  * is truncated.
434  */
435 static void
436 dd_close(void)
437 {
438         if (cfunc == def)
439                 def_close();
440         else if (cfunc == block)
441                 block_close();
442         else if (cfunc == unblock)
443                 unblock_close();
444         if (ddflags & C_OSYNC && out.dbcnt && out.dbcnt < out.dbsz) {
445                 if (ddflags & C_FILL)
446                         memset(out.dbp, fill_char, out.dbsz - out.dbcnt);
447                 else if (ddflags & (C_BLOCK | C_UNBLOCK))
448                         memset(out.dbp, ' ', out.dbsz - out.dbcnt);
449                 else
450                         memset(out.dbp, 0, out.dbsz - out.dbcnt);
451                 out.dbcnt = out.dbsz;
452         }
453         if (out.dbcnt || pending)
454                 dd_out(1);
455
456         /*
457          * If the file ends with a hole, ftruncate it to extend its size
458          * up to the end of the hole (without having to write any data).
459          */
460         if (out.seek_offset > 0 && (out.flags & ISTRUNC)) {
461                 if (ftruncate(out.fd, out.seek_offset) == -1)
462                         err(1, "truncating %s", out.name);
463         }
464 }
465
466 void
467 dd_out(int force)
468 {
469         u_char *outp;
470         size_t cnt, i, n;
471         ssize_t nw;
472         static int warned;
473         int sparse;
474
475         /*
476          * Write one or more blocks out.  The common case is writing a full
477          * output block in a single write; increment the full block stats.
478          * Otherwise, we're into partial block writes.  If a partial write,
479          * and it's a character device, just warn.  If a tape device, quit.
480          *
481          * The partial writes represent two cases.  1: Where the input block
482          * was less than expected so the output block was less than expected.
483          * 2: Where the input block was the right size but we were forced to
484          * write the block in multiple chunks.  The original versions of dd(1)
485          * never wrote a block in more than a single write, so the latter case
486          * never happened.
487          *
488          * One special case is if we're forced to do the write -- in that case
489          * we play games with the buffer size, and it's usually a partial write.
490          */
491         outp = out.db;
492
493         /*
494          * If force, first try to write all pending data, else try to write
495          * just one block. Subsequently always write data one full block at
496          * a time at most.
497          */
498         for (n = force ? out.dbcnt : out.dbsz;; n = out.dbsz) {
499                 cnt = n;
500                 do {
501                         sparse = 0;
502                         if (ddflags & C_SPARSE) {
503                                 sparse = 1;     /* Is buffer sparse? */
504                                 for (i = 0; i < cnt; i++)
505                                         if (outp[i] != 0) {
506                                                 sparse = 0;
507                                                 break;
508                                         }
509                         }
510                         if (sparse && !force) {
511                                 pending += cnt;
512                                 nw = cnt;
513                         } else {
514                                 if (pending != 0) {
515                                         /*
516                                          * Seek past hole.  Note that we need to record the
517                                          * reached offset, because we might have no more data
518                                          * to write, in which case we'll need to call
519                                          * ftruncate to extend the file size.
520                                          */
521                                         out.seek_offset = lseek(out.fd, pending, SEEK_CUR);
522                                         if (out.seek_offset == -1)
523                                                 err(2, "%s: seek error creating sparse file",
524                                                     out.name);
525                                         pending = 0;
526                                 }
527                                 if (cnt) {
528                                         nw = write(out.fd, outp, cnt);
529                                         out.seek_offset = 0;
530                                 } else {
531                                         return;
532                                 }
533                         }
534
535                         if (nw <= 0) {
536                                 if (nw == 0)
537                                         errx(1, "%s: end of device", out.name);
538                                 if (errno != EINTR)
539                                         err(1, "%s", out.name);
540                                 nw = 0;
541                         }
542
543                         outp += nw;
544                         st.bytes += nw;
545
546                         if ((size_t)nw == n && n == out.dbsz)
547                                 ++st.out_full;
548                         else
549                                 ++st.out_part;
550
551                         if ((size_t) nw != cnt) {
552                                 if (out.flags & ISTAPE)
553                                         errx(1, "%s: short write on tape device",
554                                         out.name);
555                                 if (out.flags & ISCHR && !warned) {
556                                         warned = 1;
557                                         warnx("%s: short write on character device",
558                                         out.name);
559                                 }
560                         }
561
562                         cnt -= nw;
563                 } while (cnt != 0);
564
565                 if ((out.dbcnt -= n) < out.dbsz)
566                         break;
567         }
568
569         /* Reassemble the output block. */
570         if (out.dbcnt)
571                 (void)memmove(out.db, out.dbp - out.dbcnt, out.dbcnt);
572         out.dbp = out.db + out.dbcnt;
573 }