sort.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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 is null 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, i, j;
  55. /* Special case whole string, so we don't have to make a copy */
  56. if (key->range[0] == 1 && !key->range[1] && !key->range[2] && !key->range[3]
  57. && !(flags & (FLAG_b | FLAG_d | FLAG_f | FLAG_i | FLAG_bb))
  58. ) {
  59. return str;
  60. }
  61. /* Find start of key on first pass, end on second pass */
  62. len = strlen(str);
  63. for (j = 0; j < 2; j++) {
  64. if (!key->range[2*j])
  65. end = len;
  66. /* Loop through fields */
  67. else {
  68. end = 0;
  69. for (i = 1; i < key->range[2*j] + j; i++) {
  70. if (key_separator) {
  71. /* Skip body of key and separator */
  72. while (str[end]) {
  73. if (str[end++] == key_separator)
  74. break;
  75. }
  76. } else {
  77. /* Skip leading blanks */
  78. while (isspace(str[end]))
  79. end++;
  80. /* Skip body of key */
  81. while (str[end]) {
  82. if (isspace(str[end]))
  83. break;
  84. end++;
  85. }
  86. }
  87. }
  88. }
  89. if (!j) start = end;
  90. }
  91. /* Strip leading whitespace if necessary */
  92. //XXX: skip_whitespace()
  93. if (flags & FLAG_b)
  94. while (isspace(str[start])) start++;
  95. /* Strip trailing whitespace if necessary */
  96. if (flags & FLAG_bb)
  97. while (end > start && isspace(str[end-1])) end--;
  98. /* Handle offsets on start and end */
  99. if (key->range[3]) {
  100. end += key->range[3] - 1;
  101. if (end > len) end = len;
  102. }
  103. if (key->range[1]) {
  104. start += key->range[1] - 1;
  105. if (start > len) start = len;
  106. }
  107. /* Make the copy */
  108. if (end < start) end = start;
  109. str = xstrndup(str+start, end-start);
  110. /* Handle -d */
  111. if (flags & FLAG_d) {
  112. for (start = end = 0; str[end]; end++)
  113. if (isspace(str[end]) || isalnum(str[end]))
  114. str[start++] = str[end];
  115. str[start] = '\0';
  116. }
  117. /* Handle -i */
  118. if (flags & FLAG_i) {
  119. for (start = end = 0; str[end]; end++)
  120. if (isprint(str[end]))
  121. str[start++] = str[end];
  122. str[start] = '\0';
  123. }
  124. /* Handle -f */
  125. if (flags & FLAG_f)
  126. for (i = 0; str[i]; i++)
  127. str[i] = toupper(str[i]);
  128. return str;
  129. }
  130. static struct sort_key *add_key(void)
  131. {
  132. struct sort_key **pkey = &key_list;
  133. while (*pkey)
  134. pkey = &((*pkey)->next_key);
  135. return *pkey = xzalloc(sizeof(struct sort_key));
  136. }
  137. #define GET_LINE(fp) \
  138. ((option_mask32 & FLAG_z) \
  139. ? bb_get_chunk_from_file(fp, NULL) \
  140. : xmalloc_getline(fp))
  141. #else
  142. #define GET_LINE(fp) xmalloc_getline(fp)
  143. #endif
  144. /* Iterate through keys list and perform comparisons */
  145. static int compare_keys(const void *xarg, const void *yarg)
  146. {
  147. int flags = option_mask32, retval = 0;
  148. char *x, *y;
  149. #if ENABLE_FEATURE_SORT_BIG
  150. struct sort_key *key;
  151. for (key = key_list; !retval && key; key = key->next_key) {
  152. flags = key->flags ? key->flags : option_mask32;
  153. /* Chop out and modify key chunks, handling -dfib */
  154. x = get_key(*(char **)xarg, key, flags);
  155. y = get_key(*(char **)yarg, key, flags);
  156. #else
  157. /* This curly bracket serves no purpose but to match the nesting
  158. level of the for () loop we're not using */
  159. {
  160. x = *(char **)xarg;
  161. y = *(char **)yarg;
  162. #endif
  163. /* Perform actual comparison */
  164. switch (flags & 7) {
  165. default:
  166. bb_error_msg_and_die("unknown sort type");
  167. break;
  168. /* Ascii sort */
  169. case 0:
  170. #if ENABLE_LOCALE_SUPPORT
  171. retval = strcoll(x, y);
  172. #else
  173. retval = strcmp(x, y);
  174. #endif
  175. break;
  176. #if ENABLE_FEATURE_SORT_BIG
  177. case FLAG_g: {
  178. char *xx, *yy;
  179. double dx = strtod(x, &xx);
  180. double dy = strtod(y, &yy);
  181. /* not numbers < NaN < -infinity < numbers < +infinity) */
  182. if (x == xx)
  183. retval = (y == yy ? 0 : -1);
  184. else if (y == yy)
  185. retval = 1;
  186. /* Check for isnan */
  187. else if (dx != dx)
  188. retval = (dy != dy) ? 0 : -1;
  189. else if (dy != dy)
  190. retval = 1;
  191. /* Check for infinity. Could underflow, but it avoids libm. */
  192. else if (1.0 / dx == 0.0) {
  193. if (dx < 0)
  194. retval = (1.0 / dy == 0.0 && dy < 0) ? 0 : -1;
  195. else
  196. retval = (1.0 / dy == 0.0 && dy > 0) ? 0 : 1;
  197. } else if (1.0 / dy == 0.0)
  198. retval = (dy < 0) ? 1 : -1;
  199. else
  200. retval = (dx > dy) ? 1 : ((dx < dy) ? -1 : 0);
  201. break;
  202. }
  203. case FLAG_M: {
  204. struct tm thyme;
  205. int dx;
  206. char *xx, *yy;
  207. xx = strptime(x, "%b", &thyme);
  208. dx = thyme.tm_mon;
  209. yy = strptime(y, "%b", &thyme);
  210. if (!xx)
  211. retval = (!yy) ? 0 : -1;
  212. else if (!yy)
  213. retval = 1;
  214. else
  215. retval = (dx == thyme.tm_mon) ? 0 : dx - thyme.tm_mon;
  216. break;
  217. }
  218. /* Full floating point version of -n */
  219. case FLAG_n: {
  220. double dx = atof(x);
  221. double dy = atof(y);
  222. retval = (dx > dy) ? 1 : ((dx < dy) ? -1 : 0);
  223. break;
  224. }
  225. } /* switch */
  226. /* Free key copies. */
  227. if (x != *(char **)xarg) free(x);
  228. if (y != *(char **)yarg) free(y);
  229. /* if (retval) break; - done by for () anyway */
  230. #else
  231. /* Integer version of -n for tiny systems */
  232. case FLAG_n:
  233. retval = atoi(x) - atoi(y);
  234. break;
  235. } /* switch */
  236. #endif
  237. } /* for */
  238. /* Perform fallback sort if necessary */
  239. if (!retval && !(option_mask32 & FLAG_s))
  240. retval = strcmp(*(char **)xarg, *(char **)yarg);
  241. if (flags & FLAG_r) return -retval;
  242. return retval;
  243. }
  244. #if ENABLE_FEATURE_SORT_BIG
  245. static unsigned str2u(char **str)
  246. {
  247. unsigned long lu;
  248. if (!isdigit((*str)[0]))
  249. bb_error_msg_and_die("bad field specification");
  250. lu = strtoul(*str, str, 10);
  251. if ((sizeof(long) > sizeof(int) && lu > INT_MAX) || !lu)
  252. bb_error_msg_and_die("bad field specification");
  253. return lu;
  254. }
  255. #endif
  256. int sort_main(int argc, char **argv);
  257. int sort_main(int argc, char **argv)
  258. {
  259. FILE *fp, *outfile = stdout;
  260. char *line, **lines = NULL;
  261. char *str_ignored, *str_o, *str_t;
  262. llist_t *lst_k = NULL;
  263. int i, flag;
  264. int linecount = 0;
  265. xfunc_error_retval = 2;
  266. /* Parse command line options */
  267. /* -o and -t can be given at most once */
  268. opt_complementary = "o--o:t--t:" /* -t, -o: maximum one of each */
  269. "k::"; /* -k takes list */
  270. getopt32(argv, OPT_STR, &str_ignored, &str_ignored, &str_o, &lst_k, &str_t);
  271. #if ENABLE_FEATURE_SORT_BIG
  272. if (option_mask32 & FLAG_o) outfile = xfopen(str_o, "w");
  273. if (option_mask32 & FLAG_t) {
  274. if (!str_t[0] || str_t[1])
  275. bb_error_msg_and_die("bad -t parameter");
  276. key_separator = str_t[0];
  277. }
  278. /* parse sort key */
  279. while (lst_k) {
  280. enum {
  281. FLAG_allowed_for_k =
  282. FLAG_n | /* Numeric sort */
  283. FLAG_g | /* Sort using strtod() */
  284. FLAG_M | /* Sort date */
  285. FLAG_b | /* Ignore leading blanks */
  286. FLAG_r | /* Reverse */
  287. FLAG_d | /* Ignore !(isalnum()|isspace()) */
  288. FLAG_f | /* Force uppercase */
  289. FLAG_i | /* Ignore !isprint() */
  290. 0
  291. };
  292. struct sort_key *key = add_key();
  293. char *str_k = lst_k->data;
  294. const char *temp2;
  295. i = 0; /* i==0 before comma, 1 after (-k3,6) */
  296. while (*str_k) {
  297. /* Start of range */
  298. /* Cannot use bb_strtou - suffix can be a letter */
  299. key->range[2*i] = str2u(&str_k);
  300. if (*str_k == '.') {
  301. str_k++;
  302. key->range[2*i+1] = str2u(&str_k);
  303. }
  304. while (*str_k) {
  305. if (*str_k == ',' && !i++) {
  306. str_k++;
  307. break;
  308. } /* no else needed: fall through to syntax error
  309. because comma isn't in OPT_STR */
  310. temp2 = strchr(OPT_STR, *str_k);
  311. if (!temp2)
  312. bb_error_msg_and_die("unknown key option");
  313. flag = 1 << (temp2 - OPT_STR);
  314. if (flag & ~FLAG_allowed_for_k)
  315. bb_error_msg_and_die("unknown sort type");
  316. /* b after ',' means strip _trailing_ space */
  317. if (i && flag == FLAG_b) flag = FLAG_bb;
  318. key->flags |= flag;
  319. str_k++;
  320. }
  321. }
  322. /* leaking lst_k... */
  323. lst_k = lst_k->link;
  324. }
  325. #endif
  326. /* global b strips leading and trailing spaces */
  327. if (option_mask32 & FLAG_b) option_mask32 |= FLAG_bb;
  328. /* Open input files and read data */
  329. for (i = argv[optind] ? optind : optind-1; argv[i]; i++) {
  330. fp = stdin;
  331. if (i >= optind && NOT_LONE_DASH(argv[i]))
  332. fp = xfopen(argv[i], "r");
  333. for (;;) {
  334. line = GET_LINE(fp);
  335. if (!line) break;
  336. if (!(linecount & 63))
  337. lines = xrealloc(lines, sizeof(char *) * (linecount + 64));
  338. lines[linecount++] = line;
  339. }
  340. fclose(fp);
  341. }
  342. #if ENABLE_FEATURE_SORT_BIG
  343. /* if no key, perform alphabetic sort */
  344. if (!key_list)
  345. add_key()->range[0] = 1;
  346. /* handle -c */
  347. if (option_mask32 & FLAG_c) {
  348. int j = (option_mask32 & FLAG_u) ? -1 : 0;
  349. for (i = 1; i < linecount; i++)
  350. if (compare_keys(&lines[i-1], &lines[i]) > j) {
  351. fprintf(stderr, "Check line %d\n", i);
  352. return 1;
  353. }
  354. return 0;
  355. }
  356. #endif
  357. /* Perform the actual sort */
  358. qsort(lines, linecount, sizeof(char *), compare_keys);
  359. /* handle -u */
  360. if (option_mask32 & FLAG_u) {
  361. flag = 0;
  362. /* coreutils 6.3 drop lines for which only key is the same */
  363. /* -- disabling last-resort compare... */
  364. option_mask32 |= FLAG_s;
  365. for (i = 1; i < linecount; i++) {
  366. if (!compare_keys(&lines[flag], &lines[i]))
  367. free(lines[i]);
  368. else
  369. lines[++flag] = lines[i];
  370. }
  371. if (linecount) linecount = flag+1;
  372. }
  373. /* Print it */
  374. for (i = 0; i < linecount; i++)
  375. fprintf(outfile, "%s\n", lines[i]);
  376. fflush_stdout_and_exit(EXIT_SUCCESS);
  377. }