[BACK]Return to sort.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / sort

Annotation of src/usr.bin/sort/sort.c, Revision 1.53

1.53    ! millert     1: /*     $OpenBSD: sort.c,v 1.52 2015/03/31 12:16:02 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: {
1.53    ! millert   312:        if (!issetugid()) {
        !           313:                char *td;
1.44      millert   314:
1.53    ! millert   315:                td = getenv("TMPDIR");
        !           316:                if (td != NULL)
        !           317:                        tmpdir = sort_strdup(td);
        !           318:        }
1.44      millert   319: }
                    320:
                    321: /*
                    322:  * Parse -S option.
                    323:  */
                    324: static unsigned long long
                    325: parse_memory_buffer_value(const char *value)
                    326: {
                    327:
                    328:        if (value == NULL)
                    329:                return available_free_memory;
                    330:        else {
                    331:                char *endptr;
                    332:                unsigned long long membuf;
                    333:
                    334:                endptr = NULL;
                    335:                errno = 0;
                    336:                membuf = strtoll(value, &endptr, 10);
                    337:
                    338:                if (errno != 0) {
                    339:                        warn("Wrong memory buffer specification");
                    340:                        membuf = available_free_memory;
                    341:                } else {
                    342:                        switch (*endptr){
                    343:                        case 'Y':
                    344:                                membuf *= 1024;
                    345:                                /* FALLTHROUGH */
                    346:                        case 'Z':
                    347:                                membuf *= 1024;
                    348:                                /* FALLTHROUGH */
                    349:                        case 'E':
                    350:                                membuf *= 1024;
                    351:                                /* FALLTHROUGH */
                    352:                        case 'P':
                    353:                                membuf *= 1024;
                    354:                                /* FALLTHROUGH */
                    355:                        case 'T':
                    356:                                membuf *= 1024;
                    357:                                /* FALLTHROUGH */
                    358:                        case 'G':
                    359:                                membuf *= 1024;
                    360:                                /* FALLTHROUGH */
                    361:                        case 'M':
                    362:                                membuf *= 1024;
                    363:                                /* FALLTHROUGH */
                    364:                        case '\0':
                    365:                        case 'K':
                    366:                                membuf *= 1024;
                    367:                                /* FALLTHROUGH */
                    368:                        case 'b':
                    369:                                break;
                    370:                        case '%':
                    371:                                membuf = (available_free_memory * membuf) /
                    372:                                    100;
                    373:                                break;
                    374:                        default:
                    375:                                warnc(EINVAL, "%s", optarg);
                    376:                                membuf = available_free_memory;
                    377:                        }
                    378:                }
                    379:                return membuf;
                    380:        }
                    381: }
                    382:
                    383: /*
                    384:  * Signal handler that clears the temporary files.
                    385:  */
                    386: static void
1.49      millert   387: sig_handler(int sig __unused)
1.44      millert   388: {
                    389:
                    390:        clear_tmp_files();
1.50      millert   391:        _exit(2);
1.44      millert   392: }
                    393:
                    394: /*
                    395:  * Set signal handler on panic signals.
                    396:  */
                    397: static void
                    398: set_signal_handler(void)
                    399: {
                    400:        struct sigaction sa;
1.49      millert   401:        int i, signals[] = {SIGTERM, SIGHUP, SIGINT, SIGQUIT, SIGUSR1, SIGUSR2,
                    402:            SIGPIPE, SIGXCPU, SIGXFSZ, SIGVTALRM, SIGPROF, 0};
1.44      millert   403:
                    404:        memset(&sa, 0, sizeof(sa));
1.49      millert   405:        sigfillset(&sa.sa_mask);
                    406:        sa.sa_flags = SA_RESTART;
                    407:        sa.sa_handler = sig_handler;
                    408:
                    409:        for (i = 0; signals[i] != 0; i++) {
                    410:                if (sigaction(signals[i], &sa, NULL) < 0) {
                    411:                        warn("sigaction(%d)", i);
                    412:                        continue;
                    413:                }
1.44      millert   414:        }
                    415: }
                    416:
                    417: /*
                    418:  * Print "unknown" message and exit with status 2.
                    419:  */
                    420: static void
                    421: unknown(const char *what)
                    422: {
                    423:
                    424:        errx(2, "Unknown feature: %s", what);
                    425: }
                    426:
                    427: /*
                    428:  * Check whether contradictory input options are used.
                    429:  */
                    430: static void
                    431: check_mutually_exclusive_flags(char c, bool *mef_flags)
                    432: {
                    433:        int i, fo_index, mec;
                    434:        bool found_others, found_this;
                    435:
                    436:        found_others = found_this =false;
                    437:        fo_index = 0;
                    438:
                    439:        for (i = 0; i < NUMBER_OF_MUTUALLY_EXCLUSIVE_FLAGS; i++) {
                    440:                mec = mutually_exclusive_flags[i];
                    441:
                    442:                if (mec != c) {
                    443:                        if (mef_flags[i]) {
                    444:                                if (found_this)
                    445:                                        errx(1, "%c:%c: mutually exclusive flags", c, mec);
                    446:                                found_others = true;
                    447:                                fo_index = i;
                    448:                        }
                    449:                } else {
                    450:                        if (found_others)
                    451:                                errx(1, "%c:%c: mutually exclusive flags", c, mutually_exclusive_flags[fo_index]);
                    452:                        mef_flags[i] = true;
                    453:                        found_this = true;
                    454:                }
                    455:        }
                    456: }
                    457:
                    458: /*
                    459:  * Initialise sort opts data.
                    460:  */
                    461: static void
                    462: set_sort_opts(void)
                    463: {
                    464:
                    465:        memset(&default_sort_mods_object, 0,
                    466:            sizeof(default_sort_mods_object));
                    467:        memset(&sort_opts_vals, 0, sizeof(sort_opts_vals));
                    468:        default_sort_mods_object.func =
                    469:            get_sort_func(&default_sort_mods_object);
                    470: }
                    471:
                    472: /*
                    473:  * Set a sort modifier on a sort modifiers object.
                    474:  */
                    475: static bool
                    476: set_sort_modifier(struct sort_mods *sm, int c)
                    477: {
                    478:
                    479:        if (sm) {
                    480:                switch (c){
                    481:                case 'b':
                    482:                        sm->bflag = true;
1.1       millert   483:                        break;
                    484:                case 'd':
1.44      millert   485:                        sm->dflag = true;
                    486:                        break;
1.4       millert   487:                case 'f':
1.44      millert   488:                        sm->fflag = true;
                    489:                        break;
                    490:                case 'g':
                    491:                        sm->gflag = true;
                    492:                        need_hint = true;
                    493:                        break;
1.1       millert   494:                case 'i':
1.44      millert   495:                        sm->iflag = true;
1.1       millert   496:                        break;
                    497:                case 'R':
1.44      millert   498:                        sm->Rflag = true;
                    499:                        need_random = true;
1.1       millert   500:                        break;
1.44      millert   501:                case 'M':
                    502:                        initialise_months();
                    503:                        sm->Mflag = true;
                    504:                        need_hint = true;
1.1       millert   505:                        break;
1.44      millert   506:                case 'n':
                    507:                        sm->nflag = true;
                    508:                        need_hint = true;
                    509:                        print_symbols_on_debug = true;
1.1       millert   510:                        break;
1.44      millert   511:                case 'r':
                    512:                        sm->rflag = true;
1.1       millert   513:                        break;
1.44      millert   514:                case 'V':
                    515:                        sm->Vflag = true;
1.1       millert   516:                        break;
1.44      millert   517:                case 'h':
                    518:                        sm->hflag = true;
                    519:                        need_hint = true;
                    520:                        print_symbols_on_debug = true;
1.1       millert   521:                        break;
1.8       deraadt   522:                default:
1.44      millert   523:                        return false;
1.1       millert   524:                }
1.44      millert   525:                sort_opts_vals.complex_sort = true;
                    526:                sm->func = get_sort_func(sm);
                    527:        }
                    528:        return true;
                    529: }
                    530:
                    531: /*
                    532:  * Parse POS in -k option.
                    533:  */
                    534: static int
                    535: parse_pos(const char *s, struct key_specs *ks, bool *mef_flags, bool second)
                    536: {
                    537:        regmatch_t pmatch[4];
                    538:        regex_t re;
                    539:        char *c, *f;
                    540:        const char *sregexp = "^([0-9]+)(\\.[0-9]+)?([bdfirMngRhV]+)?$";
                    541:        size_t len, nmatch;
                    542:        int ret;
                    543:
                    544:        ret = -1;
                    545:        nmatch = 4;
                    546:        c = f = NULL;
                    547:
                    548:        if (regcomp(&re, sregexp, REG_EXTENDED) != 0)
                    549:                return -1;
                    550:
                    551:        if (regexec(&re, s, nmatch, pmatch, 0) != 0)
                    552:                goto end;
                    553:
                    554:        if (pmatch[0].rm_eo <= pmatch[0].rm_so)
                    555:                goto end;
                    556:
                    557:        if (pmatch[1].rm_eo <= pmatch[1].rm_so)
                    558:                goto end;
                    559:
                    560:        len = pmatch[1].rm_eo - pmatch[1].rm_so;
                    561:        f = sort_malloc((len + 1) * sizeof(char));
                    562:
                    563:        strncpy(f, s + pmatch[1].rm_so, len);
                    564:        f[len] = '\0';
                    565:
                    566:        if (second) {
                    567:                errno = 0;
                    568:                ks->f2 = (size_t) strtoul(f, NULL, 10);
                    569:                if (errno != 0)
                    570:                        err(2, "-k");
                    571:                if (ks->f2 == 0) {
                    572:                        warn("0 field in key specs");
                    573:                        goto end;
                    574:                }
                    575:        } else {
                    576:                errno = 0;
                    577:                ks->f1 = (size_t) strtoul(f, NULL, 10);
                    578:                if (errno != 0)
                    579:                        err(2, "-k");
                    580:                if (ks->f1 == 0) {
                    581:                        warn("0 field in key specs");
                    582:                        goto end;
                    583:                }
                    584:        }
                    585:
                    586:        if (pmatch[2].rm_eo > pmatch[2].rm_so) {
                    587:                len = pmatch[2].rm_eo - pmatch[2].rm_so - 1;
                    588:                c = sort_malloc((len + 1) * sizeof(char));
                    589:
                    590:                strncpy(c, s + pmatch[2].rm_so + 1, len);
                    591:                c[len] = '\0';
                    592:
                    593:                if (second) {
                    594:                        errno = 0;
                    595:                        ks->c2 = (size_t) strtoul(c, NULL, 10);
                    596:                        if (errno != 0)
                    597:                                err(2, "-k");
                    598:                } else {
                    599:                        errno = 0;
                    600:                        ks->c1 = (size_t) strtoul(c, NULL, 10);
                    601:                        if (errno != 0)
                    602:                                err(2, "-k");
                    603:                        if (ks->c1 == 0) {
                    604:                                warn("0 column in key specs");
                    605:                                goto end;
                    606:                        }
                    607:                }
                    608:        } else {
                    609:                if (second)
                    610:                        ks->c2 = 0;
                    611:                else
                    612:                        ks->c1 = 1;
                    613:        }
                    614:
                    615:        if (pmatch[3].rm_eo > pmatch[3].rm_so) {
                    616:                regoff_t i = 0;
                    617:
                    618:                for (i = pmatch[3].rm_so; i < pmatch[3].rm_eo; i++) {
                    619:                        check_mutually_exclusive_flags(s[i], mef_flags);
                    620:                        if (s[i] == 'b') {
                    621:                                if (second)
                    622:                                        ks->pos2b = true;
                    623:                                else
                    624:                                        ks->pos1b = true;
                    625:                        } else if (!set_sort_modifier(&(ks->sm), s[i]))
                    626:                                goto end;
                    627:                }
                    628:        }
                    629:
                    630:        ret = 0;
                    631:
                    632: end:
                    633:
                    634:        if (c)
                    635:                sort_free(c);
                    636:        if (f)
                    637:                sort_free(f);
                    638:        regfree(&re);
                    639:
                    640:        return ret;
                    641: }
                    642:
                    643: /*
                    644:  * Parse -k option value.
                    645:  */
                    646: static int
                    647: parse_k(const char *s, struct key_specs *ks)
                    648: {
                    649:        int ret = -1;
                    650:        bool mef_flags[NUMBER_OF_MUTUALLY_EXCLUSIVE_FLAGS] =
                    651:            { false, false, false, false, false, false };
                    652:
                    653:        if (s && *s) {
                    654:                char *sptr;
                    655:
                    656:                sptr = strchr(s, ',');
                    657:                if (sptr) {
                    658:                        size_t size1;
                    659:                        char *pos1, *pos2;
                    660:
                    661:                        size1 = sptr - s;
                    662:
                    663:                        if (size1 < 1)
                    664:                                return -1;
                    665:                        pos1 = sort_malloc((size1 + 1) * sizeof(char));
                    666:
                    667:                        strncpy(pos1, s, size1);
                    668:                        pos1[size1] = '\0';
                    669:
                    670:                        ret = parse_pos(pos1, ks, mef_flags, false);
                    671:
                    672:                        sort_free(pos1);
                    673:                        if (ret < 0)
                    674:                                return ret;
                    675:
                    676:                        pos2 = sort_strdup(sptr + 1);
                    677:                        ret = parse_pos(pos2, ks, mef_flags, true);
                    678:                        sort_free(pos2);
                    679:                } else
                    680:                        ret = parse_pos(s, ks, mef_flags, false);
1.1       millert   681:        }
1.4       millert   682:
1.44      millert   683:        return ret;
                    684: }
                    685:
                    686: /*
                    687:  * Parse POS in +POS -POS option.
                    688:  */
                    689: static int
                    690: parse_pos_obs(const char *s, int *nf, int *nc, char *sopts)
                    691: {
                    692:        regex_t re;
                    693:        regmatch_t pmatch[4];
                    694:        char *c, *f;
                    695:        const char *sregexp = "^([0-9]+)(\\.[0-9]+)?([A-Za-z]+)?$";
                    696:        int ret;
                    697:        size_t len, nmatch;
                    698:
                    699:        ret = -1;
                    700:        nmatch = 4;
                    701:        c = f = NULL;
                    702:        *nc = *nf = 0;
                    703:
                    704:        if (regcomp(&re, sregexp, REG_EXTENDED) != 0)
                    705:                return -1;
                    706:
                    707:        if (regexec(&re, s, nmatch, pmatch, 0) != 0)
                    708:                goto end;
                    709:
                    710:        if (pmatch[0].rm_eo <= pmatch[0].rm_so)
                    711:                goto end;
                    712:
                    713:        if (pmatch[1].rm_eo <= pmatch[1].rm_so)
                    714:                goto end;
                    715:
                    716:        len = pmatch[1].rm_eo - pmatch[1].rm_so;
                    717:        f = sort_malloc((len + 1) * sizeof(char));
                    718:
                    719:        strncpy(f, s + pmatch[1].rm_so, len);
                    720:        f[len] = '\0';
                    721:
                    722:        errno = 0;
                    723:        *nf = (size_t) strtoul(f, NULL, 10);
                    724:        if (errno != 0)
                    725:                errx(2, "Invalid key position");
                    726:
                    727:        if (pmatch[2].rm_eo > pmatch[2].rm_so) {
                    728:                len = pmatch[2].rm_eo - pmatch[2].rm_so - 1;
                    729:                c = sort_malloc((len + 1) * sizeof(char));
                    730:
                    731:                strncpy(c, s + pmatch[2].rm_so + 1, len);
                    732:                c[len] = '\0';
                    733:
                    734:                errno = 0;
                    735:                *nc = (size_t) strtoul(c, NULL, 10);
                    736:                if (errno != 0)
                    737:                        errx(2, "Invalid key position");
                    738:        }
                    739:
                    740:        if (pmatch[3].rm_eo > pmatch[3].rm_so) {
                    741:
                    742:                len = pmatch[3].rm_eo - pmatch[3].rm_so;
1.4       millert   743:
1.44      millert   744:                strncpy(sopts, s + pmatch[3].rm_so, len);
                    745:                sopts[len] = '\0';
1.1       millert   746:        }
1.4       millert   747:
1.44      millert   748:        ret = 0;
1.4       millert   749:
1.44      millert   750: end:
                    751:        if (c)
                    752:                sort_free(c);
                    753:        if (f)
                    754:                sort_free(f);
                    755:        regfree(&re);
                    756:
                    757:        return ret;
                    758: }
                    759:
                    760: /*
                    761:  * "Translate" obsolete +POS1 -POS2 syntax into new -kPOS1,POS2 syntax
                    762:  */
                    763: static void
                    764: fix_obsolete_keys(int *argc, char **argv)
                    765: {
                    766:        char sopt[129];
                    767:        int i;
                    768:
                    769:        for (i = 1; i < *argc; i++) {
                    770:                char *arg1;
                    771:
                    772:                arg1 = argv[i];
                    773:
                    774:                if (strlen(arg1) > 1 && arg1[0] == '+') {
                    775:                        int c1, f1;
                    776:                        char sopts1[128];
                    777:
                    778:                        sopts1[0] = 0;
                    779:                        c1 = f1 = 0;
                    780:
                    781:                        if (parse_pos_obs(arg1 + 1, &f1, &c1, sopts1) < 0)
                    782:                                continue;
1.1       millert   783:                        else {
1.44      millert   784:                                f1 += 1;
                    785:                                c1 += 1;
                    786:                                if (i + 1 < *argc) {
                    787:                                        char *arg2 = argv[i + 1];
                    788:
                    789:                                        if (strlen(arg2) > 1 &&
                    790:                                            arg2[0] == '-') {
                    791:                                                int c2, f2;
                    792:                                                char sopts2[128];
                    793:
                    794:                                                sopts2[0] = 0;
                    795:                                                c2 = f2 = 0;
                    796:
                    797:                                                if (parse_pos_obs(arg2 + 1,
                    798:                                                    &f2, &c2, sopts2) >= 0) {
                    799:                                                        int j;
                    800:                                                        if (c2 > 0)
                    801:                                                                f2 += 1;
                    802:                                                        snprintf(sopt,
                    803:                                                            sizeof(sopt),
                    804:                                                            "-k%d.%d%s,%d.%d%s",
                    805:                                                            f1, c1, sopts1, f2,
                    806:                                                            c2, sopts2);
                    807:                                                        argv[i] = sort_strdup(sopt);
                    808:                                                        for (j = i + 1; j + 1 < *argc; j++)
                    809:                                                                argv[j] = argv[j + 1];
                    810:                                                        *argc -= 1;
                    811:                                                        continue;
                    812:                                                }
                    813:                                        }
                    814:                                }
                    815:                                snprintf(sopt, sizeof(sopt), "-k%d.%d%s",
                    816:                                    f1, c1, sopts1);
                    817:                                argv[i] = sort_strdup(sopt);
1.1       millert   818:                        }
1.44      millert   819:                }
1.1       millert   820:        }
1.44      millert   821: }
                    822:
                    823: /*
                    824:  * Set random seed
                    825:  */
                    826: static void
                    827: set_random_seed(void)
                    828: {
                    829:        if (!need_random)
                    830:                return;
1.4       millert   831:
1.44      millert   832:        MD5Init(&md5_ctx);
                    833:        if (random_source != NULL) {
                    834:                unsigned char buf[BUFSIZ];
                    835:                size_t nr;
                    836:                FILE *fp;
                    837:
                    838:                if ((fp = fopen(random_source, "r")) == NULL)
                    839:                        err(2, "%s", random_source);
                    840:                while ((nr = fread(buf, 1, sizeof(buf), fp)) != 0)
                    841:                        MD5Update(&md5_ctx, buf, nr);
                    842:                if (ferror(fp))
                    843:                        err(2, "%s", random_source);
                    844:                fclose(fp);
1.1       millert   845:        } else {
1.44      millert   846:                unsigned char rsd[1024];
                    847:
                    848:                arc4random_buf(rsd, sizeof(rsd));
                    849:                MD5Update(&md5_ctx, rsd, sizeof(rsd));
                    850:        }
                    851: }
                    852:
                    853: /*
                    854:  * Main function.
                    855:  */
                    856: int
                    857: main(int argc, char *argv[])
                    858: {
                    859:        char *outfile, *real_outfile;
                    860:        int c, result;
                    861:        size_t i;
                    862:        bool mef_flags[NUMBER_OF_MUTUALLY_EXCLUSIVE_FLAGS] =
                    863:            { false, false, false, false, false, false };
                    864:
                    865:        result = 0;
1.51      millert   866:        outfile = "-";
1.44      millert   867:        real_outfile = NULL;
                    868:
                    869:        struct sort_mods *sm = &default_sort_mods_object;
                    870:
                    871:        init_tmp_files();
                    872:
                    873:        set_signal_handler();
                    874:
1.51      millert   875:        atexit(clear_tmp_files);
                    876:
1.44      millert   877:        set_hw_params();
                    878:        set_locale();
                    879:        set_tmpdir();
                    880:        set_sort_opts();
                    881:
                    882:        fix_obsolete_keys(&argc, argv);
                    883:
                    884:        while (((c = getopt_long(argc, argv, OPTIONS, long_options, NULL))
                    885:            != -1)) {
                    886:
                    887:                check_mutually_exclusive_flags(c, mef_flags);
                    888:
                    889:                if (!set_sort_modifier(sm, c)) {
                    890:
                    891:                        switch (c) {
                    892:                        case 'c':
                    893:                                sort_opts_vals.cflag = true;
                    894:                                if (optarg) {
                    895:                                        if (!strcmp(optarg, "diagnose-first"))
                    896:                                                ;
                    897:                                        else if (!strcmp(optarg, "silent") ||
                    898:                                            !strcmp(optarg, "quiet"))
                    899:                                                sort_opts_vals.csilentflag = true;
                    900:                                        else if (*optarg)
                    901:                                                unknown(optarg);
                    902:                                }
                    903:                                break;
                    904:                        case 'C':
                    905:                                sort_opts_vals.cflag = true;
                    906:                                sort_opts_vals.csilentflag = true;
                    907:                                break;
                    908:                        case 'k':
                    909:                        {
                    910:                                sort_opts_vals.complex_sort = true;
                    911:                                sort_opts_vals.kflag = true;
                    912:
                    913:                                keys_num++;
                    914:                                keys = sort_reallocarray(keys, keys_num,
                    915:                                    sizeof(struct key_specs));
                    916:                                memset(&(keys[keys_num - 1]), 0,
                    917:                                    sizeof(struct key_specs));
                    918:
                    919:                                if (parse_k(optarg, &(keys[keys_num - 1]))
                    920:                                    < 0) {
                    921:                                        errc(2, EINVAL, "-k %s", optarg);
                    922:                                }
                    923:
                    924:                                break;
                    925:                        }
                    926:                        case 'm':
                    927:                                sort_opts_vals.mflag = true;
                    928:                                break;
                    929:                        case 'o':
1.51      millert   930:                                outfile = optarg;
1.44      millert   931:                                break;
                    932:                        case 's':
                    933:                                sort_opts_vals.sflag = true;
                    934:                                break;
                    935:                        case 'S':
                    936:                                available_free_memory =
                    937:                                    parse_memory_buffer_value(optarg);
                    938:                                break;
                    939:                        case 'T':
                    940:                                tmpdir = sort_strdup(optarg);
                    941:                                break;
                    942:                        case 't':
                    943:                                while (strlen(optarg) > 1) {
                    944:                                        if (optarg[0] != '\\') {
                    945:                                                errc(2, EINVAL, "%s", optarg);
                    946:                                        }
                    947:                                        optarg += 1;
                    948:                                        if (*optarg == '0') {
                    949:                                                *optarg = 0;
                    950:                                                break;
                    951:                                        }
                    952:                                }
                    953:                                sort_opts_vals.tflag = true;
                    954:                                sort_opts_vals.field_sep = btowc(optarg[0]);
                    955:                                if (sort_opts_vals.field_sep == WEOF) {
                    956:                                        errno = EINVAL;
                    957:                                        err(2, NULL);
                    958:                                }
                    959:                                if (!gnusort_numeric_compatibility) {
                    960:                                        if (symbol_decimal_point == sort_opts_vals.field_sep)
                    961:                                                symbol_decimal_point = WEOF;
                    962:                                        if (symbol_thousands_sep == sort_opts_vals.field_sep)
                    963:                                                symbol_thousands_sep = WEOF;
                    964:                                        if (symbol_negative_sign == sort_opts_vals.field_sep)
                    965:                                                symbol_negative_sign = WEOF;
                    966:                                        if (symbol_positive_sign == sort_opts_vals.field_sep)
                    967:                                                symbol_positive_sign = WEOF;
                    968:                                }
                    969:                                break;
                    970:                        case 'u':
                    971:                                sort_opts_vals.uflag = true;
                    972:                                /* stable sort for the correct unique val */
                    973:                                sort_opts_vals.sflag = true;
                    974:                                break;
                    975:                        case 'z':
                    976:                                sort_opts_vals.zflag = true;
                    977:                                break;
                    978:                        case SORT_OPT:
                    979:                                if (optarg) {
                    980:                                        if (!strcmp(optarg, "general-numeric"))
                    981:                                                set_sort_modifier(sm, 'g');
                    982:                                        else if (!strcmp(optarg, "human-numeric"))
                    983:                                                set_sort_modifier(sm, 'h');
                    984:                                        else if (!strcmp(optarg, "numeric"))
                    985:                                                set_sort_modifier(sm, 'n');
                    986:                                        else if (!strcmp(optarg, "month"))
                    987:                                                set_sort_modifier(sm, 'M');
                    988:                                        else if (!strcmp(optarg, "random"))
                    989:                                                set_sort_modifier(sm, 'R');
                    990:                                        else
                    991:                                                unknown(optarg);
                    992:                                }
                    993:                                break;
                    994:                        case QSORT_OPT:
                    995:                                sort_opts_vals.sort_method = SORT_QSORT;
                    996:                                break;
                    997:                        case 'H':
                    998:                                sort_opts_vals.sort_method = SORT_MERGESORT;
                    999:                                break;
                   1000:                        case MMAP_OPT:
                   1001:                                use_mmap = true;
                   1002:                                break;
                   1003:                        case HEAPSORT_OPT:
                   1004:                                sort_opts_vals.sort_method = SORT_HEAPSORT;
                   1005:                                break;
                   1006:                        case RADIXSORT_OPT:
                   1007:                                sort_opts_vals.sort_method = SORT_RADIXSORT;
                   1008:                                break;
                   1009:                        case RANDOMSOURCE_OPT:
                   1010:                                random_source = strdup(optarg);
                   1011:                                break;
                   1012:                        case COMPRESSPROGRAM_OPT:
                   1013:                                compress_program = strdup(optarg);
                   1014:                                break;
                   1015:                        case FF_OPT:
                   1016:                                read_fns_from_file0(optarg);
                   1017:                                break;
                   1018:                        case BS_OPT:
                   1019:                        {
                   1020:                                errno = 0;
                   1021:                                long mof = strtol(optarg, NULL, 10);
                   1022:                                if (errno != 0)
                   1023:                                        err(2, "--batch-size");
                   1024:                                if (mof >= 2)
                   1025:                                        max_open_files = (size_t) mof + 1;
                   1026:                        }
                   1027:                                break;
                   1028:                        case VERSION_OPT:
                   1029:                                printf("%s\n", VERSION);
                   1030:                                exit(EXIT_SUCCESS);
                   1031:                                /* NOTREACHED */
                   1032:                                break;
                   1033:                        case DEBUG_OPT:
                   1034:                                debug_sort = true;
                   1035:                                break;
                   1036:                        case HELP_OPT:
                   1037:                                usage(0);
                   1038:                                /* NOTREACHED */
                   1039:                                break;
                   1040:                        default:
                   1041:                                usage(2);
                   1042:                                /* NOTREACHED */
                   1043:                        }
                   1044:                }
                   1045:        }
                   1046:
                   1047:        argc -= optind;
                   1048:        argv += optind;
                   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: */
1.51      millert  1101:        if (strcmp(outfile, "-") != 0) {
                   1102:                struct stat sb;
                   1103:                int fd, i;
1.44      millert  1104:
                   1105:                for (i = 0; i < argc; ++i) {
                   1106:                        if (strcmp(argv[i], outfile) == 0) {
1.51      millert  1107:                                if (stat(outfile, &sb) == -1)
                   1108:                                        err(2, "%s", outfile);
                   1109:                                if (access(outfile, W_OK) == -1)
                   1110:                                        err(2, "%s", outfile);
                   1111:                                real_outfile = outfile;
                   1112:                                sort_asprintf(&outfile, "%s.XXXXXXXXXX",
                   1113:                                    real_outfile);
                   1114:                                if ((fd = mkstemp(outfile)) == -1 ||
                   1115:                                    fchmod(fd, sb.st_mode & ALLPERMS) == -1)
                   1116:                                        err(2, "%s", outfile);
                   1117:                                close(fd);
1.44      millert  1118:                                tmp_file_atexit(outfile);
1.51      millert  1119:                                break;
1.44      millert  1120:                        }
                   1121:                }
                   1122:        }
                   1123:
                   1124:        if (!sort_opts_vals.cflag && !sort_opts_vals.mflag) {
                   1125:                struct file_list fl;
                   1126:                struct sort_list list;
                   1127:
                   1128:                sort_list_init(&list);
                   1129:                file_list_init(&fl, true);
                   1130:
                   1131:                if (argc < 1)
                   1132:                        procfile("-", &list, &fl);
                   1133:                else {
                   1134:                        while (argc > 0) {
                   1135:                                procfile(*argv, &list, &fl);
                   1136:                                --argc;
                   1137:                                ++argv;
                   1138:                        }
                   1139:                }
                   1140:
                   1141:                if (fl.count < 1)
                   1142:                        sort_list_to_file(&list, outfile);
                   1143:                else {
                   1144:                        if (list.count > 0) {
                   1145:                                char *flast = new_tmp_file_name();
                   1146:
                   1147:                                sort_list_to_file(&list, flast);
                   1148:                                file_list_add(&fl, flast, false);
                   1149:                        }
                   1150:                        merge_files(&fl, outfile);
                   1151:                }
                   1152:
                   1153:                file_list_clean(&fl);
                   1154:
                   1155:                /*
                   1156:                 * We are about to exit the program, so we can ignore
                   1157:                 * the clean-up for speed
                   1158:                 *
                   1159:                 * sort_list_clean(&list);
                   1160:                 */
                   1161:
                   1162:        } else if (sort_opts_vals.cflag) {
                   1163:                result = (argc == 0) ? (check("-")) : (check(*argv));
                   1164:        } else if (sort_opts_vals.mflag) {
                   1165:                struct file_list fl;
                   1166:
                   1167:                file_list_init(&fl, false);
                   1168:                file_list_populate(&fl, argc, argv, true);
                   1169:                merge_files(&fl, outfile);
                   1170:                file_list_clean(&fl);
                   1171:        }
                   1172:
                   1173:        if (real_outfile) {
                   1174:                if (rename(outfile, real_outfile) < 0)
                   1175:                        err(2, "%s", real_outfile);
1.51      millert  1176:                sort_free(outfile);
1.44      millert  1177:        }
1.4       millert  1178:
1.44      millert  1179:        return result;
1.1       millert  1180: }