sort.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  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[.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 -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 NUL terminated input and output"
  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. //TODO: needs setlocale(LC_NUMERIC, "C")?
  278. double dx = strtod(x, &xx);
  279. double dy = strtod(y, &yy);
  280. /* not numbers < NaN < -infinity < numbers < +infinity) */
  281. if (x == xx)
  282. retval = (y == yy ? 0 : -1);
  283. else if (y == yy)
  284. retval = 1;
  285. /* Check for isnan */
  286. else if (dx != dx)
  287. retval = (dy != dy) ? 0 : -1;
  288. else if (dy != dy)
  289. retval = 1;
  290. /* Check for infinity. Could underflow, but it avoids libm. */
  291. else if (1.0 / dx == 0.0) {
  292. if (dx < 0)
  293. retval = (1.0 / dy == 0.0 && dy < 0) ? 0 : -1;
  294. else
  295. retval = (1.0 / dy == 0.0 && dy > 0) ? 0 : 1;
  296. } else if (1.0 / dy == 0.0)
  297. retval = (dy < 0) ? 1 : -1;
  298. else
  299. retval = (dx > dy) ? 1 : ((dx < dy) ? -1 : 0);
  300. break;
  301. }
  302. case FLAG_M: {
  303. struct tm thyme;
  304. int dx;
  305. char *xx, *yy;
  306. xx = strptime(x, "%b", &thyme);
  307. dx = thyme.tm_mon;
  308. yy = strptime(y, "%b", &thyme);
  309. if (!xx)
  310. retval = (!yy) ? 0 : -1;
  311. else if (!yy)
  312. retval = 1;
  313. else
  314. retval = dx - thyme.tm_mon;
  315. break;
  316. }
  317. /* Full floating point version of -n */
  318. case FLAG_n: {
  319. double dx = atof(x);
  320. double dy = atof(y);
  321. retval = (dx > dy) ? 1 : ((dx < dy) ? -1 : 0);
  322. break;
  323. }
  324. } /* switch */
  325. /* Free key copies. */
  326. if (x != *(char **)xarg) free(x);
  327. if (y != *(char **)yarg) free(y);
  328. /* if (retval) break; - done by for () anyway */
  329. #else
  330. /* Integer version of -n for tiny systems */
  331. case FLAG_n:
  332. retval = atoi(x) - atoi(y);
  333. break;
  334. } /* switch */
  335. #endif
  336. } /* for */
  337. if (retval == 0) {
  338. /* So far lines are "the same" */
  339. if (option_mask32 & FLAG_s) {
  340. /* "Stable sort": later line is "greater than",
  341. * IOW: do not allow qsort() to swap equal lines.
  342. */
  343. uint32_t *p32;
  344. uint32_t x32, y32;
  345. char *line;
  346. unsigned len;
  347. line = *(char**)xarg;
  348. len = (strlen(line) + 4) & (~3u);
  349. p32 = (void*)(line + len);
  350. x32 = *p32;
  351. line = *(char**)yarg;
  352. len = (strlen(line) + 4) & (~3u);
  353. p32 = (void*)(line + len);
  354. y32 = *p32;
  355. /* If x > y, 1, else -1 */
  356. retval = (x32 > y32) * 2 - 1;
  357. } else
  358. if (!(option_mask32 & FLAG_no_tie_break)) {
  359. /* fallback sort */
  360. flags = option_mask32;
  361. retval = strcmp(*(char **)xarg, *(char **)yarg);
  362. }
  363. }
  364. if (flags & FLAG_r)
  365. return -retval;
  366. return retval;
  367. }
  368. #if ENABLE_FEATURE_SORT_BIG
  369. static unsigned str2u(char **str)
  370. {
  371. unsigned long lu;
  372. if (!isdigit((*str)[0]))
  373. bb_simple_error_msg_and_die("bad field specification");
  374. lu = strtoul(*str, str, 10);
  375. if ((sizeof(long) > sizeof(int) && lu > INT_MAX) || !lu)
  376. bb_simple_error_msg_and_die("bad field specification");
  377. return lu;
  378. }
  379. #endif
  380. int sort_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  381. int sort_main(int argc UNUSED_PARAM, char **argv)
  382. {
  383. char **lines;
  384. char *str_ignored, *str_o, *str_t;
  385. llist_t *lst_k = NULL;
  386. int i;
  387. int linecount;
  388. unsigned opts;
  389. #if ENABLE_FEATURE_SORT_OPTIMIZE_MEMORY
  390. bool can_drop_dups;
  391. size_t prev_len = 0;
  392. char *prev_line = (char*) "";
  393. /* Postpone optimizing if the input is small, < 16k lines:
  394. * even just free()ing duplicate lines takes time.
  395. */
  396. size_t count_to_optimize_dups = 0x3fff;
  397. #endif
  398. xfunc_error_retval = 2;
  399. /* Parse command line options */
  400. opts = getopt32(argv,
  401. sort_opt_str,
  402. &str_ignored, &str_ignored, &str_o, &lst_k, &str_t
  403. );
  404. #if ENABLE_FEATURE_SORT_OPTIMIZE_MEMORY
  405. /* Can drop dups only if -u but no "complicating" options,
  406. * IOW: if we do a full line compares. Safe options:
  407. * -o FILE Output to FILE
  408. * -z Lines are terminated by NUL, not newline
  409. * -r Reverse sort order
  410. * -s Stable (don't sort ties alphabetically)
  411. * Not sure about these:
  412. * -b Ignore leading blanks
  413. * -f Ignore case
  414. * -i Ignore unprintable characters
  415. * -d Dictionary order (blank or alphanumeric only)
  416. * -n Sort numbers
  417. * -g General numerical sort
  418. * -M Sort month
  419. */
  420. can_drop_dups = ((opts & ~(FLAG_o|FLAG_z|FLAG_r|FLAG_s)) == FLAG_u);
  421. /* Stable sort needs every line to be uniquely allocated,
  422. * disable optimization to reuse strings:
  423. */
  424. if (opts & FLAG_s)
  425. count_to_optimize_dups = (size_t)-1L;
  426. #endif
  427. /* global b strips leading and trailing spaces */
  428. if (opts & FLAG_b)
  429. option_mask32 |= FLAG_bb;
  430. #if ENABLE_FEATURE_SORT_BIG
  431. if (opts & FLAG_t) {
  432. if (!str_t[0] || str_t[1])
  433. bb_simple_error_msg_and_die("bad -t parameter");
  434. key_separator = str_t[0];
  435. }
  436. /* note: below this point we use option_mask32, not opts,
  437. * since that reduces register pressure and makes code smaller */
  438. /* Parse sort key */
  439. while (lst_k) {
  440. enum {
  441. FLAG_allowed_for_k =
  442. FLAG_n | /* Numeric sort */
  443. FLAG_g | /* Sort using strtod() */
  444. FLAG_M | /* Sort date */
  445. FLAG_b | /* Ignore leading blanks */
  446. FLAG_r | /* Reverse */
  447. FLAG_d | /* Ignore !(isalnum()|isspace()) */
  448. FLAG_f | /* Force uppercase */
  449. FLAG_i | /* Ignore !isprint() */
  450. 0
  451. };
  452. struct sort_key *key = add_key();
  453. char *str_k = llist_pop(&lst_k);
  454. i = 0; /* i==0 before comma, 1 after (-k3,6) */
  455. while (*str_k) {
  456. /* Start of range */
  457. /* Cannot use bb_strtou - suffix can be a letter */
  458. key->range[2*i] = str2u(&str_k);
  459. if (*str_k == '.') {
  460. str_k++;
  461. key->range[2*i+1] = str2u(&str_k);
  462. }
  463. while (*str_k) {
  464. int flag;
  465. const char *idx;
  466. if (*str_k == ',' && !i++) {
  467. str_k++;
  468. break;
  469. } /* no else needed: fall through to syntax error
  470. because comma isn't in OPT_STR */
  471. idx = strchr(OPT_STR, *str_k);
  472. if (!idx)
  473. bb_simple_error_msg_and_die("unknown key option");
  474. flag = 1 << (idx - OPT_STR);
  475. if (flag & ~FLAG_allowed_for_k)
  476. bb_simple_error_msg_and_die("unknown sort type");
  477. /* b after ',' means strip _trailing_ space */
  478. if (i && flag == FLAG_b)
  479. flag = FLAG_bb;
  480. key->flags |= flag;
  481. str_k++;
  482. }
  483. }
  484. }
  485. #endif
  486. /* Open input files and read data */
  487. argv += optind;
  488. if (!*argv)
  489. *--argv = (char*)"-";
  490. linecount = 0;
  491. lines = NULL;
  492. do {
  493. /* coreutils 6.9 compat: abort on first open error,
  494. * do not continue to next file: */
  495. FILE *fp = xfopen_stdin(*argv);
  496. for (;;) {
  497. char *line = GET_LINE(fp);
  498. if (!line)
  499. break;
  500. #if ENABLE_FEATURE_SORT_OPTIMIZE_MEMORY
  501. if (count_to_optimize_dups != 0)
  502. count_to_optimize_dups--;
  503. if (count_to_optimize_dups == 0) {
  504. size_t len;
  505. char *new_line;
  506. /* On kernel/linux/arch/ *.[ch] files,
  507. * this reduces memory usage by 6%.
  508. * yes | head -99999999 | sort
  509. * goes down from 1900Mb to 380 Mb.
  510. */
  511. len = strlen(line);
  512. if (len <= prev_len) {
  513. new_line = prev_line + (prev_len - len);
  514. if (strcmp(line, new_line) == 0) {
  515. /* it's a tail of the prev line */
  516. if (can_drop_dups && prev_len == len) {
  517. /* it's identical to prev line */
  518. free(line);
  519. continue;
  520. }
  521. free(line);
  522. line = new_line;
  523. /* continue using longer prev_line
  524. * for future tail tests.
  525. */
  526. goto skip;
  527. }
  528. }
  529. prev_len = len;
  530. prev_line = line;
  531. skip: ;
  532. }
  533. #else
  534. //TODO: lighter version which only drops total dups if can_drop_dups == true
  535. #endif
  536. lines = xrealloc_vector(lines, 6, linecount);
  537. lines[linecount++] = line;
  538. }
  539. fclose_if_not_stdin(fp);
  540. } while (*++argv);
  541. #if ENABLE_FEATURE_SORT_BIG
  542. /* If no key, perform alphabetic sort */
  543. if (!key_list)
  544. add_key()->range[0] = 1;
  545. /* Handle -c */
  546. if (option_mask32 & FLAG_c) {
  547. int j = (option_mask32 & FLAG_u) ? -1 : 0;
  548. for (i = 1; i < linecount; i++) {
  549. if (compare_keys(&lines[i-1], &lines[i]) > j) {
  550. fprintf(stderr, "Check line %u\n", i);
  551. return EXIT_FAILURE;
  552. }
  553. }
  554. return EXIT_SUCCESS;
  555. }
  556. #endif
  557. /* For stable sort, store original line position beyond terminating NUL */
  558. if (option_mask32 & FLAG_s) {
  559. for (i = 0; i < linecount; i++) {
  560. uint32_t *p32;
  561. char *line;
  562. unsigned len;
  563. line = lines[i];
  564. len = (strlen(line) + 4) & (~3u);
  565. lines[i] = line = xrealloc(line, len + 4);
  566. p32 = (void*)(line + len);
  567. *p32 = i;
  568. }
  569. /*option_mask32 |= FLAG_no_tie_break;*/
  570. /* ^^^redundant: if FLAG_s, compare_keys() does no tie break */
  571. }
  572. /* Perform the actual sort */
  573. qsort(lines, linecount, sizeof(lines[0]), compare_keys);
  574. /* Handle -u */
  575. if (option_mask32 & FLAG_u) {
  576. int j = 0;
  577. /* coreutils 6.3 drop lines for which only key is the same
  578. * -- disabling last-resort compare, or else compare_keys()
  579. * will be the same only for completely identical lines.
  580. */
  581. option_mask32 |= FLAG_no_tie_break;
  582. for (i = 1; i < linecount; i++) {
  583. if (compare_keys(&lines[j], &lines[i]) == 0)
  584. free(lines[i]);
  585. else
  586. lines[++j] = lines[i];
  587. }
  588. if (linecount)
  589. linecount = j+1;
  590. }
  591. /* Print it */
  592. #if ENABLE_FEATURE_SORT_BIG
  593. /* Open output file _after_ we read all input ones */
  594. if (option_mask32 & FLAG_o)
  595. xmove_fd(xopen(str_o, O_WRONLY|O_CREAT|O_TRUNC), STDOUT_FILENO);
  596. #endif
  597. {
  598. int ch = (option_mask32 & FLAG_z) ? '\0' : '\n';
  599. for (i = 0; i < linecount; i++)
  600. printf("%s%c", lines[i], ch);
  601. }
  602. fflush_stdout_and_exit(EXIT_SUCCESS);
  603. }