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