sort.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * SuS3 compliant sort implementation for busybox
  4. *
  5. * Copyright (C) 2004 by Rob Landley <rob@landley.net>
  6. *
  7. * MAINTAINER: Rob Landley <rob@landley.net>
  8. *
  9. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  10. *
  11. * See SuS3 sort standard at:
  12. * http://www.opengroup.org/onlinepubs/007904975/utilities/sort.html
  13. */
  14. #include "libbb.h"
  15. /* This is a NOEXEC applet. Be very careful! */
  16. /*
  17. sort [-m][-o output][-bdfinru][-t char][-k keydef]... [file...]
  18. sort -c [-bdfinru][-t char][-k keydef][file]
  19. */
  20. /* These are sort types */
  21. static const char OPT_STR[] ALIGN1 = "ngMucszbrdfimS:T:o:k:t:";
  22. enum {
  23. FLAG_n = 1, /* Numeric sort */
  24. FLAG_g = 2, /* Sort using strtod() */
  25. FLAG_M = 4, /* Sort date */
  26. /* ucsz apply to root level only, not keys. b at root level implies bb */
  27. FLAG_u = 8, /* Unique */
  28. FLAG_c = 0x10, /* Check: no output, exit(!ordered) */
  29. FLAG_s = 0x20, /* Stable sort, no ascii fallback at end */
  30. FLAG_z = 0x40, /* Input and output is NUL terminated, not \n */
  31. /* These can be applied to search keys, the previous four can't */
  32. FLAG_b = 0x80, /* Ignore leading blanks */
  33. FLAG_r = 0x100, /* Reverse */
  34. FLAG_d = 0x200, /* Ignore !(isalnum()|isspace()) */
  35. FLAG_f = 0x400, /* Force uppercase */
  36. FLAG_i = 0x800, /* Ignore !isprint() */
  37. FLAG_m = 0x1000, /* ignored: merge already sorted files; do not sort */
  38. FLAG_S = 0x2000, /* ignored: -S, --buffer-size=SIZE */
  39. FLAG_T = 0x4000, /* ignored: -T, --temporary-directory=DIR */
  40. FLAG_o = 0x8000,
  41. FLAG_k = 0x10000,
  42. FLAG_t = 0x20000,
  43. FLAG_bb = 0x80000000, /* Ignore trailing blanks */
  44. };
  45. #if ENABLE_FEATURE_SORT_BIG
  46. static char key_separator;
  47. static struct sort_key {
  48. struct sort_key *next_key; /* linked list */
  49. unsigned range[4]; /* start word, start char, end word, end char */
  50. unsigned flags;
  51. } *key_list;
  52. static char *get_key(char *str, struct sort_key *key, int flags)
  53. {
  54. int start = 0, end = 0, len, j;
  55. unsigned i;
  56. /* Special case whole string, so we don't have to make a copy */
  57. if (key->range[0] == 1 && !key->range[1] && !key->range[2] && !key->range[3]
  58. && !(flags & (FLAG_b | FLAG_d | FLAG_f | FLAG_i | FLAG_bb))
  59. ) {
  60. return str;
  61. }
  62. /* Find start of key on first pass, end on second pass */
  63. len = strlen(str);
  64. for (j = 0; j < 2; j++) {
  65. if (!key->range[2*j])
  66. end = len;
  67. /* Loop through fields */
  68. else {
  69. end = 0;
  70. for (i = 1; i < key->range[2*j] + j; i++) {
  71. if (key_separator) {
  72. /* Skip body of key and separator */
  73. while (str[end]) {
  74. if (str[end++] == key_separator)
  75. break;
  76. }
  77. } else {
  78. /* Skip leading blanks */
  79. while (isspace(str[end]))
  80. end++;
  81. /* Skip body of key */
  82. while (str[end]) {
  83. if (isspace(str[end]))
  84. break;
  85. end++;
  86. }
  87. }
  88. }
  89. }
  90. if (!j) start = end;
  91. }
  92. /* Strip leading whitespace if necessary */
  93. //XXX: skip_whitespace()
  94. if (flags & FLAG_b)
  95. while (isspace(str[start])) start++;
  96. /* Strip trailing whitespace if necessary */
  97. if (flags & FLAG_bb)
  98. while (end > start && isspace(str[end-1])) end--;
  99. /* Handle offsets on start and end */
  100. if (key->range[3]) {
  101. end += key->range[3] - 1;
  102. if (end > len) end = len;
  103. }
  104. if (key->range[1]) {
  105. start += key->range[1] - 1;
  106. if (start > len) start = len;
  107. }
  108. /* Make the copy */
  109. if (end < start) end = start;
  110. str = xstrndup(str+start, end-start);
  111. /* Handle -d */
  112. if (flags & FLAG_d) {
  113. for (start = end = 0; str[end]; end++)
  114. if (isspace(str[end]) || isalnum(str[end]))
  115. str[start++] = str[end];
  116. str[start] = '\0';
  117. }
  118. /* Handle -i */
  119. if (flags & FLAG_i) {
  120. for (start = end = 0; str[end]; end++)
  121. if (isprint_asciionly(str[end]))
  122. str[start++] = str[end];
  123. str[start] = '\0';
  124. }
  125. /* Handle -f */
  126. if (flags & FLAG_f)
  127. for (i = 0; str[i]; i++)
  128. str[i] = toupper(str[i]);
  129. return str;
  130. }
  131. static struct sort_key *add_key(void)
  132. {
  133. struct sort_key **pkey = &key_list;
  134. while (*pkey)
  135. pkey = &((*pkey)->next_key);
  136. return *pkey = xzalloc(sizeof(struct sort_key));
  137. }
  138. #define GET_LINE(fp) \
  139. ((option_mask32 & FLAG_z) \
  140. ? bb_get_chunk_from_file(fp, NULL) \
  141. : xmalloc_fgetline(fp))
  142. #else
  143. #define GET_LINE(fp) xmalloc_fgetline(fp)
  144. #endif
  145. /* Iterate through keys list and perform comparisons */
  146. static int compare_keys(const void *xarg, const void *yarg)
  147. {
  148. int flags = option_mask32, retval = 0;
  149. char *x, *y;
  150. #if ENABLE_FEATURE_SORT_BIG
  151. struct sort_key *key;
  152. for (key = key_list; !retval && key; key = key->next_key) {
  153. flags = key->flags ? key->flags : option_mask32;
  154. /* Chop out and modify key chunks, handling -dfib */
  155. x = get_key(*(char **)xarg, key, flags);
  156. y = get_key(*(char **)yarg, key, flags);
  157. #else
  158. /* This curly bracket serves no purpose but to match the nesting
  159. level of the for () loop we're not using */
  160. {
  161. x = *(char **)xarg;
  162. y = *(char **)yarg;
  163. #endif
  164. /* Perform actual comparison */
  165. switch (flags & 7) {
  166. default:
  167. bb_error_msg_and_die("unknown sort type");
  168. break;
  169. /* Ascii sort */
  170. case 0:
  171. #if ENABLE_LOCALE_SUPPORT
  172. retval = strcoll(x, y);
  173. #else
  174. retval = strcmp(x, y);
  175. #endif
  176. break;
  177. #if ENABLE_FEATURE_SORT_BIG
  178. case FLAG_g: {
  179. char *xx, *yy;
  180. double dx = strtod(x, &xx);
  181. double dy = strtod(y, &yy);
  182. /* not numbers < NaN < -infinity < numbers < +infinity) */
  183. if (x == xx)
  184. retval = (y == yy ? 0 : -1);
  185. else if (y == yy)
  186. retval = 1;
  187. /* Check for isnan */
  188. else if (dx != dx)
  189. retval = (dy != dy) ? 0 : -1;
  190. else if (dy != dy)
  191. retval = 1;
  192. /* Check for infinity. Could underflow, but it avoids libm. */
  193. else if (1.0 / dx == 0.0) {
  194. if (dx < 0)
  195. retval = (1.0 / dy == 0.0 && dy < 0) ? 0 : -1;
  196. else
  197. retval = (1.0 / dy == 0.0 && dy > 0) ? 0 : 1;
  198. } else if (1.0 / dy == 0.0)
  199. retval = (dy < 0) ? 1 : -1;
  200. else
  201. retval = (dx > dy) ? 1 : ((dx < dy) ? -1 : 0);
  202. break;
  203. }
  204. case FLAG_M: {
  205. struct tm thyme;
  206. int dx;
  207. char *xx, *yy;
  208. xx = strptime(x, "%b", &thyme);
  209. dx = thyme.tm_mon;
  210. yy = strptime(y, "%b", &thyme);
  211. if (!xx)
  212. retval = (!yy) ? 0 : -1;
  213. else if (!yy)
  214. retval = 1;
  215. else
  216. retval = (dx == thyme.tm_mon) ? 0 : dx - thyme.tm_mon;
  217. break;
  218. }
  219. /* Full floating point version of -n */
  220. case FLAG_n: {
  221. double dx = atof(x);
  222. double dy = atof(y);
  223. retval = (dx > dy) ? 1 : ((dx < dy) ? -1 : 0);
  224. break;
  225. }
  226. } /* switch */
  227. /* Free key copies. */
  228. if (x != *(char **)xarg) free(x);
  229. if (y != *(char **)yarg) free(y);
  230. /* if (retval) break; - done by for () anyway */
  231. #else
  232. /* Integer version of -n for tiny systems */
  233. case FLAG_n:
  234. retval = atoi(x) - atoi(y);
  235. break;
  236. } /* switch */
  237. #endif
  238. } /* for */
  239. /* Perform fallback sort if necessary */
  240. if (!retval && !(option_mask32 & FLAG_s))
  241. retval = strcmp(*(char **)xarg, *(char **)yarg);
  242. if (flags & FLAG_r) return -retval;
  243. return retval;
  244. }
  245. #if ENABLE_FEATURE_SORT_BIG
  246. static unsigned str2u(char **str)
  247. {
  248. unsigned long lu;
  249. if (!isdigit((*str)[0]))
  250. bb_error_msg_and_die("bad field specification");
  251. lu = strtoul(*str, str, 10);
  252. if ((sizeof(long) > sizeof(int) && lu > INT_MAX) || !lu)
  253. bb_error_msg_and_die("bad field specification");
  254. return lu;
  255. }
  256. #endif
  257. int sort_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  258. int sort_main(int argc UNUSED_PARAM, char **argv)
  259. {
  260. char *line, **lines;
  261. char *str_ignored, *str_o, *str_t;
  262. llist_t *lst_k = NULL;
  263. int i, flag;
  264. int linecount;
  265. unsigned opts;
  266. xfunc_error_retval = 2;
  267. /* Parse command line options */
  268. /* -o and -t can be given at most once */
  269. opt_complementary = "o--o:t--t:" /* -t, -o: at most one of each */
  270. "k::"; /* -k takes list */
  271. opts = getopt32(argv, OPT_STR, &str_ignored, &str_ignored, &str_o, &lst_k, &str_t);
  272. /* global b strips leading and trailing spaces */
  273. if (opts & FLAG_b)
  274. option_mask32 |= FLAG_bb;
  275. #if ENABLE_FEATURE_SORT_BIG
  276. if (opts & FLAG_t) {
  277. if (!str_t[0] || str_t[1])
  278. bb_error_msg_and_die("bad -t parameter");
  279. key_separator = str_t[0];
  280. }
  281. /* note: below this point we use option_mask32, not opts,
  282. * since that reduces register pressure and makes code smaller */
  283. /* parse sort key */
  284. while (lst_k) {
  285. enum {
  286. FLAG_allowed_for_k =
  287. FLAG_n | /* Numeric sort */
  288. FLAG_g | /* Sort using strtod() */
  289. FLAG_M | /* Sort date */
  290. FLAG_b | /* Ignore leading blanks */
  291. FLAG_r | /* Reverse */
  292. FLAG_d | /* Ignore !(isalnum()|isspace()) */
  293. FLAG_f | /* Force uppercase */
  294. FLAG_i | /* Ignore !isprint() */
  295. 0
  296. };
  297. struct sort_key *key = add_key();
  298. char *str_k = llist_pop(&lst_k);
  299. i = 0; /* i==0 before comma, 1 after (-k3,6) */
  300. while (*str_k) {
  301. /* Start of range */
  302. /* Cannot use bb_strtou - suffix can be a letter */
  303. key->range[2*i] = str2u(&str_k);
  304. if (*str_k == '.') {
  305. str_k++;
  306. key->range[2*i+1] = str2u(&str_k);
  307. }
  308. while (*str_k) {
  309. const char *temp2;
  310. if (*str_k == ',' && !i++) {
  311. str_k++;
  312. break;
  313. } /* no else needed: fall through to syntax error
  314. because comma isn't in OPT_STR */
  315. temp2 = strchr(OPT_STR, *str_k);
  316. if (!temp2)
  317. bb_error_msg_and_die("unknown key option");
  318. flag = 1 << (temp2 - OPT_STR);
  319. if (flag & ~FLAG_allowed_for_k)
  320. bb_error_msg_and_die("unknown sort type");
  321. /* b after ',' means strip _trailing_ space */
  322. if (i && flag == FLAG_b)
  323. flag = FLAG_bb;
  324. key->flags |= flag;
  325. str_k++;
  326. }
  327. }
  328. }
  329. #endif
  330. /* Open input files and read data */
  331. argv += optind;
  332. if (!*argv)
  333. *--argv = (char*)"-";
  334. linecount = 0;
  335. lines = NULL;
  336. do {
  337. /* coreutils 6.9 compat: abort on first open error,
  338. * do not continue to next file: */
  339. FILE *fp = xfopen_stdin(*argv);
  340. for (;;) {
  341. line = GET_LINE(fp);
  342. if (!line)
  343. break;
  344. lines = xrealloc_vector(lines, 6, linecount);
  345. lines[linecount++] = line;
  346. }
  347. fclose_if_not_stdin(fp);
  348. } while (*++argv);
  349. #if ENABLE_FEATURE_SORT_BIG
  350. /* if no key, perform alphabetic sort */
  351. if (!key_list)
  352. add_key()->range[0] = 1;
  353. /* handle -c */
  354. if (option_mask32 & FLAG_c) {
  355. int j = (option_mask32 & FLAG_u) ? -1 : 0;
  356. for (i = 1; i < linecount; i++) {
  357. if (compare_keys(&lines[i-1], &lines[i]) > j) {
  358. fprintf(stderr, "Check line %u\n", i);
  359. return EXIT_FAILURE;
  360. }
  361. }
  362. return EXIT_SUCCESS;
  363. }
  364. #endif
  365. /* Perform the actual sort */
  366. qsort(lines, linecount, sizeof(lines[0]), compare_keys);
  367. /* handle -u */
  368. if (option_mask32 & FLAG_u) {
  369. flag = 0;
  370. /* coreutils 6.3 drop lines for which only key is the same */
  371. /* -- disabling last-resort compare... */
  372. option_mask32 |= FLAG_s;
  373. for (i = 1; i < linecount; i++) {
  374. if (compare_keys(&lines[flag], &lines[i]) == 0)
  375. free(lines[i]);
  376. else
  377. lines[++flag] = lines[i];
  378. }
  379. if (linecount)
  380. linecount = flag+1;
  381. }
  382. /* Print it */
  383. #if ENABLE_FEATURE_SORT_BIG
  384. /* Open output file _after_ we read all input ones */
  385. if (option_mask32 & FLAG_o)
  386. xmove_fd(xopen(str_o, O_WRONLY|O_CREAT|O_TRUNC), STDOUT_FILENO);
  387. #endif
  388. flag = (option_mask32 & FLAG_z) ? '\0' : '\n';
  389. for (i = 0; i < linecount; i++)
  390. printf("%s%c", lines[i], flag);
  391. fflush_stdout_and_exit(EXIT_SUCCESS);
  392. }