dd.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Mini dd implementation for busybox
  4. *
  5. *
  6. * Copyright (C) 2000,2001 Matt Kraai
  7. *
  8. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  9. */
  10. //config:config DD
  11. //config: bool "dd"
  12. //config: default y
  13. //config: help
  14. //config: dd copies a file (from standard input to standard output,
  15. //config: by default) using specific input and output blocksizes,
  16. //config: while optionally performing conversions on it.
  17. //config:
  18. //config:config FEATURE_DD_SIGNAL_HANDLING
  19. //config: bool "Enable signal handling for status reporting"
  20. //config: default y
  21. //config: depends on DD
  22. //config: help
  23. //config: Sending a SIGUSR1 signal to a running `dd' process makes it
  24. //config: print to standard error the number of records read and written
  25. //config: so far, then to resume copying.
  26. //config:
  27. //config: $ dd if=/dev/zero of=/dev/null &
  28. //config: $ pid=$!; kill -USR1 $pid; sleep 1; kill $pid
  29. //config: 10899206+0 records in
  30. //config: 10899206+0 records out
  31. //config:
  32. //config:config FEATURE_DD_THIRD_STATUS_LINE
  33. //config: bool "Enable the third status line upon signal"
  34. //config: default y
  35. //config: depends on DD && FEATURE_DD_SIGNAL_HANDLING
  36. //config: help
  37. //config: Displays a coreutils-like third status line with transferred bytes,
  38. //config: elapsed time and speed.
  39. //config:
  40. //config:config FEATURE_DD_IBS_OBS
  41. //config: bool "Enable ibs, obs and conv options"
  42. //config: default y
  43. //config: depends on DD
  44. //config: help
  45. //config: Enables support for writing a certain number of bytes in and out,
  46. //config: at a time, and performing conversions on the data stream.
  47. //config:
  48. //config:config FEATURE_DD_STATUS
  49. //config: bool "Enable status display options"
  50. //config: default y
  51. //config: depends on DD
  52. //config: help
  53. //config: Enables support for status=noxfer/none option.
  54. //usage:#define dd_trivial_usage
  55. //usage: "[if=FILE] [of=FILE] " IF_FEATURE_DD_IBS_OBS("[ibs=N] [obs=N] ") "[bs=N] [count=N] [skip=N]\n"
  56. //usage: " [seek=N]" IF_FEATURE_DD_IBS_OBS(" [conv=notrunc|noerror|sync|fsync] [iflag=skip_bytes]")
  57. //usage:#define dd_full_usage "\n\n"
  58. //usage: "Copy a file with converting and formatting\n"
  59. //usage: "\n if=FILE Read from FILE instead of stdin"
  60. //usage: "\n of=FILE Write to FILE instead of stdout"
  61. //usage: "\n bs=N Read and write N bytes at a time"
  62. //usage: IF_FEATURE_DD_IBS_OBS(
  63. //usage: "\n ibs=N Read N bytes at a time"
  64. //usage: )
  65. //usage: IF_FEATURE_DD_IBS_OBS(
  66. //usage: "\n obs=N Write N bytes at a time"
  67. //usage: )
  68. //usage: "\n count=N Copy only N input blocks"
  69. //usage: "\n skip=N Skip N input blocks"
  70. //usage: "\n seek=N Skip N output blocks"
  71. //usage: IF_FEATURE_DD_IBS_OBS(
  72. //usage: "\n conv=notrunc Don't truncate output file"
  73. //usage: "\n conv=noerror Continue after read errors"
  74. //usage: "\n conv=sync Pad blocks with zeros"
  75. //usage: "\n conv=fsync Physically write data out before finishing"
  76. //usage: "\n conv=swab Swap every pair of bytes"
  77. //usage: "\n iflag=skip_bytes skip=N is in bytes"
  78. //usage: )
  79. //usage: IF_FEATURE_DD_STATUS(
  80. //usage: "\n status=noxfer Suppress rate output"
  81. //usage: "\n status=none Suppress all output"
  82. //usage: )
  83. //usage: "\n"
  84. //usage: "\nN may be suffixed by c (1), w (2), b (512), kB (1000), k (1024), MB, M, GB, G"
  85. //usage:
  86. //usage:#define dd_example_usage
  87. //usage: "$ dd if=/dev/zero of=/dev/ram1 bs=1M count=4\n"
  88. //usage: "4+0 records in\n"
  89. //usage: "4+0 records out\n"
  90. #include "libbb.h"
  91. #include "common_bufsiz.h"
  92. /* This is a NOEXEC applet. Be very careful! */
  93. enum {
  94. ifd = STDIN_FILENO,
  95. ofd = STDOUT_FILENO,
  96. };
  97. struct globals {
  98. off_t out_full, out_part, in_full, in_part;
  99. #if ENABLE_FEATURE_DD_THIRD_STATUS_LINE
  100. unsigned long long total_bytes;
  101. unsigned long long begin_time_us;
  102. #endif
  103. int flags;
  104. } FIX_ALIASING;
  105. #define G (*(struct globals*)bb_common_bufsiz1)
  106. #define INIT_G() do { \
  107. setup_common_bufsiz(); \
  108. /* we have to zero it out because of NOEXEC */ \
  109. memset(&G, 0, sizeof(G)); \
  110. } while (0)
  111. enum {
  112. /* Must be in the same order as OP_conv_XXX! */
  113. /* (see "flags |= (1 << what)" below) */
  114. FLAG_NOTRUNC = (1 << 0) * ENABLE_FEATURE_DD_IBS_OBS,
  115. FLAG_SYNC = (1 << 1) * ENABLE_FEATURE_DD_IBS_OBS,
  116. FLAG_NOERROR = (1 << 2) * ENABLE_FEATURE_DD_IBS_OBS,
  117. FLAG_FSYNC = (1 << 3) * ENABLE_FEATURE_DD_IBS_OBS,
  118. FLAG_SWAB = (1 << 4) * ENABLE_FEATURE_DD_IBS_OBS,
  119. /* end of conv flags */
  120. /* start of input flags */
  121. FLAG_IFLAG_SHIFT = 5,
  122. FLAG_SKIP_BYTES = (1 << 5) * ENABLE_FEATURE_DD_IBS_OBS,
  123. /* end of input flags */
  124. FLAG_TWOBUFS = (1 << 6) * ENABLE_FEATURE_DD_IBS_OBS,
  125. FLAG_COUNT = 1 << 7,
  126. FLAG_STATUS = 1 << 8,
  127. FLAG_STATUS_NONE = 1 << 9,
  128. FLAG_STATUS_NOXFER = 1 << 10,
  129. };
  130. static void dd_output_status(int UNUSED_PARAM cur_signal)
  131. {
  132. #if ENABLE_FEATURE_DD_THIRD_STATUS_LINE
  133. double seconds;
  134. unsigned long long bytes_sec;
  135. unsigned long long now_us = monotonic_us(); /* before fprintf */
  136. #endif
  137. /* Deliberately using %u, not %d */
  138. fprintf(stderr, "%"OFF_FMT"u+%"OFF_FMT"u records in\n"
  139. "%"OFF_FMT"u+%"OFF_FMT"u records out\n",
  140. G.in_full, G.in_part,
  141. G.out_full, G.out_part);
  142. #if ENABLE_FEATURE_DD_THIRD_STATUS_LINE
  143. # if ENABLE_FEATURE_DD_STATUS
  144. if (G.flags & FLAG_STATUS_NOXFER) /* status=noxfer active? */
  145. return;
  146. //TODO: should status=none make dd stop reacting to USR1 entirely?
  147. //So far we react to it (we print the stats),
  148. //status=none only suppresses final, non-USR1 generated status message.
  149. # endif
  150. fprintf(stderr, "%llu bytes (%sB) copied, ",
  151. G.total_bytes,
  152. /* show fractional digit, use suffixes */
  153. make_human_readable_str(G.total_bytes, 1, 0)
  154. );
  155. /* Corner cases:
  156. * ./busybox dd </dev/null >/dev/null
  157. * ./busybox dd bs=1M count=2000 </dev/zero >/dev/null
  158. * (echo DONE) | ./busybox dd >/dev/null
  159. * (sleep 1; echo DONE) | ./busybox dd >/dev/null
  160. */
  161. seconds = (now_us - G.begin_time_us) / 1000000.0;
  162. bytes_sec = G.total_bytes / seconds;
  163. fprintf(stderr, "%f seconds, %sB/s\n",
  164. seconds,
  165. /* show fractional digit, use suffixes */
  166. make_human_readable_str(bytes_sec, 1, 0)
  167. );
  168. #endif
  169. }
  170. static ssize_t full_write_or_warn(const void *buf, size_t len,
  171. const char *const filename)
  172. {
  173. ssize_t n = full_write(ofd, buf, len);
  174. if (n < 0)
  175. bb_perror_msg("writing '%s'", filename);
  176. return n;
  177. }
  178. static bool write_and_stats(const void *buf, size_t len, size_t obs,
  179. const char *filename)
  180. {
  181. ssize_t n = full_write_or_warn(buf, len, filename);
  182. if (n < 0)
  183. return 1;
  184. if ((size_t)n == obs)
  185. G.out_full++;
  186. else if (n) /* > 0 */
  187. G.out_part++;
  188. #if ENABLE_FEATURE_DD_THIRD_STATUS_LINE
  189. G.total_bytes += n;
  190. #endif
  191. return 0;
  192. }
  193. #if ENABLE_LFS
  194. # define XATOU_SFX xatoull_sfx
  195. #else
  196. # define XATOU_SFX xatoul_sfx
  197. #endif
  198. #if ENABLE_FEATURE_DD_IBS_OBS
  199. static int parse_comma_flags(char *val, const char *words, const char *error_in)
  200. {
  201. int flags = 0;
  202. while (1) {
  203. int n;
  204. char *arg;
  205. /* find ',', replace them with NUL so we can use val for
  206. * index_in_strings() without copying.
  207. * We rely on val being non-null, else strchr would fault.
  208. */
  209. arg = strchr(val, ',');
  210. if (arg)
  211. *arg = '\0';
  212. n = index_in_strings(words, val);
  213. if (n < 0)
  214. bb_error_msg_and_die(bb_msg_invalid_arg_to, val, error_in);
  215. flags |= (1 << n);
  216. if (!arg) /* no ',' left, so this was the last specifier */
  217. break;
  218. *arg = ','; /* to preserve ps listing */
  219. val = arg + 1; /* skip this keyword and ',' */
  220. }
  221. return flags;
  222. }
  223. #endif
  224. int dd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  225. int dd_main(int argc UNUSED_PARAM, char **argv)
  226. {
  227. static const char keywords[] ALIGN1 =
  228. "bs\0""count\0""seek\0""skip\0""if\0""of\0"IF_FEATURE_DD_STATUS("status\0")
  229. #if ENABLE_FEATURE_DD_IBS_OBS
  230. "ibs\0""obs\0""conv\0""iflag\0"
  231. #endif
  232. ;
  233. #if ENABLE_FEATURE_DD_IBS_OBS
  234. static const char conv_words[] ALIGN1 =
  235. "notrunc\0""sync\0""noerror\0""fsync\0""swab\0";
  236. static const char iflag_words[] ALIGN1 =
  237. "skip_bytes\0";
  238. #endif
  239. #if ENABLE_FEATURE_DD_STATUS
  240. static const char status_words[] ALIGN1 =
  241. "none\0""noxfer\0";
  242. #endif
  243. enum {
  244. OP_bs = 0,
  245. OP_count,
  246. OP_seek,
  247. OP_skip,
  248. OP_if,
  249. OP_of,
  250. IF_FEATURE_DD_STATUS(OP_status,)
  251. #if ENABLE_FEATURE_DD_IBS_OBS
  252. OP_ibs,
  253. OP_obs,
  254. OP_conv,
  255. OP_iflag,
  256. /* Must be in the same order as FLAG_XXX! */
  257. OP_conv_notrunc = 0,
  258. OP_conv_sync,
  259. OP_conv_noerror,
  260. OP_conv_fsync,
  261. OP_conv_swab,
  262. /* Unimplemented conv=XXX: */
  263. //nocreat do not create the output file
  264. //excl fail if the output file already exists
  265. //fdatasync physically write output file data before finishing
  266. //lcase change upper case to lower case
  267. //ucase change lower case to upper case
  268. //block pad newline-terminated records with spaces to cbs-size
  269. //unblock replace trailing spaces in cbs-size records with newline
  270. //ascii from EBCDIC to ASCII
  271. //ebcdic from ASCII to EBCDIC
  272. //ibm from ASCII to alternate EBCDIC
  273. /* Partially implemented: */
  274. //swab swap every pair of input bytes: will abort on non-even reads
  275. OP_iflag_skip_bytes,
  276. #endif
  277. };
  278. smallint exitcode = EXIT_FAILURE;
  279. int i;
  280. size_t ibs = 512;
  281. char *ibuf;
  282. #if ENABLE_FEATURE_DD_IBS_OBS
  283. size_t obs = 512;
  284. char *obuf;
  285. #else
  286. # define obs ibs
  287. # define obuf ibuf
  288. #endif
  289. /* These are all zeroed at once! */
  290. struct {
  291. size_t oc;
  292. ssize_t prev_read_size; /* for detecting swab failure */
  293. off_t count;
  294. off_t seek, skip;
  295. const char *infile, *outfile;
  296. } Z;
  297. #define oc (Z.oc )
  298. #define prev_read_size (Z.prev_read_size)
  299. #define count (Z.count )
  300. #define seek (Z.seek )
  301. #define skip (Z.skip )
  302. #define infile (Z.infile )
  303. #define outfile (Z.outfile)
  304. memset(&Z, 0, sizeof(Z));
  305. INIT_G();
  306. //fflush_all(); - is this needed because of NOEXEC?
  307. for (i = 1; argv[i]; i++) {
  308. int what;
  309. char *val;
  310. char *arg = argv[i];
  311. #if ENABLE_DESKTOP
  312. /* "dd --". NB: coreutils 6.9 will complain if they see
  313. * more than one of them. We wouldn't. */
  314. if (arg[0] == '-' && arg[1] == '-' && arg[2] == '\0')
  315. continue;
  316. #endif
  317. val = strchr(arg, '=');
  318. if (val == NULL)
  319. bb_show_usage();
  320. *val = '\0';
  321. what = index_in_strings(keywords, arg);
  322. if (what < 0)
  323. bb_show_usage();
  324. /* *val = '='; - to preserve ps listing? */
  325. val++;
  326. #if ENABLE_FEATURE_DD_IBS_OBS
  327. if (what == OP_ibs) {
  328. /* Must fit into positive ssize_t */
  329. ibs = xatoul_range_sfx(val, 1, ((size_t)-1L)/2, cwbkMG_suffixes);
  330. /*continue;*/
  331. }
  332. if (what == OP_obs) {
  333. obs = xatoul_range_sfx(val, 1, ((size_t)-1L)/2, cwbkMG_suffixes);
  334. /*continue;*/
  335. }
  336. if (what == OP_conv) {
  337. G.flags |= parse_comma_flags(val, conv_words, "conv");
  338. /*continue;*/
  339. }
  340. if (what == OP_iflag) {
  341. G.flags |= parse_comma_flags(val, iflag_words, "iflag") << FLAG_IFLAG_SHIFT;
  342. /*continue;*/
  343. }
  344. #endif
  345. if (what == OP_bs) {
  346. ibs = xatoul_range_sfx(val, 1, ((size_t)-1L)/2, cwbkMG_suffixes);
  347. obs = ibs;
  348. /*continue;*/
  349. }
  350. /* These can be large: */
  351. if (what == OP_count) {
  352. G.flags |= FLAG_COUNT;
  353. count = XATOU_SFX(val, cwbkMG_suffixes);
  354. /*continue;*/
  355. }
  356. if (what == OP_seek) {
  357. seek = XATOU_SFX(val, cwbkMG_suffixes);
  358. /*continue;*/
  359. }
  360. if (what == OP_skip) {
  361. skip = XATOU_SFX(val, cwbkMG_suffixes);
  362. /*continue;*/
  363. }
  364. if (what == OP_if) {
  365. infile = val;
  366. /*continue;*/
  367. }
  368. if (what == OP_of) {
  369. outfile = val;
  370. /*continue;*/
  371. }
  372. #if ENABLE_FEATURE_DD_STATUS
  373. if (what == OP_status) {
  374. int n;
  375. n = index_in_strings(status_words, val);
  376. if (n < 0)
  377. bb_error_msg_and_die(bb_msg_invalid_arg_to, val, "status");
  378. G.flags |= FLAG_STATUS << n;
  379. /*continue;*/
  380. }
  381. #endif
  382. } /* end of "for (argv[i])" */
  383. //XXX:FIXME for huge ibs or obs, malloc'ing them isn't the brightest idea ever
  384. ibuf = xmalloc(ibs);
  385. obuf = ibuf;
  386. #if ENABLE_FEATURE_DD_IBS_OBS
  387. if (ibs != obs) {
  388. G.flags |= FLAG_TWOBUFS;
  389. obuf = xmalloc(obs);
  390. }
  391. #endif
  392. #if ENABLE_FEATURE_DD_SIGNAL_HANDLING
  393. signal_SA_RESTART_empty_mask(SIGUSR1, dd_output_status);
  394. #endif
  395. #if ENABLE_FEATURE_DD_THIRD_STATUS_LINE
  396. G.begin_time_us = monotonic_us();
  397. #endif
  398. if (infile) {
  399. xmove_fd(xopen(infile, O_RDONLY), ifd);
  400. } else {
  401. infile = bb_msg_standard_input;
  402. }
  403. if (outfile) {
  404. int oflag = O_WRONLY | O_CREAT;
  405. if (!seek && !(G.flags & FLAG_NOTRUNC))
  406. oflag |= O_TRUNC;
  407. xmove_fd(xopen(outfile, oflag), ofd);
  408. if (seek && !(G.flags & FLAG_NOTRUNC)) {
  409. if (ftruncate(ofd, seek * obs) < 0) {
  410. struct stat st;
  411. if (fstat(ofd, &st) < 0
  412. || S_ISREG(st.st_mode)
  413. || S_ISDIR(st.st_mode)
  414. ) {
  415. goto die_outfile;
  416. }
  417. }
  418. }
  419. } else {
  420. outfile = bb_msg_standard_output;
  421. }
  422. if (skip) {
  423. size_t blocksz = (G.flags & FLAG_SKIP_BYTES) ? 1 : ibs;
  424. if (lseek(ifd, skip * blocksz, SEEK_CUR) < 0) {
  425. do {
  426. ssize_t n = safe_read(ifd, ibuf, blocksz);
  427. if (n < 0)
  428. goto die_infile;
  429. if (n == 0)
  430. break;
  431. } while (--skip != 0);
  432. }
  433. }
  434. if (seek) {
  435. if (lseek(ofd, seek * obs, SEEK_CUR) < 0)
  436. goto die_outfile;
  437. }
  438. while (!(G.flags & FLAG_COUNT) || (G.in_full + G.in_part != count)) {
  439. ssize_t n;
  440. n = safe_read(ifd, ibuf, ibs);
  441. if (n == 0)
  442. break;
  443. if (n < 0) {
  444. /* "Bad block" */
  445. if (!(G.flags & FLAG_NOERROR))
  446. goto die_infile;
  447. bb_simple_perror_msg(infile);
  448. /* GNU dd with conv=noerror skips over bad blocks */
  449. xlseek(ifd, ibs, SEEK_CUR);
  450. /* conv=noerror,sync writes NULs,
  451. * conv=noerror just ignores input bad blocks */
  452. n = 0;
  453. }
  454. if (G.flags & FLAG_SWAB) {
  455. uint16_t *p16;
  456. ssize_t n2;
  457. /* Our code allows only last read to be odd-sized */
  458. if (prev_read_size & 1)
  459. bb_error_msg_and_die("can't swab %lu byte buffer",
  460. (unsigned long)prev_read_size);
  461. prev_read_size = n;
  462. /* If n is odd, last byte is not swapped:
  463. * echo -n "qwe" | dd conv=swab
  464. * prints "wqe".
  465. */
  466. p16 = (void*) ibuf;
  467. n2 = (n >> 1);
  468. while (--n2 >= 0) {
  469. *p16 = bswap_16(*p16);
  470. p16++;
  471. }
  472. }
  473. if ((size_t)n == ibs)
  474. G.in_full++;
  475. else {
  476. G.in_part++;
  477. if (G.flags & FLAG_SYNC) {
  478. memset(ibuf + n, 0, ibs - n);
  479. n = ibs;
  480. }
  481. }
  482. if (G.flags & FLAG_TWOBUFS) {
  483. char *tmp = ibuf;
  484. while (n) {
  485. size_t d = obs - oc;
  486. if (d > (size_t)n)
  487. d = n;
  488. memcpy(obuf + oc, tmp, d);
  489. n -= d;
  490. tmp += d;
  491. oc += d;
  492. if (oc == obs) {
  493. if (write_and_stats(obuf, obs, obs, outfile))
  494. goto out_status;
  495. oc = 0;
  496. }
  497. }
  498. } else {
  499. if (write_and_stats(ibuf, n, obs, outfile))
  500. goto out_status;
  501. }
  502. if (G.flags & FLAG_FSYNC) {
  503. if (fsync(ofd) < 0)
  504. goto die_outfile;
  505. }
  506. }
  507. if (ENABLE_FEATURE_DD_IBS_OBS && oc) {
  508. if (write_and_stats(obuf, oc, obs, outfile))
  509. goto out_status;
  510. }
  511. if (close(ifd) < 0) {
  512. die_infile:
  513. bb_simple_perror_msg_and_die(infile);
  514. }
  515. if (close(ofd) < 0) {
  516. die_outfile:
  517. bb_simple_perror_msg_and_die(outfile);
  518. }
  519. exitcode = EXIT_SUCCESS;
  520. out_status:
  521. if (!ENABLE_FEATURE_DD_STATUS || !(G.flags & FLAG_STATUS_NONE))
  522. dd_output_status(0);
  523. if (ENABLE_FEATURE_CLEAN_UP) {
  524. free(obuf);
  525. if (G.flags & FLAG_TWOBUFS)
  526. free(ibuf);
  527. }
  528. return exitcode;
  529. }