sort.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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 tarball for details.
  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(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 ATTRIBUTE_UNUSED, char **argv)
  259. {
  260. FILE *fp, *outfile = stdout;
  261. char *line, **lines = NULL;
  262. char *str_ignored, *str_o, *str_t;
  263. llist_t *lst_k = NULL;
  264. int i, flag;
  265. int linecount = 0;
  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: maximum one of each */
  270. "k::"; /* -k takes list */
  271. getopt32(argv, OPT_STR, &str_ignored, &str_ignored, &str_o, &lst_k, &str_t);
  272. #if ENABLE_FEATURE_SORT_BIG
  273. if (option_mask32 & FLAG_o) outfile = xfopen(str_o, "w");
  274. if (option_mask32 & FLAG_t) {
  275. if (!str_t[0] || str_t[1])
  276. bb_error_msg_and_die("bad -t parameter");
  277. key_separator = str_t[0];
  278. }
  279. /* parse sort key */
  280. while (lst_k) {
  281. enum {
  282. FLAG_allowed_for_k =
  283. FLAG_n | /* Numeric sort */
  284. FLAG_g | /* Sort using strtod() */
  285. FLAG_M | /* Sort date */
  286. FLAG_b | /* Ignore leading blanks */
  287. FLAG_r | /* Reverse */
  288. FLAG_d | /* Ignore !(isalnum()|isspace()) */
  289. FLAG_f | /* Force uppercase */
  290. FLAG_i | /* Ignore !isprint() */
  291. 0
  292. };
  293. struct sort_key *key = add_key();
  294. char *str_k = llist_pop(&lst_k);
  295. const char *temp2;
  296. i = 0; /* i==0 before comma, 1 after (-k3,6) */
  297. while (*str_k) {
  298. /* Start of range */
  299. /* Cannot use bb_strtou - suffix can be a letter */
  300. key->range[2*i] = str2u(&str_k);
  301. if (*str_k == '.') {
  302. str_k++;
  303. key->range[2*i+1] = str2u(&str_k);
  304. }
  305. while (*str_k) {
  306. if (*str_k == ',' && !i++) {
  307. str_k++;
  308. break;
  309. } /* no else needed: fall through to syntax error
  310. because comma isn't in OPT_STR */
  311. temp2 = strchr(OPT_STR, *str_k);
  312. if (!temp2)
  313. bb_error_msg_and_die("unknown key option");
  314. flag = 1 << (temp2 - OPT_STR);
  315. if (flag & ~FLAG_allowed_for_k)
  316. bb_error_msg_and_die("unknown sort type");
  317. /* b after ',' means strip _trailing_ space */
  318. if (i && flag == FLAG_b) flag = FLAG_bb;
  319. key->flags |= flag;
  320. str_k++;
  321. }
  322. }
  323. }
  324. #endif
  325. /* global b strips leading and trailing spaces */
  326. if (option_mask32 & FLAG_b) option_mask32 |= FLAG_bb;
  327. /* Open input files and read data */
  328. argv += optind;
  329. if (!*argv)
  330. *--argv = (char*)"-";
  331. do {
  332. /* coreutils 6.9 compat: abort on first open error,
  333. * do not continue to next file: */
  334. fp = xfopen_stdin(*argv);
  335. for (;;) {
  336. line = GET_LINE(fp);
  337. if (!line) break;
  338. if (!(linecount & 63))
  339. lines = xrealloc(lines, sizeof(char *) * (linecount + 64));
  340. lines[linecount++] = line;
  341. }
  342. fclose_if_not_stdin(fp);
  343. } while (*++argv);
  344. #if ENABLE_FEATURE_SORT_BIG
  345. /* if no key, perform alphabetic sort */
  346. if (!key_list)
  347. add_key()->range[0] = 1;
  348. /* handle -c */
  349. if (option_mask32 & FLAG_c) {
  350. int j = (option_mask32 & FLAG_u) ? -1 : 0;
  351. for (i = 1; i < linecount; i++)
  352. if (compare_keys(&lines[i-1], &lines[i]) > j) {
  353. fprintf(stderr, "Check line %d\n", i);
  354. return EXIT_FAILURE;
  355. }
  356. return EXIT_SUCCESS;
  357. }
  358. #endif
  359. /* Perform the actual sort */
  360. qsort(lines, linecount, sizeof(char *), compare_keys);
  361. /* handle -u */
  362. if (option_mask32 & FLAG_u) {
  363. flag = 0;
  364. /* coreutils 6.3 drop lines for which only key is the same */
  365. /* -- disabling last-resort compare... */
  366. option_mask32 |= FLAG_s;
  367. for (i = 1; i < linecount; i++) {
  368. if (!compare_keys(&lines[flag], &lines[i]))
  369. free(lines[i]);
  370. else
  371. lines[++flag] = lines[i];
  372. }
  373. if (linecount) linecount = flag+1;
  374. }
  375. /* Print it */
  376. flag = (option_mask32 & FLAG_z) ? '\0' : '\n';
  377. for (i = 0; i < linecount; i++)
  378. fprintf(outfile, "%s%c", lines[i], flag);
  379. fflush_stdout_and_exit(EXIT_SUCCESS);
  380. }