sort.c 10 KB

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