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