Annotation of src/usr.bin/sort/sort.c, Revision 1.49
1.49 ! millert 1: /* $OpenBSD: sort.c,v 1.48 2015/03/20 23:04:07 millert Exp $ */
1.1 millert 2:
3: /*-
1.44 millert 4: * Copyright (C) 2009 Gabor Kovesdan <gabor@FreeBSD.org>
5: * Copyright (C) 2012 Oleg Moskalenko <mom040267@gmail.com>
6: * All rights reserved.
1.1 millert 7: *
8: * Redistribution and use in source and binary forms, with or without
9: * modification, are permitted provided that the following conditions
10: * are met:
11: * 1. Redistributions of source code must retain the above copyright
12: * notice, this list of conditions and the following disclaimer.
13: * 2. Redistributions in binary form must reproduce the above copyright
14: * notice, this list of conditions and the following disclaimer in the
15: * documentation and/or other materials provided with the distribution.
16: *
1.44 millert 17: * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
1.1 millert 18: * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19: * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1.44 millert 20: * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
1.1 millert 21: * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22: * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23: * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24: * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25: * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26: * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27: * SUCH DAMAGE.
28: */
29:
1.48 millert 30: #include <sys/resource.h>
1.44 millert 31: #include <sys/stat.h>
1.48 millert 32: #include <sys/sysctl.h>
1.44 millert 33: #include <sys/types.h>
1.1 millert 34:
1.44 millert 35: #include <err.h>
36: #include <errno.h>
37: #include <getopt.h>
38: #include <limits.h>
1.16 ericj 39: #include <locale.h>
1.44 millert 40: #include <md5.h>
41: #include <regex.h>
1.1 millert 42: #include <signal.h>
1.44 millert 43: #include <stdbool.h>
44: #include <stdio.h>
1.1 millert 45: #include <stdlib.h>
46: #include <string.h>
47: #include <unistd.h>
1.44 millert 48: #include <wchar.h>
49: #include <wctype.h>
50:
51: #include "coll.h"
52: #include "file.h"
53: #include "sort.h"
54:
55: #define OPTIONS "bCcdfgHhik:Mmno:RrS:st:T:uVz"
56:
57: static bool need_random;
58: static const char *random_source;
59:
60: MD5_CTX md5_ctx;
61:
62: struct sort_opts sort_opts_vals;
63:
64: bool debug_sort;
65: bool need_hint;
66:
67: static bool gnusort_numeric_compatibility;
68:
69: static struct sort_mods default_sort_mods_object;
70: struct sort_mods * const default_sort_mods = &default_sort_mods_object;
71:
72: static bool print_symbols_on_debug;
73:
74: /*
75: * Arguments from file (when file0-from option is used:
76: */
77: static size_t argc_from_file0 = (size_t)-1;
78: static char **argv_from_file0;
79:
80: /*
81: * Placeholder symbols for options which have no single-character equivalent
82: */
83: enum {
84: SORT_OPT = CHAR_MAX + 1,
85: HELP_OPT,
86: FF_OPT,
87: BS_OPT,
88: VERSION_OPT,
89: DEBUG_OPT,
90: RANDOMSOURCE_OPT,
91: COMPRESSPROGRAM_OPT,
92: QSORT_OPT,
93: HEAPSORT_OPT,
94: RADIXSORT_OPT,
95: MMAP_OPT
96: };
97:
98: #define NUMBER_OF_MUTUALLY_EXCLUSIVE_FLAGS 6
99: static const char mutually_exclusive_flags[NUMBER_OF_MUTUALLY_EXCLUSIVE_FLAGS] = { 'M', 'n', 'g', 'R', 'h', 'V' };
100:
101: static const struct option long_options[] = {
102: { "batch-size", required_argument, NULL, BS_OPT },
103: { "buffer-size", required_argument, NULL, 'S' },
104: { "check", optional_argument, NULL, 'c' },
105: { "check=silent|quiet", optional_argument, NULL, 'C' },
106: { "compress-program", required_argument, NULL, COMPRESSPROGRAM_OPT },
107: { "debug", no_argument, NULL, DEBUG_OPT },
108: { "dictionary-order", no_argument, NULL, 'd' },
109: { "field-separator", required_argument, NULL, 't' },
110: { "files0-from", required_argument, NULL, FF_OPT },
111: { "general-numeric-sort", no_argument, NULL, 'g' },
112: { "heapsort", no_argument, NULL, HEAPSORT_OPT },
113: { "help", no_argument, NULL, HELP_OPT },
114: { "human-numeric-sort", no_argument, NULL, 'h' },
115: { "ignore-leading-blanks", no_argument, NULL, 'b' },
116: { "ignore-case", no_argument, NULL, 'f' },
117: { "ignore-nonprinting", no_argument, NULL, 'i' },
118: { "key", required_argument, NULL, 'k' },
119: { "merge", no_argument, NULL, 'm' },
120: { "mergesort", no_argument, NULL, 'H' },
121: { "mmap", no_argument, NULL, MMAP_OPT },
122: { "month-sort", no_argument, NULL, 'M' },
123: { "numeric-sort", no_argument, NULL, 'n' },
124: { "output", required_argument, NULL, 'o' },
125: { "qsort", no_argument, NULL, QSORT_OPT },
126: { "radixsort", no_argument, NULL, RADIXSORT_OPT },
127: { "random-sort", no_argument, NULL, 'R' },
128: { "random-source", required_argument, NULL, RANDOMSOURCE_OPT },
129: { "reverse", no_argument, NULL, 'r' },
130: { "sort", required_argument, NULL, SORT_OPT },
131: { "stable", no_argument, NULL, 's' },
132: { "temporary-directory", required_argument, NULL, 'T' },
133: { "unique", no_argument, NULL, 'u' },
134: { "version", no_argument, NULL, VERSION_OPT },
135: { "version-sort", no_argument, NULL, 'V' },
136: { "zero-terminated", no_argument, NULL, 'z' },
137: { NULL, no_argument, NULL, 0 }
138: };
139:
140: /*
141: * Check where sort modifier is present
142: */
143: static bool
144: sort_modifier_empty(struct sort_mods *sm)
145: {
146:
147: if (sm == NULL)
148: return true;
149: return !(sm->Mflag || sm->Vflag || sm->nflag || sm->gflag ||
150: sm->rflag || sm->Rflag || sm->hflag || sm->dflag || sm->fflag);
151: }
152:
153: /*
154: * Print out usage text.
155: */
156: static __dead void
157: usage(int exit_val)
158: {
1.1 millert 159:
1.44 millert 160: fprintf(exit_val ? stderr : stdout,
1.46 jmc 161: "usage: %s [-bCcdfgHhiMmnRrsuVz] [-k field1[,field2]] [-o output] "
1.45 jmc 162: "[-S size]\n\t[-T dir] [-t char] [file ...]\n", getprogname());
1.44 millert 163: exit(exit_val);
164: }
1.4 millert 165:
1.1 millert 166: /*
1.44 millert 167: * Read input file names from a file (file0-from option).
1.1 millert 168: */
1.44 millert 169: static void
170: read_fns_from_file0(const char *fn)
171: {
1.47 millert 172: FILE *f;
173: char *line = NULL;
174: size_t linesize = 0;
175: ssize_t linelen;
176:
177: if (fn == NULL)
178: return;
179:
180: f = fopen(fn, "r");
181: if (f == NULL)
182: err(2, "%s", fn);
183:
184: while ((linelen = getdelim(&line, &linesize, '\0', f)) != -1) {
185: if (*line != '\0') {
186: if (argc_from_file0 == (size_t)-1)
187: argc_from_file0 = 0;
188: ++argc_from_file0;
189: argv_from_file0 = sort_reallocarray(argv_from_file0,
190: argc_from_file0, sizeof(char *));
191: argv_from_file0[argc_from_file0 - 1] = line;
192: } else {
193: free(line);
1.44 millert 194: }
1.47 millert 195: line = NULL;
196: linesize = 0;
1.44 millert 197: }
1.47 millert 198: if (ferror(f))
199: err(2, "%s: getdelim", fn);
200:
201: closefile(f, fn);
1.44 millert 202: }
1.4 millert 203:
1.1 millert 204: /*
1.44 millert 205: * Check how much RAM is available for the sort.
1.1 millert 206: */
1.44 millert 207: static void
208: set_hw_params(void)
209: {
1.48 millert 210: long long user_memory;
211: struct rlimit rl;
212: size_t len;
213: int mib[] = { CTL_HW, HW_USERMEM64 };
214:
215: /* Get total user (non-kernel) memory. */
216: len = sizeof(user_memory);
217: if (sysctl(mib, 2, &user_memory, &len, NULL, 0) == -1)
218: user_memory = -1;
219:
220: /* Increase our data size to the max */
221: if (getrlimit(RLIMIT_DATA, &rl) == 0) {
222: free_memory = (unsigned long long)rl.rlim_cur;
223: rl.rlim_cur = rl.rlim_max;
224: if (setrlimit(RLIMIT_DATA, &rl) == 0) {
225: free_memory = (unsigned long long)rl.rlim_max;
226: } else {
227: warn("Can't set resource limit to max data size");
228: }
229: } else
230: warn("Can't get resource limit for data size");
1.1 millert 231:
1.48 millert 232: /* We prefer to use temp files rather than swap space. */
233: if (user_memory != -1 && free_memory > user_memory)
234: free_memory = user_memory;
1.44 millert 235:
236: available_free_memory = free_memory / 2;
237: }
238:
239: /*
240: * Convert "plain" symbol to wide symbol, with default value.
241: */
242: static void
243: conv_mbtowc(wchar_t *wc, const char *c, const wchar_t def)
244: {
1.1 millert 245:
1.44 millert 246: if (wc && c) {
247: int res;
1.1 millert 248:
1.44 millert 249: res = mbtowc(wc, c, MB_CUR_MAX);
250: if (res < 1)
251: *wc = def;
1.12 millert 252: }
1.44 millert 253: }
1.12 millert 254:
1.44 millert 255: /*
256: * Set current locale symbols.
257: */
258: static void
259: set_locale(void)
1.1 millert 260: {
1.44 millert 261: struct lconv *lc;
262: const char *locale;
1.4 millert 263:
1.16 ericj 264: setlocale(LC_ALL, "");
265:
1.44 millert 266: lc = localeconv();
267:
268: if (lc) {
269: /* obtain LC_NUMERIC info */
270: /* Convert to wide char form */
271: conv_mbtowc(&symbol_decimal_point, lc->decimal_point,
272: symbol_decimal_point);
273: conv_mbtowc(&symbol_thousands_sep, lc->thousands_sep,
274: symbol_thousands_sep);
275: conv_mbtowc(&symbol_positive_sign, lc->positive_sign,
276: symbol_positive_sign);
277: conv_mbtowc(&symbol_negative_sign, lc->negative_sign,
278: symbol_negative_sign);
279: }
280:
281: if (getenv("GNUSORT_NUMERIC_COMPATIBILITY"))
282: gnusort_numeric_compatibility = true;
283:
284: locale = setlocale(LC_COLLATE, NULL);
285: if (locale != NULL) {
286: char *tmpl;
287: const char *byteclocale;
288:
289: tmpl = sort_strdup(locale);
290: byteclocale = setlocale(LC_COLLATE, "C");
291: if (byteclocale && strcmp(byteclocale, tmpl) == 0) {
292: byte_sort = true;
293: } else {
294: byteclocale = setlocale(LC_COLLATE, "POSIX");
295: if (byteclocale && strcmp(byteclocale, tmpl) == 0)
296: byte_sort = true;
297: else
298: setlocale(LC_COLLATE, tmpl);
299: }
300: sort_free(tmpl);
301: }
302: if (!byte_sort)
303: sort_mb_cur_max = MB_CUR_MAX;
304: }
305:
306: /*
307: * Set directory temporary files.
308: */
309: static void
310: set_tmpdir(void)
311: {
312: char *td;
313:
314: td = getenv("TMPDIR");
315: if (td != NULL)
316: tmpdir = sort_strdup(td);
317: }
318:
319: /*
320: * Parse -S option.
321: */
322: static unsigned long long
323: parse_memory_buffer_value(const char *value)
324: {
325:
326: if (value == NULL)
327: return available_free_memory;
328: else {
329: char *endptr;
330: unsigned long long membuf;
331:
332: endptr = NULL;
333: errno = 0;
334: membuf = strtoll(value, &endptr, 10);
335:
336: if (errno != 0) {
337: warn("Wrong memory buffer specification");
338: membuf = available_free_memory;
339: } else {
340: switch (*endptr){
341: case 'Y':
342: membuf *= 1024;
343: /* FALLTHROUGH */
344: case 'Z':
345: membuf *= 1024;
346: /* FALLTHROUGH */
347: case 'E':
348: membuf *= 1024;
349: /* FALLTHROUGH */
350: case 'P':
351: membuf *= 1024;
352: /* FALLTHROUGH */
353: case 'T':
354: membuf *= 1024;
355: /* FALLTHROUGH */
356: case 'G':
357: membuf *= 1024;
358: /* FALLTHROUGH */
359: case 'M':
360: membuf *= 1024;
361: /* FALLTHROUGH */
362: case '\0':
363: case 'K':
364: membuf *= 1024;
365: /* FALLTHROUGH */
366: case 'b':
367: break;
368: case '%':
369: membuf = (available_free_memory * membuf) /
370: 100;
371: break;
372: default:
373: warnc(EINVAL, "%s", optarg);
374: membuf = available_free_memory;
375: }
376: }
377: return membuf;
378: }
379: }
380:
381: /*
382: * Signal handler that clears the temporary files.
383: */
384: static void
1.49 ! millert 385: sig_handler(int sig __unused)
1.44 millert 386: {
387:
388: clear_tmp_files();
389: exit(2);
390: }
391:
392: /*
393: * Set signal handler on panic signals.
394: */
395: static void
396: set_signal_handler(void)
397: {
398: struct sigaction sa;
1.49 ! millert 399: int i, signals[] = {SIGTERM, SIGHUP, SIGINT, SIGQUIT, SIGUSR1, SIGUSR2,
! 400: SIGPIPE, SIGXCPU, SIGXFSZ, SIGVTALRM, SIGPROF, 0};
1.44 millert 401:
402: memset(&sa, 0, sizeof(sa));
1.49 ! millert 403: sigfillset(&sa.sa_mask);
! 404: sa.sa_flags = SA_RESTART;
! 405: sa.sa_handler = sig_handler;
! 406:
! 407: for (i = 0; signals[i] != 0; i++) {
! 408: if (sigaction(signals[i], &sa, NULL) < 0) {
! 409: warn("sigaction(%d)", i);
! 410: continue;
! 411: }
1.44 millert 412: }
413: }
414:
415: /*
416: * Print "unknown" message and exit with status 2.
417: */
418: static void
419: unknown(const char *what)
420: {
421:
422: errx(2, "Unknown feature: %s", what);
423: }
424:
425: /*
426: * Check whether contradictory input options are used.
427: */
428: static void
429: check_mutually_exclusive_flags(char c, bool *mef_flags)
430: {
431: int i, fo_index, mec;
432: bool found_others, found_this;
433:
434: found_others = found_this =false;
435: fo_index = 0;
436:
437: for (i = 0; i < NUMBER_OF_MUTUALLY_EXCLUSIVE_FLAGS; i++) {
438: mec = mutually_exclusive_flags[i];
439:
440: if (mec != c) {
441: if (mef_flags[i]) {
442: if (found_this)
443: errx(1, "%c:%c: mutually exclusive flags", c, mec);
444: found_others = true;
445: fo_index = i;
446: }
447: } else {
448: if (found_others)
449: errx(1, "%c:%c: mutually exclusive flags", c, mutually_exclusive_flags[fo_index]);
450: mef_flags[i] = true;
451: found_this = true;
452: }
453: }
454: }
455:
456: /*
457: * Initialise sort opts data.
458: */
459: static void
460: set_sort_opts(void)
461: {
462:
463: memset(&default_sort_mods_object, 0,
464: sizeof(default_sort_mods_object));
465: memset(&sort_opts_vals, 0, sizeof(sort_opts_vals));
466: default_sort_mods_object.func =
467: get_sort_func(&default_sort_mods_object);
468: }
469:
470: /*
471: * Set a sort modifier on a sort modifiers object.
472: */
473: static bool
474: set_sort_modifier(struct sort_mods *sm, int c)
475: {
476:
477: if (sm) {
478: switch (c){
479: case 'b':
480: sm->bflag = true;
1.1 millert 481: break;
482: case 'd':
1.44 millert 483: sm->dflag = true;
484: break;
1.4 millert 485: case 'f':
1.44 millert 486: sm->fflag = true;
487: break;
488: case 'g':
489: sm->gflag = true;
490: need_hint = true;
491: break;
1.1 millert 492: case 'i':
1.44 millert 493: sm->iflag = true;
1.1 millert 494: break;
495: case 'R':
1.44 millert 496: sm->Rflag = true;
497: need_random = true;
1.1 millert 498: break;
1.44 millert 499: case 'M':
500: initialise_months();
501: sm->Mflag = true;
502: need_hint = true;
1.1 millert 503: break;
1.44 millert 504: case 'n':
505: sm->nflag = true;
506: need_hint = true;
507: print_symbols_on_debug = true;
1.1 millert 508: break;
1.44 millert 509: case 'r':
510: sm->rflag = true;
1.1 millert 511: break;
1.44 millert 512: case 'V':
513: sm->Vflag = true;
1.1 millert 514: break;
1.44 millert 515: case 'h':
516: sm->hflag = true;
517: need_hint = true;
518: print_symbols_on_debug = true;
1.1 millert 519: break;
1.8 deraadt 520: default:
1.44 millert 521: return false;
1.1 millert 522: }
1.44 millert 523: sort_opts_vals.complex_sort = true;
524: sm->func = get_sort_func(sm);
525: }
526: return true;
527: }
528:
529: /*
530: * Parse POS in -k option.
531: */
532: static int
533: parse_pos(const char *s, struct key_specs *ks, bool *mef_flags, bool second)
534: {
535: regmatch_t pmatch[4];
536: regex_t re;
537: char *c, *f;
538: const char *sregexp = "^([0-9]+)(\\.[0-9]+)?([bdfirMngRhV]+)?$";
539: size_t len, nmatch;
540: int ret;
541:
542: ret = -1;
543: nmatch = 4;
544: c = f = NULL;
545:
546: if (regcomp(&re, sregexp, REG_EXTENDED) != 0)
547: return -1;
548:
549: if (regexec(&re, s, nmatch, pmatch, 0) != 0)
550: goto end;
551:
552: if (pmatch[0].rm_eo <= pmatch[0].rm_so)
553: goto end;
554:
555: if (pmatch[1].rm_eo <= pmatch[1].rm_so)
556: goto end;
557:
558: len = pmatch[1].rm_eo - pmatch[1].rm_so;
559: f = sort_malloc((len + 1) * sizeof(char));
560:
561: strncpy(f, s + pmatch[1].rm_so, len);
562: f[len] = '\0';
563:
564: if (second) {
565: errno = 0;
566: ks->f2 = (size_t) strtoul(f, NULL, 10);
567: if (errno != 0)
568: err(2, "-k");
569: if (ks->f2 == 0) {
570: warn("0 field in key specs");
571: goto end;
572: }
573: } else {
574: errno = 0;
575: ks->f1 = (size_t) strtoul(f, NULL, 10);
576: if (errno != 0)
577: err(2, "-k");
578: if (ks->f1 == 0) {
579: warn("0 field in key specs");
580: goto end;
581: }
582: }
583:
584: if (pmatch[2].rm_eo > pmatch[2].rm_so) {
585: len = pmatch[2].rm_eo - pmatch[2].rm_so - 1;
586: c = sort_malloc((len + 1) * sizeof(char));
587:
588: strncpy(c, s + pmatch[2].rm_so + 1, len);
589: c[len] = '\0';
590:
591: if (second) {
592: errno = 0;
593: ks->c2 = (size_t) strtoul(c, NULL, 10);
594: if (errno != 0)
595: err(2, "-k");
596: } else {
597: errno = 0;
598: ks->c1 = (size_t) strtoul(c, NULL, 10);
599: if (errno != 0)
600: err(2, "-k");
601: if (ks->c1 == 0) {
602: warn("0 column in key specs");
603: goto end;
604: }
605: }
606: } else {
607: if (second)
608: ks->c2 = 0;
609: else
610: ks->c1 = 1;
611: }
612:
613: if (pmatch[3].rm_eo > pmatch[3].rm_so) {
614: regoff_t i = 0;
615:
616: for (i = pmatch[3].rm_so; i < pmatch[3].rm_eo; i++) {
617: check_mutually_exclusive_flags(s[i], mef_flags);
618: if (s[i] == 'b') {
619: if (second)
620: ks->pos2b = true;
621: else
622: ks->pos1b = true;
623: } else if (!set_sort_modifier(&(ks->sm), s[i]))
624: goto end;
625: }
626: }
627:
628: ret = 0;
629:
630: end:
631:
632: if (c)
633: sort_free(c);
634: if (f)
635: sort_free(f);
636: regfree(&re);
637:
638: return ret;
639: }
640:
641: /*
642: * Parse -k option value.
643: */
644: static int
645: parse_k(const char *s, struct key_specs *ks)
646: {
647: int ret = -1;
648: bool mef_flags[NUMBER_OF_MUTUALLY_EXCLUSIVE_FLAGS] =
649: { false, false, false, false, false, false };
650:
651: if (s && *s) {
652: char *sptr;
653:
654: sptr = strchr(s, ',');
655: if (sptr) {
656: size_t size1;
657: char *pos1, *pos2;
658:
659: size1 = sptr - s;
660:
661: if (size1 < 1)
662: return -1;
663: pos1 = sort_malloc((size1 + 1) * sizeof(char));
664:
665: strncpy(pos1, s, size1);
666: pos1[size1] = '\0';
667:
668: ret = parse_pos(pos1, ks, mef_flags, false);
669:
670: sort_free(pos1);
671: if (ret < 0)
672: return ret;
673:
674: pos2 = sort_strdup(sptr + 1);
675: ret = parse_pos(pos2, ks, mef_flags, true);
676: sort_free(pos2);
677: } else
678: ret = parse_pos(s, ks, mef_flags, false);
1.1 millert 679: }
1.4 millert 680:
1.44 millert 681: return ret;
682: }
683:
684: /*
685: * Parse POS in +POS -POS option.
686: */
687: static int
688: parse_pos_obs(const char *s, int *nf, int *nc, char *sopts)
689: {
690: regex_t re;
691: regmatch_t pmatch[4];
692: char *c, *f;
693: const char *sregexp = "^([0-9]+)(\\.[0-9]+)?([A-Za-z]+)?$";
694: int ret;
695: size_t len, nmatch;
696:
697: ret = -1;
698: nmatch = 4;
699: c = f = NULL;
700: *nc = *nf = 0;
701:
702: if (regcomp(&re, sregexp, REG_EXTENDED) != 0)
703: return -1;
704:
705: if (regexec(&re, s, nmatch, pmatch, 0) != 0)
706: goto end;
707:
708: if (pmatch[0].rm_eo <= pmatch[0].rm_so)
709: goto end;
710:
711: if (pmatch[1].rm_eo <= pmatch[1].rm_so)
712: goto end;
713:
714: len = pmatch[1].rm_eo - pmatch[1].rm_so;
715: f = sort_malloc((len + 1) * sizeof(char));
716:
717: strncpy(f, s + pmatch[1].rm_so, len);
718: f[len] = '\0';
719:
720: errno = 0;
721: *nf = (size_t) strtoul(f, NULL, 10);
722: if (errno != 0)
723: errx(2, "Invalid key position");
724:
725: if (pmatch[2].rm_eo > pmatch[2].rm_so) {
726: len = pmatch[2].rm_eo - pmatch[2].rm_so - 1;
727: c = sort_malloc((len + 1) * sizeof(char));
728:
729: strncpy(c, s + pmatch[2].rm_so + 1, len);
730: c[len] = '\0';
731:
732: errno = 0;
733: *nc = (size_t) strtoul(c, NULL, 10);
734: if (errno != 0)
735: errx(2, "Invalid key position");
736: }
737:
738: if (pmatch[3].rm_eo > pmatch[3].rm_so) {
739:
740: len = pmatch[3].rm_eo - pmatch[3].rm_so;
1.4 millert 741:
1.44 millert 742: strncpy(sopts, s + pmatch[3].rm_so, len);
743: sopts[len] = '\0';
1.1 millert 744: }
1.4 millert 745:
1.44 millert 746: ret = 0;
1.4 millert 747:
1.44 millert 748: end:
749: if (c)
750: sort_free(c);
751: if (f)
752: sort_free(f);
753: regfree(&re);
754:
755: return ret;
756: }
757:
758: /*
759: * "Translate" obsolete +POS1 -POS2 syntax into new -kPOS1,POS2 syntax
760: */
761: static void
762: fix_obsolete_keys(int *argc, char **argv)
763: {
764: char sopt[129];
765: int i;
766:
767: for (i = 1; i < *argc; i++) {
768: char *arg1;
769:
770: arg1 = argv[i];
771:
772: if (strlen(arg1) > 1 && arg1[0] == '+') {
773: int c1, f1;
774: char sopts1[128];
775:
776: sopts1[0] = 0;
777: c1 = f1 = 0;
778:
779: if (parse_pos_obs(arg1 + 1, &f1, &c1, sopts1) < 0)
780: continue;
1.1 millert 781: else {
1.44 millert 782: f1 += 1;
783: c1 += 1;
784: if (i + 1 < *argc) {
785: char *arg2 = argv[i + 1];
786:
787: if (strlen(arg2) > 1 &&
788: arg2[0] == '-') {
789: int c2, f2;
790: char sopts2[128];
791:
792: sopts2[0] = 0;
793: c2 = f2 = 0;
794:
795: if (parse_pos_obs(arg2 + 1,
796: &f2, &c2, sopts2) >= 0) {
797: int j;
798: if (c2 > 0)
799: f2 += 1;
800: snprintf(sopt,
801: sizeof(sopt),
802: "-k%d.%d%s,%d.%d%s",
803: f1, c1, sopts1, f2,
804: c2, sopts2);
805: argv[i] = sort_strdup(sopt);
806: for (j = i + 1; j + 1 < *argc; j++)
807: argv[j] = argv[j + 1];
808: *argc -= 1;
809: continue;
810: }
811: }
812: }
813: snprintf(sopt, sizeof(sopt), "-k%d.%d%s",
814: f1, c1, sopts1);
815: argv[i] = sort_strdup(sopt);
1.1 millert 816: }
1.44 millert 817: }
1.1 millert 818: }
1.44 millert 819: }
820:
821: /*
822: * Set random seed
823: */
824: static void
825: set_random_seed(void)
826: {
827: if (!need_random)
828: return;
1.4 millert 829:
1.44 millert 830: MD5Init(&md5_ctx);
831: if (random_source != NULL) {
832: unsigned char buf[BUFSIZ];
833: size_t nr;
834: FILE *fp;
835:
836: if ((fp = fopen(random_source, "r")) == NULL)
837: err(2, "%s", random_source);
838: while ((nr = fread(buf, 1, sizeof(buf), fp)) != 0)
839: MD5Update(&md5_ctx, buf, nr);
840: if (ferror(fp))
841: err(2, "%s", random_source);
842: fclose(fp);
1.1 millert 843: } else {
1.44 millert 844: unsigned char rsd[1024];
845:
846: arc4random_buf(rsd, sizeof(rsd));
847: MD5Update(&md5_ctx, rsd, sizeof(rsd));
848: }
849: }
850:
851: /*
852: * Main function.
853: */
854: int
855: main(int argc, char *argv[])
856: {
857: char *outfile, *real_outfile;
858: int c, result;
859: size_t i;
860: bool mef_flags[NUMBER_OF_MUTUALLY_EXCLUSIVE_FLAGS] =
861: { false, false, false, false, false, false };
862:
863: result = 0;
864: outfile = sort_strdup("-");
865: real_outfile = NULL;
866:
867: struct sort_mods *sm = &default_sort_mods_object;
868:
869: init_tmp_files();
870:
871: set_signal_handler();
872:
873: set_hw_params();
874: set_locale();
875: set_tmpdir();
876: set_sort_opts();
877:
878: fix_obsolete_keys(&argc, argv);
879:
880: while (((c = getopt_long(argc, argv, OPTIONS, long_options, NULL))
881: != -1)) {
882:
883: check_mutually_exclusive_flags(c, mef_flags);
884:
885: if (!set_sort_modifier(sm, c)) {
886:
887: switch (c) {
888: case 'c':
889: sort_opts_vals.cflag = true;
890: if (optarg) {
891: if (!strcmp(optarg, "diagnose-first"))
892: ;
893: else if (!strcmp(optarg, "silent") ||
894: !strcmp(optarg, "quiet"))
895: sort_opts_vals.csilentflag = true;
896: else if (*optarg)
897: unknown(optarg);
898: }
899: break;
900: case 'C':
901: sort_opts_vals.cflag = true;
902: sort_opts_vals.csilentflag = true;
903: break;
904: case 'k':
905: {
906: sort_opts_vals.complex_sort = true;
907: sort_opts_vals.kflag = true;
908:
909: keys_num++;
910: keys = sort_reallocarray(keys, keys_num,
911: sizeof(struct key_specs));
912: memset(&(keys[keys_num - 1]), 0,
913: sizeof(struct key_specs));
914:
915: if (parse_k(optarg, &(keys[keys_num - 1]))
916: < 0) {
917: errc(2, EINVAL, "-k %s", optarg);
918: }
919:
920: break;
921: }
922: case 'm':
923: sort_opts_vals.mflag = true;
924: break;
925: case 'o':
926: sort_free(outfile);
927: outfile = sort_strdup(optarg);
928: break;
929: case 's':
930: sort_opts_vals.sflag = true;
931: break;
932: case 'S':
933: available_free_memory =
934: parse_memory_buffer_value(optarg);
935: break;
936: case 'T':
937: tmpdir = sort_strdup(optarg);
938: break;
939: case 't':
940: while (strlen(optarg) > 1) {
941: if (optarg[0] != '\\') {
942: errc(2, EINVAL, "%s", optarg);
943: }
944: optarg += 1;
945: if (*optarg == '0') {
946: *optarg = 0;
947: break;
948: }
949: }
950: sort_opts_vals.tflag = true;
951: sort_opts_vals.field_sep = btowc(optarg[0]);
952: if (sort_opts_vals.field_sep == WEOF) {
953: errno = EINVAL;
954: err(2, NULL);
955: }
956: if (!gnusort_numeric_compatibility) {
957: if (symbol_decimal_point == sort_opts_vals.field_sep)
958: symbol_decimal_point = WEOF;
959: if (symbol_thousands_sep == sort_opts_vals.field_sep)
960: symbol_thousands_sep = WEOF;
961: if (symbol_negative_sign == sort_opts_vals.field_sep)
962: symbol_negative_sign = WEOF;
963: if (symbol_positive_sign == sort_opts_vals.field_sep)
964: symbol_positive_sign = WEOF;
965: }
966: break;
967: case 'u':
968: sort_opts_vals.uflag = true;
969: /* stable sort for the correct unique val */
970: sort_opts_vals.sflag = true;
971: break;
972: case 'z':
973: sort_opts_vals.zflag = true;
974: break;
975: case SORT_OPT:
976: if (optarg) {
977: if (!strcmp(optarg, "general-numeric"))
978: set_sort_modifier(sm, 'g');
979: else if (!strcmp(optarg, "human-numeric"))
980: set_sort_modifier(sm, 'h');
981: else if (!strcmp(optarg, "numeric"))
982: set_sort_modifier(sm, 'n');
983: else if (!strcmp(optarg, "month"))
984: set_sort_modifier(sm, 'M');
985: else if (!strcmp(optarg, "random"))
986: set_sort_modifier(sm, 'R');
987: else
988: unknown(optarg);
989: }
990: break;
991: case QSORT_OPT:
992: sort_opts_vals.sort_method = SORT_QSORT;
993: break;
994: case 'H':
995: sort_opts_vals.sort_method = SORT_MERGESORT;
996: break;
997: case MMAP_OPT:
998: use_mmap = true;
999: break;
1000: case HEAPSORT_OPT:
1001: sort_opts_vals.sort_method = SORT_HEAPSORT;
1002: break;
1003: case RADIXSORT_OPT:
1004: sort_opts_vals.sort_method = SORT_RADIXSORT;
1005: break;
1006: case RANDOMSOURCE_OPT:
1007: random_source = strdup(optarg);
1008: break;
1009: case COMPRESSPROGRAM_OPT:
1010: compress_program = strdup(optarg);
1011: break;
1012: case FF_OPT:
1013: read_fns_from_file0(optarg);
1014: break;
1015: case BS_OPT:
1016: {
1017: errno = 0;
1018: long mof = strtol(optarg, NULL, 10);
1019: if (errno != 0)
1020: err(2, "--batch-size");
1021: if (mof >= 2)
1022: max_open_files = (size_t) mof + 1;
1023: }
1024: break;
1025: case VERSION_OPT:
1026: printf("%s\n", VERSION);
1027: exit(EXIT_SUCCESS);
1028: /* NOTREACHED */
1029: break;
1030: case DEBUG_OPT:
1031: debug_sort = true;
1032: break;
1033: case HELP_OPT:
1034: usage(0);
1035: /* NOTREACHED */
1036: break;
1037: default:
1038: usage(2);
1039: /* NOTREACHED */
1040: }
1041: }
1042: }
1043:
1044: argc -= optind;
1045: argv += optind;
1046:
1047: if (sort_opts_vals.cflag && sort_opts_vals.mflag)
1048: errx(1, "%c:%c: mutually exclusive flags", 'm', 'c');
1049:
1050: if (keys_num == 0) {
1051: keys_num = 1;
1052: keys = sort_realloc(keys, sizeof(struct key_specs));
1053: memset(&(keys[0]), 0, sizeof(struct key_specs));
1054: keys[0].c1 = 1;
1055: keys[0].pos1b = default_sort_mods->bflag;
1056: keys[0].pos2b = default_sort_mods->bflag;
1057: memcpy(&(keys[0].sm), default_sort_mods,
1058: sizeof(struct sort_mods));
1059: }
1060:
1061: for (i = 0; i < keys_num; i++) {
1062: struct key_specs *ks;
1063:
1064: ks = &(keys[i]);
1065:
1066: if (sort_modifier_empty(&(ks->sm)) && !(ks->pos1b) &&
1067: !(ks->pos2b)) {
1068: ks->pos1b = sm->bflag;
1069: ks->pos2b = sm->bflag;
1070: memcpy(&(ks->sm), sm, sizeof(struct sort_mods));
1071: }
1072:
1073: ks->sm.func = get_sort_func(&(ks->sm));
1074: }
1075:
1076: if (argv_from_file0) {
1077: argc = argc_from_file0;
1078: argv = argv_from_file0;
1079: }
1080:
1081: if (debug_sort) {
1082: printf("Memory to be used for sorting: %llu\n",
1083: available_free_memory);
1084: printf("Using collate rules of %s locale\n",
1085: setlocale(LC_COLLATE, NULL));
1086: if (byte_sort)
1087: printf("Byte sort is used\n");
1088: if (print_symbols_on_debug) {
1089: printf("Decimal Point: <%lc>\n", symbol_decimal_point);
1090: if (symbol_thousands_sep)
1091: printf("Thousands separator: <%lc>\n",
1092: symbol_thousands_sep);
1093: printf("Positive sign: <%lc>\n", symbol_positive_sign);
1094: printf("Negative sign: <%lc>\n", symbol_negative_sign);
1095: }
1096: }
1097:
1098: set_random_seed();
1.4 millert 1099:
1.44 millert 1100: /* Case when the outfile equals one of the input files: */
1101: if (strcmp(outfile, "-")) {
1102: int i;
1103:
1104: for (i = 0; i < argc; ++i) {
1105: if (strcmp(argv[i], outfile) == 0) {
1106: real_outfile = sort_strdup(outfile);
1107: for (;;) {
1108: const size_t size = strlen(outfile) + strlen(".tmp") + 1;
1109: outfile = sort_realloc(outfile, size);
1110: strlcat(outfile, ".tmp", size);
1111: if (access(outfile, F_OK) < 0)
1112: break;
1113: }
1114: tmp_file_atexit(outfile);
1115: }
1116: }
1117: }
1118:
1119: if (!sort_opts_vals.cflag && !sort_opts_vals.mflag) {
1120: struct file_list fl;
1121: struct sort_list list;
1122:
1123: sort_list_init(&list);
1124: file_list_init(&fl, true);
1125:
1126: if (argc < 1)
1127: procfile("-", &list, &fl);
1128: else {
1129: while (argc > 0) {
1130: procfile(*argv, &list, &fl);
1131: --argc;
1132: ++argv;
1133: }
1134: }
1135:
1136: if (fl.count < 1)
1137: sort_list_to_file(&list, outfile);
1138: else {
1139: if (list.count > 0) {
1140: char *flast = new_tmp_file_name();
1141:
1142: sort_list_to_file(&list, flast);
1143: file_list_add(&fl, flast, false);
1144: }
1145: merge_files(&fl, outfile);
1146: }
1147:
1148: file_list_clean(&fl);
1149:
1150: /*
1151: * We are about to exit the program, so we can ignore
1152: * the clean-up for speed
1153: *
1154: * sort_list_clean(&list);
1155: */
1156:
1157: } else if (sort_opts_vals.cflag) {
1158: result = (argc == 0) ? (check("-")) : (check(*argv));
1159: } else if (sort_opts_vals.mflag) {
1160: struct file_list fl;
1161:
1162: file_list_init(&fl, false);
1163: file_list_populate(&fl, argc, argv, true);
1164: merge_files(&fl, outfile);
1165: file_list_clean(&fl);
1166: }
1167:
1168: if (real_outfile) {
1169: unlink(real_outfile);
1170: if (rename(outfile, real_outfile) < 0)
1171: err(2, "%s", real_outfile);
1172: sort_free(real_outfile);
1173: }
1174:
1175: sort_free(outfile);
1.4 millert 1176:
1.44 millert 1177: return result;
1.1 millert 1178: }