dd.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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. //usage:#define dd_trivial_usage
  11. //usage: "[if=FILE] [of=FILE] " IF_FEATURE_DD_IBS_OBS("[ibs=N] [obs=N] ") "[bs=N] [count=N] [skip=N]\n"
  12. //usage: " [seek=N]" IF_FEATURE_DD_IBS_OBS(" [conv=notrunc|noerror|sync|fsync]")
  13. //usage:#define dd_full_usage "\n\n"
  14. //usage: "Copy a file with converting and formatting\n"
  15. //usage: "\n if=FILE Read from FILE instead of stdin"
  16. //usage: "\n of=FILE Write to FILE instead of stdout"
  17. //usage: "\n bs=N Read and write N bytes at a time"
  18. //usage: IF_FEATURE_DD_IBS_OBS(
  19. //usage: "\n ibs=N Read N bytes at a time"
  20. //usage: )
  21. //usage: IF_FEATURE_DD_IBS_OBS(
  22. //usage: "\n obs=N Write N bytes at a time"
  23. //usage: )
  24. //usage: "\n count=N Copy only N input blocks"
  25. //usage: "\n skip=N Skip N input blocks"
  26. //usage: "\n seek=N Skip N output blocks"
  27. //usage: IF_FEATURE_DD_IBS_OBS(
  28. //usage: "\n conv=notrunc Don't truncate output file"
  29. //usage: "\n conv=noerror Continue after read errors"
  30. //usage: "\n conv=sync Pad blocks with zeros"
  31. //usage: "\n conv=fsync Physically write data out before finishing"
  32. //usage: "\n conv=swab Swap every pair of bytes"
  33. //usage: )
  34. //usage: "\n"
  35. //usage: "\nN may be suffixed by c (1), w (2), b (512), kD (1000), k (1024), MD, M, GD, G"
  36. //usage:
  37. //usage:#define dd_example_usage
  38. //usage: "$ dd if=/dev/zero of=/dev/ram1 bs=1M count=4\n"
  39. //usage: "4+0 records in\n"
  40. //usage: "4+0 records out\n"
  41. #include "libbb.h"
  42. /* This is a NOEXEC applet. Be very careful! */
  43. enum {
  44. ifd = STDIN_FILENO,
  45. ofd = STDOUT_FILENO,
  46. };
  47. static const struct suffix_mult dd_suffixes[] = {
  48. { "c", 1 },
  49. { "w", 2 },
  50. { "b", 512 },
  51. { "kD", 1000 },
  52. { "k", 1024 },
  53. { "K", 1024 }, /* compat with coreutils dd */
  54. { "MD", 1000000 },
  55. { "M", 1048576 },
  56. { "GD", 1000000000 },
  57. { "G", 1073741824 },
  58. { "", 0 }
  59. };
  60. struct globals {
  61. off_t out_full, out_part, in_full, in_part;
  62. #if ENABLE_FEATURE_DD_THIRD_STATUS_LINE
  63. unsigned long long total_bytes;
  64. unsigned long long begin_time_us;
  65. #endif
  66. } FIX_ALIASING;
  67. #define G (*(struct globals*)&bb_common_bufsiz1)
  68. #define INIT_G() do { \
  69. /* we have to zero it out because of NOEXEC */ \
  70. memset(&G, 0, sizeof(G)); \
  71. } while (0)
  72. static void dd_output_status(int UNUSED_PARAM cur_signal)
  73. {
  74. #if ENABLE_FEATURE_DD_THIRD_STATUS_LINE
  75. double seconds;
  76. unsigned long long bytes_sec;
  77. unsigned long long now_us = monotonic_us(); /* before fprintf */
  78. #endif
  79. /* Deliberately using %u, not %d */
  80. fprintf(stderr, "%"OFF_FMT"u+%"OFF_FMT"u records in\n"
  81. "%"OFF_FMT"u+%"OFF_FMT"u records out\n",
  82. G.in_full, G.in_part,
  83. G.out_full, G.out_part);
  84. #if ENABLE_FEATURE_DD_THIRD_STATUS_LINE
  85. fprintf(stderr, "%llu bytes (%sB) copied, ",
  86. G.total_bytes,
  87. /* show fractional digit, use suffixes */
  88. make_human_readable_str(G.total_bytes, 1, 0)
  89. );
  90. /* Corner cases:
  91. * ./busybox dd </dev/null >/dev/null
  92. * ./busybox dd bs=1M count=2000 </dev/zero >/dev/null
  93. * (echo DONE) | ./busybox dd >/dev/null
  94. * (sleep 1; echo DONE) | ./busybox dd >/dev/null
  95. */
  96. seconds = (now_us - G.begin_time_us) / 1000000.0;
  97. bytes_sec = G.total_bytes / seconds;
  98. fprintf(stderr, "%f seconds, %sB/s\n",
  99. seconds,
  100. /* show fractional digit, use suffixes */
  101. make_human_readable_str(bytes_sec, 1, 0)
  102. );
  103. #endif
  104. }
  105. static ssize_t full_write_or_warn(const void *buf, size_t len,
  106. const char *const filename)
  107. {
  108. ssize_t n = full_write(ofd, buf, len);
  109. if (n < 0)
  110. bb_perror_msg("writing '%s'", filename);
  111. return n;
  112. }
  113. static bool write_and_stats(const void *buf, size_t len, size_t obs,
  114. const char *filename)
  115. {
  116. ssize_t n = full_write_or_warn(buf, len, filename);
  117. if (n < 0)
  118. return 1;
  119. if ((size_t)n == obs)
  120. G.out_full++;
  121. else if (n) /* > 0 */
  122. G.out_part++;
  123. #if ENABLE_FEATURE_DD_THIRD_STATUS_LINE
  124. G.total_bytes += n;
  125. #endif
  126. return 0;
  127. }
  128. #if ENABLE_LFS
  129. # define XATOU_SFX xatoull_sfx
  130. #else
  131. # define XATOU_SFX xatoul_sfx
  132. #endif
  133. int dd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  134. int dd_main(int argc UNUSED_PARAM, char **argv)
  135. {
  136. enum {
  137. /* Must be in the same order as OP_conv_XXX! */
  138. /* (see "flags |= (1 << what)" below) */
  139. FLAG_NOTRUNC = (1 << 0) * ENABLE_FEATURE_DD_IBS_OBS,
  140. FLAG_SYNC = (1 << 1) * ENABLE_FEATURE_DD_IBS_OBS,
  141. FLAG_NOERROR = (1 << 2) * ENABLE_FEATURE_DD_IBS_OBS,
  142. FLAG_FSYNC = (1 << 3) * ENABLE_FEATURE_DD_IBS_OBS,
  143. FLAG_SWAB = (1 << 4) * ENABLE_FEATURE_DD_IBS_OBS,
  144. /* end of conv flags */
  145. FLAG_TWOBUFS = (1 << 5) * ENABLE_FEATURE_DD_IBS_OBS,
  146. FLAG_COUNT = 1 << 6,
  147. };
  148. static const char keywords[] ALIGN1 =
  149. "bs\0""count\0""seek\0""skip\0""if\0""of\0"
  150. #if ENABLE_FEATURE_DD_IBS_OBS
  151. "ibs\0""obs\0""conv\0"
  152. #endif
  153. ;
  154. #if ENABLE_FEATURE_DD_IBS_OBS
  155. static const char conv_words[] ALIGN1 =
  156. "notrunc\0""sync\0""noerror\0""fsync\0""swab\0";
  157. #endif
  158. enum {
  159. OP_bs = 0,
  160. OP_count,
  161. OP_seek,
  162. OP_skip,
  163. OP_if,
  164. OP_of,
  165. #if ENABLE_FEATURE_DD_IBS_OBS
  166. OP_ibs,
  167. OP_obs,
  168. OP_conv,
  169. /* Must be in the same order as FLAG_XXX! */
  170. OP_conv_notrunc = 0,
  171. OP_conv_sync,
  172. OP_conv_noerror,
  173. OP_conv_fsync,
  174. OP_conv_swab,
  175. /* Unimplemented conv=XXX: */
  176. //nocreat do not create the output file
  177. //excl fail if the output file already exists
  178. //fdatasync physically write output file data before finishing
  179. //lcase change upper case to lower case
  180. //ucase change lower case to upper case
  181. //block pad newline-terminated records with spaces to cbs-size
  182. //unblock replace trailing spaces in cbs-size records with newline
  183. //ascii from EBCDIC to ASCII
  184. //ebcdic from ASCII to EBCDIC
  185. //ibm from ASCII to alternate EBCDIC
  186. /* Partially implemented: */
  187. //swab swap every pair of input bytes: will abort on non-even reads
  188. #endif
  189. };
  190. smallint exitcode = EXIT_FAILURE;
  191. int i;
  192. size_t ibs = 512;
  193. char *ibuf;
  194. #if ENABLE_FEATURE_DD_IBS_OBS
  195. size_t obs = 512;
  196. char *obuf;
  197. #else
  198. # define obs ibs
  199. # define obuf ibuf
  200. #endif
  201. /* These are all zeroed at once! */
  202. struct {
  203. int flags;
  204. size_t oc;
  205. ssize_t prev_read_size; /* for detecting swab failure */
  206. off_t count;
  207. off_t seek, skip;
  208. const char *infile, *outfile;
  209. } Z;
  210. #define flags (Z.flags )
  211. #define oc (Z.oc )
  212. #define prev_read_size (Z.prev_read_size)
  213. #define count (Z.count )
  214. #define seek (Z.seek )
  215. #define skip (Z.skip )
  216. #define infile (Z.infile )
  217. #define outfile (Z.outfile)
  218. memset(&Z, 0, sizeof(Z));
  219. INIT_G();
  220. //fflush_all(); - is this needed because of NOEXEC?
  221. for (i = 1; argv[i]; i++) {
  222. int what;
  223. char *val;
  224. char *arg = argv[i];
  225. #if ENABLE_DESKTOP
  226. /* "dd --". NB: coreutils 6.9 will complain if they see
  227. * more than one of them. We wouldn't. */
  228. if (arg[0] == '-' && arg[1] == '-' && arg[2] == '\0')
  229. continue;
  230. #endif
  231. val = strchr(arg, '=');
  232. if (val == NULL)
  233. bb_show_usage();
  234. *val = '\0';
  235. what = index_in_strings(keywords, arg);
  236. if (what < 0)
  237. bb_show_usage();
  238. /* *val = '='; - to preserve ps listing? */
  239. val++;
  240. #if ENABLE_FEATURE_DD_IBS_OBS
  241. if (what == OP_ibs) {
  242. /* Must fit into positive ssize_t */
  243. ibs = xatoul_range_sfx(val, 1, ((size_t)-1L)/2, dd_suffixes);
  244. /*continue;*/
  245. }
  246. if (what == OP_obs) {
  247. obs = xatoul_range_sfx(val, 1, ((size_t)-1L)/2, dd_suffixes);
  248. /*continue;*/
  249. }
  250. if (what == OP_conv) {
  251. while (1) {
  252. int n;
  253. /* find ',', replace them with NUL so we can use val for
  254. * index_in_strings() without copying.
  255. * We rely on val being non-null, else strchr would fault.
  256. */
  257. arg = strchr(val, ',');
  258. if (arg)
  259. *arg = '\0';
  260. n = index_in_strings(conv_words, val);
  261. if (n < 0)
  262. bb_error_msg_and_die(bb_msg_invalid_arg, val, "conv");
  263. flags |= (1 << n);
  264. if (!arg) /* no ',' left, so this was the last specifier */
  265. break;
  266. /* *arg = ','; - to preserve ps listing? */
  267. val = arg + 1; /* skip this keyword and ',' */
  268. }
  269. /*continue;*/
  270. }
  271. #endif
  272. if (what == OP_bs) {
  273. ibs = xatoul_range_sfx(val, 1, ((size_t)-1L)/2, dd_suffixes);
  274. obs = ibs;
  275. /*continue;*/
  276. }
  277. /* These can be large: */
  278. if (what == OP_count) {
  279. flags |= FLAG_COUNT;
  280. count = XATOU_SFX(val, dd_suffixes);
  281. /*continue;*/
  282. }
  283. if (what == OP_seek) {
  284. seek = XATOU_SFX(val, dd_suffixes);
  285. /*continue;*/
  286. }
  287. if (what == OP_skip) {
  288. skip = XATOU_SFX(val, dd_suffixes);
  289. /*continue;*/
  290. }
  291. if (what == OP_if) {
  292. infile = val;
  293. /*continue;*/
  294. }
  295. if (what == OP_of) {
  296. outfile = val;
  297. /*continue;*/
  298. }
  299. } /* end of "for (argv[i])" */
  300. //XXX:FIXME for huge ibs or obs, malloc'ing them isn't the brightest idea ever
  301. ibuf = xmalloc(ibs);
  302. obuf = ibuf;
  303. #if ENABLE_FEATURE_DD_IBS_OBS
  304. if (ibs != obs) {
  305. flags |= FLAG_TWOBUFS;
  306. obuf = xmalloc(obs);
  307. }
  308. #endif
  309. #if ENABLE_FEATURE_DD_SIGNAL_HANDLING
  310. signal_SA_RESTART_empty_mask(SIGUSR1, dd_output_status);
  311. #endif
  312. #if ENABLE_FEATURE_DD_THIRD_STATUS_LINE
  313. G.begin_time_us = monotonic_us();
  314. #endif
  315. if (infile) {
  316. xmove_fd(xopen(infile, O_RDONLY), ifd);
  317. } else {
  318. infile = bb_msg_standard_input;
  319. }
  320. if (outfile) {
  321. int oflag = O_WRONLY | O_CREAT;
  322. if (!seek && !(flags & FLAG_NOTRUNC))
  323. oflag |= O_TRUNC;
  324. xmove_fd(xopen(outfile, oflag), ofd);
  325. if (seek && !(flags & FLAG_NOTRUNC)) {
  326. if (ftruncate(ofd, seek * obs) < 0) {
  327. struct stat st;
  328. if (fstat(ofd, &st) < 0
  329. || S_ISREG(st.st_mode)
  330. || S_ISDIR(st.st_mode)
  331. ) {
  332. goto die_outfile;
  333. }
  334. }
  335. }
  336. } else {
  337. outfile = bb_msg_standard_output;
  338. }
  339. if (skip) {
  340. if (lseek(ifd, skip * ibs, SEEK_CUR) < 0) {
  341. do {
  342. ssize_t n = safe_read(ifd, ibuf, ibs);
  343. if (n < 0)
  344. goto die_infile;
  345. if (n == 0)
  346. break;
  347. } while (--skip != 0);
  348. }
  349. }
  350. if (seek) {
  351. if (lseek(ofd, seek * obs, SEEK_CUR) < 0)
  352. goto die_outfile;
  353. }
  354. while (!(flags & FLAG_COUNT) || (G.in_full + G.in_part != count)) {
  355. ssize_t n;
  356. n = safe_read(ifd, ibuf, ibs);
  357. if (n == 0)
  358. break;
  359. if (n < 0) {
  360. /* "Bad block" */
  361. if (!(flags & FLAG_NOERROR))
  362. goto die_infile;
  363. bb_simple_perror_msg(infile);
  364. /* GNU dd with conv=noerror skips over bad blocks */
  365. xlseek(ifd, ibs, SEEK_CUR);
  366. /* conv=noerror,sync writes NULs,
  367. * conv=noerror just ignores input bad blocks */
  368. n = 0;
  369. }
  370. if (flags & FLAG_SWAB) {
  371. uint16_t *p16;
  372. ssize_t n2;
  373. /* Our code allows only last read to be odd-sized */
  374. if (prev_read_size & 1)
  375. bb_error_msg_and_die("can't swab %lu byte buffer",
  376. (unsigned long)prev_read_size);
  377. prev_read_size = n;
  378. /* If n is odd, last byte is not swapped:
  379. * echo -n "qwe" | dd conv=swab
  380. * prints "wqe".
  381. */
  382. p16 = (void*) ibuf;
  383. n2 = (n >> 1);
  384. while (--n2 >= 0) {
  385. *p16 = bswap_16(*p16);
  386. p16++;
  387. }
  388. }
  389. if ((size_t)n == ibs)
  390. G.in_full++;
  391. else {
  392. G.in_part++;
  393. if (flags & FLAG_SYNC) {
  394. memset(ibuf + n, 0, ibs - n);
  395. n = ibs;
  396. }
  397. }
  398. if (flags & FLAG_TWOBUFS) {
  399. char *tmp = ibuf;
  400. while (n) {
  401. size_t d = obs - oc;
  402. if (d > (size_t)n)
  403. d = n;
  404. memcpy(obuf + oc, tmp, d);
  405. n -= d;
  406. tmp += d;
  407. oc += d;
  408. if (oc == obs) {
  409. if (write_and_stats(obuf, obs, obs, outfile))
  410. goto out_status;
  411. oc = 0;
  412. }
  413. }
  414. } else {
  415. if (write_and_stats(ibuf, n, obs, outfile))
  416. goto out_status;
  417. }
  418. if (flags & FLAG_FSYNC) {
  419. if (fsync(ofd) < 0)
  420. goto die_outfile;
  421. }
  422. }
  423. if (ENABLE_FEATURE_DD_IBS_OBS && oc) {
  424. if (write_and_stats(obuf, oc, obs, outfile))
  425. goto out_status;
  426. }
  427. if (close(ifd) < 0) {
  428. die_infile:
  429. bb_simple_perror_msg_and_die(infile);
  430. }
  431. if (close(ofd) < 0) {
  432. die_outfile:
  433. bb_simple_perror_msg_and_die(outfile);
  434. }
  435. exitcode = EXIT_SUCCESS;
  436. out_status:
  437. dd_output_status(0);
  438. if (ENABLE_FEATURE_CLEAN_UP) {
  439. free(obuf);
  440. if (flags & FLAG_TWOBUFS)
  441. free(ibuf);
  442. }
  443. return exitcode;
  444. }