1 /* vi: set sw=4 ts=4: */
3 * SuS3 compliant sort implementation for busybox
5 * Copyright (C) 2004 by Rob Landley <rob@landley.net>
7 * MAINTAINER: Rob Landley <rob@landley.net>
9 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
11 * See SuS3 sort standard at:
12 * http://www.opengroup.org/onlinepubs/007904975/utilities/sort.html
15 //config: bool "sort (7.4 kb)"
18 //config: sort is used to sort lines of text in specified files.
20 //config:config FEATURE_SORT_BIG
21 //config: bool "Full SuSv3 compliant sort (support -ktcbdfiozgM)"
23 //config: depends on SORT
25 //config: Without this, sort only supports -r, -u, -s, 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.
29 //config: The SuSv3 sort standard is available at:
30 //config: http://www.opengroup.org/onlinepubs/007904975/utilities/sort.html
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
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.
40 //applet:IF_SORT(APPLET_NOEXEC(sort, sort, BB_DIR_USR_BIN, BB_SUID_DROP, sort))
42 //kbuild:lib-$(CONFIG_SORT) += sort.o
44 //usage:#define sort_trivial_usage
46 //usage: IF_FEATURE_SORT_BIG("gMcszbdfiokt] [-o FILE] [-k start[.offset][opts][,end[.offset][opts]] [-t CHAR")
47 //usage: "] [FILE]..."
48 //usage:#define sort_full_usage "\n\n"
49 //usage: "Sort lines of text\n"
50 //usage: IF_FEATURE_SORT_BIG(
51 //usage: "\n -o FILE Output to FILE"
52 //usage: "\n -c Check whether input is sorted"
53 //usage: "\n -b Ignore leading blanks"
54 //usage: "\n -f Ignore case"
55 //usage: "\n -i Ignore unprintable characters"
56 //usage: "\n -d Dictionary order (blank or alphanumeric only)"
58 //-h, --human-numeric-sort: compare human readable numbers (e.g., 2K 1G)
59 //usage: "\n -n Sort numbers"
60 //usage: IF_FEATURE_SORT_BIG(
61 //usage: "\n -g General numerical sort"
62 //usage: "\n -M Sort month"
63 //usage: "\n -t CHAR Field separator"
64 //usage: "\n -k N[,M] Sort by Nth field"
66 //usage: "\n -r Reverse sort order"
67 //usage: "\n -s Stable (don't sort ties alphabetically)"
68 //usage: "\n -u Suppress duplicate lines"
69 //usage: IF_FEATURE_SORT_BIG(
70 //usage: "\n -z Lines are terminated by NUL, not newline"
71 ///////: "\n -m Ignored for GNU compatibility"
72 ///////: "\n -S BUFSZ Ignored for GNU compatibility"
73 ///////: "\n -T TMPDIR Ignored for GNU compatibility"
76 //usage:#define sort_example_usage
77 //usage: "$ echo -e \"e\\nf\\nb\\nd\\nc\\na\" | sort\n"
84 //usage: IF_FEATURE_SORT_BIG(
85 //usage: "$ echo -e \"c 3\\nb 2\\nd 2\" | $SORT -k 2,2n -k 1,1r\n"
94 /* These are sort types */
96 FLAG_n = 1, /* Numeric sort */
97 FLAG_g = 2, /* Sort using strtod() */
98 FLAG_M = 4, /* Sort date */
99 /* ucsz apply to root level only, not keys. b at root level implies bb */
100 FLAG_u = 8, /* Unique */
101 FLAG_c = 0x10, /* Check: no output, exit(!ordered) */
102 FLAG_s = 0x20, /* Stable sort, no ascii fallback at end */
103 FLAG_z = 0x40, /* Input and output is NUL terminated, not \n */
104 /* These can be applied to search keys, the previous four can't */
105 FLAG_b = 0x80, /* Ignore leading blanks */
106 FLAG_r = 0x100, /* Reverse */
107 FLAG_d = 0x200, /* Ignore !(isalnum()|isspace()) */
108 FLAG_f = 0x400, /* Force uppercase */
109 FLAG_i = 0x800, /* Ignore !isprint() */
110 FLAG_m = 0x1000, /* ignored: merge already sorted files; do not sort */
111 FLAG_S = 0x2000, /* ignored: -S, --buffer-size=SIZE */
112 FLAG_T = 0x4000, /* ignored: -T, --temporary-directory=DIR */
116 FLAG_bb = 0x80000000, /* Ignore trailing blanks */
117 FLAG_no_tie_break = 0x40000000,
120 static const char sort_opt_str[] ALIGN1 = "^"
121 "ngMucszbrdfimS:T:o:k:*t:"
122 "\0" "o--o:t--t"/*-t, -o: at most one of each*/;
124 * OPT_STR must not be string literal, needs to have stable address:
125 * code uses "strchr(OPT_STR,c) - OPT_STR" idiom.
127 #define OPT_STR (sort_opt_str + 1)
129 #if ENABLE_FEATURE_SORT_BIG
130 static char key_separator;
132 static struct sort_key {
133 struct sort_key *next_key; /* linked list */
134 unsigned range[4]; /* start word, start char, end word, end char */
139 /* This is a NOEXEC applet. Be very careful! */
142 static char *get_key(char *str, struct sort_key *key, int flags)
144 int start = start; /* for compiler */
149 /* Special case whole string, so we don't have to make a copy */
150 if (key->range[0] == 1 && !key->range[1] && !key->range[2] && !key->range[3]
151 && !(flags & (FLAG_b | FLAG_d | FLAG_f | FLAG_i | FLAG_bb))
156 /* Find start of key on first pass, end on second pass */
158 for (j = 0; j < 2; j++) {
159 if (!key->range[2*j])
161 /* Loop through fields */
163 unsigned char ch = 0;
166 for (i = 1; i < key->range[2*j] + j; i++) {
168 /* Skip body of key and separator */
169 while ((ch = str[end]) != '\0') {
171 if (ch == key_separator)
175 /* Skip leading blanks */
176 while (isspace(str[end]))
178 /* Skip body of key */
179 while (str[end] != '\0') {
180 if (isspace(str[end]))
186 /* Remove last delim: "abc:def:" => "abc:def" */
188 //if (str[end-1] != key_separator)
189 // bb_error_msg(_and_die("BUG! "
190 // "str[start:%d,end:%d]:'%.*s'",
191 // start, end, (int)(end-start), &str[start]);
197 /* Strip leading whitespace if necessary */
199 /* not using skip_whitespace() for speed */
200 while (isspace(str[start])) start++;
201 /* Strip trailing whitespace if necessary */
203 while (end > start && isspace(str[end-1])) end--;
204 /* -kSTART,N.ENDCHAR: honor ENDCHAR (1-based) */
207 if (end > len) end = len;
209 /* -kN.STARTCHAR[,...]: honor STARTCHAR (1-based) */
211 start += key->range[1] - 1;
212 if (start > len) start = len;
217 str = xstrndup(str+start, end-start);
219 if (flags & FLAG_d) {
220 for (start = end = 0; str[end]; end++)
221 if (isspace(str[end]) || isalnum(str[end]))
222 str[start++] = str[end];
226 if (flags & FLAG_i) {
227 for (start = end = 0; str[end]; end++)
228 if (isprint_asciionly(str[end]))
229 str[start++] = str[end];
234 for (i = 0; str[i]; i++)
235 str[i] = toupper(str[i]);
240 static struct sort_key *add_key(void)
242 struct sort_key **pkey = &key_list;
244 pkey = &((*pkey)->next_key);
245 return *pkey = xzalloc(sizeof(struct sort_key));
248 #define GET_LINE(fp) \
249 ((option_mask32 & FLAG_z) \
250 ? bb_get_chunk_from_file(fp, NULL) \
251 : xmalloc_fgetline(fp))
253 #define GET_LINE(fp) xmalloc_fgetline(fp)
256 /* Iterate through keys list and perform comparisons */
257 static int compare_keys(const void *xarg, const void *yarg)
259 int flags = option_mask32, retval = 0;
262 #if ENABLE_FEATURE_SORT_BIG
263 struct sort_key *key;
265 for (key = key_list; !retval && key; key = key->next_key) {
266 flags = key->flags ? key->flags : option_mask32;
267 /* Chop out and modify key chunks, handling -dfib */
268 x = get_key(*(char **)xarg, key, flags);
269 y = get_key(*(char **)yarg, key, flags);
271 /* This curly bracket serves no purpose but to match the nesting
272 * level of the for () loop we're not using */
277 /* Perform actual comparison */
278 switch (flags & (FLAG_n | FLAG_M | FLAG_g)) {
280 bb_error_msg_and_die("unknown sort type");
284 #if ENABLE_LOCALE_SUPPORT
285 retval = strcoll(x, y);
287 retval = strcmp(x, y);
290 #if ENABLE_FEATURE_SORT_BIG
293 double dx = strtod(x, &xx);
294 double dy = strtod(y, &yy);
295 /* not numbers < NaN < -infinity < numbers < +infinity) */
297 retval = (y == yy ? 0 : -1);
300 /* Check for isnan */
302 retval = (dy != dy) ? 0 : -1;
305 /* Check for infinity. Could underflow, but it avoids libm. */
306 else if (1.0 / dx == 0.0) {
308 retval = (1.0 / dy == 0.0 && dy < 0) ? 0 : -1;
310 retval = (1.0 / dy == 0.0 && dy > 0) ? 0 : 1;
311 } else if (1.0 / dy == 0.0)
312 retval = (dy < 0) ? 1 : -1;
314 retval = (dx > dy) ? 1 : ((dx < dy) ? -1 : 0);
322 xx = strptime(x, "%b", &thyme);
324 yy = strptime(y, "%b", &thyme);
326 retval = (!yy) ? 0 : -1;
330 retval = dx - thyme.tm_mon;
333 /* Full floating point version of -n */
337 retval = (dx > dy) ? 1 : ((dx < dy) ? -1 : 0);
341 /* Free key copies. */
342 if (x != *(char **)xarg) free(x);
343 if (y != *(char **)yarg) free(y);
344 /* if (retval) break; - done by for () anyway */
346 /* Integer version of -n for tiny systems */
348 retval = atoi(x) - atoi(y);
355 /* So far lines are "the same" */
357 if (option_mask32 & FLAG_s) {
358 /* "Stable sort": later line is "greater than",
359 * IOW: do not allow qsort() to swap equal lines.
366 line = *(char**)xarg;
367 len = (strlen(line) + 4) & (~3u);
368 p32 = (void*)(line + len);
370 line = *(char**)yarg;
371 len = (strlen(line) + 4) & (~3u);
372 p32 = (void*)(line + len);
375 /* If x > y, 1, else -1 */
376 retval = (x32 > y32) * 2 - 1;
378 if (!(option_mask32 & FLAG_no_tie_break)) {
380 flags = option_mask32;
381 retval = strcmp(*(char **)xarg, *(char **)yarg);
391 #if ENABLE_FEATURE_SORT_BIG
392 static unsigned str2u(char **str)
395 if (!isdigit((*str)[0]))
396 bb_error_msg_and_die("bad field specification");
397 lu = strtoul(*str, str, 10);
398 if ((sizeof(long) > sizeof(int) && lu > INT_MAX) || !lu)
399 bb_error_msg_and_die("bad field specification");
404 int sort_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
405 int sort_main(int argc UNUSED_PARAM, char **argv)
408 char *str_ignored, *str_o, *str_t;
409 llist_t *lst_k = NULL;
413 #if ENABLE_FEATURE_SORT_OPTIMIZE_MEMORY
416 /* Postpone optimizing if the input is small, < 16k lines:
417 * even just free()ing duplicate lines takes time.
419 size_t count_to_optimize_dups = 0x3fff;
422 xfunc_error_retval = 2;
424 /* Parse command line options */
425 opts = getopt32(argv,
427 &str_ignored, &str_ignored, &str_o, &lst_k, &str_t
429 #if ENABLE_FEATURE_SORT_OPTIMIZE_MEMORY
430 /* Can drop dups only if -u but no "complicating" options,
431 * IOW: if we do a full line compares. Safe options:
432 * -o FILE Output to FILE
433 * -z Lines are terminated by NUL, not newline
434 * -r Reverse sort order
435 * -s Stable (don't sort ties alphabetically)
436 * Not sure about these:
437 * -b Ignore leading blanks
439 * -i Ignore unprintable characters
440 * -d Dictionary order (blank or alphanumeric only)
442 * -g General numerical sort
445 can_drop_dups = ((opts & ~(FLAG_o|FLAG_z|FLAG_r|FLAG_s)) == FLAG_u);
446 /* Stable sort needs every line to be uniquely allocated,
447 * disable optimization to reuse strings:
450 count_to_optimize_dups = (size_t)-1L;
452 /* global b strips leading and trailing spaces */
454 option_mask32 |= FLAG_bb;
455 #if ENABLE_FEATURE_SORT_BIG
457 if (!str_t[0] || str_t[1])
458 bb_error_msg_and_die("bad -t parameter");
459 key_separator = str_t[0];
461 /* note: below this point we use option_mask32, not opts,
462 * since that reduces register pressure and makes code smaller */
468 FLAG_n | /* Numeric sort */
469 FLAG_g | /* Sort using strtod() */
470 FLAG_M | /* Sort date */
471 FLAG_b | /* Ignore leading blanks */
472 FLAG_r | /* Reverse */
473 FLAG_d | /* Ignore !(isalnum()|isspace()) */
474 FLAG_f | /* Force uppercase */
475 FLAG_i | /* Ignore !isprint() */
478 struct sort_key *key = add_key();
479 char *str_k = llist_pop(&lst_k);
481 i = 0; /* i==0 before comma, 1 after (-k3,6) */
484 /* Cannot use bb_strtou - suffix can be a letter */
485 key->range[2*i] = str2u(&str_k);
488 key->range[2*i+1] = str2u(&str_k);
494 if (*str_k == ',' && !i++) {
497 } /* no else needed: fall through to syntax error
498 because comma isn't in OPT_STR */
499 idx = strchr(OPT_STR, *str_k);
501 bb_error_msg_and_die("unknown key option");
502 flag = 1 << (idx - OPT_STR);
503 if (flag & ~FLAG_allowed_for_k)
504 bb_error_msg_and_die("unknown sort type");
505 /* b after ',' means strip _trailing_ space */
506 if (i && flag == FLAG_b)
515 /* Open input files and read data */
518 *--argv = (char*)"-";
522 /* coreutils 6.9 compat: abort on first open error,
523 * do not continue to next file: */
524 FILE *fp = xfopen_stdin(*argv);
526 char *line = GET_LINE(fp);
530 #if ENABLE_FEATURE_SORT_OPTIMIZE_MEMORY
531 if (count_to_optimize_dups != 0)
532 count_to_optimize_dups--;
533 if (count_to_optimize_dups == 0) {
538 /* On kernel/linux/arch/ *.[ch] files,
539 * this reduces memory usage by 6%.
540 * yes | head -99999999 | sort
541 * goes down from 1900Mb to 380 Mb.
543 if (first == '\0' || first == '\n') {
544 len = !(first == '\0');
545 new_line = (char*)"\n" + 1 - len;
549 if (len <= prev_len) {
550 new_line = lines[linecount-1] + (prev_len - len);
551 if (strcmp(line, new_line) == 0) {
552 if (can_drop_dups && prev_len == len) {
564 lines = xrealloc_vector(lines, 6, linecount);
565 lines[linecount++] = line;
567 fclose_if_not_stdin(fp);
570 #if ENABLE_FEATURE_SORT_BIG
571 /* If no key, perform alphabetic sort */
573 add_key()->range[0] = 1;
575 if (option_mask32 & FLAG_c) {
576 int j = (option_mask32 & FLAG_u) ? -1 : 0;
577 for (i = 1; i < linecount; i++) {
578 if (compare_keys(&lines[i-1], &lines[i]) > j) {
579 fprintf(stderr, "Check line %u\n", i);
586 //TODO: lighter version which only drops total dups if can_drop_dups == true
589 /* For stable sort, store original line position beyond terminating NUL */
590 if (option_mask32 & FLAG_s) {
591 for (i = 0; i < linecount; i++) {
597 len = (strlen(line) + 4) & (~3u);
598 lines[i] = line = xrealloc(line, len + 4);
599 p32 = (void*)(line + len);
602 /*option_mask32 |= FLAG_no_tie_break;*/
603 /* ^^^redundant: if FLAG_s, compare_keys() does no tie break */
606 /* Perform the actual sort */
607 qsort(lines, linecount, sizeof(lines[0]), compare_keys);
610 if (option_mask32 & FLAG_u) {
612 /* coreutils 6.3 drop lines for which only key is the same
613 * -- disabling last-resort compare, or else compare_keys()
614 * will be the same only for completely identical lines.
616 option_mask32 |= FLAG_no_tie_break;
617 for (i = 1; i < linecount; i++) {
618 if (compare_keys(&lines[j], &lines[i]) == 0)
621 lines[++j] = lines[i];
628 #if ENABLE_FEATURE_SORT_BIG
629 /* Open output file _after_ we read all input ones */
630 if (option_mask32 & FLAG_o)
631 xmove_fd(xopen(str_o, O_WRONLY|O_CREAT|O_TRUNC), STDOUT_FILENO);
634 int ch = (option_mask32 & FLAG_z) ? '\0' : '\n';
635 for (i = 0; i < linecount; i++)
636 printf("%s%c", lines[i], ch);
639 fflush_stdout_and_exit(EXIT_SUCCESS);