sort.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  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. //config:config SORT
  15. //config: bool "sort (7.7 kb)"
  16. //config: default y
  17. //config: help
  18. //config: sort is used to sort lines of text in specified files.
  19. //config:
  20. //config:config FEATURE_SORT_BIG
  21. //config: bool "Full SuSv3 compliant sort (support -ktcbdfioghM)"
  22. //config: default y
  23. //config: depends on SORT
  24. //config: help
  25. //config: Without this, sort only supports -rusz, and an integer version
  26. //config: of -n. Selecting this adds sort keys, floating point support, and
  27. //config: more. This adds a little over 3k to a nonstatic build on x86.
  28. //config:
  29. //config: The SuSv3 sort standard is available at:
  30. //config: http://www.opengroup.org/onlinepubs/007904975/utilities/sort.html
  31. //config:
  32. //config:config FEATURE_SORT_OPTIMIZE_MEMORY
  33. //config: bool "Use less memory (but might be slower)"
  34. //config: default n # defaults to N since we are size-paranoid tribe
  35. //config: depends on SORT
  36. //config: help
  37. //config: Attempt to use less memory (by storing only one copy
  38. //config: of duplicated lines, and such). Useful if you work on huge files.
  39. //applet:IF_SORT(APPLET_NOEXEC(sort, sort, BB_DIR_USR_BIN, BB_SUID_DROP, sort))
  40. //kbuild:lib-$(CONFIG_SORT) += sort.o
  41. //usage:#define sort_trivial_usage
  42. //usage: "[-nru"
  43. //usage: IF_FEATURE_SORT_BIG("ghMcszbdfiokt] [-o FILE] [-k START[.OFS][OPTS][,END[.OFS][OPTS]] [-t CHAR")
  44. //usage: "] [FILE]..."
  45. //usage:#define sort_full_usage "\n\n"
  46. //usage: "Sort lines of text\n"
  47. //usage: IF_FEATURE_SORT_BIG(
  48. //usage: "\n -o FILE Output to FILE"
  49. //usage: "\n -c Check whether input is sorted"
  50. //usage: "\n -b Ignore leading blanks"
  51. //usage: "\n -f Ignore case"
  52. //usage: "\n -i Ignore unprintable characters"
  53. //usage: "\n -d Dictionary order (blank or alphanumeric only)"
  54. //usage: )
  55. //-h, --human-numeric-sort: compare human readable numbers (e.g., 2K 1G)
  56. //usage: "\n -n Sort numbers"
  57. //usage: IF_FEATURE_SORT_BIG(
  58. //usage: "\n -g General numerical sort"
  59. //usage: "\n -h Sort human readable numbers (2K 1G)"
  60. //usage: "\n -M Sort month"
  61. //usage: "\n -V Sort version"
  62. //usage: "\n -t CHAR Field separator"
  63. //usage: "\n -k N[,M] Sort by Nth field"
  64. //usage: )
  65. //usage: "\n -r Reverse sort order"
  66. //usage: "\n -s Stable (don't sort ties alphabetically)"
  67. //usage: "\n -u Suppress duplicate lines"
  68. //usage: "\n -z NUL terminated input and output"
  69. ///////: "\n -m Ignored for GNU compatibility"
  70. ///////: "\n -S BUFSZ Ignored for GNU compatibility"
  71. ///////: "\n -T TMPDIR Ignored for GNU compatibility"
  72. //usage:
  73. //usage:#define sort_example_usage
  74. //usage: "$ echo -e \"e\\nf\\nb\\nd\\nc\\na\" | sort\n"
  75. //usage: "a\n"
  76. //usage: "b\n"
  77. //usage: "c\n"
  78. //usage: "d\n"
  79. //usage: "e\n"
  80. //usage: "f\n"
  81. //usage: IF_FEATURE_SORT_BIG(
  82. //usage: "$ echo -e \"c 3\\nb 2\\nd 2\" | $SORT -k 2,2n -k 1,1r\n"
  83. //usage: "d 2\n"
  84. //usage: "b 2\n"
  85. //usage: "c 3\n"
  86. //usage: )
  87. //usage: ""
  88. #include "libbb.h"
  89. /* These are sort types */
  90. enum {
  91. FLAG_n = 1 << 0, /* Numeric sort */
  92. FLAG_g = 1 << 1, /* Sort using strtod() */
  93. FLAG_h = 1 << 2, /* Sort using strtod(), plus KMGT suffixes */
  94. FLAG_M = 1 << 3, /* Sort date */
  95. FLAG_V = 1 << 4, /* Sort version */
  96. /* ucsz apply to root level only, not keys. b at root level implies bb */
  97. FLAG_u = 1 << 5, /* Unique */
  98. FLAG_c = 1 << 6, /* Check: no output, exit(!ordered) */
  99. FLAG_s = 1 << 7, /* Stable sort, no ascii fallback at end */
  100. FLAG_z = 1 << 8, /* Input and output is NUL terminated, not \n */
  101. /* These can be applied to search keys, the previous four can't */
  102. FLAG_b = 1 << 9, /* Ignore leading blanks */
  103. FLAG_r = 1 << 10, /* Reverse */
  104. FLAG_d = 1 << 11, /* Ignore !(isalnum()|isspace()) */
  105. FLAG_f = 1 << 12, /* Force uppercase */
  106. FLAG_i = 1 << 13, /* Ignore !isprint() */
  107. FLAG_m = 1 << 14, /* ignored: merge already sorted files; do not sort */
  108. FLAG_S = 1 << 15, /* ignored: -S, --buffer-size=SIZE */
  109. FLAG_T = 1 << 16, /* ignored: -T, --temporary-directory=DIR */
  110. FLAG_o = 1 << 17,
  111. FLAG_k = 1 << 18,
  112. FLAG_t = 1 << 19,
  113. FLAG_bb = 0x80000000, /* Ignore trailing blanks */
  114. FLAG_no_tie_break = 0x40000000,
  115. };
  116. static const char sort_opt_str[] ALIGN1 = "^"
  117. "nghMVucszbrdfimS:T:o:k:*t:"
  118. "\0" "o--o:t--t"/*-t, -o: at most one of each*/;
  119. /*
  120. * OPT_STR must not be string literal, needs to have stable address:
  121. * code uses "strchr(OPT_STR,c) - OPT_STR" idiom.
  122. */
  123. #define OPT_STR (sort_opt_str + 1)
  124. #if ENABLE_FEATURE_SORT_BIG
  125. static char key_separator;
  126. static struct sort_key {
  127. struct sort_key *next_key; /* linked list */
  128. unsigned range[4]; /* start word, start char, end word, end char */
  129. unsigned flags;
  130. } *key_list;
  131. /* This is a NOEXEC applet. Be very careful! */
  132. static char *get_key(char *str, struct sort_key *key, int flags)
  133. {
  134. int start = start; /* for compiler */
  135. int end;
  136. int len, j;
  137. unsigned i;
  138. /* Special case whole string, so we don't have to make a copy */
  139. if (key->range[0] == 1 && !key->range[1] && !key->range[2] && !key->range[3]
  140. && !(flags & (FLAG_b | FLAG_d | FLAG_f | FLAG_i | FLAG_bb))
  141. ) {
  142. return str;
  143. }
  144. /* Find start of key on first pass, end on second pass */
  145. len = strlen(str);
  146. for (j = 0; j < 2; j++) {
  147. if (!key->range[2*j])
  148. end = len;
  149. /* Loop through fields */
  150. else {
  151. unsigned char ch = 0;
  152. end = 0;
  153. for (i = 1; i < key->range[2*j] + j; i++) {
  154. if (key_separator) {
  155. /* Skip body of key and separator */
  156. while ((ch = str[end]) != '\0') {
  157. end++;
  158. if (ch == key_separator)
  159. break;
  160. }
  161. } else {
  162. /* Skip leading blanks */
  163. while (isspace(str[end]))
  164. end++;
  165. /* Skip body of key */
  166. while (str[end] != '\0') {
  167. if (isspace(str[end]))
  168. break;
  169. end++;
  170. }
  171. }
  172. }
  173. /* Remove last delim: "abc:def:" => "abc:def" */
  174. if (j && ch) {
  175. //if (str[end-1] != key_separator)
  176. // bb_error_msg(_and_die("BUG! "
  177. // "str[start:%d,end:%d]:'%.*s'",
  178. // start, end, (int)(end-start), &str[start]);
  179. end--;
  180. }
  181. }
  182. if (!j) start = end;
  183. }
  184. /* Strip leading whitespace if necessary */
  185. if (flags & FLAG_b)
  186. /* not using skip_whitespace() for speed */
  187. while (isspace(str[start])) start++;
  188. /* Strip trailing whitespace if necessary */
  189. if (flags & FLAG_bb)
  190. while (end > start && isspace(str[end-1])) end--;
  191. /* -kSTART,N.ENDCHAR: honor ENDCHAR (1-based) */
  192. if (key->range[3]) {
  193. end = key->range[3];
  194. if (end > len) end = len;
  195. }
  196. /* -kN.STARTCHAR[,...]: honor STARTCHAR (1-based) */
  197. if (key->range[1]) {
  198. start += key->range[1] - 1;
  199. if (start > len) start = len;
  200. }
  201. /* Make the copy */
  202. if (end < start)
  203. end = start;
  204. str = xstrndup(str+start, end-start);
  205. /* Handle -d */
  206. if (flags & FLAG_d) {
  207. for (start = end = 0; str[end]; end++)
  208. if (isspace(str[end]) || isalnum(str[end]))
  209. str[start++] = str[end];
  210. str[start] = '\0';
  211. }
  212. /* Handle -i */
  213. if (flags & FLAG_i) {
  214. for (start = end = 0; str[end]; end++)
  215. if (isprint_asciionly(str[end]))
  216. str[start++] = str[end];
  217. str[start] = '\0';
  218. }
  219. /* Handle -f */
  220. if (flags & FLAG_f)
  221. for (i = 0; str[i]; i++)
  222. str[i] = toupper(str[i]);
  223. return str;
  224. }
  225. static struct sort_key *add_key(void)
  226. {
  227. struct sort_key **pkey = &key_list;
  228. while (*pkey)
  229. pkey = &((*pkey)->next_key);
  230. return *pkey = xzalloc(sizeof(struct sort_key));
  231. }
  232. #define GET_LINE(fp) \
  233. ((option_mask32 & FLAG_z) \
  234. ? bb_get_chunk_from_file(fp, NULL) \
  235. : xmalloc_fgetline(fp))
  236. #else
  237. #define GET_LINE(fp) xmalloc_fgetline(fp)
  238. #endif
  239. #if ENABLE_FEATURE_SORT_BIG
  240. static int scale_suffix(const char *tail)
  241. {
  242. static const char suffix[] ALIGN1 = "kmgtpezy";
  243. const char *s;
  244. int n;
  245. if (!tail[0])
  246. return -1;
  247. s = strchr(suffix, tail[0] | 0x20);
  248. if (!s)
  249. return -1;
  250. n = s - suffix;
  251. if (n != 0 && tail[0] >= 'a')
  252. return -1; /* mg... not accepted, only MG... */
  253. return n;
  254. }
  255. #endif
  256. /* Iterate through keys list and perform comparisons */
  257. static int compare_keys(const void *xarg, const void *yarg)
  258. {
  259. int flags = option_mask32, retval = 0;
  260. char *x, *y;
  261. #if ENABLE_FEATURE_SORT_BIG
  262. struct sort_key *key;
  263. for (key = key_list; !retval && key; key = key->next_key) {
  264. flags = key->flags ? key->flags : option_mask32;
  265. /* Chop out and modify key chunks, handling -dfib */
  266. x = get_key(*(char **)xarg, key, flags);
  267. y = get_key(*(char **)yarg, key, flags);
  268. #else
  269. /* This curly bracket serves no purpose but to match the nesting
  270. * level of the for () loop we're not using */
  271. {
  272. x = *(char **)xarg;
  273. y = *(char **)yarg;
  274. #endif
  275. /* Perform actual comparison */
  276. switch (flags & (FLAG_n | FLAG_g | FLAG_h | FLAG_M | FLAG_V)) {
  277. default:
  278. bb_simple_error_msg_and_die("unknown sort type");
  279. break;
  280. #if defined(HAVE_STRVERSCMP) && HAVE_STRVERSCMP == 1
  281. case FLAG_V:
  282. retval = strverscmp(x, y);
  283. break;
  284. #endif
  285. /* Ascii sort */
  286. case 0:
  287. #if ENABLE_LOCALE_SUPPORT
  288. retval = strcoll(x, y);
  289. #else
  290. retval = strcmp(x, y);
  291. #endif
  292. break;
  293. #if ENABLE_FEATURE_SORT_BIG
  294. case FLAG_g:
  295. case FLAG_h: {
  296. char *xx, *yy;
  297. //TODO: needs setlocale(LC_NUMERIC, "C")?
  298. double dx = strtod(x, &xx);
  299. double dy = strtod(y, &yy);
  300. /* not numbers < NaN < -infinity < numbers < +infinity) */
  301. if (x == xx)
  302. retval = (y == yy ? 0 : -1);
  303. else if (y == yy)
  304. retval = 1;
  305. /* Check for isnan */
  306. else if (dx != dx)
  307. retval = (dy != dy) ? 0 : -1;
  308. else if (dy != dy)
  309. retval = 1;
  310. else {
  311. if (flags & FLAG_h) {
  312. int xs = scale_suffix(xx);
  313. int ys = scale_suffix(yy);
  314. if (xs != ys) {
  315. retval = xs - ys;
  316. break;
  317. }
  318. }
  319. /* Check for infinity. Could underflow, but it avoids libm. */
  320. if (1.0 / dx == 0.0) {
  321. if (dx < 0)
  322. retval = (1.0 / dy == 0.0 && dy < 0) ? 0 : -1;
  323. else
  324. retval = (1.0 / dy == 0.0 && dy > 0) ? 0 : 1;
  325. } else if (1.0 / dy == 0.0)
  326. retval = (dy < 0) ? 1 : -1;
  327. else
  328. retval = (dx > dy) ? 1 : ((dx < dy) ? -1 : 0);
  329. }
  330. break;
  331. }
  332. case FLAG_M: {
  333. struct tm thyme;
  334. int dx;
  335. char *xx, *yy;
  336. xx = strptime(skip_whitespace(x), "%b", &thyme);
  337. dx = thyme.tm_mon;
  338. yy = strptime(skip_whitespace(y), "%b", &thyme);
  339. if (!xx)
  340. retval = (!yy) ? 0 : -1;
  341. else if (!yy)
  342. retval = 1;
  343. else
  344. retval = dx - thyme.tm_mon;
  345. break;
  346. }
  347. /* Full floating point version of -n */
  348. case FLAG_n: {
  349. double dx = atof(x);
  350. double dy = atof(y);
  351. retval = (dx > dy) ? 1 : ((dx < dy) ? -1 : 0);
  352. break;
  353. }
  354. } /* switch */
  355. /* Free key copies. */
  356. if (x != *(char **)xarg) free(x);
  357. if (y != *(char **)yarg) free(y);
  358. /* if (retval) break; - done by for () anyway */
  359. #else
  360. /* Integer version of -n for tiny systems */
  361. case FLAG_n:
  362. retval = atoi(x) - atoi(y);
  363. break;
  364. } /* switch */
  365. #endif
  366. } /* for */
  367. if (retval == 0) {
  368. /* So far lines are "the same" */
  369. if (option_mask32 & FLAG_s) {
  370. /* "Stable sort": later line is "greater than",
  371. * IOW: do not allow qsort() to swap equal lines.
  372. */
  373. uint32_t *p32;
  374. uint32_t x32, y32;
  375. char *line;
  376. unsigned len;
  377. line = *(char**)xarg;
  378. len = (strlen(line) + 4) & (~3u);
  379. p32 = (void*)(line + len);
  380. x32 = *p32;
  381. line = *(char**)yarg;
  382. len = (strlen(line) + 4) & (~3u);
  383. p32 = (void*)(line + len);
  384. y32 = *p32;
  385. /* If x > y, 1, else -1 */
  386. retval = (x32 > y32) * 2 - 1;
  387. /* Here, -r has no effect! */
  388. return retval;
  389. }
  390. if (!(option_mask32 & FLAG_no_tie_break)) {
  391. /* fallback sort */
  392. flags = option_mask32;
  393. retval = strcmp(*(char **)xarg, *(char **)yarg);
  394. }
  395. }
  396. if (flags & FLAG_r)
  397. return -retval;
  398. return retval;
  399. }
  400. #if ENABLE_FEATURE_SORT_BIG
  401. static unsigned str2u(char **str)
  402. {
  403. unsigned long lu;
  404. if (!isdigit((*str)[0]))
  405. bb_simple_error_msg_and_die("bad field specification");
  406. lu = strtoul(*str, str, 10);
  407. if ((sizeof(long) > sizeof(int) && lu > INT_MAX) || !lu)
  408. bb_simple_error_msg_and_die("bad field specification");
  409. return lu;
  410. }
  411. #endif
  412. int sort_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  413. int sort_main(int argc UNUSED_PARAM, char **argv)
  414. {
  415. char **lines;
  416. char *str_ignored, *str_o, *str_t;
  417. llist_t *lst_k = NULL;
  418. int i;
  419. int linecount;
  420. unsigned opts;
  421. #if ENABLE_FEATURE_SORT_OPTIMIZE_MEMORY
  422. bool can_drop_dups;
  423. size_t prev_len = 0;
  424. char *prev_line = (char*) "";
  425. /* Postpone optimizing if the input is small, < 16k lines:
  426. * even just free()ing duplicate lines takes time.
  427. */
  428. size_t count_to_optimize_dups = 0x3fff;
  429. #endif
  430. xfunc_error_retval = 2;
  431. /* Parse command line options */
  432. opts = getopt32(argv,
  433. sort_opt_str,
  434. &str_ignored, &str_ignored, &str_o, &lst_k, &str_t
  435. );
  436. #if ENABLE_FEATURE_SORT_OPTIMIZE_MEMORY
  437. /* Can drop dups only if -u but no "complicating" options,
  438. * IOW: if we do a full line compares. Safe options:
  439. * -o FILE Output to FILE
  440. * -z Lines are terminated by NUL, not newline
  441. * -r Reverse sort order
  442. * -s Stable (don't sort ties alphabetically)
  443. * Not sure about these:
  444. * -b Ignore leading blanks
  445. * -f Ignore case
  446. * -i Ignore unprintable characters
  447. * -d Dictionary order (blank or alphanumeric only)
  448. * -n Sort numbers
  449. * -g General numerical sort
  450. * -M Sort month
  451. */
  452. can_drop_dups = ((opts & ~(FLAG_o|FLAG_z|FLAG_r|FLAG_s)) == FLAG_u);
  453. /* Stable sort needs every line to be uniquely allocated,
  454. * disable optimization to reuse strings:
  455. */
  456. if (opts & FLAG_s)
  457. count_to_optimize_dups = (size_t)-1L;
  458. #endif
  459. /* global b strips leading and trailing spaces */
  460. if (opts & FLAG_b)
  461. option_mask32 |= FLAG_bb;
  462. #if ENABLE_FEATURE_SORT_BIG
  463. if (opts & FLAG_t) {
  464. if (!str_t[0] || str_t[1])
  465. bb_simple_error_msg_and_die("bad -t parameter");
  466. key_separator = str_t[0];
  467. }
  468. /* note: below this point we use option_mask32, not opts,
  469. * since that reduces register pressure and makes code smaller */
  470. /* Parse sort key */
  471. while (lst_k) {
  472. enum {
  473. FLAG_allowed_for_k =
  474. FLAG_n | /* Numeric sort */
  475. FLAG_g | /* Sort using strtod() */
  476. FLAG_h | /* Sort using strtod(), plus KMGT suffixes */
  477. FLAG_M | /* Sort date */
  478. FLAG_b | /* Ignore leading blanks */
  479. FLAG_r | /* Reverse */
  480. FLAG_d | /* Ignore !(isalnum()|isspace()) */
  481. FLAG_f | /* Force uppercase */
  482. FLAG_i | /* Ignore !isprint() */
  483. 0
  484. };
  485. struct sort_key *key = add_key();
  486. char *str_k = llist_pop(&lst_k);
  487. i = 0; /* i==0 before comma, 1 after (-k3,6) */
  488. while (*str_k) {
  489. /* Start of range */
  490. /* Cannot use bb_strtou - suffix can be a letter */
  491. key->range[2*i] = str2u(&str_k);
  492. if (*str_k == '.') {
  493. str_k++;
  494. key->range[2*i+1] = str2u(&str_k);
  495. }
  496. while (*str_k) {
  497. int flag;
  498. const char *idx;
  499. if (*str_k == ',' && !i++) {
  500. str_k++;
  501. break;
  502. } /* no else needed: fall through to syntax error
  503. because comma isn't in OPT_STR */
  504. idx = strchr(OPT_STR, *str_k);
  505. if (!idx)
  506. bb_simple_error_msg_and_die("unknown key option");
  507. flag = 1 << (idx - OPT_STR);
  508. if (flag & ~FLAG_allowed_for_k)
  509. bb_simple_error_msg_and_die("unknown sort type");
  510. /* b after ',' means strip _trailing_ space */
  511. if (i && flag == FLAG_b)
  512. flag = FLAG_bb;
  513. key->flags |= flag;
  514. str_k++;
  515. }
  516. }
  517. }
  518. #endif
  519. /* Open input files and read data */
  520. argv += optind;
  521. if (!*argv)
  522. *--argv = (char*)"-";
  523. linecount = 0;
  524. lines = NULL;
  525. do {
  526. /* coreutils 6.9 compat: abort on first open error,
  527. * do not continue to next file: */
  528. FILE *fp = xfopen_stdin(*argv);
  529. for (;;) {
  530. char *line = GET_LINE(fp);
  531. if (!line)
  532. break;
  533. #if ENABLE_FEATURE_SORT_OPTIMIZE_MEMORY
  534. if (count_to_optimize_dups != 0)
  535. count_to_optimize_dups--;
  536. if (count_to_optimize_dups == 0) {
  537. size_t len;
  538. char *new_line;
  539. /* On kernel/linux/arch/ *.[ch] files,
  540. * this reduces memory usage by 6%.
  541. * yes | head -99999999 | sort
  542. * goes down from 1900Mb to 380 Mb.
  543. */
  544. len = strlen(line);
  545. if (len <= prev_len) {
  546. new_line = prev_line + (prev_len - len);
  547. if (strcmp(line, new_line) == 0) {
  548. /* it's a tail of the prev line */
  549. if (can_drop_dups && prev_len == len) {
  550. /* it's identical to prev line */
  551. free(line);
  552. continue;
  553. }
  554. free(line);
  555. line = new_line;
  556. /* continue using longer prev_line
  557. * for future tail tests.
  558. */
  559. goto skip;
  560. }
  561. }
  562. prev_len = len;
  563. prev_line = line;
  564. skip: ;
  565. }
  566. #else
  567. //TODO: lighter version which only drops total dups if can_drop_dups == true
  568. #endif
  569. lines = xrealloc_vector(lines, 6, linecount);
  570. lines[linecount++] = line;
  571. }
  572. fclose_if_not_stdin(fp);
  573. } while (*++argv);
  574. #if ENABLE_FEATURE_SORT_BIG
  575. /* If no key, perform alphabetic sort */
  576. if (!key_list)
  577. add_key()->range[0] = 1;
  578. /* Handle -c */
  579. if (option_mask32 & FLAG_c) {
  580. int j = (option_mask32 & FLAG_u) ? -1 : 0;
  581. for (i = 1; i < linecount; i++) {
  582. if (compare_keys(&lines[i-1], &lines[i]) > j) {
  583. fprintf(stderr, "Check line %u\n", i);
  584. return EXIT_FAILURE;
  585. }
  586. }
  587. return EXIT_SUCCESS;
  588. }
  589. #endif
  590. /* For stable sort, store original line position beyond terminating NUL */
  591. if (option_mask32 & FLAG_s) {
  592. for (i = 0; i < linecount; i++) {
  593. uint32_t *p32;
  594. char *line;
  595. unsigned len;
  596. line = lines[i];
  597. len = (strlen(line) + 4) & (~3u);
  598. lines[i] = line = xrealloc(line, len + 4);
  599. p32 = (void*)(line + len);
  600. *p32 = i;
  601. }
  602. /*option_mask32 |= FLAG_no_tie_break;*/
  603. /* ^^^redundant: if FLAG_s, compare_keys() does no tie break */
  604. }
  605. /* Perform the actual sort */
  606. qsort(lines, linecount, sizeof(lines[0]), compare_keys);
  607. /* Handle -u */
  608. if (option_mask32 & FLAG_u) {
  609. int j = 0;
  610. /* coreutils 6.3 drop lines for which only key is the same:
  611. * - disabling last-resort compare, or else compare_keys()
  612. * will be the same only for completely identical lines
  613. * - disabling -s (same reasons)
  614. */
  615. option_mask32 = (option_mask32 | FLAG_no_tie_break) & (~FLAG_s);
  616. for (i = 1; i < linecount; i++) {
  617. if (compare_keys(&lines[j], &lines[i]) == 0)
  618. free(lines[i]);
  619. else
  620. lines[++j] = lines[i];
  621. }
  622. if (linecount)
  623. linecount = j+1;
  624. }
  625. /* Print it */
  626. #if ENABLE_FEATURE_SORT_BIG
  627. /* Open output file _after_ we read all input ones */
  628. if (option_mask32 & FLAG_o)
  629. xmove_fd(xopen(str_o, O_WRONLY|O_CREAT|O_TRUNC), STDOUT_FILENO);
  630. #endif
  631. {
  632. int ch = (option_mask32 & FLAG_z) ? '\0' : '\n';
  633. for (i = 0; i < linecount; i++)
  634. printf("%s%c", lines[i], ch);
  635. }
  636. fflush_stdout_and_exit_SUCCESS();
  637. }