Annotation of src/usr.bin/sort/sort.c, Revision 1.67
1.67 ! millert 1: /* $OpenBSD: sort.c,v 1.66 2015/04/01 21:45:50 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: return !(sm->Mflag || sm->Vflag || sm->nflag || sm->gflag ||
147: sm->rflag || sm->Rflag || sm->hflag || sm->dflag || sm->fflag);
148: }
149:
150: /*
151: * Print out usage text.
152: */
153: static __dead void
154: usage(int exit_val)
155: {
156: fprintf(exit_val ? stderr : stdout,
1.46 jmc 157: "usage: %s [-bCcdfgHhiMmnRrsuVz] [-k field1[,field2]] [-o output] "
1.45 jmc 158: "[-S size]\n\t[-T dir] [-t char] [file ...]\n", getprogname());
1.44 millert 159: exit(exit_val);
160: }
1.4 millert 161:
1.1 millert 162: /*
1.44 millert 163: * Read input file names from a file (file0-from option).
1.1 millert 164: */
1.44 millert 165: static void
166: read_fns_from_file0(const char *fn)
167: {
1.47 millert 168: FILE *f;
169: char *line = NULL;
170: size_t linesize = 0;
171: ssize_t linelen;
172:
173: f = fopen(fn, "r");
174: if (f == NULL)
175: err(2, "%s", fn);
176:
177: while ((linelen = getdelim(&line, &linesize, '\0', f)) != -1) {
178: if (*line != '\0') {
179: if (argc_from_file0 == (size_t)-1)
180: argc_from_file0 = 0;
181: ++argc_from_file0;
182: argv_from_file0 = sort_reallocarray(argv_from_file0,
183: argc_from_file0, sizeof(char *));
184: argv_from_file0[argc_from_file0 - 1] = line;
185: } else {
186: free(line);
1.44 millert 187: }
1.47 millert 188: line = NULL;
189: linesize = 0;
1.44 millert 190: }
1.47 millert 191: if (ferror(f))
192: err(2, "%s: getdelim", fn);
193:
194: closefile(f, fn);
1.44 millert 195: }
1.4 millert 196:
1.1 millert 197: /*
1.44 millert 198: * Check how much RAM is available for the sort.
1.1 millert 199: */
1.44 millert 200: static void
201: set_hw_params(void)
202: {
1.48 millert 203: long long user_memory;
204: struct rlimit rl;
205: size_t len;
206: int mib[] = { CTL_HW, HW_USERMEM64 };
207:
208: /* Get total user (non-kernel) memory. */
209: len = sizeof(user_memory);
210: if (sysctl(mib, 2, &user_memory, &len, NULL, 0) == -1)
211: user_memory = -1;
212:
213: /* Increase our data size to the max */
214: if (getrlimit(RLIMIT_DATA, &rl) == 0) {
215: free_memory = (unsigned long long)rl.rlim_cur;
216: rl.rlim_cur = rl.rlim_max;
217: if (setrlimit(RLIMIT_DATA, &rl) == 0) {
218: free_memory = (unsigned long long)rl.rlim_max;
219: } else {
220: warn("Can't set resource limit to max data size");
221: }
222: } else
223: warn("Can't get resource limit for data size");
1.1 millert 224:
1.48 millert 225: /* We prefer to use temp files rather than swap space. */
226: if (user_memory != -1 && free_memory > user_memory)
227: free_memory = user_memory;
1.44 millert 228:
229: available_free_memory = free_memory / 2;
230: }
231:
232: /*
233: * Convert "plain" symbol to wide symbol, with default value.
234: */
235: static void
236: conv_mbtowc(wchar_t *wc, const char *c, const wchar_t def)
237: {
1.66 millert 238: int res;
1.1 millert 239:
1.66 millert 240: res = mbtowc(wc, c, MB_CUR_MAX);
241: if (res < 1)
242: *wc = def;
1.44 millert 243: }
1.12 millert 244:
1.44 millert 245: /*
246: * Set current locale symbols.
247: */
248: static void
249: set_locale(void)
1.1 millert 250: {
1.44 millert 251: struct lconv *lc;
252: const char *locale;
1.4 millert 253:
1.16 ericj 254: setlocale(LC_ALL, "");
255:
1.66 millert 256: /* Obtain LC_NUMERIC info */
1.44 millert 257: lc = localeconv();
258:
1.66 millert 259: /* Convert to wide char form */
260: conv_mbtowc(&symbol_decimal_point, lc->decimal_point,
261: symbol_decimal_point);
262: conv_mbtowc(&symbol_thousands_sep, lc->thousands_sep,
263: symbol_thousands_sep);
264: conv_mbtowc(&symbol_positive_sign, lc->positive_sign,
265: symbol_positive_sign);
266: conv_mbtowc(&symbol_negative_sign, lc->negative_sign,
267: symbol_negative_sign);
1.44 millert 268:
269: if (getenv("GNUSORT_NUMERIC_COMPATIBILITY"))
270: gnusort_numeric_compatibility = true;
271:
272: locale = setlocale(LC_COLLATE, NULL);
273: if (locale != NULL) {
274: char *tmpl;
275: const char *byteclocale;
276:
277: tmpl = sort_strdup(locale);
278: byteclocale = setlocale(LC_COLLATE, "C");
279: if (byteclocale && strcmp(byteclocale, tmpl) == 0) {
280: byte_sort = true;
281: } else {
282: byteclocale = setlocale(LC_COLLATE, "POSIX");
283: if (byteclocale && strcmp(byteclocale, tmpl) == 0)
284: byte_sort = true;
285: else
286: setlocale(LC_COLLATE, tmpl);
287: }
288: sort_free(tmpl);
289: }
290: if (!byte_sort)
291: sort_mb_cur_max = MB_CUR_MAX;
292: }
293:
294: /*
295: * Set directory temporary files.
296: */
297: static void
298: set_tmpdir(void)
299: {
1.53 millert 300: if (!issetugid()) {
301: char *td;
1.44 millert 302:
1.53 millert 303: td = getenv("TMPDIR");
304: if (td != NULL)
305: tmpdir = sort_strdup(td);
306: }
1.44 millert 307: }
308:
309: /*
310: * Parse -S option.
311: */
312: static unsigned long long
313: parse_memory_buffer_value(const char *value)
314: {
1.66 millert 315: char *endptr;
316: unsigned long long membuf;
317:
318: membuf = strtoll(value, &endptr, 10);
319: if (endptr == value || (long long)membuf < 0 ||
320: (errno == ERANGE && membuf == LLONG_MAX))
321: errx(2, "invalid memory buffer size: %s", value);
322:
323: switch (*endptr) {
324: case 'Y':
325: membuf *= 1024;
326: /* FALLTHROUGH */
327: case 'Z':
328: membuf *= 1024;
329: /* FALLTHROUGH */
330: case 'E':
331: membuf *= 1024;
332: /* FALLTHROUGH */
333: case 'P':
334: membuf *= 1024;
335: /* FALLTHROUGH */
336: case 'T':
337: membuf *= 1024;
338: /* FALLTHROUGH */
339: case 'G':
340: membuf *= 1024;
341: /* FALLTHROUGH */
342: case 'M':
343: membuf *= 1024;
344: /* FALLTHROUGH */
345: case '\0':
346: case 'K':
347: membuf *= 1024;
348: /* FALLTHROUGH */
349: case 'b':
350: break;
351: case '%':
352: membuf = (available_free_memory * membuf) /
353: 100;
354: break;
355: default:
356: warnc(EINVAL, "%s", optarg);
357: membuf = available_free_memory;
1.44 millert 358: }
1.66 millert 359: return membuf;
1.44 millert 360: }
361:
362: /*
363: * Signal handler that clears the temporary files.
364: */
365: static void
1.49 millert 366: sig_handler(int sig __unused)
1.44 millert 367: {
368: clear_tmp_files();
1.50 millert 369: _exit(2);
1.44 millert 370: }
371:
372: /*
373: * Set signal handler on panic signals.
374: */
375: static void
376: set_signal_handler(void)
377: {
378: struct sigaction sa;
1.49 millert 379: int i, signals[] = {SIGTERM, SIGHUP, SIGINT, SIGQUIT, SIGUSR1, SIGUSR2,
380: SIGPIPE, SIGXCPU, SIGXFSZ, SIGVTALRM, SIGPROF, 0};
1.44 millert 381:
382: memset(&sa, 0, sizeof(sa));
1.49 millert 383: sigfillset(&sa.sa_mask);
384: sa.sa_flags = SA_RESTART;
385: sa.sa_handler = sig_handler;
386:
387: for (i = 0; signals[i] != 0; i++) {
388: if (sigaction(signals[i], &sa, NULL) < 0) {
389: warn("sigaction(%d)", i);
390: continue;
391: }
1.44 millert 392: }
393: }
394:
395: /*
396: * Print "unknown" message and exit with status 2.
397: */
398: static void
399: unknown(const char *what)
400: {
401: errx(2, "Unknown feature: %s", what);
402: }
403:
404: /*
405: * Check whether contradictory input options are used.
406: */
407: static void
408: check_mutually_exclusive_flags(char c, bool *mef_flags)
409: {
410: int i, fo_index, mec;
411: bool found_others, found_this;
412:
413: found_others = found_this =false;
414: fo_index = 0;
415:
416: for (i = 0; i < NUMBER_OF_MUTUALLY_EXCLUSIVE_FLAGS; i++) {
417: mec = mutually_exclusive_flags[i];
418:
419: if (mec != c) {
420: if (mef_flags[i]) {
1.65 millert 421: if (found_this) {
422: errx(2,
423: "%c:%c: mutually exclusive flags",
424: c, mec);
425: }
1.44 millert 426: found_others = true;
427: fo_index = i;
428: }
429: } else {
1.65 millert 430: if (found_others) {
431: errx(2,
432: "%c:%c: mutually exclusive flags",
433: c, mutually_exclusive_flags[fo_index]);
434: }
1.44 millert 435: mef_flags[i] = true;
436: found_this = true;
437: }
438: }
439: }
440:
441: /*
442: * Initialise sort opts data.
443: */
444: static void
445: set_sort_opts(void)
446: {
447: memset(&default_sort_mods_object, 0,
448: sizeof(default_sort_mods_object));
449: memset(&sort_opts_vals, 0, sizeof(sort_opts_vals));
450: default_sort_mods_object.func =
451: get_sort_func(&default_sort_mods_object);
452: }
453:
454: /*
455: * Set a sort modifier on a sort modifiers object.
456: */
457: static bool
458: set_sort_modifier(struct sort_mods *sm, int c)
459: {
1.66 millert 460: switch (c) {
461: case 'b':
462: sm->bflag = true;
463: break;
464: case 'd':
465: sm->dflag = true;
466: break;
467: case 'f':
468: sm->fflag = true;
469: break;
470: case 'g':
471: sm->gflag = true;
472: need_hint = true;
473: break;
474: case 'i':
475: sm->iflag = true;
476: break;
477: case 'R':
478: sm->Rflag = true;
479: need_random = true;
480: break;
481: case 'M':
482: initialise_months();
483: sm->Mflag = true;
484: need_hint = true;
485: break;
486: case 'n':
487: sm->nflag = true;
488: need_hint = true;
489: print_symbols_on_debug = true;
490: break;
491: case 'r':
492: sm->rflag = true;
493: break;
494: case 'V':
495: sm->Vflag = true;
496: break;
497: case 'h':
498: sm->hflag = true;
499: need_hint = true;
500: print_symbols_on_debug = true;
501: break;
502: default:
503: return false;
1.44 millert 504: }
1.66 millert 505: sort_opts_vals.complex_sort = true;
506: sm->func = get_sort_func(sm);
507:
1.44 millert 508: return true;
509: }
510:
511: /*
512: * Parse POS in -k option.
513: */
514: static int
515: parse_pos(const char *s, struct key_specs *ks, bool *mef_flags, bool second)
516: {
517: regmatch_t pmatch[4];
518: regex_t re;
519: char *c, *f;
520: const char *sregexp = "^([0-9]+)(\\.[0-9]+)?([bdfirMngRhV]+)?$";
521: size_t len, nmatch;
522: int ret;
523:
524: ret = -1;
525: nmatch = 4;
526: c = f = NULL;
527:
528: if (regcomp(&re, sregexp, REG_EXTENDED) != 0)
529: return -1;
530:
531: if (regexec(&re, s, nmatch, pmatch, 0) != 0)
532: goto end;
533:
534: if (pmatch[0].rm_eo <= pmatch[0].rm_so)
535: goto end;
536:
537: if (pmatch[1].rm_eo <= pmatch[1].rm_so)
538: goto end;
539:
540: len = pmatch[1].rm_eo - pmatch[1].rm_so;
541:
1.57 millert 542: f = sort_malloc(len + 1);
543: memcpy(f, s + pmatch[1].rm_so, len);
1.44 millert 544: f[len] = '\0';
545:
546: if (second) {
547: errno = 0;
1.58 millert 548: ks->f2 = (size_t)strtoul(f, NULL, 10);
1.44 millert 549: if (errno != 0)
1.58 millert 550: goto end;
1.44 millert 551: if (ks->f2 == 0) {
552: warn("0 field in key specs");
553: goto end;
554: }
555: } else {
556: errno = 0;
1.58 millert 557: ks->f1 = (size_t)strtoul(f, NULL, 10);
1.44 millert 558: if (errno != 0)
1.58 millert 559: goto end;
1.44 millert 560: if (ks->f1 == 0) {
561: warn("0 field in key specs");
562: goto end;
563: }
564: }
565:
566: if (pmatch[2].rm_eo > pmatch[2].rm_so) {
567: len = pmatch[2].rm_eo - pmatch[2].rm_so - 1;
568:
1.57 millert 569: c = sort_malloc(len + 1);
570: memcpy(c, s + pmatch[2].rm_so + 1, len);
1.44 millert 571: c[len] = '\0';
572:
573: if (second) {
574: errno = 0;
1.58 millert 575: ks->c2 = (size_t)strtoul(c, NULL, 10);
1.44 millert 576: if (errno != 0)
1.58 millert 577: goto end;
1.44 millert 578: } else {
579: errno = 0;
1.58 millert 580: ks->c1 = (size_t)strtoul(c, NULL, 10);
1.44 millert 581: if (errno != 0)
1.58 millert 582: goto end;
1.44 millert 583: if (ks->c1 == 0) {
584: warn("0 column in key specs");
585: goto end;
586: }
587: }
588: } else {
589: if (second)
590: ks->c2 = 0;
591: else
592: ks->c1 = 1;
593: }
594:
595: if (pmatch[3].rm_eo > pmatch[3].rm_so) {
596: regoff_t i = 0;
597:
598: for (i = pmatch[3].rm_so; i < pmatch[3].rm_eo; i++) {
599: check_mutually_exclusive_flags(s[i], mef_flags);
600: if (s[i] == 'b') {
601: if (second)
602: ks->pos2b = true;
603: else
604: ks->pos1b = true;
605: } else if (!set_sort_modifier(&(ks->sm), s[i]))
606: goto end;
607: }
608: }
609:
610: ret = 0;
611:
612: end:
1.61 millert 613: sort_free(c);
614: sort_free(f);
1.44 millert 615: regfree(&re);
616:
617: return ret;
618: }
619:
620: /*
621: * Parse -k option value.
622: */
623: static int
624: parse_k(const char *s, struct key_specs *ks)
625: {
626: int ret = -1;
627: bool mef_flags[NUMBER_OF_MUTUALLY_EXCLUSIVE_FLAGS] =
628: { false, false, false, false, false, false };
629:
1.66 millert 630: if (*s != '\0') {
1.44 millert 631: char *sptr;
632:
633: sptr = strchr(s, ',');
634: if (sptr) {
635: size_t size1;
636: char *pos1, *pos2;
637:
638: size1 = sptr - s;
639:
640: if (size1 < 1)
641: return -1;
642:
1.57 millert 643: pos1 = sort_malloc(size1 + 1);
644: memcpy(pos1, s, size1);
1.44 millert 645: pos1[size1] = '\0';
646:
647: ret = parse_pos(pos1, ks, mef_flags, false);
648:
649: sort_free(pos1);
650: if (ret < 0)
651: return ret;
652:
653: pos2 = sort_strdup(sptr + 1);
654: ret = parse_pos(pos2, ks, mef_flags, true);
655: sort_free(pos2);
656: } else
657: ret = parse_pos(s, ks, mef_flags, false);
1.1 millert 658: }
1.4 millert 659:
1.44 millert 660: return ret;
661: }
662:
663: /*
664: * Parse POS in +POS -POS option.
665: */
666: static int
1.66 millert 667: parse_pos_obs(const char *s, size_t *nf, size_t *nc, char *sopts, size_t sopts_size)
1.44 millert 668: {
669: regex_t re;
670: regmatch_t pmatch[4];
671: char *c, *f;
672: const char *sregexp = "^([0-9]+)(\\.[0-9]+)?([A-Za-z]+)?$";
673: int ret;
674: size_t len, nmatch;
675:
676: ret = -1;
677: nmatch = 4;
678: c = f = NULL;
679: *nc = *nf = 0;
680:
681: if (regcomp(&re, sregexp, REG_EXTENDED) != 0)
682: return -1;
683:
684: if (regexec(&re, s, nmatch, pmatch, 0) != 0)
685: goto end;
686:
687: if (pmatch[0].rm_eo <= pmatch[0].rm_so)
688: goto end;
689:
690: if (pmatch[1].rm_eo <= pmatch[1].rm_so)
691: goto end;
692:
693: len = pmatch[1].rm_eo - pmatch[1].rm_so;
694:
1.57 millert 695: f = sort_malloc(len + 1);
696: memcpy(f, s + pmatch[1].rm_so, len);
1.44 millert 697: f[len] = '\0';
698:
699: errno = 0;
1.66 millert 700: *nf = (size_t)strtoul(f, NULL, 10);
1.44 millert 701: if (errno != 0)
702: errx(2, "Invalid key position");
703:
704: if (pmatch[2].rm_eo > pmatch[2].rm_so) {
705: len = pmatch[2].rm_eo - pmatch[2].rm_so - 1;
1.57 millert 706:
1.63 millert 707: c = sort_malloc(len + 1);
1.57 millert 708: memcpy(c, s + pmatch[2].rm_so + 1, len);
1.44 millert 709: c[len] = '\0';
710:
711: errno = 0;
1.66 millert 712: *nc = (size_t)strtoul(c, NULL, 10);
1.44 millert 713: if (errno != 0)
714: errx(2, "Invalid key position");
715: }
716:
717: if (pmatch[3].rm_eo > pmatch[3].rm_so) {
718:
719: len = pmatch[3].rm_eo - pmatch[3].rm_so;
1.4 millert 720:
1.56 millert 721: if (len >= sopts_size)
722: errx(2, "Invalid key position");
1.57 millert 723: memcpy(sopts, s + pmatch[3].rm_so, len);
1.44 millert 724: sopts[len] = '\0';
1.1 millert 725: }
1.4 millert 726:
1.44 millert 727: ret = 0;
1.4 millert 728:
1.44 millert 729: end:
1.61 millert 730: sort_free(c);
731: sort_free(f);
1.44 millert 732: regfree(&re);
733:
734: return ret;
735: }
736:
737: /*
738: * "Translate" obsolete +POS1 -POS2 syntax into new -kPOS1,POS2 syntax
739: */
740: static void
741: fix_obsolete_keys(int *argc, char **argv)
742: {
743: char sopt[129];
744: int i;
745:
746: for (i = 1; i < *argc; i++) {
1.60 millert 747: const char *arg1 = argv[i];
1.44 millert 748:
1.60 millert 749: if (arg1[0] == '+') {
1.56 millert 750: size_t c1, f1;
1.44 millert 751: char sopts1[128];
752:
753: sopts1[0] = 0;
754: c1 = f1 = 0;
755:
1.56 millert 756: if (parse_pos_obs(arg1 + 1, &f1, &c1, sopts1,
757: sizeof(sopts1)) < 0)
1.44 millert 758: continue;
1.60 millert 759:
760: f1 += 1;
761: c1 += 1;
762: if (i + 1 < *argc) {
763: const char *arg2 = argv[i + 1];
764:
765: if (arg2[0] == '-') {
766: size_t c2, f2;
767: char sopts2[128];
768:
769: sopts2[0] = 0;
770: c2 = f2 = 0;
771:
772: if (parse_pos_obs(arg2 + 1, &f2, &c2,
773: sopts2, sizeof(sopts2)) >= 0) {
774: int j;
775: if (c2 > 0)
776: f2 += 1;
777: snprintf(sopt, sizeof(sopt),
778: "-k%zu.%zu%s,%zu.%zu%s",
779: f1, c1, sopts1, f2,
780: c2, sopts2);
781: argv[i] = sort_strdup(sopt);
782: for (j = i + 1; j + 1 < *argc; j++)
783: argv[j] = argv[j + 1];
784: *argc -= 1;
785: continue;
1.44 millert 786: }
787: }
1.1 millert 788: }
1.60 millert 789: snprintf(sopt, sizeof(sopt), "-k%zu.%zu%s",
790: f1, c1, sopts1);
791: argv[i] = sort_strdup(sopt);
1.44 millert 792: }
1.1 millert 793: }
1.44 millert 794: }
795:
796: /*
797: * Set random seed
798: */
799: static void
800: set_random_seed(void)
801: {
802: if (!need_random)
803: return;
1.4 millert 804:
1.44 millert 805: MD5Init(&md5_ctx);
806: if (random_source != NULL) {
807: unsigned char buf[BUFSIZ];
808: size_t nr;
809: FILE *fp;
810:
811: if ((fp = fopen(random_source, "r")) == NULL)
812: err(2, "%s", random_source);
813: while ((nr = fread(buf, 1, sizeof(buf), fp)) != 0)
814: MD5Update(&md5_ctx, buf, nr);
815: if (ferror(fp))
816: err(2, "%s", random_source);
817: fclose(fp);
1.1 millert 818: } else {
1.44 millert 819: unsigned char rsd[1024];
820:
821: arc4random_buf(rsd, sizeof(rsd));
822: MD5Update(&md5_ctx, rsd, sizeof(rsd));
823: }
824: }
825:
826: /*
827: * Main function.
828: */
829: int
830: main(int argc, char *argv[])
831: {
832: char *outfile, *real_outfile;
833: int c, result;
834: size_t i;
835: bool mef_flags[NUMBER_OF_MUTUALLY_EXCLUSIVE_FLAGS] =
836: { false, false, false, false, false, false };
837:
838: result = 0;
1.51 millert 839: outfile = "-";
1.44 millert 840: real_outfile = NULL;
841:
842: struct sort_mods *sm = &default_sort_mods_object;
843:
844: init_tmp_files();
845:
846: set_signal_handler();
847:
1.51 millert 848: atexit(clear_tmp_files);
849:
1.44 millert 850: set_hw_params();
851: set_locale();
852: set_tmpdir();
853: set_sort_opts();
854:
855: fix_obsolete_keys(&argc, argv);
856:
857: while (((c = getopt_long(argc, argv, OPTIONS, long_options, NULL))
858: != -1)) {
859:
860: check_mutually_exclusive_flags(c, mef_flags);
861:
862: if (!set_sort_modifier(sm, c)) {
863: switch (c) {
864: case 'c':
865: sort_opts_vals.cflag = true;
866: if (optarg) {
867: if (!strcmp(optarg, "diagnose-first"))
868: ;
869: else if (!strcmp(optarg, "silent") ||
870: !strcmp(optarg, "quiet"))
871: sort_opts_vals.csilentflag = true;
872: else if (*optarg)
873: unknown(optarg);
874: }
875: break;
876: case 'C':
877: sort_opts_vals.cflag = true;
878: sort_opts_vals.csilentflag = true;
879: break;
880: case 'k':
881: {
882: sort_opts_vals.complex_sort = true;
883: sort_opts_vals.kflag = true;
884:
885: keys_num++;
886: keys = sort_reallocarray(keys, keys_num,
887: sizeof(struct key_specs));
888: memset(&(keys[keys_num - 1]), 0,
889: sizeof(struct key_specs));
890:
1.66 millert 891: if (parse_k(optarg, &(keys[keys_num - 1])) < 0)
1.44 millert 892: errc(2, EINVAL, "-k %s", optarg);
893:
894: break;
895: }
896: case 'm':
897: sort_opts_vals.mflag = true;
898: break;
899: case 'o':
1.51 millert 900: outfile = optarg;
1.44 millert 901: break;
902: case 's':
903: sort_opts_vals.sflag = true;
904: break;
905: case 'S':
906: available_free_memory =
907: parse_memory_buffer_value(optarg);
908: break;
909: case 'T':
910: tmpdir = sort_strdup(optarg);
911: break;
912: case 't':
913: while (strlen(optarg) > 1) {
914: if (optarg[0] != '\\') {
915: errc(2, EINVAL, "%s", optarg);
916: }
917: optarg += 1;
918: if (*optarg == '0') {
919: *optarg = 0;
920: break;
921: }
922: }
923: sort_opts_vals.tflag = true;
924: sort_opts_vals.field_sep = btowc(optarg[0]);
925: if (sort_opts_vals.field_sep == WEOF) {
926: errno = EINVAL;
927: err(2, NULL);
928: }
929: if (!gnusort_numeric_compatibility) {
930: if (symbol_decimal_point == sort_opts_vals.field_sep)
931: symbol_decimal_point = WEOF;
932: if (symbol_thousands_sep == sort_opts_vals.field_sep)
933: symbol_thousands_sep = WEOF;
934: if (symbol_negative_sign == sort_opts_vals.field_sep)
935: symbol_negative_sign = WEOF;
936: if (symbol_positive_sign == sort_opts_vals.field_sep)
937: symbol_positive_sign = WEOF;
938: }
939: break;
940: case 'u':
941: sort_opts_vals.uflag = true;
942: /* stable sort for the correct unique val */
943: sort_opts_vals.sflag = true;
944: break;
945: case 'z':
946: sort_opts_vals.zflag = true;
947: break;
948: case SORT_OPT:
1.62 millert 949: if (!strcmp(optarg, "general-numeric"))
950: set_sort_modifier(sm, 'g');
951: else if (!strcmp(optarg, "human-numeric"))
952: set_sort_modifier(sm, 'h');
953: else if (!strcmp(optarg, "numeric"))
954: set_sort_modifier(sm, 'n');
955: else if (!strcmp(optarg, "month"))
956: set_sort_modifier(sm, 'M');
957: else if (!strcmp(optarg, "random"))
958: set_sort_modifier(sm, 'R');
959: else
960: unknown(optarg);
1.44 millert 961: break;
962: case QSORT_OPT:
963: sort_opts_vals.sort_method = SORT_QSORT;
964: break;
965: case 'H':
966: sort_opts_vals.sort_method = SORT_MERGESORT;
967: break;
968: case MMAP_OPT:
969: use_mmap = true;
970: break;
971: case HEAPSORT_OPT:
972: sort_opts_vals.sort_method = SORT_HEAPSORT;
973: break;
974: case RADIXSORT_OPT:
975: sort_opts_vals.sort_method = SORT_RADIXSORT;
976: break;
977: case RANDOMSOURCE_OPT:
978: random_source = strdup(optarg);
979: break;
980: case COMPRESSPROGRAM_OPT:
981: compress_program = strdup(optarg);
982: break;
983: case FF_OPT:
984: read_fns_from_file0(optarg);
985: break;
986: case BS_OPT:
987: {
1.54 millert 988: const char *errstr;
989:
990: max_open_files = strtonum(optarg, 2,
991: UINT_MAX - 1, &errstr) + 1;
992: if (errstr != NULL)
993: errx(2, "--batch-size argument is %s",
994: errstr);
995: break;
1.44 millert 996: }
997: case VERSION_OPT:
998: printf("%s\n", VERSION);
999: exit(EXIT_SUCCESS);
1000: /* NOTREACHED */
1001: break;
1002: case DEBUG_OPT:
1003: debug_sort = true;
1004: break;
1005: case HELP_OPT:
1006: usage(0);
1007: /* NOTREACHED */
1008: break;
1009: default:
1010: usage(2);
1011: /* NOTREACHED */
1012: }
1013: }
1014: }
1015:
1016: argc -= optind;
1017: argv += optind;
1018:
1019: if (keys_num == 0) {
1020: keys_num = 1;
1.67 ! millert 1021: keys = sort_reallocarray(keys, 1, sizeof(struct key_specs));
1.44 millert 1022: memset(&(keys[0]), 0, sizeof(struct key_specs));
1023: keys[0].c1 = 1;
1024: keys[0].pos1b = default_sort_mods->bflag;
1025: keys[0].pos2b = default_sort_mods->bflag;
1026: memcpy(&(keys[0].sm), default_sort_mods,
1027: sizeof(struct sort_mods));
1028: }
1029:
1030: for (i = 0; i < keys_num; i++) {
1031: struct key_specs *ks;
1032:
1033: ks = &(keys[i]);
1034:
1035: if (sort_modifier_empty(&(ks->sm)) && !(ks->pos1b) &&
1036: !(ks->pos2b)) {
1037: ks->pos1b = sm->bflag;
1038: ks->pos2b = sm->bflag;
1039: memcpy(&(ks->sm), sm, sizeof(struct sort_mods));
1040: }
1041:
1042: ks->sm.func = get_sort_func(&(ks->sm));
1043: }
1044:
1045: if (argv_from_file0) {
1046: argc = argc_from_file0;
1047: argv = argv_from_file0;
1048: }
1049:
1050: if (debug_sort) {
1051: printf("Memory to be used for sorting: %llu\n",
1052: available_free_memory);
1053: printf("Using collate rules of %s locale\n",
1054: setlocale(LC_COLLATE, NULL));
1055: if (byte_sort)
1056: printf("Byte sort is used\n");
1057: if (print_symbols_on_debug) {
1058: printf("Decimal Point: <%lc>\n", symbol_decimal_point);
1059: if (symbol_thousands_sep)
1060: printf("Thousands separator: <%lc>\n",
1061: symbol_thousands_sep);
1062: printf("Positive sign: <%lc>\n", symbol_positive_sign);
1063: printf("Negative sign: <%lc>\n", symbol_negative_sign);
1064: }
1065: }
1066:
1067: set_random_seed();
1.4 millert 1068:
1.44 millert 1069: /* Case when the outfile equals one of the input files: */
1.51 millert 1070: if (strcmp(outfile, "-") != 0) {
1071: struct stat sb;
1072: int fd, i;
1.44 millert 1073:
1074: for (i = 0; i < argc; ++i) {
1075: if (strcmp(argv[i], outfile) == 0) {
1.51 millert 1076: if (stat(outfile, &sb) == -1)
1077: err(2, "%s", outfile);
1078: if (access(outfile, W_OK) == -1)
1079: err(2, "%s", outfile);
1080: real_outfile = outfile;
1081: sort_asprintf(&outfile, "%s.XXXXXXXXXX",
1082: real_outfile);
1083: if ((fd = mkstemp(outfile)) == -1 ||
1084: fchmod(fd, sb.st_mode & ALLPERMS) == -1)
1085: err(2, "%s", outfile);
1086: close(fd);
1.44 millert 1087: tmp_file_atexit(outfile);
1.51 millert 1088: break;
1.44 millert 1089: }
1090: }
1091: }
1092:
1093: if (!sort_opts_vals.cflag && !sort_opts_vals.mflag) {
1094: struct file_list fl;
1095: struct sort_list list;
1096:
1097: sort_list_init(&list);
1098: file_list_init(&fl, true);
1099:
1100: if (argc < 1)
1101: procfile("-", &list, &fl);
1102: else {
1103: while (argc > 0) {
1104: procfile(*argv, &list, &fl);
1105: --argc;
1106: ++argv;
1107: }
1108: }
1109:
1110: if (fl.count < 1)
1111: sort_list_to_file(&list, outfile);
1112: else {
1113: if (list.count > 0) {
1114: char *flast = new_tmp_file_name();
1115:
1116: sort_list_to_file(&list, flast);
1117: file_list_add(&fl, flast, false);
1118: }
1119: merge_files(&fl, outfile);
1120: }
1121:
1122: file_list_clean(&fl);
1123:
1124: /*
1125: * We are about to exit the program, so we can ignore
1126: * the clean-up for speed
1127: *
1128: * sort_list_clean(&list);
1129: */
1130:
1131: } else if (sort_opts_vals.cflag) {
1132: result = (argc == 0) ? (check("-")) : (check(*argv));
1133: } else if (sort_opts_vals.mflag) {
1134: struct file_list fl;
1135:
1136: file_list_init(&fl, false);
1137: file_list_populate(&fl, argc, argv, true);
1138: merge_files(&fl, outfile);
1139: file_list_clean(&fl);
1140: }
1141:
1142: if (real_outfile) {
1143: if (rename(outfile, real_outfile) < 0)
1144: err(2, "%s", real_outfile);
1.51 millert 1145: sort_free(outfile);
1.44 millert 1146: }
1.4 millert 1147:
1.44 millert 1148: return result;
1.1 millert 1149: }