dd.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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: )
  33. //usage: "\n"
  34. //usage: "\nNumbers may be suffixed by c (x1), w (x2), b (x512), kD (x1000), k (x1024),"
  35. //usage: "\nMD (x1000000), M (x1048576), GD (x1000000000) or G (x1073741824)"
  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,
  140. FLAG_SYNC = 1 << 1,
  141. FLAG_NOERROR = 1 << 2,
  142. FLAG_FSYNC = 1 << 3,
  143. /* end of conv flags */
  144. FLAG_TWOBUFS = 1 << 4,
  145. FLAG_COUNT = 1 << 5,
  146. };
  147. static const char keywords[] ALIGN1 =
  148. "bs\0""count\0""seek\0""skip\0""if\0""of\0"
  149. #if ENABLE_FEATURE_DD_IBS_OBS
  150. "ibs\0""obs\0""conv\0"
  151. #endif
  152. ;
  153. #if ENABLE_FEATURE_DD_IBS_OBS
  154. static const char conv_words[] ALIGN1 =
  155. "notrunc\0""sync\0""noerror\0""fsync\0";
  156. #endif
  157. enum {
  158. OP_bs = 0,
  159. OP_count,
  160. OP_seek,
  161. OP_skip,
  162. OP_if,
  163. OP_of,
  164. #if ENABLE_FEATURE_DD_IBS_OBS
  165. OP_ibs,
  166. OP_obs,
  167. OP_conv,
  168. /* Must be in the same order as FLAG_XXX! */
  169. OP_conv_notrunc = 0,
  170. OP_conv_sync,
  171. OP_conv_noerror,
  172. OP_conv_fsync,
  173. /* Unimplemented conv=XXX: */
  174. //nocreat do not create the output file
  175. //excl fail if the output file already exists
  176. //fdatasync physically write output file data before finishing
  177. //swab swap every pair of input bytes
  178. //lcase change upper case to lower case
  179. //ucase change lower case to upper case
  180. //block pad newline-terminated records with spaces to cbs-size
  181. //unblock replace trailing spaces in cbs-size records with newline
  182. //ascii from EBCDIC to ASCII
  183. //ebcdic from ASCII to EBCDIC
  184. //ibm from ASCII to alternate EBCDIC
  185. #endif
  186. };
  187. int exitcode = EXIT_FAILURE;
  188. size_t ibs = 512, obs = 512;
  189. ssize_t n, w;
  190. char *ibuf, *obuf;
  191. /* And these are all zeroed at once! */
  192. struct {
  193. int flags;
  194. size_t oc;
  195. off_t count;
  196. off_t seek, skip;
  197. const char *infile, *outfile;
  198. } Z;
  199. #define flags (Z.flags )
  200. #define oc (Z.oc )
  201. #define count (Z.count )
  202. #define seek (Z.seek )
  203. #define skip (Z.skip )
  204. #define infile (Z.infile )
  205. #define outfile (Z.outfile)
  206. memset(&Z, 0, sizeof(Z));
  207. INIT_G();
  208. //fflush_all(); - is this needed because of NOEXEC?
  209. for (n = 1; argv[n]; n++) {
  210. int what;
  211. char *val;
  212. char *arg = argv[n];
  213. #if ENABLE_DESKTOP
  214. /* "dd --". NB: coreutils 6.9 will complain if they see
  215. * more than one of them. We wouldn't. */
  216. if (arg[0] == '-' && arg[1] == '-' && arg[2] == '\0')
  217. continue;
  218. #endif
  219. val = strchr(arg, '=');
  220. if (val == NULL)
  221. bb_show_usage();
  222. *val = '\0';
  223. what = index_in_strings(keywords, arg);
  224. if (what < 0)
  225. bb_show_usage();
  226. /* *val = '='; - to preserve ps listing? */
  227. val++;
  228. #if ENABLE_FEATURE_DD_IBS_OBS
  229. if (what == OP_ibs) {
  230. /* Must fit into positive ssize_t */
  231. ibs = xatoul_range_sfx(val, 1, ((size_t)-1L)/2, dd_suffixes);
  232. /*continue;*/
  233. }
  234. if (what == OP_obs) {
  235. obs = xatoul_range_sfx(val, 1, ((size_t)-1L)/2, dd_suffixes);
  236. /*continue;*/
  237. }
  238. if (what == OP_conv) {
  239. while (1) {
  240. /* find ',', replace them with NUL so we can use val for
  241. * index_in_strings() without copying.
  242. * We rely on val being non-null, else strchr would fault.
  243. */
  244. arg = strchr(val, ',');
  245. if (arg)
  246. *arg = '\0';
  247. what = index_in_strings(conv_words, val);
  248. if (what < 0)
  249. bb_error_msg_and_die(bb_msg_invalid_arg, val, "conv");
  250. flags |= (1 << what);
  251. if (!arg) /* no ',' left, so this was the last specifier */
  252. break;
  253. /* *arg = ','; - to preserve ps listing? */
  254. val = arg + 1; /* skip this keyword and ',' */
  255. }
  256. continue; /* we trashed 'what', can't fall through */
  257. }
  258. #endif
  259. if (what == OP_bs) {
  260. ibs = obs = xatoul_range_sfx(val, 1, ((size_t)-1L)/2, dd_suffixes);
  261. /*continue;*/
  262. }
  263. /* These can be large: */
  264. if (what == OP_count) {
  265. flags |= FLAG_COUNT;
  266. count = XATOU_SFX(val, dd_suffixes);
  267. /*continue;*/
  268. }
  269. if (what == OP_seek) {
  270. seek = XATOU_SFX(val, dd_suffixes);
  271. /*continue;*/
  272. }
  273. if (what == OP_skip) {
  274. skip = XATOU_SFX(val, dd_suffixes);
  275. /*continue;*/
  276. }
  277. if (what == OP_if) {
  278. infile = val;
  279. /*continue;*/
  280. }
  281. if (what == OP_of) {
  282. outfile = val;
  283. /*continue;*/
  284. }
  285. } /* end of "for (argv[n])" */
  286. //XXX:FIXME for huge ibs or obs, malloc'ing them isn't the brightest idea ever
  287. ibuf = obuf = xmalloc(ibs);
  288. if (ibs != obs) {
  289. flags |= FLAG_TWOBUFS;
  290. obuf = xmalloc(obs);
  291. }
  292. #if ENABLE_FEATURE_DD_SIGNAL_HANDLING
  293. signal_SA_RESTART_empty_mask(SIGUSR1, dd_output_status);
  294. #endif
  295. #if ENABLE_FEATURE_DD_THIRD_STATUS_LINE
  296. G.begin_time_us = monotonic_us();
  297. #endif
  298. if (infile != NULL)
  299. xmove_fd(xopen(infile, O_RDONLY), ifd);
  300. else {
  301. infile = bb_msg_standard_input;
  302. }
  303. if (outfile != NULL) {
  304. int oflag = O_WRONLY | O_CREAT;
  305. if (!seek && !(flags & FLAG_NOTRUNC))
  306. oflag |= O_TRUNC;
  307. xmove_fd(xopen(outfile, oflag), ofd);
  308. if (seek && !(flags & FLAG_NOTRUNC)) {
  309. if (ftruncate(ofd, seek * obs) < 0) {
  310. struct stat st;
  311. if (fstat(ofd, &st) < 0
  312. || S_ISREG(st.st_mode)
  313. || S_ISDIR(st.st_mode)
  314. ) {
  315. goto die_outfile;
  316. }
  317. }
  318. }
  319. } else {
  320. outfile = bb_msg_standard_output;
  321. }
  322. if (skip) {
  323. if (lseek(ifd, skip * ibs, SEEK_CUR) < 0) {
  324. while (skip-- > 0) {
  325. n = safe_read(ifd, ibuf, ibs);
  326. if (n < 0)
  327. goto die_infile;
  328. if (n == 0)
  329. break;
  330. }
  331. }
  332. }
  333. if (seek) {
  334. if (lseek(ofd, seek * obs, SEEK_CUR) < 0)
  335. goto die_outfile;
  336. }
  337. while (!(flags & FLAG_COUNT) || (G.in_full + G.in_part != count)) {
  338. n = safe_read(ifd, ibuf, ibs);
  339. if (n == 0)
  340. break;
  341. if (n < 0) {
  342. /* "Bad block" */
  343. if (!(flags & FLAG_NOERROR))
  344. goto die_infile;
  345. bb_simple_perror_msg(infile);
  346. /* GNU dd with conv=noerror skips over bad blocks */
  347. xlseek(ifd, ibs, SEEK_CUR);
  348. /* conv=noerror,sync writes NULs,
  349. * conv=noerror just ignores input bad blocks */
  350. n = 0;
  351. }
  352. if ((size_t)n == ibs)
  353. G.in_full++;
  354. else {
  355. G.in_part++;
  356. if (flags & FLAG_SYNC) {
  357. memset(ibuf + n, 0, ibs - n);
  358. n = ibs;
  359. }
  360. }
  361. if (flags & FLAG_TWOBUFS) {
  362. char *tmp = ibuf;
  363. while (n) {
  364. size_t d = obs - oc;
  365. if (d > (size_t)n)
  366. d = n;
  367. memcpy(obuf + oc, tmp, d);
  368. n -= d;
  369. tmp += d;
  370. oc += d;
  371. if (oc == obs) {
  372. if (write_and_stats(obuf, obs, obs, outfile))
  373. goto out_status;
  374. oc = 0;
  375. }
  376. }
  377. } else if (write_and_stats(ibuf, n, obs, outfile))
  378. goto out_status;
  379. if (flags & FLAG_FSYNC) {
  380. if (fsync(ofd) < 0)
  381. goto die_outfile;
  382. }
  383. }
  384. if (ENABLE_FEATURE_DD_IBS_OBS && oc) {
  385. w = full_write_or_warn(obuf, oc, outfile);
  386. if (w < 0) goto out_status;
  387. if (w > 0) G.out_part++;
  388. }
  389. if (close(ifd) < 0) {
  390. die_infile:
  391. bb_simple_perror_msg_and_die(infile);
  392. }
  393. if (close(ofd) < 0) {
  394. die_outfile:
  395. bb_simple_perror_msg_and_die(outfile);
  396. }
  397. exitcode = EXIT_SUCCESS;
  398. out_status:
  399. dd_output_status(0);
  400. if (ENABLE_FEATURE_CLEAN_UP) {
  401. free(obuf);
  402. if (flags & FLAG_TWOBUFS)
  403. free(ibuf);
  404. }
  405. return exitcode;
  406. }