-
Notifications
You must be signed in to change notification settings - Fork 0
/
zic.c
3961 lines (3671 loc) · 101 KB
/
zic.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
/* Compile .zi time zone data into TZif binary files. */
/*
** This file is in the public domain, so clarified as of
** 2006-07-17 by Arthur David Olson.
*/
/* Use the system 'time' function, instead of any private replacement.
This avoids creating an unnecessary dependency on localtime.c. */
#undef EPOCH_LOCAL
#undef EPOCH_OFFSET
#undef RESERVE_STD_EXT_IDS
#undef time_tz
#include "version.h"
#include "private.h"
#include "tzdir.h"
#include "tzfile.h"
#include <fcntl.h>
#include <locale.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
typedef int_fast64_t zic_t;
static zic_t const
ZIC_MIN = INT_FAST64_MIN,
ZIC_MAX = INT_FAST64_MAX,
ZIC32_MIN = -1 - (zic_t) 0x7fffffff,
ZIC32_MAX = 0x7fffffff;
#define SCNdZIC SCNdFAST64
#ifndef ZIC_MAX_ABBR_LEN_WO_WARN
# define ZIC_MAX_ABBR_LEN_WO_WARN 6
#endif /* !defined ZIC_MAX_ABBR_LEN_WO_WARN */
/* Minimum and maximum years, assuming signed 32-bit time_t. */
enum { YEAR_32BIT_MIN = 1901, YEAR_32BIT_MAX = 2038 };
/* An upper bound on how much a format might grow due to concatenation. */
enum { FORMAT_LEN_GROWTH_BOUND = 5 };
#ifdef HAVE_DIRECT_H
# include <direct.h>
# include <io.h>
# undef mkdir
# define mkdir(name, mode) _mkdir(name)
#endif
#ifndef HAVE_GETRANDOM
# ifdef __has_include
# if __has_include(<sys/random.h>)
# include <sys/random.h>
# endif
# elif 2 < __GLIBC__ + (25 <= __GLIBC_MINOR__)
# include <sys/random.h>
# endif
# define HAVE_GETRANDOM GRND_RANDOM
#elif HAVE_GETRANDOM
# include <sys/random.h>
#endif
#if HAVE_SYS_STAT_H
# include <sys/stat.h>
#endif
#ifdef S_IRUSR
# define MKDIR_UMASK (S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH)
#else
# define MKDIR_UMASK 0755
#endif
/* The minimum alignment of a type, for pre-C23 platforms.
The __SUNPRO_C test is because Oracle Developer Studio 12.6 lacks
<stdalign.h> even though __STDC_VERSION__ == 201112. */
#if __STDC_VERSION__ < 201112 || defined __SUNPRO_C
# define alignof(type) offsetof(struct { char a; type b; }, b)
#elif __STDC_VERSION__ < 202311
# include <stdalign.h>
#endif
/* The maximum length of a text line, including the trailing newline. */
#ifndef _POSIX2_LINE_MAX
# define _POSIX2_LINE_MAX 2048
#endif
/* The type for line numbers. Use PRIdMAX to format them; formerly
there was also "#define PRIdLINENO PRIdMAX" and formats used
PRIdLINENO, but xgettext cannot grok that. */
typedef intmax_t lineno;
struct rule {
int r_filenum;
lineno r_linenum;
const char * r_name;
zic_t r_loyear; /* for example, 1986 */
zic_t r_hiyear; /* for example, 1986 */
bool r_hiwasnum;
int r_month; /* 0..11 */
int r_dycode; /* see below */
int r_dayofmonth;
int r_wday;
zic_t r_tod; /* time from midnight */
bool r_todisstd; /* is r_tod standard time? */
bool r_todisut; /* is r_tod UT? */
bool r_isdst; /* is this daylight saving time? */
zic_t r_save; /* offset from standard time */
const char * r_abbrvar; /* variable part of abbreviation */
bool r_todo; /* a rule to do (used in outzone) */
zic_t r_temp; /* used in outzone */
};
/*
** r_dycode r_dayofmonth r_wday
*/
enum {
DC_DOM, /* 1..31 */ /* unused */
DC_DOWGEQ, /* 1..31 */ /* 0..6 (Sun..Sat) */
DC_DOWLEQ /* 1..31 */ /* 0..6 (Sun..Sat) */
};
struct zone {
int z_filenum;
lineno z_linenum;
const char * z_name;
zic_t z_stdoff;
char * z_rule;
const char * z_format;
char z_format_specifier;
bool z_isdst;
zic_t z_save;
struct rule * z_rules;
ptrdiff_t z_nrules;
struct rule z_untilrule;
zic_t z_untiltime;
};
#if !HAVE_POSIX_DECLS
extern int getopt(int argc, char * const argv[],
const char * options);
extern int link(const char * target, const char * linkname);
extern char * optarg;
extern int optind;
#endif
#if ! HAVE_SYMLINK
static ssize_t
readlink(char const *restrict file, char *restrict buf, size_t size)
{
errno = ENOTSUP;
return -1;
}
static int
symlink(char const *target, char const *linkname)
{
errno = ENOTSUP;
return -1;
}
#endif
#ifndef AT_SYMLINK_FOLLOW
# define linkat(targetdir, target, linknamedir, linkname, flag) \
(errno = ENOTSUP, -1)
#endif
static void addtt(zic_t starttime, int type);
static int addtype(zic_t, char const *, bool, bool, bool);
static void leapadd(zic_t, int, int);
static void adjleap(void);
static void associate(void);
static void dolink(const char *, const char *, bool);
static int getfields(char *, char **, int);
static zic_t gethms(const char * string, const char * errstring);
static zic_t getsave(char *, bool *);
static void inexpires(char **, int);
static void infile(int, char const *);
static void inleap(char ** fields, int nfields);
static void inlink(char ** fields, int nfields);
static void inrule(char ** fields, int nfields);
static bool inzcont(char ** fields, int nfields);
static bool inzone(char ** fields, int nfields);
static bool inzsub(char **, int, bool);
static int itssymlink(char const *, int *);
static bool is_alpha(char a);
static char lowerit(char);
static void mkdirs(char const *, bool);
static void newabbr(const char * abbr);
static zic_t oadd(zic_t t1, zic_t t2);
static void outzone(const struct zone * zp, ptrdiff_t ntzones);
static zic_t rpytime(const struct rule * rp, zic_t wantedy);
static bool rulesub(struct rule * rp,
const char * loyearp, const char * hiyearp,
const char * typep, const char * monthp,
const char * dayp, const char * timep);
static zic_t tadd(zic_t t1, zic_t t2);
/* Bound on length of what %z can expand to. */
enum { PERCENT_Z_LEN_BOUND = sizeof "+995959" - 1 };
static int charcnt;
static bool errors;
static bool warnings;
static int filenum;
static int leapcnt;
static bool leapseen;
static zic_t leapminyear;
static zic_t leapmaxyear;
static lineno linenum;
static int max_abbrvar_len = PERCENT_Z_LEN_BOUND;
static int max_format_len;
static zic_t max_year;
static zic_t min_year;
static bool noise;
static int rfilenum;
static lineno rlinenum;
static const char * progname;
static char const * leapsec;
static char *const * main_argv;
static ptrdiff_t timecnt;
static ptrdiff_t timecnt_alloc;
static int typecnt;
static int unspecifiedtype;
/*
** Line codes.
*/
enum {
LC_RULE,
LC_ZONE,
LC_LINK,
LC_LEAP,
LC_EXPIRES
};
/*
** Which fields are which on a Zone line.
*/
enum {
ZF_NAME = 1,
ZF_STDOFF,
ZF_RULE,
ZF_FORMAT,
ZF_TILYEAR,
ZF_TILMONTH,
ZF_TILDAY,
ZF_TILTIME,
ZONE_MAXFIELDS,
ZONE_MINFIELDS = ZF_TILYEAR
};
/*
** Which fields are which on a Zone continuation line.
*/
enum {
ZFC_STDOFF,
ZFC_RULE,
ZFC_FORMAT,
ZFC_TILYEAR,
ZFC_TILMONTH,
ZFC_TILDAY,
ZFC_TILTIME,
ZONEC_MAXFIELDS,
ZONEC_MINFIELDS = ZFC_TILYEAR
};
/*
** Which files are which on a Rule line.
*/
enum {
RF_NAME = 1,
RF_LOYEAR,
RF_HIYEAR,
RF_COMMAND,
RF_MONTH,
RF_DAY,
RF_TOD,
RF_SAVE,
RF_ABBRVAR,
RULE_FIELDS
};
/*
** Which fields are which on a Link line.
*/
enum {
LF_TARGET = 1,
LF_LINKNAME,
LINK_FIELDS
};
/*
** Which fields are which on a Leap line.
*/
enum {
LP_YEAR = 1,
LP_MONTH,
LP_DAY,
LP_TIME,
LP_CORR,
LP_ROLL,
LEAP_FIELDS,
/* Expires lines are like Leap lines, except without CORR and ROLL fields. */
EXPIRES_FIELDS = LP_TIME + 1
};
/* The maximum number of fields on any of the above lines.
(The "+"s pacify gcc -Wenum-compare.) */
enum {
MAX_FIELDS = max(max(+RULE_FIELDS, +LINK_FIELDS),
max(+LEAP_FIELDS, +EXPIRES_FIELDS))
};
/*
** Year synonyms.
*/
enum {
YR_MINIMUM, /* "minimum" is for backward compatibility only */
YR_MAXIMUM,
YR_ONLY
};
static struct rule * rules;
static ptrdiff_t nrules; /* number of rules */
static ptrdiff_t nrules_alloc;
static struct zone * zones;
static ptrdiff_t nzones; /* number of zones */
static ptrdiff_t nzones_alloc;
struct link {
int l_filenum;
lineno l_linenum;
const char * l_target;
const char * l_linkname;
};
static struct link * links;
static ptrdiff_t nlinks;
static ptrdiff_t nlinks_alloc;
struct lookup {
const char * l_word;
const int l_value;
};
static struct lookup const * byword(const char * string,
const struct lookup * lp);
static struct lookup const zi_line_codes[] = {
{ "Rule", LC_RULE },
{ "Zone", LC_ZONE },
{ "Link", LC_LINK },
{ NULL, 0 }
};
static struct lookup const leap_line_codes[] = {
{ "Leap", LC_LEAP },
{ "Expires", LC_EXPIRES },
{ NULL, 0}
};
static struct lookup const mon_names[] = {
{ "January", TM_JANUARY },
{ "February", TM_FEBRUARY },
{ "March", TM_MARCH },
{ "April", TM_APRIL },
{ "May", TM_MAY },
{ "June", TM_JUNE },
{ "July", TM_JULY },
{ "August", TM_AUGUST },
{ "September", TM_SEPTEMBER },
{ "October", TM_OCTOBER },
{ "November", TM_NOVEMBER },
{ "December", TM_DECEMBER },
{ NULL, 0 }
};
static struct lookup const wday_names[] = {
{ "Sunday", TM_SUNDAY },
{ "Monday", TM_MONDAY },
{ "Tuesday", TM_TUESDAY },
{ "Wednesday", TM_WEDNESDAY },
{ "Thursday", TM_THURSDAY },
{ "Friday", TM_FRIDAY },
{ "Saturday", TM_SATURDAY },
{ NULL, 0 }
};
static struct lookup const lasts[] = {
{ "last-Sunday", TM_SUNDAY },
{ "last-Monday", TM_MONDAY },
{ "last-Tuesday", TM_TUESDAY },
{ "last-Wednesday", TM_WEDNESDAY },
{ "last-Thursday", TM_THURSDAY },
{ "last-Friday", TM_FRIDAY },
{ "last-Saturday", TM_SATURDAY },
{ NULL, 0 }
};
static struct lookup const begin_years[] = {
{ "minimum", YR_MINIMUM },
{ NULL, 0 }
};
static struct lookup const end_years[] = {
{ "maximum", YR_MAXIMUM },
{ "only", YR_ONLY },
{ NULL, 0 }
};
static struct lookup const leap_types[] = {
{ "Rolling", true },
{ "Stationary", false },
{ NULL, 0 }
};
static const int len_months[2][MONSPERYEAR] = {
{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
{ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
};
static const int len_years[2] = {
DAYSPERNYEAR, DAYSPERLYEAR
};
static struct attype {
zic_t at;
bool dontmerge;
unsigned char type;
} * attypes;
static zic_t utoffs[TZ_MAX_TYPES];
static char isdsts[TZ_MAX_TYPES];
static unsigned char desigidx[TZ_MAX_TYPES];
static bool ttisstds[TZ_MAX_TYPES];
static bool ttisuts[TZ_MAX_TYPES];
static char chars[TZ_MAX_CHARS];
static zic_t trans[TZ_MAX_LEAPS];
static zic_t corr[TZ_MAX_LEAPS];
static char roll[TZ_MAX_LEAPS];
/*
** Memory allocation.
*/
ATTRIBUTE_NORETURN static void
memory_exhausted(const char *msg)
{
fprintf(stderr, _("%s: Memory exhausted: %s\n"), progname, msg);
exit(EXIT_FAILURE);
}
ATTRIBUTE_NORETURN static void
size_overflow(void)
{
memory_exhausted(_("size overflow"));
}
ATTRIBUTE_PURE_114833 static ptrdiff_t
size_sum(size_t a, size_t b)
{
#ifdef ckd_add
ptrdiff_t sum;
if (!ckd_add(&sum, a, b) && sum <= INDEX_MAX)
return sum;
#else
if (a <= INDEX_MAX && b <= INDEX_MAX - a)
return a + b;
#endif
size_overflow();
}
ATTRIBUTE_PURE_114833 static ptrdiff_t
size_product(ptrdiff_t nitems, ptrdiff_t itemsize)
{
#ifdef ckd_mul
ptrdiff_t product;
if (!ckd_mul(&product, nitems, itemsize) && product <= INDEX_MAX)
return product;
#else
ptrdiff_t nitems_max = INDEX_MAX / itemsize;
if (nitems <= nitems_max)
return nitems * itemsize;
#endif
size_overflow();
}
ATTRIBUTE_PURE_114833 static ptrdiff_t
align_to(ptrdiff_t size, ptrdiff_t alignment)
{
ptrdiff_t lo_bits = alignment - 1, sum = size_sum(size, lo_bits);
return sum & ~lo_bits;
}
#if !HAVE_STRDUP
static char *
strdup(char const *str)
{
char *result = malloc(strlen(str) + 1);
return result ? strcpy(result, str) : result;
}
#endif
static void *
memcheck(void *ptr)
{
if (ptr == NULL)
memory_exhausted(strerror(HAVE_MALLOC_ERRNO ? errno : ENOMEM));
return ptr;
}
static void *
emalloc(size_t size)
{
return memcheck(malloc(size));
}
static void *
erealloc(void *ptr, size_t size)
{
return memcheck(realloc(ptr, size));
}
static char *
estrdup(char const *str)
{
return memcheck(strdup(str));
}
static ptrdiff_t
grow_nitems_alloc(ptrdiff_t *nitems_alloc, ptrdiff_t itemsize)
{
ptrdiff_t addend = (*nitems_alloc >> 1) + 1;
#if defined ckd_add && defined ckd_mul
ptrdiff_t product;
if (!ckd_add(nitems_alloc, *nitems_alloc, addend)
&& !ckd_mul(&product, *nitems_alloc, itemsize) && product <= INDEX_MAX)
return product;
#else
if (*nitems_alloc <= ((INDEX_MAX - 1) / 3 * 2) / itemsize) {
*nitems_alloc += addend;
return *nitems_alloc * itemsize;
}
#endif
memory_exhausted(_("integer overflow"));
}
static void *
growalloc(void *ptr, ptrdiff_t itemsize, ptrdiff_t nitems,
ptrdiff_t *nitems_alloc)
{
return (nitems < *nitems_alloc
? ptr
: erealloc(ptr, grow_nitems_alloc(nitems_alloc, itemsize)));
}
/*
** Error handling.
*/
/* In most of the code, an input file name is represented by its index
into the main argument vector, except that LEAPSEC_FILENUM stands
for leapsec and COMMAND_LINE_FILENUM stands for the command line. */
enum { LEAPSEC_FILENUM = -2, COMMAND_LINE_FILENUM = -1 };
/* Return the name of the Ith input file, for diagnostics. */
static char const *
filename(int i)
{
if (i == COMMAND_LINE_FILENUM)
return _("command line");
else {
char const *fname = i == LEAPSEC_FILENUM ? leapsec : main_argv[i];
return strcmp(fname, "-") == 0 ? _("standard input") : fname;
}
}
static void
eats(int fnum, lineno num, int rfnum, lineno rnum)
{
filenum = fnum;
linenum = num;
rfilenum = rfnum;
rlinenum = rnum;
}
static void
eat(int fnum, lineno num)
{
eats(fnum, num, 0, -1);
}
ATTRIBUTE_FORMAT((printf, 1, 0)) static void
verror(const char *const string, va_list args)
{
/*
** Match the format of "cc" to allow sh users to
** zic ... 2>&1 | error -t "*" -v
** on BSD systems.
*/
if (filenum)
fprintf(stderr, _("\"%s\", line %"PRIdMAX": "),
filename(filenum), linenum);
vfprintf(stderr, string, args);
if (rfilenum)
fprintf(stderr, _(" (rule from \"%s\", line %"PRIdMAX")"),
filename(rfilenum), rlinenum);
fprintf(stderr, "\n");
}
ATTRIBUTE_FORMAT((printf, 1, 2)) static void
error(const char *const string, ...)
{
va_list args;
va_start(args, string);
verror(string, args);
va_end(args);
errors = true;
}
ATTRIBUTE_FORMAT((printf, 1, 2)) static void
warning(const char *const string, ...)
{
va_list args;
fprintf(stderr, _("warning: "));
va_start(args, string);
verror(string, args);
va_end(args);
warnings = true;
}
/* Close STREAM. If it had an I/O error, report it against DIR/NAME,
remove TEMPNAME if nonnull, and then exit. */
static void
close_file(FILE *stream, char const *dir, char const *name,
char const *tempname)
{
char const *e = (ferror(stream) ? _("I/O error")
: fclose(stream) != 0 ? strerror(errno) : NULL);
if (e) {
fprintf(stderr, "%s: %s%s%s%s%s\n", progname,
dir ? dir : "", dir ? "/" : "",
name ? name : "", name ? ": " : "",
e);
if (tempname)
remove(tempname);
exit(EXIT_FAILURE);
}
}
ATTRIBUTE_NORETURN static void
usage(FILE *stream, int status)
{
fprintf(stream,
_("%s: usage is %s [ --version ] [ --help ] [ -v ] \\\n"
"\t[ -b {slim|fat} ] [ -d directory ] [ -l localtime ]"
" [ -L leapseconds ] \\\n"
"\t[ -p posixrules ] [ -r '[@lo][/@hi]' ] [ -R '@hi' ] \\\n"
"\t[ -t localtime-link ] \\\n"
"\t[ filename ... ]\n\n"
"Report bugs to %s.\n"),
progname, progname, REPORT_BUGS_TO);
if (status == EXIT_SUCCESS)
close_file(stream, NULL, NULL, NULL);
exit(status);
}
/* Change the working directory to DIR, possibly creating DIR and its
ancestors. After this is done, all files are accessed with names
relative to DIR. */
static void
change_directory(char const *dir)
{
if (chdir(dir) != 0) {
int chdir_errno = errno;
if (chdir_errno == ENOENT) {
mkdirs(dir, false);
chdir_errno = chdir(dir) == 0 ? 0 : errno;
}
if (chdir_errno != 0) {
fprintf(stderr, _("%s: Can't chdir to %s: %s\n"),
progname, dir, strerror(chdir_errno));
exit(EXIT_FAILURE);
}
}
}
/* Compare the two links A and B, for a stable sort by link name. */
static int
qsort_linkcmp(void const *a, void const *b)
{
struct link const *l = a;
struct link const *m = b;
int cmp = strcmp(l->l_linkname, m->l_linkname);
if (cmp)
return cmp;
/* The link names are the same. Make the sort stable by comparing
file numbers (where subtraction cannot overflow) and possibly
line numbers (where it can). */
cmp = l->l_filenum - m->l_filenum;
if (cmp)
return cmp;
return (l->l_linenum > m->l_linenum) - (l->l_linenum < m->l_linenum);
}
/* Compare the string KEY to the link B, for bsearch. */
static int
bsearch_linkcmp(void const *key, void const *b)
{
struct link const *m = b;
return strcmp(key, m->l_linkname);
}
/* Make the links specified by the Link lines. */
static void
make_links(void)
{
ptrdiff_t i, j, nalinks, pass_size;
if (1 < nlinks)
qsort(links, nlinks, sizeof *links, qsort_linkcmp);
/* Ignore each link superseded by a later link with the same name. */
j = 0;
for (i = 0; i < nlinks; i++) {
while (i + 1 < nlinks
&& strcmp(links[i].l_linkname, links[i + 1].l_linkname) == 0)
i++;
links[j++] = links[i];
}
nlinks = pass_size = j;
/* Walk through the link array making links. However,
if a link's target has not been made yet, append a copy to the
end of the array. The end of the array will gradually fill
up with a small sorted subsequence of not-yet-made links.
nalinks counts all the links in the array, including copies.
When we reach the copied subsequence, it may still contain
a link to a not-yet-made link, so the process repeats.
At any given point in time, the link array consists of the
following subregions, where 0 <= i <= j <= nalinks and
0 <= nlinks <= nalinks:
0 .. (i - 1):
links that either have been made, or have been copied to a
later point point in the array (this later point can be in
any of the three subregions)
i .. (j - 1):
not-yet-made links for this pass
j .. (nalinks - 1):
not-yet-made links that this pass has skipped because
they were links to not-yet-made links
The first subregion might not be sorted if nlinks < i;
the other two subregions are sorted. This algorithm does
not alter entries 0 .. (nlinks - 1), which remain sorted.
If there are L links, this algorithm is O(C*L*log(L)) where
C is the length of the longest link chain. Usually C is
short (e.g., 3) though its worst-case value is L. */
j = nalinks = nlinks;
for (i = 0; i < nalinks; i++) {
struct link *l;
eat(links[i].l_filenum, links[i].l_linenum);
/* If this pass examined all its links, start the next pass. */
if (i == j) {
if (nalinks - i == pass_size) {
error(_("\"Link %s %s\" is part of a link cycle"),
links[i].l_target, links[i].l_linkname);
break;
}
j = nalinks;
pass_size = nalinks - i;
}
/* Diagnose self links, which the cycle detection algorithm would not
otherwise catch. */
if (strcmp(links[i].l_target, links[i].l_linkname) == 0) {
error(_("link %s targets itself"), links[i].l_target);
continue;
}
/* Make this link unless its target has not been made yet. */
l = bsearch(links[i].l_target, &links[i + 1], j - (i + 1),
sizeof *links, bsearch_linkcmp);
if (!l)
l = bsearch(links[i].l_target, &links[j], nalinks - j,
sizeof *links, bsearch_linkcmp);
if (!l)
dolink(links[i].l_target, links[i].l_linkname, false);
else {
/* The link target has not been made yet; copy the link to the end. */
links = growalloc(links, sizeof *links, nalinks, &nlinks_alloc);
links[nalinks++] = links[i];
}
if (noise && i < nlinks) {
if (l)
warning(_("link %s targeting link %s mishandled by pre-2023 zic"),
links[i].l_linkname, links[i].l_target);
else if (bsearch(links[i].l_target, links, nlinks, sizeof *links,
bsearch_linkcmp))
warning(_("link %s targeting link %s"),
links[i].l_linkname, links[i].l_target);
}
}
}
/* Simple signal handling: just set a flag that is checked
periodically outside critical sections. To set up the handler,
prefer sigaction if available to close a signal race. */
static sig_atomic_t got_signal;
static void
signal_handler(int sig)
{
#ifndef SA_SIGINFO
signal(sig, signal_handler);
#endif
got_signal = sig;
}
/* Arrange for SIGINT etc. to be caught by the handler. */
static void
catch_signals(void)
{
static int const signals[] = {
#ifdef SIGHUP
SIGHUP,
#endif
SIGINT,
#ifdef SIGPIPE
SIGPIPE,
#endif
SIGTERM
};
int i;
for (i = 0; i < sizeof signals / sizeof signals[0]; i++) {
#ifdef SA_SIGINFO
struct sigaction act0, act;
act.sa_handler = signal_handler;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
if (sigaction(signals[i], &act, &act0) == 0
&& ! (act0.sa_flags & SA_SIGINFO) && act0.sa_handler == SIG_IGN) {
sigaction(signals[i], &act0, NULL);
got_signal = 0;
}
#else
if (signal(signals[i], signal_handler) == SIG_IGN) {
signal(signals[i], SIG_IGN);
got_signal = 0;
}
#endif
}
}
/* If a signal has arrived, terminate zic with appropriate status. */
static void
check_for_signal(void)
{
int sig = got_signal;
if (sig) {
signal(sig, SIG_DFL);
raise(sig);
abort(); /* A bug in 'raise'. */
}
}
enum { TIME_T_BITS_IN_FILE = 64 };
/* The minimum and maximum values representable in a TZif file. */
static zic_t const min_time = MINVAL(zic_t, TIME_T_BITS_IN_FILE);
static zic_t const max_time = MAXVAL(zic_t, TIME_T_BITS_IN_FILE);
/* The minimum, and one less than the maximum, values specified by
the -r option. These default to MIN_TIME and MAX_TIME. */
static zic_t lo_time = MINVAL(zic_t, TIME_T_BITS_IN_FILE);
static zic_t hi_time = MAXVAL(zic_t, TIME_T_BITS_IN_FILE);
/* The time specified by the -R option, defaulting to MIN_TIME;
or lo_time, whichever is greater. */
static zic_t redundant_time = MINVAL(zic_t, TIME_T_BITS_IN_FILE);
/* The time specified by an Expires line, or negative if no such line. */
static zic_t leapexpires = -1;
/* Set the time range of the output to TIMERANGE.
Return true if successful. */
static bool
timerange_option(char *timerange)
{
intmax_t lo = min_time, hi = max_time;
char *lo_end = timerange, *hi_end;
if (*timerange == '@') {
errno = 0;
lo = strtoimax(timerange + 1, &lo_end, 10);
if (lo_end == timerange + 1 || (lo == INTMAX_MAX && errno == ERANGE))
return false;
}
hi_end = lo_end;
if (lo_end[0] == '/' && lo_end[1] == '@') {
errno = 0;
hi = strtoimax(lo_end + 2, &hi_end, 10);
if (hi_end == lo_end + 2 || hi == INTMAX_MIN)
return false;
hi -= ! (hi == INTMAX_MAX && errno == ERANGE);
}
if (*hi_end || hi < lo || max_time < lo || hi < min_time)
return false;
lo_time = max(lo, min_time);
hi_time = min(hi, max_time);
return true;
}
/* Generate redundant time stamps up to OPT. Return true if successful. */
static bool
redundant_time_option(char *opt)
{
if (*opt == '@') {
intmax_t redundant;
char *opt_end;
redundant = strtoimax(opt + 1, &opt_end, 10);
if (opt_end != opt + 1 && !*opt_end) {
redundant_time = max(redundant_time, redundant);
return true;
}
}
return false;
}
static const char * psxrules;
static const char * lcltime;
static const char * directory;
static const char * tzdefault;
/* -1 if the TZif output file should be slim, 0 if default, 1 if the
output should be fat for backward compatibility. ZIC_BLOAT_DEFAULT
determines the default. */
static int bloat;
static bool
want_bloat(void)
{
return 0 <= bloat;
}
#ifndef ZIC_BLOAT_DEFAULT
# define ZIC_BLOAT_DEFAULT "slim"
#endif
int
main(int argc, char **argv)
{
register int c, k;
register ptrdiff_t i, j;
bool timerange_given = false;
#ifdef S_IWGRP
umask(umask(S_IWGRP | S_IWOTH) | (S_IWGRP | S_IWOTH));
#endif
#if HAVE_GETTEXT
setlocale(LC_ALL, "");
# ifdef TZ_DOMAINDIR
bindtextdomain(TZ_DOMAIN, TZ_DOMAINDIR);
# endif /* defined TEXTDOMAINDIR */
textdomain(TZ_DOMAIN);
#endif /* HAVE_GETTEXT */
main_argv = argv;
progname = argv[0] ? argv[0] : "zic";
if (TYPE_BIT(zic_t) < 64) {
fprintf(stderr, "%s: %s\n", progname,
_("wild compilation-time specification of zic_t"));
return EXIT_FAILURE;
}
for (k = 1; k < argc; k++)
if (strcmp(argv[k], "--version") == 0) {
printf("zic %s%s\n", PKGVERSION, TZVERSION);
close_file(stdout, NULL, NULL, NULL);
return EXIT_SUCCESS;
} else if (strcmp(argv[k], "--help") == 0) {