sort.c 17 KB

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