mirrored from git://git.sv.gnu.org/coreutils.git
-
Notifications
You must be signed in to change notification settings - Fork 892
/
sort.c
4780 lines (4141 loc) · 142 KB
/
sort.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* sort - sort lines of text (with all kinds of options).
Copyright (C) 1988-2019 Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Written December 1988 by Mike Haertel.
The author may be reached (Email) at the address mike@gnu.ai.mit.edu,
or (US mail) as Mike Haertel c/o Free Software Foundation.
Ørn E. Hansen added NLS support in 1997. */
#include <config.h>
#include <getopt.h>
#include <pthread.h>
#include <sys/resource.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <assert.h>
#include "system.h"
#include "argmatch.h"
#include "die.h"
#include "error.h"
#include "fadvise.h"
#include "filevercmp.h"
#include "flexmember.h"
#include "hard-locale.h"
#include "hash.h"
#include "heap.h"
#include "ignore-value.h"
#include "md5.h"
#include "mbswidth.h"
#include "nproc.h"
#include "physmem.h"
#include "posixver.h"
#include "quote.h"
#include "randread.h"
#include "readtokens0.h"
#include "stdlib--.h"
#include "strnumcmp.h"
#include "xmemcoll.h"
#include "xnanosleep.h"
#include "xstrtol.h"
#ifndef RLIMIT_DATA
struct rlimit { size_t rlim_cur; };
# define getrlimit(Resource, Rlp) (-1)
#endif
/* The official name of this program (e.g., no 'g' prefix). */
#define PROGRAM_NAME "sort"
#define AUTHORS \
proper_name ("Mike Haertel"), \
proper_name ("Paul Eggert")
#if HAVE_LANGINFO_CODESET
# include <langinfo.h>
#endif
/* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is
present. */
#ifndef SA_NOCLDSTOP
# define SA_NOCLDSTOP 0
/* No sigprocmask. Always 'return' zero. */
# define sigprocmask(How, Set, Oset) (0)
# define sigset_t int
# if ! HAVE_SIGINTERRUPT
# define siginterrupt(sig, flag) /* empty */
# endif
#endif
#if !defined OPEN_MAX && defined NR_OPEN
# define OPEN_MAX NR_OPEN
#endif
#if !defined OPEN_MAX
# define OPEN_MAX 20
#endif
#define UCHAR_LIM (UCHAR_MAX + 1)
#ifndef DEFAULT_TMPDIR
# define DEFAULT_TMPDIR "/tmp"
#endif
/* Maximum number of lines to merge every time a NODE is taken from
the merge queue. Node is at LEVEL in the binary merge tree,
and is responsible for merging TOTAL lines. */
#define MAX_MERGE(total, level) (((total) >> (2 * ((level) + 1))) + 1)
/* Heuristic value for the number of lines for which it is worth creating
a subthread, during an internal merge sort. I.e., it is a small number
of "average" lines for which sorting via two threads is faster than
sorting via one on an "average" system. On a dual-core 2.0 GHz i686
system with 3GB of RAM and 2MB of L2 cache, a file containing 128K
lines of gensort -a output is sorted slightly faster with --parallel=2
than with --parallel=1. By contrast, using --parallel=1 is about 10%
faster than using --parallel=2 with a 64K-line input. */
enum { SUBTHREAD_LINES_HEURISTIC = 128 * 1024 };
verify (4 <= SUBTHREAD_LINES_HEURISTIC);
/* The number of threads after which there are
diminishing performance gains. */
enum { DEFAULT_MAX_THREADS = 8 };
/* Exit statuses. */
enum
{
/* POSIX says to exit with status 1 if invoked with -c and the
input is not properly sorted. */
SORT_OUT_OF_ORDER = 1,
/* POSIX says any other irregular exit must exit with a status
code greater than 1. */
SORT_FAILURE = 2
};
enum
{
/* The number of times we should try to fork a compression process
(we retry if the fork call fails). We don't _need_ to compress
temp files, this is just to reduce disk access, so this number
can be small. Each retry doubles in duration. */
MAX_FORK_TRIES_COMPRESS = 4,
/* The number of times we should try to fork a decompression process.
If we can't fork a decompression process, we can't sort, so this
number should be big. Each retry doubles in duration. */
MAX_FORK_TRIES_DECOMPRESS = 9
};
enum
{
/* Level of the end-of-merge node, one level above the root. */
MERGE_END = 0,
/* Level of the root node in merge tree. */
MERGE_ROOT = 1
};
/* The representation of the decimal point in the current locale. */
static int decimal_point;
/* Thousands separator; if -1, then there isn't one. */
static int thousands_sep;
/* Nonzero if the corresponding locales are hard. */
static bool hard_LC_COLLATE;
#if HAVE_NL_LANGINFO
static bool hard_LC_TIME;
#endif
#define NONZERO(x) ((x) != 0)
/* The kind of blanks for '-b' to skip in various options. */
enum blanktype { bl_start, bl_end, bl_both };
/* The character marking end of line. Default to \n. */
static char eolchar = '\n';
/* Lines are held in core as counted strings. */
struct line
{
char *text; /* Text of the line. */
size_t length; /* Length including final newline. */
char *keybeg; /* Start of first key. */
char *keylim; /* Limit of first key. */
};
/* Input buffers. */
struct buffer
{
char *buf; /* Dynamically allocated buffer,
partitioned into 3 regions:
- input data;
- unused area;
- an array of lines, in reverse order. */
size_t used; /* Number of bytes used for input data. */
size_t nlines; /* Number of lines in the line array. */
size_t alloc; /* Number of bytes allocated. */
size_t left; /* Number of bytes left from previous reads. */
size_t line_bytes; /* Number of bytes to reserve for each line. */
bool eof; /* An EOF has been read. */
};
/* Sort key. */
struct keyfield
{
size_t sword; /* Zero-origin 'word' to start at. */
size_t schar; /* Additional characters to skip. */
size_t eword; /* Zero-origin last 'word' of key. */
size_t echar; /* Additional characters in field. */
bool const *ignore; /* Boolean array of characters to ignore. */
char const *translate; /* Translation applied to characters. */
bool skipsblanks; /* Skip leading blanks when finding start. */
bool skipeblanks; /* Skip leading blanks when finding end. */
bool numeric; /* Flag for numeric comparison. Handle
strings of digits with optional decimal
point, but no exponential notation. */
bool random; /* Sort by random hash of key. */
bool general_numeric; /* Flag for general, numeric comparison.
Handle numbers in exponential notation. */
bool human_numeric; /* Flag for sorting by human readable
units with either SI or IEC prefixes. */
bool month; /* Flag for comparison by month name. */
bool reverse; /* Reverse the sense of comparison. */
bool version; /* sort by version number */
bool traditional_used; /* Traditional key option format is used. */
struct keyfield *next; /* Next keyfield to try. */
};
struct month
{
char const *name;
int val;
};
/* Binary merge tree node. */
struct merge_node
{
struct line *lo; /* Lines to merge from LO child node. */
struct line *hi; /* Lines to merge from HI child node. */
struct line *end_lo; /* End of available lines from LO. */
struct line *end_hi; /* End of available lines from HI. */
struct line **dest; /* Pointer to destination of merge. */
size_t nlo; /* Total Lines remaining from LO. */
size_t nhi; /* Total lines remaining from HI. */
struct merge_node *parent; /* Parent node. */
struct merge_node *lo_child; /* LO child node. */
struct merge_node *hi_child; /* HI child node. */
unsigned int level; /* Level in merge tree. */
bool queued; /* Node is already in heap. */
pthread_mutex_t lock; /* Lock for node operations. */
};
/* Priority queue of merge nodes. */
struct merge_node_queue
{
struct heap *priority_queue; /* Priority queue of merge tree nodes. */
pthread_mutex_t mutex; /* Lock for queue operations. */
pthread_cond_t cond; /* Conditional wait for empty queue to populate
when popping. */
};
/* Used to implement --unique (-u). */
static struct line saved_line;
/* FIXME: None of these tables work with multibyte character sets.
Also, there are many other bugs when handling multibyte characters.
One way to fix this is to rewrite 'sort' to use wide characters
internally, but doing this with good performance is a bit
tricky. */
/* Table of blanks. */
static bool blanks[UCHAR_LIM];
/* Table of non-printing characters. */
static bool nonprinting[UCHAR_LIM];
/* Table of non-dictionary characters (not letters, digits, or blanks). */
static bool nondictionary[UCHAR_LIM];
/* Translation table folding lower case to upper. */
static char fold_toupper[UCHAR_LIM];
#define MONTHS_PER_YEAR 12
/* Table mapping month names to integers.
Alphabetic order allows binary search. */
static struct month monthtab[] =
{
{"APR", 4},
{"AUG", 8},
{"DEC", 12},
{"FEB", 2},
{"JAN", 1},
{"JUL", 7},
{"JUN", 6},
{"MAR", 3},
{"MAY", 5},
{"NOV", 11},
{"OCT", 10},
{"SEP", 9}
};
/* During the merge phase, the number of files to merge at once. */
#define NMERGE_DEFAULT 16
/* Minimum size for a merge or check buffer. */
#define MIN_MERGE_BUFFER_SIZE (2 + sizeof (struct line))
/* Minimum sort size; the code might not work with smaller sizes. */
#define MIN_SORT_SIZE (nmerge * MIN_MERGE_BUFFER_SIZE)
/* The number of bytes needed for a merge or check buffer, which can
function relatively efficiently even if it holds only one line. If
a longer line is seen, this value is increased. */
static size_t merge_buffer_size = MAX (MIN_MERGE_BUFFER_SIZE, 256 * 1024);
/* The approximate maximum number of bytes of main memory to use, as
specified by the user. Zero if the user has not specified a size. */
static size_t sort_size;
/* The initial allocation factor for non-regular files.
This is used, e.g., when reading from a pipe.
Don't make it too big, since it is multiplied by ~130 to
obtain the size of the actual buffer sort will allocate.
Also, there may be 8 threads all doing this at the same time. */
#define INPUT_FILE_SIZE_GUESS (128 * 1024)
/* Array of directory names in which any temporary files are to be created. */
static char const **temp_dirs;
/* Number of temporary directory names used. */
static size_t temp_dir_count;
/* Number of allocated slots in temp_dirs. */
static size_t temp_dir_alloc;
/* Flag to reverse the order of all comparisons. */
static bool reverse;
/* Flag for stable sort. This turns off the last ditch bytewise
comparison of lines, and instead leaves lines in the same order
they were read if all keys compare equal. */
static bool stable;
/* If TAB has this value, blanks separate fields. */
enum { TAB_DEFAULT = CHAR_MAX + 1 };
/* Tab character separating fields. If TAB_DEFAULT, then fields are
separated by the empty string between a non-blank character and a blank
character. */
static int tab = TAB_DEFAULT;
/* Flag to remove consecutive duplicate lines from the output.
Only the last of a sequence of equal lines will be output. */
static bool unique;
/* Nonzero if any of the input files are the standard input. */
static bool have_read_stdin;
/* List of key field comparisons to be tried. */
static struct keyfield *keylist;
/* Program used to (de)compress temp files. Must accept -d. */
static char const *compress_program;
/* Annotate the output with extra info to aid the user. */
static bool debug;
/* Maximum number of files to merge in one go. If more than this
number are present, temp files will be used. */
static unsigned int nmerge = NMERGE_DEFAULT;
/* Output an error to stderr and exit using async-signal-safe routines.
This can be used safely from signal handlers,
and between fork and exec of multithreaded processes. */
static void async_safe_die (int, const char *) ATTRIBUTE_NORETURN;
static void
async_safe_die (int errnum, const char *errstr)
{
ignore_value (write (STDERR_FILENO, errstr, strlen (errstr)));
/* Even if defined HAVE_STRERROR_R, we can't use it,
as it may return a translated string etc. and even if not
may call malloc which is unsafe. We might improve this
by testing for sys_errlist and using that if available.
For now just report the error number. */
if (errnum)
{
char errbuf[INT_BUFSIZE_BOUND (errnum)];
char *p = inttostr (errnum, errbuf);
ignore_value (write (STDERR_FILENO, ": errno ", 8));
ignore_value (write (STDERR_FILENO, p, strlen (p)));
}
ignore_value (write (STDERR_FILENO, "\n", 1));
_exit (SORT_FAILURE);
}
/* Report MESSAGE for FILE, then clean up and exit.
If FILE is null, it represents standard output. */
static void sort_die (char const *, char const *) ATTRIBUTE_NORETURN;
static void
sort_die (char const *message, char const *file)
{
die (SORT_FAILURE, errno, "%s: %s", message,
quotef (file ? file : _("standard output")));
}
void
usage (int status)
{
if (status != EXIT_SUCCESS)
emit_try_help ();
else
{
printf (_("\
Usage: %s [OPTION]... [FILE]...\n\
or: %s [OPTION]... --files0-from=F\n\
"),
program_name, program_name);
fputs (_("\
Write sorted concatenation of all FILE(s) to standard output.\n\
"), stdout);
emit_stdin_note ();
emit_mandatory_arg_note ();
fputs (_("\
Ordering options:\n\
\n\
"), stdout);
fputs (_("\
-b, --ignore-leading-blanks ignore leading blanks\n\
-d, --dictionary-order consider only blanks and alphanumeric characters\
\n\
-f, --ignore-case fold lower case to upper case characters\n\
"), stdout);
fputs (_("\
-g, --general-numeric-sort compare according to general numerical value\n\
-i, --ignore-nonprinting consider only printable characters\n\
-M, --month-sort compare (unknown) < 'JAN' < ... < 'DEC'\n\
"), stdout);
fputs (_("\
-h, --human-numeric-sort compare human readable numbers (e.g., 2K 1G)\n\
"), stdout);
fputs (_("\
-n, --numeric-sort compare according to string numerical value\n\
-R, --random-sort shuffle, but group identical keys. See shuf(1)\n\
--random-source=FILE get random bytes from FILE\n\
-r, --reverse reverse the result of comparisons\n\
"), stdout);
fputs (_("\
--sort=WORD sort according to WORD:\n\
general-numeric -g, human-numeric -h, month -M,\
\n\
numeric -n, random -R, version -V\n\
-V, --version-sort natural sort of (version) numbers within text\n\
\n\
"), stdout);
fputs (_("\
Other options:\n\
\n\
"), stdout);
fputs (_("\
--batch-size=NMERGE merge at most NMERGE inputs at once;\n\
for more use temp files\n\
"), stdout);
fputs (_("\
-c, --check, --check=diagnose-first check for sorted input; do not sort\n\
-C, --check=quiet, --check=silent like -c, but do not report first bad line\
\n\
--compress-program=PROG compress temporaries with PROG;\n\
decompress them with PROG -d\n\
"), stdout);
fputs (_("\
--debug annotate the part of the line used to sort,\n\
and warn about questionable usage to stderr\n\
--files0-from=F read input from the files specified by\n\
NUL-terminated names in file F;\n\
If F is - then read names from standard input\n\
"), stdout);
fputs (_("\
-k, --key=KEYDEF sort via a key; KEYDEF gives location and type\n\
-m, --merge merge already sorted files; do not sort\n\
"), stdout);
fputs (_("\
-o, --output=FILE write result to FILE instead of standard output\n\
-s, --stable stabilize sort by disabling last-resort comparison\
\n\
-S, --buffer-size=SIZE use SIZE for main memory buffer\n\
"), stdout);
printf (_("\
-t, --field-separator=SEP use SEP instead of non-blank to blank transition\n\
-T, --temporary-directory=DIR use DIR for temporaries, not $TMPDIR or %s;\n\
multiple options specify multiple directories\n\
--parallel=N change the number of sorts run concurrently to N\n\
-u, --unique with -c, check for strict ordering;\n\
without -c, output only the first of an equal run\
\n\
"), DEFAULT_TMPDIR);
fputs (_("\
-z, --zero-terminated line delimiter is NUL, not newline\n\
"), stdout);
fputs (HELP_OPTION_DESCRIPTION, stdout);
fputs (VERSION_OPTION_DESCRIPTION, stdout);
fputs (_("\
\n\
KEYDEF is F[.C][OPTS][,F[.C][OPTS]] for start and stop position, where F is a\n\
field number and C a character position in the field; both are origin 1, and\n\
the stop position defaults to the line's end. If neither -t nor -b is in\n\
effect, characters in a field are counted from the beginning of the preceding\n\
whitespace. OPTS is one or more single-letter ordering options [bdfgiMhnRrV],\
\n\
which override global ordering options for that key. If no key is given, use\n\
the entire line as the key. Use --debug to diagnose incorrect key usage.\n\
\n\
SIZE may be followed by the following multiplicative suffixes:\n\
"), stdout);
fputs (_("\
% 1% of memory, b 1, K 1024 (default), and so on for M, G, T, P, E, Z, Y.\n\
\n\
*** WARNING ***\n\
The locale specified by the environment affects sort order.\n\
Set LC_ALL=C to get the traditional sort order that uses\n\
native byte values.\n\
"), stdout );
emit_ancillary_info (PROGRAM_NAME);
}
exit (status);
}
/* For long options that have no equivalent short option, use a
non-character as a pseudo short option, starting with CHAR_MAX + 1. */
enum
{
CHECK_OPTION = CHAR_MAX + 1,
COMPRESS_PROGRAM_OPTION,
DEBUG_PROGRAM_OPTION,
FILES0_FROM_OPTION,
NMERGE_OPTION,
RANDOM_SOURCE_OPTION,
SORT_OPTION,
PARALLEL_OPTION
};
static char const short_options[] = "-bcCdfghik:mMno:rRsS:t:T:uVy:z";
static struct option const long_options[] =
{
{"ignore-leading-blanks", no_argument, NULL, 'b'},
{"check", optional_argument, NULL, CHECK_OPTION},
{"compress-program", required_argument, NULL, COMPRESS_PROGRAM_OPTION},
{"debug", no_argument, NULL, DEBUG_PROGRAM_OPTION},
{"dictionary-order", no_argument, NULL, 'd'},
{"ignore-case", no_argument, NULL, 'f'},
{"files0-from", required_argument, NULL, FILES0_FROM_OPTION},
{"general-numeric-sort", no_argument, NULL, 'g'},
{"ignore-nonprinting", no_argument, NULL, 'i'},
{"key", required_argument, NULL, 'k'},
{"merge", no_argument, NULL, 'm'},
{"month-sort", no_argument, NULL, 'M'},
{"numeric-sort", no_argument, NULL, 'n'},
{"human-numeric-sort", no_argument, NULL, 'h'},
{"version-sort", no_argument, NULL, 'V'},
{"random-sort", no_argument, NULL, 'R'},
{"random-source", required_argument, NULL, RANDOM_SOURCE_OPTION},
{"sort", required_argument, NULL, SORT_OPTION},
{"output", required_argument, NULL, 'o'},
{"reverse", no_argument, NULL, 'r'},
{"stable", no_argument, NULL, 's'},
{"batch-size", required_argument, NULL, NMERGE_OPTION},
{"buffer-size", required_argument, NULL, 'S'},
{"field-separator", required_argument, NULL, 't'},
{"temporary-directory", required_argument, NULL, 'T'},
{"unique", no_argument, NULL, 'u'},
{"zero-terminated", no_argument, NULL, 'z'},
{"parallel", required_argument, NULL, PARALLEL_OPTION},
{GETOPT_HELP_OPTION_DECL},
{GETOPT_VERSION_OPTION_DECL},
{NULL, 0, NULL, 0},
};
#define CHECK_TABLE \
_ct_("quiet", 'C') \
_ct_("silent", 'C') \
_ct_("diagnose-first", 'c')
static char const *const check_args[] =
{
#define _ct_(_s, _c) _s,
CHECK_TABLE NULL
#undef _ct_
};
static char const check_types[] =
{
#define _ct_(_s, _c) _c,
CHECK_TABLE
#undef _ct_
};
#define SORT_TABLE \
_st_("general-numeric", 'g') \
_st_("human-numeric", 'h') \
_st_("month", 'M') \
_st_("numeric", 'n') \
_st_("random", 'R') \
_st_("version", 'V')
static char const *const sort_args[] =
{
#define _st_(_s, _c) _s,
SORT_TABLE NULL
#undef _st_
};
static char const sort_types[] =
{
#define _st_(_s, _c) _c,
SORT_TABLE
#undef _st_
};
/* The set of signals that are caught. */
static sigset_t caught_signals;
/* Critical section status. */
struct cs_status
{
bool valid;
sigset_t sigs;
};
/* Enter a critical section. */
static void
cs_enter (struct cs_status *status)
{
int ret = pthread_sigmask (SIG_BLOCK, &caught_signals, &status->sigs);
status->valid = ret == 0;
}
/* Leave a critical section. */
static void
cs_leave (struct cs_status const *status)
{
if (status->valid)
{
/* Ignore failure when restoring the signal mask. */
pthread_sigmask (SIG_SETMASK, &status->sigs, NULL);
}
}
/* Possible states for a temp file. If compressed, the file's status
is unreaped or reaped, depending on whether 'sort' has waited for
the subprocess to finish. */
enum { UNCOMPRESSED, UNREAPED, REAPED };
/* The list of temporary files. */
struct tempnode
{
struct tempnode *volatile next;
pid_t pid; /* The subprocess PID; undefined if state == UNCOMPRESSED. */
char state;
char name[FLEXIBLE_ARRAY_MEMBER];
};
static struct tempnode *volatile temphead;
static struct tempnode *volatile *temptail = &temphead;
/* A file to be sorted. */
struct sortfile
{
/* The file's name. */
char const *name;
/* Non-null if this is a temporary file, in which case NAME == TEMP->name. */
struct tempnode *temp;
};
/* Map PIDs of unreaped subprocesses to their struct tempnode objects. */
static Hash_table *proctab;
enum { INIT_PROCTAB_SIZE = 47 };
static size_t
proctab_hasher (void const *entry, size_t tabsize)
{
struct tempnode const *node = entry;
return node->pid % tabsize;
}
static bool
proctab_comparator (void const *e1, void const *e2)
{
struct tempnode const *n1 = e1;
struct tempnode const *n2 = e2;
return n1->pid == n2->pid;
}
/* The number of unreaped child processes. */
static pid_t nprocs;
static bool delete_proc (pid_t);
/* If PID is positive, wait for the child process with that PID to
exit, and assume that PID has already been removed from the process
table. If PID is 0 or -1, clean up some child that has exited (by
waiting for it, and removing it from the proc table) and return the
child's process ID. However, if PID is 0 and no children have
exited, return 0 without waiting. */
static pid_t
reap (pid_t pid)
{
int status;
pid_t cpid = waitpid ((pid ? pid : -1), &status, (pid ? 0 : WNOHANG));
if (cpid < 0)
die (SORT_FAILURE, errno, _("waiting for %s [-d]"),
quoteaf (compress_program));
else if (0 < cpid && (0 < pid || delete_proc (cpid)))
{
if (! WIFEXITED (status) || WEXITSTATUS (status))
die (SORT_FAILURE, 0, _("%s [-d] terminated abnormally"),
quoteaf (compress_program));
--nprocs;
}
return cpid;
}
/* TEMP represents a new process; add it to the process table. Create
the process table the first time it's called. */
static void
register_proc (struct tempnode *temp)
{
if (! proctab)
{
proctab = hash_initialize (INIT_PROCTAB_SIZE, NULL,
proctab_hasher,
proctab_comparator,
NULL);
if (! proctab)
xalloc_die ();
}
temp->state = UNREAPED;
if (! hash_insert (proctab, temp))
xalloc_die ();
}
/* If PID is in the process table, remove it and return true.
Otherwise, return false. */
static bool
delete_proc (pid_t pid)
{
struct tempnode test;
test.pid = pid;
struct tempnode *node = hash_delete (proctab, &test);
if (! node)
return false;
node->state = REAPED;
return true;
}
/* Remove PID from the process table, and wait for it to exit if it
hasn't already. */
static void
wait_proc (pid_t pid)
{
if (delete_proc (pid))
reap (pid);
}
/* Reap any exited children. Do not block; reap only those that have
already exited. */
static void
reap_exited (void)
{
while (0 < nprocs && reap (0))
continue;
}
/* Reap at least one exited child, waiting if necessary. */
static void
reap_some (void)
{
reap (-1);
reap_exited ();
}
/* Reap all children, waiting if necessary. */
static void
reap_all (void)
{
while (0 < nprocs)
reap (-1);
}
/* Clean up any remaining temporary files. */
static void
cleanup (void)
{
struct tempnode const *node;
for (node = temphead; node; node = node->next)
unlink (node->name);
temphead = NULL;
}
/* Cleanup actions to take when exiting. */
static void
exit_cleanup (void)
{
if (temphead)
{
/* Clean up any remaining temporary files in a critical section so
that a signal handler does not try to clean them too. */
struct cs_status cs;
cs_enter (&cs);
cleanup ();
cs_leave (&cs);
}
close_stdout ();
}
/* Create a new temporary file, returning its newly allocated tempnode.
Store into *PFD the file descriptor open for writing.
If the creation fails, return NULL and store -1 into *PFD if the
failure is due to file descriptor exhaustion and
SURVIVE_FD_EXHAUSTION; otherwise, die. */
static struct tempnode *
create_temp_file (int *pfd, bool survive_fd_exhaustion)
{
static char const slashbase[] = "/sortXXXXXX";
static size_t temp_dir_index;
int fd;
int saved_errno;
char const *temp_dir = temp_dirs[temp_dir_index];
size_t len = strlen (temp_dir);
struct tempnode *node =
xmalloc (FLEXSIZEOF (struct tempnode, name, len + sizeof slashbase));
char *file = node->name;
struct cs_status cs;
memcpy (file, temp_dir, len);
memcpy (file + len, slashbase, sizeof slashbase);
node->next = NULL;
if (++temp_dir_index == temp_dir_count)
temp_dir_index = 0;
/* Create the temporary file in a critical section, to avoid races. */
cs_enter (&cs);
fd = mkostemp (file, O_CLOEXEC);
if (0 <= fd)
{
*temptail = node;
temptail = &node->next;
}
saved_errno = errno;
cs_leave (&cs);
errno = saved_errno;
if (fd < 0)
{
if (! (survive_fd_exhaustion && errno == EMFILE))
die (SORT_FAILURE, errno, _("cannot create temporary file in %s"),
quoteaf (temp_dir));
free (node);
node = NULL;
}
*pfd = fd;
return node;
}
/* Return a pointer to stdout status, or NULL on failure. */
static struct stat *
get_outstatus (void)
{
static int outstat_errno;
static struct stat outstat;
if (outstat_errno == 0)
outstat_errno = fstat (STDOUT_FILENO, &outstat) == 0 ? -1 : errno;
return outstat_errno < 0 ? &outstat : NULL;
}
/* Return a stream for FILE, opened with mode HOW. If HOW is "w",
the file is already open on standard output, and needs to be
truncated unless FILE is null. When opening for input, "-"
means standard input. To avoid confusion, do not return file
descriptors STDIN_FILENO, STDOUT_FILENO, or STDERR_FILENO when
opening an ordinary FILE. Return NULL if unsuccessful.
Use fadvise to specify an access pattern for input files.
There are a few hints we could possibly provide,
and after careful testing it was decided that
specifying FADVISE_SEQUENTIAL was not detrimental
to any cases. On Linux 2.6.31, this option doubles
the size of read ahead performed and thus was seen to
benefit these cases:
Merging
Sorting with a smaller internal buffer
Reading from faster flash devices
In _addition_ one could also specify other hints...
FADVISE_WILLNEED was tested, but Linux 2.6.31
at least uses that to _synchronously_ prepopulate the cache
with the specified range. While sort does need to
read all of its input before outputting, a synchronous
read of the whole file up front precludes any processing
that sort could do in parallel with the system doing
read ahead of the data. This was seen to have negative effects
in a couple of cases:
Merging
Sorting with a smaller internal buffer
This option was seen to shorten the runtime for sort
on a multicore system with lots of RAM and other processes
competing for CPU. It could be argued that more explicit
scheduling hints with 'nice' et. al. are more appropriate
for this situation.
FADVISE_NOREUSE is a possibility as it could lower
the priority of input data in the cache as sort will
only need to process it once. However its functionality
has changed over Linux kernel versions and as of 2.6.31
it does nothing and thus we can't depend on what it might
do in future.
FADVISE_DONTNEED is not appropriate for user specified
input files, but for temp files we do want to drop the
cache immediately after processing. This is done implicitly
however when the files are unlinked. */
static FILE *
stream_open (char const *file, char const *how)
{
FILE *fp;
if (*how == 'r')
{
if (STREQ (file, "-"))
{
have_read_stdin = true;
fp = stdin;
}
else
{
int fd = open (file, O_RDONLY | O_CLOEXEC);
fp = fd < 0 ? NULL : fdopen (fd, how);
}
fadvise (fp, FADVISE_SEQUENTIAL);
}
else if (*how == 'w')
{
if (file && ftruncate (STDOUT_FILENO, 0) != 0)
{
int ftruncate_errno = errno;
struct stat *outst = get_outstatus ();
if (!outst || S_ISREG (outst->st_mode) || S_TYPEISSHM (outst))
die (SORT_FAILURE, ftruncate_errno, _("%s: error truncating"),
quotef (file));
}
fp = stdout;
}
else
assert (!"unexpected mode passed to stream_open");
return fp;
}
/* Same as stream_open, except always return a non-null value; die on
failure. */
static FILE *
xfopen (char const *file, char const *how)
{
FILE *fp = stream_open (file, how);
if (!fp)
sort_die (_("open failed"), file);
return fp;
}
/* Close FP, whose name is FILE, and report any errors. */
static void
xfclose (FILE *fp, char const *file)
{
switch (fileno (fp))
{