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

Annotation of src/usr.bin/sort/file.c, Revision 1.7

1.7     ! tobias      1: /*     $OpenBSD: file.c,v 1.6 2015/04/01 19:06:18 millert Exp $        */
1.1       millert     2:
                      3: /*-
                      4:  * Copyright (C) 2009 Gabor Kovesdan <gabor@FreeBSD.org>
                      5:  * Copyright (C) 2012 Oleg Moskalenko <mom040267@gmail.com>
                      6:  * All rights reserved.
                      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:  *
                     17:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
                     18:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
                     19:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
                     20:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
                     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:
                     30: #include <sys/mman.h>
                     31: #include <sys/stat.h>
                     32: #include <sys/types.h>
                     33: #include <sys/queue.h>
                     34:
                     35: #include <err.h>
                     36: #include <fcntl.h>
                     37: #include <stdio.h>
                     38: #include <stdlib.h>
                     39: #include <string.h>
                     40: #include <unistd.h>
                     41: #include <wchar.h>
                     42: #include <wctype.h>
                     43:
                     44: #include "coll.h"
                     45: #include "file.h"
                     46: #include "radixsort.h"
                     47:
                     48: unsigned long long free_memory = 1000000;
                     49: unsigned long long available_free_memory = 1000000;
                     50:
                     51: bool use_mmap;
                     52:
                     53: const char *tmpdir = "/var/tmp";
                     54: const char *compress_program;
                     55:
                     56: size_t max_open_files = 16;
                     57:
                     58: /*
                     59:  * How much space we read from file at once
                     60:  */
                     61: #define READ_CHUNK 4096
                     62:
                     63: /*
                     64:  * File reader structure
                     65:  */
                     66: struct file_reader {
                     67:        struct reader_buffer     rb;
                     68:        FILE                    *file;
                     69:        char                    *fname;
                     70:        unsigned char           *buffer;
                     71:        unsigned char           *mmapaddr;
                     72:        unsigned char           *mmapptr;
                     73:        size_t                   bsz;
                     74:        size_t                   cbsz;
                     75:        size_t                   mmapsize;
                     76:        size_t                   strbeg;
                     77:        int                      fd;
                     78:        char                     elsymb;
                     79: };
                     80:
                     81: /*
                     82:  * Structure to be used in file merge process.
                     83:  */
                     84: struct file_header {
                     85:        struct file_reader              *fr;
                     86:        struct sort_list_item           *si; /* current top line */
                     87:        size_t                           file_pos;
                     88: };
                     89:
                     90: /*
                     91:  * List elements of "cleanable" files list.
                     92:  */
                     93: struct CLEANABLE_FILE {
                     94:        char                            *fn;
                     95:        LIST_ENTRY(CLEANABLE_FILE)       files;
                     96: };
                     97:
                     98: /*
                     99:  * List header of "cleanable" files list.
                    100:  */
                    101: static LIST_HEAD(CLEANABLE_FILES, CLEANABLE_FILE) tmp_files;
                    102:
                    103: /*
                    104:  * Init tmp files list
                    105:  */
                    106: void
                    107: init_tmp_files(void)
                    108: {
                    109:
                    110:        LIST_INIT(&tmp_files);
                    111: }
                    112:
                    113: /*
                    114:  * Save name of a tmp file for signal cleanup
                    115:  */
                    116: void
                    117: tmp_file_atexit(const char *tmp_file)
                    118: {
                    119:
                    120:        if (tmp_file) {
                    121:                struct CLEANABLE_FILE *item =
                    122:                    sort_malloc(sizeof(struct CLEANABLE_FILE));
                    123:                item->fn = sort_strdup(tmp_file);
                    124:                LIST_INSERT_HEAD(&tmp_files, item, files);
                    125:        }
                    126: }
                    127:
                    128: /*
                    129:  * Clear tmp files
                    130:  */
                    131: void
                    132: clear_tmp_files(void)
                    133: {
                    134:        struct CLEANABLE_FILE *item;
                    135:
                    136:        LIST_FOREACH(item, &tmp_files, files) {
                    137:                if (item != NULL && item->fn != NULL)
                    138:                        unlink(item->fn);
                    139:        }
                    140: }
                    141:
                    142: /*
                    143:  * Check whether a file is a temporary file
                    144:  */
                    145: static bool
                    146: file_is_tmp(const char *fn)
                    147: {
                    148:        struct CLEANABLE_FILE *item;
                    149:        bool ret = false;
                    150:
                    151:        if (fn) {
                    152:                LIST_FOREACH(item, &tmp_files, files) {
                    153:                        if (item != NULL && item->fn != NULL)
                    154:                                if (strcmp(item->fn, fn) == 0) {
                    155:                                        ret = true;
                    156:                                        break;
                    157:                                }
                    158:                }
                    159:        }
                    160:
                    161:        return ret;
                    162: }
                    163:
                    164: /*
                    165:  * Generate new temporary file name
                    166:  */
                    167: char *
                    168: new_tmp_file_name(void)
                    169: {
                    170:        char *ret;
1.7     ! tobias    171:        int fd;
1.1       millert   172:
1.7     ! tobias    173:        sort_asprintf(&ret, "%s/.bsdsort.XXXXXXXXXX", tmpdir);
        !           174:        if ((fd = mkstemp(ret)) == -1)
        !           175:                err(2, "%s", ret);
        !           176:        close(fd);
1.1       millert   177:        tmp_file_atexit(ret);
                    178:        return ret;
                    179: }
                    180:
                    181: /*
                    182:  * Initialize file list
                    183:  */
                    184: void
                    185: file_list_init(struct file_list *fl, bool tmp)
                    186: {
                    187:
                    188:        if (fl) {
                    189:                fl->count = 0;
                    190:                fl->sz = 0;
                    191:                fl->fns = NULL;
                    192:                fl->tmp = tmp;
                    193:        }
                    194: }
                    195:
                    196: /*
                    197:  * Add a file name to the list
                    198:  */
                    199: void
                    200: file_list_add(struct file_list *fl, char *fn, bool allocate)
                    201: {
                    202:
                    203:        if (fl && fn) {
                    204:                if (fl->count >= fl->sz || fl->fns == NULL) {
                    205:                        fl->sz = fl->sz * 2 + 1;
                    206:                        fl->fns = sort_reallocarray(fl->fns, fl->sz,
                    207:                            sizeof(char *));
                    208:                }
                    209:                fl->fns[fl->count] = allocate ? sort_strdup(fn) : fn;
                    210:                fl->count += 1;
                    211:        }
                    212: }
                    213:
                    214: /*
                    215:  * Populate file list from array of file names
                    216:  */
                    217: void
                    218: file_list_populate(struct file_list *fl, int argc, char **argv, bool allocate)
                    219: {
                    220:
                    221:        if (fl && argv) {
                    222:                int i;
                    223:
                    224:                for (i = 0; i < argc; i++)
                    225:                        file_list_add(fl, argv[i], allocate);
                    226:        }
                    227: }
                    228:
                    229: /*
                    230:  * Clean file list data and delete the files,
                    231:  * if this is a list of temporary files
                    232:  */
                    233: void
                    234: file_list_clean(struct file_list *fl)
                    235: {
                    236:
                    237:        if (fl) {
                    238:                if (fl->fns) {
                    239:                        size_t i;
                    240:
                    241:                        for (i = 0; i < fl->count; i++) {
                    242:                                if (fl->fns[i]) {
                    243:                                        if (fl->tmp)
                    244:                                                unlink(fl->fns[i]);
                    245:                                        sort_free(fl->fns[i]);
                    246:                                        fl->fns[i] = 0;
                    247:                                }
                    248:                        }
                    249:                        sort_free(fl->fns);
                    250:                        fl->fns = NULL;
                    251:                }
                    252:                fl->sz = 0;
                    253:                fl->count = 0;
                    254:                fl->tmp = false;
                    255:        }
                    256: }
                    257:
                    258: /*
                    259:  * Init sort list
                    260:  */
                    261: void
                    262: sort_list_init(struct sort_list *l)
                    263: {
                    264:
                    265:        if (l) {
                    266:                l->count = 0;
                    267:                l->size = 0;
                    268:                l->memsize = sizeof(struct sort_list);
                    269:                l->list = NULL;
                    270:        }
                    271: }
                    272:
                    273: /*
                    274:  * Add string to sort list
                    275:  */
                    276: void
                    277: sort_list_add(struct sort_list *l, struct bwstring *str)
                    278: {
                    279:
                    280:        if (l && str) {
                    281:                size_t indx = l->count;
                    282:
                    283:                if ((l->list == NULL) || (indx >= l->size)) {
                    284:                        size_t newsize = (l->size + 1) + 1024;
                    285:
                    286:                        l->list = sort_reallocarray(l->list, newsize,
                    287:                            sizeof(struct sort_list_item *));
                    288:                        l->memsize += (newsize - l->size) *
                    289:                            sizeof(struct sort_list_item *);
                    290:                        l->size = newsize;
                    291:                }
                    292:                l->list[indx] = sort_list_item_alloc();
                    293:                sort_list_item_set(l->list[indx], str);
                    294:                l->memsize += sort_list_item_size(l->list[indx]);
                    295:                l->count += 1;
                    296:        }
                    297: }
                    298:
                    299: /*
                    300:  * Clean sort list data
                    301:  */
                    302: void
                    303: sort_list_clean(struct sort_list *l)
                    304: {
                    305:
                    306:        if (l) {
                    307:                if (l->list) {
                    308:                        size_t i;
                    309:
                    310:                        for (i = 0; i < l->count; i++) {
                    311:                                struct sort_list_item *item;
                    312:
                    313:                                item = l->list[i];
                    314:
                    315:                                if (item) {
                    316:                                        sort_list_item_clean(item);
                    317:                                        sort_free(item);
                    318:                                        l->list[i] = NULL;
                    319:                                }
                    320:                        }
                    321:                        sort_free(l->list);
                    322:                        l->list = NULL;
                    323:                }
                    324:                l->count = 0;
                    325:                l->size = 0;
                    326:                l->memsize = sizeof(struct sort_list);
                    327:        }
                    328: }
                    329:
                    330: /*
                    331:  * Write sort list to file
                    332:  */
                    333: void
                    334: sort_list_dump(struct sort_list *l, const char *fn)
                    335: {
                    336:
                    337:        if (l && fn) {
                    338:                FILE *f;
                    339:
                    340:                f = openfile(fn, "w");
                    341:                if (f == NULL)
                    342:                        err(2, "%s", fn);
                    343:
                    344:                if (l->list) {
                    345:                        size_t i;
                    346:                        if (!sort_opts_vals.uflag) {
                    347:                                for (i = 0; i < l->count; ++i)
                    348:                                        bwsfwrite(l->list[i]->str, f,
                    349:                                            sort_opts_vals.zflag);
                    350:                        } else {
                    351:                                struct sort_list_item *last_printed_item = NULL;
                    352:                                struct sort_list_item *item;
                    353:                                for (i = 0; i < l->count; ++i) {
                    354:                                        item = l->list[i];
                    355:                                        if ((last_printed_item == NULL) ||
                    356:                                            list_coll(&last_printed_item, &item)) {
                    357:                                                bwsfwrite(item->str, f, sort_opts_vals.zflag);
                    358:                                                last_printed_item = item;
                    359:                                        }
                    360:                                }
                    361:                        }
                    362:                }
                    363:
                    364:                closefile(f, fn);
                    365:        }
                    366: }
                    367:
                    368: /*
                    369:  * Checks if the given file is sorted.  Stops at the first disorder,
                    370:  * prints the disordered line and returns 1.
                    371:  */
                    372: int
                    373: check(const char *fn)
                    374: {
                    375:        struct bwstring *s1, *s2, *s1disorder, *s2disorder;
                    376:        struct file_reader *fr;
                    377:        struct keys_array *ka1, *ka2;
                    378:        int res;
                    379:        size_t pos, posdisorder;
                    380:
                    381:        s1 = s2 = s1disorder = s2disorder = NULL;
                    382:        ka1 = ka2 = NULL;
                    383:
                    384:        fr = file_reader_init(fn);
                    385:
                    386:        res = 0;
                    387:        pos = 1;
                    388:        posdisorder = 1;
                    389:
                    390:        if (fr == NULL) {
                    391:                err(2, "%s", fn);
                    392:                goto end;
                    393:        }
                    394:
                    395:        s1 = file_reader_readline(fr);
                    396:        if (s1 == NULL)
                    397:                goto end;
                    398:
                    399:        ka1 = keys_array_alloc();
                    400:        preproc(s1, ka1);
                    401:
                    402:        s2 = file_reader_readline(fr);
                    403:        if (s2 == NULL)
                    404:                goto end;
                    405:
                    406:        ka2 = keys_array_alloc();
                    407:        preproc(s2, ka2);
                    408:
                    409:        for (;;) {
                    410:
                    411:                if (debug_sort) {
                    412:                        bwsprintf(stdout, s2, "s1=<", ">");
                    413:                        bwsprintf(stdout, s1, "s2=<", ">");
                    414:                }
                    415:                int cmp = key_coll(ka2, ka1, 0);
                    416:                if (debug_sort)
                    417:                        printf("; cmp1=%d", cmp);
                    418:
                    419:                if (!cmp && sort_opts_vals.complex_sort &&
                    420:                    !(sort_opts_vals.uflag) && !(sort_opts_vals.sflag)) {
                    421:                        cmp = top_level_str_coll(s2, s1);
                    422:                        if (debug_sort)
                    423:                                printf("; cmp2=%d", cmp);
                    424:                }
                    425:                if (debug_sort)
                    426:                        printf("\n");
                    427:
                    428:                if ((sort_opts_vals.uflag && (cmp <= 0)) || (cmp < 0)) {
                    429:                        if (!(sort_opts_vals.csilentflag)) {
                    430:                                s2disorder = bwsdup(s2);
                    431:                                posdisorder = pos;
                    432:                                if (debug_sort)
                    433:                                        s1disorder = bwsdup(s1);
                    434:                        }
                    435:                        res = 1;
                    436:                        goto end;
                    437:                }
                    438:
                    439:                pos++;
                    440:
                    441:                clean_keys_array(s1, ka1);
                    442:                sort_free(ka1);
                    443:                ka1 = ka2;
                    444:                ka2 = NULL;
                    445:
                    446:                bwsfree(s1);
                    447:                s1 = s2;
                    448:
                    449:                s2 = file_reader_readline(fr);
                    450:                if (s2 == NULL)
                    451:                        goto end;
                    452:
                    453:                ka2 = keys_array_alloc();
                    454:                preproc(s2, ka2);
                    455:        }
                    456:
                    457: end:
                    458:        if (ka1) {
                    459:                clean_keys_array(s1, ka1);
                    460:                sort_free(ka1);
                    461:        }
                    462:
                    463:        if (s1)
                    464:                bwsfree(s1);
                    465:
                    466:        if (ka2) {
                    467:                clean_keys_array(s2, ka2);
                    468:                sort_free(ka2);
                    469:        }
                    470:
                    471:        if (s2)
                    472:                bwsfree(s2);
                    473:
                    474:        if (fn == NULL || *fn == 0 || strcmp(fn, "-") == 0) {
                    475:                for (;;) {
                    476:                        s2 = file_reader_readline(fr);
                    477:                        if (s2 == NULL)
                    478:                                break;
                    479:                        bwsfree(s2);
                    480:                }
                    481:        }
                    482:
                    483:        file_reader_free(fr);
                    484:
                    485:        if (s2disorder) {
                    486:                bws_disorder_warnx(s2disorder, fn, posdisorder);
                    487:                if (s1disorder) {
                    488:                        bws_disorder_warnx(s1disorder, fn, posdisorder);
                    489:                        if (s1disorder != s2disorder)
                    490:                                bwsfree(s1disorder);
                    491:                }
                    492:                bwsfree(s2disorder);
                    493:                s1disorder = NULL;
                    494:                s2disorder = NULL;
                    495:        }
                    496:
                    497:        if (res)
                    498:                exit(res);
                    499:
                    500:        return 0;
                    501: }
                    502:
                    503: /*
                    504:  * Opens a file.  If the given filename is "-", stdout will be
                    505:  * opened.
                    506:  */
                    507: FILE *
                    508: openfile(const char *fn, const char *mode)
                    509: {
                    510:        FILE *file;
                    511:
                    512:        if (strcmp(fn, "-") == 0) {
                    513:                return (mode && mode[0] == 'r') ? stdin : stdout;
                    514:        } else {
                    515:                mode_t orig_file_mask = 0;
                    516:                int is_tmp = file_is_tmp(fn);
                    517:
                    518:                if (is_tmp && (mode[0] == 'w'))
                    519:                        orig_file_mask = umask(S_IWGRP | S_IWOTH |
                    520:                            S_IRGRP | S_IROTH);
                    521:
                    522:                if (is_tmp && (compress_program != NULL)) {
                    523:                        char *cmd;
                    524:
                    525:                        fflush(stdout);
                    526:
                    527:                        if (mode[0] == 'r')
1.6       millert   528:                                sort_asprintf(&cmd, "%s -d < %s",
1.5       tobias    529:                                    compress_program, fn);
1.1       millert   530:                        else if (mode[0] == 'w')
1.6       millert   531:                                sort_asprintf(&cmd, "%s > %s",
1.1       millert   532:                                    compress_program, fn);
                    533:                        else
                    534:                                err(2, "Wrong file mode");
                    535:
                    536:                        if ((file = popen(cmd, mode)) == NULL)
                    537:                                err(2, NULL);
                    538:
                    539:                        sort_free(cmd);
                    540:
                    541:                } else if ((file = fopen(fn, mode)) == NULL)
                    542:                        err(2, "%s", fn);
                    543:
                    544:                if (is_tmp && (mode[0] == 'w'))
                    545:                        umask(orig_file_mask);
                    546:        }
                    547:
                    548:        return file;
                    549: }
                    550:
                    551: /*
                    552:  * Close file
                    553:  */
                    554: void
                    555: closefile(FILE *f, const char *fn)
                    556: {
                    557:        if (f == NULL) {
                    558:                ;
                    559:        } else if (f == stdin) {
                    560:                ;
                    561:        } else if (f == stdout) {
                    562:                fflush(f);
                    563:        } else {
                    564:                if (file_is_tmp(fn) && compress_program != NULL) {
                    565:                        if (pclose(f) < 0)
                    566:                                err(2, NULL);
                    567:                } else
                    568:                        fclose(f);
                    569:        }
                    570: }
                    571:
                    572: /*
                    573:  * Reads a file into the internal buffer.
                    574:  */
                    575: struct file_reader *
                    576: file_reader_init(const char *fsrc)
                    577: {
                    578:        struct file_reader *ret;
                    579:
                    580:        if (fsrc == NULL)
                    581:                fsrc = "-";
                    582:
1.2       millert   583:        ret = sort_calloc(1, sizeof(struct file_reader));
1.1       millert   584:
                    585:        ret->elsymb = '\n';
                    586:        if (sort_opts_vals.zflag)
                    587:                ret->elsymb = 0;
                    588:
                    589:        ret->fname = sort_strdup(fsrc);
                    590:
                    591:        if (strcmp(fsrc, "-") && (compress_program == NULL) && use_mmap) {
                    592:                struct stat stat_buf;
                    593:                void *addr;
                    594:                size_t sz = 0;
                    595:                int fd;
                    596:
                    597:                fd = open(fsrc, O_RDONLY);
                    598:                if (fd < 0)
                    599:                        err(2, "%s", fsrc);
                    600:
                    601:                if (fstat(fd, &stat_buf) < 0)
                    602:                        err(2, "%s", fsrc);
                    603:                sz = stat_buf.st_size;
                    604:
                    605:                addr = mmap(NULL, sz, PROT_READ, 0, fd, 0);
                    606:                if (addr == MAP_FAILED) {
                    607:                        close(fd);
                    608:                } else {
                    609:                        ret->fd = fd;
                    610:                        ret->mmapaddr = addr;
                    611:                        ret->mmapsize = sz;
                    612:                        ret->mmapptr = ret->mmapaddr;
                    613:                        posix_madvise(addr, sz, POSIX_MADV_SEQUENTIAL);
                    614:                }
                    615:        }
                    616:
                    617:        if (ret->mmapaddr == NULL) {
                    618:                ret->file = openfile(fsrc, "r");
                    619:                if (ret->file == NULL)
                    620:                        err(2, "%s", fsrc);
                    621:
                    622:                if (strcmp(fsrc, "-")) {
                    623:                        ret->cbsz = READ_CHUNK;
                    624:                        ret->buffer = sort_malloc(ret->cbsz);
                    625:                        ret->bsz = 0;
                    626:                        ret->strbeg = 0;
                    627:
                    628:                        ret->bsz = fread(ret->buffer, 1, ret->cbsz, ret->file);
                    629:                        if (ret->bsz == 0) {
                    630:                                if (ferror(ret->file))
                    631:                                        err(2, NULL);
                    632:                        }
                    633:                }
                    634:        }
                    635:
                    636:        return ret;
                    637: }
                    638:
                    639: struct bwstring *
                    640: file_reader_readline(struct file_reader *fr)
                    641: {
                    642:        struct bwstring *ret = NULL;
                    643:
                    644:        if (fr->mmapaddr) {
                    645:                unsigned char *mmapend;
                    646:
                    647:                mmapend = fr->mmapaddr + fr->mmapsize;
                    648:                if (fr->mmapptr >= mmapend)
                    649:                        return NULL;
                    650:                else {
                    651:                        unsigned char *strend;
                    652:                        size_t sz;
                    653:
                    654:                        sz = mmapend - fr->mmapptr;
                    655:                        strend = memchr(fr->mmapptr, fr->elsymb, sz);
                    656:
                    657:                        if (strend == NULL) {
                    658:                                ret = bwscsbdup(fr->mmapptr, sz);
                    659:                                fr->mmapptr = mmapend;
                    660:                        } else {
                    661:                                ret = bwscsbdup(fr->mmapptr, strend -
                    662:                                    fr->mmapptr);
                    663:                                fr->mmapptr = strend + 1;
                    664:                        }
                    665:                }
                    666:
                    667:        } else if (fr->file != stdin) {
                    668:                unsigned char *strend;
                    669:                size_t bsz1, remsz, search_start;
                    670:
                    671:                search_start = 0;
                    672:                remsz = 0;
                    673:                strend = NULL;
                    674:
                    675:                if (fr->bsz > fr->strbeg)
                    676:                        remsz = fr->bsz - fr->strbeg;
                    677:
                    678:                /* line read cycle */
                    679:                for (;;) {
                    680:                        if (remsz > search_start)
                    681:                                strend = memchr(fr->buffer + fr->strbeg +
                    682:                                    search_start, fr->elsymb, remsz -
                    683:                                    search_start);
                    684:                        else
                    685:                                strend = NULL;
                    686:
                    687:                        if (strend)
                    688:                                break;
                    689:                        if (feof(fr->file))
                    690:                                break;
                    691:
                    692:                        if (fr->bsz != fr->cbsz)
                    693:                                /* NOTREACHED */
                    694:                                err(2, "File read software error 1");
                    695:
                    696:                        if (remsz > (READ_CHUNK >> 1)) {
                    697:                                search_start = fr->cbsz - fr->strbeg;
                    698:                                fr->cbsz += READ_CHUNK;
                    699:                                fr->buffer = sort_realloc(fr->buffer,
                    700:                                    fr->cbsz);
                    701:                                bsz1 = fread(fr->buffer + fr->bsz, 1,
                    702:                                    READ_CHUNK, fr->file);
                    703:                                if (bsz1 == 0) {
                    704:                                        if (ferror(fr->file))
                    705:                                                err(2, NULL);
                    706:                                        break;
                    707:                                }
                    708:                                fr->bsz += bsz1;
                    709:                                remsz += bsz1;
                    710:                        } else {
                    711:                                if (remsz > 0 && fr->strbeg>0)
                    712:                                        bcopy(fr->buffer + fr->strbeg,
                    713:                                            fr->buffer, remsz);
                    714:
                    715:                                fr->strbeg = 0;
                    716:                                search_start = remsz;
                    717:                                bsz1 = fread(fr->buffer + remsz, 1,
                    718:                                    fr->cbsz - remsz, fr->file);
                    719:                                if (bsz1 == 0) {
                    720:                                        if (ferror(fr->file))
                    721:                                                err(2, NULL);
                    722:                                        break;
                    723:                                }
                    724:                                fr->bsz = remsz + bsz1;
                    725:                                remsz = fr->bsz;
                    726:                        }
                    727:                }
                    728:
                    729:                if (strend == NULL)
                    730:                        strend = fr->buffer + fr->bsz;
                    731:
                    732:                if ((fr->buffer + fr->strbeg <= strend) &&
                    733:                    (fr->strbeg < fr->bsz) && (remsz>0))
                    734:                        ret = bwscsbdup(fr->buffer + fr->strbeg, strend -
                    735:                            fr->buffer - fr->strbeg);
                    736:
                    737:                fr->strbeg = (strend - fr->buffer) + 1;
                    738:
                    739:        } else {
                    740:                size_t len = 0;
                    741:
                    742:                ret = bwsfgetln(fr->file, &len, sort_opts_vals.zflag,
                    743:                    &(fr->rb));
                    744:        }
                    745:
                    746:        return ret;
                    747: }
                    748:
                    749: static void
                    750: file_reader_clean(struct file_reader *fr)
                    751: {
                    752:
                    753:        if (fr) {
                    754:                if (fr->mmapaddr)
                    755:                        munmap(fr->mmapaddr, fr->mmapsize);
                    756:
                    757:                if (fr->fd)
                    758:                        close(fr->fd);
                    759:
                    760:                if (fr->buffer)
                    761:                        sort_free(fr->buffer);
                    762:
                    763:                if (fr->file)
                    764:                        if (fr->file != stdin)
                    765:                                closefile(fr->file, fr->fname);
                    766:
                    767:                if (fr->fname)
                    768:                        sort_free(fr->fname);
                    769:
                    770:                memset(fr, 0, sizeof(struct file_reader));
                    771:        }
                    772: }
                    773:
                    774: void
                    775: file_reader_free(struct file_reader *fr)
                    776: {
                    777:
                    778:        if (fr) {
                    779:                file_reader_clean(fr);
                    780:                sort_free(fr);
                    781:        }
                    782: }
                    783:
                    784: int
                    785: procfile(const char *fsrc, struct sort_list *list, struct file_list *fl)
                    786: {
                    787:        struct file_reader *fr;
                    788:
                    789:        fr = file_reader_init(fsrc);
                    790:        if (fr == NULL)
                    791:                err(2, "%s", fsrc);
                    792:
                    793:        /* file browse cycle */
                    794:        for (;;) {
                    795:                struct bwstring *bws;
                    796:
                    797:                bws = file_reader_readline(fr);
                    798:
                    799:                if (bws == NULL)
                    800:                        break;
                    801:
                    802:                sort_list_add(list, bws);
                    803:
                    804:                if (list->memsize >= available_free_memory) {
                    805:                        char *fn;
                    806:
                    807:                        fn = new_tmp_file_name();
                    808:                        sort_list_to_file(list, fn);
                    809:                        file_list_add(fl, fn, false);
                    810:                        sort_list_clean(list);
                    811:                }
                    812:        }
                    813:
                    814:        file_reader_free(fr);
                    815:
                    816:        return 0;
                    817: }
                    818:
                    819: /*
                    820:  * Compare file headers. Files with EOF always go to the end of the list.
                    821:  */
                    822: static int
                    823: file_header_cmp(struct file_header *f1, struct file_header *f2)
                    824: {
                    825:
                    826:        if (f1 == f2)
                    827:                return 0;
                    828:        else {
                    829:                if (f1->fr == NULL) {
                    830:                        return (f2->fr == NULL) ? 0 : 1;
                    831:                } else if (f2->fr == NULL)
                    832:                        return -1;
                    833:                else {
                    834:                        int ret;
                    835:
                    836:                        ret = list_coll(&(f1->si), &(f2->si));
                    837:                        if (!ret)
                    838:                                return (f1->file_pos < f2->file_pos) ? -1 : 1;
                    839:                        return ret;
                    840:                }
                    841:        }
                    842: }
                    843:
                    844: /*
                    845:  * Allocate and init file header structure
                    846:  */
                    847: static void
                    848: file_header_init(struct file_header **fh, const char *fn, size_t file_pos)
                    849: {
                    850:
                    851:        if (fh && fn) {
                    852:                struct bwstring *line;
                    853:
                    854:                *fh = sort_malloc(sizeof(struct file_header));
                    855:                (*fh)->file_pos = file_pos;
                    856:                (*fh)->fr = file_reader_init(fn);
                    857:                if ((*fh)->fr == NULL) {
                    858:                        err(2, "Cannot open %s for reading",
                    859:                            strcmp(fn, "-") == 0 ? "stdin" : fn);
                    860:                }
                    861:                line = file_reader_readline((*fh)->fr);
                    862:                if (line == NULL) {
                    863:                        file_reader_free((*fh)->fr);
                    864:                        (*fh)->fr = NULL;
                    865:                        (*fh)->si = NULL;
                    866:                } else {
                    867:                        (*fh)->si = sort_list_item_alloc();
                    868:                        sort_list_item_set((*fh)->si, line);
                    869:                }
                    870:        }
                    871: }
                    872:
                    873: /*
                    874:  * Close file
                    875:  */
                    876: static void
                    877: file_header_close(struct file_header **fh)
                    878: {
                    879:
                    880:        if (fh && *fh) {
                    881:                if ((*fh)->fr) {
                    882:                        file_reader_free((*fh)->fr);
                    883:                        (*fh)->fr = NULL;
                    884:                }
                    885:                if ((*fh)->si) {
                    886:                        sort_list_item_clean((*fh)->si);
                    887:                        sort_free((*fh)->si);
                    888:                        (*fh)->si = NULL;
                    889:                }
                    890:                sort_free(*fh);
                    891:                *fh = NULL;
                    892:        }
                    893: }
                    894:
                    895: /*
                    896:  * Swap two array elements
                    897:  */
                    898: static void
                    899: file_header_swap(struct file_header **fh, size_t i1, size_t i2)
                    900: {
                    901:        struct file_header *tmp;
                    902:
                    903:        tmp = fh[i1];
                    904:        fh[i1] = fh[i2];
                    905:        fh[i2] = tmp;
                    906: }
                    907:
                    908: /* heap algorithm ==>> */
                    909:
                    910: /*
                    911:  * See heap sort algorithm
                    912:  * "Raises" last element to its right place
                    913:  */
                    914: static void
                    915: file_header_heap_swim(struct file_header **fh, size_t indx)
                    916: {
                    917:
                    918:        if (indx > 0) {
                    919:                size_t parent_index;
                    920:
                    921:                parent_index = (indx - 1) >> 1;
                    922:
                    923:                if (file_header_cmp(fh[indx], fh[parent_index]) < 0) {
                    924:                        /* swap child and parent and continue */
                    925:                        file_header_swap(fh, indx, parent_index);
                    926:                        file_header_heap_swim(fh, parent_index);
                    927:                }
                    928:        }
                    929: }
                    930:
                    931: /*
                    932:  * Sink the top element to its correct position
                    933:  */
                    934: static void
                    935: file_header_heap_sink(struct file_header **fh, size_t indx, size_t size)
                    936: {
                    937:        size_t left_child_index;
                    938:        size_t right_child_index;
                    939:
                    940:        left_child_index = indx + indx + 1;
                    941:        right_child_index = left_child_index + 1;
                    942:
                    943:        if (left_child_index < size) {
                    944:                size_t min_child_index;
                    945:
                    946:                min_child_index = left_child_index;
                    947:
                    948:                if ((right_child_index < size) &&
                    949:                    (file_header_cmp(fh[left_child_index],
                    950:                    fh[right_child_index]) > 0))
                    951:                        min_child_index = right_child_index;
                    952:                if (file_header_cmp(fh[indx], fh[min_child_index]) > 0) {
                    953:                        file_header_swap(fh, indx, min_child_index);
                    954:                        file_header_heap_sink(fh, min_child_index, size);
                    955:                }
                    956:        }
                    957: }
                    958:
                    959: /* <<== heap algorithm */
                    960:
                    961: /*
                    962:  * Adds element to the "left" end
                    963:  */
                    964: static void
                    965: file_header_list_rearrange_from_header(struct file_header **fh, size_t size)
                    966: {
                    967:
                    968:        file_header_heap_sink(fh, 0, size);
                    969: }
                    970:
                    971: /*
                    972:  * Adds element to the "right" end
                    973:  */
                    974: static void
                    975: file_header_list_push(struct file_header *f, struct file_header **fh, size_t size)
                    976: {
                    977:
                    978:        fh[size++] = f;
                    979:        file_header_heap_swim(fh, size - 1);
                    980: }
                    981:
                    982: struct last_printed
                    983: {
                    984:        struct bwstring *str;
                    985: };
                    986:
                    987: /*
                    988:  * Prints the current line of the file
                    989:  */
                    990: static void
                    991: file_header_print(struct file_header *fh, FILE *f_out, struct last_printed *lp)
                    992: {
                    993:
                    994:        if (fh && fh->fr && f_out && fh->si && fh->si->str) {
                    995:                if (sort_opts_vals.uflag) {
                    996:                        if ((lp->str == NULL) || (str_list_coll(lp->str, &(fh->si)))) {
                    997:                                bwsfwrite(fh->si->str, f_out, sort_opts_vals.zflag);
                    998:                                if (lp->str)
                    999:                                        bwsfree(lp->str);
                   1000:                                lp->str = bwsdup(fh->si->str);
                   1001:                        }
                   1002:                } else
                   1003:                        bwsfwrite(fh->si->str, f_out, sort_opts_vals.zflag);
                   1004:        }
                   1005: }
                   1006:
                   1007: /*
                   1008:  * Read next line
                   1009:  */
                   1010: static void
                   1011: file_header_read_next(struct file_header *fh)
                   1012: {
                   1013:
                   1014:        if (fh && fh->fr) {
                   1015:                struct bwstring *tmp;
                   1016:
                   1017:                tmp = file_reader_readline(fh->fr);
                   1018:                if (tmp == NULL) {
                   1019:                        file_reader_free(fh->fr);
                   1020:                        fh->fr = NULL;
                   1021:                        if (fh->si) {
                   1022:                                sort_list_item_clean(fh->si);
                   1023:                                sort_free(fh->si);
                   1024:                                fh->si = NULL;
                   1025:                        }
                   1026:                } else {
                   1027:                        if (fh->si == NULL)
                   1028:                                fh->si = sort_list_item_alloc();
                   1029:                        sort_list_item_set(fh->si, tmp);
                   1030:                }
                   1031:        }
                   1032: }
                   1033:
                   1034: /*
                   1035:  * Merge array of "files headers"
                   1036:  */
                   1037: static void
                   1038: file_headers_merge(size_t fnum, struct file_header **fh, FILE *f_out)
                   1039: {
                   1040:        struct last_printed lp;
                   1041:        size_t i;
                   1042:
                   1043:        memset(&lp, 0, sizeof(lp));
                   1044:
                   1045:        /*
                   1046:         * construct the initial sort structure
                   1047:         */
                   1048:        for (i = 0; i < fnum; i++)
                   1049:                file_header_list_push(fh[i], fh, i);
                   1050:
                   1051:        while (fh[0]->fr) { /* unfinished files are always in front */
                   1052:                /* output the smallest line: */
                   1053:                file_header_print(fh[0], f_out, &lp);
                   1054:                /* read a new line, if possible: */
                   1055:                file_header_read_next(fh[0]);
                   1056:                /* re-arrange the list: */
                   1057:                file_header_list_rearrange_from_header(fh, fnum);
                   1058:        }
                   1059:
                   1060:        if (lp.str)
                   1061:                bwsfree(lp.str);
                   1062: }
                   1063:
                   1064: /*
                   1065:  * Merges the given files into the output file, which can be
                   1066:  * stdout.
                   1067:  */
                   1068: static void
                   1069: merge_files_array(size_t argc, char **argv, const char *fn_out)
                   1070: {
                   1071:
                   1072:        if (argv && fn_out) {
                   1073:                struct file_header **fh;
                   1074:                FILE *f_out;
                   1075:                size_t i;
                   1076:
                   1077:                f_out = openfile(fn_out, "w");
                   1078:
                   1079:                if (f_out == NULL)
                   1080:                        err(2, "%s", fn_out);
                   1081:
                   1082:                fh = sort_malloc((argc + 1) * sizeof(struct file_header *));
                   1083:
                   1084:                for (i = 0; i < argc; i++)
                   1085:                        file_header_init(fh + i, argv[i], (size_t) i);
                   1086:
                   1087:                file_headers_merge(argc, fh, f_out);
                   1088:
                   1089:                for (i = 0; i < argc; i++)
                   1090:                        file_header_close(fh + i);
                   1091:
                   1092:                sort_free(fh);
                   1093:
                   1094:                closefile(f_out, fn_out);
                   1095:        }
                   1096: }
                   1097:
                   1098: /*
                   1099:  * Shrinks the file list until its size smaller than max number of opened files
                   1100:  */
                   1101: static int
                   1102: shrink_file_list(struct file_list *fl)
                   1103: {
                   1104:
                   1105:        if (fl == NULL || (size_t)fl->count < max_open_files)
                   1106:                return 0;
                   1107:        else {
                   1108:                struct file_list new_fl;
                   1109:                size_t indx = 0;
                   1110:
                   1111:                file_list_init(&new_fl, true);
                   1112:                while (indx < fl->count) {
                   1113:                        char *fnew;
                   1114:                        size_t num;
                   1115:
                   1116:                        num = fl->count - indx;
                   1117:                        fnew = new_tmp_file_name();
                   1118:
                   1119:                        if ((size_t) num >= max_open_files)
                   1120:                                num = max_open_files - 1;
                   1121:                        merge_files_array(num, fl->fns + indx, fnew);
                   1122:                        if (fl->tmp) {
                   1123:                                size_t i;
                   1124:
                   1125:                                for (i = 0; i < num; i++)
                   1126:                                        unlink(fl->fns[indx + i]);
                   1127:                        }
                   1128:                        file_list_add(&new_fl, fnew, false);
                   1129:                        indx += num;
                   1130:                }
                   1131:                fl->tmp = false; /* already taken care of */
                   1132:                file_list_clean(fl);
                   1133:
                   1134:                fl->count = new_fl.count;
                   1135:                fl->fns = new_fl.fns;
                   1136:                fl->sz = new_fl.sz;
                   1137:                fl->tmp = new_fl.tmp;
                   1138:
                   1139:                return 1;
                   1140:        }
                   1141: }
                   1142:
                   1143: /*
                   1144:  * Merge list of files
                   1145:  */
                   1146: void
                   1147: merge_files(struct file_list *fl, const char *fn_out)
                   1148: {
                   1149:
                   1150:        if (fl && fn_out) {
                   1151:                while (shrink_file_list(fl));
                   1152:
                   1153:                merge_files_array(fl->count, fl->fns, fn_out);
                   1154:        }
                   1155: }
                   1156:
                   1157: static const char *
                   1158: get_sort_method_name(int sm)
                   1159: {
                   1160:
                   1161:        if (sm == SORT_MERGESORT)
                   1162:                return "mergesort";
                   1163:        else if (sort_opts_vals.sort_method == SORT_RADIXSORT)
                   1164:                return "radixsort";
                   1165:        else if (sort_opts_vals.sort_method == SORT_HEAPSORT)
                   1166:                return "heapsort";
                   1167:        else
                   1168:                return "quicksort";
                   1169: }
                   1170:
                   1171: /*
                   1172:  * Sort list of lines and writes it to the file
                   1173:  */
                   1174: void
                   1175: sort_list_to_file(struct sort_list *list, const char *outfile)
                   1176: {
                   1177:        struct sort_mods *sm = &(keys[0].sm);
                   1178:
                   1179:        if (!sm->Mflag && !sm->Rflag && !sm->Vflag &&
                   1180:            !sm->gflag && !sm->hflag && !sm->nflag) {
                   1181:                if ((sort_opts_vals.sort_method == SORT_DEFAULT) && byte_sort)
                   1182:                        sort_opts_vals.sort_method = SORT_RADIXSORT;
                   1183:
                   1184:        } else if (sort_opts_vals.sort_method == SORT_RADIXSORT)
                   1185:                err(2, "Radix sort cannot be used with these sort options");
                   1186:
                   1187:        /*
                   1188:         * to handle stable sort and the unique cases in the
                   1189:         * right order, we need stable basic algorithm
                   1190:         */
                   1191:        if (sort_opts_vals.sflag) {
                   1192:                switch (sort_opts_vals.sort_method){
                   1193:                case SORT_MERGESORT:
                   1194:                        break;
                   1195:                case SORT_RADIXSORT:
                   1196:                        break;
                   1197:                case SORT_DEFAULT:
                   1198:                        sort_opts_vals.sort_method = SORT_MERGESORT;
                   1199:                        break;
                   1200:                default:
                   1201:                        errx(2, "The chosen sort method cannot be used with "
                   1202:                            "stable and/or unique sort");
                   1203:                };
                   1204:        }
                   1205:
                   1206:        if (sort_opts_vals.sort_method == SORT_DEFAULT)
                   1207:                sort_opts_vals.sort_method = DEFAULT_SORT_ALGORITHM;
                   1208:
                   1209:        if (debug_sort)
                   1210:                printf("sort_method=%s\n",
                   1211:                    get_sort_method_name(sort_opts_vals.sort_method));
                   1212:
                   1213:        switch (sort_opts_vals.sort_method){
                   1214:        case SORT_RADIXSORT:
                   1215:                rxsort(list->list, list->count);
                   1216:                break;
                   1217:        case SORT_MERGESORT:
                   1218:                mergesort(list->list, list->count,
                   1219:                    sizeof(struct sort_list_item *), list_coll);
                   1220:                break;
                   1221:        case SORT_HEAPSORT:
                   1222:                heapsort(list->list, list->count,
                   1223:                    sizeof(struct sort_list_item *), list_coll);
                   1224:                break;
                   1225:        case SORT_QSORT:
                   1226:                qsort(list->list, list->count,
                   1227:                    sizeof(struct sort_list_item *), list_coll);
                   1228:                break;
                   1229:        default:
                   1230:                DEFAULT_SORT_FUNC(list->list, list->count,
                   1231:                    sizeof(struct sort_list_item *), list_coll);
                   1232:                break;
                   1233:        }
                   1234:        sort_list_dump(list, outfile);
                   1235: }