dd.c 14 KB

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