[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.52

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