summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
Diffstat (limited to 'lib')
-rw-r--r--lib/ChangeLog-2007 (renamed from lib/ChangeLog)10
-rw-r--r--lib/Makefile.am38
-rw-r--r--lib/Makefile.in1636
-rw-r--r--lib/TODO40
-rw-r--r--lib/__fpending.h34
-rw-r--r--lib/acl-errno-valid.c52
-rw-r--r--lib/acl-internal.c507
-rw-r--r--lib/acl-internal.h302
-rw-r--r--lib/acl.c256
-rw-r--r--lib/acl.h30
-rw-r--r--lib/acl_entries.c68
-rw-r--r--lib/alignof.h50
-rw-r--r--lib/alloca.c173
-rw-r--r--lib/alloca.in.h (renamed from lib/alloca_.h)27
-rw-r--r--lib/allocator.c5
-rw-r--r--lib/allocator.h58
-rw-r--r--lib/allocsa.c137
-rw-r--r--lib/anytostr.c57
-rw-r--r--lib/areadlink-with-size.c (renamed from lib/xreadlink-with-size.c)79
-rw-r--r--lib/areadlink.c56
-rw-r--r--lib/areadlink.h33
-rw-r--r--lib/areadlinkat.c65
-rw-r--r--lib/argmatch.c101
-rw-r--r--lib/argmatch.h58
-rw-r--r--lib/argv-iter.c111
-rw-r--r--lib/argv-iter.h42
-rw-r--r--lib/arpa_inet.in.h140
-rw-r--r--lib/asnprintf.c7
-rw-r--r--lib/asprintf.c14
-rw-r--r--lib/assure.h37
-rw-r--r--lib/at-func.c130
-rw-r--r--lib/at-func2.c282
-rw-r--r--lib/atexit.c13
-rw-r--r--lib/backupfile.c95
-rw-r--r--lib/backupfile.h16
-rw-r--r--lib/base32.c587
-rw-r--r--lib/base32.h60
-rw-r--r--lib/base64.c422
-rw-r--r--lib/base64.h40
-rw-r--r--lib/basename-lgpl.c75
-rw-r--r--lib/basename.c87
-rw-r--r--lib/bitrotate.c3
-rw-r--r--lib/bitrotate.h136
-rw-r--r--lib/btowc.c39
-rw-r--r--lib/buffer-lcm.c44
-rw-r--r--lib/buffer-lcm.h2
-rw-r--r--lib/c-ctype.c395
-rw-r--r--lib/c-ctype.h464
-rw-r--r--lib/c-strcase.h13
-rw-r--r--lib/c-strcasecmp.c9
-rw-r--r--lib/c-strcaseeq.h181
-rw-r--r--lib/c-strncasecmp.c9
-rw-r--r--lib/c-strtod.c59
-rw-r--r--lib/c-strtod.h39
-rw-r--r--lib/calloc.c63
-rw-r--r--lib/canon-host.c30
-rw-r--r--lib/canon-host.h21
-rw-r--r--lib/canonicalize.c471
-rw-r--r--lib/canonicalize.h44
-rw-r--r--lib/careadlinkat.c160
-rw-r--r--lib/careadlinkat.h67
-rw-r--r--lib/chdir-long.c132
-rw-r--r--lib/chdir-long.h17
-rw-r--r--lib/chmodat.c3
-rw-r--r--lib/chown.c145
-rw-r--r--lib/chownat.c3
-rw-r--r--lib/cloexec.c60
-rw-r--r--lib/cloexec.h36
-rw-r--r--lib/close-stream.c28
-rw-r--r--lib/close.c69
-rw-r--r--lib/closedir.c71
-rw-r--r--lib/closein.c112
-rw-r--r--lib/closein.h32
-rw-r--r--lib/closeout.c62
-rw-r--r--lib/closeout.h15
-rw-r--r--[-rwxr-xr-x]lib/config.charset1137
-rw-r--r--lib/config.hin2202
-rw-r--r--lib/copy-acl.c61
-rw-r--r--lib/creat-safer.c11
-rw-r--r--lib/ctype.in.h57
-rw-r--r--lib/cycle-check.c36
-rw-r--r--lib/cycle-check.h34
-rw-r--r--lib/di-set.c259
-rw-r--r--lib/di-set.h19
-rw-r--r--lib/diacrit.c26
-rw-r--r--lib/diacrit.h14
-rw-r--r--lib/dirchownmod.c131
-rw-r--r--lib/dirent--.h24
-rw-r--r--lib/dirent-private.h40
-rw-r--r--lib/dirent-safer.h22
-rw-r--r--lib/dirent.in.h267
-rw-r--r--lib/dirent_.h42
-rw-r--r--lib/dirfd.c87
-rw-r--r--lib/dirfd.h29
-rw-r--r--lib/dirname-lgpl.c86
-rw-r--r--lib/dirname.c73
-rw-r--r--lib/dirname.h58
-rw-r--r--lib/dosname.h53
-rw-r--r--lib/dtoastr.c2
-rw-r--r--lib/dtotimespec.c59
-rw-r--r--lib/dup-safer-flag.c38
-rw-r--r--lib/dup-safer.c21
-rw-r--r--lib/dup.c86
-rw-r--r--lib/dup2.c187
-rw-r--r--lib/errno.in.h279
-rw-r--r--lib/error.c226
-rw-r--r--lib/error.h59
-rw-r--r--lib/euidaccess-stat.c143
-rw-r--r--lib/euidaccess-stat.h5
-rw-r--r--lib/euidaccess.c70
-rw-r--r--lib/euidaccess.h3
-rw-r--r--lib/exclude.c606
-rw-r--r--lib/exclude.h40
-rw-r--r--lib/exitfail.c12
-rw-r--r--lib/exitfail.h12
-rw-r--r--lib/faccessat.c45
-rw-r--r--lib/fadvise.c43
-rw-r--r--lib/fadvise.h72
-rw-r--r--lib/fchdir.c325
-rw-r--r--lib/fchmodat.c31
-rw-r--r--lib/fchown-stub.c4
-rw-r--r--lib/fchownat.c108
-rw-r--r--lib/fclose.c110
-rw-r--r--lib/fcntl--.h16
-rw-r--r--lib/fcntl-safer.h15
-rw-r--r--lib/fcntl.c414
-rw-r--r--lib/fcntl.in.h363
-rw-r--r--lib/fcntl_.h116
-rw-r--r--lib/fd-hook.c116
-rw-r--r--lib/fd-hook.h119
-rw-r--r--lib/fd-reopen.c19
-rw-r--r--lib/fd-reopen.h11
-rw-r--r--lib/fd-safer-flag.c52
-rw-r--r--lib/fd-safer.c18
-rw-r--r--lib/fdatasync.c27
-rw-r--r--lib/fdopen.c69
-rw-r--r--lib/fdopendir.c249
-rw-r--r--lib/fdutimensat.c57
-rw-r--r--lib/fflush.c229
-rw-r--r--lib/file-has-acl.c514
-rw-r--r--lib/file-set.c74
-rw-r--r--lib/file-set.h15
-rw-r--r--lib/file-type.c75
-rw-r--r--lib/file-type.h13
-rw-r--r--lib/fileblocks.c23
-rw-r--r--lib/filemode.c79
-rw-r--r--lib/filemode.h31
-rw-r--r--lib/filename.h54
-rw-r--r--lib/filenamecat-lgpl.c88
-rw-r--r--lib/filenamecat.c109
-rw-r--r--lib/filenamecat.h19
-rw-r--r--lib/filevercmp.c181
-rw-r--r--lib/filevercmp.h42
-rw-r--r--lib/float+.h147
-rw-r--r--lib/float.c33
-rw-r--r--lib/float.in.h188
-rw-r--r--lib/fnmatch.c224
-rw-r--r--lib/fnmatch.in.h67
-rw-r--r--lib/fnmatch_.h65
-rw-r--r--lib/fnmatch_loop.c1899
-rw-r--r--lib/fopen-safer.c55
-rw-r--r--lib/fopen.c110
-rw-r--r--lib/fpending.c (renamed from lib/__fpending.c)16
-rw-r--r--lib/fpending.h29
-rw-r--r--lib/fprintftime.h17
-rw-r--r--lib/fpucw.h108
-rw-r--r--lib/fpurge.c147
-rw-r--r--lib/freadahead.c94
-rw-r--r--lib/freadahead.h47
-rw-r--r--lib/freading.c75
-rw-r--r--lib/freading.h53
-rw-r--r--lib/freadptr.c121
-rw-r--r--lib/freadptr.h48
-rw-r--r--lib/freadseek.c144
-rw-r--r--lib/freadseek.h42
-rw-r--r--lib/freopen-safer.c103
-rw-r--r--lib/freopen.c67
-rw-r--r--lib/frexp.c168
-rw-r--r--lib/frexpl.c35
-rw-r--r--lib/fseek.c30
-rw-r--r--lib/fseeko.c162
-rw-r--r--lib/fseterr.c80
-rw-r--r--lib/fseterr.h45
-rw-r--r--lib/fstat.c88
-rw-r--r--lib/fstatat.c132
-rw-r--r--lib/fsusage.c148
-rw-r--r--lib/fsusage.h25
-rw-r--r--lib/fsync.c83
-rw-r--r--lib/ftell.c37
-rw-r--r--lib/ftello.c85
-rw-r--r--lib/ftoastr.c137
-rw-r--r--lib/ftoastr.h145
-rw-r--r--lib/ftruncate.c212
-rw-r--r--lib/fts-cycle.c67
-rw-r--r--lib/fts.c2885
-rw-r--r--lib/fts_.h305
-rw-r--r--lib/full-read.c11
-rw-r--r--lib/full-read.h11
-rw-r--r--lib/full-write.c22
-rw-r--r--lib/full-write.h11
-rw-r--r--lib/futimens.c37
-rw-r--r--lib/gai_strerror.c36
-rw-r--r--lib/get-permissions.c291
-rw-r--r--lib/getaddrinfo.c225
-rw-r--r--lib/getaddrinfo.h155
-rw-r--r--lib/getcwd-lgpl.c126
-rw-r--r--lib/getcwd.c376
-rw-r--r--lib/getdate.c3359
-rw-r--r--lib/getdate.y1520
-rw-r--r--lib/getdelim.c111
-rw-r--r--lib/getdelim.h28
-rw-r--r--lib/getdtablesize.c121
-rw-r--r--lib/getfilecon.c87
-rw-r--r--lib/getgroups.c111
-rw-r--r--lib/gethostname.c68
-rw-r--r--lib/gethrxtime.c30
-rw-r--r--lib/gethrxtime.h41
-rw-r--r--lib/getline.c11
-rw-r--r--lib/getline.h28
-rw-r--r--lib/getloadavg.c482
-rw-r--r--lib/getlogin.c41
-rw-r--r--lib/getndelim2.c198
-rw-r--r--lib/getndelim2.h11
-rw-r--r--lib/getopt.c1450
-rw-r--r--lib/getopt.in.h (renamed from lib/getopt_.h)141
-rw-r--r--lib/getopt1.c153
-rw-r--r--lib/getopt_int.h124
-rw-r--r--lib/getpagesize.c39
-rw-r--r--lib/getpagesize.h68
-rw-r--r--lib/getpass.c148
-rw-r--r--lib/getpass.h9
-rw-r--r--lib/gettext.h64
-rw-r--r--lib/gettime.c11
-rw-r--r--lib/gettimeofday.c46
-rw-r--r--lib/getugroups.c146
-rw-r--r--lib/getugroups.h19
-rw-r--r--lib/getusershell.c44
-rw-r--r--lib/gl_openssl.h116
-rw-r--r--lib/glthread/lock.c1057
-rw-r--r--lib/glthread/lock.h927
-rw-r--r--lib/glthread/threadlib.c73
-rw-r--r--lib/glthread/tls.c61
-rw-r--r--lib/glthread/tls.h299
-rw-r--r--lib/gnulib.mk4852
-rw-r--r--lib/group-member.c90
-rw-r--r--lib/group-member.h26
-rw-r--r--lib/hard-locale.c57
-rw-r--r--lib/hard-locale.h11
-rw-r--r--lib/hash-pjw.c11
-rw-r--r--lib/hash-pjw.h14
-rw-r--r--lib/hash-triple.c77
-rw-r--r--lib/hash-triple.h24
-rw-r--r--lib/hash.c827
-rw-r--r--lib/hash.h79
-rw-r--r--lib/heap.c151
-rw-r--r--lib/heap.h26
-rw-r--r--lib/human.c354
-rw-r--r--lib/human.h18
-rw-r--r--lib/i-ring.c11
-rw-r--r--lib/i-ring.h13
-rw-r--r--lib/iconv.c449
-rw-r--r--lib/iconv.in.h110
-rw-r--r--lib/iconv_close.c46
-rw-r--r--lib/iconv_open-aix.gperf44
-rw-r--r--lib/iconv_open-aix.h256
-rw-r--r--lib/iconv_open-hpux.gperf56
-rw-r--r--lib/iconv_open-hpux.h299
-rw-r--r--lib/iconv_open-irix.gperf31
-rw-r--r--lib/iconv_open-irix.h199
-rw-r--r--lib/iconv_open-osf.gperf50
-rw-r--r--lib/iconv_open-osf.h278
-rw-r--r--lib/iconv_open-solaris.gperf30
-rw-r--r--lib/iconv_open-solaris.h190
-rw-r--r--lib/iconv_open.c172
-rw-r--r--lib/idcache.c54
-rw-r--r--lib/idcache.h11
-rw-r--r--lib/ignore-value.h50
-rw-r--r--lib/imaxtostr.c4
-rw-r--r--lib/inet_ntop.c150
-rw-r--r--lib/inet_ntop.h42
-rw-r--r--lib/ino-map.c164
-rw-r--r--lib/ino-map.h19
-rw-r--r--lib/intprops.h419
-rw-r--r--lib/inttostr.c54
-rw-r--r--lib/inttostr.h38
-rw-r--r--lib/inttypes.in.h1144
-rw-r--r--lib/inttypes_.h1095
-rw-r--r--lib/isapipe.c86
-rw-r--r--lib/isatty.c83
-rw-r--r--lib/isblank.c33
-rw-r--r--lib/isnan.c189
-rw-r--r--lib/isnand-nolibm.h33
-rw-r--r--lib/isnand.c19
-rw-r--r--lib/isnanf-nolibm.h40
-rw-r--r--lib/isnanf.c20
-rw-r--r--lib/isnanl-nolibm.h33
-rw-r--r--lib/isnanl.c20
-rw-r--r--lib/iswblank.c (renamed from lib/free.c)25
-rw-r--r--lib/itold.c28
-rw-r--r--lib/langinfo.in.h194
-rw-r--r--lib/lchmod.h35
-rw-r--r--lib/lchown.c88
-rw-r--r--lib/lchown.h42
-rw-r--r--lib/ldtoastr.c2
-rw-r--r--lib/linebuffer.c59
-rw-r--r--lib/linebuffer.h31
-rw-r--r--lib/link.c211
-rw-r--r--lib/linkat.c357
-rw-r--r--lib/local.mk5
-rw-r--r--lib/localcharset.c569
-rw-r--r--lib/localcharset.h7
-rw-r--r--lib/locale.in.h216
-rw-r--r--lib/localeconv.c103
-rw-r--r--lib/long-options.c59
-rw-r--r--lib/long-options.h24
-rw-r--r--lib/lseek.c67
-rw-r--r--lib/lstat.c95
-rw-r--r--lib/lstat.h24
-rw-r--r--lib/malloc.c35
-rw-r--r--lib/malloca.c149
-rw-r--r--lib/malloca.h (renamed from lib/allocsa.h)67
-rw-r--r--lib/malloca.valgrind (renamed from lib/allocsa.valgrind)6
-rw-r--r--lib/math.c4
-rw-r--r--lib/math.in.h2278
-rw-r--r--lib/mbchar.c21
-rw-r--r--lib/mbchar.h135
-rw-r--r--lib/mbiter.c3
-rw-r--r--lib/mbiter.h225
-rw-r--r--lib/mbrlen.c32
-rw-r--r--lib/mbrtowc.c407
-rw-r--r--lib/mbsalign.c278
-rw-r--r--lib/mbsalign.h59
-rw-r--r--lib/mbscasecmp.c65
-rw-r--r--lib/mbsinit.c61
-rw-r--r--lib/mbslen.c44
-rw-r--r--lib/mbsrtowcs-impl.h122
-rw-r--r--lib/mbsrtowcs-state.c37
-rw-r--r--lib/mbsrtowcs.c32
-rw-r--r--lib/mbsstr.c384
-rw-r--r--lib/mbswidth.c234
-rw-r--r--lib/mbswidth.h13
-rw-r--r--lib/mbtowc-impl.h44
-rw-r--r--lib/mbtowc.c26
-rw-r--r--lib/mbuiter.c3
-rw-r--r--lib/mbuiter.h132
-rw-r--r--lib/md5.c195
-rw-r--r--lib/md5.h59
-rw-r--r--lib/memcasecmp.c16
-rw-r--r--lib/memcasecmp.h13
-rw-r--r--lib/memchr.c221
-rw-r--r--lib/memchr.valgrind14
-rw-r--r--lib/memchr2.c169
-rw-r--r--lib/memchr2.h32
-rw-r--r--lib/memchr2.valgrind14
-rw-r--r--lib/memcmp.c363
-rw-r--r--lib/memcmp2.c36
-rw-r--r--lib/memcmp2.h40
-rw-r--r--lib/memcoll.c107
-rw-r--r--lib/memcoll.h12
-rw-r--r--lib/memcpy.c36
-rw-r--r--lib/memmove.c26
-rw-r--r--lib/mempcpy.c7
-rw-r--r--lib/memrchr.c219
-rw-r--r--lib/memset.c28
-rw-r--r--lib/memxfrm.c106
-rw-r--r--lib/memxfrm.h2
-rw-r--r--lib/mgetgroups.c201
-rw-r--r--lib/mgetgroups.h22
-rw-r--r--lib/mkancesdirs.c121
-rw-r--r--lib/mkancesdirs.h2
-rw-r--r--lib/mkdir-p.c226
-rw-r--r--lib/mkdir-p.h33
-rw-r--r--lib/mkdir.c60
-rw-r--r--lib/mkdirat.c43
-rw-r--r--lib/mkfifo.c58
-rw-r--r--lib/mknod.c74
-rw-r--r--lib/mkstemp-safer.c40
-rw-r--r--lib/mkstemp.c33
-rw-r--r--lib/mktime-internal.h4
-rw-r--r--lib/mktime.c242
-rw-r--r--lib/modechange.c400
-rw-r--r--lib/modechange.h15
-rw-r--r--lib/mountlist.c828
-rw-r--r--lib/mountlist.h28
-rw-r--r--lib/mpsort.c111
-rw-r--r--lib/msvc-inval.c129
-rw-r--r--lib/msvc-inval.h222
-rw-r--r--lib/msvc-nothrow.c49
-rw-r--r--lib/msvc-nothrow.h43
-rw-r--r--lib/nanosleep.c268
-rw-r--r--lib/netdb.in.h265
-rw-r--r--lib/netinet_in.in.h (renamed from lib/netinet_in_.h)30
-rw-r--r--lib/nl_langinfo.c322
-rw-r--r--lib/nproc.c357
-rw-r--r--lib/nproc.h46
-rw-r--r--lib/obstack.c408
-rw-r--r--lib/obstack.h844
-rw-r--r--lib/offtostr.c4
-rw-r--r--lib/open-safer.c20
-rw-r--r--lib/open.c181
-rw-r--r--lib/openat-die.c47
-rw-r--r--lib/openat-priv.h67
-rw-r--r--lib/openat-proc.c159
-rw-r--r--lib/openat-safer.c46
-rw-r--r--lib/openat.c326
-rw-r--r--lib/openat.h136
-rw-r--r--lib/opendir-safer.c76
-rw-r--r--lib/opendir.c169
-rw-r--r--lib/parse-datetime.c3350
-rw-r--r--lib/parse-datetime.h (renamed from lib/getdate.h)13
-rw-r--r--lib/parse-datetime.y1626
-rw-r--r--lib/pathmax.h58
-rw-r--r--lib/physmem.c118
-rw-r--r--lib/physmem.h11
-rw-r--r--lib/pipe-safer.c31
-rw-r--r--lib/pipe.c50
-rw-r--r--lib/posixtm.c244
-rw-r--r--lib/posixtm.h11
-rw-r--r--lib/posixver.c16
-rw-r--r--lib/printf-args.c206
-rw-r--r--lib/printf-args.h86
-rw-r--r--lib/printf-frexp.c190
-rw-r--r--lib/printf-frexp.h23
-rw-r--r--lib/printf-frexpl.c37
-rw-r--r--lib/printf-frexpl.h23
-rw-r--r--lib/printf-parse.c1018
-rw-r--r--lib/printf-parse.h149
-rw-r--r--lib/priv-set.c145
-rw-r--r--lib/priv-set.h64
-rw-r--r--lib/progname.c92
-rw-r--r--lib/progname.h62
-rw-r--r--lib/propername.c318
-rw-r--r--lib/propername.h106
-rw-r--r--lib/pthread.c4
-rw-r--r--lib/pthread.in.h295
-rw-r--r--lib/putenv.c150
-rw-r--r--lib/qcopy-acl.c51
-rw-r--r--lib/qset-acl.c49
-rw-r--r--lib/quote.c41
-rw-r--r--lib/quote.h42
-rw-r--r--lib/quotearg.c1008
-rw-r--r--lib/quotearg.h339
-rw-r--r--lib/raise.c68
-rw-r--r--lib/rand-isaac.c391
-rw-r--r--lib/rand-isaac.h61
-rw-r--r--lib/randint.c149
-rw-r--r--lib/randint.h14
-rw-r--r--lib/randperm.c178
-rw-r--r--lib/randperm.h2
-rw-r--r--lib/randread.c185
-rw-r--r--lib/randread.h11
-rw-r--r--lib/read-file.c188
-rw-r--r--lib/read-file.h33
-rw-r--r--lib/read.c85
-rw-r--r--lib/readdir.c98
-rw-r--r--lib/readlink.c58
-rw-r--r--lib/readlinkat.c79
-rw-r--r--lib/readtokens.c137
-rw-r--r--lib/readtokens.h18
-rw-r--r--lib/readtokens0.c39
-rw-r--r--lib/readtokens0.h11
-rw-r--r--lib/readutmp.c39
-rw-r--r--lib/readutmp.h23
-rw-r--r--lib/realloc.c54
-rw-r--r--lib/ref-add.sin7
-rw-r--r--lib/ref-del.sin7
-rw-r--r--lib/regcomp.c687
-rw-r--r--lib/regex.c36
-rw-r--r--lib/regex.h273
-rw-r--r--lib/regex_internal.c244
-rw-r--r--lib/regex_internal.h228
-rw-r--r--lib/regexec.c400
-rw-r--r--lib/remove.c43
-rw-r--r--lib/rename-dest-slash.c88
-rw-r--r--lib/rename.c470
-rw-r--r--lib/rewinddir.c49
-rw-r--r--lib/rmdir.c77
-rw-r--r--lib/root-dev-ino.c17
-rw-r--r--lib/root-dev-ino.h23
-rw-r--r--lib/root-uid.h30
-rw-r--r--lib/rpmatch.c151
-rw-r--r--lib/safe-read.c21
-rw-r--r--lib/safe-read.h24
-rw-r--r--lib/safe-write.c11
-rw-r--r--lib/safe-write.h24
-rw-r--r--lib/same-inode.h25
-rw-r--r--lib/same.c59
-rw-r--r--lib/same.h12
-rw-r--r--lib/save-cwd.c52
-rw-r--r--lib/save-cwd.h12
-rw-r--r--lib/savedir.c195
-rw-r--r--lib/savedir.h34
-rw-r--r--lib/savewd.c228
-rw-r--r--lib/savewd.h56
-rw-r--r--lib/sched.in.h64
-rw-r--r--lib/se-context.c3
-rw-r--r--lib/se-context.in.h46
-rw-r--r--lib/se-selinux.c3
-rw-r--r--lib/se-selinux.in.h123
-rw-r--r--lib/secure_getenv.c41
-rw-r--r--lib/select.c575
-rw-r--r--lib/selinux-at.c71
-rw-r--r--lib/selinux-at.h52
-rw-r--r--lib/set-acl.c48
-rw-r--r--lib/set-permissions.c846
-rw-r--r--lib/setenv.c296
-rw-r--r--lib/setenv.h54
-rw-r--r--lib/settime.c24
-rw-r--r--lib/sha1.c193
-rw-r--r--lib/sha1.h53
-rw-r--r--lib/sha256.c268
-rw-r--r--lib/sha256.h65
-rw-r--r--lib/sha512.c306
-rw-r--r--lib/sha512.h59
-rw-r--r--lib/sig-handler.c3
-rw-r--r--lib/sig-handler.h54
-rw-r--r--lib/sig2str.c87
-rw-r--r--lib/sig2str.h21
-rw-r--r--lib/sigaction.c204
-rw-r--r--lib/siglist.h132
-rw-r--r--lib/signal.in.h463
-rw-r--r--lib/signbitd.c64
-rw-r--r--lib/signbitf.c64
-rw-r--r--lib/signbitl.c64
-rw-r--r--lib/sigprocmask.c349
-rw-r--r--lib/size_max.h30
-rw-r--r--lib/smack.h46
-rw-r--r--lib/snprintf.c22
-rw-r--r--lib/socket_.h85
-rw-r--r--lib/sockets.c157
-rw-r--r--lib/sockets.h62
-rw-r--r--lib/stat-size.h107
-rw-r--r--lib/stat-time.c3
-rw-r--r--lib/stat-time.h105
-rw-r--r--lib/stat.c138
-rw-r--r--lib/stat_.h275
-rw-r--r--lib/statat.c3
-rw-r--r--lib/stdalign.in.h121
-rw-r--r--lib/stdarg.in.h35
-rw-r--r--lib/stdbool.in.h (renamed from lib/stdbool_.h)76
-rw-r--r--lib/stddef.in.h108
-rw-r--r--lib/stdint.in.h (renamed from lib/stdint_.h)404
-rw-r--r--lib/stdio--.h35
-rw-r--r--lib/stdio-impl.h113
-rw-r--r--lib/stdio-safer.h24
-rw-r--r--lib/stdio.in.h1357
-rw-r--r--lib/stdio_.h192
-rw-r--r--lib/stdlib--.h23
-rw-r--r--lib/stdlib-safer.h23
-rw-r--r--lib/stdlib.in.h977
-rw-r--r--lib/stdlib_.h141
-rw-r--r--lib/stpcpy.c10
-rw-r--r--lib/stpncpy.c92
-rw-r--r--lib/str-kmp.h153
-rw-r--r--lib/str-two-way.h452
-rw-r--r--lib/strcspn.c41
-rw-r--r--lib/strdup.c9
-rw-r--r--lib/streq.h176
-rw-r--r--lib/strerror-override.c302
-rw-r--r--lib/strerror-override.h56
-rw-r--r--lib/strerror.c70
-rw-r--r--lib/strftime.c1857
-rw-r--r--lib/strftime.h26
-rw-r--r--lib/striconv.c463
-rw-r--r--lib/striconv.h75
-rw-r--r--lib/string.in.h1046
-rw-r--r--lib/string_.h544
-rw-r--r--lib/strintcmp.c11
-rw-r--r--lib/stripslash.c14
-rw-r--r--lib/strncat.c33
-rw-r--r--lib/strndup.c9
-rw-r--r--lib/strnlen.c7
-rw-r--r--lib/strnlen1.c11
-rw-r--r--lib/strnlen1.h14
-rw-r--r--lib/strnumcmp-in.h162
-rw-r--r--lib/strnumcmp.c15
-rw-r--r--lib/strnumcmp.h2
-rw-r--r--lib/strpbrk.c11
-rw-r--r--lib/strsignal.c200
-rw-r--r--lib/strstr.c82
-rw-r--r--lib/strtod.c429
-rw-r--r--lib/strtoimax.c46
-rw-r--r--lib/strtol.c135
-rw-r--r--lib/strtoll.c18
-rw-r--r--lib/strtoul.c15
-rw-r--r--lib/strtoull.c11
-rw-r--r--lib/strverscmp.c131
-rw-r--r--lib/strverscmp.h24
-rw-r--r--lib/symlink.c57
-rw-r--r--lib/sys_ioctl.in.h78
-rw-r--r--lib/sys_resource.in.h111
-rw-r--r--lib/sys_select.in.h314
-rw-r--r--lib/sys_socket.c4
-rw-r--r--lib/sys_socket.in.h692
-rw-r--r--lib/sys_stat.in.h732
-rw-r--r--lib/sys_time.in.h213
-rw-r--r--lib/sys_time_.h44
-rw-r--r--lib/sys_types.in.h53
-rw-r--r--lib/sys_uio.in.h63
-rw-r--r--lib/sys_utsname.in.h108
-rw-r--r--lib/sys_wait.in.h129
-rw-r--r--lib/t-fpending.c42
-rw-r--r--lib/tempname.c298
-rw-r--r--lib/tempname.h70
-rw-r--r--lib/termios.in.h73
-rw-r--r--lib/time-internal.h49
-rw-r--r--lib/time.in.h297
-rw-r--r--lib/time_.h107
-rw-r--r--lib/time_r.c9
-rw-r--r--lib/time_rz.c323
-rw-r--r--lib/timegm.c38
-rw-r--r--lib/timespec.c3
-rw-r--r--lib/timespec.h95
-rw-r--r--lib/trim.c129
-rw-r--r--lib/trim.h33
-rw-r--r--lib/u64.c4
-rw-r--r--lib/u64.h53
-rw-r--r--lib/uinttostr.c4
-rw-r--r--lib/umaxtostr.c4
-rw-r--r--lib/uname.c268
-rw-r--r--lib/unicodeio.c126
-rw-r--r--lib/unicodeio.h27
-rw-r--r--lib/unistd--.h16
-rw-r--r--lib/unistd-safer.h22
-rw-r--r--lib/unistd.c4
-rw-r--r--lib/unistd.in.h1586
-rw-r--r--lib/unistd_.h192
-rw-r--r--lib/unistr.in.h750
-rw-r--r--lib/unistr/u8-mbtoucr.c285
-rw-r--r--lib/unistr/u8-uctomb-aux.c69
-rw-r--r--lib/unistr/u8-uctomb.c88
-rw-r--r--lib/unitypes.in.h46
-rw-r--r--lib/uniwidth.in.h72
-rw-r--r--lib/uniwidth/cjk.h37
-rw-r--r--lib/uniwidth/width.c450
-rw-r--r--lib/unlink.c97
-rw-r--r--lib/unlinkat.c122
-rw-r--r--lib/unlinkdir.c68
-rw-r--r--lib/unlinkdir.h27
-rw-r--r--lib/unlocked-io.h13
-rw-r--r--lib/unsetenv.c77
-rw-r--r--lib/userspec.c190
-rw-r--r--lib/userspec.h2
-rw-r--r--lib/utime.c109
-rw-r--r--lib/utimecmp.c417
-rw-r--r--lib/utimecmp.h11
-rw-r--r--lib/utimens.c535
-rw-r--r--lib/utimens.h48
-rw-r--r--lib/utimensat.c158
-rw-r--r--lib/vasnprintf.c6177
-rw-r--r--lib/vasnprintf.h32
-rw-r--r--lib/vasprintf.c18
-rw-r--r--lib/vasprintf.h69
-rw-r--r--lib/verify.h226
-rw-r--r--lib/verror.c77
-rw-r--r--lib/verror.h54
-rw-r--r--lib/version-etc-fsf.c11
-rw-r--r--lib/version-etc.c209
-rw-r--r--lib/version-etc.h65
-rw-r--r--lib/vfprintf.c74
-rw-r--r--lib/vprintf.c33
-rw-r--r--lib/w32sock.h136
-rw-r--r--lib/wchar.in.h1038
-rw-r--r--lib/wchar_.h42
-rw-r--r--lib/wcrtomb.c53
-rw-r--r--lib/wcswidth-impl.h43
-rw-r--r--lib/wcswidth.c25
-rw-r--r--lib/wctype-h.c4
-rw-r--r--lib/wctype.in.h514
-rw-r--r--lib/wctype_.h154
-rw-r--r--lib/wcwidth.c50
-rw-r--r--lib/wcwidth.h57
-rw-r--r--lib/write-any-file.c51
-rw-r--r--lib/write-any-file.h2
-rw-r--r--lib/write.c145
-rw-r--r--lib/xalloc-die.c15
-rw-r--r--lib/xalloc-oversized.h47
-rw-r--r--lib/xalloc.h187
-rw-r--r--lib/xasprintf.c34
-rw-r--r--lib/xdectoimax.c6
-rw-r--r--lib/xdectoint.c86
-rw-r--r--lib/xdectoint.h36
-rw-r--r--lib/xdectoumax.c6
-rw-r--r--lib/xfreopen.c42
-rw-r--r--lib/xfreopen.h2
-rw-r--r--lib/xfts.c61
-rw-r--r--lib/xfts.h7
-rw-r--r--lib/xgetcwd.c12
-rw-r--r--lib/xgetcwd.h11
-rw-r--r--lib/xgetgroups.c37
-rw-r--r--lib/xgethostname.c45
-rw-r--r--lib/xmalloc.c37
-rw-r--r--lib/xmemcoll.c48
-rw-r--r--lib/xmemcoll.h1
-rw-r--r--lib/xmemxfrm.c63
-rw-r--r--lib/xmemxfrm.h2
-rw-r--r--lib/xnanosleep.c81
-rw-r--r--lib/xprintf.c79
-rw-r--r--lib/xprintf.h45
-rw-r--r--lib/xreadlink.c111
-rw-r--r--lib/xreadlink.h27
-rw-r--r--lib/xsize.c3
-rw-r--r--lib/xsize.h117
-rw-r--r--lib/xstriconv.c62
-rw-r--r--lib/xstriconv.h78
-rw-r--r--lib/xstrndup.c11
-rw-r--r--lib/xstrndup.h11
-rw-r--r--lib/xstrtod.c19
-rw-r--r--lib/xstrtod.h16
-rw-r--r--lib/xstrtol-error.c98
-rw-r--r--lib/xstrtol.c253
-rw-r--r--lib/xstrtol.h76
-rw-r--r--lib/xtime.c3
-rw-r--r--lib/xtime.h65
-rw-r--r--lib/xvasprintf.c110
-rw-r--r--lib/xvasprintf.h55
-rw-r--r--lib/yesno.c27
-rw-r--r--lib/yesno.h12
718 files changed, 89797 insertions, 32680 deletions
diff --git a/lib/ChangeLog b/lib/ChangeLog-2007
index e1b4c7a..bbb3eab 100644
--- a/lib/ChangeLog
+++ b/lib/ChangeLog-2007
@@ -1,3 +1,8 @@
+2007-05-31 Jim Meyering <jim@meyering.net>
+
+ * printf-parse.c, vasnprintf.c, unicodeio.c: Remove local
+ copies, so we now get these files from gnulib.
+
2007-03-20 Jim Meyering <jim@meyering.net>
Fix a typo in the handling of %x and %X.
@@ -2724,7 +2729,7 @@
(local_zone): Accumulate dsts_seen rather than relying on tm_isdst
not being INT_MAX.
(get_date): Initialize dsts_seen, and check that it doesn't go over 1.
- Use pc_rels_seen to decide whther a date is absolute.
+ Use pc_rels_seen to decide whether a date is absolute.
* getdate.y (number): Don't overwrite year.
(get_date): Initialize pc.year.digits to 0, not 4, to enable above
@@ -8741,8 +8746,7 @@
-----
- Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free
- Software Foundation, Inc.
+ Copyright (C) 2000-2016 Free Software Foundation, Inc.
Copying and distribution of this file, with or without
modification, are permitted provided the copyright notice
diff --git a/lib/Makefile.am b/lib/Makefile.am
deleted file mode 100644
index cfa22be..0000000
--- a/lib/Makefile.am
+++ /dev/null
@@ -1,38 +0,0 @@
-## Makefile for gnulib/lib -*-Makefile-*-
-
-# Copyright (C) 1995-2006 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 2, 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, write to the Free Software
-## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-## 02110-1301, USA.
-
-include gnulib.mk
-
-AM_CFLAGS = $(WARNING_CFLAGS) $(WERROR_CFLAGS)
-
-noinst_PROGRAMS = t-fpending
-LDADD = $(noinst_LIBRARIES)
-
-libcoreutils_a_SOURCES += \
- buffer-lcm.c buffer-lcm.h \
- xmemxfrm.c xmemxfrm.h
-
-libcoreutils_a_LIBADD += $(LIBOBJS)
-libcoreutils_a_DEPENDENCIES += $(LIBOBJS)
-
-check: unit-test
-
-.PHONY: unit-test
-unit-test: t-fpending
- ./t-fpending > /dev/null
diff --git a/lib/Makefile.in b/lib/Makefile.in
deleted file mode 100644
index 772d8f3..0000000
--- a/lib/Makefile.in
+++ /dev/null
@@ -1,1636 +0,0 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
-# @configure_input@
-
-# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-@SET_MAKE@
-
-# Copyright (C) 1995-2006 Free Software Foundation, Inc.
-
-# Copyright (C) 2004-2007 Free Software Foundation, Inc.
-#
-# This file is free software, distributed under the terms of the GNU
-# General Public License. As a special exception to the GNU General
-# Public License, this file may be distributed as part of a program
-# that contains a configuration script generated by Autoconf, under
-# the same distribution terms as the rest of that program.
-#
-# Generated by gnulib-tool.
-# Reproduce by: gnulib-tool --import --dir=. --local-dir=gl --lib=libcoreutils --source-base=lib --m4-base=m4 --doc-base=doc --aux-dir=build-aux --avoid=lock --avoid=size_max --avoid=xsize --avoid=canonicalize-lgpl --no-libtool --macro-prefix=gl acl alloca announce-gen argmatch assert atexit backupfile base64 c-strcase c-strtod c-strtold calloc canon-host canonicalize chown cloexec closeout config-h configmake cycle-check d-ino d-type diacrit dirfd dirname dup2 error euidaccess exclude exitfail fchdir fcntl fcntl-safer fdl file-type fileblocks filemode filenamecat fnmatch-gnu fopen-safer fprintftime free fsusage ftruncate fts getdate getgroups gethrxtime getline getloadavg getndelim2 getopt getpagesize getpass-gnu gettext gettime gettimeofday getugroups getusershell gnupload group-member hard-locale hash hash-pjw host-os human idcache inttostr inttypes isapipe lchmod lchown lib-ignore linebuffer link-follow long-options lstat malloc mbswidth md5 memcasecmp memchr memcmp memcpy memmove mempcpy memrchr memset mkancesdirs mkdir mkdir-p mkstemp mktime modechange mountlist mpsort obstack pathmax perl physmem posixtm posixver putenv quote quotearg raise readlink readtokens readtokens0 readutmp realloc regex rename rename-dest-slash rmdir rmdir-errno root-dev-ino rpmatch safe-read same save-cwd savedir savewd settime sha1 sig2str ssize_t stat-macros stat-time stdbool stdlib-safer stpcpy strcspn strftime strpbrk strtod strtoimax strtol strtoumax strverscmp sys_stat timespec tzset unicodeio unistd-safer unlink-busy unlinkdir unlocked-io uptime userspec utime utimecmp utimens vasprintf verify version-etc-fsf wcwidth winsz-ioctl winsz-termios xalloc xgetcwd xgethostname xmemcoll xnanosleep xreadlink xreadlink-with-size xstrtod xstrtoimax xstrtol xstrtold xstrtoumax yesno
-
-
-
-
-VPATH = @srcdir@
-pkgdatadir = $(datadir)/@PACKAGE@
-pkglibdir = $(libdir)/@PACKAGE@
-pkgincludedir = $(includedir)/@PACKAGE@
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = @build@
-host_triplet = @host@
-DIST_COMMON = $(noinst_HEADERS) $(srcdir)/Makefile.am \
- $(srcdir)/Makefile.in $(srcdir)/config.hin $(srcdir)/gnulib.mk \
- ChangeLog TODO alloca.c euidaccess-stat.c euidaccess-stat.h \
- fd-reopen.c fd-reopen.h getdate.c memxfrm.c memxfrm.h \
- rand-isaac.c rand-isaac.h randint.c randint.h randperm.c \
- randperm.h randread.c randread.h sha256.c sha256.h sha512.c \
- sha512.h strintcmp.c strnumcmp-in.h strnumcmp.c strnumcmp.h \
- u64.h xfts.c xfts.h
-noinst_PROGRAMS = t-fpending$(EXEEXT)
-subdir = lib
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/m4/absolute-header.m4 \
- $(top_srcdir)/m4/acl.m4 $(top_srcdir)/m4/alloca.m4 \
- $(top_srcdir)/m4/allocsa.m4 $(top_srcdir)/m4/argmatch.m4 \
- $(top_srcdir)/m4/arpa_inet_h.m4 $(top_srcdir)/m4/assert.m4 \
- $(top_srcdir)/m4/atexit.m4 $(top_srcdir)/m4/autobuild.m4 \
- $(top_srcdir)/m4/backupfile.m4 $(top_srcdir)/m4/base64.m4 \
- $(top_srcdir)/m4/bison.m4 $(top_srcdir)/m4/boottime.m4 \
- $(top_srcdir)/m4/c-strtod.m4 $(top_srcdir)/m4/calloc.m4 \
- $(top_srcdir)/m4/canon-host.m4 \
- $(top_srcdir)/m4/canonicalize.m4 \
- $(top_srcdir)/m4/chdir-long.m4 $(top_srcdir)/m4/check-decl.m4 \
- $(top_srcdir)/m4/chown.m4 $(top_srcdir)/m4/clock_time.m4 \
- $(top_srcdir)/m4/cloexec.m4 $(top_srcdir)/m4/close-stream.m4 \
- $(top_srcdir)/m4/closeout.m4 $(top_srcdir)/m4/codeset.m4 \
- $(top_srcdir)/m4/config-h.m4 $(top_srcdir)/m4/cycle-check.m4 \
- $(top_srcdir)/m4/d-ino.m4 $(top_srcdir)/m4/d-type.m4 \
- $(top_srcdir)/m4/dirfd.m4 $(top_srcdir)/m4/dirname.m4 \
- $(top_srcdir)/m4/dos.m4 $(top_srcdir)/m4/double-slash-root.m4 \
- $(top_srcdir)/m4/dup2.m4 $(top_srcdir)/m4/eealloc.m4 \
- $(top_srcdir)/m4/eoverflow.m4 $(top_srcdir)/m4/error.m4 \
- $(top_srcdir)/m4/euidaccess-stat.m4 \
- $(top_srcdir)/m4/euidaccess.m4 $(top_srcdir)/m4/exclude.m4 \
- $(top_srcdir)/m4/exitfail.m4 $(top_srcdir)/m4/extensions.m4 \
- $(top_srcdir)/m4/fchdir.m4 $(top_srcdir)/m4/fcntl-safer.m4 \
- $(top_srcdir)/m4/fcntl_h.m4 $(top_srcdir)/m4/fd-reopen.m4 \
- $(top_srcdir)/m4/file-type.m4 $(top_srcdir)/m4/fileblocks.m4 \
- $(top_srcdir)/m4/filemode.m4 $(top_srcdir)/m4/filenamecat.m4 \
- $(top_srcdir)/m4/flexmember.m4 $(top_srcdir)/m4/fnmatch.m4 \
- $(top_srcdir)/m4/fpending.m4 $(top_srcdir)/m4/fprintftime.m4 \
- $(top_srcdir)/m4/free.m4 $(top_srcdir)/m4/fstypename.m4 \
- $(top_srcdir)/m4/fsusage.m4 $(top_srcdir)/m4/ftruncate.m4 \
- $(top_srcdir)/m4/fts.m4 $(top_srcdir)/m4/getaddrinfo.m4 \
- $(top_srcdir)/m4/getcwd-abort-bug.m4 \
- $(top_srcdir)/m4/getcwd-path-max.m4 $(top_srcdir)/m4/getcwd.m4 \
- $(top_srcdir)/m4/getdate.m4 $(top_srcdir)/m4/getdelim.m4 \
- $(top_srcdir)/m4/getgroups.m4 $(top_srcdir)/m4/gethostname.m4 \
- $(top_srcdir)/m4/gethrxtime.m4 $(top_srcdir)/m4/getline.m4 \
- $(top_srcdir)/m4/getloadavg.m4 $(top_srcdir)/m4/getndelim2.m4 \
- $(top_srcdir)/m4/getopt.m4 $(top_srcdir)/m4/getpagesize.m4 \
- $(top_srcdir)/m4/getpass.m4 $(top_srcdir)/m4/gettext.m4 \
- $(top_srcdir)/m4/gettime.m4 $(top_srcdir)/m4/gettimeofday.m4 \
- $(top_srcdir)/m4/getugroups.m4 \
- $(top_srcdir)/m4/getusershell.m4 $(top_srcdir)/m4/glibc21.m4 \
- $(top_srcdir)/m4/gnulib-common.m4 \
- $(top_srcdir)/m4/gnulib-comp.m4 \
- $(top_srcdir)/m4/group-member.m4 \
- $(top_srcdir)/m4/hard-locale.m4 $(top_srcdir)/m4/hash.m4 \
- $(top_srcdir)/m4/host-os.m4 $(top_srcdir)/m4/human.m4 \
- $(top_srcdir)/m4/i-ring.m4 $(top_srcdir)/m4/iconv.m4 \
- $(top_srcdir)/m4/idcache.m4 $(top_srcdir)/m4/inet_ntop.m4 \
- $(top_srcdir)/m4/inline.m4 $(top_srcdir)/m4/intmax_t.m4 \
- $(top_srcdir)/m4/inttostr.m4 $(top_srcdir)/m4/inttypes-pri.m4 \
- $(top_srcdir)/m4/inttypes.m4 $(top_srcdir)/m4/inttypes_h.m4 \
- $(top_srcdir)/m4/isapipe.m4 $(top_srcdir)/m4/jm-macros.m4 \
- $(top_srcdir)/m4/jm-winsz1.m4 $(top_srcdir)/m4/jm-winsz2.m4 \
- $(top_srcdir)/m4/lchmod.m4 $(top_srcdir)/m4/lchown.m4 \
- $(top_srcdir)/m4/lib-check.m4 $(top_srcdir)/m4/lib-ignore.m4 \
- $(top_srcdir)/m4/lib-ld.m4 $(top_srcdir)/m4/lib-link.m4 \
- $(top_srcdir)/m4/lib-prefix.m4 $(top_srcdir)/m4/link-follow.m4 \
- $(top_srcdir)/m4/localcharset.m4 \
- $(top_srcdir)/m4/long-options.m4 \
- $(top_srcdir)/m4/longdouble.m4 $(top_srcdir)/m4/longlong.m4 \
- $(top_srcdir)/m4/ls-mntd-fs.m4 $(top_srcdir)/m4/lstat.m4 \
- $(top_srcdir)/m4/mbchar.m4 $(top_srcdir)/m4/mbiter.m4 \
- $(top_srcdir)/m4/mbrtowc.m4 $(top_srcdir)/m4/mbscasecmp.m4 \
- $(top_srcdir)/m4/mbstate_t.m4 $(top_srcdir)/m4/mbswidth.m4 \
- $(top_srcdir)/m4/md5.m4 $(top_srcdir)/m4/memcasecmp.m4 \
- $(top_srcdir)/m4/memchr.m4 $(top_srcdir)/m4/memcmp.m4 \
- $(top_srcdir)/m4/memcoll.m4 $(top_srcdir)/m4/memcpy.m4 \
- $(top_srcdir)/m4/memmove.m4 $(top_srcdir)/m4/mempcpy.m4 \
- $(top_srcdir)/m4/memrchr.m4 $(top_srcdir)/m4/memset.m4 \
- $(top_srcdir)/m4/memxfrm.m4 $(top_srcdir)/m4/mkancesdirs.m4 \
- $(top_srcdir)/m4/mkdir-p.m4 $(top_srcdir)/m4/mkdir-slash.m4 \
- $(top_srcdir)/m4/mkstemp.m4 $(top_srcdir)/m4/mktime.m4 \
- $(top_srcdir)/m4/modechange.m4 $(top_srcdir)/m4/mountlist.m4 \
- $(top_srcdir)/m4/mpsort.m4 $(top_srcdir)/m4/nanosleep.m4 \
- $(top_srcdir)/m4/netinet_in_h.m4 $(top_srcdir)/m4/nls.m4 \
- $(top_srcdir)/m4/openat.m4 $(top_srcdir)/m4/pathmax.m4 \
- $(top_srcdir)/m4/perl.m4 $(top_srcdir)/m4/physmem.m4 \
- $(top_srcdir)/m4/po.m4 $(top_srcdir)/m4/posixtm.m4 \
- $(top_srcdir)/m4/posixver.m4 $(top_srcdir)/m4/prereq.m4 \
- $(top_srcdir)/m4/progtest.m4 $(top_srcdir)/m4/putenv.m4 \
- $(top_srcdir)/m4/quote.m4 $(top_srcdir)/m4/quotearg.m4 \
- $(top_srcdir)/m4/randint.m4 $(top_srcdir)/m4/randperm.m4 \
- $(top_srcdir)/m4/randread.m4 $(top_srcdir)/m4/readlink.m4 \
- $(top_srcdir)/m4/readtokens.m4 $(top_srcdir)/m4/readutmp.m4 \
- $(top_srcdir)/m4/regex.m4 \
- $(top_srcdir)/m4/rename-dest-slash.m4 \
- $(top_srcdir)/m4/rename.m4 $(top_srcdir)/m4/rmdir-errno.m4 \
- $(top_srcdir)/m4/rmdir.m4 $(top_srcdir)/m4/root-dev-ino.m4 \
- $(top_srcdir)/m4/rpmatch.m4 $(top_srcdir)/m4/safe-read.m4 \
- $(top_srcdir)/m4/safe-write.m4 $(top_srcdir)/m4/same.m4 \
- $(top_srcdir)/m4/save-cwd.m4 $(top_srcdir)/m4/savedir.m4 \
- $(top_srcdir)/m4/savewd.m4 $(top_srcdir)/m4/setenv.m4 \
- $(top_srcdir)/m4/settime.m4 $(top_srcdir)/m4/sha1.m4 \
- $(top_srcdir)/m4/sha256.m4 $(top_srcdir)/m4/sha512.m4 \
- $(top_srcdir)/m4/sig2str.m4 $(top_srcdir)/m4/snprintf.m4 \
- $(top_srcdir)/m4/socklen.m4 $(top_srcdir)/m4/sockpfaf.m4 \
- $(top_srcdir)/m4/ssize_t.m4 $(top_srcdir)/m4/st_dm_mode.m4 \
- $(top_srcdir)/m4/stat-prog.m4 $(top_srcdir)/m4/stat-time.m4 \
- $(top_srcdir)/m4/stdarg.m4 $(top_srcdir)/m4/stdbool.m4 \
- $(top_srcdir)/m4/stdint.m4 $(top_srcdir)/m4/stdint_h.m4 \
- $(top_srcdir)/m4/stdio-safer.m4 $(top_srcdir)/m4/stdio_h.m4 \
- $(top_srcdir)/m4/stdlib-safer.m4 $(top_srcdir)/m4/stdlib_h.m4 \
- $(top_srcdir)/m4/stpcpy.m4 $(top_srcdir)/m4/strcspn.m4 \
- $(top_srcdir)/m4/strdup.m4 $(top_srcdir)/m4/strftime.m4 \
- $(top_srcdir)/m4/string_h.m4 $(top_srcdir)/m4/strndup.m4 \
- $(top_srcdir)/m4/strnlen.m4 $(top_srcdir)/m4/strnumcmp.m4 \
- $(top_srcdir)/m4/strpbrk.m4 $(top_srcdir)/m4/strtod.m4 \
- $(top_srcdir)/m4/strtoimax.m4 $(top_srcdir)/m4/strtol.m4 \
- $(top_srcdir)/m4/strtoll.m4 $(top_srcdir)/m4/strtoul.m4 \
- $(top_srcdir)/m4/strtoull.m4 $(top_srcdir)/m4/strtoumax.m4 \
- $(top_srcdir)/m4/strverscmp.m4 \
- $(top_srcdir)/m4/sys_socket_h.m4 \
- $(top_srcdir)/m4/sys_stat_h.m4 $(top_srcdir)/m4/sys_time_h.m4 \
- $(top_srcdir)/m4/tempname.m4 $(top_srcdir)/m4/time_h.m4 \
- $(top_srcdir)/m4/time_r.m4 $(top_srcdir)/m4/timespec.m4 \
- $(top_srcdir)/m4/tm_gmtoff.m4 $(top_srcdir)/m4/tzset.m4 \
- $(top_srcdir)/m4/unicodeio.m4 $(top_srcdir)/m4/unistd-safer.m4 \
- $(top_srcdir)/m4/unistd_h.m4 $(top_srcdir)/m4/unlink-busy.m4 \
- $(top_srcdir)/m4/unlinkdir.m4 $(top_srcdir)/m4/unlocked-io.m4 \
- $(top_srcdir)/m4/uptime.m4 $(top_srcdir)/m4/userspec.m4 \
- $(top_srcdir)/m4/utimbuf.m4 $(top_srcdir)/m4/utime.m4 \
- $(top_srcdir)/m4/utimecmp.m4 $(top_srcdir)/m4/utimens.m4 \
- $(top_srcdir)/m4/utimes-null.m4 $(top_srcdir)/m4/utimes.m4 \
- $(top_srcdir)/m4/vasnprintf.m4 $(top_srcdir)/m4/vasprintf.m4 \
- $(top_srcdir)/m4/wchar.m4 $(top_srcdir)/m4/wchar_t.m4 \
- $(top_srcdir)/m4/wctype.m4 $(top_srcdir)/m4/wcwidth.m4 \
- $(top_srcdir)/m4/wint_t.m4 $(top_srcdir)/m4/xalloc.m4 \
- $(top_srcdir)/m4/xfts.m4 $(top_srcdir)/m4/xgetcwd.m4 \
- $(top_srcdir)/m4/xnanosleep.m4 $(top_srcdir)/m4/xstrndup.m4 \
- $(top_srcdir)/m4/xstrtod.m4 $(top_srcdir)/m4/xstrtol.m4 \
- $(top_srcdir)/m4/yesno.m4 $(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
- $(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = config.h
-CONFIG_CLEAN_FILES =
-LIBRARIES = $(noinst_LIBRARIES)
-AR = ar
-ARFLAGS = cru
-libcoreutils_a_AR = $(AR) $(ARFLAGS)
-am__DEPENDENCIES_1 =
-am_libcoreutils_a_OBJECTS = allocsa.$(OBJEXT) base64.$(OBJEXT) \
- c-ctype.$(OBJEXT) c-strcasecmp.$(OBJEXT) \
- c-strncasecmp.$(OBJEXT) diacrit.$(OBJEXT) full-read.$(OBJEXT) \
- full-write.$(OBJEXT) getdate.$(OBJEXT) hash-pjw.$(OBJEXT) \
- linebuffer.$(OBJEXT) localcharset.$(OBJEXT) mbchar.$(OBJEXT) \
- mbscasecmp.$(OBJEXT) mbswidth.$(OBJEXT) readtokens0.$(OBJEXT) \
- savewd.$(OBJEXT) strnlen1.$(OBJEXT) unicodeio.$(OBJEXT) \
- version-etc.$(OBJEXT) version-etc-fsf.$(OBJEXT) \
- xalloc-die.$(OBJEXT) xgethostname.$(OBJEXT) xmemcoll.$(OBJEXT) \
- xreadlink.$(OBJEXT) xreadlink-with-size.$(OBJEXT) \
- xstrndup.$(OBJEXT) xstrtoimax.$(OBJEXT) xstrtoumax.$(OBJEXT) \
- buffer-lcm.$(OBJEXT) xmemxfrm.$(OBJEXT)
-libcoreutils_a_OBJECTS = $(am_libcoreutils_a_OBJECTS)
-LTLIBRARIES = $(noinst_LTLIBRARIES)
-PROGRAMS = $(noinst_PROGRAMS)
-t_fpending_SOURCES = t-fpending.c
-t_fpending_OBJECTS = t-fpending.$(OBJEXT)
-t_fpending_LDADD = $(LDADD)
-t_fpending_DEPENDENCIES = $(noinst_LIBRARIES)
-DEFAULT_INCLUDES = -I.@am__isrc@
-depcomp = $(SHELL) $(top_srcdir)/build-aux/depcomp
-am__depfiles_maybe = depfiles
-COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
- $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
-CCLD = $(CC)
-LINK = $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@
-YACCCOMPILE = $(YACC) $(YFLAGS) $(AM_YFLAGS)
-YLWRAP = $(top_srcdir)/build-aux/ylwrap
-SOURCES = $(libcoreutils_a_SOURCES) $(EXTRA_libcoreutils_a_SOURCES) \
- t-fpending.c
-DIST_SOURCES = $(libcoreutils_a_SOURCES) \
- $(EXTRA_libcoreutils_a_SOURCES) t-fpending.c
-HEADERS = $(noinst_HEADERS)
-ETAGS = etags
-CTAGS = ctags
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-ABSOLUTE_DIRENT_H = @ABSOLUTE_DIRENT_H@
-ABSOLUTE_FCNTL_H = @ABSOLUTE_FCNTL_H@
-ABSOLUTE_INTTYPES_H = @ABSOLUTE_INTTYPES_H@
-ABSOLUTE_NETINET_IN_H = @ABSOLUTE_NETINET_IN_H@
-ABSOLUTE_STDINT_H = @ABSOLUTE_STDINT_H@
-ABSOLUTE_STDIO_H = @ABSOLUTE_STDIO_H@
-ABSOLUTE_STDLIB_H = @ABSOLUTE_STDLIB_H@
-ABSOLUTE_STRING_H = @ABSOLUTE_STRING_H@
-ABSOLUTE_SYS_SOCKET_H = @ABSOLUTE_SYS_SOCKET_H@
-ABSOLUTE_SYS_STAT_H = @ABSOLUTE_SYS_STAT_H@
-ABSOLUTE_SYS_TIME_H = @ABSOLUTE_SYS_TIME_H@
-ABSOLUTE_TIME_H = @ABSOLUTE_TIME_H@
-ABSOLUTE_UNISTD_H = @ABSOLUTE_UNISTD_H@
-ABSOLUTE_WCHAR_H = @ABSOLUTE_WCHAR_H@
-ABSOLUTE_WCTYPE_H = @ABSOLUTE_WCTYPE_H@
-ACLOCAL = @ACLOCAL@
-ALLOCA = @ALLOCA@
-ALLOCA_H = @ALLOCA_H@
-AMTAR = @AMTAR@
-ARPA_INET_H = @ARPA_INET_H@
-AUTOCONF = @AUTOCONF@
-AUTOHEADER = @AUTOHEADER@
-AUTOMAKE = @AUTOMAKE@
-AWK = @AWK@
-BITSIZEOF_PTRDIFF_T = @BITSIZEOF_PTRDIFF_T@
-BITSIZEOF_SIG_ATOMIC_T = @BITSIZEOF_SIG_ATOMIC_T@
-BITSIZEOF_SIZE_T = @BITSIZEOF_SIZE_T@
-BITSIZEOF_WCHAR_T = @BITSIZEOF_WCHAR_T@
-BITSIZEOF_WINT_T = @BITSIZEOF_WINT_T@
-CC = @CC@
-CCDEPMODE = @CCDEPMODE@
-CFLAGS = @CFLAGS@
-CPP = @CPP@
-CPPFLAGS = @CPPFLAGS@
-CYGPATH_W = @CYGPATH_W@
-DEFAULT_POSIX2_VERSION = @DEFAULT_POSIX2_VERSION@
-DEFS = @DEFS@
-DEPDIR = @DEPDIR@
-DF_PROG = @DF_PROG@
-DIRENT_H = @DIRENT_H@
-ECHO_C = @ECHO_C@
-ECHO_N = @ECHO_N@
-ECHO_T = @ECHO_T@
-EGREP = @EGREP@
-EOVERFLOW = @EOVERFLOW@
-EXEEXT = @EXEEXT@
-FCNTL_H = @FCNTL_H@
-FNMATCH_H = @FNMATCH_H@
-GETLOADAVG_LIBS = @GETLOADAVG_LIBS@
-GETOPT_H = @GETOPT_H@
-GLIBC21 = @GLIBC21@
-GMSGFMT = @GMSGFMT@
-GMSGFMT_015 = @GMSGFMT_015@
-GNULIB_CHOWN = @GNULIB_CHOWN@
-GNULIB_DUP2 = @GNULIB_DUP2@
-GNULIB_FCHDIR = @GNULIB_FCHDIR@
-GNULIB_FPRINTF_POSIX = @GNULIB_FPRINTF_POSIX@
-GNULIB_FTRUNCATE = @GNULIB_FTRUNCATE@
-GNULIB_GETCWD = @GNULIB_GETCWD@
-GNULIB_GETLOGIN_R = @GNULIB_GETLOGIN_R@
-GNULIB_GETSUBOPT = @GNULIB_GETSUBOPT@
-GNULIB_IMAXABS = @GNULIB_IMAXABS@
-GNULIB_IMAXDIV = @GNULIB_IMAXDIV@
-GNULIB_MBSCASECMP = @GNULIB_MBSCASECMP@
-GNULIB_MBSCASESTR = @GNULIB_MBSCASESTR@
-GNULIB_MBSCHR = @GNULIB_MBSCHR@
-GNULIB_MBSCSPN = @GNULIB_MBSCSPN@
-GNULIB_MBSLEN = @GNULIB_MBSLEN@
-GNULIB_MBSNCASECMP = @GNULIB_MBSNCASECMP@
-GNULIB_MBSPBRK = @GNULIB_MBSPBRK@
-GNULIB_MBSPCASECMP = @GNULIB_MBSPCASECMP@
-GNULIB_MBSRCHR = @GNULIB_MBSRCHR@
-GNULIB_MBSSEP = @GNULIB_MBSSEP@
-GNULIB_MBSSPN = @GNULIB_MBSSPN@
-GNULIB_MBSSTR = @GNULIB_MBSSTR@
-GNULIB_MBSTOK_R = @GNULIB_MBSTOK_R@
-GNULIB_MEMMEM = @GNULIB_MEMMEM@
-GNULIB_MEMPCPY = @GNULIB_MEMPCPY@
-GNULIB_MEMRCHR = @GNULIB_MEMRCHR@
-GNULIB_MKDTEMP = @GNULIB_MKDTEMP@
-GNULIB_MKSTEMP = @GNULIB_MKSTEMP@
-GNULIB_PRINTF_POSIX = @GNULIB_PRINTF_POSIX@
-GNULIB_READLINK = @GNULIB_READLINK@
-GNULIB_SNPRINTF = @GNULIB_SNPRINTF@
-GNULIB_SPRINTF_POSIX = @GNULIB_SPRINTF_POSIX@
-GNULIB_STPCPY = @GNULIB_STPCPY@
-GNULIB_STPNCPY = @GNULIB_STPNCPY@
-GNULIB_STRCASESTR = @GNULIB_STRCASESTR@
-GNULIB_STRCHRNUL = @GNULIB_STRCHRNUL@
-GNULIB_STRDUP = @GNULIB_STRDUP@
-GNULIB_STRNDUP = @GNULIB_STRNDUP@
-GNULIB_STRNLEN = @GNULIB_STRNLEN@
-GNULIB_STRPBRK = @GNULIB_STRPBRK@
-GNULIB_STRSEP = @GNULIB_STRSEP@
-GNULIB_STRTOIMAX = @GNULIB_STRTOIMAX@
-GNULIB_STRTOK_R = @GNULIB_STRTOK_R@
-GNULIB_STRTOUMAX = @GNULIB_STRTOUMAX@
-GNULIB_VFPRINTF_POSIX = @GNULIB_VFPRINTF_POSIX@
-GNULIB_VPRINTF_POSIX = @GNULIB_VPRINTF_POSIX@
-GNULIB_VSNPRINTF = @GNULIB_VSNPRINTF@
-GNULIB_VSPRINTF_POSIX = @GNULIB_VSPRINTF_POSIX@
-GNU_PACKAGE = @GNU_PACKAGE@
-GREP = @GREP@
-HAVE_DECL_GETLOGIN_R = @HAVE_DECL_GETLOGIN_R@
-HAVE_DECL_IMAXABS = @HAVE_DECL_IMAXABS@
-HAVE_DECL_IMAXDIV = @HAVE_DECL_IMAXDIV@
-HAVE_DECL_MEMMEM = @HAVE_DECL_MEMMEM@
-HAVE_DECL_MEMRCHR = @HAVE_DECL_MEMRCHR@
-HAVE_DECL_SNPRINTF = @HAVE_DECL_SNPRINTF@
-HAVE_DECL_STRDUP = @HAVE_DECL_STRDUP@
-HAVE_DECL_STRNCASECMP = @HAVE_DECL_STRNCASECMP@
-HAVE_DECL_STRNDUP = @HAVE_DECL_STRNDUP@
-HAVE_DECL_STRNLEN = @HAVE_DECL_STRNLEN@
-HAVE_DECL_STRTOIMAX = @HAVE_DECL_STRTOIMAX@
-HAVE_DECL_STRTOK_R = @HAVE_DECL_STRTOK_R@
-HAVE_DECL_STRTOUMAX = @HAVE_DECL_STRTOUMAX@
-HAVE_DECL_VSNPRINTF = @HAVE_DECL_VSNPRINTF@
-HAVE_DUP2 = @HAVE_DUP2@
-HAVE_FTRUNCATE = @HAVE_FTRUNCATE@
-HAVE_GETSUBOPT = @HAVE_GETSUBOPT@
-HAVE_INTTYPES_H = @HAVE_INTTYPES_H@
-HAVE_LONG_LONG_INT = @HAVE_LONG_LONG_INT@
-HAVE_MEMPCPY = @HAVE_MEMPCPY@
-HAVE_MKDTEMP = @HAVE_MKDTEMP@
-HAVE_NETINET_IN_H = @HAVE_NETINET_IN_H@
-HAVE_READLINK = @HAVE_READLINK@
-HAVE_SIGNED_SIG_ATOMIC_T = @HAVE_SIGNED_SIG_ATOMIC_T@
-HAVE_SIGNED_WCHAR_T = @HAVE_SIGNED_WCHAR_T@
-HAVE_SIGNED_WINT_T = @HAVE_SIGNED_WINT_T@
-HAVE_STDINT_H = @HAVE_STDINT_H@
-HAVE_STPCPY = @HAVE_STPCPY@
-HAVE_STPNCPY = @HAVE_STPNCPY@
-HAVE_STRCASECMP = @HAVE_STRCASECMP@
-HAVE_STRCASESTR = @HAVE_STRCASESTR@
-HAVE_STRCHRNUL = @HAVE_STRCHRNUL@
-HAVE_STRNDUP = @HAVE_STRNDUP@
-HAVE_STRPBRK = @HAVE_STRPBRK@
-HAVE_STRSEP = @HAVE_STRSEP@
-HAVE_STRUCT_TIMEVAL = @HAVE_STRUCT_TIMEVAL@
-HAVE_SYS_BITYPES_H = @HAVE_SYS_BITYPES_H@
-HAVE_SYS_INTTYPES_H = @HAVE_SYS_INTTYPES_H@
-HAVE_SYS_SOCKET_H = @HAVE_SYS_SOCKET_H@
-HAVE_SYS_TIME_H = @HAVE_SYS_TIME_H@
-HAVE_SYS_TYPES_H = @HAVE_SYS_TYPES_H@
-HAVE_UNISTD_H = @HAVE_UNISTD_H@
-HAVE_UNSIGNED_LONG_LONG_INT = @HAVE_UNSIGNED_LONG_LONG_INT@
-HAVE_WCTYPE_H = @HAVE_WCTYPE_H@
-HAVE_WINSOCK2_H = @HAVE_WINSOCK2_H@
-HAVE_WINT_T = @HAVE_WINT_T@
-HAVE_WS2TCPIP_H = @HAVE_WS2TCPIP_H@
-HAVE__BOOL = @HAVE__BOOL@
-HELP2MAN = @HELP2MAN@
-INSTALL = @INSTALL@
-INSTALL_DATA = @INSTALL_DATA@
-INSTALL_PROGRAM = @INSTALL_PROGRAM@
-INSTALL_SCRIPT = @INSTALL_SCRIPT@
-INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
-INTLLIBS = @INTLLIBS@
-INTL_MACOSX_LIBS = @INTL_MACOSX_LIBS@
-INTTYPES_H = @INTTYPES_H@
-KMEM_GROUP = @KMEM_GROUP@
-LDFLAGS = @LDFLAGS@
-LIBCOREUTILS_LIBDEPS = @LIBCOREUTILS_LIBDEPS@
-LIBCOREUTILS_LTLIBDEPS = @LIBCOREUTILS_LTLIBDEPS@
-LIBICONV = @LIBICONV@
-LIBINTL = @LIBINTL@
-LIBOBJS = @LIBOBJS@
-LIBS = @LIBS@ $(POW_LIB)
-LIB_ACL = @LIB_ACL@
-LIB_ACL_TRIVIAL = @LIB_ACL_TRIVIAL@
-LIB_CLOCK_GETTIME = @LIB_CLOCK_GETTIME@
-LIB_CRYPT = @LIB_CRYPT@
-LIB_EACCESS = @LIB_EACCESS@
-LIB_FDATASYNC = @LIB_FDATASYNC@
-LIB_GETHRXTIME = @LIB_GETHRXTIME@
-LIB_NANOSLEEP = @LIB_NANOSLEEP@
-LN_S = @LN_S@
-LTLIBICONV = @LTLIBICONV@
-LTLIBINTL = @LTLIBINTL@
-LTLIBOBJS = @LTLIBOBJS@
-MAKEINFO = @MAKEINFO@
-MAN = @MAN@
-MKDIR_P = @MKDIR_P@
-MSGFMT = @MSGFMT@
-MSGFMT_015 = @MSGFMT_015@
-MSGMERGE = @MSGMERGE@
-NEED_SETGID = @NEED_SETGID@
-NETINET_IN_H = @NETINET_IN_H@
-OBJEXT = @OBJEXT@
-OPTIONAL_BIN_PROGS = @OPTIONAL_BIN_PROGS@
-PACKAGE = @PACKAGE@
-PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
-PACKAGE_NAME = @PACKAGE_NAME@
-PACKAGE_STRING = @PACKAGE_STRING@
-PACKAGE_TARNAME = @PACKAGE_TARNAME@
-PACKAGE_VERSION = @PACKAGE_VERSION@
-PATH_SEPARATOR = @PATH_SEPARATOR@
-PERL = @PERL@
-POSUB = @POSUB@
-POW_LIB = @POW_LIB@
-PRIPTR_PREFIX = @PRIPTR_PREFIX@
-PRI_MACROS_BROKEN = @PRI_MACROS_BROKEN@
-PTRDIFF_T_SUFFIX = @PTRDIFF_T_SUFFIX@
-RANLIB = @RANLIB@
-REPLACE_CHOWN = @REPLACE_CHOWN@
-REPLACE_FCHDIR = @REPLACE_FCHDIR@
-REPLACE_FPRINTF = @REPLACE_FPRINTF@
-REPLACE_GETCWD = @REPLACE_GETCWD@
-REPLACE_GETTIMEOFDAY = @REPLACE_GETTIMEOFDAY@
-REPLACE_LOCALTIME_R = @REPLACE_LOCALTIME_R@
-REPLACE_MKSTEMP = @REPLACE_MKSTEMP@
-REPLACE_NANOSLEEP = @REPLACE_NANOSLEEP@
-REPLACE_PRINTF = @REPLACE_PRINTF@
-REPLACE_SNPRINTF = @REPLACE_SNPRINTF@
-REPLACE_SPRINTF = @REPLACE_SPRINTF@
-REPLACE_STRPTIME = @REPLACE_STRPTIME@
-REPLACE_TIMEGM = @REPLACE_TIMEGM@
-REPLACE_VFPRINTF = @REPLACE_VFPRINTF@
-REPLACE_VPRINTF = @REPLACE_VPRINTF@
-REPLACE_VSNPRINTF = @REPLACE_VSNPRINTF@
-REPLACE_VSPRINTF = @REPLACE_VSPRINTF@
-SEQ_LIBM = @SEQ_LIBM@
-SET_MAKE = @SET_MAKE@
-SHELL = @SHELL@
-SIG_ATOMIC_T_SUFFIX = @SIG_ATOMIC_T_SUFFIX@
-SIZE_T_SUFFIX = @SIZE_T_SUFFIX@
-STDBOOL_H = @STDBOOL_H@
-STDINT_H = @STDINT_H@
-STRIP = @STRIP@
-SYS_SOCKET_H = @SYS_SOCKET_H@
-SYS_STAT_H = @SYS_STAT_H@
-SYS_TIME_H = @SYS_TIME_H@
-SYS_TIME_H_DEFINES_STRUCT_TIMESPEC = @SYS_TIME_H_DEFINES_STRUCT_TIMESPEC@
-TIME_H_DEFINES_STRUCT_TIMESPEC = @TIME_H_DEFINES_STRUCT_TIMESPEC@
-U = @U@
-USE_NLS = @USE_NLS@
-VERSION = @VERSION@
-WCHAR_H = @WCHAR_H@
-WCHAR_T_SUFFIX = @WCHAR_T_SUFFIX@
-WCTYPE_H = @WCTYPE_H@
-WINT_T_SUFFIX = @WINT_T_SUFFIX@
-XGETTEXT = @XGETTEXT@
-XGETTEXT_015 = @XGETTEXT_015@
-YACC = @YACC@
-YFLAGS = @YFLAGS@
-abs_builddir = @abs_builddir@
-abs_srcdir = @abs_srcdir@
-abs_top_builddir = @abs_top_builddir@
-abs_top_srcdir = @abs_top_srcdir@
-ac_ct_CC = @ac_ct_CC@
-am__include = @am__include@
-am__leading_dot = @am__leading_dot@
-am__quote = @am__quote@
-am__tar = @am__tar@
-am__untar = @am__untar@
-bindir = @bindir@
-build = @build@
-build_alias = @build_alias@
-build_cpu = @build_cpu@
-build_os = @build_os@
-build_vendor = @build_vendor@
-builddir = @builddir@
-datadir = @datadir@
-datarootdir = @datarootdir@
-docdir = @docdir@
-dvidir = @dvidir@
-exec_prefix = @exec_prefix@
-gl_LIBOBJS = @gl_LIBOBJS@
-gl_LTLIBOBJS = @gl_LTLIBOBJS@
-host = @host@
-host_alias = @host_alias@
-host_cpu = @host_cpu@
-host_os = @host_os@
-host_vendor = @host_vendor@
-htmldir = @htmldir@
-includedir = @includedir@
-infodir = @infodir@
-install_sh = @install_sh@
-libdir = @libdir@
-libexecdir = @libexecdir@
-localedir = @localedir@
-localstatedir = @localstatedir@
-mandir = @mandir@
-mkdir_p = @mkdir_p@
-oldincludedir = @oldincludedir@
-pdfdir = @pdfdir@
-prefix = @prefix@
-program_transform_name = @program_transform_name@
-psdir = @psdir@
-sbindir = @sbindir@
-sharedstatedir = @sharedstatedir@
-srcdir = @srcdir@
-sysconfdir = @sysconfdir@
-target_alias = @target_alias@
-top_builddir = @top_builddir@
-top_srcdir = @top_srcdir@
-AUTOMAKE_OPTIONS = 1.5 gnits
-noinst_HEADERS =
-noinst_LIBRARIES = libcoreutils.a
-noinst_LTLIBRARIES =
-EXTRA_DIST = acl-internal.h acl.c acl.h acl_entries.c file-has-acl.c \
- alloca.c alloca_.h allocsa.valgrind argmatch.c argmatch.h \
- atexit.c backupfile.c backupfile.h c-strtod.c c-strtod.h \
- c-strtod.c c-strtod.h c-strtold.c calloc.c canon-host.c \
- canon-host.h canonicalize.c canonicalize.h pathmax.h \
- chdir-long.c chdir-long.h chown.c fchown-stub.c cloexec.c \
- cloexec.h close-stream.c close-stream.h closeout.c closeout.h \
- cycle-check.c cycle-check.h dev-ino.h dirfd.c dirfd.h \
- basename.c dirname.c dirname.h stripslash.c dup2.c error.c \
- error.h euidaccess.c euidaccess.h exclude.c exclude.h \
- exitfail.c exitfail.h dirent_.h fchdir.c fcntl_.h \
- creat-safer.c fcntl--.h fcntl-safer.h open-safer.c file-type.c \
- file-type.h fileblocks.c filemode.c filemode.h filenamecat.c \
- filenamecat.h fnmatch.c fnmatch_.h fnmatch_loop.c \
- fopen-safer.c stdio--.h stdio-safer.h __fpending.c \
- __fpending.h fprintftime.c fprintftime.h free.c fsusage.c \
- fsusage.h ftruncate.c fts-cycle.c fts.c fts_.h gai_strerror.c \
- getaddrinfo.c getaddrinfo.h getcwd.c getdate.c getdate.h \
- getdelim.c getdelim.h getgroups.c gethostname.c gethrxtime.c \
- gethrxtime.h xtime.h getline.c getline.h getloadavg.c \
- getndelim2.c getndelim2.h getopt.c getopt1.c getopt_.h \
- getopt_int.h getpagesize.h getpass.c getpass.h gettime.c \
- gettimeofday.c getugroups.c getusershell.c group-member.c \
- group-member.h hard-locale.c hard-locale.h hash.c hash.h \
- human.c human.h i-ring.c i-ring.h idcache.c inet_ntop.c \
- inet_ntop.h intprops.h imaxtostr.c inttostr.c inttostr.h \
- offtostr.c uinttostr.c umaxtostr.c inttypes_.h isapipe.c \
- isapipe.h lchmod.h lchown.c lchown.h config.charset \
- ref-add.sin ref-del.sin long-options.c long-options.h lstat.c \
- lstat.h malloc.c mbchar.h md5.c md5.h memcasecmp.c \
- memcasecmp.h memchr.c memcmp.c memcoll.c memcoll.h memcpy.c \
- memmove.c mempcpy.c memrchr.c memset.c mkancesdirs.c \
- mkancesdirs.h mkdir.c dirchownmod.c dirchownmod.h mkdir-p.c \
- mkdir-p.h mkstemp.c mktime.c modechange.c modechange.h \
- mountlist.c mountlist.h mpsort.c mpsort.h nanosleep.c \
- netinet_in_.h obstack.c obstack.h at-func.c fchmodat.c \
- fchownat.c fstatat.c mkdirat.c openat-die.c openat-priv.h \
- openat-proc.c openat.c openat.h pathmax.h physmem.c physmem.h \
- posixtm.c posixtm.h posixver.c posixver.h putenv.c quote.c \
- quote.h quotearg.c quotearg.h raise.c readlink.c readtokens.c \
- readtokens.h readutmp.c readutmp.h realloc.c regcomp.c regex.c \
- regex.h regex_internal.c regex_internal.h regexec.c rename.c \
- rename-dest-slash.c rmdir.c root-dev-ino.c root-dev-ino.h \
- rpmatch.c safe-read.c safe-read.h safe-write.c safe-write.h \
- same.c same.h same-inode.h save-cwd.c save-cwd.h savedir.c \
- savedir.h setenv.c setenv.h unsetenv.c settime.c sha1.c sha1.h \
- sig2str.c sig2str.h snprintf.c stat-macros.h stat-time.h \
- stdbool_.h stdint_.h stdio_.h stdlib_.h mkstemp-safer.c \
- stdlib--.h stdlib-safer.h stpcpy.c strcspn.c strdup.c \
- strftime.c strftime.h string_.h strndup.c strnlen.c strpbrk.c \
- strtod.c strtoimax.c strtol.c strtoll.c strtoul.c strtoull.c \
- strtoumax.c strverscmp.c strverscmp.h socket_.h stat_.h \
- sys_time_.h tempname.c tempname.h time_.h time_r.c timespec.h \
- unistd_.h dup-safer.c fd-safer.c pipe-safer.c unistd--.h \
- unistd-safer.h unlinkdir.c unlinkdir.h unlocked-io.h \
- inttostr.h userspec.c userspec.h utime.c utimecmp.c utimecmp.h \
- utimens.c utimens.h asnprintf.c printf-args.c printf-args.h \
- printf-parse.c printf-parse.h vasnprintf.c vasnprintf.h \
- asprintf.c vasprintf.c vasprintf.h wchar_.h wctype_.h xalloc.h \
- xmalloc.c xgetcwd.c xgetcwd.h xnanosleep.c xnanosleep.h \
- xreadlink.h xreadlink.h xstrtod.c xstrtod.h xstrtol.c \
- xstrtol.h xstrtoul.c xstrtod.c xstrtod.h xstrtold.c yesno.c \
- yesno.h
-BUILT_SOURCES = $(ALLOCA_H) $(ARPA_INET_H) configmake.h $(DIRENT_H) \
- $(FCNTL_H) $(FNMATCH_H) getdate.c $(GETOPT_H) $(INTTYPES_H) \
- $(NETINET_IN_H) $(STDBOOL_H) $(STDINT_H) stdio.h stdlib.h \
- string.h $(SYS_SOCKET_H) $(SYS_STAT_H) $(SYS_TIME_H) time.h \
- unistd.h $(WCHAR_H) $(WCTYPE_H)
-SUFFIXES = .sed .sin
-MOSTLYCLEANFILES = core *.stackdump alloca.h alloca.h-t arpa/inet.h \
- arpa/inet.h-t dirent.h dirent.h-t fcntl.h fcntl.h-t fnmatch.h \
- fnmatch.h-t getopt.h getopt.h-t inttypes.h inttypes.h-t \
- netinet/in.h netinet/in.h-t stdbool.h stdbool.h-t stdint.h \
- stdint.h-t stdio.h stdio.h-t stdlib.h stdlib.h-t string.h \
- string.h-t sys/socket.h sys/socket.h-t sys/stat.h sys/stat.h-t \
- sys/time.h sys/time.h-t time.h time.h-t unistd.h unistd.h-t \
- wchar.h wchar.h-t wctype.h wctype.h-t
-MOSTLYCLEANDIRS = arpa netinet sys sys
-CLEANFILES = configmake.h configmake.h-t charset.alias ref-add.sed \
- ref-del.sed
-DISTCLEANFILES =
-MAINTAINERCLEANFILES = getdate.c
-AM_CPPFLAGS =
-
-# This is for those projects which use "gettextize --intl" to put a source-code
-# copy of libintl into their package. In such projects, every Makefile.am needs
-# -I$(top_builddir)/intl, so that <libintl.h> can be found in this directory.
-# For the Makefile.ams in other directories it is the maintainer's
-# responsibility; for the one from gnulib we do it here.
-# This option has no effect when the user disables NLS (because then the intl
-# directory contains no libintl.h file) or when the project does not use
-# "gettextize --intl".
-#AM_CPPFLAGS += -I$(top_builddir)/intl
-libcoreutils_a_SOURCES = allocsa.h allocsa.c base64.h base64.c \
- c-ctype.h c-ctype.c c-strcase.h c-strcasecmp.c c-strncasecmp.c \
- diacrit.h diacrit.c full-read.h full-read.c full-write.h \
- full-write.c getdate.y gettext.h hash-pjw.h hash-pjw.c \
- linebuffer.h linebuffer.c localcharset.h localcharset.c \
- mbchar.c mbscasecmp.c mbswidth.h mbswidth.c mbuiter.h \
- readtokens0.h readtokens0.c savewd.h savewd.c strnlen1.h \
- strnlen1.c unicodeio.h unicodeio.c verify.h version-etc.h \
- version-etc.c version-etc-fsf.c wcwidth.h xalloc-die.c \
- xgethostname.h xgethostname.c xmemcoll.h xmemcoll.c \
- xreadlink.c xreadlink-with-size.c xstrndup.h xstrndup.c \
- xstrtoimax.c xstrtoumax.c buffer-lcm.c buffer-lcm.h xmemxfrm.c \
- xmemxfrm.h
-libcoreutils_a_LIBADD = $(gl_LIBOBJS) @ALLOCA@ $(LIBOBJS)
-libcoreutils_a_DEPENDENCIES = $(gl_LIBOBJS) @ALLOCA@ $(LIBOBJS)
-EXTRA_libcoreutils_a_SOURCES = acl.c acl_entries.c file-has-acl.c \
- alloca.c argmatch.c atexit.c backupfile.c c-strtod.c \
- c-strtod.c c-strtold.c calloc.c canon-host.c canonicalize.c \
- chdir-long.c chown.c fchown-stub.c cloexec.c close-stream.c \
- closeout.c cycle-check.c dirfd.c basename.c dirname.c \
- stripslash.c dup2.c error.c euidaccess.c exclude.c exitfail.c \
- fchdir.c creat-safer.c open-safer.c file-type.c fileblocks.c \
- filemode.c filenamecat.c fnmatch.c fnmatch_loop.c \
- fopen-safer.c __fpending.c fprintftime.c free.c fsusage.c \
- ftruncate.c fts-cycle.c fts.c gai_strerror.c getaddrinfo.c \
- getcwd.c getdelim.c getgroups.c gethostname.c gethrxtime.c \
- getline.c getloadavg.c getndelim2.c getopt.c getopt1.c \
- getpass.c gettime.c gettimeofday.c getugroups.c getusershell.c \
- group-member.c hard-locale.c hash.c human.c i-ring.c idcache.c \
- inet_ntop.c imaxtostr.c inttostr.c offtostr.c uinttostr.c \
- umaxtostr.c isapipe.c lchown.c long-options.c lstat.c malloc.c \
- md5.c memcasecmp.c memchr.c memcmp.c memcoll.c memcpy.c \
- memmove.c mempcpy.c memrchr.c memset.c mkancesdirs.c mkdir.c \
- dirchownmod.c mkdir-p.c mkstemp.c mktime.c modechange.c \
- mountlist.c mpsort.c nanosleep.c obstack.c at-func.c \
- fchmodat.c fchownat.c fstatat.c mkdirat.c openat-die.c \
- openat-proc.c openat.c physmem.c posixtm.c posixver.c putenv.c \
- quote.c quotearg.c raise.c readlink.c readtokens.c readutmp.c \
- realloc.c regcomp.c regex.c regex_internal.c regexec.c \
- rename.c rename-dest-slash.c rmdir.c root-dev-ino.c rpmatch.c \
- safe-read.c safe-write.c same.c save-cwd.c savedir.c setenv.c \
- unsetenv.c settime.c sha1.c sig2str.c snprintf.c \
- mkstemp-safer.c stpcpy.c strcspn.c strdup.c strftime.c \
- strndup.c strnlen.c strpbrk.c strtod.c strtoimax.c strtol.c \
- strtoll.c strtoul.c strtoull.c strtoumax.c strverscmp.c \
- tempname.c time_r.c dup-safer.c fd-safer.c pipe-safer.c \
- unlinkdir.c userspec.c utime.c utimecmp.c utimens.c \
- asnprintf.c printf-args.c printf-parse.c vasnprintf.c \
- asprintf.c vasprintf.c xmalloc.c xgetcwd.c xnanosleep.c \
- xstrtod.c xstrtol.c xstrtoul.c xstrtod.c xstrtold.c yesno.c
-LINK_WARNING_H = $(top_srcdir)/build-aux/link-warning.h
-charset_alias = $(DESTDIR)$(libdir)/charset.alias
-charset_tmp = $(DESTDIR)$(libdir)/charset.tmp
-AM_CFLAGS = $(WARNING_CFLAGS) $(WERROR_CFLAGS)
-LDADD = $(noinst_LIBRARIES)
-all: $(BUILT_SOURCES) config.h
- $(MAKE) $(AM_MAKEFLAGS) all-am
-
-.SUFFIXES:
-.SUFFIXES: .sed .sin .c .o .obj .y
-$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(srcdir)/gnulib.mk $(am__configure_deps)
- @for dep in $?; do \
- case '$(am__configure_deps)' in \
- *$$dep*) \
- cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
- && exit 0; \
- exit 1;; \
- esac; \
- done; \
- echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnits lib/Makefile'; \
- cd $(top_srcdir) && \
- $(AUTOMAKE) --gnits lib/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
- @case '$?' in \
- *config.status*) \
- cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
- *) \
- echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
- cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
- esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
- cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure: $(am__configure_deps)
- cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4): $(am__aclocal_m4_deps)
- cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-config.h: stamp-h1
- @if test ! -f $@; then \
- rm -f stamp-h1; \
- $(MAKE) $(AM_MAKEFLAGS) stamp-h1; \
- else :; fi
-
-stamp-h1: $(srcdir)/config.hin $(top_builddir)/config.status
- @rm -f stamp-h1
- cd $(top_builddir) && $(SHELL) ./config.status lib/config.h
-$(srcdir)/config.hin: $(am__configure_deps)
- cd $(top_srcdir) && $(AUTOHEADER)
- rm -f stamp-h1
- touch $@
-
-distclean-hdr:
- -rm -f config.h stamp-h1
-
-clean-noinstLIBRARIES:
- -test -z "$(noinst_LIBRARIES)" || rm -f $(noinst_LIBRARIES)
-libcoreutils.a: $(libcoreutils_a_OBJECTS) $(libcoreutils_a_DEPENDENCIES)
- -rm -f libcoreutils.a
- $(libcoreutils_a_AR) libcoreutils.a $(libcoreutils_a_OBJECTS) $(libcoreutils_a_LIBADD)
- $(RANLIB) libcoreutils.a
-
-clean-noinstLTLIBRARIES:
- -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES)
- @list='$(noinst_LTLIBRARIES)'; for p in $$list; do \
- dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \
- test "$$dir" != "$$p" || dir=.; \
- echo "rm -f \"$${dir}/so_locations\""; \
- rm -f "$${dir}/so_locations"; \
- done
-
-clean-noinstPROGRAMS:
- -test -z "$(noinst_PROGRAMS)" || rm -f $(noinst_PROGRAMS)
-t-fpending$(EXEEXT): $(t_fpending_OBJECTS) $(t_fpending_DEPENDENCIES)
- @rm -f t-fpending$(EXEEXT)
- $(LINK) $(t_fpending_OBJECTS) $(t_fpending_LDADD) $(LIBS)
-
-mostlyclean-compile:
- -rm -f *.$(OBJEXT)
-
-distclean-compile:
- -rm -f *.tab.c
-
-@AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/alloca.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/euidaccess-stat.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/fd-reopen.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/memxfrm.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/rand-isaac.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/randint.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/randperm.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/randread.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/sha256.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/sha512.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/strintcmp.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/strnumcmp.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/xfts.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/__fpending.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/acl.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/acl_entries.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/alloca.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/allocsa.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/argmatch.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asnprintf.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/asprintf.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/at-func.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/atexit.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/backupfile.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/base64.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/basename.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/buffer-lcm.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/c-ctype.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/c-strcasecmp.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/c-strncasecmp.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/c-strtod.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/c-strtold.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/calloc.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/canon-host.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/canonicalize.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/chdir-long.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/chown.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/cloexec.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/close-stream.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/closeout.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/creat-safer.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/cycle-check.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/diacrit.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dirchownmod.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dirfd.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dirname.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dup-safer.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dup2.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/error.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/euidaccess.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/exclude.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/exitfail.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fchdir.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fchmodat.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fchown-stub.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fchownat.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fd-safer.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/file-has-acl.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/file-type.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fileblocks.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/filemode.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/filenamecat.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fnmatch.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fnmatch_loop.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fopen-safer.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fprintftime.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/free.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fstatat.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fsusage.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ftruncate.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fts-cycle.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fts.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/full-read.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/full-write.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gai_strerror.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/getaddrinfo.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/getcwd.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/getdate.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/getdelim.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/getgroups.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gethostname.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gethrxtime.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/getline.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/getloadavg.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/getndelim2.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/getopt.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/getopt1.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/getpass.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gettime.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gettimeofday.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/getugroups.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/getusershell.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/group-member.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/hard-locale.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/hash-pjw.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/hash.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/human.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/i-ring.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/idcache.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/imaxtostr.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/inet_ntop.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/inttostr.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/isapipe.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/lchown.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/linebuffer.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/localcharset.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/long-options.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/lstat.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/malloc.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/mbchar.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/mbscasecmp.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/mbswidth.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/md5.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/memcasecmp.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/memchr.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/memcmp.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/memcoll.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/memcpy.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/memmove.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/mempcpy.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/memrchr.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/memset.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/mkancesdirs.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/mkdir-p.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/mkdir.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/mkdirat.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/mkstemp-safer.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/mkstemp.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/mktime.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/modechange.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/mountlist.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/mpsort.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/nanosleep.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/obstack.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/offtostr.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/open-safer.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/openat-die.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/openat-proc.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/openat.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/physmem.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/pipe-safer.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/posixtm.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/posixver.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/printf-args.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/printf-parse.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/putenv.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/quote.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/quotearg.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/raise.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/readlink.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/readtokens.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/readtokens0.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/readutmp.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/realloc.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/regcomp.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/regex.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/regex_internal.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/regexec.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/rename-dest-slash.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/rename.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/rmdir.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/root-dev-ino.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/rpmatch.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/safe-read.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/safe-write.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/same.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/save-cwd.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/savedir.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/savewd.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/setenv.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/settime.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sha1.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sig2str.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/snprintf.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/stpcpy.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/strcspn.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/strdup.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/strftime.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/stripslash.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/strndup.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/strnlen.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/strnlen1.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/strpbrk.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/strtod.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/strtoimax.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/strtol.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/strtoll.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/strtoul.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/strtoull.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/strtoumax.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/strverscmp.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/t-fpending.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/tempname.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/time_r.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/uinttostr.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/umaxtostr.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/unicodeio.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/unlinkdir.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/unsetenv.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/userspec.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/utime.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/utimecmp.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/utimens.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/vasnprintf.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/vasprintf.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/version-etc-fsf.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/version-etc.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/xalloc-die.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/xgetcwd.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/xgethostname.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/xmalloc.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/xmemcoll.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/xmemxfrm.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/xnanosleep.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/xreadlink-with-size.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/xreadlink.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/xstrndup.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/xstrtod.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/xstrtoimax.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/xstrtol.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/xstrtold.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/xstrtoul.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/xstrtoumax.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/yesno.Po@am__quote@
-
-.c.o:
-@am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
-@am__fastdepCC_TRUE@ mv -f $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@ $(COMPILE) -c $<
-
-.c.obj:
-@am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'`
-@am__fastdepCC_TRUE@ mv -f $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'`
-
-.y.c:
- $(am__skipyacc) $(SHELL) $(YLWRAP) $< y.tab.c $@ y.tab.h $*.h y.output $*.output -- $(YACCCOMPILE)
-
-ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
- list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
- unique=`for i in $$list; do \
- if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
- done | \
- $(AWK) ' { files[$$0] = 1; } \
- END { for (i in files) print i; }'`; \
- mkid -fID $$unique
-tags: TAGS
-
-TAGS: $(HEADERS) $(SOURCES) config.hin $(TAGS_DEPENDENCIES) \
- $(TAGS_FILES) $(LISP)
- tags=; \
- here=`pwd`; \
- list='$(SOURCES) $(HEADERS) config.hin $(LISP) $(TAGS_FILES)'; \
- unique=`for i in $$list; do \
- if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
- done | \
- $(AWK) ' { files[$$0] = 1; } \
- END { for (i in files) print i; }'`; \
- if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
- test -n "$$unique" || unique=$$empty_fix; \
- $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
- $$tags $$unique; \
- fi
-ctags: CTAGS
-CTAGS: $(HEADERS) $(SOURCES) config.hin $(TAGS_DEPENDENCIES) \
- $(TAGS_FILES) $(LISP)
- tags=; \
- here=`pwd`; \
- list='$(SOURCES) $(HEADERS) config.hin $(LISP) $(TAGS_FILES)'; \
- unique=`for i in $$list; do \
- if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
- done | \
- $(AWK) ' { files[$$0] = 1; } \
- END { for (i in files) print i; }'`; \
- test -z "$(CTAGS_ARGS)$$tags$$unique" \
- || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
- $$tags $$unique
-
-GTAGS:
- here=`$(am__cd) $(top_builddir) && pwd` \
- && cd $(top_srcdir) \
- && gtags -i $(GTAGS_ARGS) $$here
-
-distclean-tags:
- -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
-
-distdir: $(DISTFILES)
- @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
- topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
- list='$(DISTFILES)'; \
- dist_files=`for file in $$list; do echo $$file; done | \
- sed -e "s|^$$srcdirstrip/||;t" \
- -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
- case $$dist_files in \
- */*) $(MKDIR_P) `echo "$$dist_files" | \
- sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
- sort -u` ;; \
- esac; \
- for file in $$dist_files; do \
- if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
- if test -d $$d/$$file; then \
- dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
- if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
- cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
- fi; \
- cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
- else \
- test -f $(distdir)/$$file \
- || cp -p $$d/$$file $(distdir)/$$file \
- || exit 1; \
- fi; \
- done
-check-am: all-am
-check: $(BUILT_SOURCES)
- $(MAKE) $(AM_MAKEFLAGS) check-am
-all-am: Makefile $(LIBRARIES) $(LTLIBRARIES) $(PROGRAMS) $(HEADERS) \
- config.h all-local
-installdirs:
-install: $(BUILT_SOURCES)
- $(MAKE) $(AM_MAKEFLAGS) install-am
-install-exec: install-exec-am
-install-data: install-data-am
-uninstall: uninstall-am
-
-install-am: all-am
- @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-am
-install-strip:
- $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
- install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
- `test -z '$(STRIP)' || \
- echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
-mostlyclean-generic:
- -test -z "$(MOSTLYCLEANFILES)" || rm -f $(MOSTLYCLEANFILES)
-
-clean-generic:
- -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES)
-
-distclean-generic:
- -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
- -test -z "$(DISTCLEANFILES)" || rm -f $(DISTCLEANFILES)
-
-maintainer-clean-generic:
- @echo "This command is intended for maintainers to use"
- @echo "it deletes files that may require special tools to rebuild."
- -rm -f getdate.c
- -test -z "$(BUILT_SOURCES)" || rm -f $(BUILT_SOURCES)
- -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES)
-clean: clean-am
-
-clean-am: clean-generic clean-noinstLIBRARIES clean-noinstLTLIBRARIES \
- clean-noinstPROGRAMS mostlyclean-am
-
-distclean: distclean-am
- -rm -rf $(DEPDIR) ./$(DEPDIR)
- -rm -f Makefile
-distclean-am: clean-am distclean-compile distclean-generic \
- distclean-hdr distclean-tags
-
-dvi: dvi-am
-
-dvi-am:
-
-html: html-am
-
-info: info-am
-
-info-am:
-
-install-data-am:
-
-install-dvi: install-dvi-am
-
-install-exec-am: install-exec-local
-
-install-html: install-html-am
-
-install-info: install-info-am
-
-install-man:
-
-install-pdf: install-pdf-am
-
-install-ps: install-ps-am
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-am
- -rm -rf $(DEPDIR) ./$(DEPDIR)
- -rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-am
-
-mostlyclean-am: mostlyclean-compile mostlyclean-generic \
- mostlyclean-local
-
-pdf: pdf-am
-
-pdf-am:
-
-ps: ps-am
-
-ps-am:
-
-uninstall-am: uninstall-local
-
-.MAKE: install-am install-strip
-
-.PHONY: CTAGS GTAGS all all-am all-local check check-am clean \
- clean-generic clean-noinstLIBRARIES clean-noinstLTLIBRARIES \
- clean-noinstPROGRAMS ctags distclean distclean-compile \
- distclean-generic distclean-hdr distclean-tags distdir dvi \
- dvi-am html html-am info info-am install install-am \
- install-data install-data-am install-dvi install-dvi-am \
- install-exec install-exec-am install-exec-local install-html \
- install-html-am install-info install-info-am install-man \
- install-pdf install-pdf-am install-ps install-ps-am \
- install-strip installcheck installcheck-am installdirs \
- maintainer-clean maintainer-clean-generic mostlyclean \
- mostlyclean-compile mostlyclean-generic mostlyclean-local pdf \
- pdf-am ps ps-am tags uninstall uninstall-am uninstall-local
-
-
-# We need the following in order to create <alloca.h> when the system
-# doesn't have one that works with the given compiler.
-alloca.h: alloca_.h
- { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
- cat $(srcdir)/alloca_.h; \
- } > $@-t
- mv -f $@-t $@
-
-# We need the following in order to create <arpa/inet.h> when the system
-# doesn't have one.
-arpa/inet.h:
- @MKDIR_P@ arpa
- rm -f $@-t $@
- { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
- echo '#include <sys/socket.h>'; \
- } > $@-t
- mv $@-t $@
-
-# Retrieve values of the variables through 'configure' followed by
-# 'make', not directly through 'configure', so that a user who
-# sets some of these variables consistently on the 'make' command
-# line gets correct results.
-#
-# One advantage of this approach, compared to the classical
-# approach of adding -DLIBDIR=\"$(libdir)\" etc. to AM_CPPFLAGS,
-# is that it protects against the use of undefined variables.
-# If, say, $(libdir) is not set in the Makefile, LIBDIR is not
-# defined by this module, and code using LIBDIR gives a
-# compilation error.
-#
-# Another advantage is that 'make' output is shorter.
-#
-# Listed in the same order as the GNU makefile conventions.
-# The Automake-defined pkg* macros are appended, in the order
-# listed in the Automake 1.10a+ documentation.
-configmake.h: Makefile
- rm -f $@-t $@
- { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
- echo '#define PREFIX "$(prefix)"'; \
- echo '#define EXEC_PREFIX "$(exec_prefix)"'; \
- echo '#define BINDIR "$(bindir)"'; \
- echo '#define SBINDIR "$(sbindir)"'; \
- echo '#define LIBEXECDIR "$(libexecdir)"'; \
- echo '#define DATAROOTDIR "$(datarootdir)"'; \
- echo '#define DATADIR "$(datadir)"'; \
- echo '#define SYSCONFDIR "$(sysconfdir)"'; \
- echo '#define SHAREDSTATEDIR "$(sharedstatedir)"'; \
- echo '#define LOCALSTATEDIR "$(localstatedir)"'; \
- echo '#define INCLUDEDIR "$(includedir)"'; \
- echo '#define OLDINCLUDEDIR "$(oldincludedir)"'; \
- echo '#define DOCDIR "$(docdir)"'; \
- echo '#define INFODIR "$(infodir)"'; \
- echo '#define HTMLDIR "$(htmldir)"'; \
- echo '#define DVIDIR "$(dvidir)"'; \
- echo '#define PDFDIR "$(pdfdir)"'; \
- echo '#define PSDIR "$(psdir)"'; \
- echo '#define LIBDIR "$(libdir)"'; \
- echo '#define LISPDIR "$(lispdir)"'; \
- echo '#define LOCALEDIR "$(localedir)"'; \
- echo '#define MANDIR "$(mandir)"'; \
- echo '#define MANEXT "$(manext)"'; \
- echo '#define PKGDATADIR "$(pkgdatadir)"'; \
- echo '#define PKGINCLUDEDIR "$(pkgincludedir)"'; \
- echo '#define PKGLIBDIR "$(pkglibdir)"'; \
- echo '#define PKGLIBEXECDIR "$(pkglibexecdir)"'; \
- } | sed '/""/d' > $@-t
- mv $@-t $@
-
-# We need the following in order to create <dirent.h> when the system
-# doesn't have one that works with the given compiler.
-dirent.h: dirent_.h
- rm -f $@-t $@
- { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
- sed -e 's|@''ABSOLUTE_DIRENT_H''@|$(ABSOLUTE_DIRENT_H)|g' \
- -e 's|@''REPLACE_FCHDIR''@|$(REPLACE_FCHDIR)|g' \
- < $(srcdir)/dirent_.h; \
- } > $@-t
- mv $@-t $@
-
-# We need the following in order to create <fcntl.h> when the system
-# doesn't have one that works with the given compiler.
-fcntl.h: fcntl_.h
- rm -f $@-t $@
- { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
- sed -e 's|@''ABSOLUTE_FCNTL_H''@|$(ABSOLUTE_FCNTL_H)|g' \
- < $(srcdir)/fcntl_.h; \
- } > $@-t
- mv $@-t $@
-
-# We need the following in order to create <fnmatch.h> when the system
-# doesn't have one that supports the required API.
-fnmatch.h: fnmatch_.h
- { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
- cat $(srcdir)/fnmatch_.h; \
- } > $@-t
- mv -f $@-t $@
-
-# We need the following in order to create <getopt.h> when the system
-# doesn't have one that works with the given compiler.
-getopt.h: getopt_.h
- { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
- cat $(srcdir)/getopt_.h; \
- } > $@-t
- mv -f $@-t $@
-
-# We need the following in order to create <inttypes.h> when the system
-# doesn't have one that works with the given compiler.
-inttypes.h: inttypes_.h
- rm -f $@-t $@
- { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
- sed -e 's/@''HAVE_INTTYPES_H''@/$(HAVE_INTTYPES_H)/g' \
- -e 's|@''ABSOLUTE_INTTYPES_H''@|$(ABSOLUTE_INTTYPES_H)|g' \
- -e 's/@''PRI_MACROS_BROKEN''@/$(PRI_MACROS_BROKEN)/g' \
- -e 's/@''HAVE_LONG_LONG_INT''@/$(HAVE_LONG_LONG_INT)/g' \
- -e 's/@''HAVE_UNSIGNED_LONG_LONG_INT''@/$(HAVE_UNSIGNED_LONG_LONG_INT)/g' \
- -e 's/@''PRIPTR_PREFIX''@/$(PRIPTR_PREFIX)/g' \
- -e 's/@''GNULIB_IMAXABS''@/$(GNULIB_IMAXABS)/g' \
- -e 's/@''GNULIB_IMAXDIV''@/$(GNULIB_IMAXDIV)/g' \
- -e 's/@''GNULIB_STRTOIMAX''@/$(GNULIB_STRTOIMAX)/g' \
- -e 's/@''GNULIB_STRTOUMAX''@/$(GNULIB_STRTOUMAX)/g' \
- -e 's/@''HAVE_DECL_IMAXABS''@/$(HAVE_DECL_IMAXABS)/g' \
- -e 's/@''HAVE_DECL_IMAXDIV''@/$(HAVE_DECL_IMAXDIV)/g' \
- -e 's/@''HAVE_DECL_STRTOIMAX''@/$(HAVE_DECL_STRTOIMAX)/g' \
- -e 's/@''HAVE_DECL_STRTOUMAX''@/$(HAVE_DECL_STRTOUMAX)/g' \
- -e '/definition of GL_LINK_WARNING/r $(LINK_WARNING_H)' \
- < $(srcdir)/inttypes_.h; \
- } > $@-t
- mv $@-t $@
-
-# We need the following in order to install a simple file in $(libdir)
-# which is shared with other installed packages. We use a list of referencing
-# packages so that "make uninstall" will remove the file if and only if it
-# is not used by another installed package.
-# On systems with glibc-2.1 or newer, the file is redundant, therefore we
-# avoid installing it.
-
-all-local: charset.alias ref-add.sed ref-del.sed
-install-exec-local: all-local
- test $(GLIBC21) != no || $(mkinstalldirs) $(DESTDIR)$(libdir)
- if test -f $(charset_alias); then \
- sed -f ref-add.sed $(charset_alias) > $(charset_tmp) ; \
- $(INSTALL_DATA) $(charset_tmp) $(charset_alias) ; \
- rm -f $(charset_tmp) ; \
- else \
- if test $(GLIBC21) = no; then \
- sed -f ref-add.sed charset.alias > $(charset_tmp) ; \
- $(INSTALL_DATA) $(charset_tmp) $(charset_alias) ; \
- rm -f $(charset_tmp) ; \
- fi ; \
- fi
-
-uninstall-local: all-local
- if test -f $(charset_alias); then \
- sed -f ref-del.sed $(charset_alias) > $(charset_tmp); \
- if grep '^# Packages using this file: $$' $(charset_tmp) \
- > /dev/null; then \
- rm -f $(charset_alias); \
- else \
- $(INSTALL_DATA) $(charset_tmp) $(charset_alias); \
- fi; \
- rm -f $(charset_tmp); \
- fi
-
-charset.alias: config.charset
- rm -f t-$@ $@
- $(SHELL) $(srcdir)/config.charset '$(host)' > t-$@
- mv t-$@ $@
-.sin.sed:
- rm -f t-$@ $@
- sed -e '/^#/d' -e 's/@''PACKAGE''@/$(PACKAGE)/g' $< > t-$@
- mv t-$@ $@
-
-# We need the following in order to create <netinet/in.h> when the system
-# doesn't have one.
-netinet/in.h:
- @MKDIR_P@ netinet
- rm -f $@-t $@
- { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
- sed -e 's|@''ABSOLUTE_NETINET_IN_H''@|$(ABSOLUTE_NETINET_IN_H)|g' \
- -e 's|@''HAVE_NETINET_IN_H''@|$(HAVE_NETINET_IN_H)|g' \
- < $(srcdir)/netinet_in_.h; \
- } > $@-t
- mv $@-t $@
-
-# We need the following in order to create <stdbool.h> when the system
-# doesn't have one that works.
-stdbool.h: stdbool_.h
- rm -f $@-t $@
- { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
- sed -e 's/@''HAVE__BOOL''@/$(HAVE__BOOL)/g' < $(srcdir)/stdbool_.h; \
- } > $@-t
- mv $@-t $@
-
-# We need the following in order to create <stdint.h> when the system
-# doesn't have one that works with the given compiler.
-stdint.h: stdint_.h
- rm -f $@-t $@
- { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
- sed -e 's/@''HAVE_STDINT_H''@/$(HAVE_STDINT_H)/g' \
- -e 's|@''ABSOLUTE_STDINT_H''@|$(ABSOLUTE_STDINT_H)|g' \
- -e 's/@''HAVE_SYS_TYPES_H''@/$(HAVE_SYS_TYPES_H)/g' \
- -e 's/@''HAVE_INTTYPES_H''@/$(HAVE_INTTYPES_H)/g' \
- -e 's/@''HAVE_SYS_INTTYPES_H''@/$(HAVE_SYS_INTTYPES_H)/g' \
- -e 's/@''HAVE_SYS_BITYPES_H''@/$(HAVE_SYS_BITYPES_H)/g' \
- -e 's/@''HAVE_LONG_LONG_INT''@/$(HAVE_LONG_LONG_INT)/g' \
- -e 's/@''HAVE_UNSIGNED_LONG_LONG_INT''@/$(HAVE_UNSIGNED_LONG_LONG_INT)/g' \
- -e 's/@''BITSIZEOF_PTRDIFF_T''@/$(BITSIZEOF_PTRDIFF_T)/g' \
- -e 's/@''PTRDIFF_T_SUFFIX''@/$(PTRDIFF_T_SUFFIX)/g' \
- -e 's/@''BITSIZEOF_SIG_ATOMIC_T''@/$(BITSIZEOF_SIG_ATOMIC_T)/g' \
- -e 's/@''HAVE_SIGNED_SIG_ATOMIC_T''@/$(HAVE_SIGNED_SIG_ATOMIC_T)/g' \
- -e 's/@''SIG_ATOMIC_T_SUFFIX''@/$(SIG_ATOMIC_T_SUFFIX)/g' \
- -e 's/@''BITSIZEOF_SIZE_T''@/$(BITSIZEOF_SIZE_T)/g' \
- -e 's/@''SIZE_T_SUFFIX''@/$(SIZE_T_SUFFIX)/g' \
- -e 's/@''BITSIZEOF_WCHAR_T''@/$(BITSIZEOF_WCHAR_T)/g' \
- -e 's/@''HAVE_SIGNED_WCHAR_T''@/$(HAVE_SIGNED_WCHAR_T)/g' \
- -e 's/@''WCHAR_T_SUFFIX''@/$(WCHAR_T_SUFFIX)/g' \
- -e 's/@''BITSIZEOF_WINT_T''@/$(BITSIZEOF_WINT_T)/g' \
- -e 's/@''HAVE_SIGNED_WINT_T''@/$(HAVE_SIGNED_WINT_T)/g' \
- -e 's/@''WINT_T_SUFFIX''@/$(WINT_T_SUFFIX)/g' \
- < $(srcdir)/stdint_.h; \
- } > $@-t
- mv $@-t $@
-
-# We need the following in order to create <stdio.h> when the system
-# doesn't have one that works with the given compiler.
-stdio.h: stdio_.h
- rm -f $@-t $@
- { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */' && \
- sed -e 's|@''ABSOLUTE_STDIO_H''@|$(ABSOLUTE_STDIO_H)|g' \
- -e 's|@''GNULIB_FPRINTF_POSIX''@|$(GNULIB_FPRINTF_POSIX)|g' \
- -e 's|@''GNULIB_PRINTF_POSIX''@|$(GNULIB_PRINTF_POSIX)|g' \
- -e 's|@''GNULIB_SNPRINTF''@|$(GNULIB_SNPRINTF)|g' \
- -e 's|@''GNULIB_SPRINTF_POSIX''@|$(GNULIB_SPRINTF_POSIX)|g' \
- -e 's|@''GNULIB_VFPRINTF_POSIX''@|$(GNULIB_VFPRINTF_POSIX)|g' \
- -e 's|@''GNULIB_VPRINTF_POSIX''@|$(GNULIB_VPRINTF_POSIX)|g' \
- -e 's|@''GNULIB_VSNPRINTF''@|$(GNULIB_VSNPRINTF)|g' \
- -e 's|@''GNULIB_VSPRINTF_POSIX''@|$(GNULIB_VSPRINTF_POSIX)|g' \
- -e 's|@''REPLACE_FPRINTF''@|$(REPLACE_FPRINTF)|g' \
- -e 's|@''REPLACE_VFPRINTF''@|$(REPLACE_VFPRINTF)|g' \
- -e 's|@''REPLACE_PRINTF''@|$(REPLACE_PRINTF)|g' \
- -e 's|@''REPLACE_VPRINTF''@|$(REPLACE_VPRINTF)|g' \
- -e 's|@''REPLACE_SNPRINTF''@|$(REPLACE_SNPRINTF)|g' \
- -e 's|@''HAVE_DECL_SNPRINTF''@|$(HAVE_DECL_SNPRINTF)|g' \
- -e 's|@''REPLACE_VSNPRINTF''@|$(REPLACE_VSNPRINTF)|g' \
- -e 's|@''HAVE_DECL_VSNPRINTF''@|$(HAVE_DECL_VSNPRINTF)|g' \
- -e 's|@''REPLACE_SPRINTF''@|$(REPLACE_SPRINTF)|g' \
- -e 's|@''REPLACE_VSPRINTF''@|$(REPLACE_VSPRINTF)|g' \
- -e '/definition of GL_LINK_WARNING/r $(LINK_WARNING_H)' \
- < $(srcdir)/stdio_.h; \
- } > $@-t
- mv $@-t $@
-
-# We need the following in order to create <stdlib.h> when the system
-# doesn't have one that works with the given compiler.
-stdlib.h: stdlib_.h
- rm -f $@-t $@
- { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */' && \
- sed -e 's|@''ABSOLUTE_STDLIB_H''@|$(ABSOLUTE_STDLIB_H)|g' \
- -e 's|@''GNULIB_GETSUBOPT''@|$(GNULIB_GETSUBOPT)|g' \
- -e 's|@''GNULIB_MKDTEMP''@|$(GNULIB_MKDTEMP)|g' \
- -e 's|@''GNULIB_MKSTEMP''@|$(GNULIB_MKSTEMP)|g' \
- -e 's|@''HAVE_GETSUBOPT''@|$(HAVE_GETSUBOPT)|g' \
- -e 's|@''HAVE_MKDTEMP''@|$(HAVE_MKDTEMP)|g' \
- -e 's|@''REPLACE_MKSTEMP''@|$(REPLACE_MKSTEMP)|g' \
- -e '/definition of GL_LINK_WARNING/r $(LINK_WARNING_H)' \
- < $(srcdir)/stdlib_.h; \
- } > $@-t
- mv $@-t $@
-
-# We need the following in order to create <string.h> when the system
-# doesn't have one that works with the given compiler.
-string.h: string_.h
- rm -f $@-t $@
- { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */' && \
- sed -e 's|@''ABSOLUTE_STRING_H''@|$(ABSOLUTE_STRING_H)|g' \
- -e 's|@''GNULIB_MBSLEN''@|$(GNULIB_MBSLEN)|g' \
- -e 's|@''GNULIB_MBSCHR''@|$(GNULIB_MBSCHR)|g' \
- -e 's|@''GNULIB_MBSRCHR''@|$(GNULIB_MBSRCHR)|g' \
- -e 's|@''GNULIB_MBSSTR''@|$(GNULIB_MBSSTR)|g' \
- -e 's|@''GNULIB_MBSCASECMP''@|$(GNULIB_MBSCASECMP)|g' \
- -e 's|@''GNULIB_MBSNCASECMP''@|$(GNULIB_MBSNCASECMP)|g' \
- -e 's|@''GNULIB_MBSPCASECMP''@|$(GNULIB_MBSPCASECMP)|g' \
- -e 's|@''GNULIB_MBSCASESTR''@|$(GNULIB_MBSCASESTR)|g' \
- -e 's|@''GNULIB_MBSCSPN''@|$(GNULIB_MBSCSPN)|g' \
- -e 's|@''GNULIB_MBSPBRK''@|$(GNULIB_MBSPBRK)|g' \
- -e 's|@''GNULIB_MBSSPN''@|$(GNULIB_MBSSPN)|g' \
- -e 's|@''GNULIB_MBSSEP''@|$(GNULIB_MBSSEP)|g' \
- -e 's|@''GNULIB_MBSTOK_R''@|$(GNULIB_MBSTOK_R)|g' \
- -e 's|@''GNULIB_MEMMEM''@|$(GNULIB_MEMMEM)|g' \
- -e 's|@''GNULIB_MEMPCPY''@|$(GNULIB_MEMPCPY)|g' \
- -e 's|@''GNULIB_MEMRCHR''@|$(GNULIB_MEMRCHR)|g' \
- -e 's|@''GNULIB_STPCPY''@|$(GNULIB_STPCPY)|g' \
- -e 's|@''GNULIB_STPNCPY''@|$(GNULIB_STPNCPY)|g' \
- -e 's|@''GNULIB_STRCHRNUL''@|$(GNULIB_STRCHRNUL)|g' \
- -e 's|@''GNULIB_STRDUP''@|$(GNULIB_STRDUP)|g' \
- -e 's|@''GNULIB_STRNDUP''@|$(GNULIB_STRNDUP)|g' \
- -e 's|@''GNULIB_STRNLEN''@|$(GNULIB_STRNLEN)|g' \
- -e 's|@''GNULIB_STRPBRK''@|$(GNULIB_STRPBRK)|g' \
- -e 's|@''GNULIB_STRSEP''@|$(GNULIB_STRSEP)|g' \
- -e 's|@''GNULIB_STRCASESTR''@|$(GNULIB_STRCASESTR)|g' \
- -e 's|@''GNULIB_STRTOK_R''@|$(GNULIB_STRTOK_R)|g' \
- -e 's|@''HAVE_DECL_MEMMEM''@|$(HAVE_DECL_MEMMEM)|g' \
- -e 's|@''HAVE_MEMPCPY''@|$(HAVE_MEMPCPY)|g' \
- -e 's|@''HAVE_DECL_MEMRCHR''@|$(HAVE_DECL_MEMRCHR)|g' \
- -e 's|@''HAVE_STPCPY''@|$(HAVE_STPCPY)|g' \
- -e 's|@''HAVE_STPNCPY''@|$(HAVE_STPNCPY)|g' \
- -e 's|@''HAVE_STRCASECMP''@|$(HAVE_STRCASECMP)|g' \
- -e 's|@''HAVE_DECL_STRNCASECMP''@|$(HAVE_DECL_STRNCASECMP)|g' \
- -e 's|@''HAVE_STRCHRNUL''@|$(HAVE_STRCHRNUL)|g' \
- -e 's|@''HAVE_DECL_STRDUP''@|$(HAVE_DECL_STRDUP)|g' \
- -e 's|@''HAVE_STRNDUP''@|$(HAVE_STRNDUP)|g' \
- -e 's|@''HAVE_DECL_STRNDUP''@|$(HAVE_DECL_STRNDUP)|g' \
- -e 's|@''HAVE_DECL_STRNLEN''@|$(HAVE_DECL_STRNLEN)|g' \
- -e 's|@''HAVE_STRPBRK''@|$(HAVE_STRPBRK)|g' \
- -e 's|@''HAVE_STRSEP''@|$(HAVE_STRSEP)|g' \
- -e 's|@''HAVE_STRCASESTR''@|$(HAVE_STRCASESTR)|g' \
- -e 's|@''HAVE_DECL_STRTOK_R''@|$(HAVE_DECL_STRTOK_R)|g' \
- -e '/definition of GL_LINK_WARNING/r $(LINK_WARNING_H)' \
- < $(srcdir)/string_.h; \
- } > $@-t
- mv $@-t $@
-
-# We need the following in order to create <sys/socket.h> when the system
-# doesn't have one that works with the given compiler.
-sys/socket.h: socket_.h
- @MKDIR_P@ sys
- { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
- sed -e 's|@''ABSOLUTE_SYS_SOCKET_H''@|$(ABSOLUTE_SYS_SOCKET_H)|g' \
- -e 's|@''HAVE_SYS_SOCKET_H''@|$(HAVE_SYS_SOCKET_H)|g' \
- -e 's|@''HAVE_WINSOCK2_H''@|$(HAVE_WINSOCK2_H)|g' \
- -e 's|@''HAVE_WS2TCPIP_H''@|$(HAVE_WS2TCPIP_H)|g' \
- < $(srcdir)/socket_.h; \
- } > $@-t
- mv -f $@-t $@
-
-# We need the following in order to create <sys/stat.h> when the system
-# has one that is incomplete.
-sys/stat.h: stat_.h
- @MKDIR_P@ sys
- rm -f $@-t $@
- { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
- sed -e 's|@''ABSOLUTE_SYS_STAT_H''@|$(ABSOLUTE_SYS_STAT_H)|g' \
- < $(srcdir)/stat_.h; \
- } > $@-t
- mv $@-t $@
-
-# We need the following in order to create <sys/time.h> when the system
-# doesn't have one that works with the given compiler.
-sys/time.h: sys_time_.h
- @MKDIR_P@ sys
- rm -f $@-t $@
- { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
- sed -e 's/@''HAVE_SYS_TIME_H''@/$(HAVE_SYS_TIME_H)/g' \
- -e 's|@''ABSOLUTE_SYS_TIME_H''@|$(ABSOLUTE_SYS_TIME_H)|g' \
- -e 's/@''REPLACE_GETTIMEOFDAY''@/$(REPLACE_GETTIMEOFDAY)/g' \
- -e 's/@''HAVE_STRUCT_TIMEVAL''@/$(HAVE_STRUCT_TIMEVAL)/g' \
- < $(srcdir)/sys_time_.h; \
- } > $@-t
- mv $@-t $@
-
-# We need the following in order to create <time.h> when the system
-# doesn't have one that works with the given compiler.
-time.h: time_.h
- rm -f $@-t $@
- { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */' && \
- sed -e 's|@ABSOLUTE_TIME_H''@|$(ABSOLUTE_TIME_H)|g' \
- -e 's|@REPLACE_LOCALTIME_R''@|$(REPLACE_LOCALTIME_R)|g' \
- -e 's|@REPLACE_NANOSLEEP''@|$(REPLACE_NANOSLEEP)|g' \
- -e 's|@REPLACE_STRPTIME''@|$(REPLACE_STRPTIME)|g' \
- -e 's|@REPLACE_TIMEGM''@|$(REPLACE_TIMEGM)|g' \
- -e 's|@SYS_TIME_H_DEFINES_STRUCT_TIMESPEC''@|$(SYS_TIME_H_DEFINES_STRUCT_TIMESPEC)|g' \
- -e 's|@TIME_H_DEFINES_STRUCT_TIMESPEC''@|$(TIME_H_DEFINES_STRUCT_TIMESPEC)|g' \
- < $(srcdir)/time_.h; \
- } > $@-t
- mv $@-t $@
-
-# We need the following in order to create an empty placeholder for
-# <unistd.h> when the system doesn't have one.
-unistd.h: unistd_.h
- rm -f $@-t $@
- { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
- sed -e 's|@''HAVE_UNISTD_H''@|$(HAVE_UNISTD_H)|g' \
- -e 's|@''ABSOLUTE_UNISTD_H''@|$(ABSOLUTE_UNISTD_H)|g' \
- -e 's|@''GNULIB_CHOWN''@|$(GNULIB_CHOWN)|g' \
- -e 's|@''GNULIB_DUP2''@|$(GNULIB_DUP2)|g' \
- -e 's|@''GNULIB_FCHDIR''@|$(GNULIB_FCHDIR)|g' \
- -e 's|@''GNULIB_FTRUNCATE''@|$(GNULIB_FTRUNCATE)|g' \
- -e 's|@''GNULIB_GETCWD''@|$(GNULIB_GETCWD)|g' \
- -e 's|@''GNULIB_GETLOGIN_R''@|$(GNULIB_GETLOGIN_R)|g' \
- -e 's|@''GNULIB_READLINK''@|$(GNULIB_READLINK)|g' \
- -e 's|@''HAVE_DUP2''@|$(HAVE_DUP2)|g' \
- -e 's|@''HAVE_FTRUNCATE''@|$(HAVE_FTRUNCATE)|g' \
- -e 's|@''HAVE_READLINK''@|$(HAVE_READLINK)|g' \
- -e 's|@''HAVE_DECL_GETLOGIN_R''@|$(HAVE_DECL_GETLOGIN_R)|g' \
- -e 's|@''REPLACE_CHOWN''@|$(REPLACE_CHOWN)|g' \
- -e 's|@''REPLACE_FCHDIR''@|$(REPLACE_FCHDIR)|g' \
- -e 's|@''REPLACE_GETCWD''@|$(REPLACE_GETCWD)|g' \
- < $(srcdir)/unistd_.h; \
- } > $@-t
- mv $@-t $@
-
-# We need the following in order to create <wchar.h> when the system
-# version does not work standalone.
-wchar.h: wchar_.h
- rm -f $@-t $@
- { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
- sed -e 's|@''ABSOLUTE_WCHAR_H''@|$(ABSOLUTE_WCHAR_H)|g' \
- < $(srcdir)/wchar_.h; \
- } > $@-t
- mv $@-t $@
-
-# We need the following in order to create <wctype.h> when the system
-# doesn't have one that works with the given compiler.
-wctype.h: wctype_.h
- rm -f $@-t $@
- { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
- sed -e 's/@''HAVE_WCTYPE_H''@/$(HAVE_WCTYPE_H)/g' \
- -e 's|@''ABSOLUTE_WCTYPE_H''@|$(ABSOLUTE_WCTYPE_H)|g' \
- -e 's/@''HAVE_WCTYPE_CTMP_BUG''@/$(HAVE_WCTYPE_CTMP_BUG)/g' \
- -e 's/@''HAVE_WINT_T''@/$(HAVE_WINT_T)/g' \
- < $(srcdir)/wctype_.h; \
- } > $@-t
- mv $@-t $@
-
-mostlyclean-local: mostlyclean-generic
- @for dir in '' $(MOSTLYCLEANDIRS); do \
- if test -n "$$dir" && test -d $$dir; then \
- echo "rmdir $$dir"; rmdir $$dir; \
- fi; \
- done
-
-check: unit-test
-
-.PHONY: unit-test
-unit-test: t-fpending
- ./t-fpending > /dev/null
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/lib/TODO b/lib/TODO
deleted file mode 100644
index 4da5d0c..0000000
--- a/lib/TODO
+++ /dev/null
@@ -1,40 +0,0 @@
-Things to do to hash.c:
-
-Always use curly braces around statements in if/else/while/do/etc.
-that span more than a line -- even around multiline simple statements
-or single-line simple statements preceded by a comment line.
-
-Never have lines longer than 80 chars.
-
-Remove ^L characters. We don't want/need such crutches.
-Get a good (smart) pagination filter. I have one (a perl script)
-that usually does a decent job for me -- I called it something
-like stdc-print and think I sent you an early verison.
-
-I don't like the name `cursor'. I much prefer short names
-like `p' for index variables. I doubt I'll change all of them,
-but thought you should know why some will probably end up changing.
-
-#define USE_OBSTACK somewhere
-
-Fix this comment. Depending on system and application...
-Mention fragmentation.
- +#if USE_OBSTACK
- + /* Whenever obstacks are used, it is possible to allocate all overflowed
- + entries into a single stack, so they all can be freed in a single
- + operation. It is not clear if the speedup is worth the trouble. */
- + struct obstack entry_stack;
- +#endif
-
-
-assert (bucket_limit - bucket == n_buckets) ?
-
-remove.c: s/done/successful or ok
-
-
------
-Copyright (C) 1998 Free Software Foundation, Inc.
-
-Copying and distribution of this file, with or without
-modification, are permitted provided the copyright notice
-and this notice are preserved.
diff --git a/lib/__fpending.h b/lib/__fpending.h
deleted file mode 100644
index 8a8aabc..0000000
--- a/lib/__fpending.h
+++ /dev/null
@@ -1,34 +0,0 @@
-/* Declare __fpending.
-
- Copyright (C) 2000, 2003, 2005, 2006 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-
- Written by Jim Meyering. */
-
-#include <stddef.h>
-#include <stdio.h>
-
-#ifndef HAVE_DECL___FPENDING
-"this configure-time declaration test was not run"
-#endif
-
-#if HAVE_DECL___FPENDING
-# if HAVE_STDIO_EXT_H
-# include <stdio_ext.h>
-# endif
-#else
-size_t __fpending (FILE *);
-#endif
diff --git a/lib/acl-errno-valid.c b/lib/acl-errno-valid.c
new file mode 100644
index 0000000..086f75f
--- /dev/null
+++ b/lib/acl-errno-valid.c
@@ -0,0 +1,52 @@
+/* Test whether ACLs are well supported on this system.
+
+ Copyright 2013-2016 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 <http://www.gnu.org/licenses/>.
+
+ Written by Paul Eggert. */
+
+#include <config.h>
+
+#include <acl.h>
+
+#include <errno.h>
+
+/* Return true if errno value ERRNUM indicates that ACLs are well
+ supported on this system. ERRNUM should be an errno value obtained
+ after an ACL-related system call fails. */
+bool
+acl_errno_valid (int errnum)
+{
+ /* Recognize some common errors such as from an NFS mount that does
+ not support ACLs, even when local drives do. */
+ switch (errnum)
+ {
+ case EBUSY: return false;
+ case EINVAL: return false;
+#if defined __APPLE__ && defined __MACH__
+ case ENOENT: return false;
+#endif
+ case ENOSYS: return false;
+
+#if defined ENOTSUP && ENOTSUP != EOPNOTSUPP
+# if ENOTSUP != ENOSYS /* Needed for the MS-Windows port of GNU Emacs. */
+ case ENOTSUP: return false;
+# endif
+#endif
+
+ case EOPNOTSUPP: return false;
+ default: return true;
+ }
+}
diff --git a/lib/acl-internal.c b/lib/acl-internal.c
new file mode 100644
index 0000000..4de60c3
--- /dev/null
+++ b/lib/acl-internal.c
@@ -0,0 +1,507 @@
+/* Test whether a file has a nontrivial ACL. -*- coding: utf-8 -*-
+
+ Copyright (C) 2002-2003, 2005-2016 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 <http://www.gnu.org/licenses/>.
+
+ Written by Paul Eggert, Andreas Grünbacher, and Bruno Haible. */
+
+#include <config.h>
+
+#include "acl.h"
+
+#include "acl-internal.h"
+
+#if USE_ACL && HAVE_ACL_GET_FILE
+
+# if HAVE_ACL_TYPE_EXTENDED /* Mac OS X */
+
+/* ACL is an ACL, from a file, stored as type ACL_TYPE_EXTENDED.
+ Return 1 if the given ACL is non-trivial.
+ Return 0 if it is trivial. */
+int
+acl_extended_nontrivial (acl_t acl)
+{
+ /* acl is non-trivial if it is non-empty. */
+ return (acl_entries (acl) > 0);
+}
+
+# else /* Linux, FreeBSD, IRIX, Tru64 */
+
+/* ACL is an ACL, from a file, stored as type ACL_TYPE_ACCESS.
+ Return 1 if the given ACL is non-trivial.
+ Return 0 if it is trivial, i.e. equivalent to a simple stat() mode.
+ Return -1 and set errno upon failure to determine it. */
+int
+acl_access_nontrivial (acl_t acl)
+{
+ /* acl is non-trivial if it has some entries other than for "user::",
+ "group::", and "other::". Normally these three should be present
+ at least, allowing us to write
+ return (3 < acl_entries (acl));
+ but the following code is more robust. */
+# if HAVE_ACL_FIRST_ENTRY /* Linux, FreeBSD */
+
+ acl_entry_t ace;
+ int got_one;
+
+ for (got_one = acl_get_entry (acl, ACL_FIRST_ENTRY, &ace);
+ got_one > 0;
+ got_one = acl_get_entry (acl, ACL_NEXT_ENTRY, &ace))
+ {
+ acl_tag_t tag;
+ if (acl_get_tag_type (ace, &tag) < 0)
+ return -1;
+ if (!(tag == ACL_USER_OBJ || tag == ACL_GROUP_OBJ || tag == ACL_OTHER))
+ return 1;
+ }
+ return got_one;
+
+# elif HAVE_ACL_TO_SHORT_TEXT /* IRIX */
+ /* Don't use acl_get_entry: it is undocumented. */
+
+ int count = acl->acl_cnt;
+ int i;
+
+ for (i = 0; i < count; i++)
+ {
+ acl_entry_t ace = &acl->acl_entry[i];
+ acl_tag_t tag = ace->ae_tag;
+
+ if (!(tag == ACL_USER_OBJ || tag == ACL_GROUP_OBJ
+ || tag == ACL_OTHER_OBJ))
+ return 1;
+ }
+ return 0;
+
+# elif HAVE_ACL_FREE_TEXT /* Tru64 */
+ /* Don't use acl_get_entry: it takes only one argument and does not work. */
+
+ int count = acl->acl_num;
+ acl_entry_t ace;
+
+ for (ace = acl->acl_first; count > 0; ace = ace->next, count--)
+ {
+ acl_tag_t tag;
+ acl_perm_t perm;
+
+ tag = ace->entry->acl_type;
+ if (!(tag == ACL_USER_OBJ || tag == ACL_GROUP_OBJ || tag == ACL_OTHER))
+ return 1;
+
+ perm = ace->entry->acl_perm;
+ /* On Tru64, perm can also contain non-standard bits such as
+ PERM_INSERT, PERM_DELETE, PERM_MODIFY, PERM_LOOKUP, ... */
+ if ((perm & ~(ACL_READ | ACL_WRITE | ACL_EXECUTE)) != 0)
+ return 1;
+ }
+ return 0;
+
+# else
+
+ errno = ENOSYS;
+ return -1;
+# endif
+}
+
+int
+acl_default_nontrivial (acl_t acl)
+{
+ /* acl is non-trivial if it is non-empty. */
+ return (acl_entries (acl) > 0);
+}
+
+# endif
+
+#elif USE_ACL && HAVE_FACL && defined GETACL /* Solaris, Cygwin, not HP-UX */
+
+/* Test an ACL retrieved with GETACL.
+ Return 1 if the given ACL, consisting of COUNT entries, is non-trivial.
+ Return 0 if it is trivial, i.e. equivalent to a simple stat() mode. */
+int
+acl_nontrivial (int count, aclent_t *entries)
+{
+ int i;
+
+ for (i = 0; i < count; i++)
+ {
+ aclent_t *ace = &entries[i];
+
+ /* Note: If ace->a_type = USER_OBJ, ace->a_id is the st_uid from stat().
+ If ace->a_type = GROUP_OBJ, ace->a_id is the st_gid from stat().
+ We don't need to check ace->a_id in these cases. */
+ if (!(ace->a_type == USER_OBJ
+ || ace->a_type == GROUP_OBJ
+ || ace->a_type == OTHER_OBJ
+ /* Note: Cygwin does not return a CLASS_OBJ ("mask:") entry
+ sometimes. */
+ || ace->a_type == CLASS_OBJ))
+ return 1;
+ }
+ return 0;
+}
+
+# ifdef ACE_GETACL
+
+/* A shortcut for a bitmask. */
+# define NEW_ACE_WRITEA_DATA (NEW_ACE_WRITE_DATA | NEW_ACE_APPEND_DATA)
+
+/* Test an ACL retrieved with ACE_GETACL.
+ Return 1 if the given ACL, consisting of COUNT entries, is non-trivial.
+ Return 0 if it is trivial, i.e. equivalent to a simple stat() mode. */
+int
+acl_ace_nontrivial (int count, ace_t *entries)
+{
+ int i;
+
+ /* The flags in the ace_t structure changed in a binary incompatible way
+ when ACL_NO_TRIVIAL etc. were introduced in <sys/acl.h> version 1.15.
+ How to distinguish the two conventions at runtime?
+ In the old convention, usually three ACEs have a_flags = ACE_OWNER /
+ ACE_GROUP / ACE_OTHER, in the range 0x0100..0x0400. In the new
+ convention, these values are not used. */
+ int old_convention = 0;
+
+ for (i = 0; i < count; i++)
+ if (entries[i].a_flags & (OLD_ACE_OWNER | OLD_ACE_GROUP | OLD_ACE_OTHER))
+ {
+ old_convention = 1;
+ break;
+ }
+
+ if (old_convention)
+ /* Running on Solaris 10. */
+ for (i = 0; i < count; i++)
+ {
+ ace_t *ace = &entries[i];
+
+ /* Note:
+ If ace->a_flags = ACE_OWNER, ace->a_who is the st_uid from stat().
+ If ace->a_flags = ACE_GROUP, ace->a_who is the st_gid from stat().
+ We don't need to check ace->a_who in these cases. */
+ if (!(ace->a_type == OLD_ALLOW
+ && (ace->a_flags == OLD_ACE_OWNER
+ || ace->a_flags == OLD_ACE_GROUP
+ || ace->a_flags == OLD_ACE_OTHER)))
+ return 1;
+ }
+ else
+ {
+ /* Running on Solaris 10 (newer version) or Solaris 11. */
+ unsigned int access_masks[6] =
+ {
+ 0, /* owner@ deny */
+ 0, /* owner@ allow */
+ 0, /* group@ deny */
+ 0, /* group@ allow */
+ 0, /* everyone@ deny */
+ 0 /* everyone@ allow */
+ };
+
+ for (i = 0; i < count; i++)
+ {
+ ace_t *ace = &entries[i];
+ unsigned int index1;
+ unsigned int index2;
+
+ if (ace->a_type == NEW_ACE_ACCESS_ALLOWED_ACE_TYPE)
+ index1 = 1;
+ else if (ace->a_type == NEW_ACE_ACCESS_DENIED_ACE_TYPE)
+ index1 = 0;
+ else
+ return 1;
+
+ if (ace->a_flags == NEW_ACE_OWNER)
+ index2 = 0;
+ else if (ace->a_flags == (NEW_ACE_GROUP | NEW_ACE_IDENTIFIER_GROUP))
+ index2 = 2;
+ else if (ace->a_flags == NEW_ACE_EVERYONE)
+ index2 = 4;
+ else
+ return 1;
+
+ access_masks[index1 + index2] |= ace->a_access_mask;
+ }
+
+ /* The same bit shouldn't be both allowed and denied. */
+ if (access_masks[0] & access_masks[1])
+ return 1;
+ if (access_masks[2] & access_masks[3])
+ return 1;
+ if (access_masks[4] & access_masks[5])
+ return 1;
+
+ /* Check minimum masks. */
+ if ((NEW_ACE_WRITE_NAMED_ATTRS
+ | NEW_ACE_WRITE_ATTRIBUTES
+ | NEW_ACE_WRITE_ACL
+ | NEW_ACE_WRITE_OWNER)
+ & ~ access_masks[1])
+ return 1;
+ access_masks[1] &= ~(NEW_ACE_WRITE_NAMED_ATTRS
+ | NEW_ACE_WRITE_ATTRIBUTES
+ | NEW_ACE_WRITE_ACL
+ | NEW_ACE_WRITE_OWNER);
+ if ((NEW_ACE_READ_NAMED_ATTRS
+ | NEW_ACE_READ_ATTRIBUTES
+ | NEW_ACE_READ_ACL
+ | NEW_ACE_SYNCHRONIZE)
+ & ~ access_masks[5])
+ return 1;
+ access_masks[5] &= ~(NEW_ACE_READ_NAMED_ATTRS
+ | NEW_ACE_READ_ATTRIBUTES
+ | NEW_ACE_READ_ACL
+ | NEW_ACE_SYNCHRONIZE);
+
+ /* Check the allowed or denied bits. */
+ switch ((access_masks[0] | access_masks[1])
+ & ~(NEW_ACE_READ_NAMED_ATTRS
+ | NEW_ACE_READ_ATTRIBUTES
+ | NEW_ACE_READ_ACL
+ | NEW_ACE_SYNCHRONIZE))
+ {
+ case 0:
+ case NEW_ACE_READ_DATA:
+ case NEW_ACE_WRITEA_DATA:
+ case NEW_ACE_READ_DATA | NEW_ACE_WRITEA_DATA:
+ case NEW_ACE_EXECUTE:
+ case NEW_ACE_READ_DATA | NEW_ACE_EXECUTE:
+ case NEW_ACE_WRITEA_DATA | NEW_ACE_EXECUTE:
+ case NEW_ACE_READ_DATA | NEW_ACE_WRITEA_DATA | NEW_ACE_EXECUTE:
+ break;
+ default:
+ return 1;
+ }
+ switch ((access_masks[2] | access_masks[3])
+ & ~(NEW_ACE_READ_NAMED_ATTRS
+ | NEW_ACE_READ_ATTRIBUTES
+ | NEW_ACE_READ_ACL
+ | NEW_ACE_SYNCHRONIZE))
+ {
+ case 0:
+ case NEW_ACE_READ_DATA:
+ case NEW_ACE_WRITEA_DATA:
+ case NEW_ACE_READ_DATA | NEW_ACE_WRITEA_DATA:
+ case NEW_ACE_EXECUTE:
+ case NEW_ACE_READ_DATA | NEW_ACE_EXECUTE:
+ case NEW_ACE_WRITEA_DATA | NEW_ACE_EXECUTE:
+ case NEW_ACE_READ_DATA | NEW_ACE_WRITEA_DATA | NEW_ACE_EXECUTE:
+ break;
+ default:
+ return 1;
+ }
+ switch ((access_masks[4] | access_masks[5])
+ & ~(NEW_ACE_WRITE_NAMED_ATTRS
+ | NEW_ACE_WRITE_ATTRIBUTES
+ | NEW_ACE_WRITE_ACL
+ | NEW_ACE_WRITE_OWNER))
+ {
+ case 0:
+ case NEW_ACE_READ_DATA:
+ case NEW_ACE_WRITEA_DATA:
+ case NEW_ACE_READ_DATA | NEW_ACE_WRITEA_DATA:
+ case NEW_ACE_EXECUTE:
+ case NEW_ACE_READ_DATA | NEW_ACE_EXECUTE:
+ case NEW_ACE_WRITEA_DATA | NEW_ACE_EXECUTE:
+ case NEW_ACE_READ_DATA | NEW_ACE_WRITEA_DATA | NEW_ACE_EXECUTE:
+ break;
+ default:
+ return 1;
+ }
+
+ /* Check that the NEW_ACE_WRITE_DATA and NEW_ACE_APPEND_DATA bits are
+ either both allowed or both denied. */
+ if (((access_masks[0] & NEW_ACE_WRITE_DATA) != 0)
+ != ((access_masks[0] & NEW_ACE_APPEND_DATA) != 0))
+ return 1;
+ if (((access_masks[2] & NEW_ACE_WRITE_DATA) != 0)
+ != ((access_masks[2] & NEW_ACE_APPEND_DATA) != 0))
+ return 1;
+ if (((access_masks[4] & NEW_ACE_WRITE_DATA) != 0)
+ != ((access_masks[4] & NEW_ACE_APPEND_DATA) != 0))
+ return 1;
+ }
+
+ return 0;
+}
+
+# endif
+
+#elif USE_ACL && HAVE_GETACL /* HP-UX */
+
+/* Return 1 if the given ACL is non-trivial.
+ Return 0 if it is trivial, i.e. equivalent to a simple stat() mode. */
+int
+acl_nontrivial (int count, struct acl_entry *entries)
+{
+ int i;
+
+ if (count > 3)
+ return 1;
+
+ for (i = 0; i < count; i++)
+ {
+ struct acl_entry *ace = &entries[i];
+
+ if (ace->uid != ACL_NSUSER && ace->gid != ACL_NSGROUP)
+ return 1;
+ }
+ return 0;
+}
+
+# if HAVE_ACLV_H /* HP-UX >= 11.11 */
+
+/* Return 1 if the given ACL is non-trivial.
+ Return 0 if it is trivial, i.e. equivalent to a simple stat() mode. */
+int
+aclv_nontrivial (int count, struct acl *entries)
+{
+ int i;
+
+ for (i = 0; i < count; i++)
+ {
+ struct acl *ace = &entries[i];
+
+ /* Note: If ace->a_type = USER_OBJ, ace->a_id is the st_uid from stat().
+ If ace->a_type = GROUP_OBJ, ace->a_id is the st_gid from stat().
+ We don't need to check ace->a_id in these cases. */
+ if (!(ace->a_type == USER_OBJ /* no need to check ace->a_id here */
+ || ace->a_type == GROUP_OBJ /* no need to check ace->a_id here */
+ || ace->a_type == CLASS_OBJ
+ || ace->a_type == OTHER_OBJ))
+ return 1;
+ }
+ return 0;
+}
+
+# endif
+
+#elif USE_ACL && (HAVE_ACLX_GET || HAVE_STATACL) /* AIX */
+
+/* Return 1 if the given ACL is non-trivial.
+ Return 0 if it is trivial, i.e. equivalent to a simple stat() mode. */
+int
+acl_nontrivial (struct acl *a)
+{
+ /* The normal way to iterate through an ACL is like this:
+ struct acl_entry *ace;
+ for (ace = a->acl_ext; ace != acl_last (a); ace = acl_nxt (ace))
+ {
+ struct ace_id *aei;
+ switch (ace->ace_type)
+ {
+ case ACC_PERMIT:
+ case ACC_DENY:
+ case ACC_SPECIFY:
+ ...;
+ }
+ for (aei = ace->ace_id; aei != id_last (ace); aei = id_nxt (aei))
+ ...
+ }
+ */
+ return (acl_last (a) != a->acl_ext ? 1 : 0);
+}
+
+# if HAVE_ACLX_GET && defined ACL_AIX_WIP /* newer AIX */
+
+/* Return 1 if the given ACL is non-trivial.
+ Return 0 if it is trivial, i.e. equivalent to a simple stat() mode. */
+int
+acl_nfs4_nontrivial (nfs4_acl_int_t *a)
+{
+# if 1 /* let's try this first */
+ return (a->aclEntryN > 0 ? 1 : 0);
+# else
+ int count = a->aclEntryN;
+ int i;
+
+ for (i = 0; i < count; i++)
+ {
+ nfs4_ace_int_t *ace = &a->aclEntry[i];
+
+ if (!((ace->flags & ACE4_ID_SPECIAL) != 0
+ && (ace->aceWho.special_whoid == ACE4_WHO_OWNER
+ || ace->aceWho.special_whoid == ACE4_WHO_GROUP
+ || ace->aceWho.special_whoid == ACE4_WHO_EVERYONE)
+ && ace->aceType == ACE4_ACCESS_ALLOWED_ACE_TYPE
+ && ace->aceFlags == 0
+ && (ace->aceMask & ~(ACE4_READ_DATA | ACE4_LIST_DIRECTORY
+ | ACE4_WRITE_DATA | ACE4_ADD_FILE
+ | ACE4_EXECUTE)) == 0))
+ return 1;
+ }
+ return 0;
+# endif
+}
+
+# endif
+
+#elif USE_ACL && HAVE_ACLSORT /* NonStop Kernel */
+
+/* Test an ACL retrieved with ACL_GET.
+ Return 1 if the given ACL, consisting of COUNT entries, is non-trivial.
+ Return 0 if it is trivial, i.e. equivalent to a simple stat() mode. */
+int
+acl_nontrivial (int count, struct acl *entries)
+{
+ int i;
+
+ for (i = 0; i < count; i++)
+ {
+ struct acl *ace = &entries[i];
+
+ /* Note: If ace->a_type = USER_OBJ, ace->a_id is the st_uid from stat().
+ If ace->a_type = GROUP_OBJ, ace->a_id is the st_gid from stat().
+ We don't need to check ace->a_id in these cases. */
+ if (!(ace->a_type == USER_OBJ /* no need to check ace->a_id here */
+ || ace->a_type == GROUP_OBJ /* no need to check ace->a_id here */
+ || ace->a_type == CLASS_OBJ
+ || ace->a_type == OTHER_OBJ))
+ return 1;
+ }
+ return 0;
+}
+
+#endif
+
+void
+free_permission_context (struct permission_context *ctx)
+{
+#if USE_ACL
+# if HAVE_ACL_GET_FILE /* Linux, FreeBSD, Mac OS X, IRIX, Tru64 */
+ if (ctx->acl)
+ acl_free (ctx->acl);
+# if !HAVE_ACL_TYPE_EXTENDED
+ if (ctx->default_acl)
+ acl_free (ctx->default_acl);
+# endif
+
+# elif defined GETACL /* Solaris, Cygwin */
+ free (ctx->entries);
+# ifdef ACE_GETACL
+ free (ctx->ace_entries);
+# endif
+
+# elif HAVE_GETACL /* HP-UX */
+
+# if HAVE_ACLV_H
+# endif
+
+# elif HAVE_STATACL /* older AIX */
+
+# elif HAVE_ACLSORT /* NonStop Kernel */
+
+# endif
+#endif
+}
diff --git a/lib/acl-internal.h b/lib/acl-internal.h
index e224a78..636273e 100644
--- a/lib/acl-internal.h
+++ b/lib/acl-internal.h
@@ -1,11 +1,11 @@
-/* Internal implementation of access control lists.
+/* Internal implementation of access control lists. -*- coding: utf-8 -*-
- Copyright (C) 2002, 2003, 2005, 2006, 2007 Free Software Foundation, Inc.
+ Copyright (C) 2002-2003, 2005-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,74 +13,290 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
- Written by Paul Eggert and Andreas Gruenbacher. */
-
-#include <config.h>
+ Written by Paul Eggert, Andreas Grünbacher, and Bruno Haible. */
#include "acl.h"
#include <stdbool.h>
#include <stdlib.h>
+/* All systems define the ACL related API in <sys/acl.h>. */
+#if HAVE_SYS_ACL_H
+# include <sys/acl.h>
+#endif
+#if defined HAVE_FACL && ! defined GETACLCNT && defined ACL_CNT
+# define GETACLCNT ACL_CNT
+#endif
+
+/* On Linux, additional ACL related API is available in <acl/libacl.h>. */
#ifdef HAVE_ACL_LIBACL_H
# include <acl/libacl.h>
#endif
-#include "error.h"
-#include "quote.h"
+/* On HP-UX >= 11.11, additional ACL API is available in <aclv.h>. */
+#if HAVE_ACLV_H
+# include <sys/types.h>
+# include <aclv.h>
+/* HP-UX 11.11 lacks these declarations. */
+extern int acl (char *, int, int, struct acl *);
+extern int aclsort (int, int, struct acl *);
+#endif
#include <errno.h>
-#ifndef ENOSYS
-# define ENOSYS (-1)
-#endif
-#ifndef ENOTSUP
-# define ENOTSUP (-1)
+
+#include <limits.h>
+#ifndef MIN
+# define MIN(a,b) ((a) < (b) ? (a) : (b))
#endif
-#include "gettext.h"
-#define _(msgid) gettext (msgid)
+#ifndef SIZE_MAX
+# define SIZE_MAX ((size_t) -1)
+#endif
#ifndef HAVE_FCHMOD
# define HAVE_FCHMOD false
# define fchmod(fd, mode) (-1)
#endif
-#ifndef MIN_ACL_ENTRIES
-# define MIN_ACL_ENTRIES 4
+#ifndef _GL_INLINE_HEADER_BEGIN
+ #error "Please include config.h first."
+#endif
+_GL_INLINE_HEADER_BEGIN
+#ifndef ACL_INTERNAL_INLINE
+# define ACL_INTERNAL_INLINE _GL_INLINE
#endif
+#if USE_ACL
+
+# if HAVE_ACL_GET_FILE
+/* POSIX 1003.1e (draft 17 -- abandoned) specific version. */
+/* Linux, FreeBSD, Mac OS X, IRIX, Tru64 */
+
+# ifndef MIN_ACL_ENTRIES
+# define MIN_ACL_ENTRIES 4
+# endif
+
/* POSIX 1003.1e (draft 17) */
-#ifndef HAVE_ACL_GET_FD
-# define HAVE_ACL_GET_FD false
-# define acl_get_fd(fd) (NULL)
-#endif
+# ifdef HAVE_ACL_GET_FD
+/* Most platforms have a 1-argument acl_get_fd, only OSF/1 has a 2-argument
+ macro(!). */
+# if HAVE_ACL_FREE_TEXT /* OSF/1 */
+ACL_INTERNAL_INLINE acl_t
+rpl_acl_get_fd (int fd)
+{
+ return acl_get_fd (fd, ACL_TYPE_ACCESS);
+}
+# undef acl_get_fd
+# define acl_get_fd rpl_acl_get_fd
+# endif
+# else
+# define HAVE_ACL_GET_FD false
+# undef acl_get_fd
+# define acl_get_fd(fd) (NULL)
+# endif
/* POSIX 1003.1e (draft 17) */
-#ifndef HAVE_ACL_SET_FD
-# define HAVE_ACL_SET_FD false
-# define acl_set_fd(fd, acl) (-1)
-#endif
+# ifdef HAVE_ACL_SET_FD
+/* Most platforms have a 2-argument acl_set_fd, only OSF/1 has a 3-argument
+ macro(!). */
+# if HAVE_ACL_FREE_TEXT /* OSF/1 */
+ACL_INTERNAL_INLINE int
+rpl_acl_set_fd (int fd, acl_t acl)
+{
+ return acl_set_fd (fd, ACL_TYPE_ACCESS, acl);
+}
+# undef acl_set_fd
+# define acl_set_fd rpl_acl_set_fd
+# endif
+# else
+# define HAVE_ACL_SET_FD false
+# undef acl_set_fd
+# define acl_set_fd(fd, acl) (-1)
+# endif
-/* Linux-specific */
-#ifndef HAVE_ACL_EXTENDED_FILE
-# define HAVE_ACL_EXTENDED_FILE false
-# define acl_extended_file(name) (-1)
-#endif
+/* POSIX 1003.1e (draft 13) */
+# if ! HAVE_ACL_FREE_TEXT
+# define acl_free_text(buf) acl_free (buf)
+# endif
/* Linux-specific */
-#ifndef HAVE_ACL_FROM_MODE
-# define HAVE_ACL_FROM_MODE false
-# define acl_from_mode(mode) (NULL)
+# ifndef HAVE_ACL_EXTENDED_FILE
+# define HAVE_ACL_EXTENDED_FILE false
+# define acl_extended_file(name) (-1)
+# endif
+
+# if ! defined HAVE_ACL_FROM_MODE && ! defined HAVE_ACL_FROM_TEXT
+# define acl_from_mode (NULL)
+# endif
+
+/* Set to 0 if a file's mode is stored independently from the ACL. */
+# if (HAVE_ACL_COPY_EXT_NATIVE && HAVE_ACL_CREATE_ENTRY_NP) || defined __sgi /* Mac OS X, IRIX */
+# define MODE_INSIDE_ACL 0
+# endif
+
+/* Return the number of entries in ACL.
+ Return -1 and set errno upon failure to determine it. */
+/* Define a replacement for acl_entries if needed. (Only Linux has it.) */
+# if !HAVE_ACL_ENTRIES
+# define acl_entries rpl_acl_entries
+extern int acl_entries (acl_t);
+# endif
+
+# if HAVE_ACL_TYPE_EXTENDED /* Mac OS X */
+/* ACL is an ACL, from a file, stored as type ACL_TYPE_EXTENDED.
+ Return 1 if the given ACL is non-trivial.
+ Return 0 if it is trivial. */
+extern int acl_extended_nontrivial (acl_t);
+# else
+/* ACL is an ACL, from a file, stored as type ACL_TYPE_ACCESS.
+ Return 1 if the given ACL is non-trivial.
+ Return 0 if it is trivial, i.e. equivalent to a simple stat() mode.
+ Return -1 and set errno upon failure to determine it. */
+extern int acl_access_nontrivial (acl_t);
+
+/* ACL is an ACL, from a file, stored as type ACL_TYPE_DEFAULT.
+ Return 1 if the given ACL is non-trivial.
+ Return 0 if it is trivial, i.e. equivalent to a simple stat() mode.
+ Return -1 and set errno upon failure to determine it. */
+extern int acl_default_nontrivial (acl_t);
+# endif
+
+# elif HAVE_FACL && defined GETACL /* Solaris, Cygwin, not HP-UX */
+
+/* Set to 0 if a file's mode is stored independently from the ACL. */
+# if defined __CYGWIN__ /* Cygwin */
+# define MODE_INSIDE_ACL 0
+# endif
+
+/* Return 1 if the given ACL is non-trivial.
+ Return 0 if it is trivial, i.e. equivalent to a simple stat() mode. */
+extern int acl_nontrivial (int count, aclent_t *entries) _GL_ATTRIBUTE_PURE;
+
+# ifdef ACE_GETACL /* Solaris 10 */
+
+/* Test an ACL retrieved with ACE_GETACL.
+ Return 1 if the given ACL, consisting of COUNT entries, is non-trivial.
+ Return 0 if it is trivial, i.e. equivalent to a simple stat() mode. */
+extern int acl_ace_nontrivial (int count, ace_t *entries) _GL_ATTRIBUTE_PURE;
+
+/* Definitions for when the built executable is executed on Solaris 10
+ (newer version) or Solaris 11. */
+/* For a_type. */
+# define OLD_ALLOW 0
+# define OLD_DENY 1
+# define NEW_ACE_ACCESS_ALLOWED_ACE_TYPE 0 /* replaces ALLOW */
+# define NEW_ACE_ACCESS_DENIED_ACE_TYPE 1 /* replaces DENY */
+/* For a_flags. */
+# define OLD_ACE_OWNER 0x0100
+# define OLD_ACE_GROUP 0x0200
+# define OLD_ACE_OTHER 0x0400
+# define NEW_ACE_OWNER 0x1000
+# define NEW_ACE_GROUP 0x2000
+# define NEW_ACE_IDENTIFIER_GROUP 0x0040
+# define NEW_ACE_EVERYONE 0x4000
+/* For a_access_mask. */
+# define NEW_ACE_READ_DATA 0x001 /* corresponds to 'r' */
+# define NEW_ACE_WRITE_DATA 0x002 /* corresponds to 'w' */
+# define NEW_ACE_APPEND_DATA 0x004
+# define NEW_ACE_READ_NAMED_ATTRS 0x008
+# define NEW_ACE_WRITE_NAMED_ATTRS 0x010
+# define NEW_ACE_EXECUTE 0x020
+# define NEW_ACE_DELETE_CHILD 0x040
+# define NEW_ACE_READ_ATTRIBUTES 0x080
+# define NEW_ACE_WRITE_ATTRIBUTES 0x100
+# define NEW_ACE_DELETE 0x10000
+# define NEW_ACE_READ_ACL 0x20000
+# define NEW_ACE_WRITE_ACL 0x40000
+# define NEW_ACE_WRITE_OWNER 0x80000
+# define NEW_ACE_SYNCHRONIZE 0x100000
+
+# endif
+
+# elif HAVE_GETACL /* HP-UX */
+
+/* Return 1 if the given ACL is non-trivial.
+ Return 0 if it is trivial, i.e. equivalent to a simple stat() mode. */
+extern int acl_nontrivial (int count, struct acl_entry *entries);
+
+# if HAVE_ACLV_H /* HP-UX >= 11.11 */
+
+/* Return 1 if the given ACL is non-trivial.
+ Return 0 if it is trivial, i.e. equivalent to a simple stat() mode. */
+extern int aclv_nontrivial (int count, struct acl *entries);
+
+# endif
+
+# elif HAVE_ACLX_GET && 0 /* AIX */
+
+/* TODO */
+
+# elif HAVE_STATACL /* older AIX */
+
+/* Return 1 if the given ACL is non-trivial.
+ Return 0 if it is trivial, i.e. equivalent to a simple stat() mode. */
+extern int acl_nontrivial (struct acl *a);
+
+# elif HAVE_ACLSORT /* NonStop Kernel */
+
+/* Return 1 if the given ACL is non-trivial.
+ Return 0 if it is trivial, i.e. equivalent to a simple stat() mode. */
+extern int acl_nontrivial (int count, struct acl *entries);
+
+# endif
+
+/* Set to 1 if a file's mode is implicit by the ACL. */
+# ifndef MODE_INSIDE_ACL
+# define MODE_INSIDE_ACL 1
+# endif
+
#endif
-#define ACL_NOT_WELL_SUPPORTED(Errno) \
- ((Errno) == ENOTSUP || (Errno) == ENOSYS || (Errno) == EINVAL)
+struct permission_context {
+ mode_t mode;
+#if USE_ACL
+# if HAVE_ACL_GET_FILE /* Linux, FreeBSD, Mac OS X, IRIX, Tru64 */
+ acl_t acl;
+# if !HAVE_ACL_TYPE_EXTENDED
+ acl_t default_acl;
+# endif
+ bool acls_not_supported;
+
+# elif defined GETACL /* Solaris, Cygwin */
+ int count;
+ aclent_t *entries;
+# ifdef ACE_GETACL
+ int ace_count;
+ ace_t *ace_entries;
+# endif
-/* Define a replacement for acl_entries if needed. */
-#if USE_ACL && HAVE_ACL_GET_FILE && HAVE_ACL_FREE && !HAVE_ACL_ENTRIES
-# define acl_entries rpl_acl_entries
-int acl_entries (acl_t);
+# elif HAVE_GETACL /* HP-UX */
+ struct acl_entry entries[NACLENTRIES];
+ int count;
+# if HAVE_ACLV_H
+ struct acl aclv_entries[NACLVENTRIES];
+ int aclv_count;
+# endif
+
+# elif HAVE_STATACL /* older AIX */
+ union { struct acl a; char room[4096]; } u;
+ bool have_u;
+
+# elif HAVE_ACLSORT /* NonStop Kernel */
+ struct acl entries[NACLENTRIES];
+ int count;
+
+# endif
#endif
+};
+
+int get_permissions (const char *, int, mode_t, struct permission_context *);
+int set_permissions (struct permission_context *, const char *, int);
+void free_permission_context (struct permission_context *)
+#if ! (defined USE_ACL && (HAVE_ACL_GET_FILE || defined GETACL))
+ _GL_ATTRIBUTE_CONST
+#endif
+ ;
+
+_GL_INLINE_HEADER_END
diff --git a/lib/acl.c b/lib/acl.c
deleted file mode 100644
index 84c595a..0000000
--- a/lib/acl.c
+++ /dev/null
@@ -1,256 +0,0 @@
-/* acl.c - access control lists
-
- Copyright (C) 2002, 2003, 2005, 2006, 2007 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-
- Written by Paul Eggert and Andreas Gruenbacher. */
-
-#include <config.h>
-
-#include "acl.h"
-
-#include "acl-internal.h"
-
-/* If DESC is a valid file descriptor use fchmod to change the
- file's mode to MODE on systems that have fchown. On systems
- that don't have fchown and if DESC is invalid, use chown on
- NAME instead. */
-
-int
-chmod_or_fchmod (const char *name, int desc, mode_t mode)
-{
- if (HAVE_FCHMOD && desc != -1)
- return fchmod (desc, mode);
- else
- return chmod (name, mode);
-}
-
-/* Copy access control lists from one file to another. If SOURCE_DESC is
- a valid file descriptor, use file descriptor operations, else use
- filename based operations on SRC_NAME. Likewise for DEST_DESC and
- DEST_NAME.
- If access control lists are not available, fchmod the target file to
- MODE. Also sets the non-permission bits of the destination file
- (S_ISUID, S_ISGID, S_ISVTX) to those from MODE if any are set.
- System call return value semantics. */
-
-int
-copy_acl (const char *src_name, int source_desc, const char *dst_name,
- int dest_desc, mode_t mode)
-{
- int ret;
-
-#if USE_ACL && HAVE_ACL_GET_FILE && HAVE_ACL_SET_FILE && HAVE_ACL_FREE
- /* POSIX 1003.1e (draft 17 -- abandoned) specific version. */
-
- acl_t acl;
- if (HAVE_ACL_GET_FD && source_desc != -1)
- acl = acl_get_fd (source_desc);
- else
- acl = acl_get_file (src_name, ACL_TYPE_ACCESS);
- if (acl == NULL)
- {
- if (ACL_NOT_WELL_SUPPORTED (errno))
- return set_acl (dst_name, dest_desc, mode);
- else
- {
- error (0, errno, "%s", quote (src_name));
- return -1;
- }
- }
-
- if (HAVE_ACL_SET_FD && dest_desc != -1)
- ret = acl_set_fd (dest_desc, acl);
- else
- ret = acl_set_file (dst_name, ACL_TYPE_ACCESS, acl);
- if (ret != 0)
- {
- int saved_errno = errno;
-
- if (ACL_NOT_WELL_SUPPORTED (errno))
- {
- int n = acl_entries (acl);
-
- acl_free (acl);
- if (n == 3)
- {
- if (chmod_or_fchmod (dst_name, dest_desc, mode) != 0)
- saved_errno = errno;
- else
- return 0;
- }
- else
- chmod_or_fchmod (dst_name, dest_desc, mode);
- }
- else
- {
- acl_free (acl);
- chmod_or_fchmod (dst_name, dest_desc, mode);
- }
- error (0, saved_errno, _("preserving permissions for %s"),
- quote (dst_name));
- return -1;
- }
- else
- acl_free (acl);
-
- if (mode & (S_ISUID | S_ISGID | S_ISVTX))
- {
- /* We did not call chmod so far, so the special bits have not yet
- been set. */
-
- if (chmod_or_fchmod (dst_name, dest_desc, mode) != 0)
- {
- error (0, errno, _("preserving permissions for %s"),
- quote (dst_name));
- return -1;
- }
- }
-
- if (S_ISDIR (mode))
- {
- acl = acl_get_file (src_name, ACL_TYPE_DEFAULT);
- if (acl == NULL)
- {
- error (0, errno, "%s", quote (src_name));
- return -1;
- }
-
- if (acl_set_file (dst_name, ACL_TYPE_DEFAULT, acl))
- {
- error (0, errno, _("preserving permissions for %s"),
- quote (dst_name));
- acl_free (acl);
- return -1;
- }
- else
- acl_free (acl);
- }
- return 0;
-#else
- ret = chmod_or_fchmod (dst_name, dest_desc, mode);
- if (ret != 0)
- error (0, errno, _("preserving permissions for %s"), quote (dst_name));
- return ret;
-#endif
-}
-
-/* Set the access control lists of a file. If DESC is a valid file
- descriptor, use file descriptor operations where available, else use
- filename based operations on NAME. If access control lists are not
- available, fchmod the target file to MODE. Also sets the
- non-permission bits of the destination file (S_ISUID, S_ISGID, S_ISVTX)
- to those from MODE if any are set. System call return value
- semantics. */
-
-int
-set_acl (char const *name, int desc, mode_t mode)
-{
-#if USE_ACL && HAVE_ACL_SET_FILE && HAVE_ACL_FREE
- /* POSIX 1003.1e draft 17 (abandoned) specific version. */
-
- /* We must also have have_acl_from_text and acl_delete_def_file.
- (acl_delete_def_file could be emulated with acl_init followed
- by acl_set_file, but acl_set_file with an empty acl is
- unspecified.) */
-
-# ifndef HAVE_ACL_FROM_TEXT
-# error Must have acl_from_text (see POSIX 1003.1e draft 17).
-# endif
-# ifndef HAVE_ACL_DELETE_DEF_FILE
-# error Must have acl_delete_def_file (see POSIX 1003.1e draft 17).
-# endif
-
- acl_t acl;
- int ret;
-
- if (HAVE_ACL_FROM_MODE)
- {
- acl = acl_from_mode (mode);
- if (!acl)
- {
- error (0, errno, "%s", quote (name));
- return -1;
- }
- }
- else
- {
- char acl_text[] = "u::---,g::---,o::---";
-
- if (mode & S_IRUSR) acl_text[ 3] = 'r';
- if (mode & S_IWUSR) acl_text[ 4] = 'w';
- if (mode & S_IXUSR) acl_text[ 5] = 'x';
- if (mode & S_IRGRP) acl_text[10] = 'r';
- if (mode & S_IWGRP) acl_text[11] = 'w';
- if (mode & S_IXGRP) acl_text[12] = 'x';
- if (mode & S_IROTH) acl_text[17] = 'r';
- if (mode & S_IWOTH) acl_text[18] = 'w';
- if (mode & S_IXOTH) acl_text[19] = 'x';
-
- acl = acl_from_text (acl_text);
- if (!acl)
- {
- error (0, errno, "%s", quote (name));
- return -1;
- }
- }
- if (HAVE_ACL_SET_FD && desc != -1)
- ret = acl_set_fd (desc, acl);
- else
- ret = acl_set_file (name, ACL_TYPE_ACCESS, acl);
- if (ret != 0)
- {
- int saved_errno = errno;
- acl_free (acl);
-
- if (ACL_NOT_WELL_SUPPORTED (errno))
- {
- if (chmod_or_fchmod (name, desc, mode) != 0)
- saved_errno = errno;
- else
- return 0;
- }
- error (0, saved_errno, _("setting permissions for %s"), quote (name));
- return -1;
- }
- else
- acl_free (acl);
-
- if (S_ISDIR (mode) && acl_delete_def_file (name))
- {
- error (0, errno, _("setting permissions for %s"), quote (name));
- return -1;
- }
-
- if (mode & (S_ISUID | S_ISGID | S_ISVTX))
- {
- /* We did not call chmod so far, so the special bits have not yet
- been set. */
-
- if (chmod_or_fchmod (name, desc, mode))
- {
- error (0, errno, _("preserving permissions for %s"), quote (name));
- return -1;
- }
- }
- return 0;
-#else
- int ret = chmod_or_fchmod (name, desc, mode);
- if (ret)
- error (0, errno, _("setting permissions for %s"), quote (name));
- return ret;
-#endif
-}
diff --git a/lib/acl.h b/lib/acl.h
index 18fb732..491b1ba 100644
--- a/lib/acl.h
+++ b/lib/acl.h
@@ -1,11 +1,11 @@
/* acl.c - access control lists
- Copyright (C) 2002 Free Software Foundation, Inc.
+ Copyright (C) 2002, 2008-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,23 +13,23 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
Written by Paul Eggert. */
-#include <sys/types.h>
-
-#if HAVE_SYS_ACL_H
-# include <sys/acl.h>
-#endif
-#if defined HAVE_ACL && ! defined GETACLCNT && defined ACL_CNT
-# define GETACLCNT ACL_CNT
-#endif
+#ifndef _GL_ACL_H
+#define _GL_ACL_H 1
+#include <stdbool.h>
+#include <sys/types.h>
#include <sys/stat.h>
+bool acl_errno_valid (int) _GL_ATTRIBUTE_CONST;
int file_has_acl (char const *, struct stat const *);
-int copy_acl (char const *, int, char const *, int, mode_t);
+int qset_acl (char const *, int, mode_t);
int set_acl (char const *, int, mode_t);
+int qcopy_acl (char const *, int, char const *, int, mode_t);
+int copy_acl (char const *, int, char const *, int, mode_t);
int chmod_or_fchmod (char const *, int, mode_t);
+
+#endif
diff --git a/lib/acl_entries.c b/lib/acl_entries.c
index 25c8bb8..9fc9cf5 100644
--- a/lib/acl_entries.c
+++ b/lib/acl_entries.c
@@ -1,11 +1,11 @@
/* Return the number of entries in an ACL.
- Copyright (C) 2002, 2003, 2005, 2006, 2007 Free Software Foundation, Inc.
+ Copyright (C) 2002-2003, 2005-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
Written by Paul Eggert and Andreas Gruenbacher. */
@@ -22,18 +21,55 @@
#include "acl-internal.h"
-/* Return the number of entries in ACL. */
+/* This file assumes POSIX-draft like ACLs
+ (Linux, FreeBSD, Mac OS X, IRIX, Tru64). */
+
+/* Return the number of entries in ACL.
+ Return -1 and set errno upon failure to determine it. */
int
acl_entries (acl_t acl)
{
- char *t;
- int entries = 0;
- char *text = acl_to_text (acl, NULL);
- if (! text)
- return -1;
- for (t = text; *t; t++)
- entries += (*t == '\n');
- acl_free (text);
- return entries;
+ int count = 0;
+
+ if (acl != NULL)
+ {
+#if HAVE_ACL_FIRST_ENTRY /* Linux, FreeBSD, Mac OS X */
+# if HAVE_ACL_TYPE_EXTENDED /* Mac OS X */
+ /* acl_get_entry returns 0 when it successfully fetches an entry,
+ and -1/EINVAL at the end. */
+ acl_entry_t ace;
+ int got_one;
+
+ for (got_one = acl_get_entry (acl, ACL_FIRST_ENTRY, &ace);
+ got_one >= 0;
+ got_one = acl_get_entry (acl, ACL_NEXT_ENTRY, &ace))
+ count++;
+# else /* Linux, FreeBSD */
+ /* acl_get_entry returns 1 when it successfully fetches an entry,
+ and 0 at the end. */
+ acl_entry_t ace;
+ int got_one;
+
+ for (got_one = acl_get_entry (acl, ACL_FIRST_ENTRY, &ace);
+ got_one > 0;
+ got_one = acl_get_entry (acl, ACL_NEXT_ENTRY, &ace))
+ count++;
+ if (got_one < 0)
+ return -1;
+# endif
+#else /* IRIX, Tru64 */
+# if HAVE_ACL_TO_SHORT_TEXT /* IRIX */
+ /* Don't use acl_get_entry: it is undocumented. */
+ count = acl->acl_cnt;
+# endif
+# if HAVE_ACL_FREE_TEXT /* Tru64 */
+ /* Don't use acl_get_entry: it takes only one argument and does not
+ work. */
+ count = acl->acl_num;
+# endif
+#endif
+ }
+
+ return count;
}
diff --git a/lib/alignof.h b/lib/alignof.h
new file mode 100644
index 0000000..9b51af0
--- /dev/null
+++ b/lib/alignof.h
@@ -0,0 +1,50 @@
+/* Determine alignment of types.
+ Copyright (C) 2003-2004, 2006, 2009-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _ALIGNOF_H
+#define _ALIGNOF_H
+
+#include <stddef.h>
+
+/* alignof_slot (TYPE)
+ Determine the alignment of a structure slot (field) of a given type,
+ at compile time. Note that the result depends on the ABI.
+ This is the same as alignof (TYPE) and _Alignof (TYPE), defined in
+ <stdalign.h> if __alignof_is_defined is 1.
+ Note: The result cannot be used as a value for an 'enum' constant,
+ due to bugs in HP-UX 10.20 cc and AIX 3.2.5 xlc. */
+#if defined __cplusplus
+ template <class type> struct alignof_helper { char __slot1; type __slot2; };
+# define alignof_slot(type) offsetof (alignof_helper<type>, __slot2)
+#else
+# define alignof_slot(type) offsetof (struct { char __slot1; type __slot2; }, __slot2)
+#endif
+
+/* alignof_type (TYPE)
+ Determine the good alignment of an object of the given type at compile time.
+ Note that this is not necessarily the same as alignof_slot(type).
+ For example, with GNU C on x86 platforms: alignof_type(double) = 8, but
+ - when -malign-double is not specified: alignof_slot(double) = 4,
+ - when -malign-double is specified: alignof_slot(double) = 8.
+ Note: The result cannot be used as a value for an 'enum' constant,
+ due to bugs in HP-UX 10.20 cc and AIX 3.2.5 xlc. */
+#if defined __GNUC__ || defined __IBM__ALIGNOF__
+# define alignof_type __alignof__
+#else
+# define alignof_type alignof_slot
+#endif
+
+#endif /* _ALIGNOF_H */
diff --git a/lib/alloca.c b/lib/alloca.c
index 3a1f4e2..ee0f018 100644
--- a/lib/alloca.c
+++ b/lib/alloca.c
@@ -81,38 +81,27 @@ long i00afunc ();
STACK_DIRECTION = 0 => direction of growth unknown */
# ifndef STACK_DIRECTION
-# define STACK_DIRECTION 0 /* Direction unknown. */
+# define STACK_DIRECTION 0 /* Direction unknown. */
# endif
# if STACK_DIRECTION != 0
-# define STACK_DIR STACK_DIRECTION /* Known at compile-time. */
+# define STACK_DIR STACK_DIRECTION /* Known at compile-time. */
# else /* STACK_DIRECTION == 0; need run-time code. */
-static int stack_dir; /* 1 or -1 once known. */
-# define STACK_DIR stack_dir
+static int stack_dir; /* 1 or -1 once known. */
+# define STACK_DIR stack_dir
-static void
-find_stack_direction (void)
+static int
+find_stack_direction (int *addr, int depth)
{
- static char *addr = NULL; /* Address of first `dummy', once known. */
- auto char dummy; /* To get stack address. */
-
- if (addr == NULL)
- { /* Initial entry. */
- addr = ADDRESS_FUNCTION (dummy);
-
- find_stack_direction (); /* Recurse once. */
- }
- else
- {
- /* Second entry. */
- if (ADDRESS_FUNCTION (dummy) > addr)
- stack_dir = 1; /* Stack grew upward. */
- else
- stack_dir = -1; /* Stack grew downward. */
- }
+ int dir, dummy = 0;
+ if (! addr)
+ addr = &dummy;
+ *addr = addr < &dummy ? 1 : addr == &dummy ? 0 : -1;
+ dir = depth ? find_stack_direction (addr, depth - 1) : 0;
+ return dir + dummy;
}
# endif /* STACK_DIRECTION == 0 */
@@ -124,21 +113,21 @@ find_stack_direction (void)
It is very important that sizeof(header) agree with malloc
alignment chunk size. The following default should work okay. */
-# ifndef ALIGN_SIZE
-# define ALIGN_SIZE sizeof(double)
+# ifndef ALIGN_SIZE
+# define ALIGN_SIZE sizeof(double)
# endif
typedef union hdr
{
- char align[ALIGN_SIZE]; /* To force sizeof(header). */
+ char align[ALIGN_SIZE]; /* To force sizeof(header). */
struct
{
- union hdr *next; /* For chaining headers. */
- char *deep; /* For stack depth measure. */
+ union hdr *next; /* For chaining headers. */
+ char *deep; /* For stack depth measure. */
} h;
} header;
-static header *last_alloca_header = NULL; /* -> last alloca header. */
+static header *last_alloca_header = NULL; /* -> last alloca header. */
/* Return a pointer to at least SIZE bytes of storage,
which will be automatically reclaimed upon exit from
@@ -150,19 +139,19 @@ static header *last_alloca_header = NULL; /* -> last alloca header. */
void *
alloca (size_t size)
{
- auto char probe; /* Probes stack depth: */
+ auto char probe; /* Probes stack depth: */
register char *depth = ADDRESS_FUNCTION (probe);
# if STACK_DIRECTION == 0
- if (STACK_DIR == 0) /* Unknown growth direction. */
- find_stack_direction ();
+ if (STACK_DIR == 0) /* Unknown growth direction. */
+ STACK_DIR = find_stack_direction (NULL, (size & 1) + 20);
# endif
/* Reclaim garbage, defined as all alloca'd storage that
was allocated from deeper in the stack than currently. */
{
- register header *hp; /* Traverses linked list. */
+ register header *hp; /* Traverses linked list. */
# ifdef emacs
BLOCK_INPUT;
@@ -170,18 +159,18 @@ alloca (size_t size)
for (hp = last_alloca_header; hp != NULL;)
if ((STACK_DIR > 0 && hp->h.deep > depth)
- || (STACK_DIR < 0 && hp->h.deep < depth))
- {
- register header *np = hp->h.next;
+ || (STACK_DIR < 0 && hp->h.deep < depth))
+ {
+ register header *np = hp->h.next;
- free (hp); /* Collect garbage. */
+ free (hp); /* Collect garbage. */
- hp = np; /* -> next header. */
- }
+ hp = np; /* -> next header. */
+ }
else
- break; /* Rest are not deeper. */
+ break; /* Rest are not deeper. */
- last_alloca_header = hp; /* -> last valid storage. */
+ last_alloca_header = hp; /* -> last valid storage. */
# ifdef emacs
UNBLOCK_INPUT;
@@ -189,7 +178,7 @@ alloca (size_t size)
}
if (size == 0)
- return NULL; /* No allocation required. */
+ return NULL; /* No allocation required. */
/* Allocate combined header + user data storage. */
@@ -229,10 +218,10 @@ alloca (size_t size)
/* Stack structures for CRAY-1, CRAY X-MP, and CRAY Y-MP */
struct stack_control_header
{
- long shgrow:32; /* Number of times stack has grown. */
- long shaseg:32; /* Size of increments to stack. */
- long shhwm:32; /* High water mark of stack. */
- long shsize:32; /* Current size of stack (all segments). */
+ long shgrow:32; /* Number of times stack has grown. */
+ long shaseg:32; /* Size of increments to stack. */
+ long shhwm:32; /* High water mark of stack. */
+ long shsize:32; /* Current size of stack (all segments). */
};
/* The stack segment linkage control information occurs at
@@ -244,21 +233,21 @@ struct stack_control_header
struct stack_segment_linkage
{
- long ss[0200]; /* 0200 overflow words. */
- long sssize:32; /* Number of words in this segment. */
- long ssbase:32; /* Offset to stack base. */
+ long ss[0200]; /* 0200 overflow words. */
+ long sssize:32; /* Number of words in this segment. */
+ long ssbase:32; /* Offset to stack base. */
long:32;
- long sspseg:32; /* Offset to linkage control of previous
- segment of stack. */
+ long sspseg:32; /* Offset to linkage control of previous
+ segment of stack. */
long:32;
- long sstcpt:32; /* Pointer to task common address block. */
- long sscsnm; /* Private control structure number for
- microtasking. */
- long ssusr1; /* Reserved for user. */
- long ssusr2; /* Reserved for user. */
- long sstpid; /* Process ID for pid based multi-tasking. */
- long ssgvup; /* Pointer to multitasking thread giveup. */
- long sscray[7]; /* Reserved for Cray Research. */
+ long sstcpt:32; /* Pointer to task common address block. */
+ long sscsnm; /* Private control structure number for
+ microtasking. */
+ long ssusr1; /* Reserved for user. */
+ long ssusr2; /* Reserved for user. */
+ long sstpid; /* Process ID for pid based multi-tasking. */
+ long ssgvup; /* Pointer to multitasking thread giveup. */
+ long sscray[7]; /* Reserved for Cray Research. */
long ssa0;
long ssa1;
long ssa2;
@@ -282,27 +271,27 @@ struct stack_segment_linkage
returned by the STKSTAT library routine. */
struct stk_stat
{
- long now; /* Current total stack size. */
- long maxc; /* Amount of contiguous space which would
- be required to satisfy the maximum
- stack demand to date. */
- long high_water; /* Stack high-water mark. */
- long overflows; /* Number of stack overflow ($STKOFEN) calls. */
- long hits; /* Number of internal buffer hits. */
- long extends; /* Number of block extensions. */
- long stko_mallocs; /* Block allocations by $STKOFEN. */
- long underflows; /* Number of stack underflow calls ($STKRETN). */
- long stko_free; /* Number of deallocations by $STKRETN. */
- long stkm_free; /* Number of deallocations by $STKMRET. */
- long segments; /* Current number of stack segments. */
- long maxs; /* Maximum number of stack segments so far. */
- long pad_size; /* Stack pad size. */
- long current_address; /* Current stack segment address. */
- long current_size; /* Current stack segment size. This
- number is actually corrupted by STKSTAT to
- include the fifteen word trailer area. */
- long initial_address; /* Address of initial segment. */
- long initial_size; /* Size of initial segment. */
+ long now; /* Current total stack size. */
+ long maxc; /* Amount of contiguous space which would
+ be required to satisfy the maximum
+ stack demand to date. */
+ long high_water; /* Stack high-water mark. */
+ long overflows; /* Number of stack overflow ($STKOFEN) calls. */
+ long hits; /* Number of internal buffer hits. */
+ long extends; /* Number of block extensions. */
+ long stko_mallocs; /* Block allocations by $STKOFEN. */
+ long underflows; /* Number of stack underflow calls ($STKRETN). */
+ long stko_free; /* Number of deallocations by $STKRETN. */
+ long stkm_free; /* Number of deallocations by $STKMRET. */
+ long segments; /* Current number of stack segments. */
+ long maxs; /* Maximum number of stack segments so far. */
+ long pad_size; /* Stack pad size. */
+ long current_address; /* Current stack segment address. */
+ long current_size; /* Current stack segment size. This
+ number is actually corrupted by STKSTAT to
+ include the fifteen word trailer area. */
+ long initial_address; /* Address of initial segment. */
+ long initial_size; /* Size of initial segment. */
};
/* The following structure describes the data structure which trails
@@ -311,13 +300,13 @@ struct stk_stat
struct stk_trailer
{
- long this_address; /* Address of this block. */
- long this_size; /* Size of this block (does not include
- this trailer). */
+ long this_address; /* Address of this block. */
+ long this_size; /* Size of this block (does not include
+ this trailer). */
long unknown2;
long unknown3;
- long link; /* Address of trailer block of previous
- segment. */
+ long link; /* Address of trailer block of previous
+ segment. */
long unknown5;
long unknown6;
long unknown7;
@@ -355,8 +344,8 @@ i00afunc (long *address)
/* Set up the iteration. */
trailer = (struct stk_trailer *) (status.current_address
- + status.current_size
- - 15);
+ + status.current_size
+ - 15);
/* There must be at least one stack segment. Therefore it is
a fatal error if "trailer" is null. */
@@ -371,10 +360,10 @@ i00afunc (long *address)
block = (long *) trailer->this_address;
size = trailer->this_size;
if (block == 0 || size == 0)
- abort ();
+ abort ();
trailer = (struct stk_trailer *) trailer->link;
if ((block <= address) && (address < (block + size)))
- break;
+ break;
}
/* Set the result to the offset in this segment and add the sizes
@@ -390,7 +379,7 @@ i00afunc (long *address)
do
{
if (trailer->this_size <= 0)
- abort ();
+ abort ();
result += trailer->this_size;
trailer = (struct stk_trailer *) trailer->link;
}
@@ -453,7 +442,7 @@ i00afunc (long address)
fprintf (stderr, "%011o %011o %011o\n", this_segment, address, stkl);
# endif
if (pseg == 0)
- break;
+ break;
stkl = stkl - pseg;
ssptr = (struct stack_segment_linkage *) stkl;
size = ssptr->sssize;
@@ -486,4 +475,4 @@ i00afunc (long address)
# endif /* CRAY */
# endif /* no alloca */
-#endif /* not GCC version 2 */
+#endif /* not GCC 2 */
diff --git a/lib/alloca_.h b/lib/alloca.in.h
index dd0b3e9..d457ebb 100644
--- a/lib/alloca_.h
+++ b/lib/alloca.in.h
@@ -1,11 +1,11 @@
/* Memory allocation on the stack.
- Copyright (C) 1995, 1999, 2001, 2002, 2003, 2004, 2006 Free Software
- Foundation, Inc.
+ Copyright (C) 1995, 1999, 2001-2004, 2006-2016 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 2, or (at your option)
+ by the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -14,14 +14,14 @@
General Public License for more details.
You should have received a copy of the GNU General Public
- License along with this program; if not, write to the Free Software
- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
- USA. */
+ License along with this program; if not, see
+ <http://www.gnu.org/licenses/>.
+ */
/* Avoid using the symbol _ALLOCA_H here, as Bison assumes _ALLOCA_H
means there is a real alloca function. */
-#ifndef _GNULIB_ALLOCA_H
-# define _GNULIB_ALLOCA_H
+#ifndef _GL_ALLOCA_H
+#define _GL_ALLOCA_H
/* alloca (N) returns a pointer to N bytes of memory
allocated on the stack, which will last until the function returns.
@@ -42,6 +42,15 @@
# elif defined _MSC_VER
# include <malloc.h>
# define alloca _alloca
+# elif defined __DECC && defined __VMS
+# define alloca __ALLOCA
+# elif defined __TANDEM && defined _TNS_E_TARGET
+# ifdef __cplusplus
+extern "C"
+# endif
+void *_alloca (unsigned short);
+# pragma intrinsic (_alloca)
+# define alloca _alloca
# else
# include <stddef.h>
# ifdef __cplusplus
@@ -51,4 +60,4 @@ void *alloca (size_t);
# endif
#endif
-#endif /* _GNULIB_ALLOCA_H */
+#endif /* _GL_ALLOCA_H */
diff --git a/lib/allocator.c b/lib/allocator.c
new file mode 100644
index 0000000..2c1a3da
--- /dev/null
+++ b/lib/allocator.c
@@ -0,0 +1,5 @@
+#define _GL_USE_STDLIB_ALLOC 1
+#include <config.h>
+#include "allocator.h"
+#include <stdlib.h>
+struct allocator const stdlib_allocator = { malloc, realloc, free, NULL };
diff --git a/lib/allocator.h b/lib/allocator.h
new file mode 100644
index 0000000..1f1eab6
--- /dev/null
+++ b/lib/allocator.h
@@ -0,0 +1,58 @@
+/* Memory allocators such as malloc+free.
+
+ Copyright (C) 2011-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Paul Eggert. */
+
+#ifndef _GL_ALLOCATOR_H
+#define _GL_ALLOCATOR_H
+
+#include <stddef.h>
+
+/* An object describing a memory allocator family. */
+
+struct allocator
+{
+ /* Do not use GCC attributes such as __attribute__ ((malloc)) with
+ the function types pointed at by these members, because these
+ attributes do not work with pointers to functions. See
+ <http://lists.gnu.org/archive/html/bug-gnulib/2011-04/msg00007.html>. */
+
+ /* Call ALLOCATE to allocate memory, like 'malloc'. On failure ALLOCATE
+ should return NULL, though not necessarily set errno. When given
+ a zero size it may return NULL even if successful. */
+ void *(*allocate) (size_t);
+
+ /* If nonnull, call REALLOCATE to reallocate memory, like 'realloc'.
+ On failure REALLOCATE should return NULL, though not necessarily set
+ errno. When given a zero size it may return NULL even if
+ successful. */
+ void *(*reallocate) (void *, size_t);
+
+ /* Call FREE to free memory, like 'free'. */
+ void (*free) (void *);
+
+ /* If nonnull, call DIE (SIZE) if MALLOC (SIZE) or REALLOC (...,
+ SIZE) fails. DIE should not return. SIZE should equal SIZE_MAX
+ if size_t overflow was detected while calculating sizes to be
+ passed to MALLOC or REALLOC. */
+ void (*die) (size_t);
+};
+
+/* An allocator using the stdlib functions and a null DIE function. */
+extern struct allocator const stdlib_allocator;
+
+#endif /* _GL_ALLOCATOR_H */
diff --git a/lib/allocsa.c b/lib/allocsa.c
deleted file mode 100644
index 97652e6..0000000
--- a/lib/allocsa.c
+++ /dev/null
@@ -1,137 +0,0 @@
-/* Safe automatic memory allocation.
- Copyright (C) 2003, 2006 Free Software Foundation, Inc.
- Written by Bruno Haible <bruno@clisp.org>, 2003.
-
- 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-#include <config.h>
-
-/* Specification. */
-#include "allocsa.h"
-
-/* The speed critical point in this file is freesa() applied to an alloca()
- result: it must be fast, to match the speed of alloca(). The speed of
- mallocsa() and freesa() in the other case are not critical, because they
- are only invoked for big memory sizes. */
-
-#if HAVE_ALLOCA
-
-/* Store the mallocsa() results in a hash table. This is needed to reliably
- distinguish a mallocsa() result and an alloca() result.
-
- Although it is possible that the same pointer is returned by alloca() and
- by mallocsa() at different times in the same application, it does not lead
- to a bug in freesa(), because:
- - Before a pointer returned by alloca() can point into malloc()ed memory,
- the function must return, and once this has happened the programmer must
- not call freesa() on it anyway.
- - Before a pointer returned by mallocsa() can point into the stack, it
- must be freed. The only function that can free it is freesa(), and
- when freesa() frees it, it also removes it from the hash table. */
-
-#define MAGIC_NUMBER 0x1415fb4a
-#define MAGIC_SIZE sizeof (int)
-/* This is how the header info would look like without any alignment
- considerations. */
-struct preliminary_header { void *next; char room[MAGIC_SIZE]; };
-/* But the header's size must be a multiple of sa_alignment_max. */
-#define HEADER_SIZE \
- (((sizeof (struct preliminary_header) + sa_alignment_max - 1) / sa_alignment_max) * sa_alignment_max)
-struct header { void *next; char room[HEADER_SIZE - sizeof (struct preliminary_header) + MAGIC_SIZE]; };
-/* Verify that HEADER_SIZE == sizeof (struct header). */
-typedef int verify1[2 * (HEADER_SIZE == sizeof (struct header)) - 1];
-/* We make the hash table quite big, so that during lookups the probability
- of empty hash buckets is quite high. There is no need to make the hash
- table resizable, because when the hash table gets filled so much that the
- lookup becomes slow, it means that the application has memory leaks. */
-#define HASH_TABLE_SIZE 257
-static void * mallocsa_results[HASH_TABLE_SIZE];
-
-#endif
-
-void *
-mallocsa (size_t n)
-{
-#if HAVE_ALLOCA
- /* Allocate one more word, that serves as an indicator for malloc()ed
- memory, so that freesa() of an alloca() result is fast. */
- size_t nplus = n + HEADER_SIZE;
-
- if (nplus >= n)
- {
- char *p = (char *) malloc (nplus);
-
- if (p != NULL)
- {
- size_t slot;
-
- p += HEADER_SIZE;
-
- /* Put a magic number into the indicator word. */
- ((int *) p)[-1] = MAGIC_NUMBER;
-
- /* Enter p into the hash table. */
- slot = (unsigned long) p % HASH_TABLE_SIZE;
- ((struct header *) (p - HEADER_SIZE))->next = mallocsa_results[slot];
- mallocsa_results[slot] = p;
-
- return p;
- }
- }
- /* Out of memory. */
- return NULL;
-#else
-# if !MALLOC_0_IS_NONNULL
- if (n == 0)
- n = 1;
-# endif
- return malloc (n);
-#endif
-}
-
-#if HAVE_ALLOCA
-void
-freesa (void *p)
-{
- /* mallocsa() may have returned NULL. */
- if (p != NULL)
- {
- /* Attempt to quickly distinguish the mallocsa() result - which has
- a magic indicator word - and the alloca() result - which has an
- uninitialized indicator word. It is for this test that sa_increment
- additional bytes are allocated in the alloca() case. */
- if (((int *) p)[-1] == MAGIC_NUMBER)
- {
- /* Looks like a mallocsa() result. To see whether it really is one,
- perform a lookup in the hash table. */
- size_t slot = (unsigned long) p % HASH_TABLE_SIZE;
- void **chain = &mallocsa_results[slot];
- for (; *chain != NULL;)
- {
- if (*chain == p)
- {
- /* Found it. Remove it from the hash table and free it. */
- char *p_begin = (char *) p - HEADER_SIZE;
- *chain = ((struct header *) p_begin)->next;
- free (p_begin);
- return;
- }
- chain = &((struct header *) ((char *) *chain - HEADER_SIZE))->next;
- }
- }
- /* At this point, we know it was not a mallocsa() result. */
- }
-}
-#endif
diff --git a/lib/anytostr.c b/lib/anytostr.c
new file mode 100644
index 0000000..39aab0e
--- /dev/null
+++ b/lib/anytostr.c
@@ -0,0 +1,57 @@
+/* anytostr.c -- convert integers to printable strings
+
+ Copyright (C) 2001, 2006, 2008-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Paul Eggert */
+
+/* Tell gcc not to warn about the (i < 0) test, below. */
+#if (__GNUC__ == 4 && 3 <= __GNUC_MINOR__) || 4 < __GNUC__
+# pragma GCC diagnostic ignored "-Wtype-limits"
+#elif defined __clang__
+# pragma clang diagnostic ignored "-Wtautological-compare"
+#endif
+
+#include <config.h>
+
+#include "inttostr.h"
+
+/* Convert I to a printable string in BUF, which must be at least
+ INT_BUFSIZE_BOUND (INTTYPE) bytes long. Return the address of the
+ printable string, which need not start at BUF. */
+
+char * __attribute_warn_unused_result__
+anytostr (inttype i, char *buf)
+{
+ char *p = buf + INT_STRLEN_BOUND (inttype);
+ *p = 0;
+
+ if (i < 0)
+ {
+ do
+ *--p = '0' - i % 10;
+ while ((i /= 10) != 0);
+
+ *--p = '-';
+ }
+ else
+ {
+ do
+ *--p = '0' + i % 10;
+ while ((i /= 10) != 0);
+ }
+
+ return p;
+}
diff --git a/lib/xreadlink-with-size.c b/lib/areadlink-with-size.c
index 5524a8a..238ea47 100644
--- a/lib/xreadlink-with-size.c
+++ b/lib/areadlink-with-size.c
@@ -1,12 +1,12 @@
-/* xreadlink.c -- readlink wrapper to return the link name in malloc'd storage
+/* readlink wrapper to return the link name in malloc'd storage.
+ Unlike xreadlink and xreadlink_with_size, don't ever call exit.
- Copyright (C) 2001, 2003, 2004, 2005, 2006, 2007 Free Software
- Foundation, Inc.
+ Copyright (C) 2001, 2003-2007, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,26 +14,20 @@
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with this program; see the file COPYING.
- If not, write to the Free Software Foundation,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Jim Meyering <jim@meyering.net> */
#include <config.h>
-#include "xreadlink.h"
+#include "areadlink.h"
-#include <stdio.h>
#include <errno.h>
#include <limits.h>
-#include <sys/types.h>
+#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
-#ifndef SIZE_MAX
-# define SIZE_MAX ((size_t) -1)
-#endif
#ifndef SSIZE_MAX
# define SSIZE_MAX ((ssize_t) (SIZE_MAX / 2))
#endif
@@ -47,18 +41,15 @@
#define MAXSIZE (SIZE_MAX < SSIZE_MAX ? SIZE_MAX : SSIZE_MAX)
-#include "xalloc.h"
-
/* Call readlink to get the symbolic link value of FILE.
SIZE is a hint as to how long the link is expected to be;
typically it is taken from st_size. It need not be correct.
Return a pointer to that NUL-terminated string in malloc'd storage.
- If readlink fails, return NULL (caller may use errno to diagnose).
- If malloc fails, or if the link value is longer than SSIZE_MAX :-),
- give a diagnostic and exit. */
+ If readlink fails, malloc fails, or if the link value is longer
+ than SSIZE_MAX, return NULL (caller may use errno to diagnose). */
char *
-xreadlink_with_size (char const *file, size_t size)
+areadlink_with_size (char const *file, size_t size)
{
/* Some buggy file systems report garbage in st_size. Defend
against them by ignoring outlandish st_size values in the initial
@@ -66,40 +57,48 @@ xreadlink_with_size (char const *file, size_t size)
size_t symlink_max = SYMLINK_MAX;
size_t INITIAL_LIMIT_BOUND = 8 * 1024;
size_t initial_limit = (symlink_max < INITIAL_LIMIT_BOUND
- ? symlink_max + 1
- : INITIAL_LIMIT_BOUND);
+ ? symlink_max + 1
+ : INITIAL_LIMIT_BOUND);
/* The initial buffer size for the link value. */
size_t buf_size = size < initial_limit ? size + 1 : initial_limit;
while (1)
{
- char *buffer = xmalloc (buf_size);
- ssize_t r = readlink (file, buffer, buf_size);
- size_t link_length = r;
+ ssize_t r;
+ size_t link_length;
+ char *buffer = malloc (buf_size);
+
+ if (buffer == NULL)
+ return NULL;
+ r = readlink (file, buffer, buf_size);
+ link_length = r;
/* On AIX 5L v5.3 and HP-UX 11i v2 04/09, readlink returns -1
- with errno == ERANGE if the buffer is too small. */
+ with errno == ERANGE if the buffer is too small. */
if (r < 0 && errno != ERANGE)
- {
- int saved_errno = errno;
- free (buffer);
- errno = saved_errno;
- return NULL;
- }
+ {
+ int saved_errno = errno;
+ free (buffer);
+ errno = saved_errno;
+ return NULL;
+ }
if (link_length < buf_size)
- {
- buffer[link_length] = 0;
- return buffer;
- }
+ {
+ buffer[link_length] = 0;
+ return buffer;
+ }
free (buffer);
if (buf_size <= MAXSIZE / 2)
- buf_size *= 2;
+ buf_size *= 2;
else if (buf_size < MAXSIZE)
- buf_size = MAXSIZE;
+ buf_size = MAXSIZE;
else
- xalloc_die ();
+ {
+ errno = ENOMEM;
+ return NULL;
+ }
}
}
diff --git a/lib/areadlink.c b/lib/areadlink.c
new file mode 100644
index 0000000..fee84a3
--- /dev/null
+++ b/lib/areadlink.c
@@ -0,0 +1,56 @@
+/* areadlink.c -- readlink wrapper to return the link name in malloc'd storage
+ Unlike xreadlink and xreadlink_with_size, don't ever call exit.
+
+ Copyright (C) 2001, 2003-2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Jim Meyering <jim@meyering.net>
+ and Bruno Haible <bruno@clisp.org>. */
+
+#include <config.h>
+
+/* Specification. */
+#include "areadlink.h"
+
+#include "careadlinkat.h"
+
+#include <stdlib.h>
+#include <unistd.h>
+
+/* Get the symbolic link value of FILENAME and put it into BUFFER, with
+ size BUFFER_SIZE. This function acts like readlink but has
+ readlinkat's signature. */
+static ssize_t
+careadlinkatcwd (int fd, char const *filename, char *buffer,
+ size_t buffer_size)
+{
+ /* FD must be AT_FDCWD here, otherwise the caller is using this
+ function in contexts it was not meant for. */
+ if (fd != AT_FDCWD)
+ abort ();
+ return readlink (filename, buffer, buffer_size);
+}
+
+/* Call readlink to get the symbolic link value of FILENAME.
+ Return a pointer to that NUL-terminated string in malloc'd storage.
+ If readlink fails, return NULL and set errno.
+ If allocation fails, or if the link value is longer than SIZE_MAX :-),
+ return NULL and set errno to ENOMEM. */
+
+char *
+areadlink (char const *filename)
+{
+ return careadlinkat (AT_FDCWD, filename, NULL, 0, NULL, careadlinkatcwd);
+}
diff --git a/lib/areadlink.h b/lib/areadlink.h
new file mode 100644
index 0000000..829c959
--- /dev/null
+++ b/lib/areadlink.h
@@ -0,0 +1,33 @@
+/* Read symbolic links without size limitation.
+
+ Copyright (C) 2001, 2003-2004, 2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Jim Meyering <jim@meyering.net> */
+
+#include <stddef.h>
+
+extern char *areadlink (char const *filename);
+extern char *areadlink_with_size (char const *filename, size_t size_hint);
+
+#if GNULIB_AREADLINKAT
+extern char *areadlinkat (int fd, char const *filename);
+#endif
+
+#if GNULIB_AREADLINKAT_WITH_SIZE
+extern char *areadlinkat_with_size (int fd, char const *filename,
+ size_t size_hint);
+#endif
diff --git a/lib/areadlinkat.c b/lib/areadlinkat.c
new file mode 100644
index 0000000..4a08879
--- /dev/null
+++ b/lib/areadlinkat.c
@@ -0,0 +1,65 @@
+/* areadlinkat.c -- readlinkat wrapper to return malloc'd link name
+ Unlike xreadlinkat, only call exit on failure to change directory.
+
+ Copyright (C) 2001, 2003-2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Jim Meyering <jim@meyering.net>,
+ and Bruno Haible <bruno@clisp.org>,
+ and Eric Blake <ebb9@byu.net>. */
+
+#include <config.h>
+
+/* Specification. */
+#include "areadlink.h"
+
+#include "careadlinkat.h"
+
+#if HAVE_READLINKAT
+
+/* Call readlinkat to get the symbolic link value of FILENAME relative to FD.
+ Return a pointer to that NUL-terminated string in malloc'd storage.
+ If readlinkat fails, return NULL and set errno (although failure to
+ change directory will issue a diagnostic and exit).
+ If allocation fails, or if the link value is longer than SIZE_MAX :-),
+ return NULL and set errno to ENOMEM. */
+
+char *
+areadlinkat (int fd, char const *filename)
+{
+ return careadlinkat (fd, filename, NULL, 0, NULL, readlinkat);
+}
+
+#else /* !HAVE_READLINKAT */
+
+/* It is more efficient to change directories only once and call
+ areadlink, rather than repeatedly call the replacement
+ readlinkat. */
+
+# define AT_FUNC_NAME areadlinkat
+# define AT_FUNC_F1 areadlink
+# define AT_FUNC_POST_FILE_PARAM_DECLS /* empty */
+# define AT_FUNC_POST_FILE_ARGS /* empty */
+# define AT_FUNC_RESULT char *
+# define AT_FUNC_FAIL NULL
+# include "at-func.c"
+# undef AT_FUNC_NAME
+# undef AT_FUNC_F1
+# undef AT_FUNC_POST_FILE_PARAM_DECLS
+# undef AT_FUNC_POST_FILE_ARGS
+# undef AT_FUNC_RESULT
+# undef AT_FUNC_FAIL
+
+#endif /* !HAVE_READLINKAT */
diff --git a/lib/argmatch.c b/lib/argmatch.c
index 72d9248..bd1ad71 100644
--- a/lib/argmatch.c
+++ b/lib/argmatch.c
@@ -1,12 +1,12 @@
/* argmatch.c -- find a match for a string in an array
- Copyright (C) 1990, 1998, 1999, 2001, 2002, 2003, 2004, 2005, 2006, 2007
- Free Software Foundation, Inc.
+ Copyright (C) 1990, 1998-1999, 2001-2007, 2009-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by David MacKenzie <djm@ai.mit.edu>
Modified by Akim Demaille <demaille@inf.enst.fr> */
@@ -78,16 +77,16 @@ argmatch_exit_fn argmatch_die = __argmatch_die;
synonyms, i.e., for
"yes", "yop" -> 0
"no", "nope" -> 1
- "y" is a valid argument, for `0', and "n" for `1'. */
+ "y" is a valid argument, for 0, and "n" for 1. */
ptrdiff_t
argmatch (const char *arg, const char *const *arglist,
- const char *vallist, size_t valsize)
+ const char *vallist, size_t valsize)
{
- size_t i; /* Temporary index in ARGLIST. */
- size_t arglen; /* Length of ARG. */
- ptrdiff_t matchind = -1; /* Index of first nonexact match. */
- bool ambiguous = false; /* If true, multiple nonexact match(es). */
+ size_t i; /* Temporary index in ARGLIST. */
+ size_t arglen; /* Length of ARG. */
+ ptrdiff_t matchind = -1; /* Index of first nonexact match. */
+ bool ambiguous = false; /* If true, multiple nonexact match(es). */
arglen = strlen (arg);
@@ -95,26 +94,26 @@ argmatch (const char *arg, const char *const *arglist,
for (i = 0; arglist[i]; i++)
{
if (!strncmp (arglist[i], arg, arglen))
- {
- if (strlen (arglist[i]) == arglen)
- /* Exact match found. */
- return i;
- else if (matchind == -1)
- /* First nonexact match found. */
- matchind = i;
- else
- {
- /* Second nonexact match found. */
- if (vallist == NULL
- || memcmp (vallist + valsize * matchind,
- vallist + valsize * i, valsize))
- {
- /* There is a real ambiguity, or we could not
- disambiguate. */
- ambiguous = true;
- }
- }
- }
+ {
+ if (strlen (arglist[i]) == arglen)
+ /* Exact match found. */
+ return i;
+ else if (matchind == -1)
+ /* First nonexact match found. */
+ matchind = i;
+ else
+ {
+ /* Second nonexact match found. */
+ if (vallist == NULL
+ || memcmp (vallist + valsize * matchind,
+ vallist + valsize * i, valsize))
+ {
+ /* There is a real ambiguity, or we could not
+ disambiguate. */
+ ambiguous = true;
+ }
+ }
+ }
}
if (ambiguous)
return -2;
@@ -131,11 +130,11 @@ void
argmatch_invalid (const char *context, const char *value, ptrdiff_t problem)
{
char const *format = (problem == -1
- ? _("invalid argument %s for %s")
- : _("ambiguous argument %s for %s"));
+ ? _("invalid argument %s for %s")
+ : _("ambiguous argument %s for %s"));
error (0, 0, format, quotearg_n_style (0, ARGMATCH_QUOTING_STYLE, value),
- quote_n (1, context));
+ quote_n (1, context));
}
/* List the valid arguments for argmatch.
@@ -144,24 +143,24 @@ argmatch_invalid (const char *context, const char *value, ptrdiff_t problem)
VALSIZE is the size of the elements of VALLIST */
void
argmatch_valid (const char *const *arglist,
- const char *vallist, size_t valsize)
+ const char *vallist, size_t valsize)
{
size_t i;
const char *last_val = NULL;
/* We try to put synonyms on the same line. The assumption is that
synonyms follow each other */
- fprintf (stderr, _("Valid arguments are:"));
+ fputs (_("Valid arguments are:"), stderr);
for (i = 0; arglist[i]; i++)
if ((i == 0)
- || memcmp (last_val, vallist + valsize * i, valsize))
+ || memcmp (last_val, vallist + valsize * i, valsize))
{
- fprintf (stderr, "\n - `%s'", arglist[i]);
- last_val = vallist + valsize * i;
+ fprintf (stderr, "\n - %s", quote (arglist[i]));
+ last_val = vallist + valsize * i;
}
else
{
- fprintf (stderr, ", `%s'", arglist[i]);
+ fprintf (stderr, ", %s", quote (arglist[i]));
}
putc ('\n', stderr);
}
@@ -174,9 +173,9 @@ argmatch_valid (const char *const *arglist,
ptrdiff_t
__xargmatch_internal (const char *context,
- const char *arg, const char *const *arglist,
- const char *vallist, size_t valsize,
- argmatch_exit_fn exit_fn)
+ const char *arg, const char *const *arglist,
+ const char *vallist, size_t valsize,
+ argmatch_exit_fn exit_fn)
{
ptrdiff_t res = argmatch (arg, arglist, vallist, valsize);
if (res >= 0)
@@ -195,8 +194,8 @@ __xargmatch_internal (const char *context,
return the first corresponding argument in ARGLIST */
const char *
argmatch_to_argument (const char *value,
- const char *const *arglist,
- const char *vallist, size_t valsize)
+ const char *const *arglist,
+ const char *vallist, size_t valsize)
{
size_t i;
@@ -264,14 +263,14 @@ main (int argc, const char *const *argv)
if ((cp = getenv ("VERSION_CONTROL")))
backup_type = XARGMATCH ("$VERSION_CONTROL", cp,
- backup_args, backup_vals);
+ backup_args, backup_vals);
if (argc == 2)
backup_type = XARGMATCH (program_name, argv[1],
- backup_args, backup_vals);
+ backup_args, backup_vals);
- printf ("The version control is `%s'\n",
- ARGMATCH_TO_ARGUMENT (backup_type, backup_args, backup_vals));
+ printf ("The version control is '%s'\n",
+ ARGMATCH_TO_ARGUMENT (backup_type, backup_args, backup_vals));
return 0;
}
diff --git a/lib/argmatch.h b/lib/argmatch.h
index f2dfe59..43cda5a 100644
--- a/lib/argmatch.h
+++ b/lib/argmatch.h
@@ -1,12 +1,12 @@
/* argmatch.h -- definitions and prototypes for argmatch.c
- Copyright (C) 1990, 1998, 1999, 2001, 2002, 2004, 2005 Free Software
+ Copyright (C) 1990, 1998-1999, 2001-2002, 2004-2005, 2009-2016 Free Software
Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by David MacKenzie <djm@ai.mit.edu>
Modified by Akim Demaille <demaille@inf.enst.fr> */
@@ -27,6 +26,10 @@
# include "verify.h"
+#ifdef __cplusplus
+extern "C" {
+#endif
+
# define ARRAY_CARDINALITY(Array) (sizeof (Array) / sizeof *(Array))
/* Assert there are as many real arguments as there are values
@@ -41,21 +44,21 @@
to the same values in VALLIST). */
ptrdiff_t argmatch (char const *arg, char const *const *arglist,
- char const *vallist, size_t valsize);
+ char const *vallist, size_t valsize) _GL_ATTRIBUTE_PURE;
# define ARGMATCH(Arg, Arglist, Vallist) \
argmatch (Arg, Arglist, (char const *) (Vallist), sizeof *(Vallist))
/* xargmatch calls this function when it fails. This function should not
return. By default, this is a function that calls ARGMATCH_DIE which
- in turn defaults to `exit (exit_failure)'. */
+ in turn defaults to 'exit (exit_failure)'. */
typedef void (*argmatch_exit_fn) (void);
extern argmatch_exit_fn argmatch_die;
/* Report on stderr why argmatch failed. Report correct values. */
void argmatch_invalid (char const *context, char const *value,
- ptrdiff_t problem);
+ ptrdiff_t problem);
/* Left for compatibility with the old name invalid_arg */
@@ -67,37 +70,42 @@ void argmatch_invalid (char const *context, char const *value,
/* Report on stderr the list of possible arguments. */
void argmatch_valid (char const *const *arglist,
- char const *vallist, size_t valsize);
+ char const *vallist, size_t valsize);
# define ARGMATCH_VALID(Arglist, Vallist) \
argmatch_valid (Arglist, (char const *) (Vallist), sizeof *(Vallist))
-/* Same as argmatch, but upon failure, reports a explanation on the
- failure, and exits using the function EXIT_FN. */
+/* Same as argmatch, but upon failure, report an explanation of the
+ failure, and exit using the function EXIT_FN. */
ptrdiff_t __xargmatch_internal (char const *context,
- char const *arg, char const *const *arglist,
- char const *vallist, size_t valsize,
- argmatch_exit_fn exit_fn);
+ char const *arg, char const *const *arglist,
+ char const *vallist, size_t valsize,
+ argmatch_exit_fn exit_fn);
/* Programmer friendly interface to __xargmatch_internal. */
-# define XARGMATCH(Context, Arg, Arglist, Vallist) \
- ((Vallist) [__xargmatch_internal (Context, Arg, Arglist, \
- (char const *) (Vallist), \
- sizeof *(Vallist), \
- argmatch_die)])
+# define XARGMATCH(Context, Arg, Arglist, Vallist) \
+ ((Vallist) [__xargmatch_internal (Context, Arg, Arglist, \
+ (char const *) (Vallist), \
+ sizeof *(Vallist), \
+ argmatch_die)])
/* Convert a value into a corresponding argument. */
char const *argmatch_to_argument (char const *value,
- char const *const *arglist,
- char const *vallist, size_t valsize);
+ char const *const *arglist,
+ char const *vallist, size_t valsize)
+ _GL_ATTRIBUTE_PURE;
+
+# define ARGMATCH_TO_ARGUMENT(Value, Arglist, Vallist) \
+ argmatch_to_argument (Value, Arglist, \
+ (char const *) (Vallist), sizeof *(Vallist))
-# define ARGMATCH_TO_ARGUMENT(Value, Arglist, Vallist) \
- argmatch_to_argument (Value, Arglist, \
- (char const *) (Vallist), sizeof *(Vallist))
+#ifdef __cplusplus
+}
+#endif
#endif /* ARGMATCH_H_ */
diff --git a/lib/argv-iter.c b/lib/argv-iter.c
new file mode 100644
index 0000000..8f05e58
--- /dev/null
+++ b/lib/argv-iter.c
@@ -0,0 +1,111 @@
+/* Iterate over arguments from argv or --files0-from=FILE
+ Copyright (C) 2008-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Jim Meyering. */
+
+#include <config.h>
+#include "argv-iter.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+struct argv_iterator
+{
+ /* Test FP to determine whether in read-mode or argv-mode. */
+ /* file-mode: fp records position */
+ FILE *fp;
+ size_t item_idx;
+ char *tok;
+ size_t buf_len;
+
+ /* argv-mode: record just argv and current pointer */
+ char **arg_list;
+ char **p;
+};
+
+struct argv_iterator *
+argv_iter_init_argv (char **argv)
+{
+ struct argv_iterator *ai = malloc (sizeof *ai);
+ if (!ai)
+ return NULL;
+ ai->fp = NULL;
+ ai->arg_list = argv;
+ ai->p = argv;
+ return ai;
+}
+
+/* Initialize to read from the stream, FP.
+ The input is expected to contain a list of NUL-delimited tokens. */
+struct argv_iterator *
+argv_iter_init_stream (FILE *fp)
+{
+ struct argv_iterator *ai = malloc (sizeof *ai);
+ if (!ai)
+ return NULL;
+ ai->fp = fp;
+ ai->tok = NULL;
+ ai->buf_len = 0;
+
+ ai->item_idx = 0;
+ ai->arg_list = NULL;
+ return ai;
+}
+
+char *
+argv_iter (struct argv_iterator *ai, enum argv_iter_err *err)
+{
+ if (ai->fp)
+ {
+ ssize_t len = getdelim (&ai->tok, &ai->buf_len, '\0', ai->fp);
+ if (len < 0)
+ {
+ *err = feof (ai->fp) ? AI_ERR_EOF : AI_ERR_READ;
+ return NULL;
+ }
+
+ *err = AI_ERR_OK;
+ ai->item_idx++;
+ return ai->tok;
+ }
+ else
+ {
+ if (*(ai->p) == NULL)
+ {
+ *err = AI_ERR_EOF;
+ return NULL;
+ }
+ else
+ {
+ *err = AI_ERR_OK;
+ return *(ai->p++);
+ }
+ }
+}
+
+size_t
+argv_iter_n_args (struct argv_iterator const *ai)
+{
+ return ai->fp ? ai->item_idx : ai->p - ai->arg_list;
+}
+
+void
+argv_iter_free (struct argv_iterator *ai)
+{
+ if (ai->fp)
+ free (ai->tok);
+ free (ai);
+}
diff --git a/lib/argv-iter.h b/lib/argv-iter.h
new file mode 100644
index 0000000..c9dcfed
--- /dev/null
+++ b/lib/argv-iter.h
@@ -0,0 +1,42 @@
+/* Iterate over arguments from argv or --files0-from=FILE
+ Copyright (C) 2008-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <stdio.h>
+#include <stdbool.h>
+
+/* Definition of _GL_ARG_NONNULL. */
+#include "arg-nonnull.h"
+
+struct argv_iterator;
+
+enum argv_iter_err
+{
+ AI_ERR_OK = 1,
+ AI_ERR_EOF,
+ AI_ERR_MEM,
+ AI_ERR_READ
+};
+
+struct argv_iterator *argv_iter_init_argv (char **argv)
+ _GL_ARG_NONNULL ((1));
+struct argv_iterator *argv_iter_init_stream (FILE *fp)
+ _GL_ARG_NONNULL ((1));
+char *argv_iter (struct argv_iterator *, enum argv_iter_err *)
+ _GL_ARG_NONNULL ((1, 2));
+size_t argv_iter_n_args (struct argv_iterator const *)
+ _GL_ATTRIBUTE_PURE _GL_ARG_NONNULL ((1));
+void argv_iter_free (struct argv_iterator *)
+ _GL_ARG_NONNULL ((1));
diff --git a/lib/arpa_inet.in.h b/lib/arpa_inet.in.h
new file mode 100644
index 0000000..026c4dc
--- /dev/null
+++ b/lib/arpa_inet.in.h
@@ -0,0 +1,140 @@
+/* A GNU-like <arpa/inet.h>.
+
+ Copyright (C) 2005-2006, 2008-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _@GUARD_PREFIX@_ARPA_INET_H
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+#if @HAVE_FEATURES_H@
+# include <features.h> /* for __GLIBC__ */
+#endif
+
+/* Gnulib's sys/socket.h is responsible for defining socklen_t (used below) and
+ for pulling in winsock2.h etc. under MinGW.
+ But avoid namespace pollution on glibc systems. */
+#ifndef __GLIBC__
+# include <sys/socket.h>
+#endif
+
+/* On NonStop Kernel, inet_ntop and inet_pton are declared in <netdb.h>.
+ But avoid namespace pollution on glibc systems. */
+#if defined __TANDEM && !defined __GLIBC__
+# include <netdb.h>
+#endif
+
+#if @HAVE_ARPA_INET_H@
+
+/* The include_next requires a split double-inclusion guard. */
+# @INCLUDE_NEXT@ @NEXT_ARPA_INET_H@
+
+#endif
+
+#ifndef _@GUARD_PREFIX@_ARPA_INET_H
+#define _@GUARD_PREFIX@_ARPA_INET_H
+
+/* The definitions of _GL_FUNCDECL_RPL etc. are copied here. */
+
+/* The definition of _GL_ARG_NONNULL is copied here. */
+
+/* The definition of _GL_WARN_ON_USE is copied here. */
+
+
+#if @GNULIB_INET_NTOP@
+/* Converts an internet address from internal format to a printable,
+ presentable format.
+ AF is an internet address family, such as AF_INET or AF_INET6.
+ SRC points to a 'struct in_addr' (for AF_INET) or 'struct in6_addr'
+ (for AF_INET6).
+ DST points to a buffer having room for CNT bytes.
+ The printable representation of the address (in numeric form, not
+ surrounded by [...], no reverse DNS is done) is placed in DST, and
+ DST is returned. If an error occurs, the return value is NULL and
+ errno is set. If CNT bytes are not sufficient to hold the result,
+ the return value is NULL and errno is set to ENOSPC. A good value
+ for CNT is 46.
+
+ For more details, see the POSIX:2001 specification
+ <http://www.opengroup.org/susv3xsh/inet_ntop.html>. */
+# if @REPLACE_INET_NTOP@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef inet_ntop
+# define inet_ntop rpl_inet_ntop
+# endif
+_GL_FUNCDECL_RPL (inet_ntop, const char *,
+ (int af, const void *restrict src,
+ char *restrict dst, socklen_t cnt)
+ _GL_ARG_NONNULL ((2, 3)));
+_GL_CXXALIAS_RPL (inet_ntop, const char *,
+ (int af, const void *restrict src,
+ char *restrict dst, socklen_t cnt));
+# else
+# if !@HAVE_DECL_INET_NTOP@
+_GL_FUNCDECL_SYS (inet_ntop, const char *,
+ (int af, const void *restrict src,
+ char *restrict dst, socklen_t cnt)
+ _GL_ARG_NONNULL ((2, 3)));
+# endif
+/* Need to cast, because on NonStop Kernel, the fourth parameter is
+ size_t cnt. */
+_GL_CXXALIAS_SYS_CAST (inet_ntop, const char *,
+ (int af, const void *restrict src,
+ char *restrict dst, socklen_t cnt));
+# endif
+_GL_CXXALIASWARN (inet_ntop);
+#elif defined GNULIB_POSIXCHECK
+# undef inet_ntop
+# if HAVE_RAW_DECL_INET_NTOP
+_GL_WARN_ON_USE (inet_ntop, "inet_ntop is unportable - "
+ "use gnulib module inet_ntop for portability");
+# endif
+#endif
+
+#if @GNULIB_INET_PTON@
+# if @REPLACE_INET_PTON@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef inet_pton
+# define inet_pton rpl_inet_pton
+# endif
+_GL_FUNCDECL_RPL (inet_pton, int,
+ (int af, const char *restrict src, void *restrict dst)
+ _GL_ARG_NONNULL ((2, 3)));
+_GL_CXXALIAS_RPL (inet_pton, int,
+ (int af, const char *restrict src, void *restrict dst));
+# else
+# if !@HAVE_DECL_INET_PTON@
+_GL_FUNCDECL_SYS (inet_pton, int,
+ (int af, const char *restrict src, void *restrict dst)
+ _GL_ARG_NONNULL ((2, 3)));
+# endif
+_GL_CXXALIAS_SYS (inet_pton, int,
+ (int af, const char *restrict src, void *restrict dst));
+# endif
+_GL_CXXALIASWARN (inet_pton);
+#elif defined GNULIB_POSIXCHECK
+# undef inet_pton
+# if HAVE_RAW_DECL_INET_PTON
+_GL_WARN_ON_USE (inet_pton, "inet_pton is unportable - "
+ "use gnulib module inet_pton for portability");
+# endif
+#endif
+
+
+#endif /* _@GUARD_PREFIX@_ARPA_INET_H */
+#endif /* _@GUARD_PREFIX@_ARPA_INET_H */
diff --git a/lib/asnprintf.c b/lib/asnprintf.c
index 26c3988..f23b776 100644
--- a/lib/asnprintf.c
+++ b/lib/asnprintf.c
@@ -1,9 +1,9 @@
/* Formatted output to strings.
- Copyright (C) 1999, 2002, 2006 Free Software Foundation, Inc.
+ Copyright (C) 1999, 2002, 2006, 2009-2016 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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -12,8 +12,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ with this program; if not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
diff --git a/lib/asprintf.c b/lib/asprintf.c
index 29ac6cf..d0ca5f2 100644
--- a/lib/asprintf.c
+++ b/lib/asprintf.c
@@ -1,9 +1,10 @@
/* Formatted output to strings.
- Copyright (C) 1999, 2002, 2006 Free Software Foundation, Inc.
+ Copyright (C) 1999, 2002, 2006-2007, 2009-2016 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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -12,13 +13,16 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ with this program; if not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
/* Specification. */
-#include "vasprintf.h"
+#ifdef IN_LIBASPRINTF
+# include "vasprintf.h"
+#else
+# include <stdio.h>
+#endif
#include <stdarg.h>
diff --git a/lib/assure.h b/lib/assure.h
new file mode 100644
index 0000000..de1f665
--- /dev/null
+++ b/lib/assure.h
@@ -0,0 +1,37 @@
+/* Run-time assert-like macros.
+
+ Copyright (C) 2014-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Paul Eggert. */
+
+#ifndef _GL_ASSURE_H
+#define _GL_ASSURE_H
+
+#include <assert.h>
+
+/* Check E's value at runtime, and report an error and abort if not.
+ However, do nothng if NDEBUG is defined.
+
+ Unlike standard 'assert', this macro always compiles E even when NDEBUG
+ is defined, so as to catch typos and avoid some GCC warnings. */
+
+#ifdef NDEBUG
+# define assure(E) ((void) (0 && (E)))
+#else
+# define assure(E) assert (E)
+#endif
+
+#endif
diff --git a/lib/at-func.c b/lib/at-func.c
index f98c207..5a8894a 100644
--- a/lib/at-func.c
+++ b/lib/at-func.c
@@ -1,10 +1,10 @@
-/* Define an at-style functions like fstatat, unlinkat, fchownat, etc.
- Copyright (C) 2006 Free Software Foundation, Inc.
+/* Define at-style functions like fstatat, unlinkat, fchownat, etc.
+ Copyright (C) 2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -12,67 +12,123 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* written by Jim Meyering */
-#define CALL_FUNC(F) \
- (AT_FUNC_USE_F1_COND \
- ? AT_FUNC_F1 (F AT_FUNC_POST_FILE_ARGS) \
+#include "dosname.h" /* solely for definition of IS_ABSOLUTE_FILE_NAME */
+
+#ifdef GNULIB_SUPPORT_ONLY_AT_FDCWD
+# include <errno.h>
+# ifndef ENOTSUP
+# define ENOTSUP EINVAL
+# endif
+#else
+# include "openat.h"
+# include "openat-priv.h"
+# include "save-cwd.h"
+#endif
+
+#ifdef AT_FUNC_USE_F1_COND
+# define CALL_FUNC(F) \
+ (flag == AT_FUNC_USE_F1_COND \
+ ? AT_FUNC_F1 (F AT_FUNC_POST_FILE_ARGS) \
: AT_FUNC_F2 (F AT_FUNC_POST_FILE_ARGS))
+# define VALIDATE_FLAG(F) \
+ if (flag & ~AT_FUNC_USE_F1_COND) \
+ { \
+ errno = EINVAL; \
+ return FUNC_FAIL; \
+ }
+#else
+# define CALL_FUNC(F) (AT_FUNC_F1 (F AT_FUNC_POST_FILE_ARGS))
+# define VALIDATE_FLAG(F) /* empty */
+#endif
+
+#ifdef AT_FUNC_RESULT
+# define FUNC_RESULT AT_FUNC_RESULT
+#else
+# define FUNC_RESULT int
+#endif
-/* Call AT_FUNC_F1 or AT_FUNC_F2 (testing AT_FUNC_USE_F1_COND to
- determine which) to operate on FILE, which is in the directory
- open on descriptor FD. If possible, do it without changing the
+#ifdef AT_FUNC_FAIL
+# define FUNC_FAIL AT_FUNC_FAIL
+#else
+# define FUNC_FAIL -1
+#endif
+
+/* Call AT_FUNC_F1 to operate on FILE, which is in the directory
+ open on descriptor FD. If AT_FUNC_USE_F1_COND is defined to a value,
+ AT_FUNC_POST_FILE_PARAM_DECLS must include a parameter named flag;
+ call AT_FUNC_F2 if FLAG is 0 or fail if FLAG contains more bits than
+ AT_FUNC_USE_F1_COND. Return int and fail with -1 unless AT_FUNC_RESULT
+ or AT_FUNC_FAIL are defined. If possible, do it without changing the
working directory. Otherwise, resort to using save_cwd/fchdir,
then AT_FUNC_F?/restore_cwd. If either the save_cwd or the restore_cwd
fails, then give a diagnostic and exit nonzero. */
-int
+FUNC_RESULT
AT_FUNC_NAME (int fd, char const *file AT_FUNC_POST_FILE_PARAM_DECLS)
{
- struct saved_cwd saved_cwd;
- int saved_errno;
- int err;
+ VALIDATE_FLAG (flag);
if (fd == AT_FDCWD || IS_ABSOLUTE_FILE_NAME (file))
return CALL_FUNC (file);
+#ifdef GNULIB_SUPPORT_ONLY_AT_FDCWD
+ errno = ENOTSUP;
+ return FUNC_FAIL;
+#else
{
- char buf[OPENAT_BUFFER_SIZE];
- char *proc_file = openat_proc_name (buf, fd, file);
+ /* Be careful to choose names unlikely to conflict with
+ AT_FUNC_POST_FILE_PARAM_DECLS. */
+ struct saved_cwd saved_cwd;
+ int saved_errno;
+ FUNC_RESULT err;
+
+ {
+ char proc_buf[OPENAT_BUFFER_SIZE];
+ char *proc_file = openat_proc_name (proc_buf, fd, file);
if (proc_file)
{
- int proc_result = CALL_FUNC (proc_file);
- int proc_errno = errno;
- if (proc_file != buf)
- free (proc_file);
- /* If the syscall succeeds, or if it fails with an unexpected
- errno value, then return right away. Otherwise, fall through
- and resort to using save_cwd/restore_cwd. */
- if (0 <= proc_result)
- return proc_result;
- if (! EXPECTED_ERRNO (proc_errno))
- {
- errno = proc_errno;
- return proc_result;
- }
+ FUNC_RESULT proc_result = CALL_FUNC (proc_file);
+ int proc_errno = errno;
+ if (proc_file != proc_buf)
+ free (proc_file);
+ /* If the syscall succeeds, or if it fails with an unexpected
+ errno value, then return right away. Otherwise, fall through
+ and resort to using save_cwd/restore_cwd. */
+ if (FUNC_FAIL != proc_result)
+ return proc_result;
+ if (! EXPECTED_ERRNO (proc_errno))
+ {
+ errno = proc_errno;
+ return proc_result;
+ }
}
}
if (save_cwd (&saved_cwd) != 0)
openat_save_fail (errno);
+ if (0 <= fd && fd == saved_cwd.desc)
+ {
+ /* If saving the working directory collides with the user's
+ requested fd, then the user's fd must have been closed to
+ begin with. */
+ free_cwd (&saved_cwd);
+ errno = EBADF;
+ return FUNC_FAIL;
+ }
if (fchdir (fd) != 0)
{
saved_errno = errno;
free_cwd (&saved_cwd);
errno = saved_errno;
- return -1;
+ return FUNC_FAIL;
}
err = CALL_FUNC (file);
- saved_errno = (err < 0 ? errno : 0);
+ saved_errno = (err == FUNC_FAIL ? errno : 0);
if (restore_cwd (&saved_cwd) != 0)
openat_restore_fail (errno);
@@ -82,5 +138,9 @@ AT_FUNC_NAME (int fd, char const *file AT_FUNC_POST_FILE_PARAM_DECLS)
if (saved_errno)
errno = saved_errno;
return err;
+ }
+#endif
}
#undef CALL_FUNC
+#undef FUNC_RESULT
+#undef FUNC_FAIL
diff --git a/lib/at-func2.c b/lib/at-func2.c
new file mode 100644
index 0000000..0dd2c71
--- /dev/null
+++ b/lib/at-func2.c
@@ -0,0 +1,282 @@
+/* Define 2-FD at-style functions like linkat or renameat.
+ Copyright (C) 2006, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* written by Jim Meyering and Eric Blake */
+
+#include <config.h>
+
+#include "openat-priv.h"
+
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "dosname.h" /* solely for definition of IS_ABSOLUTE_FILE_NAME */
+#include "filenamecat.h"
+#include "openat.h"
+#include "same-inode.h"
+#include "save-cwd.h"
+
+/* Call FUNC to operate on a pair of files, where FILE1 is relative to FD1,
+ and FILE2 is relative to FD2. If possible, do it without changing the
+ working directory. Otherwise, resort to using save_cwd/fchdir,
+ FUNC, restore_cwd (up to two times). If either the save_cwd or the
+ restore_cwd fails, then give a diagnostic and exit nonzero. */
+int
+at_func2 (int fd1, char const *file1,
+ int fd2, char const *file2,
+ int (*func) (char const *file1, char const *file2))
+{
+ struct saved_cwd saved_cwd;
+ int saved_errno;
+ int err;
+ char *file1_alt;
+ char *file2_alt;
+ struct stat st1;
+ struct stat st2;
+
+ /* There are 16 possible scenarios, based on whether an fd is
+ AT_FDCWD or real, and whether a file is absolute or relative:
+
+ fd1 file1 fd2 file2 action
+ 0 cwd abs cwd abs direct call
+ 1 cwd abs cwd rel direct call
+ 2 cwd abs fd abs direct call
+ 3 cwd abs fd rel chdir to fd2
+ 4 cwd rel cwd abs direct call
+ 5 cwd rel cwd rel direct call
+ 6 cwd rel fd abs direct call
+ 7 cwd rel fd rel convert file1 to abs, then case 3
+ 8 fd abs cwd abs direct call
+ 9 fd abs cwd rel direct call
+ 10 fd abs fd abs direct call
+ 11 fd abs fd rel chdir to fd2
+ 12 fd rel cwd abs chdir to fd1
+ 13 fd rel cwd rel convert file2 to abs, then case 12
+ 14 fd rel fd abs chdir to fd1
+ 15a fd1 rel fd1 rel chdir to fd1
+ 15b fd1 rel fd2 rel chdir to fd1, then case 7
+
+ Try some optimizations to reduce fd to AT_FDCWD, or to at least
+ avoid converting an absolute name or doing a double chdir. */
+
+ if ((fd1 == AT_FDCWD || IS_ABSOLUTE_FILE_NAME (file1))
+ && (fd2 == AT_FDCWD || IS_ABSOLUTE_FILE_NAME (file2)))
+ return func (file1, file2); /* Case 0-2, 4-6, 8-10. */
+
+ /* If /proc/self/fd works, we don't need any stat or chdir. */
+ {
+ char proc_buf1[OPENAT_BUFFER_SIZE];
+ char *proc_file1 = ((fd1 == AT_FDCWD || IS_ABSOLUTE_FILE_NAME (file1))
+ ? (char *) file1
+ : openat_proc_name (proc_buf1, fd1, file1));
+ if (proc_file1)
+ {
+ char proc_buf2[OPENAT_BUFFER_SIZE];
+ char *proc_file2 = ((fd2 == AT_FDCWD || IS_ABSOLUTE_FILE_NAME (file2))
+ ? (char *) file2
+ : openat_proc_name (proc_buf2, fd2, file2));
+ if (proc_file2)
+ {
+ int proc_result = func (proc_file1, proc_file2);
+ int proc_errno = errno;
+ if (proc_file1 != proc_buf1 && proc_file1 != file1)
+ free (proc_file1);
+ if (proc_file2 != proc_buf2 && proc_file2 != file2)
+ free (proc_file2);
+ /* If the syscall succeeds, or if it fails with an unexpected
+ errno value, then return right away. Otherwise, fall through
+ and resort to using save_cwd/restore_cwd. */
+ if (0 <= proc_result)
+ return proc_result;
+ if (! EXPECTED_ERRNO (proc_errno))
+ {
+ errno = proc_errno;
+ return proc_result;
+ }
+ }
+ else if (proc_file1 != proc_buf1 && proc_file1 != file1)
+ free (proc_file1);
+ }
+ }
+
+ /* Cases 3, 7, 11-15 remain. Time to normalize directory fds, if
+ possible. */
+ if (IS_ABSOLUTE_FILE_NAME (file1))
+ fd1 = AT_FDCWD; /* Case 11 reduced to 3. */
+ else if (IS_ABSOLUTE_FILE_NAME (file2))
+ fd2 = AT_FDCWD; /* Case 14 reduced to 12. */
+
+ /* Cases 3, 7, 12, 13, 15 remain. */
+
+ if (fd1 == AT_FDCWD) /* Cases 3, 7. */
+ {
+ if (stat (".", &st1) == -1 || fstat (fd2, &st2) == -1)
+ return -1;
+ if (!S_ISDIR (st2.st_mode))
+ {
+ errno = ENOTDIR;
+ return -1;
+ }
+ if (SAME_INODE (st1, st2)) /* Reduced to cases 1, 5. */
+ return func (file1, file2);
+ }
+ else if (fd2 == AT_FDCWD) /* Cases 12, 13. */
+ {
+ if (stat (".", &st2) == -1 || fstat (fd1, &st1) == -1)
+ return -1;
+ if (!S_ISDIR (st1.st_mode))
+ {
+ errno = ENOTDIR;
+ return -1;
+ }
+ if (SAME_INODE (st1, st2)) /* Reduced to cases 4, 5. */
+ return func (file1, file2);
+ }
+ else if (fd1 != fd2) /* Case 15b. */
+ {
+ if (fstat (fd1, &st1) == -1 || fstat (fd2, &st2) == -1)
+ return -1;
+ if (!S_ISDIR (st1.st_mode) || !S_ISDIR (st2.st_mode))
+ {
+ errno = ENOTDIR;
+ return -1;
+ }
+ if (SAME_INODE (st1, st2)) /* Reduced to case 15a. */
+ {
+ fd2 = fd1;
+ if (stat (".", &st1) == 0 && SAME_INODE (st1, st2))
+ return func (file1, file2); /* Further reduced to case 5. */
+ }
+ }
+ else /* Case 15a. */
+ {
+ if (fstat (fd1, &st1) == -1)
+ return -1;
+ if (!S_ISDIR (st1.st_mode))
+ {
+ errno = ENOTDIR;
+ return -1;
+ }
+ if (stat (".", &st2) == 0 && SAME_INODE (st1, st2))
+ return func (file1, file2); /* Reduced to case 5. */
+ }
+
+ /* Cases 3, 7, 12, 13, 15a, 15b remain. With all reductions in
+ place, it is time to start changing directories. */
+
+ if (save_cwd (&saved_cwd) != 0)
+ openat_save_fail (errno);
+
+ if (fd1 != AT_FDCWD && fd2 != AT_FDCWD && fd1 != fd2) /* Case 15b. */
+ {
+ if (fchdir (fd1) != 0)
+ {
+ saved_errno = errno;
+ free_cwd (&saved_cwd);
+ errno = saved_errno;
+ return -1;
+ }
+ fd1 = AT_FDCWD; /* Reduced to case 7. */
+ }
+
+ /* Cases 3, 7, 12, 13, 15a remain. Convert one relative name to
+ absolute, if necessary. */
+
+ file1_alt = (char *) file1;
+ file2_alt = (char *) file2;
+
+ if (fd1 == AT_FDCWD && !IS_ABSOLUTE_FILE_NAME (file1)) /* Case 7. */
+ {
+ /* It would be nicer to use:
+ file1_alt = file_name_concat (xgetcwd (), file1, NULL);
+ but libraries should not call xalloc_die. */
+ char *cwd = getcwd (NULL, 0);
+ if (!cwd)
+ {
+ saved_errno = errno;
+ free_cwd (&saved_cwd);
+ errno = saved_errno;
+ return -1;
+ }
+ file1_alt = mfile_name_concat (cwd, file1, NULL);
+ if (!file1_alt)
+ {
+ saved_errno = errno;
+ free (cwd);
+ free_cwd (&saved_cwd);
+ errno = saved_errno;
+ return -1;
+ }
+ free (cwd); /* Reduced to case 3. */
+ }
+ else if (fd2 == AT_FDCWD && !IS_ABSOLUTE_FILE_NAME (file2)) /* Case 13. */
+ {
+ char *cwd = getcwd (NULL, 0);
+ if (!cwd)
+ {
+ saved_errno = errno;
+ free_cwd (&saved_cwd);
+ errno = saved_errno;
+ return -1;
+ }
+ file2_alt = mfile_name_concat (cwd, file2, NULL);
+ if (!file2_alt)
+ {
+ saved_errno = errno;
+ free (cwd);
+ free_cwd (&saved_cwd);
+ errno = saved_errno;
+ return -1;
+ }
+ free (cwd); /* Reduced to case 12. */
+ }
+
+ /* Cases 3, 12, 15a remain. Change to the correct directory. */
+ if (fchdir (fd1 == AT_FDCWD ? fd2 : fd1) != 0)
+ {
+ saved_errno = errno;
+ free_cwd (&saved_cwd);
+ if (file1 != file1_alt)
+ free (file1_alt);
+ else if (file2 != file2_alt)
+ free (file2_alt);
+ errno = saved_errno;
+ return -1;
+ }
+
+ /* Finally safe to perform the user's function, then clean up. */
+
+ err = func (file1_alt, file2_alt);
+ saved_errno = (err < 0 ? errno : 0);
+
+ if (file1 != file1_alt)
+ free (file1_alt);
+ else if (file2 != file2_alt)
+ free (file2_alt);
+
+ if (restore_cwd (&saved_cwd) != 0)
+ openat_restore_fail (errno);
+
+ free_cwd (&saved_cwd);
+
+ if (saved_errno)
+ errno = saved_errno;
+ return err;
+}
+#undef CALL_FUNC
+#undef FUNC_RESULT
diff --git a/lib/atexit.c b/lib/atexit.c
deleted file mode 100644
index 5ef33e5..0000000
--- a/lib/atexit.c
+++ /dev/null
@@ -1,13 +0,0 @@
-/* Wrapper to implement ANSI C's atexit using SunOS's on_exit. */
-/* This function is in the public domain. --Mike Stump. */
-
-#include <config.h>
-
-int
-atexit (void (*f) (void))
-{
- /* If the system doesn't provide a definition for atexit, use on_exit
- if the system provides that. */
- on_exit (f, 0);
- return 0;
-}
diff --git a/lib/backupfile.c b/lib/backupfile.c
index adfc0e5..1fe369e 100644
--- a/lib/backupfile.c
+++ b/lib/backupfile.c
@@ -1,13 +1,11 @@
/* backupfile.c -- make Emacs style backup file names
- Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
- 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software
- Foundation, Inc.
+ Copyright (C) 1990-2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -15,9 +13,7 @@
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with this program; see the file COPYING.
- If not, write to the Free Software Foundation,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert and David MacKenzie.
Some algorithms adapted from GNU Emacs. */
@@ -39,7 +35,7 @@
#include <unistd.h>
-#include <dirent.h>
+#include "dirent--.h"
#ifndef _D_EXACT_NAMLEN
# define _D_EXACT_NAMLEN(dp) strlen ((dp)->d_name)
#endif
@@ -79,14 +75,9 @@
- It's typically faster.
POSIX says that only '0' through '9' are digits. Prefer ISDIGIT to
ISDIGIT unless it's important to use the locale's definition
- of `digit' even when the host does not conform to POSIX. */
+ of "digit" even when the host does not conform to POSIX. */
#define ISDIGIT(c) ((unsigned int) (c) - '0' <= 9)
-/* The results of opendir() in this file are not used with dirfd and fchdir,
- therefore save some unnecessary work in fchdir.c. */
-#undef opendir
-#undef closedir
-
/* The extension added to file names to produce a simple (as opposed
to numbered) backup file name. */
char const *simple_backup_suffix = "~";
@@ -110,18 +101,18 @@ check_extension (char *file, size_t filelen, char e)
long name_max;
/* Temporarily modify the buffer into its parent directory name,
- invoke pathconf on the directory, and then restore the buffer. */
+ invoke pathconf on the directory, and then restore the buffer. */
char tmp[sizeof "."];
memcpy (tmp, base, sizeof ".");
strcpy (base, ".");
errno = 0;
name_max = pathconf (file, _PC_NAME_MAX);
if (0 <= name_max || errno == 0)
- {
- long size = baselen_max = name_max;
- if (name_max != size)
- baselen_max = SIZE_MAX;
- }
+ {
+ long size = baselen_max = name_max;
+ if (name_max != size)
+ baselen_max = SIZE_MAX;
+ }
memcpy (base, tmp, sizeof ".");
}
@@ -130,21 +121,21 @@ check_extension (char *file, size_t filelen, char e)
/* Live within DOS's 8.3 limit. */
char *dot = strchr (base, '.');
if (!dot)
- baselen_max = 8;
+ baselen_max = 8;
else
- {
- char const *second_dot = strchr (dot + 1, '.');
- baselen_max = (second_dot
- ? second_dot - base
- : dot + 1 - base + 3);
- }
+ {
+ char const *second_dot = strchr (dot + 1, '.');
+ baselen_max = (second_dot
+ ? second_dot - base
+ : dot + 1 - base + 3);
+ }
}
if (baselen_max < baselen)
{
baselen = file + filelen - base;
if (baselen_max <= baselen)
- baselen = baselen_max - 1;
+ baselen = baselen_max - 1;
base[baselen] = e;
base[baselen + 1] = '\0';
}
@@ -210,41 +201,41 @@ numbered_backup (char **buffer, size_t buffer_size, size_t filelen)
size_t new_buflen;
if (! REAL_DIR_ENTRY (dp) || _D_EXACT_NAMLEN (dp) < baselen + 4)
- continue;
+ continue;
if (memcmp (buf + base_offset, dp->d_name, baselen + 2) != 0)
- continue;
+ continue;
p = dp->d_name + baselen + 2;
/* Check whether this file has a version number and if so,
- whether it is larger. Use string operations rather than
- integer arithmetic, to avoid problems with integer overflow. */
+ whether it is larger. Use string operations rather than
+ integer arithmetic, to avoid problems with integer overflow. */
if (! ('1' <= *p && *p <= '9'))
- continue;
+ continue;
all_9s = (*p == '9');
for (versionlen = 1; ISDIGIT (p[versionlen]); versionlen++)
- all_9s &= (p[versionlen] == '9');
+ all_9s &= (p[versionlen] == '9');
if (! (p[versionlen] == '~' && !p[versionlen + 1]
- && (versionlenmax < versionlen
- || (versionlenmax == versionlen
- && memcmp (buf + filelen + 2, p, versionlen) <= 0))))
- continue;
+ && (versionlenmax < versionlen
+ || (versionlenmax == versionlen
+ && memcmp (buf + filelen + 2, p, versionlen) <= 0))))
+ continue;
/* This directory has the largest version number seen so far.
- Append this highest numbered extension to the file name,
- prepending '0' to the number if it is all 9s. */
+ Append this highest numbered extension to the file name,
+ prepending '0' to the number if it is all 9s. */
versionlenmax = all_9s + versionlen;
result = (all_9s ? BACKUP_IS_LONGER : BACKUP_IS_SAME_LENGTH);
new_buflen = filelen + 2 + versionlenmax + 1;
if (buffer_size <= new_buflen)
- {
- buf = xnrealloc (buf, 2, new_buflen);
- buffer_size = new_buflen * 2;
- }
+ {
+ buf = xnrealloc (buf, 2, new_buflen);
+ buffer_size = new_buflen * 2;
+ }
q = buf + filelen;
*q++ = '.';
*q++ = '~';
@@ -256,7 +247,7 @@ numbered_backup (char **buffer, size_t buffer_size, size_t filelen)
q += versionlen;
while (*--q == '9')
- *q = '0';
+ *q = '0';
++*q;
}
@@ -293,15 +284,15 @@ find_backup_file_name (char const *file, enum backup_type backup_type)
switch (numbered_backup (&s, ssize, filelen))
{
case BACKUP_IS_SAME_LENGTH:
- return s;
+ return s;
case BACKUP_IS_LONGER:
- simple = false;
- break;
+ simple = false;
+ break;
case BACKUP_IS_NEW:
- simple = (backup_type == numbered_existing_backups);
- break;
+ simple = (backup_type == numbered_existing_backups);
+ break;
}
if (simple)
diff --git a/lib/backupfile.h b/lib/backupfile.h
index 7b44e58..18ca4a5 100644
--- a/lib/backupfile.h
+++ b/lib/backupfile.h
@@ -1,12 +1,12 @@
/* backupfile.h -- declarations for making Emacs style backup file names
- Copyright (C) 1990, 1991, 1992, 1997, 1998, 1999, 2003, 2004 Free
- Software Foundation, Inc.
+ Copyright (C) 1990-1992, 1997-1999, 2003-2004, 2009-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,9 +14,7 @@
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with this program; see the file COPYING.
- If not, write to the Free Software Foundation,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifndef BACKUPFILE_H_
# define BACKUPFILE_H_
@@ -43,7 +41,7 @@ enum backup_type
numbered_backups
};
-# define VALID_BACKUP_TYPE(Type) \
+# define VALID_BACKUP_TYPE(Type) \
((unsigned int) (Type) <= numbered_backups)
extern char const *simple_backup_suffix;
diff --git a/lib/base32.c b/lib/base32.c
new file mode 100644
index 0000000..28f10ba
--- /dev/null
+++ b/lib/base32.c
@@ -0,0 +1,587 @@
+/* base32.c -- Encode binary data using printable characters.
+ Copyright (C) 1999-2001, 2004-2006, 2009-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+/* Adapted from Simon Josefsson's base64 code by Gijs van Tulder.
+ *
+ * See also RFC 4648 <http://www.ietf.org/rfc/rfc4648.txt>.
+ *
+ * Be careful with error checking. Here is how you would typically
+ * use these functions:
+ *
+ * bool ok = base32_decode_alloc (in, inlen, &out, &outlen);
+ * if (!ok)
+ * FAIL: input was not valid base32
+ * if (out == NULL)
+ * FAIL: memory allocation error
+ * OK: data in OUT/OUTLEN
+ *
+ * size_t outlen = base32_encode_alloc (in, inlen, &out);
+ * if (out == NULL && outlen == 0 && inlen != 0)
+ * FAIL: input too long
+ * if (out == NULL)
+ * FAIL: memory allocation error
+ * OK: data in OUT/OUTLEN.
+ *
+ */
+
+#include <config.h>
+
+/* Get prototype. */
+#include "base32.h"
+
+/* Get malloc. */
+#include <stdlib.h>
+
+/* Get UCHAR_MAX. */
+#include <limits.h>
+
+#include <string.h>
+
+/* C89 compliant way to cast 'char' to 'unsigned char'. */
+static unsigned char
+to_uchar (char ch)
+{
+ return ch;
+}
+
+/* Base32 encode IN array of size INLEN into OUT array of size OUTLEN.
+ If OUTLEN is less than BASE32_LENGTH(INLEN), write as many bytes as
+ possible. If OUTLEN is larger than BASE32_LENGTH(INLEN), also zero
+ terminate the output buffer. */
+void
+base32_encode (const char *restrict in, size_t inlen,
+ char *restrict out, size_t outlen)
+{
+ static const char b32str[32] =
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
+
+ while (inlen && outlen)
+ {
+ *out++ = b32str[(to_uchar (in[0]) >> 3) & 0x1f];
+ if (!--outlen)
+ break;
+ *out++ = b32str[((to_uchar (in[0]) << 2)
+ + (--inlen ? to_uchar (in[1]) >> 6 : 0))
+ & 0x1f];
+ if (!--outlen)
+ break;
+ *out++ =
+ (inlen
+ ? b32str[(to_uchar (in[1]) >> 1) & 0x1f]
+ : '=');
+ if (!--outlen)
+ break;
+ *out++ =
+ (inlen
+ ? b32str[((to_uchar (in[1]) << 4)
+ + (--inlen ? to_uchar (in[2]) >> 4 : 0))
+ & 0x1f]
+ : '=');
+ if (!--outlen)
+ break;
+ *out++ =
+ (inlen
+ ? b32str[((to_uchar (in[2]) << 1)
+ + (--inlen ? to_uchar (in[3]) >> 7 : 0))
+ & 0x1f]
+ : '=');
+ if (!--outlen)
+ break;
+ *out++ =
+ (inlen
+ ? b32str[(to_uchar (in[3]) >> 2) & 0x1f]
+ : '=');
+ if (!--outlen)
+ break;
+ *out++ =
+ (inlen
+ ? b32str[((to_uchar (in[3]) << 3)
+ + (--inlen ? to_uchar (in[4]) >> 5 : 0))
+ & 0x1f]
+ : '=');
+ if (!--outlen)
+ break;
+ *out++ = inlen ? b32str[to_uchar (in[4]) & 0x1f] : '=';
+ if (!--outlen)
+ break;
+ if (inlen)
+ inlen--;
+ if (inlen)
+ in += 5;
+ }
+
+ if (outlen)
+ *out = '\0';
+}
+
+/* Allocate a buffer and store zero terminated base32 encoded data
+ from array IN of size INLEN, returning BASE32_LENGTH(INLEN), i.e.,
+ the length of the encoded data, excluding the terminating zero. On
+ return, the OUT variable will hold a pointer to newly allocated
+ memory that must be deallocated by the caller. If output string
+ length would overflow, 0 is returned and OUT is set to NULL. If
+ memory allocation failed, OUT is set to NULL, and the return value
+ indicates length of the requested memory block, i.e.,
+ BASE32_LENGTH(inlen) + 1. */
+size_t
+base32_encode_alloc (const char *in, size_t inlen, char **out)
+{
+ size_t outlen = 1 + BASE32_LENGTH (inlen);
+
+ /* Check for overflow in outlen computation.
+ *
+ * If there is no overflow, outlen >= inlen.
+ *
+ * TODO Is this a sufficient check? (See the notes in base64.c.)
+ */
+ if (inlen > outlen)
+ {
+ *out = NULL;
+ return 0;
+ }
+
+ *out = malloc (outlen);
+ if (!*out)
+ return outlen;
+
+ base32_encode (in, inlen, *out, outlen);
+
+ return outlen - 1;
+}
+
+/* With this approach this file works independent of the charset used
+ (think EBCDIC). However, it does assume that the characters in the
+ Base32 alphabet (A-Z2-7) are encoded in 0..255. POSIX
+ 1003.1-2001 require that char and unsigned char are 8-bit
+ quantities, though, taking care of that problem. But this may be a
+ potential problem on non-POSIX C99 platforms.
+
+ IBM C V6 for AIX mishandles "#define B32(x) ...'x'...", so use "_"
+ as the formal parameter rather than "x". */
+#define B32(_) \
+ ((_) == 'A' ? 0 \
+ : (_) == 'B' ? 1 \
+ : (_) == 'C' ? 2 \
+ : (_) == 'D' ? 3 \
+ : (_) == 'E' ? 4 \
+ : (_) == 'F' ? 5 \
+ : (_) == 'G' ? 6 \
+ : (_) == 'H' ? 7 \
+ : (_) == 'I' ? 8 \
+ : (_) == 'J' ? 9 \
+ : (_) == 'K' ? 10 \
+ : (_) == 'L' ? 11 \
+ : (_) == 'M' ? 12 \
+ : (_) == 'N' ? 13 \
+ : (_) == 'O' ? 14 \
+ : (_) == 'P' ? 15 \
+ : (_) == 'Q' ? 16 \
+ : (_) == 'R' ? 17 \
+ : (_) == 'S' ? 18 \
+ : (_) == 'T' ? 19 \
+ : (_) == 'U' ? 20 \
+ : (_) == 'V' ? 21 \
+ : (_) == 'W' ? 22 \
+ : (_) == 'X' ? 23 \
+ : (_) == 'Y' ? 24 \
+ : (_) == 'Z' ? 25 \
+ : (_) == '2' ? 26 \
+ : (_) == '3' ? 27 \
+ : (_) == '4' ? 28 \
+ : (_) == '5' ? 29 \
+ : (_) == '6' ? 30 \
+ : (_) == '7' ? 31 \
+ : -1)
+
+static const signed char b32[0x100] = {
+ B32 (0), B32 (1), B32 (2), B32 (3),
+ B32 (4), B32 (5), B32 (6), B32 (7),
+ B32 (8), B32 (9), B32 (10), B32 (11),
+ B32 (12), B32 (13), B32 (14), B32 (15),
+ B32 (16), B32 (17), B32 (18), B32 (19),
+ B32 (20), B32 (21), B32 (22), B32 (23),
+ B32 (24), B32 (25), B32 (26), B32 (27),
+ B32 (28), B32 (29), B32 (30), B32 (31),
+ B32 (32), B32 (33), B32 (34), B32 (35),
+ B32 (36), B32 (37), B32 (38), B32 (39),
+ B32 (40), B32 (41), B32 (42), B32 (43),
+ B32 (44), B32 (45), B32 (46), B32 (47),
+ B32 (48), B32 (49), B32 (50), B32 (51),
+ B32 (52), B32 (53), B32 (54), B32 (55),
+ B32 (56), B32 (57), B32 (58), B32 (59),
+ B32 (60), B32 (61), B32 (62), B32 (63),
+ B32 (32), B32 (65), B32 (66), B32 (67),
+ B32 (68), B32 (69), B32 (70), B32 (71),
+ B32 (72), B32 (73), B32 (74), B32 (75),
+ B32 (76), B32 (77), B32 (78), B32 (79),
+ B32 (80), B32 (81), B32 (82), B32 (83),
+ B32 (84), B32 (85), B32 (86), B32 (87),
+ B32 (88), B32 (89), B32 (90), B32 (91),
+ B32 (92), B32 (93), B32 (94), B32 (95),
+ B32 (96), B32 (97), B32 (98), B32 (99),
+ B32 (100), B32 (101), B32 (102), B32 (103),
+ B32 (104), B32 (105), B32 (106), B32 (107),
+ B32 (108), B32 (109), B32 (110), B32 (111),
+ B32 (112), B32 (113), B32 (114), B32 (115),
+ B32 (116), B32 (117), B32 (118), B32 (119),
+ B32 (120), B32 (121), B32 (122), B32 (123),
+ B32 (124), B32 (125), B32 (126), B32 (127),
+ B32 (128), B32 (129), B32 (130), B32 (131),
+ B32 (132), B32 (133), B32 (134), B32 (135),
+ B32 (136), B32 (137), B32 (138), B32 (139),
+ B32 (140), B32 (141), B32 (142), B32 (143),
+ B32 (144), B32 (145), B32 (146), B32 (147),
+ B32 (148), B32 (149), B32 (150), B32 (151),
+ B32 (152), B32 (153), B32 (154), B32 (155),
+ B32 (156), B32 (157), B32 (158), B32 (159),
+ B32 (160), B32 (161), B32 (162), B32 (163),
+ B32 (132), B32 (165), B32 (166), B32 (167),
+ B32 (168), B32 (169), B32 (170), B32 (171),
+ B32 (172), B32 (173), B32 (174), B32 (175),
+ B32 (176), B32 (177), B32 (178), B32 (179),
+ B32 (180), B32 (181), B32 (182), B32 (183),
+ B32 (184), B32 (185), B32 (186), B32 (187),
+ B32 (188), B32 (189), B32 (190), B32 (191),
+ B32 (192), B32 (193), B32 (194), B32 (195),
+ B32 (196), B32 (197), B32 (198), B32 (199),
+ B32 (200), B32 (201), B32 (202), B32 (203),
+ B32 (204), B32 (205), B32 (206), B32 (207),
+ B32 (208), B32 (209), B32 (210), B32 (211),
+ B32 (212), B32 (213), B32 (214), B32 (215),
+ B32 (216), B32 (217), B32 (218), B32 (219),
+ B32 (220), B32 (221), B32 (222), B32 (223),
+ B32 (224), B32 (225), B32 (226), B32 (227),
+ B32 (228), B32 (229), B32 (230), B32 (231),
+ B32 (232), B32 (233), B32 (234), B32 (235),
+ B32 (236), B32 (237), B32 (238), B32 (239),
+ B32 (240), B32 (241), B32 (242), B32 (243),
+ B32 (244), B32 (245), B32 (246), B32 (247),
+ B32 (248), B32 (249), B32 (250), B32 (251),
+ B32 (252), B32 (253), B32 (254), B32 (255)
+};
+
+#if UCHAR_MAX == 255
+# define uchar_in_range(c) true
+#else
+# define uchar_in_range(c) ((c) <= 255)
+#endif
+
+/* Return true if CH is a character from the Base32 alphabet, and
+ false otherwise. Note that '=' is padding and not considered to be
+ part of the alphabet. */
+bool
+isbase32 (char ch)
+{
+ return uchar_in_range (to_uchar (ch)) && 0 <= b32[to_uchar (ch)];
+}
+
+/* Initialize decode-context buffer, CTX. */
+void
+base32_decode_ctx_init (struct base32_decode_context *ctx)
+{
+ ctx->i = 0;
+}
+
+/* If CTX->i is 0 or 8, there are eight or more bytes in [*IN..IN_END), and
+ none of those eight is a newline, then return *IN. Otherwise, copy up to
+ 4 - CTX->i non-newline bytes from that range into CTX->buf, starting at
+ index CTX->i and setting CTX->i to reflect the number of bytes copied,
+ and return CTX->buf. In either case, advance *IN to point to the byte
+ after the last one processed, and set *N_NON_NEWLINE to the number of
+ verified non-newline bytes accessible through the returned pointer. */
+static char *
+get_8 (struct base32_decode_context *ctx,
+ char const *restrict *in, char const *restrict in_end,
+ size_t *n_non_newline)
+{
+ if (ctx->i == 8)
+ ctx->i = 0;
+
+ if (ctx->i == 0)
+ {
+ char const *t = *in;
+ if (8 <= in_end - *in && memchr (t, '\n', 8) == NULL)
+ {
+ /* This is the common case: no newline. */
+ *in += 8;
+ *n_non_newline = 8;
+ return (char *) t;
+ }
+ }
+
+ {
+ /* Copy non-newline bytes into BUF. */
+ char const *p = *in;
+ while (p < in_end)
+ {
+ char c = *p++;
+ if (c != '\n')
+ {
+ ctx->buf[ctx->i++] = c;
+ if (ctx->i == 8)
+ break;
+ }
+ }
+
+ *in = p;
+ *n_non_newline = ctx->i;
+ return ctx->buf;
+ }
+}
+
+#define return_false \
+ do \
+ { \
+ *outp = out; \
+ return false; \
+ } \
+ while (false)
+
+/* Decode eight bytes of base32-encoded data, IN, of length INLEN
+ into the output buffer, *OUT, of size *OUTLEN bytes. Return true if
+ decoding is successful, false otherwise. If *OUTLEN is too small,
+ as many bytes as possible are written to *OUT. On return, advance
+ *OUT to point to the byte after the last one written, and decrement
+ *OUTLEN to reflect the number of bytes remaining in *OUT. */
+static bool
+decode_8 (char const *restrict in, size_t inlen,
+ char *restrict *outp, size_t *outleft)
+{
+ char *out = *outp;
+ if (inlen < 8)
+ return false;
+
+ if (!isbase32 (in[0]) || !isbase32 (in[1]) )
+ return false;
+
+ if (*outleft)
+ {
+ *out++ = ((b32[to_uchar (in[0])] << 3)
+ | (b32[to_uchar (in[1])] >> 2));
+ --*outleft;
+ }
+
+ if (in[2] == '=')
+ {
+ if (in[3] != '=' || in[4] != '=' || in[5] != '='
+ || in[6] != '=' || in[7] != '=')
+ return_false;
+ }
+ else
+ {
+ if (!isbase32 (in[2]) || !isbase32 (in[3]))
+ return_false;
+
+ if (*outleft)
+ {
+ *out++ = ((b32[to_uchar (in[1])] << 6)
+ | (b32[to_uchar (in[2])] << 1)
+ | (b32[to_uchar (in[3])] >> 4));
+ --*outleft;
+ }
+
+ if (in[4] == '=')
+ {
+ if (in[5] != '=' || in[6] != '=' || in[7] != '=')
+ return_false;
+ }
+ else
+ {
+ if (!isbase32 (in[4]))
+ return_false;
+
+ if (*outleft)
+ {
+ *out++ = ((b32[to_uchar (in[3])] << 4)
+ | (b32[to_uchar (in[4])] >> 1));
+ --*outleft;
+ }
+
+ if (in[5] == '=')
+ {
+ if (in[6] != '=' || in[7] != '=')
+ return_false;
+ }
+ else
+ {
+ if (!isbase32 (in[5]) || !isbase32 (in[6]))
+ return_false;
+
+ if (*outleft)
+ {
+ *out++ = ((b32[to_uchar (in[4])] << 7)
+ | (b32[to_uchar (in[5])] << 2)
+ | (b32[to_uchar (in[6])] >> 3));
+ --*outleft;
+ }
+
+ if (in[7] != '=')
+ {
+ if (!isbase32 (in[7]))
+ return_false;
+
+ if (*outleft)
+ {
+ *out++ = ((b32[to_uchar (in[6])] << 5)
+ | (b32[to_uchar (in[7])]));
+ --*outleft;
+ }
+ }
+ }
+ }
+ }
+
+ *outp = out;
+ return true;
+}
+
+/* Decode base32-encoded input array IN of length INLEN to output array
+ OUT that can hold *OUTLEN bytes. The input data may be interspersed
+ with newlines. Return true if decoding was successful, i.e. if the
+ input was valid base32 data, false otherwise. If *OUTLEN is too
+ small, as many bytes as possible will be written to OUT. On return,
+ *OUTLEN holds the length of decoded bytes in OUT. Note that as soon
+ as any non-alphabet, non-newline character is encountered, decoding
+ is stopped and false is returned. If INLEN is zero, then process
+ only whatever data is stored in CTX.
+
+ Initially, CTX must have been initialized via base32_decode_ctx_init.
+ Subsequent calls to this function must reuse whatever state is recorded
+ in that buffer. It is necessary for when a octuple of base32 input
+ bytes spans two input buffers.
+
+ If CTX is NULL then newlines are treated as garbage and the input
+ buffer is processed as a unit. */
+
+bool
+base32_decode_ctx (struct base32_decode_context *ctx,
+ const char *restrict in, size_t inlen,
+ char *restrict out, size_t *outlen)
+{
+ size_t outleft = *outlen;
+ bool ignore_newlines = ctx != NULL;
+ bool flush_ctx = false;
+ unsigned int ctx_i = 0;
+
+ if (ignore_newlines)
+ {
+ ctx_i = ctx->i;
+ flush_ctx = inlen == 0;
+ }
+
+
+ while (true)
+ {
+ size_t outleft_save = outleft;
+ if (ctx_i == 0 && !flush_ctx)
+ {
+ while (true)
+ {
+ /* Save a copy of outleft, in case we need to re-parse this
+ block of four bytes. */
+ outleft_save = outleft;
+ if (!decode_8 (in, inlen, &out, &outleft))
+ break;
+
+ in += 8;
+ inlen -= 8;
+ }
+ }
+
+ if (inlen == 0 && !flush_ctx)
+ break;
+
+ /* Handle the common case of 72-byte wrapped lines.
+ This also handles any other multiple-of-8-byte wrapping. */
+ if (inlen && *in == '\n' && ignore_newlines)
+ {
+ ++in;
+ --inlen;
+ continue;
+ }
+
+ /* Restore OUT and OUTLEFT. */
+ out -= outleft_save - outleft;
+ outleft = outleft_save;
+
+ {
+ char const *in_end = in + inlen;
+ char const *non_nl;
+
+ if (ignore_newlines)
+ non_nl = get_8 (ctx, &in, in_end, &inlen);
+ else
+ non_nl = in; /* Might have nl in this case. */
+
+ /* If the input is empty or consists solely of newlines (0 non-newlines),
+ then we're done. Likewise if there are fewer than 8 bytes when not
+ flushing context and not treating newlines as garbage. */
+ if (inlen == 0 || (inlen < 8 && !flush_ctx && ignore_newlines))
+ {
+ inlen = 0;
+ break;
+ }
+ if (!decode_8 (non_nl, inlen, &out, &outleft))
+ break;
+
+ inlen = in_end - in;
+ }
+ }
+
+ *outlen -= outleft;
+
+ return inlen == 0;
+}
+
+/* Allocate an output buffer in *OUT, and decode the base32 encoded
+ data stored in IN of size INLEN to the *OUT buffer. On return, the
+ size of the decoded data is stored in *OUTLEN. OUTLEN may be NULL,
+ if the caller is not interested in the decoded length. *OUT may be
+ NULL to indicate an out of memory error, in which case *OUTLEN
+ contains the size of the memory block needed. The function returns
+ true on successful decoding and memory allocation errors. (Use the
+ *OUT and *OUTLEN parameters to differentiate between successful
+ decoding and memory error.) The function returns false if the
+ input was invalid, in which case *OUT is NULL and *OUTLEN is
+ undefined. */
+bool
+base32_decode_alloc_ctx (struct base32_decode_context *ctx,
+ const char *in, size_t inlen, char **out,
+ size_t *outlen)
+{
+ /* This may allocate a few bytes too many, depending on input,
+ but it's not worth the extra CPU time to compute the exact size.
+ The exact size is 5 * inlen / 8, minus one or more bytes if the
+ input is padded with one or more "=".
+ Dividing before multiplying avoids the possibility of overflow. */
+ size_t needlen = 5 * (inlen / 8) + 5;
+
+ *out = malloc (needlen);
+ if (!*out)
+ return true;
+
+ if (!base32_decode_ctx (ctx, in, inlen, *out, &needlen))
+ {
+ free (*out);
+ *out = NULL;
+ return false;
+ }
+
+ if (outlen)
+ *outlen = needlen;
+
+ return true;
+}
diff --git a/lib/base32.h b/lib/base32.h
new file mode 100644
index 0000000..fdfad3a
--- /dev/null
+++ b/lib/base32.h
@@ -0,0 +1,60 @@
+/* base32.h -- Encode binary data using printable characters.
+ Copyright (C) 2004-2006, 2009-2016 Free Software Foundation, Inc.
+ Adapted from Simon Josefsson's base64 code by Gijs van Tulder.
+
+ 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, 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef BASE32_H
+# define BASE32_H
+
+/* Get size_t. */
+# include <stddef.h>
+
+/* Get bool. */
+# include <stdbool.h>
+
+/* This uses that the expression (n+(k-1))/k means the smallest
+ integer >= n/k, i.e., the ceiling of n/k. */
+# define BASE32_LENGTH(inlen) ((((inlen) + 4) / 5) * 8)
+
+struct base32_decode_context
+{
+ unsigned int i;
+ char buf[8];
+};
+
+extern bool isbase32 (char ch) _GL_ATTRIBUTE_CONST;
+
+extern void base32_encode (const char *restrict in, size_t inlen,
+ char *restrict out, size_t outlen);
+
+extern size_t base32_encode_alloc (const char *in, size_t inlen, char **out);
+
+extern void base32_decode_ctx_init (struct base32_decode_context *ctx);
+
+extern bool base32_decode_ctx (struct base32_decode_context *ctx,
+ const char *restrict in, size_t inlen,
+ char *restrict out, size_t *outlen);
+
+extern bool base32_decode_alloc_ctx (struct base32_decode_context *ctx,
+ const char *in, size_t inlen,
+ char **out, size_t *outlen);
+
+#define base32_decode(in, inlen, out, outlen) \
+ base32_decode_ctx (NULL, in, inlen, out, outlen)
+
+#define base32_decode_alloc(in, inlen, out, outlen) \
+ base32_decode_alloc_ctx (NULL, in, inlen, out, outlen)
+
+#endif /* BASE32_H */
diff --git a/lib/base64.c b/lib/base64.c
index 5312902..1fbb9e8 100644
--- a/lib/base64.c
+++ b/lib/base64.c
@@ -1,12 +1,9 @@
-/* -*- buffer-read-only: t -*- vi: set ro: */
-/* DO NOT EDIT! GENERATED AUTOMATICALLY! */
/* base64.c -- Encode binary data using printable characters.
- Copyright (C) 1999, 2000, 2001, 2004, 2005, 2006, 2007 Free Software
- Foundation, Inc.
+ Copyright (C) 1999-2001, 2004-2006, 2009-2016 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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -15,14 +12,13 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program; if not, see <http://www.gnu.org/licenses/>. */
/* Written by Simon Josefsson. Partially adapted from GNU MailUtils
* (mailbox/filter_trans.c, as of 2004-11-28). Improved by review
* from Paul Eggert, Bruno Haible, and Stepan Kasal.
*
- * See also RFC 3548 <http://www.ietf.org/rfc/rfc3548.txt>.
+ * See also RFC 4648 <http://www.ietf.org/rfc/rfc4648.txt>.
*
* Be careful with error checking. Here is how you would typically
* use these functions:
@@ -57,48 +53,79 @@
#include <string.h>
/* C89 compliant way to cast 'char' to 'unsigned char'. */
-static inline unsigned char
+static unsigned char
to_uchar (char ch)
{
return ch;
}
+static const char b64c[64] =
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
+/* Base64 encode IN array of size INLEN into OUT array. OUT needs
+ to be of length >= BASE64_LENGTH(INLEN), and INLEN needs to be
+ a multiple of 3. */
+static void
+base64_encode_fast (const char *restrict in, size_t inlen, char *restrict out)
+{
+ while (inlen)
+ {
+ *out++ = b64c[to_uchar (in[0]) >> 2];
+ *out++ = b64c[((to_uchar (in[0]) << 4) + (to_uchar (in[1]) >> 4)) & 0x3f];
+ *out++ = b64c[((to_uchar (in[1]) << 2) + (to_uchar (in[2]) >> 6)) & 0x3f];
+ *out++ = b64c[to_uchar (in[2]) & 0x3f];
+
+ inlen -= 3;
+ in += 3;
+ }
+}
+
/* Base64 encode IN array of size INLEN into OUT array of size OUTLEN.
If OUTLEN is less than BASE64_LENGTH(INLEN), write as many bytes as
possible. If OUTLEN is larger than BASE64_LENGTH(INLEN), also zero
terminate the output buffer. */
void
base64_encode (const char *restrict in, size_t inlen,
- char *restrict out, size_t outlen)
+ char *restrict out, size_t outlen)
{
- static const char b64str[64] =
- "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+ /* Note this outlen constraint can be enforced at compile time.
+ I.E. that the output buffer is exactly large enough to hold
+ the encoded inlen bytes. The inlen constraints (of corresponding
+ to outlen, and being a multiple of 3) can change at runtime
+ at the end of input. However the common case when reading
+ large inputs is to have both constraints satisfied, so we depend
+ on both in base_encode_fast(). */
+ if (outlen % 4 == 0 && inlen == outlen / 4 * 3)
+ {
+ base64_encode_fast (in, inlen, out);
+ return;
+ }
while (inlen && outlen)
{
- *out++ = b64str[(to_uchar (in[0]) >> 2) & 0x3f];
+ *out++ = b64c[to_uchar (in[0]) >> 2];
if (!--outlen)
- break;
- *out++ = b64str[((to_uchar (in[0]) << 4)
- + (--inlen ? to_uchar (in[1]) >> 4 : 0))
- & 0x3f];
+ break;
+ *out++ = b64c[((to_uchar (in[0]) << 4)
+ + (--inlen ? to_uchar (in[1]) >> 4 : 0))
+ & 0x3f];
if (!--outlen)
- break;
+ break;
*out++ =
- (inlen
- ? b64str[((to_uchar (in[1]) << 2)
- + (--inlen ? to_uchar (in[2]) >> 6 : 0))
- & 0x3f]
- : '=');
+ (inlen
+ ? b64c[((to_uchar (in[1]) << 2)
+ + (--inlen ? to_uchar (in[2]) >> 6 : 0))
+ & 0x3f]
+ : '=');
if (!--outlen)
- break;
- *out++ = inlen ? b64str[to_uchar (in[2]) & 0x3f] : '=';
+ break;
+ *out++ = inlen ? b64c[to_uchar (in[2]) & 0x3f] : '=';
if (!--outlen)
- break;
+ break;
if (inlen)
- inlen--;
+ inlen--;
if (inlen)
- in += 3;
+ in += 3;
}
if (outlen)
@@ -155,71 +182,71 @@ base64_encode_alloc (const char *in, size_t inlen, char **out)
IBM C V6 for AIX mishandles "#define B64(x) ...'x'...", so use "_"
as the formal parameter rather than "x". */
-#define B64(_) \
- ((_) == 'A' ? 0 \
- : (_) == 'B' ? 1 \
- : (_) == 'C' ? 2 \
- : (_) == 'D' ? 3 \
- : (_) == 'E' ? 4 \
- : (_) == 'F' ? 5 \
- : (_) == 'G' ? 6 \
- : (_) == 'H' ? 7 \
- : (_) == 'I' ? 8 \
- : (_) == 'J' ? 9 \
- : (_) == 'K' ? 10 \
- : (_) == 'L' ? 11 \
- : (_) == 'M' ? 12 \
- : (_) == 'N' ? 13 \
- : (_) == 'O' ? 14 \
- : (_) == 'P' ? 15 \
- : (_) == 'Q' ? 16 \
- : (_) == 'R' ? 17 \
- : (_) == 'S' ? 18 \
- : (_) == 'T' ? 19 \
- : (_) == 'U' ? 20 \
- : (_) == 'V' ? 21 \
- : (_) == 'W' ? 22 \
- : (_) == 'X' ? 23 \
- : (_) == 'Y' ? 24 \
- : (_) == 'Z' ? 25 \
- : (_) == 'a' ? 26 \
- : (_) == 'b' ? 27 \
- : (_) == 'c' ? 28 \
- : (_) == 'd' ? 29 \
- : (_) == 'e' ? 30 \
- : (_) == 'f' ? 31 \
- : (_) == 'g' ? 32 \
- : (_) == 'h' ? 33 \
- : (_) == 'i' ? 34 \
- : (_) == 'j' ? 35 \
- : (_) == 'k' ? 36 \
- : (_) == 'l' ? 37 \
- : (_) == 'm' ? 38 \
- : (_) == 'n' ? 39 \
- : (_) == 'o' ? 40 \
- : (_) == 'p' ? 41 \
- : (_) == 'q' ? 42 \
- : (_) == 'r' ? 43 \
- : (_) == 's' ? 44 \
- : (_) == 't' ? 45 \
- : (_) == 'u' ? 46 \
- : (_) == 'v' ? 47 \
- : (_) == 'w' ? 48 \
- : (_) == 'x' ? 49 \
- : (_) == 'y' ? 50 \
- : (_) == 'z' ? 51 \
- : (_) == '0' ? 52 \
- : (_) == '1' ? 53 \
- : (_) == '2' ? 54 \
- : (_) == '3' ? 55 \
- : (_) == '4' ? 56 \
- : (_) == '5' ? 57 \
- : (_) == '6' ? 58 \
- : (_) == '7' ? 59 \
- : (_) == '8' ? 60 \
- : (_) == '9' ? 61 \
- : (_) == '+' ? 62 \
- : (_) == '/' ? 63 \
+#define B64(_) \
+ ((_) == 'A' ? 0 \
+ : (_) == 'B' ? 1 \
+ : (_) == 'C' ? 2 \
+ : (_) == 'D' ? 3 \
+ : (_) == 'E' ? 4 \
+ : (_) == 'F' ? 5 \
+ : (_) == 'G' ? 6 \
+ : (_) == 'H' ? 7 \
+ : (_) == 'I' ? 8 \
+ : (_) == 'J' ? 9 \
+ : (_) == 'K' ? 10 \
+ : (_) == 'L' ? 11 \
+ : (_) == 'M' ? 12 \
+ : (_) == 'N' ? 13 \
+ : (_) == 'O' ? 14 \
+ : (_) == 'P' ? 15 \
+ : (_) == 'Q' ? 16 \
+ : (_) == 'R' ? 17 \
+ : (_) == 'S' ? 18 \
+ : (_) == 'T' ? 19 \
+ : (_) == 'U' ? 20 \
+ : (_) == 'V' ? 21 \
+ : (_) == 'W' ? 22 \
+ : (_) == 'X' ? 23 \
+ : (_) == 'Y' ? 24 \
+ : (_) == 'Z' ? 25 \
+ : (_) == 'a' ? 26 \
+ : (_) == 'b' ? 27 \
+ : (_) == 'c' ? 28 \
+ : (_) == 'd' ? 29 \
+ : (_) == 'e' ? 30 \
+ : (_) == 'f' ? 31 \
+ : (_) == 'g' ? 32 \
+ : (_) == 'h' ? 33 \
+ : (_) == 'i' ? 34 \
+ : (_) == 'j' ? 35 \
+ : (_) == 'k' ? 36 \
+ : (_) == 'l' ? 37 \
+ : (_) == 'm' ? 38 \
+ : (_) == 'n' ? 39 \
+ : (_) == 'o' ? 40 \
+ : (_) == 'p' ? 41 \
+ : (_) == 'q' ? 42 \
+ : (_) == 'r' ? 43 \
+ : (_) == 's' ? 44 \
+ : (_) == 't' ? 45 \
+ : (_) == 'u' ? 46 \
+ : (_) == 'v' ? 47 \
+ : (_) == 'w' ? 48 \
+ : (_) == 'x' ? 49 \
+ : (_) == 'y' ? 50 \
+ : (_) == 'z' ? 51 \
+ : (_) == '0' ? 52 \
+ : (_) == '1' ? 53 \
+ : (_) == '2' ? 54 \
+ : (_) == '3' ? 55 \
+ : (_) == '4' ? 56 \
+ : (_) == '5' ? 57 \
+ : (_) == '6' ? 58 \
+ : (_) == '7' ? 59 \
+ : (_) == '8' ? 60 \
+ : (_) == '9' ? 61 \
+ : (_) == '+' ? 62 \
+ : (_) == '/' ? 63 \
: -1)
static const signed char b64[0x100] = {
@@ -318,7 +345,7 @@ base64_decode_ctx_init (struct base64_decode_context *ctx)
and return CTX->buf. In either case, advance *IN to point to the byte
after the last one processed, and set *N_NON_NEWLINE to the number of
verified non-newline bytes accessible through the returned pointer. */
-static inline char *
+static char *
get_4 (struct base64_decode_context *ctx,
char const *restrict *in, char const *restrict in_end,
size_t *n_non_newline)
@@ -330,12 +357,12 @@ get_4 (struct base64_decode_context *ctx,
{
char const *t = *in;
if (4 <= in_end - *in && memchr (t, '\n', 4) == NULL)
- {
- /* This is the common case: no newline. */
- *in += 4;
- *n_non_newline = 4;
- return (char *) t;
- }
+ {
+ /* This is the common case: no newline. */
+ *in += 4;
+ *n_non_newline = 4;
+ return (char *) t;
+ }
}
{
@@ -343,13 +370,13 @@ get_4 (struct base64_decode_context *ctx,
char const *p = *in;
while (p < in_end)
{
- char c = *p++;
- if (c != '\n')
- {
- ctx->buf[ctx->i++] = c;
- if (ctx->i == 4)
- break;
- }
+ char c = *p++;
+ if (c != '\n')
+ {
+ ctx->buf[ctx->i++] = c;
+ if (ctx->i == 4)
+ break;
+ }
}
*in = p;
@@ -358,12 +385,12 @@ get_4 (struct base64_decode_context *ctx,
}
}
-#define return_false \
- do \
- { \
- *outp = out; \
- return false; \
- } \
+#define return_false \
+ do \
+ { \
+ *outp = out; \
+ return false; \
+ } \
while (false)
/* Decode up to four bytes of base64-encoded data, IN, of length INLEN
@@ -372,9 +399,9 @@ get_4 (struct base64_decode_context *ctx,
as many bytes as possible are written to *OUT. On return, advance
*OUT to point to the byte after the last one written, and decrement
*OUTLEN to reflect the number of bytes remaining in *OUT. */
-static inline bool
+static bool
decode_4 (char const *restrict in, size_t inlen,
- char *restrict *outp, size_t *outleft)
+ char *restrict *outp, size_t *outleft)
{
char *out = *outp;
if (inlen < 2)
@@ -386,7 +413,7 @@ decode_4 (char const *restrict in, size_t inlen,
if (*outleft)
{
*out++ = ((b64[to_uchar (in[0])] << 2)
- | (b64[to_uchar (in[1])] >> 4));
+ | (b64[to_uchar (in[1])] >> 4));
--*outleft;
}
@@ -396,43 +423,43 @@ decode_4 (char const *restrict in, size_t inlen,
if (in[2] == '=')
{
if (inlen != 4)
- return_false;
+ return_false;
if (in[3] != '=')
- return_false;
+ return_false;
}
else
{
if (!isbase64 (in[2]))
- return_false;
+ return_false;
if (*outleft)
- {
- *out++ = (((b64[to_uchar (in[1])] << 4) & 0xf0)
- | (b64[to_uchar (in[2])] >> 2));
- --*outleft;
- }
+ {
+ *out++ = (((b64[to_uchar (in[1])] << 4) & 0xf0)
+ | (b64[to_uchar (in[2])] >> 2));
+ --*outleft;
+ }
if (inlen == 3)
- return_false;
+ return_false;
if (in[3] == '=')
- {
- if (inlen != 4)
- return_false;
- }
+ {
+ if (inlen != 4)
+ return_false;
+ }
else
- {
- if (!isbase64 (in[3]))
- return_false;
-
- if (*outleft)
- {
- *out++ = (((b64[to_uchar (in[2])] << 6) & 0xc0)
- | b64[to_uchar (in[3])]);
- --*outleft;
- }
- }
+ {
+ if (!isbase64 (in[3]))
+ return_false;
+
+ if (*outleft)
+ {
+ *out++ = (((b64[to_uchar (in[2])] << 6) & 0xc0)
+ | b64[to_uchar (in[3])]);
+ --*outleft;
+ }
+ }
}
*outp = out;
@@ -452,66 +479,83 @@ decode_4 (char const *restrict in, size_t inlen,
Initially, CTX must have been initialized via base64_decode_ctx_init.
Subsequent calls to this function must reuse whatever state is recorded
in that buffer. It is necessary for when a quadruple of base64 input
- bytes spans two input buffers. */
+ bytes spans two input buffers.
+
+ If CTX is NULL then newlines are treated as garbage and the input
+ buffer is processed as a unit. */
bool
-base64_decode (struct base64_decode_context *ctx,
- const char *restrict in, size_t inlen,
- char *restrict out, size_t *outlen)
+base64_decode_ctx (struct base64_decode_context *ctx,
+ const char *restrict in, size_t inlen,
+ char *restrict out, size_t *outlen)
{
size_t outleft = *outlen;
- bool flush_ctx = inlen == 0;
+ bool ignore_newlines = ctx != NULL;
+ bool flush_ctx = false;
+ unsigned int ctx_i = 0;
+
+ if (ignore_newlines)
+ {
+ ctx_i = ctx->i;
+ flush_ctx = inlen == 0;
+ }
+
while (true)
{
size_t outleft_save = outleft;
- if (ctx->i == 0 && !flush_ctx)
- {
- while (true)
- {
- /* Save a copy of outleft, in case we need to re-parse this
- block of four bytes. */
- outleft_save = outleft;
- if (!decode_4 (in, inlen, &out, &outleft))
- break;
-
- in += 4;
- inlen -= 4;
- }
- }
+ if (ctx_i == 0 && !flush_ctx)
+ {
+ while (true)
+ {
+ /* Save a copy of outleft, in case we need to re-parse this
+ block of four bytes. */
+ outleft_save = outleft;
+ if (!decode_4 (in, inlen, &out, &outleft))
+ break;
+
+ in += 4;
+ inlen -= 4;
+ }
+ }
if (inlen == 0 && !flush_ctx)
- break;
+ break;
/* Handle the common case of 72-byte wrapped lines.
- This also handles any other multiple-of-4-byte wrapping. */
- if (inlen && *in == '\n')
- {
- ++in;
- --inlen;
- continue;
- }
+ This also handles any other multiple-of-4-byte wrapping. */
+ if (inlen && *in == '\n' && ignore_newlines)
+ {
+ ++in;
+ --inlen;
+ continue;
+ }
/* Restore OUT and OUTLEFT. */
out -= outleft_save - outleft;
outleft = outleft_save;
{
- char const *in_end = in + inlen;
- char const *non_nl = get_4 (ctx, &in, in_end, &inlen);
-
- /* If the input is empty or consists solely of newlines (0 non-newlines),
- then we're done. Likewise if there are fewer than 4 bytes when not
- flushing context. */
- if (inlen == 0 || (inlen < 4 && !flush_ctx))
- {
- inlen = 0;
- break;
- }
- if (!decode_4 (non_nl, inlen, &out, &outleft))
- break;
-
- inlen = in_end - in;
+ char const *in_end = in + inlen;
+ char const *non_nl;
+
+ if (ignore_newlines)
+ non_nl = get_4 (ctx, &in, in_end, &inlen);
+ else
+ non_nl = in; /* Might have nl in this case. */
+
+ /* If the input is empty or consists solely of newlines (0 non-newlines),
+ then we're done. Likewise if there are fewer than 4 bytes when not
+ flushing context and not treating newlines as garbage. */
+ if (inlen == 0 || (inlen < 4 && !flush_ctx && ignore_newlines))
+ {
+ inlen = 0;
+ break;
+ }
+ if (!decode_4 (non_nl, inlen, &out, &outleft))
+ break;
+
+ inlen = in_end - in;
}
}
@@ -532,22 +576,22 @@ base64_decode (struct base64_decode_context *ctx,
input was invalid, in which case *OUT is NULL and *OUTLEN is
undefined. */
bool
-base64_decode_alloc (struct base64_decode_context *ctx,
- const char *in, size_t inlen, char **out,
- size_t *outlen)
+base64_decode_alloc_ctx (struct base64_decode_context *ctx,
+ const char *in, size_t inlen, char **out,
+ size_t *outlen)
{
/* This may allocate a few bytes too many, depending on input,
but it's not worth the extra CPU time to compute the exact size.
- The exact size is 3 * inlen / 4, minus 1 if the input ends
- with "=" and minus another 1 if the input ends with "==".
+ The exact size is 3 * (inlen + (ctx ? ctx->i : 0)) / 4, minus 1 if the
+ input ends with "=" and minus another 1 if the input ends with "==".
Dividing before multiplying avoids the possibility of overflow. */
- size_t needlen = 3 * (inlen / 4) + 2;
+ size_t needlen = 3 * (inlen / 4) + 3;
*out = malloc (needlen);
if (!*out)
return true;
- if (!base64_decode (ctx, in, inlen, *out, &needlen))
+ if (!base64_decode_ctx (ctx, in, inlen, *out, &needlen))
{
free (*out);
*out = NULL;
diff --git a/lib/base64.h b/lib/base64.h
index 0399edf..0dbf657 100644
--- a/lib/base64.h
+++ b/lib/base64.h
@@ -1,12 +1,10 @@
-/* -*- buffer-read-only: t -*- vi: set ro: */
-/* DO NOT EDIT! GENERATED AUTOMATICALLY! */
/* base64.h -- Encode binary data using printable characters.
- Copyright (C) 2004, 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2004-2006, 2009-2016 Free Software Foundation, Inc.
Written by Simon Josefsson.
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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -15,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program; if not, see <http://www.gnu.org/licenses/>. */
#ifndef BASE64_H
# define BASE64_H
@@ -27,6 +24,10 @@
/* Get bool. */
# include <stdbool.h>
+# ifdef __cplusplus
+extern "C" {
+# endif
+
/* This uses that the expression (n+(k-1))/k means the smallest
integer >= n/k, i.e., the ceiling of n/k. */
# define BASE64_LENGTH(inlen) ((((inlen) + 2) / 3) * 4)
@@ -37,20 +38,31 @@ struct base64_decode_context
char buf[4];
};
-extern bool isbase64 (char ch);
+extern bool isbase64 (char ch) _GL_ATTRIBUTE_CONST;
extern void base64_encode (const char *restrict in, size_t inlen,
- char *restrict out, size_t outlen);
+ char *restrict out, size_t outlen);
extern size_t base64_encode_alloc (const char *in, size_t inlen, char **out);
extern void base64_decode_ctx_init (struct base64_decode_context *ctx);
-extern bool base64_decode (struct base64_decode_context *ctx,
- const char *restrict in, size_t inlen,
- char *restrict out, size_t *outlen);
-extern bool base64_decode_alloc (struct base64_decode_context *ctx,
- const char *in, size_t inlen,
- char **out, size_t *outlen);
+extern bool base64_decode_ctx (struct base64_decode_context *ctx,
+ const char *restrict in, size_t inlen,
+ char *restrict out, size_t *outlen);
+
+extern bool base64_decode_alloc_ctx (struct base64_decode_context *ctx,
+ const char *in, size_t inlen,
+ char **out, size_t *outlen);
+
+#define base64_decode(in, inlen, out, outlen) \
+ base64_decode_ctx (NULL, in, inlen, out, outlen)
+
+#define base64_decode_alloc(in, inlen, out, outlen) \
+ base64_decode_alloc_ctx (NULL, in, inlen, out, outlen)
+
+# ifdef __cplusplus
+}
+# endif
#endif /* BASE64_H */
diff --git a/lib/basename-lgpl.c b/lib/basename-lgpl.c
new file mode 100644
index 0000000..1182109
--- /dev/null
+++ b/lib/basename-lgpl.c
@@ -0,0 +1,75 @@
+/* basename.c -- return the last element in a file name
+
+ Copyright (C) 1990, 1998-2001, 2003-2006, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+#include "dirname.h"
+
+#include <string.h>
+
+/* Return the address of the last file name component of NAME. If
+ NAME has no relative file name components because it is a file
+ system root, return the empty string. */
+
+char *
+last_component (char const *name)
+{
+ char const *base = name + FILE_SYSTEM_PREFIX_LEN (name);
+ char const *p;
+ bool saw_slash = false;
+
+ while (ISSLASH (*base))
+ base++;
+
+ for (p = base; *p; p++)
+ {
+ if (ISSLASH (*p))
+ saw_slash = true;
+ else if (saw_slash)
+ {
+ base = p;
+ saw_slash = false;
+ }
+ }
+
+ return (char *) base;
+}
+
+/* Return the length of the basename NAME. Typically NAME is the
+ value returned by base_name or last_component. Act like strlen
+ (NAME), except omit all trailing slashes. */
+
+size_t
+base_len (char const *name)
+{
+ size_t len;
+ size_t prefix_len = FILE_SYSTEM_PREFIX_LEN (name);
+
+ for (len = strlen (name); 1 < len && ISSLASH (name[len - 1]); len--)
+ continue;
+
+ if (DOUBLE_SLASH_IS_DISTINCT_ROOT && len == 1
+ && ISSLASH (name[0]) && ISSLASH (name[1]) && ! name[2])
+ return 2;
+
+ if (FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE && prefix_len
+ && len == prefix_len && ISSLASH (name[prefix_len]))
+ return prefix_len + 1;
+
+ return len;
+}
diff --git a/lib/basename.c b/lib/basename.c
index fbe17ff..ed1872d 100644
--- a/lib/basename.c
+++ b/lib/basename.c
@@ -1,12 +1,12 @@
/* basename.c -- return the last element in a file name
- Copyright (C) 1990, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006 Free
- Software Foundation, Inc.
+ Copyright (C) 1990, 1998-2001, 2003-2006, 2009-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
@@ -25,52 +24,6 @@
#include "xalloc.h"
#include "xstrndup.h"
-/* Return the address of the last file name component of NAME. If
- NAME has no relative file name components because it is a file
- system root, return the empty string. */
-
-char *
-last_component (char const *name)
-{
- char const *base = name + FILE_SYSTEM_PREFIX_LEN (name);
- char const *p;
- bool saw_slash = false;
-
- while (ISSLASH (*base))
- base++;
-
- for (p = base; *p; p++)
- {
- if (ISSLASH (*p))
- saw_slash = true;
- else if (saw_slash)
- {
- base = p;
- saw_slash = false;
- }
- }
-
- return (char *) base;
-}
-
-
-/* In general, we can't use the builtin `basename' function if available,
- since it has different meanings in different environments.
- In some environments the builtin `basename' modifies its argument.
-
- Return the last file name component of NAME, allocated with
- xmalloc. On systems with drive letters, a leading "./"
- distinguishes relative names that would otherwise look like a drive
- letter. Unlike POSIX basename(), NAME cannot be NULL,
- base_name("") returns "", and the first trailing slash is not
- stripped.
-
- If lstat (NAME) would succeed, then { chdir (dir_name (NAME));
- lstat (base_name (NAME)); } will access the same file. Likewise,
- if the sequence { chdir (dir_name (NAME));
- rename (base_name (NAME), "foo"); } succeeds, you have renamed NAME
- to "foo" in the same directory NAME was in. */
-
char *
base_name (char const *name)
{
@@ -87,8 +40,8 @@ base_name (char const *name)
if (ISSLASH (base[length]))
length++;
- /* On systems with drive letters, `a/b:c' must return `./b:c' rather
- than `b:c' to avoid confusion with a drive letter. On systems
+ /* On systems with drive letters, "a/b:c" must return "./b:c" rather
+ than "b:c" to avoid confusion with a drive letter. On systems
with pure POSIX semantics, this is not an issue. */
if (FILE_SYSTEM_PREFIX_LEN (base))
{
@@ -103,27 +56,3 @@ base_name (char const *name)
/* Finally, copy the basename. */
return xstrndup (base, length);
}
-
-/* Return the length of the basename NAME. Typically NAME is the
- value returned by base_name or last_component. Act like strlen
- (NAME), except omit all trailing slashes. */
-
-size_t
-base_len (char const *name)
-{
- size_t len;
- size_t prefix_len = FILE_SYSTEM_PREFIX_LEN (name);
-
- for (len = strlen (name); 1 < len && ISSLASH (name[len - 1]); len--)
- continue;
-
- if (DOUBLE_SLASH_IS_DISTINCT_ROOT && len == 1
- && ISSLASH (name[0]) && ISSLASH (name[1]) && ! name[2])
- return 2;
-
- if (FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE && prefix_len
- && len == prefix_len && ISSLASH (name[prefix_len]))
- return prefix_len + 1;
-
- return len;
-}
diff --git a/lib/bitrotate.c b/lib/bitrotate.c
new file mode 100644
index 0000000..a8f6028
--- /dev/null
+++ b/lib/bitrotate.c
@@ -0,0 +1,3 @@
+#include <config.h>
+#define BITROTATE_INLINE _GL_EXTERN_INLINE
+#include "bitrotate.h"
diff --git a/lib/bitrotate.h b/lib/bitrotate.h
new file mode 100644
index 0000000..a259481
--- /dev/null
+++ b/lib/bitrotate.h
@@ -0,0 +1,136 @@
+/* bitrotate.h - Rotate bits in integers
+ Copyright (C) 2008-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Simon Josefsson <simon@josefsson.org>, 2008. */
+
+#ifndef _GL_BITROTATE_H
+#define _GL_BITROTATE_H
+
+#include <limits.h>
+#include <stdint.h>
+#include <sys/types.h>
+
+#ifndef _GL_INLINE_HEADER_BEGIN
+ #error "Please include config.h first."
+#endif
+_GL_INLINE_HEADER_BEGIN
+#ifndef BITROTATE_INLINE
+# define BITROTATE_INLINE _GL_INLINE
+#endif
+
+#ifdef UINT64_MAX
+/* Given an unsigned 64-bit argument X, return the value corresponding
+ to rotating the bits N steps to the left. N must be between 1 and
+ 63 inclusive. */
+BITROTATE_INLINE uint64_t
+rotl64 (uint64_t x, int n)
+{
+ return ((x << n) | (x >> (64 - n))) & UINT64_MAX;
+}
+
+/* Given an unsigned 64-bit argument X, return the value corresponding
+ to rotating the bits N steps to the right. N must be between 1 to
+ 63 inclusive.*/
+BITROTATE_INLINE uint64_t
+rotr64 (uint64_t x, int n)
+{
+ return ((x >> n) | (x << (64 - n))) & UINT64_MAX;
+}
+#endif
+
+/* Given an unsigned 32-bit argument X, return the value corresponding
+ to rotating the bits N steps to the left. N must be between 1 and
+ 31 inclusive. */
+BITROTATE_INLINE uint32_t
+rotl32 (uint32_t x, int n)
+{
+ return ((x << n) | (x >> (32 - n))) & UINT32_MAX;
+}
+
+/* Given an unsigned 32-bit argument X, return the value corresponding
+ to rotating the bits N steps to the right. N must be between 1 to
+ 31 inclusive.*/
+BITROTATE_INLINE uint32_t
+rotr32 (uint32_t x, int n)
+{
+ return ((x >> n) | (x << (32 - n))) & UINT32_MAX;
+}
+
+/* Given a size_t argument X, return the value corresponding
+ to rotating the bits N steps to the left. N must be between 1 and
+ (CHAR_BIT * sizeof (size_t) - 1) inclusive. */
+BITROTATE_INLINE size_t
+rotl_sz (size_t x, int n)
+{
+ return ((x << n) | (x >> ((CHAR_BIT * sizeof x) - n))) & SIZE_MAX;
+}
+
+/* Given a size_t argument X, return the value corresponding
+ to rotating the bits N steps to the right. N must be between 1 to
+ (CHAR_BIT * sizeof (size_t) - 1) inclusive. */
+BITROTATE_INLINE size_t
+rotr_sz (size_t x, int n)
+{
+ return ((x >> n) | (x << ((CHAR_BIT * sizeof x) - n))) & SIZE_MAX;
+}
+
+/* Given an unsigned 16-bit argument X, return the value corresponding
+ to rotating the bits N steps to the left. N must be between 1 to
+ 15 inclusive, but on most relevant targets N can also be 0 and 16
+ because 'int' is at least 32 bits and the arguments must widen
+ before shifting. */
+BITROTATE_INLINE uint16_t
+rotl16 (uint16_t x, int n)
+{
+ return ((x << n) | (x >> (16 - n))) & UINT16_MAX;
+}
+
+/* Given an unsigned 16-bit argument X, return the value corresponding
+ to rotating the bits N steps to the right. N must be in 1 to 15
+ inclusive, but on most relevant targets N can also be 0 and 16
+ because 'int' is at least 32 bits and the arguments must widen
+ before shifting. */
+BITROTATE_INLINE uint16_t
+rotr16 (uint16_t x, int n)
+{
+ return ((x >> n) | (x << (16 - n))) & UINT16_MAX;
+}
+
+/* Given an unsigned 8-bit argument X, return the value corresponding
+ to rotating the bits N steps to the left. N must be between 1 to 7
+ inclusive, but on most relevant targets N can also be 0 and 8
+ because 'int' is at least 32 bits and the arguments must widen
+ before shifting. */
+BITROTATE_INLINE uint8_t
+rotl8 (uint8_t x, int n)
+{
+ return ((x << n) | (x >> (8 - n))) & UINT8_MAX;
+}
+
+/* Given an unsigned 8-bit argument X, return the value corresponding
+ to rotating the bits N steps to the right. N must be in 1 to 7
+ inclusive, but on most relevant targets N can also be 0 and 8
+ because 'int' is at least 32 bits and the arguments must widen
+ before shifting. */
+BITROTATE_INLINE uint8_t
+rotr8 (uint8_t x, int n)
+{
+ return ((x >> n) | (x << (8 - n))) & UINT8_MAX;
+}
+
+_GL_INLINE_HEADER_END
+
+#endif /* _GL_BITROTATE_H */
diff --git a/lib/btowc.c b/lib/btowc.c
new file mode 100644
index 0000000..e7badf9
--- /dev/null
+++ b/lib/btowc.c
@@ -0,0 +1,39 @@
+/* Convert unibyte character to wide character.
+ Copyright (C) 2008, 2010-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2008.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <wchar.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+
+wint_t
+btowc (int c)
+{
+ if (c != EOF)
+ {
+ char buf[1];
+ wchar_t wc;
+
+ buf[0] = c;
+ if (mbtowc (&wc, buf, 1) >= 0)
+ return wc;
+ }
+ return WEOF;
+}
diff --git a/lib/buffer-lcm.c b/lib/buffer-lcm.c
index c3f6109..44b736e 100644
--- a/lib/buffer-lcm.c
+++ b/lib/buffer-lcm.c
@@ -1,11 +1,11 @@
/* buffer-lcm.c - compute a good buffer size for dealing with two files
- Copyright (C) 2002, 2005 Free Software Foundation, Inc.
+ Copyright (C) 2002-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,11 +13,11 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
+#include <config.h>
#include "buffer-lcm.h"
/* Return a buffer size suitable for doing I/O with files whose block
@@ -35,22 +35,22 @@ buffer_lcm (size_t a, size_t b, size_t lcm_max)
else
{
if (b)
- {
- /* Return lcm (A, B) if it is in range; otherwise, fall back
- on A. */
-
- size_t lcm, m, n, q, r;
-
- /* N = gcd (A, B). */
- for (m = a, n = b; (r = m % n) != 0; m = n, n = r)
- continue;
-
- /* LCM = lcm (A, B), if in range. */
- q = a / n;
- lcm = q * b;
- if (lcm <= lcm_max && lcm / b == q)
- return lcm;
- }
+ {
+ /* Return lcm (A, B) if it is in range; otherwise, fall back
+ on A. */
+
+ size_t lcm, m, n, q, r;
+
+ /* N = gcd (A, B). */
+ for (m = a, n = b; (r = m % n) != 0; m = n, n = r)
+ continue;
+
+ /* LCM = lcm (A, B), if in range. */
+ q = a / n;
+ lcm = q * b;
+ if (lcm <= lcm_max && lcm / b == q)
+ return lcm;
+ }
size = a;
}
diff --git a/lib/buffer-lcm.h b/lib/buffer-lcm.h
index 9a6cdf5..454c65b 100644
--- a/lib/buffer-lcm.h
+++ b/lib/buffer-lcm.h
@@ -1,2 +1,2 @@
#include <stddef.h>
-size_t buffer_lcm (size_t, size_t, size_t);
+size_t buffer_lcm (size_t, size_t, size_t) _GL_ATTRIBUTE_CONST;
diff --git a/lib/c-ctype.c b/lib/c-ctype.c
index 36569b8..5d9d4d8 100644
--- a/lib/c-ctype.c
+++ b/lib/c-ctype.c
@@ -1,396 +1,3 @@
-/* Character handling in C locale.
-
- Copyright 2000-2003, 2006 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 2 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, write to the Free Software Foundation,
-Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
#include <config.h>
-
-/* Specification. */
-#define NO_C_CTYPE_MACROS
+#define C_CTYPE_INLINE _GL_EXTERN_INLINE
#include "c-ctype.h"
-
-/* The function isascii is not locale dependent. Its use in EBCDIC is
- questionable. */
-bool
-c_isascii (int c)
-{
- return (c >= 0x00 && c <= 0x7f);
-}
-
-bool
-c_isalnum (int c)
-{
-#if C_CTYPE_CONSECUTIVE_DIGITS \
- && C_CTYPE_CONSECUTIVE_UPPERCASE && C_CTYPE_CONSECUTIVE_LOWERCASE
-#if C_CTYPE_ASCII
- return ((c >= '0' && c <= '9')
- || ((c & ~0x20) >= 'A' && (c & ~0x20) <= 'Z'));
-#else
- return ((c >= '0' && c <= '9')
- || (c >= 'A' && c <= 'Z')
- || (c >= 'a' && c <= 'z'));
-#endif
-#else
- switch (c)
- {
- case '0': case '1': case '2': case '3': case '4': case '5':
- case '6': case '7': case '8': case '9':
- case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
- case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
- case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
- case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
- case 'Y': case 'Z':
- case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
- case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
- case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
- case 's': case 't': case 'u': case 'v': case 'w': case 'x':
- case 'y': case 'z':
- return 1;
- default:
- return 0;
- }
-#endif
-}
-
-bool
-c_isalpha (int c)
-{
-#if C_CTYPE_CONSECUTIVE_UPPERCASE && C_CTYPE_CONSECUTIVE_LOWERCASE
-#if C_CTYPE_ASCII
- return ((c & ~0x20) >= 'A' && (c & ~0x20) <= 'Z');
-#else
- return ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'));
-#endif
-#else
- switch (c)
- {
- case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
- case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
- case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
- case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
- case 'Y': case 'Z':
- case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
- case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
- case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
- case 's': case 't': case 'u': case 'v': case 'w': case 'x':
- case 'y': case 'z':
- return 1;
- default:
- return 0;
- }
-#endif
-}
-
-bool
-c_isblank (int c)
-{
- return (c == ' ' || c == '\t');
-}
-
-bool
-c_iscntrl (int c)
-{
-#if C_CTYPE_ASCII
- return ((c & ~0x1f) == 0 || c == 0x7f);
-#else
- switch (c)
- {
- case ' ': case '!': case '"': case '#': case '$': case '%':
- case '&': case '\'': case '(': case ')': case '*': case '+':
- case ',': case '-': case '.': case '/':
- case '0': case '1': case '2': case '3': case '4': case '5':
- case '6': case '7': case '8': case '9':
- case ':': case ';': case '<': case '=': case '>': case '?':
- case '@':
- case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
- case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
- case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
- case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
- case 'Y': case 'Z':
- case '[': case '\\': case ']': case '^': case '_': case '`':
- case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
- case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
- case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
- case 's': case 't': case 'u': case 'v': case 'w': case 'x':
- case 'y': case 'z':
- case '{': case '|': case '}': case '~':
- return 0;
- default:
- return 1;
- }
-#endif
-}
-
-bool
-c_isdigit (int c)
-{
-#if C_CTYPE_CONSECUTIVE_DIGITS
- return (c >= '0' && c <= '9');
-#else
- switch (c)
- {
- case '0': case '1': case '2': case '3': case '4': case '5':
- case '6': case '7': case '8': case '9':
- return 1;
- default:
- return 0;
- }
-#endif
-}
-
-bool
-c_islower (int c)
-{
-#if C_CTYPE_CONSECUTIVE_LOWERCASE
- return (c >= 'a' && c <= 'z');
-#else
- switch (c)
- {
- case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
- case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
- case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
- case 's': case 't': case 'u': case 'v': case 'w': case 'x':
- case 'y': case 'z':
- return 1;
- default:
- return 0;
- }
-#endif
-}
-
-bool
-c_isgraph (int c)
-{
-#if C_CTYPE_ASCII
- return (c >= '!' && c <= '~');
-#else
- switch (c)
- {
- case '!': case '"': case '#': case '$': case '%': case '&':
- case '\'': case '(': case ')': case '*': case '+': case ',':
- case '-': case '.': case '/':
- case '0': case '1': case '2': case '3': case '4': case '5':
- case '6': case '7': case '8': case '9':
- case ':': case ';': case '<': case '=': case '>': case '?':
- case '@':
- case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
- case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
- case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
- case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
- case 'Y': case 'Z':
- case '[': case '\\': case ']': case '^': case '_': case '`':
- case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
- case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
- case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
- case 's': case 't': case 'u': case 'v': case 'w': case 'x':
- case 'y': case 'z':
- case '{': case '|': case '}': case '~':
- return 1;
- default:
- return 0;
- }
-#endif
-}
-
-bool
-c_isprint (int c)
-{
-#if C_CTYPE_ASCII
- return (c >= ' ' && c <= '~');
-#else
- switch (c)
- {
- case ' ': case '!': case '"': case '#': case '$': case '%':
- case '&': case '\'': case '(': case ')': case '*': case '+':
- case ',': case '-': case '.': case '/':
- case '0': case '1': case '2': case '3': case '4': case '5':
- case '6': case '7': case '8': case '9':
- case ':': case ';': case '<': case '=': case '>': case '?':
- case '@':
- case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
- case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
- case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
- case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
- case 'Y': case 'Z':
- case '[': case '\\': case ']': case '^': case '_': case '`':
- case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
- case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
- case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
- case 's': case 't': case 'u': case 'v': case 'w': case 'x':
- case 'y': case 'z':
- case '{': case '|': case '}': case '~':
- return 1;
- default:
- return 0;
- }
-#endif
-}
-
-bool
-c_ispunct (int c)
-{
-#if C_CTYPE_ASCII
- return ((c >= '!' && c <= '~')
- && !((c >= '0' && c <= '9')
- || ((c & ~0x20) >= 'A' && (c & ~0x20) <= 'Z')));
-#else
- switch (c)
- {
- case '!': case '"': case '#': case '$': case '%': case '&':
- case '\'': case '(': case ')': case '*': case '+': case ',':
- case '-': case '.': case '/':
- case ':': case ';': case '<': case '=': case '>': case '?':
- case '@':
- case '[': case '\\': case ']': case '^': case '_': case '`':
- case '{': case '|': case '}': case '~':
- return 1;
- default:
- return 0;
- }
-#endif
-}
-
-bool
-c_isspace (int c)
-{
- return (c == ' ' || c == '\t'
- || c == '\n' || c == '\v' || c == '\f' || c == '\r');
-}
-
-bool
-c_isupper (int c)
-{
-#if C_CTYPE_CONSECUTIVE_UPPERCASE
- return (c >= 'A' && c <= 'Z');
-#else
- switch (c)
- {
- case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
- case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
- case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
- case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
- case 'Y': case 'Z':
- return 1;
- default:
- return 0;
- }
-#endif
-}
-
-bool
-c_isxdigit (int c)
-{
-#if C_CTYPE_CONSECUTIVE_DIGITS \
- && C_CTYPE_CONSECUTIVE_UPPERCASE && C_CTYPE_CONSECUTIVE_LOWERCASE
-#if C_CTYPE_ASCII
- return ((c >= '0' && c <= '9')
- || ((c & ~0x20) >= 'A' && (c & ~0x20) <= 'F'));
-#else
- return ((c >= '0' && c <= '9')
- || (c >= 'A' && c <= 'F')
- || (c >= 'a' && c <= 'f'));
-#endif
-#else
- switch (c)
- {
- case '0': case '1': case '2': case '3': case '4': case '5':
- case '6': case '7': case '8': case '9':
- case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
- case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
- return 1;
- default:
- return 0;
- }
-#endif
-}
-
-int
-c_tolower (int c)
-{
-#if C_CTYPE_CONSECUTIVE_UPPERCASE && C_CTYPE_CONSECUTIVE_LOWERCASE
- return (c >= 'A' && c <= 'Z' ? c - 'A' + 'a' : c);
-#else
- switch (c)
- {
- case 'A': return 'a';
- case 'B': return 'b';
- case 'C': return 'c';
- case 'D': return 'd';
- case 'E': return 'e';
- case 'F': return 'f';
- case 'G': return 'g';
- case 'H': return 'h';
- case 'I': return 'i';
- case 'J': return 'j';
- case 'K': return 'k';
- case 'L': return 'l';
- case 'M': return 'm';
- case 'N': return 'n';
- case 'O': return 'o';
- case 'P': return 'p';
- case 'Q': return 'q';
- case 'R': return 'r';
- case 'S': return 's';
- case 'T': return 't';
- case 'U': return 'u';
- case 'V': return 'v';
- case 'W': return 'w';
- case 'X': return 'x';
- case 'Y': return 'y';
- case 'Z': return 'z';
- default: return c;
- }
-#endif
-}
-
-int
-c_toupper (int c)
-{
-#if C_CTYPE_CONSECUTIVE_UPPERCASE && C_CTYPE_CONSECUTIVE_LOWERCASE
- return (c >= 'a' && c <= 'z' ? c - 'a' + 'A' : c);
-#else
- switch (c)
- {
- case 'a': return 'A';
- case 'b': return 'B';
- case 'c': return 'C';
- case 'd': return 'D';
- case 'e': return 'E';
- case 'f': return 'F';
- case 'g': return 'G';
- case 'h': return 'H';
- case 'i': return 'I';
- case 'j': return 'J';
- case 'k': return 'K';
- case 'l': return 'L';
- case 'm': return 'M';
- case 'n': return 'N';
- case 'o': return 'O';
- case 'p': return 'P';
- case 'q': return 'Q';
- case 'r': return 'R';
- case 's': return 'S';
- case 't': return 'T';
- case 'u': return 'U';
- case 'v': return 'V';
- case 'w': return 'W';
- case 'x': return 'X';
- case 'y': return 'Y';
- case 'z': return 'Z';
- default: return c;
- }
-#endif
-}
diff --git a/lib/c-ctype.h b/lib/c-ctype.h
index b26eccf..717ae78 100644
--- a/lib/c-ctype.h
+++ b/lib/c-ctype.h
@@ -5,11 +5,11 @@
<ctype.h> functions' behaviour depends on the current locale set via
setlocale.
- Copyright (C) 2000-2003, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2000-2003, 2006, 2008-2016 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 2 of the License, or
+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,
@@ -18,14 +18,20 @@ 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, write to the Free Software Foundation,
-Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+along with this program; if not, see <http://www.gnu.org/licenses/>. */
#ifndef C_CTYPE_H
#define C_CTYPE_H
#include <stdbool.h>
+#ifndef _GL_INLINE_HEADER_BEGIN
+ #error "Please include config.h first."
+#endif
+_GL_INLINE_HEADER_BEGIN
+#ifndef C_CTYPE_INLINE
+# define C_CTYPE_INLINE _GL_INLINE
+#endif
#ifdef __cplusplus
extern "C" {
@@ -40,38 +46,6 @@ extern "C" {
characters. */
-/* Check whether the ASCII optimizations apply. */
-
-/* ANSI C89 (and ISO C99 5.2.1.3 too) already guarantees that
- '0', '1', ..., '9' have consecutive integer values. */
-#define C_CTYPE_CONSECUTIVE_DIGITS 1
-
-#if ('A' <= 'Z') \
- && ('A' + 1 == 'B') && ('B' + 1 == 'C') && ('C' + 1 == 'D') \
- && ('D' + 1 == 'E') && ('E' + 1 == 'F') && ('F' + 1 == 'G') \
- && ('G' + 1 == 'H') && ('H' + 1 == 'I') && ('I' + 1 == 'J') \
- && ('J' + 1 == 'K') && ('K' + 1 == 'L') && ('L' + 1 == 'M') \
- && ('M' + 1 == 'N') && ('N' + 1 == 'O') && ('O' + 1 == 'P') \
- && ('P' + 1 == 'Q') && ('Q' + 1 == 'R') && ('R' + 1 == 'S') \
- && ('S' + 1 == 'T') && ('T' + 1 == 'U') && ('U' + 1 == 'V') \
- && ('V' + 1 == 'W') && ('W' + 1 == 'X') && ('X' + 1 == 'Y') \
- && ('Y' + 1 == 'Z')
-#define C_CTYPE_CONSECUTIVE_UPPERCASE 1
-#endif
-
-#if ('a' <= 'z') \
- && ('a' + 1 == 'b') && ('b' + 1 == 'c') && ('c' + 1 == 'd') \
- && ('d' + 1 == 'e') && ('e' + 1 == 'f') && ('f' + 1 == 'g') \
- && ('g' + 1 == 'h') && ('h' + 1 == 'i') && ('i' + 1 == 'j') \
- && ('j' + 1 == 'k') && ('k' + 1 == 'l') && ('l' + 1 == 'm') \
- && ('m' + 1 == 'n') && ('n' + 1 == 'o') && ('o' + 1 == 'p') \
- && ('p' + 1 == 'q') && ('q' + 1 == 'r') && ('r' + 1 == 's') \
- && ('s' + 1 == 't') && ('t' + 1 == 'u') && ('u' + 1 == 'v') \
- && ('v' + 1 == 'w') && ('w' + 1 == 'x') && ('x' + 1 == 'y') \
- && ('y' + 1 == 'z')
-#define C_CTYPE_CONSECUTIVE_LOWERCASE 1
-#endif
-
#if (' ' == 32) && ('!' == 33) && ('"' == 34) && ('#' == 35) \
&& ('%' == 37) && ('&' == 38) && ('\'' == 39) && ('(' == 40) \
&& (')' == 41) && ('*' == 42) && ('+' == 43) && (',' == 44) \
@@ -97,184 +71,296 @@ extern "C" {
&& ('{' == 123) && ('|' == 124) && ('}' == 125) && ('~' == 126)
/* The character set is ASCII or one of its variants or extensions, not EBCDIC.
Testing the value of '\n' and '\r' is not relevant. */
-#define C_CTYPE_ASCII 1
+# define C_CTYPE_ASCII 1
+#elif ! (' ' == '\x40' && '0' == '\xf0' \
+ && 'A' == '\xc1' && 'J' == '\xd1' && 'S' == '\xe2' \
+ && 'a' == '\x81' && 'j' == '\x91' && 's' == '\xa2')
+# error "Only ASCII and EBCDIC are supported"
#endif
+#if 'A' < 0
+# error "EBCDIC and char is signed -- not supported"
+#endif
-/* Function declarations. */
-
-extern bool c_isascii (int c); /* not locale dependent */
-
-extern bool c_isalnum (int c);
-extern bool c_isalpha (int c);
-extern bool c_isblank (int c);
-extern bool c_iscntrl (int c);
-extern bool c_isdigit (int c);
-extern bool c_islower (int c);
-extern bool c_isgraph (int c);
-extern bool c_isprint (int c);
-extern bool c_ispunct (int c);
-extern bool c_isspace (int c);
-extern bool c_isupper (int c);
-extern bool c_isxdigit (int c);
-
-extern int c_tolower (int c);
-extern int c_toupper (int c);
-
-
-#if defined __GNUC__ && defined __OPTIMIZE__ && !defined __OPTIMIZE_SIZE__ && !defined NO_C_CTYPE_MACROS
+/* Cases for control characters. */
-/* ASCII optimizations. */
+#define _C_CTYPE_CNTRL \
+ case '\a': case '\b': case '\f': case '\n': \
+ case '\r': case '\t': case '\v': \
+ _C_CTYPE_OTHER_CNTRL
-#undef c_isascii
-#define c_isascii(c) \
- ({ int __c = (c); \
- (__c >= 0x00 && __c <= 0x7f); \
- })
+/* ASCII control characters other than those with \-letter escapes. */
-#if C_CTYPE_CONSECUTIVE_DIGITS \
- && C_CTYPE_CONSECUTIVE_UPPERCASE && C_CTYPE_CONSECUTIVE_LOWERCASE
#if C_CTYPE_ASCII
-#undef c_isalnum
-#define c_isalnum(c) \
- ({ int __c = (c); \
- ((__c >= '0' && __c <= '9') \
- || ((__c & ~0x20) >= 'A' && (__c & ~0x20) <= 'Z')); \
- })
+# define _C_CTYPE_OTHER_CNTRL \
+ case '\x00': case '\x01': case '\x02': case '\x03': \
+ case '\x04': case '\x05': case '\x06': case '\x0e': \
+ case '\x0f': case '\x10': case '\x11': case '\x12': \
+ case '\x13': case '\x14': case '\x15': case '\x16': \
+ case '\x17': case '\x18': case '\x19': case '\x1a': \
+ case '\x1b': case '\x1c': case '\x1d': case '\x1e': \
+ case '\x1f': case '\x7f'
#else
-#undef c_isalnum
-#define c_isalnum(c) \
- ({ int __c = (c); \
- ((__c >= '0' && __c <= '9') \
- || (__c >= 'A' && __c <= 'Z') \
- || (__c >= 'a' && __c <= 'z')); \
- })
-#endif
+ /* Use EBCDIC code page 1047's assignments for ASCII control chars;
+ assume all EBCDIC code pages agree about these assignments. */
+# define _C_CTYPE_OTHER_CNTRL \
+ case '\x00': case '\x01': case '\x02': case '\x03': \
+ case '\x07': case '\x0e': case '\x0f': case '\x10': \
+ case '\x11': case '\x12': case '\x13': case '\x18': \
+ case '\x19': case '\x1c': case '\x1d': case '\x1e': \
+ case '\x1f': case '\x26': case '\x27': case '\x2d': \
+ case '\x2e': case '\x32': case '\x37': case '\x3c': \
+ case '\x3d': case '\x3f'
#endif
-#if C_CTYPE_CONSECUTIVE_UPPERCASE && C_CTYPE_CONSECUTIVE_LOWERCASE
-#if C_CTYPE_ASCII
-#undef c_isalpha
-#define c_isalpha(c) \
- ({ int __c = (c); \
- ((__c & ~0x20) >= 'A' && (__c & ~0x20) <= 'Z'); \
- })
-#else
-#undef c_isalpha
-#define c_isalpha(c) \
- ({ int __c = (c); \
- ((__c >= 'A' && __c <= 'Z') || (__c >= 'a' && __c <= 'z')); \
- })
-#endif
-#endif
+/* Cases for lowercase hex letters, and lowercase letters, all offset by N. */
+
+#define _C_CTYPE_LOWER_A_THRU_F_N(n) \
+ case 'a' + (n): case 'b' + (n): case 'c' + (n): case 'd' + (n): \
+ case 'e' + (n): case 'f' + (n)
+#define _C_CTYPE_LOWER_N(n) \
+ _C_CTYPE_LOWER_A_THRU_F_N(n): \
+ case 'g' + (n): case 'h' + (n): case 'i' + (n): case 'j' + (n): \
+ case 'k' + (n): case 'l' + (n): case 'm' + (n): case 'n' + (n): \
+ case 'o' + (n): case 'p' + (n): case 'q' + (n): case 'r' + (n): \
+ case 's' + (n): case 't' + (n): case 'u' + (n): case 'v' + (n): \
+ case 'w' + (n): case 'x' + (n): case 'y' + (n): case 'z' + (n)
+
+/* Cases for hex letters, digits, lower, punct, and upper. */
+
+#define _C_CTYPE_A_THRU_F \
+ _C_CTYPE_LOWER_A_THRU_F_N (0): \
+ _C_CTYPE_LOWER_A_THRU_F_N ('A' - 'a')
+#define _C_CTYPE_DIGIT \
+ case '0': case '1': case '2': case '3': \
+ case '4': case '5': case '6': case '7': \
+ case '8': case '9'
+#define _C_CTYPE_LOWER _C_CTYPE_LOWER_N (0)
+#define _C_CTYPE_PUNCT \
+ case '!': case '"': case '#': case '$': \
+ case '%': case '&': case '\'': case '(': \
+ case ')': case '*': case '+': case ',': \
+ case '-': case '.': case '/': case ':': \
+ case ';': case '<': case '=': case '>': \
+ case '?': case '@': case '[': case '\\': \
+ case ']': case '^': case '_': case '`': \
+ case '{': case '|': case '}': case '~'
+#define _C_CTYPE_UPPER _C_CTYPE_LOWER_N ('A' - 'a')
+
+
+/* Function definitions. */
+
+/* Unlike the functions in <ctype.h>, which require an argument in the range
+ of the 'unsigned char' type, the functions here operate on values that are
+ in the 'unsigned char' range or in the 'char' range. In other words,
+ when you have a 'char' value, you need to cast it before using it as
+ argument to a <ctype.h> function:
+
+ const char *s = ...;
+ if (isalpha ((unsigned char) *s)) ...
+
+ but you don't need to cast it for the functions defined in this file:
+
+ const char *s = ...;
+ if (c_isalpha (*s)) ...
+ */
+
+C_CTYPE_INLINE bool
+c_isalnum (int c)
+{
+ switch (c)
+ {
+ _C_CTYPE_DIGIT:
+ _C_CTYPE_LOWER:
+ _C_CTYPE_UPPER:
+ return true;
+ default:
+ return false;
+ }
+}
-#undef c_isblank
-#define c_isblank(c) \
- ({ int __c = (c); \
- (__c == ' ' || __c == '\t'); \
- })
+C_CTYPE_INLINE bool
+c_isalpha (int c)
+{
+ switch (c)
+ {
+ _C_CTYPE_LOWER:
+ _C_CTYPE_UPPER:
+ return true;
+ default:
+ return false;
+ }
+}
-#if C_CTYPE_ASCII
-#undef c_iscntrl
-#define c_iscntrl(c) \
- ({ int __c = (c); \
- ((__c & ~0x1f) == 0 || __c == 0x7f); \
- })
-#endif
+/* The function isascii is not locale dependent.
+ Its use in EBCDIC is questionable. */
+C_CTYPE_INLINE bool
+c_isascii (int c)
+{
+ switch (c)
+ {
+ case ' ':
+ _C_CTYPE_CNTRL:
+ _C_CTYPE_DIGIT:
+ _C_CTYPE_LOWER:
+ _C_CTYPE_PUNCT:
+ _C_CTYPE_UPPER:
+ return true;
+ default:
+ return false;
+ }
+}
-#if C_CTYPE_CONSECUTIVE_DIGITS
-#undef c_isdigit
-#define c_isdigit(c) \
- ({ int __c = (c); \
- (__c >= '0' && __c <= '9'); \
- })
-#endif
+C_CTYPE_INLINE bool
+c_isblank (int c)
+{
+ return c == ' ' || c == '\t';
+}
-#if C_CTYPE_CONSECUTIVE_LOWERCASE
-#undef c_islower
-#define c_islower(c) \
- ({ int __c = (c); \
- (__c >= 'a' && __c <= 'z'); \
- })
-#endif
+C_CTYPE_INLINE bool
+c_iscntrl (int c)
+{
+ switch (c)
+ {
+ _C_CTYPE_CNTRL:
+ return true;
+ default:
+ return false;
+ }
+}
-#if C_CTYPE_ASCII
-#undef c_isgraph
-#define c_isgraph(c) \
- ({ int __c = (c); \
- (__c >= '!' && __c <= '~'); \
- })
-#endif
+C_CTYPE_INLINE bool
+c_isdigit (int c)
+{
+ switch (c)
+ {
+ _C_CTYPE_DIGIT:
+ return true;
+ default:
+ return false;
+ }
+}
-#if C_CTYPE_ASCII
-#undef c_isprint
-#define c_isprint(c) \
- ({ int __c = (c); \
- (__c >= ' ' && __c <= '~'); \
- })
-#endif
+C_CTYPE_INLINE bool
+c_isgraph (int c)
+{
+ switch (c)
+ {
+ _C_CTYPE_DIGIT:
+ _C_CTYPE_LOWER:
+ _C_CTYPE_PUNCT:
+ _C_CTYPE_UPPER:
+ return true;
+ default:
+ return false;
+ }
+}
-#if C_CTYPE_ASCII
-#undef c_ispunct
-#define c_ispunct(c) \
- ({ int _c = (c); \
- (c_isgraph (_c) && ! c_isalnum (_c)); \
- })
-#endif
+C_CTYPE_INLINE bool
+c_islower (int c)
+{
+ switch (c)
+ {
+ _C_CTYPE_LOWER:
+ return true;
+ default:
+ return false;
+ }
+}
-#undef c_isspace
-#define c_isspace(c) \
- ({ int __c = (c); \
- (__c == ' ' || __c == '\t' \
- || __c == '\n' || __c == '\v' || __c == '\f' || __c == '\r'); \
- })
-
-#if C_CTYPE_CONSECUTIVE_UPPERCASE
-#undef c_isupper
-#define c_isupper(c) \
- ({ int __c = (c); \
- (__c >= 'A' && __c <= 'Z'); \
- })
-#endif
+C_CTYPE_INLINE bool
+c_isprint (int c)
+{
+ switch (c)
+ {
+ case ' ':
+ _C_CTYPE_DIGIT:
+ _C_CTYPE_LOWER:
+ _C_CTYPE_PUNCT:
+ _C_CTYPE_UPPER:
+ return true;
+ default:
+ return false;
+ }
+}
-#if C_CTYPE_CONSECUTIVE_DIGITS \
- && C_CTYPE_CONSECUTIVE_UPPERCASE && C_CTYPE_CONSECUTIVE_LOWERCASE
-#if C_CTYPE_ASCII
-#undef c_isxdigit
-#define c_isxdigit(c) \
- ({ int __c = (c); \
- ((__c >= '0' && __c <= '9') \
- || ((__c & ~0x20) >= 'A' && (__c & ~0x20) <= 'F')); \
- })
-#else
-#undef c_isxdigit
-#define c_isxdigit(c) \
- ({ int __c = (c); \
- ((__c >= '0' && __c <= '9') \
- || (__c >= 'A' && __c <= 'F') \
- || (__c >= 'a' && __c <= 'f')); \
- })
-#endif
-#endif
+C_CTYPE_INLINE bool
+c_ispunct (int c)
+{
+ switch (c)
+ {
+ _C_CTYPE_PUNCT:
+ return true;
+ default:
+ return false;
+ }
+}
-#if C_CTYPE_CONSECUTIVE_UPPERCASE && C_CTYPE_CONSECUTIVE_LOWERCASE
-#undef c_tolower
-#define c_tolower(c) \
- ({ int __c = (c); \
- (__c >= 'A' && __c <= 'Z' ? __c - 'A' + 'a' : __c); \
- })
-#undef c_toupper
-#define c_toupper(c) \
- ({ int __c = (c); \
- (__c >= 'a' && __c <= 'z' ? __c - 'a' + 'A' : __c); \
- })
-#endif
+C_CTYPE_INLINE bool
+c_isspace (int c)
+{
+ switch (c)
+ {
+ case ' ': case '\t': case '\n': case '\v': case '\f': case '\r':
+ return true;
+ default:
+ return false;
+ }
+}
-#endif /* optimizing for speed */
+C_CTYPE_INLINE bool
+c_isupper (int c)
+{
+ switch (c)
+ {
+ _C_CTYPE_UPPER:
+ return true;
+ default:
+ return false;
+ }
+}
+C_CTYPE_INLINE bool
+c_isxdigit (int c)
+{
+ switch (c)
+ {
+ _C_CTYPE_DIGIT:
+ _C_CTYPE_A_THRU_F:
+ return true;
+ default:
+ return false;
+ }
+}
+
+C_CTYPE_INLINE int
+c_tolower (int c)
+{
+ switch (c)
+ {
+ _C_CTYPE_UPPER:
+ return c - 'A' + 'a';
+ default:
+ return c;
+ }
+}
+
+C_CTYPE_INLINE int
+c_toupper (int c)
+{
+ switch (c)
+ {
+ _C_CTYPE_LOWER:
+ return c - 'a' + 'A';
+ default:
+ return c;
+ }
+}
#ifdef __cplusplus
}
#endif
+_GL_INLINE_HEADER_END
+
#endif /* C_CTYPE_H */
diff --git a/lib/c-strcase.h b/lib/c-strcase.h
index 1ababff..7e570f5 100644
--- a/lib/c-strcase.h
+++ b/lib/c-strcase.h
@@ -1,9 +1,10 @@
/* Case-insensitive string comparison functions in C locale.
- Copyright (C) 1995-1996, 2001, 2003, 2005 Free Software Foundation, Inc.
+ Copyright (C) 1995-1996, 2001, 2003, 2005, 2009-2016 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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -12,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program; if not, see <http://www.gnu.org/licenses/>. */
#ifndef C_STRCASE_H
#define C_STRCASE_H
@@ -39,12 +39,13 @@ extern "C" {
/* Compare strings S1 and S2, ignoring case, returning less than, equal to or
greater than zero if S1 is lexicographically less than, equal to or greater
than S2. */
-extern int c_strcasecmp (const char *s1, const char *s2);
+extern int c_strcasecmp (const char *s1, const char *s2) _GL_ATTRIBUTE_PURE;
/* Compare no more than N characters of strings S1 and S2, ignoring case,
returning less than, equal to or greater than zero if S1 is
lexicographically less than, equal to or greater than S2. */
-extern int c_strncasecmp (const char *s1, const char *s2, size_t n);
+extern int c_strncasecmp (const char *s1, const char *s2, size_t n)
+ _GL_ATTRIBUTE_PURE;
#ifdef __cplusplus
diff --git a/lib/c-strcasecmp.c b/lib/c-strcasecmp.c
index 13b15f9..bd113b7 100644
--- a/lib/c-strcasecmp.c
+++ b/lib/c-strcasecmp.c
@@ -1,9 +1,9 @@
/* c-strcasecmp.c -- case insensitive string comparator in C locale
- Copyright (C) 1998-1999, 2005-2006 Free Software Foundation, Inc.
+ Copyright (C) 1998-1999, 2005-2006, 2009-2016 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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -12,8 +12,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program; if not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
@@ -40,7 +39,7 @@ c_strcasecmp (const char *s1, const char *s2)
c2 = c_tolower (*p2);
if (c1 == '\0')
- break;
+ break;
++p1;
++p2;
diff --git a/lib/c-strcaseeq.h b/lib/c-strcaseeq.h
new file mode 100644
index 0000000..ed57251
--- /dev/null
+++ b/lib/c-strcaseeq.h
@@ -0,0 +1,181 @@
+/* Optimized case-insensitive string comparison in C locale.
+ Copyright (C) 2001-2002, 2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Bruno Haible <bruno@clisp.org>. */
+
+#include "c-strcase.h"
+#include "c-ctype.h"
+
+/* STRCASEEQ allows to optimize string comparison with a small literal string.
+ STRCASEEQ (s, "UTF-8", 'U','T','F','-','8',0,0,0,0)
+ is semantically equivalent to
+ c_strcasecmp (s, "UTF-8") == 0
+ just faster. */
+
+/* Help GCC to generate good code for string comparisons with
+ immediate strings. */
+#if defined (__GNUC__) && defined (__OPTIMIZE__)
+
+/* Case insensitive comparison of ASCII characters. */
+# if C_CTYPE_ASCII
+# define CASEEQ(other,upper) \
+ (c_isupper (upper) ? ((other) & ~0x20) == (upper) : (other) == (upper))
+# else
+# define CASEEQ(other,upper) \
+ (c_toupper (other) == (upper))
+# endif
+
+static inline int
+strcaseeq9 (const char *s1, const char *s2)
+{
+ return c_strcasecmp (s1 + 9, s2 + 9) == 0;
+}
+
+static inline int
+strcaseeq8 (const char *s1, const char *s2, char s28)
+{
+ if (CASEEQ (s1[8], s28))
+ {
+ if (s28 == 0)
+ return 1;
+ else
+ return strcaseeq9 (s1, s2);
+ }
+ else
+ return 0;
+}
+
+static inline int
+strcaseeq7 (const char *s1, const char *s2, char s27, char s28)
+{
+ if (CASEEQ (s1[7], s27))
+ {
+ if (s27 == 0)
+ return 1;
+ else
+ return strcaseeq8 (s1, s2, s28);
+ }
+ else
+ return 0;
+}
+
+static inline int
+strcaseeq6 (const char *s1, const char *s2, char s26, char s27, char s28)
+{
+ if (CASEEQ (s1[6], s26))
+ {
+ if (s26 == 0)
+ return 1;
+ else
+ return strcaseeq7 (s1, s2, s27, s28);
+ }
+ else
+ return 0;
+}
+
+static inline int
+strcaseeq5 (const char *s1, const char *s2, char s25, char s26, char s27, char s28)
+{
+ if (CASEEQ (s1[5], s25))
+ {
+ if (s25 == 0)
+ return 1;
+ else
+ return strcaseeq6 (s1, s2, s26, s27, s28);
+ }
+ else
+ return 0;
+}
+
+static inline int
+strcaseeq4 (const char *s1, const char *s2, char s24, char s25, char s26, char s27, char s28)
+{
+ if (CASEEQ (s1[4], s24))
+ {
+ if (s24 == 0)
+ return 1;
+ else
+ return strcaseeq5 (s1, s2, s25, s26, s27, s28);
+ }
+ else
+ return 0;
+}
+
+static inline int
+strcaseeq3 (const char *s1, const char *s2, char s23, char s24, char s25, char s26, char s27, char s28)
+{
+ if (CASEEQ (s1[3], s23))
+ {
+ if (s23 == 0)
+ return 1;
+ else
+ return strcaseeq4 (s1, s2, s24, s25, s26, s27, s28);
+ }
+ else
+ return 0;
+}
+
+static inline int
+strcaseeq2 (const char *s1, const char *s2, char s22, char s23, char s24, char s25, char s26, char s27, char s28)
+{
+ if (CASEEQ (s1[2], s22))
+ {
+ if (s22 == 0)
+ return 1;
+ else
+ return strcaseeq3 (s1, s2, s23, s24, s25, s26, s27, s28);
+ }
+ else
+ return 0;
+}
+
+static inline int
+strcaseeq1 (const char *s1, const char *s2, char s21, char s22, char s23, char s24, char s25, char s26, char s27, char s28)
+{
+ if (CASEEQ (s1[1], s21))
+ {
+ if (s21 == 0)
+ return 1;
+ else
+ return strcaseeq2 (s1, s2, s22, s23, s24, s25, s26, s27, s28);
+ }
+ else
+ return 0;
+}
+
+static inline int
+strcaseeq0 (const char *s1, const char *s2, char s20, char s21, char s22, char s23, char s24, char s25, char s26, char s27, char s28)
+{
+ if (CASEEQ (s1[0], s20))
+ {
+ if (s20 == 0)
+ return 1;
+ else
+ return strcaseeq1 (s1, s2, s21, s22, s23, s24, s25, s26, s27, s28);
+ }
+ else
+ return 0;
+}
+
+#define STRCASEEQ(s1,s2,s20,s21,s22,s23,s24,s25,s26,s27,s28) \
+ strcaseeq0 (s1, s2, s20, s21, s22, s23, s24, s25, s26, s27, s28)
+
+#else
+
+#define STRCASEEQ(s1,s2,s20,s21,s22,s23,s24,s25,s26,s27,s28) \
+ (c_strcasecmp (s1, s2) == 0)
+
+#endif
diff --git a/lib/c-strncasecmp.c b/lib/c-strncasecmp.c
index 274e9b7..c316929 100644
--- a/lib/c-strncasecmp.c
+++ b/lib/c-strncasecmp.c
@@ -1,9 +1,9 @@
/* c-strncasecmp.c -- case insensitive string comparator in C locale
- Copyright (C) 1998-1999, 2005-2006 Free Software Foundation, Inc.
+ Copyright (C) 1998-1999, 2005-2006, 2009-2016 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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -12,8 +12,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program; if not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
@@ -40,7 +39,7 @@ c_strncasecmp (const char *s1, const char *s2, size_t n)
c2 = c_tolower (*p2);
if (--n == 0 || c1 == '\0')
- break;
+ break;
++p1;
++p2;
diff --git a/lib/c-strtod.c b/lib/c-strtod.c
index 2234ed0..8466d1d 100644
--- a/lib/c-strtod.c
+++ b/lib/c-strtod.c
@@ -1,11 +1,11 @@
/* Convert string to double, using the C locale.
- Copyright (C) 2003, 2004, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2003-2004, 2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
@@ -22,10 +21,10 @@
#include "c-strtod.h"
+#include <errno.h>
#include <locale.h>
#include <stdlib.h>
-
-#include "xalloc.h"
+#include <string.h>
#if LONG
# define C_STRTOD c_strtold
@@ -44,16 +43,41 @@
# define STRTOD strtod
#endif
+#if defined LC_ALL_MASK && (LONG ? HAVE_STRTOLD_L : HAVE_STRTOD_L)
+
+/* Cache for the C locale object.
+ Marked volatile so that different threads see the same value
+ (avoids locking). */
+static volatile locale_t c_locale_cache;
+
+/* Return the C locale object, or (locale_t) 0 with errno set
+ if it cannot be created. */
+static locale_t
+c_locale (void)
+{
+ if (!c_locale_cache)
+ c_locale_cache = newlocale (LC_ALL_MASK, "C", (locale_t) 0);
+ return c_locale_cache;
+}
+
+#endif
+
DOUBLE
C_STRTOD (char const *nptr, char **endptr)
{
DOUBLE r;
-#ifdef LC_ALL_MASK
+#if defined LC_ALL_MASK && (LONG ? HAVE_STRTOLD_L : HAVE_STRTOD_L)
+
+ locale_t locale = c_locale ();
+ if (!locale)
+ {
+ if (endptr)
+ *endptr = (char *) nptr;
+ return 0; /* errno is set here */
+ }
- locale_t c_locale = newlocale (LC_ALL_MASK, "C", 0);
- r = STRTOD_L (nptr, endptr, c_locale);
- freelocale (c_locale);
+ r = STRTOD_L (nptr, endptr, locale);
#else
@@ -61,7 +85,13 @@ C_STRTOD (char const *nptr, char **endptr)
if (saved_locale)
{
- saved_locale = xstrdup (saved_locale);
+ saved_locale = strdup (saved_locale);
+ if (saved_locale == NULL)
+ {
+ if (endptr)
+ *endptr = (char *) nptr;
+ return 0; /* errno is set here */
+ }
setlocale (LC_NUMERIC, "C");
}
@@ -69,8 +99,11 @@ C_STRTOD (char const *nptr, char **endptr)
if (saved_locale)
{
+ int saved_errno = errno;
+
setlocale (LC_NUMERIC, saved_locale);
free (saved_locale);
+ errno = saved_errno;
}
#endif
diff --git a/lib/c-strtod.h b/lib/c-strtod.h
index ca9a9e7..394a19a 100644
--- a/lib/c-strtod.h
+++ b/lib/c-strtod.h
@@ -1,2 +1,37 @@
-double c_strtod (char const *, char **);
-long double c_strtold (char const *, char **);
+/* Convert string to double, using the C locale. -*- coding: utf-8 -*-
+
+ Copyright (C) 2003-2004, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Parse the initial portion of the string pointed to by NPTR as a floating-
+ point number (in decimal or hexadecimal notation), like in the C locale:
+ accepting only the ASCII digits '0'..'9', and only '.' as decimal point
+ character.
+ If ENDPTR is not NULL, set *ENDPTR to point to the first byte beyond the
+ parsed number or to NPTR if the string does not start with a parsable
+ number.
+ Return value:
+ - If successful, return the value as a double or 'long double',
+ respectively, and don't modify errno.
+ - In case of overflow, return ±HUGE_VAL or ±HUGE_VALL, respectively, and
+ set errno to ERANGE.
+ - In case of underflow, return a value very near to 0 and set errno to
+ ERANGE.
+ - If the string does not start with a number at all, return 0 (and recall
+ that if ENDPTR != NULL, *ENDPTR is set to NPTR), and maybe set errno to
+ EINVAL.
+ - In case of other error, return 0 and set errno, for example to ENOMEM. */
+extern double c_strtod (char const *nptr, char **endptr);
+extern long double c_strtold (char const *nptr, char **endptr);
diff --git a/lib/calloc.c b/lib/calloc.c
index c8b1e1e..a04a269 100644
--- a/lib/calloc.c
+++ b/lib/calloc.c
@@ -1,11 +1,11 @@
/* calloc() function that is glibc compatible.
- This wrapper function is required at least on Tru64 UNIX 5.1.
- Copyright (C) 2004, 2005, 2006 Free Software Foundation, Inc.
+ This wrapper function is required at least on Tru64 UNIX 5.1 and mingw.
+ Copyright (C) 2004-2007, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,32 +13,61 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
-/* written by Jim Meyering */
+/* written by Jim Meyering and Bruno Haible */
#include <config.h>
-#undef calloc
+/* Only the AC_FUNC_CALLOC macro defines 'calloc' already in config.h. */
+#ifdef calloc
+# define NEED_CALLOC_GNU 1
+# undef calloc
+/* Whereas the gnulib module 'calloc-gnu' defines HAVE_CALLOC_GNU. */
+#elif GNULIB_CALLOC_GNU && !HAVE_CALLOC_GNU
+# define NEED_CALLOC_GNU 1
+#endif
+/* Specification. */
#include <stdlib.h>
+#include <errno.h>
+
+/* Call the system's calloc below. */
+#undef calloc
+
/* Allocate and zero-fill an NxS-byte block of memory from the heap.
If N or S is zero, allocate and zero-fill a 1-byte block. */
void *
rpl_calloc (size_t n, size_t s)
{
- size_t bytes;
+ void *result;
+#if NEED_CALLOC_GNU
if (n == 0 || s == 0)
- return calloc (1, 1);
+ {
+ n = 1;
+ s = 1;
+ }
+ else
+ {
+ /* Defend against buggy calloc implementations that mishandle
+ size_t overflow. */
+ size_t bytes = n * s;
+ if (bytes / s != n)
+ {
+ errno = ENOMEM;
+ return NULL;
+ }
+ }
+#endif
+
+ result = calloc (n, s);
- /* Defend against buggy calloc implementations that mishandle
- size_t overflow. */
- bytes = n * s;
- if (bytes / s != n)
- return NULL;
+#if !HAVE_CALLOC_POSIX
+ if (result == NULL)
+ errno = ENOMEM;
+#endif
- return calloc (n, s);
+ return result;
}
diff --git a/lib/canon-host.c b/lib/canon-host.c
index 50ba67a..101aec0 100644
--- a/lib/canon-host.c
+++ b/lib/canon-host.c
@@ -1,30 +1,28 @@
/* Host name canonicalization
- Copyright (C) 2005, 2006, 2007 Free Software Foundation, Inc.
+ Copyright (C) 2005-2016 Free Software Foundation, Inc.
Written by Derek Price <derek@ximbiot.com>.
- 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 2, or (at
- your option) any later version.
+ 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, 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.
+ 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
#include "canon-host.h"
#include <string.h>
-
-#include "getaddrinfo.h"
+#include <netdb.h>
/* Store the last error for the single-threaded version of this function. */
static int last_cherror;
@@ -71,11 +69,11 @@ canon_host_r (char const *host, int *cherror)
if (!status)
{
/* http://lists.gnu.org/archive/html/bug-coreutils/2006-09/msg00300.html
- says Darwin 7.9.0 getaddrinfo returns 0 but sets
- res->ai_canonname to NULL. */
+ says Darwin 7.9.0 getaddrinfo returns 0 but sets
+ res->ai_canonname to NULL. */
retval = strdup (res->ai_canonname ? res->ai_canonname : host);
if (!retval && cherror)
- *cherror = EAI_MEMORY;
+ *cherror = EAI_MEMORY;
freeaddrinfo (res);
}
else if (cherror)
diff --git a/lib/canon-host.h b/lib/canon-host.h
index c1f6cb1..e9bf8a2 100644
--- a/lib/canon-host.h
+++ b/lib/canon-host.h
@@ -1,22 +1,21 @@
/* Host name canonicalization
- Copyright (C) 2005 Free Software Foundation, Inc.
+ Copyright (C) 2005, 2009-2016 Free Software Foundation, Inc.
Written by Derek Price <derek@ximbiot.com>
- 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 2, or (at
- your option) any later version.
+ 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, 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.
+ 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifndef CANON_HOST_H
# define CANON_HOST_H 1
diff --git a/lib/canonicalize.c b/lib/canonicalize.c
index 48e4a23..900f1a3 100644
--- a/lib/canonicalize.c
+++ b/lib/canonicalize.c
@@ -1,10 +1,10 @@
/* Return the canonical absolute name of a given file.
- Copyright (C) 1996-2007 Free Software Foundation, Inc.
+ Copyright (C) 1996-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -12,121 +12,88 @@
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with this program; see the file COPYING.
- If not, write to the Free Software Foundation,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
#include "canonicalize.h"
+#include <errno.h>
#include <stdlib.h>
#include <string.h>
-
-#if HAVE_SYS_PARAM_H
-# include <sys/param.h>
-#endif
-
#include <sys/stat.h>
-
#include <unistd.h>
-#include <errno.h>
-#include <stddef.h>
-
-#include "cycle-check.h"
-#include "filenamecat.h"
+#include "areadlink.h"
+#include "file-set.h"
+#include "hash-triple.h"
+#include "pathmax.h"
#include "xalloc.h"
#include "xgetcwd.h"
+#include "dosname.h"
+
+#define MULTIPLE_BITS_SET(i) (((i) & ((i) - 1)) != 0)
-#ifndef ELOOP
-# define ELOOP 0
+/* In this file, we cannot handle file names longer than PATH_MAX.
+ On systems with no file name length limit, use a fallback. */
+#ifndef PATH_MAX
+# define PATH_MAX 8192
#endif
-#ifndef __set_errno
-# define __set_errno(Val) errno = (Val)
+
+#ifndef DOUBLE_SLASH_IS_DISTINCT_ROOT
+# define DOUBLE_SLASH_IS_DISTINCT_ROOT 0
#endif
-#include "pathmax.h"
-#include "xreadlink.h"
+#if ISSLASH ('\\')
+# define SLASHES "/\\"
+#else
+# define SLASHES "/"
+#endif
-#if !HAVE_CANONICALIZE_FILE_NAME
+#if !((HAVE_CANONICALIZE_FILE_NAME && FUNC_REALPATH_WORKS) \
+ || GNULIB_CANONICALIZE_LGPL)
/* Return the canonical absolute name of file NAME. A canonical name
- does not contain any `.', `..' components nor any repeated file name
+ does not contain any ".", ".." components nor any repeated file name
separators ('/') or symlinks. All components must exist.
The result is malloc'd. */
char *
canonicalize_file_name (const char *name)
{
-# if HAVE_RESOLVEPATH
-
- char *resolved, *extra_buf = NULL;
- size_t resolved_size;
- ssize_t resolved_len;
-
- if (name == NULL)
- {
- __set_errno (EINVAL);
- return NULL;
- }
-
- if (name[0] == '\0')
- {
- __set_errno (ENOENT);
- return NULL;
- }
-
- /* All known hosts with resolvepath (e.g. Solaris 7) don't turn
- relative names into absolute ones, so prepend the working
- directory if the file name is not absolute. */
- if (name[0] != '/')
- {
- char *wd;
-
- if (!(wd = xgetcwd ()))
- return NULL;
-
- extra_buf = file_name_concat (wd, name, NULL);
- name = extra_buf;
- free (wd);
- }
+ return canonicalize_filename_mode (name, CAN_EXISTING);
+}
+#endif /* !HAVE_CANONICALIZE_FILE_NAME */
- resolved_size = strlen (name);
- while (1)
+/* Return true if we've already seen the triple, <FILENAME, dev, ino>.
+ If *HT is not initialized, initialize it. */
+static bool
+seen_triple (Hash_table **ht, char const *filename, struct stat const *st)
+{
+ if (*ht == NULL)
{
- resolved_size = 2 * resolved_size + 1;
- resolved = xmalloc (resolved_size);
- resolved_len = resolvepath (name, resolved, resolved_size);
- if (resolved_len < 0)
- {
- free (resolved);
- free (extra_buf);
- return NULL;
- }
- if (resolved_len < resolved_size)
- break;
- free (resolved);
+ size_t initial_capacity = 7;
+ *ht = hash_initialize (initial_capacity,
+ NULL,
+ triple_hash,
+ triple_compare_ino_str,
+ triple_free);
+ if (*ht == NULL)
+ xalloc_die ();
}
- free (extra_buf);
-
- /* NUL-terminate the resulting name. */
- resolved[resolved_len] = '\0';
-
- return resolved;
-
-# else
+ if (seen_file (*ht, filename, st))
+ return true;
- return canonicalize_filename_mode (name, CAN_EXISTING);
-
-# endif /* !HAVE_RESOLVEPATH */
+ record_file (*ht, filename, st);
+ return false;
}
-#endif /* !HAVE_CANONICALIZE_FILE_NAME */
-/* Return the canonical absolute name of file NAME. A canonical name
- does not contain any `.', `..' components nor any repeated file name
- separators ('/') or symlinks. Whether components must exist
- or not depends on canonicalize mode. The result is malloc'd. */
+/* Return the canonical absolute name of file NAME, while treating
+ missing elements according to CAN_MODE. A canonical name
+ does not contain any ".", ".." components nor any repeated file name
+ separators ('/') or, depending on other CAN_MODE flags, symlinks.
+ Whether components must exist or not depends on canonicalize mode.
+ The result is malloc'd. */
char *
canonicalize_filename_mode (const char *name, canonicalize_mode_t can_mode)
@@ -136,172 +103,252 @@ canonicalize_filename_mode (const char *name, canonicalize_mode_t can_mode)
char const *end;
char const *rname_limit;
size_t extra_len = 0;
- struct cycle_check_state cycle_state;
+ Hash_table *ht = NULL;
+ int saved_errno;
+ int can_flags = can_mode & ~CAN_MODE_MASK;
+ bool logical = can_flags & CAN_NOLINKS;
+ size_t prefix_len;
+
+ can_mode &= CAN_MODE_MASK;
+
+ if (MULTIPLE_BITS_SET (can_mode))
+ {
+ errno = EINVAL;
+ return NULL;
+ }
if (name == NULL)
{
- __set_errno (EINVAL);
+ errno = EINVAL;
return NULL;
}
if (name[0] == '\0')
{
- __set_errno (ENOENT);
+ errno = ENOENT;
return NULL;
}
- if (name[0] != '/')
+ /* This is always zero for Posix hosts, but can be 2 for MS-Windows
+ and MS-DOS X:/foo/bar file names. */
+ prefix_len = FILE_SYSTEM_PREFIX_LEN (name);
+
+ if (!IS_ABSOLUTE_FILE_NAME (name))
{
rname = xgetcwd ();
if (!rname)
- return NULL;
+ return NULL;
dest = strchr (rname, '\0');
if (dest - rname < PATH_MAX)
- {
- char *p = xrealloc (rname, PATH_MAX);
- dest = p + (dest - rname);
- rname = p;
- rname_limit = rname + PATH_MAX;
- }
+ {
+ char *p = xrealloc (rname, PATH_MAX);
+ dest = p + (dest - rname);
+ rname = p;
+ rname_limit = rname + PATH_MAX;
+ }
else
- {
- rname_limit = dest;
- }
+ {
+ rname_limit = dest;
+ }
+ start = name;
+ prefix_len = FILE_SYSTEM_PREFIX_LEN (rname);
}
else
{
rname = xmalloc (PATH_MAX);
rname_limit = rname + PATH_MAX;
- rname[0] = '/';
- dest = rname + 1;
+ dest = rname;
+ if (prefix_len)
+ {
+ memcpy (rname, name, prefix_len);
+ dest += prefix_len;
+ }
+ *dest++ = '/';
+ if (DOUBLE_SLASH_IS_DISTINCT_ROOT)
+ {
+ if (ISSLASH (name[1]) && !ISSLASH (name[2]) && !prefix_len)
+ *dest++ = '/';
+ *dest = '\0';
+ }
+ start = name + prefix_len;
}
- cycle_check_init (&cycle_state);
- for (start = end = name; *start; start = end)
+ for ( ; *start; start = end)
{
/* Skip sequence of multiple file name separators. */
- while (*start == '/')
- ++start;
+ while (ISSLASH (*start))
+ ++start;
/* Find end of component. */
- for (end = start; *end && *end != '/'; ++end)
- /* Nothing. */;
+ for (end = start; *end && !ISSLASH (*end); ++end)
+ /* Nothing. */;
if (end - start == 0)
- break;
+ break;
else if (end - start == 1 && start[0] == '.')
- /* nothing */;
+ /* nothing */;
else if (end - start == 2 && start[0] == '.' && start[1] == '.')
- {
- /* Back up to previous component, ignore if at root already. */
- if (dest > rname + 1)
- while ((--dest)[-1] != '/');
- }
+ {
+ /* Back up to previous component, ignore if at root already. */
+ if (dest > rname + prefix_len + 1)
+ for (--dest; dest > rname && !ISSLASH (dest[-1]); --dest)
+ continue;
+ if (DOUBLE_SLASH_IS_DISTINCT_ROOT && dest == rname + 1
+ && !prefix_len && ISSLASH (*dest) && !ISSLASH (dest[1]))
+ dest++;
+ }
else
- {
- struct stat st;
-
- if (dest[-1] != '/')
- *dest++ = '/';
-
- if (dest + (end - start) >= rname_limit)
- {
- ptrdiff_t dest_offset = dest - rname;
- size_t new_size = rname_limit - rname;
-
- if (end - start + 1 > PATH_MAX)
- new_size += end - start + 1;
- else
- new_size += PATH_MAX;
- rname = xrealloc (rname, new_size);
- rname_limit = rname + new_size;
-
- dest = rname + dest_offset;
- }
-
- dest = memcpy (dest, start, end - start);
- dest += end - start;
- *dest = '\0';
-
- if (lstat (rname, &st) != 0)
- {
- if (can_mode == CAN_EXISTING)
- goto error;
- if (can_mode == CAN_ALL_BUT_LAST && *end)
- goto error;
- st.st_mode = 0;
- }
-
- if (S_ISLNK (st.st_mode))
- {
- char *buf;
- size_t n, len;
-
- if (cycle_check (&cycle_state, &st))
- {
- __set_errno (ELOOP);
- if (can_mode == CAN_MISSING)
- continue;
- else
- goto error;
- }
-
- buf = xreadlink_with_size (rname, st.st_size);
- if (!buf)
- {
- if (can_mode == CAN_MISSING)
- continue;
- else
- goto error;
- }
-
- n = strlen (buf);
- len = strlen (end);
-
- if (!extra_len)
- {
- extra_len =
- ((n + len + 1) > PATH_MAX) ? (n + len + 1) : PATH_MAX;
- extra_buf = xmalloc (extra_len);
- }
- else if ((n + len + 1) > extra_len)
- {
- extra_len = n + len + 1;
- extra_buf = xrealloc (extra_buf, extra_len);
- }
-
- /* Careful here, end may be a pointer into extra_buf... */
- memmove (&extra_buf[n], end, len + 1);
- name = end = memcpy (extra_buf, buf, n);
-
- if (buf[0] == '/')
- dest = rname + 1; /* It's an absolute symlink */
- else
- /* Back up to previous component, ignore if at root already: */
- if (dest > rname + 1)
- while ((--dest)[-1] != '/');
-
- free (buf);
- }
- else
- {
- if (!S_ISDIR (st.st_mode) && *end && (can_mode != CAN_MISSING))
- {
- errno = ENOTDIR;
- goto error;
- }
- }
- }
+ {
+ struct stat st;
+
+ if (!ISSLASH (dest[-1]))
+ *dest++ = '/';
+
+ if (dest + (end - start) >= rname_limit)
+ {
+ ptrdiff_t dest_offset = dest - rname;
+ size_t new_size = rname_limit - rname;
+
+ if (end - start + 1 > PATH_MAX)
+ new_size += end - start + 1;
+ else
+ new_size += PATH_MAX;
+ rname = xrealloc (rname, new_size);
+ rname_limit = rname + new_size;
+
+ dest = rname + dest_offset;
+ }
+
+ dest = memcpy (dest, start, end - start);
+ dest += end - start;
+ *dest = '\0';
+
+ if (logical && (can_mode == CAN_MISSING))
+ {
+ /* Avoid the stat in this case as it's inconsequential.
+ i.e. we're neither resolving symlinks or testing
+ component existence. */
+ st.st_mode = 0;
+ }
+ else if ((logical ? stat (rname, &st) : lstat (rname, &st)) != 0)
+ {
+ saved_errno = errno;
+ if (can_mode == CAN_EXISTING)
+ goto error;
+ if (can_mode == CAN_ALL_BUT_LAST)
+ {
+ if (end[strspn (end, SLASHES)] || saved_errno != ENOENT)
+ goto error;
+ continue;
+ }
+ st.st_mode = 0;
+ }
+
+ if (S_ISLNK (st.st_mode))
+ {
+ char *buf;
+ size_t n, len;
+
+ /* Detect loops. We cannot use the cycle-check module here,
+ since it's actually possible to encounter the same symlink
+ more than once in a given traversal. However, encountering
+ the same symlink,NAME pair twice does indicate a loop. */
+ if (seen_triple (&ht, name, &st))
+ {
+ if (can_mode == CAN_MISSING)
+ continue;
+ saved_errno = ELOOP;
+ goto error;
+ }
+
+ buf = areadlink_with_size (rname, st.st_size);
+ if (!buf)
+ {
+ if (can_mode == CAN_MISSING && errno != ENOMEM)
+ continue;
+ saved_errno = errno;
+ goto error;
+ }
+
+ n = strlen (buf);
+ len = strlen (end);
+
+ if (!extra_len)
+ {
+ extra_len =
+ ((n + len + 1) > PATH_MAX) ? (n + len + 1) : PATH_MAX;
+ extra_buf = xmalloc (extra_len);
+ }
+ else if ((n + len + 1) > extra_len)
+ {
+ extra_len = n + len + 1;
+ extra_buf = xrealloc (extra_buf, extra_len);
+ }
+
+ /* Careful here, end may be a pointer into extra_buf... */
+ memmove (&extra_buf[n], end, len + 1);
+ name = end = memcpy (extra_buf, buf, n);
+
+ if (IS_ABSOLUTE_FILE_NAME (buf))
+ {
+ size_t pfxlen = FILE_SYSTEM_PREFIX_LEN (buf);
+
+ if (pfxlen)
+ memcpy (rname, buf, pfxlen);
+ dest = rname + pfxlen;
+ *dest++ = '/'; /* It's an absolute symlink */
+ if (DOUBLE_SLASH_IS_DISTINCT_ROOT)
+ {
+ if (ISSLASH (buf[1]) && !ISSLASH (buf[2]) && !pfxlen)
+ *dest++ = '/';
+ *dest = '\0';
+ }
+ /* Install the new prefix to be in effect hereafter. */
+ prefix_len = pfxlen;
+ }
+ else
+ {
+ /* Back up to previous component, ignore if at root
+ already: */
+ if (dest > rname + prefix_len + 1)
+ for (--dest; dest > rname && !ISSLASH (dest[-1]); --dest)
+ continue;
+ if (DOUBLE_SLASH_IS_DISTINCT_ROOT && dest == rname + 1
+ && ISSLASH (*dest) && !ISSLASH (dest[1]) && !prefix_len)
+ dest++;
+ }
+
+ free (buf);
+ }
+ else
+ {
+ if (!S_ISDIR (st.st_mode) && *end && (can_mode != CAN_MISSING))
+ {
+ saved_errno = ENOTDIR;
+ goto error;
+ }
+ }
+ }
}
- if (dest > rname + 1 && dest[-1] == '/')
+ if (dest > rname + prefix_len + 1 && ISSLASH (dest[-1]))
--dest;
+ if (DOUBLE_SLASH_IS_DISTINCT_ROOT && dest == rname + 1 && !prefix_len
+ && ISSLASH (*dest) && !ISSLASH (dest[1]))
+ dest++;
*dest = '\0';
+ if (rname_limit != dest + 1)
+ rname = xrealloc (rname, dest - rname + 1);
free (extra_buf);
+ if (ht)
+ hash_free (ht);
return rname;
error:
free (extra_buf);
free (rname);
+ if (ht)
+ hash_free (ht);
+ errno = saved_errno;
return NULL;
}
diff --git a/lib/canonicalize.h b/lib/canonicalize.h
index 5c4d3f1..ccbb93f 100644
--- a/lib/canonicalize.h
+++ b/lib/canonicalize.h
@@ -1,10 +1,10 @@
/* Return the canonical absolute name of a given file.
- Copyright (C) 1996-2007 Free Software Foundation, Inc.
+ Copyright (C) 1996-2007, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -12,14 +12,15 @@
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with this program; see the file COPYING.
- If not, write to the Free Software Foundation,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifndef CANONICALIZE_H_
# define CANONICALIZE_H_
-# if GNULIB_CANONICALIZE
+#include <stdlib.h> /* for canonicalize_file_name */
+
+#define CAN_MODE_MASK (CAN_EXISTING | CAN_ALL_BUT_LAST | CAN_MISSING)
+
enum canonicalize_mode_t
{
/* All components must exist. */
@@ -29,26 +30,19 @@ enum canonicalize_mode_t
CAN_ALL_BUT_LAST = 1,
/* No requirements on components existence. */
- CAN_MISSING = 2
+ CAN_MISSING = 2,
+
+ /* Don't expand symlinks. */
+ CAN_NOLINKS = 4
};
typedef enum canonicalize_mode_t canonicalize_mode_t;
-/* Return a malloc'd string containing the canonical absolute name of
- the named file. This acts like canonicalize_file_name, except that
- whether components must exist depends on the canonicalize_mode_t
- argument. */
+/* Return the canonical absolute name of file NAME, while treating
+ missing elements according to CAN_MODE. A canonical name
+ does not contain any `.', `..' components nor any repeated file name
+ separators ('/') or, depending on other CAN_MODE flags, symlinks.
+ Whether components must exist or not depends on canonicalize mode.
+ The result is malloc'd. */
char *canonicalize_filename_mode (const char *, canonicalize_mode_t);
-# endif
-
-# if HAVE_DECL_CANONICALIZE_FILE_NAME
-# include <stdlib.h>
-# else
-/* Return a malloc'd string containing the canonical absolute name of
- the named file. If any file name component does not exist or is a
- symlink to a nonexistent file, return NULL. A canonical name does
- not contain any `.', `..' components nor any repeated file name
- separators ('/') or symlinks. */
-char *canonicalize_file_name (const char *);
-# endif
#endif /* !CANONICALIZE_H_ */
diff --git a/lib/careadlinkat.c b/lib/careadlinkat.c
new file mode 100644
index 0000000..4180de9
--- /dev/null
+++ b/lib/careadlinkat.c
@@ -0,0 +1,160 @@
+/* Read symbolic links into a buffer without size limitation, relative to fd.
+
+ Copyright (C) 2001, 2003-2004, 2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Paul Eggert, Bruno Haible, and Jim Meyering. */
+
+#include <config.h>
+
+#include "careadlinkat.h"
+
+#include <errno.h>
+#include <limits.h>
+#include <string.h>
+#include <unistd.h>
+
+/* Define this independently so that stdint.h is not a prerequisite. */
+#ifndef SIZE_MAX
+# define SIZE_MAX ((size_t) -1)
+#endif
+
+#ifndef SSIZE_MAX
+# define SSIZE_MAX ((ssize_t) (SIZE_MAX / 2))
+#endif
+
+#include "allocator.h"
+
+/* Assuming the current directory is FD, get the symbolic link value
+ of FILENAME as a null-terminated string and put it into a buffer.
+ If FD is AT_FDCWD, FILENAME is interpreted relative to the current
+ working directory, as in openat.
+
+ If the link is small enough to fit into BUFFER put it there.
+ BUFFER's size is BUFFER_SIZE, and BUFFER can be null
+ if BUFFER_SIZE is zero.
+
+ If the link is not small, put it into a dynamically allocated
+ buffer managed by ALLOC. It is the caller's responsibility to free
+ the returned value if it is nonnull and is not BUFFER. A null
+ ALLOC stands for the standard allocator.
+
+ The PREADLINKAT function specifies how to read links. It operates
+ like POSIX readlinkat()
+ <http://pubs.opengroup.org/onlinepubs/9699919799/functions/readlink.html>
+ but can assume that its first argument is the same as FD.
+
+ If successful, return the buffer address; otherwise return NULL and
+ set errno. */
+
+char *
+careadlinkat (int fd, char const *filename,
+ char *buffer, size_t buffer_size,
+ struct allocator const *alloc,
+ ssize_t (*preadlinkat) (int, char const *, char *, size_t))
+{
+ char *buf;
+ size_t buf_size;
+ size_t buf_size_max =
+ SSIZE_MAX < SIZE_MAX ? (size_t) SSIZE_MAX + 1 : SIZE_MAX;
+ char stack_buf[1024];
+
+ if (! alloc)
+ alloc = &stdlib_allocator;
+
+ if (! buffer_size)
+ {
+ /* Allocate the initial buffer on the stack. This way, in the
+ common case of a symlink of small size, we get away with a
+ single small malloc() instead of a big malloc() followed by a
+ shrinking realloc(). */
+ buffer = stack_buf;
+ buffer_size = sizeof stack_buf;
+ }
+
+ buf = buffer;
+ buf_size = buffer_size;
+
+ do
+ {
+ /* Attempt to read the link into the current buffer. */
+ ssize_t link_length = preadlinkat (fd, filename, buf, buf_size);
+ size_t link_size;
+ if (link_length < 0)
+ {
+ /* On AIX 5L v5.3 and HP-UX 11i v2 04/09, readlink returns -1
+ with errno == ERANGE if the buffer is too small. */
+ int readlinkat_errno = errno;
+ if (readlinkat_errno != ERANGE)
+ {
+ if (buf != buffer)
+ {
+ alloc->free (buf);
+ errno = readlinkat_errno;
+ }
+ return NULL;
+ }
+ }
+
+ link_size = link_length;
+
+ if (link_size < buf_size)
+ {
+ buf[link_size++] = '\0';
+
+ if (buf == stack_buf)
+ {
+ char *b = (char *) alloc->allocate (link_size);
+ buf_size = link_size;
+ if (! b)
+ break;
+ memcpy (b, buf, link_size);
+ buf = b;
+ }
+ else if (link_size < buf_size && buf != buffer && alloc->reallocate)
+ {
+ /* Shrink BUF before returning it. */
+ char *b = (char *) alloc->reallocate (buf, link_size);
+ if (b)
+ buf = b;
+ }
+
+ return buf;
+ }
+
+ if (buf != buffer)
+ alloc->free (buf);
+
+ if (buf_size <= buf_size_max / 2)
+ buf_size *= 2;
+ else if (buf_size < buf_size_max)
+ buf_size = buf_size_max;
+ else if (buf_size_max < SIZE_MAX)
+ {
+ errno = ENAMETOOLONG;
+ return NULL;
+ }
+ else
+ break;
+ buf = (char *) alloc->allocate (buf_size);
+ }
+ while (buf);
+
+ if (alloc->die)
+ alloc->die (buf_size);
+ errno = ENOMEM;
+ return NULL;
+}
diff --git a/lib/careadlinkat.h b/lib/careadlinkat.h
new file mode 100644
index 0000000..84ede3e
--- /dev/null
+++ b/lib/careadlinkat.h
@@ -0,0 +1,67 @@
+/* Read symbolic links into a buffer without size limitation, relative to fd.
+
+ Copyright (C) 2011-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Paul Eggert, Bruno Haible, and Jim Meyering. */
+
+#ifndef _GL_CAREADLINKAT_H
+#define _GL_CAREADLINKAT_H
+
+#include <fcntl.h>
+#include <unistd.h>
+
+struct allocator;
+
+/* Assuming the current directory is FD, get the symbolic link value
+ of FILENAME as a null-terminated string and put it into a buffer.
+ If FD is AT_FDCWD, FILENAME is interpreted relative to the current
+ working directory, as in openat.
+
+ If the link is small enough to fit into BUFFER put it there.
+ BUFFER's size is BUFFER_SIZE, and BUFFER can be null
+ if BUFFER_SIZE is zero.
+
+ If the link is not small, put it into a dynamically allocated
+ buffer managed by ALLOC. It is the caller's responsibility to free
+ the returned value if it is nonnull and is not BUFFER.
+
+ The PREADLINKAT function specifies how to read links. It operates
+ like POSIX readlinkat()
+ <http://pubs.opengroup.org/onlinepubs/9699919799/functions/readlink.html>
+ but can assume that its first argument is the same as FD.
+
+ If successful, return the buffer address; otherwise return NULL and
+ set errno. */
+
+char *careadlinkat (int fd, char const *filename,
+ char *buffer, size_t buffer_size,
+ struct allocator const *alloc,
+ ssize_t (*preadlinkat) (int, char const *,
+ char *, size_t));
+
+/* Suitable value for careadlinkat's FD argument. */
+#if HAVE_READLINKAT
+/* AT_FDCWD is declared in <fcntl.h>. */
+#else
+/* Define AT_FDCWD independently, so that the careadlinkat module does
+ not depend on the fcntl-h module. We might as well use the same value
+ as fcntl-h. */
+# ifndef AT_FDCWD
+# define AT_FDCWD (-3041965)
+# endif
+#endif
+
+#endif /* _GL_CAREADLINKAT_H */
diff --git a/lib/chdir-long.c b/lib/chdir-long.c
index 3fc7ef2..546b4b0 100644
--- a/lib/chdir-long.c
+++ b/lib/chdir-long.c
@@ -1,10 +1,10 @@
/* provide a chdir function that tries not to fail due to ENAMETOOLONG
- Copyright (C) 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
+ Copyright (C) 2004-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -12,8 +12,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* written by Jim Meyering */
@@ -21,44 +20,48 @@
#include "chdir-long.h"
+#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
-#include <errno.h>
#include <stdio.h>
-#include <assert.h>
-#include "openat.h"
+#include "assure.h"
#ifndef PATH_MAX
# error "compile this file only if your system defines PATH_MAX"
#endif
+/* The results of openat() in this file are not leaked to any
+ single-threaded code that could use stdio.
+ FIXME - if the kernel ever adds support for multi-thread safety for
+ avoiding standard fds, then we should use openat_safer. */
+
struct cd_buf
{
int fd;
};
-static inline void
+static void
cdb_init (struct cd_buf *cdb)
{
cdb->fd = AT_FDCWD;
}
-static inline int
+static int
cdb_fchdir (struct cd_buf const *cdb)
{
return fchdir (cdb->fd);
}
-static inline void
+static void
cdb_free (struct cd_buf const *cdb)
{
if (0 <= cdb->fd)
{
bool close_fail = close (cdb->fd);
- assert (! close_fail);
+ assure (! close_fail);
}
}
@@ -70,7 +73,7 @@ static int
cdb_advance_fd (struct cd_buf *cdb, char const *dir)
{
int new_fd = openat (cdb->fd, dir,
- O_RDONLY | O_DIRECTORY | O_NOCTTY | O_NONBLOCK);
+ O_SEARCH | O_DIRECTORY | O_NOCTTY | O_NONBLOCK);
if (new_fd < 0)
return -1;
@@ -81,7 +84,7 @@ cdb_advance_fd (struct cd_buf *cdb, char const *dir)
}
/* Return a pointer to the first non-slash in S. */
-static inline char *
+static char * _GL_ATTRIBUTE_PURE
find_non_slash (char const *s)
{
size_t n_slash = strspn (s, "/");
@@ -94,7 +97,7 @@ find_non_slash (char const *s)
name. It handles an arbitrarily long directory name by operating
on manageable portions of the name. On systems without the openat
syscall, this means changing the working directory to more and more
- `distant' points along the long directory name and then restoring
+ "distant" points along the long directory name and then restoring
the working directory. If any of those attempts to save or restore
the working directory fails, this function exits nonzero.
@@ -120,8 +123,8 @@ chdir_long (char *dir)
/* If DIR is the empty string, then the chdir above
must have failed and set errno to ENOENT. */
- assert (0 < len);
- assert (PATH_MAX <= len);
+ assure (0 < len);
+ assure (PATH_MAX <= len);
/* Count leading slashes. */
n_leading_slash = strspn (dir, "/");
@@ -133,59 +136,59 @@ chdir_long (char *dir)
code in the following loop cleaner. */
if (n_leading_slash == 2)
{
- int err;
- /* Find next slash.
- We already know that dir[2] is neither a slash nor '\0'. */
- char *slash = memchr (dir + 3, '/', dir_end - (dir + 3));
- if (slash == NULL)
- {
- errno = ENAMETOOLONG;
- return -1;
- }
- *slash = '\0';
- err = cdb_advance_fd (&cdb, dir);
- *slash = '/';
- if (err != 0)
- goto Fail;
- dir = find_non_slash (slash + 1);
+ int err;
+ /* Find next slash.
+ We already know that dir[2] is neither a slash nor '\0'. */
+ char *slash = memchr (dir + 3, '/', dir_end - (dir + 3));
+ if (slash == NULL)
+ {
+ errno = ENAMETOOLONG;
+ return -1;
+ }
+ *slash = '\0';
+ err = cdb_advance_fd (&cdb, dir);
+ *slash = '/';
+ if (err != 0)
+ goto Fail;
+ dir = find_non_slash (slash + 1);
}
else if (n_leading_slash)
{
- if (cdb_advance_fd (&cdb, "/") != 0)
- goto Fail;
- dir += n_leading_slash;
+ if (cdb_advance_fd (&cdb, "/") != 0)
+ goto Fail;
+ dir += n_leading_slash;
}
- assert (*dir != '/');
- assert (dir <= dir_end);
+ assure (*dir != '/');
+ assure (dir <= dir_end);
while (PATH_MAX <= dir_end - dir)
{
- int err;
- /* Find a slash that is PATH_MAX or fewer bytes away from dir.
- I.e. see if there is a slash that will give us a name of
- length PATH_MAX-1 or less. */
- char *slash = memrchr (dir, '/', PATH_MAX);
- if (slash == NULL)
- {
- errno = ENAMETOOLONG;
- return -1;
- }
-
- *slash = '\0';
- assert (slash - dir < PATH_MAX);
- err = cdb_advance_fd (&cdb, dir);
- *slash = '/';
- if (err != 0)
- goto Fail;
-
- dir = find_non_slash (slash + 1);
+ int err;
+ /* Find a slash that is PATH_MAX or fewer bytes away from dir.
+ I.e. see if there is a slash that will give us a name of
+ length PATH_MAX-1 or less. */
+ char *slash = memrchr (dir, '/', PATH_MAX);
+ if (slash == NULL)
+ {
+ errno = ENAMETOOLONG;
+ return -1;
+ }
+
+ *slash = '\0';
+ assure (slash - dir < PATH_MAX);
+ err = cdb_advance_fd (&cdb, dir);
+ *slash = '/';
+ if (err != 0)
+ goto Fail;
+
+ dir = find_non_slash (slash + 1);
}
if (dir < dir_end)
{
- if (cdb_advance_fd (&cdb, dir) != 0)
- goto Fail;
+ if (cdb_advance_fd (&cdb, dir) != 0)
+ goto Fail;
}
if (cdb_fchdir (&cdb) != 0)
@@ -206,7 +209,6 @@ chdir_long (char *dir)
#if TEST_CHDIR
-# include <stdio.h>
# include "closeout.h"
# include "error.h"
@@ -227,10 +229,10 @@ main (int argc, char *argv[])
{
int saved_errno = errno;
if (feof (stdin))
- exit (0);
+ exit (0);
error (EXIT_FAILURE, saved_errno,
- "reading standard input");
+ "reading standard input");
}
else if (len == 0)
exit (0);
@@ -240,12 +242,12 @@ main (int argc, char *argv[])
if (chdir_long (line) != 0)
error (EXIT_FAILURE, errno,
- "chdir_long failed: %s", line);
+ "chdir_long failed: %s", line);
if (argc <= 1)
{
- /* Using `pwd' here makes sense only if it is a robust implementation,
- like the one in coreutils after the 2004-04-19 changes. */
+ /* Using 'pwd' here makes sense only if it is a robust implementation,
+ like the one in coreutils after the 2004-04-19 changes. */
char const *cmd = "pwd";
execlp (cmd, (char *) NULL);
error (EXIT_FAILURE, errno, "%s", cmd);
diff --git a/lib/chdir-long.h b/lib/chdir-long.h
index 4852b40..614b6cf 100644
--- a/lib/chdir-long.h
+++ b/lib/chdir-long.h
@@ -1,10 +1,10 @@
/* provide a chdir function that tries not to fail due to ENAMETOOLONG
- Copyright (C) 2004, 2005 Free Software Foundation, Inc.
+ Copyright (C) 2004-2005, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -12,19 +12,14 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Jim Meyering. */
#include <unistd.h>
#include <limits.h>
-#ifndef PATH_MAX
-# ifdef MAXPATHLEN
-# define PATH_MAX MAXPATHLEN
-# endif
-#endif
+#include "pathmax.h"
/* On systems without PATH_MAX, presume that chdir accepts
arbitrarily long directory names. */
diff --git a/lib/chmodat.c b/lib/chmodat.c
new file mode 100644
index 0000000..3c69689
--- /dev/null
+++ b/lib/chmodat.c
@@ -0,0 +1,3 @@
+#include <config.h>
+#define FCHMODAT_INLINE _GL_EXTERN_INLINE
+#include "openat.h"
diff --git a/lib/chown.c b/lib/chown.c
index b7786f6..ba6be74 100644
--- a/lib/chown.c
+++ b/lib/chown.c
@@ -1,12 +1,12 @@
/* provide consistent interface to chown for systems that don't interpret
- an ID of -1 as meaning `don't change the corresponding ID'.
+ an ID of -1 as meaning "don't change the corresponding ID".
- Copyright (C) 1997, 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
+ Copyright (C) 1997, 2004-2007, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* written by Jim Meyering */
@@ -24,47 +23,64 @@
/* Specification. */
#include <unistd.h>
+#include <errno.h>
+#include <fcntl.h>
#include <stdbool.h>
-#include <sys/types.h>
+#include <string.h>
#include <sys/stat.h>
-#include <fcntl.h>
-#include <errno.h>
-/* Below we refer to the system's chown(). */
-#undef chown
+#if !HAVE_CHOWN
-/* The results of open() in this file are not used with fchdir,
- therefore save some unnecessary work in fchdir.c. */
-#undef open
-#undef close
+/* Simple stub that always fails with ENOSYS, for mingw. */
+int
+chown (const char *file _GL_UNUSED, uid_t uid _GL_UNUSED,
+ gid_t gid _GL_UNUSED)
+{
+ errno = ENOSYS;
+ return -1;
+}
+
+#else /* HAVE_CHOWN */
+
+/* Below we refer to the system's chown(). */
+# undef chown
/* Provide a more-closely POSIX-conforming version of chown on
systems with one or both of the following problems:
- chown doesn't treat an ID of -1 as meaning
- `don't change the corresponding ID'.
+ "don't change the corresponding ID".
- chown doesn't dereference symlinks. */
int
rpl_chown (const char *file, uid_t uid, gid_t gid)
{
-#if CHOWN_FAILS_TO_HONOR_ID_OF_NEGATIVE_ONE
- if (gid == (gid_t) -1 || uid == (uid_t) -1)
+ struct stat st;
+ bool stat_valid = false;
+ int result;
+
+# if CHOWN_CHANGE_TIME_BUG
+ if (gid != (gid_t) -1 || uid != (uid_t) -1)
{
- struct stat file_stats;
+ if (stat (file, &st))
+ return -1;
+ stat_valid = true;
+ }
+# endif
+# if CHOWN_FAILS_TO_HONOR_ID_OF_NEGATIVE_ONE
+ if (gid == (gid_t) -1 || uid == (uid_t) -1)
+ {
/* Stat file to get id(s) that should remain unchanged. */
- if (stat (file, &file_stats))
- return -1;
-
+ if (!stat_valid && stat (file, &st))
+ return -1;
if (gid == (gid_t) -1)
- gid = file_stats.st_gid;
-
+ gid = st.st_gid;
if (uid == (uid_t) -1)
- uid = file_stats.st_uid;
+ uid = st.st_uid;
}
-#endif
+# endif
-#if CHOWN_MODIFIES_SYMLINK
+# if CHOWN_MODIFIES_SYMLINK
{
/* Handle the case in which the system-supplied chown function
does *not* follow symlinks. Instead, it changes permissions
@@ -74,31 +90,62 @@ rpl_chown (const char *file, uid_t uid, gid_t gid)
int open_flags = O_NONBLOCK | O_NOCTTY;
int fd = open (file, O_RDONLY | open_flags);
if (0 <= fd
- || (errno == EACCES
- && 0 <= (fd = open (file, O_WRONLY | open_flags))))
+ || (errno == EACCES
+ && 0 <= (fd = open (file, O_WRONLY | open_flags))))
{
- int result = fchown (fd, uid, gid);
- int saved_errno = errno;
-
- /* POSIX says fchown can fail with errno == EINVAL on sockets,
- so fall back on chown in that case. */
- struct stat sb;
- bool fchown_socket_failure =
- (result != 0 && saved_errno == EINVAL
- && fstat (fd, &sb) == 0 && S_ISFIFO (sb.st_mode));
-
- close (fd);
-
- if (! fchown_socket_failure)
- {
- errno = saved_errno;
- return result;
- }
+ int saved_errno;
+ bool fchown_socket_failure;
+
+ result = fchown (fd, uid, gid);
+ saved_errno = errno;
+
+ /* POSIX says fchown can fail with errno == EINVAL on sockets
+ and pipes, so fall back on chown in that case. */
+ fchown_socket_failure =
+ (result != 0 && saved_errno == EINVAL
+ && fstat (fd, &st) == 0
+ && (S_ISFIFO (st.st_mode) || S_ISSOCK (st.st_mode)));
+
+ close (fd);
+
+ if (! fchown_socket_failure)
+ {
+ errno = saved_errno;
+ return result;
+ }
}
else if (errno != EACCES)
return -1;
}
-#endif
+# endif
- return chown (file, uid, gid);
+# if CHOWN_TRAILING_SLASH_BUG
+ if (!stat_valid)
+ {
+ size_t len = strlen (file);
+ if (len && file[len - 1] == '/' && stat (file, &st))
+ return -1;
+ }
+# endif
+
+ result = chown (file, uid, gid);
+
+# if CHOWN_CHANGE_TIME_BUG
+ if (result == 0 && stat_valid
+ && (uid == st.st_uid || uid == (uid_t) -1)
+ && (gid == st.st_gid || gid == (gid_t) -1))
+ {
+ /* No change in ownership, but at least one argument was not -1,
+ so we are required to update ctime. Since chown succeeded,
+ we assume that chmod will do likewise. Fortunately, on all
+ known systems where a 'no-op' chown skips the ctime update, a
+ 'no-op' chmod still does the trick. */
+ result = chmod (file, st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO
+ | S_ISUID | S_ISGID | S_ISVTX));
+ }
+# endif
+
+ return result;
}
+
+#endif /* HAVE_CHOWN */
diff --git a/lib/chownat.c b/lib/chownat.c
new file mode 100644
index 0000000..3937f9c
--- /dev/null
+++ b/lib/chownat.c
@@ -0,0 +1,3 @@
+#include <config.h>
+#define FCHOWNAT_INLINE _GL_EXTERN_INLINE
+#include "openat.h"
diff --git a/lib/cloexec.c b/lib/cloexec.c
index 6480006..1202836 100644
--- a/lib/cloexec.c
+++ b/lib/cloexec.c
@@ -1,11 +1,11 @@
/* closexec.c - set or clear the close-on-exec descriptor flag
- Copyright (C) 1991, 2004, 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 1991, 2004-2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
The code is taken from glibc/manual/llio.texi */
@@ -22,21 +21,24 @@
#include "cloexec.h"
-#include <unistd.h>
+#include <errno.h>
#include <fcntl.h>
+#include <unistd.h>
-#ifndef FD_CLOEXEC
-# define FD_CLOEXEC 1
-#endif
-
-/* Set the `FD_CLOEXEC' flag of DESC if VALUE is true,
+/* Set the 'FD_CLOEXEC' flag of DESC if VALUE is true,
or clear the flag if VALUE is false.
- Return 0 on success, or -1 on error with `errno' set. */
+ Return 0 on success, or -1 on error with 'errno' set.
+
+ Note that on MingW, this function does NOT protect DESC from being
+ inherited into spawned children. Instead, either use dup_cloexec
+ followed by closing the original DESC, or use interfaces such as
+ open or pipe2 that accept flags like O_CLOEXEC to create DESC
+ non-inheritable in the first place. */
int
set_cloexec_flag (int desc, bool value)
{
-#if defined F_GETFD && defined F_SETFD
+#ifdef F_SETFD
int flags = fcntl (desc, F_GETFD, 0);
@@ -45,15 +47,37 @@ set_cloexec_flag (int desc, bool value)
int newflags = (value ? flags | FD_CLOEXEC : flags & ~FD_CLOEXEC);
if (flags == newflags
- || fcntl (desc, F_SETFD, newflags) != -1)
- return 0;
+ || fcntl (desc, F_SETFD, newflags) != -1)
+ return 0;
}
return -1;
-#else
+#else /* !F_SETFD */
+
+ /* Use dup2 to reject invalid file descriptors; the cloexec flag
+ will be unaffected. */
+ if (desc < 0)
+ {
+ errno = EBADF;
+ return -1;
+ }
+ if (dup2 (desc, desc) < 0)
+ /* errno is EBADF here. */
+ return -1;
+ /* There is nothing we can do on this kind of platform. Punt. */
return 0;
+#endif /* !F_SETFD */
+}
+
-#endif
+/* Duplicates a file handle FD, while marking the copy to be closed
+ prior to exec or spawn. Returns -1 and sets errno if FD could not
+ be duplicated. */
+
+int
+dup_cloexec (int fd)
+{
+ return fcntl (fd, F_DUPFD_CLOEXEC, 0);
}
diff --git a/lib/cloexec.h b/lib/cloexec.h
index c25921d..0e58437 100644
--- a/lib/cloexec.h
+++ b/lib/cloexec.h
@@ -1,2 +1,38 @@
+/* closexec.c - set or clear the close-on-exec descriptor flag
+
+ Copyright (C) 2004, 2009-2016 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 <http://www.gnu.org/licenses/>.
+
+*/
+
#include <stdbool.h>
+
+/* Set the 'FD_CLOEXEC' flag of DESC if VALUE is true,
+ or clear the flag if VALUE is false.
+ Return 0 on success, or -1 on error with 'errno' set.
+
+ Note that on MingW, this function does NOT protect DESC from being
+ inherited into spawned children. Instead, either use dup_cloexec
+ followed by closing the original DESC, or use interfaces such as
+ open or pipe2 that accept flags like O_CLOEXEC to create DESC
+ non-inheritable in the first place. */
+
int set_cloexec_flag (int desc, bool value);
+
+/* Duplicates a file handle FD, while marking the copy to be closed
+ prior to exec or spawn. Returns -1 and sets errno if FD could not
+ be duplicated. */
+
+int dup_cloexec (int fd);
diff --git a/lib/close-stream.c b/lib/close-stream.c
index 72d0d68..0c4beae 100644
--- a/lib/close-stream.c
+++ b/lib/close-stream.c
@@ -1,12 +1,11 @@
/* Close a stream, with nicer error checking than fclose's.
- Copyright (C) 1998, 1999, 2000, 2001, 2002, 2004, 2006 Free
- Software Foundation, Inc.
+ Copyright (C) 1998-2002, 2004, 2006-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
@@ -24,7 +22,7 @@
#include <errno.h>
#include <stdbool.h>
-#include "__fpending.h"
+#include "fpending.h"
#if USE_UNLOCKED_IO
# include "unlocked-io.h"
@@ -34,6 +32,10 @@
otherwise. A failure might set errno to 0 if the error number
cannot be determined.
+ A failure with errno set to EPIPE may or may not indicate an error
+ situation worth signaling to the user. See the documentation of the
+ close_stdout_set_ignore_EPIPE function for details.
+
If a program writes *anything* to STREAM, that program should close
STREAM and make sure that it succeeds before exiting. Otherwise,
suppose that you go to the extreme of checking the return status
@@ -53,22 +55,22 @@
int
close_stream (FILE *stream)
{
- bool some_pending = (__fpending (stream) != 0);
- bool prev_fail = (ferror (stream) != 0);
- bool fclose_fail = (fclose (stream) != 0);
+ const bool some_pending = (__fpending (stream) != 0);
+ const bool prev_fail = (ferror (stream) != 0);
+ const bool fclose_fail = (fclose (stream) != 0);
/* Return an error indication if there was a previous failure or if
fclose failed, with one exception: ignore an fclose failure if
there was no previous error, no data remains to be flushed, and
fclose failed with EBADF. That can happen when a program like cp
- is invoked like this `cp a b >&-' (i.e., with standard output
+ is invoked like this 'cp a b >&-' (i.e., with standard output
closed) and doesn't generate any output (hence no previous error
and nothing to be flushed). */
if (prev_fail || (fclose_fail && (some_pending || errno != EBADF)))
{
if (! fclose_fail)
- errno = 0;
+ errno = 0;
return EOF;
}
diff --git a/lib/close.c b/lib/close.c
new file mode 100644
index 0000000..46a7aa5
--- /dev/null
+++ b/lib/close.c
@@ -0,0 +1,69 @@
+/* close replacement.
+ Copyright (C) 2008-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <unistd.h>
+
+#include <errno.h>
+
+#include "fd-hook.h"
+#include "msvc-inval.h"
+
+#undef close
+
+#if HAVE_MSVC_INVALID_PARAMETER_HANDLER
+static int
+close_nothrow (int fd)
+{
+ int result;
+
+ TRY_MSVC_INVAL
+ {
+ result = close (fd);
+ }
+ CATCH_MSVC_INVAL
+ {
+ result = -1;
+ errno = EBADF;
+ }
+ DONE_MSVC_INVAL;
+
+ return result;
+}
+#else
+# define close_nothrow close
+#endif
+
+/* Override close() to call into other gnulib modules. */
+
+int
+rpl_close (int fd)
+{
+#if WINDOWS_SOCKETS
+ int retval = execute_all_close_hooks (close_nothrow, fd);
+#else
+ int retval = close_nothrow (fd);
+#endif
+
+#if REPLACE_FCHDIR
+ if (retval >= 0)
+ _gl_unregister_fd (fd);
+#endif
+
+ return retval;
+}
diff --git a/lib/closedir.c b/lib/closedir.c
new file mode 100644
index 0000000..30d1290
--- /dev/null
+++ b/lib/closedir.c
@@ -0,0 +1,71 @@
+/* Stop reading the entries of a directory.
+ Copyright (C) 2006-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <dirent.h>
+
+#if REPLACE_FCHDIR
+# include <unistd.h>
+#endif
+
+#if HAVE_CLOSEDIR
+
+/* Override closedir(), to keep track of the open file descriptors.
+ Needed because there is a function dirfd(). */
+
+#else
+
+# include <stdlib.h>
+
+# include "dirent-private.h"
+
+#endif
+
+int
+closedir (DIR *dirp)
+{
+# if REPLACE_FCHDIR || REPLACE_DIRFD
+ int fd = dirfd (dirp);
+# endif
+ int retval;
+
+#if HAVE_CLOSEDIR
+# undef closedir
+
+ retval = closedir (dirp);
+
+# ifdef __KLIBC__
+ if (!retval)
+ _gl_unregister_dirp_fd (fd);
+# endif
+#else
+
+ if (dirp->current != INVALID_HANDLE_VALUE)
+ FindClose (dirp->current);
+ free (dirp);
+
+ retval = 0;
+
+#endif
+
+#if REPLACE_FCHDIR
+ if (retval >= 0)
+ _gl_unregister_fd (fd);
+#endif
+ return retval;
+}
diff --git a/lib/closein.c b/lib/closein.c
new file mode 100644
index 0000000..7415b19
--- /dev/null
+++ b/lib/closein.c
@@ -0,0 +1,112 @@
+/* Close standard input, rewinding seekable stdin if necessary.
+
+ Copyright (C) 2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+#include "closein.h"
+
+#include <errno.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <unistd.h>
+
+#include "gettext.h"
+#define _(msgid) gettext (msgid)
+
+#include "close-stream.h"
+#include "closeout.h"
+#include "error.h"
+#include "exitfail.h"
+#include "freadahead.h"
+#include "quotearg.h"
+
+static const char *file_name;
+
+/* Set the file name to be reported in the event an error is detected
+ on stdin by close_stdin. See also close_stdout_set_file_name, if
+ an error is detected when closing stdout. */
+void
+close_stdin_set_file_name (const char *file)
+{
+ file_name = file;
+}
+
+/* Close standard input, rewinding any unused input if stdin is
+ seekable. On error, issue a diagnostic and _exit with status
+ 'exit_failure'. Then call close_stdout.
+
+ Most programs can get by with close_stdout. close_stdin is only
+ needed when a program wants to guarantee that partially read input
+ from seekable stdin is not consumed, for any subsequent clients.
+ For example, POSIX requires that these two commands behave alike:
+
+ (sed -ne 1q; cat) < file
+ tail -n +2 file
+
+ Since close_stdin is commonly registered via 'atexit', POSIX
+ and the C standard both say that it should not call 'exit',
+ because the behavior is undefined if 'exit' is called more than
+ once. So it calls '_exit' instead of 'exit'. If close_stdin
+ is registered via atexit before other functions are registered,
+ the other functions can act before this _exit is invoked.
+
+ Applications that use close_stdout should flush any streams other
+ than stdin, stdout, and stderr before exiting, since the call to
+ _exit will bypass other buffer flushing. Applications should be
+ flushing and closing other streams anyway, to check for I/O errors.
+ Also, applications should not use tmpfile, since _exit can bypass
+ the removal of these files.
+
+ It's important to detect such failures and exit nonzero because many
+ tools (most notably 'make' and other build-management systems) depend
+ on being able to detect failure in other tools via their exit status. */
+
+void
+close_stdin (void)
+{
+ bool fail = false;
+
+ /* There is no need to flush stdin if we can determine quickly that stdin's
+ input buffer is empty; in this case we know that if stdin is seekable,
+ (fseeko (stdin, 0, SEEK_CUR), ftello (stdin))
+ == lseek (0, 0, SEEK_CUR). */
+ if (freadahead (stdin) > 0)
+ {
+ /* Only attempt flush if stdin is seekable, as fflush is entitled to
+ fail on non-seekable streams. */
+ if (fseeko (stdin, 0, SEEK_CUR) == 0 && fflush (stdin) != 0)
+ fail = true;
+ }
+ if (close_stream (stdin) != 0)
+ fail = true;
+ if (fail)
+ {
+ /* Report failure, but defer exit until after closing stdout,
+ since the failure report should still be flushed. */
+ char const *close_error = _("error closing file");
+ if (file_name)
+ error (0, errno, "%s: %s", quotearg_colon (file_name),
+ close_error);
+ else
+ error (0, errno, "%s", close_error);
+ }
+
+ close_stdout ();
+
+ if (fail)
+ _exit (exit_failure);
+}
diff --git a/lib/closein.h b/lib/closein.h
new file mode 100644
index 0000000..c578839
--- /dev/null
+++ b/lib/closein.h
@@ -0,0 +1,32 @@
+/* Close standard input, rewinding seekable stdin if necessary.
+
+ Copyright (C) 2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _GL_CLOSEIN_H
+# define _GL_CLOSEIN_H 1
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+void close_stdin_set_file_name (const char *file);
+void close_stdin (void);
+
+# ifdef __cplusplus
+}
+# endif
+
+#endif
diff --git a/lib/closeout.c b/lib/closeout.c
index 830f16f..311faf4 100644
--- a/lib/closeout.c
+++ b/lib/closeout.c
@@ -1,12 +1,12 @@
/* Close standard output and standard error, exiting with a diagnostic on error.
- Copyright (C) 1998, 1999, 2000, 2001, 2002, 2004, 2006 Free
- Software Foundation, Inc.
+ Copyright (C) 1998-2002, 2004, 2006, 2008-2016 Free Software Foundation,
+ Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,14 +14,14 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
#include "closeout.h"
#include <errno.h>
+#include <stdbool.h>
#include <stdio.h>
#include <unistd.h>
@@ -43,6 +43,43 @@ close_stdout_set_file_name (const char *file)
file_name = file;
}
+static bool ignore_EPIPE /* = false */;
+
+/* Specify the reaction to an EPIPE error during the closing of stdout:
+ - If ignore = true, it shall be ignored.
+ - If ignore = false, it shall evoke a diagnostic, along with a nonzero
+ exit status.
+ The default is ignore = false.
+
+ This setting matters only if the SIGPIPE signal is ignored (i.e. its
+ handler set to SIG_IGN) or blocked. Only particular programs need to
+ temporarily ignore SIGPIPE. If SIGPIPE is ignored or blocked because
+ it was ignored or blocked in the parent process when it created the
+ child process, it usually is a bug in the parent process: It is bad
+ practice to have SIGPIPE ignored or blocked while creating a child
+ process.
+
+ EPIPE occurs when writing to a pipe or socket that has no readers now,
+ when SIGPIPE is ignored or blocked.
+
+ The ignore = false setting is suitable for a scenario where it is normally
+ guaranteed that the pipe writer terminates before the pipe reader. In
+ this case, an EPIPE is an indication of a premature termination of the
+ pipe reader and should lead to a diagnostic and a nonzero exit status.
+
+ The ignore = true setting is suitable for a scenario where you don't know
+ ahead of time whether the pipe writer or the pipe reader will terminate
+ first. In this case, an EPIPE is an indication that the pipe writer can
+ stop doing useless write() calls; this is what close_stdout does anyway.
+ EPIPE is part of the normal pipe/socket shutdown protocol in this case,
+ and should not lead to a diagnostic message. */
+
+void
+close_stdout_set_ignore_EPIPE (bool ignore)
+{
+ ignore_EPIPE = ignore;
+}
+
/* Close standard output. On error, issue a diagnostic and _exit
with status 'exit_failure'.
@@ -63,20 +100,21 @@ close_stdout_set_file_name (const char *file)
can bypass the removal of these files.
It's important to detect such failures and exit nonzero because many
- tools (most notably `make' and other build-management systems) depend
+ tools (most notably 'make' and other build-management systems) depend
on being able to detect failure in other tools via their exit status. */
void
close_stdout (void)
{
- if (close_stream (stdout) != 0)
+ if (close_stream (stdout) != 0
+ && !(ignore_EPIPE && errno == EPIPE))
{
char const *write_error = _("write error");
if (file_name)
- error (0, errno, "%s: %s", quotearg_colon (file_name),
- write_error);
+ error (0, errno, "%s: %s", quotearg_colon (file_name),
+ write_error);
else
- error (0, errno, "%s", write_error);
+ error (0, errno, "%s", write_error);
_exit (exit_failure);
}
diff --git a/lib/closeout.h b/lib/closeout.h
index 8bed23b..bde9bf0 100644
--- a/lib/closeout.h
+++ b/lib/closeout.h
@@ -1,11 +1,12 @@
/* Close standard output and standard error.
- Copyright (C) 1998, 2000, 2003, 2004, 2006 Free Software Foundation, Inc.
+ Copyright (C) 1998, 2000, 2003-2004, 2006, 2008-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,17 +14,19 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifndef CLOSEOUT_H
# define CLOSEOUT_H 1
+# include <stdbool.h>
+
# ifdef __cplusplus
extern "C" {
# endif
void close_stdout_set_file_name (const char *file);
+void close_stdout_set_ignore_EPIPE (bool ignore);
void close_stdout (void);
# ifdef __cplusplus
diff --git a/lib/config.charset b/lib/config.charset
index 148ea44..947d916 100755..100644
--- a/lib/config.charset
+++ b/lib/config.charset
@@ -1,11 +1,11 @@
#! /bin/sh
# Output a system dependent table of character encoding aliases.
#
-# Copyright (C) 2000-2004, 2006 Free Software Foundation, Inc.
+# Copyright (C) 2000-2004, 2006-2016 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 2, or (at your option)
+# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -14,8 +14,7 @@
# 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, write to the Free Software Foundation,
-# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+# with this program; if not, see <http://www.gnu.org/licenses/>.
#
# The table consists of lines of the form
# ALIAS CANONICAL
@@ -30,21 +29,23 @@
# The current list of GNU canonical charset names is as follows.
#
# name MIME? used by which systems
-# ASCII, ANSI_X3.4-1968 glibc solaris freebsd netbsd darwin
-# ISO-8859-1 Y glibc aix hpux irix osf solaris freebsd netbsd darwin
-# ISO-8859-2 Y glibc aix hpux irix osf solaris freebsd netbsd darwin
-# ISO-8859-3 Y glibc solaris
-# ISO-8859-4 Y osf solaris freebsd netbsd darwin
-# ISO-8859-5 Y glibc aix hpux irix osf solaris freebsd netbsd darwin
-# ISO-8859-6 Y glibc aix hpux solaris
-# ISO-8859-7 Y glibc aix hpux irix osf solaris netbsd darwin
-# ISO-8859-8 Y glibc aix hpux osf solaris
-# ISO-8859-9 Y glibc aix hpux irix osf solaris darwin
-# ISO-8859-13 glibc netbsd darwin
-# ISO-8859-14 glibc
-# ISO-8859-15 glibc aix osf solaris freebsd darwin
-# KOI8-R Y glibc solaris freebsd netbsd darwin
-# KOI8-U Y glibc freebsd netbsd darwin
+# (darwin = Mac OS X, woe32 = native Windows)
+#
+# ASCII, ANSI_X3.4-1968 glibc solaris freebsd netbsd darwin cygwin
+# ISO-8859-1 Y glibc aix hpux irix osf solaris freebsd netbsd openbsd darwin cygwin
+# ISO-8859-2 Y glibc aix hpux irix osf solaris freebsd netbsd openbsd darwin cygwin
+# ISO-8859-3 Y glibc solaris cygwin
+# ISO-8859-4 Y osf solaris freebsd netbsd openbsd darwin
+# ISO-8859-5 Y glibc aix hpux irix osf solaris freebsd netbsd openbsd darwin cygwin
+# ISO-8859-6 Y glibc aix hpux solaris cygwin
+# ISO-8859-7 Y glibc aix hpux irix osf solaris netbsd openbsd darwin cygwin
+# ISO-8859-8 Y glibc aix hpux osf solaris cygwin
+# ISO-8859-9 Y glibc aix hpux irix osf solaris darwin cygwin
+# ISO-8859-13 glibc netbsd openbsd darwin cygwin
+# ISO-8859-14 glibc cygwin
+# ISO-8859-15 glibc aix osf solaris freebsd netbsd openbsd darwin cygwin
+# KOI8-R Y glibc solaris freebsd netbsd openbsd darwin
+# KOI8-U Y glibc freebsd netbsd openbsd darwin cygwin
# KOI8-T glibc
# CP437 dos
# CP775 dos
@@ -57,20 +58,21 @@
# CP862 dos
# CP864 dos
# CP865 dos
-# CP866 freebsd netbsd darwin dos
+# CP866 freebsd netbsd openbsd darwin dos
# CP869 dos
# CP874 woe32 dos
# CP922 aix
-# CP932 aix woe32 dos
+# CP932 aix cygwin woe32 dos
# CP943 aix
-# CP949 osf woe32 dos
+# CP949 osf darwin woe32 dos
# CP950 woe32 dos
# CP1046 aix
# CP1124 aix
# CP1125 dos
# CP1129 aix
+# CP1131 darwin
# CP1250 woe32
-# CP1251 glibc solaris netbsd darwin woe32
+# CP1251 glibc solaris netbsd openbsd darwin cygwin woe32
# CP1252 aix woe32
# CP1253 woe32
# CP1254 woe32
@@ -79,18 +81,20 @@
# CP1257 woe32
# GB2312 Y glibc aix hpux irix solaris freebsd netbsd darwin
# EUC-JP Y glibc aix hpux irix osf solaris freebsd netbsd darwin
-# EUC-KR Y glibc aix hpux irix osf solaris freebsd netbsd darwin
+# EUC-KR Y glibc aix hpux irix osf solaris freebsd netbsd darwin cygwin
# EUC-TW glibc aix hpux irix osf solaris netbsd
-# BIG5 Y glibc aix hpux osf solaris freebsd netbsd darwin
-# BIG5-HKSCS glibc solaris
-# GBK glibc aix osf solaris woe32 dos
-# GB18030 glibc solaris netbsd
+# BIG5 Y glibc aix hpux osf solaris freebsd netbsd darwin cygwin
+# BIG5-HKSCS glibc solaris darwin
+# GBK glibc aix osf solaris darwin cygwin woe32 dos
+# GB18030 glibc solaris netbsd darwin
# SHIFT_JIS Y hpux osf solaris freebsd netbsd darwin
# JOHAB glibc solaris woe32
-# TIS-620 glibc aix hpux osf solaris
+# TIS-620 glibc aix hpux osf solaris cygwin
# VISCII Y glibc
# TCVN5712-1 glibc
-# GEORGIAN-PS glibc
+# ARMSCII-8 glibc darwin
+# GEORGIAN-PS glibc cygwin
+# PT154 glibc
# HP-ROMAN8 hpux
# HP-ARABIC8 hpux
# HP-GREEK8 hpux
@@ -99,7 +103,7 @@
# HP-KANA8 hpux
# DEC-KANJI osf
# DEC-HANYU osf
-# UTF-8 Y glibc aix hpux osf solaris netbsd darwin
+# UTF-8 Y glibc aix hpux osf solaris netbsd darwin cygwin
#
# Note: Names which are not marked as being a MIME name should not be used in
# Internet protocols for information interchange (mail, news, etc.).
@@ -120,520 +124,559 @@ echo "# It was automatically generated from config.charset."
# List of references, updated during installation:
echo "# Packages using this file: "
case "$os" in
- linux-gnulibc1*)
- # Linux libc5 doesn't have nl_langinfo(CODESET); therefore
- # localcharset.c falls back to using the full locale name
- # from the environment variables.
- echo "C ASCII"
- echo "POSIX ASCII"
- for l in af af_ZA ca ca_ES da da_DK de de_AT de_BE de_CH de_DE de_LU \
- en en_AU en_BW en_CA en_DK en_GB en_IE en_NZ en_US en_ZA \
- en_ZW es es_AR es_BO es_CL es_CO es_DO es_EC es_ES es_GT \
- es_HN es_MX es_PA es_PE es_PY es_SV es_US es_UY es_VE et \
- et_EE eu eu_ES fi fi_FI fo fo_FO fr fr_BE fr_CA fr_CH fr_FR \
- fr_LU ga ga_IE gl gl_ES id id_ID in in_ID is is_IS it it_CH \
- it_IT kl kl_GL nl nl_BE nl_NL no no_NO pt pt_BR pt_PT sv \
- sv_FI sv_SE; do
- echo "$l ISO-8859-1"
- echo "$l.iso-8859-1 ISO-8859-1"
- echo "$l.iso-8859-15 ISO-8859-15"
- echo "$l.iso-8859-15@euro ISO-8859-15"
- echo "$l@euro ISO-8859-15"
- echo "$l.cp-437 CP437"
- echo "$l.cp-850 CP850"
- echo "$l.cp-1252 CP1252"
- echo "$l.cp-1252@euro CP1252"
- #echo "$l.atari-st ATARI-ST" # not a commonly used encoding
- echo "$l.utf-8 UTF-8"
- echo "$l.utf-8@euro UTF-8"
- done
- for l in cs cs_CZ hr hr_HR hu hu_HU pl pl_PL ro ro_RO sk sk_SK sl \
- sl_SI sr sr_CS sr_YU; do
- echo "$l ISO-8859-2"
- echo "$l.iso-8859-2 ISO-8859-2"
- echo "$l.cp-852 CP852"
- echo "$l.cp-1250 CP1250"
- echo "$l.utf-8 UTF-8"
- done
- for l in mk mk_MK ru ru_RU; do
- echo "$l ISO-8859-5"
- echo "$l.iso-8859-5 ISO-8859-5"
- echo "$l.koi8-r KOI8-R"
- echo "$l.cp-866 CP866"
- echo "$l.cp-1251 CP1251"
- echo "$l.utf-8 UTF-8"
- done
- for l in ar ar_SA; do
- echo "$l ISO-8859-6"
- echo "$l.iso-8859-6 ISO-8859-6"
- echo "$l.cp-864 CP864"
- #echo "$l.cp-868 CP868" # not a commonly used encoding
- echo "$l.cp-1256 CP1256"
- echo "$l.utf-8 UTF-8"
- done
- for l in el el_GR gr gr_GR; do
- echo "$l ISO-8859-7"
- echo "$l.iso-8859-7 ISO-8859-7"
- echo "$l.cp-869 CP869"
- echo "$l.cp-1253 CP1253"
- echo "$l.cp-1253@euro CP1253"
- echo "$l.utf-8 UTF-8"
- echo "$l.utf-8@euro UTF-8"
- done
- for l in he he_IL iw iw_IL; do
- echo "$l ISO-8859-8"
- echo "$l.iso-8859-8 ISO-8859-8"
- echo "$l.cp-862 CP862"
- echo "$l.cp-1255 CP1255"
- echo "$l.utf-8 UTF-8"
- done
- for l in tr tr_TR; do
- echo "$l ISO-8859-9"
- echo "$l.iso-8859-9 ISO-8859-9"
- echo "$l.cp-857 CP857"
- echo "$l.cp-1254 CP1254"
- echo "$l.utf-8 UTF-8"
- done
- for l in lt lt_LT lv lv_LV; do
- #echo "$l BALTIC" # not a commonly used encoding, wrong encoding name
- echo "$l ISO-8859-13"
- done
- for l in ru_UA uk uk_UA; do
- echo "$l KOI8-U"
- done
- for l in zh zh_CN; do
- #echo "$l GB_2312-80" # not a commonly used encoding, wrong encoding name
- echo "$l GB2312"
- done
- for l in ja ja_JP ja_JP.EUC; do
- echo "$l EUC-JP"
- done
- for l in ko ko_KR; do
- echo "$l EUC-KR"
- done
- for l in th th_TH; do
- echo "$l TIS-620"
- done
- for l in fa fa_IR; do
- #echo "$l ISIRI-3342" # a broken encoding
- echo "$l.utf-8 UTF-8"
- done
- ;;
- linux* | *-gnu*)
- # With glibc-2.1 or newer, we don't need any canonicalization,
- # because glibc has iconv and both glibc and libiconv support all
- # GNU canonical names directly. Therefore, the Makefile does not
- # need to install the alias file at all.
- # The following applies only to glibc-2.0.x and older libcs.
- echo "ISO_646.IRV:1983 ASCII"
- ;;
- aix*)
- echo "ISO8859-1 ISO-8859-1"
- echo "ISO8859-2 ISO-8859-2"
- echo "ISO8859-5 ISO-8859-5"
- echo "ISO8859-6 ISO-8859-6"
- echo "ISO8859-7 ISO-8859-7"
- echo "ISO8859-8 ISO-8859-8"
- echo "ISO8859-9 ISO-8859-9"
- echo "ISO8859-15 ISO-8859-15"
- echo "IBM-850 CP850"
- echo "IBM-856 CP856"
- echo "IBM-921 ISO-8859-13"
- echo "IBM-922 CP922"
- echo "IBM-932 CP932"
- echo "IBM-943 CP943"
- echo "IBM-1046 CP1046"
- echo "IBM-1124 CP1124"
- echo "IBM-1129 CP1129"
- echo "IBM-1252 CP1252"
- echo "IBM-eucCN GB2312"
- echo "IBM-eucJP EUC-JP"
- echo "IBM-eucKR EUC-KR"
- echo "IBM-eucTW EUC-TW"
- echo "big5 BIG5"
- echo "GBK GBK"
- echo "TIS-620 TIS-620"
- echo "UTF-8 UTF-8"
- ;;
- hpux*)
- echo "iso88591 ISO-8859-1"
- echo "iso88592 ISO-8859-2"
- echo "iso88595 ISO-8859-5"
- echo "iso88596 ISO-8859-6"
- echo "iso88597 ISO-8859-7"
- echo "iso88598 ISO-8859-8"
- echo "iso88599 ISO-8859-9"
- echo "iso885915 ISO-8859-15"
- echo "roman8 HP-ROMAN8"
- echo "arabic8 HP-ARABIC8"
- echo "greek8 HP-GREEK8"
- echo "hebrew8 HP-HEBREW8"
- echo "turkish8 HP-TURKISH8"
- echo "kana8 HP-KANA8"
- echo "tis620 TIS-620"
- echo "big5 BIG5"
- echo "eucJP EUC-JP"
- echo "eucKR EUC-KR"
- echo "eucTW EUC-TW"
- echo "hp15CN GB2312"
- #echo "ccdc ?" # what is this?
- echo "SJIS SHIFT_JIS"
- echo "utf8 UTF-8"
- ;;
- irix*)
- echo "ISO8859-1 ISO-8859-1"
- echo "ISO8859-2 ISO-8859-2"
- echo "ISO8859-5 ISO-8859-5"
- echo "ISO8859-7 ISO-8859-7"
- echo "ISO8859-9 ISO-8859-9"
- echo "eucCN GB2312"
- echo "eucJP EUC-JP"
- echo "eucKR EUC-KR"
- echo "eucTW EUC-TW"
- ;;
- osf*)
- echo "ISO8859-1 ISO-8859-1"
- echo "ISO8859-2 ISO-8859-2"
- echo "ISO8859-4 ISO-8859-4"
- echo "ISO8859-5 ISO-8859-5"
- echo "ISO8859-7 ISO-8859-7"
- echo "ISO8859-8 ISO-8859-8"
- echo "ISO8859-9 ISO-8859-9"
- echo "ISO8859-15 ISO-8859-15"
- echo "cp850 CP850"
- echo "big5 BIG5"
- echo "dechanyu DEC-HANYU"
- echo "dechanzi GB2312"
- echo "deckanji DEC-KANJI"
- echo "deckorean EUC-KR"
- echo "eucJP EUC-JP"
- echo "eucKR EUC-KR"
- echo "eucTW EUC-TW"
- echo "GBK GBK"
- echo "KSC5601 CP949"
- echo "sdeckanji EUC-JP"
- echo "SJIS SHIFT_JIS"
- echo "TACTIS TIS-620"
- echo "UTF-8 UTF-8"
- ;;
- solaris*)
- echo "646 ASCII"
- echo "ISO8859-1 ISO-8859-1"
- echo "ISO8859-2 ISO-8859-2"
- echo "ISO8859-3 ISO-8859-3"
- echo "ISO8859-4 ISO-8859-4"
- echo "ISO8859-5 ISO-8859-5"
- echo "ISO8859-6 ISO-8859-6"
- echo "ISO8859-7 ISO-8859-7"
- echo "ISO8859-8 ISO-8859-8"
- echo "ISO8859-9 ISO-8859-9"
- echo "ISO8859-15 ISO-8859-15"
- echo "koi8-r KOI8-R"
- echo "ansi-1251 CP1251"
- echo "BIG5 BIG5"
- echo "Big5-HKSCS BIG5-HKSCS"
- echo "gb2312 GB2312"
- echo "GBK GBK"
- echo "GB18030 GB18030"
- echo "cns11643 EUC-TW"
- echo "5601 EUC-KR"
- echo "ko_KR.johap92 JOHAB"
- echo "eucJP EUC-JP"
- echo "PCK SHIFT_JIS"
- echo "TIS620.2533 TIS-620"
- #echo "sun_eu_greek ?" # what is this?
- echo "UTF-8 UTF-8"
- ;;
- freebsd* | os2*)
- # FreeBSD 4.2 doesn't have nl_langinfo(CODESET); therefore
- # localcharset.c falls back to using the full locale name
- # from the environment variables.
- # Likewise for OS/2. OS/2 has XFree86 just like FreeBSD. Just
- # reuse FreeBSD's locale data for OS/2.
- echo "C ASCII"
- echo "US-ASCII ASCII"
- for l in la_LN lt_LN; do
- echo "$l.ASCII ASCII"
- done
- for l in da_DK de_AT de_CH de_DE en_AU en_CA en_GB en_US es_ES \
- fi_FI fr_BE fr_CA fr_CH fr_FR is_IS it_CH it_IT la_LN \
- lt_LN nl_BE nl_NL no_NO pt_PT sv_SE; do
- echo "$l.ISO_8859-1 ISO-8859-1"
- echo "$l.DIS_8859-15 ISO-8859-15"
- done
- for l in cs_CZ hr_HR hu_HU la_LN lt_LN pl_PL sl_SI; do
- echo "$l.ISO_8859-2 ISO-8859-2"
- done
- for l in la_LN lt_LT; do
- echo "$l.ISO_8859-4 ISO-8859-4"
- done
- for l in ru_RU ru_SU; do
- echo "$l.KOI8-R KOI8-R"
- echo "$l.ISO_8859-5 ISO-8859-5"
- echo "$l.CP866 CP866"
- done
- echo "uk_UA.KOI8-U KOI8-U"
- echo "zh_TW.BIG5 BIG5"
- echo "zh_TW.Big5 BIG5"
- echo "zh_CN.EUC GB2312"
- echo "ja_JP.EUC EUC-JP"
- echo "ja_JP.SJIS SHIFT_JIS"
- echo "ja_JP.Shift_JIS SHIFT_JIS"
- echo "ko_KR.EUC EUC-KR"
- ;;
- netbsd*)
- echo "646 ASCII"
- echo "ISO8859-1 ISO-8859-1"
- echo "ISO8859-2 ISO-8859-2"
- echo "ISO8859-4 ISO-8859-4"
- echo "ISO8859-5 ISO-8859-5"
- echo "ISO8859-7 ISO-8859-7"
- echo "ISO8859-13 ISO-8859-13"
- echo "ISO8859-15 ISO-8859-15"
- echo "eucCN GB2312"
- echo "eucJP EUC-JP"
- echo "eucKR EUC-KR"
- echo "eucTW EUC-TW"
- echo "BIG5 BIG5"
- echo "SJIS SHIFT_JIS"
- ;;
- darwin[56]*)
- # Darwin 6.8 doesn't have nl_langinfo(CODESET); therefore
- # localcharset.c falls back to using the full locale name
- # from the environment variables.
- echo "C ASCII"
- for l in en_AU en_CA en_GB en_US la_LN; do
- echo "$l.US-ASCII ASCII"
- done
- for l in da_DK de_AT de_CH de_DE en_AU en_CA en_GB en_US es_ES \
- fi_FI fr_BE fr_CA fr_CH fr_FR is_IS it_CH it_IT nl_BE \
- nl_NL no_NO pt_PT sv_SE; do
- echo "$l ISO-8859-1"
- echo "$l.ISO8859-1 ISO-8859-1"
- echo "$l.ISO8859-15 ISO-8859-15"
- done
- for l in la_LN; do
- echo "$l.ISO8859-1 ISO-8859-1"
- echo "$l.ISO8859-15 ISO-8859-15"
- done
- for l in cs_CZ hr_HR hu_HU la_LN pl_PL sl_SI; do
- echo "$l.ISO8859-2 ISO-8859-2"
- done
- for l in la_LN lt_LT; do
- echo "$l.ISO8859-4 ISO-8859-4"
- done
- for l in ru_RU; do
- echo "$l.KOI8-R KOI8-R"
- echo "$l.ISO8859-5 ISO-8859-5"
- echo "$l.CP866 CP866"
- done
- for l in bg_BG; do
- echo "$l.CP1251 CP1251"
- done
- echo "uk_UA.KOI8-U KOI8-U"
- echo "zh_TW.BIG5 BIG5"
- echo "zh_TW.Big5 BIG5"
- echo "zh_CN.EUC GB2312"
- echo "ja_JP.EUC EUC-JP"
- echo "ja_JP.SJIS SHIFT_JIS"
- echo "ko_KR.EUC EUC-KR"
- ;;
- darwin*)
- # Darwin 7.5 has nl_langinfo(CODESET), but it is useless:
- # - It returns the empty string when LANG is set to a locale of the
- # form ll_CC, although ll_CC/LC_CTYPE is a symlink to an UTF-8
- # LC_CTYPE file.
- # - The environment variables LANG, LC_CTYPE, LC_ALL are not set by
- # the system; nl_langinfo(CODESET) returns "US-ASCII" in this case.
- # - The documentation says:
- # "... all code that calls BSD system routines should ensure
- # that the const *char parameters of these routines are in UTF-8
- # encoding. All BSD system functions expect their string
- # parameters to be in UTF-8 encoding and nothing else."
- # It also says
- # "An additional caveat is that string parameters for files,
- # paths, and other file-system entities must be in canonical
- # UTF-8. In a canonical UTF-8 Unicode string, all decomposable
- # characters are decomposed ..."
- # but this is not true: You can pass non-decomposed UTF-8 strings
- # to file system functions, and it is the OS which will convert
- # them to decomposed UTF-8 before accessing the file system.
- # - The Apple Terminal application displays UTF-8 by default.
- # - However, other applications are free to use different encodings:
- # - xterm uses ISO-8859-1 by default.
- # - TextEdit uses MacRoman by default.
- # We prefer UTF-8 over decomposed UTF-8-MAC because one should
- # minimize the use of decomposed Unicode. Unfortunately, through the
- # Darwin file system, decomposed UTF-8 strings are leaked into user
- # space nevertheless.
- echo "* UTF-8"
- ;;
- beos*)
- # BeOS has a single locale, and it has UTF-8 encoding.
- echo "* UTF-8"
- ;;
- msdosdjgpp*)
- # DJGPP 2.03 doesn't have nl_langinfo(CODESET); therefore
- # localcharset.c falls back to using the full locale name
- # from the environment variables.
- echo "#"
- echo "# The encodings given here may not all be correct."
- echo "# If you find that the encoding given for your language and"
- echo "# country is not the one your DOS machine actually uses, just"
- echo "# correct it in this file, and send a mail to"
- echo "# Juan Manuel Guerrero <juan.guerrero@gmx.de>"
- echo "# and Bruno Haible <bruno@clisp.org>."
- echo "#"
- echo "C ASCII"
- # ISO-8859-1 languages
- echo "ca CP850"
- echo "ca_ES CP850"
- echo "da CP865" # not CP850 ??
- echo "da_DK CP865" # not CP850 ??
- echo "de CP850"
- echo "de_AT CP850"
- echo "de_CH CP850"
- echo "de_DE CP850"
- echo "en CP850"
- echo "en_AU CP850" # not CP437 ??
- echo "en_CA CP850"
- echo "en_GB CP850"
- echo "en_NZ CP437"
- echo "en_US CP437"
- echo "en_ZA CP850" # not CP437 ??
- echo "es CP850"
- echo "es_AR CP850"
- echo "es_BO CP850"
- echo "es_CL CP850"
- echo "es_CO CP850"
- echo "es_CR CP850"
- echo "es_CU CP850"
- echo "es_DO CP850"
- echo "es_EC CP850"
- echo "es_ES CP850"
- echo "es_GT CP850"
- echo "es_HN CP850"
- echo "es_MX CP850"
- echo "es_NI CP850"
- echo "es_PA CP850"
- echo "es_PY CP850"
- echo "es_PE CP850"
- echo "es_SV CP850"
- echo "es_UY CP850"
- echo "es_VE CP850"
- echo "et CP850"
- echo "et_EE CP850"
- echo "eu CP850"
- echo "eu_ES CP850"
- echo "fi CP850"
- echo "fi_FI CP850"
- echo "fr CP850"
- echo "fr_BE CP850"
- echo "fr_CA CP850"
- echo "fr_CH CP850"
- echo "fr_FR CP850"
- echo "ga CP850"
- echo "ga_IE CP850"
- echo "gd CP850"
- echo "gd_GB CP850"
- echo "gl CP850"
- echo "gl_ES CP850"
- echo "id CP850" # not CP437 ??
- echo "id_ID CP850" # not CP437 ??
- echo "is CP861" # not CP850 ??
- echo "is_IS CP861" # not CP850 ??
- echo "it CP850"
- echo "it_CH CP850"
- echo "it_IT CP850"
- echo "lt CP775"
- echo "lt_LT CP775"
- echo "lv CP775"
- echo "lv_LV CP775"
- echo "nb CP865" # not CP850 ??
- echo "nb_NO CP865" # not CP850 ??
- echo "nl CP850"
- echo "nl_BE CP850"
- echo "nl_NL CP850"
- echo "nn CP865" # not CP850 ??
- echo "nn_NO CP865" # not CP850 ??
- echo "no CP865" # not CP850 ??
- echo "no_NO CP865" # not CP850 ??
- echo "pt CP850"
- echo "pt_BR CP850"
- echo "pt_PT CP850"
- echo "sv CP850"
- echo "sv_SE CP850"
- # ISO-8859-2 languages
- echo "cs CP852"
- echo "cs_CZ CP852"
- echo "hr CP852"
- echo "hr_HR CP852"
- echo "hu CP852"
- echo "hu_HU CP852"
- echo "pl CP852"
- echo "pl_PL CP852"
- echo "ro CP852"
- echo "ro_RO CP852"
- echo "sk CP852"
- echo "sk_SK CP852"
- echo "sl CP852"
- echo "sl_SI CP852"
- echo "sq CP852"
- echo "sq_AL CP852"
- echo "sr CP852" # CP852 or CP866 or CP855 ??
- echo "sr_CS CP852" # CP852 or CP866 or CP855 ??
- echo "sr_YU CP852" # CP852 or CP866 or CP855 ??
- # ISO-8859-3 languages
- echo "mt CP850"
- echo "mt_MT CP850"
- # ISO-8859-5 languages
- echo "be CP866"
- echo "be_BE CP866"
- echo "bg CP866" # not CP855 ??
- echo "bg_BG CP866" # not CP855 ??
- echo "mk CP866" # not CP855 ??
- echo "mk_MK CP866" # not CP855 ??
- echo "ru CP866"
- echo "ru_RU CP866"
- echo "uk CP1125"
- echo "uk_UA CP1125"
- # ISO-8859-6 languages
- echo "ar CP864"
- echo "ar_AE CP864"
- echo "ar_DZ CP864"
- echo "ar_EG CP864"
- echo "ar_IQ CP864"
- echo "ar_IR CP864"
- echo "ar_JO CP864"
- echo "ar_KW CP864"
- echo "ar_MA CP864"
- echo "ar_OM CP864"
- echo "ar_QA CP864"
- echo "ar_SA CP864"
- echo "ar_SY CP864"
- # ISO-8859-7 languages
- echo "el CP869"
- echo "el_GR CP869"
- # ISO-8859-8 languages
- echo "he CP862"
- echo "he_IL CP862"
- # ISO-8859-9 languages
- echo "tr CP857"
- echo "tr_TR CP857"
- # Japanese
- echo "ja CP932"
- echo "ja_JP CP932"
- # Chinese
- echo "zh_CN GBK"
- echo "zh_TW CP950" # not CP938 ??
- # Korean
- echo "kr CP949" # not CP934 ??
- echo "kr_KR CP949" # not CP934 ??
- # Thai
- echo "th CP874"
- echo "th_TH CP874"
- # Other
- echo "eo CP850"
- echo "eo_EO CP850"
- ;;
+ linux-gnulibc1*)
+ # Linux libc5 doesn't have nl_langinfo(CODESET); therefore
+ # localcharset.c falls back to using the full locale name
+ # from the environment variables.
+ echo "C ASCII"
+ echo "POSIX ASCII"
+ for l in af af_ZA ca ca_ES da da_DK de de_AT de_BE de_CH de_DE de_LU \
+ en en_AU en_BW en_CA en_DK en_GB en_IE en_NZ en_US en_ZA \
+ en_ZW es es_AR es_BO es_CL es_CO es_DO es_EC es_ES es_GT \
+ es_HN es_MX es_PA es_PE es_PY es_SV es_US es_UY es_VE et \
+ et_EE eu eu_ES fi fi_FI fo fo_FO fr fr_BE fr_CA fr_CH fr_FR \
+ fr_LU ga ga_IE gl gl_ES id id_ID in in_ID is is_IS it it_CH \
+ it_IT kl kl_GL nl nl_BE nl_NL no no_NO pt pt_BR pt_PT sv \
+ sv_FI sv_SE; do
+ echo "$l ISO-8859-1"
+ echo "$l.iso-8859-1 ISO-8859-1"
+ echo "$l.iso-8859-15 ISO-8859-15"
+ echo "$l.iso-8859-15@euro ISO-8859-15"
+ echo "$l@euro ISO-8859-15"
+ echo "$l.cp-437 CP437"
+ echo "$l.cp-850 CP850"
+ echo "$l.cp-1252 CP1252"
+ echo "$l.cp-1252@euro CP1252"
+ #echo "$l.atari-st ATARI-ST" # not a commonly used encoding
+ echo "$l.utf-8 UTF-8"
+ echo "$l.utf-8@euro UTF-8"
+ done
+ for l in cs cs_CZ hr hr_HR hu hu_HU pl pl_PL ro ro_RO sk sk_SK sl \
+ sl_SI sr sr_CS sr_YU; do
+ echo "$l ISO-8859-2"
+ echo "$l.iso-8859-2 ISO-8859-2"
+ echo "$l.cp-852 CP852"
+ echo "$l.cp-1250 CP1250"
+ echo "$l.utf-8 UTF-8"
+ done
+ for l in mk mk_MK ru ru_RU; do
+ echo "$l ISO-8859-5"
+ echo "$l.iso-8859-5 ISO-8859-5"
+ echo "$l.koi8-r KOI8-R"
+ echo "$l.cp-866 CP866"
+ echo "$l.cp-1251 CP1251"
+ echo "$l.utf-8 UTF-8"
+ done
+ for l in ar ar_SA; do
+ echo "$l ISO-8859-6"
+ echo "$l.iso-8859-6 ISO-8859-6"
+ echo "$l.cp-864 CP864"
+ #echo "$l.cp-868 CP868" # not a commonly used encoding
+ echo "$l.cp-1256 CP1256"
+ echo "$l.utf-8 UTF-8"
+ done
+ for l in el el_GR gr gr_GR; do
+ echo "$l ISO-8859-7"
+ echo "$l.iso-8859-7 ISO-8859-7"
+ echo "$l.cp-869 CP869"
+ echo "$l.cp-1253 CP1253"
+ echo "$l.cp-1253@euro CP1253"
+ echo "$l.utf-8 UTF-8"
+ echo "$l.utf-8@euro UTF-8"
+ done
+ for l in he he_IL iw iw_IL; do
+ echo "$l ISO-8859-8"
+ echo "$l.iso-8859-8 ISO-8859-8"
+ echo "$l.cp-862 CP862"
+ echo "$l.cp-1255 CP1255"
+ echo "$l.utf-8 UTF-8"
+ done
+ for l in tr tr_TR; do
+ echo "$l ISO-8859-9"
+ echo "$l.iso-8859-9 ISO-8859-9"
+ echo "$l.cp-857 CP857"
+ echo "$l.cp-1254 CP1254"
+ echo "$l.utf-8 UTF-8"
+ done
+ for l in lt lt_LT lv lv_LV; do
+ #echo "$l BALTIC" # not a commonly used encoding, wrong encoding name
+ echo "$l ISO-8859-13"
+ done
+ for l in ru_UA uk uk_UA; do
+ echo "$l KOI8-U"
+ done
+ for l in zh zh_CN; do
+ #echo "$l GB_2312-80" # not a commonly used encoding, wrong encoding name
+ echo "$l GB2312"
+ done
+ for l in ja ja_JP ja_JP.EUC; do
+ echo "$l EUC-JP"
+ done
+ for l in ko ko_KR; do
+ echo "$l EUC-KR"
+ done
+ for l in th th_TH; do
+ echo "$l TIS-620"
+ done
+ for l in fa fa_IR; do
+ #echo "$l ISIRI-3342" # a broken encoding
+ echo "$l.utf-8 UTF-8"
+ done
+ ;;
+ linux* | *-gnu*)
+ # With glibc-2.1 or newer, we don't need any canonicalization,
+ # because glibc has iconv and both glibc and libiconv support all
+ # GNU canonical names directly. Therefore, the Makefile does not
+ # need to install the alias file at all.
+ # The following applies only to glibc-2.0.x and older libcs.
+ echo "ISO_646.IRV:1983 ASCII"
+ ;;
+ aix*)
+ echo "ISO8859-1 ISO-8859-1"
+ echo "ISO8859-2 ISO-8859-2"
+ echo "ISO8859-5 ISO-8859-5"
+ echo "ISO8859-6 ISO-8859-6"
+ echo "ISO8859-7 ISO-8859-7"
+ echo "ISO8859-8 ISO-8859-8"
+ echo "ISO8859-9 ISO-8859-9"
+ echo "ISO8859-15 ISO-8859-15"
+ echo "IBM-850 CP850"
+ echo "IBM-856 CP856"
+ echo "IBM-921 ISO-8859-13"
+ echo "IBM-922 CP922"
+ echo "IBM-932 CP932"
+ echo "IBM-943 CP943"
+ echo "IBM-1046 CP1046"
+ echo "IBM-1124 CP1124"
+ echo "IBM-1129 CP1129"
+ echo "IBM-1252 CP1252"
+ echo "IBM-eucCN GB2312"
+ echo "IBM-eucJP EUC-JP"
+ echo "IBM-eucKR EUC-KR"
+ echo "IBM-eucTW EUC-TW"
+ echo "big5 BIG5"
+ echo "GBK GBK"
+ echo "TIS-620 TIS-620"
+ echo "UTF-8 UTF-8"
+ ;;
+ hpux*)
+ echo "iso88591 ISO-8859-1"
+ echo "iso88592 ISO-8859-2"
+ echo "iso88595 ISO-8859-5"
+ echo "iso88596 ISO-8859-6"
+ echo "iso88597 ISO-8859-7"
+ echo "iso88598 ISO-8859-8"
+ echo "iso88599 ISO-8859-9"
+ echo "iso885915 ISO-8859-15"
+ echo "roman8 HP-ROMAN8"
+ echo "arabic8 HP-ARABIC8"
+ echo "greek8 HP-GREEK8"
+ echo "hebrew8 HP-HEBREW8"
+ echo "turkish8 HP-TURKISH8"
+ echo "kana8 HP-KANA8"
+ echo "tis620 TIS-620"
+ echo "big5 BIG5"
+ echo "eucJP EUC-JP"
+ echo "eucKR EUC-KR"
+ echo "eucTW EUC-TW"
+ echo "hp15CN GB2312"
+ #echo "ccdc ?" # what is this?
+ echo "SJIS SHIFT_JIS"
+ echo "utf8 UTF-8"
+ ;;
+ irix*)
+ echo "ISO8859-1 ISO-8859-1"
+ echo "ISO8859-2 ISO-8859-2"
+ echo "ISO8859-5 ISO-8859-5"
+ echo "ISO8859-7 ISO-8859-7"
+ echo "ISO8859-9 ISO-8859-9"
+ echo "eucCN GB2312"
+ echo "eucJP EUC-JP"
+ echo "eucKR EUC-KR"
+ echo "eucTW EUC-TW"
+ ;;
+ osf*)
+ echo "ISO8859-1 ISO-8859-1"
+ echo "ISO8859-2 ISO-8859-2"
+ echo "ISO8859-4 ISO-8859-4"
+ echo "ISO8859-5 ISO-8859-5"
+ echo "ISO8859-7 ISO-8859-7"
+ echo "ISO8859-8 ISO-8859-8"
+ echo "ISO8859-9 ISO-8859-9"
+ echo "ISO8859-15 ISO-8859-15"
+ echo "cp850 CP850"
+ echo "big5 BIG5"
+ echo "dechanyu DEC-HANYU"
+ echo "dechanzi GB2312"
+ echo "deckanji DEC-KANJI"
+ echo "deckorean EUC-KR"
+ echo "eucJP EUC-JP"
+ echo "eucKR EUC-KR"
+ echo "eucTW EUC-TW"
+ echo "GBK GBK"
+ echo "KSC5601 CP949"
+ echo "sdeckanji EUC-JP"
+ echo "SJIS SHIFT_JIS"
+ echo "TACTIS TIS-620"
+ echo "UTF-8 UTF-8"
+ ;;
+ solaris*)
+ echo "646 ASCII"
+ echo "ISO8859-1 ISO-8859-1"
+ echo "ISO8859-2 ISO-8859-2"
+ echo "ISO8859-3 ISO-8859-3"
+ echo "ISO8859-4 ISO-8859-4"
+ echo "ISO8859-5 ISO-8859-5"
+ echo "ISO8859-6 ISO-8859-6"
+ echo "ISO8859-7 ISO-8859-7"
+ echo "ISO8859-8 ISO-8859-8"
+ echo "ISO8859-9 ISO-8859-9"
+ echo "ISO8859-15 ISO-8859-15"
+ echo "koi8-r KOI8-R"
+ echo "ansi-1251 CP1251"
+ echo "BIG5 BIG5"
+ echo "Big5-HKSCS BIG5-HKSCS"
+ echo "gb2312 GB2312"
+ echo "GBK GBK"
+ echo "GB18030 GB18030"
+ echo "cns11643 EUC-TW"
+ echo "5601 EUC-KR"
+ echo "ko_KR.johap92 JOHAB"
+ echo "eucJP EUC-JP"
+ echo "PCK SHIFT_JIS"
+ echo "TIS620.2533 TIS-620"
+ #echo "sun_eu_greek ?" # what is this?
+ echo "UTF-8 UTF-8"
+ ;;
+ freebsd*)
+ # FreeBSD 4.2 doesn't have nl_langinfo(CODESET); therefore
+ # localcharset.c falls back to using the full locale name
+ # from the environment variables.
+ echo "C ASCII"
+ echo "US-ASCII ASCII"
+ for l in la_LN lt_LN; do
+ echo "$l.ASCII ASCII"
+ done
+ for l in da_DK de_AT de_CH de_DE en_AU en_CA en_GB en_US es_ES \
+ fi_FI fr_BE fr_CA fr_CH fr_FR is_IS it_CH it_IT la_LN \
+ lt_LN nl_BE nl_NL no_NO pt_PT sv_SE; do
+ echo "$l.ISO_8859-1 ISO-8859-1"
+ echo "$l.DIS_8859-15 ISO-8859-15"
+ done
+ for l in cs_CZ hr_HR hu_HU la_LN lt_LN pl_PL sl_SI; do
+ echo "$l.ISO_8859-2 ISO-8859-2"
+ done
+ for l in la_LN lt_LT; do
+ echo "$l.ISO_8859-4 ISO-8859-4"
+ done
+ for l in ru_RU ru_SU; do
+ echo "$l.KOI8-R KOI8-R"
+ echo "$l.ISO_8859-5 ISO-8859-5"
+ echo "$l.CP866 CP866"
+ done
+ echo "uk_UA.KOI8-U KOI8-U"
+ echo "zh_TW.BIG5 BIG5"
+ echo "zh_TW.Big5 BIG5"
+ echo "zh_CN.EUC GB2312"
+ echo "ja_JP.EUC EUC-JP"
+ echo "ja_JP.SJIS SHIFT_JIS"
+ echo "ja_JP.Shift_JIS SHIFT_JIS"
+ echo "ko_KR.EUC EUC-KR"
+ ;;
+ netbsd*)
+ echo "646 ASCII"
+ echo "ISO8859-1 ISO-8859-1"
+ echo "ISO8859-2 ISO-8859-2"
+ echo "ISO8859-4 ISO-8859-4"
+ echo "ISO8859-5 ISO-8859-5"
+ echo "ISO8859-7 ISO-8859-7"
+ echo "ISO8859-13 ISO-8859-13"
+ echo "ISO8859-15 ISO-8859-15"
+ echo "eucCN GB2312"
+ echo "eucJP EUC-JP"
+ echo "eucKR EUC-KR"
+ echo "eucTW EUC-TW"
+ echo "BIG5 BIG5"
+ echo "SJIS SHIFT_JIS"
+ ;;
+ openbsd*)
+ echo "646 ASCII"
+ echo "ISO8859-1 ISO-8859-1"
+ echo "ISO8859-2 ISO-8859-2"
+ echo "ISO8859-4 ISO-8859-4"
+ echo "ISO8859-5 ISO-8859-5"
+ echo "ISO8859-7 ISO-8859-7"
+ echo "ISO8859-13 ISO-8859-13"
+ echo "ISO8859-15 ISO-8859-15"
+ ;;
+ darwin[56]*)
+ # Darwin 6.8 doesn't have nl_langinfo(CODESET); therefore
+ # localcharset.c falls back to using the full locale name
+ # from the environment variables.
+ echo "C ASCII"
+ for l in en_AU en_CA en_GB en_US la_LN; do
+ echo "$l.US-ASCII ASCII"
+ done
+ for l in da_DK de_AT de_CH de_DE en_AU en_CA en_GB en_US es_ES \
+ fi_FI fr_BE fr_CA fr_CH fr_FR is_IS it_CH it_IT nl_BE \
+ nl_NL no_NO pt_PT sv_SE; do
+ echo "$l ISO-8859-1"
+ echo "$l.ISO8859-1 ISO-8859-1"
+ echo "$l.ISO8859-15 ISO-8859-15"
+ done
+ for l in la_LN; do
+ echo "$l.ISO8859-1 ISO-8859-1"
+ echo "$l.ISO8859-15 ISO-8859-15"
+ done
+ for l in cs_CZ hr_HR hu_HU la_LN pl_PL sl_SI; do
+ echo "$l.ISO8859-2 ISO-8859-2"
+ done
+ for l in la_LN lt_LT; do
+ echo "$l.ISO8859-4 ISO-8859-4"
+ done
+ for l in ru_RU; do
+ echo "$l.KOI8-R KOI8-R"
+ echo "$l.ISO8859-5 ISO-8859-5"
+ echo "$l.CP866 CP866"
+ done
+ for l in bg_BG; do
+ echo "$l.CP1251 CP1251"
+ done
+ echo "uk_UA.KOI8-U KOI8-U"
+ echo "zh_TW.BIG5 BIG5"
+ echo "zh_TW.Big5 BIG5"
+ echo "zh_CN.EUC GB2312"
+ echo "ja_JP.EUC EUC-JP"
+ echo "ja_JP.SJIS SHIFT_JIS"
+ echo "ko_KR.EUC EUC-KR"
+ ;;
+ darwin*)
+ # Darwin 7.5 has nl_langinfo(CODESET), but sometimes its value is
+ # useless:
+ # - It returns the empty string when LANG is set to a locale of the
+ # form ll_CC, although ll_CC/LC_CTYPE is a symlink to an UTF-8
+ # LC_CTYPE file.
+ # - The environment variables LANG, LC_CTYPE, LC_ALL are not set by
+ # the system; nl_langinfo(CODESET) returns "US-ASCII" in this case.
+ # - The documentation says:
+ # "... all code that calls BSD system routines should ensure
+ # that the const *char parameters of these routines are in UTF-8
+ # encoding. All BSD system functions expect their string
+ # parameters to be in UTF-8 encoding and nothing else."
+ # It also says
+ # "An additional caveat is that string parameters for files,
+ # paths, and other file-system entities must be in canonical
+ # UTF-8. In a canonical UTF-8 Unicode string, all decomposable
+ # characters are decomposed ..."
+ # but this is not true: You can pass non-decomposed UTF-8 strings
+ # to file system functions, and it is the OS which will convert
+ # them to decomposed UTF-8 before accessing the file system.
+ # - The Apple Terminal application displays UTF-8 by default.
+ # - However, other applications are free to use different encodings:
+ # - xterm uses ISO-8859-1 by default.
+ # - TextEdit uses MacRoman by default.
+ # We prefer UTF-8 over decomposed UTF-8-MAC because one should
+ # minimize the use of decomposed Unicode. Unfortunately, through the
+ # Darwin file system, decomposed UTF-8 strings are leaked into user
+ # space nevertheless.
+ # Then there are also the locales with encodings other than US-ASCII
+ # and UTF-8. These locales can be occasionally useful to users (e.g.
+ # when grepping through ISO-8859-1 encoded text files), when all their
+ # file names are in US-ASCII.
+ echo "ISO8859-1 ISO-8859-1"
+ echo "ISO8859-2 ISO-8859-2"
+ echo "ISO8859-4 ISO-8859-4"
+ echo "ISO8859-5 ISO-8859-5"
+ echo "ISO8859-7 ISO-8859-7"
+ echo "ISO8859-9 ISO-8859-9"
+ echo "ISO8859-13 ISO-8859-13"
+ echo "ISO8859-15 ISO-8859-15"
+ echo "KOI8-R KOI8-R"
+ echo "KOI8-U KOI8-U"
+ echo "CP866 CP866"
+ echo "CP949 CP949"
+ echo "CP1131 CP1131"
+ echo "CP1251 CP1251"
+ echo "eucCN GB2312"
+ echo "GB2312 GB2312"
+ echo "eucJP EUC-JP"
+ echo "eucKR EUC-KR"
+ echo "Big5 BIG5"
+ echo "Big5HKSCS BIG5-HKSCS"
+ echo "GBK GBK"
+ echo "GB18030 GB18030"
+ echo "SJIS SHIFT_JIS"
+ echo "ARMSCII-8 ARMSCII-8"
+ echo "PT154 PT154"
+ #echo "ISCII-DEV ?"
+ echo "* UTF-8"
+ ;;
+ beos* | haiku*)
+ # BeOS and Haiku have a single locale, and it has UTF-8 encoding.
+ echo "* UTF-8"
+ ;;
+ msdosdjgpp*)
+ # DJGPP 2.03 doesn't have nl_langinfo(CODESET); therefore
+ # localcharset.c falls back to using the full locale name
+ # from the environment variables.
+ echo "#"
+ echo "# The encodings given here may not all be correct."
+ echo "# If you find that the encoding given for your language and"
+ echo "# country is not the one your DOS machine actually uses, just"
+ echo "# correct it in this file, and send a mail to"
+ echo "# Juan Manuel Guerrero <juan.guerrero@gmx.de>"
+ echo "# and Bruno Haible <bruno@clisp.org>."
+ echo "#"
+ echo "C ASCII"
+ # ISO-8859-1 languages
+ echo "ca CP850"
+ echo "ca_ES CP850"
+ echo "da CP865" # not CP850 ??
+ echo "da_DK CP865" # not CP850 ??
+ echo "de CP850"
+ echo "de_AT CP850"
+ echo "de_CH CP850"
+ echo "de_DE CP850"
+ echo "en CP850"
+ echo "en_AU CP850" # not CP437 ??
+ echo "en_CA CP850"
+ echo "en_GB CP850"
+ echo "en_NZ CP437"
+ echo "en_US CP437"
+ echo "en_ZA CP850" # not CP437 ??
+ echo "es CP850"
+ echo "es_AR CP850"
+ echo "es_BO CP850"
+ echo "es_CL CP850"
+ echo "es_CO CP850"
+ echo "es_CR CP850"
+ echo "es_CU CP850"
+ echo "es_DO CP850"
+ echo "es_EC CP850"
+ echo "es_ES CP850"
+ echo "es_GT CP850"
+ echo "es_HN CP850"
+ echo "es_MX CP850"
+ echo "es_NI CP850"
+ echo "es_PA CP850"
+ echo "es_PY CP850"
+ echo "es_PE CP850"
+ echo "es_SV CP850"
+ echo "es_UY CP850"
+ echo "es_VE CP850"
+ echo "et CP850"
+ echo "et_EE CP850"
+ echo "eu CP850"
+ echo "eu_ES CP850"
+ echo "fi CP850"
+ echo "fi_FI CP850"
+ echo "fr CP850"
+ echo "fr_BE CP850"
+ echo "fr_CA CP850"
+ echo "fr_CH CP850"
+ echo "fr_FR CP850"
+ echo "ga CP850"
+ echo "ga_IE CP850"
+ echo "gd CP850"
+ echo "gd_GB CP850"
+ echo "gl CP850"
+ echo "gl_ES CP850"
+ echo "id CP850" # not CP437 ??
+ echo "id_ID CP850" # not CP437 ??
+ echo "is CP861" # not CP850 ??
+ echo "is_IS CP861" # not CP850 ??
+ echo "it CP850"
+ echo "it_CH CP850"
+ echo "it_IT CP850"
+ echo "lt CP775"
+ echo "lt_LT CP775"
+ echo "lv CP775"
+ echo "lv_LV CP775"
+ echo "nb CP865" # not CP850 ??
+ echo "nb_NO CP865" # not CP850 ??
+ echo "nl CP850"
+ echo "nl_BE CP850"
+ echo "nl_NL CP850"
+ echo "nn CP865" # not CP850 ??
+ echo "nn_NO CP865" # not CP850 ??
+ echo "no CP865" # not CP850 ??
+ echo "no_NO CP865" # not CP850 ??
+ echo "pt CP850"
+ echo "pt_BR CP850"
+ echo "pt_PT CP850"
+ echo "sv CP850"
+ echo "sv_SE CP850"
+ # ISO-8859-2 languages
+ echo "cs CP852"
+ echo "cs_CZ CP852"
+ echo "hr CP852"
+ echo "hr_HR CP852"
+ echo "hu CP852"
+ echo "hu_HU CP852"
+ echo "pl CP852"
+ echo "pl_PL CP852"
+ echo "ro CP852"
+ echo "ro_RO CP852"
+ echo "sk CP852"
+ echo "sk_SK CP852"
+ echo "sl CP852"
+ echo "sl_SI CP852"
+ echo "sq CP852"
+ echo "sq_AL CP852"
+ echo "sr CP852" # CP852 or CP866 or CP855 ??
+ echo "sr_CS CP852" # CP852 or CP866 or CP855 ??
+ echo "sr_YU CP852" # CP852 or CP866 or CP855 ??
+ # ISO-8859-3 languages
+ echo "mt CP850"
+ echo "mt_MT CP850"
+ # ISO-8859-5 languages
+ echo "be CP866"
+ echo "be_BE CP866"
+ echo "bg CP866" # not CP855 ??
+ echo "bg_BG CP866" # not CP855 ??
+ echo "mk CP866" # not CP855 ??
+ echo "mk_MK CP866" # not CP855 ??
+ echo "ru CP866"
+ echo "ru_RU CP866"
+ echo "uk CP1125"
+ echo "uk_UA CP1125"
+ # ISO-8859-6 languages
+ echo "ar CP864"
+ echo "ar_AE CP864"
+ echo "ar_DZ CP864"
+ echo "ar_EG CP864"
+ echo "ar_IQ CP864"
+ echo "ar_IR CP864"
+ echo "ar_JO CP864"
+ echo "ar_KW CP864"
+ echo "ar_MA CP864"
+ echo "ar_OM CP864"
+ echo "ar_QA CP864"
+ echo "ar_SA CP864"
+ echo "ar_SY CP864"
+ # ISO-8859-7 languages
+ echo "el CP869"
+ echo "el_GR CP869"
+ # ISO-8859-8 languages
+ echo "he CP862"
+ echo "he_IL CP862"
+ # ISO-8859-9 languages
+ echo "tr CP857"
+ echo "tr_TR CP857"
+ # Japanese
+ echo "ja CP932"
+ echo "ja_JP CP932"
+ # Chinese
+ echo "zh_CN GBK"
+ echo "zh_TW CP950" # not CP938 ??
+ # Korean
+ echo "kr CP949" # not CP934 ??
+ echo "kr_KR CP949" # not CP934 ??
+ # Thai
+ echo "th CP874"
+ echo "th_TH CP874"
+ # Other
+ echo "eo CP850"
+ echo "eo_EO CP850"
+ ;;
esac
diff --git a/lib/config.hin b/lib/config.hin
index 748b425..d483d6d 100644
--- a/lib/config.hin
+++ b/lib/config.hin
@@ -1,49 +1,7 @@
/* lib/config.hin. Generated from configure.ac by autoheader. */
-/* Define this to an absolute name of <dirent.h>. */
-#undef ABSOLUTE_DIRENT_H
-
-/* Define this to an absolute name of <fcntl.h>. */
-#undef ABSOLUTE_FCNTL_H
-
-/* Define this to an absolute name of <inttypes.h>. */
-#undef ABSOLUTE_INTTYPES_H
-
-/* Define this to an absolute name of <netinet/in.h>. */
-#undef ABSOLUTE_NETINET_IN_H
-
-/* Define this to an absolute name of <stdint.h>. */
-#undef ABSOLUTE_STDINT_H
-
-/* Define this to an absolute name of <stdio.h>. */
-#undef ABSOLUTE_STDIO_H
-
-/* Define this to an absolute name of <stdlib.h>. */
-#undef ABSOLUTE_STDLIB_H
-
-/* Define this to an absolute name of <string.h>. */
-#undef ABSOLUTE_STRING_H
-
-/* Define this to an absolute name of <sys/socket.h>. */
-#undef ABSOLUTE_SYS_SOCKET_H
-
-/* Define this to an absolute name of <sys/stat.h>. */
-#undef ABSOLUTE_SYS_STAT_H
-
-/* Define this to an absolute name of <sys/time.h>. */
-#undef ABSOLUTE_SYS_TIME_H
-
-/* Define this to an absolute name of <time.h>. */
-#undef ABSOLUTE_TIME_H
-
-/* Define this to an absolute name of <unistd.h>. */
-#undef ABSOLUTE_UNISTD_H
-
-/* Define this to an absolute name of <wchar.h>. */
-#undef ABSOLUTE_WCHAR_H
-
-/* Define this to an absolute name of <wctype.h>. */
-#undef ABSOLUTE_WCTYPE_H
+/* Define if building universal (internal helper macro) */
+#undef AC_APPLE_UNIVERSAL_BUILD
/* Define to the function xargmatch calls on failures. */
#undef ARGMATCH_DIE
@@ -66,12 +24,23 @@
/* Define to the number of bits in type 'wint_t'. */
#undef BITSIZEOF_WINT_T
+/* Define if you wish *printf() functions that have a safe handling of
+ non-IEEE-754 'long double' values. */
+#undef CHECK_PRINTF_SAFE
+
+/* Define to 1 if chown fails to change ctime when at least one argument was
+ not -1. */
+#undef CHOWN_CHANGE_TIME_BUG
+
/* Define if chown is not POSIX compliant regarding IDs of -1. */
#undef CHOWN_FAILS_TO_HONOR_ID_OF_NEGATIVE_ONE
/* Define if chown modifies symlinks. */
#undef CHOWN_MODIFIES_SYMLINK
+/* Define to 1 if chown mishandles trailing slash. */
+#undef CHOWN_TRAILING_SLASH_BUG
+
/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
systems. This function is required for `alloca.c' support on those systems.
*/
@@ -80,17 +49,27 @@
/* Define to 1 if using `alloca.c'. */
#undef C_ALLOCA
-/* Define to 1 if using `getloadavg.c'. */
-#undef C_GETLOADAVG
+/* Define as the bit index in the word where to find bit 0 of the exponent of
+ 'double'. */
+#undef DBL_EXPBIT0_BIT
+
+/* Define as the word index where to find the exponent of 'double'. */
+#undef DBL_EXPBIT0_WORD
+
+/* Define as the bit index in the word where to find the sign of 'double'. */
+#undef DBL_SIGNBIT_BIT
+
+/* Define as the word index where to find the sign of 'double'. */
+#undef DBL_SIGNBIT_WORD
/* Define the default level of POSIX conformance. The value is of the form
YYYYMM, specifying the year and month the standard was adopted. If not
defined here, it defaults to the value of _POSIX2_VERSION in <unistd.h>.
Define to 199209 to default to POSIX 1003.2-1992, which makes standard
- programs like `head', `tail', and `sort' accept obsolete options like `+10'
- and `-10'. Define to 200112 to default to POSIX 1003.1-2001, which makes
- these standard programs treat leading-`+' operands as file names and
- require modern usages like `-n 10' instead of `-10'. Whether defined here
+ programs like 'head', 'tail', and 'sort' accept obsolete options like '+10'
+ and '-10'. Define to 200112 to default to POSIX 1003.1-2001, which makes
+ these standard programs treat leading-'+' operands as file names and
+ require modern usages like '-n 10' instead of '-10'. Whether defined here
or not, the default can be overridden at run time via the _POSIX2_VERSION
environment variable. */
#undef DEFAULT_POSIX2_VERSION
@@ -111,35 +90,26 @@
/* Define to 1 if // is a file system root distinct from /. */
#undef DOUBLE_SLASH_IS_DISTINCT_ROOT
-/* Define if there is a member named d_ino in the struct describing directory
- headers. */
+/* Define if struct dirent has a member d_ino that actually works. */
#undef D_INO_IN_DIRENT
/* Define to 1 if translation of program messages to the user's native
language is requested. */
#undef ENABLE_NLS
-/* Define as good substitute value for EOVERFLOW. */
-#undef EOVERFLOW
-
-/* Define if gnulib's fchdir() replacement is used. */
-#undef FCHDIR_REPLACEMENT
+/* Define to 1 if your platform has fchownat, but it does not reject an empty
+ file name. */
+#undef FCHOWNAT_EMPTY_FILENAME_BUG
-/* Define on systems for which file names may have a so-called `drive letter'
- prefix, define this to compute the length of that prefix, including the
- colon. */
-#undef FILE_SYSTEM_ACCEPTS_DRIVE_LETTER_PREFIX
+/* Define to 1 if your platform has fchownat, but it cannot perform lchown
+ tasks. */
+#undef FCHOWNAT_NOFOLLOW_BUG
-/* Define if the backslash character may also serve as a file name component
- separator. */
-#undef FILE_SYSTEM_BACKSLASH_IS_FILE_NAME_SEPARATOR
-
-/* Define if a drive letter prefix denotes a relative path if it is not
- followed by a file name component separator. */
-#undef FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE
+/* Define this to 1 if F_DUPFD behavior does not match POSIX */
+#undef FCNTL_DUPFD_BUGGY
/* Define to nothing if C supports flexible array members, and to 1 if it does
- not. That way, with a declaration like `struct s { int n; double
+ not. That way, with a declaration like 'struct s { int n; double
d[FLEXIBLE_ARRAY_MEMBER]; };', the struct hack can be used with pre-C99
compilers. When computing the size of such an object, don't use 'sizeof
(struct s)' as it overestimates the size. Use 'offsetof (struct s, d)'
@@ -147,34 +117,642 @@
MSVC and with C++ compilers. */
#undef FLEXIBLE_ARRAY_MEMBER
+/* Define as the bit index in the word where to find bit 0 of the exponent of
+ 'float'. */
+#undef FLT_EXPBIT0_BIT
+
+/* Define as the word index where to find the exponent of 'float'. */
+#undef FLT_EXPBIT0_WORD
+
+/* Define as the bit index in the word where to find the sign of 'float'. */
+#undef FLT_SIGNBIT_BIT
+
+/* Define as the word index where to find the sign of 'float'. */
+#undef FLT_SIGNBIT_WORD
+
+/* Define to 1 if fopen() fails to recognize a trailing slash. */
+#undef FOPEN_TRAILING_SLASH_BUG
+
+/* Enable compile-time and run-time bounds-checking, and some warnings,
+ without upsetting glibc 2.15+. */
+ #if !defined _FORTIFY_SOURCE && defined __OPTIMIZE__ && __OPTIMIZE__
+ # define _FORTIFY_SOURCE 2
+ #endif
+
+
+/* Define to 1 if the system's ftello function has the Solaris bug. */
+#undef FTELLO_BROKEN_AFTER_SWITCHING_FROM_READ_TO_WRITE
+
+/* Define to 1 if fflush is known to work on stdin as per POSIX.1-2008, 0 if
+ fflush is known to not work, -1 if unknown. */
+#undef FUNC_FFLUSH_STDIN
+
+/* Define to 1 if mkdir mistakenly creates a directory given with a trailing
+ dot component. */
+#undef FUNC_MKDIR_DOT_BUG
+
+/* Define to 1 if nl_langinfo (YESEXPR) returns a non-empty string. */
+#undef FUNC_NL_LANGINFO_YESEXPR_WORKS
+
+/* Define to 1 if realpath() can malloc memory, always gives an absolute path,
+ and handles trailing slash correctly. */
+#undef FUNC_REALPATH_WORKS
+
+/* Define to 1 if ungetc is broken when used on arbitrary bytes. */
+#undef FUNC_UNGETC_BROKEN
+
+/* Define to 1 if futimesat mishandles a NULL file name. */
+#undef FUTIMESAT_NULL_BUG
+
/* Define to the type of elements in the array set by `getgroups'. Usually
this is either `int' or `gid_t'. */
#undef GETGROUPS_T
-/* Define to 1 if the `getloadavg' function needs to be run setuid or setgid.
+/* Define this to 1 if getgroups(0,NULL) does not return the number of groups.
*/
-#undef GETLOADAVG_PRIVILEGED
+#undef GETGROUPS_ZERO_BUG
/* Define if gettimeofday clobbers the localtime buffer. */
#undef GETTIMEOFDAY_CLOBBERS_LOCALTIME
-/* Define to 1 when using the gnulib module canonicalize. */
+/* Define this to 'void' or 'struct timezone' to match the system's
+ declaration of the second argument to gettimeofday. */
+#undef GETTIMEOFDAY_TIMEZONE
+
+/* Define to 1 if getxattr works with XATTR_NAME_POSIX_ACL_ACCESS and
+ XATTR_NAME_POSIX_ACL_DEFAULT. */
+#undef GETXATTR_WITH_POSIX_ACLS
+
+/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
+ whether the gnulib module areadlinkat shall be considered present. */
+#undef GNULIB_AREADLINKAT
+
+/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
+ whether the gnulib module calloc-gnu shall be considered present. */
+#undef GNULIB_CALLOC_GNU
+
+/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
+ whether the gnulib module canonicalize shall be considered present. */
#undef GNULIB_CANONICALIZE
-/* Define to 1 when using the gnulib module close-stream. */
+/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
+ whether the gnulib module close-stream shall be considered present. */
#undef GNULIB_CLOSE_STREAM
-/* Define to 1 when using the gnulib module fcntl-safer. */
+/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
+ whether the gnulib module dirent-safer shall be considered present. */
+#undef GNULIB_DIRENT_SAFER
+
+/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
+ whether the gnulib module dirname shall be considered present. */
+#undef GNULIB_DIRNAME
+
+/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
+ whether the gnulib module faccessat shall be considered present. */
+#undef GNULIB_FACCESSAT
+
+/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
+ whether the gnulib module fchmodat shall be considered present. */
+#undef GNULIB_FCHMODAT
+
+/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
+ whether the gnulib module fchownat shall be considered present. */
+#undef GNULIB_FCHOWNAT
+
+/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
+ whether the gnulib module fcntl-safer shall be considered present. */
#undef GNULIB_FCNTL_SAFER
-/* Define to 1 when using the gnulib module fopen-safer. */
+/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
+ whether the gnulib module fdopendir shall be considered present. */
+#undef GNULIB_FDOPENDIR
+
+/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
+ whether the gnulib module fdutimensat shall be considered present. */
+#undef GNULIB_FDUTIMENSAT
+
+/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
+ whether the gnulib module fd-safer-flag shall be considered present. */
+#undef GNULIB_FD_SAFER_FLAG
+
+/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
+ whether the gnulib module fflush shall be considered present. */
+#undef GNULIB_FFLUSH
+
+/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
+ whether the gnulib module filenamecat shall be considered present. */
+#undef GNULIB_FILENAMECAT
+
+/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
+ whether the gnulib module fopen-safer shall be considered present. */
#undef GNULIB_FOPEN_SAFER
-/* Define to 1 when using the gnulib module fts. */
-#undef GNULIB_FTS
+/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
+ whether the gnulib module freopen-safer shall be considered present. */
+#undef GNULIB_FREOPEN_SAFER
+
+/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
+ whether the gnulib module fscanf shall be considered present. */
+#undef GNULIB_FSCANF
+
+/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
+ whether the gnulib module getcwd shall be considered present. */
+#undef GNULIB_GETCWD
+
+/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
+ whether the gnulib module lock shall be considered present. */
+#undef GNULIB_LOCK
+
+/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
+ whether the gnulib module malloc-gnu shall be considered present. */
+#undef GNULIB_MALLOC_GNU
+
+/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
+ whether the gnulib module openat shall be considered present. */
+#undef GNULIB_OPENAT
+
+/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
+ whether the gnulib module openat-safer shall be considered present. */
+#undef GNULIB_OPENAT_SAFER
+
+/* enable some gnulib portability checks */
+#undef GNULIB_PORTCHECK
+
+/* Define to 1 if printf and friends should be labeled with attribute
+ "__gnu_printf__" instead of "__printf__" */
+#undef GNULIB_PRINTF_ATTRIBUTE_FLAVOR_GNU
+
+/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
+ whether the gnulib module pthread shall be considered present. */
+#undef GNULIB_PTHREAD
+
+/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
+ whether the gnulib module realloc-gnu shall be considered present. */
+#undef GNULIB_REALLOC_GNU
+
+/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
+ whether the gnulib module scanf shall be considered present. */
+#undef GNULIB_SCANF
+
+/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
+ whether the gnulib module snprintf shall be considered present. */
+#undef GNULIB_SNPRINTF
+
+/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
+ whether the gnulib module statat shall be considered present. */
+#undef GNULIB_STATAT
+
+/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
+ whether the gnulib module strerror shall be considered present. */
+#undef GNULIB_STRERROR
+
+/* Define to 1 when the gnulib module accept should be tested. */
+#undef GNULIB_TEST_ACCEPT
+
+/* Define to 1 when the gnulib module bind should be tested. */
+#undef GNULIB_TEST_BIND
+
+/* Define to 1 when the gnulib module btowc should be tested. */
+#undef GNULIB_TEST_BTOWC
+
+/* Define to 1 when the gnulib module calloc-posix should be tested. */
+#undef GNULIB_TEST_CALLOC_POSIX
+
+/* Define to 1 when the gnulib module canonicalize should be tested. */
+#undef GNULIB_TEST_CANONICALIZE
+
+/* Define to 1 when the gnulib module canonicalize_file_name should be tested.
+ */
+#undef GNULIB_TEST_CANONICALIZE_FILE_NAME
+
+/* Define to 1 when the gnulib module chdir should be tested. */
+#undef GNULIB_TEST_CHDIR
+
+/* Define to 1 when the gnulib module chown should be tested. */
+#undef GNULIB_TEST_CHOWN
+
+/* Define to 1 when the gnulib module cloexec should be tested. */
+#undef GNULIB_TEST_CLOEXEC
+
+/* Define to 1 when the gnulib module close should be tested. */
+#undef GNULIB_TEST_CLOSE
+
+/* Define to 1 when the gnulib module closedir should be tested. */
+#undef GNULIB_TEST_CLOSEDIR
+
+/* Define to 1 when the gnulib module connect should be tested. */
+#undef GNULIB_TEST_CONNECT
+
+/* Define to 1 when the gnulib module dirfd should be tested. */
+#undef GNULIB_TEST_DIRFD
+
+/* Define to 1 when the gnulib module dup should be tested. */
+#undef GNULIB_TEST_DUP
+
+/* Define to 1 when the gnulib module dup2 should be tested. */
+#undef GNULIB_TEST_DUP2
+
+/* Define to 1 when the gnulib module environ should be tested. */
+#undef GNULIB_TEST_ENVIRON
+
+/* Define to 1 when the gnulib module euidaccess should be tested. */
+#undef GNULIB_TEST_EUIDACCESS
+
+/* Define to 1 when the gnulib module faccessat should be tested. */
+#undef GNULIB_TEST_FACCESSAT
+
+/* Define to 1 when the gnulib module fchdir should be tested. */
+#undef GNULIB_TEST_FCHDIR
+
+/* Define to 1 when the gnulib module fchmodat should be tested. */
+#undef GNULIB_TEST_FCHMODAT
+
+/* Define to 1 when the gnulib module fchownat should be tested. */
+#undef GNULIB_TEST_FCHOWNAT
+
+/* Define to 1 when the gnulib module fclose should be tested. */
+#undef GNULIB_TEST_FCLOSE
+
+/* Define to 1 when the gnulib module fcntl should be tested. */
+#undef GNULIB_TEST_FCNTL
+
+/* Define to 1 when the gnulib module fdatasync should be tested. */
+#undef GNULIB_TEST_FDATASYNC
+
+/* Define to 1 when the gnulib module fdopen should be tested. */
+#undef GNULIB_TEST_FDOPEN
+
+/* Define to 1 when the gnulib module fdopendir should be tested. */
+#undef GNULIB_TEST_FDOPENDIR
+
+/* Define to 1 when the gnulib module fflush should be tested. */
+#undef GNULIB_TEST_FFLUSH
+
+/* Define to 1 when the gnulib module fopen should be tested. */
+#undef GNULIB_TEST_FOPEN
+
+/* Define to 1 when the gnulib module fpurge should be tested. */
+#undef GNULIB_TEST_FPURGE
+
+/* Define to 1 when the gnulib module freopen should be tested. */
+#undef GNULIB_TEST_FREOPEN
+
+/* Define to 1 when the gnulib module frexp should be tested. */
+#undef GNULIB_TEST_FREXP
+
+/* Define to 1 when the gnulib module frexpl should be tested. */
+#undef GNULIB_TEST_FREXPL
+
+/* Define to 1 when the gnulib module fseek should be tested. */
+#undef GNULIB_TEST_FSEEK
+
+/* Define to 1 when the gnulib module fseeko should be tested. */
+#undef GNULIB_TEST_FSEEKO
+
+/* Define to 1 when the gnulib module fstat should be tested. */
+#undef GNULIB_TEST_FSTAT
+
+/* Define to 1 when the gnulib module fstatat should be tested. */
+#undef GNULIB_TEST_FSTATAT
+
+/* Define to 1 when the gnulib module fsync should be tested. */
+#undef GNULIB_TEST_FSYNC
+
+/* Define to 1 when the gnulib module ftell should be tested. */
+#undef GNULIB_TEST_FTELL
+
+/* Define to 1 when the gnulib module ftello should be tested. */
+#undef GNULIB_TEST_FTELLO
+
+/* Define to 1 when the gnulib module ftruncate should be tested. */
+#undef GNULIB_TEST_FTRUNCATE
+
+/* Define to 1 when the gnulib module futimens should be tested. */
+#undef GNULIB_TEST_FUTIMENS
+
+/* Define to 1 when the gnulib module getaddrinfo should be tested. */
+#undef GNULIB_TEST_GETADDRINFO
+
+/* Define to 1 when the gnulib module getcwd should be tested. */
+#undef GNULIB_TEST_GETCWD
+
+/* Define to 1 when the gnulib module getdelim should be tested. */
+#undef GNULIB_TEST_GETDELIM
+
+/* Define to 1 when the gnulib module getdtablesize should be tested. */
+#undef GNULIB_TEST_GETDTABLESIZE
+
+/* Define to 1 when the gnulib module getgroups should be tested. */
+#undef GNULIB_TEST_GETGROUPS
+
+/* Define to 1 when the gnulib module gethostname should be tested. */
+#undef GNULIB_TEST_GETHOSTNAME
+
+/* Define to 1 when the gnulib module getline should be tested. */
+#undef GNULIB_TEST_GETLINE
+
+/* Define to 1 when the gnulib module getloadavg should be tested. */
+#undef GNULIB_TEST_GETLOADAVG
+
+/* Define to 1 when the gnulib module getlogin should be tested. */
+#undef GNULIB_TEST_GETLOGIN
+
+/* Define to 1 when the gnulib module getopt-gnu should be tested. */
+#undef GNULIB_TEST_GETOPT_GNU
+
+/* Define to 1 when the gnulib module getpagesize should be tested. */
+#undef GNULIB_TEST_GETPAGESIZE
+
+/* Define to 1 when the gnulib module gettimeofday should be tested. */
+#undef GNULIB_TEST_GETTIMEOFDAY
+
+/* Define to 1 when the gnulib module getusershell should be tested. */
+#undef GNULIB_TEST_GETUSERSHELL
+
+/* Define to 1 when the gnulib module group-member should be tested. */
+#undef GNULIB_TEST_GROUP_MEMBER
+
+/* Define to 1 when the gnulib module ioctl should be tested. */
+#undef GNULIB_TEST_IOCTL
+
+/* Define to 1 when the gnulib module isatty should be tested. */
+#undef GNULIB_TEST_ISATTY
+
+/* Define to 1 when the gnulib module iswblank should be tested. */
+#undef GNULIB_TEST_ISWBLANK
+
+/* Define to 1 when the gnulib module lchmod should be tested. */
+#undef GNULIB_TEST_LCHMOD
+
+/* Define to 1 when the gnulib module lchown should be tested. */
+#undef GNULIB_TEST_LCHOWN
+
+/* Define to 1 when the gnulib module link should be tested. */
+#undef GNULIB_TEST_LINK
+
+/* Define to 1 when the gnulib module linkat should be tested. */
+#undef GNULIB_TEST_LINKAT
+
+/* Define to 1 when the gnulib module listen should be tested. */
+#undef GNULIB_TEST_LISTEN
+
+/* Define to 1 when the gnulib module localeconv should be tested. */
+#undef GNULIB_TEST_LOCALECONV
+
+/* Define to 1 when the gnulib module lseek should be tested. */
+#undef GNULIB_TEST_LSEEK
+
+/* Define to 1 when the gnulib module lstat should be tested. */
+#undef GNULIB_TEST_LSTAT
+
+/* Define to 1 when the gnulib module malloc-posix should be tested. */
+#undef GNULIB_TEST_MALLOC_POSIX
+
+/* Define to 1 when the gnulib module mbrlen should be tested. */
+#undef GNULIB_TEST_MBRLEN
+
+/* Define to 1 when the gnulib module mbrtowc should be tested. */
+#undef GNULIB_TEST_MBRTOWC
+
+/* Define to 1 when the gnulib module mbscasecmp should be tested. */
+#undef GNULIB_TEST_MBSCASECMP
+
+/* Define to 1 when the gnulib module mbsinit should be tested. */
+#undef GNULIB_TEST_MBSINIT
+
+/* Define to 1 when the gnulib module mbslen should be tested. */
+#undef GNULIB_TEST_MBSLEN
+
+/* Define to 1 when the gnulib module mbsrtowcs should be tested. */
+#undef GNULIB_TEST_MBSRTOWCS
+
+/* Define to 1 when the gnulib module mbsstr should be tested. */
+#undef GNULIB_TEST_MBSSTR
+
+/* Define to 1 when the gnulib module mbtowc should be tested. */
+#undef GNULIB_TEST_MBTOWC
+
+/* Define to 1 when the gnulib module memchr should be tested. */
+#undef GNULIB_TEST_MEMCHR
+
+/* Define to 1 when the gnulib module mempcpy should be tested. */
+#undef GNULIB_TEST_MEMPCPY
+
+/* Define to 1 when the gnulib module memrchr should be tested. */
+#undef GNULIB_TEST_MEMRCHR
+
+/* Define to 1 when the gnulib module mkfifo should be tested. */
+#undef GNULIB_TEST_MKFIFO
+
+/* Define to 1 when the gnulib module mknod should be tested. */
+#undef GNULIB_TEST_MKNOD
+
+/* Define to 1 when the gnulib module mkstemp should be tested. */
+#undef GNULIB_TEST_MKSTEMP
+
+/* Define to 1 when the gnulib module mktime should be tested. */
+#undef GNULIB_TEST_MKTIME
+
+/* Define to 1 when the gnulib module nanosleep should be tested. */
+#undef GNULIB_TEST_NANOSLEEP
-/* The concatenation of the strings `GNU ', and PACKAGE. */
-#undef GNU_PACKAGE
+/* Define to 1 when the gnulib module nl_langinfo should be tested. */
+#undef GNULIB_TEST_NL_LANGINFO
+
+/* Define to 1 when the gnulib module open should be tested. */
+#undef GNULIB_TEST_OPEN
+
+/* Define to 1 when the gnulib module openat should be tested. */
+#undef GNULIB_TEST_OPENAT
+
+/* Define to 1 when the gnulib module opendir should be tested. */
+#undef GNULIB_TEST_OPENDIR
+
+/* Define to 1 when the gnulib module perror should be tested. */
+#undef GNULIB_TEST_PERROR
+
+/* Define to 1 when the gnulib module pipe should be tested. */
+#undef GNULIB_TEST_PIPE
+
+/* Define to 1 when the gnulib module putenv should be tested. */
+#undef GNULIB_TEST_PUTENV
+
+/* Define to 1 when the gnulib module raise should be tested. */
+#undef GNULIB_TEST_RAISE
+
+/* Define to 1 when the gnulib module read should be tested. */
+#undef GNULIB_TEST_READ
+
+/* Define to 1 when the gnulib module readdir should be tested. */
+#undef GNULIB_TEST_READDIR
+
+/* Define to 1 when the gnulib module readlink should be tested. */
+#undef GNULIB_TEST_READLINK
+
+/* Define to 1 when the gnulib module readlinkat should be tested. */
+#undef GNULIB_TEST_READLINKAT
+
+/* Define to 1 when the gnulib module realloc-posix should be tested. */
+#undef GNULIB_TEST_REALLOC_POSIX
+
+/* Define to 1 when the gnulib module remove should be tested. */
+#undef GNULIB_TEST_REMOVE
+
+/* Define to 1 when the gnulib module rename should be tested. */
+#undef GNULIB_TEST_RENAME
+
+/* Define to 1 when the gnulib module rewinddir should be tested. */
+#undef GNULIB_TEST_REWINDDIR
+
+/* Define to 1 when the gnulib module rmdir should be tested. */
+#undef GNULIB_TEST_RMDIR
+
+/* Define to 1 when the gnulib module rpmatch should be tested. */
+#undef GNULIB_TEST_RPMATCH
+
+/* Define to 1 when the gnulib module secure_getenv should be tested. */
+#undef GNULIB_TEST_SECURE_GETENV
+
+/* Define to 1 when the gnulib module select should be tested. */
+#undef GNULIB_TEST_SELECT
+
+/* Define to 1 when the gnulib module setenv should be tested. */
+#undef GNULIB_TEST_SETENV
+
+/* Define to 1 when the gnulib module setlocale should be tested. */
+#undef GNULIB_TEST_SETLOCALE
+
+/* Define to 1 when the gnulib module setsockopt should be tested. */
+#undef GNULIB_TEST_SETSOCKOPT
+
+/* Define to 1 when the gnulib module sigaction should be tested. */
+#undef GNULIB_TEST_SIGACTION
+
+/* Define to 1 when the gnulib module signbit should be tested. */
+#undef GNULIB_TEST_SIGNBIT
+
+/* Define to 1 when the gnulib module sigprocmask should be tested. */
+#undef GNULIB_TEST_SIGPROCMASK
+
+/* Define to 1 when the gnulib module sleep should be tested. */
+#undef GNULIB_TEST_SLEEP
+
+/* Define to 1 when the gnulib module snprintf should be tested. */
+#undef GNULIB_TEST_SNPRINTF
+
+/* Define to 1 when the gnulib module socket should be tested. */
+#undef GNULIB_TEST_SOCKET
+
+/* Define to 1 when the gnulib module stat should be tested. */
+#undef GNULIB_TEST_STAT
+
+/* Define to 1 when the gnulib module stpcpy should be tested. */
+#undef GNULIB_TEST_STPCPY
+
+/* Define to 1 when the gnulib module stpncpy should be tested. */
+#undef GNULIB_TEST_STPNCPY
+
+/* Define to 1 when the gnulib module strdup should be tested. */
+#undef GNULIB_TEST_STRDUP
+
+/* Define to 1 when the gnulib module strerror should be tested. */
+#undef GNULIB_TEST_STRERROR
+
+/* Define to 1 when the gnulib module strerror_r should be tested. */
+#undef GNULIB_TEST_STRERROR_R
+
+/* Define to 1 when the gnulib module strncat should be tested. */
+#undef GNULIB_TEST_STRNCAT
+
+/* Define to 1 when the gnulib module strndup should be tested. */
+#undef GNULIB_TEST_STRNDUP
+
+/* Define to 1 when the gnulib module strnlen should be tested. */
+#undef GNULIB_TEST_STRNLEN
+
+/* Define to 1 when the gnulib module strpbrk should be tested. */
+#undef GNULIB_TEST_STRPBRK
+
+/* Define to 1 when the gnulib module strsignal should be tested. */
+#undef GNULIB_TEST_STRSIGNAL
+
+/* Define to 1 when the gnulib module strstr should be tested. */
+#undef GNULIB_TEST_STRSTR
+
+/* Define to 1 when the gnulib module strtod should be tested. */
+#undef GNULIB_TEST_STRTOD
+
+/* Define to 1 when the gnulib module strtoll should be tested. */
+#undef GNULIB_TEST_STRTOLL
+
+/* Define to 1 when the gnulib module strtoull should be tested. */
+#undef GNULIB_TEST_STRTOULL
+
+/* Define to 1 when the gnulib module symlink should be tested. */
+#undef GNULIB_TEST_SYMLINK
+
+/* Define to 1 when the gnulib module symlinkat should be tested. */
+#undef GNULIB_TEST_SYMLINKAT
+
+/* Define to 1 when the gnulib module timegm should be tested. */
+#undef GNULIB_TEST_TIMEGM
+
+/* Define to 1 when the gnulib module time_r should be tested. */
+#undef GNULIB_TEST_TIME_R
+
+/* Define to 1 when the gnulib module time_rz should be tested. */
+#undef GNULIB_TEST_TIME_RZ
+
+/* Define to 1 when the gnulib module unlink should be tested. */
+#undef GNULIB_TEST_UNLINK
+
+/* Define to 1 when the gnulib module unlinkat should be tested. */
+#undef GNULIB_TEST_UNLINKAT
+
+/* Define to 1 when the gnulib module unsetenv should be tested. */
+#undef GNULIB_TEST_UNSETENV
+
+/* Define to 1 when the gnulib module utimensat should be tested. */
+#undef GNULIB_TEST_UTIMENSAT
+
+/* Define to 1 when the gnulib module vasprintf should be tested. */
+#undef GNULIB_TEST_VASPRINTF
+
+/* Define to 1 when the gnulib module vfprintf-posix should be tested. */
+#undef GNULIB_TEST_VFPRINTF_POSIX
+
+/* Define to 1 when the gnulib module vprintf-posix should be tested. */
+#undef GNULIB_TEST_VPRINTF_POSIX
+
+/* Define to 1 when the gnulib module wcrtomb should be tested. */
+#undef GNULIB_TEST_WCRTOMB
+
+/* Define to 1 when the gnulib module wcswidth should be tested. */
+#undef GNULIB_TEST_WCSWIDTH
+
+/* Define to 1 when the gnulib module wctob should be tested. */
+#undef GNULIB_TEST_WCTOB
+
+/* Define to 1 when the gnulib module wctomb should be tested. */
+#undef GNULIB_TEST_WCTOMB
+
+/* Define to 1 when the gnulib module wcwidth should be tested. */
+#undef GNULIB_TEST_WCWIDTH
+
+/* Define to 1 when the gnulib module write should be tested. */
+#undef GNULIB_TEST_WRITE
+
+/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
+ whether the gnulib module unistr/u8-mbtoucr shall be considered present. */
+#undef GNULIB_UNISTR_U8_MBTOUCR
+
+/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
+ whether the gnulib module unistr/u8-uctomb shall be considered present. */
+#undef GNULIB_UNISTR_U8_UCTOMB
+
+/* Define to a C preprocessor expression that evaluates to 1 or 0, depending
+ whether the gnulib module xgetgroups shall be considered present. */
+#undef GNULIB_XGETGROUPS
/* Define if your system defines TIOCGWINSZ in sys/ioctl.h. */
#undef GWINSZ_IN_SYS_IOCTL
@@ -182,21 +760,48 @@
/* Define if your system defines TIOCGWINSZ in sys/pty.h. */
#undef GWINSZ_IN_SYS_PTY
-/* Define to 1 if you have the `acl' function. */
-#undef HAVE_ACL
+/* Define to 1 if you have the `access' function. */
+#undef HAVE_ACCESS
+
+/* Define to 1 if you have the `aclsort' function. */
+#undef HAVE_ACLSORT
+
+/* Define to 1 if you have the <aclv.h> header file. */
+#undef HAVE_ACLV_H
+
+/* Define to 1 if you have the `aclx_get' function. */
+#undef HAVE_ACLX_GET
+
+/* Define to 1 if you have the `acl_copy_ext_native' function. */
+#undef HAVE_ACL_COPY_EXT_NATIVE
+
+/* Define to 1 if you have the `acl_create_entry_np' function. */
+#undef HAVE_ACL_CREATE_ENTRY_NP
/* Define to 1 if you have the `acl_delete_def_file' function. */
#undef HAVE_ACL_DELETE_DEF_FILE
+/* Define to 1 if you have the `acl_delete_fd_np' function. */
+#undef HAVE_ACL_DELETE_FD_NP
+
+/* Define to 1 if you have the `acl_delete_file_np' function. */
+#undef HAVE_ACL_DELETE_FILE_NP
+
/* Define to 1 if you have the `acl_entries' function. */
#undef HAVE_ACL_ENTRIES
/* Define to 1 if you have the `acl_extended_file' function. */
#undef HAVE_ACL_EXTENDED_FILE
+/* Define to 1 if the constant ACL_FIRST_ENTRY exists. */
+#undef HAVE_ACL_FIRST_ENTRY
+
/* Define to 1 if you have the `acl_free' function. */
#undef HAVE_ACL_FREE
+/* Define to 1 if you have the `acl_free_text' function. */
+#undef HAVE_ACL_FREE_TEXT
+
/* Define to 1 if you have the `acl_from_mode' function. */
#undef HAVE_ACL_FROM_MODE
@@ -218,18 +823,21 @@
/* Define to 1 if you have the `acl_set_file' function. */
#undef HAVE_ACL_SET_FILE
+/* Define to 1 if you have the `acl_to_short_text' function. */
+#undef HAVE_ACL_TO_SHORT_TEXT
+
/* Define to 1 if you have the `acl_trivial' function. */
#undef HAVE_ACL_TRIVIAL
-/* Define to 1 if you have the `alarm' function. */
-#undef HAVE_ALARM
+/* Define to 1 if the ACL type ACL_TYPE_EXTENDED exists. */
+#undef HAVE_ACL_TYPE_EXTENDED
/* Define to 1 if you have 'alloca' after including <alloca.h>, a header that
may be supplied by this distribution. */
#undef HAVE_ALLOCA
-/* Define HAVE_ALLOCA_H for backward compatibility with older code that
- includes <alloca.h> only if HAVE_ALLOCA_H is defined. */
+/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
+ */
#undef HAVE_ALLOCA_H
/* Define if you have an arithmetic hrtime_t type. */
@@ -238,8 +846,14 @@
/* Define to 1 if you have the <arpa/inet.h> header file. */
#undef HAVE_ARPA_INET_H
-/* Define to 1 if you have the `atexit' function. */
-#undef HAVE_ATEXIT
+/* Define to 1 if you have the `attr_copy_file' function. */
+#undef HAVE_ATTR_COPY_FILE
+
+/* Define to 1 if you have the <attr/error_context.h> header file. */
+#undef HAVE_ATTR_ERROR_CONTEXT_H
+
+/* Define to 1 if you have the <attr/libattr.h> header file. */
+#undef HAVE_ATTR_LIBATTR_H
/* Define to 1 if you have the <bp-sym.h> header file. */
#undef HAVE_BP_SYM_H
@@ -247,28 +861,37 @@
/* Define to 1 if you have the `btowc' function. */
#undef HAVE_BTOWC
-/* Define to 1 if nanosleep mishandle large arguments. */
+/* Define to 1 if nanosleep mishandles large arguments. */
#undef HAVE_BUG_BIG_NANOSLEEP
/* Define to 1 if strtold conforms to C99. */
#undef HAVE_C99_STRTOLD
-/* Define to 1 if your system has a GNU libc compatible `calloc' function, and
+/* Define to 1 if your system has a GNU libc compatible 'calloc' function, and
to 0 otherwise. */
-#undef HAVE_CALLOC
+#undef HAVE_CALLOC_GNU
+
+/* Define if the 'calloc' function is POSIX compliant. */
+#undef HAVE_CALLOC_POSIX
/* Define to 1 if you have the `canonicalize_file_name' function. */
#undef HAVE_CANONICALIZE_FILE_NAME
-/* Define to 1 if you have the MacOS X function CFLocaleCopyCurrent in the
+/* libcap usability */
+#undef HAVE_CAP
+
+/* Define to 1 if you have the `catgets' function. */
+#undef HAVE_CATGETS
+
+/* Define to 1 if you have the Mac OS X function CFLocaleCopyCurrent in the
CoreFoundation framework. */
#undef HAVE_CFLOCALECOPYCURRENT
-/* Define to 1 if you have the MacOS X function CFPreferencesCopyAppValue in
+/* Define to 1 if you have the Mac OS X function CFPreferencesCopyAppValue in
the CoreFoundation framework. */
#undef HAVE_CFPREFERENCESCOPYAPPVALUE
-/* Define to 1 if your system has a working `chown' function. */
+/* Define to 1 if you have the `chown' function. */
#undef HAVE_CHOWN
/* Define to 1 if you have the `chroot' function. */
@@ -283,9 +906,24 @@
/* Define to 1 if you have the `clock_settime' function. */
#undef HAVE_CLOCK_SETTIME
+/* Define to 1 if you have the `closedir' function. */
+#undef HAVE_CLOSEDIR
+
/* Define if you have compound literals. */
#undef HAVE_COMPOUND_LITERALS
+/* Define if the copysignf function is declared in <math.h> and available in
+ libc. */
+#undef HAVE_COPYSIGNF_IN_LIBC
+
+/* Define if the copysignl function is declared in <math.h> and available in
+ libc. */
+#undef HAVE_COPYSIGNL_IN_LIBC
+
+/* Define if the copysign function is declared in <math.h> and available in
+ libc. */
+#undef HAVE_COPYSIGN_IN_LIBC
+
/* FIXME */
#undef HAVE_C_LINE
@@ -293,21 +931,41 @@
*/
#undef HAVE_DCGETTEXT
-/* Define to 1 if you have the declaration of `canonicalize_file_name', and to
- 0 if you don't. */
-#undef HAVE_DECL_CANONICALIZE_FILE_NAME
+/* Define to 1 if you have the declaration of `alarm', and to 0 if you don't.
+ */
+#undef HAVE_DECL_ALARM
/* Define to 1 if you have the declaration of `clearerr_unlocked', and to 0 if
you don't. */
#undef HAVE_DECL_CLEARERR_UNLOCKED
+/* Define to 1 if you have the declaration of `copysign', and to 0 if you
+ don't. */
+#undef HAVE_DECL_COPYSIGN
+
+/* Define to 1 if you have the declaration of `copysignf', and to 0 if you
+ don't. */
+#undef HAVE_DECL_COPYSIGNF
+
+/* Define to 1 if you have the declaration of `copysignl', and to 0 if you
+ don't. */
+#undef HAVE_DECL_COPYSIGNL
+
/* Define to 1 if you have the declaration of `dirfd', and to 0 if you don't.
*/
#undef HAVE_DECL_DIRFD
-/* Define to 1 if you have the declaration of `euidaccess', and to 0 if you
+/* Define to 1 if you have the declaration of `fchdir', and to 0 if you don't.
+ */
+#undef HAVE_DECL_FCHDIR
+
+/* Define to 1 if you have the declaration of `fdatasync', and to 0 if you
don't. */
-#undef HAVE_DECL_EUIDACCESS
+#undef HAVE_DECL_FDATASYNC
+
+/* Define to 1 if you have the declaration of `fdopendir', and to 0 if you
+ don't. */
+#undef HAVE_DECL_FDOPENDIR
/* Define to 1 if you have the declaration of `feof_unlocked', and to 0 if you
don't. */
@@ -329,6 +987,10 @@
don't. */
#undef HAVE_DECL_FLOCKFILE
+/* Define to 1 if you have the declaration of `fpurge', and to 0 if you don't.
+ */
+#undef HAVE_DECL_FPURGE
+
/* Define to 1 if you have the declaration of `fputc_unlocked', and to 0 if
you don't. */
#undef HAVE_DECL_FPUTC_UNLOCKED
@@ -341,14 +1003,18 @@
you don't. */
#undef HAVE_DECL_FREAD_UNLOCKED
-/* Define to 1 if you have the declaration of `free', and to 0 if you don't.
- */
-#undef HAVE_DECL_FREE
-
/* Define to 1 if you have the declaration of `freeaddrinfo', and to 0 if you
don't. */
#undef HAVE_DECL_FREEADDRINFO
+/* Define to 1 if you have the declaration of `fseeko', and to 0 if you don't.
+ */
+#undef HAVE_DECL_FSEEKO
+
+/* Define to 1 if you have the declaration of `ftello', and to 0 if you don't.
+ */
+#undef HAVE_DECL_FTELLO
+
/* Define to 1 if you have the declaration of `funlockfile', and to 0 if you
don't. */
#undef HAVE_DECL_FUNLOCKFILE
@@ -361,6 +1027,10 @@
don't. */
#undef HAVE_DECL_GAI_STRERROR
+/* Define to 1 if you have the declaration of `gai_strerrorA', and to 0 if you
+ don't. */
+#undef HAVE_DECL_GAI_STRERRORA
+
/* Define to 1 if you have the declaration of `getaddrinfo', and to 0 if you
don't. */
#undef HAVE_DECL_GETADDRINFO
@@ -381,6 +1051,10 @@
don't. */
#undef HAVE_DECL_GETDELIM
+/* Define to 1 if you have the declaration of `getdtablesize', and to 0 if you
+ don't. */
+#undef HAVE_DECL_GETDTABLESIZE
+
/* Define to 1 if you have the declaration of `getenv', and to 0 if you don't.
*/
#undef HAVE_DECL_GETENV
@@ -421,53 +1095,69 @@
*/
#undef HAVE_DECL_GETUID
-/* Define to 1 if you have the declaration of `getutent', and to 0 if you
- don't. */
-#undef HAVE_DECL_GETUTENT
-
-/* Define to 1 if you have the declaration of `imaxabs', and to 0 if you
+/* Define to 1 if you have the declaration of `getusershell', and to 0 if you
don't. */
-#undef HAVE_DECL_IMAXABS
+#undef HAVE_DECL_GETUSERSHELL
-/* Define to 1 if you have the declaration of `imaxdiv', and to 0 if you
+/* Define to 1 if you have the declaration of `getutent', and to 0 if you
don't. */
-#undef HAVE_DECL_IMAXDIV
+#undef HAVE_DECL_GETUTENT
/* Define to 1 if you have the declaration of `inet_ntop', and to 0 if you
don't. */
#undef HAVE_DECL_INET_NTOP
+/* Define to 1 if you have the declaration of `inet_pton', and to 0 if you
+ don't. */
+#undef HAVE_DECL_INET_PTON
+
/* Define to 1 if you have the declaration of `isblank', and to 0 if you
don't. */
#undef HAVE_DECL_ISBLANK
-/* Define to 1 if you have the declaration of `lchown', and to 0 if you don't.
- */
-#undef HAVE_DECL_LCHOWN
+/* Define to 1 if you have the declaration of `iswblank', and to 0 if you
+ don't. */
+#undef HAVE_DECL_ISWBLANK
-/* Define to 1 if you have the declaration of `lseek', and to 0 if you don't.
- */
-#undef HAVE_DECL_LSEEK
+/* Define to 1 if you have the declaration of `localtime_r', and to 0 if you
+ don't. */
+#undef HAVE_DECL_LOCALTIME_R
-/* Define to 1 if you have the declaration of `malloc', and to 0 if you don't.
+/* Define to 1 if you have the declaration of `mbrlen', and to 0 if you don't.
*/
-#undef HAVE_DECL_MALLOC
+#undef HAVE_DECL_MBRLEN
+
+/* Define to 1 if you have the declaration of `mbrtowc', and to 0 if you
+ don't. */
+#undef HAVE_DECL_MBRTOWC
+
+/* Define to 1 if you have the declaration of `mbsinit', and to 0 if you
+ don't. */
+#undef HAVE_DECL_MBSINIT
+
+/* Define to 1 if you have the declaration of `mbsrtowcs', and to 0 if you
+ don't. */
+#undef HAVE_DECL_MBSRTOWCS
/* Define to 1 if you have a declaration of mbswidth() in <wchar.h>, and to 0
otherwise. */
#undef HAVE_DECL_MBSWIDTH_IN_WCHAR_H
-/* Define to 1 if you have the declaration of `memchr', and to 0 if you don't.
- */
-#undef HAVE_DECL_MEMCHR
-
/* Define to 1 if you have the declaration of `memrchr', and to 0 if you
don't. */
#undef HAVE_DECL_MEMRCHR
-/* Define to 1 if you have the declaration of `mkdir', and to 0 if you don't.
- */
-#undef HAVE_DECL_MKDIR
+/* Define to 1 if you have the declaration of `mpz_inits', and to 0 if you
+ don't. */
+#undef HAVE_DECL_MPZ_INITS
+
+/* Define to 1 if you have the declaration of `program_invocation_name', and
+ to 0 if you don't. */
+#undef HAVE_DECL_PROGRAM_INVOCATION_NAME
+
+/* Define to 1 if you have the declaration of `program_invocation_short_name',
+ and to 0 if you don't. */
+#undef HAVE_DECL_PROGRAM_INVOCATION_SHORT_NAME
/* Define to 1 if you have the declaration of `putchar_unlocked', and to 0 if
you don't. */
@@ -477,18 +1167,26 @@
don't. */
#undef HAVE_DECL_PUTC_UNLOCKED
-/* Define to 1 if you have the declaration of `realloc', and to 0 if you
- don't. */
-#undef HAVE_DECL_REALLOC
+/* Define to 1 if you have the declaration of `setenv', and to 0 if you don't.
+ */
+#undef HAVE_DECL_SETENV
/* Define to 1 if you have the declaration of `setregid', and to 0 if you
don't. */
#undef HAVE_DECL_SETREGID
+/* Define to 1 if you have the declaration of `sleep', and to 0 if you don't.
+ */
+#undef HAVE_DECL_SLEEP
+
/* Define to 1 if you have the declaration of `snprintf', and to 0 if you
don't. */
#undef HAVE_DECL_SNPRINTF
+/* Define to 1 if you have the declaration of `stpncpy', and to 0 if you
+ don't. */
+#undef HAVE_DECL_STPNCPY
+
/* Define to 1 if you have the declaration of `strdup', and to 0 if you don't.
*/
#undef HAVE_DECL_STRDUP
@@ -533,6 +1231,10 @@
don't. */
#undef HAVE_DECL_SYS_SIGLIST
+/* Define to 1 if you have the declaration of `towlower', and to 0 if you
+ don't. */
+#undef HAVE_DECL_TOWLOWER
+
/* Define to 1 if you have the declaration of `ttyname', and to 0 if you
don't. */
#undef HAVE_DECL_TTYNAME
@@ -541,10 +1243,30 @@
*/
#undef HAVE_DECL_TZNAME
+/* Define to 1 if you have the declaration of `unsetenv', and to 0 if you
+ don't. */
+#undef HAVE_DECL_UNSETENV
+
+/* Define to 1 if you have the declaration of `wcrtomb', and to 0 if you
+ don't. */
+#undef HAVE_DECL_WCRTOMB
+
+/* Define to 1 if you have the declaration of `wctob', and to 0 if you don't.
+ */
+#undef HAVE_DECL_WCTOB
+
/* Define to 1 if you have the declaration of `wcwidth', and to 0 if you
don't. */
#undef HAVE_DECL_WCWIDTH
+/* Define to 1 if you have the declaration of `_putenv', and to 0 if you
+ don't. */
+#undef HAVE_DECL__PUTENV
+
+/* Define to 1 if you have the declaration of `_snprintf', and to 0 if you
+ don't. */
+#undef HAVE_DECL__SNPRINTF
+
/* Define to 1 if you have the declaration of `_sys_siglist', and to 0 if you
don't. */
#undef HAVE_DECL__SYS_SIGLIST
@@ -570,7 +1292,7 @@
/* Define to 1 if you have the `dirfd' function. */
#undef HAVE_DIRFD
-/* Define to 1 if you have the `dup2' function. */
+/* Define to 1 if you have the 'dup2' function. */
#undef HAVE_DUP2
/* Define to 1 if you have the <dustat.h> header file. */
@@ -591,6 +1313,15 @@
/* Define to 1 if you have the `euidaccess' function. */
#undef HAVE_EUIDACCESS
+/* Define to 1 if you have the `faccessat' function. */
+#undef HAVE_FACCESSAT
+
+/* Define to 1 if you have the `facl' function. */
+#undef HAVE_FACL
+
+/* Define to 1 if you have the `fallocate' function. */
+#undef HAVE_FALLOCATE
+
/* Define to 1 if you have the `fchdir' function. */
#undef HAVE_FCHDIR
@@ -603,8 +1334,8 @@
/* Define to 1 if you have the `fchown' function. */
#undef HAVE_FCHOWN
-/* Define to 1 if you have the <fcntl.h> header file. */
-#undef HAVE_FCNTL_H
+/* Define to 1 if you have the `fcntl' function. */
+#undef HAVE_FCNTL
/* Define to 1 if you have the `fdatasync' function. */
#undef HAVE_FDATASYNC
@@ -612,6 +1343,9 @@
/* Define to 1 if you have the `fdopendir' function. */
#undef HAVE_FDOPENDIR
+/* Define to 1 if you have the <features.h> header file. */
+#undef HAVE_FEATURES_H
+
/* Define to 1 if pipes are FIFOs, 0 if sockets. Leave undefined if not known.
*/
#undef HAVE_FIFO_PIPES
@@ -622,9 +1356,30 @@
/* Define to 1 if you have the `fork' function. */
#undef HAVE_FORK
+/* whether fpsetprec is present and required */
+#undef HAVE_FPSETPREC
+
+/* Define to 1 if you have the `fpurge' function. */
+#undef HAVE_FPURGE
+
+/* Define if the frexpl function is available in libc. */
+#undef HAVE_FREXPL_IN_LIBC
+
+/* Define if the frexp function is available in libc. */
+#undef HAVE_FREXP_IN_LIBC
+
/* Define to 1 if fseeko (and presumably ftello) exists and is declared. */
#undef HAVE_FSEEKO
+/* Define to 1 if you have the `fstatat' function. */
+#undef HAVE_FSTATAT
+
+/* Define to 1 if you have the `fstatfs' function. */
+#undef HAVE_FSTATFS
+
+/* Define to 1 if you have the `fsync' function. */
+#undef HAVE_FSYNC
+
/* Define to 1 if you have the <fs_info.h> header file. */
#undef HAVE_FS_INFO_H
@@ -637,21 +1392,46 @@
/* Define to 1 if you have the `funlockfile' function. */
#undef HAVE_FUNLOCKFILE
+/* Define to 1 if you have the `futimens' function. */
+#undef HAVE_FUTIMENS
+
/* Define to 1 if you have the `futimes' function. */
#undef HAVE_FUTIMES
/* Define to 1 if you have the `futimesat' function. */
#undef HAVE_FUTIMESAT
-/* Define to 1 if you have the `gai_strerror' function. */
-#undef HAVE_GAI_STRERROR
+/* Define to 1 if you have the `getacl' function. */
+#undef HAVE_GETACL
+
+/* Define to 1 if you have the `getattrat' function. */
+#undef HAVE_GETATTRAT
-/* Define to 1 if you have the `getaddrinfo' function. */
-#undef HAVE_GETADDRINFO
+/* Define to 1 if getcwd works, but with shorter paths than is generally
+ tested with the replacement. */
+#undef HAVE_GETCWD_SHORTER
/* Define to 1 if you have the `getdelim' function. */
#undef HAVE_GETDELIM
+/* Define to 1 if you have the `getdtablesize' function. */
+#undef HAVE_GETDTABLESIZE
+
+/* Define to 1 if you have the `getegid' function. */
+#undef HAVE_GETEGID
+
+/* Define to 1 if you have the `getgrent_nomembers' function. */
+#undef HAVE_GETGRENT_NOMEMBERS
+
+/* Define to 1 if you have the `getgrgid_nomembers' function. */
+#undef HAVE_GETGRGID_NOMEMBERS
+
+/* Define to 1 if you have the `getgrnam_nomembers' function. */
+#undef HAVE_GETGRNAM_NOMEMBERS
+
+/* Define to 1 if you have the `getgrouplist' function. */
+#undef HAVE_GETGROUPLIST
+
/* Define to 1 if your system has a working `getgroups' function. */
#undef HAVE_GETGROUPS
@@ -664,8 +1444,11 @@
/* Define to 1 if you have the `gethostname' function. */
#undef HAVE_GETHOSTNAME
-/* Define to 1 if you have the `getloadavg' function. */
-#undef HAVE_GETLOADAVG
+/* Define to 1 if you have the `getlocalename_l' function. */
+#undef HAVE_GETLOCALENAME_L
+
+/* Define to 1 if you have the `getlogin' function. */
+#undef HAVE_GETLOGIN
/* Define to 1 if you have the `getmntent' function. */
#undef HAVE_GETMNTENT
@@ -682,8 +1465,11 @@
/* Define to 1 if you have the `getpagesize' function. */
#undef HAVE_GETPAGESIZE
-/* Define to 1 if you have the `getspnam' function. */
-#undef HAVE_GETSPNAM
+/* Define to 1 if you have the `getppriv' function. */
+#undef HAVE_GETPPRIV
+
+/* Define to 1 if you have the `getservbyname' function. */
+#undef HAVE_GETSERVBYNAME
/* Define to 1 if you have the `getsysinfo' function. */
#undef HAVE_GETSYSINFO
@@ -697,6 +1483,12 @@
/* Define to 1 if you have the `getusershell' function. */
#undef HAVE_GETUSERSHELL
+/* Define if you have GNU libgmp (or replacement) */
+#undef HAVE_GMP
+
+/* Define to 1 if you have the <gmp.h> header file. */
+#undef HAVE_GMP_H
+
/* Define to 1 if you have the <grp.h> header file. */
#undef HAVE_GRP_H
@@ -706,12 +1498,18 @@
/* Define to 1 if you have the <hurd.h> header file. */
#undef HAVE_HURD_H
-/* Define if you have the iconv() function. */
+/* Define if you have the iconv() function and it works. */
#undef HAVE_ICONV
+/* Define to 1 if you have the <iconv.h> header file. */
+#undef HAVE_ICONV_H
+
/* Define to 1 if you have the `inet_ntop' function. */
#undef HAVE_INET_NTOP
+/* Define to 1 if you have the `inet_pton' function. */
+#undef HAVE_INET_PTON
+
/* Define to 1 if you have the `initgroups' function. */
#undef HAVE_INITGROUPS
@@ -720,6 +1518,12 @@
*/
#undef HAVE_INLINE
+/* Define to 1 if you have usable inotify support. */
+#undef HAVE_INOTIFY
+
+/* Define to 1 if you have the `inotify_init' function. */
+#undef HAVE_INOTIFY_INIT
+
/* Define if you have the 'intmax_t' type in <stdint.h> or <inttypes.h>. */
#undef HAVE_INTMAX_T
@@ -730,8 +1534,8 @@
declares uintmax_t. */
#undef HAVE_INTTYPES_H_WITH_UINTMAX
-/* Define to 1 if you have the <io.h> header file. */
-#undef HAVE_IO_H
+/* Define to 1 if you have the `ioctl' function. */
+#undef HAVE_IOCTL
/* Define to 1 if <sys/socket.h> defines AF_INET. */
#undef HAVE_IPV4
@@ -745,6 +1549,24 @@
/* Define to 1 if you have the `isascii' function. */
#undef HAVE_ISASCII
+/* Define to 1 if you have the `isblank' function. */
+#undef HAVE_ISBLANK
+
+/* Define if the isnan(double) function is available in libc. */
+#undef HAVE_ISNAND_IN_LIBC
+
+/* Define if the isnan(float) function is available in libc. */
+#undef HAVE_ISNANF_IN_LIBC
+
+/* Define if the isnan(long double) function is available in libc. */
+#undef HAVE_ISNANL_IN_LIBC
+
+/* Define to 1 if you have the `issetugid' function. */
+#undef HAVE_ISSETUGID
+
+/* Define to 1 if you have the `iswblank' function. */
+#undef HAVE_ISWBLANK
+
/* Define to 1 if you have the `iswcntrl' function. */
#undef HAVE_ISWCNTRL
@@ -757,59 +1579,71 @@
/* Define if you have <langinfo.h> and nl_langinfo(CODESET). */
#undef HAVE_LANGINFO_CODESET
+/* Define to 1 if you have the <langinfo.h> header file. */
+#undef HAVE_LANGINFO_H
+
+/* Define if you have <langinfo.h> and nl_langinfo(YESEXPR). */
+#undef HAVE_LANGINFO_YESEXPR
+
/* Define to 1 if you have the `lchmod' function. */
#undef HAVE_LCHMOD
/* Define to 1 if you have the `lchown' function. */
#undef HAVE_LCHOWN
+/* Define if your <locale.h> file defines LC_MESSAGES. */
+#undef HAVE_LC_MESSAGES
+
+/* Define if the ldexpl function is available in libc. */
+#undef HAVE_LDEXPL_IN_LIBC
+
+/* Define if the ldexp function is available in libc. */
+#undef HAVE_LDEXP_IN_LIBC
+
/* Define to 1 if you have the `dgc' library (-ldgc). */
#undef HAVE_LIBDGC
/* Define to 1 if you have the <libgen.h> header file. */
#undef HAVE_LIBGEN_H
+/* Define to 1 if you have the <libintl.h> header file. */
+#undef HAVE_LIBINTL_H
+
/* Define to 1 if you have the `kstat' library (-lkstat). */
#undef HAVE_LIBKSTAT
-/* Define to 1 if you have the `ldgc' library (-lldgc). */
-#undef HAVE_LIBLDGC
-
/* Define to 1 if you have the `os' library (-los). */
#undef HAVE_LIBOS
-/* Define to 1 if you have the `ypsec' library (-lypsec). */
-#undef HAVE_LIBYPSEC
+/* Define to 1 if you have the `perfstat' library (-lperfstat). */
+#undef HAVE_LIBPERFSTAT
-/* Define to 1 if you have the `listmntent' function. */
-#undef HAVE_LISTMNTENT
+/* Define to 1 if you have the `link' function. */
+#undef HAVE_LINK
+
+/* Define to 1 if you have the `linkat' function. */
+#undef HAVE_LINKAT
-/* Define to 1 if you have the <locale.h> header file. */
-#undef HAVE_LOCALE_H
+/* Define to 1 if you have the <linux/falloc.h> header file. */
+#undef HAVE_LINUX_FALLOC_H
-/* Define to 1 if the type `long double' works and has more range or precision
- than `double'. */
-#undef HAVE_LONG_DOUBLE
+/* Define to 1 if you have the `listmntent' function. */
+#undef HAVE_LISTMNTENT
-/* Define to 1 if the type `long double' works and has more range or precision
- than `double'. */
-#undef HAVE_LONG_DOUBLE_WIDER
+/* Define to 1 if you have the `localtime_r' function. */
+#undef HAVE_LOCALTIME_R
/* Define to 1 if you support file names longer than 14 characters. */
#undef HAVE_LONG_FILE_NAMES
-/* Define if you have the 'long long' type. */
-#undef HAVE_LONG_LONG
-
-/* Define to 1 if the system has the type `long long int'. */
+/* Define to 1 if the system has the type 'long long int'. */
#undef HAVE_LONG_LONG_INT
/* Define to 1 if you have the `lstat' function. */
#undef HAVE_LSTAT
-/* Define to 1 if `lstat' has the bug that it succeeds when given the
- zero-length file name argument. */
-#undef HAVE_LSTAT_EMPTY_STRING_BUG
+/* Define to 1 if you have the `lutimes' function. */
+#undef HAVE_LUTIMES
/* Define to 1 if you have the <machine/hal_sysinfo.h> header file. */
#undef HAVE_MACHINE_HAL_SYSINFO_H
@@ -817,12 +1651,25 @@
/* Define to 1 if you have the <mach/mach.h> header file. */
#undef HAVE_MACH_MACH_H
-/* Define to 1 if your system has a GNU libc compatible `malloc' function, and
+/* Define to 1 if your system has a GNU libc compatible 'malloc' function, and
to 0 otherwise. */
-#undef HAVE_MALLOC
+#undef HAVE_MALLOC_GNU
+
+/* Define to 1 if you have the <malloc.h> header file. */
+#undef HAVE_MALLOC_H
+
+/* Define if the 'malloc' function is POSIX compliant. */
+#undef HAVE_MALLOC_POSIX
+
+/* Define to 1 if mmap()'s MAP_ANONYMOUS flag is available after including
+ config.h and <sys/mman.h>. */
+#undef HAVE_MAP_ANONYMOUS
+
+/* Define to 1 if you have the `matchpathcon_init_prefix' function. */
+#undef HAVE_MATCHPATHCON_INIT_PREFIX
-/* Define to 1 if you have the `mblen' function. */
-#undef HAVE_MBLEN
+/* Define to 1 if you have the <math.h> header file. */
+#undef HAVE_MATH_H
/* Define to 1 if you have the `mbrlen' function. */
#undef HAVE_MBRLEN
@@ -833,21 +1680,15 @@
/* Define to 1 if you have the `mbsinit' function. */
#undef HAVE_MBSINIT
+/* Define to 1 if you have the `mbslen' function. */
+#undef HAVE_MBSLEN
+
/* Define to 1 if you have the `mbsrtowcs' function. */
#undef HAVE_MBSRTOWCS
/* Define to 1 if <wchar.h> declares mbstate_t. */
#undef HAVE_MBSTATE_T
-/* Define to 1 if you have the `memchr' function. */
-#undef HAVE_MEMCHR
-
-/* Define to 1 if you have the `memcpy' function. */
-#undef HAVE_MEMCPY
-
-/* Define to 1 if you have the `memmove' function. */
-#undef HAVE_MEMMOVE
-
/* Define to 1 if you have the <memory.h> header file. */
#undef HAVE_MEMORY_H
@@ -857,21 +1698,35 @@
/* Define to 1 if you have the `memrchr' function. */
#undef HAVE_MEMRCHR
-/* Define to 1 if you have the `memset' function. */
-#undef HAVE_MEMSET
-
/* Define to 1 if you have the `microuptime' function. */
#undef HAVE_MICROUPTIME
-/* Define to 1 if you have the `mkdirat' function. */
-#undef HAVE_MKDIRAT
+/* Define to 1 if getcwd minimally works, that is, its result can be trusted
+ when it succeeds. */
+#undef HAVE_MINIMALLY_WORKING_GETCWD
/* Define to 1 if you have the `mkfifo' function. */
#undef HAVE_MKFIFO
+/* Define to 1 if you have the `mknod' function. */
+#undef HAVE_MKNOD
+
+/* Define to 1 if you have the `mkstemp' function. */
+#undef HAVE_MKSTEMP
+
/* Define to 1 if you have the <mntent.h> header file. */
#undef HAVE_MNTENT_H
+/* Define to 1 if you have the `mode_to_security_class' function. */
+#undef HAVE_MODE_TO_SECURITY_CLASS
+
+/* Define to 1 if you have the `mprotect' function. */
+#undef HAVE_MPROTECT
+
+/* Define to 1 on MSVC platforms that have the "invalid parameter handler"
+ concept. */
+#undef HAVE_MSVC_INVALID_PARAMETER_HANDLER
+
/* Define to 1 if you have the `nanotime' function. */
#undef HAVE_NANOTIME
@@ -884,6 +1739,9 @@
/* Define to 1 if you have the <netinet/in.h> header file. */
#undef HAVE_NETINET_IN_H
+/* Define to 1 if you have the `newlocale' function. */
+#undef HAVE_NEWLOCALE
+
/* Define to 1 if you have the `next_dev' function. */
#undef HAVE_NEXT_DEV
@@ -899,19 +1757,35 @@
/* Define to 1 if you have the <nlist.h> header file. */
#undef HAVE_NLIST_H
-/* Define to 1 if libc includes obstacks. */
+/* Define to 1 if you have the `nl_langinfo' function. */
+#undef HAVE_NL_LANGINFO
+
+/* Define to 1 if the system has obstacks that work with any size object. */
#undef HAVE_OBSTACK
/* Define to 1 if you have the `openat' function. */
#undef HAVE_OPENAT
+/* Define to 1 if you have the `opendir' function. */
+#undef HAVE_OPENDIR
+
+/* Define to 1 if libcrypto is used for MD5. */
+#undef HAVE_OPENSSL_MD5
+
+/* Define to 1 if libcrypto is used for SHA1. */
+#undef HAVE_OPENSSL_SHA1
+
+/* Define to 1 if libcrypto is used for SHA256. */
+#undef HAVE_OPENSSL_SHA256
+
+/* Define to 1 if libcrypto is used for SHA512. */
+#undef HAVE_OPENSSL_SHA512
+
/* Define to 1 if you have the <OS.h> header file. */
#undef HAVE_OS_H
/* Define to 1 if getcwd works, except it sometimes fails when it shouldn't,
- setting errno to ERANGE, ENAMETOOLONG, or ENOENT. If __GETCWD_PREFIX is not
- defined, it doesn't matter whether HAVE_PARTLY_WORKING_GETCWD is defined.
- */
+ setting errno to ERANGE, ENAMETOOLONG, or ENOENT. */
#undef HAVE_PARTLY_WORKING_GETCWD
/* Define to 1 if you have the `pathconf' function. */
@@ -923,6 +1797,12 @@
/* Define to 1 if you have the `pipe' function. */
#undef HAVE_PIPE
+/* Define to 1 if you have the `posix_fadvise' function. */
+#undef HAVE_POSIX_FADVISE
+
+/* Define to 1 if you have the `prctl' function. */
+#undef HAVE_PRCTL
+
/* Define to 1 if you have the <priv.h> header file. */
#undef HAVE_PRIV_H
@@ -935,8 +1815,23 @@
/* Define to 1 if you have the `pstat_getstatic' function. */
#undef HAVE_PSTAT_GETSTATIC
-/* Define to 1 if the system has the type `ptrdiff_t'. */
-#undef HAVE_PTRDIFF_T
+/* Define to 1 if you have the `pthread_atfork' function. */
+#undef HAVE_PTHREAD_ATFORK
+
+/* Define to 1 if you have the <pthread.h> header file. */
+#undef HAVE_PTHREAD_H
+
+/* Define if the <pthread.h> defines PTHREAD_MUTEX_RECURSIVE. */
+#undef HAVE_PTHREAD_MUTEX_RECURSIVE
+
+/* Define if the POSIX multithreading library has read/write locks. */
+#undef HAVE_PTHREAD_RWLOCK
+
+/* Define to 1 if the system has the type `pthread_spinlock_t'. */
+#undef HAVE_PTHREAD_SPINLOCK_T
+
+/* Define to 1 if the system has the type `pthread_t'. */
+#undef HAVE_PTHREAD_T
/* Define to 1 if you have the <pwd.h> header file. */
#undef HAVE_PWD_H
@@ -944,18 +1839,27 @@
/* Define to 1 if you have the `raise' function. */
#undef HAVE_RAISE
+/* Define to 1 if you have the `readdir' function. */
+#undef HAVE_READDIR
+
/* Define to 1 if you have the `readlink' function. */
#undef HAVE_READLINK
-/* Define to 1 if your system has a GNU libc compatible `realloc' function,
+/* Define to 1 if you have the `readlinkat' function. */
+#undef HAVE_READLINKAT
+
+/* Define to 1 if your system has a GNU libc compatible 'realloc' function,
and to 0 otherwise. */
-#undef HAVE_REALLOC
+#undef HAVE_REALLOC_GNU
-/* Define to 1 if you have the `resolvepath' function. */
-#undef HAVE_RESOLVEPATH
+/* Define if the 'realloc' function is POSIX compliant. */
+#undef HAVE_REALLOC_POSIX
-/* Define to 1 if you have the `rmdir' function. */
-#undef HAVE_RMDIR
+/* Define to 1 if you have the `realpath' function. */
+#undef HAVE_REALPATH
+
+/* Define to 1 if you have the `rewinddir' function. */
+#undef HAVE_REWINDDIR
/* Define to 1 if you have the `rpmatch' function. */
#undef HAVE_RPMATCH
@@ -963,9 +1867,42 @@
/* Define to 1 if you have run the test for working tzset. */
#undef HAVE_RUN_TZSET_TEST
+/* Define to 1 if 'long double' and 'double' have the same representation. */
+#undef HAVE_SAME_LONG_DOUBLE_AS_DOUBLE
+
+/* Define to 1 if the system has the type `sa_family_t'. */
+#undef HAVE_SA_FAMILY_T
+
+/* Define to 1 if you have the `sched_getaffinity' function. */
+#undef HAVE_SCHED_GETAFFINITY
+
+/* Define to 1 if sched_getaffinity has a glibc compatible declaration. */
+#undef HAVE_SCHED_GETAFFINITY_LIKE_GLIBC
+
+/* Define to 1 if you have the `sched_getaffinity_np' function. */
+#undef HAVE_SCHED_GETAFFINITY_NP
+
+/* Define to 1 if you have the <sched.h> header file. */
+#undef HAVE_SCHED_H
+
/* Define to 1 if you have the <search.h> header file. */
#undef HAVE_SEARCH_H
+/* Define to 1 if you have the `secure_getenv' function. */
+#undef HAVE_SECURE_GETENV
+
+/* Define to 1 if you have the <selinux/context.h> header file. */
+#undef HAVE_SELINUX_CONTEXT_H
+
+/* Define to 1 if you have the <selinux/flask.h> header file. */
+#undef HAVE_SELINUX_FLASK_H
+
+/* Define to 1 if you have the <selinux/selinux.h> header file. */
+#undef HAVE_SELINUX_SELINUX_H
+
+/* Define to 1 if you have the `setdtablesize' function. */
+#undef HAVE_SETDTABLESIZE
+
/* Define to 1 if you have the `setenv' function. */
#undef HAVE_SETENV
@@ -975,15 +1912,30 @@
/* Define to 1 if you have the `sethostname' function. */
#undef HAVE_SETHOSTNAME
+/* Define to 1 if you have the `setlocale' function. */
+#undef HAVE_SETLOCALE
+
+/* Define to 1 if you have the `setrlimit' function. */
+#undef HAVE_SETRLIMIT
+
/* Define to 1 if you have the `settimeofday' function. */
#undef HAVE_SETTIMEOFDAY
-/* Define to 1 if you have the <shadow.h> header file. */
-#undef HAVE_SHADOW_H
+/* Define to 1 if you have the `shutdown' function. */
+#undef HAVE_SHUTDOWN
/* Define to 1 if you have the `sig2str' function. */
#undef HAVE_SIG2STR
+/* Define to 1 if you have the `sigaction' function. */
+#undef HAVE_SIGACTION
+
+/* Define to 1 if you have the `sigaltstack' function. */
+#undef HAVE_SIGALTSTACK
+
+/* Define to 1 if the system has the type `siginfo_t'. */
+#undef HAVE_SIGINFO_T
+
/* Define to 1 if you have the `siginterrupt' function. */
#undef HAVE_SIGINTERRUPT
@@ -996,11 +1948,28 @@
/* Define to 1 if 'wint_t' is a signed integer type. */
#undef HAVE_SIGNED_WINT_T
+/* Define to 1 if the system has the type `sigset_t'. */
+#undef HAVE_SIGSET_T
+
+/* Define to 1 if you have the `sleep' function. */
+#undef HAVE_SLEEP
+
+/* libsmack usability */
+#undef HAVE_SMACK
+
/* Define to 1 if you have the `snprintf' function. */
#undef HAVE_SNPRINTF
-/* Define to 1 if stdbool.h conforms to C99. */
-#undef HAVE_STDBOOL_H
+/* Define if the return value of the snprintf function is the number of of
+ bytes (excluding the terminating NUL) that would have been produced if the
+ buffer had been large enough. */
+#undef HAVE_SNPRINTF_RETVAL_C99
+
+/* Define to 1 if you have the `statacl' function. */
+#undef HAVE_STATACL
+
+/* Define to 1 if you have the `statvfs' function. */
+#undef HAVE_STATVFS
/* Define to 1 if you have the <stdint.h> header file. */
#undef HAVE_STDINT_H
@@ -1012,9 +1981,6 @@
/* Define to 1 if you have the <stdio_ext.h> header file. */
#undef HAVE_STDIO_EXT_H
-/* Define to 1 if you have the <stdio.h> header file. */
-#undef HAVE_STDIO_H
-
/* Define to 1 if you have the <stdlib.h> header file. */
#undef HAVE_STDLIB_H
@@ -1024,12 +1990,8 @@
/* Define to 1 if you have the `stpcpy' function. */
#undef HAVE_STPCPY
-/* Define to 1 if you have the `strcoll' function and it is properly defined.
- */
-#undef HAVE_STRCOLL
-
-/* Define to 1 if you have the `strcspn' function. */
-#undef HAVE_STRCSPN
+/* Define if you have the stpncpy() function and it works. */
+#undef HAVE_STPNCPY
/* Define to 1 if you have the `strdup' function. */
#undef HAVE_STRDUP
@@ -1043,27 +2005,36 @@
/* Define to 1 if you have the <string.h> header file. */
#undef HAVE_STRING_H
-/* Define if you have the strndup() function and it works. */
+/* Define to 1 if you have the `strndup' function. */
#undef HAVE_STRNDUP
+/* Define to 1 if you have the `strnlen' function. */
+#undef HAVE_STRNLEN
+
/* Define to 1 if you have the <stropts.h> header file. */
#undef HAVE_STROPTS_H
/* Define to 1 if you have the `strpbrk' function. */
#undef HAVE_STRPBRK
+/* Define to 1 if you have the `strsignal' function. */
+#undef HAVE_STRSIGNAL
+
+/* Define to 1 if you have the `strtod_l' function. */
+#undef HAVE_STRTOD_L
+
+/* Define to 1 if you have the `strtof' function. */
+#undef HAVE_STRTOF
+
/* Define to 1 if you have the `strtoimax' function. */
#undef HAVE_STRTOIMAX
-/* Define to 1 if you have the `strtol' function. */
-#undef HAVE_STRTOL
+/* Define to 1 if you have the `strtold_l' function. */
+#undef HAVE_STRTOLD_L
/* Define to 1 if you have the `strtoll' function. */
#undef HAVE_STRTOLL
-/* Define to 1 if you have the `strtoul' function. */
-#undef HAVE_STRTOUL
-
/* Define to 1 if you have the `strtoull' function. */
#undef HAVE_STRTOULL
@@ -1077,129 +2048,150 @@
headers. */
#undef HAVE_STRUCT_DIRENT_D_TYPE
-/* Define to 1 if `f_fstypename' is member of `struct fsstat'. */
+/* Define to 1 if `f_fstypename' is a member of `struct fsstat'. */
#undef HAVE_STRUCT_FSSTAT_F_FSTYPENAME
-/* Define to 1 if `n_un.n_name' is member of `struct nlist'. */
+/* Define to 1 if `decimal_point' is a member of `struct lconv'. */
+#undef HAVE_STRUCT_LCONV_DECIMAL_POINT
+
+/* Define to 1 if `n_un.n_name' is a member of `struct nlist'. */
#undef HAVE_STRUCT_NLIST_N_UN_N_NAME
-/* Define to 1 if `sp_pwdp' is member of `struct spwd'. */
-#undef HAVE_STRUCT_SPWD_SP_PWDP
+/* Define to 1 if `sa_sigaction' is a member of `struct sigaction'. */
+#undef HAVE_STRUCT_SIGACTION_SA_SIGACTION
+
+/* Define to 1 if `sa_len' is a member of `struct sockaddr'. */
+#undef HAVE_STRUCT_SOCKADDR_SA_LEN
-/* Define to 1 if `f_fstypename' is member of `struct statfs'. */
+/* Define to 1 if the system has the type `struct sockaddr_storage'. */
+#undef HAVE_STRUCT_SOCKADDR_STORAGE
+
+/* Define to 1 if `ss_family' is a member of `struct sockaddr_storage'. */
+#undef HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY
+
+/* Define to 1 if `f_frsize' is a member of `struct statfs'. */
+#undef HAVE_STRUCT_STATFS_F_FRSIZE
+
+/* Define to 1 if `f_fstypename' is a member of `struct statfs'. */
#undef HAVE_STRUCT_STATFS_F_FSTYPENAME
-/* Define to 1 if `f_namelen' is member of `struct statfs'. */
+/* Define to 1 if `f_namelen' is a member of `struct statfs'. */
#undef HAVE_STRUCT_STATFS_F_NAMELEN
-/* Define to 1 if `f_type' is member of `struct statfs'. */
+/* Define to 1 if `f_type' is a member of `struct statfs'. */
#undef HAVE_STRUCT_STATFS_F_TYPE
-/* Define to 1 if `f_basetype' is member of `struct statvfs'. */
+/* Define to 1 if `f_basetype' is a member of `struct statvfs'. */
#undef HAVE_STRUCT_STATVFS_F_BASETYPE
-/* Define to 1 if `f_fstypename' is member of `struct statvfs'. */
+/* Define to 1 if `f_fstypename' is a member of `struct statvfs'. */
#undef HAVE_STRUCT_STATVFS_F_FSTYPENAME
-/* Define to 1 if `f_namemax' is member of `struct statvfs'. */
+/* Define to 1 if `f_namemax' is a member of `struct statvfs'. */
#undef HAVE_STRUCT_STATVFS_F_NAMEMAX
-/* Define to 1 if `f_type' is member of `struct statvfs'. */
+/* Define to 1 if `f_type' is a member of `struct statvfs'. */
#undef HAVE_STRUCT_STATVFS_F_TYPE
-/* Define to 1 if `st_atimensec' is member of `struct stat'. */
+/* Define to 1 if `st_atimensec' is a member of `struct stat'. */
#undef HAVE_STRUCT_STAT_ST_ATIMENSEC
-/* Define to 1 if `st_atimespec.tv_nsec' is member of `struct stat'. */
+/* Define to 1 if `st_atimespec.tv_nsec' is a member of `struct stat'. */
#undef HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC
-/* Define to 1 if `st_atim.st__tim.tv_nsec' is member of `struct stat'. */
+/* Define to 1 if `st_atim.st__tim.tv_nsec' is a member of `struct stat'. */
#undef HAVE_STRUCT_STAT_ST_ATIM_ST__TIM_TV_NSEC
-/* Define to 1 if `st_atim.tv_nsec' is member of `struct stat'. */
+/* Define to 1 if `st_atim.tv_nsec' is a member of `struct stat'. */
#undef HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC
-/* Define to 1 if `st_author' is member of `struct stat'. */
+/* Define to 1 if `st_author' is a member of `struct stat'. */
#undef HAVE_STRUCT_STAT_ST_AUTHOR
-/* Define to 1 if `st_blocks' is member of `struct stat'. */
+/* Define to 1 if `st_birthtimensec' is a member of `struct stat'. */
+#undef HAVE_STRUCT_STAT_ST_BIRTHTIMENSEC
+
+/* Define to 1 if `st_birthtimespec.tv_nsec' is a member of `struct stat'. */
+#undef HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC_TV_NSEC
+
+/* Define to 1 if `st_birthtim.tv_nsec' is a member of `struct stat'. */
+#undef HAVE_STRUCT_STAT_ST_BIRTHTIM_TV_NSEC
+
+/* Define to 1 if `st_blocks' is a member of `struct stat'. */
#undef HAVE_STRUCT_STAT_ST_BLOCKS
-/* Define to 1 if `st_spare1' is member of `struct stat'. */
-#undef HAVE_STRUCT_STAT_ST_SPARE1
+/* Define to 1 if `mem_unit' is a member of `struct sysinfo'. */
+#undef HAVE_STRUCT_SYSINFO_MEM_UNIT
-/* Define to 1 if `tm_zone' is member of `struct tm'. */
+/* Define to 1 if `tm_zone' is a member of `struct tm'. */
#undef HAVE_STRUCT_TM_TM_ZONE
/* Define if struct utimbuf is declared -- usually in <utime.h>. Some systems
have utime.h but don't declare the struct anywhere. */
#undef HAVE_STRUCT_UTIMBUF
-/* Define to 1 if `ut_exit' is member of `struct utmpx'. */
+/* Define to 1 if `ut_exit' is a member of `struct utmpx'. */
#undef HAVE_STRUCT_UTMPX_UT_EXIT
-/* Define to 1 if `ut_exit.e_exit' is member of `struct utmpx'. */
+/* Define to 1 if `ut_exit.e_exit' is a member of `struct utmpx'. */
#undef HAVE_STRUCT_UTMPX_UT_EXIT_E_EXIT
-/* Define to 1 if `ut_exit.e_termination' is member of `struct utmpx'. */
+/* Define to 1 if `ut_exit.e_termination' is a member of `struct utmpx'. */
#undef HAVE_STRUCT_UTMPX_UT_EXIT_E_TERMINATION
-/* Define to 1 if `ut_exit.ut_exit' is member of `struct utmpx'. */
+/* Define to 1 if `ut_exit.ut_exit' is a member of `struct utmpx'. */
#undef HAVE_STRUCT_UTMPX_UT_EXIT_UT_EXIT
-/* Define to 1 if `ut_exit.ut_termination' is member of `struct utmpx'. */
+/* Define to 1 if `ut_exit.ut_termination' is a member of `struct utmpx'. */
#undef HAVE_STRUCT_UTMPX_UT_EXIT_UT_TERMINATION
-/* Define to 1 if `ut_id' is member of `struct utmpx'. */
+/* Define to 1 if `ut_id' is a member of `struct utmpx'. */
#undef HAVE_STRUCT_UTMPX_UT_ID
-/* Define to 1 if `ut_name' is member of `struct utmpx'. */
+/* Define to 1 if `ut_name' is a member of `struct utmpx'. */
#undef HAVE_STRUCT_UTMPX_UT_NAME
-/* Define to 1 if `ut_pid' is member of `struct utmpx'. */
+/* Define to 1 if `ut_pid' is a member of `struct utmpx'. */
#undef HAVE_STRUCT_UTMPX_UT_PID
-/* Define to 1 if `ut_type' is member of `struct utmpx'. */
+/* Define to 1 if `ut_type' is a member of `struct utmpx'. */
#undef HAVE_STRUCT_UTMPX_UT_TYPE
-/* Define to 1 if `ut_user' is member of `struct utmpx'. */
+/* Define to 1 if `ut_user' is a member of `struct utmpx'. */
#undef HAVE_STRUCT_UTMPX_UT_USER
-/* Define to 1 if `ut_exit' is member of `struct utmp'. */
+/* Define to 1 if `ut_exit' is a member of `struct utmp'. */
#undef HAVE_STRUCT_UTMP_UT_EXIT
-/* Define to 1 if `ut_exit.e_exit' is member of `struct utmp'. */
+/* Define to 1 if `ut_exit.e_exit' is a member of `struct utmp'. */
#undef HAVE_STRUCT_UTMP_UT_EXIT_E_EXIT
-/* Define to 1 if `ut_exit.e_termination' is member of `struct utmp'. */
+/* Define to 1 if `ut_exit.e_termination' is a member of `struct utmp'. */
#undef HAVE_STRUCT_UTMP_UT_EXIT_E_TERMINATION
-/* Define to 1 if `ut_exit.ut_exit' is member of `struct utmp'. */
+/* Define to 1 if `ut_exit.ut_exit' is a member of `struct utmp'. */
#undef HAVE_STRUCT_UTMP_UT_EXIT_UT_EXIT
-/* Define to 1 if `ut_exit.ut_termination' is member of `struct utmp'. */
+/* Define to 1 if `ut_exit.ut_termination' is a member of `struct utmp'. */
#undef HAVE_STRUCT_UTMP_UT_EXIT_UT_TERMINATION
-/* Define to 1 if `ut_id' is member of `struct utmp'. */
+/* Define to 1 if `ut_id' is a member of `struct utmp'. */
#undef HAVE_STRUCT_UTMP_UT_ID
-/* Define to 1 if `ut_name' is member of `struct utmp'. */
+/* Define to 1 if `ut_name' is a member of `struct utmp'. */
#undef HAVE_STRUCT_UTMP_UT_NAME
-/* Define to 1 if `ut_pid' is member of `struct utmp'. */
+/* Define to 1 if `ut_pid' is a member of `struct utmp'. */
#undef HAVE_STRUCT_UTMP_UT_PID
-/* Define to 1 if `ut_type' is member of `struct utmp'. */
+/* Define to 1 if `ut_type' is a member of `struct utmp'. */
#undef HAVE_STRUCT_UTMP_UT_TYPE
-/* Define to 1 if `ut_user' is member of `struct utmp'. */
+/* Define to 1 if `ut_user' is a member of `struct utmp'. */
#undef HAVE_STRUCT_UTMP_UT_USER
-/* Define to 1 if you have the `strverscmp' function. */
-#undef HAVE_STRVERSCMP
-
-/* Define to 1 if you have the `strxfrm' function. */
-#undef HAVE_STRXFRM
+/* Define to 1 if the system has the type `struct utsname'. */
+#undef HAVE_STRUCT_UTSNAME
/* Define to 1 if your `struct stat' has `st_blocks'. Deprecated, use
`HAVE_STRUCT_STAT_ST_BLOCKS' instead. */
@@ -1208,9 +2200,18 @@
/* Define if struct stat has an st_dm_mode member. */
#undef HAVE_ST_DM_MODE
+/* Define to 1 if you have the `symlink' function. */
+#undef HAVE_SYMLINK
+
+/* Define to 1 if you have the `symlinkat' function. */
+#undef HAVE_SYMLINKAT
+
/* Define to 1 if you have the `sync' function. */
#undef HAVE_SYNC
+/* Define to 1 if you have the `syncfs' function. */
+#undef HAVE_SYNCFS
+
/* Define to 1 if you have the `sysctl' function. */
#undef HAVE_SYSCTL
@@ -1247,6 +2248,12 @@
/* Define to 1 if you have the <sys/ioctl.h> header file. */
#undef HAVE_SYS_IOCTL_H
+/* Define to 1 if you have the <sys/loadavg.h> header file. */
+#undef HAVE_SYS_LOADAVG_H
+
+/* Define to 1 if you have the <sys/mman.h> header file. */
+#undef HAVE_SYS_MMAN_H
+
/* Define to 1 if you have the <sys/mntent.h> header file. */
#undef HAVE_SYS_MNTENT_H
@@ -1307,6 +2314,12 @@
/* Define to 1 if you have the <sys/ucred.h> header file. */
#undef HAVE_SYS_UCRED_H
+/* Define to 1 if you have the <sys/uio.h> header file. */
+#undef HAVE_SYS_UIO_H
+
+/* Define to 1 if you have the <sys/utsname.h> header file. */
+#undef HAVE_SYS_UTSNAME_H
+
/* Define to 1 if you have the <sys/vfs.h> header file. */
#undef HAVE_SYS_VFS_H
@@ -1328,8 +2341,14 @@
/* Define to 1 if you have the <termios.h> header file. */
#undef HAVE_TERMIOS_H
-/* Define to 1 if you have the <time.h> header file. */
-#undef HAVE_TIME_H
+/* Define to 1 if you have the `timegm' function. */
+#undef HAVE_TIMEGM
+
+/* Define to 1 if you have the `timer_settime' function. */
+#undef HAVE_TIMER_SETTIME
+
+/* Define to 1 if the system has the type `timezone_t'. */
+#undef HAVE_TIMEZONE_T
/* Define if struct tm has the tm_gmtoff member. */
#undef HAVE_TM_GMTOFF
@@ -1338,9 +2357,15 @@
`HAVE_STRUCT_TM_TM_ZONE' instead. */
#undef HAVE_TM_ZONE
+/* Define to 1 if you have the `towlower' function. */
+#undef HAVE_TOWLOWER
+
/* Define to 1 if you have the `tsearch' function. */
#undef HAVE_TSEARCH
+/* Define to 1 if you have the `ttyname' function. */
+#undef HAVE_TTYNAME
+
/* Define to 1 if you don't have `tm_zone' but do have the external array
`tzname'. */
#undef HAVE_TZNAME
@@ -1354,21 +2379,24 @@
/* Define to 1 if you have the <unistd.h> header file. */
#undef HAVE_UNISTD_H
+/* Define to 1 if you have the `unlinkat' function. */
+#undef HAVE_UNLINKAT
+
/* Define to 1 if you have the `unsetenv' function. */
#undef HAVE_UNSETENV
-/* Define to 1 if the system has the type `unsigned long long int'. */
+/* Define to 1 if the system has the type 'unsigned long long int'. */
#undef HAVE_UNSIGNED_LONG_LONG_INT
-/* Define if utimes accepts a null argument */
-#undef HAVE_UTIMES_NULL
+/* Define to 1 if you have the `uselocale' function. */
+#undef HAVE_USELOCALE
+
+/* Define to 1 if you have the `utimensat' function. */
+#undef HAVE_UTIMENSAT
/* Define to 1 if you have the <utime.h> header file. */
#undef HAVE_UTIME_H
-/* Define to 1 if `utime(file, NULL)' sets file's timestamp to the present. */
-#undef HAVE_UTIME_NULL
-
/* Define to 1 if you have the `utmpname' function. */
#undef HAVE_UTMPNAME
@@ -1405,12 +2433,18 @@
/* Define to 1 if you have the `wcrtomb' function. */
#undef HAVE_WCRTOMB
-/* Define to 1 if you have the `wcscoll' function. */
-#undef HAVE_WCSCOLL
-
/* Define to 1 if you have the `wcslen' function. */
#undef HAVE_WCSLEN
+/* Define to 1 if you have the `wcsnlen' function. */
+#undef HAVE_WCSNLEN
+
+/* Define to 1 if you have the `wcswidth' function. */
+#undef HAVE_WCSWIDTH
+
+/* Define to 1 if you have the `wctob' function. */
+#undef HAVE_WCTOB
+
/* Define to 1 if you have the <wctype.h> header file. */
#undef HAVE_WCTYPE_H
@@ -1435,6 +2469,10 @@
/* Define to 1 if `fork' works. */
#undef HAVE_WORKING_FORK
+/* Define to 1 if fstatat (..., 0) works. For example, it does not work in AIX
+ 7.1. */
+#undef HAVE_WORKING_FSTATAT_ZERO_FLAG
+
/* Define to 1 if O_NOATIME works. */
#undef HAVE_WORKING_O_NOATIME
@@ -1450,41 +2488,100 @@
/* Define to 1 if you have the <ws2tcpip.h> header file. */
#undef HAVE_WS2TCPIP_H
+/* Define to 1 if you have the <xlocale.h> header file. */
+#undef HAVE_XLOCALE_H
+
/* Define to 1 if the system has the type `_Bool'. */
#undef HAVE__BOOL
+/* Define to 1 if you have the `_fseeki64' function. */
+#undef HAVE__FSEEKI64
+
+/* Define to 1 if you have the `_ftelli64' function. */
+#undef HAVE__FTELLI64
+
/* Define to 1 if you have the `_ftime' function. */
#undef HAVE__FTIME
+/* Define to 1 if you have the `_set_invalid_parameter_handler' function. */
+#undef HAVE__SET_INVALID_PARAMETER_HANDLER
+
/* Define to 1 if you have the external variable, _system_configuration with a
member named physmem. */
#undef HAVE__SYSTEM_CONFIGURATION
-/* Define to 1 if you have the `__fpending' function. */
-#undef HAVE___FPENDING
+/* Define to 1 if you have the `__fpurge' function. */
+#undef HAVE___FPURGE
+
+/* Define to 1 if you have the `__freadahead' function. */
+#undef HAVE___FREADAHEAD
+
+/* Define to 1 if you have the `__freading' function. */
+#undef HAVE___FREADING
+
+/* Define to 1 if you have the `__freadptr' function. */
+#undef HAVE___FREADPTR
+
+/* Define to 1 if you have the `__freadptrinc' function. */
+#undef HAVE___FREADPTRINC
+
+/* Define to 1 if you have the `__fseterr' function. */
+#undef HAVE___FSETERR
/* Define to 1 if you have the `__fsetlocking' function. */
#undef HAVE___FSETLOCKING
+/* Define to 1 if you have the `__secure_getenv' function. */
+#undef HAVE___SECURE_GETENV
+
+/* Define to 1 if you have the `__xpg_strerror_r' function. */
+#undef HAVE___XPG_STRERROR_R
+
+/* Define HOST_NAME_MAX when <limits.h> does not define it. */
+#undef HOST_NAME_MAX
+
/* The host operating system. */
#undef HOST_OPERATING_SYSTEM
/* Define as const if the declaration of iconv() needs const. */
#undef ICONV_CONST
-#if FILE_SYSTEM_BACKSLASH_IS_FILE_NAME_SEPARATOR
-# define ISSLASH(C) ((C) == '/' || (C) == '\\')
-#else
-# define ISSLASH(C) ((C) == '/')
-#endif
+/* Define to a symbolic name denoting the flavor of iconv_open()
+ implementation. */
+#undef ICONV_FLAVOR
+
+/* Define as the bit index in the word where to find bit 0 of the exponent of
+ 'long double'. */
+#undef LDBL_EXPBIT0_BIT
+
+/* Define as the word index where to find the exponent of 'long double'. */
+#undef LDBL_EXPBIT0_WORD
-/* Define if `link(2)' dereferences symbolic links. */
+/* Define as the bit index in the word where to find the sign of 'long
+ double'. */
+#undef LDBL_SIGNBIT_BIT
+
+/* Define as the word index where to find the sign of 'long double'. */
+#undef LDBL_SIGNBIT_WORD
+
+/* Define to 1 if linkat can create hardlinks to symlinks */
+#undef LINKAT_SYMLINK_NOTSUP
+
+/* Define to 1 if linkat fails to recognize a trailing slash. */
+#undef LINKAT_TRAILING_SLASH_BUG
+
+/* Define to 1 if 'link(2)' dereferences symbolic links, 0 if it creates hard
+ links to symlinks, -1 if it depends on the variable __xpg4, and -2 if
+ unknown. */
#undef LINK_FOLLOWS_SYMLINKS
/* FIXME */
#undef LOCALTIME_CACHE
-/* Define to 1 if `lstat' dereferences a symlink specified with a trailing
+/* Define to 1 if lseek does not detect pipes. */
+#undef LSEEK_PIPE_BROKEN
+
+/* Define to 1 if 'lstat' dereferences a symlink specified with a trailing
slash. */
#undef LSTAT_FOLLOWS_SLASHED_SYMLINK
@@ -1499,6 +2596,31 @@
/* If malloc(0) is != NULL, define this to 1. Otherwise define this to 0. */
#undef MALLOC_0_IS_NONNULL
+/* Define to a substitute value for mmap()'s MAP_ANONYMOUS flag. */
+#undef MAP_ANONYMOUS
+
+/* Define if the mbrtowc function does not return (size_t) -2 for empty input.
+ */
+#undef MBRTOWC_EMPTY_INPUT_BUG
+
+/* Define if the mbrtowc function has the NULL pwc argument bug. */
+#undef MBRTOWC_NULL_ARG1_BUG
+
+/* Define if the mbrtowc function has the NULL string argument bug. */
+#undef MBRTOWC_NULL_ARG2_BUG
+
+/* Define if the mbrtowc function does not return 0 for a NUL character. */
+#undef MBRTOWC_NUL_RETVAL_BUG
+
+/* Define if the mbrtowc function returns a wrong return value. */
+#undef MBRTOWC_RETVAL_BUG
+
+/* Define to 1 if mkfifo does not reject trailing slash */
+#undef MKFIFO_TRAILING_SLASH_BUG
+
+/* Define to 1 if mknod cannot create a fifo without super-user privileges */
+#undef MKNOD_FIFO_BUG
+
/* Define if there is no specific function for reading the list of mounted
file systems. fread will be used to read /etc/mnttab. (SVR2) */
#undef MOUNTED_FREAD
@@ -1539,24 +2661,75 @@
3.0) */
#undef MOUNTED_GETMNTINFO2
+/* Define if we are on interix, and ought to use statvfs plus some special
+ knowledge on where mounted file systems can be found. (Interix) */
+#undef MOUNTED_INTERIX_STATVFS
+
/* Define if there is a function named listmntent that can be used to list all
mounted file systems. (UNICOS) */
#undef MOUNTED_LISTMNTENT
/* Define if there is a function named mntctl that can be used to read the
list of mounted file systems, and there is a system header file that
- declares `struct vmount.' (AIX) */
+ declares 'struct vmount'. (AIX) */
#undef MOUNTED_VMOUNT
/* Define to 1 if assertions should be disabled. */
#undef NDEBUG
-/* Define to 1 if your `struct nlist' has an `n_un' member. Obsolete, depend
- on `HAVE_STRUCT_NLIST_N_UN_N_NAME */
-#undef NLIST_NAME_UNION
+/* Define if the vasnprintf implementation needs special code for the 'a' and
+ 'A' directives. */
+#undef NEED_PRINTF_DIRECTIVE_A
+
+/* Define if the vasnprintf implementation needs special code for the 'F'
+ directive. */
+#undef NEED_PRINTF_DIRECTIVE_F
+
+/* Define if the vasnprintf implementation needs special code for the 'ls'
+ directive. */
+#undef NEED_PRINTF_DIRECTIVE_LS
+
+/* Define if the vasnprintf implementation needs special code for 'double'
+ arguments. */
+#undef NEED_PRINTF_DOUBLE
+
+/* Define if the vasnprintf implementation needs special code for surviving
+ out-of-memory conditions. */
+#undef NEED_PRINTF_ENOMEM
+
+/* Define if the vasnprintf implementation needs special code for the ' flag.
+ */
+#undef NEED_PRINTF_FLAG_GROUPING
+
+/* Define if the vasnprintf implementation needs special code for the '-'
+ flag. */
+#undef NEED_PRINTF_FLAG_LEFTADJUST
+
+/* Define if the vasnprintf implementation needs special code for the 0 flag.
+ */
+#undef NEED_PRINTF_FLAG_ZERO
+
+/* Define if the vasnprintf implementation needs special code for infinite
+ 'double' arguments. */
+#undef NEED_PRINTF_INFINITE_DOUBLE
+
+/* Define if the vasnprintf implementation needs special code for infinite
+ 'long double' arguments. */
+#undef NEED_PRINTF_INFINITE_LONG_DOUBLE
+
+/* Define if the vasnprintf implementation needs special code for 'long
+ double' arguments. */
+#undef NEED_PRINTF_LONG_DOUBLE
+
+/* Define if the vasnprintf implementation needs special code for supporting
+ large precisions without arbitrary bounds. */
+#undef NEED_PRINTF_UNBOUNDED_PRECISION
-/* Define to 1 if your C compiler doesn't accept -c and -o together. */
-#undef NO_MINUS_C_MINUS_O
+/* Define to 1 if the nlist n_name member is a pointer */
+#undef N_NAME_POINTER
+
+/* Define to 1 if open() fails to recognize a trailing slash. */
+#undef OPEN_TRAILING_SLASH_BUG
/* Name of package */
#undef PACKAGE
@@ -1567,16 +2740,28 @@
/* Define to the full name of this package. */
#undef PACKAGE_NAME
+/* String identifying the packager of this software */
+#undef PACKAGE_PACKAGER
+
+/* Packager info for bug reports (URL/e-mail/...) */
+#undef PACKAGE_PACKAGER_BUG_REPORTS
+
+/* Packager-specific version information */
+#undef PACKAGE_PACKAGER_VERSION
+
/* Define to the full name and version of this package. */
#undef PACKAGE_STRING
/* Define to the one symbol short name of this package. */
#undef PACKAGE_TARNAME
+/* Define to the home page for this package. */
+#undef PACKAGE_URL
+
/* Define to the version of this package. */
#undef PACKAGE_VERSION
-/* the number of pending output bytes on stream `fp' */
+/* the number of pending output bytes on stream 'fp' */
#undef PENDING_OUTPUT_N_BYTES
/* Define to the maximum link count that a true pipe can have. */
@@ -1592,30 +2777,81 @@
/* Define if <inttypes.h> exists and defines unusable PRI* macros. */
#undef PRI_MACROS_BROKEN
-/* Define to 1 if the C compiler supports function prototypes. */
-#undef PROTOTYPES
+/* Define to the type that is the result of default argument promotions of
+ type mode_t. */
+#undef PROMOTED_MODE_T
+
+/* Define if the pthread_in_use() detection is hard. */
+#undef PTHREAD_IN_USE_DETECTION_HARD
/* Define to l, ll, u, ul, ull, etc., as suitable for constants of type
'ptrdiff_t'. */
#undef PTRDIFF_T_SUFFIX
-/* Define if rename does not work for source file names with a trailing slash,
- like the one from SunOS 4.1.1_U1. */
-#undef RENAME_TRAILING_SLASH_BUG
+/* Define to 1 if readlink fails to recognize a trailing slash. */
+#undef READLINK_TRAILING_SLASH_BUG
+
+/* Define if rename does not work when the destination file exists, as on
+ Cygwin 1.5 or Windows. */
+#undef RENAME_DEST_EXISTS_BUG
+
+/* Define if rename fails to leave hard links alone, as on NetBSD 1.6 or
+ Cygwin 1.5. */
+#undef RENAME_HARD_LINK_BUG
+
+/* Define if rename does not correctly handle slashes on the destination
+ argument, such as on Solaris 10 or NetBSD 1.6. */
+#undef RENAME_TRAILING_SLASH_DEST_BUG
+
+/* Define if rename does not correctly handle slashes on the source argument,
+ such as on Solaris 9 or cygwin 1.5. */
+#undef RENAME_TRAILING_SLASH_SOURCE_BUG
+
+/* Define to 1 if gnulib's dirfd() replacement is used. */
+#undef REPLACE_DIRFD
+
+/* Define to 1 if gnulib's fchdir() replacement is used. */
+#undef REPLACE_FCHDIR
+
+/* Define to 1 if stat needs help when passed a directory name with a trailing
+ slash */
+#undef REPLACE_FUNC_STAT_DIR
+
+/* Define to 1 if stat needs help when passed a file name with a trailing
+ slash */
+#undef REPLACE_FUNC_STAT_FILE
+
+/* Define if nl_langinfo exists but is overridden by gnulib. */
+#undef REPLACE_NL_LANGINFO
+
+/* Define to 1 if open() should work around the inability to open a directory.
+ */
+#undef REPLACE_OPEN_DIRECTORY
+
+/* Define to 1 if strerror(0) does not return a message implying success. */
+#undef REPLACE_STRERROR_0
/* Define if vasnprintf exists but is overridden by gnulib. */
#undef REPLACE_VASNPRINTF
-/* Define if vasprintf exists but is overridden by gnulib. */
-#undef REPLACE_VASPRINTF
+/* Define if vfprintf is overridden by a POSIX compliant gnulib
+ implementation. */
+#undef REPLACE_VFPRINTF_POSIX
-/* the value to which errno is set when rmdir fails on a nonempty directory */
-#undef RMDIR_ERRNO_NOT_EMPTY
+/* Define if vprintf is overridden by a POSIX compliant gnulib implementation.
+ */
+#undef REPLACE_VPRINTF_POSIX
/* Define to l, ll, u, ul, ull, etc., as suitable for constants of type
'sig_atomic_t'. */
#undef SIG_ATOMIC_T_SUFFIX
+/* Define as the maximum value of type 'size_t', if the system doesn't define
+ it. */
+#ifndef SIZE_MAX
+# undef SIZE_MAX
+#endif
+
/* Define to l, ll, u, ul, ull, etc., as suitable for constants of type
'size_t'. */
#undef SIZE_T_SUFFIX
@@ -1645,6 +2881,10 @@
(4.3BSD, SunOS 4, HP-UX, AIX PS/2) */
#undef STAT_STATFS2_BSIZE
+/* Define if statfs takes 2 args and struct statfs has a field named f_frsize.
+ (glibc/Linux > 2.6) */
+#undef STAT_STATFS2_FRSIZE
+
/* Define if statfs takes 2 args and struct statfs has a field named f_fsize.
(4.4BSD, NetBSD) */
#undef STAT_STATFS2_FSIZE
@@ -1656,12 +2896,15 @@
/* Define if statfs takes 3 args. (DEC Alpha running OSF/1) */
#undef STAT_STATFS3_OSF1
-/* Define if statfs takes 4 args. (SVR3, Dynix, Irix, Dolphin) */
+/* Define if statfs takes 4 args. (SVR3, Dynix, old Irix, old AIX, Dolphin) */
#undef STAT_STATFS4
/* Define if there is a function named statvfs. (SVR4) */
#undef STAT_STATVFS
+/* Define if statvfs64 should be preferred over statvfs. */
+#undef STAT_STATVFS64
+
/* Define to 1 if you have the ANSI C header files. */
#undef STDC_HEADERS
@@ -1680,12 +2923,18 @@
/* FIXME */
#undef TERMIOS_NEEDS_XOPEN_SOURCE
+/* Define to 1 if all 'time_t' values fit in a 'long int'. */
+#undef TIME_T_FITS_IN_LONG_INT
+
/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
#undef TIME_WITH_SYS_TIME
/* Define to 1 if your <sys/time.h> declares `struct tm'. */
#undef TM_IN_SYS_TIME
+/* group used by system for TTYs */
+#undef TTY_GROUP_NAME
+
/* Define to 1 if the type of the st_atim member of a struct stat is struct
timespec. */
#undef TYPEOF_STRUCT_STAT_ST_ATIM_IS_STRUCT_TIMESPEC
@@ -1703,24 +2952,93 @@
/* Define to 1 if unlink (dir) cannot possibly succeed. */
#undef UNLINK_CANNOT_UNLINK_DIR
-/* Define if you want access control list support. */
+/* Define to 1 if unlink() on a parent directory may succeed */
+#undef UNLINK_PARENT_BUG
+
+/* Define to nonzero if you want access control list support. */
#undef USE_ACL
+/* Define if the POSIX multithreading library can be used. */
+#undef USE_POSIX_THREADS
+
+/* Define if references to the POSIX multithreading library should be made
+ weak. */
+#undef USE_POSIX_THREADS_WEAK
+
+/* Define if the GNU Pth multithreading library can be used. */
+#undef USE_PTH_THREADS
+
+/* Define if references to the GNU Pth multithreading library should be made
+ weak. */
+#undef USE_PTH_THREADS_WEAK
+
+/* Define if the old Solaris multithreading library can be used. */
+#undef USE_SOLARIS_THREADS
+
+/* Define if references to the old Solaris multithreading library should be
+ made weak. */
+#undef USE_SOLARIS_THREADS_WEAK
+
+/* Enable extensions on AIX 3, Interix. */
+#ifndef _ALL_SOURCE
+# undef _ALL_SOURCE
+#endif
+/* Enable general extensions on OS X. */
+#ifndef _DARWIN_C_SOURCE
+# undef _DARWIN_C_SOURCE
+#endif
+/* Enable GNU extensions on systems that have them. */
+#ifndef _GNU_SOURCE
+# undef _GNU_SOURCE
+#endif
+/* Use GNU style printf and scanf. */
+#ifndef __USE_MINGW_ANSI_STDIO
+# undef __USE_MINGW_ANSI_STDIO
+#endif
+/* Enable threading extensions on Solaris. */
+#ifndef _POSIX_PTHREAD_SEMANTICS
+# undef _POSIX_PTHREAD_SEMANTICS
+#endif
+/* Enable extensions on HP NonStop. */
+#ifndef _TANDEM_SOURCE
+# undef _TANDEM_SOURCE
+#endif
+/* Enable X/Open extensions if necessary. HP-UX 11.11 defines
+ mbstate_t only if _XOPEN_SOURCE is defined to 500, regardless of
+ whether compiling with -Ae or -D_HPUX_SOURCE=1. */
+#ifndef _XOPEN_SOURCE
+# undef _XOPEN_SOURCE
+#endif
+/* Enable general extensions on Solaris. */
+#ifndef __EXTENSIONS__
+# undef __EXTENSIONS__
+#endif
+
+
/* Define to 1 if you want getc etc. to use unlocked I/O if available.
Unlocked I/O can improve performance in unithreaded apps, but it is not
safe for multithreaded apps. */
#undef USE_UNLOCKED_IO
+/* Define if the native Windows multithreading API can be used. */
+#undef USE_WINDOWS_THREADS
+
+/* Define if you want extended attribute support. */
+#undef USE_XATTR
+
/* Version number of package */
#undef VERSION
-/* Define if unsetenv() returns void, not int. */
+/* Define to 1 if unsetenv returns void instead of int. */
#undef VOID_UNSETENV
/* Define to l, ll, u, ul, ull, etc., as suitable for constants of type
'wchar_t'. */
#undef WCHAR_T_SUFFIX
+/* Define if WSAStartup is needed. */
+#undef WINDOWS_SOCKETS
+
/* Define if sys/ptem.h is required for struct winsize. */
#undef WINSIZE_IN_PTEM
@@ -1728,24 +3046,27 @@
'wint_t'. */
#undef WINT_T_SUFFIX
-/* Define to 1 if your processor stores words with the most significant byte
- first (like Motorola and SPARC, unlike Intel and VAX). */
-#undef WORDS_BIGENDIAN
-
-/* Define to 1 if on AIX 3.
- System headers sometimes define this.
- We just want to avoid a redefinition error message. */
-#ifndef _ALL_SOURCE
-# undef _ALL_SOURCE
+/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
+ significant byte first (like Motorola and SPARC, unlike Intel). */
+#if defined AC_APPLE_UNIVERSAL_BUILD
+# if defined __BIG_ENDIAN__
+# define WORDS_BIGENDIAN 1
+# endif
+#else
+# ifndef WORDS_BIGENDIAN
+# undef WORDS_BIGENDIAN
+# endif
#endif
+/* Enable large inode numbers on Mac OS X 10.5. */
+#undef _DARWIN_USE_64_BIT_INODE
+
/* Number of bits in a file offset, on hosts where this is settable. */
#undef _FILE_OFFSET_BITS
-/* Enable GNU extensions on systems that have them. */
-#ifndef _GNU_SOURCE
-# undef _GNU_SOURCE
-#endif
+/* Define to 1 if Gnulib overrides 'struct stat' on Windows so that struct
+ stat.st_size becomes 64-bit. */
+#undef _GL_WINDOWS_64_BIT_ST_SIZE
/* Define to 1 to make fseeko visible on some hosts (e.g. glibc 2.2). */
#undef _LARGEFILE_SOURCE
@@ -1753,57 +3074,156 @@
/* Define for large files, on AIX-style hosts. */
#undef _LARGE_FILES
+/* Define to 1 on Solaris. */
+#undef _LCONV_C99
+
/* Define to 1 if on MINIX. */
#undef _MINIX
+/* Define to 1 to make NetBSD features available. MINIX 3 needs this. */
+#undef _NETBSD_SOURCE
+
+/* The _Noreturn keyword of C11. */
+#if ! (defined _Noreturn \
+ || (defined __STDC_VERSION__ && 201112 <= __STDC_VERSION__))
+# if (3 <= __GNUC__ || (__GNUC__ == 2 && 8 <= __GNUC_MINOR__) \
+ || 0x5110 <= __SUNPRO_C)
+# define _Noreturn __attribute__ ((__noreturn__))
+# elif defined _MSC_VER && 1200 <= _MSC_VER
+# define _Noreturn __declspec (noreturn)
+# else
+# define _Noreturn
+# endif
+#endif
+
+
/* Define to 2 if the system does not provide POSIX.1 features except with
this defined. */
#undef _POSIX_1_SOURCE
-/* Define to 1 if you need to in order for `stat' and other things to work. */
+/* Define to 1 in order to get the POSIX compatible declarations of socket
+ functions. */
+#undef _POSIX_PII_SOCKET
+
+/* Define to 1 if you need to in order for 'stat' and other things to work. */
#undef _POSIX_SOURCE
+/* For thread-safety on OSF/1, Solaris. */
+#undef _REENTRANT
+
+/* Define if you want <regex.h> to include <limits.h>, so that it consistently
+ overrides <limits.h>'s RE_DUP_MAX. */
+#undef _REGEX_INCLUDE_LIMITS_H
+
/* Define if you want regoff_t to be at least as wide POSIX requires. */
#undef _REGEX_LARGE_OFFSETS
-/* Enable extensions on Solaris. */
-#ifndef __EXTENSIONS__
-# undef __EXTENSIONS__
-#endif
-#ifndef _POSIX_PTHREAD_SEMANTICS
-# undef _POSIX_PTHREAD_SEMANTICS
-#endif
-#ifndef _TANDEM_SOURCE
-# undef _TANDEM_SOURCE
-#endif
+/* For thread-safety on AIX, FreeBSD. */
+#undef _THREAD_SAFE
/* Define to rpl_ if the getopt replacement functions and variables should be
used. */
#undef __GETOPT_PREFIX
-/* Define to rpl_ if the openat replacement function should be used. */
-#undef __OPENAT_PREFIX
-
-/* Define like PROTOTYPES; this can be used by system headers. */
-#undef __PROTOTYPES
+/* Please see the Gnulib manual for how to use these macros.
+
+ Suppress extern inline with HP-UX cc, as it appears to be broken; see
+ <http://lists.gnu.org/archive/html/bug-texinfo/2013-02/msg00030.html>.
+
+ Suppress extern inline with Sun C in standards-conformance mode, as it
+ mishandles inline functions that call each other. E.g., for 'inline void f
+ (void) { } inline void g (void) { f (); }', c99 incorrectly complains
+ 'reference to static identifier "f" in extern inline function'.
+ This bug was observed with Sun C 5.12 SunOS_i386 2011/11/16.
+
+ Suppress extern inline (with or without __attribute__ ((__gnu_inline__)))
+ on configurations that mistakenly use 'static inline' to implement
+ functions or macros in standard C headers like <ctype.h>. For example,
+ if isdigit is mistakenly implemented via a static inline function,
+ a program containing an extern inline function that calls isdigit
+ may not work since the C standard prohibits extern inline functions
+ from calling static functions. This bug is known to occur on:
+
+ OS X 10.8 and earlier; see:
+ http://lists.gnu.org/archive/html/bug-gnulib/2012-12/msg00023.html
+
+ DragonFly; see
+ http://muscles.dragonflybsd.org/bulk/bleeding-edge-potential/latest-per-pkg/ah-tty-0.3.12.log
+
+ FreeBSD; see:
+ http://lists.gnu.org/archive/html/bug-gnulib/2014-07/msg00104.html
+
+ OS X 10.9 has a macro __header_inline indicating the bug is fixed for C and
+ for clang but remains for g++; see <http://trac.macports.org/ticket/41033>.
+ Assume DragonFly and FreeBSD will be similar. */
+#if (((defined __APPLE__ && defined __MACH__) \
+ || defined __DragonFly__ || defined __FreeBSD__) \
+ && (defined __header_inline \
+ ? (defined __cplusplus && defined __GNUC_STDC_INLINE__ \
+ && ! defined __clang__) \
+ : ((! defined _DONT_USE_CTYPE_INLINE_ \
+ && (defined __GNUC__ || defined __cplusplus)) \
+ || (defined _FORTIFY_SOURCE && 0 < _FORTIFY_SOURCE \
+ && defined __GNUC__ && ! defined __cplusplus))))
+# define _GL_EXTERN_INLINE_STDHEADER_BUG
+#endif
+#if ((__GNUC__ \
+ ? defined __GNUC_STDC_INLINE__ && __GNUC_STDC_INLINE__ \
+ : (199901L <= __STDC_VERSION__ \
+ && !defined __HP_cc \
+ && !(defined __SUNPRO_C && __STDC__))) \
+ && !defined _GL_EXTERN_INLINE_STDHEADER_BUG)
+# define _GL_INLINE inline
+# define _GL_EXTERN_INLINE extern inline
+# define _GL_EXTERN_INLINE_IN_USE
+#elif (2 < __GNUC__ + (7 <= __GNUC_MINOR__) && !defined __STRICT_ANSI__ \
+ && !defined _GL_EXTERN_INLINE_STDHEADER_BUG)
+# if defined __GNUC_GNU_INLINE__ && __GNUC_GNU_INLINE__
+ /* __gnu_inline__ suppresses a GCC 4.2 diagnostic. */
+# define _GL_INLINE extern inline __attribute__ ((__gnu_inline__))
+# else
+# define _GL_INLINE extern inline
+# endif
+# define _GL_EXTERN_INLINE extern
+# define _GL_EXTERN_INLINE_IN_USE
+#else
+# define _GL_INLINE static _GL_UNUSED
+# define _GL_EXTERN_INLINE static _GL_UNUSED
+#endif
-/* Define to rpl_calloc if the replacement function should be used. */
-#undef calloc
+/* In GCC 4.6 (inclusive) to 5.1 (exclusive),
+ suppress bogus "no previous prototype for 'FOO'"
+ and "no previous declaration for 'FOO'" diagnostics,
+ when FOO is an inline function in the header; see
+ <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=54113> and
+ <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=63877>. */
+#if __GNUC__ == 4 && 6 <= __GNUC_MINOR__
+# if defined __GNUC_STDC_INLINE__ && __GNUC_STDC_INLINE__
+# define _GL_INLINE_HEADER_CONST_PRAGMA
+# else
+# define _GL_INLINE_HEADER_CONST_PRAGMA \
+ _Pragma ("GCC diagnostic ignored \"-Wsuggest-attribute=const\"")
+# endif
+# define _GL_INLINE_HEADER_BEGIN \
+ _Pragma ("GCC diagnostic push") \
+ _Pragma ("GCC diagnostic ignored \"-Wmissing-prototypes\"") \
+ _Pragma ("GCC diagnostic ignored \"-Wmissing-declarations\"") \
+ _GL_INLINE_HEADER_CONST_PRAGMA
+# define _GL_INLINE_HEADER_END \
+ _Pragma ("GCC diagnostic pop")
+#else
+# define _GL_INLINE_HEADER_BEGIN
+# define _GL_INLINE_HEADER_END
+#endif
-/* Define to rpl_fchownat if the replacement function should be used. */
-#undef fchownat
+/* Always use our fgetfilecon wrapper. */
+#undef fgetfilecon
/* Define to a replacement function name for fnmatch(). */
#undef fnmatch
-/* Define to rpl_free if the replacement function should be used. */
-#undef free
-
-/* Define as rpl_getgroups if getgroups doesn't work right. */
-#undef getgroups
-
-/* Define to a replacement function name for getline(). */
-#undef getline
+/* Always use our getfilecon wrapper. */
+#undef getfilecon
/* Define to a replacement function name for getpass(). */
#undef getpass
@@ -1814,9 +3234,6 @@
/* A replacement for va_copy, if needed. */
#define gl_va_copy(a,b) ((a) = (b))
-/* Define to rpl_gmtime if the replacement function should be used. */
-#undef gmtime
-
/* Define to `__inline__' or `__inline' if that's what the C compiler
calls it, or to nothing if 'inline' is not supported under any name. */
#ifndef __cplusplus
@@ -1829,29 +3246,33 @@
/* Define to long or long long if <stdint.h> and <inttypes.h> don't define. */
#undef intmax_t
-/* Define to rpl_localtime if the replacement function should be used. */
-#undef localtime
+/* Work around a bug in Apple GCC 4.0.1 build 5465: In C99 mode, it supports
+ the ISO C 99 semantics of 'extern inline' (unlike the GNU C semantics of
+ earlier versions), but does not display it by setting __GNUC_STDC_INLINE__.
+ __APPLE__ && __MACH__ test for Mac OS X.
+ __APPLE_CC__ tests for the Apple compiler and its version.
+ __STDC_VERSION__ tests for the C99 mode. */
+#if defined __APPLE__ && defined __MACH__ && __APPLE_CC__ >= 5465 && !defined __cplusplus && __STDC_VERSION__ >= 199901L && !defined __GNUC_STDC_INLINE__
+# define __GNUC_STDC_INLINE__ 1
+#endif
+
+/* Always use our lgetfilecon wrapper. */
+#undef lgetfilecon
+
+/* Define to 1 if the compiler is checking for lint. */
+#undef lint
/* Define to `unsigned int' if <sys/types.h> does not define. */
#undef major_t
-/* Define to rpl_malloc if the replacement function should be used. */
-#undef malloc
-
/* Define to a type if <wchar.h> does not define. */
#undef mbstate_t
-/* Define to rpl_memcmp if the replacement function should be used. */
-#undef memcmp
-
/* Define to `unsigned int' if <sys/types.h> does not define. */
#undef minor_t
-/* Define to rpl_mkdir if the replacement function should be used. */
-#undef mkdir
-
-/* Define to rpl_mktime if the replacement function should be used. */
-#undef mktime
+/* Define to the real name of the mktime_internal function. */
+#undef mktime_internal
/* Define to `int' if <sys/types.h> does not define. */
#undef mode_t
@@ -1859,14 +3280,18 @@
/* Define to the name of the strftime replacement function. */
#undef my_strftime
+/* Define to the type of st_nlink in struct stat, or a supertype. */
+#undef nlink_t
+
/* Define to `long int' if <sys/types.h> does not define. */
#undef off_t
/* Define to `int' if <sys/types.h> does not define. */
#undef pid_t
-/* Define to rpl_putenv if the replacement function should be used. */
-#undef putenv
+/* Define as the type of the result of subtracting two pointers, if the system
+ doesn't define it. */
+#undef ptrdiff_t
/* Define to rpl_re_comp if the replacement should be used. */
#undef re_comp
@@ -1901,9 +3326,6 @@
/* Define to rpl_re_syntax_options if the replacement should be used. */
#undef re_syntax_options
-/* Define to rpl_realloc if the replacement function should be used. */
-#undef realloc
-
/* Define to rpl_regcomp if the replacement should be used. */
#undef regcomp
@@ -1916,13 +3338,19 @@
/* Define to rpl_regfree if the replacement should be used. */
#undef regfree
-/* Define to rpl_rename_dest_slash if the replacement function should be used.
- */
-#undef rename
-
-/* Define to equivalent of C99 restrict keyword, or to nothing if this is not
- supported. Do not define if restrict is supported directly. */
+/* Define to the equivalent of the C99 'restrict' keyword, or to
+ nothing if this is not supported. Do not define if restrict is
+ supported directly. */
#undef restrict
+/* Work around a bug in Sun C++: it does not support _Restrict or
+ __restrict__, even though the corresponding Sun C compiler ends up with
+ "#define restrict _Restrict" or "#define restrict __restrict__" in the
+ previous line. Perhaps some future version of Sun C++ will work with
+ restrict; if so, hopefully it defines __RESTRICT like Sun C does. */
+#if defined __SUNPRO_CC && !defined __RESTRICT
+# define _Restrict
+# define __restrict__
+#endif
/* Define to `unsigned int' if <sys/types.h> does not define. */
#undef size_t
@@ -1933,20 +3361,48 @@
/* Define as a signed type of the same size as size_t. */
#undef ssize_t
-/* Define to rpl_strnlen if the replacement function should be used. */
-#undef strnlen
-
-/* Define to rpl_strtod if the replacement function should be used. */
-#undef strtod
-
/* Define to rpl_tzset if the wrapper function should be used. */
#undef tzset
/* Define to `int' if <sys/types.h> doesn't define. */
#undef uid_t
-/* Define to rpl_utime if the replacement function should be used. */
-#undef utime
+/* Define as a marker that can be attached to declarations that might not
+ be used. This helps to reduce warnings, such as from
+ GCC -Wunused-parameter. */
+#if __GNUC__ >= 3 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 7)
+# define _GL_UNUSED __attribute__ ((__unused__))
+#else
+# define _GL_UNUSED
+#endif
+/* The name _UNUSED_PARAMETER_ is an earlier spelling, although the name
+ is a misnomer outside of parameter lists. */
+#define _UNUSED_PARAMETER_ _GL_UNUSED
+
+/* gcc supports the "unused" attribute on possibly unused labels, and
+ g++ has since version 4.5. Note to support C++ as well as C,
+ _GL_UNUSED_LABEL should be used with a trailing ; */
+#if !defined __cplusplus || __GNUC__ > 4 \
+ || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5)
+# define _GL_UNUSED_LABEL _GL_UNUSED
+#else
+# define _GL_UNUSED_LABEL
+#endif
+
+/* The __pure__ attribute was added in gcc 2.96. */
+#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96)
+# define _GL_ATTRIBUTE_PURE __attribute__ ((__pure__))
+#else
+# define _GL_ATTRIBUTE_PURE /* empty */
+#endif
+
+/* The __const__ attribute was added in gcc 2.95. */
+#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 95)
+# define _GL_ATTRIBUTE_CONST __attribute__ ((__const__))
+#else
+# define _GL_ATTRIBUTE_CONST /* empty */
+#endif
+
/* Define as a macro for copying va_list variables. */
#undef va_copy
diff --git a/lib/copy-acl.c b/lib/copy-acl.c
new file mode 100644
index 0000000..4b6b443
--- /dev/null
+++ b/lib/copy-acl.c
@@ -0,0 +1,61 @@
+/* Copy access control list from one file to file. -*- coding: utf-8 -*-
+
+ Copyright (C) 2002-2003, 2005-2016 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 <http://www.gnu.org/licenses/>.
+
+ Written by Paul Eggert, Andreas Grünbacher, and Bruno Haible. */
+
+#include <config.h>
+
+#include "acl.h"
+
+#include <errno.h>
+
+#include "quote.h"
+#include "error.h"
+#include "gettext.h"
+#define _(msgid) gettext (msgid)
+
+
+/* Copy access control lists from one file to another. If SOURCE_DESC is
+ a valid file descriptor, use file descriptor operations, else use
+ filename based operations on SRC_NAME. Likewise for DEST_DESC and
+ DST_NAME.
+ If access control lists are not available, fchmod the target file to
+ MODE. Also sets the non-permission bits of the destination file
+ (S_ISUID, S_ISGID, S_ISVTX) to those from MODE if any are set.
+ Return 0 if successful, otherwise output a diagnostic and return a
+ negative error code. */
+
+int
+copy_acl (const char *src_name, int source_desc, const char *dst_name,
+ int dest_desc, mode_t mode)
+{
+ int ret = qcopy_acl (src_name, source_desc, dst_name, dest_desc, mode);
+ switch (ret)
+ {
+ case -2:
+ error (0, errno, "%s", quote (src_name));
+ break;
+
+ case -1:
+ error (0, errno, _("preserving permissions for %s"), quote (dst_name));
+ break;
+
+ default:
+ break;
+ }
+ return ret;
+}
diff --git a/lib/creat-safer.c b/lib/creat-safer.c
index f4a2e59..c49bc71 100644
--- a/lib/creat-safer.c
+++ b/lib/creat-safer.c
@@ -1,11 +1,11 @@
/* Invoke creat, but avoid some glitches.
- Copyright (C) 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2005-2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Jim Meyering. */
diff --git a/lib/ctype.in.h b/lib/ctype.in.h
new file mode 100644
index 0000000..217812d
--- /dev/null
+++ b/lib/ctype.in.h
@@ -0,0 +1,57 @@
+/* A substitute for ISO C99 <ctype.h>, for platforms on which it is incomplete.
+
+ Copyright (C) 2009-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Bruno Haible. */
+
+/*
+ * ISO C 99 <ctype.h> for platforms on which it is incomplete.
+ * <http://www.opengroup.org/onlinepubs/9699919799/basedefs/ctype.h.html>
+ */
+
+#ifndef _@GUARD_PREFIX@_CTYPE_H
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+/* Include the original <ctype.h>. */
+/* The include_next requires a split double-inclusion guard. */
+#@INCLUDE_NEXT@ @NEXT_CTYPE_H@
+
+#ifndef _@GUARD_PREFIX@_CTYPE_H
+#define _@GUARD_PREFIX@_CTYPE_H
+
+/* The definitions of _GL_FUNCDECL_RPL etc. are copied here. */
+
+/* The definition of _GL_WARN_ON_USE is copied here. */
+
+/* Return non-zero if c is a blank, i.e. a space or tab character. */
+#if @GNULIB_ISBLANK@
+# if !@HAVE_ISBLANK@
+_GL_EXTERN_C int isblank (int c);
+# endif
+#elif defined GNULIB_POSIXCHECK
+# undef isblank
+# if HAVE_RAW_DECL_ISBLANK
+_GL_WARN_ON_USE (isblank, "isblank is unportable - "
+ "use gnulib module isblank for portability");
+# endif
+#endif
+
+#endif /* _@GUARD_PREFIX@_CTYPE_H */
+#endif /* _@GUARD_PREFIX@_CTYPE_H */
diff --git a/lib/cycle-check.c b/lib/cycle-check.c
index 5359d71..0181996 100644
--- a/lib/cycle-check.c
+++ b/lib/cycle-check.c
@@ -1,11 +1,11 @@
/* help detect directory cycles efficiently
- Copyright (C) 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2003-2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,29 +13,27 @@
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with this program; see the file COPYING.
- If not, write to the Free Software Foundation,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Jim Meyering */
#include <config.h>
+#include "cycle-check.h"
+
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
-#include <assert.h>
#include <stdlib.h>
-
#include <stdbool.h>
-#include "cycle-check.h"
+#include "assure.h"
#define CC_MAGIC 9827862
/* Return true if I is a power of 2, or is zero. */
-static inline bool
+static bool
is_zero_or_power_of_two (uintmax_t i)
{
return (i & (i - 1)) == 0;
@@ -52,14 +50,14 @@ cycle_check_init (struct cycle_check_state *state)
descending chdir call, with SB corresponding to the chdir operand.
If SB corresponds to a directory that has already been seen,
return true to indicate that there is a directory cycle.
- Note that this is done `lazily', which means that some of
+ Note that this is done "lazily", which means that some of
the directories in the cycle may be processed twice before
the cycle is detected. */
bool
cycle_check (struct cycle_check_state *state, struct stat const *sb)
{
- assert (state->magic == CC_MAGIC);
+ assure (state->magic == CC_MAGIC);
/* If the current directory ever happens to be the same
as the one we last recorded for the cycle detection,
@@ -67,17 +65,17 @@ cycle_check (struct cycle_check_state *state, struct stat const *sb)
if (state->chdir_counter && SAME_INODE (*sb, state->dev_ino))
return true;
- /* If the number of `descending' chdir calls is a power of two,
+ /* If the number of "descending" chdir calls is a power of two,
record the dev/ino of the current directory. */
if (is_zero_or_power_of_two (++(state->chdir_counter)))
{
/* On all architectures that we know about, if the counter
- overflows then there is a directory cycle here somewhere,
- even if we haven't detected it yet. Typically this happens
- only after the counter is incremented 2**64 times, so it's a
- fairly theoretical point. */
+ overflows then there is a directory cycle here somewhere,
+ even if we haven't detected it yet. Typically this happens
+ only after the counter is incremented 2**64 times, so it's a
+ fairly theoretical point. */
if (state->chdir_counter == 0)
- return true;
+ return true;
state->dev_ino.st_dev = sb->st_dev;
state->dev_ino.st_ino = sb->st_ino;
diff --git a/lib/cycle-check.h b/lib/cycle-check.h
index afd7a8f..10c9a88 100644
--- a/lib/cycle-check.h
+++ b/lib/cycle-check.h
@@ -1,11 +1,11 @@
/* help detect directory cycles efficiently
- Copyright (C) 2003, 2004, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2003-2004, 2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,9 +13,7 @@
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with this program; see the file COPYING.
- If not, write to the Free Software Foundation,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Jim Meyering */
@@ -37,18 +35,18 @@ struct cycle_check_state
void cycle_check_init (struct cycle_check_state *state);
bool cycle_check (struct cycle_check_state *state, struct stat const *sb);
-# define CYCLE_CHECK_REFLECT_CHDIR_UP(State, SB_dir, SB_subdir) \
- do \
- { \
+# define CYCLE_CHECK_REFLECT_CHDIR_UP(State, SB_dir, SB_subdir) \
+ do \
+ { \
/* You must call cycle_check at least once before using this macro. */ \
- if ((State)->chdir_counter == 0) \
- abort (); \
- if (SAME_INODE ((State)->dev_ino, SB_subdir)) \
- { \
- (State)->dev_ino.st_dev = (SB_dir).st_dev; \
- (State)->dev_ino.st_ino = (SB_dir).st_ino; \
- } \
- } \
+ if ((State)->chdir_counter == 0) \
+ abort (); \
+ if (SAME_INODE ((State)->dev_ino, SB_subdir)) \
+ { \
+ (State)->dev_ino.st_dev = (SB_dir).st_dev; \
+ (State)->dev_ino.st_ino = (SB_dir).st_ino; \
+ } \
+ } \
while (0)
#endif
diff --git a/lib/di-set.c b/lib/di-set.c
new file mode 100644
index 0000000..daf9516
--- /dev/null
+++ b/lib/di-set.c
@@ -0,0 +1,259 @@
+/* Set operations for device-inode pairs stored in a space-efficient manner.
+
+ Copyright 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* written by Paul Eggert and Jim Meyering */
+
+#include <config.h>
+#include "di-set.h"
+
+#include "hash.h"
+#include "ino-map.h"
+
+#include <limits.h>
+#include <stdlib.h>
+
+/* The hash package hashes "void *", but this package wants to hash
+ integers. Use integers that are as large as possible, but no
+ larger than void *, so that they can be cast to void * and back
+ without losing information. */
+typedef size_t hashint;
+#define HASHINT_MAX ((hashint) -1)
+
+/* Integers represent inode numbers. Integers in the range
+ 1..(LARGE_INO_MIN-1) represent inode numbers directly. (The hash
+ package does not work with null pointers, so inode 0 cannot be used
+ as a key.) To find the representations of other inode numbers, map
+ them through INO_MAP. */
+#define LARGE_INO_MIN (HASHINT_MAX / 2)
+
+/* Set operations for device-inode pairs stored in a space-efficient
+ manner. Use a two-level hash table. The top level hashes by
+ device number, as there are typically a small number of devices.
+ The lower level hashes by mapped inode numbers. In the typical
+ case where the inode number is positive and small, the inode number
+ maps to itself, masquerading as a void * value; otherwise, its
+ value is the result of hashing the inode value through INO_MAP. */
+
+/* A pair that maps a device number to a set of inode numbers. */
+struct di_ent
+{
+ dev_t dev;
+ struct hash_table *ino_set;
+};
+
+/* A two-level hash table that manages and indexes these pairs. */
+struct di_set
+{
+ /* Map device numbers to sets of inode number representatives. */
+ struct hash_table *dev_map;
+
+ /* If nonnull, map large inode numbers to their small
+ representatives. If null, there are no large inode numbers in
+ this set. */
+ struct ino_map *ino_map;
+
+ /* Cache of the most recently allocated and otherwise-unused storage
+ for probing this table. */
+ struct di_ent *probe;
+};
+
+/* Hash a device-inode-set entry. */
+static size_t
+di_ent_hash (void const *x, size_t table_size)
+{
+ struct di_ent const *p = x;
+ dev_t dev = p->dev;
+
+ /* When DEV is wider than size_t, exclusive-OR the words of DEV into H.
+ This avoids loss of info, without applying % to the wider type,
+ which could be quite slow on some systems. */
+ size_t h = dev;
+ unsigned int i;
+ unsigned int n_words = sizeof dev / sizeof h + (sizeof dev % sizeof h != 0);
+ for (i = 1; i < n_words; i++)
+ h ^= dev >> CHAR_BIT * sizeof h * i;
+
+ return h % table_size;
+}
+
+/* Return true if two device-inode-set entries are the same. */
+static bool
+di_ent_compare (void const *x, void const *y)
+{
+ struct di_ent const *a = x;
+ struct di_ent const *b = y;
+ return a->dev == b->dev;
+}
+
+/* Free a device-inode-set entry. */
+static void
+di_ent_free (void *v)
+{
+ struct di_ent *a = v;
+ hash_free (a->ino_set);
+ free (a);
+}
+
+/* Create a set of device-inode pairs. Return NULL on allocation failure. */
+struct di_set *
+di_set_alloc (void)
+{
+ struct di_set *dis = malloc (sizeof *dis);
+ if (dis)
+ {
+ enum { INITIAL_DEV_MAP_SIZE = 11 };
+ dis->dev_map = hash_initialize (INITIAL_DEV_MAP_SIZE, NULL,
+ di_ent_hash, di_ent_compare,
+ di_ent_free);
+ if (! dis->dev_map)
+ {
+ free (dis);
+ return NULL;
+ }
+ dis->ino_map = NULL;
+ dis->probe = NULL;
+ }
+
+ return dis;
+}
+
+/* Free a set of device-inode pairs. */
+void
+di_set_free (struct di_set *dis)
+{
+ hash_free (dis->dev_map);
+ free (dis->ino_map);
+ free (dis->probe);
+ free (dis);
+}
+
+/* Hash an encoded inode number I. */
+static size_t
+di_ino_hash (void const *i, size_t table_size)
+{
+ return (hashint) i % table_size;
+}
+
+/* Using the DIS table, map a device to a hash table that represents
+ a set of inode numbers. Return NULL on error. */
+static struct hash_table *
+map_device (struct di_set *dis, dev_t dev)
+{
+ /* Find space for the probe, reusing the cache if available. */
+ struct di_ent *ent;
+ struct di_ent *probe = dis->probe;
+ if (probe)
+ {
+ /* If repeating a recent query, return the cached result. */
+ if (probe->dev == dev)
+ return probe->ino_set;
+ }
+ else
+ {
+ dis->probe = probe = malloc (sizeof *probe);
+ if (! probe)
+ return NULL;
+ }
+
+ /* Probe for the device. */
+ probe->dev = dev;
+ ent = hash_insert (dis->dev_map, probe);
+ if (! ent)
+ return NULL;
+
+ if (ent != probe)
+ {
+ /* Use the existing entry. */
+ probe->ino_set = ent->ino_set;
+ }
+ else
+ {
+ enum { INITIAL_INO_SET_SIZE = 1021 };
+
+ /* Prepare to allocate a new probe next time; this one is in use. */
+ dis->probe = NULL;
+
+ /* DEV is new; allocate an inode set for it. */
+ probe->ino_set = hash_initialize (INITIAL_INO_SET_SIZE, NULL,
+ di_ino_hash, NULL, NULL);
+ }
+
+ return probe->ino_set;
+}
+
+/* Using the DIS table, map an inode number to a mapped value.
+ Return INO_MAP_INSERT_FAILURE on error. */
+static hashint
+map_inode_number (struct di_set *dis, ino_t ino)
+{
+ if (0 < ino && ino < LARGE_INO_MIN)
+ return ino;
+
+ if (! dis->ino_map)
+ {
+ dis->ino_map = ino_map_alloc (LARGE_INO_MIN);
+ if (! dis->ino_map)
+ return INO_MAP_INSERT_FAILURE;
+ }
+
+ return ino_map_insert (dis->ino_map, ino);
+}
+
+/* Attempt to insert the DEV,INO pair into the set DIS.
+ If it matches a pair already in DIS, keep that pair and return 0.
+ Otherwise, if insertion is successful, return 1.
+ Upon any failure return -1. */
+int
+di_set_insert (struct di_set *dis, dev_t dev, ino_t ino)
+{
+ hashint i;
+
+ /* Map the device number to a set of inodes. */
+ struct hash_table *ino_set = map_device (dis, dev);
+ if (! ino_set)
+ return -1;
+
+ /* Map the inode number to a small representative I. */
+ i = map_inode_number (dis, ino);
+ if (i == INO_MAP_INSERT_FAILURE)
+ return -1;
+
+ /* Put I into the inode set. */
+ return hash_insert_if_absent (ino_set, (void const *) i, NULL);
+}
+
+/* Look up the DEV,INO pair in the set DIS.
+ If found, return 1; if not found, return 0.
+ Upon any failure return -1. */
+int
+di_set_lookup (struct di_set *dis, dev_t dev, ino_t ino)
+{
+ hashint i;
+
+ /* Map the device number to a set of inodes. */
+ struct hash_table *ino_set = map_device (dis, dev);
+ if (! ino_set)
+ return -1;
+
+ /* Map the inode number to a small representative I. */
+ i = map_inode_number (dis, ino);
+ if (i == INO_MAP_INSERT_FAILURE)
+ return -1;
+
+ /* Perform the look-up. */
+ return !!hash_lookup (ino_set, (void const *) i);
+}
diff --git a/lib/di-set.h b/lib/di-set.h
new file mode 100644
index 0000000..abc3161
--- /dev/null
+++ b/lib/di-set.h
@@ -0,0 +1,19 @@
+#ifndef _GL_DI_SET_H
+# define _GL_DI_SET_H
+
+# include <sys/types.h>
+
+# undef _GL_ATTRIBUTE_NONNULL
+# if __GNUC__ == 3 && __GNUC_MINOR__ >= 3 || 3 < __GNUC__
+# define _GL_ATTRIBUTE_NONNULL(m) __attribute__ ((__nonnull__ (m)))
+# else
+# define _GL_ATTRIBUTE_NONNULL(m)
+# endif
+
+struct di_set *di_set_alloc (void);
+int di_set_insert (struct di_set *, dev_t, ino_t) _GL_ATTRIBUTE_NONNULL (1);
+void di_set_free (struct di_set *) _GL_ATTRIBUTE_NONNULL (1);
+int di_set_lookup (struct di_set *dis, dev_t dev, ino_t ino)
+ _GL_ATTRIBUTE_NONNULL (1);
+
+#endif
diff --git a/lib/diacrit.c b/lib/diacrit.c
index fc2d6b7..6808fae 100644
--- a/lib/diacrit.c
+++ b/lib/diacrit.c
@@ -1,16 +1,16 @@
-/* Diacritics processing for a few character codes.
+/* Diacritics processing for a few character codes. -*- coding: utf-8 -*-
- Copyright (C) 1990, 1991, 1992, 1993, 2000, 2006 Free Software
- Foundation, Inc.
+ Copyright (C) 1990-1993, 2000, 2006, 2009-2016 Free Software Foundation,
+ Inc.
François Pinard <pinard@iro.umontreal.ca>, 1988.
All this file is a temporary hack, waiting for locales in GNU.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -18,9 +18,7 @@
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with this program; see the file COPYING.
- If not, write to the Free Software Foundation,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
@@ -31,7 +29,7 @@
/*--------------------------------------------------------------------.
| For each alphabetic character, returns what it would be without its |
-| possible diacritic symbol. |
+| possible diacritic symbol. |
`--------------------------------------------------------------------*/
const char diacrit_base[256] =
@@ -96,10 +94,10 @@ const char diacrit_base[256] =
/*------------------------------------------------------------------------.
| For each alphabetic character, returns a code of what its diacritic is, |
-| according to the following codes: 1 (eE) over aA for latin diphtongs; 2 |
-| (') acute accent; 3 (`) grave accent; 4 (^) circumflex accent; 5 (") |
-| umlaut or diaraesis; 6 (~) tilda; 7 (,) cedilla; 8 (o) covering degree |
-| symbol; 9 (|) slashed character. |
+| according to the following codes: 1 (eE) over aA for latin diphthongs; |
+| 2 (') acute accent; 3 (`) grave accent; 4 (^) circumflex accent; 5 (") |
+| umlaut or diaeresis; 6 (~) tilda; 7 (,) cedilla; 8 (o) covering degree |
+| symbol; 9 (|) slashed character. |
`------------------------------------------------------------------------*/
const char diacrit_diac[256] =
diff --git a/lib/diacrit.h b/lib/diacrit.h
index 54eb60f..3a590f8 100644
--- a/lib/diacrit.h
+++ b/lib/diacrit.h
@@ -1,13 +1,13 @@
-/* Diacritics processing for a few character codes.
- Copyright (C) 1990, 1991, 1992, 1993 Free Software Foundation, Inc.
+/* Diacritics processing for a few character codes. -*- coding: utf-8 -*-
+ Copyright (C) 1990-1993, 2009-2016 Free Software Foundation, Inc.
François Pinard <pinard@iro.umontreal.ca>, 1988.
All this file is a temporary hack, waiting for locales in GNU.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -15,9 +15,7 @@
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with this program; see the file COPYING.
- If not, write to the Free Software Foundation,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
extern const char diacrit_base[]; /* characters without diacritics */
extern const char diacrit_diac[]; /* diacritic code for each character */
diff --git a/lib/dirchownmod.c b/lib/dirchownmod.c
index b3e9518..09dcc5c 100644
--- a/lib/dirchownmod.c
+++ b/lib/dirchownmod.c
@@ -1,11 +1,11 @@
/* Change the ownership and mode bits of a directory.
- Copyright (C) 2006 Free Software Foundation, Inc.
+ Copyright (C) 2006-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
@@ -27,8 +26,6 @@
#include <sys/stat.h>
#include <unistd.h>
-#include "lchmod.h"
-#include "lchown.h"
#include "stat-macros.h"
#ifndef HAVE_FCHMOD
@@ -62,8 +59,8 @@
int
dirchownmod (int fd, char const *dir, mode_t mkdir_mode,
- uid_t owner, gid_t group,
- mode_t mode, mode_t mode_bits)
+ uid_t owner, gid_t group,
+ mode_t mode, mode_t mode_bits)
{
struct stat st;
int result = (fd < 0 ? stat (dir, &st) : fstat (fd, &st));
@@ -73,71 +70,71 @@ dirchownmod (int fd, char const *dir, mode_t mkdir_mode,
mode_t dir_mode = st.st_mode;
/* Check whether DIR is a directory. If FD is nonnegative, this
- check avoids changing the ownership and mode bits of the
- wrong file in many cases. This doesn't fix all the race
- conditions, but it is better than nothing. */
+ check avoids changing the ownership and mode bits of the
+ wrong file in many cases. This doesn't fix all the race
+ conditions, but it is better than nothing. */
if (! S_ISDIR (dir_mode))
- {
- errno = ENOTDIR;
- result = -1;
- }
+ {
+ errno = ENOTDIR;
+ result = -1;
+ }
else
- {
- /* If at least one of the S_IXUGO bits are set, chown might
- clear the S_ISUID and S_SGID bits. Keep track of any
- file mode bits whose values are indeterminate due to this
- issue. */
- mode_t indeterminate = 0;
-
- /* On some systems, chown clears S_ISUID and S_ISGID, so do
- chown before chmod. On older System V hosts, ordinary
- users can give their files away via chown; don't worry
- about that here, since users shouldn't do that. */
-
- if ((owner != (uid_t) -1 && owner != st.st_uid)
- || (group != (gid_t) -1 && group != st.st_gid))
- {
- result = (0 <= fd
- ? fchown (fd, owner, group)
- : mkdir_mode != (mode_t) -1
- ? lchown (dir, owner, group)
- : chown (dir, owner, group));
-
- /* Either the user cares about an indeterminate bit and
- it'll be set properly by chmod below, or the user
- doesn't care and it's OK to use the bit's pre-chown
- value. So there's no need to re-stat DIR here. */
-
- if (result == 0 && (dir_mode & S_IXUGO))
- indeterminate = dir_mode & (S_ISUID | S_ISGID);
- }
-
- /* If the file mode bits might not be right, use chmod to
- change them. Don't change bits the user doesn't care
- about. */
- if (result == 0 && (((dir_mode ^ mode) | indeterminate) & mode_bits))
- {
- mode_t chmod_mode =
- mode | (dir_mode & CHMOD_MODE_BITS & ~mode_bits);
- result = (HAVE_FCHMOD && 0 <= fd
- ? fchmod (fd, chmod_mode)
- : mkdir_mode != (mode_t) -1
- ? lchmod (dir, chmod_mode)
- : chmod (dir, chmod_mode));
- }
- }
+ {
+ /* If at least one of the S_IXUGO bits are set, chown might
+ clear the S_ISUID and S_SGID bits. Keep track of any
+ file mode bits whose values are indeterminate due to this
+ issue. */
+ mode_t indeterminate = 0;
+
+ /* On some systems, chown clears S_ISUID and S_ISGID, so do
+ chown before chmod. On older System V hosts, ordinary
+ users can give their files away via chown; don't worry
+ about that here, since users shouldn't do that. */
+
+ if ((owner != (uid_t) -1 && owner != st.st_uid)
+ || (group != (gid_t) -1 && group != st.st_gid))
+ {
+ result = (0 <= fd
+ ? fchown (fd, owner, group)
+ : mkdir_mode != (mode_t) -1
+ ? lchown (dir, owner, group)
+ : chown (dir, owner, group));
+
+ /* Either the user cares about an indeterminate bit and
+ it'll be set properly by chmod below, or the user
+ doesn't care and it's OK to use the bit's pre-chown
+ value. So there's no need to re-stat DIR here. */
+
+ if (result == 0 && (dir_mode & S_IXUGO))
+ indeterminate = dir_mode & (S_ISUID | S_ISGID);
+ }
+
+ /* If the file mode bits might not be right, use chmod to
+ change them. Don't change bits the user doesn't care
+ about. */
+ if (result == 0 && (((dir_mode ^ mode) | indeterminate) & mode_bits))
+ {
+ mode_t chmod_mode =
+ mode | (dir_mode & CHMOD_MODE_BITS & ~mode_bits);
+ result = (HAVE_FCHMOD && 0 <= fd
+ ? fchmod (fd, chmod_mode)
+ : mkdir_mode != (mode_t) -1
+ ? lchmod (dir, chmod_mode)
+ : chmod (dir, chmod_mode));
+ }
+ }
}
if (0 <= fd)
{
if (result == 0)
- result = close (fd);
+ result = close (fd);
else
- {
- int e = errno;
- close (fd);
- errno = e;
- }
+ {
+ int e = errno;
+ close (fd);
+ errno = e;
+ }
}
return result;
diff --git a/lib/dirent--.h b/lib/dirent--.h
new file mode 100644
index 0000000..ea4c114
--- /dev/null
+++ b/lib/dirent--.h
@@ -0,0 +1,24 @@
+/* Like dirent.h, but redefine some names to avoid glitches.
+
+ Copyright (C) 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Eric Blake. */
+
+#include "dirent-safer.h"
+
+#undef opendir
+#define opendir opendir_safer
+#define GNULIB_defined_opendir 1
diff --git a/lib/dirent-private.h b/lib/dirent-private.h
new file mode 100644
index 0000000..9b200f3
--- /dev/null
+++ b/lib/dirent-private.h
@@ -0,0 +1,40 @@
+/* Private details of the DIR type.
+ Copyright (C) 2011-2016 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _DIRENT_PRIVATE_H
+#define _DIRENT_PRIVATE_H 1
+
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+
+struct gl_directory
+{
+ /* Status, or error code to produce in next readdir() call.
+ -2 means the end of the directory is already reached,
+ -1 means the entry was already filled by FindFirstFile,
+ 0 means the entry needs to be filled using FindNextFile.
+ A positive value is an error code. */
+ int status;
+ /* Handle, reading the directory, at current position. */
+ HANDLE current;
+ /* Found directory entry. */
+ WIN32_FIND_DATA entry;
+ /* Argument to pass to FindFirstFile. It consists of the absolutized
+ directory name, followed by a directory separator and the wildcards. */
+ char dir_name_mask[1];
+};
+
+#endif /* _DIRENT_PRIVATE_H */
diff --git a/lib/dirent-safer.h b/lib/dirent-safer.h
new file mode 100644
index 0000000..93d3188
--- /dev/null
+++ b/lib/dirent-safer.h
@@ -0,0 +1,22 @@
+/* Invoke dirent-like functions, but avoid some glitches.
+
+ Copyright (C) 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Eric Blake. */
+
+#include <dirent.h>
+
+DIR *opendir_safer (const char *name);
diff --git a/lib/dirent.in.h b/lib/dirent.in.h
new file mode 100644
index 0000000..65482d7
--- /dev/null
+++ b/lib/dirent.in.h
@@ -0,0 +1,267 @@
+/* A GNU-like <dirent.h>.
+ Copyright (C) 2006-2016 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _@GUARD_PREFIX@_DIRENT_H
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+/* The include_next requires a split double-inclusion guard. */
+#if @HAVE_DIRENT_H@
+# @INCLUDE_NEXT@ @NEXT_DIRENT_H@
+#endif
+
+#ifndef _@GUARD_PREFIX@_DIRENT_H
+#define _@GUARD_PREFIX@_DIRENT_H
+
+/* Get ino_t. Needed on some systems, including glibc 2.8. */
+#include <sys/types.h>
+
+#if !@HAVE_DIRENT_H@
+/* Define types DIR and 'struct dirent'. */
+# if !GNULIB_defined_struct_dirent
+struct dirent
+{
+ char d_type;
+ char d_name[1];
+};
+/* Possible values for 'd_type'. */
+# define DT_UNKNOWN 0
+# define DT_FIFO 1 /* FIFO */
+# define DT_CHR 2 /* character device */
+# define DT_DIR 4 /* directory */
+# define DT_BLK 6 /* block device */
+# define DT_REG 8 /* regular file */
+# define DT_LNK 10 /* symbolic link */
+# define DT_SOCK 12 /* socket */
+# define DT_WHT 14 /* whiteout */
+typedef struct gl_directory DIR;
+# define GNULIB_defined_struct_dirent 1
+# endif
+#endif
+
+/* The __attribute__ feature is available in gcc versions 2.5 and later.
+ The attribute __pure__ was added in gcc 2.96. */
+#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96)
+# define _GL_ATTRIBUTE_PURE __attribute__ ((__pure__))
+#else
+# define _GL_ATTRIBUTE_PURE /* empty */
+#endif
+
+/* The definitions of _GL_FUNCDECL_RPL etc. are copied here. */
+
+/* The definition of _GL_ARG_NONNULL is copied here. */
+
+/* The definition of _GL_WARN_ON_USE is copied here. */
+
+
+/* Declare overridden functions. */
+
+#if @GNULIB_OPENDIR@
+# if @REPLACE_OPENDIR@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef opendir
+# define opendir rpl_opendir
+# define GNULIB_defined_opendir 1
+# endif
+_GL_FUNCDECL_RPL (opendir, DIR *, (const char *dir_name) _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (opendir, DIR *, (const char *dir_name));
+# else
+# if !@HAVE_OPENDIR@
+_GL_FUNCDECL_SYS (opendir, DIR *, (const char *dir_name) _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (opendir, DIR *, (const char *dir_name));
+# endif
+_GL_CXXALIASWARN (opendir);
+#elif defined GNULIB_POSIXCHECK
+# undef opendir
+# if HAVE_RAW_DECL_OPENDIR
+_GL_WARN_ON_USE (opendir, "opendir is not portable - "
+ "use gnulib module opendir for portability");
+# endif
+#endif
+
+#if @GNULIB_READDIR@
+# if !@HAVE_READDIR@
+_GL_FUNCDECL_SYS (readdir, struct dirent *, (DIR *dirp) _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (readdir, struct dirent *, (DIR *dirp));
+_GL_CXXALIASWARN (readdir);
+#elif defined GNULIB_POSIXCHECK
+# undef readdir
+# if HAVE_RAW_DECL_READDIR
+_GL_WARN_ON_USE (readdir, "readdir is not portable - "
+ "use gnulib module readdir for portability");
+# endif
+#endif
+
+#if @GNULIB_REWINDDIR@
+# if !@HAVE_REWINDDIR@
+_GL_FUNCDECL_SYS (rewinddir, void, (DIR *dirp) _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (rewinddir, void, (DIR *dirp));
+_GL_CXXALIASWARN (rewinddir);
+#elif defined GNULIB_POSIXCHECK
+# undef rewinddir
+# if HAVE_RAW_DECL_REWINDDIR
+_GL_WARN_ON_USE (rewinddir, "rewinddir is not portable - "
+ "use gnulib module rewinddir for portability");
+# endif
+#endif
+
+#if @GNULIB_CLOSEDIR@
+# if @REPLACE_CLOSEDIR@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef closedir
+# define closedir rpl_closedir
+# define GNULIB_defined_closedir 1
+# endif
+_GL_FUNCDECL_RPL (closedir, int, (DIR *dirp) _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (closedir, int, (DIR *dirp));
+# else
+# if !@HAVE_CLOSEDIR@
+_GL_FUNCDECL_SYS (closedir, int, (DIR *dirp) _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (closedir, int, (DIR *dirp));
+# endif
+_GL_CXXALIASWARN (closedir);
+#elif defined GNULIB_POSIXCHECK
+# undef closedir
+# if HAVE_RAW_DECL_CLOSEDIR
+_GL_WARN_ON_USE (closedir, "closedir is not portable - "
+ "use gnulib module closedir for portability");
+# endif
+#endif
+
+#if @GNULIB_DIRFD@
+/* Return the file descriptor associated with the given directory stream,
+ or -1 if none exists. */
+# if @REPLACE_DIRFD@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef dirfd
+# define dirfd rpl_dirfd
+# endif
+_GL_FUNCDECL_RPL (dirfd, int, (DIR *) _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (dirfd, int, (DIR *));
+
+# ifdef __KLIBC__
+/* Gnulib internal hooks needed to maintain the dirfd metadata. */
+_GL_EXTERN_C int _gl_register_dirp_fd (int fd, DIR *dirp)
+ _GL_ARG_NONNULL ((2));
+_GL_EXTERN_C void _gl_unregister_dirp_fd (int fd);
+# endif
+# else
+# if defined __cplusplus && defined GNULIB_NAMESPACE && defined dirfd
+ /* dirfd is defined as a macro and not as a function.
+ Turn it into a function and get rid of the macro. */
+static inline int (dirfd) (DIR *dp) { return dirfd (dp); }
+# undef dirfd
+# endif
+# if !(@HAVE_DECL_DIRFD@ || defined dirfd)
+_GL_FUNCDECL_SYS (dirfd, int, (DIR *) _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (dirfd, int, (DIR *));
+# endif
+_GL_CXXALIASWARN (dirfd);
+#elif defined GNULIB_POSIXCHECK
+# undef dirfd
+# if HAVE_RAW_DECL_DIRFD
+_GL_WARN_ON_USE (dirfd, "dirfd is unportable - "
+ "use gnulib module dirfd for portability");
+# endif
+#endif
+
+#if @GNULIB_FDOPENDIR@
+/* Open a directory stream visiting the given directory file
+ descriptor. Return NULL and set errno if fd is not visiting a
+ directory. On success, this function consumes fd (it will be
+ implicitly closed either by this function or by a subsequent
+ closedir). */
+# if @REPLACE_FDOPENDIR@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef fdopendir
+# define fdopendir rpl_fdopendir
+# endif
+_GL_FUNCDECL_RPL (fdopendir, DIR *, (int fd));
+_GL_CXXALIAS_RPL (fdopendir, DIR *, (int fd));
+# else
+# if !@HAVE_FDOPENDIR@ || !@HAVE_DECL_FDOPENDIR@
+_GL_FUNCDECL_SYS (fdopendir, DIR *, (int fd));
+# endif
+_GL_CXXALIAS_SYS (fdopendir, DIR *, (int fd));
+# endif
+_GL_CXXALIASWARN (fdopendir);
+#elif defined GNULIB_POSIXCHECK
+# undef fdopendir
+# if HAVE_RAW_DECL_FDOPENDIR
+_GL_WARN_ON_USE (fdopendir, "fdopendir is unportable - "
+ "use gnulib module fdopendir for portability");
+# endif
+#endif
+
+#if @GNULIB_SCANDIR@
+/* Scan the directory DIR, calling FILTER on each directory entry.
+ Entries for which FILTER returns nonzero are individually malloc'd,
+ sorted using qsort with CMP, and collected in a malloc'd array in
+ *NAMELIST. Returns the number of entries selected, or -1 on error. */
+# if !@HAVE_SCANDIR@
+_GL_FUNCDECL_SYS (scandir, int,
+ (const char *dir, struct dirent ***namelist,
+ int (*filter) (const struct dirent *),
+ int (*cmp) (const struct dirent **, const struct dirent **))
+ _GL_ARG_NONNULL ((1, 2, 4)));
+# endif
+/* Need to cast, because on glibc systems, the fourth parameter is
+ int (*cmp) (const void *, const void *). */
+_GL_CXXALIAS_SYS_CAST (scandir, int,
+ (const char *dir, struct dirent ***namelist,
+ int (*filter) (const struct dirent *),
+ int (*cmp) (const struct dirent **, const struct dirent **)));
+_GL_CXXALIASWARN (scandir);
+#elif defined GNULIB_POSIXCHECK
+# undef scandir
+# if HAVE_RAW_DECL_SCANDIR
+_GL_WARN_ON_USE (scandir, "scandir is unportable - "
+ "use gnulib module scandir for portability");
+# endif
+#endif
+
+#if @GNULIB_ALPHASORT@
+/* Compare two 'struct dirent' entries alphabetically. */
+# if !@HAVE_ALPHASORT@
+_GL_FUNCDECL_SYS (alphasort, int,
+ (const struct dirent **, const struct dirent **)
+ _GL_ATTRIBUTE_PURE
+ _GL_ARG_NONNULL ((1, 2)));
+# endif
+/* Need to cast, because on glibc systems, the parameters are
+ (const void *, const void *). */
+_GL_CXXALIAS_SYS_CAST (alphasort, int,
+ (const struct dirent **, const struct dirent **));
+_GL_CXXALIASWARN (alphasort);
+#elif defined GNULIB_POSIXCHECK
+# undef alphasort
+# if HAVE_RAW_DECL_ALPHASORT
+_GL_WARN_ON_USE (alphasort, "alphasort is unportable - "
+ "use gnulib module alphasort for portability");
+# endif
+#endif
+
+
+#endif /* _@GUARD_PREFIX@_DIRENT_H */
+#endif /* _@GUARD_PREFIX@_DIRENT_H */
diff --git a/lib/dirent_.h b/lib/dirent_.h
deleted file mode 100644
index 3fa8480..0000000
--- a/lib/dirent_.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/* Wrapper around <dirent.h>.
- Copyright (C) 2006-2007 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-#ifndef _GL_DIRENT_H
-#define _GL_DIRENT_H
-
-#include @ABSOLUTE_DIRENT_H@
-
-
-/* Declare overridden functions. */
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#if @REPLACE_FCHDIR@
-# define opendir rpl_opendir
-extern DIR * opendir (const char *);
-# define closedir rpl_closedir
-extern int closedir (DIR *);
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-
-
-#endif /* _GL_DIRENT_H */
diff --git a/lib/dirfd.c b/lib/dirfd.c
index 06cb3c4..a325848 100644
--- a/lib/dirfd.c
+++ b/lib/dirfd.c
@@ -1,11 +1,11 @@
/* dirfd.c -- return the file descriptor associated with an open DIR*
- Copyright (C) 2001, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2001, 2006, 2008-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,17 +13,86 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Jim Meyering. */
#include <config.h>
-#include "dirfd.h"
+#include <dirent.h>
+#include <errno.h>
+
+#ifdef __KLIBC__
+# include <stdlib.h>
+# include <io.h>
+
+static struct dirp_fd_list
+{
+ DIR *dirp;
+ int fd;
+ struct dirp_fd_list *next;
+} *dirp_fd_start = NULL;
+
+/* Register fd associated with dirp to dirp_fd_list. */
+int
+_gl_register_dirp_fd (int fd, DIR *dirp)
+{
+ struct dirp_fd_list *new_dirp_fd = malloc (sizeof *new_dirp_fd);
+ if (!new_dirp_fd)
+ return -1;
+
+ new_dirp_fd->dirp = dirp;
+ new_dirp_fd->fd = fd;
+ new_dirp_fd->next = dirp_fd_start;
+
+ dirp_fd_start = new_dirp_fd;
+
+ return 0;
+}
+
+/* Unregister fd from dirp_fd_list with closing it */
+void
+_gl_unregister_dirp_fd (int fd)
+{
+ struct dirp_fd_list *dirp_fd;
+ struct dirp_fd_list *dirp_fd_prev;
+
+ for (dirp_fd_prev = NULL, dirp_fd = dirp_fd_start; dirp_fd;
+ dirp_fd_prev = dirp_fd, dirp_fd = dirp_fd->next)
+ {
+ if (dirp_fd->fd == fd)
+ {
+ if (dirp_fd_prev)
+ dirp_fd_prev->next = dirp_fd->next;
+ else /* dirp_fd == dirp_fd_start */
+ dirp_fd_start = dirp_fd_start->next;
+
+ close (fd);
+ free (dirp_fd);
+ break;
+ }
+ }
+}
+#endif
int
-dirfd (DIR const *dir_p)
+dirfd (DIR *dir_p)
{
- return DIR_TO_FD (dir_p);
+ int fd = DIR_TO_FD (dir_p);
+ if (fd == -1)
+#ifndef __KLIBC__
+ errno = ENOTSUP;
+#else
+ {
+ struct dirp_fd_list *dirp_fd;
+
+ for (dirp_fd = dirp_fd_start; dirp_fd; dirp_fd = dirp_fd->next)
+ if (dirp_fd->dirp == dir_p)
+ return dirp_fd->fd;
+
+ errno = EINVAL;
+ }
+#endif
+
+ return fd;
}
diff --git a/lib/dirfd.h b/lib/dirfd.h
deleted file mode 100644
index 05b7777..0000000
--- a/lib/dirfd.h
+++ /dev/null
@@ -1,29 +0,0 @@
-/* Declare dirfd, if necessary.
- Copyright (C) 2001, 2002, 2006 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-
- Written by Jim Meyering. */
-
-#include <sys/types.h>
-
-#include <dirent.h>
-
-#ifndef HAVE_DECL_DIRFD
-"this configure-time declaration test was not run"
-#endif
-#if !HAVE_DECL_DIRFD && !defined dirfd
-int dirfd (DIR const *);
-#endif
diff --git a/lib/dirname-lgpl.c b/lib/dirname-lgpl.c
new file mode 100644
index 0000000..a7aabf9
--- /dev/null
+++ b/lib/dirname-lgpl.c
@@ -0,0 +1,86 @@
+/* dirname.c -- return all but the last element in a file name
+
+ Copyright (C) 1990, 1998, 2000-2001, 2003-2006, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+#include "dirname.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+/* Return the length of the prefix of FILE that will be used by
+ dir_name. If FILE is in the working directory, this returns zero
+ even though 'dir_name (FILE)' will return ".". Works properly even
+ if there are trailing slashes (by effectively ignoring them). */
+
+size_t
+dir_len (char const *file)
+{
+ size_t prefix_length = FILE_SYSTEM_PREFIX_LEN (file);
+ size_t length;
+
+ /* Advance prefix_length beyond important leading slashes. */
+ prefix_length += (prefix_length != 0
+ ? (FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE
+ && ISSLASH (file[prefix_length]))
+ : (ISSLASH (file[0])
+ ? ((DOUBLE_SLASH_IS_DISTINCT_ROOT
+ && ISSLASH (file[1]) && ! ISSLASH (file[2])
+ ? 2 : 1))
+ : 0));
+
+ /* Strip the basename and any redundant slashes before it. */
+ for (length = last_component (file) - file;
+ prefix_length < length; length--)
+ if (! ISSLASH (file[length - 1]))
+ break;
+ return length;
+}
+
+
+/* In general, we can't use the builtin 'dirname' function if available,
+ since it has different meanings in different environments.
+ In some environments the builtin 'dirname' modifies its argument.
+
+ Return the leading directories part of FILE, allocated with malloc.
+ Works properly even if there are trailing slashes (by effectively
+ ignoring them). Return NULL on failure.
+
+ If lstat (FILE) would succeed, then { chdir (dir_name (FILE));
+ lstat (base_name (FILE)); } will access the same file. Likewise,
+ if the sequence { chdir (dir_name (FILE));
+ rename (base_name (FILE), "foo"); } succeeds, you have renamed FILE
+ to "foo" in the same directory FILE was in. */
+
+char *
+mdir_name (char const *file)
+{
+ size_t length = dir_len (file);
+ bool append_dot = (length == 0
+ || (FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE
+ && length == FILE_SYSTEM_PREFIX_LEN (file)
+ && file[2] != '\0' && ! ISSLASH (file[2])));
+ char *dir = malloc (length + append_dot + 1);
+ if (!dir)
+ return NULL;
+ memcpy (dir, file, length);
+ if (append_dot)
+ dir[length++] = '.';
+ dir[length] = '\0';
+ return dir;
+}
diff --git a/lib/dirname.c b/lib/dirname.c
index 16552c6..07aac13 100644
--- a/lib/dirname.c
+++ b/lib/dirname.c
@@ -1,12 +1,12 @@
/* dirname.c -- return all but the last element in a file name
- Copyright (C) 1990, 1998, 2000, 2001, 2003, 2004, 2005, 2006 Free Software
+ Copyright (C) 1990, 1998, 2000-2001, 2003-2006, 2009-2016 Free Software
Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,72 +14,25 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
#include "dirname.h"
+#include <stdlib.h>
#include <string.h>
#include "xalloc.h"
-/* Return the length of the prefix of FILE that will be used by
- dir_name. If FILE is in the working directory, this returns zero
- even though `dir_name (FILE)' will return ".". Works properly even
- if there are trailing slashes (by effectively ignoring them). */
-
-size_t
-dir_len (char const *file)
-{
- size_t prefix_length = FILE_SYSTEM_PREFIX_LEN (file);
- size_t length;
-
- /* Advance prefix_length beyond important leading slashes. */
- prefix_length += (prefix_length != 0
- ? (FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE
- && ISSLASH (file[prefix_length]))
- : (ISSLASH (file[0])
- ? ((DOUBLE_SLASH_IS_DISTINCT_ROOT
- && ISSLASH (file[1]) && ! ISSLASH (file[2])
- ? 2 : 1))
- : 0));
-
- /* Strip the basename and any redundant slashes before it. */
- for (length = last_component (file) - file;
- prefix_length < length; length--)
- if (! ISSLASH (file[length - 1]))
- break;
- return length;
-}
-
-
-/* In general, we can't use the builtin `dirname' function if available,
- since it has different meanings in different environments.
- In some environments the builtin `dirname' modifies its argument.
-
- Return the leading directories part of FILE, allocated with xmalloc.
- Works properly even if there are trailing slashes (by effectively
- ignoring them). Unlike POSIX dirname(), FILE cannot be NULL.
-
- If lstat (FILE) would succeed, then { chdir (dir_name (FILE));
- lstat (base_name (FILE)); } will access the same file. Likewise,
- if the sequence { chdir (dir_name (FILE));
- rename (base_name (FILE), "foo"); } succeeds, you have renamed FILE
- to "foo" in the same directory FILE was in. */
+/* Just like mdir_name (dirname-lgpl.c), except, rather than
+ returning NULL upon malloc failure, here, we report the
+ "memory exhausted" condition and exit. */
char *
dir_name (char const *file)
{
- size_t length = dir_len (file);
- bool append_dot = (length == 0
- || (FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE
- && length == FILE_SYSTEM_PREFIX_LEN (file)
- && file[2] != '\0' && ! ISSLASH (file[2])));
- char *dir = xmalloc (length + append_dot + 1);
- memcpy (dir, file, length);
- if (append_dot)
- dir[length++] = '.';
- dir[length] = '\0';
- return dir;
+ char *result = mdir_name (file);
+ if (!result)
+ xalloc_die ();
+ return result;
}
diff --git a/lib/dirname.h b/lib/dirname.h
index 91e7ed3..875b31b 100644
--- a/lib/dirname.h
+++ b/lib/dirname.h
@@ -1,11 +1,12 @@
/* Take file names apart into directory and base names.
- Copyright (C) 1998, 2001, 2003-2006 Free Software Foundation, Inc.
+ Copyright (C) 1998, 2001, 2003-2006, 2009-2016 Free Software Foundation,
+ Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,58 +14,41 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifndef DIRNAME_H_
# define DIRNAME_H_ 1
# include <stdbool.h>
# include <stddef.h>
+# include "dosname.h"
# ifndef DIRECTORY_SEPARATOR
# define DIRECTORY_SEPARATOR '/'
# endif
-# ifndef ISSLASH
-# define ISSLASH(C) ((C) == DIRECTORY_SEPARATOR)
-# endif
-
-# ifndef FILE_SYSTEM_PREFIX_LEN
-# if FILE_SYSTEM_ACCEPTS_DRIVE_LETTER_PREFIX
- /* This internal macro assumes ASCII, but all hosts that support drive
- letters use ASCII. */
-# define _IS_DRIVE_LETTER(c) (((unsigned int) (c) | ('a' - 'A')) - 'a' \
- <= 'z' - 'a')
-# define FILE_SYSTEM_PREFIX_LEN(Filename) \
- (_IS_DRIVE_LETTER ((Filename)[0]) && (Filename)[1] == ':' ? 2 : 0)
-# else
-# define FILE_SYSTEM_PREFIX_LEN(Filename) 0
-# endif
-# endif
-
-# ifndef FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE
-# define FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE 0
-# endif
-
# ifndef DOUBLE_SLASH_IS_DISTINCT_ROOT
# define DOUBLE_SLASH_IS_DISTINCT_ROOT 0
# endif
-# if FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE
-# define IS_ABSOLUTE_FILE_NAME(F) ISSLASH ((F)[FILE_SYSTEM_PREFIX_LEN (F)])
-# else
-# define IS_ABSOLUTE_FILE_NAME(F) \
- (ISSLASH ((F)[0]) || 0 < FILE_SYSTEM_PREFIX_LEN (F))
-# endif
-# define IS_RELATIVE_FILE_NAME(F) (! IS_ABSOLUTE_FILE_NAME (F))
+#ifdef __cplusplus
+extern "C" {
+#endif
+# if GNULIB_DIRNAME
char *base_name (char const *file);
char *dir_name (char const *file);
-size_t base_len (char const *file);
-size_t dir_len (char const *file);
-char *last_component (char const *file);
+# endif
+
+char *mdir_name (char const *file);
+size_t base_len (char const *file) _GL_ATTRIBUTE_PURE;
+size_t dir_len (char const *file) _GL_ATTRIBUTE_PURE;
+char *last_component (char const *file) _GL_ATTRIBUTE_PURE;
bool strip_trailing_slashes (char *file);
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
#endif /* not DIRNAME_H_ */
diff --git a/lib/dosname.h b/lib/dosname.h
new file mode 100644
index 0000000..83a953f
--- /dev/null
+++ b/lib/dosname.h
@@ -0,0 +1,53 @@
+/* File names on MS-DOS/Windows systems.
+
+ Copyright (C) 2000-2001, 2004-2006, 2009-2016 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 <http://www.gnu.org/licenses/>.
+
+ From Paul Eggert and Jim Meyering. */
+
+#ifndef _DOSNAME_H
+#define _DOSNAME_H
+
+#if (defined _WIN32 || defined __WIN32__ || \
+ defined __MSDOS__ || defined __CYGWIN__ || \
+ defined __EMX__ || defined __DJGPP__)
+ /* This internal macro assumes ASCII, but all hosts that support drive
+ letters use ASCII. */
+# define _IS_DRIVE_LETTER(C) (((unsigned int) (C) | ('a' - 'A')) - 'a' \
+ <= 'z' - 'a')
+# define FILE_SYSTEM_PREFIX_LEN(Filename) \
+ (_IS_DRIVE_LETTER ((Filename)[0]) && (Filename)[1] == ':' ? 2 : 0)
+# ifndef __CYGWIN__
+# define FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE 1
+# endif
+# define ISSLASH(C) ((C) == '/' || (C) == '\\')
+#else
+# define FILE_SYSTEM_PREFIX_LEN(Filename) 0
+# define ISSLASH(C) ((C) == '/')
+#endif
+
+#ifndef FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE
+# define FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE 0
+#endif
+
+#if FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE
+# define IS_ABSOLUTE_FILE_NAME(F) ISSLASH ((F)[FILE_SYSTEM_PREFIX_LEN (F)])
+# else
+# define IS_ABSOLUTE_FILE_NAME(F) \
+ (ISSLASH ((F)[0]) || FILE_SYSTEM_PREFIX_LEN (F) != 0)
+#endif
+#define IS_RELATIVE_FILE_NAME(F) (! IS_ABSOLUTE_FILE_NAME (F))
+
+#endif /* DOSNAME_H_ */
diff --git a/lib/dtoastr.c b/lib/dtoastr.c
new file mode 100644
index 0000000..aed181d
--- /dev/null
+++ b/lib/dtoastr.c
@@ -0,0 +1,2 @@
+#define LENGTH 2
+#include "ftoastr.c"
diff --git a/lib/dtotimespec.c b/lib/dtotimespec.c
new file mode 100644
index 0000000..9028044
--- /dev/null
+++ b/lib/dtotimespec.c
@@ -0,0 +1,59 @@
+/* Convert double to timespec.
+
+ Copyright (C) 2011-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* written by Paul Eggert */
+
+/* Convert the double value SEC to a struct timespec. Round toward
+ positive infinity. On overflow, return an extremal value. */
+
+#include <config.h>
+
+#include "timespec.h"
+
+#include "intprops.h"
+
+struct timespec
+dtotimespec (double sec)
+{
+ double min_representable = TYPE_MINIMUM (time_t);
+ double max_representable =
+ ((TYPE_MAXIMUM (time_t) * (double) TIMESPEC_RESOLUTION
+ + (TIMESPEC_RESOLUTION - 1))
+ / TIMESPEC_RESOLUTION);
+
+ if (! (min_representable < sec))
+ return make_timespec (TYPE_MINIMUM (time_t), 0);
+ else if (! (sec < max_representable))
+ return make_timespec (TYPE_MAXIMUM (time_t), TIMESPEC_RESOLUTION - 1);
+ else
+ {
+ time_t s = sec;
+ double frac = TIMESPEC_RESOLUTION * (sec - s);
+ long ns = frac;
+ ns += ns < frac;
+ s += ns / TIMESPEC_RESOLUTION;
+ ns %= TIMESPEC_RESOLUTION;
+
+ if (ns < 0)
+ {
+ s--;
+ ns += TIMESPEC_RESOLUTION;
+ }
+
+ return make_timespec (s, ns);
+ }
+}
diff --git a/lib/dup-safer-flag.c b/lib/dup-safer-flag.c
new file mode 100644
index 0000000..f5b81b7
--- /dev/null
+++ b/lib/dup-safer-flag.c
@@ -0,0 +1,38 @@
+/* Duplicate a file descriptor result, avoiding clobbering
+ STD{IN,OUT,ERR}_FILENO, with specific flags.
+
+ Copyright (C) 2001, 2004-2006, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Paul Eggert and Eric Blake. */
+
+#include <config.h>
+
+/* Specification. */
+#include "unistd-safer.h"
+
+#include <fcntl.h>
+#include <unistd.h>
+
+/* Like dup, but do not return STDIN_FILENO, STDOUT_FILENO, or
+ STDERR_FILENO. If FLAG contains O_CLOEXEC, behave like
+ fcntl(F_DUPFD_CLOEXEC) rather than fcntl(F_DUPFD). */
+
+int
+dup_safer_flag (int fd, int flag)
+{
+ return fcntl (fd, (flag & O_CLOEXEC) ? F_DUPFD_CLOEXEC : F_DUPFD,
+ STDERR_FILENO + 1);
+}
diff --git a/lib/dup-safer.c b/lib/dup-safer.c
index 7b12b61..6ed8f79 100644
--- a/lib/dup-safer.c
+++ b/lib/dup-safer.c
@@ -1,11 +1,11 @@
/* Invoke dup, but avoid some glitches.
- Copyright (C) 2001, 2004, 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2001, 2004-2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
@@ -23,11 +22,7 @@
#include "unistd-safer.h"
#include <fcntl.h>
-
#include <unistd.h>
-#ifndef STDERR_FILENO
-# define STDERR_FILENO 2
-#endif
/* Like dup, but do not return STDIN_FILENO, STDOUT_FILENO, or
STDERR_FILENO. */
@@ -35,11 +30,5 @@
int
dup_safer (int fd)
{
-#if defined F_DUPFD && !defined FCHDIR_REPLACEMENT
return fcntl (fd, F_DUPFD, STDERR_FILENO + 1);
-#else
- /* fd_safer calls us back, but eventually the recursion unwinds and
- does the right thing. */
- return fd_safer (dup (fd));
-#endif
}
diff --git a/lib/dup.c b/lib/dup.c
new file mode 100644
index 0000000..034fcf8
--- /dev/null
+++ b/lib/dup.c
@@ -0,0 +1,86 @@
+/* Duplicate an open file descriptor.
+
+ Copyright (C) 2011-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <unistd.h>
+
+#include <errno.h>
+
+#include "msvc-inval.h"
+
+#undef dup
+
+#if HAVE_MSVC_INVALID_PARAMETER_HANDLER
+static int
+dup_nothrow (int fd)
+{
+ int result;
+
+ TRY_MSVC_INVAL
+ {
+ result = dup (fd);
+ }
+ CATCH_MSVC_INVAL
+ {
+ result = -1;
+ errno = EBADF;
+ }
+ DONE_MSVC_INVAL;
+
+ return result;
+}
+#elif defined __KLIBC__
+# include <fcntl.h>
+# include <sys/stat.h>
+
+# include <InnoTekLIBC/backend.h>
+
+static int
+dup_nothrow (int fd)
+{
+ int dupfd;
+ struct stat sbuf;
+
+ dupfd = dup (fd);
+ if (dupfd == -1 && errno == ENOTSUP \
+ && !fstat (fd, &sbuf) && S_ISDIR (sbuf.st_mode))
+ {
+ char path[_MAX_PATH];
+
+ /* Get a path from fd */
+ if (!__libc_Back_ioFHToPath (fd, path, sizeof (path)))
+ dupfd = open (path, O_RDONLY);
+ }
+
+ return dupfd;
+}
+#else
+# define dup_nothrow dup
+#endif
+
+int
+rpl_dup (int fd)
+{
+ int result = dup_nothrow (fd);
+#if REPLACE_FCHDIR
+ if (result >= 0)
+ result = _gl_register_dup (fd, result);
+#endif
+ return result;
+}
diff --git a/lib/dup2.c b/lib/dup2.c
index 8894481..5d026f2 100644
--- a/lib/dup2.c
+++ b/lib/dup2.c
@@ -1,11 +1,11 @@
/* Duplicate an open file descriptor to a specified file descriptor.
- Copyright (C) 1999, 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
+ Copyright (C) 1999, 2004-2007, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* written by Paul Eggert */
@@ -26,7 +25,156 @@
#include <errno.h>
#include <fcntl.h>
-#ifndef F_DUPFD
+#if HAVE_DUP2
+
+# undef dup2
+
+# if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+
+/* Get declarations of the native Windows API functions. */
+# define WIN32_LEAN_AND_MEAN
+# include <windows.h>
+
+# include "msvc-inval.h"
+
+/* Get _get_osfhandle. */
+# include "msvc-nothrow.h"
+
+static int
+ms_windows_dup2 (int fd, int desired_fd)
+{
+ int result;
+
+ /* If fd is closed, mingw hangs on dup2 (fd, fd). If fd is open,
+ dup2 (fd, fd) returns 0, but all further attempts to use fd in
+ future dup2 calls will hang. */
+ if (fd == desired_fd)
+ {
+ if ((HANDLE) _get_osfhandle (fd) == INVALID_HANDLE_VALUE)
+ {
+ errno = EBADF;
+ return -1;
+ }
+ return fd;
+ }
+
+ /* Wine 1.0.1 return 0 when desired_fd is negative but not -1:
+ http://bugs.winehq.org/show_bug.cgi?id=21289 */
+ if (desired_fd < 0)
+ {
+ errno = EBADF;
+ return -1;
+ }
+
+ TRY_MSVC_INVAL
+ {
+ result = dup2 (fd, desired_fd);
+ }
+ CATCH_MSVC_INVAL
+ {
+ errno = EBADF;
+ result = -1;
+ }
+ DONE_MSVC_INVAL;
+
+ if (result == 0)
+ result = desired_fd;
+
+ return result;
+}
+
+# define dup2 ms_windows_dup2
+
+# elif defined __KLIBC__
+
+# include <InnoTekLIBC/backend.h>
+
+static int
+klibc_dup2dirfd (int fd, int desired_fd)
+{
+ int tempfd;
+ int dupfd;
+
+ tempfd = open ("NUL", O_RDONLY);
+ if (tempfd == -1)
+ return -1;
+
+ if (tempfd == desired_fd)
+ {
+ close (tempfd);
+
+ char path[_MAX_PATH];
+ if (__libc_Back_ioFHToPath (fd, path, sizeof (path)))
+ return -1;
+
+ return open(path, O_RDONLY);
+ }
+
+ dupfd = klibc_dup2dirfd (fd, desired_fd);
+
+ close (tempfd);
+
+ return dupfd;
+}
+
+static int
+klibc_dup2 (int fd, int desired_fd)
+{
+ int dupfd;
+ struct stat sbuf;
+
+ dupfd = dup2 (fd, desired_fd);
+ if (dupfd == -1 && errno == ENOTSUP \
+ && !fstat (fd, &sbuf) && S_ISDIR (sbuf.st_mode))
+ {
+ close (desired_fd);
+
+ return klibc_dup2dirfd (fd, desired_fd);
+ }
+
+ return dupfd;
+}
+
+# define dup2 klibc_dup2
+# endif
+
+int
+rpl_dup2 (int fd, int desired_fd)
+{
+ int result;
+
+# ifdef F_GETFL
+ /* On Linux kernels 2.6.26-2.6.29, dup2 (fd, fd) returns -EBADF.
+ On Cygwin 1.5.x, dup2 (1, 1) returns 0.
+ On Cygwin 1.7.17, dup2 (1, -1) dumps core.
+ On Cygwin 1.7.25, dup2 (1, 256) can dump core.
+ On Haiku, dup2 (fd, fd) mistakenly clears FD_CLOEXEC. */
+# if HAVE_SETDTABLESIZE
+ setdtablesize (desired_fd + 1);
+# endif
+ if (desired_fd < 0)
+ fd = desired_fd;
+ if (fd == desired_fd)
+ return fcntl (fd, F_GETFL) == -1 ? -1 : fd;
+# endif
+
+ result = dup2 (fd, desired_fd);
+
+ /* Correct an errno value on FreeBSD 6.1 and Cygwin 1.5.x. */
+ if (result == -1 && errno == EMFILE)
+ errno = EBADF;
+# if REPLACE_FCHDIR
+ if (fd != desired_fd && result != -1)
+ result = _gl_register_dup (fd, result);
+# endif
+ return result;
+}
+
+#else /* !HAVE_DUP2 */
+
+/* On older platforms, dup2 did not exist. */
+
+# ifndef F_DUPFD
static int
dupfd (int fd, int desired_fd)
{
@@ -42,17 +190,26 @@ dupfd (int fd, int desired_fd)
return r;
}
}
-#endif
+# endif
int
dup2 (int fd, int desired_fd)
{
- if (fd == desired_fd)
- return fd;
+ int result = fcntl (fd, F_GETFL) < 0 ? -1 : fd;
+ if (result == -1 || fd == desired_fd)
+ return result;
close (desired_fd);
-#ifdef F_DUPFD
- return fcntl (fd, F_DUPFD, desired_fd);
-#else
- return dupfd (fd, desired_fd);
-#endif
+# ifdef F_DUPFD
+ result = fcntl (fd, F_DUPFD, desired_fd);
+# if REPLACE_FCHDIR
+ if (0 <= result)
+ result = _gl_register_dup (fd, result);
+# endif
+# else
+ result = dupfd (fd, desired_fd);
+# endif
+ if (result == -1 && (errno == EMFILE || errno == EINVAL))
+ errno = EBADF;
+ return result;
}
+#endif /* !HAVE_DUP2 */
diff --git a/lib/errno.in.h b/lib/errno.in.h
new file mode 100644
index 0000000..b8397ee
--- /dev/null
+++ b/lib/errno.in.h
@@ -0,0 +1,279 @@
+/* A POSIX-like <errno.h>.
+
+ Copyright (C) 2008-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _@GUARD_PREFIX@_ERRNO_H
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+/* The include_next requires a split double-inclusion guard. */
+#@INCLUDE_NEXT@ @NEXT_ERRNO_H@
+
+#ifndef _@GUARD_PREFIX@_ERRNO_H
+#define _@GUARD_PREFIX@_ERRNO_H
+
+
+/* On native Windows platforms, many macros are not defined. */
+# if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+
+/* These are the same values as defined by MSVC 10, for interoperability. */
+
+# ifndef ENOMSG
+# define ENOMSG 122
+# define GNULIB_defined_ENOMSG 1
+# endif
+
+# ifndef EIDRM
+# define EIDRM 111
+# define GNULIB_defined_EIDRM 1
+# endif
+
+# ifndef ENOLINK
+# define ENOLINK 121
+# define GNULIB_defined_ENOLINK 1
+# endif
+
+# ifndef EPROTO
+# define EPROTO 134
+# define GNULIB_defined_EPROTO 1
+# endif
+
+# ifndef EBADMSG
+# define EBADMSG 104
+# define GNULIB_defined_EBADMSG 1
+# endif
+
+# ifndef EOVERFLOW
+# define EOVERFLOW 132
+# define GNULIB_defined_EOVERFLOW 1
+# endif
+
+# ifndef ENOTSUP
+# define ENOTSUP 129
+# define GNULIB_defined_ENOTSUP 1
+# endif
+
+# ifndef ENETRESET
+# define ENETRESET 117
+# define GNULIB_defined_ENETRESET 1
+# endif
+
+# ifndef ECONNABORTED
+# define ECONNABORTED 106
+# define GNULIB_defined_ECONNABORTED 1
+# endif
+
+# ifndef ECANCELED
+# define ECANCELED 105
+# define GNULIB_defined_ECANCELED 1
+# endif
+
+# ifndef EOWNERDEAD
+# define EOWNERDEAD 133
+# define GNULIB_defined_EOWNERDEAD 1
+# endif
+
+# ifndef ENOTRECOVERABLE
+# define ENOTRECOVERABLE 127
+# define GNULIB_defined_ENOTRECOVERABLE 1
+# endif
+
+# ifndef EINPROGRESS
+# define EINPROGRESS 112
+# define EALREADY 103
+# define ENOTSOCK 128
+# define EDESTADDRREQ 109
+# define EMSGSIZE 115
+# define EPROTOTYPE 136
+# define ENOPROTOOPT 123
+# define EPROTONOSUPPORT 135
+# define EOPNOTSUPP 130
+# define EAFNOSUPPORT 102
+# define EADDRINUSE 100
+# define EADDRNOTAVAIL 101
+# define ENETDOWN 116
+# define ENETUNREACH 118
+# define ECONNRESET 108
+# define ENOBUFS 119
+# define EISCONN 113
+# define ENOTCONN 126
+# define ETIMEDOUT 138
+# define ECONNREFUSED 107
+# define ELOOP 114
+# define EHOSTUNREACH 110
+# define EWOULDBLOCK 140
+# define GNULIB_defined_ESOCK 1
+# endif
+
+# ifndef ETXTBSY
+# define ETXTBSY 139
+# define ENODATA 120 /* not required by POSIX */
+# define ENOSR 124 /* not required by POSIX */
+# define ENOSTR 125 /* not required by POSIX */
+# define ETIME 137 /* not required by POSIX */
+# define EOTHER 131 /* not required by POSIX */
+# define GNULIB_defined_ESTREAMS 1
+# endif
+
+/* These are intentionally the same values as the WSA* error numbers, defined
+ in <winsock2.h>. */
+# define ESOCKTNOSUPPORT 10044 /* not required by POSIX */
+# define EPFNOSUPPORT 10046 /* not required by POSIX */
+# define ESHUTDOWN 10058 /* not required by POSIX */
+# define ETOOMANYREFS 10059 /* not required by POSIX */
+# define EHOSTDOWN 10064 /* not required by POSIX */
+# define EPROCLIM 10067 /* not required by POSIX */
+# define EUSERS 10068 /* not required by POSIX */
+# define EDQUOT 10069
+# define ESTALE 10070
+# define EREMOTE 10071 /* not required by POSIX */
+# define GNULIB_defined_EWINSOCK 1
+
+# endif
+
+
+/* On OSF/1 5.1, when _XOPEN_SOURCE_EXTENDED is not defined, the macros
+ EMULTIHOP, ENOLINK, EOVERFLOW are not defined. */
+# if @EMULTIHOP_HIDDEN@
+# define EMULTIHOP @EMULTIHOP_VALUE@
+# define GNULIB_defined_EMULTIHOP 1
+# endif
+# if @ENOLINK_HIDDEN@
+# define ENOLINK @ENOLINK_VALUE@
+# define GNULIB_defined_ENOLINK 1
+# endif
+# if @EOVERFLOW_HIDDEN@
+# define EOVERFLOW @EOVERFLOW_VALUE@
+# define GNULIB_defined_EOVERFLOW 1
+# endif
+
+
+/* On OpenBSD 4.0 and on native Windows, the macros ENOMSG, EIDRM, ENOLINK,
+ EPROTO, EMULTIHOP, EBADMSG, EOVERFLOW, ENOTSUP, ECANCELED are not defined.
+ Likewise, on NonStop Kernel, EDQUOT is not defined.
+ Define them here. Values >= 2000 seem safe to use: Solaris ESTALE = 151,
+ HP-UX EWOULDBLOCK = 246, IRIX EDQUOT = 1133.
+
+ Note: When one of these systems defines some of these macros some day,
+ binaries will have to be recompiled so that they recognizes the new
+ errno values from the system. */
+
+# ifndef ENOMSG
+# define ENOMSG 2000
+# define GNULIB_defined_ENOMSG 1
+# endif
+
+# ifndef EIDRM
+# define EIDRM 2001
+# define GNULIB_defined_EIDRM 1
+# endif
+
+# ifndef ENOLINK
+# define ENOLINK 2002
+# define GNULIB_defined_ENOLINK 1
+# endif
+
+# ifndef EPROTO
+# define EPROTO 2003
+# define GNULIB_defined_EPROTO 1
+# endif
+
+# ifndef EMULTIHOP
+# define EMULTIHOP 2004
+# define GNULIB_defined_EMULTIHOP 1
+# endif
+
+# ifndef EBADMSG
+# define EBADMSG 2005
+# define GNULIB_defined_EBADMSG 1
+# endif
+
+# ifndef EOVERFLOW
+# define EOVERFLOW 2006
+# define GNULIB_defined_EOVERFLOW 1
+# endif
+
+# ifndef ENOTSUP
+# define ENOTSUP 2007
+# define GNULIB_defined_ENOTSUP 1
+# endif
+
+# ifndef ENETRESET
+# define ENETRESET 2011
+# define GNULIB_defined_ENETRESET 1
+# endif
+
+# ifndef ECONNABORTED
+# define ECONNABORTED 2012
+# define GNULIB_defined_ECONNABORTED 1
+# endif
+
+# ifndef ESTALE
+# define ESTALE 2009
+# define GNULIB_defined_ESTALE 1
+# endif
+
+# ifndef EDQUOT
+# define EDQUOT 2010
+# define GNULIB_defined_EDQUOT 1
+# endif
+
+# ifndef ECANCELED
+# define ECANCELED 2008
+# define GNULIB_defined_ECANCELED 1
+# endif
+
+/* On many platforms, the macros EOWNERDEAD and ENOTRECOVERABLE are not
+ defined. */
+
+# ifndef EOWNERDEAD
+# if defined __sun
+ /* Use the same values as defined for Solaris >= 8, for
+ interoperability. */
+# define EOWNERDEAD 58
+# define ENOTRECOVERABLE 59
+# elif (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+ /* We have a conflict here: pthreads-win32 defines these values
+ differently than MSVC 10. It's hairy to decide which one to use. */
+# if defined __MINGW32__ && !defined USE_WINDOWS_THREADS
+ /* Use the same values as defined by pthreads-win32, for
+ interoperability. */
+# define EOWNERDEAD 43
+# define ENOTRECOVERABLE 44
+# else
+ /* Use the same values as defined by MSVC 10, for
+ interoperability. */
+# define EOWNERDEAD 133
+# define ENOTRECOVERABLE 127
+# endif
+# else
+# define EOWNERDEAD 2013
+# define ENOTRECOVERABLE 2014
+# endif
+# define GNULIB_defined_EOWNERDEAD 1
+# define GNULIB_defined_ENOTRECOVERABLE 1
+# endif
+
+# ifndef EILSEQ
+# define EILSEQ 2015
+# define GNULIB_defined_EILSEQ 1
+# endif
+
+#endif /* _@GUARD_PREFIX@_ERRNO_H */
+#endif /* _@GUARD_PREFIX@_ERRNO_H */
diff --git a/lib/error.c b/lib/error.c
index cf86343..56ac889 100644
--- a/lib/error.c
+++ b/lib/error.c
@@ -1,20 +1,19 @@
/* Error handler for noninteractive utilities
- Copyright (C) 1990-1998, 2000-2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 1990-1998, 2000-2007, 2009-2016 Free Software Foundation, Inc.
This file is part of the GNU C Library.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by David MacKenzie <djm@gnu.ai.mit.edu>. */
@@ -31,6 +30,7 @@
#if !_LIBC && ENABLE_NLS
# include "gettext.h"
+# define _(msgid) gettext (msgid)
#endif
#ifdef _LIBC
@@ -39,6 +39,9 @@
# include <stdint.h>
# include <wchar.h>
# define mbsrtowcs __mbsrtowcs
+# define USE_UNLOCKED_IO 0
+# define _GL_ATTRIBUTE_FORMAT_PRINTF(a, b)
+# define _GL_ARG_NONNULL(a)
#endif
#if USE_UNLOCKED_IO
@@ -54,7 +57,7 @@
function without parameters instead. */
void (*error_print_progname) (void);
-/* This variable is incremented each time `error' is called. */
+/* This variable is incremented each time 'error' is called. */
unsigned int error_message_count;
#ifdef _LIBC
@@ -65,31 +68,49 @@ unsigned int error_message_count;
# include <limits.h>
# include <libio/libioP.h>
-/* In GNU libc we want do not want to use the common name `error' directly.
+/* In GNU libc we want do not want to use the common name 'error' directly.
Instead make it a weak alias. */
extern void __error (int status, int errnum, const char *message, ...)
__attribute__ ((__format__ (__printf__, 3, 4)));
extern void __error_at_line (int status, int errnum, const char *file_name,
- unsigned int line_number, const char *message,
- ...)
- __attribute__ ((__format__ (__printf__, 5, 6)));;
+ unsigned int line_number, const char *message,
+ ...)
+ __attribute__ ((__format__ (__printf__, 5, 6)));
# define error __error
# define error_at_line __error_at_line
# include <libio/iolibio.h>
-# define fflush(s) INTUSE(_IO_fflush) (s)
+# define fflush(s) _IO_fflush (s)
# undef putc
-# define putc(c, fp) INTUSE(_IO_putc) (c, fp)
+# define putc(c, fp) _IO_putc (c, fp)
# include <bits/libc-lock.h>
#else /* not _LIBC */
-# if !HAVE_DECL_STRERROR_R && STRERROR_R_CHAR_P
+# include <fcntl.h>
+# include <unistd.h>
+
+# if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+/* Get declarations of the native Windows API functions. */
+# define WIN32_LEAN_AND_MEAN
+# include <windows.h>
+/* Get _get_osfhandle. */
+# include "msvc-nothrow.h"
+# endif
+
+/* The gnulib override of fcntl is not needed in this file. */
+# undef fcntl
+
+# if !HAVE_DECL_STRERROR_R
# ifndef HAVE_DECL_STRERROR_R
"this configure-time declaration test was not run"
# endif
+# if STRERROR_R_CHAR_P
char *strerror_r ();
+# else
+int strerror_r ();
+# endif
# endif
/* The calling program should define program_name and set it to the
@@ -98,8 +119,53 @@ extern char *program_name;
# if HAVE_STRERROR_R || defined strerror_r
# define __strerror_r strerror_r
-# endif /* HAVE_STRERROR_R || defined strerror_r */
-#endif /* not _LIBC */
+# endif /* HAVE_STRERROR_R || defined strerror_r */
+#endif /* not _LIBC */
+
+#if !_LIBC
+/* Return non-zero if FD is open. */
+static int
+is_open (int fd)
+{
+# if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+ /* On native Windows: The initial state of unassigned standard file
+ descriptors is that they are open but point to an INVALID_HANDLE_VALUE.
+ There is no fcntl, and the gnulib replacement fcntl does not support
+ F_GETFL. */
+ return (HANDLE) _get_osfhandle (fd) != INVALID_HANDLE_VALUE;
+# else
+# ifndef F_GETFL
+# error Please port fcntl to your platform
+# endif
+ return 0 <= fcntl (fd, F_GETFL);
+# endif
+}
+#endif
+
+static void
+flush_stdout (void)
+{
+#if !_LIBC
+ int stdout_fd;
+
+# if GNULIB_FREOPEN_SAFER
+ /* Use of gnulib's freopen-safer module normally ensures that
+ fileno (stdout) == 1
+ whenever stdout is open. */
+ stdout_fd = STDOUT_FILENO;
+# else
+ /* POSIX states that fileno (stdout) after fclose is unspecified. But in
+ practice it is not a problem, because stdout is statically allocated and
+ the fd of a FILE stream is stored as a field in its allocated memory. */
+ stdout_fd = fileno (stdout);
+# endif
+ /* POSIX states that fflush (stdout) after fclose is unspecified; it
+ is safe in glibc, but not on all other platforms. fflush (NULL)
+ is always defined, but too draconian. */
+ if (0 <= stdout_fd && is_open (stdout_fd))
+#endif
+ fflush (stdout);
+}
static void
print_errno_message (int errnum)
@@ -108,7 +174,7 @@ print_errno_message (int errnum)
#if defined HAVE_STRERROR_R || _LIBC
char errbuf[1024];
-# if STRERROR_R_CHAR_P || _LIBC
+# if _LIBC || STRERROR_R_CHAR_P
s = __strerror_r (errnum, errbuf, sizeof errbuf);
# else
if (__strerror_r (errnum, errbuf, sizeof errbuf) == 0)
@@ -132,13 +198,12 @@ print_errno_message (int errnum)
#endif
}
-static void
+static void _GL_ATTRIBUTE_FORMAT_PRINTF (3, 0) _GL_ARG_NONNULL ((3))
error_tail (int status, int errnum, const char *message, va_list args)
{
#if _LIBC
if (_IO_fwide (stderr, 0) > 0)
{
-# define ALLOCA_LIMIT 2000
size_t len = strlen (message) + 1;
wchar_t *wmessage = NULL;
mbstate_t st;
@@ -147,58 +212,58 @@ error_tail (int status, int errnum, const char *message, va_list args)
bool use_malloc = false;
while (1)
- {
- if (__libc_use_alloca (len * sizeof (wchar_t)))
- wmessage = (wchar_t *) alloca (len * sizeof (wchar_t));
- else
- {
- if (!use_malloc)
- wmessage = NULL;
-
- wchar_t *p = (wchar_t *) realloc (wmessage,
- len * sizeof (wchar_t));
- if (p == NULL)
- {
- free (wmessage);
- fputws_unlocked (L"out of memory\n", stderr);
- return;
- }
- wmessage = p;
- use_malloc = true;
- }
-
- memset (&st, '\0', sizeof (st));
- tmp = message;
-
- res = mbsrtowcs (wmessage, &tmp, len, &st);
- if (res != len)
- break;
-
- if (__builtin_expect (len >= SIZE_MAX / 2, 0))
- {
- /* This really should not happen if everything is fine. */
- res = (size_t) -1;
- break;
- }
-
- len *= 2;
- }
+ {
+ if (__libc_use_alloca (len * sizeof (wchar_t)))
+ wmessage = (wchar_t *) alloca (len * sizeof (wchar_t));
+ else
+ {
+ if (!use_malloc)
+ wmessage = NULL;
+
+ wchar_t *p = (wchar_t *) realloc (wmessage,
+ len * sizeof (wchar_t));
+ if (p == NULL)
+ {
+ free (wmessage);
+ fputws_unlocked (L"out of memory\n", stderr);
+ return;
+ }
+ wmessage = p;
+ use_malloc = true;
+ }
+
+ memset (&st, '\0', sizeof (st));
+ tmp = message;
+
+ res = mbsrtowcs (wmessage, &tmp, len, &st);
+ if (res != len)
+ break;
+
+ if (__builtin_expect (len >= SIZE_MAX / sizeof (wchar_t) / 2, 0))
+ {
+ /* This really should not happen if everything is fine. */
+ res = (size_t) -1;
+ break;
+ }
+
+ len *= 2;
+ }
if (res == (size_t) -1)
- {
- /* The string cannot be converted. */
- if (use_malloc)
- {
- free (wmessage);
- use_malloc = false;
- }
- wmessage = (wchar_t *) L"???";
- }
+ {
+ /* The string cannot be converted. */
+ if (use_malloc)
+ {
+ free (wmessage);
+ use_malloc = false;
+ }
+ wmessage = (wchar_t *) L"???";
+ }
__vfwprintf (stderr, wmessage, args);
if (use_malloc)
- free (wmessage);
+ free (wmessage);
}
else
#endif
@@ -233,10 +298,10 @@ error (int status, int errnum, const char *message, ...)
cancellation. Therefore disable cancellation for now. */
int state = PTHREAD_CANCEL_ENABLE;
__libc_ptf_call (pthread_setcancelstate, (PTHREAD_CANCEL_DISABLE, &state),
- 0);
+ 0);
#endif
- fflush (stdout);
+ flush_stdout ();
#ifdef _LIBC
_IO_flockfile (stderr);
#endif
@@ -268,7 +333,7 @@ int error_one_per_line;
void
error_at_line (int status, int errnum, const char *file_name,
- unsigned int line_number, const char *message, ...)
+ unsigned int line_number, const char *message, ...)
{
va_list args;
@@ -278,10 +343,13 @@ error_at_line (int status, int errnum, const char *file_name,
static unsigned int old_line_number;
if (old_line_number == line_number
- && (file_name == old_file_name
- || strcmp (old_file_name, file_name) == 0))
- /* Simply return and print nothing. */
- return;
+ && (file_name == old_file_name
+ || (old_file_name != NULL
+ && file_name != NULL
+ && strcmp (old_file_name, file_name) == 0)))
+
+ /* Simply return and print nothing. */
+ return;
old_file_name = file_name;
old_line_number = line_number;
@@ -292,10 +360,10 @@ error_at_line (int status, int errnum, const char *file_name,
cancellation. Therefore disable cancellation for now. */
int state = PTHREAD_CANCEL_ENABLE;
__libc_ptf_call (pthread_setcancelstate, (PTHREAD_CANCEL_DISABLE, &state),
- 0);
+ 0);
#endif
- fflush (stdout);
+ flush_stdout ();
#ifdef _LIBC
_IO_flockfile (stderr);
#endif
@@ -311,11 +379,11 @@ error_at_line (int status, int errnum, const char *file_name,
}
#if _LIBC
- __fxprintf (NULL, file_name != NULL ? "%s:%d: " : " ",
- file_name, line_number);
+ __fxprintf (NULL, file_name != NULL ? "%s:%u: " : " ",
+ file_name, line_number);
#else
- fprintf (stderr, file_name != NULL ? "%s:%d: " : " ",
- file_name, line_number);
+ fprintf (stderr, file_name != NULL ? "%s:%u: " : " ",
+ file_name, line_number);
#endif
va_start (args, message);
diff --git a/lib/error.h b/lib/error.h
index 5a5f247..6a69db0 100644
--- a/lib/error.h
+++ b/lib/error.h
@@ -1,65 +1,74 @@
/* Declaration for error-reporting function
- Copyright (C) 1995, 1996, 1997, 2003, 2006 Free Software Foundation, Inc.
+ Copyright (C) 1995-1997, 2003, 2006, 2008-2016 Free Software Foundation,
+ Inc.
This file is part of the GNU C Library.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifndef _ERROR_H
#define _ERROR_H 1
-#ifndef __attribute__
-/* This feature is available in gcc versions 2.5 and later. */
-# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 5) || __STRICT_ANSI__
-# define __attribute__(Spec) /* empty */
-# endif
-/* The __-protected variants of `format' and `printf' attributes
- are accepted by gcc versions 2.6.4 (effectively 2.7) and later. */
-# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 7)
-# define __format__ format
-# define __printf__ printf
+/* The __attribute__ feature is available in gcc versions 2.5 and later.
+ The __-protected variants of the attributes 'format' and 'printf' are
+ accepted by gcc versions 2.6.4 (effectively 2.7) and later.
+ We enable _GL_ATTRIBUTE_FORMAT only if these are supported too, because
+ gnulib and libintl do '#define printf __printf__' when they override
+ the 'printf' function. */
+#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 7)
+# define _GL_ATTRIBUTE_FORMAT(spec) __attribute__ ((__format__ spec))
+#else
+# define _GL_ATTRIBUTE_FORMAT(spec) /* empty */
+#endif
+
+/* On mingw, the flavor of printf depends on whether the extensions module
+ * is in use; the check for <stdio.h> determines the witness macro. */
+#ifndef _GL_ATTRIBUTE_SPEC_PRINTF
+# if GNULIB_PRINTF_ATTRIBUTE_FLAVOR_GNU
+# define _GL_ATTRIBUTE_SPEC_PRINTF __gnu_printf__
+# else
+# define _GL_ATTRIBUTE_SPEC_PRINTF __printf__
# endif
#endif
-#ifdef __cplusplus
+#ifdef __cplusplus
extern "C" {
#endif
-/* Print a message with `fprintf (stderr, FORMAT, ...)';
+/* Print a message with 'fprintf (stderr, FORMAT, ...)';
if ERRNUM is nonzero, follow it with ": " and strerror (ERRNUM).
- If STATUS is nonzero, terminate the program with `exit (STATUS)'. */
+ If STATUS is nonzero, terminate the program with 'exit (STATUS)'. */
extern void error (int __status, int __errnum, const char *__format, ...)
- __attribute__ ((__format__ (__printf__, 3, 4)));
+ _GL_ATTRIBUTE_FORMAT ((_GL_ATTRIBUTE_SPEC_PRINTF, 3, 4));
extern void error_at_line (int __status, int __errnum, const char *__fname,
- unsigned int __lineno, const char *__format, ...)
- __attribute__ ((__format__ (__printf__, 5, 6)));
+ unsigned int __lineno, const char *__format, ...)
+ _GL_ATTRIBUTE_FORMAT ((_GL_ATTRIBUTE_SPEC_PRINTF, 5, 6));
/* If NULL, error will flush stdout, then print on stderr the program
name, a colon and a space. Otherwise, error will call this
function without parameters instead. */
extern void (*error_print_progname) (void);
-/* This variable is incremented each time `error' is called. */
+/* This variable is incremented each time 'error' is called. */
extern unsigned int error_message_count;
/* Sometimes we want to have at most one error per line. This
variable controls whether this mode is selected or not. */
extern int error_one_per_line;
-#ifdef __cplusplus
+#ifdef __cplusplus
}
#endif
diff --git a/lib/euidaccess-stat.c b/lib/euidaccess-stat.c
deleted file mode 100644
index 7663c46..0000000
--- a/lib/euidaccess-stat.c
+++ /dev/null
@@ -1,143 +0,0 @@
-/* euidaccess-stat -- check if effective user id can access lstat'd file
- This function is probably useful only for choosing whether to issue
- a prompt in an implementation of POSIX-specified rm.
-
- Copyright (C) 2005, 2006 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-/* Adapted for use in GNU remove.c by Jim Meyering. */
-
-#include <config.h>
-
-#include "euidaccess-stat.h"
-
-#include <unistd.h>
-
-#ifndef F_OK
-# define F_OK 0
-# define X_OK 1
-# define W_OK 2
-# define R_OK 4
-#endif
-
-#include "group-member.h"
-#include "stat-macros.h"
-
-/* Return true if the current user has permission of type MODE
- on the file from which stat buffer *ST was obtained, ignoring
- ACLs, attributes, `read-only'ness, etc...
- Otherwise, return false.
-
- Like the reentrant version of euidaccess, but starting with
- a stat buffer rather than a file name. Hence, this function
- never calls access or accessx, and doesn't take into account
- whether the file has ACLs or other attributes, or resides on
- a read-only file system. */
-
-bool
-euidaccess_stat (struct stat const *st, int mode)
-{
- uid_t euid;
- unsigned int granted;
-
- /* Convert the mode to traditional form, clearing any bogus bits. */
- if (R_OK == 4 && W_OK == 2 && X_OK == 1 && F_OK == 0)
- mode &= 7;
- else
- mode = ((mode & R_OK ? 4 : 0)
- + (mode & W_OK ? 2 : 0)
- + (mode & X_OK ? 1 : 0));
-
- if (mode == 0)
- return true; /* The file exists. */
-
- euid = geteuid ();
-
- /* The super-user can read and write any file, and execute any file
- that anyone can execute. */
- if (euid == 0 && ((mode & X_OK) == 0
- || (st->st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))))
- return true;
-
- /* Convert the file's permission bits to traditional form. */
- if ( S_IRUSR == (4 << 6)
- && S_IWUSR == (2 << 6)
- && S_IXUSR == (1 << 6)
- && S_IRGRP == (4 << 3)
- && S_IWGRP == (2 << 3)
- && S_IXGRP == (1 << 3)
- && S_IROTH == (4 << 0)
- && S_IWOTH == (2 << 0)
- && S_IXOTH == (1 << 0))
- granted = st->st_mode;
- else
- granted = ( (st->st_mode & S_IRUSR ? 4 << 6 : 0)
- + (st->st_mode & S_IWUSR ? 2 << 6 : 0)
- + (st->st_mode & S_IXUSR ? 1 << 6 : 0)
- + (st->st_mode & S_IRGRP ? 4 << 3 : 0)
- + (st->st_mode & S_IWGRP ? 2 << 3 : 0)
- + (st->st_mode & S_IXGRP ? 1 << 3 : 0)
- + (st->st_mode & S_IROTH ? 4 << 0 : 0)
- + (st->st_mode & S_IWOTH ? 2 << 0 : 0)
- + (st->st_mode & S_IXOTH ? 1 << 0 : 0));
-
- if (euid == st->st_uid)
- granted >>= 6;
- else
- {
- gid_t egid = getegid ();
- if (egid == st->st_gid || group_member (st->st_gid))
- granted >>= 3;
- }
-
- if ((mode & ~granted) == 0)
- return true;
-
- return false;
-}
-
-
-#ifdef TEST
-# include <errno.h>
-# include <stdio.h>
-# include <stdlib.h>
-
-# include "error.h"
-# define _(msg) msg
-
-char *program_name;
-
-int
-main (int argc, char **argv)
-{
- char *file;
- int mode;
- bool ok;
- struct stat st;
-
- program_name = argv[0];
- if (argc < 3)
- abort ();
- file = argv[1];
- mode = atoi (argv[2]);
- if (lstat (file, &st) != 0)
- error (EXIT_FAILURE, errno, _("cannot stat %s"), file);
-
- ok = euidaccess_stat (&st, mode);
- printf ("%s: %s\n", file, ok ? "y" : "n");
- exit (0);
-}
-#endif
diff --git a/lib/euidaccess-stat.h b/lib/euidaccess-stat.h
deleted file mode 100644
index de24961..0000000
--- a/lib/euidaccess-stat.h
+++ /dev/null
@@ -1,5 +0,0 @@
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <stdbool.h>
-
-bool euidaccess_stat (struct stat const *st, int mode);
diff --git a/lib/euidaccess.c b/lib/euidaccess.c
index 5148a5b..82af941 100644
--- a/lib/euidaccess.c
+++ b/lib/euidaccess.c
@@ -1,36 +1,37 @@
/* euidaccess -- check if effective user id can access file
- Copyright (C) 1990, 1991, 1995, 1998, 2000, 2003, 2004, 2005, 2006
- Free Software Foundation, Inc.
+ Copyright (C) 1990-1991, 1995, 1998, 2000, 2003-2006, 2008-2016 Free
+ Software Foundation, Inc.
This file is part of the GNU C Library.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by David MacKenzie and Torbjorn Granlund.
Adapted for GNU C library by Roland McGrath. */
#ifndef _LIBC
# include <config.h>
-# include "euidaccess.h"
#endif
+#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
+#include "root-uid.h"
+
#if HAVE_LIBGEN_H
# include <libgen.h>
#endif
@@ -64,14 +65,10 @@
# undef stat
# define stat stat64
-#else
-
-# include "group-member.h"
-
#endif
/* Return 0 if the user has permission of type MODE on FILE;
- otherwise, return -1 and set `errno'.
+ otherwise, return -1 and set 'errno'.
Like access, except that it uses the effective user and group
id's instead of the real ones, and it does not always check for read-only
file system, text busy, etc. */
@@ -79,13 +76,15 @@
int
euidaccess (const char *file, int mode)
{
-#if defined EFF_ONLY_OK
+#if HAVE_FACCESSAT /* glibc, AIX 7, Solaris 11, Cygwin 1.7 */
+ return faccessat (AT_FDCWD, file, mode, AT_EACCESS);
+#elif defined EFF_ONLY_OK /* IRIX, OSF/1, Interix */
return access (file, mode | EFF_ONLY_OK);
-#elif defined ACC_SELF
+#elif defined ACC_SELF /* AIX */
return accessx (file, mode, ACC_SELF);
-#elif HAVE_EACCESS
+#elif HAVE_EACCESS /* FreeBSD */
return eaccess (file, mode);
-#else
+#else /* Mac OS X, NetBSD, OpenBSD, HP-UX, Solaris, Cygwin, mingw, BeOS */
uid_t uid = getuid ();
gid_t gid = getgid ();
@@ -110,18 +109,18 @@ euidaccess (const char *file, int mode)
int saved_errno;
if (uid != euid)
- setreuid (euid, uid);
+ setreuid (euid, uid);
if (gid != egid)
- setregid (egid, gid);
+ setregid (egid, gid);
result = access (file, mode);
saved_errno = errno;
/* Restore them. */
if (uid != euid)
- setreuid (uid, euid);
+ setreuid (uid, euid);
if (gid != egid)
- setregid (gid, egid);
+ setregid (gid, egid);
errno = saved_errno;
return result;
@@ -143,8 +142,9 @@ euidaccess (const char *file, int mode)
/* The super-user can read and write any file, and execute any file
that anyone can execute. */
- if (euid == 0 && ((mode & X_OK) == 0
- || (stats.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))))
+ if (euid == ROOT_UID
+ && ((mode & X_OK) == 0
+ || (stats.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))))
return 0;
/* Convert the mode to traditional form, clearing any bogus bits. */
@@ -152,11 +152,11 @@ euidaccess (const char *file, int mode)
mode &= 7;
else
mode = ((mode & R_OK ? 4 : 0)
- + (mode & W_OK ? 2 : 0)
- + (mode & X_OK ? 1 : 0));
+ + (mode & W_OK ? 2 : 0)
+ + (mode & X_OK ? 1 : 0));
if (mode == 0)
- return 0; /* The file exists. */
+ return 0; /* The file exists. */
/* Convert the file's permission bits to traditional form. */
if (S_IRUSR == (4 << 6) && S_IWUSR == (2 << 6) && S_IXUSR == (1 << 6)
@@ -165,14 +165,14 @@ euidaccess (const char *file, int mode)
granted = stats.st_mode;
else
granted = ((stats.st_mode & S_IRUSR ? 4 << 6 : 0)
- + (stats.st_mode & S_IWUSR ? 2 << 6 : 0)
- + (stats.st_mode & S_IXUSR ? 1 << 6 : 0)
- + (stats.st_mode & S_IRGRP ? 4 << 3 : 0)
- + (stats.st_mode & S_IWGRP ? 2 << 3 : 0)
- + (stats.st_mode & S_IXGRP ? 1 << 3 : 0)
- + (stats.st_mode & S_IROTH ? 4 << 0 : 0)
- + (stats.st_mode & S_IWOTH ? 2 << 0 : 0)
- + (stats.st_mode & S_IXOTH ? 1 << 0 : 0));
+ + (stats.st_mode & S_IWUSR ? 2 << 6 : 0)
+ + (stats.st_mode & S_IXUSR ? 1 << 6 : 0)
+ + (stats.st_mode & S_IRGRP ? 4 << 3 : 0)
+ + (stats.st_mode & S_IWGRP ? 2 << 3 : 0)
+ + (stats.st_mode & S_IXGRP ? 1 << 3 : 0)
+ + (stats.st_mode & S_IROTH ? 4 << 0 : 0)
+ + (stats.st_mode & S_IWOTH ? 2 << 0 : 0)
+ + (stats.st_mode & S_IXOTH ? 1 << 0 : 0));
if (euid == stats.st_uid)
granted >>= 6;
diff --git a/lib/euidaccess.h b/lib/euidaccess.h
deleted file mode 100644
index 17b7e98..0000000
--- a/lib/euidaccess.h
+++ /dev/null
@@ -1,3 +0,0 @@
-#if ! HAVE_DECL_EUIDACCESS
-int euidaccess (char const *file, int mode);
-#endif
diff --git a/lib/exclude.c b/lib/exclude.c
index ed34d0f..92dacc4 100644
--- a/lib/exclude.c
+++ b/lib/exclude.c
@@ -1,12 +1,12 @@
/* exclude.c -- exclude file names
- Copyright (C) 1992, 1993, 1994, 1997, 1999, 2000, 2001, 2002, 2003,
- 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
+ Copyright (C) 1992-1994, 1997, 1999-2007, 2009-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,11 +14,12 @@
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with this program; see the file COPYING.
- If not, write to the Free Software Foundation,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
-/* Written by Paul Eggert <eggert@twinsun.com> */
+/* Written by Paul Eggert <eggert@twinsun.com>
+ and Sergey Poznyakoff <gray@gnu.org>.
+ Thanks to Phil Proudman <phil@proudman51.freeserve.co.uk>
+ for improvement suggestions. */
#include <config.h>
@@ -30,11 +31,16 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#include <wctype.h>
+#include <regex.h>
#include "exclude.h"
+#include "hash.h"
+#include "mbuiter.h"
#include "fnmatch.h"
#include "xalloc.h"
#include "verify.h"
+#include "filename.h"
#if USE_UNLOCKED_IO
# include "unlocked-io.h"
@@ -52,28 +58,133 @@
#endif
verify (((EXCLUDE_ANCHORED | EXCLUDE_INCLUDE | EXCLUDE_WILDCARDS)
- & (FNM_PATHNAME | FNM_NOESCAPE | FNM_PERIOD | FNM_LEADING_DIR
- | FNM_CASEFOLD | FNM_EXTMATCH))
- == 0);
+ & (FNM_PATHNAME | FNM_NOESCAPE | FNM_PERIOD | FNM_LEADING_DIR
+ | FNM_CASEFOLD | FNM_EXTMATCH))
+ == 0);
+
+
+/* Exclusion patterns are grouped into a singly-linked list of
+ "exclusion segments". Each segment represents a set of patterns
+ that can be matches using the same algorithm. Non-wildcard
+ patterns are kept in hash tables, to speed up searches. Wildcard
+ patterns are stored as arrays of patterns. */
+
/* An exclude pattern-options pair. The options are fnmatch options
ORed with EXCLUDE_* options. */
struct patopts
{
- char const *pattern;
int options;
+ union
+ {
+ char const *pattern;
+ regex_t re;
+ } v;
};
-/* An exclude list, of pattern-options pairs. */
+/* An array of pattern-options pairs. */
-struct exclude
+struct exclude_pattern
{
struct patopts *exclude;
size_t exclude_alloc;
size_t exclude_count;
};
+enum exclude_type
+ {
+ exclude_hash, /* a hash table of excluded names */
+ exclude_pattern /* an array of exclude patterns */
+ };
+
+struct exclude_segment
+ {
+ struct exclude_segment *next; /* next segment in list */
+ enum exclude_type type; /* type of this segment */
+ int options; /* common options for this segment */
+ union
+ {
+ Hash_table *table; /* for type == exclude_hash */
+ struct exclude_pattern pat; /* for type == exclude_pattern */
+ } v;
+ };
+
+struct pattern_buffer
+ {
+ struct pattern_buffer *next;
+ char *base;
+ };
+
+/* The exclude structure keeps a singly-linked list of exclude segments,
+ maintained in reverse order. */
+struct exclude
+ {
+ struct exclude_segment *head;
+ struct pattern_buffer *patbuf;
+ };
+
+/* Register BUF in the pattern buffer list of EX. ADD_FUNC (see
+ add_exclude_file and add_exclude_fp below) can use this function
+ if it modifies the pattern, to ensure the allocated memory will be
+ properly reclaimed upon calling free_exclude. */
+void
+exclude_add_pattern_buffer (struct exclude *ex, char *buf)
+{
+ struct pattern_buffer *pbuf = xmalloc (sizeof *pbuf);
+ pbuf->base = buf;
+ pbuf->next = ex->patbuf;
+ ex->patbuf = pbuf;
+}
+
+/* Return true if STR has or may have wildcards, when matched with OPTIONS.
+ Return false if STR definitely does not have wildcards. */
+bool
+fnmatch_pattern_has_wildcards (const char *str, int options)
+{
+ while (1)
+ {
+ switch (*str++)
+ {
+ case '.':
+ case '{':
+ case '}':
+ case '(':
+ case ')':
+ if (options & EXCLUDE_REGEX)
+ return true;
+ break;
+
+ case '\\':
+ if (options & EXCLUDE_REGEX)
+ continue;
+ else
+ str += ! (options & FNM_NOESCAPE) && *str;
+ break;
+
+ case '+': case '@': case '!':
+ if (options & FNM_EXTMATCH && *str == '(')
+ return true;
+ break;
+
+ case '?': case '*': case '[':
+ return true;
+
+ case '\0':
+ return false;
+ }
+ }
+}
+
+static void
+unescape_pattern (char *str)
+{
+ char const *q = str;
+ do
+ q += *q == '\\' && q[1];
+ while ((*str++ = *q++));
+}
+
/* Return a newly allocated and empty exclude list. */
struct exclude *
@@ -82,12 +193,136 @@ new_exclude (void)
return xzalloc (sizeof *new_exclude ());
}
-/* Free the storage associated with an exclude list. */
+/* Calculate the hash of string. */
+static size_t
+string_hasher (void const *data, size_t n_buckets)
+{
+ char const *p = data;
+ return hash_string (p, n_buckets);
+}
+
+/* Ditto, for case-insensitive hashes */
+static size_t
+string_hasher_ci (void const *data, size_t n_buckets)
+{
+ char const *p = data;
+ mbui_iterator_t iter;
+ size_t value = 0;
+
+ for (mbui_init (iter, p); mbui_avail (iter); mbui_advance (iter))
+ {
+ mbchar_t m = mbui_cur (iter);
+ wchar_t wc;
+
+ if (m.wc_valid)
+ wc = towlower (m.wc);
+ else
+ wc = *m.ptr;
+
+ value = (value * 31 + wc) % n_buckets;
+ }
+
+ return value;
+}
+
+/* compare two strings for equality */
+static bool
+string_compare (void const *data1, void const *data2)
+{
+ char const *p1 = data1;
+ char const *p2 = data2;
+ return strcmp (p1, p2) == 0;
+}
+
+/* compare two strings for equality, case-insensitive */
+static bool
+string_compare_ci (void const *data1, void const *data2)
+{
+ char const *p1 = data1;
+ char const *p2 = data2;
+ return mbscasecmp (p1, p2) == 0;
+}
+
+static void
+string_free (void *data)
+{
+ free (data);
+}
+
+/* Create new exclude segment of given TYPE and OPTIONS, and attach it
+ to the head of EX. */
+static void
+new_exclude_segment (struct exclude *ex, enum exclude_type type, int options)
+{
+ struct exclude_segment *sp = xzalloc (sizeof (struct exclude_segment));
+ sp->type = type;
+ sp->options = options;
+ switch (type)
+ {
+ case exclude_pattern:
+ break;
+
+ case exclude_hash:
+ sp->v.table = hash_initialize (0, NULL,
+ (options & FNM_CASEFOLD) ?
+ string_hasher_ci
+ : string_hasher,
+ (options & FNM_CASEFOLD) ?
+ string_compare_ci
+ : string_compare,
+ string_free);
+ break;
+ }
+ sp->next = ex->head;
+ ex->head = sp;
+}
+
+/* Free a single exclude segment */
+static void
+free_exclude_segment (struct exclude_segment *seg)
+{
+ size_t i;
+
+ switch (seg->type)
+ {
+ case exclude_pattern:
+ for (i = 0; i < seg->v.pat.exclude_count; i++)
+ {
+ if (seg->v.pat.exclude[i].options & EXCLUDE_REGEX)
+ regfree (&seg->v.pat.exclude[i].v.re);
+ }
+ free (seg->v.pat.exclude);
+ break;
+
+ case exclude_hash:
+ hash_free (seg->v.table);
+ break;
+ }
+ free (seg);
+}
+/* Free the storage associated with an exclude list. */
void
free_exclude (struct exclude *ex)
{
- free (ex->exclude);
+ struct exclude_segment *seg;
+ struct pattern_buffer *pbuf;
+
+ for (seg = ex->head; seg; )
+ {
+ struct exclude_segment *next = seg->next;
+ free_exclude_segment (seg);
+ seg = next;
+ }
+
+ for (pbuf = ex->patbuf; pbuf; )
+ {
+ struct pattern_buffer *next = pbuf->next;
+ free (pbuf->base);
+ free (pbuf);
+ pbuf = next;
+ }
+
free (ex);
}
@@ -99,41 +334,41 @@ fnmatch_no_wildcards (char const *pattern, char const *f, int options)
{
if (! (options & FNM_LEADING_DIR))
return ((options & FNM_CASEFOLD)
- ? mbscasecmp (pattern, f)
- : strcmp (pattern, f));
+ ? mbscasecmp (pattern, f)
+ : strcmp (pattern, f));
else if (! (options & FNM_CASEFOLD))
{
size_t patlen = strlen (pattern);
int r = strncmp (pattern, f, patlen);
if (! r)
- {
- r = f[patlen];
- if (r == '/')
- r = 0;
- }
+ {
+ r = f[patlen];
+ if (r == '/')
+ r = 0;
+ }
return r;
}
else
{
/* Walk through a copy of F, seeing whether P matches any prefix
- of F.
+ of F.
- FIXME: This is an O(N**2) algorithm; it should be O(N).
- Also, the copy should not be necessary. However, fixing this
- will probably involve a change to the mbs* API. */
+ FIXME: This is an O(N**2) algorithm; it should be O(N).
+ Also, the copy should not be necessary. However, fixing this
+ will probably involve a change to the mbs* API. */
char *fcopy = xstrdup (f);
char *p;
int r;
for (p = fcopy; ; *p++ = '/')
- {
- p = strchr (p, '/');
- if (p)
- *p = '\0';
- r = mbscasecmp (pattern, fcopy);
- if (!p || r <= 0)
- break;
- }
+ {
+ p = strchr (p, '/');
+ if (p)
+ *p = '\0';
+ r = mbscasecmp (pattern, fcopy);
+ if (!p || r <= 0)
+ break;
+ }
free (fcopy);
return r;
}
@@ -157,36 +392,124 @@ exclude_fnmatch (char const *pattern, char const *f, int options)
return matched;
}
+static bool
+exclude_patopts (struct patopts const *opts, char const *f)
+{
+ int options = opts->options;
+
+ return (options & EXCLUDE_REGEX)
+ ? regexec (&opts->v.re, f, 0, NULL, 0) == 0
+ : exclude_fnmatch (opts->v.pattern, f, options);
+}
+
+/* Return true if the exclude_pattern segment SEG matches F. */
+
+static bool
+file_pattern_matches (struct exclude_segment const *seg, char const *f)
+{
+ size_t exclude_count = seg->v.pat.exclude_count;
+ struct patopts const *exclude = seg->v.pat.exclude;
+ size_t i;
+
+ for (i = 0; i < exclude_count; i++)
+ {
+ if (exclude_patopts (exclude + i, f))
+ return true;
+ }
+ return false;
+}
+
+/* Return true if the exclude_hash segment SEG matches F.
+ BUFFER is an auxiliary storage of the same length as F (with nul
+ terminator included) */
+static bool
+file_name_matches (struct exclude_segment const *seg, char const *f,
+ char *buffer)
+{
+ int options = seg->options;
+ Hash_table *table = seg->v.table;
+
+ do
+ {
+ /* initialize the pattern */
+ strcpy (buffer, f);
+
+ while (1)
+ {
+ if (hash_lookup (table, buffer))
+ return true;
+ if (options & FNM_LEADING_DIR)
+ {
+ char *p = strrchr (buffer, '/');
+ if (p)
+ {
+ *p = 0;
+ continue;
+ }
+ }
+ break;
+ }
+
+ if (!(options & EXCLUDE_ANCHORED))
+ {
+ f = strchr (f, '/');
+ if (f)
+ f++;
+ }
+ else
+ break;
+ }
+ while (f);
+
+ return false;
+}
+
/* Return true if EX excludes F. */
bool
excluded_file_name (struct exclude const *ex, char const *f)
{
- size_t exclude_count = ex->exclude_count;
+ struct exclude_segment *seg;
+ bool invert = false;
+ char *filename = NULL;
- /* If no options are given, the default is to include. */
- if (exclude_count == 0)
+ /* If no patterns are given, the default is to include. */
+ if (!ex->head)
return false;
- else
- {
- struct patopts const *exclude = ex->exclude;
- size_t i;
-
- /* Otherwise, the default is the opposite of the first option. */
- bool excluded = !! (exclude[0].options & EXCLUDE_INCLUDE);
- /* Scan through the options, seeing whether they change F from
- excluded to included or vice versa. */
- for (i = 0; i < exclude_count; i++)
- {
- char const *pattern = exclude[i].pattern;
- int options = exclude[i].options;
- if (excluded == !! (options & EXCLUDE_INCLUDE))
- excluded ^= exclude_fnmatch (pattern, f, options);
- }
-
- return excluded;
+ /* Scan through the segments, reporting the status of the first match.
+ The segments are in reverse order, so this reports the status of
+ the last match in the original option list. */
+ for (seg = ex->head; ; seg = seg->next)
+ {
+ if (seg->type == exclude_hash)
+ {
+ if (!filename)
+ filename = xmalloc (strlen (f) + 1);
+ if (file_name_matches (seg, f, filename))
+ break;
+ }
+ else
+ {
+ if (file_pattern_matches (seg, f))
+ break;
+ }
+
+ if (! seg->next)
+ {
+ /* If patterns are given but none match, the default is the
+ opposite of the last segment (i.e., the first in the
+ original option list). For example, in the command
+ 'grep -r --exclude="a*" --include="*b" pat dir', the
+ first option is --exclude so any file name matching
+ neither a* nor *b is included. */
+ invert = true;
+ break;
+ }
}
+
+ free (filename);
+ return invert ^ ! (seg->options & EXCLUDE_INCLUDE);
}
/* Append to EX the exclusion PATTERN with OPTIONS. */
@@ -194,82 +517,179 @@ excluded_file_name (struct exclude const *ex, char const *f)
void
add_exclude (struct exclude *ex, char const *pattern, int options)
{
+ struct exclude_segment *seg;
+ struct exclude_pattern *pat;
struct patopts *patopts;
- if (ex->exclude_count == ex->exclude_alloc)
- ex->exclude = x2nrealloc (ex->exclude, &ex->exclude_alloc,
- sizeof *ex->exclude);
+ if ((options & (EXCLUDE_REGEX|EXCLUDE_WILDCARDS))
+ && fnmatch_pattern_has_wildcards (pattern, options))
+ {
+ if (! (ex->head && ex->head->type == exclude_pattern
+ && ((ex->head->options & EXCLUDE_INCLUDE)
+ == (options & EXCLUDE_INCLUDE))))
+ new_exclude_segment (ex, exclude_pattern, options);
+
+ seg = ex->head;
+
+ pat = &seg->v.pat;
+ if (pat->exclude_count == pat->exclude_alloc)
+ pat->exclude = x2nrealloc (pat->exclude, &pat->exclude_alloc,
+ sizeof *pat->exclude);
+ patopts = &pat->exclude[pat->exclude_count++];
- patopts = &ex->exclude[ex->exclude_count++];
- patopts->pattern = pattern;
- patopts->options = options;
+ patopts->options = options;
+ if (options & EXCLUDE_REGEX)
+ {
+ int rc;
+ int cflags = REG_NOSUB|REG_EXTENDED|
+ ((options & FNM_CASEFOLD) ? REG_ICASE : 0);
+
+ if (options & FNM_LEADING_DIR)
+ {
+ char *tmp;
+ size_t len = strlen (pattern);
+
+ while (len > 0 && ISSLASH (pattern[len-1]))
+ --len;
+
+ if (len == 0)
+ rc = 1;
+ else
+ {
+ tmp = xmalloc (len + 7);
+ memcpy (tmp, pattern, len);
+ strcpy (tmp + len, "(/.*)?");
+ rc = regcomp (&patopts->v.re, tmp, cflags);
+ free (tmp);
+ }
+ }
+ else
+ rc = regcomp (&patopts->v.re, pattern, cflags);
+
+ if (rc)
+ {
+ pat->exclude_count--;
+ return;
+ }
+ }
+ else
+ {
+ if (options & EXCLUDE_ALLOC)
+ {
+ pattern = xstrdup (pattern);
+ exclude_add_pattern_buffer (ex, (char*) pattern);
+ }
+ patopts->v.pattern = pattern;
+ }
+ }
+ else
+ {
+ char *str, *p;
+ int exclude_hash_flags = (EXCLUDE_INCLUDE | EXCLUDE_ANCHORED
+ | FNM_LEADING_DIR | FNM_CASEFOLD);
+ if (! (ex->head && ex->head->type == exclude_hash
+ && ((ex->head->options & exclude_hash_flags)
+ == (options & exclude_hash_flags))))
+ new_exclude_segment (ex, exclude_hash, options);
+ seg = ex->head;
+
+ str = xstrdup (pattern);
+ if ((options & (EXCLUDE_WILDCARDS | FNM_NOESCAPE)) == EXCLUDE_WILDCARDS)
+ unescape_pattern (str);
+ p = hash_insert (seg->v.table, str);
+ if (p != str)
+ free (str);
+ }
}
/* Use ADD_FUNC to append to EX the patterns in FILE_NAME, each with
OPTIONS. LINE_END terminates each pattern in the file. If
LINE_END is a space character, ignore trailing spaces and empty
- lines in FILE. Return -1 on failure, 0 on success. */
+ lines in FP. Return -1 on failure, 0 on success. */
int
-add_exclude_file (void (*add_func) (struct exclude *, char const *, int),
- struct exclude *ex, char const *file_name, int options,
- char line_end)
+add_exclude_fp (void (*add_func) (struct exclude *, char const *, int, void *),
+ struct exclude *ex, FILE *fp, int options,
+ char line_end,
+ void *data)
{
- bool use_stdin = file_name[0] == '-' && !file_name[1];
- FILE *in;
char *buf = NULL;
char *p;
- char const *pattern;
+ char *pattern;
char const *lim;
size_t buf_alloc = 0;
size_t buf_count = 0;
int c;
int e = 0;
- if (use_stdin)
- in = stdin;
- else if (! (in = fopen (file_name, "r")))
- return -1;
-
- while ((c = getc (in)) != EOF)
+ while ((c = getc (fp)) != EOF)
{
if (buf_count == buf_alloc)
- buf = x2realloc (buf, &buf_alloc);
+ buf = x2realloc (buf, &buf_alloc);
buf[buf_count++] = c;
}
- if (ferror (in))
- e = errno;
-
- if (!use_stdin && fclose (in) != 0)
+ if (ferror (fp))
e = errno;
buf = xrealloc (buf, buf_count + 1);
buf[buf_count] = line_end;
lim = buf + buf_count + ! (buf_count == 0 || buf[buf_count - 1] == line_end);
+
+ exclude_add_pattern_buffer (ex, buf);
+
pattern = buf;
for (p = buf; p < lim; p++)
if (*p == line_end)
{
- char *pattern_end = p;
+ char *pattern_end = p;
- if (isspace ((unsigned char) line_end))
- {
- for (; ; pattern_end--)
- if (pattern_end == pattern)
- goto next_pattern;
- else if (! isspace ((unsigned char) pattern_end[-1]))
- break;
- }
+ if (isspace ((unsigned char) line_end))
+ {
+ for (; ; pattern_end--)
+ if (pattern_end == pattern)
+ goto next_pattern;
+ else if (! isspace ((unsigned char) pattern_end[-1]))
+ break;
+ }
- *pattern_end = '\0';
- (*add_func) (ex, pattern, options);
+ *pattern_end = '\0';
+ (*add_func) (ex, pattern, options, data);
next_pattern:
- pattern = p + 1;
+ pattern = p + 1;
}
errno = e;
return e ? -1 : 0;
}
+
+static void
+call_addfn (struct exclude *ex, char const *pattern, int options, void *data)
+{
+ void (**addfnptr) (struct exclude *, char const *, int) = data;
+ (*addfnptr) (ex, pattern, options);
+}
+
+int
+add_exclude_file (void (*add_func) (struct exclude *, char const *, int),
+ struct exclude *ex, char const *file_name, int options,
+ char line_end)
+{
+ bool use_stdin = file_name[0] == '-' && !file_name[1];
+ FILE *in;
+ int rc = 0;
+
+ if (use_stdin)
+ in = stdin;
+ else if (! (in = fopen (file_name, "r")))
+ return -1;
+
+ rc = add_exclude_fp (call_addfn, ex, in, options, line_end, &add_func);
+
+ if (!use_stdin && fclose (in) != 0)
+ rc = -1;
+
+ return rc;
+}
diff --git a/lib/exclude.h b/lib/exclude.h
index 203e384..8cb8b36 100644
--- a/lib/exclude.h
+++ b/lib/exclude.h
@@ -1,12 +1,12 @@
/* exclude.h -- declarations for excluding file names
- Copyright (C) 1992, 1993, 1994, 1997, 1999, 2001, 2002, 2003, 2005,
- 2006 Free Software Foundation, Inc.
+ Copyright (C) 1992-1994, 1997, 1999, 2001-2003, 2005-2006, 2009-2016 Free
+ Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,11 +14,16 @@
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with this program; see the file COPYING.
- If not, write to the Free Software Foundation,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
-/* Written by Paul Eggert <eggert@twinsun.com> */
+#ifndef _GL_EXCLUDE_H
+#define _GL_EXCLUDE_H 1
+
+#include <stdbool.h>
+#include <stdio.h>
+
+/* Written by Paul Eggert <eggert@twinsun.com>
+ and Sergey Poznyakoff <gray@gnu.org> */
/* Exclude options, which can be ORed with fnmatch options. */
@@ -33,12 +38,25 @@
option, these characters are ordinary and fnmatch is not used. */
#define EXCLUDE_WILDCARDS (1 << 28)
+/* Patterns are POSIX extended regular expressions */
+#define EXCLUDE_REGEX (1 << 27)
+
+/* Allocate storage for the pattern */
+#define EXCLUDE_ALLOC (1 << 26)
+
struct exclude;
+bool fnmatch_pattern_has_wildcards (const char *, int) _GL_ATTRIBUTE_PURE;
+
struct exclude *new_exclude (void);
void free_exclude (struct exclude *);
void add_exclude (struct exclude *, char const *, int);
int add_exclude_file (void (*) (struct exclude *, char const *, int),
- struct exclude *, char const *, int, char);
+ struct exclude *, char const *, int, char);
+int add_exclude_fp (void (*) (struct exclude *, char const *, int, void *),
+ struct exclude *, FILE *, int, char, void *);
bool excluded_file_name (struct exclude const *, char const *);
-bool exclude_fnmatch (char const *pattern, char const *f, int options);
+void exclude_add_pattern_buffer (struct exclude *ex, char *buf);
+bool exclude_fnmatch (char const *, char const *, int);
+
+#endif /* _GL_EXCLUDE_H */
diff --git a/lib/exitfail.c b/lib/exitfail.c
index 373d325..8033c22 100644
--- a/lib/exitfail.c
+++ b/lib/exitfail.c
@@ -1,11 +1,11 @@
/* Failure exit status
- Copyright (C) 2002, 2003, 2005, 2006, 2007 Free Software Foundation, Inc.
+ Copyright (C) 2002-2003, 2005-2007, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,9 +13,7 @@
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with this program; see the file COPYING.
- If not, write to the Free Software Foundation,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
diff --git a/lib/exitfail.h b/lib/exitfail.h
index e46cf9c..62311bd 100644
--- a/lib/exitfail.h
+++ b/lib/exitfail.h
@@ -1,11 +1,11 @@
/* Failure exit status
- Copyright (C) 2002 Free Software Foundation, Inc.
+ Copyright (C) 2002, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,6 @@
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with this program; see the file COPYING.
- If not, write to the Free Software Foundation,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
extern int volatile exit_failure;
diff --git a/lib/faccessat.c b/lib/faccessat.c
new file mode 100644
index 0000000..1743fa3
--- /dev/null
+++ b/lib/faccessat.c
@@ -0,0 +1,45 @@
+/* Check the access rights of a file relative to an open directory.
+ Copyright (C) 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* written by Eric Blake */
+
+#include <config.h>
+
+#include <unistd.h>
+#include <fcntl.h>
+
+#ifndef HAVE_ACCESS
+/* Mingw lacks access, but it also lacks real vs. effective ids, so
+ the gnulib euidaccess module is good enough. */
+# undef access
+# define access euidaccess
+#endif
+
+/* Invoke access or euidaccess on file, FILE, using mode MODE, in the directory
+ open on descriptor FD. If possible, do it without changing the
+ working directory. Otherwise, resort to using save_cwd/fchdir, then
+ (access|euidaccess)/restore_cwd. If either the save_cwd or the
+ restore_cwd fails, then give a diagnostic and exit nonzero.
+ Note that this implementation only supports AT_EACCESS, although some
+ native versions also support AT_SYMLINK_NOFOLLOW. */
+
+#define AT_FUNC_NAME faccessat
+#define AT_FUNC_F1 euidaccess
+#define AT_FUNC_F2 access
+#define AT_FUNC_USE_F1_COND AT_EACCESS
+#define AT_FUNC_POST_FILE_PARAM_DECLS , int mode, int flag
+#define AT_FUNC_POST_FILE_ARGS , mode
+#include "at-func.c"
diff --git a/lib/fadvise.c b/lib/fadvise.c
new file mode 100644
index 0000000..ddac592
--- /dev/null
+++ b/lib/fadvise.c
@@ -0,0 +1,43 @@
+/* Declare an access pattern hint for files.
+ Copyright (C) 2010-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Without this pragma, gcc suggests that (given !HAVE_POSIX_FADVISE)
+ the fdadvise function might be a candidate for attribute 'const'. */
+#if (__GNUC__ == 4 && 6 <= __GNUC_MINOR__) || 4 < __GNUC__
+# pragma GCC diagnostic ignored "-Wsuggest-attribute=const"
+#endif
+
+#include <config.h>
+#include "fadvise.h"
+
+#include <stdio.h>
+#include <fcntl.h>
+#include "ignore-value.h"
+
+void
+fdadvise (int fd, off_t offset, off_t len, fadvice_t advice)
+{
+#if HAVE_POSIX_FADVISE
+ ignore_value (posix_fadvise (fd, offset, len, advice));
+#endif
+}
+
+void
+fadvise (FILE *fp, fadvice_t advice)
+{
+ if (fp)
+ fdadvise (fileno (fp), 0, 0, advice);
+}
diff --git a/lib/fadvise.h b/lib/fadvise.h
new file mode 100644
index 0000000..1a44cb1
--- /dev/null
+++ b/lib/fadvise.h
@@ -0,0 +1,72 @@
+/* Declare an access pattern hint for files.
+ Copyright (C) 2010-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+#include <stdio.h>
+#include <fcntl.h>
+#include <sys/types.h>
+
+/* There are a few hints one can provide, which have the
+ following characteristics on Linux 2.6.31 at least.
+
+ POSIX_FADV_SEQUENTIAL
+ Doubles the size of read ahead done for file
+ POSIX_FADV_WILLNEED
+ _synchronously_ prepopulate the buffer cache with the file
+ POSIX_FADV_NOREUSE
+ Could lower priority of data in buffer caches,
+ but currently does nothing.
+ POSIX_FADV_DONTNEED
+ Drop the file from cache.
+ Note this is automatically done when files are unlinked.
+
+ We use this enum "type" both to make it explicit that
+ these options are mutually exclusive, and to discourage
+ the passing of the possibly undefined POSIX_FADV_... values.
+ Note we could #undef the POSIX_FADV_ values, but that would
+ preclude using the posix_fadvise() function with its standard
+ constants. Using posix_fadvise() might be required if the return
+ value is needed, but it must be guarded by appropriate #ifdefs. */
+
+#if HAVE_POSIX_FADVISE
+typedef enum {
+ FADVISE_NORMAL = POSIX_FADV_NORMAL,
+ FADVISE_SEQUENTIAL = POSIX_FADV_SEQUENTIAL,
+ FADVISE_NOREUSE = POSIX_FADV_NOREUSE,
+ FADVISE_DONTNEED = POSIX_FADV_DONTNEED,
+ FADVISE_WILLNEED = POSIX_FADV_WILLNEED,
+ FADVISE_RANDOM = POSIX_FADV_RANDOM
+} fadvice_t;
+#else
+typedef enum {
+ FADVISE_NORMAL,
+ FADVISE_SEQUENTIAL,
+ FADVISE_NOREUSE,
+ FADVISE_DONTNEED,
+ FADVISE_WILLNEED,
+ FADVISE_RANDOM
+} fadvice_t;
+#endif
+
+/* We ignore any errors as these hints are only advisory.
+ There is the chance one can pass invalid ADVICE, which will
+ not be indicated, but given the simplicity of the interface
+ this is unlikely. Also not returning errors allows the
+ unconditional passing of descriptors to non standard files,
+ which will just be ignored if unsupported. */
+
+void fdadvise (int fd, off_t offset, off_t len, fadvice_t advice);
+void fadvise (FILE *fp, fadvice_t advice);
diff --git a/lib/fchdir.c b/lib/fchdir.c
index e3ec2fc..8a7a072 100644
--- a/lib/fchdir.c
+++ b/lib/fchdir.c
@@ -1,10 +1,10 @@
/* fchdir replacement.
- Copyright (C) 2006, 2007 Free Software Foundation, Inc.
+ Copyright (C) 2006-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -12,268 +12,197 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
/* Specification. */
#include <unistd.h>
+#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
-#include <stdarg.h>
+#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
-#include <dirent.h>
-#include "canonicalize.h"
-#include "dirfd.h"
+#include "assure.h"
+#include "dosname.h"
+#include "filenamecat.h"
+
+#ifndef REPLACE_OPEN_DIRECTORY
+# define REPLACE_OPEN_DIRECTORY 0
+#endif
/* This replacement assumes that a directory is not renamed while opened
- through a file descriptor. */
+ through a file descriptor.
-/* Array of file descriptors opened. If it points to a directory, it stores
- info about this directory; otherwise it stores an errno value of ENOTDIR. */
+ FIXME: On mingw, this would be possible to enforce if we were to
+ also open a HANDLE to each directory currently visited by a file
+ descriptor, since mingw refuses to rename any in-use file system
+ object. */
+
+/* Array of file descriptors opened. If REPLACE_OPEN_DIRECTORY or if it points
+ to a directory, it stores info about this directory. */
typedef struct
{
char *name; /* Absolute name of the directory, or NULL. */
- int saved_errno; /* If name == NULL: The error code describing the failure
- reason. */
+ /* FIXME - add a DIR* member to make dirfd possible on mingw? */
} dir_info_t;
static dir_info_t *dirs;
static size_t dirs_allocated;
-/* Try to ensure dirs has enough room for a slot at index fd. */
-static void
+/* Try to ensure dirs has enough room for a slot at index fd; free any
+ contents already in that slot. Return false and set errno to
+ ENOMEM on allocation failure. */
+static bool
ensure_dirs_slot (size_t fd)
{
- if (fd >= dirs_allocated)
+ if (fd < dirs_allocated)
+ free (dirs[fd].name);
+ else
{
size_t new_allocated;
dir_info_t *new_dirs;
- size_t i;
new_allocated = 2 * dirs_allocated + 1;
if (new_allocated <= fd)
- new_allocated = fd + 1;
+ new_allocated = fd + 1;
new_dirs =
- (dirs != NULL
- ? (dir_info_t *) realloc (dirs, new_allocated * sizeof (dir_info_t))
- : (dir_info_t *) malloc (new_allocated * sizeof (dir_info_t)));
- if (new_dirs != NULL)
- {
- for (i = dirs_allocated; i < new_allocated; i++)
- {
- new_dirs[i].name = NULL;
- new_dirs[i].saved_errno = ENOTDIR;
- }
- dirs = new_dirs;
- dirs_allocated = new_allocated;
- }
+ (dirs != NULL
+ ? (dir_info_t *) realloc (dirs, new_allocated * sizeof *dirs)
+ : (dir_info_t *) malloc (new_allocated * sizeof *dirs));
+ if (new_dirs == NULL)
+ return false;
+ memset (new_dirs + dirs_allocated, 0,
+ (new_allocated - dirs_allocated) * sizeof *dirs);
+ dirs = new_dirs;
+ dirs_allocated = new_allocated;
}
+ return true;
}
-/* Override open() and close(), to keep track of the open file descriptors. */
-
-int
-close (int fd)
-#undef close
+/* Return an absolute name of DIR in malloc'd storage. */
+static char *
+get_name (char const *dir)
{
- int retval = close (fd);
+ char *cwd;
+ char *result;
+ int saved_errno;
+
+ if (IS_ABSOLUTE_FILE_NAME (dir))
+ return strdup (dir);
+
+ /* We often encounter "."; treat it as a special case. */
+ cwd = getcwd (NULL, 0);
+ if (!cwd || (dir[0] == '.' && dir[1] == '\0'))
+ return cwd;
+
+ result = mfile_name_concat (cwd, dir, NULL);
+ saved_errno = errno;
+ free (cwd);
+ errno = saved_errno;
+ return result;
+}
- if (retval >= 0 && fd >= 0 && fd < dirs_allocated)
+/* Hook into the gnulib replacements for open() and close() to keep track
+ of the open file descriptors. */
+
+/* Close FD, cleaning up any fd to name mapping if fd was visiting a
+ directory. */
+void
+_gl_unregister_fd (int fd)
+{
+ if (fd >= 0 && fd < dirs_allocated)
{
- if (dirs[fd].name != NULL)
- free (dirs[fd].name);
+ free (dirs[fd].name);
dirs[fd].name = NULL;
- dirs[fd].saved_errno = ENOTDIR;
}
- return retval;
}
+/* Mark FD as visiting FILENAME. FD must be non-negative, and refer
+ to an open file descriptor. If REPLACE_OPEN_DIRECTORY is non-zero,
+ this should only be called if FD is visiting a directory. Close FD
+ and return -1 if there is insufficient memory to track the
+ directory name; otherwise return FD. */
int
-open (const char *filename, int flags, ...)
-#undef open
+_gl_register_fd (int fd, const char *filename)
{
- mode_t mode;
- int fd;
struct stat statbuf;
- mode = 0;
- if (flags & O_CREAT)
+ assure (0 <= fd);
+ if (REPLACE_OPEN_DIRECTORY
+ || (fstat (fd, &statbuf) == 0 && S_ISDIR (statbuf.st_mode)))
{
- va_list arg;
- va_start (arg, flags);
-
- /* If mode_t is narrower than int, use the promoted type (int),
- not mode_t. Use sizeof to guess whether mode_t is narrower;
- we don't know of any practical counterexamples. */
- mode = (sizeof (mode_t) < sizeof (int)
- ? va_arg (arg, int)
- : va_arg (arg, mode_t));
-
- va_end (arg);
- }
- fd = open (filename, flags, mode);
- if (fd >= 0)
- {
- ensure_dirs_slot (fd);
- if (fd < dirs_allocated
- && fstat (fd, &statbuf) >= 0 && S_ISDIR (statbuf.st_mode))
- {
- dirs[fd].name = canonicalize_file_name (filename);
- if (dirs[fd].name == NULL)
- dirs[fd].saved_errno = errno;
- }
+ if (!ensure_dirs_slot (fd)
+ || (dirs[fd].name = get_name (filename)) == NULL)
+ {
+ int saved_errno = errno;
+ close (fd);
+ errno = saved_errno;
+ return -1;
+ }
}
return fd;
}
-/* Override opendir() and closedir(), to keep track of the open file
- descriptors. Needed because there is a function dirfd(). */
-
+/* Mark NEWFD as a duplicate of OLDFD; useful from dup, dup2, dup3,
+ and fcntl. Both arguments must be valid and distinct file
+ descriptors. Close NEWFD and return -1 if OLDFD is tracking a
+ directory, but there is insufficient memory to track the same
+ directory in NEWFD; otherwise return NEWFD. */
int
-closedir (DIR *dp)
-#undef closedir
-{
- int fd = dirfd (dp);
- int retval = closedir (dp);
-
- if (retval >= 0 && fd >= 0 && fd < dirs_allocated)
- {
- if (dirs[fd].name != NULL)
- free (dirs[fd].name);
- dirs[fd].name = NULL;
- dirs[fd].saved_errno = ENOTDIR;
- }
- return retval;
-}
-
-DIR *
-opendir (const char *filename)
-#undef opendir
+_gl_register_dup (int oldfd, int newfd)
{
- DIR *dp;
-
- dp = opendir (filename);
- if (dp != NULL)
+ assure (0 <= oldfd && 0 <= newfd && oldfd != newfd);
+ if (oldfd < dirs_allocated && dirs[oldfd].name)
{
- int fd = dirfd (dp);
- if (fd >= 0)
- {
- ensure_dirs_slot (fd);
- if (fd < dirs_allocated)
- {
- dirs[fd].name = canonicalize_file_name (filename);
- if (dirs[fd].name == NULL)
- dirs[fd].saved_errno = errno;
- }
- }
+ /* Duplicated a directory; must ensure newfd is allocated. */
+ if (!ensure_dirs_slot (newfd)
+ || (dirs[newfd].name = strdup (dirs[oldfd].name)) == NULL)
+ {
+ int saved_errno = errno;
+ close (newfd);
+ errno = saved_errno;
+ newfd = -1;
+ }
}
- return dp;
-}
-
-/* Override dup() and dup2(), to keep track of open file descriptors. */
-
-int
-dup (int oldfd)
-#undef dup
-{
- int newfd = dup (oldfd);
-
- if (oldfd >= 0 && newfd >= 0)
+ else if (newfd < dirs_allocated)
{
- ensure_dirs_slot (newfd);
- if (newfd < dirs_allocated)
- {
- if (oldfd < dirs_allocated)
- {
- if (dirs[oldfd].name != NULL)
- {
- dirs[newfd].name = strdup (dirs[oldfd].name);
- if (dirs[newfd].name == NULL)
- dirs[newfd].saved_errno = ENOMEM;
- }
- else
- {
- dirs[newfd].name = NULL;
- dirs[newfd].saved_errno = dirs[oldfd].saved_errno;
- }
- }
- else
- {
- dirs[newfd].name = NULL;
- dirs[newfd].saved_errno = ENOMEM;
- }
- }
+ /* Duplicated a non-directory; ensure newfd is cleared. */
+ free (dirs[newfd].name);
+ dirs[newfd].name = NULL;
}
return newfd;
}
-int
-dup2 (int oldfd, int newfd)
-#undef dup2
+/* If FD is currently visiting a directory, then return the name of
+ that directory. Otherwise, return NULL and set errno. */
+const char *
+_gl_directory_name (int fd)
{
- int retval = dup2 (oldfd, newfd);
-
- if (retval >= 0 && oldfd >= 0 && newfd >= 0 && newfd != oldfd)
+ if (0 <= fd && fd < dirs_allocated && dirs[fd].name != NULL)
+ return dirs[fd].name;
+ /* At this point, fd is either invalid, or open but not a directory.
+ If dup2 fails, errno is correctly EBADF. */
+ if (0 <= fd)
{
- ensure_dirs_slot (newfd);
- if (newfd < dirs_allocated)
- {
- if (oldfd < dirs_allocated)
- {
- if (dirs[oldfd].name != NULL)
- {
- dirs[newfd].name = strdup (dirs[oldfd].name);
- if (dirs[newfd].name == NULL)
- dirs[newfd].saved_errno = ENOMEM;
- }
- else
- {
- dirs[newfd].name = NULL;
- dirs[newfd].saved_errno = dirs[oldfd].saved_errno;
- }
- }
- else
- {
- dirs[newfd].name = NULL;
- dirs[newfd].saved_errno = ENOMEM;
- }
- }
+ if (dup2 (fd, fd) == fd)
+ errno = ENOTDIR;
}
- return retval;
+ else
+ errno = EBADF;
+ return NULL;
}
+
/* Implement fchdir() in terms of chdir(). */
int
fchdir (int fd)
{
- if (fd >= 0)
- {
- if (fd < dirs_allocated)
- {
- if (dirs[fd].name != NULL)
- return chdir (dirs[fd].name);
- else
- {
- errno = dirs[fd].saved_errno;
- return -1;
- }
- }
- else
- {
- errno = ENOMEM;
- return -1;
- }
- }
- else
- {
- errno = EBADF;
- return -1;
- }
+ const char *name = _gl_directory_name (fd);
+ return name ? chdir (name) : -1;
}
diff --git a/lib/fchmodat.c b/lib/fchmodat.c
index 2598b70..3d0604c 100644
--- a/lib/fchmodat.c
+++ b/lib/fchmodat.c
@@ -1,10 +1,10 @@
/* Change the protections of file relative to an open directory.
- Copyright (C) 2006 Free Software Foundation, Inc.
+ Copyright (C) 2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -12,39 +12,42 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* written by Jim Meyering */
#include <config.h>
-#include "openat.h"
-#include "dirname.h" /* solely for definition of IS_ABSOLUTE_FILE_NAME */
-#include "save-cwd.h"
-#include "openat-priv.h"
+#include <sys/stat.h>
+
+#include <errno.h>
#ifndef HAVE_LCHMOD
/* Use a different name, to avoid conflicting with any
system-supplied declaration. */
# undef lchmod
# define lchmod lchmod_rpl
-static int lchmod (char const *f, mode_t m) { errno = ENOSYS; return -1; }
+static int
+lchmod (char const *f _GL_UNUSED, mode_t m _GL_UNUSED)
+{
+ errno = ENOSYS;
+ return -1;
+}
#endif
/* Solaris 10 has no function like this.
Invoke chmod or lchmod on file, FILE, using mode MODE, in the directory
open on descriptor FD. If possible, do it without changing the
working directory. Otherwise, resort to using save_cwd/fchdir,
- then mkdir/restore_cwd. If either the save_cwd or the restore_cwd
- fails, then give a diagnostic and exit nonzero.
+ then (chmod|lchmod)/restore_cwd. If either the save_cwd or the
+ restore_cwd fails, then give a diagnostic and exit nonzero.
Note that an attempt to use a FLAG value of AT_SYMLINK_NOFOLLOW
on a system without lchmod support causes this function to fail. */
#define AT_FUNC_NAME fchmodat
#define AT_FUNC_F1 lchmod
#define AT_FUNC_F2 chmod
-#define AT_FUNC_USE_F1_COND flag == AT_SYMLINK_NOFOLLOW
+#define AT_FUNC_USE_F1_COND AT_SYMLINK_NOFOLLOW
#define AT_FUNC_POST_FILE_PARAM_DECLS , mode_t mode, int flag
#define AT_FUNC_POST_FILE_ARGS , mode
#include "at-func.c"
diff --git a/lib/fchown-stub.c b/lib/fchown-stub.c
index 6be750b..62b6969 100644
--- a/lib/fchown-stub.c
+++ b/lib/fchown-stub.c
@@ -3,9 +3,9 @@
#include <sys/types.h>
#include <errno.h>
-/* A trivial substitute for `fchown'.
+/* A trivial substitute for 'fchown'.
- DJGPP 2.03 and earlier (and perhaps later) don't have `fchown',
+ DJGPP 2.03 and earlier (and perhaps later) don't have 'fchown',
so we pretend no-one has permission for this operation. */
int
diff --git a/lib/fchownat.c b/lib/fchownat.c
index 801c92a..7f1c160 100644
--- a/lib/fchownat.c
+++ b/lib/fchownat.c
@@ -4,12 +4,12 @@
when the buggy fchownat-with-AT_SYMLINK_NOFOLLOW operates on a symlink, it
mistakenly affects the symlink referent, rather than the symlink itself.
- Copyright (C) 2006-2007 Free Software Foundation, Inc.
+ Copyright (C) 2006-2007, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -17,34 +17,98 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* written by Jim Meyering */
#include <config.h>
-#include "openat.h"
-
#include <unistd.h>
-#include "dirname.h" /* solely for definition of IS_ABSOLUTE_FILE_NAME */
-#include "lchown.h"
-#include "save-cwd.h"
-#include "openat-priv.h"
+#include <errno.h>
+#include <string.h>
+
+#include "openat.h"
+
+#if !HAVE_FCHOWNAT
/* Replacement for Solaris' function by the same name.
Invoke chown or lchown on file, FILE, using OWNER and GROUP, in the
directory open on descriptor FD. If FLAG is AT_SYMLINK_NOFOLLOW, then
use lchown, otherwise, use chown. If possible, do it without changing
the working directory. Otherwise, resort to using save_cwd/fchdir,
- then mkdir/restore_cwd. If either the save_cwd or the restore_cwd
- fails, then give a diagnostic and exit nonzero. */
-
-#define AT_FUNC_NAME fchownat
-#define AT_FUNC_F1 lchown
-#define AT_FUNC_F2 chown
-#define AT_FUNC_USE_F1_COND flag == AT_SYMLINK_NOFOLLOW
-#define AT_FUNC_POST_FILE_PARAM_DECLS , uid_t owner, gid_t group, int flag
-#define AT_FUNC_POST_FILE_ARGS , owner, group
-#include "at-func.c"
+ then (chown|lchown)/restore_cwd. If either the save_cwd or the
+ restore_cwd fails, then give a diagnostic and exit nonzero. */
+
+# define AT_FUNC_NAME fchownat
+# define AT_FUNC_F1 lchown
+# define AT_FUNC_F2 chown
+# define AT_FUNC_USE_F1_COND AT_SYMLINK_NOFOLLOW
+# define AT_FUNC_POST_FILE_PARAM_DECLS , uid_t owner, gid_t group, int flag
+# define AT_FUNC_POST_FILE_ARGS , owner, group
+# include "at-func.c"
+# undef AT_FUNC_NAME
+# undef AT_FUNC_F1
+# undef AT_FUNC_F2
+# undef AT_FUNC_USE_F1_COND
+# undef AT_FUNC_POST_FILE_PARAM_DECLS
+# undef AT_FUNC_POST_FILE_ARGS
+
+#else /* HAVE_FCHOWNAT */
+
+# undef fchownat
+
+# if FCHOWNAT_NOFOLLOW_BUG
+
+/* Failure to handle AT_SYMLINK_NOFOLLOW requires the /proc/self/fd or
+ fchdir workaround to call lchown for lchownat, but there is no need
+ to penalize chownat. */
+static int
+local_lchownat (int fd, char const *file, uid_t owner, gid_t group);
+
+# define AT_FUNC_NAME local_lchownat
+# define AT_FUNC_F1 lchown
+# define AT_FUNC_POST_FILE_PARAM_DECLS , uid_t owner, gid_t group
+# define AT_FUNC_POST_FILE_ARGS , owner, group
+# include "at-func.c"
+# undef AT_FUNC_NAME
+# undef AT_FUNC_F1
+# undef AT_FUNC_POST_FILE_PARAM_DECLS
+# undef AT_FUNC_POST_FILE_ARGS
+
+# endif
+
+/* Work around bugs with trailing slash, using the same workarounds as
+ chown and lchown. */
+
+int
+rpl_fchownat (int fd, char const *file, uid_t owner, gid_t group, int flag)
+{
+# if FCHOWNAT_NOFOLLOW_BUG
+ if (flag == AT_SYMLINK_NOFOLLOW)
+ return local_lchownat (fd, file, owner, group);
+# endif
+# if FCHOWNAT_EMPTY_FILENAME_BUG
+ if (file[0] == '\0')
+ {
+ errno = ENOENT;
+ return -1;
+ }
+# endif
+# if CHOWN_TRAILING_SLASH_BUG
+ {
+ size_t len = strlen (file);
+ struct stat st;
+ if (len && file[len - 1] == '/')
+ {
+ if (statat (fd, file, &st))
+ return -1;
+ if (flag == AT_SYMLINK_NOFOLLOW)
+ return fchownat (fd, file, owner, group, 0);
+ }
+ }
+# endif
+ return fchownat (fd, file, owner, group, flag);
+}
+
+#endif /* HAVE_FCHOWNAT */
diff --git a/lib/fclose.c b/lib/fclose.c
new file mode 100644
index 0000000..d4783f6
--- /dev/null
+++ b/lib/fclose.c
@@ -0,0 +1,110 @@
+/* fclose replacement.
+ Copyright (C) 2008-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <stdio.h>
+
+#include <errno.h>
+#include <unistd.h>
+
+#include "freading.h"
+#include "msvc-inval.h"
+
+#undef fclose
+
+#if HAVE_MSVC_INVALID_PARAMETER_HANDLER
+static int
+fclose_nothrow (FILE *fp)
+{
+ int result;
+
+ TRY_MSVC_INVAL
+ {
+ result = fclose (fp);
+ }
+ CATCH_MSVC_INVAL
+ {
+ result = EOF;
+ errno = EBADF;
+ }
+ DONE_MSVC_INVAL;
+
+ return result;
+}
+#else
+# define fclose_nothrow fclose
+#endif
+
+/* Override fclose() to call the overridden fflush() or close(). */
+
+int
+rpl_fclose (FILE *fp)
+{
+ int saved_errno = 0;
+ int fd;
+ int result = 0;
+
+ /* Don't change behavior on memstreams. */
+ fd = fileno (fp);
+ if (fd < 0)
+ return fclose_nothrow (fp);
+
+ /* We only need to flush the file if it is not reading or if it is
+ seekable. This only guarantees the file position of input files
+ if the fflush module is also in use. */
+ if ((!freading (fp) || lseek (fileno (fp), 0, SEEK_CUR) != -1)
+ && fflush (fp))
+ saved_errno = errno;
+
+ /* fclose() calls close(), but we need to also invoke all hooks that our
+ overridden close() function invokes. See lib/close.c. */
+#if WINDOWS_SOCKETS
+ /* Call the overridden close(), then the original fclose().
+ Note about multithread-safety: There is a race condition where some
+ other thread could open fd between our close and fclose. */
+ if (close (fd) < 0 && saved_errno == 0)
+ saved_errno = errno;
+
+ fclose_nothrow (fp); /* will fail with errno = EBADF,
+ if we did not lose a race */
+
+#else /* !WINDOWS_SOCKETS */
+ /* Call fclose() and invoke all hooks of the overridden close(). */
+
+# if REPLACE_FCHDIR
+ /* Note about multithread-safety: There is a race condition here as well.
+ Some other thread could open fd between our calls to fclose and
+ _gl_unregister_fd. */
+ result = fclose_nothrow (fp);
+ if (result == 0)
+ _gl_unregister_fd (fd);
+# else
+ /* No race condition here. */
+ result = fclose_nothrow (fp);
+# endif
+
+#endif /* !WINDOWS_SOCKETS */
+
+ if (saved_errno != 0)
+ {
+ errno = saved_errno;
+ result = EOF;
+ }
+
+ return result;
+}
diff --git a/lib/fcntl--.h b/lib/fcntl--.h
index 51b869e..14f218c 100644
--- a/lib/fcntl--.h
+++ b/lib/fcntl--.h
@@ -1,11 +1,11 @@
/* Like fcntl.h, but redefine some names to avoid glitches.
- Copyright (C) 2005 Free Software Foundation, Inc.
+ Copyright (C) 2005, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
@@ -26,3 +25,8 @@
#undef creat
#define creat creat_safer
+
+#if GNULIB_OPENAT_SAFER
+# undef openat
+# define openat openat_safer
+#endif
diff --git a/lib/fcntl-safer.h b/lib/fcntl-safer.h
index cab6aab..21e9333 100644
--- a/lib/fcntl-safer.h
+++ b/lib/fcntl-safer.h
@@ -1,11 +1,11 @@
/* Invoke fcntl-like functions, but avoid some glitches.
- Copyright (C) 2005 Free Software Foundation, Inc.
+ Copyright (C) 2005, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
@@ -22,3 +21,7 @@
int open_safer (char const *, int, ...);
int creat_safer (char const *, mode_t);
+
+#if GNULIB_OPENAT_SAFER
+int openat_safer (int, char const *, int, ...);
+#endif
diff --git a/lib/fcntl.c b/lib/fcntl.c
new file mode 100644
index 0000000..fd17e96
--- /dev/null
+++ b/lib/fcntl.c
@@ -0,0 +1,414 @@
+/* Provide file descriptor control.
+
+ Copyright (C) 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Eric Blake <ebb9@byu.net>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <fcntl.h>
+
+#include <errno.h>
+#include <limits.h>
+#include <stdarg.h>
+#include <unistd.h>
+
+#if !HAVE_FCNTL
+# define rpl_fcntl fcntl
+#endif
+#undef fcntl
+
+#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+/* Get declarations of the native Windows API functions. */
+# define WIN32_LEAN_AND_MEAN
+# include <windows.h>
+
+/* Get _get_osfhandle. */
+# include "msvc-nothrow.h"
+
+/* Upper bound on getdtablesize(). See lib/getdtablesize.c. */
+# define OPEN_MAX_MAX 0x10000
+
+/* Duplicate OLDFD into the first available slot of at least NEWFD,
+ which must be positive, with FLAGS determining whether the duplicate
+ will be inheritable. */
+static int
+dupfd (int oldfd, int newfd, int flags)
+{
+ /* Mingw has no way to create an arbitrary fd. Iterate until all
+ file descriptors less than newfd are filled up. */
+ HANDLE curr_process = GetCurrentProcess ();
+ HANDLE old_handle = (HANDLE) _get_osfhandle (oldfd);
+ unsigned char fds_to_close[OPEN_MAX_MAX / CHAR_BIT];
+ unsigned int fds_to_close_bound = 0;
+ int result;
+ BOOL inherit = flags & O_CLOEXEC ? FALSE : TRUE;
+ int mode;
+
+ if (newfd < 0 || getdtablesize () <= newfd)
+ {
+ errno = EINVAL;
+ return -1;
+ }
+ if (old_handle == INVALID_HANDLE_VALUE
+ || (mode = setmode (oldfd, O_BINARY)) == -1)
+ {
+ /* oldfd is not open, or is an unassigned standard file
+ descriptor. */
+ errno = EBADF;
+ return -1;
+ }
+ setmode (oldfd, mode);
+ flags |= mode;
+
+ for (;;)
+ {
+ HANDLE new_handle;
+ int duplicated_fd;
+ unsigned int index;
+
+ if (!DuplicateHandle (curr_process, /* SourceProcessHandle */
+ old_handle, /* SourceHandle */
+ curr_process, /* TargetProcessHandle */
+ (PHANDLE) &new_handle, /* TargetHandle */
+ (DWORD) 0, /* DesiredAccess */
+ inherit, /* InheritHandle */
+ DUPLICATE_SAME_ACCESS)) /* Options */
+ {
+ switch (GetLastError ())
+ {
+ case ERROR_TOO_MANY_OPEN_FILES:
+ errno = EMFILE;
+ break;
+ case ERROR_INVALID_HANDLE:
+ case ERROR_INVALID_TARGET_HANDLE:
+ case ERROR_DIRECT_ACCESS_HANDLE:
+ errno = EBADF;
+ break;
+ case ERROR_INVALID_PARAMETER:
+ case ERROR_INVALID_FUNCTION:
+ case ERROR_INVALID_ACCESS:
+ errno = EINVAL;
+ break;
+ default:
+ errno = EACCES;
+ break;
+ }
+ result = -1;
+ break;
+ }
+ duplicated_fd = _open_osfhandle ((intptr_t) new_handle, flags);
+ if (duplicated_fd < 0)
+ {
+ CloseHandle (new_handle);
+ result = -1;
+ break;
+ }
+ if (newfd <= duplicated_fd)
+ {
+ result = duplicated_fd;
+ break;
+ }
+
+ /* Set the bit duplicated_fd in fds_to_close[]. */
+ index = (unsigned int) duplicated_fd / CHAR_BIT;
+ if (fds_to_close_bound <= index)
+ {
+ if (sizeof fds_to_close <= index)
+ /* Need to increase OPEN_MAX_MAX. */
+ abort ();
+ memset (fds_to_close + fds_to_close_bound, '\0',
+ index + 1 - fds_to_close_bound);
+ fds_to_close_bound = index + 1;
+ }
+ fds_to_close[index] |= 1 << ((unsigned int) duplicated_fd % CHAR_BIT);
+ }
+
+ /* Close the previous fds that turned out to be too small. */
+ {
+ int saved_errno = errno;
+ unsigned int duplicated_fd;
+
+ for (duplicated_fd = 0;
+ duplicated_fd < fds_to_close_bound * CHAR_BIT;
+ duplicated_fd++)
+ if ((fds_to_close[duplicated_fd / CHAR_BIT]
+ >> (duplicated_fd % CHAR_BIT))
+ & 1)
+ close (duplicated_fd);
+
+ errno = saved_errno;
+ }
+
+# if REPLACE_FCHDIR
+ if (0 <= result)
+ result = _gl_register_dup (oldfd, result);
+# endif
+ return result;
+}
+#endif /* W32 */
+
+#ifdef __KLIBC__
+
+# define INCL_DOS
+# include <os2.h>
+
+static int
+klibc_fcntl (int fd, int action, /* arg */...)
+{
+ va_list arg_ptr;
+ int arg;
+ struct stat sbuf;
+ int result = -1;
+
+ va_start (arg_ptr, action);
+ arg = va_arg (arg_ptr, int);
+ result = fcntl (fd, action, arg);
+ /* EPERM for F_DUPFD, ENOTSUP for others */
+ if (result == -1 && (errno == EPERM || errno == ENOTSUP)
+ && !fstat (fd, &sbuf) && S_ISDIR (sbuf.st_mode))
+ {
+ ULONG ulMode;
+
+ switch (action)
+ {
+ case F_DUPFD:
+ /* Find available fd */
+ while (fcntl (arg, F_GETFL) != -1 || errno != EBADF)
+ arg++;
+
+ result = dup2 (fd, arg);
+ break;
+
+ /* Using underlying APIs is right ? */
+ case F_GETFD:
+ if (DosQueryFHState (fd, &ulMode))
+ break;
+
+ result = (ulMode & OPEN_FLAGS_NOINHERIT) ? FD_CLOEXEC : 0;
+ break;
+
+ case F_SETFD:
+ if (arg & ~FD_CLOEXEC)
+ break;
+
+ if (DosQueryFHState (fd, &ulMode))
+ break;
+
+ if (arg & FD_CLOEXEC)
+ ulMode |= OPEN_FLAGS_NOINHERIT;
+ else
+ ulMode &= ~OPEN_FLAGS_NOINHERIT;
+
+ /* Filter supported flags. */
+ ulMode &= (OPEN_FLAGS_WRITE_THROUGH | OPEN_FLAGS_FAIL_ON_ERROR
+ | OPEN_FLAGS_NO_CACHE | OPEN_FLAGS_NOINHERIT);
+
+ if (DosSetFHState (fd, ulMode))
+ break;
+
+ result = 0;
+ break;
+
+ case F_GETFL:
+ result = 0;
+ break;
+
+ case F_SETFL:
+ if (arg != 0)
+ break;
+
+ result = 0;
+ break;
+
+ default :
+ errno = EINVAL;
+ break;
+ }
+ }
+
+ va_end (arg_ptr);
+
+ return result;
+}
+
+# define fcntl klibc_fcntl
+#endif
+
+/* Perform the specified ACTION on the file descriptor FD, possibly
+ using the argument ARG further described below. This replacement
+ handles the following actions, and forwards all others on to the
+ native fcntl. An unrecognized ACTION returns -1 with errno set to
+ EINVAL.
+
+ F_DUPFD - duplicate FD, with int ARG being the minimum target fd.
+ If successful, return the duplicate, which will be inheritable;
+ otherwise return -1 and set errno.
+
+ F_DUPFD_CLOEXEC - duplicate FD, with int ARG being the minimum
+ target fd. If successful, return the duplicate, which will not be
+ inheritable; otherwise return -1 and set errno.
+
+ F_GETFD - ARG need not be present. If successful, return a
+ non-negative value containing the descriptor flags of FD (only
+ FD_CLOEXEC is portable, but other flags may be present); otherwise
+ return -1 and set errno. */
+
+int
+rpl_fcntl (int fd, int action, /* arg */...)
+{
+ va_list arg;
+ int result = -1;
+ va_start (arg, action);
+ switch (action)
+ {
+
+#if !HAVE_FCNTL
+ case F_DUPFD:
+ {
+ int target = va_arg (arg, int);
+ result = dupfd (fd, target, 0);
+ break;
+ }
+#elif FCNTL_DUPFD_BUGGY || REPLACE_FCHDIR
+ case F_DUPFD:
+ {
+ int target = va_arg (arg, int);
+ /* Detect invalid target; needed for cygwin 1.5.x. */
+ if (target < 0 || getdtablesize () <= target)
+ errno = EINVAL;
+ else
+ {
+ /* Haiku alpha 2 loses fd flags on original. */
+ int flags = fcntl (fd, F_GETFD);
+ if (flags < 0)
+ {
+ result = -1;
+ break;
+ }
+ result = fcntl (fd, action, target);
+ if (0 <= result && fcntl (fd, F_SETFD, flags) == -1)
+ {
+ int saved_errno = errno;
+ close (result);
+ result = -1;
+ errno = saved_errno;
+ }
+# if REPLACE_FCHDIR
+ if (0 <= result)
+ result = _gl_register_dup (fd, result);
+# endif
+ }
+ break;
+ } /* F_DUPFD */
+#endif /* FCNTL_DUPFD_BUGGY || REPLACE_FCHDIR */
+
+ case F_DUPFD_CLOEXEC:
+ {
+ int target = va_arg (arg, int);
+
+#if !HAVE_FCNTL
+ result = dupfd (fd, target, O_CLOEXEC);
+ break;
+#else /* HAVE_FCNTL */
+ /* Try the system call first, if the headers claim it exists
+ (that is, if GNULIB_defined_F_DUPFD_CLOEXEC is 0), since we
+ may be running with a glibc that has the macro but with an
+ older kernel that does not support it. Cache the
+ information on whether the system call really works, but
+ avoid caching failure if the corresponding F_DUPFD fails
+ for any reason. 0 = unknown, 1 = yes, -1 = no. */
+ static int have_dupfd_cloexec = GNULIB_defined_F_DUPFD_CLOEXEC ? -1 : 0;
+ if (0 <= have_dupfd_cloexec)
+ {
+ result = fcntl (fd, action, target);
+ if (0 <= result || errno != EINVAL)
+ {
+ have_dupfd_cloexec = 1;
+# if REPLACE_FCHDIR
+ if (0 <= result)
+ result = _gl_register_dup (fd, result);
+# endif
+ }
+ else
+ {
+ result = rpl_fcntl (fd, F_DUPFD, target);
+ if (result < 0)
+ break;
+ have_dupfd_cloexec = -1;
+ }
+ }
+ else
+ result = rpl_fcntl (fd, F_DUPFD, target);
+ if (0 <= result && have_dupfd_cloexec == -1)
+ {
+ int flags = fcntl (result, F_GETFD);
+ if (flags < 0 || fcntl (result, F_SETFD, flags | FD_CLOEXEC) == -1)
+ {
+ int saved_errno = errno;
+ close (result);
+ errno = saved_errno;
+ result = -1;
+ }
+ }
+ break;
+#endif /* HAVE_FCNTL */
+ } /* F_DUPFD_CLOEXEC */
+
+#if !HAVE_FCNTL
+ case F_GETFD:
+ {
+# if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+ HANDLE handle = (HANDLE) _get_osfhandle (fd);
+ DWORD flags;
+ if (handle == INVALID_HANDLE_VALUE
+ || GetHandleInformation (handle, &flags) == 0)
+ errno = EBADF;
+ else
+ result = (flags & HANDLE_FLAG_INHERIT) ? 0 : FD_CLOEXEC;
+# else /* !W32 */
+ /* Use dup2 to reject invalid file descriptors. No way to
+ access this information, so punt. */
+ if (0 <= dup2 (fd, fd))
+ result = 0;
+# endif /* !W32 */
+ break;
+ } /* F_GETFD */
+#endif /* !HAVE_FCNTL */
+
+ /* Implementing F_SETFD on mingw is not trivial - there is no
+ API for changing the O_NOINHERIT bit on an fd, and merely
+ changing the HANDLE_FLAG_INHERIT bit on the underlying handle
+ can lead to odd state. It may be possible by duplicating the
+ handle, using _open_osfhandle with the right flags, then
+ using dup2 to move the duplicate onto the original, but that
+ is not supported for now. */
+
+ default:
+ {
+#if HAVE_FCNTL
+ void *p = va_arg (arg, void *);
+ result = fcntl (fd, action, p);
+#else
+ errno = EINVAL;
+#endif
+ break;
+ }
+ }
+ va_end (arg);
+ return result;
+}
diff --git a/lib/fcntl.in.h b/lib/fcntl.in.h
new file mode 100644
index 0000000..b943973
--- /dev/null
+++ b/lib/fcntl.in.h
@@ -0,0 +1,363 @@
+/* Like <fcntl.h>, but with non-working flags defined to 0.
+
+ Copyright (C) 2006-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* written by Paul Eggert */
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+#if defined __need_system_fcntl_h
+/* Special invocation convention. */
+
+/* Needed before <sys/stat.h>.
+ May also define off_t to a 64-bit type on native Windows. */
+#include <sys/types.h>
+/* On some systems other than glibc, <sys/stat.h> is a prerequisite of
+ <fcntl.h>. On glibc systems, we would like to avoid namespace pollution.
+ But on glibc systems, <fcntl.h> includes <sys/stat.h> inside an
+ extern "C" { ... } block, which leads to errors in C++ mode with the
+ overridden <sys/stat.h> from gnulib. These errors are known to be gone
+ with g++ version >= 4.3. */
+#if !(defined __GLIBC__ || defined __UCLIBC__) || (defined __cplusplus && defined GNULIB_NAMESPACE && (defined __ICC || !(__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))))
+# include <sys/stat.h>
+#endif
+#@INCLUDE_NEXT@ @NEXT_FCNTL_H@
+
+#else
+/* Normal invocation convention. */
+
+#ifndef _@GUARD_PREFIX@_FCNTL_H
+
+/* Needed before <sys/stat.h>.
+ May also define off_t to a 64-bit type on native Windows. */
+#include <sys/types.h>
+/* On some systems other than glibc, <sys/stat.h> is a prerequisite of
+ <fcntl.h>. On glibc systems, we would like to avoid namespace pollution.
+ But on glibc systems, <fcntl.h> includes <sys/stat.h> inside an
+ extern "C" { ... } block, which leads to errors in C++ mode with the
+ overridden <sys/stat.h> from gnulib. These errors are known to be gone
+ with g++ version >= 4.3. */
+#if !(defined __GLIBC__ || defined __UCLIBC__) || (defined __cplusplus && defined GNULIB_NAMESPACE && (defined __ICC || !(__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))))
+# include <sys/stat.h>
+#endif
+/* The include_next requires a split double-inclusion guard. */
+#@INCLUDE_NEXT@ @NEXT_FCNTL_H@
+
+#ifndef _@GUARD_PREFIX@_FCNTL_H
+#define _@GUARD_PREFIX@_FCNTL_H
+
+#ifndef __GLIBC__ /* Avoid namespace pollution on glibc systems. */
+# include <unistd.h>
+#endif
+
+/* Native Windows platforms declare open(), creat() in <io.h>. */
+#if (@GNULIB_OPEN@ || defined GNULIB_POSIXCHECK) \
+ && ((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__)
+# include <io.h>
+#endif
+
+
+/* The definitions of _GL_FUNCDECL_RPL etc. are copied here. */
+
+/* The definition of _GL_ARG_NONNULL is copied here. */
+
+/* The definition of _GL_WARN_ON_USE is copied here. */
+
+
+/* Declare overridden functions. */
+
+#if @GNULIB_FCNTL@
+# if @REPLACE_FCNTL@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef fcntl
+# define fcntl rpl_fcntl
+# endif
+_GL_FUNCDECL_RPL (fcntl, int, (int fd, int action, ...));
+_GL_CXXALIAS_RPL (fcntl, int, (int fd, int action, ...));
+# else
+# if !@HAVE_FCNTL@
+_GL_FUNCDECL_SYS (fcntl, int, (int fd, int action, ...));
+# endif
+_GL_CXXALIAS_SYS (fcntl, int, (int fd, int action, ...));
+# endif
+_GL_CXXALIASWARN (fcntl);
+#elif defined GNULIB_POSIXCHECK
+# undef fcntl
+# if HAVE_RAW_DECL_FCNTL
+_GL_WARN_ON_USE (fcntl, "fcntl is not always POSIX compliant - "
+ "use gnulib module fcntl for portability");
+# endif
+#endif
+
+#if @GNULIB_OPEN@
+# if @REPLACE_OPEN@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef open
+# define open rpl_open
+# endif
+_GL_FUNCDECL_RPL (open, int, (const char *filename, int flags, ...)
+ _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (open, int, (const char *filename, int flags, ...));
+# else
+_GL_CXXALIAS_SYS (open, int, (const char *filename, int flags, ...));
+# endif
+/* On HP-UX 11, in C++ mode, open() is defined as an inline function with a
+ default argument. _GL_CXXALIASWARN does not work in this case. */
+# if !defined __hpux
+_GL_CXXALIASWARN (open);
+# endif
+#elif defined GNULIB_POSIXCHECK
+# undef open
+/* Assume open is always declared. */
+_GL_WARN_ON_USE (open, "open is not always POSIX compliant - "
+ "use gnulib module open for portability");
+#endif
+
+#if @GNULIB_OPENAT@
+# if @REPLACE_OPENAT@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef openat
+# define openat rpl_openat
+# endif
+_GL_FUNCDECL_RPL (openat, int,
+ (int fd, char const *file, int flags, /* mode_t mode */ ...)
+ _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_RPL (openat, int,
+ (int fd, char const *file, int flags, /* mode_t mode */ ...));
+# else
+# if !@HAVE_OPENAT@
+_GL_FUNCDECL_SYS (openat, int,
+ (int fd, char const *file, int flags, /* mode_t mode */ ...)
+ _GL_ARG_NONNULL ((2)));
+# endif
+_GL_CXXALIAS_SYS (openat, int,
+ (int fd, char const *file, int flags, /* mode_t mode */ ...));
+# endif
+_GL_CXXALIASWARN (openat);
+#elif defined GNULIB_POSIXCHECK
+# undef openat
+# if HAVE_RAW_DECL_OPENAT
+_GL_WARN_ON_USE (openat, "openat is not portable - "
+ "use gnulib module openat for portability");
+# endif
+#endif
+
+
+/* Fix up the FD_* macros, only known to be missing on mingw. */
+
+#ifndef FD_CLOEXEC
+# define FD_CLOEXEC 1
+#endif
+
+/* Fix up the supported F_* macros. Intentionally leave other F_*
+ macros undefined. Only known to be missing on mingw. */
+
+#ifndef F_DUPFD_CLOEXEC
+# define F_DUPFD_CLOEXEC 0x40000000
+/* Witness variable: 1 if gnulib defined F_DUPFD_CLOEXEC, 0 otherwise. */
+# define GNULIB_defined_F_DUPFD_CLOEXEC 1
+#else
+# define GNULIB_defined_F_DUPFD_CLOEXEC 0
+#endif
+
+#ifndef F_DUPFD
+# define F_DUPFD 1
+#endif
+
+#ifndef F_GETFD
+# define F_GETFD 2
+#endif
+
+/* Fix up the O_* macros. */
+
+/* AIX 7.1 with XL C 12.1 defines O_CLOEXEC, O_NOFOLLOW, and O_TTY_INIT
+ to values outside 'int' range, so omit these misdefinitions.
+ But avoid namespace pollution on non-AIX systems. */
+#ifdef _AIX
+# include <limits.h>
+# if defined O_CLOEXEC && ! (INT_MIN <= O_CLOEXEC && O_CLOEXEC <= INT_MAX)
+# undef O_CLOEXEC
+# endif
+# if defined O_NOFOLLOW && ! (INT_MIN <= O_NOFOLLOW && O_NOFOLLOW <= INT_MAX)
+# undef O_NOFOLLOW
+# endif
+# if defined O_TTY_INIT && ! (INT_MIN <= O_TTY_INIT && O_TTY_INIT <= INT_MAX)
+# undef O_TTY_INIT
+# endif
+#endif
+
+#if !defined O_DIRECT && defined O_DIRECTIO
+/* Tru64 spells it 'O_DIRECTIO'. */
+# define O_DIRECT O_DIRECTIO
+#endif
+
+#if !defined O_CLOEXEC && defined O_NOINHERIT
+/* Mingw spells it 'O_NOINHERIT'. */
+# define O_CLOEXEC O_NOINHERIT
+#endif
+
+#ifndef O_CLOEXEC
+# define O_CLOEXEC 0
+#endif
+
+#ifndef O_DIRECT
+# define O_DIRECT 0
+#endif
+
+#ifndef O_DIRECTORY
+# define O_DIRECTORY 0
+#endif
+
+#ifndef O_DSYNC
+# define O_DSYNC 0
+#endif
+
+#ifndef O_EXEC
+# define O_EXEC O_RDONLY /* This is often close enough in older systems. */
+#endif
+
+#ifndef O_IGNORE_CTTY
+# define O_IGNORE_CTTY 0
+#endif
+
+#ifndef O_NDELAY
+# define O_NDELAY 0
+#endif
+
+#ifndef O_NOATIME
+# define O_NOATIME 0
+#endif
+
+#ifndef O_NONBLOCK
+# define O_NONBLOCK O_NDELAY
+#endif
+
+/* If the gnulib module 'nonblocking' is in use, guarantee a working non-zero
+ value of O_NONBLOCK. Otherwise, O_NONBLOCK is defined (above) to O_NDELAY
+ or to 0 as fallback. */
+#if @GNULIB_NONBLOCKING@
+# if O_NONBLOCK
+# define GNULIB_defined_O_NONBLOCK 0
+# else
+# define GNULIB_defined_O_NONBLOCK 1
+# undef O_NONBLOCK
+# define O_NONBLOCK 0x40000000
+# endif
+#endif
+
+#ifndef O_NOCTTY
+# define O_NOCTTY 0
+#endif
+
+#ifndef O_NOFOLLOW
+# define O_NOFOLLOW 0
+#endif
+
+#ifndef O_NOLINK
+# define O_NOLINK 0
+#endif
+
+#ifndef O_NOLINKS
+# define O_NOLINKS 0
+#endif
+
+#ifndef O_NOTRANS
+# define O_NOTRANS 0
+#endif
+
+#ifndef O_RSYNC
+# define O_RSYNC 0
+#endif
+
+#ifndef O_SEARCH
+# define O_SEARCH O_RDONLY /* This is often close enough in older systems. */
+#endif
+
+#ifndef O_SYNC
+# define O_SYNC 0
+#endif
+
+#ifndef O_TTY_INIT
+# define O_TTY_INIT 0
+#endif
+
+#if ~O_ACCMODE & (O_RDONLY | O_WRONLY | O_RDWR | O_EXEC | O_SEARCH)
+# undef O_ACCMODE
+# define O_ACCMODE (O_RDONLY | O_WRONLY | O_RDWR | O_EXEC | O_SEARCH)
+#endif
+
+/* For systems that distinguish between text and binary I/O.
+ O_BINARY is usually declared in fcntl.h */
+#if !defined O_BINARY && defined _O_BINARY
+ /* For MSC-compatible compilers. */
+# define O_BINARY _O_BINARY
+# define O_TEXT _O_TEXT
+#endif
+
+#if defined __BEOS__ || defined __HAIKU__
+ /* BeOS 5 and Haiku have O_BINARY and O_TEXT, but they have no effect. */
+# undef O_BINARY
+# undef O_TEXT
+#endif
+
+#ifndef O_BINARY
+# define O_BINARY 0
+# define O_TEXT 0
+#endif
+
+/* Fix up the AT_* macros. */
+
+/* Work around a bug in Solaris 9 and 10: AT_FDCWD is positive. Its
+ value exceeds INT_MAX, so its use as an int doesn't conform to the
+ C standard, and GCC and Sun C complain in some cases. If the bug
+ is present, undef AT_FDCWD here, so it can be redefined below. */
+#if 0 < AT_FDCWD && AT_FDCWD == 0xffd19553
+# undef AT_FDCWD
+#endif
+
+/* Use the same bit pattern as Solaris 9, but with the proper
+ signedness. The bit pattern is important, in case this actually is
+ Solaris with the above workaround. */
+#ifndef AT_FDCWD
+# define AT_FDCWD (-3041965)
+#endif
+
+/* Use the same values as Solaris 9. This shouldn't matter, but
+ there's no real reason to differ. */
+#ifndef AT_SYMLINK_NOFOLLOW
+# define AT_SYMLINK_NOFOLLOW 4096
+#endif
+
+#ifndef AT_REMOVEDIR
+# define AT_REMOVEDIR 1
+#endif
+
+/* Solaris 9 lacks these two, so just pick unique values. */
+#ifndef AT_SYMLINK_FOLLOW
+# define AT_SYMLINK_FOLLOW 2
+#endif
+
+#ifndef AT_EACCESS
+# define AT_EACCESS 4
+#endif
+
+
+#endif /* _@GUARD_PREFIX@_FCNTL_H */
+#endif /* _@GUARD_PREFIX@_FCNTL_H */
+#endif
diff --git a/lib/fcntl_.h b/lib/fcntl_.h
deleted file mode 100644
index e16ad54..0000000
--- a/lib/fcntl_.h
+++ /dev/null
@@ -1,116 +0,0 @@
-/* Like <fcntl.h>, but with non-working flags defined to 0.
-
- Copyright (C) 2006 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-/* written by Paul Eggert */
-
-#ifndef _GL_FCNTL_H
-#define _GL_FCNTL_H
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <unistd.h>
-#include @ABSOLUTE_FCNTL_H@
-
-
-/* Declare overridden functions. */
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifdef FCHDIR_REPLACEMENT
-# define open rpl_open
-extern int open (const char *, int, ...);
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-
-
-/* Fix up the O_* macros. */
-
-#if !defined O_DIRECT && defined O_DIRECTIO
-/* Tru64 spells it `O_DIRECTIO'. */
-# define O_DIRECT O_DIRECTIO
-#endif
-
-#ifndef O_DIRECT
-# define O_DIRECT 0
-#endif
-
-#ifndef O_DIRECTORY
-# define O_DIRECTORY 0
-#endif
-
-#ifndef O_DSYNC
-# define O_DSYNC 0
-#endif
-
-#ifndef O_NDELAY
-# define O_NDELAY 0
-#endif
-
-#ifndef O_NOATIME
-# define O_NOATIME 0
-#endif
-
-#ifndef O_NONBLOCK
-# define O_NONBLOCK O_NDELAY
-#endif
-
-#ifndef O_NOCTTY
-# define O_NOCTTY 0
-#endif
-
-#ifndef O_NOFOLLOW
-# define O_NOFOLLOW 0
-#endif
-
-#ifndef O_NOLINKS
-# define O_NOLINKS 0
-#endif
-
-#ifndef O_RSYNC
-# define O_RSYNC 0
-#endif
-
-#ifndef O_SYNC
-# define O_SYNC 0
-#endif
-
-/* For systems that distinguish between text and binary I/O.
- O_BINARY is usually declared in fcntl.h */
-#if !defined O_BINARY && defined _O_BINARY
- /* For MSC-compatible compilers. */
-# define O_BINARY _O_BINARY
-# define O_TEXT _O_TEXT
-#endif
-
-#ifdef __BEOS__
- /* BeOS 5 has O_BINARY and O_TEXT, but they have no effect. */
-# undef O_BINARY
-# undef O_TEXT
-#endif
-
-#ifndef O_BINARY
-# define O_BINARY 0
-# define O_TEXT 0
-#endif
-
-#endif
diff --git a/lib/fd-hook.c b/lib/fd-hook.c
new file mode 100644
index 0000000..8676c6b
--- /dev/null
+++ b/lib/fd-hook.c
@@ -0,0 +1,116 @@
+/* Hook for making making file descriptor functions close(), ioctl() extensible.
+ Copyright (C) 2009-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2009.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include "fd-hook.h"
+
+#include <stdlib.h>
+
+/* Currently, this entire code is only needed for the handling of sockets
+ on native Windows platforms. */
+#if WINDOWS_SOCKETS
+
+/* The first and last link in the doubly linked list.
+ Initially the list is empty. */
+static struct fd_hook anchor = { &anchor, &anchor, NULL, NULL };
+
+int
+execute_close_hooks (const struct fd_hook *remaining_list, gl_close_fn primary,
+ int fd)
+{
+ if (remaining_list == &anchor)
+ /* End of list reached. */
+ return primary (fd);
+ else
+ return remaining_list->private_close_fn (remaining_list->private_next,
+ primary, fd);
+}
+
+int
+execute_all_close_hooks (gl_close_fn primary, int fd)
+{
+ return execute_close_hooks (anchor.private_next, primary, fd);
+}
+
+int
+execute_ioctl_hooks (const struct fd_hook *remaining_list, gl_ioctl_fn primary,
+ int fd, int request, void *arg)
+{
+ if (remaining_list == &anchor)
+ /* End of list reached. */
+ return primary (fd, request, arg);
+ else
+ return remaining_list->private_ioctl_fn (remaining_list->private_next,
+ primary, fd, request, arg);
+}
+
+int
+execute_all_ioctl_hooks (gl_ioctl_fn primary,
+ int fd, int request, void *arg)
+{
+ return execute_ioctl_hooks (anchor.private_next, primary, fd, request, arg);
+}
+
+void
+register_fd_hook (close_hook_fn close_hook, ioctl_hook_fn ioctl_hook, struct fd_hook *link)
+{
+ if (close_hook == NULL)
+ close_hook = execute_close_hooks;
+ if (ioctl_hook == NULL)
+ ioctl_hook = execute_ioctl_hooks;
+
+ if (link->private_next == NULL && link->private_prev == NULL)
+ {
+ /* Add the link to the doubly linked list. */
+ link->private_next = anchor.private_next;
+ link->private_prev = &anchor;
+ link->private_close_fn = close_hook;
+ link->private_ioctl_fn = ioctl_hook;
+ anchor.private_next->private_prev = link;
+ anchor.private_next = link;
+ }
+ else
+ {
+ /* The link is already in use. */
+ if (link->private_close_fn != close_hook
+ || link->private_ioctl_fn != ioctl_hook)
+ abort ();
+ }
+}
+
+void
+unregister_fd_hook (struct fd_hook *link)
+{
+ struct fd_hook *next = link->private_next;
+ struct fd_hook *prev = link->private_prev;
+
+ if (next != NULL && prev != NULL)
+ {
+ /* The link is in use. Remove it from the doubly linked list. */
+ prev->private_next = next;
+ next->private_prev = prev;
+ /* Clear the link, to mark it unused. */
+ link->private_next = NULL;
+ link->private_prev = NULL;
+ link->private_close_fn = NULL;
+ link->private_ioctl_fn = NULL;
+ }
+}
+
+#endif
diff --git a/lib/fd-hook.h b/lib/fd-hook.h
new file mode 100644
index 0000000..9568d07
--- /dev/null
+++ b/lib/fd-hook.h
@@ -0,0 +1,119 @@
+/* Hook for making making file descriptor functions close(), ioctl() extensible.
+ Copyright (C) 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+
+#ifndef FD_HOOK_H
+#define FD_HOOK_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/* Currently, this entire code is only needed for the handling of sockets
+ on native Windows platforms. */
+#if WINDOWS_SOCKETS
+
+
+/* Type of function that closes FD. */
+typedef int (*gl_close_fn) (int fd);
+
+/* Type of function that applies a control request to FD. */
+typedef int (*gl_ioctl_fn) (int fd, int request, void *arg);
+
+/* An element of the list of file descriptor hooks.
+ In CLOS (Common Lisp Object System) speak, it consists of an "around"
+ method for the close() function and an "around" method for the ioctl()
+ function.
+ The fields of this structure are considered private. */
+struct fd_hook
+{
+ /* Doubly linked list. */
+ struct fd_hook *private_next;
+ struct fd_hook *private_prev;
+ /* Function that treats the types of FD that it knows about and calls
+ execute_close_hooks (REMAINING_LIST, PRIMARY, FD) as a fallback. */
+ int (*private_close_fn) (const struct fd_hook *remaining_list,
+ gl_close_fn primary,
+ int fd);
+ /* Function that treats the types of FD that it knows about and calls
+ execute_ioctl_hooks (REMAINING_LIST, PRIMARY, FD, REQUEST, ARG) as a
+ fallback. */
+ int (*private_ioctl_fn) (const struct fd_hook *remaining_list,
+ gl_ioctl_fn primary,
+ int fd, int request, void *arg);
+};
+
+/* This type of function closes FD, applying special knowledge for the FD
+ types it knows about, and calls
+ execute_close_hooks (REMAINING_LIST, PRIMARY, FD)
+ for the other FD types.
+ In CLOS speak, REMAINING_LIST is the remaining list of "around" methods,
+ and PRIMARY is the "primary" method for close(). */
+typedef int (*close_hook_fn) (const struct fd_hook *remaining_list,
+ gl_close_fn primary,
+ int fd);
+
+/* Execute the close hooks in REMAINING_LIST, with PRIMARY as "primary" method.
+ Return 0 or -1, like close() would do. */
+extern int execute_close_hooks (const struct fd_hook *remaining_list,
+ gl_close_fn primary,
+ int fd);
+
+/* Execute all close hooks, with PRIMARY as "primary" method.
+ Return 0 or -1, like close() would do. */
+extern int execute_all_close_hooks (gl_close_fn primary, int fd);
+
+/* This type of function applies a control request to FD, applying special
+ knowledge for the FD types it knows about, and calls
+ execute_ioctl_hooks (REMAINING_LIST, PRIMARY, FD, REQUEST, ARG)
+ for the other FD types.
+ In CLOS speak, REMAINING_LIST is the remaining list of "around" methods,
+ and PRIMARY is the "primary" method for ioctl(). */
+typedef int (*ioctl_hook_fn) (const struct fd_hook *remaining_list,
+ gl_ioctl_fn primary,
+ int fd, int request, void *arg);
+
+/* Execute the ioctl hooks in REMAINING_LIST, with PRIMARY as "primary" method.
+ Return 0 or -1, like ioctl() would do. */
+extern int execute_ioctl_hooks (const struct fd_hook *remaining_list,
+ gl_ioctl_fn primary,
+ int fd, int request, void *arg);
+
+/* Execute all ioctl hooks, with PRIMARY as "primary" method.
+ Return 0 or -1, like ioctl() would do. */
+extern int execute_all_ioctl_hooks (gl_ioctl_fn primary,
+ int fd, int request, void *arg);
+
+/* Add a function pair to the list of file descriptor hooks.
+ CLOSE_HOOK and IOCTL_HOOK may be NULL, indicating no change.
+ The LINK variable points to a piece of memory which is guaranteed to be
+ accessible until the corresponding call to unregister_fd_hook. */
+extern void register_fd_hook (close_hook_fn close_hook, ioctl_hook_fn ioctl_hook,
+ struct fd_hook *link);
+
+/* Removes a hook from the list of file descriptor hooks. */
+extern void unregister_fd_hook (struct fd_hook *link);
+
+
+#endif
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* FD_HOOK_H */
diff --git a/lib/fd-reopen.c b/lib/fd-reopen.c
index 99376e3..1c3a0f6 100644
--- a/lib/fd-reopen.c
+++ b/lib/fd-reopen.c
@@ -1,11 +1,11 @@
/* Invoke open, but return either a desired file descriptor or -1.
- Copyright (C) 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2005-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
@@ -27,20 +26,18 @@
#include <unistd.h>
/* Open a file to a particular file descriptor. This is like standard
- `open', except it always returns DESIRED_FD if successful. */
+ 'open', except it always returns DESIRED_FD if successful. */
int
fd_reopen (int desired_fd, char const *file, int flags, mode_t mode)
{
- int fd;
+ int fd = open (file, flags, mode);
- close (desired_fd);
- fd = open (file, flags, mode);
if (fd == desired_fd || fd < 0)
return fd;
else
{
- int fd2 = fcntl (fd, F_DUPFD, desired_fd);
+ int fd2 = dup2 (fd, desired_fd);
int saved_errno = errno;
close (fd);
errno = saved_errno;
diff --git a/lib/fd-reopen.h b/lib/fd-reopen.h
index af4bcfe..bcd6bcc 100644
--- a/lib/fd-reopen.h
+++ b/lib/fd-reopen.h
@@ -1,11 +1,11 @@
/* Invoke open, but return either a desired file descriptor or -1.
- Copyright (C) 2005 Free Software Foundation, Inc.
+ Copyright (C) 2005-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
diff --git a/lib/fd-safer-flag.c b/lib/fd-safer-flag.c
new file mode 100644
index 0000000..4b86583
--- /dev/null
+++ b/lib/fd-safer-flag.c
@@ -0,0 +1,52 @@
+/* Adjust a file descriptor result so that it avoids clobbering
+ STD{IN,OUT,ERR}_FILENO, with specific flags.
+
+ Copyright (C) 2005-2006, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Paul Eggert and Eric Blake. */
+
+#include <config.h>
+
+/* Specification. */
+#include "unistd-safer.h"
+
+#include <errno.h>
+#include <unistd.h>
+
+/* Return FD, unless FD would be a copy of standard input, output, or
+ error; in that case, return a duplicate of FD, closing FD. If FLAG
+ contains O_CLOEXEC, the returned FD will have close-on-exec
+ semantics. On failure to duplicate, close FD, set errno, and
+ return -1. Preserve errno if FD is negative, so that the caller
+ can always inspect errno when the returned value is negative.
+
+ This function is usefully wrapped around functions that return file
+ descriptors, e.g., fd_safer_flag (open ("file", O_RDONLY | flag), flag). */
+
+int
+fd_safer_flag (int fd, int flag)
+{
+ if (STDIN_FILENO <= fd && fd <= STDERR_FILENO)
+ {
+ int f = dup_safer_flag (fd, flag);
+ int e = errno;
+ close (fd);
+ errno = e;
+ fd = f;
+ }
+
+ return fd;
+}
diff --git a/lib/fd-safer.c b/lib/fd-safer.c
index 256bfa4..8a6bee2 100644
--- a/lib/fd-safer.c
+++ b/lib/fd-safer.c
@@ -1,11 +1,11 @@
/* Return a safer copy of a file descriptor.
- Copyright (C) 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2005-2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
@@ -23,14 +22,7 @@
#include "unistd-safer.h"
#include <errno.h>
-
#include <unistd.h>
-#ifndef STDIN_FILENO
-# define STDIN_FILENO 0
-#endif
-#ifndef STDERR_FILENO
-# define STDERR_FILENO 2
-#endif
/* Return FD, unless FD would be a copy of standard input, output, or
error; in that case, return a duplicate of FD, closing FD. On
diff --git a/lib/fdatasync.c b/lib/fdatasync.c
new file mode 100644
index 0000000..3351a0a
--- /dev/null
+++ b/lib/fdatasync.c
@@ -0,0 +1,27 @@
+/* Emulate fdatasync on platforms that lack it.
+
+ Copyright (C) 2011-2016 Free Software Foundation, Inc.
+
+ This library 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 library 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+#include <unistd.h>
+
+int
+fdatasync (int fd)
+{
+ /* This does more work than strictly necessary, but is the best we
+ can do portably. */
+ return fsync (fd);
+}
diff --git a/lib/fdopen.c b/lib/fdopen.c
new file mode 100644
index 0000000..61fbfdf
--- /dev/null
+++ b/lib/fdopen.c
@@ -0,0 +1,69 @@
+/* Open a stream with a given file descriptor.
+ Copyright (C) 2011-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <stdio.h>
+
+#include <errno.h>
+
+#if HAVE_MSVC_INVALID_PARAMETER_HANDLER
+# include "msvc-inval.h"
+#endif
+
+#undef fdopen
+
+#if HAVE_MSVC_INVALID_PARAMETER_HANDLER
+static FILE *
+fdopen_nothrow (int fd, const char *mode)
+{
+ FILE *result;
+
+ TRY_MSVC_INVAL
+ {
+ result = fdopen (fd, mode);
+ }
+ CATCH_MSVC_INVAL
+ {
+ result = NULL;
+ }
+ DONE_MSVC_INVAL;
+
+ return result;
+}
+#else
+# define fdopen_nothrow fdopen
+#endif
+
+FILE *
+rpl_fdopen (int fd, const char *mode)
+{
+ int saved_errno = errno;
+ FILE *fp;
+
+ errno = 0;
+ fp = fdopen_nothrow (fd, mode);
+ if (fp == NULL)
+ {
+ if (errno == 0)
+ errno = EBADF;
+ }
+ else
+ errno = saved_errno;
+
+ return fp;
+}
diff --git a/lib/fdopendir.c b/lib/fdopendir.c
new file mode 100644
index 0000000..c1f4dcb
--- /dev/null
+++ b/lib/fdopendir.c
@@ -0,0 +1,249 @@
+/* provide a replacement fdopendir function
+ Copyright (C) 2004-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* written by Jim Meyering */
+
+#include <config.h>
+
+#include <dirent.h>
+
+#include <stdlib.h>
+#include <unistd.h>
+
+#if !HAVE_FDOPENDIR
+
+# include "openat.h"
+# include "openat-priv.h"
+# include "save-cwd.h"
+
+# if GNULIB_DIRENT_SAFER
+# include "dirent--.h"
+# endif
+
+# ifndef REPLACE_FCHDIR
+# define REPLACE_FCHDIR 0
+# endif
+
+static DIR *fdopendir_with_dup (int, int, struct saved_cwd const *);
+static DIR *fd_clone_opendir (int, struct saved_cwd const *);
+
+/* Replacement for POSIX fdopendir.
+
+ First, try to simulate it via opendir ("/proc/self/fd/..."). Failing
+ that, simulate it by using fchdir metadata, or by doing
+ save_cwd/fchdir/opendir(".")/restore_cwd.
+ If either the save_cwd or the restore_cwd fails (relatively unlikely),
+ then give a diagnostic and exit nonzero.
+
+ If successful, the resulting stream is based on FD in
+ implementations where streams are based on file descriptors and in
+ applications where no other thread or signal handler allocates or
+ frees file descriptors. In other cases, consult dirfd on the result
+ to find out whether FD is still being used.
+
+ Otherwise, this function works just like POSIX fdopendir.
+
+ W A R N I N G:
+
+ Unlike other fd-related functions, this one places constraints on FD.
+ If this function returns successfully, FD is under control of the
+ dirent.h system, and the caller should not close or modify the state of
+ FD other than by the dirent.h functions. */
+# ifdef __KLIBC__
+# include <InnoTekLIBC/backend.h>
+
+DIR *
+fdopendir (int fd)
+{
+ char path[_MAX_PATH];
+ DIR *dirp;
+
+ /* Get a path from fd */
+ if (__libc_Back_ioFHToPath (fd, path, sizeof (path)))
+ return NULL;
+
+ dirp = opendir (path);
+ if (!dirp)
+ return NULL;
+
+ /* Unregister fd registered by opendir() */
+ _gl_unregister_dirp_fd (dirfd (dirp));
+
+ /* Register our fd */
+ if (_gl_register_dirp_fd (fd, dirp))
+ {
+ int saved_errno = errno;
+
+ closedir (dirp);
+
+ errno = saved_errno;
+
+ dirp = NULL;
+ }
+
+ return dirp;
+}
+# else
+DIR *
+fdopendir (int fd)
+{
+ DIR *dir = fdopendir_with_dup (fd, -1, NULL);
+
+ if (! REPLACE_FCHDIR && ! dir)
+ {
+ int saved_errno = errno;
+ if (EXPECTED_ERRNO (saved_errno))
+ {
+ struct saved_cwd cwd;
+ if (save_cwd (&cwd) != 0)
+ openat_save_fail (errno);
+ dir = fdopendir_with_dup (fd, -1, &cwd);
+ saved_errno = errno;
+ free_cwd (&cwd);
+ errno = saved_errno;
+ }
+ }
+
+ return dir;
+}
+# endif
+
+/* Like fdopendir, except that if OLDER_DUPFD is not -1, it is known
+ to be a dup of FD which is less than FD - 1 and which will be
+ closed by the caller and not otherwise used by the caller. This
+ function makes sure that FD is closed and all file descriptors less
+ than FD are open, and then calls fd_clone_opendir on a dup of FD.
+ That way, barring race conditions, fd_clone_opendir returns a
+ stream whose file descriptor is FD.
+
+ If REPLACE_FCHDIR or CWD is null, use opendir ("/proc/self/fd/...",
+ falling back on fchdir metadata. Otherwise, CWD is a saved version
+ of the working directory; use fchdir/opendir(".")/restore_cwd(CWD). */
+static DIR *
+fdopendir_with_dup (int fd, int older_dupfd, struct saved_cwd const *cwd)
+{
+ int dupfd = dup (fd);
+ if (dupfd < 0 && errno == EMFILE)
+ dupfd = older_dupfd;
+ if (dupfd < 0)
+ return NULL;
+ else
+ {
+ DIR *dir;
+ int saved_errno;
+ if (dupfd < fd - 1 && dupfd != older_dupfd)
+ {
+ dir = fdopendir_with_dup (fd, dupfd, cwd);
+ saved_errno = errno;
+ }
+ else
+ {
+ close (fd);
+ dir = fd_clone_opendir (dupfd, cwd);
+ saved_errno = errno;
+ if (! dir)
+ {
+ int fd1 = dup (dupfd);
+ if (fd1 != fd)
+ openat_save_fail (fd1 < 0 ? errno : EBADF);
+ }
+ }
+
+ if (dupfd != older_dupfd)
+ close (dupfd);
+ errno = saved_errno;
+ return dir;
+ }
+}
+
+/* Like fdopendir, except the result controls a clone of FD. It is
+ the caller's responsibility both to close FD and (if the result is
+ not null) to closedir the result. */
+static DIR *
+fd_clone_opendir (int fd, struct saved_cwd const *cwd)
+{
+ if (REPLACE_FCHDIR || ! cwd)
+ {
+ DIR *dir = NULL;
+ int saved_errno = EOPNOTSUPP;
+ char buf[OPENAT_BUFFER_SIZE];
+ char *proc_file = openat_proc_name (buf, fd, ".");
+ if (proc_file)
+ {
+ dir = opendir (proc_file);
+ saved_errno = errno;
+ if (proc_file != buf)
+ free (proc_file);
+ }
+# if REPLACE_FCHDIR
+ if (! dir && EXPECTED_ERRNO (saved_errno))
+ {
+ char const *name = _gl_directory_name (fd);
+ DIR *dp = name ? opendir (name) : NULL;
+
+ /* The caller has done an elaborate dance to arrange for opendir to
+ consume just the right file descriptor. If dirfd returns -1,
+ though, we're on a system like mingw where opendir does not
+ consume a file descriptor. Consume it via 'dup' instead. */
+ if (dp && dirfd (dp) < 0)
+ dup (fd);
+
+ return dp;
+ }
+# endif
+ errno = saved_errno;
+ return dir;
+ }
+ else
+ {
+ if (fchdir (fd) != 0)
+ return NULL;
+ else
+ {
+ DIR *dir = opendir (".");
+ int saved_errno = errno;
+ if (restore_cwd (cwd) != 0)
+ openat_restore_fail (errno);
+ errno = saved_errno;
+ return dir;
+ }
+ }
+}
+
+#else /* HAVE_FDOPENDIR */
+
+# include <errno.h>
+# include <sys/stat.h>
+
+# undef fdopendir
+
+/* Like fdopendir, but work around GNU/Hurd bug by validating FD. */
+
+DIR *
+rpl_fdopendir (int fd)
+{
+ struct stat st;
+ if (fstat (fd, &st))
+ return NULL;
+ if (!S_ISDIR (st.st_mode))
+ {
+ errno = ENOTDIR;
+ return NULL;
+ }
+ return fdopendir (fd);
+}
+
+#endif /* HAVE_FDOPENDIR */
diff --git a/lib/fdutimensat.c b/lib/fdutimensat.c
new file mode 100644
index 0000000..b5e22ab
--- /dev/null
+++ b/lib/fdutimensat.c
@@ -0,0 +1,57 @@
+/* Set file access and modification times.
+
+ Copyright (C) 2009-2016 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 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Eric Blake. */
+
+/* derived from a function in utimens.c */
+
+#include <config.h>
+
+#include "utimens.h"
+
+#include <errno.h>
+#include <fcntl.h>
+#include <sys/stat.h>
+
+/* Set the access and modification time stamps of FD (a.k.a. FILE) to be
+ TIMESPEC[0] and TIMESPEC[1], respectively; relative to directory DIR.
+ FD must be either negative -- in which case it is ignored --
+ or a file descriptor that is open on FILE.
+ If FD is nonnegative, then FILE can be NULL, which means
+ use just futimes (or equivalent) instead of utimes (or equivalent),
+ and fail if on an old system without futimes (or equivalent).
+ If TIMESPEC is null, set the time stamps to the current time.
+ ATFLAG is passed to utimensat if FD is negative or futimens was
+ unsupported, which can allow operation on FILE as a symlink.
+ Return 0 on success, -1 (setting errno) on failure. */
+
+int
+fdutimensat (int fd, int dir, char const *file, struct timespec const ts[2],
+ int atflag)
+{
+ int result = 1;
+ if (0 <= fd)
+ result = futimens (fd, ts);
+ if (file && (fd < 0 || (result == -1 && errno == ENOSYS)))
+ result = utimensat (dir, file, ts, atflag);
+ if (result == 1)
+ {
+ errno = EBADF;
+ result = -1;
+ }
+ return result;
+}
diff --git a/lib/fflush.c b/lib/fflush.c
new file mode 100644
index 0000000..2bd7cc9
--- /dev/null
+++ b/lib/fflush.c
@@ -0,0 +1,229 @@
+/* fflush.c -- allow flushing input streams
+ Copyright (C) 2007-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Eric Blake. */
+
+#include <config.h>
+
+/* Specification. */
+#include <stdio.h>
+
+#include <errno.h>
+#include <unistd.h>
+
+#include "freading.h"
+
+#include "stdio-impl.h"
+
+#include "unused-parameter.h"
+
+#undef fflush
+
+
+#if defined _IO_ftrylockfile || __GNU_LIBRARY__ == 1 /* GNU libc, BeOS, Haiku, Linux libc5 */
+
+/* Clear the stream's ungetc buffer, preserving the value of ftello (fp). */
+static void
+clear_ungetc_buffer_preserving_position (FILE *fp)
+{
+ if (fp->_flags & _IO_IN_BACKUP)
+ /* _IO_free_backup_area is a bit complicated. Simply call fseek. */
+ fseeko (fp, 0, SEEK_CUR);
+}
+
+#else
+
+/* Clear the stream's ungetc buffer. May modify the value of ftello (fp). */
+static void
+clear_ungetc_buffer (FILE *fp)
+{
+# if defined __sferror || defined __DragonFly__ || defined __ANDROID__
+ /* FreeBSD, NetBSD, OpenBSD, DragonFly, Mac OS X, Cygwin, Android */
+ if (HASUB (fp))
+ {
+ fp_->_p += fp_->_r;
+ fp_->_r = 0;
+ }
+# elif defined __EMX__ /* emx+gcc */
+ if (fp->_ungetc_count > 0)
+ {
+ fp->_ungetc_count = 0;
+ fp->_rcount = - fp->_rcount;
+ }
+# elif defined _IOERR /* Minix, AIX, HP-UX, IRIX, OSF/1, Solaris, OpenServer, mingw, NonStop Kernel */
+ /* Nothing to do. */
+# else /* other implementations */
+ fseeko (fp, 0, SEEK_CUR);
+# endif
+}
+
+#endif
+
+#if ! (defined _IO_ftrylockfile || __GNU_LIBRARY__ == 1 /* GNU libc, BeOS, Haiku, Linux libc5 */)
+
+# if (defined __sferror || defined __DragonFly__ || defined __ANDROID__) && defined __SNPT
+/* FreeBSD, NetBSD, OpenBSD, DragonFly, Mac OS X, Cygwin, Android */
+
+static int
+disable_seek_optimization (FILE *fp)
+{
+ int saved_flags = fp_->_flags & (__SOPT | __SNPT);
+ fp_->_flags = (fp_->_flags & ~__SOPT) | __SNPT;
+ return saved_flags;
+}
+
+static void
+restore_seek_optimization (FILE *fp, int saved_flags)
+{
+ fp_->_flags = (fp_->_flags & ~(__SOPT | __SNPT)) | saved_flags;
+}
+
+# else
+
+static void
+update_fpos_cache (FILE *fp _GL_UNUSED_PARAMETER,
+ off_t pos _GL_UNUSED_PARAMETER)
+{
+# if defined __sferror || defined __DragonFly__ || defined __ANDROID__
+ /* FreeBSD, NetBSD, OpenBSD, DragonFly, Mac OS X, Cygwin, Android */
+# if defined __CYGWIN__
+ /* fp_->_offset is typed as an integer. */
+ fp_->_offset = pos;
+# else
+ /* fp_->_offset is an fpos_t. */
+ /* Use a union, since on NetBSD, the compilation flags determine
+ whether fpos_t is typedef'd to off_t or a struct containing a
+ single off_t member. */
+ union
+ {
+ fpos_t f;
+ off_t o;
+ } u;
+ u.o = pos;
+ fp_->_offset = u.f;
+# endif
+ fp_->_flags |= __SOFF;
+# endif
+}
+# endif
+#endif
+
+/* Flush all pending data on STREAM according to POSIX rules. Both
+ output and seekable input streams are supported. */
+int
+rpl_fflush (FILE *stream)
+{
+ /* When stream is NULL, POSIX and C99 only require flushing of "output
+ streams and update streams in which the most recent operation was not
+ input", and all implementations do this.
+
+ When stream is "an output stream or an update stream in which the most
+ recent operation was not input", POSIX and C99 requires that fflush
+ writes out any buffered data, and all implementations do this.
+
+ When stream is, however, an input stream or an update stream in
+ which the most recent operation was input, C99 specifies nothing,
+ and POSIX only specifies behavior if the stream is seekable.
+ mingw, in particular, drops the input buffer, leaving the file
+ descriptor positioned at the end of the input buffer. I.e. ftell
+ (stream) is lost. We don't want to call the implementation's
+ fflush in this case.
+
+ We test ! freading (stream) here, rather than fwriting (stream), because
+ what we need to know is whether the stream holds a "read buffer", and on
+ mingw this is indicated by _IOREAD, regardless of _IOWRT. */
+ if (stream == NULL || ! freading (stream))
+ return fflush (stream);
+
+#if defined _IO_ftrylockfile || __GNU_LIBRARY__ == 1 /* GNU libc, BeOS, Haiku, Linux libc5 */
+
+ clear_ungetc_buffer_preserving_position (stream);
+
+ return fflush (stream);
+
+#else
+ {
+ /* Notes about the file-position indicator:
+ 1) The file position indicator is incremented by fgetc() and decremented
+ by ungetc():
+ <http://www.opengroup.org/susv3/functions/fgetc.html>
+ "... the fgetc() function shall ... advance the associated file
+ position indicator for the stream ..."
+ <http://www.opengroup.org/susv3/functions/ungetc.html>
+ "The file-position indicator is decremented by each successful
+ call to ungetc()..."
+ 2) <http://www.opengroup.org/susv3/functions/ungetc.html> says:
+ "The value of the file-position indicator for the stream after
+ reading or discarding all pushed-back bytes shall be the same
+ as it was before the bytes were pushed back."
+ Here we are discarding all pushed-back bytes. But more specifically,
+ 3) <http://www.opengroup.org/austin/aardvark/latest/xshbug3.txt> says:
+ "[After fflush(),] the file offset of the underlying open file
+ description shall be set to the file position of the stream, and
+ any characters pushed back onto the stream by ungetc() ... shall
+ be discarded." */
+
+ /* POSIX does not specify fflush behavior for non-seekable input
+ streams. Some implementations purge unread data, some return
+ EBADF, some do nothing. */
+ off_t pos = ftello (stream);
+ if (pos == -1)
+ {
+ errno = EBADF;
+ return EOF;
+ }
+
+ /* Clear the ungetc buffer. */
+ clear_ungetc_buffer (stream);
+
+ /* To get here, we must be flushing a seekable input stream, so the
+ semantics of fpurge are now appropriate to clear the buffer. To
+ avoid losing data, the lseek is also necessary. */
+ {
+ int result = fpurge (stream);
+ if (result != 0)
+ return result;
+ }
+
+# if (defined __sferror || defined __DragonFly__ || defined __ANDROID__) && defined __SNPT
+ /* FreeBSD, NetBSD, OpenBSD, DragonFly, Mac OS X, Cygwin, Android */
+
+ {
+ /* Disable seek optimization for the next fseeko call. This tells the
+ following fseeko call to seek to the desired position directly, rather
+ than to seek to a block-aligned boundary. */
+ int saved_flags = disable_seek_optimization (stream);
+ int result = fseeko (stream, pos, SEEK_SET);
+
+ restore_seek_optimization (stream, saved_flags);
+ return result;
+ }
+
+# else
+
+ pos = lseek (fileno (stream), pos, SEEK_SET);
+ if (pos == -1)
+ return EOF;
+ /* After a successful lseek, update the file descriptor's position cache
+ in the stream. */
+ update_fpos_cache (stream, pos);
+
+ return 0;
+
+# endif
+ }
+#endif
+}
diff --git a/lib/file-has-acl.c b/lib/file-has-acl.c
index 218f52e..97d14be 100644
--- a/lib/file-has-acl.c
+++ b/lib/file-has-acl.c
@@ -1,11 +1,11 @@
-/* Test whether a file has a nontrivial access control list.
+/* Test whether a file has a nontrivial ACL. -*- coding: utf-8 -*-
- Copyright (C) 2002, 2003, 2005, 2006, 2007 Free Software Foundation, Inc.
+ Copyright (C) 2002-2003, 2005-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,10 +13,15 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
- Written by Paul Eggert and Andreas Gruenbacher. */
+ Written by Paul Eggert, Andreas Grünbacher, and Bruno Haible. */
+
+/* Without this pragma, gcc 4.7.0 20120126 may suggest that the
+ file_has_acl function might be candidate for attribute 'const' */
+#if (__GNUC__ == 4 && 6 <= __GNUC_MINOR__) || 4 < __GNUC__
+# pragma GCC diagnostic ignored "-Wsuggest-attribute=const"
+#endif
#include <config.h>
@@ -24,64 +29,475 @@
#include "acl-internal.h"
-/* Return 1 if NAME has a nontrivial access control list, 0 if NAME
- only has no or a base access control list, and -1 (setting errno)
- on error. SB must be set to the stat buffer of FILE. */
+#if GETXATTR_WITH_POSIX_ACLS
+# include <sys/xattr.h>
+# include <linux/xattr.h>
+#endif
+
+/* Return 1 if NAME has a nontrivial access control list,
+ 0 if ACLs are not supported, or if NAME has no or only a base ACL,
+ and -1 (setting errno) on error. Note callers can determine
+ if ACLs are not supported as errno is set in that case also.
+ SB must be set to the stat buffer of NAME,
+ obtained through stat() or lstat(). */
int
file_has_acl (char const *name, struct stat const *sb)
{
+#if USE_ACL
if (! S_ISLNK (sb->st_mode))
{
-#if USE_ACL && HAVE_ACL_TRIVIAL
- /* Solaris 10, which also has NFSv4 and ZFS style ACLs. */
- return acl_trivial (name);
+# if GETXATTR_WITH_POSIX_ACLS
+
+ ssize_t ret;
-#elif USE_ACL && HAVE_ACL && defined GETACLCNT
+ ret = getxattr (name, XATTR_NAME_POSIX_ACL_ACCESS, NULL, 0);
+ if (ret < 0 && errno == ENODATA)
+ ret = 0;
+ else if (ret > 0)
+ return 1;
- /* Solaris 2.5 through Solaris 9, and contemporaneous versions of
- HP-UX and Unixware. */
- int n = acl (name, GETACLCNT, 0, NULL);
- return n < 0 ? (errno == ENOSYS ? 0 : -1) : (MIN_ACL_ENTRIES < n);
+ if (ret == 0 && S_ISDIR (sb->st_mode))
+ {
+ ret = getxattr (name, XATTR_NAME_POSIX_ACL_DEFAULT, NULL, 0);
+ if (ret < 0 && errno == ENODATA)
+ ret = 0;
+ else if (ret > 0)
+ return 1;
+ }
-#elif USE_ACL && HAVE_ACL_GET_FILE && HAVE_ACL_FREE
+ if (ret < 0)
+ return - acl_errno_valid (errno);
+ return ret;
+
+# elif HAVE_ACL_GET_FILE
/* POSIX 1003.1e (draft 17 -- abandoned) specific version. */
+ /* Linux, FreeBSD, Mac OS X, IRIX, Tru64 */
int ret;
- if (HAVE_ACL_EXTENDED_FILE)
- ret = acl_extended_file (name);
- else
- {
- acl_t acl = acl_get_file (name, ACL_TYPE_ACCESS);
- if (acl)
- {
- ret = (3 < acl_entries (acl));
- acl_free (acl);
- if (ret == 0 && S_ISDIR (sb->st_mode))
- {
- acl = acl_get_file (name, ACL_TYPE_DEFAULT);
- if (acl)
- {
- ret = (0 < acl_entries (acl));
- acl_free (acl);
- }
- else
- ret = -1;
- }
- }
- else
- ret = -1;
- }
+ if (HAVE_ACL_EXTENDED_FILE) /* Linux */
+ {
+ /* On Linux, acl_extended_file is an optimized function: It only
+ makes two calls to getxattr(), one for ACL_TYPE_ACCESS, one for
+ ACL_TYPE_DEFAULT. */
+ ret = acl_extended_file (name);
+ }
+ else /* FreeBSD, Mac OS X, IRIX, Tru64 */
+ {
+# if HAVE_ACL_TYPE_EXTENDED /* Mac OS X */
+ /* On Mac OS X, acl_get_file (name, ACL_TYPE_ACCESS)
+ and acl_get_file (name, ACL_TYPE_DEFAULT)
+ always return NULL / EINVAL. There is no point in making
+ these two useless calls. The real ACL is retrieved through
+ acl_get_file (name, ACL_TYPE_EXTENDED). */
+ acl_t acl = acl_get_file (name, ACL_TYPE_EXTENDED);
+ if (acl)
+ {
+ ret = acl_extended_nontrivial (acl);
+ acl_free (acl);
+ }
+ else
+ ret = -1;
+# else /* FreeBSD, IRIX, Tru64 */
+ acl_t acl = acl_get_file (name, ACL_TYPE_ACCESS);
+ if (acl)
+ {
+ int saved_errno;
+
+ ret = acl_access_nontrivial (acl);
+ saved_errno = errno;
+ acl_free (acl);
+ errno = saved_errno;
+# if HAVE_ACL_FREE_TEXT /* Tru64 */
+ /* On OSF/1, acl_get_file (name, ACL_TYPE_DEFAULT) always
+ returns NULL with errno not set. There is no point in
+ making this call. */
+# else /* FreeBSD, IRIX */
+ /* On Linux, FreeBSD, IRIX, acl_get_file (name, ACL_TYPE_ACCESS)
+ and acl_get_file (name, ACL_TYPE_DEFAULT) on a directory
+ either both succeed or both fail; it depends on the
+ file system. Therefore there is no point in making the second
+ call if the first one already failed. */
+ if (ret == 0 && S_ISDIR (sb->st_mode))
+ {
+ acl = acl_get_file (name, ACL_TYPE_DEFAULT);
+ if (acl)
+ {
+ ret = (0 < acl_entries (acl));
+ acl_free (acl);
+ }
+ else
+ ret = -1;
+ }
+# endif
+ }
+ else
+ ret = -1;
+# endif
+ }
if (ret < 0)
- return ACL_NOT_WELL_SUPPORTED (errno) ? 0 : -1;
+ return - acl_errno_valid (errno);
return ret;
-#endif
- }
- /* FIXME: Add support for AIX, Irix, and Tru64. Please see Samba's
- source/lib/sysacls.c file for fix-related ideas. */
+# elif HAVE_FACL && defined GETACL /* Solaris, Cygwin, not HP-UX */
+
+# if defined ACL_NO_TRIVIAL
+
+ /* Solaris 10 (newer version), which has additional API declared in
+ <sys/acl.h> (acl_t) and implemented in libsec (acl_set, acl_trivial,
+ acl_fromtext, ...). */
+ return acl_trivial (name);
+
+# else /* Solaris, Cygwin, general case */
+
+ /* Solaris 2.5 through Solaris 10, Cygwin, and contemporaneous versions
+ of Unixware. The acl() call returns the access and default ACL both
+ at once. */
+ {
+ /* Initially, try to read the entries into a stack-allocated buffer.
+ Use malloc if it does not fit. */
+ enum
+ {
+ alloc_init = 4000 / sizeof (aclent_t), /* >= 3 */
+ alloc_max = MIN (INT_MAX, SIZE_MAX / sizeof (aclent_t))
+ };
+ aclent_t buf[alloc_init];
+ size_t alloc = alloc_init;
+ aclent_t *entries = buf;
+ aclent_t *malloced = NULL;
+ int count;
+
+ for (;;)
+ {
+ count = acl (name, GETACL, alloc, entries);
+ if (count < 0 && errno == ENOSPC)
+ {
+ /* Increase the size of the buffer. */
+ free (malloced);
+ if (alloc > alloc_max / 2)
+ {
+ errno = ENOMEM;
+ return -1;
+ }
+ alloc = 2 * alloc; /* <= alloc_max */
+ entries = malloced =
+ (aclent_t *) malloc (alloc * sizeof (aclent_t));
+ if (entries == NULL)
+ {
+ errno = ENOMEM;
+ return -1;
+ }
+ continue;
+ }
+ break;
+ }
+ if (count < 0)
+ {
+ if (errno == ENOSYS || errno == ENOTSUP)
+ ;
+ else
+ {
+ int saved_errno = errno;
+ free (malloced);
+ errno = saved_errno;
+ return -1;
+ }
+ }
+ else if (count == 0)
+ ;
+ else
+ {
+ /* Don't use MIN_ACL_ENTRIES: It's set to 4 on Cygwin, but Cygwin
+ returns only 3 entries for files with no ACL. But this is safe:
+ If there are more than 4 entries, there cannot be only the
+ "user::", "group::", "other:", and "mask:" entries. */
+ if (count > 4)
+ {
+ free (malloced);
+ return 1;
+ }
+
+ if (acl_nontrivial (count, entries))
+ {
+ free (malloced);
+ return 1;
+ }
+ }
+ free (malloced);
+ }
+
+# ifdef ACE_GETACL
+ /* Solaris also has a different variant of ACLs, used in ZFS and NFSv4
+ file systems (whereas the other ones are used in UFS file systems). */
+ {
+ /* Initially, try to read the entries into a stack-allocated buffer.
+ Use malloc if it does not fit. */
+ enum
+ {
+ alloc_init = 4000 / sizeof (ace_t), /* >= 3 */
+ alloc_max = MIN (INT_MAX, SIZE_MAX / sizeof (ace_t))
+ };
+ ace_t buf[alloc_init];
+ size_t alloc = alloc_init;
+ ace_t *entries = buf;
+ ace_t *malloced = NULL;
+ int count;
+
+ for (;;)
+ {
+ count = acl (name, ACE_GETACL, alloc, entries);
+ if (count < 0 && errno == ENOSPC)
+ {
+ /* Increase the size of the buffer. */
+ free (malloced);
+ if (alloc > alloc_max / 2)
+ {
+ errno = ENOMEM;
+ return -1;
+ }
+ alloc = 2 * alloc; /* <= alloc_max */
+ entries = malloced = (ace_t *) malloc (alloc * sizeof (ace_t));
+ if (entries == NULL)
+ {
+ errno = ENOMEM;
+ return -1;
+ }
+ continue;
+ }
+ break;
+ }
+ if (count < 0)
+ {
+ if (errno == ENOSYS || errno == EINVAL)
+ ;
+ else
+ {
+ int saved_errno = errno;
+ free (malloced);
+ errno = saved_errno;
+ return -1;
+ }
+ }
+ else if (count == 0)
+ ;
+ else
+ {
+ /* In the old (original Solaris 10) convention:
+ If there are more than 3 entries, there cannot be only the
+ ACE_OWNER, ACE_GROUP, ACE_OTHER entries.
+ In the newer Solaris 10 and Solaris 11 convention:
+ If there are more than 6 entries, there cannot be only the
+ ACE_OWNER, ACE_GROUP, ACE_EVERYONE entries, each once with
+ NEW_ACE_ACCESS_ALLOWED_ACE_TYPE and once with
+ NEW_ACE_ACCESS_DENIED_ACE_TYPE. */
+ if (count > 6)
+ {
+ free (malloced);
+ return 1;
+ }
+
+ if (acl_ace_nontrivial (count, entries))
+ {
+ free (malloced);
+ return 1;
+ }
+ }
+ free (malloced);
+ }
+# endif
+
+ return 0;
+# endif
+
+# elif HAVE_GETACL /* HP-UX */
+
+ {
+ struct acl_entry entries[NACLENTRIES];
+ int count;
+
+ count = getacl (name, NACLENTRIES, entries);
+
+ if (count < 0)
+ {
+ /* ENOSYS is seen on newer HP-UX versions.
+ EOPNOTSUPP is typically seen on NFS mounts.
+ ENOTSUP was seen on Quantum StorNext file systems (cvfs). */
+ if (errno == ENOSYS || errno == EOPNOTSUPP || errno == ENOTSUP)
+ ;
+ else
+ return -1;
+ }
+ else if (count == 0)
+ return 0;
+ else /* count > 0 */
+ {
+ if (count > NACLENTRIES)
+ /* If NACLENTRIES cannot be trusted, use dynamic memory
+ allocation. */
+ abort ();
+
+ /* If there are more than 3 entries, there cannot be only the
+ (uid,%), (%,gid), (%,%) entries. */
+ if (count > 3)
+ return 1;
+
+ {
+ struct stat statbuf;
+
+ if (stat (name, &statbuf) < 0)
+ return -1;
+
+ return acl_nontrivial (count, entries);
+ }
+ }
+ }
+
+# if HAVE_ACLV_H /* HP-UX >= 11.11 */
+
+ {
+ struct acl entries[NACLVENTRIES];
+ int count;
+
+ count = acl ((char *) name, ACL_GET, NACLVENTRIES, entries);
+
+ if (count < 0)
+ {
+ /* EOPNOTSUPP is seen on NFS in HP-UX 11.11, 11.23.
+ EINVAL is seen on NFS in HP-UX 11.31. */
+ if (errno == ENOSYS || errno == EOPNOTSUPP || errno == EINVAL)
+ ;
+ else
+ return -1;
+ }
+ else if (count == 0)
+ return 0;
+ else /* count > 0 */
+ {
+ if (count > NACLVENTRIES)
+ /* If NACLVENTRIES cannot be trusted, use dynamic memory
+ allocation. */
+ abort ();
+
+ /* If there are more than 4 entries, there cannot be only the
+ four base ACL entries. */
+ if (count > 4)
+ return 1;
+
+ return aclv_nontrivial (count, entries);
+ }
+ }
+
+# endif
+
+# elif HAVE_ACLX_GET && defined ACL_AIX_WIP /* AIX */
+
+ acl_type_t type;
+ char aclbuf[1024];
+ void *acl = aclbuf;
+ size_t aclsize = sizeof (aclbuf);
+ mode_t mode;
+
+ for (;;)
+ {
+ /* The docs say that type being 0 is equivalent to ACL_ANY, but it
+ is not true, in AIX 5.3. */
+ type.u64 = ACL_ANY;
+ if (aclx_get (name, 0, &type, aclbuf, &aclsize, &mode) >= 0)
+ break;
+ if (errno == ENOSYS)
+ return 0;
+ if (errno != ENOSPC)
+ {
+ if (acl != aclbuf)
+ {
+ int saved_errno = errno;
+ free (acl);
+ errno = saved_errno;
+ }
+ return -1;
+ }
+ aclsize = 2 * aclsize;
+ if (acl != aclbuf)
+ free (acl);
+ acl = malloc (aclsize);
+ if (acl == NULL)
+ {
+ errno = ENOMEM;
+ return -1;
+ }
+ }
+
+ if (type.u64 == ACL_AIXC)
+ {
+ int result = acl_nontrivial ((struct acl *) acl);
+ if (acl != aclbuf)
+ free (acl);
+ return result;
+ }
+ else if (type.u64 == ACL_NFS4)
+ {
+ int result = acl_nfs4_nontrivial ((nfs4_acl_int_t *) acl);
+ if (acl != aclbuf)
+ free (acl);
+ return result;
+ }
+ else
+ {
+ /* A newer type of ACL has been introduced in the system.
+ We should better support it. */
+ if (acl != aclbuf)
+ free (acl);
+ errno = EINVAL;
+ return -1;
+ }
+
+# elif HAVE_STATACL /* older AIX */
+
+ union { struct acl a; char room[4096]; } u;
+
+ if (statacl ((char *) name, STX_NORMAL, &u.a, sizeof (u)) < 0)
+ return -1;
+
+ return acl_nontrivial (&u.a);
+
+# elif HAVE_ACLSORT /* NonStop Kernel */
+
+ {
+ struct acl entries[NACLENTRIES];
+ int count;
+
+ count = acl ((char *) name, ACL_GET, NACLENTRIES, entries);
+
+ if (count < 0)
+ {
+ if (errno == ENOSYS || errno == ENOTSUP)
+ ;
+ else
+ return -1;
+ }
+ else if (count == 0)
+ return 0;
+ else /* count > 0 */
+ {
+ if (count > NACLENTRIES)
+ /* If NACLENTRIES cannot be trusted, use dynamic memory
+ allocation. */
+ abort ();
+
+ /* If there are more than 4 entries, there cannot be only the
+ four base ACL entries. */
+ if (count > 4)
+ return 1;
+
+ return acl_nontrivial (count, entries);
+ }
+ }
+
+# endif
+ }
+#endif
return 0;
}
diff --git a/lib/file-set.c b/lib/file-set.c
new file mode 100644
index 0000000..4e88479
--- /dev/null
+++ b/lib/file-set.c
@@ -0,0 +1,74 @@
+/* Specialized functions to manipulate a set of files.
+ Copyright (C) 2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* written by Jim Meyering */
+
+#include <config.h>
+#include "file-set.h"
+
+#include "hash-triple.h"
+#include "xalloc.h"
+
+/* Record file, FILE, and dev/ino from *STATS, in the hash table, HT.
+ If HT is NULL, return immediately.
+ If memory allocation fails, exit immediately. */
+void
+record_file (Hash_table *ht, char const *file, struct stat const *stats)
+{
+ struct F_triple *ent;
+
+ if (ht == NULL)
+ return;
+
+ ent = xmalloc (sizeof *ent);
+ ent->name = xstrdup (file);
+ ent->st_ino = stats->st_ino;
+ ent->st_dev = stats->st_dev;
+
+ {
+ struct F_triple *ent_from_table = hash_insert (ht, ent);
+ if (ent_from_table == NULL)
+ {
+ /* Insertion failed due to lack of memory. */
+ xalloc_die ();
+ }
+
+ if (ent_from_table != ent)
+ {
+ /* There was alread a matching entry in the table, so ENT was
+ not inserted. Free it. */
+ triple_free (ent);
+ }
+ }
+}
+
+/* Return true if there is an entry in hash table, HT,
+ for the file described by FILE and STATS. */
+bool
+seen_file (Hash_table const *ht, char const *file,
+ struct stat const *stats)
+{
+ struct F_triple new_ent;
+
+ if (ht == NULL)
+ return false;
+
+ new_ent.name = (char *) file;
+ new_ent.st_ino = stats->st_ino;
+ new_ent.st_dev = stats->st_dev;
+
+ return !!hash_lookup (ht, &new_ent);
+}
diff --git a/lib/file-set.h b/lib/file-set.h
new file mode 100644
index 0000000..4e47d95
--- /dev/null
+++ b/lib/file-set.h
@@ -0,0 +1,15 @@
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <stdbool.h>
+
+#include "hash.h"
+
+extern void record_file (Hash_table *ht, char const *file,
+ struct stat const *stats)
+#if defined __GNUC__ && ((__GNUC__ == 3 && __GNUC_MINOR__ >= 3) || __GNUC__ > 3)
+ __attribute__ ((nonnull (2, 3)))
+#endif
+;
+
+extern bool seen_file (Hash_table const *ht, char const *file,
+ struct stat const *stats);
diff --git a/lib/file-type.c b/lib/file-type.c
index 9fc7c52..b405133 100644
--- a/lib/file-type.c
+++ b/lib/file-type.c
@@ -1,12 +1,12 @@
/* Return a string describing the type of a file.
- Copyright (C) 1993, 1994, 2001, 2002, 2004, 2005, 2006 Free
- Software Foundation, Inc.
+ Copyright (C) 1993-1994, 2001-2002, 2004-2006, 2009-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
@@ -35,26 +34,19 @@ file_type (struct stat const *st)
To keep diagnostics grammatical in English, the returned string
must start with a consonant. */
+ /* Do these three first, as they're the most common. */
+
if (S_ISREG (st->st_mode))
return st->st_size == 0 ? _("regular empty file") : _("regular file");
if (S_ISDIR (st->st_mode))
return _("directory");
- if (S_ISBLK (st->st_mode))
- return _("block special file");
-
- if (S_ISCHR (st->st_mode))
- return _("character special file");
-
- if (S_ISFIFO (st->st_mode))
- return _("fifo");
-
if (S_ISLNK (st->st_mode))
return _("symbolic link");
- if (S_ISSOCK (st->st_mode))
- return _("socket");
+ /* Do the S_TYPEIS* macros next, as they may be implemented in terms
+ of S_ISNAM, and we want the more-specialized interpretation. */
if (S_TYPEISMQ (st))
return _("message queue");
@@ -68,5 +60,52 @@ file_type (struct stat const *st)
if (S_TYPEISTMO (st))
return _("typed memory object");
+ /* The remaining are in alphabetical order. */
+
+ if (S_ISBLK (st->st_mode))
+ return _("block special file");
+
+ if (S_ISCHR (st->st_mode))
+ return _("character special file");
+
+ if (S_ISCTG (st->st_mode))
+ return _("contiguous data");
+
+ if (S_ISFIFO (st->st_mode))
+ return _("fifo");
+
+ if (S_ISDOOR (st->st_mode))
+ return _("door");
+
+ if (S_ISMPB (st->st_mode))
+ return _("multiplexed block special file");
+
+ if (S_ISMPC (st->st_mode))
+ return _("multiplexed character special file");
+
+ if (S_ISMPX (st->st_mode))
+ return _("multiplexed file");
+
+ if (S_ISNAM (st->st_mode))
+ return _("named file");
+
+ if (S_ISNWK (st->st_mode))
+ return _("network special file");
+
+ if (S_ISOFD (st->st_mode))
+ return _("migrated file with data");
+
+ if (S_ISOFL (st->st_mode))
+ return _("migrated file without data");
+
+ if (S_ISPORT (st->st_mode))
+ return _("port");
+
+ if (S_ISSOCK (st->st_mode))
+ return _("socket");
+
+ if (S_ISWHT (st->st_mode))
+ return _("whiteout");
+
return _("weird file");
}
diff --git a/lib/file-type.h b/lib/file-type.h
index 1f4ca3d..0933f7a 100644
--- a/lib/file-type.h
+++ b/lib/file-type.h
@@ -1,12 +1,12 @@
/* Return a string describing the type of a file.
- Copyright (C) 1993, 1994, 2001, 2002, 2004, 2005 Free Software
+ Copyright (C) 1993-1994, 2001-2002, 2004-2005, 2009-2016 Free Software
Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert and Jim Meyering. */
@@ -25,6 +24,6 @@
# include <sys/types.h>
# include <sys/stat.h>
-char const *file_type (struct stat const *);
+char const *file_type (struct stat const *) _GL_ATTRIBUTE_PURE;
#endif /* FILE_TYPE_H */
diff --git a/lib/fileblocks.c b/lib/fileblocks.c
index 4024d1e..977370a 100644
--- a/lib/fileblocks.c
+++ b/lib/fileblocks.c
@@ -1,12 +1,12 @@
/* Convert file size to number of blocks on System V-like machines.
- Copyright (C) 1990, 1997, 1998, 1999, 2004, 2005, 2006 Free Software
+ Copyright (C) 1990, 1997-1999, 2004-2006, 2009-2016 Free Software
Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Brian L. Matthews, blm@6sceng.UUCP. */
@@ -43,7 +42,7 @@ typedef long daddr_t; /* for disk address */
# endif /* !NINDIR */
/* Number of direct block addresses in an inode. */
-# define NDIR 10
+# define NDIR 10
/* Return the number of 512-byte blocks in a file of SIZE bytes. */
@@ -58,12 +57,12 @@ st_blocks (off_t size)
indrblks = (datablks - NDIR - 1) / NINDIR + 1;
if (datablks > NDIR + NINDIR)
- {
- indrblks += (datablks - NDIR - NINDIR - 1) / (NINDIR * NINDIR) + 1;
+ {
+ indrblks += (datablks - NDIR - NINDIR - 1) / (NINDIR * NINDIR) + 1;
- if (datablks > NDIR + NINDIR + NINDIR * NINDIR)
- indrblks++;
- }
+ if (datablks > NDIR + NINDIR + NINDIR * NINDIR)
+ indrblks++;
+ }
}
return datablks + indrblks;
diff --git a/lib/filemode.c b/lib/filemode.c
index 726c331..2250ee0 100644
--- a/lib/filemode.c
+++ b/lib/filemode.c
@@ -1,12 +1,12 @@
/* filemode.c -- make a string describing file modes
- Copyright (C) 1985, 1990, 1993, 1998-2000, 2004, 2006 Free Software
- Foundation, Inc.
+ Copyright (C) 1985, 1990, 1993, 1998-2000, 2004, 2006, 2009-2016 Free
+ Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,16 +14,15 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
#include "filemode.h"
/* The following is for Cray DMF (Data Migration Facility), which is a
- HSM file system. A migrated file has a `st_dm_mode' that is
- different from the normal `st_mode', so any tests for migrated
+ HSM file system. A migrated file has a 'st_dm_mode' that is
+ different from the normal 'st_mode', so any tests for migrated
files should use the former. */
#if HAVE_ST_DM_MODE
# define IS_MIGRATED_FILE(statp) \
@@ -79,7 +78,7 @@ ftypelet (mode_t bits)
return 'C';
if (S_ISDOOR (bits))
return 'D';
- if (S_ISMPB (bits) || S_ISMPC (bits))
+ if (S_ISMPB (bits) || S_ISMPC (bits) || S_ISMPX (bits))
return 'm';
if (S_ISNWK (bits))
return 'n';
@@ -100,18 +99,18 @@ strmode (mode_t mode, char *str)
str[1] = mode & S_IRUSR ? 'r' : '-';
str[2] = mode & S_IWUSR ? 'w' : '-';
str[3] = (mode & S_ISUID
- ? (mode & S_IXUSR ? 's' : 'S')
- : (mode & S_IXUSR ? 'x' : '-'));
+ ? (mode & S_IXUSR ? 's' : 'S')
+ : (mode & S_IXUSR ? 'x' : '-'));
str[4] = mode & S_IRGRP ? 'r' : '-';
str[5] = mode & S_IWGRP ? 'w' : '-';
str[6] = (mode & S_ISGID
- ? (mode & S_IXGRP ? 's' : 'S')
- : (mode & S_IXGRP ? 'x' : '-'));
+ ? (mode & S_IXGRP ? 's' : 'S')
+ : (mode & S_IXGRP ? 'x' : '-'));
str[7] = mode & S_IROTH ? 'r' : '-';
str[8] = mode & S_IWOTH ? 'w' : '-';
str[9] = (mode & S_ISVTX
- ? (mode & S_IXOTH ? 't' : 'T')
- : (mode & S_IXOTH ? 'x' : '-'));
+ ? (mode & S_IXOTH ? 't' : 'T')
+ : (mode & S_IXOTH ? 'x' : '-'));
str[10] = ' ';
str[11] = '\0';
}
@@ -123,43 +122,43 @@ strmode (mode_t mode, char *str)
12 characters are stored in STR.
The characters stored in STR are:
- 0 File type, as in ftypelet above, except that other letters are used
+ 0 File type, as in ftypelet above, except that other letters are used
for files whose type cannot be determined solely from st_mode:
- 'F' semaphore
- 'M' migrated file (Cray DMF)
- 'Q' message queue
- 'S' shared memory object
- 'T' typed memory object
+ 'F' semaphore
+ 'M' migrated file (Cray DMF)
+ 'Q' message queue
+ 'S' shared memory object
+ 'T' typed memory object
- 1 'r' if the owner may read, '-' otherwise.
+ 1 'r' if the owner may read, '-' otherwise.
- 2 'w' if the owner may write, '-' otherwise.
+ 2 'w' if the owner may write, '-' otherwise.
- 3 'x' if the owner may execute, 's' if the file is
- set-user-id, '-' otherwise.
- 'S' if the file is set-user-id, but the execute
- bit isn't set.
+ 3 'x' if the owner may execute, 's' if the file is
+ set-user-id, '-' otherwise.
+ 'S' if the file is set-user-id, but the execute
+ bit isn't set.
- 4 'r' if group members may read, '-' otherwise.
+ 4 'r' if group members may read, '-' otherwise.
- 5 'w' if group members may write, '-' otherwise.
+ 5 'w' if group members may write, '-' otherwise.
- 6 'x' if group members may execute, 's' if the file is
- set-group-id, '-' otherwise.
- 'S' if it is set-group-id but not executable.
+ 6 'x' if group members may execute, 's' if the file is
+ set-group-id, '-' otherwise.
+ 'S' if it is set-group-id but not executable.
- 7 'r' if any user may read, '-' otherwise.
+ 7 'r' if any user may read, '-' otherwise.
- 8 'w' if any user may write, '-' otherwise.
+ 8 'w' if any user may write, '-' otherwise.
- 9 'x' if any user may execute, 't' if the file is "sticky"
- (will be retained in swap space after execution), '-'
- otherwise.
- 'T' if the file is sticky but not executable.
+ 9 'x' if any user may execute, 't' if the file is "sticky"
+ (will be retained in swap space after execution), '-'
+ otherwise.
+ 'T' if the file is sticky but not executable.
10 ' ' for compatibility with 4.4BSD strmode,
- since this interface does not support ACLs.
+ since this interface does not support ACLs.
11 '\0'. */
diff --git a/lib/filemode.h b/lib/filemode.h
index f71d994..09f345e 100644
--- a/lib/filemode.h
+++ b/lib/filemode.h
@@ -1,11 +1,12 @@
/* Make a string describing file modes.
- Copyright (C) 1998, 1999, 2003, 2006 Free Software Foundation, Inc.
+ Copyright (C) 1998-1999, 2003, 2006, 2009-2016 Free Software Foundation,
+ Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,21 +14,31 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifndef FILEMODE_H_
# include <sys/types.h>
# include <sys/stat.h>
+/* Get the declaration of strmode. */
# if HAVE_DECL_STRMODE
-# include <string.h> /* FreeBSD, OpenBSD */
+# include <string.h> /* Mac OS X, FreeBSD, OpenBSD */
# include <unistd.h> /* NetBSD */
-# else
-void strmode (mode_t mode, char *str);
# endif
-void filemodestring (struct stat const *statp, char *str);
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# if !HAVE_DECL_STRMODE
+extern void strmode (mode_t mode, char *str);
+# endif
+
+extern void filemodestring (struct stat const *statp, char *str);
+
+# ifdef __cplusplus
+}
+# endif
#endif
diff --git a/lib/filename.h b/lib/filename.h
new file mode 100644
index 0000000..7d2c31a
--- /dev/null
+++ b/lib/filename.h
@@ -0,0 +1,54 @@
+/* Basic filename support macros.
+ Copyright (C) 2001-2004, 2007-2016 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _FILENAME_H
+#define _FILENAME_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/* Pathname support.
+ ISSLASH(C) tests whether C is a directory separator character.
+ IS_ABSOLUTE_PATH(P) tests whether P is an absolute path. If it is not,
+ it may be concatenated to a directory pathname.
+ IS_PATH_WITH_DIR(P) tests whether P contains a directory specification.
+ */
+#if defined _WIN32 || defined __WIN32__ || defined __CYGWIN__ || defined __EMX__ || defined __DJGPP__
+ /* Native Windows, Cygwin, OS/2, DOS */
+# define ISSLASH(C) ((C) == '/' || (C) == '\\')
+# define HAS_DEVICE(P) \
+ ((((P)[0] >= 'A' && (P)[0] <= 'Z') || ((P)[0] >= 'a' && (P)[0] <= 'z')) \
+ && (P)[1] == ':')
+# define IS_ABSOLUTE_PATH(P) (ISSLASH ((P)[0]) || HAS_DEVICE (P))
+# define IS_PATH_WITH_DIR(P) \
+ (strchr (P, '/') != NULL || strchr (P, '\\') != NULL || HAS_DEVICE (P))
+# define FILE_SYSTEM_PREFIX_LEN(P) (HAS_DEVICE (P) ? 2 : 0)
+#else
+ /* Unix */
+# define ISSLASH(C) ((C) == '/')
+# define IS_ABSOLUTE_PATH(P) ISSLASH ((P)[0])
+# define IS_PATH_WITH_DIR(P) (strchr (P, '/') != NULL)
+# define FILE_SYSTEM_PREFIX_LEN(P) 0
+#endif
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _FILENAME_H */
diff --git a/lib/filenamecat-lgpl.c b/lib/filenamecat-lgpl.c
new file mode 100644
index 0000000..4903fbf
--- /dev/null
+++ b/lib/filenamecat-lgpl.c
@@ -0,0 +1,88 @@
+/* Concatenate two arbitrary file names.
+
+ Copyright (C) 1996-2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Jim Meyering. */
+
+#include <config.h>
+
+/* Specification. */
+#include "filenamecat.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+#include "dirname.h"
+
+#if ! HAVE_MEMPCPY && ! defined mempcpy
+# define mempcpy(D, S, N) ((void *) ((char *) memcpy (D, S, N) + (N)))
+#endif
+
+/* Return the longest suffix of F that is a relative file name.
+ If it has no such suffix, return the empty string. */
+
+static char const * _GL_ATTRIBUTE_PURE
+longest_relative_suffix (char const *f)
+{
+ for (f += FILE_SYSTEM_PREFIX_LEN (f); ISSLASH (*f); f++)
+ continue;
+ return f;
+}
+
+/* Concatenate two file name components, DIR and ABASE, in
+ newly-allocated storage and return the result.
+ The resulting file name F is such that the commands "ls F" and "(cd
+ DIR; ls BASE)" refer to the same file, where BASE is ABASE with any
+ file system prefixes and leading separators removed.
+ Arrange for a directory separator if necessary between DIR and BASE
+ in the result, removing any redundant separators.
+ In any case, if BASE_IN_RESULT is non-NULL, set
+ *BASE_IN_RESULT to point to the copy of ABASE in the returned
+ concatenation. However, if ABASE begins with more than one slash,
+ set *BASE_IN_RESULT to point to the sole corresponding slash that
+ is copied into the result buffer.
+
+ Return NULL if malloc fails. */
+
+char *
+mfile_name_concat (char const *dir, char const *abase, char **base_in_result)
+{
+ char const *dirbase = last_component (dir);
+ size_t dirbaselen = base_len (dirbase);
+ size_t dirlen = dirbase - dir + dirbaselen;
+ size_t needs_separator = (dirbaselen && ! ISSLASH (dirbase[dirbaselen - 1]));
+
+ char const *base = longest_relative_suffix (abase);
+ size_t baselen = strlen (base);
+
+ char *p_concat = malloc (dirlen + needs_separator + baselen + 1);
+ char *p;
+
+ if (p_concat == NULL)
+ return NULL;
+
+ p = mempcpy (p_concat, dir, dirlen);
+ *p = DIRECTORY_SEPARATOR;
+ p += needs_separator;
+
+ if (base_in_result)
+ *base_in_result = p - IS_ABSOLUTE_FILE_NAME (abase);
+
+ p = mempcpy (p, base, baselen);
+ *p = '\0';
+
+ return p_concat;
+}
diff --git a/lib/filenamecat.c b/lib/filenamecat.c
index bccffb2..06cfeae 100644
--- a/lib/filenamecat.c
+++ b/lib/filenamecat.c
@@ -1,12 +1,11 @@
/* Concatenate two arbitrary file names.
- Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
- 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 1996-2007, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Jim Meyering. */
@@ -24,101 +22,20 @@
/* Specification. */
#include "filenamecat.h"
+#include <stdlib.h>
#include <string.h>
-#include "dirname.h"
#include "xalloc.h"
-#if ! HAVE_MEMPCPY && ! defined mempcpy
-# define mempcpy(D, S, N) ((void *) ((char *) memcpy (D, S, N) + (N)))
-#endif
-
-/* Return the longest suffix of F that is a relative file name.
- If it has no such suffix, return the empty string. */
-
-static char const *
-longest_relative_suffix (char const *f)
-{
- for (f += FILE_SYSTEM_PREFIX_LEN (f); ISSLASH (*f); f++)
- continue;
- return f;
-}
-
-/* Concatenate two file name components, DIR and ABASE, in
- newly-allocated storage and return the result.
- The resulting file name F is such that the commands "ls F" and "(cd
- DIR; ls BASE)" refer to the same file, where BASE is ABASE with any
- file system prefixes and leading separators removed.
- Arrange for a directory separator if necessary between DIR and BASE
- in the result, removing any redundant separators.
- In any case, if BASE_IN_RESULT is non-NULL, set
- *BASE_IN_RESULT to point to the copy of ABASE in the returned
- concatenation. However, if ABASE begins with more than one slash,
- set *BASE_IN_RESULT to point to the sole corresponding slash that
- is copied into the result buffer.
-
- Report an error if memory is exhausted. */
+/* Just like mfile_name_concat (filenamecat-lgpl.c), except, rather than
+ returning NULL upon malloc failure, here, we report the
+ "memory exhausted" condition and exit. */
char *
file_name_concat (char const *dir, char const *abase, char **base_in_result)
{
- char const *dirbase = last_component (dir);
- size_t dirbaselen = base_len (dirbase);
- size_t dirlen = dirbase - dir + dirbaselen;
- size_t needs_separator = (dirbaselen && ! ISSLASH (dirbase[dirbaselen - 1]));
-
- char const *base = longest_relative_suffix (abase);
- size_t baselen = strlen (base);
-
- char *p_concat = xmalloc (dirlen + needs_separator + baselen + 1);
- char *p;
-
- p = mempcpy (p_concat, dir, dirlen);
- *p = DIRECTORY_SEPARATOR;
- p += needs_separator;
-
- if (base_in_result)
- *base_in_result = p - IS_ABSOLUTE_FILE_NAME (abase);
-
- p = mempcpy (p, base, baselen);
- *p = '\0';
-
- return p_concat;
-}
-
-#ifdef TEST_FILE_NAME_CONCAT
-# include <stdlib.h>
-# include <stdio.h>
-int
-main ()
-{
- static char const *const tests[][3] =
- {
- {"a", "b", "a/b"},
- {"a/", "b", "a/b"},
- {"a/", "/b", "a/b"},
- {"a", "/b", "a/b"},
-
- {"/", "b", "/b"},
- {"/", "/b", "/b"},
- {"/", "/", "/"},
- {"a", "/", "a/"}, /* this might deserve a diagnostic */
- {"/a", "/", "/a/"}, /* this might deserve a diagnostic */
- {"a", "//b", "a/b"},
- };
- size_t i;
- bool fail = false;
- for (i = 0; i < sizeof tests / sizeof tests[0]; i++)
- {
- char *base_in_result;
- char const *const *t = tests[i];
- char *res = file_name_concat (t[0], t[1], &base_in_result);
- if (strcmp (res, t[2]) != 0)
- {
- printf ("got %s, expected %s\n", res, t[2]);
- fail = true;
- }
- }
- exit (fail ? EXIT_FAILURE : EXIT_SUCCESS);
+ char *p = mfile_name_concat (dir, abase, base_in_result);
+ if (p == NULL)
+ xalloc_die ();
+ return p;
}
-#endif
diff --git a/lib/filenamecat.h b/lib/filenamecat.h
index c943b67..791a0af 100644
--- a/lib/filenamecat.h
+++ b/lib/filenamecat.h
@@ -1,11 +1,12 @@
/* Concatenate two arbitrary file names.
- Copyright (C) 1996, 1997, 2003, 2005 Free Software Foundation, Inc.
+ Copyright (C) 1996-1997, 2003, 2005, 2007, 2009-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,10 +14,14 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Jim Meyering. */
+#if GNULIB_FILENAMECAT
char *file_name_concat (char const *dir, char const *base,
- char **base_in_result);
+ char **base_in_result);
+#endif
+
+char *mfile_name_concat (char const *dir, char const *base,
+ char **base_in_result);
diff --git a/lib/filevercmp.c b/lib/filevercmp.c
new file mode 100644
index 0000000..a75c946
--- /dev/null
+++ b/lib/filevercmp.c
@@ -0,0 +1,181 @@
+/*
+ Copyright (C) 1995 Ian Jackson <iwj10@cus.cam.ac.uk>
+ Copyright (C) 2001 Anthony Towns <aj@azure.humbug.org.au>
+ Copyright (C) 2008-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+#include "filevercmp.h"
+
+#include <sys/types.h>
+#include <stdlib.h>
+#include <stdbool.h>
+#include <string.h>
+#include <c-ctype.h>
+#include <limits.h>
+
+/* Match a file suffix defined by this regular expression:
+ /(\.[A-Za-z~][A-Za-z0-9~]*)*$/
+ Scan the string *STR and return a pointer to the matching suffix, or
+ NULL if not found. Upon return, *STR points to terminating NUL. */
+static const char *
+match_suffix (const char **str)
+{
+ const char *match = NULL;
+ bool read_alpha = false;
+ while (**str)
+ {
+ if (read_alpha)
+ {
+ read_alpha = false;
+ if (!c_isalpha (**str) && '~' != **str)
+ match = NULL;
+ }
+ else if ('.' == **str)
+ {
+ read_alpha = true;
+ if (!match)
+ match = *str;
+ }
+ else if (!c_isalnum (**str) && '~' != **str)
+ match = NULL;
+ (*str)++;
+ }
+ return match;
+}
+
+/* verrevcmp helper function */
+static int
+order (unsigned char c)
+{
+ if (c_isdigit (c))
+ return 0;
+ else if (c_isalpha (c))
+ return c;
+ else if (c == '~')
+ return -1;
+ else
+ return (int) c + UCHAR_MAX + 1;
+}
+
+/* slightly modified verrevcmp function from dpkg
+ S1, S2 - compared string
+ S1_LEN, S2_LEN - length of strings to be scanned
+
+ This implements the algorithm for comparison of version strings
+ specified by Debian and now widely adopted. The detailed
+ specification can be found in the Debian Policy Manual in the
+ section on the 'Version' control field. This version of the code
+ implements that from s5.6.12 of Debian Policy v3.8.0.1
+ http://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-Version */
+static int _GL_ATTRIBUTE_PURE
+verrevcmp (const char *s1, size_t s1_len, const char *s2, size_t s2_len)
+{
+ size_t s1_pos = 0;
+ size_t s2_pos = 0;
+ while (s1_pos < s1_len || s2_pos < s2_len)
+ {
+ int first_diff = 0;
+ while ((s1_pos < s1_len && !c_isdigit (s1[s1_pos]))
+ || (s2_pos < s2_len && !c_isdigit (s2[s2_pos])))
+ {
+ int s1_c = (s1_pos == s1_len) ? 0 : order (s1[s1_pos]);
+ int s2_c = (s2_pos == s2_len) ? 0 : order (s2[s2_pos]);
+ if (s1_c != s2_c)
+ return s1_c - s2_c;
+ s1_pos++;
+ s2_pos++;
+ }
+ while (s1[s1_pos] == '0')
+ s1_pos++;
+ while (s2[s2_pos] == '0')
+ s2_pos++;
+ while (c_isdigit (s1[s1_pos]) && c_isdigit (s2[s2_pos]))
+ {
+ if (!first_diff)
+ first_diff = s1[s1_pos] - s2[s2_pos];
+ s1_pos++;
+ s2_pos++;
+ }
+ if (c_isdigit (s1[s1_pos]))
+ return 1;
+ if (c_isdigit (s2[s2_pos]))
+ return -1;
+ if (first_diff)
+ return first_diff;
+ }
+ return 0;
+}
+
+/* Compare version strings S1 and S2.
+ See filevercmp.h for function description. */
+int
+filevercmp (const char *s1, const char *s2)
+{
+ const char *s1_pos;
+ const char *s2_pos;
+ const char *s1_suffix, *s2_suffix;
+ size_t s1_len, s2_len;
+ int result;
+
+ /* easy comparison to see if strings are identical */
+ int simple_cmp = strcmp (s1, s2);
+ if (simple_cmp == 0)
+ return 0;
+
+ /* special handle for "", "." and ".." */
+ if (!*s1)
+ return -1;
+ if (!*s2)
+ return 1;
+ if (0 == strcmp (".", s1))
+ return -1;
+ if (0 == strcmp (".", s2))
+ return 1;
+ if (0 == strcmp ("..", s1))
+ return -1;
+ if (0 == strcmp ("..", s2))
+ return 1;
+
+ /* special handle for other hidden files */
+ if (*s1 == '.' && *s2 != '.')
+ return -1;
+ if (*s1 != '.' && *s2 == '.')
+ return 1;
+ if (*s1 == '.' && *s2 == '.')
+ {
+ s1++;
+ s2++;
+ }
+
+ /* "cut" file suffixes */
+ s1_pos = s1;
+ s2_pos = s2;
+ s1_suffix = match_suffix (&s1_pos);
+ s2_suffix = match_suffix (&s2_pos);
+ s1_len = (s1_suffix ? s1_suffix : s1_pos) - s1;
+ s2_len = (s2_suffix ? s2_suffix : s2_pos) - s2;
+
+ /* restore file suffixes if strings are identical after "cut" */
+ if ((s1_suffix || s2_suffix) && (s1_len == s2_len)
+ && 0 == strncmp (s1, s2, s1_len))
+ {
+ s1_len = s1_pos - s1;
+ s2_len = s2_pos - s2;
+ }
+
+ result = verrevcmp (s1, s1_len, s2, s2_len);
+ return result == 0 ? simple_cmp : result;
+}
diff --git a/lib/filevercmp.h b/lib/filevercmp.h
new file mode 100644
index 0000000..220b71b
--- /dev/null
+++ b/lib/filevercmp.h
@@ -0,0 +1,42 @@
+/*
+ Copyright (C) 1995 Ian Jackson <iwj10@cus.cam.ac.uk>
+ Copyright (C) 2001 Anthony Towns <aj@azure.humbug.org.au>
+ Copyright (C) 2008-2016 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef FILEVERCMP_H
+#define FILEVERCMP_H
+
+/* Compare version strings:
+
+ This function compares strings S1 and S2:
+ 1) By PREFIX in the same way as strcmp.
+ 2) Then by VERSION (most similarly to version compare of Debian's dpkg).
+ Leading zeros in version numbers are ignored.
+ 3) If both (PREFIX and VERSION) are equal, strcmp function is used for
+ comparison. So this function can return 0 if (and only if) strings S1
+ and S2 are identical.
+
+ It returns number >0 for S1 > S2, 0 for S1 == S2 and number <0 for S1 < S2.
+
+ This function compares strings, in a way that if VER1 and VER2 are version
+ numbers and PREFIX and SUFFIX (SUFFIX defined as (\.[A-Za-z~][A-Za-z0-9~]*)*)
+ are strings then VER1 < VER2 implies filevercmp (PREFIX VER1 SUFFIX,
+ PREFIX VER2 SUFFIX) < 0.
+
+ This function is intended to be a replacement for strverscmp. */
+int filevercmp (const char *s1, const char *s2) _GL_ATTRIBUTE_PURE;
+
+#endif /* FILEVERCMP_H */
diff --git a/lib/float+.h b/lib/float+.h
new file mode 100644
index 0000000..00fcc76
--- /dev/null
+++ b/lib/float+.h
@@ -0,0 +1,147 @@
+/* Supplemental information about the floating-point formats.
+ Copyright (C) 2007, 2009-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2007.
+
+ 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, 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _FLOATPLUS_H
+#define _FLOATPLUS_H
+
+#include <float.h>
+#include <limits.h>
+
+/* Number of bits in the mantissa of a floating-point number, including the
+ "hidden bit". */
+#if FLT_RADIX == 2
+# define FLT_MANT_BIT FLT_MANT_DIG
+# define DBL_MANT_BIT DBL_MANT_DIG
+# define LDBL_MANT_BIT LDBL_MANT_DIG
+#elif FLT_RADIX == 4
+# define FLT_MANT_BIT (FLT_MANT_DIG * 2)
+# define DBL_MANT_BIT (DBL_MANT_DIG * 2)
+# define LDBL_MANT_BIT (LDBL_MANT_DIG * 2)
+#elif FLT_RADIX == 16
+# define FLT_MANT_BIT (FLT_MANT_DIG * 4)
+# define DBL_MANT_BIT (DBL_MANT_DIG * 4)
+# define LDBL_MANT_BIT (LDBL_MANT_DIG * 4)
+#endif
+
+/* Bit mask that can be used to mask the exponent, as an unsigned number. */
+#define FLT_EXP_MASK ((FLT_MAX_EXP - FLT_MIN_EXP) | 7)
+#define DBL_EXP_MASK ((DBL_MAX_EXP - DBL_MIN_EXP) | 7)
+#define LDBL_EXP_MASK ((LDBL_MAX_EXP - LDBL_MIN_EXP) | 7)
+
+/* Number of bits used for the exponent of a floating-point number, including
+ the exponent's sign. */
+#define FLT_EXP_BIT \
+ (FLT_EXP_MASK < 0x100 ? 8 : \
+ FLT_EXP_MASK < 0x200 ? 9 : \
+ FLT_EXP_MASK < 0x400 ? 10 : \
+ FLT_EXP_MASK < 0x800 ? 11 : \
+ FLT_EXP_MASK < 0x1000 ? 12 : \
+ FLT_EXP_MASK < 0x2000 ? 13 : \
+ FLT_EXP_MASK < 0x4000 ? 14 : \
+ FLT_EXP_MASK < 0x8000 ? 15 : \
+ FLT_EXP_MASK < 0x10000 ? 16 : \
+ FLT_EXP_MASK < 0x20000 ? 17 : \
+ FLT_EXP_MASK < 0x40000 ? 18 : \
+ FLT_EXP_MASK < 0x80000 ? 19 : \
+ FLT_EXP_MASK < 0x100000 ? 20 : \
+ FLT_EXP_MASK < 0x200000 ? 21 : \
+ FLT_EXP_MASK < 0x400000 ? 22 : \
+ FLT_EXP_MASK < 0x800000 ? 23 : \
+ FLT_EXP_MASK < 0x1000000 ? 24 : \
+ FLT_EXP_MASK < 0x2000000 ? 25 : \
+ FLT_EXP_MASK < 0x4000000 ? 26 : \
+ FLT_EXP_MASK < 0x8000000 ? 27 : \
+ FLT_EXP_MASK < 0x10000000 ? 28 : \
+ FLT_EXP_MASK < 0x20000000 ? 29 : \
+ FLT_EXP_MASK < 0x40000000 ? 30 : \
+ FLT_EXP_MASK <= 0x7fffffff ? 31 : \
+ 32)
+#define DBL_EXP_BIT \
+ (DBL_EXP_MASK < 0x100 ? 8 : \
+ DBL_EXP_MASK < 0x200 ? 9 : \
+ DBL_EXP_MASK < 0x400 ? 10 : \
+ DBL_EXP_MASK < 0x800 ? 11 : \
+ DBL_EXP_MASK < 0x1000 ? 12 : \
+ DBL_EXP_MASK < 0x2000 ? 13 : \
+ DBL_EXP_MASK < 0x4000 ? 14 : \
+ DBL_EXP_MASK < 0x8000 ? 15 : \
+ DBL_EXP_MASK < 0x10000 ? 16 : \
+ DBL_EXP_MASK < 0x20000 ? 17 : \
+ DBL_EXP_MASK < 0x40000 ? 18 : \
+ DBL_EXP_MASK < 0x80000 ? 19 : \
+ DBL_EXP_MASK < 0x100000 ? 20 : \
+ DBL_EXP_MASK < 0x200000 ? 21 : \
+ DBL_EXP_MASK < 0x400000 ? 22 : \
+ DBL_EXP_MASK < 0x800000 ? 23 : \
+ DBL_EXP_MASK < 0x1000000 ? 24 : \
+ DBL_EXP_MASK < 0x2000000 ? 25 : \
+ DBL_EXP_MASK < 0x4000000 ? 26 : \
+ DBL_EXP_MASK < 0x8000000 ? 27 : \
+ DBL_EXP_MASK < 0x10000000 ? 28 : \
+ DBL_EXP_MASK < 0x20000000 ? 29 : \
+ DBL_EXP_MASK < 0x40000000 ? 30 : \
+ DBL_EXP_MASK <= 0x7fffffff ? 31 : \
+ 32)
+#define LDBL_EXP_BIT \
+ (LDBL_EXP_MASK < 0x100 ? 8 : \
+ LDBL_EXP_MASK < 0x200 ? 9 : \
+ LDBL_EXP_MASK < 0x400 ? 10 : \
+ LDBL_EXP_MASK < 0x800 ? 11 : \
+ LDBL_EXP_MASK < 0x1000 ? 12 : \
+ LDBL_EXP_MASK < 0x2000 ? 13 : \
+ LDBL_EXP_MASK < 0x4000 ? 14 : \
+ LDBL_EXP_MASK < 0x8000 ? 15 : \
+ LDBL_EXP_MASK < 0x10000 ? 16 : \
+ LDBL_EXP_MASK < 0x20000 ? 17 : \
+ LDBL_EXP_MASK < 0x40000 ? 18 : \
+ LDBL_EXP_MASK < 0x80000 ? 19 : \
+ LDBL_EXP_MASK < 0x100000 ? 20 : \
+ LDBL_EXP_MASK < 0x200000 ? 21 : \
+ LDBL_EXP_MASK < 0x400000 ? 22 : \
+ LDBL_EXP_MASK < 0x800000 ? 23 : \
+ LDBL_EXP_MASK < 0x1000000 ? 24 : \
+ LDBL_EXP_MASK < 0x2000000 ? 25 : \
+ LDBL_EXP_MASK < 0x4000000 ? 26 : \
+ LDBL_EXP_MASK < 0x8000000 ? 27 : \
+ LDBL_EXP_MASK < 0x10000000 ? 28 : \
+ LDBL_EXP_MASK < 0x20000000 ? 29 : \
+ LDBL_EXP_MASK < 0x40000000 ? 30 : \
+ LDBL_EXP_MASK <= 0x7fffffff ? 31 : \
+ 32)
+
+/* Number of bits used for a floating-point number: the mantissa (not
+ counting the "hidden bit", since it may or may not be explicit), the
+ exponent, and the sign. */
+#define FLT_TOTAL_BIT ((FLT_MANT_BIT - 1) + FLT_EXP_BIT + 1)
+#define DBL_TOTAL_BIT ((DBL_MANT_BIT - 1) + DBL_EXP_BIT + 1)
+#define LDBL_TOTAL_BIT ((LDBL_MANT_BIT - 1) + LDBL_EXP_BIT + 1)
+
+/* Number of bytes used for a floating-point number.
+ This can be smaller than the 'sizeof'. For example, on i386 systems,
+ 'long double' most often have LDBL_MANT_BIT = 64, LDBL_EXP_BIT = 16, hence
+ LDBL_TOTAL_BIT = 80 bits, i.e. 10 bytes of consecutive memory, but
+ sizeof (long double) = 12 or = 16. */
+#define SIZEOF_FLT ((FLT_TOTAL_BIT + CHAR_BIT - 1) / CHAR_BIT)
+#define SIZEOF_DBL ((DBL_TOTAL_BIT + CHAR_BIT - 1) / CHAR_BIT)
+#define SIZEOF_LDBL ((LDBL_TOTAL_BIT + CHAR_BIT - 1) / CHAR_BIT)
+
+/* Verify that SIZEOF_FLT <= sizeof (float) etc. */
+typedef int verify_sizeof_flt[SIZEOF_FLT <= sizeof (float) ? 1 : -1];
+typedef int verify_sizeof_dbl[SIZEOF_DBL <= sizeof (double) ? 1 : - 1];
+typedef int verify_sizeof_ldbl[SIZEOF_LDBL <= sizeof (long double) ? 1 : - 1];
+
+#endif /* _FLOATPLUS_H */
diff --git a/lib/float.c b/lib/float.c
new file mode 100644
index 0000000..1bad2ee
--- /dev/null
+++ b/lib/float.c
@@ -0,0 +1,33 @@
+/* Auxiliary definitions for <float.h>.
+ Copyright (C) 2011-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2011.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <float.h>
+
+#if (defined _ARCH_PPC || defined _POWER) && (defined _AIX || defined __linux__) && (LDBL_MANT_DIG == 106) && defined __GNUC__
+const union gl_long_double_union gl_LDBL_MAX =
+ { { DBL_MAX, DBL_MAX / (double)134217728UL / (double)134217728UL } };
+#elif defined __i386__
+const union gl_long_double_union gl_LDBL_MAX =
+ { { 0xFFFFFFFF, 0xFFFFFFFF, 32766 } };
+#else
+/* This declaration is solely to ensure that after preprocessing
+ this file is never empty. */
+typedef int dummy;
+#endif
diff --git a/lib/float.in.h b/lib/float.in.h
new file mode 100644
index 0000000..0b93d90
--- /dev/null
+++ b/lib/float.in.h
@@ -0,0 +1,188 @@
+/* A correct <float.h>.
+
+ Copyright (C) 2007-2016 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _@GUARD_PREFIX@_FLOAT_H
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+/* The include_next requires a split double-inclusion guard. */
+#@INCLUDE_NEXT@ @NEXT_FLOAT_H@
+
+#ifndef _@GUARD_PREFIX@_FLOAT_H
+#define _@GUARD_PREFIX@_FLOAT_H
+
+/* 'long double' properties. */
+
+#if defined __i386__ && (defined __BEOS__ || defined __OpenBSD__)
+/* Number of mantissa units, in base FLT_RADIX. */
+# undef LDBL_MANT_DIG
+# define LDBL_MANT_DIG 64
+/* Number of decimal digits that is sufficient for representing a number. */
+# undef LDBL_DIG
+# define LDBL_DIG 18
+/* x-1 where x is the smallest representable number > 1. */
+# undef LDBL_EPSILON
+# define LDBL_EPSILON 1.0842021724855044340E-19L
+/* Minimum e such that FLT_RADIX^(e-1) is a normalized number. */
+# undef LDBL_MIN_EXP
+# define LDBL_MIN_EXP (-16381)
+/* Maximum e such that FLT_RADIX^(e-1) is a representable finite number. */
+# undef LDBL_MAX_EXP
+# define LDBL_MAX_EXP 16384
+/* Minimum positive normalized number. */
+# undef LDBL_MIN
+# define LDBL_MIN 3.3621031431120935063E-4932L
+/* Maximum representable finite number. */
+# undef LDBL_MAX
+# define LDBL_MAX 1.1897314953572317650E+4932L
+/* Minimum e such that 10^e is in the range of normalized numbers. */
+# undef LDBL_MIN_10_EXP
+# define LDBL_MIN_10_EXP (-4931)
+/* Maximum e such that 10^e is in the range of representable finite numbers. */
+# undef LDBL_MAX_10_EXP
+# define LDBL_MAX_10_EXP 4932
+#endif
+
+/* On FreeBSD/x86 6.4, the 'long double' type really has only 53 bits of
+ precision in the compiler but 64 bits of precision at runtime. See
+ <http://lists.gnu.org/archive/html/bug-gnulib/2008-07/msg00063.html>. */
+#if defined __i386__ && defined __FreeBSD__
+/* Number of mantissa units, in base FLT_RADIX. */
+# undef LDBL_MANT_DIG
+# define LDBL_MANT_DIG 64
+/* Number of decimal digits that is sufficient for representing a number. */
+# undef LDBL_DIG
+# define LDBL_DIG 18
+/* x-1 where x is the smallest representable number > 1. */
+# undef LDBL_EPSILON
+# define LDBL_EPSILON 1.084202172485504434007452800869941711426e-19L /* 2^-63 */
+/* Minimum e such that FLT_RADIX^(e-1) is a normalized number. */
+# undef LDBL_MIN_EXP
+# define LDBL_MIN_EXP (-16381)
+/* Maximum e such that FLT_RADIX^(e-1) is a representable finite number. */
+# undef LDBL_MAX_EXP
+# define LDBL_MAX_EXP 16384
+/* Minimum positive normalized number. */
+# undef LDBL_MIN
+# define LDBL_MIN 3.3621031431120935E-4932L /* = 0x1p-16382L */
+/* Maximum representable finite number. */
+# undef LDBL_MAX
+/* LDBL_MAX is represented as { 0xFFFFFFFF, 0xFFFFFFFF, 32766 }.
+ But the largest literal that GCC allows us to write is
+ 0x0.fffffffffffff8p16384L = { 0xFFFFF800, 0xFFFFFFFF, 32766 }.
+ So, define it like this through a reference to an external variable
+
+ const unsigned int LDBL_MAX[3] = { 0xFFFFFFFF, 0xFFFFFFFF, 32766 };
+ extern const long double LDBL_MAX;
+
+ Unfortunately, this is not a constant expression. */
+union gl_long_double_union
+ {
+ struct { unsigned int lo; unsigned int hi; unsigned int exponent; } xd;
+ long double ld;
+ };
+extern const union gl_long_double_union gl_LDBL_MAX;
+# define LDBL_MAX (gl_LDBL_MAX.ld)
+/* Minimum e such that 10^e is in the range of normalized numbers. */
+# undef LDBL_MIN_10_EXP
+# define LDBL_MIN_10_EXP (-4931)
+/* Maximum e such that 10^e is in the range of representable finite numbers. */
+# undef LDBL_MAX_10_EXP
+# define LDBL_MAX_10_EXP 4932
+#endif
+
+/* On AIX 7.1 with gcc 4.2, the values of LDBL_MIN_EXP, LDBL_MIN, LDBL_MAX are
+ wrong.
+ On Linux/PowerPC with gcc 4.4, the value of LDBL_MAX is wrong. */
+#if (defined _ARCH_PPC || defined _POWER) && defined _AIX && (LDBL_MANT_DIG == 106) && defined __GNUC__
+# undef LDBL_MIN_EXP
+# define LDBL_MIN_EXP DBL_MIN_EXP
+# undef LDBL_MIN_10_EXP
+# define LDBL_MIN_10_EXP DBL_MIN_10_EXP
+# undef LDBL_MIN
+# define LDBL_MIN 2.22507385850720138309023271733240406422e-308L /* DBL_MIN = 2^-1022 */
+#endif
+#if (defined _ARCH_PPC || defined _POWER) && (defined _AIX || defined __linux__) && (LDBL_MANT_DIG == 106) && defined __GNUC__
+# undef LDBL_MAX
+/* LDBL_MAX is represented as { 0x7FEFFFFF, 0xFFFFFFFF, 0x7C8FFFFF, 0xFFFFFFFF }.
+ It is not easy to define:
+ #define LDBL_MAX 1.79769313486231580793728971405302307166e308L
+ is too small, whereas
+ #define LDBL_MAX 1.79769313486231580793728971405302307167e308L
+ is too large. Apparently a bug in GCC decimal-to-binary conversion.
+ Also, I can't get values larger than
+ #define LDBL63 ((long double) (1ULL << 63))
+ #define LDBL882 (LDBL63 * LDBL63 * LDBL63 * LDBL63 * LDBL63 * LDBL63 * LDBL63 * LDBL63 * LDBL63 * LDBL63 * LDBL63 * LDBL63 * LDBL63 * LDBL63)
+ #define LDBL945 (LDBL63 * LDBL63 * LDBL63 * LDBL63 * LDBL63 * LDBL63 * LDBL63 * LDBL63 * LDBL63 * LDBL63 * LDBL63 * LDBL63 * LDBL63 * LDBL63 * LDBL63)
+ #define LDBL1008 (LDBL63 * LDBL63 * LDBL63 * LDBL63 * LDBL63 * LDBL63 * LDBL63 * LDBL63 * LDBL63 * LDBL63 * LDBL63 * LDBL63 * LDBL63 * LDBL63 * LDBL63 * LDBL63)
+ #define LDBL_MAX (LDBL1008 * 65535.0L + LDBL945 * (long double) 9223372036821221375ULL + LDBL882 * (long double) 4611686018427387904ULL)
+ which is represented as { 0x7FEFFFFF, 0xFFFFFFFF, 0x7C8FFFFF, 0xF8000000 }.
+ So, define it like this through a reference to an external variable
+
+ const double LDBL_MAX[2] = { DBL_MAX, DBL_MAX / (double)134217728UL / (double)134217728UL };
+ extern const long double LDBL_MAX;
+
+ or through a pointer cast
+
+ #define LDBL_MAX \
+ (*(const long double *) (double[]) { DBL_MAX, DBL_MAX / (double)134217728UL / (double)134217728UL })
+
+ Unfortunately, this is not a constant expression, and the latter expression
+ does not work well when GCC is optimizing.. */
+union gl_long_double_union
+ {
+ struct { double hi; double lo; } dd;
+ long double ld;
+ };
+extern const union gl_long_double_union gl_LDBL_MAX;
+# define LDBL_MAX (gl_LDBL_MAX.ld)
+#endif
+
+/* On IRIX 6.5, with cc, the value of LDBL_MANT_DIG is wrong.
+ On IRIX 6.5, with gcc 4.2, the values of LDBL_MIN_EXP, LDBL_MIN, LDBL_EPSILON
+ are wrong. */
+#if defined __sgi && (LDBL_MANT_DIG >= 106)
+# undef LDBL_MANT_DIG
+# define LDBL_MANT_DIG 106
+# if defined __GNUC__
+# undef LDBL_MIN_EXP
+# define LDBL_MIN_EXP DBL_MIN_EXP
+# undef LDBL_MIN_10_EXP
+# define LDBL_MIN_10_EXP DBL_MIN_10_EXP
+# undef LDBL_MIN
+# define LDBL_MIN 2.22507385850720138309023271733240406422e-308L /* DBL_MIN = 2^-1022 */
+# undef LDBL_EPSILON
+# define LDBL_EPSILON 2.46519032881566189191165176650870696773e-32L /* 2^-105 */
+# endif
+#endif
+
+#if @REPLACE_ITOLD@
+/* Pull in a function that fixes the 'int' to 'long double' conversion
+ of glibc 2.7. */
+extern
+# ifdef __cplusplus
+"C"
+# endif
+void _Qp_itoq (long double *, int);
+static void (*_gl_float_fix_itold) (long double *, int) = _Qp_itoq;
+#endif
+
+#endif /* _@GUARD_PREFIX@_FLOAT_H */
+#endif /* _@GUARD_PREFIX@_FLOAT_H */
diff --git a/lib/fnmatch.c b/lib/fnmatch.c
index 02dd365..cae3020 100644
--- a/lib/fnmatch.c
+++ b/lib/fnmatch.c
@@ -1,9 +1,8 @@
-/* Copyright (C) 1991,1992,1993,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007
- Free Software Foundation, Inc.
+/* Copyright (C) 1991-1993, 1996-2007, 2009-2016 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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -12,8 +11,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program; if not, see <http://www.gnu.org/licenses/>. */
#ifndef _LIBC
# include <config.h>
@@ -21,7 +19,7 @@
/* Enable GNU extensions in fnmatch.h. */
#ifndef _GNU_SOURCE
-# define _GNU_SOURCE 1
+# define _GNU_SOURCE 1
#endif
#if ! defined __builtin_expect && __GNUC__ < 3
@@ -43,7 +41,7 @@
(HAVE_WCTYPE_H && HAVE_BTOWC && HAVE_ISWCTYPE \
&& HAVE_WMEMCHR && (HAVE_WMEMCPY || HAVE_WMEMPCPY))
-/* For platform which support the ISO C amendement 1 functionality we
+/* For platform which support the ISO C amendment 1 functionality we
support user defined character classes. */
#if defined _LIBC || WIDE_CHAR_SUPPORT
# include <wctype.h>
@@ -79,21 +77,21 @@ extern int fnmatch (const char *pattern, const char *string, int flags);
Library, but also included in many other GNU distributions. Compiling
and linking in this code is a waste when using the GNU C library
(especially if it is a shared library). Rather than having every GNU
- program understand `configure --with-gnu-libc' and omit the object files,
+ program understand 'configure --with-gnu-libc' and omit the object files,
it is simpler to just do this in the source for each such file. */
#if defined _LIBC || !defined __GNU_LIBRARY__ || !HAVE_FNMATCH_GNU
-# if ! (defined isblank || HAVE_DECL_ISBLANK)
+# if ! (defined isblank || (HAVE_ISBLANK && HAVE_DECL_ISBLANK))
# define isblank(c) ((c) == ' ' || (c) == '\t')
# endif
-# define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
+# define STREQ(s1, s2) (strcmp (s1, s2) == 0)
# if defined _LIBC || WIDE_CHAR_SUPPORT
/* The GNU C library provides support for user-defined character classes
- and the functions from ISO C amendement 1. */
+ and the functions from ISO C amendment 1. */
# ifdef CHARCLASS_NAME_MAX
# define CHAR_CLASS_MAX_LENGTH CHARCLASS_NAME_MAX
# else
@@ -109,25 +107,25 @@ extern int fnmatch (const char *pattern, const char *string, int flags);
# endif
# ifdef _LIBC
-# define ISWCTYPE(WC, WT) __iswctype (WC, WT)
+# define ISWCTYPE(WC, WT) __iswctype (WC, WT)
# else
-# define ISWCTYPE(WC, WT) iswctype (WC, WT)
+# define ISWCTYPE(WC, WT) iswctype (WC, WT)
# endif
# if (HAVE_MBSTATE_T && HAVE_MBSRTOWCS) || _LIBC
/* In this case we are implementing the multibyte character handling. */
-# define HANDLE_MULTIBYTE 1
+# define HANDLE_MULTIBYTE 1
# endif
# else
-# define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
-
-# define IS_CHAR_CLASS(string) \
- (STREQ (string, "alpha") || STREQ (string, "upper") \
- || STREQ (string, "lower") || STREQ (string, "digit") \
- || STREQ (string, "alnum") || STREQ (string, "xdigit") \
- || STREQ (string, "space") || STREQ (string, "print") \
- || STREQ (string, "punct") || STREQ (string, "graph") \
+# define CHAR_CLASS_MAX_LENGTH 6 /* Namely, 'xdigit'. */
+
+# define IS_CHAR_CLASS(string) \
+ (STREQ (string, "alpha") || STREQ (string, "upper") \
+ || STREQ (string, "lower") || STREQ (string, "digit") \
+ || STREQ (string, "alnum") || STREQ (string, "xdigit") \
+ || STREQ (string, "space") || STREQ (string, "print") \
+ || STREQ (string, "punct") || STREQ (string, "graph") \
|| STREQ (string, "cntrl") || STREQ (string, "blank"))
# endif
@@ -145,17 +143,17 @@ static int posixly_correct;
/* Note that this evaluates C many times. */
# define FOLD(c) ((flags & FNM_CASEFOLD) ? tolower (c) : (c))
-# define CHAR char
-# define UCHAR unsigned char
-# define INT int
-# define FCT internal_fnmatch
-# define EXT ext_match
-# define END end_pattern
-# define L_(CS) CS
+# define CHAR char
+# define UCHAR unsigned char
+# define INT int
+# define FCT internal_fnmatch
+# define EXT ext_match
+# define END end_pattern
+# define L_(CS) CS
# ifdef _LIBC
-# define BTOWC(C) __btowc (C)
+# define BTOWC(C) __btowc (C)
# else
-# define BTOWC(C) btowc (C)
+# define BTOWC(C) btowc (C)
# endif
# define STRLEN(S) strlen (S)
# define STRCAT(D, S) strcat (D, S)
@@ -169,20 +167,19 @@ static int posixly_correct;
# endif
# endif
# define MEMCHR(S, C, N) memchr (S, C, N)
-# define STRCOLL(S1, S2) strcoll (S1, S2)
# include "fnmatch_loop.c"
# if HANDLE_MULTIBYTE
# define FOLD(c) ((flags & FNM_CASEFOLD) ? towlower (c) : (c))
-# define CHAR wchar_t
-# define UCHAR wint_t
-# define INT wint_t
-# define FCT internal_fnwmatch
-# define EXT ext_wmatch
-# define END end_wpattern
-# define L_(CS) L##CS
-# define BTOWC(C) (C)
+# define CHAR wchar_t
+# define UCHAR wint_t
+# define INT wint_t
+# define FCT internal_fnwmatch
+# define EXT ext_wmatch
+# define END end_wpattern
+# define L_(CS) L##CS
+# define BTOWC(C) (C)
# ifdef _LIBC
# define STRLEN(S) __wcslen (S)
# define STRCAT(D, S) __wcscat (D, S)
@@ -197,7 +194,6 @@ static int posixly_correct;
# endif
# endif
# define MEMCHR(S, C, N) wmemchr (S, C, N)
-# define STRCOLL(S1, S2) wcscoll (S1, S2)
# define WIDE_CHAR_VERSION 1
# undef IS_CHAR_CLASS
@@ -218,40 +214,40 @@ is_char_class (const wchar_t *wcs)
/* Test for a printable character from the portable character set. */
# ifdef _LIBC
if (*wcs < 0x20 || *wcs > 0x7e
- || *wcs == 0x24 || *wcs == 0x40 || *wcs == 0x60)
- return (wctype_t) 0;
+ || *wcs == 0x24 || *wcs == 0x40 || *wcs == 0x60)
+ return (wctype_t) 0;
# else
switch (*wcs)
- {
- case L' ': case L'!': case L'"': case L'#': case L'%':
- case L'&': case L'\'': case L'(': case L')': case L'*':
- case L'+': case L',': case L'-': case L'.': case L'/':
- case L'0': case L'1': case L'2': case L'3': case L'4':
- case L'5': case L'6': case L'7': case L'8': case L'9':
- case L':': case L';': case L'<': case L'=': case L'>':
- case L'?':
- case L'A': case L'B': case L'C': case L'D': case L'E':
- case L'F': case L'G': case L'H': case L'I': case L'J':
- case L'K': case L'L': case L'M': case L'N': case L'O':
- case L'P': case L'Q': case L'R': case L'S': case L'T':
- case L'U': case L'V': case L'W': case L'X': case L'Y':
- case L'Z':
- case L'[': case L'\\': case L']': case L'^': case L'_':
- case L'a': case L'b': case L'c': case L'd': case L'e':
- case L'f': case L'g': case L'h': case L'i': case L'j':
- case L'k': case L'l': case L'm': case L'n': case L'o':
- case L'p': case L'q': case L'r': case L's': case L't':
- case L'u': case L'v': case L'w': case L'x': case L'y':
- case L'z': case L'{': case L'|': case L'}': case L'~':
- break;
- default:
- return (wctype_t) 0;
- }
+ {
+ case L' ': case L'!': case L'"': case L'#': case L'%':
+ case L'&': case L'\'': case L'(': case L')': case L'*':
+ case L'+': case L',': case L'-': case L'.': case L'/':
+ case L'0': case L'1': case L'2': case L'3': case L'4':
+ case L'5': case L'6': case L'7': case L'8': case L'9':
+ case L':': case L';': case L'<': case L'=': case L'>':
+ case L'?':
+ case L'A': case L'B': case L'C': case L'D': case L'E':
+ case L'F': case L'G': case L'H': case L'I': case L'J':
+ case L'K': case L'L': case L'M': case L'N': case L'O':
+ case L'P': case L'Q': case L'R': case L'S': case L'T':
+ case L'U': case L'V': case L'W': case L'X': case L'Y':
+ case L'Z':
+ case L'[': case L'\\': case L']': case L'^': case L'_':
+ case L'a': case L'b': case L'c': case L'd': case L'e':
+ case L'f': case L'g': case L'h': case L'i': case L'j':
+ case L'k': case L'l': case L'm': case L'n': case L'o':
+ case L'p': case L'q': case L'r': case L's': case L't':
+ case L'u': case L'v': case L'w': case L'x': case L'y':
+ case L'z': case L'{': case L'|': case L'}': case L'~':
+ break;
+ default:
+ return (wctype_t) 0;
+ }
# endif
/* Avoid overrunning the buffer. */
if (cp == s + CHAR_CLASS_MAX_LENGTH)
- return (wctype_t) 0;
+ return (wctype_t) 0;
*cp++ = (char) *wcs++;
}
@@ -287,58 +283,58 @@ fnmatch (const char *pattern, const char *string, int flags)
int res;
/* Calculate the size needed to convert the strings to
- wide characters. */
+ wide characters. */
memset (&ps, '\0', sizeof (ps));
patsize = mbsrtowcs (NULL, &pattern, 0, &ps) + 1;
if (__builtin_expect (patsize != 0, 1))
- {
- assert (mbsinit (&ps));
- strsize = mbsrtowcs (NULL, &string, 0, &ps) + 1;
- if (__builtin_expect (strsize != 0, 1))
- {
- assert (mbsinit (&ps));
- totsize = patsize + strsize;
- if (__builtin_expect (! (patsize <= totsize
- && totsize <= SIZE_MAX / sizeof (wchar_t)),
- 0))
- {
- errno = ENOMEM;
- return -1;
- }
-
- /* Allocate room for the wide characters. */
- if (__builtin_expect (totsize < ALLOCA_LIMIT, 1))
- wpattern = (wchar_t *) alloca (totsize * sizeof (wchar_t));
- else
- {
- wpattern = malloc (totsize * sizeof (wchar_t));
- if (__builtin_expect (! wpattern, 0))
- {
- errno = ENOMEM;
- return -1;
- }
- }
- wstring = wpattern + patsize;
-
- /* Convert the strings into wide characters. */
- mbsrtowcs (wpattern, &pattern, patsize, &ps);
- assert (mbsinit (&ps));
- mbsrtowcs (wstring, &string, strsize, &ps);
-
- res = internal_fnwmatch (wpattern, wstring, wstring + strsize - 1,
- flags & FNM_PERIOD, flags);
-
- if (__builtin_expect (! (totsize < ALLOCA_LIMIT), 0))
- free (wpattern);
- return res;
- }
- }
+ {
+ assert (mbsinit (&ps));
+ strsize = mbsrtowcs (NULL, &string, 0, &ps) + 1;
+ if (__builtin_expect (strsize != 0, 1))
+ {
+ assert (mbsinit (&ps));
+ totsize = patsize + strsize;
+ if (__builtin_expect (! (patsize <= totsize
+ && totsize <= SIZE_MAX / sizeof (wchar_t)),
+ 0))
+ {
+ errno = ENOMEM;
+ return -1;
+ }
+
+ /* Allocate room for the wide characters. */
+ if (__builtin_expect (totsize < ALLOCA_LIMIT, 1))
+ wpattern = (wchar_t *) alloca (totsize * sizeof (wchar_t));
+ else
+ {
+ wpattern = malloc (totsize * sizeof (wchar_t));
+ if (__builtin_expect (! wpattern, 0))
+ {
+ errno = ENOMEM;
+ return -1;
+ }
+ }
+ wstring = wpattern + patsize;
+
+ /* Convert the strings into wide characters. */
+ mbsrtowcs (wpattern, &pattern, patsize, &ps);
+ assert (mbsinit (&ps));
+ mbsrtowcs (wstring, &string, strsize, &ps);
+
+ res = internal_fnwmatch (wpattern, wstring, wstring + strsize - 1,
+ flags & FNM_PERIOD, flags);
+
+ if (__builtin_expect (! (totsize < ALLOCA_LIMIT), 0))
+ free (wpattern);
+ return res;
+ }
+ }
}
# endif /* HANDLE_MULTIBYTE */
return internal_fnmatch (pattern, string, string + strlen (string),
- flags & FNM_PERIOD, flags);
+ flags & FNM_PERIOD, flags);
}
# ifdef _LIBC
@@ -351,4 +347,4 @@ compat_symbol (libc, __fnmatch_old, fnmatch, GLIBC_2_0);
libc_hidden_ver (__fnmatch, fnmatch)
# endif
-#endif /* _LIBC or not __GNU_LIBRARY__. */
+#endif /* _LIBC or not __GNU_LIBRARY__. */
diff --git a/lib/fnmatch.in.h b/lib/fnmatch.in.h
new file mode 100644
index 0000000..890ee56
--- /dev/null
+++ b/lib/fnmatch.in.h
@@ -0,0 +1,67 @@
+/* Copyright (C) 1991-1993, 1996-1999, 2001-2003, 2005, 2007, 2009-2016 Free
+ Software Foundation, Inc.
+
+ This file is part of the GNU C Library.
+
+ 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, 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _FNMATCH_H
+#define _FNMATCH_H 1
+
+/* The definition of _GL_ARG_NONNULL is copied here. */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* We #undef these before defining them because some losing systems
+ (HP-UX A.08.07 for example) define these in <unistd.h>. */
+#undef FNM_PATHNAME
+#undef FNM_NOESCAPE
+#undef FNM_PERIOD
+
+/* Bits set in the FLAGS argument to 'fnmatch'. */
+#define FNM_PATHNAME (1 << 0) /* No wildcard can ever match '/'. */
+#define FNM_NOESCAPE (1 << 1) /* Backslashes don't quote special chars. */
+#define FNM_PERIOD (1 << 2) /* Leading '.' is matched only explicitly. */
+
+#if !defined _POSIX_C_SOURCE || _POSIX_C_SOURCE < 2 || defined _GNU_SOURCE
+# define FNM_FILE_NAME FNM_PATHNAME /* Preferred GNU name. */
+# define FNM_LEADING_DIR (1 << 3) /* Ignore '/...' after a match. */
+# define FNM_CASEFOLD (1 << 4) /* Compare without regard to case. */
+# define FNM_EXTMATCH (1 << 5) /* Use ksh-like extended matching. */
+#endif
+
+/* Value returned by 'fnmatch' if STRING does not match PATTERN. */
+#define FNM_NOMATCH 1
+
+/* This value is returned if the implementation does not support
+ 'fnmatch'. Since this is not the case here it will never be
+ returned but the conformance test suites still require the symbol
+ to be defined. */
+#ifdef _XOPEN_SOURCE
+# define FNM_NOSYS (-1)
+#endif
+
+/* Match NAME against the file name pattern PATTERN,
+ returning zero if it matches, FNM_NOMATCH if not. */
+extern int fnmatch (const char *__pattern, const char *__name,
+ int __flags)
+ _GL_ARG_NONNULL ((1, 2));
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* fnmatch.h */
diff --git a/lib/fnmatch_.h b/lib/fnmatch_.h
deleted file mode 100644
index b086b45..0000000
--- a/lib/fnmatch_.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/* Copyright (C) 1991, 1992, 1993, 1996, 1997, 1998, 1999, 2001, 2002, 2003,
- 2005, 2007 Free Software Foundation, Inc.
-
- This file is part of the GNU C Library.
-
- 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-#ifndef _FNMATCH_H
-#define _FNMATCH_H 1
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* We #undef these before defining them because some losing systems
- (HP-UX A.08.07 for example) define these in <unistd.h>. */
-#undef FNM_PATHNAME
-#undef FNM_NOESCAPE
-#undef FNM_PERIOD
-
-/* Bits set in the FLAGS argument to `fnmatch'. */
-#define FNM_PATHNAME (1 << 0) /* No wildcard can ever match `/'. */
-#define FNM_NOESCAPE (1 << 1) /* Backslashes don't quote special chars. */
-#define FNM_PERIOD (1 << 2) /* Leading `.' is matched only explicitly. */
-
-#if !defined _POSIX_C_SOURCE || _POSIX_C_SOURCE < 2 || defined _GNU_SOURCE
-# define FNM_FILE_NAME FNM_PATHNAME /* Preferred GNU name. */
-# define FNM_LEADING_DIR (1 << 3) /* Ignore `/...' after a match. */
-# define FNM_CASEFOLD (1 << 4) /* Compare without regard to case. */
-# define FNM_EXTMATCH (1 << 5) /* Use ksh-like extended matching. */
-#endif
-
-/* Value returned by `fnmatch' if STRING does not match PATTERN. */
-#define FNM_NOMATCH 1
-
-/* This value is returned if the implementation does not support
- `fnmatch'. Since this is not the case here it will never be
- returned but the conformance test suites still require the symbol
- to be defined. */
-#ifdef _XOPEN_SOURCE
-# define FNM_NOSYS (-1)
-#endif
-
-/* Match NAME against the file name pattern PATTERN,
- returning zero if it matches, FNM_NOMATCH if not. */
-extern int fnmatch (const char *__pattern, const char *__name,
- int __flags);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* fnmatch.h */
diff --git a/lib/fnmatch_loop.c b/lib/fnmatch_loop.c
index d1008c2..e613c91 100644
--- a/lib/fnmatch_loop.c
+++ b/lib/fnmatch_loop.c
@@ -1,10 +1,9 @@
-/* Copyright (C) 1991,1992,1993,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006
- Free Software Foundation, Inc.
+/* Copyright (C) 1991-1993, 1996-2006, 2009-2016 Free Software Foundation, Inc.
This file is part of the GNU C Library.
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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -13,13 +12,12 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program; if not, see <http://www.gnu.org/licenses/>. */
/* Match STRING against the file name pattern PATTERN, returning zero if
it matches, nonzero if not. */
static int EXT (INT opt, const CHAR *pattern, const CHAR *string,
- const CHAR *string_end, bool no_leading_period, int flags)
+ const CHAR *string_end, bool no_leading_period, int flags)
internal_function;
static const CHAR *END (const CHAR *patternp) internal_function;
@@ -46,310 +44,314 @@ FCT (const CHAR *pattern, const CHAR *string, const CHAR *string_end,
c = FOLD (c);
switch (c)
- {
- case L_('?'):
- if (__builtin_expect (flags & FNM_EXTMATCH, 0) && *p == '(')
- {
- int res;
-
- res = EXT (c, p, n, string_end, no_leading_period,
- flags);
- if (res != -1)
- return res;
- }
-
- if (n == string_end)
- return FNM_NOMATCH;
- else if (*n == L_('/') && (flags & FNM_FILE_NAME))
- return FNM_NOMATCH;
- else if (*n == L_('.') && no_leading_period)
- return FNM_NOMATCH;
- break;
-
- case L_('\\'):
- if (!(flags & FNM_NOESCAPE))
- {
- c = *p++;
- if (c == L_('\0'))
- /* Trailing \ loses. */
- return FNM_NOMATCH;
- c = FOLD (c);
- }
- if (n == string_end || FOLD ((UCHAR) *n) != c)
- return FNM_NOMATCH;
- break;
-
- case L_('*'):
- if (__builtin_expect (flags & FNM_EXTMATCH, 0) && *p == '(')
- {
- int res;
-
- res = EXT (c, p, n, string_end, no_leading_period,
- flags);
- if (res != -1)
- return res;
- }
-
- if (n != string_end && *n == L_('.') && no_leading_period)
- return FNM_NOMATCH;
-
- for (c = *p++; c == L_('?') || c == L_('*'); c = *p++)
- {
- if (*p == L_('(') && (flags & FNM_EXTMATCH) != 0)
- {
- const CHAR *endp = END (p);
- if (endp != p)
- {
- /* This is a pattern. Skip over it. */
- p = endp;
- continue;
- }
- }
-
- if (c == L_('?'))
- {
- /* A ? needs to match one character. */
- if (n == string_end)
- /* There isn't another character; no match. */
- return FNM_NOMATCH;
- else if (*n == L_('/')
- && __builtin_expect (flags & FNM_FILE_NAME, 0))
- /* A slash does not match a wildcard under
- FNM_FILE_NAME. */
- return FNM_NOMATCH;
- else
- /* One character of the string is consumed in matching
- this ? wildcard, so *??? won't match if there are
- less than three characters. */
- ++n;
- }
- }
-
- if (c == L_('\0'))
- /* The wildcard(s) is/are the last element of the pattern.
- If the name is a file name and contains another slash
- this means it cannot match, unless the FNM_LEADING_DIR
- flag is set. */
- {
- int result = (flags & FNM_FILE_NAME) == 0 ? 0 : FNM_NOMATCH;
-
- if (flags & FNM_FILE_NAME)
- {
- if (flags & FNM_LEADING_DIR)
- result = 0;
- else
- {
- if (MEMCHR (n, L_('/'), string_end - n) == NULL)
- result = 0;
- }
- }
-
- return result;
- }
- else
- {
- const CHAR *endp;
-
- endp = MEMCHR (n, (flags & FNM_FILE_NAME) ? L_('/') : L_('\0'),
- string_end - n);
- if (endp == NULL)
- endp = string_end;
-
- if (c == L_('[')
- || (__builtin_expect (flags & FNM_EXTMATCH, 0) != 0
- && (c == L_('@') || c == L_('+') || c == L_('!'))
- && *p == L_('(')))
- {
- int flags2 = ((flags & FNM_FILE_NAME)
- ? flags : (flags & ~FNM_PERIOD));
- bool no_leading_period2 = no_leading_period;
-
- for (--p; n < endp; ++n, no_leading_period2 = false)
- if (FCT (p, n, string_end, no_leading_period2, flags2)
- == 0)
- return 0;
- }
- else if (c == L_('/') && (flags & FNM_FILE_NAME))
- {
- while (n < string_end && *n != L_('/'))
- ++n;
- if (n < string_end && *n == L_('/')
- && (FCT (p, n + 1, string_end, flags & FNM_PERIOD, flags)
- == 0))
- return 0;
- }
- else
- {
- int flags2 = ((flags & FNM_FILE_NAME)
- ? flags : (flags & ~FNM_PERIOD));
- int no_leading_period2 = no_leading_period;
-
- if (c == L_('\\') && !(flags & FNM_NOESCAPE))
- c = *p;
- c = FOLD (c);
- for (--p; n < endp; ++n, no_leading_period2 = false)
- if (FOLD ((UCHAR) *n) == c
- && (FCT (p, n, string_end, no_leading_period2, flags2)
- == 0))
- return 0;
- }
- }
-
- /* If we come here no match is possible with the wildcard. */
- return FNM_NOMATCH;
-
- case L_('['):
- {
- /* Nonzero if the sense of the character class is inverted. */
- register bool not;
- CHAR cold;
- UCHAR fn;
-
- if (posixly_correct == 0)
- posixly_correct = getenv ("POSIXLY_CORRECT") != NULL ? 1 : -1;
-
- if (n == string_end)
- return FNM_NOMATCH;
-
- if (*n == L_('.') && no_leading_period)
- return FNM_NOMATCH;
-
- if (*n == L_('/') && (flags & FNM_FILE_NAME))
- /* `/' cannot be matched. */
- return FNM_NOMATCH;
-
- not = (*p == L_('!') || (posixly_correct < 0 && *p == L_('^')));
- if (not)
- ++p;
-
- fn = FOLD ((UCHAR) *n);
-
- c = *p++;
- for (;;)
- {
- if (!(flags & FNM_NOESCAPE) && c == L_('\\'))
- {
- if (*p == L_('\0'))
- return FNM_NOMATCH;
- c = FOLD ((UCHAR) *p);
- ++p;
-
- goto normal_bracket;
- }
- else if (c == L_('[') && *p == L_(':'))
- {
- /* Leave room for the null. */
- CHAR str[CHAR_CLASS_MAX_LENGTH + 1];
- size_t c1 = 0;
+ {
+ case L_('?'):
+ if (__builtin_expect (flags & FNM_EXTMATCH, 0) && *p == '(')
+ {
+ int res;
+
+ res = EXT (c, p, n, string_end, no_leading_period,
+ flags);
+ if (res != -1)
+ return res;
+ }
+
+ if (n == string_end)
+ return FNM_NOMATCH;
+ else if (*n == L_('/') && (flags & FNM_FILE_NAME))
+ return FNM_NOMATCH;
+ else if (*n == L_('.') && no_leading_period)
+ return FNM_NOMATCH;
+ break;
+
+ case L_('\\'):
+ if (!(flags & FNM_NOESCAPE))
+ {
+ c = *p++;
+ if (c == L_('\0'))
+ /* Trailing \ loses. */
+ return FNM_NOMATCH;
+ c = FOLD (c);
+ }
+ if (n == string_end || FOLD ((UCHAR) *n) != c)
+ return FNM_NOMATCH;
+ break;
+
+ case L_('*'):
+ if (__builtin_expect (flags & FNM_EXTMATCH, 0) && *p == '(')
+ {
+ int res;
+
+ res = EXT (c, p, n, string_end, no_leading_period,
+ flags);
+ if (res != -1)
+ return res;
+ }
+
+ if (n != string_end && *n == L_('.') && no_leading_period)
+ return FNM_NOMATCH;
+
+ for (c = *p++; c == L_('?') || c == L_('*'); c = *p++)
+ {
+ if (*p == L_('(') && (flags & FNM_EXTMATCH) != 0)
+ {
+ const CHAR *endp = END (p);
+ if (endp != p)
+ {
+ /* This is a pattern. Skip over it. */
+ p = endp;
+ continue;
+ }
+ }
+
+ if (c == L_('?'))
+ {
+ /* A ? needs to match one character. */
+ if (n == string_end)
+ /* There isn't another character; no match. */
+ return FNM_NOMATCH;
+ else if (*n == L_('/')
+ && __builtin_expect (flags & FNM_FILE_NAME, 0))
+ /* A slash does not match a wildcard under
+ FNM_FILE_NAME. */
+ return FNM_NOMATCH;
+ else
+ /* One character of the string is consumed in matching
+ this ? wildcard, so *??? won't match if there are
+ less than three characters. */
+ ++n;
+ }
+ }
+
+ if (c == L_('\0'))
+ /* The wildcard(s) is/are the last element of the pattern.
+ If the name is a file name and contains another slash
+ this means it cannot match, unless the FNM_LEADING_DIR
+ flag is set. */
+ {
+ int result = (flags & FNM_FILE_NAME) == 0 ? 0 : FNM_NOMATCH;
+
+ if (flags & FNM_FILE_NAME)
+ {
+ if (flags & FNM_LEADING_DIR)
+ result = 0;
+ else
+ {
+ if (MEMCHR (n, L_('/'), string_end - n) == NULL)
+ result = 0;
+ }
+ }
+
+ return result;
+ }
+ else
+ {
+ const CHAR *endp;
+
+ endp = MEMCHR (n, (flags & FNM_FILE_NAME) ? L_('/') : L_('\0'),
+ string_end - n);
+ if (endp == NULL)
+ endp = string_end;
+
+ if (c == L_('[')
+ || (__builtin_expect (flags & FNM_EXTMATCH, 0) != 0
+ && (c == L_('@') || c == L_('+') || c == L_('!'))
+ && *p == L_('(')))
+ {
+ int flags2 = ((flags & FNM_FILE_NAME)
+ ? flags : (flags & ~FNM_PERIOD));
+ bool no_leading_period2 = no_leading_period;
+
+ for (--p; n < endp; ++n, no_leading_period2 = false)
+ if (FCT (p, n, string_end, no_leading_period2, flags2)
+ == 0)
+ return 0;
+ }
+ else if (c == L_('/') && (flags & FNM_FILE_NAME))
+ {
+ while (n < string_end && *n != L_('/'))
+ ++n;
+ if (n < string_end && *n == L_('/')
+ && (FCT (p, n + 1, string_end, flags & FNM_PERIOD, flags)
+ == 0))
+ return 0;
+ }
+ else
+ {
+ int flags2 = ((flags & FNM_FILE_NAME)
+ ? flags : (flags & ~FNM_PERIOD));
+ int no_leading_period2 = no_leading_period;
+
+ if (c == L_('\\') && !(flags & FNM_NOESCAPE))
+ c = *p;
+ c = FOLD (c);
+ for (--p; n < endp; ++n, no_leading_period2 = false)
+ if (FOLD ((UCHAR) *n) == c
+ && (FCT (p, n, string_end, no_leading_period2, flags2)
+ == 0))
+ return 0;
+ }
+ }
+
+ /* If we come here no match is possible with the wildcard. */
+ return FNM_NOMATCH;
+
+ case L_('['):
+ {
+ /* Nonzero if the sense of the character class is inverted. */
+ const CHAR *p_init = p;
+ const CHAR *n_init = n;
+ register bool not;
+ CHAR cold;
+ UCHAR fn;
+
+ if (posixly_correct == 0)
+ posixly_correct = getenv ("POSIXLY_CORRECT") != NULL ? 1 : -1;
+
+ if (n == string_end)
+ return FNM_NOMATCH;
+
+ if (*n == L_('.') && no_leading_period)
+ return FNM_NOMATCH;
+
+ if (*n == L_('/') && (flags & FNM_FILE_NAME))
+ /* '/' cannot be matched. */
+ return FNM_NOMATCH;
+
+ not = (*p == L_('!') || (posixly_correct < 0 && *p == L_('^')));
+ if (not)
+ ++p;
+
+ fn = FOLD ((UCHAR) *n);
+
+ c = *p++;
+ for (;;)
+ {
+ bool is_range = false;
+
+ if (!(flags & FNM_NOESCAPE) && c == L_('\\'))
+ {
+ if (*p == L_('\0'))
+ return FNM_NOMATCH;
+ c = FOLD ((UCHAR) *p);
+ ++p;
+
+ goto normal_bracket;
+ }
+ else if (c == L_('[') && *p == L_(':'))
+ {
+ /* Leave room for the null. */
+ CHAR str[CHAR_CLASS_MAX_LENGTH + 1];
+ size_t c1 = 0;
#if defined _LIBC || WIDE_CHAR_SUPPORT
- wctype_t wt;
+ wctype_t wt;
#endif
- const CHAR *startp = p;
-
- for (;;)
- {
- if (c1 == CHAR_CLASS_MAX_LENGTH)
- /* The name is too long and therefore the pattern
- is ill-formed. */
- return FNM_NOMATCH;
-
- c = *++p;
- if (c == L_(':') && p[1] == L_(']'))
- {
- p += 2;
- break;
- }
- if (c < L_('a') || c >= L_('z'))
- {
- /* This cannot possibly be a character class name.
- Match it as a normal range. */
- p = startp;
- c = L_('[');
- goto normal_bracket;
- }
- str[c1++] = c;
- }
- str[c1] = L_('\0');
+ const CHAR *startp = p;
+
+ for (;;)
+ {
+ if (c1 == CHAR_CLASS_MAX_LENGTH)
+ /* The name is too long and therefore the pattern
+ is ill-formed. */
+ return FNM_NOMATCH;
+
+ c = *++p;
+ if (c == L_(':') && p[1] == L_(']'))
+ {
+ p += 2;
+ break;
+ }
+ if (c < L_('a') || c >= L_('z'))
+ {
+ /* This cannot possibly be a character class name.
+ Match it as a normal range. */
+ p = startp;
+ c = L_('[');
+ goto normal_bracket;
+ }
+ str[c1++] = c;
+ }
+ str[c1] = L_('\0');
#if defined _LIBC || WIDE_CHAR_SUPPORT
- wt = IS_CHAR_CLASS (str);
- if (wt == 0)
- /* Invalid character class name. */
- return FNM_NOMATCH;
+ wt = IS_CHAR_CLASS (str);
+ if (wt == 0)
+ /* Invalid character class name. */
+ return FNM_NOMATCH;
# if defined _LIBC && ! WIDE_CHAR_VERSION
- /* The following code is glibc specific but does
- there a good job in speeding up the code since
- we can avoid the btowc() call. */
- if (_ISCTYPE ((UCHAR) *n, wt))
- goto matched;
+ /* The following code is glibc specific but does
+ there a good job in speeding up the code since
+ we can avoid the btowc() call. */
+ if (_ISCTYPE ((UCHAR) *n, wt))
+ goto matched;
# else
- if (ISWCTYPE (BTOWC ((UCHAR) *n), wt))
- goto matched;
+ if (ISWCTYPE (BTOWC ((UCHAR) *n), wt))
+ goto matched;
# endif
#else
- if ((STREQ (str, L_("alnum")) && isalnum ((UCHAR) *n))
- || (STREQ (str, L_("alpha")) && isalpha ((UCHAR) *n))
- || (STREQ (str, L_("blank")) && isblank ((UCHAR) *n))
- || (STREQ (str, L_("cntrl")) && iscntrl ((UCHAR) *n))
- || (STREQ (str, L_("digit")) && isdigit ((UCHAR) *n))
- || (STREQ (str, L_("graph")) && isgraph ((UCHAR) *n))
- || (STREQ (str, L_("lower")) && islower ((UCHAR) *n))
- || (STREQ (str, L_("print")) && isprint ((UCHAR) *n))
- || (STREQ (str, L_("punct")) && ispunct ((UCHAR) *n))
- || (STREQ (str, L_("space")) && isspace ((UCHAR) *n))
- || (STREQ (str, L_("upper")) && isupper ((UCHAR) *n))
- || (STREQ (str, L_("xdigit")) && isxdigit ((UCHAR) *n)))
- goto matched;
+ if ((STREQ (str, L_("alnum")) && isalnum ((UCHAR) *n))
+ || (STREQ (str, L_("alpha")) && isalpha ((UCHAR) *n))
+ || (STREQ (str, L_("blank")) && isblank ((UCHAR) *n))
+ || (STREQ (str, L_("cntrl")) && iscntrl ((UCHAR) *n))
+ || (STREQ (str, L_("digit")) && isdigit ((UCHAR) *n))
+ || (STREQ (str, L_("graph")) && isgraph ((UCHAR) *n))
+ || (STREQ (str, L_("lower")) && islower ((UCHAR) *n))
+ || (STREQ (str, L_("print")) && isprint ((UCHAR) *n))
+ || (STREQ (str, L_("punct")) && ispunct ((UCHAR) *n))
+ || (STREQ (str, L_("space")) && isspace ((UCHAR) *n))
+ || (STREQ (str, L_("upper")) && isupper ((UCHAR) *n))
+ || (STREQ (str, L_("xdigit")) && isxdigit ((UCHAR) *n)))
+ goto matched;
#endif
- c = *p++;
- }
+ c = *p++;
+ }
#ifdef _LIBC
- else if (c == L_('[') && *p == L_('='))
- {
- UCHAR str[1];
- uint32_t nrules =
- _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
- const CHAR *startp = p;
-
- c = *++p;
- if (c == L_('\0'))
- {
- p = startp;
- c = L_('[');
- goto normal_bracket;
- }
- str[0] = c;
-
- c = *++p;
- if (c != L_('=') || p[1] != L_(']'))
- {
- p = startp;
- c = L_('[');
- goto normal_bracket;
- }
- p += 2;
-
- if (nrules == 0)
- {
- if ((UCHAR) *n == str[0])
- goto matched;
- }
- else
- {
- const int32_t *table;
+ else if (c == L_('[') && *p == L_('='))
+ {
+ UCHAR str[1];
+ uint32_t nrules =
+ _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
+ const CHAR *startp = p;
+
+ c = *++p;
+ if (c == L_('\0'))
+ {
+ p = startp;
+ c = L_('[');
+ goto normal_bracket;
+ }
+ str[0] = c;
+
+ c = *++p;
+ if (c != L_('=') || p[1] != L_(']'))
+ {
+ p = startp;
+ c = L_('[');
+ goto normal_bracket;
+ }
+ p += 2;
+
+ if (nrules == 0)
+ {
+ if ((UCHAR) *n == str[0])
+ goto matched;
+ }
+ else
+ {
+ const int32_t *table;
# if WIDE_CHAR_VERSION
- const int32_t *weights;
- const int32_t *extra;
+ const int32_t *weights;
+ const int32_t *extra;
# else
- const unsigned char *weights;
- const unsigned char *extra;
+ const unsigned char *weights;
+ const unsigned char *extra;
# endif
- const int32_t *indirect;
- int32_t idx;
- const UCHAR *cp = (const UCHAR *) str;
+ const int32_t *indirect;
+ int32_t idx;
+ const UCHAR *cp = (const UCHAR *) str;
- /* This #include defines a local function! */
+ /* This #include defines a local function! */
# if WIDE_CHAR_VERSION
# include <locale/weightwc.h>
# else
@@ -357,605 +359,613 @@ FCT (const CHAR *pattern, const CHAR *string, const CHAR *string_end,
# endif
# if WIDE_CHAR_VERSION
- table = (const int32_t *)
- _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEWC);
- weights = (const int32_t *)
- _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTWC);
- extra = (const int32_t *)
- _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAWC);
- indirect = (const int32_t *)
- _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTWC);
+ table = (const int32_t *)
+ _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEWC);
+ weights = (const int32_t *)
+ _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTWC);
+ extra = (const int32_t *)
+ _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAWC);
+ indirect = (const int32_t *)
+ _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTWC);
# else
- table = (const int32_t *)
- _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB);
- weights = (const unsigned char *)
- _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTMB);
- extra = (const unsigned char *)
- _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAMB);
- indirect = (const int32_t *)
- _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTMB);
+ table = (const int32_t *)
+ _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB);
+ weights = (const unsigned char *)
+ _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTMB);
+ extra = (const unsigned char *)
+ _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAMB);
+ indirect = (const int32_t *)
+ _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTMB);
# endif
- idx = findidx (&cp);
- if (idx != 0)
- {
- /* We found a table entry. Now see whether the
- character we are currently at has the same
- equivalance class value. */
- int len = weights[idx];
- int32_t idx2;
- const UCHAR *np = (const UCHAR *) n;
-
- idx2 = findidx (&np);
- if (idx2 != 0 && len == weights[idx2])
- {
- int cnt = 0;
-
- while (cnt < len
- && (weights[idx + 1 + cnt]
- == weights[idx2 + 1 + cnt]))
- ++cnt;
-
- if (cnt == len)
- goto matched;
- }
- }
- }
-
- c = *p++;
- }
+ idx = findidx (&cp);
+ if (idx != 0)
+ {
+ /* We found a table entry. Now see whether the
+ character we are currently at has the same
+ equivalence class value. */
+ int len = weights[idx & 0xffffff];
+ int32_t idx2;
+ const UCHAR *np = (const UCHAR *) n;
+
+ idx2 = findidx (&np);
+ if (idx2 != 0
+ && (idx >> 24) == (idx2 >> 24)
+ && len == weights[idx2 & 0xffffff])
+ {
+ int cnt = 0;
+
+ idx &= 0xffffff;
+ idx2 &= 0xffffff;
+
+ while (cnt < len
+ && (weights[idx + 1 + cnt]
+ == weights[idx2 + 1 + cnt]))
+ ++cnt;
+
+ if (cnt == len)
+ goto matched;
+ }
+ }
+ }
+
+ c = *p++;
+ }
#endif
- else if (c == L_('\0'))
- /* [ (unterminated) loses. */
- return FNM_NOMATCH;
- else
- {
- bool is_range = false;
-
+ else if (c == L_('\0'))
+ {
+ /* [ unterminated, treat as normal character. */
+ p = p_init;
+ n = n_init;
+ c = L_('[');
+ goto normal_match;
+ }
+ else
+ {
#ifdef _LIBC
- bool is_seqval = false;
-
- if (c == L_('[') && *p == L_('.'))
- {
- uint32_t nrules =
- _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
- const CHAR *startp = p;
- size_t c1 = 0;
-
- while (1)
- {
- c = *++p;
- if (c == L_('.') && p[1] == L_(']'))
- {
- p += 2;
- break;
- }
- if (c == '\0')
- return FNM_NOMATCH;
- ++c1;
- }
-
- /* We have to handling the symbols differently in
- ranges since then the collation sequence is
- important. */
- is_range = *p == L_('-') && p[1] != L_('\0');
-
- if (nrules == 0)
- {
- /* There are no names defined in the collation
- data. Therefore we only accept the trivial
- names consisting of the character itself. */
- if (c1 != 1)
- return FNM_NOMATCH;
-
- if (!is_range && *n == startp[1])
- goto matched;
-
- cold = startp[1];
- c = *p++;
- }
- else
- {
- int32_t table_size;
- const int32_t *symb_table;
+ bool is_seqval = false;
+
+ if (c == L_('[') && *p == L_('.'))
+ {
+ uint32_t nrules =
+ _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
+ const CHAR *startp = p;
+ size_t c1 = 0;
+
+ while (1)
+ {
+ c = *++p;
+ if (c == L_('.') && p[1] == L_(']'))
+ {
+ p += 2;
+ break;
+ }
+ if (c == '\0')
+ return FNM_NOMATCH;
+ ++c1;
+ }
+
+ /* We have to handling the symbols differently in
+ ranges since then the collation sequence is
+ important. */
+ is_range = *p == L_('-') && p[1] != L_('\0');
+
+ if (nrules == 0)
+ {
+ /* There are no names defined in the collation
+ data. Therefore we only accept the trivial
+ names consisting of the character itself. */
+ if (c1 != 1)
+ return FNM_NOMATCH;
+
+ if (!is_range && *n == startp[1])
+ goto matched;
+
+ cold = startp[1];
+ c = *p++;
+ }
+ else
+ {
+ int32_t table_size;
+ const int32_t *symb_table;
# ifdef WIDE_CHAR_VERSION
- char str[c1];
- size_t strcnt;
+ char str[c1];
+ size_t strcnt;
# else
# define str (startp + 1)
# endif
- const unsigned char *extra;
- int32_t idx;
- int32_t elem;
- int32_t second;
- int32_t hash;
+ const unsigned char *extra;
+ int32_t idx;
+ int32_t elem;
+ int32_t second;
+ int32_t hash;
# ifdef WIDE_CHAR_VERSION
- /* We have to convert the name to a single-byte
- string. This is possible since the names
- consist of ASCII characters and the internal
- representation is UCS4. */
- for (strcnt = 0; strcnt < c1; ++strcnt)
- str[strcnt] = startp[1 + strcnt];
+ /* We have to convert the name to a single-byte
+ string. This is possible since the names
+ consist of ASCII characters and the internal
+ representation is UCS4. */
+ for (strcnt = 0; strcnt < c1; ++strcnt)
+ str[strcnt] = startp[1 + strcnt];
# endif
- table_size =
- _NL_CURRENT_WORD (LC_COLLATE,
- _NL_COLLATE_SYMB_HASH_SIZEMB);
- symb_table = (const int32_t *)
- _NL_CURRENT (LC_COLLATE,
- _NL_COLLATE_SYMB_TABLEMB);
- extra = (const unsigned char *)
- _NL_CURRENT (LC_COLLATE,
- _NL_COLLATE_SYMB_EXTRAMB);
-
- /* Locate the character in the hashing table. */
- hash = elem_hash (str, c1);
-
- idx = 0;
- elem = hash % table_size;
- if (symb_table[2 * elem] != 0)
- {
- second = hash % (table_size - 2) + 1;
-
- do
- {
- /* First compare the hashing value. */
- if (symb_table[2 * elem] == hash
- && (c1
- == extra[symb_table[2 * elem + 1]])
- && memcmp (str,
- &extra[symb_table[2 * elem
- + 1]
- + 1], c1) == 0)
- {
- /* Yep, this is the entry. */
- idx = symb_table[2 * elem + 1];
- idx += 1 + extra[idx];
- break;
- }
-
- /* Next entry. */
- elem += second;
- }
- while (symb_table[2 * elem] != 0);
- }
-
- if (symb_table[2 * elem] != 0)
- {
- /* Compare the byte sequence but only if
- this is not part of a range. */
+ table_size =
+ _NL_CURRENT_WORD (LC_COLLATE,
+ _NL_COLLATE_SYMB_HASH_SIZEMB);
+ symb_table = (const int32_t *)
+ _NL_CURRENT (LC_COLLATE,
+ _NL_COLLATE_SYMB_TABLEMB);
+ extra = (const unsigned char *)
+ _NL_CURRENT (LC_COLLATE,
+ _NL_COLLATE_SYMB_EXTRAMB);
+
+ /* Locate the character in the hashing table. */
+ hash = elem_hash (str, c1);
+
+ idx = 0;
+ elem = hash % table_size;
+ if (symb_table[2 * elem] != 0)
+ {
+ second = hash % (table_size - 2) + 1;
+
+ do
+ {
+ /* First compare the hashing value. */
+ if (symb_table[2 * elem] == hash
+ && (c1
+ == extra[symb_table[2 * elem + 1]])
+ && memcmp (str,
+ &extra[symb_table[2 * elem
+ + 1]
+ + 1], c1) == 0)
+ {
+ /* Yep, this is the entry. */
+ idx = symb_table[2 * elem + 1];
+ idx += 1 + extra[idx];
+ break;
+ }
+
+ /* Next entry. */
+ elem += second;
+ }
+ while (symb_table[2 * elem] != 0);
+ }
+
+ if (symb_table[2 * elem] != 0)
+ {
+ /* Compare the byte sequence but only if
+ this is not part of a range. */
# ifdef WIDE_CHAR_VERSION
- int32_t *wextra;
+ int32_t *wextra;
- idx += 1 + extra[idx];
- /* Adjust for the alignment. */
- idx = (idx + 3) & ~3;
+ idx += 1 + extra[idx];
+ /* Adjust for the alignment. */
+ idx = (idx + 3) & ~3;
- wextra = (int32_t *) &extra[idx + 4];
+ wextra = (int32_t *) &extra[idx + 4];
# endif
- if (! is_range)
- {
+ if (! is_range)
+ {
# ifdef WIDE_CHAR_VERSION
- for (c1 = 0;
- (int32_t) c1 < wextra[idx];
- ++c1)
- if (n[c1] != wextra[1 + c1])
- break;
-
- if ((int32_t) c1 == wextra[idx])
- goto matched;
+ for (c1 = 0;
+ (int32_t) c1 < wextra[idx];
+ ++c1)
+ if (n[c1] != wextra[1 + c1])
+ break;
+
+ if ((int32_t) c1 == wextra[idx])
+ goto matched;
# else
- for (c1 = 0; c1 < extra[idx]; ++c1)
- if (n[c1] != extra[1 + c1])
- break;
+ for (c1 = 0; c1 < extra[idx]; ++c1)
+ if (n[c1] != extra[1 + c1])
+ break;
- if (c1 == extra[idx])
- goto matched;
+ if (c1 == extra[idx])
+ goto matched;
# endif
- }
+ }
- /* Get the collation sequence value. */
- is_seqval = true;
+ /* Get the collation sequence value. */
+ is_seqval = true;
# ifdef WIDE_CHAR_VERSION
- cold = wextra[1 + wextra[idx]];
+ cold = wextra[1 + wextra[idx]];
# else
- /* Adjust for the alignment. */
- idx += 1 + extra[idx];
- idx = (idx + 3) & ~4;
- cold = *((int32_t *) &extra[idx]);
+ /* Adjust for the alignment. */
+ idx += 1 + extra[idx];
+ idx = (idx + 3) & ~4;
+ cold = *((int32_t *) &extra[idx]);
# endif
- c = *p++;
- }
- else if (c1 == 1)
- {
- /* No valid character. Match it as a
- single byte. */
- if (!is_range && *n == str[0])
- goto matched;
-
- cold = str[0];
- c = *p++;
- }
- else
- return FNM_NOMATCH;
- }
- }
- else
+ c = *p++;
+ }
+ else if (c1 == 1)
+ {
+ /* No valid character. Match it as a
+ single byte. */
+ if (!is_range && *n == str[0])
+ goto matched;
+
+ cold = str[0];
+ c = *p++;
+ }
+ else
+ return FNM_NOMATCH;
+ }
+ }
+ else
# undef str
#endif
- {
- c = FOLD (c);
- normal_bracket:
+ {
+ c = FOLD (c);
+ normal_bracket:
- /* We have to handling the symbols differently in
- ranges since then the collation sequence is
- important. */
- is_range = (*p == L_('-') && p[1] != L_('\0')
- && p[1] != L_(']'));
+ /* We have to handling the symbols differently in
+ ranges since then the collation sequence is
+ important. */
+ is_range = (*p == L_('-') && p[1] != L_('\0')
+ && p[1] != L_(']'));
- if (!is_range && c == fn)
- goto matched;
+ if (!is_range && c == fn)
+ goto matched;
#if _LIBC
- /* This is needed if we goto normal_bracket; from
- outside of is_seqval's scope. */
- is_seqval = false;
+ /* This is needed if we goto normal_bracket; from
+ outside of is_seqval's scope. */
+ is_seqval = false;
#endif
- cold = c;
- c = *p++;
- }
+ cold = c;
+ c = *p++;
+ }
- if (c == L_('-') && *p != L_(']'))
- {
+ if (c == L_('-') && *p != L_(']'))
+ {
#if _LIBC
- /* We have to find the collation sequence
- value for C. Collation sequence is nothing
- we can regularly access. The sequence
- value is defined by the order in which the
- definitions of the collation values for the
- various characters appear in the source
- file. A strange concept, nowhere
- documented. */
- uint32_t fcollseq;
- uint32_t lcollseq;
- UCHAR cend = *p++;
+ /* We have to find the collation sequence
+ value for C. Collation sequence is nothing
+ we can regularly access. The sequence
+ value is defined by the order in which the
+ definitions of the collation values for the
+ various characters appear in the source
+ file. A strange concept, nowhere
+ documented. */
+ uint32_t fcollseq;
+ uint32_t lcollseq;
+ UCHAR cend = *p++;
# ifdef WIDE_CHAR_VERSION
- /* Search in the `names' array for the characters. */
- fcollseq = __collseq_table_lookup (collseq, fn);
- if (fcollseq == ~((uint32_t) 0))
- /* XXX We don't know anything about the character
- we are supposed to match. This means we are
- failing. */
- goto range_not_matched;
-
- if (is_seqval)
- lcollseq = cold;
- else
- lcollseq = __collseq_table_lookup (collseq, cold);
+ /* Search in the 'names' array for the characters. */
+ fcollseq = __collseq_table_lookup (collseq, fn);
+ if (fcollseq == ~((uint32_t) 0))
+ /* XXX We don't know anything about the character
+ we are supposed to match. This means we are
+ failing. */
+ goto range_not_matched;
+
+ if (is_seqval)
+ lcollseq = cold;
+ else
+ lcollseq = __collseq_table_lookup (collseq, cold);
# else
- fcollseq = collseq[fn];
- lcollseq = is_seqval ? cold : collseq[(UCHAR) cold];
+ fcollseq = collseq[fn];
+ lcollseq = is_seqval ? cold : collseq[(UCHAR) cold];
# endif
- is_seqval = false;
- if (cend == L_('[') && *p == L_('.'))
- {
- uint32_t nrules =
- _NL_CURRENT_WORD (LC_COLLATE,
- _NL_COLLATE_NRULES);
- const CHAR *startp = p;
- size_t c1 = 0;
-
- while (1)
- {
- c = *++p;
- if (c == L_('.') && p[1] == L_(']'))
- {
- p += 2;
- break;
- }
- if (c == '\0')
- return FNM_NOMATCH;
- ++c1;
- }
-
- if (nrules == 0)
- {
- /* There are no names defined in the
- collation data. Therefore we only
- accept the trivial names consisting
- of the character itself. */
- if (c1 != 1)
- return FNM_NOMATCH;
-
- cend = startp[1];
- }
- else
- {
- int32_t table_size;
- const int32_t *symb_table;
+ is_seqval = false;
+ if (cend == L_('[') && *p == L_('.'))
+ {
+ uint32_t nrules =
+ _NL_CURRENT_WORD (LC_COLLATE,
+ _NL_COLLATE_NRULES);
+ const CHAR *startp = p;
+ size_t c1 = 0;
+
+ while (1)
+ {
+ c = *++p;
+ if (c == L_('.') && p[1] == L_(']'))
+ {
+ p += 2;
+ break;
+ }
+ if (c == '\0')
+ return FNM_NOMATCH;
+ ++c1;
+ }
+
+ if (nrules == 0)
+ {
+ /* There are no names defined in the
+ collation data. Therefore we only
+ accept the trivial names consisting
+ of the character itself. */
+ if (c1 != 1)
+ return FNM_NOMATCH;
+
+ cend = startp[1];
+ }
+ else
+ {
+ int32_t table_size;
+ const int32_t *symb_table;
# ifdef WIDE_CHAR_VERSION
- char str[c1];
- size_t strcnt;
+ char str[c1];
+ size_t strcnt;
# else
# define str (startp + 1)
# endif
- const unsigned char *extra;
- int32_t idx;
- int32_t elem;
- int32_t second;
- int32_t hash;
+ const unsigned char *extra;
+ int32_t idx;
+ int32_t elem;
+ int32_t second;
+ int32_t hash;
# ifdef WIDE_CHAR_VERSION
- /* We have to convert the name to a single-byte
- string. This is possible since the names
- consist of ASCII characters and the internal
- representation is UCS4. */
- for (strcnt = 0; strcnt < c1; ++strcnt)
- str[strcnt] = startp[1 + strcnt];
+ /* We have to convert the name to a single-byte
+ string. This is possible since the names
+ consist of ASCII characters and the internal
+ representation is UCS4. */
+ for (strcnt = 0; strcnt < c1; ++strcnt)
+ str[strcnt] = startp[1 + strcnt];
# endif
- table_size =
- _NL_CURRENT_WORD (LC_COLLATE,
- _NL_COLLATE_SYMB_HASH_SIZEMB);
- symb_table = (const int32_t *)
- _NL_CURRENT (LC_COLLATE,
- _NL_COLLATE_SYMB_TABLEMB);
- extra = (const unsigned char *)
- _NL_CURRENT (LC_COLLATE,
- _NL_COLLATE_SYMB_EXTRAMB);
-
- /* Locate the character in the hashing
+ table_size =
+ _NL_CURRENT_WORD (LC_COLLATE,
+ _NL_COLLATE_SYMB_HASH_SIZEMB);
+ symb_table = (const int32_t *)
+ _NL_CURRENT (LC_COLLATE,
+ _NL_COLLATE_SYMB_TABLEMB);
+ extra = (const unsigned char *)
+ _NL_CURRENT (LC_COLLATE,
+ _NL_COLLATE_SYMB_EXTRAMB);
+
+ /* Locate the character in the hashing
table. */
- hash = elem_hash (str, c1);
-
- idx = 0;
- elem = hash % table_size;
- if (symb_table[2 * elem] != 0)
- {
- second = hash % (table_size - 2) + 1;
-
- do
- {
- /* First compare the hashing value. */
- if (symb_table[2 * elem] == hash
- && (c1
- == extra[symb_table[2 * elem + 1]])
- && memcmp (str,
- &extra[symb_table[2 * elem + 1]
- + 1], c1) == 0)
- {
- /* Yep, this is the entry. */
- idx = symb_table[2 * elem + 1];
- idx += 1 + extra[idx];
- break;
- }
-
- /* Next entry. */
- elem += second;
- }
- while (symb_table[2 * elem] != 0);
- }
-
- if (symb_table[2 * elem] != 0)
- {
- /* Compare the byte sequence but only if
- this is not part of a range. */
+ hash = elem_hash (str, c1);
+
+ idx = 0;
+ elem = hash % table_size;
+ if (symb_table[2 * elem] != 0)
+ {
+ second = hash % (table_size - 2) + 1;
+
+ do
+ {
+ /* First compare the hashing value. */
+ if (symb_table[2 * elem] == hash
+ && (c1
+ == extra[symb_table[2 * elem + 1]])
+ && memcmp (str,
+ &extra[symb_table[2 * elem + 1]
+ + 1], c1) == 0)
+ {
+ /* Yep, this is the entry. */
+ idx = symb_table[2 * elem + 1];
+ idx += 1 + extra[idx];
+ break;
+ }
+
+ /* Next entry. */
+ elem += second;
+ }
+ while (symb_table[2 * elem] != 0);
+ }
+
+ if (symb_table[2 * elem] != 0)
+ {
+ /* Compare the byte sequence but only if
+ this is not part of a range. */
# ifdef WIDE_CHAR_VERSION
- int32_t *wextra;
+ int32_t *wextra;
- idx += 1 + extra[idx];
- /* Adjust for the alignment. */
- idx = (idx + 3) & ~4;
+ idx += 1 + extra[idx];
+ /* Adjust for the alignment. */
+ idx = (idx + 3) & ~4;
- wextra = (int32_t *) &extra[idx + 4];
+ wextra = (int32_t *) &extra[idx + 4];
# endif
- /* Get the collation sequence value. */
- is_seqval = true;
+ /* Get the collation sequence value. */
+ is_seqval = true;
# ifdef WIDE_CHAR_VERSION
- cend = wextra[1 + wextra[idx]];
+ cend = wextra[1 + wextra[idx]];
# else
- /* Adjust for the alignment. */
- idx += 1 + extra[idx];
- idx = (idx + 3) & ~4;
- cend = *((int32_t *) &extra[idx]);
+ /* Adjust for the alignment. */
+ idx += 1 + extra[idx];
+ idx = (idx + 3) & ~4;
+ cend = *((int32_t *) &extra[idx]);
# endif
- }
- else if (symb_table[2 * elem] != 0 && c1 == 1)
- {
- cend = str[0];
- c = *p++;
- }
- else
- return FNM_NOMATCH;
- }
+ }
+ else if (symb_table[2 * elem] != 0 && c1 == 1)
+ {
+ cend = str[0];
+ c = *p++;
+ }
+ else
+ return FNM_NOMATCH;
+ }
# undef str
- }
- else
- {
- if (!(flags & FNM_NOESCAPE) && cend == L_('\\'))
- cend = *p++;
- if (cend == L_('\0'))
- return FNM_NOMATCH;
- cend = FOLD (cend);
- }
-
- /* XXX It is not entirely clear to me how to handle
- characters which are not mentioned in the
- collation specification. */
- if (
+ }
+ else
+ {
+ if (!(flags & FNM_NOESCAPE) && cend == L_('\\'))
+ cend = *p++;
+ if (cend == L_('\0'))
+ return FNM_NOMATCH;
+ cend = FOLD (cend);
+ }
+
+ /* XXX It is not entirely clear to me how to handle
+ characters which are not mentioned in the
+ collation specification. */
+ if (
# ifdef WIDE_CHAR_VERSION
- lcollseq == 0xffffffff ||
+ lcollseq == 0xffffffff ||
# endif
- lcollseq <= fcollseq)
- {
- /* We have to look at the upper bound. */
- uint32_t hcollseq;
-
- if (is_seqval)
- hcollseq = cend;
- else
- {
+ lcollseq <= fcollseq)
+ {
+ /* We have to look at the upper bound. */
+ uint32_t hcollseq;
+
+ if (is_seqval)
+ hcollseq = cend;
+ else
+ {
# ifdef WIDE_CHAR_VERSION
- hcollseq =
- __collseq_table_lookup (collseq, cend);
- if (hcollseq == ~((uint32_t) 0))
- {
- /* Hum, no information about the upper
- bound. The matching succeeds if the
- lower bound is matched exactly. */
- if (lcollseq != fcollseq)
- goto range_not_matched;
-
- goto matched;
- }
+ hcollseq =
+ __collseq_table_lookup (collseq, cend);
+ if (hcollseq == ~((uint32_t) 0))
+ {
+ /* Hum, no information about the upper
+ bound. The matching succeeds if the
+ lower bound is matched exactly. */
+ if (lcollseq != fcollseq)
+ goto range_not_matched;
+
+ goto matched;
+ }
# else
- hcollseq = collseq[cend];
+ hcollseq = collseq[cend];
# endif
- }
+ }
- if (lcollseq <= hcollseq && fcollseq <= hcollseq)
- goto matched;
- }
+ if (lcollseq <= hcollseq && fcollseq <= hcollseq)
+ goto matched;
+ }
# ifdef WIDE_CHAR_VERSION
- range_not_matched:
+ range_not_matched:
# endif
#else
- /* We use a boring value comparison of the character
- values. This is better than comparing using
- `strcoll' since the latter would have surprising
- and sometimes fatal consequences. */
- UCHAR cend = *p++;
-
- if (!(flags & FNM_NOESCAPE) && cend == L_('\\'))
- cend = *p++;
- if (cend == L_('\0'))
- return FNM_NOMATCH;
-
- /* It is a range. */
- if (cold <= fn && fn <= cend)
- goto matched;
+ /* We use a boring value comparison of the character
+ values. This is better than comparing using
+ 'strcoll' since the latter would have surprising
+ and sometimes fatal consequences. */
+ UCHAR cend = *p++;
+
+ if (!(flags & FNM_NOESCAPE) && cend == L_('\\'))
+ cend = *p++;
+ if (cend == L_('\0'))
+ return FNM_NOMATCH;
+
+ /* It is a range. */
+ if (cold <= fn && fn <= cend)
+ goto matched;
#endif
- c = *p++;
- }
- }
-
- if (c == L_(']'))
- break;
- }
-
- if (!not)
- return FNM_NOMATCH;
- break;
-
- matched:
- /* Skip the rest of the [...] that already matched. */
- do
- {
- ignore_next:
- c = *p++;
-
- if (c == L_('\0'))
- /* [... (unterminated) loses. */
- return FNM_NOMATCH;
-
- if (!(flags & FNM_NOESCAPE) && c == L_('\\'))
- {
- if (*p == L_('\0'))
- return FNM_NOMATCH;
- /* XXX 1003.2d11 is unclear if this is right. */
- ++p;
- }
- else if (c == L_('[') && *p == L_(':'))
- {
- int c1 = 0;
- const CHAR *startp = p;
-
- while (1)
- {
- c = *++p;
- if (++c1 == CHAR_CLASS_MAX_LENGTH)
- return FNM_NOMATCH;
-
- if (*p == L_(':') && p[1] == L_(']'))
- break;
-
- if (c < L_('a') || c >= L_('z'))
- {
- p = startp;
- goto ignore_next;
- }
- }
- p += 2;
- c = *p++;
- }
- else if (c == L_('[') && *p == L_('='))
- {
- c = *++p;
- if (c == L_('\0'))
- return FNM_NOMATCH;
- c = *++p;
- if (c != L_('=') || p[1] != L_(']'))
- return FNM_NOMATCH;
- p += 2;
- c = *p++;
- }
- else if (c == L_('[') && *p == L_('.'))
- {
- ++p;
- while (1)
- {
- c = *++p;
- if (c == '\0')
- return FNM_NOMATCH;
-
- if (*p == L_('.') && p[1] == L_(']'))
- break;
- }
- p += 2;
- c = *p++;
- }
- }
- while (c != L_(']'));
- if (not)
- return FNM_NOMATCH;
- }
- break;
-
- case L_('+'):
- case L_('@'):
- case L_('!'):
- if (__builtin_expect (flags & FNM_EXTMATCH, 0) && *p == '(')
- {
- int res;
-
- res = EXT (c, p, n, string_end, no_leading_period, flags);
- if (res != -1)
- return res;
- }
- goto normal_match;
-
- case L_('/'):
- if (NO_LEADING_PERIOD (flags))
- {
- if (n == string_end || c != (UCHAR) *n)
- return FNM_NOMATCH;
-
- new_no_leading_period = true;
- break;
- }
- /* FALLTHROUGH */
- default:
- normal_match:
- if (n == string_end || c != FOLD ((UCHAR) *n))
- return FNM_NOMATCH;
- }
+ c = *p++;
+ }
+ }
+
+ if (c == L_(']'))
+ break;
+ }
+
+ if (!not)
+ return FNM_NOMATCH;
+ break;
+
+ matched:
+ /* Skip the rest of the [...] that already matched. */
+ do
+ {
+ ignore_next:
+ c = *p++;
+
+ if (c == L_('\0'))
+ /* [... (unterminated) loses. */
+ return FNM_NOMATCH;
+
+ if (!(flags & FNM_NOESCAPE) && c == L_('\\'))
+ {
+ if (*p == L_('\0'))
+ return FNM_NOMATCH;
+ /* XXX 1003.2d11 is unclear if this is right. */
+ ++p;
+ }
+ else if (c == L_('[') && *p == L_(':'))
+ {
+ int c1 = 0;
+ const CHAR *startp = p;
+
+ while (1)
+ {
+ c = *++p;
+ if (++c1 == CHAR_CLASS_MAX_LENGTH)
+ return FNM_NOMATCH;
+
+ if (*p == L_(':') && p[1] == L_(']'))
+ break;
+
+ if (c < L_('a') || c >= L_('z'))
+ {
+ p = startp;
+ goto ignore_next;
+ }
+ }
+ p += 2;
+ c = *p++;
+ }
+ else if (c == L_('[') && *p == L_('='))
+ {
+ c = *++p;
+ if (c == L_('\0'))
+ return FNM_NOMATCH;
+ c = *++p;
+ if (c != L_('=') || p[1] != L_(']'))
+ return FNM_NOMATCH;
+ p += 2;
+ c = *p++;
+ }
+ else if (c == L_('[') && *p == L_('.'))
+ {
+ ++p;
+ while (1)
+ {
+ c = *++p;
+ if (c == '\0')
+ return FNM_NOMATCH;
+
+ if (*p == L_('.') && p[1] == L_(']'))
+ break;
+ }
+ p += 2;
+ c = *p++;
+ }
+ }
+ while (c != L_(']'));
+ if (not)
+ return FNM_NOMATCH;
+ }
+ break;
+
+ case L_('+'):
+ case L_('@'):
+ case L_('!'):
+ if (__builtin_expect (flags & FNM_EXTMATCH, 0) && *p == '(')
+ {
+ int res;
+
+ res = EXT (c, p, n, string_end, no_leading_period, flags);
+ if (res != -1)
+ return res;
+ }
+ goto normal_match;
+
+ case L_('/'):
+ if (NO_LEADING_PERIOD (flags))
+ {
+ if (n == string_end || c != (UCHAR) *n)
+ return FNM_NOMATCH;
+
+ new_no_leading_period = true;
+ break;
+ }
+ /* FALLTHROUGH */
+ default:
+ normal_match:
+ if (n == string_end || c != FOLD ((UCHAR) *n))
+ return FNM_NOMATCH;
+ }
no_leading_period = new_no_leading_period;
++n;
@@ -984,25 +994,25 @@ END (const CHAR *pattern)
return pattern;
else if (*p == L_('['))
{
- /* Handle brackets special. */
- if (posixly_correct == 0)
- posixly_correct = getenv ("POSIXLY_CORRECT") != NULL ? 1 : -1;
-
- /* Skip the not sign. We have to recognize it because of a possibly
- following ']'. */
- if (*++p == L_('!') || (posixly_correct < 0 && *p == L_('^')))
- ++p;
- /* A leading ']' is recognized as such. */
- if (*p == L_(']'))
- ++p;
- /* Skip over all characters of the list. */
- while (*p != L_(']'))
- if (*p++ == L_('\0'))
- /* This is no valid pattern. */
- return pattern;
+ /* Handle brackets special. */
+ if (posixly_correct == 0)
+ posixly_correct = getenv ("POSIXLY_CORRECT") != NULL ? 1 : -1;
+
+ /* Skip the not sign. We have to recognize it because of a possibly
+ following ']'. */
+ if (*++p == L_('!') || (posixly_correct < 0 && *p == L_('^')))
+ ++p;
+ /* A leading ']' is recognized as such. */
+ if (*p == L_(']'))
+ ++p;
+ /* Skip over all characters of the list. */
+ while (*p != L_(']'))
+ if (*p++ == L_('\0'))
+ /* This is no valid pattern. */
+ return pattern;
}
else if ((*p == L_('?') || *p == L_('*') || *p == L_('+') || *p == L_('@')
- || *p == L_('!')) && p[1] == L_('('))
+ || *p == L_('!')) && p[1] == L_('('))
p = END (p + 1);
else if (*p == L_(')'))
break;
@@ -1037,63 +1047,63 @@ EXT (INT opt, const CHAR *pattern, const CHAR *string, const CHAR *string_end,
return -1;
else if (*p == L_('['))
{
- /* Handle brackets special. */
- if (posixly_correct == 0)
- posixly_correct = getenv ("POSIXLY_CORRECT") != NULL ? 1 : -1;
-
- /* Skip the not sign. We have to recognize it because of a possibly
- following ']'. */
- if (*++p == L_('!') || (posixly_correct < 0 && *p == L_('^')))
- ++p;
- /* A leading ']' is recognized as such. */
- if (*p == L_(']'))
- ++p;
- /* Skip over all characters of the list. */
- while (*p != L_(']'))
- if (*p++ == L_('\0'))
- /* This is no valid pattern. */
- return -1;
+ /* Handle brackets special. */
+ if (posixly_correct == 0)
+ posixly_correct = getenv ("POSIXLY_CORRECT") != NULL ? 1 : -1;
+
+ /* Skip the not sign. We have to recognize it because of a possibly
+ following ']'. */
+ if (*++p == L_('!') || (posixly_correct < 0 && *p == L_('^')))
+ ++p;
+ /* A leading ']' is recognized as such. */
+ if (*p == L_(']'))
+ ++p;
+ /* Skip over all characters of the list. */
+ while (*p != L_(']'))
+ if (*p++ == L_('\0'))
+ /* This is no valid pattern. */
+ return -1;
}
else if ((*p == L_('?') || *p == L_('*') || *p == L_('+') || *p == L_('@')
- || *p == L_('!')) && p[1] == L_('('))
+ || *p == L_('!')) && p[1] == L_('('))
/* Remember the nesting level. */
++level;
else if (*p == L_(')'))
{
- if (level-- == 0)
- {
- /* This means we found the end of the pattern. */
+ if (level-- == 0)
+ {
+ /* This means we found the end of the pattern. */
#define NEW_PATTERN \
- struct patternlist *newp; \
- size_t plen; \
- size_t plensize; \
- size_t newpsize; \
- \
- plen = (opt == L_('?') || opt == L_('@') \
- ? pattern_len \
- : p - startp + 1); \
- plensize = plen * sizeof (CHAR); \
- newpsize = offsetof (struct patternlist, str) + plensize; \
- if ((size_t) -1 / sizeof (CHAR) < plen \
- || newpsize < offsetof (struct patternlist, str) \
- || ALLOCA_LIMIT <= newpsize) \
- return -1; \
- newp = (struct patternlist *) alloca (newpsize); \
- *((CHAR *) MEMPCPY (newp->str, startp, p - startp)) = L_('\0'); \
- newp->next = NULL; \
- *lastp = newp; \
- lastp = &newp->next
- NEW_PATTERN;
- break;
- }
+ struct patternlist *newp; \
+ size_t plen; \
+ size_t plensize; \
+ size_t newpsize; \
+ \
+ plen = (opt == L_('?') || opt == L_('@') \
+ ? pattern_len \
+ : p - startp + 1UL); \
+ plensize = plen * sizeof (CHAR); \
+ newpsize = offsetof (struct patternlist, str) + plensize; \
+ if ((size_t) -1 / sizeof (CHAR) < plen \
+ || newpsize < offsetof (struct patternlist, str) \
+ || ALLOCA_LIMIT <= newpsize) \
+ return -1; \
+ newp = (struct patternlist *) alloca (newpsize); \
+ *((CHAR *) MEMPCPY (newp->str, startp, p - startp)) = L_('\0'); \
+ newp->next = NULL; \
+ *lastp = newp; \
+ lastp = &newp->next
+ NEW_PATTERN;
+ break;
+ }
}
else if (*p == L_('|'))
{
- if (level == 0)
- {
- NEW_PATTERN;
- startp = p + 1;
- }
+ if (level == 0)
+ {
+ NEW_PATTERN;
+ startp = p + 1;
+ }
}
assert (list != NULL);
assert (p[-1] == L_(')'));
@@ -1103,36 +1113,36 @@ EXT (INT opt, const CHAR *pattern, const CHAR *string, const CHAR *string_end,
{
case L_('*'):
if (FCT (p, string, string_end, no_leading_period, flags) == 0)
- return 0;
+ return 0;
/* FALLTHROUGH */
case L_('+'):
do
- {
- for (rs = string; rs <= string_end; ++rs)
- /* First match the prefix with the current pattern with the
- current pattern. */
- if (FCT (list->str, string, rs, no_leading_period,
- flags & FNM_FILE_NAME ? flags : flags & ~FNM_PERIOD) == 0
- /* This was successful. Now match the rest with the rest
- of the pattern. */
- && (FCT (p, rs, string_end,
- rs == string
- ? no_leading_period
- : rs[-1] == '/' && NO_LEADING_PERIOD (flags),
- flags & FNM_FILE_NAME
- ? flags : flags & ~FNM_PERIOD) == 0
- /* This didn't work. Try the whole pattern. */
- || (rs != string
- && FCT (pattern - 1, rs, string_end,
- rs == string
- ? no_leading_period
- : rs[-1] == '/' && NO_LEADING_PERIOD (flags),
- flags & FNM_FILE_NAME
- ? flags : flags & ~FNM_PERIOD) == 0)))
- /* It worked. Signal success. */
- return 0;
- }
+ {
+ for (rs = string; rs <= string_end; ++rs)
+ /* First match the prefix with the current pattern with the
+ current pattern. */
+ if (FCT (list->str, string, rs, no_leading_period,
+ flags & FNM_FILE_NAME ? flags : flags & ~FNM_PERIOD) == 0
+ /* This was successful. Now match the rest with the rest
+ of the pattern. */
+ && (FCT (p, rs, string_end,
+ rs == string
+ ? no_leading_period
+ : rs[-1] == '/' && NO_LEADING_PERIOD (flags),
+ flags & FNM_FILE_NAME
+ ? flags : flags & ~FNM_PERIOD) == 0
+ /* This didn't work. Try the whole pattern. */
+ || (rs != string
+ && FCT (pattern - 1, rs, string_end,
+ rs == string
+ ? no_leading_period
+ : rs[-1] == '/' && NO_LEADING_PERIOD (flags),
+ flags & FNM_FILE_NAME
+ ? flags : flags & ~FNM_PERIOD) == 0)))
+ /* It worked. Signal success. */
+ return 0;
+ }
while ((list = list->next) != NULL);
/* None of the patterns lead to a match. */
@@ -1140,20 +1150,20 @@ EXT (INT opt, const CHAR *pattern, const CHAR *string, const CHAR *string_end,
case L_('?'):
if (FCT (p, string, string_end, no_leading_period, flags) == 0)
- return 0;
+ return 0;
/* FALLTHROUGH */
case L_('@'):
do
- /* I cannot believe it but `strcat' is actually acceptable
- here. Match the entire string with the prefix from the
- pattern list and the rest of the pattern following the
- pattern list. */
- if (FCT (STRCAT (list->str, p), string, string_end,
- no_leading_period,
- flags & FNM_FILE_NAME ? flags : flags & ~FNM_PERIOD) == 0)
- /* It worked. Signal success. */
- return 0;
+ /* I cannot believe it but 'strcat' is actually acceptable
+ here. Match the entire string with the prefix from the
+ pattern list and the rest of the pattern following the
+ pattern list. */
+ if (FCT (STRCAT (list->str, p), string, string_end,
+ no_leading_period,
+ flags & FNM_FILE_NAME ? flags : flags & ~FNM_PERIOD) == 0)
+ /* It worked. Signal success. */
+ return 0;
while ((list = list->next) != NULL);
/* None of the patterns lead to a match. */
@@ -1161,28 +1171,28 @@ EXT (INT opt, const CHAR *pattern, const CHAR *string, const CHAR *string_end,
case L_('!'):
for (rs = string; rs <= string_end; ++rs)
- {
- struct patternlist *runp;
-
- for (runp = list; runp != NULL; runp = runp->next)
- if (FCT (runp->str, string, rs, no_leading_period,
- flags & FNM_FILE_NAME ? flags : flags & ~FNM_PERIOD) == 0)
- break;
-
- /* If none of the patterns matched see whether the rest does. */
- if (runp == NULL
- && (FCT (p, rs, string_end,
- rs == string
- ? no_leading_period
- : rs[-1] == '/' && NO_LEADING_PERIOD (flags),
- flags & FNM_FILE_NAME ? flags : flags & ~FNM_PERIOD)
- == 0))
- /* This is successful. */
- return 0;
- }
+ {
+ struct patternlist *runp;
+
+ for (runp = list; runp != NULL; runp = runp->next)
+ if (FCT (runp->str, string, rs, no_leading_period,
+ flags & FNM_FILE_NAME ? flags : flags & ~FNM_PERIOD) == 0)
+ break;
+
+ /* If none of the patterns matched see whether the rest does. */
+ if (runp == NULL
+ && (FCT (p, rs, string_end,
+ rs == string
+ ? no_leading_period
+ : rs[-1] == '/' && NO_LEADING_PERIOD (flags),
+ flags & FNM_FILE_NAME ? flags : flags & ~FNM_PERIOD)
+ == 0))
+ /* This is successful. */
+ return 0;
+ }
/* None of the patterns together with the rest of the pattern
- lead to a match. */
+ lead to a match. */
return FNM_NOMATCH;
default:
@@ -1203,7 +1213,6 @@ EXT (INT opt, const CHAR *pattern, const CHAR *string, const CHAR *string_end,
#undef END
#undef MEMPCPY
#undef MEMCHR
-#undef STRCOLL
#undef STRLEN
#undef STRCAT
#undef L_
diff --git a/lib/fopen-safer.c b/lib/fopen-safer.c
index 3502dba..6e7c08d 100644
--- a/lib/fopen-safer.c
+++ b/lib/fopen-safer.c
@@ -1,11 +1,11 @@
/* Invoke fopen, but avoid some glitches.
- Copyright (C) 2001, 2004, 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2001, 2004-2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
@@ -26,10 +25,6 @@
#include <unistd.h>
#include "unistd-safer.h"
-#ifndef STDERR_FILENO
-# define STDERR_FILENO 2
-#endif
-
/* Like fopen, but do not return stdin, stdout, or stderr. */
FILE *
@@ -42,26 +37,26 @@ fopen_safer (char const *file, char const *mode)
int fd = fileno (fp);
if (0 <= fd && fd <= STDERR_FILENO)
- {
- int f = dup_safer (fd);
-
- if (f < 0)
- {
- int e = errno;
- fclose (fp);
- errno = e;
- return NULL;
- }
-
- if (fclose (fp) != 0
- || ! (fp = fdopen (f, mode)))
- {
- int e = errno;
- close (f);
- errno = e;
- return NULL;
- }
- }
+ {
+ int f = dup_safer (fd);
+
+ if (f < 0)
+ {
+ int e = errno;
+ fclose (fp);
+ errno = e;
+ return NULL;
+ }
+
+ if (fclose (fp) != 0
+ || ! (fp = fdopen (f, mode)))
+ {
+ int e = errno;
+ close (f);
+ errno = e;
+ return NULL;
+ }
+ }
}
return fp;
diff --git a/lib/fopen.c b/lib/fopen.c
new file mode 100644
index 0000000..6c0c847
--- /dev/null
+++ b/lib/fopen.c
@@ -0,0 +1,110 @@
+/* Open a stream to a file.
+ Copyright (C) 2007-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Bruno Haible <bruno@clisp.org>, 2007. */
+
+/* If the user's config.h happens to include <stdio.h>, let it include only
+ the system's <stdio.h> here, so that orig_fopen doesn't recurse to
+ rpl_fopen. */
+#define __need_FILE
+#include <config.h>
+
+/* Get the original definition of fopen. It might be defined as a macro. */
+#include <stdio.h>
+#undef __need_FILE
+
+static FILE *
+orig_fopen (const char *filename, const char *mode)
+{
+ return fopen (filename, mode);
+}
+
+/* Specification. */
+/* Write "stdio.h" here, not <stdio.h>, otherwise OSF/1 5.1 DTK cc eliminates
+ this include because of the preliminary #include <stdio.h> above. */
+#include "stdio.h"
+
+#include <errno.h>
+#include <fcntl.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+
+FILE *
+rpl_fopen (const char *filename, const char *mode)
+{
+#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+ if (strcmp (filename, "/dev/null") == 0)
+ filename = "NUL";
+#endif
+
+#if FOPEN_TRAILING_SLASH_BUG
+ /* If the filename ends in a slash and a mode that requires write access is
+ specified, then fail.
+ Rationale: POSIX <http://www.opengroup.org/susv3/basedefs/xbd_chap04.html>
+ says that
+ "A pathname that contains at least one non-slash character and that
+ ends with one or more trailing slashes shall be resolved as if a
+ single dot character ( '.' ) were appended to the pathname."
+ and
+ "The special filename dot shall refer to the directory specified by
+ its predecessor."
+ If the named file already exists as a directory, then if a mode that
+ requires write access is specified, fopen() must fail because POSIX
+ <http://www.opengroup.org/susv3/functions/fopen.html> says that it
+ fails with errno = EISDIR in this case.
+ If the named file does not exist or does not name a directory, then
+ fopen() must fail since the file does not contain a '.' directory. */
+ {
+ size_t len = strlen (filename);
+ if (len > 0 && filename[len - 1] == '/')
+ {
+ int fd;
+ struct stat statbuf;
+ FILE *fp;
+
+ if (mode[0] == 'w' || mode[0] == 'a')
+ {
+ errno = EISDIR;
+ return NULL;
+ }
+
+ fd = open (filename, O_RDONLY);
+ if (fd < 0)
+ return NULL;
+
+ if (fstat (fd, &statbuf) >= 0 && !S_ISDIR (statbuf.st_mode))
+ {
+ close (fd);
+ errno = ENOTDIR;
+ return NULL;
+ }
+
+ fp = fdopen (fd, mode);
+ if (fp == NULL)
+ {
+ int saved_errno = errno;
+ close (fd);
+ errno = saved_errno;
+ }
+ return fp;
+ }
+ }
+# endif
+
+ return orig_fopen (filename, mode);
+}
diff --git a/lib/__fpending.c b/lib/fpending.c
index 221aee6..a503b9f 100644
--- a/lib/__fpending.c
+++ b/lib/fpending.c
@@ -1,10 +1,11 @@
-/* __fpending.c -- return the number of pending output bytes on a stream
- Copyright (C) 2000, 2004, 2006 Free Software Foundation, Inc.
+/* fpending.c -- return the number of pending output bytes on a stream
+ Copyright (C) 2000, 2004, 2006-2007, 2009-2016 Free Software Foundation,
+ Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -12,14 +13,13 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Jim Meyering. */
#include <config.h>
-#include "__fpending.h"
+#include "fpending.h"
/* Return the number of pending (aka buffered, unflushed)
bytes on the stream, FP, that is open for writing. */
diff --git a/lib/fpending.h b/lib/fpending.h
new file mode 100644
index 0000000..61008aa
--- /dev/null
+++ b/lib/fpending.h
@@ -0,0 +1,29 @@
+/* Declare __fpending.
+
+ Copyright (C) 2000, 2003, 2005-2006, 2009-2016 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 <http://www.gnu.org/licenses/>.
+
+ Written by Jim Meyering. */
+
+#include <stddef.h>
+#include <stdio.h>
+#if HAVE_STDIO_EXT_H
+# include <stdio_ext.h>
+#endif
+
+#if !HAVE_DECL___FPENDING
+size_t __fpending (FILE *) _GL_ATTRIBUTE_PURE;
+#endif
diff --git a/lib/fprintftime.h b/lib/fprintftime.h
index e0be5cd..c92d64b 100644
--- a/lib/fprintftime.h
+++ b/lib/fprintftime.h
@@ -1,20 +1,19 @@
/* Generate time strings directly to the output. */
-/* Copyright (C) 2005 Free Software Foundation, Inc.
+/* Copyright (C) 2005, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <stdio.h>
#include <time.h>
@@ -24,7 +23,7 @@
large buffer that nstrftime would require.
Output to stream FP the result of formatting (according to the
- nstrftime format string, FMT) the time data, *TM, and the UTC
+ nstrftime format string, FMT) the time data, *TM, and the ZONE
and NANOSECONDS values. */
size_t fprintftime (FILE *fp, char const *fmt, struct tm const *tm,
- int utc, int nanoseconds);
+ timezone_t zone, int nanoseconds);
diff --git a/lib/fpucw.h b/lib/fpucw.h
new file mode 100644
index 0000000..05ee0ca
--- /dev/null
+++ b/lib/fpucw.h
@@ -0,0 +1,108 @@
+/* Manipulating the FPU control word. -*- coding: utf-8 -*-
+ Copyright (C) 2007-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2007.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _FPUCW_H
+#define _FPUCW_H
+
+/* The i386 floating point hardware (the 387 compatible FPU, not the modern
+ SSE/SSE2 hardware) has a controllable rounding precision. It is specified
+ through the 'PC' bits in the FPU control word ('fctrl' register). (See
+ the GNU libc i386 <fpu_control.h> header for details.)
+
+ On some platforms, such as Linux or Solaris, the default precision setting
+ is set to "extended precision". This means that 'long double' instructions
+ operate correctly, but 'double' computations often produce slightly
+ different results as on strictly IEEE 754 conforming systems.
+
+ On some platforms, such as NetBSD, the default precision is set to
+ "double precision". This means that 'long double' instructions will operate
+ only as 'double', i.e. lead to wrong results. Similarly on FreeBSD 6.4, at
+ least for the division of 'long double' numbers.
+
+ The FPU control word is under control of the application, i.e. it is
+ not required to be set either way by the ABI. (In fact, the i386 ABI
+ http://refspecs.freestandards.org/elf/abi386-4.pdf page 3-12 = page 38
+ is not clear about it. But in any case, gcc treats the control word
+ like a "preserved" register: it emits code that assumes that the control
+ word is preserved across calls, and it restores the control word at the
+ end of functions that modify it.)
+
+ See Vincent Lefèvre's page http://www.vinc17.org/research/extended.en.html
+ for a good explanation.
+ See http://www.uwsg.iu.edu/hypermail/linux/kernel/0103.0/0453.html for
+ some argumentation which setting should be the default. */
+
+/* This header file provides the following facilities:
+ fpucw_t integral type holding the value of 'fctrl'
+ FPU_PC_MASK bit mask denoting the precision control
+ FPU_PC_DOUBLE precision control for 53 bits mantissa
+ FPU_PC_EXTENDED precision control for 64 bits mantissa
+ GET_FPUCW () yields the current FPU control word
+ SET_FPUCW (word) sets the FPU control word
+ DECL_LONG_DOUBLE_ROUNDING variable declaration for
+ BEGIN/END_LONG_DOUBLE_ROUNDING
+ BEGIN_LONG_DOUBLE_ROUNDING () starts a sequence of instructions with
+ 'long double' safe operation precision
+ END_LONG_DOUBLE_ROUNDING () ends a sequence of instructions with
+ 'long double' safe operation precision
+ */
+
+/* Inline assembler like this works only with GNU C. */
+#if (defined __i386__ || defined __x86_64__) && defined __GNUC__
+
+typedef unsigned short fpucw_t; /* glibc calls this fpu_control_t */
+
+# define FPU_PC_MASK 0x0300
+# define FPU_PC_DOUBLE 0x200 /* glibc calls this _FPU_DOUBLE */
+# define FPU_PC_EXTENDED 0x300 /* glibc calls this _FPU_EXTENDED */
+
+# define GET_FPUCW() \
+ ({ fpucw_t _cw; \
+ __asm__ __volatile__ ("fnstcw %0" : "=m" (*&_cw)); \
+ _cw; \
+ })
+# define SET_FPUCW(word) \
+ (void)({ fpucw_t _ncw = (word); \
+ __asm__ __volatile__ ("fldcw %0" : : "m" (*&_ncw)); \
+ })
+
+# define DECL_LONG_DOUBLE_ROUNDING \
+ fpucw_t oldcw;
+# define BEGIN_LONG_DOUBLE_ROUNDING() \
+ (void)(oldcw = GET_FPUCW (), \
+ SET_FPUCW ((oldcw & ~FPU_PC_MASK) | FPU_PC_EXTENDED))
+# define END_LONG_DOUBLE_ROUNDING() \
+ SET_FPUCW (oldcw)
+
+#else
+
+typedef unsigned int fpucw_t;
+
+# define FPU_PC_MASK 0
+# define FPU_PC_DOUBLE 0
+# define FPU_PC_EXTENDED 0
+
+# define GET_FPUCW() 0
+# define SET_FPUCW(word) (void)(word)
+
+# define DECL_LONG_DOUBLE_ROUNDING
+# define BEGIN_LONG_DOUBLE_ROUNDING()
+# define END_LONG_DOUBLE_ROUNDING()
+
+#endif
+
+#endif /* _FPUCW_H */
diff --git a/lib/fpurge.c b/lib/fpurge.c
new file mode 100644
index 0000000..c85c409
--- /dev/null
+++ b/lib/fpurge.c
@@ -0,0 +1,147 @@
+/* Flushing buffers of a FILE stream.
+ Copyright (C) 2007-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <stdio.h>
+
+#if HAVE___FPURGE /* glibc >= 2.2, Haiku, Solaris >= 7 */
+# include <stdio_ext.h>
+#endif
+#include <stdlib.h>
+
+#include "stdio-impl.h"
+
+int
+fpurge (FILE *fp)
+{
+#if HAVE___FPURGE /* glibc >= 2.2, Haiku, Solaris >= 7, musl libc */
+
+ __fpurge (fp);
+ /* The __fpurge function does not have a return value. */
+ return 0;
+
+#elif HAVE_FPURGE /* FreeBSD, NetBSD, OpenBSD, DragonFly, Mac OS X, Cygwin 1.7 */
+
+ /* Call the system's fpurge function. */
+# undef fpurge
+# if !HAVE_DECL_FPURGE
+ extern int fpurge (FILE *);
+# endif
+ int result = fpurge (fp);
+# if defined __sferror || defined __DragonFly__ || defined __ANDROID__
+ /* FreeBSD, NetBSD, OpenBSD, DragonFly, Mac OS X, Cygwin, Android */
+ if (result == 0)
+ /* Correct the invariants that fpurge broke.
+ <stdio.h> on BSD systems says:
+ "The following always hold: if _flags & __SRD, _w is 0."
+ If this invariant is not fulfilled and the stream is read-write but
+ currently reading, subsequent putc or fputc calls will write directly
+ into the buffer, although they shouldn't be allowed to. */
+ if ((fp_->_flags & __SRD) != 0)
+ fp_->_w = 0;
+# endif
+ return result;
+
+#else
+
+ /* Most systems provide FILE as a struct and the necessary bitmask in
+ <stdio.h>, because they need it for implementing getc() and putc() as
+ fast macros. */
+# if defined _IO_ftrylockfile || __GNU_LIBRARY__ == 1 /* GNU libc, BeOS, Haiku, Linux libc5 */
+ fp->_IO_read_end = fp->_IO_read_ptr;
+ fp->_IO_write_ptr = fp->_IO_write_base;
+ /* Avoid memory leak when there is an active ungetc buffer. */
+ if (fp->_IO_save_base != NULL)
+ {
+ free (fp->_IO_save_base);
+ fp->_IO_save_base = NULL;
+ }
+ return 0;
+# elif defined __sferror || defined __DragonFly__ || defined __ANDROID__
+ /* FreeBSD, NetBSD, OpenBSD, DragonFly, Mac OS X, Cygwin, Android */
+ fp_->_p = fp_->_bf._base;
+ fp_->_r = 0;
+ fp_->_w = ((fp_->_flags & (__SLBF | __SNBF | __SRD)) == 0 /* fully buffered and not currently reading? */
+ ? fp_->_bf._size
+ : 0);
+ /* Avoid memory leak when there is an active ungetc buffer. */
+ if (fp_ub._base != NULL)
+ {
+ if (fp_ub._base != fp_->_ubuf)
+ free (fp_ub._base);
+ fp_ub._base = NULL;
+ }
+ return 0;
+# elif defined __EMX__ /* emx+gcc */
+ fp->_ptr = fp->_buffer;
+ fp->_rcount = 0;
+ fp->_wcount = 0;
+ fp->_ungetc_count = 0;
+ return 0;
+# elif defined __minix /* Minix */
+ fp->_ptr = fp->_buf;
+ if (fp->_ptr != NULL)
+ fp->_count = 0;
+ return 0;
+# elif defined _IOERR /* AIX, HP-UX, IRIX, OSF/1, Solaris, OpenServer, mingw, NonStop Kernel */
+ fp->_ptr = fp->_base;
+ if (fp->_ptr != NULL)
+ fp->_cnt = 0;
+ return 0;
+# elif defined __UCLIBC__ /* uClibc */
+# ifdef __STDIO_BUFFERS
+ if (fp->__modeflags & __FLAG_WRITING)
+ fp->__bufpos = fp->__bufstart;
+ else if (fp->__modeflags & (__FLAG_READONLY | __FLAG_READING))
+ fp->__bufpos = fp->__bufread;
+# endif
+ return 0;
+# elif defined __QNX__ /* QNX */
+ fp->_Rback = fp->_Back + sizeof (fp->_Back);
+ fp->_Rsave = NULL;
+ if (fp->_Mode & 0x2000 /* _MWRITE */)
+ /* fp->_Buf <= fp->_Next <= fp->_Wend */
+ fp->_Next = fp->_Buf;
+ else
+ /* fp->_Buf <= fp->_Next <= fp->_Rend */
+ fp->_Rend = fp->_Next;
+ return 0;
+# elif defined __MINT__ /* Atari FreeMiNT */
+ if (fp->__pushed_back)
+ {
+ fp->__bufp = fp->__pushback_bufp;
+ fp->__pushed_back = 0;
+ }
+ /* Preserve the current file position. */
+ if (fp->__target != -1)
+ fp->__target += fp->__bufp - fp->__buffer;
+ fp->__bufp = fp->__buffer;
+ /* Nothing in the buffer, next getc is nontrivial. */
+ fp->__get_limit = fp->__bufp;
+ /* Nothing in the buffer, next putc is nontrivial. */
+ fp->__put_limit = fp->__buffer;
+ return 0;
+# elif defined EPLAN9 /* Plan9 */
+ fp->rp = fp->wp = fp->lp = fp->buf;
+ return 0;
+# else
+# error "Please port gnulib fpurge.c to your platform! Look at the definitions of fflush, setvbuf and ungetc on your system, then report this to bug-gnulib."
+# endif
+
+#endif
+}
diff --git a/lib/freadahead.c b/lib/freadahead.c
new file mode 100644
index 0000000..38f9dfb
--- /dev/null
+++ b/lib/freadahead.c
@@ -0,0 +1,94 @@
+/* Retrieve information about a FILE stream.
+ Copyright (C) 2007-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include "freadahead.h"
+
+#include <stdlib.h>
+#include "stdio-impl.h"
+
+size_t
+freadahead (FILE *fp)
+{
+#if defined _IO_ftrylockfile || __GNU_LIBRARY__ == 1 /* GNU libc, BeOS, Haiku, Linux libc5 */
+ if (fp->_IO_write_ptr > fp->_IO_write_base)
+ return 0;
+ return (fp->_IO_read_end - fp->_IO_read_ptr)
+ + (fp->_flags & _IO_IN_BACKUP ? fp->_IO_save_end - fp->_IO_save_base :
+ 0);
+#elif defined __sferror || defined __DragonFly__ || defined __ANDROID__
+ /* FreeBSD, NetBSD, OpenBSD, DragonFly, Mac OS X, Cygwin, Android */
+ if ((fp_->_flags & __SWR) != 0 || fp_->_r < 0)
+ return 0;
+# if defined __DragonFly__
+ return __sreadahead (fp);
+# else
+ return fp_->_r
+ + (HASUB (fp) ? fp_->_ur : 0);
+# endif
+#elif defined __EMX__ /* emx+gcc */
+ if ((fp->_flags & _IOWRT) != 0)
+ return 0;
+ /* Note: fp->_ungetc_count > 0 implies fp->_rcount <= 0,
+ fp->_ungetc_count = 0 implies fp->_rcount >= 0. */
+ /* equivalent to
+ (fp->_ungetc_count == 0 ? fp->_rcount : fp->_ungetc_count - fp->_rcount) */
+ return (fp->_rcount > 0 ? fp->_rcount : fp->_ungetc_count - fp->_rcount);
+#elif defined __minix /* Minix */
+ if ((fp_->_flags & _IOWRITING) != 0)
+ return 0;
+ return fp_->_count;
+#elif defined _IOERR /* AIX, HP-UX, IRIX, OSF/1, Solaris, OpenServer, mingw, NonStop Kernel */
+ if ((fp_->_flag & _IOWRT) != 0)
+ return 0;
+ return fp_->_cnt;
+#elif defined __UCLIBC__ /* uClibc */
+# ifdef __STDIO_BUFFERS
+ if (fp->__modeflags & __FLAG_WRITING)
+ return 0;
+ return (fp->__bufread - fp->__bufpos)
+ + (fp->__modeflags & __FLAG_UNGOT ? 1 : 0);
+# else
+ return 0;
+# endif
+#elif defined __QNX__ /* QNX */
+ if ((fp->_Mode & 0x2000 /* _MWRITE */) != 0)
+ return 0;
+ /* fp->_Buf <= fp->_Next <= fp->_Rend,
+ and fp->_Rend may be overridden by fp->_Rsave. */
+ return ((fp->_Rsave ? fp->_Rsave : fp->_Rend) - fp->_Next)
+ + (fp->_Mode & 0x4000 /* _MBYTE */
+ ? (fp->_Back + sizeof (fp->_Back)) - fp->_Rback
+ : 0);
+#elif defined __MINT__ /* Atari FreeMiNT */
+ if (!fp->__mode.__read)
+ return 0;
+ return (fp->__pushed_back
+ ? fp->__get_limit - fp->__pushback_bufp + 1
+ : fp->__get_limit - fp->__bufp);
+#elif defined EPLAN9 /* Plan9 */
+ if (fp->state == 4 /* WR */ || fp->rp >= fp->wp)
+ return 0;
+ return fp->wp - fp->rp;
+#elif defined SLOW_BUT_NO_HACKS /* users can define this */
+ abort ();
+ return 0;
+#else
+ #error "Please port gnulib freadahead.c to your platform! Look at the definition of fflush, fread, ungetc on your system, then report this to bug-gnulib."
+#endif
+}
diff --git a/lib/freadahead.h b/lib/freadahead.h
new file mode 100644
index 0000000..f8211af
--- /dev/null
+++ b/lib/freadahead.h
@@ -0,0 +1,47 @@
+/* Retrieve information about a FILE stream.
+ Copyright (C) 2007-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <stddef.h>
+#include <stdio.h>
+
+/* Assuming the stream STREAM is open for reading:
+ Return the number of bytes waiting in the input buffer of STREAM.
+ This includes both the bytes that have been read from the underlying input
+ source and the bytes that have been pushed back through 'ungetc'.
+
+ If this number is 0 and the stream is not currently writing,
+ fflush (STREAM) is known to be a no-op.
+
+ STREAM must not be wide-character oriented. */
+
+#if HAVE___FREADAHEAD /* musl libc */
+
+# include <stdio_ext.h>
+# define freadahead(stream) __freadahead (stream)
+
+#else
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+extern size_t freadahead (FILE *stream) _GL_ATTRIBUTE_PURE;
+
+# ifdef __cplusplus
+}
+# endif
+
+#endif
diff --git a/lib/freading.c b/lib/freading.c
new file mode 100644
index 0000000..8a4247d
--- /dev/null
+++ b/lib/freading.c
@@ -0,0 +1,75 @@
+/* Retrieve information about a FILE stream.
+ Copyright (C) 2007-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include "freading.h"
+
+#include "stdio-impl.h"
+
+/* Don't use glibc's __freading function in glibc < 2.7, see
+ <http://sourceware.org/bugzilla/show_bug.cgi?id=4359> */
+#if !(HAVE___FREADING && (!defined __GLIBC__ || defined __UCLIBC__ || __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 7)))
+
+bool
+freading (FILE *fp)
+{
+ /* Most systems provide FILE as a struct and the necessary bitmask in
+ <stdio.h>, because they need it for implementing getc() and putc() as
+ fast macros. */
+# if defined _IO_ftrylockfile || __GNU_LIBRARY__ == 1 /* GNU libc, BeOS, Haiku, Linux libc5 */
+ return ((fp->_flags & _IO_NO_WRITES) != 0
+ || ((fp->_flags & (_IO_NO_READS | _IO_CURRENTLY_PUTTING)) == 0
+ && fp->_IO_read_base != NULL));
+# elif defined __sferror || defined __DragonFly__ || defined __ANDROID__
+ /* FreeBSD, NetBSD, OpenBSD, DragonFly, Mac OS X, Cygwin, Android */
+ return (fp_->_flags & __SRD) != 0;
+# elif defined __EMX__ /* emx+gcc */
+ return (fp->_flags & _IOREAD) != 0;
+# elif defined __minix /* Minix */
+ return (fp->_flags & _IOREADING) != 0;
+# elif defined _IOERR /* AIX, HP-UX, IRIX, OSF/1, Solaris, OpenServer, mingw, NonStop Kernel */
+# if defined __sun /* Solaris */
+ return (fp->_flag & _IOREAD) != 0 && (fp->_flag & _IOWRT) == 0;
+# else
+ return (fp->_flag & _IOREAD) != 0;
+# endif
+# elif defined __UCLIBC__ /* uClibc */
+ return (fp->__modeflags & (__FLAG_READONLY | __FLAG_READING)) != 0;
+# elif defined __QNX__ /* QNX */
+ return ((fp->_Mode & 0x2 /* _MOPENW */) == 0
+ || (fp->_Mode & 0x1000 /* _MREAD */) != 0);
+# elif defined __MINT__ /* Atari FreeMiNT */
+ if (!fp->__mode.__write)
+ return 1;
+ if (!fp->__mode.__read)
+ return 0;
+# ifdef _IO_CURRENTLY_GETTING /* Flag added on 2009-02-28 */
+ return (fp->__flags & _IO_CURRENTLY_GETTING) != 0;
+# else
+ return (fp->__buffer < fp->__get_limit /*|| fp->__bufp == fp->__put_limit ??*/);
+# endif
+# elif defined EPLAN9 /* Plan9 */
+ if (fp->state == 0 /* CLOSED */ || fp->state == 4 /* WR */)
+ return 0;
+ return (fp->state == 3 /* RD */ && (fp->bufl == 0 || fp->rp < fp->wp));
+# else
+# error "Please port gnulib freading.c to your platform!"
+# endif
+}
+
+#endif
diff --git a/lib/freading.h b/lib/freading.h
new file mode 100644
index 0000000..949efd5
--- /dev/null
+++ b/lib/freading.h
@@ -0,0 +1,53 @@
+/* Retrieve information about a FILE stream.
+ Copyright (C) 2007-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <stdbool.h>
+#include <stdio.h>
+
+/* Return true if the stream STREAM is opened read-only, or if the
+ last operation on the stream was a read operation. Return false if
+ the stream is opened write-only or append-only, or if it supports
+ writing and there is no current read operation (such as fgetc).
+
+ freading and fwriting will never both be true. If STREAM supports
+ both reads and writes, then:
+ - both freading and fwriting might be false when the stream is first
+ opened, after read encounters EOF, or after fflush,
+ - freading might be false or true and fwriting might be false
+ after repositioning (such as fseek, fsetpos, or rewind),
+ depending on the underlying implementation.
+
+ STREAM must not be wide-character oriented. */
+
+#if HAVE___FREADING && (!defined __GLIBC__ || defined __UCLIBC__ || __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 7))
+/* Solaris >= 7, not glibc >= 2.2, but glibc >= 2.7, or musl libc */
+
+# include <stdio_ext.h>
+# define freading(stream) (__freading (stream) != 0)
+
+#else
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+extern bool freading (FILE *stream) _GL_ATTRIBUTE_PURE;
+
+# ifdef __cplusplus
+}
+# endif
+
+#endif
diff --git a/lib/freadptr.c b/lib/freadptr.c
new file mode 100644
index 0000000..fbf9de2
--- /dev/null
+++ b/lib/freadptr.c
@@ -0,0 +1,121 @@
+/* Retrieve information about a FILE stream.
+ Copyright (C) 2007-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include "freadptr.h"
+
+#include <stdlib.h>
+
+#include "stdio-impl.h"
+
+const char *
+freadptr (FILE *fp, size_t *sizep)
+{
+ size_t size;
+
+ /* Keep this code in sync with freadahead! */
+#if defined _IO_ftrylockfile || __GNU_LIBRARY__ == 1 /* GNU libc, BeOS, Haiku, Linux libc5 */
+ if (fp->_IO_write_ptr > fp->_IO_write_base)
+ return NULL;
+ size = fp->_IO_read_end - fp->_IO_read_ptr;
+ if (size == 0)
+ return NULL;
+ *sizep = size;
+ return (const char *) fp->_IO_read_ptr;
+#elif defined __sferror || defined __DragonFly__ || defined __ANDROID__
+ /* FreeBSD, NetBSD, OpenBSD, DragonFly, Mac OS X, Cygwin, Android */
+ if ((fp_->_flags & __SWR) != 0 || fp_->_r < 0)
+ return NULL;
+ size = fp_->_r;
+ if (size == 0)
+ return NULL;
+ *sizep = size;
+ return (const char *) fp_->_p;
+#elif defined __EMX__ /* emx+gcc */
+ if ((fp->_flags & _IOWRT) != 0)
+ return NULL;
+ /* Note: fp->_ungetc_count > 0 implies fp->_rcount <= 0,
+ fp->_ungetc_count = 0 implies fp->_rcount >= 0. */
+ if (fp->_rcount <= 0)
+ return NULL;
+ if (!(fp->_ungetc_count == 0))
+ abort ();
+ *sizep = fp->_rcount;
+ return fp->_ptr;
+#elif defined __minix /* Minix */
+ if ((fp_->_flags & _IOWRITING) != 0)
+ return NULL;
+ size = fp_->_count;
+ if (size == 0)
+ return NULL;
+ *sizep = size;
+ return (const char *) fp_->_ptr;
+#elif defined _IOERR /* AIX, HP-UX, IRIX, OSF/1, Solaris, OpenServer, mingw, NonStop Kernel */
+ if ((fp_->_flag & _IOWRT) != 0)
+ return NULL;
+ size = fp_->_cnt;
+ if (size == 0)
+ return NULL;
+ *sizep = size;
+ return (const char *) fp_->_ptr;
+#elif defined __UCLIBC__ /* uClibc */
+# ifdef __STDIO_BUFFERS
+ if (fp->__modeflags & __FLAG_WRITING)
+ return NULL;
+ if (fp->__modeflags & __FLAG_UNGOT)
+ return NULL;
+ size = fp->__bufread - fp->__bufpos;
+ if (size == 0)
+ return NULL;
+ *sizep = size;
+ return (const char *) fp->__bufpos;
+# else
+ return NULL;
+# endif
+#elif defined __QNX__ /* QNX */
+ if ((fp->_Mode & 0x2000 /* _MWRITE */) != 0)
+ return NULL;
+ /* fp->_Buf <= fp->_Next <= fp->_Rend */
+ size = fp->_Rend - fp->_Next;
+ if (size == 0)
+ return NULL;
+ *sizep = size;
+ return (const char *) fp->_Next;
+#elif defined __MINT__ /* Atari FreeMiNT */
+ if (!fp->__mode.__read)
+ return NULL;
+ size = fp->__get_limit - fp->__bufp;
+ if (size == 0)
+ return NULL;
+ *sizep = size;
+ return fp->__bufp;
+#elif defined EPLAN9 /* Plan9 */
+ if (fp->state == 4 /* WR */)
+ return NULL;
+ if (fp->rp >= fp->wp)
+ return NULL;
+ *sizep = fp->wp - fp->rp;
+ return fp->rp;
+#elif defined SLOW_BUT_NO_HACKS /* users can define this */
+ /* This implementation is correct on any ANSI C platform. It is just
+ awfully slow. */
+ return NULL;
+#else
+ #error "Please port gnulib freadptr.c to your platform! Look at the definition of fflush, fread, getc, getc_unlocked on your system, then report this to bug-gnulib."
+#endif
+}
diff --git a/lib/freadptr.h b/lib/freadptr.h
new file mode 100644
index 0000000..96a2066
--- /dev/null
+++ b/lib/freadptr.h
@@ -0,0 +1,48 @@
+/* Retrieve information about a FILE stream.
+ Copyright (C) 2007-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <stddef.h>
+#include <stdio.h>
+
+/* Assuming the stream STREAM is open for reading:
+ Return a pointer to the input buffer of STREAM, or NULL.
+ If the returned pointer is non-NULL, *SIZEP is set to the (positive) size
+ of the input buffer.
+ If the returned pointer is NULL, you should use getc (STREAM),
+ fgetc (STREAM), or fread (..., STREAM) to access the input from STREAM.
+
+ The resulting pointer becomes invalid upon any operation on STREAM.
+
+ STREAM must not be wide-character oriented. */
+
+#if HAVE___FREADPTR /* musl libc */
+
+# include <stdio_ext.h>
+# define freadptr(stream,sizep) __freadptr (stream, sizep)
+
+#else
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+extern const char * freadptr (FILE *stream, size_t *sizep);
+
+# ifdef __cplusplus
+}
+# endif
+
+#endif
diff --git a/lib/freadseek.c b/lib/freadseek.c
new file mode 100644
index 0000000..c613c6b
--- /dev/null
+++ b/lib/freadseek.c
@@ -0,0 +1,144 @@
+/* Skipping input from a FILE stream.
+ Copyright (C) 2007-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include "freadseek.h"
+
+#include <stdlib.h>
+#include <unistd.h>
+
+#include "freadahead.h"
+#include "freadptr.h"
+
+#include "stdio-impl.h"
+
+/* Increment the in-memory pointer. INCREMENT must be at most the buffer size
+ returned by freadptr().
+ This is very cheap (no system calls). */
+static void
+freadptrinc (FILE *fp, size_t increment)
+{
+ /* Keep this code in sync with freadptr! */
+#if HAVE___FREADPTRINC /* musl libc */
+ __freadptrinc (fp, increment);
+#elif defined _IO_ftrylockfile || __GNU_LIBRARY__ == 1 /* GNU libc, BeOS, Haiku, Linux libc5 */
+ fp->_IO_read_ptr += increment;
+#elif defined __sferror || defined __DragonFly__ || defined __ANDROID__
+ /* FreeBSD, NetBSD, OpenBSD, DragonFly, Mac OS X, Cygwin, Android */
+ fp_->_p += increment;
+ fp_->_r -= increment;
+#elif defined __EMX__ /* emx+gcc */
+ fp->_ptr += increment;
+ fp->_rcount -= increment;
+#elif defined __minix /* Minix */
+ fp_->_ptr += increment;
+ fp_->_count -= increment;
+#elif defined _IOERR /* AIX, HP-UX, IRIX, OSF/1, Solaris, OpenServer, mingw, NonStop Kernel */
+ fp_->_ptr += increment;
+ fp_->_cnt -= increment;
+#elif defined __UCLIBC__ /* uClibc */
+# ifdef __STDIO_BUFFERS
+ fp->__bufpos += increment;
+# else
+ abort ();
+# endif
+#elif defined __QNX__ /* QNX */
+ fp->_Next += increment;
+#elif defined __MINT__ /* Atari FreeMiNT */
+ fp->__bufp += increment;
+#elif defined EPLAN9 /* Plan9 */
+ fp->rp += increment;
+#elif defined SLOW_BUT_NO_HACKS /* users can define this */
+#else
+ #error "Please port gnulib freadseek.c to your platform! Look at the definition of getc, getc_unlocked on your system, then report this to bug-gnulib."
+#endif
+}
+
+int
+freadseek (FILE *fp, size_t offset)
+{
+ size_t total_buffered;
+ int fd;
+
+ if (offset == 0)
+ return 0;
+
+ /* Seek over the already read and buffered input as quickly as possible,
+ without doing any system calls. */
+ total_buffered = freadahead (fp);
+ /* This loop is usually executed at most twice: once for ungetc buffer (if
+ present) and once for the main buffer. */
+ while (total_buffered > 0)
+ {
+ size_t buffered;
+
+ if (freadptr (fp, &buffered) != NULL && buffered > 0)
+ {
+ size_t increment = (buffered < offset ? buffered : offset);
+
+ freadptrinc (fp, increment);
+ offset -= increment;
+ if (offset == 0)
+ return 0;
+ total_buffered -= increment;
+ if (total_buffered == 0)
+ break;
+ }
+ /* Read one byte. If we were reading from the ungetc buffer, this
+ switches the stream back to the main buffer. */
+ if (fgetc (fp) == EOF)
+ goto eof;
+ offset--;
+ if (offset == 0)
+ return 0;
+ total_buffered--;
+ }
+
+ /* Test whether the stream is seekable or not. */
+ fd = fileno (fp);
+ if (fd >= 0 && lseek (fd, 0, SEEK_CUR) >= 0)
+ {
+ /* FP refers to a regular file. fseek is most efficient in this case. */
+ return fseeko (fp, offset, SEEK_CUR);
+ }
+ else
+ {
+ /* FP is a non-seekable stream, possibly not even referring to a file
+ descriptor. Read OFFSET bytes explicitly and discard them. */
+ char buf[4096];
+
+ do
+ {
+ size_t count = (sizeof (buf) < offset ? sizeof (buf) : offset);
+ if (fread (buf, 1, count, fp) < count)
+ goto eof;
+ offset -= count;
+ }
+ while (offset > 0);
+
+ return 0;
+ }
+
+ eof:
+ /* EOF, or error before or while reading. */
+ if (ferror (fp))
+ return EOF;
+ else
+ /* Encountered EOF. */
+ return 0;
+}
diff --git a/lib/freadseek.h b/lib/freadseek.h
new file mode 100644
index 0000000..3baec6e
--- /dev/null
+++ b/lib/freadseek.h
@@ -0,0 +1,42 @@
+/* Skipping input from a FILE stream.
+ Copyright (C) 2007-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <stddef.h>
+#include <stdio.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Assuming the stream STREAM is open for reading:
+
+ Read and discard OFFSET bytes from STREAM.
+
+ freadseek (STREAM, OFFSET) is the same as
+ fseek (STREAM, OFFSET, SEEK_CUR), except that the latter does not work
+ on non-seekable input streams (such as pipes).
+
+ Upon success, return 0.
+ Upon premature end of stream, return 0 (like fseek does).
+ Upon error, set the error indicator in the stream and return EOF.
+
+ STREAM must not be wide-character oriented. */
+
+extern int freadseek (FILE *stream, size_t offset);
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/lib/freopen-safer.c b/lib/freopen-safer.c
new file mode 100644
index 0000000..0704c16
--- /dev/null
+++ b/lib/freopen-safer.c
@@ -0,0 +1,103 @@
+/* Invoke freopen, but avoid some glitches.
+
+ Copyright (C) 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Eric Blake. */
+
+#include <config.h>
+
+#include "stdio-safer.h"
+
+#include <errno.h>
+#include <fcntl.h>
+#include <stdbool.h>
+#include <unistd.h>
+
+/* Guarantee that FD is open; all smaller FDs must already be open.
+ Return true if successful. */
+static bool
+protect_fd (int fd)
+{
+ int value = open ("/dev/null", O_RDONLY);
+ if (value != fd)
+ {
+ if (0 <= value)
+ {
+ close (value);
+ errno = EBADF; /* Unexpected; this is as good as anything else. */
+ }
+ return false;
+ }
+ return true;
+}
+
+/* Like freopen, but guarantee that reopening stdin, stdout, or stderr
+ preserves the invariant that STDxxx_FILENO==fileno(stdxxx), and
+ that no other stream will interfere with the standard streams.
+ This is necessary because most freopen implementations will change
+ the associated fd of a stream to the lowest available slot. */
+
+FILE *
+freopen_safer (char const *name, char const *mode, FILE *f)
+{
+ /* Unfortunately, we cannot use the fopen_safer approach of using
+ fdopen (dup_safer (fileno (freopen (cmd, mode, f)))), because we
+ need to return f itself. The implementation of freopen(NULL,m,f)
+ is system-dependent, so the best we can do is guarantee that all
+ lower-valued standard fds are open prior to the freopen call,
+ even though this puts more pressure on open fds. */
+ bool protect_in = false;
+ bool protect_out = false;
+ bool protect_err = false;
+ int saved_errno;
+
+ switch (fileno (f))
+ {
+ default: /* -1 or not a standard stream. */
+ if (dup2 (STDERR_FILENO, STDERR_FILENO) != STDERR_FILENO)
+ protect_err = true;
+ /* fall through */
+ case STDERR_FILENO:
+ if (dup2 (STDOUT_FILENO, STDOUT_FILENO) != STDOUT_FILENO)
+ protect_out = true;
+ /* fall through */
+ case STDOUT_FILENO:
+ if (dup2 (STDIN_FILENO, STDIN_FILENO) != STDIN_FILENO)
+ protect_in = true;
+ /* fall through */
+ case STDIN_FILENO:
+ /* Nothing left to protect. */
+ break;
+ }
+ if (protect_in && !protect_fd (STDIN_FILENO))
+ f = NULL;
+ else if (protect_out && !protect_fd (STDOUT_FILENO))
+ f = NULL;
+ else if (protect_err && !protect_fd (STDERR_FILENO))
+ f = NULL;
+ else
+ f = freopen (name, mode, f);
+ saved_errno = errno;
+ if (protect_err)
+ close (STDERR_FILENO);
+ if (protect_out)
+ close (STDOUT_FILENO);
+ if (protect_in)
+ close (STDIN_FILENO);
+ if (!f)
+ errno = saved_errno;
+ return f;
+}
diff --git a/lib/freopen.c b/lib/freopen.c
new file mode 100644
index 0000000..4cf7528
--- /dev/null
+++ b/lib/freopen.c
@@ -0,0 +1,67 @@
+/* Open a stream to a file.
+ Copyright (C) 2007-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Bruno Haible <bruno@clisp.org>, 2007. */
+
+/* If the user's config.h happens to include <stdio.h>, let it include only
+ the system's <stdio.h> here, so that orig_freopen doesn't recurse to
+ rpl_freopen. */
+#define __need_FILE
+#include <config.h>
+
+/* Get the original definition of freopen. It might be defined as a macro. */
+#include <stdio.h>
+#undef __need_FILE
+
+#include <errno.h>
+
+static FILE *
+orig_freopen (const char *filename, const char *mode, FILE *stream)
+{
+ return freopen (filename, mode, stream);
+}
+
+/* Specification. */
+/* Write "stdio.h" here, not <stdio.h>, otherwise OSF/1 5.1 DTK cc eliminates
+ this include because of the preliminary #include <stdio.h> above. */
+#include "stdio.h"
+
+#include <string.h>
+
+FILE *
+rpl_freopen (const char *filename, const char *mode, FILE *stream)
+{
+ FILE *result;
+
+#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+ if (filename != NULL && strcmp (filename, "/dev/null") == 0)
+ filename = "NUL";
+#endif
+
+ /* Clear errno to check the success of freopen() with it */
+ errno = 0;
+
+ result = orig_freopen (filename, mode, stream);
+
+#ifdef __KLIBC__
+ /* On OS/2 kLIBC, freopen() returns NULL even if it is successful
+ if filename is NULL. */
+ if (!filename && !result && !errno)
+ result = stream;
+#endif
+
+ return result;
+}
diff --git a/lib/frexp.c b/lib/frexp.c
new file mode 100644
index 0000000..5edb028
--- /dev/null
+++ b/lib/frexp.c
@@ -0,0 +1,168 @@
+/* Split a double into fraction and mantissa.
+ Copyright (C) 2007-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Paolo Bonzini <bonzini@gnu.org>, 2003, and
+ Bruno Haible <bruno@clisp.org>, 2007. */
+
+#if ! defined USE_LONG_DOUBLE
+# include <config.h>
+#endif
+
+/* Specification. */
+#include <math.h>
+
+#include <float.h>
+#ifdef USE_LONG_DOUBLE
+# include "isnanl-nolibm.h"
+# include "fpucw.h"
+#else
+# include "isnand-nolibm.h"
+#endif
+
+/* This file assumes FLT_RADIX = 2. If FLT_RADIX is a power of 2 greater
+ than 2, or not even a power of 2, some rounding errors can occur, so that
+ then the returned mantissa is only guaranteed to be <= 1.0, not < 1.0. */
+
+#ifdef USE_LONG_DOUBLE
+# define FUNC frexpl
+# define DOUBLE long double
+# define ISNAN isnanl
+# define DECL_ROUNDING DECL_LONG_DOUBLE_ROUNDING
+# define BEGIN_ROUNDING() BEGIN_LONG_DOUBLE_ROUNDING ()
+# define END_ROUNDING() END_LONG_DOUBLE_ROUNDING ()
+# define L_(literal) literal##L
+#else
+# define FUNC frexp
+# define DOUBLE double
+# define ISNAN isnand
+# define DECL_ROUNDING
+# define BEGIN_ROUNDING()
+# define END_ROUNDING()
+# define L_(literal) literal
+#endif
+
+DOUBLE
+FUNC (DOUBLE x, int *expptr)
+{
+ int sign;
+ int exponent;
+ DECL_ROUNDING
+
+ /* Test for NaN, infinity, and zero. */
+ if (ISNAN (x) || x + x == x)
+ {
+ *expptr = 0;
+ return x;
+ }
+
+ sign = 0;
+ if (x < 0)
+ {
+ x = - x;
+ sign = -1;
+ }
+
+ BEGIN_ROUNDING ();
+
+ {
+ /* Since the exponent is an 'int', it fits in 64 bits. Therefore the
+ loops are executed no more than 64 times. */
+ DOUBLE pow2[64]; /* pow2[i] = 2^2^i */
+ DOUBLE powh[64]; /* powh[i] = 2^-2^i */
+ int i;
+
+ exponent = 0;
+ if (x >= L_(1.0))
+ {
+ /* A positive exponent. */
+ DOUBLE pow2_i; /* = pow2[i] */
+ DOUBLE powh_i; /* = powh[i] */
+
+ /* Invariants: pow2_i = 2^2^i, powh_i = 2^-2^i,
+ x * 2^exponent = argument, x >= 1.0. */
+ for (i = 0, pow2_i = L_(2.0), powh_i = L_(0.5);
+ ;
+ i++, pow2_i = pow2_i * pow2_i, powh_i = powh_i * powh_i)
+ {
+ if (x >= pow2_i)
+ {
+ exponent += (1 << i);
+ x *= powh_i;
+ }
+ else
+ break;
+
+ pow2[i] = pow2_i;
+ powh[i] = powh_i;
+ }
+ /* Avoid making x too small, as it could become a denormalized
+ number and thus lose precision. */
+ while (i > 0 && x < pow2[i - 1])
+ {
+ i--;
+ powh_i = powh[i];
+ }
+ exponent += (1 << i);
+ x *= powh_i;
+ /* Here 2^-2^i <= x < 1.0. */
+ }
+ else
+ {
+ /* A negative or zero exponent. */
+ DOUBLE pow2_i; /* = pow2[i] */
+ DOUBLE powh_i; /* = powh[i] */
+
+ /* Invariants: pow2_i = 2^2^i, powh_i = 2^-2^i,
+ x * 2^exponent = argument, x < 1.0. */
+ for (i = 0, pow2_i = L_(2.0), powh_i = L_(0.5);
+ ;
+ i++, pow2_i = pow2_i * pow2_i, powh_i = powh_i * powh_i)
+ {
+ if (x < powh_i)
+ {
+ exponent -= (1 << i);
+ x *= pow2_i;
+ }
+ else
+ break;
+
+ pow2[i] = pow2_i;
+ powh[i] = powh_i;
+ }
+ /* Here 2^-2^i <= x < 1.0. */
+ }
+
+ /* Invariants: x * 2^exponent = argument, and 2^-2^i <= x < 1.0. */
+ while (i > 0)
+ {
+ i--;
+ if (x < powh[i])
+ {
+ exponent -= (1 << i);
+ x *= pow2[i];
+ }
+ }
+ /* Here 0.5 <= x < 1.0. */
+ }
+
+ if (sign < 0)
+ x = - x;
+
+ END_ROUNDING ();
+
+ *expptr = exponent;
+ return x;
+}
diff --git a/lib/frexpl.c b/lib/frexpl.c
new file mode 100644
index 0000000..714a2ff
--- /dev/null
+++ b/lib/frexpl.c
@@ -0,0 +1,35 @@
+/* Split a 'long double' into fraction and mantissa.
+ Copyright (C) 2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+#if HAVE_SAME_LONG_DOUBLE_AS_DOUBLE
+
+/* Specification. */
+# include <math.h>
+
+long double
+frexpl (long double x, int *expptr)
+{
+ return frexp (x, expptr);
+}
+
+#else
+
+# define USE_LONG_DOUBLE
+# include "frexp.c"
+
+#endif
diff --git a/lib/fseek.c b/lib/fseek.c
new file mode 100644
index 0000000..8524a42
--- /dev/null
+++ b/lib/fseek.c
@@ -0,0 +1,30 @@
+/* An fseek() function that, together with fflush(), is POSIX compliant.
+ Copyright (C) 2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <stdio.h>
+
+/* Get off_t. */
+#include <unistd.h>
+
+int
+fseek (FILE *fp, long offset, int whence)
+{
+ /* Use the replacement fseeko function with all its workarounds. */
+ return fseeko (fp, (off_t)offset, whence);
+}
diff --git a/lib/fseeko.c b/lib/fseeko.c
new file mode 100644
index 0000000..4cdb1f6
--- /dev/null
+++ b/lib/fseeko.c
@@ -0,0 +1,162 @@
+/* An fseeko() function that, together with fflush(), is POSIX compliant.
+ Copyright (C) 2007-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <stdio.h>
+
+/* Get off_t, lseek, _POSIX_VERSION. */
+#include <unistd.h>
+
+#include "stdio-impl.h"
+
+int
+fseeko (FILE *fp, off_t offset, int whence)
+#undef fseeko
+#if !HAVE_FSEEKO
+# undef fseek
+# define fseeko fseek
+#endif
+#if _GL_WINDOWS_64_BIT_OFF_T
+# undef fseeko
+# if HAVE__FSEEKI64 /* msvc, mingw64 */
+# define fseeko _fseeki64
+# else /* mingw */
+# define fseeko fseeko64
+# endif
+#endif
+{
+#if LSEEK_PIPE_BROKEN
+ /* mingw gives bogus answers rather than failure on non-seekable files. */
+ if (lseek (fileno (fp), 0, SEEK_CUR) == -1)
+ return EOF;
+#endif
+
+ /* These tests are based on fpurge.c. */
+#if defined _IO_ftrylockfile || __GNU_LIBRARY__ == 1 /* GNU libc, BeOS, Haiku, Linux libc5 */
+ if (fp->_IO_read_end == fp->_IO_read_ptr
+ && fp->_IO_write_ptr == fp->_IO_write_base
+ && fp->_IO_save_base == NULL)
+#elif defined __sferror || defined __DragonFly__ || defined __ANDROID__
+ /* FreeBSD, NetBSD, OpenBSD, DragonFly, Mac OS X, Cygwin, Android */
+# if defined __SL64 && defined __SCLE /* Cygwin */
+ if ((fp->_flags & __SL64) == 0)
+ {
+ /* Cygwin 1.5.0 through 1.5.24 failed to open stdin in 64-bit
+ mode; but has an fseeko that requires 64-bit mode. */
+ FILE *tmp = fopen ("/dev/null", "r");
+ if (!tmp)
+ return -1;
+ fp->_flags |= __SL64;
+ fp->_seek64 = tmp->_seek64;
+ fclose (tmp);
+ }
+# endif
+ if (fp_->_p == fp_->_bf._base
+ && fp_->_r == 0
+ && fp_->_w == ((fp_->_flags & (__SLBF | __SNBF | __SRD)) == 0 /* fully buffered and not currently reading? */
+ ? fp_->_bf._size
+ : 0)
+ && fp_ub._base == NULL)
+#elif defined __EMX__ /* emx+gcc */
+ if (fp->_ptr == fp->_buffer
+ && fp->_rcount == 0
+ && fp->_wcount == 0
+ && fp->_ungetc_count == 0)
+#elif defined __minix /* Minix */
+ if (fp_->_ptr == fp_->_buf
+ && (fp_->_ptr == NULL || fp_->_count == 0))
+#elif defined _IOERR /* AIX, HP-UX, IRIX, OSF/1, Solaris, OpenServer, mingw, NonStop Kernel */
+ if (fp_->_ptr == fp_->_base
+ && (fp_->_ptr == NULL || fp_->_cnt == 0))
+#elif defined __UCLIBC__ /* uClibc */
+ if (((fp->__modeflags & __FLAG_WRITING) == 0
+ || fp->__bufpos == fp->__bufstart)
+ && ((fp->__modeflags & (__FLAG_READONLY | __FLAG_READING)) == 0
+ || fp->__bufpos == fp->__bufread))
+#elif defined __QNX__ /* QNX */
+ if ((fp->_Mode & 0x2000 /* _MWRITE */ ? fp->_Next == fp->_Buf : fp->_Next == fp->_Rend)
+ && fp->_Rback == fp->_Back + sizeof (fp->_Back)
+ && fp->_Rsave == NULL)
+#elif defined __MINT__ /* Atari FreeMiNT */
+ if (fp->__bufp == fp->__buffer
+ && fp->__get_limit == fp->__bufp
+ && fp->__put_limit == fp->__bufp
+ && !fp->__pushed_back)
+#elif defined EPLAN9 /* Plan9 */
+ if (fp->rp == fp->buf
+ && fp->wp == fp->buf)
+#elif FUNC_FFLUSH_STDIN < 0 && 200809 <= _POSIX_VERSION
+ /* Cross-compiling to some other system advertising conformance to
+ POSIX.1-2008 or later. Assume fseeko and fflush work as advertised.
+ If this assumption is incorrect, please report the bug to
+ bug-gnulib. */
+ if (0)
+#else
+ #error "Please port gnulib fseeko.c to your platform! Look at the code in fseeko.c, then report this to bug-gnulib."
+#endif
+ {
+ /* We get here when an fflush() call immediately preceded this one (or
+ if ftell() has created buffers but no I/O has occurred on a
+ newly-opened stream). We know there are no buffers. */
+ off_t pos = lseek (fileno (fp), offset, whence);
+ if (pos == -1)
+ {
+#if defined __sferror || defined __DragonFly__ || defined __ANDROID__
+ /* FreeBSD, NetBSD, OpenBSD, DragonFly, Mac OS X, Cygwin, Android */
+ fp_->_flags &= ~__SOFF;
+#endif
+ return -1;
+ }
+
+#if defined _IO_ftrylockfile || __GNU_LIBRARY__ == 1 /* GNU libc, BeOS, Haiku, Linux libc5 */
+ fp->_flags &= ~_IO_EOF_SEEN;
+ fp->_offset = pos;
+#elif defined __sferror || defined __DragonFly__ || defined __ANDROID__
+ /* FreeBSD, NetBSD, OpenBSD, DragonFly, Mac OS X, Cygwin, Android */
+# if defined __CYGWIN__ || (defined __NetBSD__ && __NetBSD_Version__ >= 600000000)
+ /* fp_->_offset is typed as an integer. */
+ fp_->_offset = pos;
+# else
+ /* fp_->_offset is an fpos_t. */
+ {
+ /* Use a union, since on NetBSD, the compilation flags
+ determine whether fpos_t is typedef'd to off_t or a struct
+ containing a single off_t member. */
+ union
+ {
+ fpos_t f;
+ off_t o;
+ } u;
+ u.o = pos;
+ fp_->_offset = u.f;
+ }
+# endif
+ fp_->_flags |= __SOFF;
+ fp_->_flags &= ~__SEOF;
+#elif defined __EMX__ /* emx+gcc */
+ fp->_flags &= ~_IOEOF;
+#elif defined _IOERR /* AIX, HP-UX, IRIX, OSF/1, Solaris, OpenServer, mingw, NonStop Kernel */
+ fp->_flag &= ~_IOEOF;
+#elif defined __MINT__ /* Atari FreeMiNT */
+ fp->__offset = pos;
+ fp->__eof = 0;
+#endif
+ return 0;
+ }
+ return fseeko (fp, offset, whence);
+}
diff --git a/lib/fseterr.c b/lib/fseterr.c
new file mode 100644
index 0000000..5aaa51f
--- /dev/null
+++ b/lib/fseterr.c
@@ -0,0 +1,80 @@
+/* Set the error indicator of a stream.
+ Copyright (C) 2007-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include "fseterr.h"
+
+#include <errno.h>
+
+#include "stdio-impl.h"
+
+void
+fseterr (FILE *fp)
+{
+ /* Most systems provide FILE as a struct and the necessary bitmask in
+ <stdio.h>, because they need it for implementing getc() and putc() as
+ fast macros. */
+#if defined _IO_ftrylockfile || __GNU_LIBRARY__ == 1 /* GNU libc, BeOS, Haiku, Linux libc5 */
+ fp->_flags |= _IO_ERR_SEEN;
+#elif defined __sferror || defined __DragonFly__ || defined __ANDROID__
+ /* FreeBSD, NetBSD, OpenBSD, DragonFly, Mac OS X, Cygwin, Android */
+ fp_->_flags |= __SERR;
+#elif defined __EMX__ /* emx+gcc */
+ fp->_flags |= _IOERR;
+#elif defined __minix /* Minix */
+ fp->_flags |= _IOERR;
+#elif defined _IOERR /* AIX, HP-UX, IRIX, OSF/1, Solaris, OpenServer, mingw, NonStop Kernel */
+ fp_->_flag |= _IOERR;
+#elif defined __UCLIBC__ /* uClibc */
+ fp->__modeflags |= __FLAG_ERROR;
+#elif defined __QNX__ /* QNX */
+ fp->_Mode |= 0x200 /* _MERR */;
+#elif defined __MINT__ /* Atari FreeMiNT */
+ fp->__error = 1;
+#elif defined EPLAN9 /* Plan9 */
+ if (fp->state != 0 /* CLOSED */)
+ fp->state = 5 /* ERR */;
+#elif 0 /* unknown */
+ /* Portable fallback, based on an idea by Rich Felker.
+ Wow! 6 system calls for something that is just a bit operation!
+ Not activated on any system, because there is no way to repair FP when
+ the sequence of system calls fails, and library code should not call
+ abort(). */
+ int saved_errno;
+ int fd;
+ int fd2;
+
+ saved_errno = errno;
+ fflush (fp);
+ fd = fileno (fp);
+ fd2 = dup (fd);
+ if (fd2 >= 0)
+ {
+ close (fd);
+ fputc ('\0', fp); /* This should set the error indicator. */
+ fflush (fp); /* Or this. */
+ if (dup2 (fd2, fd) < 0)
+ /* Whee... we botched the stream and now cannot restore it! */
+ abort ();
+ close (fd2);
+ }
+ errno = saved_errno;
+#else
+ #error "Please port gnulib fseterr.c to your platform! Look at the definitions of ferror and clearerr on your system, then report this to bug-gnulib."
+#endif
+}
diff --git a/lib/fseterr.h b/lib/fseterr.h
new file mode 100644
index 0000000..467565a
--- /dev/null
+++ b/lib/fseterr.h
@@ -0,0 +1,45 @@
+/* Set the error indicator of a stream.
+ Copyright (C) 2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _FSETERR_H
+#define _FSETERR_H
+
+#include <stdio.h>
+
+/* Set the error indicator of the stream FP.
+ The "error indicator" is set when an I/O operation on the stream fails, and
+ is cleared (together with the "end-of-file" indicator) by clearerr (FP). */
+
+#if HAVE___FSETERR /* musl libc */
+
+# include <stdio_ext.h>
+# define fseterr(fp) __fseterr (fp)
+
+#else
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+extern void fseterr (FILE *fp);
+
+# ifdef __cplusplus
+}
+# endif
+
+#endif
+
+#endif /* _FSETERR_H */
diff --git a/lib/fstat.c b/lib/fstat.c
new file mode 100644
index 0000000..435c429
--- /dev/null
+++ b/lib/fstat.c
@@ -0,0 +1,88 @@
+/* fstat() replacement.
+ Copyright (C) 2011-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* If the user's config.h happens to include <sys/stat.h>, let it include only
+ the system's <sys/stat.h> here, so that orig_fstat doesn't recurse to
+ rpl_fstat. */
+#define __need_system_sys_stat_h
+#include <config.h>
+
+/* Get the original definition of fstat. It might be defined as a macro. */
+#include <sys/types.h>
+#include <sys/stat.h>
+#if _GL_WINDOWS_64_BIT_ST_SIZE
+# undef stat /* avoid warning on mingw64 with _FILE_OFFSET_BITS=64 */
+# define stat _stati64
+# undef fstat /* avoid warning on mingw64 with _FILE_OFFSET_BITS=64 */
+# define fstat _fstati64
+#endif
+#undef __need_system_sys_stat_h
+
+static int
+orig_fstat (int fd, struct stat *buf)
+{
+ return fstat (fd, buf);
+}
+
+/* Specification. */
+/* Write "sys/stat.h" here, not <sys/stat.h>, otherwise OSF/1 5.1 DTK cc
+ eliminates this include because of the preliminary #include <sys/stat.h>
+ above. */
+#include "sys/stat.h"
+
+#include <errno.h>
+#include <unistd.h>
+
+#if HAVE_MSVC_INVALID_PARAMETER_HANDLER
+# include "msvc-inval.h"
+#endif
+
+#if HAVE_MSVC_INVALID_PARAMETER_HANDLER
+static int
+fstat_nothrow (int fd, struct stat *buf)
+{
+ int result;
+
+ TRY_MSVC_INVAL
+ {
+ result = orig_fstat (fd, buf);
+ }
+ CATCH_MSVC_INVAL
+ {
+ result = -1;
+ errno = EBADF;
+ }
+ DONE_MSVC_INVAL;
+
+ return result;
+}
+#else
+# define fstat_nothrow orig_fstat
+#endif
+
+int
+rpl_fstat (int fd, struct stat *buf)
+{
+#if REPLACE_FCHDIR && REPLACE_OPEN_DIRECTORY
+ /* Handle the case when rpl_open() used a dummy file descriptor to work
+ around an open() that can't normally visit directories. */
+ const char *name = _gl_directory_name (fd);
+ if (name != NULL)
+ return stat (name, buf);
+#endif
+
+ return fstat_nothrow (fd, buf);
+}
diff --git a/lib/fstatat.c b/lib/fstatat.c
index 92a5164..ebbecfd 100644
--- a/lib/fstatat.c
+++ b/lib/fstatat.c
@@ -1,11 +1,11 @@
/* Work around an fstatat bug on Solaris 9.
- Copyright (C) 2006 Free Software Foundation, Inc.
+ Copyright (C) 2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,45 +13,123 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert and Jim Meyering. */
+/* If the user's config.h happens to include <sys/stat.h>, let it include only
+ the system's <sys/stat.h> here, so that orig_fstatat doesn't recurse to
+ rpl_fstatat. */
+#define __need_system_sys_stat_h
#include <config.h>
-#define COMPILING_FSTATAT 1
-#include "openat.h"
+/* Get the original definition of fstatat. It might be defined as a macro. */
+#include <sys/types.h>
+#include <sys/stat.h>
+#undef __need_system_sys_stat_h
+
+#if HAVE_FSTATAT
+static int
+orig_fstatat (int fd, char const *filename, struct stat *buf, int flags)
+{
+ return fstatat (fd, filename, buf, flags);
+}
+#endif
+
+/* Write "sys/stat.h" here, not <sys/stat.h>, otherwise OSF/1 5.1 DTK cc
+ eliminates this include because of the preliminary #include <sys/stat.h>
+ above. */
+#include "sys/stat.h"
#include <errno.h>
+#include <fcntl.h>
#include <string.h>
+#if HAVE_FSTATAT && HAVE_WORKING_FSTATAT_ZERO_FLAG
+
+# ifndef LSTAT_FOLLOWS_SLASHED_SYMLINK
+# define LSTAT_FOLLOWS_SLASHED_SYMLINK 0
+# endif
+
/* fstatat should always follow symbolic links that end in /, but on
- Solaris 9 it doesn't if AT_SYMLINK_NOFOLLOW is specified. This is
- the same problem that lstat.c addresses, so solve it in a similar
- way. */
+ Solaris 9 it doesn't if AT_SYMLINK_NOFOLLOW is specified.
+ Likewise, trailing slash on a non-directory should be an error.
+ These are the same problems that lstat.c and stat.c address, so
+ solve it in a similar way.
+
+ AIX 7.1 fstatat (AT_FDCWD, ..., 0) always fails, which is a bug.
+ Work around this bug if FSTATAT_AT_FDCWD_0_BROKEN is nonzero. */
int
rpl_fstatat (int fd, char const *file, struct stat *st, int flag)
{
- int result = fstatat (fd, file, st, flag);
+ int result = orig_fstatat (fd, file, st, flag);
+ size_t len;
- if (result == 0 && (flag & AT_SYMLINK_NOFOLLOW) && S_ISLNK (st->st_mode)
- && file[strlen (file) - 1] == '/')
+ if (LSTAT_FOLLOWS_SLASHED_SYMLINK || result != 0)
+ return result;
+ len = strlen (file);
+ if (flag & AT_SYMLINK_NOFOLLOW)
{
- /* FILE refers to a symbolic link and the name ends with a slash.
- Get info about the link's referent. */
- result = fstatat (fd, file, st, flag & ~AT_SYMLINK_NOFOLLOW);
- if (result == 0 && ! S_ISDIR (st->st_mode))
- {
- /* fstatat succeeded and FILE references a non-directory.
- But it was specified via a name including a trailing
- slash. Fail with errno set to ENOTDIR to indicate the
- contradiction. */
- errno = ENOTDIR;
- return -1;
- }
+ /* Fix lstat behavior. */
+ if (file[len - 1] != '/' || S_ISDIR (st->st_mode))
+ return 0;
+ if (!S_ISLNK (st->st_mode))
+ {
+ errno = ENOTDIR;
+ return -1;
+ }
+ result = orig_fstatat (fd, file, st, flag & ~AT_SYMLINK_NOFOLLOW);
+ }
+ /* Fix stat behavior. */
+ if (result == 0 && !S_ISDIR (st->st_mode) && file[len - 1] == '/')
+ {
+ errno = ENOTDIR;
+ return -1;
}
-
return result;
}
+
+#else /* ! (HAVE_FSTATAT && HAVE_WORKING_FSTATAT_ZERO_FLAG) */
+
+/* On mingw, the gnulib <sys/stat.h> defines 'stat' as a function-like
+ macro; but using it in AT_FUNC_F2 causes compilation failure
+ because the preprocessor sees a use of a macro that requires two
+ arguments but is only given one. Hence, we need an inline
+ forwarder to get past the preprocessor. */
+static int
+stat_func (char const *name, struct stat *st)
+{
+ return stat (name, st);
+}
+
+/* Likewise, if there is no native 'lstat', then the gnulib
+ <sys/stat.h> defined it as stat, which also needs adjustment. */
+# if !HAVE_LSTAT
+# undef lstat
+# define lstat stat_func
+# endif
+
+/* Replacement for Solaris' function by the same name.
+ <http://www.google.com/search?q=fstatat+site:docs.sun.com>
+ First, try to simulate it via l?stat ("/proc/self/fd/FD/FILE").
+ Failing that, simulate it via save_cwd/fchdir/(stat|lstat)/restore_cwd.
+ If either the save_cwd or the restore_cwd fails (relatively unlikely),
+ then give a diagnostic and exit nonzero.
+ Otherwise, this function works just like Solaris' fstatat. */
+
+# define AT_FUNC_NAME fstatat
+# define AT_FUNC_F1 lstat
+# define AT_FUNC_F2 stat_func
+# define AT_FUNC_USE_F1_COND AT_SYMLINK_NOFOLLOW
+# define AT_FUNC_POST_FILE_PARAM_DECLS , struct stat *st, int flag
+# define AT_FUNC_POST_FILE_ARGS , st
+# include "at-func.c"
+# undef AT_FUNC_NAME
+# undef AT_FUNC_F1
+# undef AT_FUNC_F2
+# undef AT_FUNC_USE_F1_COND
+# undef AT_FUNC_POST_FILE_PARAM_DECLS
+# undef AT_FUNC_POST_FILE_ARGS
+
+#endif /* !HAVE_FSTATAT */
diff --git a/lib/fsusage.c b/lib/fsusage.c
index 337bf53..a230538 100644
--- a/lib/fsusage.c
+++ b/lib/fsusage.c
@@ -1,12 +1,12 @@
/* fsusage.c -- return space usage of mounted file systems
- Copyright (C) 1991, 1992, 1996, 1998, 1999, 2002, 2003, 2004, 2005, 2006
- Free Software Foundation, Inc.
+ Copyright (C) 1991-1992, 1996, 1998-1999, 2002-2006, 2009-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
@@ -24,7 +23,7 @@
#include <limits.h>
#include <sys/types.h>
-#if STAT_STATVFS /* POSIX 1003.1-2001 (and later) with XSI */
+#if STAT_STATVFS || STAT_STATVFS64 /* POSIX 1003.1-2001 (and later) with XSI */
# include <sys/statvfs.h>
#else
/* Don't include backward-compatibility files unless they're needed.
@@ -32,35 +31,30 @@
# include <fcntl.h>
# include <unistd.h>
# include <sys/stat.h>
-# if HAVE_SYS_PARAM_H
-# include <sys/param.h>
-# endif
-# if HAVE_SYS_MOUNT_H
-# include <sys/mount.h>
-# endif
-# if HAVE_SYS_VFS_H
-# include <sys/vfs.h>
-# endif
-# if HAVE_SYS_FS_S5PARAM_H /* Fujitsu UXP/V */
+#if HAVE_SYS_PARAM_H
+# include <sys/param.h>
+#endif
+#if HAVE_SYS_MOUNT_H
+# include <sys/mount.h>
+#endif
+#if HAVE_SYS_VFS_H
+# include <sys/vfs.h>
+#endif
+# if HAVE_SYS_FS_S5PARAM_H /* Fujitsu UXP/V */
# include <sys/fs/s5param.h>
# endif
# if defined HAVE_SYS_FILSYS_H && !defined _CRAY
-# include <sys/filsys.h> /* SVR2 */
+# include <sys/filsys.h> /* SVR2 */
# endif
# if HAVE_SYS_STATFS_H
# include <sys/statfs.h>
# endif
-# if HAVE_DUSTAT_H /* AIX PS/2 */
+# if HAVE_DUSTAT_H /* AIX PS/2 */
# include <sys/dustat.h>
# endif
# include "full-read.h"
#endif
-/* The results of open() in this file are not used with fchdir,
- therefore save some unnecessary work in fchdir.c. */
-#undef open
-#undef close
-
/* Many space usage primitives use all 1 bits to denote a value that is
not applicable or unknown. Propagate this information by returning
a uintmax_t value that is all 1 bits if X is all 1 bits, even if X
@@ -68,13 +62,13 @@
#define PROPAGATE_ALL_ONES(x) \
((sizeof (x) < sizeof (uintmax_t) \
&& (~ (x) == (sizeof (x) < sizeof (int) \
- ? - (1 << (sizeof (x) * CHAR_BIT)) \
- : 0))) \
+ ? - (1 << (sizeof (x) * CHAR_BIT)) \
+ : 0))) \
? UINTMAX_MAX : (uintmax_t) (x))
/* Extract the top bit of X as an uintmax_t value. */
#define EXTRACT_TOP_BIT(x) ((x) \
- & ((uintmax_t) 1 << (sizeof (x) * CHAR_BIT - 1)))
+ & ((uintmax_t) 1 << (sizeof (x) * CHAR_BIT - 1)))
/* If a value is negative, many space usage primitives store it into an
integer variable by assignment, even if the variable's type is unsigned.
@@ -85,6 +79,35 @@
otherwise, use PROPAGATE_ALL_ONES. */
#define PROPAGATE_TOP_BIT(x) ((x) | ~ (EXTRACT_TOP_BIT (x) - 1))
+#ifdef STAT_STATVFS
+/* Return true if statvfs works. This is false for statvfs on systems
+ with GNU libc on Linux kernels before 2.6.36, which stats all
+ preceding entries in /proc/mounts; that makes df hang if even one
+ of the corresponding file systems is hard-mounted but not available. */
+# if ! (__linux__ && (__GLIBC__ || __UCLIBC__))
+/* The FRSIZE fallback is not required in this case. */
+# undef STAT_STATFS2_FRSIZE
+static int statvfs_works (void) { return 1; }
+# else
+# include <string.h> /* for strverscmp */
+# include <sys/utsname.h>
+# include <sys/statfs.h>
+# define STAT_STATFS2_BSIZE 1
+
+static int
+statvfs_works (void)
+{
+ static int statvfs_works_cache = -1;
+ struct utsname name;
+ if (statvfs_works_cache < 0)
+ statvfs_works_cache = (uname (&name) == 0
+ && 0 <= strverscmp (name.release, "2.6.36"));
+ return statvfs_works_cache;
+}
+# endif
+#endif
+
+
/* Fill in the fields of FSP with information about space usage for
the file system on which FILE resides.
DISK is the device on which FILE is mounted, for space-getting
@@ -95,19 +118,44 @@
int
get_fs_usage (char const *file, char const *disk, struct fs_usage *fsp)
{
-#if defined STAT_STATVFS /* POSIX */
+#ifdef STAT_STATVFS /* POSIX, except pre-2.6.36 glibc/Linux */
+
+ if (statvfs_works ())
+ {
+ struct statvfs vfsd;
+
+ if (statvfs (file, &vfsd) < 0)
+ return -1;
+
+ /* f_frsize isn't guaranteed to be supported. */
+ fsp->fsu_blocksize = (vfsd.f_frsize
+ ? PROPAGATE_ALL_ONES (vfsd.f_frsize)
+ : PROPAGATE_ALL_ONES (vfsd.f_bsize));
+
+ fsp->fsu_blocks = PROPAGATE_ALL_ONES (vfsd.f_blocks);
+ fsp->fsu_bfree = PROPAGATE_ALL_ONES (vfsd.f_bfree);
+ fsp->fsu_bavail = PROPAGATE_TOP_BIT (vfsd.f_bavail);
+ fsp->fsu_bavail_top_bit_set = EXTRACT_TOP_BIT (vfsd.f_bavail) != 0;
+ fsp->fsu_files = PROPAGATE_ALL_ONES (vfsd.f_files);
+ fsp->fsu_ffree = PROPAGATE_ALL_ONES (vfsd.f_ffree);
+ return 0;
+ }
+
+#endif
+
+#if defined STAT_STATVFS64 /* AIX */
- struct statvfs fsd;
+ struct statvfs64 fsd;
- if (statvfs (file, &fsd) < 0)
+ if (statvfs64 (file, &fsd) < 0)
return -1;
/* f_frsize isn't guaranteed to be supported. */
fsp->fsu_blocksize = (fsd.f_frsize
- ? PROPAGATE_ALL_ONES (fsd.f_frsize)
- : PROPAGATE_ALL_ONES (fsd.f_bsize));
+ ? PROPAGATE_ALL_ONES (fsd.f_frsize)
+ : PROPAGATE_ALL_ONES (fsd.f_bsize));
-#elif defined STAT_STATFS2_FS_DATA /* Ultrix */
+#elif defined STAT_STATFS2_FS_DATA /* Ultrix */
struct fs_data fsd;
@@ -122,7 +170,7 @@ get_fs_usage (char const *file, char const *disk, struct fs_usage *fsp)
fsp->fsu_files = PROPAGATE_ALL_ONES (fsd.fd_req.gtot);
fsp->fsu_ffree = PROPAGATE_ALL_ONES (fsd.fd_req.gfree);
-#elif defined STAT_READ_FILSYS /* SVR2 */
+#elif defined STAT_READ_FILSYS /* SVR2 */
# ifndef SUPERBOFF
# define SUPERBOFF (SUPERB * 512)
# endif
@@ -153,11 +201,11 @@ get_fs_usage (char const *file, char const *disk, struct fs_usage *fsp)
fsp->fsu_bavail = PROPAGATE_TOP_BIT (fsd.s_tfree);
fsp->fsu_bavail_top_bit_set = EXTRACT_TOP_BIT (fsd.s_tfree) != 0;
fsp->fsu_files = (fsd.s_isize == -1
- ? UINTMAX_MAX
- : (fsd.s_isize - 2) * INOPB * (fsd.s_type == Fs2b ? 2 : 1));
+ ? UINTMAX_MAX
+ : (fsd.s_isize - 2) * INOPB * (fsd.s_type == Fs2b ? 2 : 1));
fsp->fsu_ffree = PROPAGATE_ALL_ONES (fsd.s_tinode);
-#elif defined STAT_STATFS3_OSF1
+#elif defined STAT_STATFS3_OSF1 /* OSF/1 */
struct statfs fsd;
@@ -166,7 +214,18 @@ get_fs_usage (char const *file, char const *disk, struct fs_usage *fsp)
fsp->fsu_blocksize = PROPAGATE_ALL_ONES (fsd.f_fsize);
-#elif defined STAT_STATFS2_BSIZE /* 4.3BSD, SunOS 4, HP-UX, AIX */
+#elif defined STAT_STATFS2_FRSIZE /* 2.6 < glibc/Linux < 2.6.36 */
+
+ struct statfs fsd;
+
+ if (statfs (file, &fsd) < 0)
+ return -1;
+
+ fsp->fsu_blocksize = PROPAGATE_ALL_ONES (fsd.f_frsize);
+
+#elif defined STAT_STATFS2_BSIZE /* glibc/Linux < 2.6, 4.3BSD, SunOS 4, \
+ Mac OS X < 10.4, FreeBSD < 5.0, \
+ NetBSD < 3.0, OpenBSD < 4.4 */
struct statfs fsd;
@@ -190,7 +249,7 @@ get_fs_usage (char const *file, char const *disk, struct fs_usage *fsp)
}
# endif /* STATFS_TRUNCATES_BLOCK_COUNTS */
-#elif defined STAT_STATFS2_FSIZE /* 4.4BSD */
+#elif defined STAT_STATFS2_FSIZE /* 4.4BSD and older NetBSD */
struct statfs fsd;
@@ -199,7 +258,8 @@ get_fs_usage (char const *file, char const *disk, struct fs_usage *fsp)
fsp->fsu_blocksize = PROPAGATE_ALL_ONES (fsd.f_fsize);
-#elif defined STAT_STATFS4 /* SVR3, Dynix, Irix, AIX */
+#elif defined STAT_STATFS4 /* SVR3, Dynix, old Irix, old AIX, \
+ Dolphin */
# if !_AIX && !defined _SEQUENT_ && !defined DOLPHIN
# define f_bavail f_bfree
@@ -221,8 +281,9 @@ get_fs_usage (char const *file, char const *disk, struct fs_usage *fsp)
#endif
-#if (defined STAT_STATVFS \
- || (!defined STAT_STATFS2_FS_DATA && !defined STAT_READ_FILSYS))
+#if (defined STAT_STATVFS64 || defined STAT_STATFS3_OSF1 \
+ || defined STAT_STATFS2_FRSIZE || defined STAT_STATFS2_BSIZE \
+ || defined STAT_STATFS2_FSIZE || defined STAT_STATFS4)
fsp->fsu_blocks = PROPAGATE_ALL_ONES (fsd.f_blocks);
fsp->fsu_bfree = PROPAGATE_ALL_ONES (fsd.f_bfree);
@@ -233,6 +294,7 @@ get_fs_usage (char const *file, char const *disk, struct fs_usage *fsp)
#endif
+ (void) disk; /* avoid argument-unused warning */
return 0;
}
diff --git a/lib/fsusage.h b/lib/fsusage.h
index 7fa9f8d..811a95a 100644
--- a/lib/fsusage.h
+++ b/lib/fsusage.h
@@ -1,12 +1,12 @@
/* fsusage.h -- declarations for file system space usage info
- Copyright (C) 1991, 1992, 1997, 2003, 2004, 2005, 2006 Free Software
+ Copyright (C) 1991-1992, 1997, 2003-2006, 2009-2016 Free Software
Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Space usage statistics for a file system. Blocks are 512-byte. */
@@ -27,13 +26,13 @@
struct fs_usage
{
- uintmax_t fsu_blocksize; /* Size of a block. */
- uintmax_t fsu_blocks; /* Total blocks. */
- uintmax_t fsu_bfree; /* Free blocks available to superuser. */
- uintmax_t fsu_bavail; /* Free blocks available to non-superuser. */
- bool fsu_bavail_top_bit_set; /* 1 if fsu_bavail represents a value < 0. */
- uintmax_t fsu_files; /* Total file nodes. */
- uintmax_t fsu_ffree; /* Free file nodes. */
+ uintmax_t fsu_blocksize; /* Size of a block. */
+ uintmax_t fsu_blocks; /* Total blocks. */
+ uintmax_t fsu_bfree; /* Free blocks available to superuser. */
+ uintmax_t fsu_bavail; /* Free blocks available to non-superuser. */
+ bool fsu_bavail_top_bit_set; /* 1 if fsu_bavail represents a value < 0. */
+ uintmax_t fsu_files; /* Total file nodes. */
+ uintmax_t fsu_ffree; /* Free file nodes. */
};
int get_fs_usage (char const *file, char const *disk, struct fs_usage *fsp);
diff --git a/lib/fsync.c b/lib/fsync.c
new file mode 100644
index 0000000..5df79ba
--- /dev/null
+++ b/lib/fsync.c
@@ -0,0 +1,83 @@
+/* Emulate fsync on platforms that lack it, primarily Windows and
+ cross-compilers like MinGW.
+
+ This is derived from sqlite3 sources.
+ http://www.sqlite.org/cvstrac/rlog?f=sqlite/src/os_win.c
+ http://www.sqlite.org/copyright.html
+
+ Written by Richard W.M. Jones <rjones.at.redhat.com>
+
+ Copyright (C) 2008-2016 Free Software Foundation, Inc.
+
+ This library 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 library 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+#include <unistd.h>
+
+#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+
+/* FlushFileBuffers */
+# define WIN32_LEAN_AND_MEAN
+# include <windows.h>
+
+# include <errno.h>
+
+/* Get _get_osfhandle. */
+# include "msvc-nothrow.h"
+
+int
+fsync (int fd)
+{
+ HANDLE h = (HANDLE) _get_osfhandle (fd);
+ DWORD err;
+
+ if (h == INVALID_HANDLE_VALUE)
+ {
+ errno = EBADF;
+ return -1;
+ }
+
+ if (!FlushFileBuffers (h))
+ {
+ /* Translate some Windows errors into rough approximations of Unix
+ * errors. MSDN is useless as usual - in this case it doesn't
+ * document the full range of errors.
+ */
+ err = GetLastError ();
+ switch (err)
+ {
+ case ERROR_ACCESS_DENIED:
+ /* For a read-only handle, fsync should succeed, even though we have
+ no way to sync the access-time changes. */
+ return 0;
+
+ /* eg. Trying to fsync a tty. */
+ case ERROR_INVALID_HANDLE:
+ errno = EINVAL;
+ break;
+
+ default:
+ errno = EIO;
+ }
+ return -1;
+ }
+
+ return 0;
+}
+
+#else /* !Windows */
+
+# error "This platform lacks fsync function, and Gnulib doesn't provide a replacement. This is a bug in Gnulib."
+
+#endif /* !Windows */
diff --git a/lib/ftell.c b/lib/ftell.c
new file mode 100644
index 0000000..75ed1b2
--- /dev/null
+++ b/lib/ftell.c
@@ -0,0 +1,37 @@
+/* An ftell() function that works around platform bugs.
+ Copyright (C) 2007-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <stdio.h>
+
+#include <errno.h>
+#include <limits.h>
+
+long
+ftell (FILE *fp)
+{
+ /* Use the replacement ftello function with all its workarounds. */
+ off_t offset = ftello (fp);
+ if (LONG_MIN <= offset && offset <= LONG_MAX)
+ return /* (long) */ offset;
+ else
+ {
+ errno = EOVERFLOW;
+ return -1;
+ }
+}
diff --git a/lib/ftello.c b/lib/ftello.c
new file mode 100644
index 0000000..4c18ed1
--- /dev/null
+++ b/lib/ftello.c
@@ -0,0 +1,85 @@
+/* An ftello() function that works around platform bugs.
+ Copyright (C) 2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <stdio.h>
+
+/* Get lseek. */
+#include <unistd.h>
+
+#include "stdio-impl.h"
+
+off_t
+ftello (FILE *fp)
+#undef ftello
+#if !HAVE_FTELLO
+# undef ftell
+# define ftello ftell
+#endif
+#if _GL_WINDOWS_64_BIT_OFF_T
+# undef ftello
+# if HAVE__FTELLI64 /* msvc, mingw64 */
+# define ftello _ftelli64
+# else /* mingw */
+# define ftello ftello64
+# endif
+#endif
+{
+#if LSEEK_PIPE_BROKEN
+ /* mingw gives bogus answers rather than failure on non-seekable files. */
+ if (lseek (fileno (fp), 0, SEEK_CUR) == -1)
+ return -1;
+#endif
+
+#if FTELLO_BROKEN_AFTER_SWITCHING_FROM_READ_TO_WRITE /* Solaris */
+ /* The Solaris stdio leaves the _IOREAD flag set after reading from a file
+ reaches EOF and the program then starts writing to the file. ftello
+ gets confused by this. */
+ if (fp_->_flag & _IOWRT)
+ {
+ off_t pos;
+
+ /* Call ftello nevertheless, for the side effects that it does on fp. */
+ ftello (fp);
+
+ /* Compute the file position ourselves. */
+ pos = lseek (fileno (fp), (off_t) 0, SEEK_CUR);
+ if (pos >= 0)
+ {
+ if ((fp_->_flag & _IONBF) == 0 && fp_->_base != NULL)
+ pos += fp_->_ptr - fp_->_base;
+ }
+ return pos;
+ }
+#endif
+
+#if defined __SL64 && defined __SCLE /* Cygwin */
+ if ((fp->_flags & __SL64) == 0)
+ {
+ /* Cygwin 1.5.0 through 1.5.24 failed to open stdin in 64-bit
+ mode; but has an ftello that requires 64-bit mode. */
+ FILE *tmp = fopen ("/dev/null", "r");
+ if (!tmp)
+ return -1;
+ fp->_flags |= __SL64;
+ fp->_seek64 = tmp->_seek64;
+ fclose (tmp);
+ }
+#endif
+ return ftello (fp);
+}
diff --git a/lib/ftoastr.c b/lib/ftoastr.c
new file mode 100644
index 0000000..e3a0138
--- /dev/null
+++ b/lib/ftoastr.c
@@ -0,0 +1,137 @@
+/* floating point to accurate string
+
+ Copyright (C) 2010-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Paul Eggert. */
+
+/* This code can misbehave on some buggy or older platforms, when
+ operating on arguments on floating types other than 'double', or
+ when given unusual combinations of options. Gnulib's
+ snprintf-posix module works around many of these problems.
+
+ This code relies on sprintf, strtod, etc. operating accurately;
+ otherwise, the resulting strings could be inaccurate or too long. */
+
+#include <config.h>
+
+#include "ftoastr.h"
+
+#include <float.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#if LENGTH == 3
+# define FLOAT long double
+# define FLOAT_DIG LDBL_DIG
+# define FLOAT_MIN LDBL_MIN
+# define FLOAT_PREC_BOUND _GL_LDBL_PREC_BOUND
+# define FTOASTR ldtoastr
+# if HAVE_C99_STRTOLD
+# define STRTOF strtold
+# endif
+#elif LENGTH == 2
+# define FLOAT double
+# define FLOAT_DIG DBL_DIG
+# define FLOAT_MIN DBL_MIN
+# define FLOAT_PREC_BOUND _GL_DBL_PREC_BOUND
+# define FTOASTR dtoastr
+#else
+# define LENGTH 1
+# define FLOAT float
+# define FLOAT_DIG FLT_DIG
+# define FLOAT_MIN FLT_MIN
+# define FLOAT_PREC_BOUND _GL_FLT_PREC_BOUND
+# define FTOASTR ftoastr
+# if HAVE_STRTOF
+# define STRTOF strtof
+# endif
+#endif
+
+/* On pre-C99 hosts, approximate strtof and strtold with strtod. This
+ may generate one or two extra digits, but that's better than not
+ working at all. */
+#ifndef STRTOF
+# define STRTOF strtod
+#endif
+
+/* On hosts where it's not known that snprintf works, use sprintf to
+ implement the subset needed here. Typically BUFSIZE is big enough
+ and there's little or no performance hit. */
+#if ! GNULIB_SNPRINTF
+# undef snprintf
+# define snprintf ftoastr_snprintf
+static int
+ftoastr_snprintf (char *buf, size_t bufsize, char const *format,
+ int width, int prec, FLOAT x)
+{
+ char width_0_buffer[LENGTH == 1 ? FLT_BUFSIZE_BOUND
+ : LENGTH == 2 ? DBL_BUFSIZE_BOUND
+ : LDBL_BUFSIZE_BOUND];
+ int n = width;
+ if (bufsize < sizeof width_0_buffer)
+ {
+ n = sprintf (width_0_buffer, format, 0, prec, x);
+ if (n < 0)
+ return n;
+ if (n < width)
+ n = width;
+ }
+ if (n < bufsize)
+ n = sprintf (buf, format, width, prec, x);
+ return n;
+}
+#endif
+
+int
+FTOASTR (char *buf, size_t bufsize, int flags, int width, FLOAT x)
+{
+ /* The following method is simple but slow.
+ For ideas about speeding things up, please see:
+
+ Florian Loitsch, Printing floating-point numbers quickly and accurately
+ with integers. ACM SIGPLAN notices 46, 6 (June 2010), 233-243
+ <http://dx.doi.org/10.1145/1809028.1806623>; also see the
+ 2010-03-21 draft <http://florian.loitsch.com/tmp/article.pdf>. */
+
+ char format[sizeof "%-+ 0*.*Lg"];
+ FLOAT abs_x = x < 0 ? -x : x;
+ int prec;
+
+ char *p = format;
+ *p++ = '%';
+
+ /* Support flags that generate output parsable by strtof. */
+ *p = '-'; p += (flags & FTOASTR_LEFT_JUSTIFY ) != 0;
+ *p = '+'; p += (flags & FTOASTR_ALWAYS_SIGNED ) != 0;
+ *p = ' '; p += (flags & FTOASTR_SPACE_POSITIVE) != 0;
+ *p = '0'; p += (flags & FTOASTR_ZERO_PAD ) != 0;
+
+ *p++ = '*';
+ *p++ = '.';
+ *p++ = '*';
+ *p = 'L'; p += 2 < LENGTH;
+ *p++ = flags & FTOASTR_UPPER_E ? 'G' : 'g';
+ *p = '\0';
+
+ for (prec = abs_x < FLOAT_MIN ? 1 : FLOAT_DIG; ; prec++)
+ {
+ int n = snprintf (buf, bufsize, format, width, prec, x);
+ if (n < 0
+ || FLOAT_PREC_BOUND <= prec
+ || (n < bufsize && STRTOF (buf, NULL) == x))
+ return n;
+ }
+}
diff --git a/lib/ftoastr.h b/lib/ftoastr.h
new file mode 100644
index 0000000..9207809
--- /dev/null
+++ b/lib/ftoastr.h
@@ -0,0 +1,145 @@
+/* floating point to accurate string
+
+ Copyright (C) 2010-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Paul Eggert. */
+
+#ifndef _GL_FTOASTR_H
+
+#include "intprops.h"
+#include <float.h>
+#include <stddef.h>
+
+/* Store into BUF (of size BUFSIZE) an accurate minimal-precision
+ string representation of a floating point number. FLAGS affect the
+ formatting of the number. Pad the output string with spaces as
+ necessary to width WIDTH bytes, in the style of printf. WIDTH must
+ be nonnegative. X is the floating-point number to be converted.
+
+ Return the number of bytes stored into BUF, not counting the
+ terminating null. However, do not overrun BUF: if BUF is too
+ small, return a fairly tight (but not necessarily exact) upper
+ bound on the value that would have been returned if BUF had been
+ big enough. If SIZE is zero, BUF may be a null pointer. On error
+ (e.g., returned value would exceed INT_MAX), return -1 and set
+ errno.
+
+ Example:
+
+ char buf[DBL_BUFSIZE_BOUND];
+ int r = dtoastr (buf, sizeof buf, 0, 0, 0.1);
+
+ In the C locale, this sets R to 3 and stores "0.1" into BUF. */
+
+int ftoastr (char *buf, size_t bufsize, int flags, int width, float x);
+int dtoastr (char *buf, size_t bufsize, int flags, int width, double x);
+int ldtoastr (char *buf, size_t bufsize, int flags, int width, long double x);
+
+/* Flag values for ftoastr etc. These can be ORed together. */
+enum
+ {
+ /* Left justify within the width; the default is right justification. */
+ FTOASTR_LEFT_JUSTIFY = 1,
+
+ /* Output "+" before positive numbers; the default outputs nothing. */
+ FTOASTR_ALWAYS_SIGNED = 2,
+
+ /* Output " " before positive numbers; ignored if
+ FTOASTR_ALWAYS_SIGNED is also given. */
+ FTOASTR_SPACE_POSITIVE = 4,
+
+ /* Pad with zeros instead of spaces; ignored if FTOASTR_LEFT_JUSTIFY
+ is also given. */
+ FTOASTR_ZERO_PAD = 8,
+
+ /* Use 'E' instead of 'e' before the exponent. */
+ FTOASTR_UPPER_E = 16
+ };
+
+
+/* _GL_FLT_PREC_BOUND is an upper bound on the precision needed to
+ represent a float value without losing information. Likewise for
+ _GL_DBL_PREC_BOUND and double, and _GL_LDBL_PREC_BOUND and long double.
+ These are macros, not enums, to work around a bug in IBM xlc 12.1. */
+
+#if FLT_RADIX == 10 /* decimal floating point */
+# define _GL_FLT_PREC_BOUND FLT_MANT_DIG
+# define _GL_DBL_PREC_BOUND DBL_MANT_DIG
+# define _GL_LDBL_PREC_BOUND LDBL_MANT_DIG
+#else
+
+/* An upper bound on the number of bits needed to represent a single
+ digit in a floating-point fraction. */
+# if FLT_RADIX == 2 /* IEEE 754 floating point, VAX floating point, etc. */
+# define _GL_FLOAT_DIG_BITS_BOUND 1
+# elif FLT_RADIX <= 16 /* IBM hex floating point has FLT_RADIX == 16. */
+# define _GL_FLOAT_DIG_BITS_BOUND 4
+# else /* no machine is this bad, but let's be complete */
+# define _GL_FLOAT_DIG_BITS_BOUND (CHAR_BIT * (int) sizeof (int) - 1)
+# endif
+
+/* An upper bound on the number of decimal digits needed to represent
+ a floating point number accurately, assuming a fraction contains
+ DIG digits. For why the "+ 1" is needed, see "Binary to Decimal
+ Conversion" in David Goldberg's paper "What Every Computer
+ Scientist Should Know About Floating-Point Arithmetic"
+ <http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html>. */
+# define _GL_FLOAT_PREC_BOUND(dig) \
+ (INT_BITS_STRLEN_BOUND ((dig) * _GL_FLOAT_DIG_BITS_BOUND) + 1)
+
+# define _GL_FLT_PREC_BOUND _GL_FLOAT_PREC_BOUND ( FLT_MANT_DIG)
+# define _GL_DBL_PREC_BOUND _GL_FLOAT_PREC_BOUND ( DBL_MANT_DIG)
+# define _GL_LDBL_PREC_BOUND _GL_FLOAT_PREC_BOUND (LDBL_MANT_DIG)
+#endif
+
+
+/* Bound on the number of bytes printed for an exponent in the range
+ MIN..MAX, where MIN < 0 < MAX; printf always prints a sign and at
+ least 2 digits. Although the maximum known exponent is 4932 for
+ IEEE 754 binary128, support tight bounds for exponents up to a
+ million, just in case. */
+#define _GL_FLOAT_EXPONENT_STRLEN_BOUND(min, max) \
+ ( -100 < (min) && (max) < 100 ? 3 \
+ : -1000 < (min) && (max) < 1000 ? 4 \
+ : -10000 < (min) && (max) < 10000 ? 5 \
+ : -100000 < (min) && (max) < 100000 ? 6 \
+ : -1000000 < (min) && (max) < 1000000 ? 7 \
+ : INT_STRLEN_BOUND (int) /* not a tight bound */)
+
+/* A reasonably tight bound on the length of a type-T floating value
+ formatted with ftoastr etc. Room is needed for sign, fraction
+ digits, decimal point, "e", and exponent. POINTLEN should be a
+ reasonably tight bound on the string length of the decimal
+ point. */
+#define _GL_FLOAT_STRLEN_BOUND_L(t, pointlen) \
+ (1 + _GL_##t##_PREC_BOUND + pointlen + 1 \
+ + _GL_FLOAT_EXPONENT_STRLEN_BOUND (t##_MIN_10_EXP, t##_MAX_10_EXP))
+#define FLT_STRLEN_BOUND_L(pointlen) _GL_FLOAT_STRLEN_BOUND_L ( FLT, pointlen)
+#define DBL_STRLEN_BOUND_L(pointlen) _GL_FLOAT_STRLEN_BOUND_L ( DBL, pointlen)
+#define LDBL_STRLEN_BOUND_L(pointlen) _GL_FLOAT_STRLEN_BOUND_L (LDBL, pointlen)
+
+/* Looser bounds that are locale-independent and are integral constant
+ expressions. */
+#define FLT_STRLEN_BOUND FLT_STRLEN_BOUND_L (MB_LEN_MAX)
+#define DBL_STRLEN_BOUND DBL_STRLEN_BOUND_L (MB_LEN_MAX)
+#define LDBL_STRLEN_BOUND LDBL_STRLEN_BOUND_L (MB_LEN_MAX)
+
+/* Looser, locale-independent bounds that include the trailing null byte. */
+#define FLT_BUFSIZE_BOUND ( FLT_STRLEN_BOUND + 1)
+#define DBL_BUFSIZE_BOUND ( DBL_STRLEN_BOUND + 1)
+#define LDBL_BUFSIZE_BOUND (LDBL_STRLEN_BOUND + 1)
+
+#endif /* _GL_FTOASTR_H */
diff --git a/lib/ftruncate.c b/lib/ftruncate.c
index ff7d11b..1b39c87 100644
--- a/lib/ftruncate.c
+++ b/lib/ftruncate.c
@@ -1,90 +1,188 @@
-/* ftruncate emulations that work on some System V's.
- This file is in the public domain. */
+/* ftruncate emulations for native Windows.
+ Copyright (C) 1992-2016 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, 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 <http://www.gnu.org/licenses/>. */
#include <config.h>
/* Specification. */
#include <unistd.h>
-#include <sys/types.h>
-#include <fcntl.h>
+#if HAVE_CHSIZE
+/* A native Windows platform. */
-#ifdef F_CHSIZE
+# include <errno.h>
-int
-ftruncate (int fd, off_t length)
-{
- return fcntl (fd, F_CHSIZE, length);
-}
+# if _GL_WINDOWS_64_BIT_OFF_T
-#else /* not F_CHSIZE */
-# ifdef F_FREESP
+/* Large File Support: off_t is 64-bit, but chsize() takes only a 32-bit
+ argument. So, define a 64-bit safe SetFileSize function ourselves. */
-/* By William Kucharski <kucharsk@netcom.com>. */
+/* Ensure that <windows.h> declares GetFileSizeEx. */
+# undef _WIN32_WINNT
+# define _WIN32_WINNT 0x500
-# include <sys/stat.h>
-# include <errno.h>
+/* Get declarations of the native Windows API functions. */
+# define WIN32_LEAN_AND_MEAN
+# include <windows.h>
-int
-ftruncate (int fd, off_t length)
+/* Get _get_osfhandle. */
+# include "msvc-nothrow.h"
+
+static BOOL
+SetFileSize (HANDLE h, LONGLONG size)
{
- struct flock fl;
- struct stat filebuf;
+ LARGE_INTEGER old_size;
- if (fstat (fd, &filebuf) < 0)
- return -1;
+ if (!GetFileSizeEx (h, &old_size))
+ return FALSE;
- if (filebuf.st_size < length)
+ if (size != old_size.QuadPart)
{
- /* Extend file length. */
- if (lseek (fd, (length - 1), SEEK_SET) < 0)
- return -1;
-
- /* Write a "0" byte. */
- if (write (fd, "", 1) != 1)
- return -1;
+ /* Duplicate the handle, so we are free to modify its file position. */
+ HANDLE curr_process = GetCurrentProcess ();
+ HANDLE tmph;
+
+ if (!DuplicateHandle (curr_process, /* SourceProcessHandle */
+ h, /* SourceHandle */
+ curr_process, /* TargetProcessHandle */
+ (PHANDLE) &tmph, /* TargetHandle */
+ (DWORD) 0, /* DesiredAccess */
+ FALSE, /* InheritHandle */
+ DUPLICATE_SAME_ACCESS)) /* Options */
+ return FALSE;
+
+ if (size < old_size.QuadPart)
+ {
+ /* Reduce the size. */
+ LONG size_hi = (LONG) (size >> 32);
+ if (SetFilePointer (tmph, (LONG) size, &size_hi, FILE_BEGIN)
+ == INVALID_SET_FILE_POINTER
+ && GetLastError() != NO_ERROR)
+ {
+ CloseHandle (tmph);
+ return FALSE;
+ }
+ if (!SetEndOfFile (tmph))
+ {
+ CloseHandle (tmph);
+ return FALSE;
+ }
+ }
+ else
+ {
+ /* Increase the size by adding zero bytes at the end. */
+ static char zero_bytes[1024];
+ LONG pos_hi = 0;
+ LONG pos_lo = SetFilePointer (tmph, (LONG) 0, &pos_hi, FILE_END);
+ LONGLONG pos;
+ if (pos_lo == INVALID_SET_FILE_POINTER
+ && GetLastError() != NO_ERROR)
+ {
+ CloseHandle (tmph);
+ return FALSE;
+ }
+ pos = ((LONGLONG) pos_hi << 32) | (ULONGLONG) (ULONG) pos_lo;
+ while (pos < size)
+ {
+ DWORD written;
+ LONGLONG count = size - pos;
+ if (count > sizeof (zero_bytes))
+ count = sizeof (zero_bytes);
+ if (!WriteFile (tmph, zero_bytes, (DWORD) count, &written, NULL)
+ || written == 0)
+ {
+ CloseHandle (tmph);
+ return FALSE;
+ }
+ pos += (ULONGLONG) (ULONG) written;
+ }
+ }
+ /* Close the handle. */
+ CloseHandle (tmph);
}
- else
- {
-
- /* Truncate length. */
-
- fl.l_whence = 0;
- fl.l_len = 0;
- fl.l_start = length;
- fl.l_type = F_WRLCK; /* write lock on file space */
+ return TRUE;
+}
- /* This relies on the *undocumented* F_FREESP argument to fcntl,
- which truncates the file so that it ends at the position
- indicated by fl.l_start. Will minor miracles never cease? */
+int
+ftruncate (int fd, off_t length)
+{
+ HANDLE handle = (HANDLE) _get_osfhandle (fd);
- if (fcntl (fd, F_FREESP, &fl) < 0)
- return -1;
+ if (handle == INVALID_HANDLE_VALUE)
+ {
+ errno = EBADF;
+ return -1;
+ }
+ if (length < 0)
+ {
+ errno = EINVAL;
+ return -1;
+ }
+ if (!SetFileSize (handle, length))
+ {
+ switch (GetLastError ())
+ {
+ case ERROR_ACCESS_DENIED:
+ errno = EACCES;
+ break;
+ case ERROR_HANDLE_DISK_FULL:
+ case ERROR_DISK_FULL:
+ case ERROR_DISK_TOO_FRAGMENTED:
+ errno = ENOSPC;
+ break;
+ default:
+ errno = EIO;
+ break;
+ }
+ return -1;
}
-
return 0;
}
-# else /* not F_CHSIZE nor F_FREESP */
-# if HAVE_CHSIZE /* native Windows, e.g. mingw */
+# else
-int
-ftruncate (int fd, off_t length)
+# include <io.h>
+
+# if HAVE_MSVC_INVALID_PARAMETER_HANDLER
+# include "msvc-inval.h"
+static int
+chsize_nothrow (int fd, long length)
{
- return chsize (fd, length);
-}
+ int result;
-# else /* not F_CHSIZE nor F_FREESP nor HAVE_CHSIZE */
+ TRY_MSVC_INVAL
+ {
+ result = chsize (fd, length);
+ }
+ CATCH_MSVC_INVAL
+ {
+ result = -1;
+ errno = EBADF;
+ }
+ DONE_MSVC_INVAL;
-# include <errno.h>
+ return result;
+}
+# define chsize chsize_nothrow
+# endif
int
ftruncate (int fd, off_t length)
{
- errno = EIO;
- return -1;
+ return chsize (fd, length);
}
-# endif /* not HAVE_CHSIZE */
-# endif /* not F_FREESP */
-#endif /* not F_CHSIZE */
+# endif
+#endif
diff --git a/lib/fts-cycle.c b/lib/fts-cycle.c
index 669db58..db617f7 100644
--- a/lib/fts-cycle.c
+++ b/lib/fts-cycle.c
@@ -1,13 +1,13 @@
/* Detect cycles in file tree walks.
- Copyright (C) 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2003-2006, 2009-2016 Free Software Foundation, Inc.
Written by Jim Meyering.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -15,8 +15,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include "cycle-check.h"
#include "hash.h"
@@ -54,15 +53,15 @@ setup_dir (FTS *fts)
{
enum { HT_INITIAL_SIZE = 31 };
fts->fts_cycle.ht = hash_initialize (HT_INITIAL_SIZE, NULL, AD_hash,
- AD_compare, free);
+ AD_compare, free);
if (! fts->fts_cycle.ht)
- return false;
+ return false;
}
else
{
fts->fts_cycle.state = malloc (sizeof *fts->fts_cycle.state);
if (! fts->fts_cycle.state)
- return false;
+ return false;
cycle_check_init (fts->fts_cycle.state);
}
@@ -81,40 +80,40 @@ enter_dir (FTS *fts, FTSENT *ent)
struct Active_dir *ad_from_table;
if (!ad)
- return false;
+ return false;
ad->dev = st->st_dev;
ad->ino = st->st_ino;
ad->fts_ent = ent;
/* See if we've already encountered this directory.
- This can happen when following symlinks as well as
- with a corrupted directory hierarchy. */
+ This can happen when following symlinks as well as
+ with a corrupted directory hierarchy. */
ad_from_table = hash_insert (fts->fts_cycle.ht, ad);
if (ad_from_table != ad)
- {
- free (ad);
- if (!ad_from_table)
- return false;
-
- /* There was an entry with matching dev/inode already in the table.
- Record the fact that we've found a cycle. */
- ent->fts_cycle = ad_from_table->fts_ent;
- ent->fts_info = FTS_DC;
- }
+ {
+ free (ad);
+ if (!ad_from_table)
+ return false;
+
+ /* There was an entry with matching dev/inode already in the table.
+ Record the fact that we've found a cycle. */
+ ent->fts_cycle = ad_from_table->fts_ent;
+ ent->fts_info = FTS_DC;
+ }
}
else
{
if (cycle_check (fts->fts_cycle.state, ent->fts_statp))
- {
- /* FIXME: setting fts_cycle like this isn't proper.
- To do what the documentation requires, we'd have to
- go around the cycle again and find the right entry.
- But no callers in coreutils use the fts_cycle member. */
- ent->fts_cycle = ent;
- ent->fts_info = FTS_DC;
- }
+ {
+ /* FIXME: setting fts_cycle like this isn't proper.
+ To do what the documentation requires, we'd have to
+ go around the cycle again and find the right entry.
+ But no callers in coreutils use the fts_cycle member. */
+ ent->fts_cycle = ent;
+ ent->fts_info = FTS_DC;
+ }
}
return true;
@@ -134,15 +133,15 @@ leave_dir (FTS *fts, FTSENT *ent)
obj.ino = st->st_ino;
found = hash_delete (fts->fts_cycle.ht, &obj);
if (!found)
- abort ();
+ abort ();
free (found);
}
else
{
FTSENT *parent = ent->fts_parent;
if (parent != NULL && 0 <= parent->fts_level)
- CYCLE_CHECK_REFLECT_CHDIR_UP (fts->fts_cycle.state,
- *(parent->fts_statp), *st);
+ CYCLE_CHECK_REFLECT_CHDIR_UP (fts->fts_cycle.state,
+ *(parent->fts_statp), *st);
}
}
@@ -154,7 +153,7 @@ free_dir (FTS *sp)
if (sp->fts_options & (FTS_TIGHT_CYCLE_CHECK | FTS_LOGICAL))
{
if (sp->fts_cycle.ht)
- hash_free (sp->fts_cycle.ht);
+ hash_free (sp->fts_cycle.ht);
}
else
free (sp->fts_cycle.state);
diff --git a/lib/fts.c b/lib/fts.c
index 1b5384b..2c9df2f 100644
--- a/lib/fts.c
+++ b/lib/fts.c
@@ -1,11 +1,11 @@
/* Traverse a file hierarchy.
- Copyright (C) 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
+ Copyright (C) 2004-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,12 +13,11 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/*-
* Copyright (c) 1990, 1993, 1994
- * The Regents of the University of California. All rights reserved.
+ * The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -32,7 +31,7 @@
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
@@ -48,7 +47,7 @@
#include <config.h>
#if defined(LIBC_SCCS) && !defined(lint)
-static char sccsid[] = "@(#)fts.c 8.6 (Berkeley) 8/14/94";
+static char sccsid[] = "@(#)fts.c 8.6 (Berkeley) 8/14/94";
#endif /* LIBC_SCCS and not lint */
#include "fts_.h"
@@ -63,17 +62,21 @@ static char sccsid[] = "@(#)fts.c 8.6 (Berkeley) 8/14/94";
#endif
#include <fcntl.h>
#include <errno.h>
-#include "dirfd.h"
+#include <stdalign.h>
#include <stdbool.h>
+#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#if ! _LIBC
# include "fcntl--.h"
-# include "lstat.h"
-# include "openat.h"
+# include "dirent--.h"
# include "unistd--.h"
+/* FIXME - use fcntl(F_DUPFD_CLOEXEC)/openat(O_CLOEXEC) once they are
+ supported. */
+# include "cloexec.h"
+# include "openat.h"
# include "same-inode.h"
#endif
@@ -87,11 +90,72 @@ static char sccsid[] = "@(#)fts.c 8.6 (Berkeley) 8/14/94";
# define DT_IS_KNOWN(d) ((d)->d_type != DT_UNKNOWN)
/* True if the type of the directory entry D must be T. */
# define DT_MUST_BE(d, t) ((d)->d_type == (t))
+# define D_TYPE(d) ((d)->d_type)
#else
# define DT_IS_KNOWN(d) false
# define DT_MUST_BE(d, t) false
+# define D_TYPE(d) DT_UNKNOWN
+
+# undef DT_UNKNOWN
+# define DT_UNKNOWN 0
+
+/* Any nonzero values will do here, so long as they're distinct.
+ Undef any existing macros out of the way. */
+# undef DT_BLK
+# undef DT_CHR
+# undef DT_DIR
+# undef DT_FIFO
+# undef DT_LNK
+# undef DT_REG
+# undef DT_SOCK
+# define DT_BLK 1
+# define DT_CHR 2
+# define DT_DIR 3
+# define DT_FIFO 4
+# define DT_LNK 5
+# define DT_REG 6
+# define DT_SOCK 7
+#endif
+
+#ifndef S_IFLNK
+# define S_IFLNK 0
+#endif
+#ifndef S_IFSOCK
+# define S_IFSOCK 0
+#endif
+
+enum
+{
+ NOT_AN_INODE_NUMBER = 0
+};
+
+#ifdef D_INO_IN_DIRENT
+# define D_INO(dp) (dp)->d_ino
+#else
+/* Some systems don't have inodes, so fake them to avoid lots of ifdefs. */
+# define D_INO(dp) NOT_AN_INODE_NUMBER
+#endif
+
+/* If possible (see max_entries, below), read no more than this many directory
+ entries at a time. Without this limit (i.e., when using non-NULL
+ fts_compar), processing a directory with 4,000,000 entries requires ~1GiB
+ of memory, and handling 64M entries would require 16GiB of memory. */
+#ifndef FTS_MAX_READDIR_ENTRIES
+# define FTS_MAX_READDIR_ENTRIES 100000
#endif
+/* If there are more than this many entries in a directory,
+ and the conditions mentioned below are satisfied, then sort
+ the entries on inode number before any further processing. */
+#ifndef FTS_INODE_SORT_DIR_ENTRIES_THRESHOLD
+# define FTS_INODE_SORT_DIR_ENTRIES_THRESHOLD 10000
+#endif
+
+enum
+{
+ _FTS_INODE_SORT_DIR_ENTRIES_THRESHOLD = FTS_INODE_SORT_DIR_ENTRIES_THRESHOLD
+};
+
enum Fts_stat
{
FTS_NO_STAT_REQUIRED = 1,
@@ -107,8 +171,6 @@ enum Fts_stat
# define fchdir __fchdir
# undef open
# define open __open
-# undef opendir
-# define opendir __opendir
# undef readdir
# define readdir __readdir
#else
@@ -120,16 +182,6 @@ enum Fts_stat
# define __set_errno(Val) errno = (Val)
#endif
-#ifndef __attribute__
-# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 8) || __STRICT_ANSI__
-# define __attribute__(x) /* empty */
-# endif
-#endif
-
-#ifndef ATTRIBUTE_UNUSED
-# define ATTRIBUTE_UNUSED __attribute__ ((__unused__))
-#endif
-
/* If this host provides the openat function, then we can avoid
attempting to open "." in some initialization code below. */
#ifdef HAVE_OPENAT
@@ -139,37 +191,30 @@ enum Fts_stat
#endif
#ifdef NDEBUG
-# define fts_assert(expr) ((void) 0)
+# define fts_assert(expr) ((void) (0 && (expr)))
#else
-# define fts_assert(expr) \
- do \
- { \
- if (!(expr)) \
- abort (); \
- } \
+# define fts_assert(expr) \
+ do \
+ { \
+ if (!(expr)) \
+ abort (); \
+ } \
while (false)
#endif
-static FTSENT *fts_alloc (FTS *, const char *, size_t) internal_function;
-static FTSENT *fts_build (FTS *, int) internal_function;
-static void fts_lfree (FTSENT *) internal_function;
-static void fts_load (FTS *, FTSENT *) internal_function;
-static size_t fts_maxarglen (char * const *) internal_function;
-static void fts_padjust (FTS *, FTSENT *) internal_function;
-static bool fts_palloc (FTS *, size_t) internal_function;
-static FTSENT *fts_sort (FTS *, FTSENT *, size_t) internal_function;
+static FTSENT *fts_alloc (FTS *, const char *, size_t) internal_function;
+static FTSENT *fts_build (FTS *, int) internal_function;
+static void fts_lfree (FTSENT *) internal_function;
+static void fts_load (FTS *, FTSENT *) internal_function;
+static size_t fts_maxarglen (char * const *) internal_function;
+static void fts_padjust (FTS *, FTSENT *) internal_function;
+static bool fts_palloc (FTS *, size_t) internal_function;
+static FTSENT *fts_sort (FTS *, FTSENT *, size_t) internal_function;
static unsigned short int fts_stat (FTS *, FTSENT *, bool) internal_function;
static int fts_safe_changedir (FTS *, FTSENT *, int, const char *)
internal_function;
-#if GNULIB_FTS
-# include "fts-cycle.c"
-#else
-static bool enter_dir (FTS *fts, FTSENT *ent) { return true; }
-static void leave_dir (FTS *fts, FTSENT *ent) {}
-static bool setup_dir (FTS *fts) { return true; }
-static void free_dir (FTS *fts) {}
-#endif
+#include "fts-cycle.c"
#ifndef MAX
# define MAX(a,b) ((a) > (b) ? (a) : (b))
@@ -179,35 +224,26 @@ static void free_dir (FTS *fts) {}
# define SIZE_MAX ((size_t) -1)
#endif
-#ifndef O_DIRECTORY
-# define O_DIRECTORY 0
-#endif
+#define ISDOT(a) (a[0] == '.' && (!a[1] || (a[1] == '.' && !a[2])))
+#define STREQ(a, b) (strcmp (a, b) == 0)
-#define ISDOT(a) (a[0] == '.' && (!a[1] || (a[1] == '.' && !a[2])))
-#define STREQ(a, b) (strcmp ((a), (b)) == 0)
-
-#define CLR(opt) (sp->fts_options &= ~(opt))
-#define ISSET(opt) (sp->fts_options & (opt))
-#define SET(opt) (sp->fts_options |= (opt))
-
-/* FIXME: make this a function */
-#define RESTORE_INITIAL_CWD(sp) \
- (fd_ring_clear (&((sp)->fts_fd_ring)), \
- FCHDIR ((sp), (ISSET (FTS_CWDFD) ? AT_FDCWD : (sp)->fts_rfd)))
+#define CLR(opt) (sp->fts_options &= ~(opt))
+#define ISSET(opt) (sp->fts_options & (opt))
+#define SET(opt) (sp->fts_options |= (opt))
/* FIXME: FTS_NOCHDIR is now misnamed.
Call it FTS_USE_FULL_RELATIVE_FILE_NAMES instead. */
-#define FCHDIR(sp, fd) \
- (!ISSET(FTS_NOCHDIR) && (ISSET(FTS_CWDFD) \
- ? (cwd_advance_fd ((sp), (fd), true), 0) \
- : fchdir (fd)))
+#define FCHDIR(sp, fd) \
+ (!ISSET(FTS_NOCHDIR) && (ISSET(FTS_CWDFD) \
+ ? (cwd_advance_fd ((sp), (fd), true), 0) \
+ : fchdir (fd)))
/* fts_build flags */
/* FIXME: make this an enum */
-#define BCHILD 1 /* fts_children */
-#define BNAMES 2 /* fts_children, names only */
-#define BREAD 3 /* fts_read */
+#define BCHILD 1 /* fts_children */
+#define BNAMES 2 /* fts_children, names only */
+#define BREAD 3 /* fts_read */
#if FTS_DEBUG
# include <inttypes.h>
@@ -222,13 +258,13 @@ bool fts_debug = false;
# define fd_ring_print(a, b, c)
#endif
-#define LEAVE_DIR(Fts, Ent, Tag) \
- do \
- { \
- Dprintf ((" %s-leaving: %s\n", Tag, (Ent)->fts_path)); \
- leave_dir (Fts, Ent); \
- fd_ring_check (Fts); \
- } \
+#define LEAVE_DIR(Fts, Ent, Tag) \
+ do \
+ { \
+ Dprintf ((" %s-leaving: %s\n", Tag, (Ent)->fts_path)); \
+ leave_dir (Fts, Ent); \
+ fd_ring_check (Fts); \
+ } \
while (false)
static void
@@ -238,7 +274,7 @@ fd_ring_clear (I_ring *fd_ring)
{
int fd = i_ring_pop (fd_ring);
if (0 <= fd)
- close (fd);
+ close (fd);
}
}
@@ -250,23 +286,28 @@ fts_set_stat_required (FTSENT *p, bool required)
{
fts_assert (p->fts_info == FTS_NSOK);
p->fts_statp->st_size = (required
- ? FTS_STAT_REQUIRED
- : FTS_NO_STAT_REQUIRED);
+ ? FTS_STAT_REQUIRED
+ : FTS_NO_STAT_REQUIRED);
}
/* file-descriptor-relative opendir. */
/* FIXME: if others need this function, move it into lib/openat.c */
-static inline DIR *
+static DIR *
internal_function
-opendirat (int fd, char const *dir)
+opendirat (int fd, char const *dir, int extra_flags, int *pdir_fd)
{
- int new_fd = openat (fd, dir, O_RDONLY);
+ int new_fd = openat (fd, dir,
+ (O_RDONLY | O_DIRECTORY | O_NOCTTY | O_NONBLOCK
+ | extra_flags));
DIR *dirp;
if (new_fd < 0)
return NULL;
+ set_cloexec_flag (new_fd, true);
dirp = fdopendir (new_fd);
- if (dirp == NULL)
+ if (dirp)
+ *pdir_fd = new_fd;
+ else
{
int saved_errno = errno;
close (new_fd);
@@ -290,529 +331,783 @@ cwd_advance_fd (FTS *sp, int fd, bool chdir_down_one)
if (chdir_down_one)
{
/* Push "old" onto the ring.
- If the displaced file descriptor is non-negative, close it. */
+ If the displaced file descriptor is non-negative, close it. */
int prev_fd_in_slot = i_ring_push (&sp->fts_fd_ring, old);
fd_ring_print (sp, stderr, "post-push");
if (0 <= prev_fd_in_slot)
- close (prev_fd_in_slot); /* ignore any close failure */
+ close (prev_fd_in_slot); /* ignore any close failure */
}
else if ( ! ISSET (FTS_NOCHDIR))
{
if (0 <= old)
- close (old); /* ignore any close failure */
+ close (old); /* ignore any close failure */
}
sp->fts_cwd_fd = fd;
}
+/* Restore the initial, pre-traversal, "working directory".
+ In FTS_CWDFD mode, we merely call cwd_advance_fd, otherwise,
+ we may actually change the working directory.
+ Return 0 upon success. Upon failure, set errno and return nonzero. */
+static int
+restore_initial_cwd (FTS *sp)
+{
+ int fail = FCHDIR (sp, ISSET (FTS_CWDFD) ? AT_FDCWD : sp->fts_rfd);
+ fd_ring_clear (&(sp->fts_fd_ring));
+ return fail;
+}
+
/* Open the directory DIR if possible, and return a file
descriptor. Return -1 and set errno on failure. It doesn't matter
whether the file descriptor has read or write access. */
-static inline int
+static int
internal_function
diropen (FTS const *sp, char const *dir)
{
- int open_flags = (O_RDONLY | O_DIRECTORY | O_NOCTTY | O_NONBLOCK
- | (ISSET (FTS_PHYSICAL) ? O_NOFOLLOW : 0));
-
- return (ISSET (FTS_CWDFD)
- ? openat (sp->fts_cwd_fd, dir, open_flags)
- : open (dir, open_flags));
+ int open_flags = (O_SEARCH | O_DIRECTORY | O_NOCTTY | O_NONBLOCK
+ | (ISSET (FTS_PHYSICAL) ? O_NOFOLLOW : 0)
+ | (ISSET (FTS_NOATIME) ? O_NOATIME : 0));
+
+ int fd = (ISSET (FTS_CWDFD)
+ ? openat (sp->fts_cwd_fd, dir, open_flags)
+ : open (dir, open_flags));
+ if (0 <= fd)
+ set_cloexec_flag (fd, true);
+ return fd;
}
FTS *
fts_open (char * const *argv,
- register int options,
- int (*compar) (FTSENT const **, FTSENT const **))
+ register int options,
+ int (*compar) (FTSENT const **, FTSENT const **))
{
- register FTS *sp;
- register FTSENT *p, *root;
- register size_t nitems;
- FTSENT *parent = NULL;
- FTSENT *tmp = NULL; /* pacify gcc */
- size_t len;
- bool defer_stat;
-
- /* Options check. */
- if (options & ~FTS_OPTIONMASK) {
- __set_errno (EINVAL);
- return (NULL);
- }
- if ((options & FTS_NOCHDIR) && (options & FTS_CWDFD)) {
- __set_errno (EINVAL);
- return (NULL);
- }
- if ( ! (options & (FTS_LOGICAL | FTS_PHYSICAL))) {
- __set_errno (EINVAL);
- return (NULL);
- }
-
- /* Allocate/initialize the stream */
- if ((sp = malloc(sizeof(FTS))) == NULL)
- return (NULL);
- memset(sp, 0, sizeof(FTS));
- sp->fts_compar = compar;
- sp->fts_options = options;
-
- /* Logical walks turn on NOCHDIR; symbolic links are too hard. */
- if (ISSET(FTS_LOGICAL)) {
- SET(FTS_NOCHDIR);
- CLR(FTS_CWDFD);
- }
-
- /* Initialize fts_cwd_fd. */
- sp->fts_cwd_fd = AT_FDCWD;
- if ( ISSET(FTS_CWDFD) && ! HAVE_OPENAT_SUPPORT)
- {
- /* While it isn't technically necessary to open "." this
- early, doing it here saves us the trouble of ensuring
- later (where it'd be messier) that "." can in fact
- be opened. If not, revert to FTS_NOCHDIR mode. */
- int fd = open (".", O_RDONLY);
- if (fd < 0)
- {
- /* Even if `.' is unreadable, don't revert to FTS_NOCHDIR mode
- on systems like Linux+PROC_FS, where our openat emulation
- is good enough. Note: on a system that emulates
- openat via /proc, this technique can still fail, but
- only in extreme conditions, e.g., when the working
- directory cannot be saved (i.e. save_cwd fails) --
- and that happens on Linux only when "." is unreadable
- and the CWD would be longer than PATH_MAX.
- FIXME: once Linux kernel openat support is well established,
- replace the above open call and this entire if/else block
- with the body of the if-block below. */
- if ( openat_needs_fchdir ())
- {
- SET(FTS_NOCHDIR);
- CLR(FTS_CWDFD);
- }
- }
- else
- {
- close (fd);
- }
- }
-
- /*
- * Start out with 1K of file name space, and enough, in any case,
- * to hold the user's file names.
- */
+ register FTS *sp;
+ register FTSENT *p, *root;
+ register size_t nitems;
+ FTSENT *parent = NULL;
+ FTSENT *tmp = NULL; /* pacify gcc */
+ bool defer_stat;
+
+ /* Options check. */
+ if (options & ~FTS_OPTIONMASK) {
+ __set_errno (EINVAL);
+ return (NULL);
+ }
+ if ((options & FTS_NOCHDIR) && (options & FTS_CWDFD)) {
+ __set_errno (EINVAL);
+ return (NULL);
+ }
+ if ( ! (options & (FTS_LOGICAL | FTS_PHYSICAL))) {
+ __set_errno (EINVAL);
+ return (NULL);
+ }
+
+ /* Allocate/initialize the stream */
+ if ((sp = malloc(sizeof(FTS))) == NULL)
+ return (NULL);
+ memset(sp, 0, sizeof(FTS));
+ sp->fts_compar = compar;
+ sp->fts_options = options;
+
+ /* Logical walks turn on NOCHDIR; symbolic links are too hard. */
+ if (ISSET(FTS_LOGICAL)) {
+ SET(FTS_NOCHDIR);
+ CLR(FTS_CWDFD);
+ }
+
+ /* Initialize fts_cwd_fd. */
+ sp->fts_cwd_fd = AT_FDCWD;
+ if ( ISSET(FTS_CWDFD) && ! HAVE_OPENAT_SUPPORT)
+ {
+ /* While it isn't technically necessary to open "." this
+ early, doing it here saves us the trouble of ensuring
+ later (where it'd be messier) that "." can in fact
+ be opened. If not, revert to FTS_NOCHDIR mode. */
+ int fd = open (".",
+ O_SEARCH | (ISSET (FTS_NOATIME) ? O_NOATIME : 0));
+ if (fd < 0)
+ {
+ /* Even if "." is unreadable, don't revert to FTS_NOCHDIR mode
+ on systems like Linux+PROC_FS, where our openat emulation
+ is good enough. Note: on a system that emulates
+ openat via /proc, this technique can still fail, but
+ only in extreme conditions, e.g., when the working
+ directory cannot be saved (i.e. save_cwd fails) --
+ and that happens on Linux only when "." is unreadable
+ and the CWD would be longer than PATH_MAX.
+ FIXME: once Linux kernel openat support is well established,
+ replace the above open call and this entire if/else block
+ with the body of the if-block below. */
+ if ( openat_needs_fchdir ())
+ {
+ SET(FTS_NOCHDIR);
+ CLR(FTS_CWDFD);
+ }
+ }
+ else
+ {
+ close (fd);
+ }
+ }
+
+ /*
+ * Start out with 1K of file name space, and enough, in any case,
+ * to hold the user's file names.
+ */
#ifndef MAXPATHLEN
# define MAXPATHLEN 1024
#endif
- {
- size_t maxarglen = fts_maxarglen(argv);
- if (! fts_palloc(sp, MAX(maxarglen, MAXPATHLEN)))
- goto mem1;
- }
-
- /* Allocate/initialize root's parent. */
- if (*argv != NULL) {
- if ((parent = fts_alloc(sp, "", 0)) == NULL)
- goto mem2;
- parent->fts_level = FTS_ROOTPARENTLEVEL;
- }
-
- /* The classic fts implementation would call fts_stat with
- a new entry for each iteration of the loop below.
- If the comparison function is not specified or if the
- FTS_DEFER_STAT option is in effect, don't stat any entry
- in this loop. This is an attempt to minimize the interval
- between the initial stat/lstat/fstatat and the point at which
- a directory argument is first opened. This matters for any
- directory command line argument that resides on a file system
- without genuine i-nodes. If you specify FTS_DEFER_STAT along
- with a comparison function, that function must not access any
- data via the fts_statp pointer. */
- defer_stat = (compar == NULL || ISSET(FTS_DEFER_STAT));
-
- /* Allocate/initialize root(s). */
- for (root = NULL, nitems = 0; *argv != NULL; ++argv, ++nitems) {
- /* Don't allow zero-length file names. */
- if ((len = strlen(*argv)) == 0) {
- __set_errno (ENOENT);
- goto mem3;
- }
-
- if ((p = fts_alloc(sp, *argv, len)) == NULL)
- goto mem3;
- p->fts_level = FTS_ROOTLEVEL;
- p->fts_parent = parent;
- p->fts_accpath = p->fts_name;
- /* Even when defer_stat is true, be sure to stat the first
- command line argument, since fts_read (at least with
- FTS_XDEV) requires that. */
- if (defer_stat && root != NULL) {
- p->fts_info = FTS_NSOK;
- fts_set_stat_required(p, true);
- } else {
- p->fts_info = fts_stat(sp, p, false);
- }
-
- /*
- * If comparison routine supplied, traverse in sorted
- * order; otherwise traverse in the order specified.
- */
- if (compar) {
- p->fts_link = root;
- root = p;
- } else {
- p->fts_link = NULL;
- if (root == NULL)
- tmp = root = p;
- else {
- tmp->fts_link = p;
- tmp = p;
- }
- }
- }
- if (compar && nitems > 1)
- root = fts_sort(sp, root, nitems);
-
- /*
- * Allocate a dummy pointer and make fts_read think that we've just
- * finished the node before the root(s); set p->fts_info to FTS_INIT
- * so that everything about the "current" node is ignored.
- */
- if ((sp->fts_cur = fts_alloc(sp, "", 0)) == NULL)
- goto mem3;
- sp->fts_cur->fts_link = root;
- sp->fts_cur->fts_info = FTS_INIT;
- if (! setup_dir (sp))
- goto mem3;
-
- /*
- * If using chdir(2), grab a file descriptor pointing to dot to ensure
- * that we can get back here; this could be avoided for some file names,
- * but almost certainly not worth the effort. Slashes, symbolic links,
- * and ".." are all fairly nasty problems. Note, if we can't get the
- * descriptor we run anyway, just more slowly.
- */
- if (!ISSET(FTS_NOCHDIR) && !ISSET(FTS_CWDFD)
- && (sp->fts_rfd = diropen (sp, ".")) < 0)
- SET(FTS_NOCHDIR);
-
- i_ring_init (&sp->fts_fd_ring, -1);
- return (sp);
-
-mem3: fts_lfree(root);
- free(parent);
-mem2: free(sp->fts_path);
-mem1: free(sp);
- return (NULL);
+ {
+ size_t maxarglen = fts_maxarglen(argv);
+ if (! fts_palloc(sp, MAX(maxarglen, MAXPATHLEN)))
+ goto mem1;
+ }
+
+ /* Allocate/initialize root's parent. */
+ if (*argv != NULL) {
+ if ((parent = fts_alloc(sp, "", 0)) == NULL)
+ goto mem2;
+ parent->fts_level = FTS_ROOTPARENTLEVEL;
+ }
+
+ /* The classic fts implementation would call fts_stat with
+ a new entry for each iteration of the loop below.
+ If the comparison function is not specified or if the
+ FTS_DEFER_STAT option is in effect, don't stat any entry
+ in this loop. This is an attempt to minimize the interval
+ between the initial stat/lstat/fstatat and the point at which
+ a directory argument is first opened. This matters for any
+ directory command line argument that resides on a file system
+ without genuine i-nodes. If you specify FTS_DEFER_STAT along
+ with a comparison function, that function must not access any
+ data via the fts_statp pointer. */
+ defer_stat = (compar == NULL || ISSET(FTS_DEFER_STAT));
+
+ /* Allocate/initialize root(s). */
+ for (root = NULL, nitems = 0; *argv != NULL; ++argv, ++nitems) {
+ /* *Do* allow zero-length file names. */
+ size_t len = strlen(*argv);
+
+ if ( ! (options & FTS_VERBATIM))
+ {
+ /* If there are two or more trailing slashes, trim all but one,
+ but don't change "//" to "/", and do map "///" to "/". */
+ char const *v = *argv;
+ if (2 < len && v[len - 1] == '/')
+ while (1 < len && v[len - 2] == '/')
+ --len;
+ }
+
+ if ((p = fts_alloc(sp, *argv, len)) == NULL)
+ goto mem3;
+ p->fts_level = FTS_ROOTLEVEL;
+ p->fts_parent = parent;
+ p->fts_accpath = p->fts_name;
+ /* Even when defer_stat is true, be sure to stat the first
+ command line argument, since fts_read (at least with
+ FTS_XDEV) requires that. */
+ if (defer_stat && root != NULL) {
+ p->fts_info = FTS_NSOK;
+ fts_set_stat_required(p, true);
+ } else {
+ p->fts_info = fts_stat(sp, p, false);
+ }
+
+ /*
+ * If comparison routine supplied, traverse in sorted
+ * order; otherwise traverse in the order specified.
+ */
+ if (compar) {
+ p->fts_link = root;
+ root = p;
+ } else {
+ p->fts_link = NULL;
+ if (root == NULL)
+ tmp = root = p;
+ else {
+ tmp->fts_link = p;
+ tmp = p;
+ }
+ }
+ }
+ if (compar && nitems > 1)
+ root = fts_sort(sp, root, nitems);
+
+ /*
+ * Allocate a dummy pointer and make fts_read think that we've just
+ * finished the node before the root(s); set p->fts_info to FTS_INIT
+ * so that everything about the "current" node is ignored.
+ */
+ if ((sp->fts_cur = fts_alloc(sp, "", 0)) == NULL)
+ goto mem3;
+ sp->fts_cur->fts_link = root;
+ sp->fts_cur->fts_info = FTS_INIT;
+ if (! setup_dir (sp))
+ goto mem3;
+
+ /*
+ * If using chdir(2), grab a file descriptor pointing to dot to ensure
+ * that we can get back here; this could be avoided for some file names,
+ * but almost certainly not worth the effort. Slashes, symbolic links,
+ * and ".." are all fairly nasty problems. Note, if we can't get the
+ * descriptor we run anyway, just more slowly.
+ */
+ if (!ISSET(FTS_NOCHDIR) && !ISSET(FTS_CWDFD)
+ && (sp->fts_rfd = diropen (sp, ".")) < 0)
+ SET(FTS_NOCHDIR);
+
+ i_ring_init (&sp->fts_fd_ring, -1);
+ return (sp);
+
+mem3: fts_lfree(root);
+ free(parent);
+mem2: free(sp->fts_path);
+mem1: free(sp);
+ return (NULL);
}
static void
internal_function
fts_load (FTS *sp, register FTSENT *p)
{
- register size_t len;
- register char *cp;
-
- /*
- * Load the stream structure for the next traversal. Since we don't
- * actually enter the directory until after the preorder visit, set
- * the fts_accpath field specially so the chdir gets done to the right
- * place and the user can access the first node. From fts_open it's
- * known that the file name will fit.
- */
- len = p->fts_pathlen = p->fts_namelen;
- memmove(sp->fts_path, p->fts_name, len + 1);
- if ((cp = strrchr(p->fts_name, '/')) && (cp != p->fts_name || cp[1])) {
- len = strlen(++cp);
- memmove(p->fts_name, cp, len + 1);
- p->fts_namelen = len;
- }
- p->fts_accpath = p->fts_path = sp->fts_path;
+ register size_t len;
+ register char *cp;
+
+ /*
+ * Load the stream structure for the next traversal. Since we don't
+ * actually enter the directory until after the preorder visit, set
+ * the fts_accpath field specially so the chdir gets done to the right
+ * place and the user can access the first node. From fts_open it's
+ * known that the file name will fit.
+ */
+ len = p->fts_pathlen = p->fts_namelen;
+ memmove(sp->fts_path, p->fts_name, len + 1);
+ if ((cp = strrchr(p->fts_name, '/')) && (cp != p->fts_name || cp[1])) {
+ len = strlen(++cp);
+ memmove(p->fts_name, cp, len + 1);
+ p->fts_namelen = len;
+ }
+ p->fts_accpath = p->fts_path = sp->fts_path;
}
int
fts_close (FTS *sp)
{
- register FTSENT *freep, *p;
- int saved_errno = 0;
-
- /*
- * This still works if we haven't read anything -- the dummy structure
- * points to the root list, so we step through to the end of the root
- * list which has a valid parent pointer.
- */
- if (sp->fts_cur) {
- for (p = sp->fts_cur; p->fts_level >= FTS_ROOTLEVEL;) {
- freep = p;
- p = p->fts_link != NULL ? p->fts_link : p->fts_parent;
- free(freep);
- }
- free(p);
- }
-
- /* Free up child linked list, sort array, file name buffer. */
- if (sp->fts_child)
- fts_lfree(sp->fts_child);
- free(sp->fts_array);
- free(sp->fts_path);
-
- if (ISSET(FTS_CWDFD))
- {
- if (0 <= sp->fts_cwd_fd)
- close (sp->fts_cwd_fd);
- }
- else if (!ISSET(FTS_NOCHDIR))
- {
- /* Return to original directory, save errno if necessary. */
- if (fchdir(sp->fts_rfd))
- saved_errno = errno;
- close(sp->fts_rfd);
- }
-
- fd_ring_clear (&sp->fts_fd_ring);
- free_dir (sp);
-
- /* Free up the stream pointer. */
- free(sp);
-
- /* Set errno and return. */
- if (saved_errno) {
- __set_errno (saved_errno);
- return (-1);
- }
-
- return (0);
+ register FTSENT *freep, *p;
+ int saved_errno = 0;
+
+ /*
+ * This still works if we haven't read anything -- the dummy structure
+ * points to the root list, so we step through to the end of the root
+ * list which has a valid parent pointer.
+ */
+ if (sp->fts_cur) {
+ for (p = sp->fts_cur; p->fts_level >= FTS_ROOTLEVEL;) {
+ freep = p;
+ p = p->fts_link != NULL ? p->fts_link : p->fts_parent;
+ free(freep);
+ }
+ free(p);
+ }
+
+ /* Free up child linked list, sort array, file name buffer. */
+ if (sp->fts_child)
+ fts_lfree(sp->fts_child);
+ free(sp->fts_array);
+ free(sp->fts_path);
+
+ if (ISSET(FTS_CWDFD))
+ {
+ if (0 <= sp->fts_cwd_fd)
+ if (close (sp->fts_cwd_fd))
+ saved_errno = errno;
+ }
+ else if (!ISSET(FTS_NOCHDIR))
+ {
+ /* Return to original directory, save errno if necessary. */
+ if (fchdir(sp->fts_rfd))
+ saved_errno = errno;
+
+ /* If close fails, record errno only if saved_errno is zero,
+ so that we report the probably-more-meaningful fchdir errno. */
+ if (close (sp->fts_rfd))
+ if (saved_errno == 0)
+ saved_errno = errno;
+ }
+
+ fd_ring_clear (&sp->fts_fd_ring);
+
+ if (sp->fts_leaf_optimization_works_ht)
+ hash_free (sp->fts_leaf_optimization_works_ht);
+
+ free_dir (sp);
+
+ /* Free up the stream pointer. */
+ free(sp);
+
+ /* Set errno and return. */
+ if (saved_errno) {
+ __set_errno (saved_errno);
+ return (-1);
+ }
+
+ return (0);
+}
+
+#if defined __linux__ \
+ && HAVE_SYS_VFS_H && HAVE_FSTATFS && HAVE_STRUCT_STATFS_F_TYPE
+
+# include <sys/vfs.h>
+
+/* Linux-specific constants from coreutils' src/fs.h */
+# define S_MAGIC_TMPFS 0x1021994
+# define S_MAGIC_NFS 0x6969
+# define S_MAGIC_REISERFS 0x52654973
+# define S_MAGIC_XFS 0x58465342
+# define S_MAGIC_PROC 0x9FA0
+
+/* Return false if it is easy to determine the file system type of
+ the directory on which DIR_FD is open, and sorting dirents on
+ inode numbers is known not to improve traversal performance with
+ that type of file system. Otherwise, return true. */
+static bool
+dirent_inode_sort_may_be_useful (int dir_fd)
+{
+ /* Skip the sort only if we can determine efficiently
+ that skipping it is the right thing to do.
+ The cost of performing an unnecessary sort is negligible,
+ while the cost of *not* performing it can be O(N^2) with
+ a very large constant. */
+ struct statfs fs_buf;
+
+ /* If fstatfs fails, assume sorting would be useful. */
+ if (fstatfs (dir_fd, &fs_buf) != 0)
+ return true;
+
+ /* FIXME: what about when f_type is not an integral type?
+ deal with that if/when it's encountered. */
+ switch (fs_buf.f_type)
+ {
+ case S_MAGIC_TMPFS:
+ case S_MAGIC_NFS:
+ /* On a file system of any of these types, sorting
+ is unnecessary, and hence wasteful. */
+ return false;
+
+ default:
+ return true;
+ }
+}
+
+/* Given a file descriptor DIR_FD open on a directory D,
+ return true if it is valid to apply the leaf-optimization
+ technique of counting directories in D via stat.st_nlink. */
+static bool
+leaf_optimization_applies (int dir_fd)
+{
+ struct statfs fs_buf;
+
+ /* If fstatfs fails, assume we can't use the optimization. */
+ if (fstatfs (dir_fd, &fs_buf) != 0)
+ return false;
+
+ /* FIXME: do we need to detect AFS mount points? I doubt it,
+ unless fstatfs can report S_MAGIC_REISERFS for such a directory. */
+
+ switch (fs_buf.f_type)
+ {
+ /* List here the file system types that lack usable dirent.d_type
+ info, yet for which the optimization does apply. */
+ case S_MAGIC_REISERFS:
+ case S_MAGIC_XFS:
+ return true;
+
+ /* Explicitly list here any other file system type for which the
+ optimization is not applicable, but need documentation. */
+ case S_MAGIC_NFS:
+ /* NFS provides usable dirent.d_type but not necessarily for all entries
+ of large directories, so as per <https://bugzilla.redhat.com/1252549>
+ NFS should return true. However st_nlink values are not accurate on
+ all implementations as per <https://bugzilla.redhat.com/1299169>. */
+ /* fall through */
+ case S_MAGIC_PROC:
+ /* Per <http://bugs.debian.org/143111> /proc may have
+ bogus stat.st_nlink values. */
+ /* fall through */
+ default:
+ return false;
+ }
+}
+
+#else
+static bool
+dirent_inode_sort_may_be_useful (int dir_fd _GL_UNUSED) { return true; }
+static bool
+leaf_optimization_applies (int dir_fd _GL_UNUSED) { return false; }
+#endif
+
+/* link-count-optimization entry:
+ map a stat.st_dev number to a boolean: leaf_optimization_works */
+struct LCO_ent
+{
+ dev_t st_dev;
+ bool opt_ok;
+};
+
+/* Use a tiny initial size. If a traversal encounters more than
+ a few devices, the cost of growing/rehashing this table will be
+ rendered negligible by the number of inodes processed. */
+enum { LCO_HT_INITIAL_SIZE = 13 };
+
+static size_t
+LCO_hash (void const *x, size_t table_size)
+{
+ struct LCO_ent const *ax = x;
+ return (uintmax_t) ax->st_dev % table_size;
+}
+
+static bool
+LCO_compare (void const *x, void const *y)
+{
+ struct LCO_ent const *ax = x;
+ struct LCO_ent const *ay = y;
+ return ax->st_dev == ay->st_dev;
+}
+
+/* Ask the same question as leaf_optimization_applies, but query
+ the cache first (FTS.fts_leaf_optimization_works_ht), and if necessary,
+ update that cache. */
+static bool
+link_count_optimize_ok (FTSENT const *p)
+{
+ FTS *sp = p->fts_fts;
+ Hash_table *h = sp->fts_leaf_optimization_works_ht;
+ struct LCO_ent tmp;
+ struct LCO_ent *ent;
+ bool opt_ok;
+ struct LCO_ent *t2;
+
+ /* If we're not in CWDFD mode, don't bother with this optimization,
+ since the caller is not serious about performance. */
+ if (!ISSET(FTS_CWDFD))
+ return false;
+
+ /* map st_dev to the boolean, leaf_optimization_works */
+ if (h == NULL)
+ {
+ h = sp->fts_leaf_optimization_works_ht
+ = hash_initialize (LCO_HT_INITIAL_SIZE, NULL, LCO_hash,
+ LCO_compare, free);
+ if (h == NULL)
+ return false;
+ }
+ tmp.st_dev = p->fts_statp->st_dev;
+ ent = hash_lookup (h, &tmp);
+ if (ent)
+ return ent->opt_ok;
+
+ /* Look-up failed. Query directly and cache the result. */
+ t2 = malloc (sizeof *t2);
+ if (t2 == NULL)
+ return false;
+
+ /* Is it ok to perform the optimization in the dir, FTS_CWD_FD? */
+ opt_ok = leaf_optimization_applies (sp->fts_cwd_fd);
+ t2->opt_ok = opt_ok;
+ t2->st_dev = p->fts_statp->st_dev;
+
+ ent = hash_insert (h, t2);
+ if (ent == NULL)
+ {
+ /* insertion failed */
+ free (t2);
+ return false;
+ }
+ fts_assert (ent == t2);
+
+ return opt_ok;
}
/*
* Special case of "/" at the end of the file name so that slashes aren't
* appended which would cause file names to be written as "....//foo".
*/
-#define NAPPEND(p) \
- (p->fts_path[p->fts_pathlen - 1] == '/' \
- ? p->fts_pathlen - 1 : p->fts_pathlen)
+#define NAPPEND(p) \
+ (p->fts_path[p->fts_pathlen - 1] == '/' \
+ ? p->fts_pathlen - 1 : p->fts_pathlen)
FTSENT *
fts_read (register FTS *sp)
{
- register FTSENT *p, *tmp;
- register unsigned short int instr;
- register char *t;
-
- /* If finished or unrecoverable error, return NULL. */
- if (sp->fts_cur == NULL || ISSET(FTS_STOP))
- return (NULL);
-
- /* Set current node pointer. */
- p = sp->fts_cur;
-
- /* Save and zero out user instructions. */
- instr = p->fts_instr;
- p->fts_instr = FTS_NOINSTR;
-
- /* Any type of file may be re-visited; re-stat and re-turn. */
- if (instr == FTS_AGAIN) {
- p->fts_info = fts_stat(sp, p, false);
- return (p);
- }
- Dprintf (("fts_read: p=%s\n",
- p->fts_info == FTS_INIT ? "" : p->fts_path));
-
- /*
- * Following a symlink -- SLNONE test allows application to see
- * SLNONE and recover. If indirecting through a symlink, have
- * keep a pointer to current location. If unable to get that
- * pointer, follow fails.
- */
- if (instr == FTS_FOLLOW &&
- (p->fts_info == FTS_SL || p->fts_info == FTS_SLNONE)) {
- p->fts_info = fts_stat(sp, p, true);
- if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR)) {
- if ((p->fts_symfd = diropen (sp, ".")) < 0) {
- p->fts_errno = errno;
- p->fts_info = FTS_ERR;
- } else
- p->fts_flags |= FTS_SYMFOLLOW;
- }
- goto check_for_dir;
- }
-
- /* Directory in pre-order. */
- if (p->fts_info == FTS_D) {
- /* If skipped or crossed mount point, do post-order visit. */
- if (instr == FTS_SKIP ||
- (ISSET(FTS_XDEV) && p->fts_statp->st_dev != sp->fts_dev)) {
- if (p->fts_flags & FTS_SYMFOLLOW)
- (void)close(p->fts_symfd);
- if (sp->fts_child) {
- fts_lfree(sp->fts_child);
- sp->fts_child = NULL;
- }
- p->fts_info = FTS_DP;
- LEAVE_DIR (sp, p, "1");
- return (p);
- }
-
- /* Rebuild if only read the names and now traversing. */
- if (sp->fts_child != NULL && ISSET(FTS_NAMEONLY)) {
- CLR(FTS_NAMEONLY);
- fts_lfree(sp->fts_child);
- sp->fts_child = NULL;
- }
-
- /*
- * Cd to the subdirectory.
- *
- * If have already read and now fail to chdir, whack the list
- * to make the names come out right, and set the parent errno
- * so the application will eventually get an error condition.
- * Set the FTS_DONTCHDIR flag so that when we logically change
- * directories back to the parent we don't do a chdir.
- *
- * If haven't read do so. If the read fails, fts_build sets
- * FTS_STOP or the fts_info field of the node.
- */
- if (sp->fts_child != NULL) {
- if (fts_safe_changedir(sp, p, -1, p->fts_accpath)) {
- p->fts_errno = errno;
- p->fts_flags |= FTS_DONTCHDIR;
- for (p = sp->fts_child; p != NULL;
- p = p->fts_link)
- p->fts_accpath =
- p->fts_parent->fts_accpath;
- }
- } else if ((sp->fts_child = fts_build(sp, BREAD)) == NULL) {
- if (ISSET(FTS_STOP))
- return (NULL);
- /* If fts_build's call to fts_safe_changedir failed
- because it was not able to fchdir into a
- subdirectory, tell the caller. */
- if (p->fts_errno)
- p->fts_info = FTS_ERR;
- LEAVE_DIR (sp, p, "2");
- return (p);
- }
- p = sp->fts_child;
- sp->fts_child = NULL;
- goto name;
- }
-
- /* Move to the next node on this level. */
-next: tmp = p;
- if ((p = p->fts_link) != NULL) {
- sp->fts_cur = p;
- free(tmp);
-
- /*
- * If reached the top, return to the original directory (or
- * the root of the tree), and load the file names for the next
- * root.
- */
- if (p->fts_level == FTS_ROOTLEVEL) {
- if (RESTORE_INITIAL_CWD(sp)) {
- SET(FTS_STOP);
- return (NULL);
- }
- fts_load(sp, p);
- goto check_for_dir;
- }
-
- /*
- * User may have called fts_set on the node. If skipped,
- * ignore. If followed, get a file descriptor so we can
- * get back if necessary.
- */
- if (p->fts_instr == FTS_SKIP)
- goto next;
- if (p->fts_instr == FTS_FOLLOW) {
- p->fts_info = fts_stat(sp, p, true);
- if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR)) {
- if ((p->fts_symfd = diropen (sp, ".")) < 0) {
- p->fts_errno = errno;
- p->fts_info = FTS_ERR;
- } else
- p->fts_flags |= FTS_SYMFOLLOW;
- }
- p->fts_instr = FTS_NOINSTR;
- }
-
-name: t = sp->fts_path + NAPPEND(p->fts_parent);
- *t++ = '/';
- memmove(t, p->fts_name, p->fts_namelen + 1);
+ register FTSENT *p, *tmp;
+ register unsigned short int instr;
+ register char *t;
+
+ /* If finished or unrecoverable error, return NULL. */
+ if (sp->fts_cur == NULL || ISSET(FTS_STOP))
+ return (NULL);
+
+ /* Set current node pointer. */
+ p = sp->fts_cur;
+
+ /* Save and zero out user instructions. */
+ instr = p->fts_instr;
+ p->fts_instr = FTS_NOINSTR;
+
+ /* Any type of file may be re-visited; re-stat and re-turn. */
+ if (instr == FTS_AGAIN) {
+ p->fts_info = fts_stat(sp, p, false);
+ return (p);
+ }
+ Dprintf (("fts_read: p=%s\n",
+ p->fts_info == FTS_INIT ? "" : p->fts_path));
+
+ /*
+ * Following a symlink -- SLNONE test allows application to see
+ * SLNONE and recover. If indirecting through a symlink, have
+ * keep a pointer to current location. If unable to get that
+ * pointer, follow fails.
+ */
+ if (instr == FTS_FOLLOW &&
+ (p->fts_info == FTS_SL || p->fts_info == FTS_SLNONE)) {
+ p->fts_info = fts_stat(sp, p, true);
+ if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR)) {
+ if ((p->fts_symfd = diropen (sp, ".")) < 0) {
+ p->fts_errno = errno;
+ p->fts_info = FTS_ERR;
+ } else
+ p->fts_flags |= FTS_SYMFOLLOW;
+ }
+ goto check_for_dir;
+ }
+
+ /* Directory in pre-order. */
+ if (p->fts_info == FTS_D) {
+ /* If skipped or crossed mount point, do post-order visit. */
+ if (instr == FTS_SKIP ||
+ (ISSET(FTS_XDEV) && p->fts_statp->st_dev != sp->fts_dev)) {
+ if (p->fts_flags & FTS_SYMFOLLOW)
+ (void)close(p->fts_symfd);
+ if (sp->fts_child) {
+ fts_lfree(sp->fts_child);
+ sp->fts_child = NULL;
+ }
+ p->fts_info = FTS_DP;
+ LEAVE_DIR (sp, p, "1");
+ return (p);
+ }
+
+ /* Rebuild if only read the names and now traversing. */
+ if (sp->fts_child != NULL && ISSET(FTS_NAMEONLY)) {
+ CLR(FTS_NAMEONLY);
+ fts_lfree(sp->fts_child);
+ sp->fts_child = NULL;
+ }
+
+ /*
+ * Cd to the subdirectory.
+ *
+ * If have already read and now fail to chdir, whack the list
+ * to make the names come out right, and set the parent errno
+ * so the application will eventually get an error condition.
+ * Set the FTS_DONTCHDIR flag so that when we logically change
+ * directories back to the parent we don't do a chdir.
+ *
+ * If haven't read do so. If the read fails, fts_build sets
+ * FTS_STOP or the fts_info field of the node.
+ */
+ if (sp->fts_child != NULL) {
+ if (fts_safe_changedir(sp, p, -1, p->fts_accpath)) {
+ p->fts_errno = errno;
+ p->fts_flags |= FTS_DONTCHDIR;
+ for (p = sp->fts_child; p != NULL;
+ p = p->fts_link)
+ p->fts_accpath =
+ p->fts_parent->fts_accpath;
+ }
+ } else if ((sp->fts_child = fts_build(sp, BREAD)) == NULL) {
+ if (ISSET(FTS_STOP))
+ return (NULL);
+ /* If fts_build's call to fts_safe_changedir failed
+ because it was not able to fchdir into a
+ subdirectory, tell the caller. */
+ if (p->fts_errno && p->fts_info != FTS_DNR)
+ p->fts_info = FTS_ERR;
+ LEAVE_DIR (sp, p, "2");
+ return (p);
+ }
+ p = sp->fts_child;
+ sp->fts_child = NULL;
+ goto name;
+ }
+
+ /* Move to the next node on this level. */
+next: tmp = p;
+
+ /* If we have so many directory entries that we're reading them
+ in batches, and we've reached the end of the current batch,
+ read in a new batch. */
+ if (p->fts_link == NULL && p->fts_parent->fts_dirp)
+ {
+ p = tmp->fts_parent;
+ sp->fts_cur = p;
+ sp->fts_path[p->fts_pathlen] = '\0';
+
+ if ((p = fts_build (sp, BREAD)) == NULL)
+ {
+ if (ISSET(FTS_STOP))
+ return NULL;
+ goto cd_dot_dot;
+ }
+
+ free(tmp);
+ goto name;
+ }
+
+ if ((p = p->fts_link) != NULL) {
+ sp->fts_cur = p;
+ free(tmp);
+
+ /*
+ * If reached the top, return to the original directory (or
+ * the root of the tree), and load the file names for the next
+ * root.
+ */
+ if (p->fts_level == FTS_ROOTLEVEL) {
+ if (restore_initial_cwd(sp)) {
+ SET(FTS_STOP);
+ return (NULL);
+ }
+ free_dir(sp);
+ fts_load(sp, p);
+ setup_dir(sp);
+ goto check_for_dir;
+ }
+
+ /*
+ * User may have called fts_set on the node. If skipped,
+ * ignore. If followed, get a file descriptor so we can
+ * get back if necessary.
+ */
+ if (p->fts_instr == FTS_SKIP)
+ goto next;
+ if (p->fts_instr == FTS_FOLLOW) {
+ p->fts_info = fts_stat(sp, p, true);
+ if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR)) {
+ if ((p->fts_symfd = diropen (sp, ".")) < 0) {
+ p->fts_errno = errno;
+ p->fts_info = FTS_ERR;
+ } else
+ p->fts_flags |= FTS_SYMFOLLOW;
+ }
+ p->fts_instr = FTS_NOINSTR;
+ }
+
+name: t = sp->fts_path + NAPPEND(p->fts_parent);
+ *t++ = '/';
+ memmove(t, p->fts_name, p->fts_namelen + 1);
check_for_dir:
- sp->fts_cur = p;
- if (p->fts_info == FTS_NSOK)
- {
- if (p->fts_statp->st_size == FTS_STAT_REQUIRED)
- p->fts_info = fts_stat(sp, p, false);
- else
- fts_assert (p->fts_statp->st_size == FTS_NO_STAT_REQUIRED);
- }
-
- if (p->fts_info == FTS_D)
- {
- /* Now that P->fts_statp is guaranteed to be valid,
- if this is a command-line directory, record its
- device number, to be used for FTS_XDEV. */
- if (p->fts_level == FTS_ROOTLEVEL)
- sp->fts_dev = p->fts_statp->st_dev;
- Dprintf ((" entering: %s\n", p->fts_path));
- if (! enter_dir (sp, p))
- {
- __set_errno (ENOMEM);
- return NULL;
- }
- }
- return p;
- }
-
- /* Move up to the parent node. */
- p = tmp->fts_parent;
- sp->fts_cur = p;
- free(tmp);
-
- if (p->fts_level == FTS_ROOTPARENTLEVEL) {
- /*
- * Done; free everything up and set errno to 0 so the user
- * can distinguish between error and EOF.
- */
- free(p);
- __set_errno (0);
- return (sp->fts_cur = NULL);
- }
-
- fts_assert (p->fts_info != FTS_NSOK);
-
- /* NUL terminate the file name. */
- sp->fts_path[p->fts_pathlen] = '\0';
-
- /*
- * Return to the parent directory. If at a root node, restore
- * the initial working directory. If we came through a symlink,
- * go back through the file descriptor. Otherwise, move up
- * one level, via "..".
- */
- if (p->fts_level == FTS_ROOTLEVEL) {
- if (RESTORE_INITIAL_CWD(sp)) {
- p->fts_errno = errno;
- SET(FTS_STOP);
- }
- } else if (p->fts_flags & FTS_SYMFOLLOW) {
- if (FCHDIR(sp, p->fts_symfd)) {
- int saved_errno = errno;
- (void)close(p->fts_symfd);
- __set_errno (saved_errno);
- p->fts_errno = errno;
- SET(FTS_STOP);
- }
- (void)close(p->fts_symfd);
- } else if (!(p->fts_flags & FTS_DONTCHDIR) &&
- fts_safe_changedir(sp, p->fts_parent, -1, "..")) {
- p->fts_errno = errno;
- SET(FTS_STOP);
- }
- p->fts_info = p->fts_errno ? FTS_ERR : FTS_DP;
- if (p->fts_errno == 0)
- LEAVE_DIR (sp, p, "3");
- return ISSET(FTS_STOP) ? NULL : p;
+ sp->fts_cur = p;
+ if (p->fts_info == FTS_NSOK)
+ {
+ if (p->fts_statp->st_size == FTS_STAT_REQUIRED)
+ {
+ FTSENT *parent = p->fts_parent;
+ if (FTS_ROOTLEVEL < p->fts_level
+ /* ->fts_n_dirs_remaining is not valid
+ for command-line-specified names. */
+ && parent->fts_n_dirs_remaining == 0
+ && ISSET(FTS_NOSTAT)
+ && ISSET(FTS_PHYSICAL)
+ && link_count_optimize_ok (parent))
+ {
+ /* nothing more needed */
+ }
+ else
+ {
+ p->fts_info = fts_stat(sp, p, false);
+ if (S_ISDIR(p->fts_statp->st_mode)
+ && p->fts_level != FTS_ROOTLEVEL
+ && parent->fts_n_dirs_remaining)
+ parent->fts_n_dirs_remaining--;
+ }
+ }
+ else
+ fts_assert (p->fts_statp->st_size == FTS_NO_STAT_REQUIRED);
+ }
+
+ if (p->fts_info == FTS_D)
+ {
+ /* Now that P->fts_statp is guaranteed to be valid,
+ if this is a command-line directory, record its
+ device number, to be used for FTS_XDEV. */
+ if (p->fts_level == FTS_ROOTLEVEL)
+ sp->fts_dev = p->fts_statp->st_dev;
+ Dprintf ((" entering: %s\n", p->fts_path));
+ if (! enter_dir (sp, p))
+ {
+ __set_errno (ENOMEM);
+ return NULL;
+ }
+ }
+ return p;
+ }
+cd_dot_dot:
+
+ /* Move up to the parent node. */
+ p = tmp->fts_parent;
+ sp->fts_cur = p;
+ free(tmp);
+
+ if (p->fts_level == FTS_ROOTPARENTLEVEL) {
+ /*
+ * Done; free everything up and set errno to 0 so the user
+ * can distinguish between error and EOF.
+ */
+ free(p);
+ __set_errno (0);
+ return (sp->fts_cur = NULL);
+ }
+
+ fts_assert (p->fts_info != FTS_NSOK);
+
+ /* NUL terminate the file name. */
+ sp->fts_path[p->fts_pathlen] = '\0';
+
+ /*
+ * Return to the parent directory. If at a root node, restore
+ * the initial working directory. If we came through a symlink,
+ * go back through the file descriptor. Otherwise, move up
+ * one level, via "..".
+ */
+ if (p->fts_level == FTS_ROOTLEVEL) {
+ if (restore_initial_cwd(sp)) {
+ p->fts_errno = errno;
+ SET(FTS_STOP);
+ }
+ } else if (p->fts_flags & FTS_SYMFOLLOW) {
+ if (FCHDIR(sp, p->fts_symfd)) {
+ p->fts_errno = errno;
+ SET(FTS_STOP);
+ }
+ (void)close(p->fts_symfd);
+ } else if (!(p->fts_flags & FTS_DONTCHDIR) &&
+ fts_safe_changedir(sp, p->fts_parent, -1, "..")) {
+ p->fts_errno = errno;
+ SET(FTS_STOP);
+ }
+
+ /* If the directory causes a cycle, preserve the FTS_DC flag and keep
+ the corresponding dev/ino pair in the hash table. It is going to be
+ removed when leaving the original directory. */
+ if (p->fts_info != FTS_DC) {
+ p->fts_info = p->fts_errno ? FTS_ERR : FTS_DP;
+ if (p->fts_errno == 0)
+ LEAVE_DIR (sp, p, "3");
+ }
+ return ISSET(FTS_STOP) ? NULL : p;
}
/*
@@ -823,95 +1118,161 @@ check_for_dir:
*/
/* ARGSUSED */
int
-fts_set(FTS *sp ATTRIBUTE_UNUSED, FTSENT *p, int instr)
+fts_set(FTS *sp _GL_UNUSED, FTSENT *p, int instr)
{
- if (instr != 0 && instr != FTS_AGAIN && instr != FTS_FOLLOW &&
- instr != FTS_NOINSTR && instr != FTS_SKIP) {
- __set_errno (EINVAL);
- return (1);
- }
- p->fts_instr = instr;
- return (0);
+ if (instr != 0 && instr != FTS_AGAIN && instr != FTS_FOLLOW &&
+ instr != FTS_NOINSTR && instr != FTS_SKIP) {
+ __set_errno (EINVAL);
+ return (1);
+ }
+ p->fts_instr = instr;
+ return (0);
}
FTSENT *
fts_children (register FTS *sp, int instr)
{
- register FTSENT *p;
- int fd;
-
- if (instr != 0 && instr != FTS_NAMEONLY) {
- __set_errno (EINVAL);
- return (NULL);
- }
-
- /* Set current node pointer. */
- p = sp->fts_cur;
-
- /*
- * Errno set to 0 so user can distinguish empty directory from
- * an error.
- */
- __set_errno (0);
-
- /* Fatal errors stop here. */
- if (ISSET(FTS_STOP))
- return (NULL);
-
- /* Return logical hierarchy of user's arguments. */
- if (p->fts_info == FTS_INIT)
- return (p->fts_link);
-
- /*
- * If not a directory being visited in pre-order, stop here. Could
- * allow FTS_DNR, assuming the user has fixed the problem, but the
- * same effect is available with FTS_AGAIN.
- */
- if (p->fts_info != FTS_D /* && p->fts_info != FTS_DNR */)
- return (NULL);
-
- /* Free up any previous child list. */
- if (sp->fts_child != NULL)
- fts_lfree(sp->fts_child);
-
- if (instr == FTS_NAMEONLY) {
- SET(FTS_NAMEONLY);
- instr = BNAMES;
- } else
- instr = BCHILD;
-
- /*
- * If using chdir on a relative file name and called BEFORE fts_read
- * does its chdir to the root of a traversal, we can lose -- we need to
- * chdir into the subdirectory, and we don't know where the current
- * directory is, so we can't get back so that the upcoming chdir by
- * fts_read will work.
- */
- if (p->fts_level != FTS_ROOTLEVEL || p->fts_accpath[0] == '/' ||
- ISSET(FTS_NOCHDIR))
- return (sp->fts_child = fts_build(sp, instr));
-
- if ((fd = diropen (sp, ".")) < 0)
- return (sp->fts_child = NULL);
- sp->fts_child = fts_build(sp, instr);
- if (ISSET(FTS_CWDFD))
- {
- cwd_advance_fd (sp, fd, true);
- }
- else
- {
- if (fchdir(fd))
- {
- int saved_errno = errno;
- close (fd);
- __set_errno (saved_errno);
- return NULL;
- }
- close (fd);
- }
- return (sp->fts_child);
+ register FTSENT *p;
+ int fd;
+
+ if (instr != 0 && instr != FTS_NAMEONLY) {
+ __set_errno (EINVAL);
+ return (NULL);
+ }
+
+ /* Set current node pointer. */
+ p = sp->fts_cur;
+
+ /*
+ * Errno set to 0 so user can distinguish empty directory from
+ * an error.
+ */
+ __set_errno (0);
+
+ /* Fatal errors stop here. */
+ if (ISSET(FTS_STOP))
+ return (NULL);
+
+ /* Return logical hierarchy of user's arguments. */
+ if (p->fts_info == FTS_INIT)
+ return (p->fts_link);
+
+ /*
+ * If not a directory being visited in pre-order, stop here. Could
+ * allow FTS_DNR, assuming the user has fixed the problem, but the
+ * same effect is available with FTS_AGAIN.
+ */
+ if (p->fts_info != FTS_D /* && p->fts_info != FTS_DNR */)
+ return (NULL);
+
+ /* Free up any previous child list. */
+ if (sp->fts_child != NULL)
+ fts_lfree(sp->fts_child);
+
+ if (instr == FTS_NAMEONLY) {
+ SET(FTS_NAMEONLY);
+ instr = BNAMES;
+ } else
+ instr = BCHILD;
+
+ /*
+ * If using chdir on a relative file name and called BEFORE fts_read
+ * does its chdir to the root of a traversal, we can lose -- we need to
+ * chdir into the subdirectory, and we don't know where the current
+ * directory is, so we can't get back so that the upcoming chdir by
+ * fts_read will work.
+ */
+ if (p->fts_level != FTS_ROOTLEVEL || p->fts_accpath[0] == '/' ||
+ ISSET(FTS_NOCHDIR))
+ return (sp->fts_child = fts_build(sp, instr));
+
+ if ((fd = diropen (sp, ".")) < 0)
+ return (sp->fts_child = NULL);
+ sp->fts_child = fts_build(sp, instr);
+ if (ISSET(FTS_CWDFD))
+ {
+ cwd_advance_fd (sp, fd, true);
+ }
+ else
+ {
+ if (fchdir(fd))
+ {
+ int saved_errno = errno;
+ close (fd);
+ __set_errno (saved_errno);
+ return NULL;
+ }
+ close (fd);
+ }
+ return (sp->fts_child);
+}
+
+/* A comparison function to sort on increasing inode number.
+ For some file system types, sorting either way makes a huge
+ performance difference for a directory with very many entries,
+ but sorting on increasing values is slightly better than sorting
+ on decreasing values. The difference is in the 5% range. */
+static int
+fts_compare_ino (struct _ftsent const **a, struct _ftsent const **b)
+{
+ return (a[0]->fts_statp->st_ino < b[0]->fts_statp->st_ino ? -1
+ : b[0]->fts_statp->st_ino < a[0]->fts_statp->st_ino ? 1 : 0);
+}
+
+/* Map the dirent.d_type value, DTYPE, to the corresponding stat.st_mode
+ S_IF* bit and set ST.st_mode, thus clearing all other bits in that field. */
+static void
+set_stat_type (struct stat *st, unsigned int dtype)
+{
+ mode_t type;
+ switch (dtype)
+ {
+ case DT_BLK:
+ type = S_IFBLK;
+ break;
+ case DT_CHR:
+ type = S_IFCHR;
+ break;
+ case DT_DIR:
+ type = S_IFDIR;
+ break;
+ case DT_FIFO:
+ type = S_IFIFO;
+ break;
+ case DT_LNK:
+ type = S_IFLNK;
+ break;
+ case DT_REG:
+ type = S_IFREG;
+ break;
+ case DT_SOCK:
+ type = S_IFSOCK;
+ break;
+ default:
+ type = 0;
+ }
+ st->st_mode = type;
}
+#define closedir_and_clear(dirp) \
+ do \
+ { \
+ closedir (dirp); \
+ dirp = NULL; \
+ } \
+ while (0)
+
+#define fts_opendir(file, Pdir_fd) \
+ opendirat((! ISSET(FTS_NOCHDIR) && ISSET(FTS_CWDFD) \
+ ? sp->fts_cwd_fd : AT_FDCWD), \
+ file, \
+ (((ISSET(FTS_PHYSICAL) \
+ && ! (ISSET(FTS_COMFOLLOW) \
+ && cur->fts_level == FTS_ROOTLEVEL)) \
+ ? O_NOFOLLOW : 0) \
+ | (ISSET (FTS_NOATIME) ? O_NOATIME : 0)), \
+ Pdir_fd)
+
/*
* This is the tricky part -- do not casually change *anything* in here. The
* idea is to build the linked list of entries that are used by fts_children
@@ -930,287 +1291,360 @@ static FTSENT *
internal_function
fts_build (register FTS *sp, int type)
{
- register struct dirent *dp;
- register FTSENT *p, *head;
- register size_t nitems;
- FTSENT *cur, *tail;
- DIR *dirp;
- void *oldaddr;
- int saved_errno;
- bool descend;
- bool doadjust;
- ptrdiff_t level;
- nlink_t nlinks;
- bool nostat;
- size_t len, maxlen, new_len;
- char *cp;
-
- /* Set current node pointer. */
- cur = sp->fts_cur;
-
- /*
- * Open the directory for reading. If this fails, we're done.
- * If being called from fts_read, set the fts_info field.
- */
-#if defined FTS_WHITEOUT && 0
- if (ISSET(FTS_WHITEOUT))
- oflag = DTF_NODUP|DTF_REWIND;
- else
- oflag = DTF_HIDEW|DTF_NODUP|DTF_REWIND;
-#else
-# define __opendir2(file, flag) \
- ( ! ISSET(FTS_NOCHDIR) && ISSET(FTS_CWDFD) \
- ? opendirat(sp->fts_cwd_fd, file) \
- : opendir(file))
-#endif
- if ((dirp = __opendir2(cur->fts_accpath, oflag)) == NULL) {
- if (type == BREAD) {
- cur->fts_info = FTS_DNR;
- cur->fts_errno = errno;
- }
- return (NULL);
- }
- /* Rather than calling fts_stat for each and every entry encountered
- in the readdir loop (below), stat each directory only right after
- opening it. */
- if (cur->fts_info == FTS_NSOK)
- cur->fts_info = fts_stat(sp, cur, false);
-
- /*
- * Nlinks is the number of possible entries of type directory in the
- * directory if we're cheating on stat calls, 0 if we're not doing
- * any stat calls at all, (nlink_t) -1 if we're statting everything.
- */
- if (type == BNAMES) {
- nlinks = 0;
- /* Be quiet about nostat, GCC. */
- nostat = false;
- } else if (ISSET(FTS_NOSTAT) && ISSET(FTS_PHYSICAL)) {
- nlinks = (cur->fts_statp->st_nlink
- - (ISSET(FTS_SEEDOT) ? 0 : 2));
- nostat = true;
- } else {
- nlinks = -1;
- nostat = false;
- }
-
- /*
- * If we're going to need to stat anything or we want to descend
- * and stay in the directory, chdir. If this fails we keep going,
- * but set a flag so we don't chdir after the post-order visit.
- * We won't be able to stat anything, but we can still return the
- * names themselves. Note, that since fts_read won't be able to
- * chdir into the directory, it will have to return different file
- * names than before, i.e. "a/b" instead of "b". Since the node
- * has already been visited in pre-order, have to wait until the
- * post-order visit to return the error. There is a special case
- * here, if there was nothing to stat then it's not an error to
- * not be able to stat. This is all fairly nasty. If a program
- * needed sorted entries or stat information, they had better be
- * checking FTS_NS on the returned nodes.
- */
- if (nlinks || type == BREAD) {
- int dir_fd = dirfd(dirp);
- if (ISSET(FTS_CWDFD) && 0 <= dir_fd)
- dir_fd = dup (dir_fd);
- if (dir_fd < 0 || fts_safe_changedir(sp, cur, dir_fd, NULL)) {
- if (nlinks && type == BREAD)
- cur->fts_errno = errno;
- cur->fts_flags |= FTS_DONTCHDIR;
- descend = false;
- closedir(dirp);
- if (ISSET(FTS_CWDFD) && 0 <= dir_fd)
- close (dir_fd);
- dirp = NULL;
- } else
- descend = true;
- } else
- descend = false;
-
- /*
- * Figure out the max file name length that can be stored in the
- * current buffer -- the inner loop allocates more space as necessary.
- * We really wouldn't have to do the maxlen calculations here, we
- * could do them in fts_read before returning the name, but it's a
- * lot easier here since the length is part of the dirent structure.
- *
- * If not changing directories set a pointer so that can just append
- * each new component into the file name.
- */
- len = NAPPEND(cur);
- if (ISSET(FTS_NOCHDIR)) {
- cp = sp->fts_path + len;
- *cp++ = '/';
- } else {
- /* GCC, you're too verbose. */
- cp = NULL;
- }
- len++;
- maxlen = sp->fts_pathlen - len;
-
- level = cur->fts_level + 1;
-
- /* Read the directory, attaching each entry to the `link' pointer. */
- doadjust = false;
- for (head = tail = NULL, nitems = 0; dirp && (dp = readdir(dirp));) {
- bool is_dir;
-
- if (!ISSET(FTS_SEEDOT) && ISDOT(dp->d_name))
- continue;
-
- if ((p = fts_alloc (sp, dp->d_name,
- _D_EXACT_NAMLEN (dp))) == NULL)
- goto mem1;
- if (_D_EXACT_NAMLEN (dp) >= maxlen) {
- /* include space for NUL */
- oldaddr = sp->fts_path;
- if (! fts_palloc(sp, _D_EXACT_NAMLEN (dp) + len + 1)) {
- /*
- * No more memory. Save
- * errno, free up the current structure and the
- * structures already allocated.
- */
-mem1: saved_errno = errno;
- free(p);
- fts_lfree(head);
- closedir(dirp);
- cur->fts_info = FTS_ERR;
- SET(FTS_STOP);
- __set_errno (saved_errno);
- return (NULL);
- }
- /* Did realloc() change the pointer? */
- if (oldaddr != sp->fts_path) {
- doadjust = true;
- if (ISSET(FTS_NOCHDIR))
- cp = sp->fts_path + len;
- }
- maxlen = sp->fts_pathlen - len;
- }
-
- new_len = len + _D_EXACT_NAMLEN (dp);
- if (new_len < len) {
- /*
- * In the unlikely even that we would end up
- * with a file name longer than SIZE_MAX, free up
- * the current structure and the structures already
- * allocated, then error out with ENAMETOOLONG.
- */
- free(p);
- fts_lfree(head);
- closedir(dirp);
- cur->fts_info = FTS_ERR;
- SET(FTS_STOP);
- __set_errno (ENAMETOOLONG);
- return (NULL);
- }
- p->fts_level = level;
- p->fts_parent = sp->fts_cur;
- p->fts_pathlen = new_len;
-
-#if defined FTS_WHITEOUT && 0
- if (dp->d_type == DT_WHT)
- p->fts_flags |= FTS_ISW;
-#endif
-
- /* Build a file name for fts_stat to stat. */
- if (ISSET(FTS_NOCHDIR)) {
- p->fts_accpath = p->fts_path;
- memmove(cp, p->fts_name, p->fts_namelen + 1);
- } else
- p->fts_accpath = p->fts_name;
-
- if (sp->fts_compar == NULL || ISSET(FTS_DEFER_STAT)) {
- /* Record what fts_read will have to do with this
- entry. In many cases, it will simply fts_stat it,
- but we can take advantage of any d_type information
- to optimize away the unnecessary stat calls. I.e.,
- if FTS_NOSTAT is in effect and we're not following
- symlinks (FTS_PHYSICAL) and d_type indicates this
- is *not* a directory, then we won't have to stat it
- at all. If it *is* a directory, then (currently)
- we stat it regardless, in order to get device and
- inode numbers. Some day we might optimize that
- away, too, for directories where d_ino is known to
- be valid. */
- bool skip_stat = (ISSET(FTS_PHYSICAL)
- && ISSET(FTS_NOSTAT)
- && DT_IS_KNOWN(dp)
- && ! DT_MUST_BE(dp, DT_DIR));
- p->fts_info = FTS_NSOK;
- fts_set_stat_required(p, !skip_stat);
- is_dir = (ISSET(FTS_PHYSICAL) && ISSET(FTS_NOSTAT)
- && DT_MUST_BE(dp, DT_DIR));
- } else {
- p->fts_info = fts_stat(sp, p, false);
- is_dir = (p->fts_info == FTS_D
- || p->fts_info == FTS_DC
- || p->fts_info == FTS_DOT);
- }
-
- /* Decrement link count if applicable. */
- if (nlinks > 0 && is_dir)
- nlinks -= nostat;
-
- /* We walk in directory order so "ls -f" doesn't get upset. */
- p->fts_link = NULL;
- if (head == NULL)
- head = tail = p;
- else {
- tail->fts_link = p;
- tail = p;
- }
- ++nitems;
- }
- if (dirp)
- closedir(dirp);
-
- /*
- * If realloc() changed the address of the file name, adjust the
- * addresses for the rest of the tree and the dir list.
- */
- if (doadjust)
- fts_padjust(sp, head);
-
- /*
- * If not changing directories, reset the file name back to original
- * state.
- */
- if (ISSET(FTS_NOCHDIR)) {
- if (len == sp->fts_pathlen || nitems == 0)
- --cp;
- *cp = '\0';
- }
-
- /*
- * If descended after called from fts_children or after called from
- * fts_read and nothing found, get back. At the root level we use
- * the saved fd; if one of fts_open()'s arguments is a relative name
- * to an empty directory, we wind up here with no other way back. If
- * can't get back, we're done.
- */
- if (descend && (type == BCHILD || !nitems) &&
- (cur->fts_level == FTS_ROOTLEVEL
- ? RESTORE_INITIAL_CWD(sp)
- : fts_safe_changedir(sp, cur->fts_parent, -1, ".."))) {
- cur->fts_info = FTS_ERR;
- SET(FTS_STOP);
- fts_lfree(head);
- return (NULL);
- }
-
- /* If didn't find anything, return NULL. */
- if (!nitems) {
- if (type == BREAD)
- cur->fts_info = FTS_DP;
- fts_lfree(head);
- return (NULL);
- }
-
- /* Sort the entries. */
- if (sp->fts_compar && nitems > 1)
- head = fts_sort(sp, head, nitems);
- return (head);
+ register FTSENT *p, *head;
+ register size_t nitems;
+ FTSENT *tail;
+ void *oldaddr;
+ int saved_errno;
+ bool descend;
+ bool doadjust;
+ ptrdiff_t level;
+ nlink_t nlinks;
+ bool nostat;
+ size_t len, maxlen, new_len;
+ char *cp;
+ int dir_fd;
+ FTSENT *cur = sp->fts_cur;
+ bool continue_readdir = !!cur->fts_dirp;
+ size_t max_entries;
+
+ /* When cur->fts_dirp is non-NULL, that means we should
+ continue calling readdir on that existing DIR* pointer
+ rather than opening a new one. */
+ if (continue_readdir)
+ {
+ DIR *dp = cur->fts_dirp;
+ dir_fd = dirfd (dp);
+ if (dir_fd < 0)
+ {
+ closedir_and_clear (cur->fts_dirp);
+ if (type == BREAD)
+ {
+ cur->fts_info = FTS_DNR;
+ cur->fts_errno = errno;
+ }
+ return NULL;
+ }
+ }
+ else
+ {
+ /* Open the directory for reading. If this fails, we're done.
+ If being called from fts_read, set the fts_info field. */
+ if ((cur->fts_dirp = fts_opendir(cur->fts_accpath, &dir_fd)) == NULL)
+ {
+ if (type == BREAD)
+ {
+ cur->fts_info = FTS_DNR;
+ cur->fts_errno = errno;
+ }
+ return NULL;
+ }
+ /* Rather than calling fts_stat for each and every entry encountered
+ in the readdir loop (below), stat each directory only right after
+ opening it. */
+ if (cur->fts_info == FTS_NSOK)
+ cur->fts_info = fts_stat(sp, cur, false);
+ else if (sp->fts_options & FTS_TIGHT_CYCLE_CHECK)
+ {
+ /* Now read the stat info again after opening a directory to
+ reveal eventual changes caused by a submount triggered by
+ the traversal. But do it only for utilities which use
+ FTS_TIGHT_CYCLE_CHECK. Therefore, only find and du
+ benefit/suffer from this feature for now. */
+ LEAVE_DIR (sp, cur, "4");
+ fts_stat (sp, cur, false);
+ if (! enter_dir (sp, cur))
+ {
+ __set_errno (ENOMEM);
+ return NULL;
+ }
+ }
+ }
+
+ /* Maximum number of readdir entries to read at one time. This
+ limitation is to avoid reading millions of entries into memory
+ at once. When an fts_compar function is specified, we have no
+ choice: we must read all entries into memory before calling that
+ function. But when no such function is specified, we can read
+ entries in batches that are large enough to help us with inode-
+ sorting, yet not so large that we risk exhausting memory. */
+ max_entries = sp->fts_compar ? SIZE_MAX : FTS_MAX_READDIR_ENTRIES;
+
+ /*
+ * Nlinks is the number of possible entries of type directory in the
+ * directory if we're cheating on stat calls, 0 if we're not doing
+ * any stat calls at all, (nlink_t) -1 if we're statting everything.
+ */
+ if (type == BNAMES) {
+ nlinks = 0;
+ /* Be quiet about nostat, GCC. */
+ nostat = false;
+ } else if (ISSET(FTS_NOSTAT) && ISSET(FTS_PHYSICAL)) {
+ nlinks = (cur->fts_statp->st_nlink
+ - (ISSET(FTS_SEEDOT) ? 0 : 2));
+ nostat = true;
+ } else {
+ nlinks = -1;
+ nostat = false;
+ }
+
+ /*
+ * If we're going to need to stat anything or we want to descend
+ * and stay in the directory, chdir. If this fails we keep going,
+ * but set a flag so we don't chdir after the post-order visit.
+ * We won't be able to stat anything, but we can still return the
+ * names themselves. Note, that since fts_read won't be able to
+ * chdir into the directory, it will have to return different file
+ * names than before, i.e. "a/b" instead of "b". Since the node
+ * has already been visited in pre-order, have to wait until the
+ * post-order visit to return the error. There is a special case
+ * here, if there was nothing to stat then it's not an error to
+ * not be able to stat. This is all fairly nasty. If a program
+ * needed sorted entries or stat information, they had better be
+ * checking FTS_NS on the returned nodes.
+ */
+ if (continue_readdir)
+ {
+ /* When resuming a short readdir run, we already have
+ the required dirp and dir_fd. */
+ descend = true;
+ }
+ else if (nlinks || type == BREAD) {
+ if (ISSET(FTS_CWDFD))
+ {
+ dir_fd = dup (dir_fd);
+ if (0 <= dir_fd)
+ set_cloexec_flag (dir_fd, true);
+ }
+ if (dir_fd < 0 || fts_safe_changedir(sp, cur, dir_fd, NULL)) {
+ if (nlinks && type == BREAD)
+ cur->fts_errno = errno;
+ cur->fts_flags |= FTS_DONTCHDIR;
+ descend = false;
+ closedir_and_clear(cur->fts_dirp);
+ if (ISSET(FTS_CWDFD) && 0 <= dir_fd)
+ close (dir_fd);
+ cur->fts_dirp = NULL;
+ } else
+ descend = true;
+ } else
+ descend = false;
+
+ /*
+ * Figure out the max file name length that can be stored in the
+ * current buffer -- the inner loop allocates more space as necessary.
+ * We really wouldn't have to do the maxlen calculations here, we
+ * could do them in fts_read before returning the name, but it's a
+ * lot easier here since the length is part of the dirent structure.
+ *
+ * If not changing directories set a pointer so that can just append
+ * each new component into the file name.
+ */
+ len = NAPPEND(cur);
+ if (ISSET(FTS_NOCHDIR)) {
+ cp = sp->fts_path + len;
+ *cp++ = '/';
+ } else {
+ /* GCC, you're too verbose. */
+ cp = NULL;
+ }
+ len++;
+ maxlen = sp->fts_pathlen - len;
+
+ level = cur->fts_level + 1;
+
+ /* Read the directory, attaching each entry to the "link" pointer. */
+ doadjust = false;
+ head = NULL;
+ tail = NULL;
+ nitems = 0;
+ while (cur->fts_dirp) {
+ bool is_dir;
+ size_t d_namelen;
+ struct dirent *dp = readdir(cur->fts_dirp);
+ if (dp == NULL)
+ break;
+ if (!ISSET(FTS_SEEDOT) && ISDOT(dp->d_name))
+ continue;
+
+ d_namelen = _D_EXACT_NAMLEN (dp);
+ p = fts_alloc (sp, dp->d_name, d_namelen);
+ if (!p)
+ goto mem1;
+ if (d_namelen >= maxlen) {
+ /* include space for NUL */
+ oldaddr = sp->fts_path;
+ if (! fts_palloc(sp, d_namelen + len + 1)) {
+ /*
+ * No more memory. Save
+ * errno, free up the current structure and the
+ * structures already allocated.
+ */
+mem1: saved_errno = errno;
+ free(p);
+ fts_lfree(head);
+ closedir_and_clear(cur->fts_dirp);
+ cur->fts_info = FTS_ERR;
+ SET(FTS_STOP);
+ __set_errno (saved_errno);
+ return (NULL);
+ }
+ /* Did realloc() change the pointer? */
+ if (oldaddr != sp->fts_path) {
+ doadjust = true;
+ if (ISSET(FTS_NOCHDIR))
+ cp = sp->fts_path + len;
+ }
+ maxlen = sp->fts_pathlen - len;
+ }
+
+ new_len = len + d_namelen;
+ if (new_len < len) {
+ /*
+ * In the unlikely event that we would end up
+ * with a file name longer than SIZE_MAX, free up
+ * the current structure and the structures already
+ * allocated, then error out with ENAMETOOLONG.
+ */
+ free(p);
+ fts_lfree(head);
+ closedir_and_clear(cur->fts_dirp);
+ cur->fts_info = FTS_ERR;
+ SET(FTS_STOP);
+ __set_errno (ENAMETOOLONG);
+ return (NULL);
+ }
+ p->fts_level = level;
+ p->fts_parent = sp->fts_cur;
+ p->fts_pathlen = new_len;
+
+ /* Store dirent.d_ino, in case we need to sort
+ entries before processing them. */
+ p->fts_statp->st_ino = D_INO (dp);
+
+ /* Build a file name for fts_stat to stat. */
+ if (ISSET(FTS_NOCHDIR)) {
+ p->fts_accpath = p->fts_path;
+ memmove(cp, p->fts_name, p->fts_namelen + 1);
+ } else
+ p->fts_accpath = p->fts_name;
+
+ if (sp->fts_compar == NULL || ISSET(FTS_DEFER_STAT)) {
+ /* Record what fts_read will have to do with this
+ entry. In many cases, it will simply fts_stat it,
+ but we can take advantage of any d_type information
+ to optimize away the unnecessary stat calls. I.e.,
+ if FTS_NOSTAT is in effect and we're not following
+ symlinks (FTS_PHYSICAL) and d_type indicates this
+ is *not* a directory, then we won't have to stat it
+ at all. If it *is* a directory, then (currently)
+ we stat it regardless, in order to get device and
+ inode numbers. Some day we might optimize that
+ away, too, for directories where d_ino is known to
+ be valid. */
+ bool skip_stat = (ISSET(FTS_PHYSICAL)
+ && ISSET(FTS_NOSTAT)
+ && DT_IS_KNOWN(dp)
+ && ! DT_MUST_BE(dp, DT_DIR));
+ p->fts_info = FTS_NSOK;
+ /* Propagate dirent.d_type information back
+ to caller, when possible. */
+ set_stat_type (p->fts_statp, D_TYPE (dp));
+ fts_set_stat_required(p, !skip_stat);
+ is_dir = (ISSET(FTS_PHYSICAL)
+ && DT_MUST_BE(dp, DT_DIR));
+ } else {
+ p->fts_info = fts_stat(sp, p, false);
+ is_dir = (p->fts_info == FTS_D
+ || p->fts_info == FTS_DC
+ || p->fts_info == FTS_DOT);
+ }
+
+ /* Decrement link count if applicable. */
+ if (nlinks > 0 && is_dir)
+ nlinks -= nostat;
+
+ /* We walk in directory order so "ls -f" doesn't get upset. */
+ p->fts_link = NULL;
+ if (head == NULL)
+ head = tail = p;
+ else {
+ tail->fts_link = p;
+ tail = p;
+ }
+ ++nitems;
+ if (max_entries <= nitems) {
+ /* When there are too many dir entries, leave
+ fts_dirp open, so that a subsequent fts_read
+ can take up where we leave off. */
+ goto break_without_closedir;
+ }
+ }
+
+ if (cur->fts_dirp)
+ closedir_and_clear(cur->fts_dirp);
+
+ break_without_closedir:
+
+ /*
+ * If realloc() changed the address of the file name, adjust the
+ * addresses for the rest of the tree and the dir list.
+ */
+ if (doadjust)
+ fts_padjust(sp, head);
+
+ /*
+ * If not changing directories, reset the file name back to original
+ * state.
+ */
+ if (ISSET(FTS_NOCHDIR)) {
+ if (len == sp->fts_pathlen || nitems == 0)
+ --cp;
+ *cp = '\0';
+ }
+
+ /*
+ * If descended after called from fts_children or after called from
+ * fts_read and nothing found, get back. At the root level we use
+ * the saved fd; if one of fts_open()'s arguments is a relative name
+ * to an empty directory, we wind up here with no other way back. If
+ * can't get back, we're done.
+ */
+ if (!continue_readdir && descend && (type == BCHILD || !nitems) &&
+ (cur->fts_level == FTS_ROOTLEVEL
+ ? restore_initial_cwd(sp)
+ : fts_safe_changedir(sp, cur->fts_parent, -1, ".."))) {
+ cur->fts_info = FTS_ERR;
+ SET(FTS_STOP);
+ fts_lfree(head);
+ return (NULL);
+ }
+
+ /* If didn't find anything, return NULL. */
+ if (!nitems) {
+ if (type == BREAD)
+ cur->fts_info = FTS_DP;
+ fts_lfree(head);
+ return (NULL);
+ }
+
+ /* If there are many entries, no sorting function has been specified,
+ and this file system is of a type that may be slow with a large
+ number of entries, then sort the directory entries on increasing
+ inode numbers. */
+ if (nitems > _FTS_INODE_SORT_DIR_ENTRIES_THRESHOLD
+ && !sp->fts_compar
+ && ISSET (FTS_CWDFD)
+ && dirent_inode_sort_may_be_useful (sp->fts_cwd_fd)) {
+ sp->fts_compar = fts_compare_ino;
+ head = fts_sort (sp, head, nitems);
+ sp->fts_compar = NULL;
+ }
+
+ /* Sort the entries. */
+ if (sp->fts_compar && nitems > 1)
+ head = fts_sort(sp, head, nitems);
+ return (head);
}
#if FTS_DEBUG
@@ -1225,20 +1659,20 @@ find_matching_ancestor (FTSENT const *e_curr, struct Active_dir const *ad)
for (ent = e_curr; ent->fts_level >= FTS_ROOTLEVEL; ent = ent->fts_parent)
{
if (ad->ino == ent->fts_statp->st_ino
- && ad->dev == ent->fts_statp->st_dev)
- return;
+ && ad->dev == ent->fts_statp->st_dev)
+ return;
}
printf ("ERROR: tree dir, %s, not active\n", ad->fts_ent->fts_accpath);
printf ("active dirs:\n");
for (ent = e_curr;
ent->fts_level >= FTS_ROOTLEVEL; ent = ent->fts_parent)
printf (" %s(%"PRIuMAX"/%"PRIuMAX") to %s(%"PRIuMAX"/%"PRIuMAX")...\n",
- ad->fts_ent->fts_accpath,
- (uintmax_t) ad->dev,
- (uintmax_t) ad->ino,
- ent->fts_accpath,
- (uintmax_t) ent->fts_statp->st_dev,
- (uintmax_t) ent->fts_statp->st_ino);
+ ad->fts_ent->fts_accpath,
+ (uintmax_t) ad->dev,
+ (uintmax_t) ad->ino,
+ ent->fts_accpath,
+ (uintmax_t) ent->fts_statp->st_dev,
+ (uintmax_t) ent->fts_statp->st_ino);
}
void
@@ -1257,21 +1691,21 @@ fts_cross_check (FTS const *sp)
ad.ino = t->fts_statp->st_ino;
ad.dev = t->fts_statp->st_dev;
if ( ! hash_lookup (sp->fts_cycle.ht, &ad))
- printf ("ERROR: active dir, %s, not in tree\n", t->fts_path);
+ printf ("ERROR: active dir, %s, not in tree\n", t->fts_path);
}
/* Make sure every dir in the tree is an active dir.
But ENT is not necessarily a directory. If so, just skip this part. */
if (ent->fts_parent->fts_level >= FTS_ROOTLEVEL
&& (ent->fts_info == FTS_DP
- || ent->fts_info == FTS_D))
+ || ent->fts_info == FTS_D))
{
struct Active_dir *ad;
for (ad = hash_get_first (sp->fts_cycle.ht); ad != NULL;
- ad = hash_get_next (sp->fts_cycle.ht, ad))
- {
- find_matching_ancestor (ent, ad);
- }
+ ad = hash_get_next (sp->fts_cycle.ht, ad))
+ {
+ find_matching_ancestor (ent, ad);
+ }
}
}
@@ -1280,8 +1714,8 @@ same_fd (int fd1, int fd2)
{
struct stat sb1, sb2;
return (fstat (fd1, &sb1) == 0
- && fstat (fd2, &sb2) == 0
- && SAME_INODE (sb1, sb2));
+ && fstat (fd2, &sb2) == 0
+ && SAME_INODE (sb1, sb2));
}
static void
@@ -1299,15 +1733,15 @@ fd_ring_print (FTS const *sp, FILE *stream, char const *msg)
{
int fd = fd_ring->fts_fd_ring[i];
if (fd < 0)
- fprintf (stream, "%d: %d:\n", i, fd);
+ fprintf (stream, "%d: %d:\n", i, fd);
else
- {
- char *wd = getcwdat (fd, NULL, 0);
- fprintf (stream, "%d: %d: %s\n", i, fd, wd);
- free (wd);
- }
+ {
+ char *wd = getcwdat (fd, NULL, 0);
+ fprintf (stream, "%d: %d: %s\n", i, fd, wd);
+ free (wd);
+ }
if (i == fd_ring->fts_back)
- break;
+ break;
i = (i + I_RING_SIZE - 1) % I_RING_SIZE;
}
}
@@ -1332,26 +1766,26 @@ fd_ring_check (FTS const *sp)
{
int fd = i_ring_pop (&fd_w);
if (0 <= fd)
- {
- int parent_fd = openat (cwd_fd, "..", O_RDONLY);
- if (parent_fd < 0)
- {
- // Warn?
- break;
- }
- if (!same_fd (fd, parent_fd))
- {
- char *cwd = getcwdat (fd, NULL, 0);
- error (0, errno, "ring : %s", cwd);
- char *c2 = getcwdat (parent_fd, NULL, 0);
- error (0, errno, "parent: %s", c2);
- free (cwd);
- free (c2);
- fts_assert (0);
- }
- close (cwd_fd);
- cwd_fd = parent_fd;
- }
+ {
+ int parent_fd = openat (cwd_fd, "..", O_SEARCH | O_NOATIME);
+ if (parent_fd < 0)
+ {
+ // Warn?
+ break;
+ }
+ if (!same_fd (fd, parent_fd))
+ {
+ char *cwd = getcwdat (fd, NULL, 0);
+ error (0, errno, "ring : %s", cwd);
+ char *c2 = getcwdat (parent_fd, NULL, 0);
+ error (0, errno, "parent: %s", c2);
+ free (cwd);
+ free (c2);
+ fts_assert (0);
+ }
+ close (cwd_fd);
+ cwd_fd = parent_fd;
+ }
}
close (cwd_fd);
}
@@ -1361,78 +1795,50 @@ static unsigned short int
internal_function
fts_stat(FTS *sp, register FTSENT *p, bool follow)
{
- struct stat *sbp = p->fts_statp;
- int saved_errno;
-
- if (p->fts_level == FTS_ROOTLEVEL && ISSET(FTS_COMFOLLOW))
- follow = true;
-
-#if defined FTS_WHITEOUT && 0
- /* check for whiteout */
- if (p->fts_flags & FTS_ISW) {
- memset(sbp, '\0', sizeof (*sbp));
- sbp->st_mode = S_IFWHT;
- return (FTS_W);
- }
-#endif
-
- /*
- * If doing a logical walk, or application requested FTS_FOLLOW, do
- * a stat(2). If that fails, check for a non-existent symlink. If
- * fail, set the errno from the stat call.
- */
- if (ISSET(FTS_LOGICAL) || follow) {
- if (stat(p->fts_accpath, sbp)) {
- saved_errno = errno;
- if (errno == ENOENT
- && lstat(p->fts_accpath, sbp) == 0) {
- __set_errno (0);
- return (FTS_SLNONE);
- }
- p->fts_errno = saved_errno;
- goto err;
- }
- } else if (fstatat(sp->fts_cwd_fd, p->fts_accpath, sbp,
- AT_SYMLINK_NOFOLLOW)) {
- p->fts_errno = errno;
-err: memset(sbp, 0, sizeof(struct stat));
- return (FTS_NS);
- }
-
- if (S_ISDIR(sbp->st_mode)) {
- if (ISDOT(p->fts_name)) {
- /* Command-line "." and ".." are real directories. */
- return (p->fts_level == FTS_ROOTLEVEL ? FTS_D : FTS_DOT);
- }
-
-#if !GNULIB_FTS
- {
- /*
- * Cycle detection is done by brute force when the directory
- * is first encountered. If the tree gets deep enough or the
- * number of symbolic links to directories is high enough,
- * something faster might be worthwhile.
- */
- FTSENT *t;
-
- for (t = p->fts_parent;
- t->fts_level >= FTS_ROOTLEVEL; t = t->fts_parent)
- if (sbp->st_ino == t->fts_statp->st_ino
- && sbp->st_dev == t->fts_statp->st_dev)
- {
- p->fts_cycle = t;
- return (FTS_DC);
- }
- }
-#endif
-
- return (FTS_D);
- }
- if (S_ISLNK(sbp->st_mode))
- return (FTS_SL);
- if (S_ISREG(sbp->st_mode))
- return (FTS_F);
- return (FTS_DEFAULT);
+ struct stat *sbp = p->fts_statp;
+ int saved_errno;
+
+ if (p->fts_level == FTS_ROOTLEVEL && ISSET(FTS_COMFOLLOW))
+ follow = true;
+
+ /*
+ * If doing a logical walk, or application requested FTS_FOLLOW, do
+ * a stat(2). If that fails, check for a non-existent symlink. If
+ * fail, set the errno from the stat call.
+ */
+ if (ISSET(FTS_LOGICAL) || follow) {
+ if (stat(p->fts_accpath, sbp)) {
+ saved_errno = errno;
+ if (errno == ENOENT
+ && lstat(p->fts_accpath, sbp) == 0) {
+ __set_errno (0);
+ return (FTS_SLNONE);
+ }
+ p->fts_errno = saved_errno;
+ goto err;
+ }
+ } else if (fstatat(sp->fts_cwd_fd, p->fts_accpath, sbp,
+ AT_SYMLINK_NOFOLLOW)) {
+ p->fts_errno = errno;
+err: memset(sbp, 0, sizeof(struct stat));
+ return (FTS_NS);
+ }
+
+ if (S_ISDIR(sbp->st_mode)) {
+ p->fts_n_dirs_remaining = (sbp->st_nlink
+ - (ISSET(FTS_SEEDOT) ? 0 : 2));
+ if (ISDOT(p->fts_name)) {
+ /* Command-line "." and ".." are real directories. */
+ return (p->fts_level == FTS_ROOTLEVEL ? FTS_D : FTS_DOT);
+ }
+
+ return (FTS_D);
+ }
+ if (S_ISLNK(sbp->st_mode))
+ return (FTS_SL);
+ if (S_ISREG(sbp->st_mode))
+ return (FTS_F);
+ return (FTS_DEFAULT);
}
static int
@@ -1452,93 +1858,106 @@ static FTSENT *
internal_function
fts_sort (FTS *sp, FTSENT *head, register size_t nitems)
{
- register FTSENT **ap, *p;
-
- /* On most modern hosts, void * and FTSENT ** have the same
- run-time representation, and one can convert sp->fts_compar to
- the type qsort expects without problem. Use the heuristic that
- this is OK if the two pointer types are the same size, and if
- converting FTSENT ** to long int is the same as converting
- FTSENT ** to void * and then to long int. This heuristic isn't
- valid in general but we don't know of any counterexamples. */
- FTSENT *dummy;
- int (*compare) (void const *, void const *) =
- ((sizeof &dummy == sizeof (void *)
- && (long int) &dummy == (long int) (void *) &dummy)
- ? (int (*) (void const *, void const *)) sp->fts_compar
- : fts_compar);
-
- /*
- * Construct an array of pointers to the structures and call qsort(3).
- * Reassemble the array in the order returned by qsort. If unable to
- * sort for memory reasons, return the directory entries in their
- * current order. Allocate enough space for the current needs plus
- * 40 so don't realloc one entry at a time.
- */
- if (nitems > sp->fts_nitems) {
- struct _ftsent **a;
-
- sp->fts_nitems = nitems + 40;
- if (SIZE_MAX / sizeof *a < sp->fts_nitems
- || ! (a = realloc (sp->fts_array,
- sp->fts_nitems * sizeof *a))) {
- free(sp->fts_array);
- sp->fts_array = NULL;
- sp->fts_nitems = 0;
- return (head);
- }
- sp->fts_array = a;
- }
- for (ap = sp->fts_array, p = head; p; p = p->fts_link)
- *ap++ = p;
- qsort((void *)sp->fts_array, nitems, sizeof(FTSENT *), compare);
- for (head = *(ap = sp->fts_array); --nitems; ++ap)
- ap[0]->fts_link = ap[1];
- ap[0]->fts_link = NULL;
- return (head);
+ register FTSENT **ap, *p;
+
+ /* On most modern hosts, void * and FTSENT ** have the same
+ run-time representation, and one can convert sp->fts_compar to
+ the type qsort expects without problem. Use the heuristic that
+ this is OK if the two pointer types are the same size, and if
+ converting FTSENT ** to long int is the same as converting
+ FTSENT ** to void * and then to long int. This heuristic isn't
+ valid in general but we don't know of any counterexamples. */
+ FTSENT *dummy;
+ int (*compare) (void const *, void const *) =
+ ((sizeof &dummy == sizeof (void *)
+ && (long int) &dummy == (long int) (void *) &dummy)
+ ? (int (*) (void const *, void const *)) sp->fts_compar
+ : fts_compar);
+
+ /*
+ * Construct an array of pointers to the structures and call qsort(3).
+ * Reassemble the array in the order returned by qsort. If unable to
+ * sort for memory reasons, return the directory entries in their
+ * current order. Allocate enough space for the current needs plus
+ * 40 so don't realloc one entry at a time.
+ */
+ if (nitems > sp->fts_nitems) {
+ FTSENT **a;
+
+ sp->fts_nitems = nitems + 40;
+ if (SIZE_MAX / sizeof *a < sp->fts_nitems
+ || ! (a = realloc (sp->fts_array,
+ sp->fts_nitems * sizeof *a))) {
+ free(sp->fts_array);
+ sp->fts_array = NULL;
+ sp->fts_nitems = 0;
+ return (head);
+ }
+ sp->fts_array = a;
+ }
+ for (ap = sp->fts_array, p = head; p; p = p->fts_link)
+ *ap++ = p;
+ qsort((void *)sp->fts_array, nitems, sizeof(FTSENT *), compare);
+ for (head = *(ap = sp->fts_array); --nitems; ++ap)
+ ap[0]->fts_link = ap[1];
+ ap[0]->fts_link = NULL;
+ return (head);
}
static FTSENT *
internal_function
fts_alloc (FTS *sp, const char *name, register size_t namelen)
{
- register FTSENT *p;
- size_t len;
-
- /*
- * The file name is a variable length array. Allocate the FTSENT
- * structure and the file name in one chunk.
- */
- len = sizeof(FTSENT) + namelen;
- if ((p = malloc(len)) == NULL)
- return (NULL);
-
- /* Copy the name and guarantee NUL termination. */
- memmove(p->fts_name, name, namelen);
- p->fts_name[namelen] = '\0';
-
- p->fts_namelen = namelen;
- p->fts_fts = sp;
- p->fts_path = sp->fts_path;
- p->fts_errno = 0;
- p->fts_flags = 0;
- p->fts_instr = FTS_NOINSTR;
- p->fts_number = 0;
- p->fts_pointer = NULL;
- return (p);
+ register FTSENT *p;
+ size_t len;
+
+ /*
+ * The file name is a variable length array. Allocate the FTSENT
+ * structure and the file name in one chunk.
+ */
+ len = offsetof(FTSENT, fts_name) + namelen + 1;
+ /* Align the allocation size so that it works for FTSENT,
+ so that trailing padding may be referenced by direct access
+ to the flexible array members, without triggering undefined behavior
+ by accessing bytes beyond the heap allocation. This implicit access
+ was seen for example with ISDOT() and GCC 5.1.1 at -O2.
+ Do not use alignof (FTSENT) here, since C11 prohibits
+ taking the alignment of a structure containing a flexible
+ array member. */
+ len += alignof (max_align_t) - 1;
+ len &= ~ (alignof (max_align_t) - 1);
+ if ((p = malloc(len)) == NULL)
+ return (NULL);
+
+ /* Copy the name and guarantee NUL termination. */
+ memcpy(p->fts_name, name, namelen);
+ p->fts_name[namelen] = '\0';
+
+ p->fts_namelen = namelen;
+ p->fts_fts = sp;
+ p->fts_path = sp->fts_path;
+ p->fts_errno = 0;
+ p->fts_dirp = NULL;
+ p->fts_flags = 0;
+ p->fts_instr = FTS_NOINSTR;
+ p->fts_number = 0;
+ p->fts_pointer = NULL;
+ return (p);
}
static void
internal_function
fts_lfree (register FTSENT *head)
{
- register FTSENT *p;
-
- /* Free a linked list of structures. */
- while ((p = head)) {
- head = head->fts_link;
- free(p);
- }
+ register FTSENT *p;
+
+ /* Free a linked list of structures. */
+ while ((p = head)) {
+ head = head->fts_link;
+ if (p->fts_dirp)
+ closedir (p->fts_dirp);
+ free(p);
+ }
}
/*
@@ -1552,27 +1971,27 @@ static bool
internal_function
fts_palloc (FTS *sp, size_t more)
{
- char *p;
- size_t new_len = sp->fts_pathlen + more + 256;
-
- /*
- * See if fts_pathlen would overflow.
- */
- if (new_len < sp->fts_pathlen) {
- free(sp->fts_path);
- sp->fts_path = NULL;
- __set_errno (ENAMETOOLONG);
- return false;
- }
- sp->fts_pathlen = new_len;
- p = realloc(sp->fts_path, sp->fts_pathlen);
- if (p == NULL) {
- free(sp->fts_path);
- sp->fts_path = NULL;
- return false;
- }
- sp->fts_path = p;
- return true;
+ char *p;
+ size_t new_len = sp->fts_pathlen + more + 256;
+
+ /*
+ * See if fts_pathlen would overflow.
+ */
+ if (new_len < sp->fts_pathlen) {
+ free(sp->fts_path);
+ sp->fts_path = NULL;
+ __set_errno (ENAMETOOLONG);
+ return false;
+ }
+ sp->fts_pathlen = new_len;
+ p = realloc(sp->fts_path, sp->fts_pathlen);
+ if (p == NULL) {
+ free(sp->fts_path);
+ sp->fts_path = NULL;
+ return false;
+ }
+ sp->fts_path = p;
+ return true;
}
/*
@@ -1583,37 +2002,37 @@ static void
internal_function
fts_padjust (FTS *sp, FTSENT *head)
{
- FTSENT *p;
- char *addr = sp->fts_path;
-
-#define ADJUST(p) do { \
- if ((p)->fts_accpath != (p)->fts_name) { \
- (p)->fts_accpath = \
- (char *)addr + ((p)->fts_accpath - (p)->fts_path); \
- } \
- (p)->fts_path = addr; \
+ FTSENT *p;
+ char *addr = sp->fts_path;
+
+#define ADJUST(p) do { \
+ if ((p)->fts_accpath != (p)->fts_name) { \
+ (p)->fts_accpath = \
+ (char *)addr + ((p)->fts_accpath - (p)->fts_path); \
+ } \
+ (p)->fts_path = addr; \
} while (0)
- /* Adjust the current set of children. */
- for (p = sp->fts_child; p; p = p->fts_link)
- ADJUST(p);
-
- /* Adjust the rest of the tree, including the current level. */
- for (p = head; p->fts_level >= FTS_ROOTLEVEL;) {
- ADJUST(p);
- p = p->fts_link ? p->fts_link : p->fts_parent;
- }
+ /* Adjust the current set of children. */
+ for (p = sp->fts_child; p; p = p->fts_link)
+ ADJUST(p);
+
+ /* Adjust the rest of the tree, including the current level. */
+ for (p = head; p->fts_level >= FTS_ROOTLEVEL;) {
+ ADJUST(p);
+ p = p->fts_link ? p->fts_link : p->fts_parent;
+ }
}
static size_t
-internal_function
+internal_function _GL_ATTRIBUTE_PURE
fts_maxarglen (char * const *argv)
{
- size_t len, max;
+ size_t len, max;
- for (max = 0; *argv; ++argv)
- if ((len = strlen(*argv)) > max)
- max = len;
- return (max + 1);
+ for (max = 0; *argv; ++argv)
+ if ((len = strlen(*argv)) > max)
+ max = len;
+ return (max + 1);
}
/*
@@ -1621,7 +2040,7 @@ fts_maxarglen (char * const *argv)
* tricked by someone changing the world out from underneath us.
* Assumes p->fts_statp->st_dev and p->fts_statp->st_ino are filled in.
* If FD is non-negative, expect it to be used after this function returns,
- * and to be closed eventually. So don't pass e.g., `dirfd(dirp)' and then
+ * and to be closed eventually. So don't pass e.g., 'dirfd(dirp)' and then
* do closedir(dirp), because that would invalidate the saved FD.
* Upon failure, close FD immediately and return nonzero.
*/
@@ -1629,84 +2048,84 @@ static int
internal_function
fts_safe_changedir (FTS *sp, FTSENT *p, int fd, char const *dir)
{
- int ret;
- bool is_dotdot = dir && STREQ (dir, "..");
- int newfd;
-
- /* This clause handles the unusual case in which FTS_NOCHDIR
- is specified, along with FTS_CWDFD. In that case, there is
- no need to change even the virtual cwd file descriptor.
- However, if FD is non-negative, we do close it here. */
- if (ISSET (FTS_NOCHDIR))
- {
- if (ISSET (FTS_CWDFD) && 0 <= fd)
- close (fd);
- return 0;
- }
-
- if (fd < 0 && is_dotdot && ISSET (FTS_CWDFD))
- {
- /* When possible, skip the diropen and subsequent fstat+dev/ino
- comparison. I.e., when changing to parent directory
- (chdir ("..")), use a file descriptor from the ring and
- save the overhead of diropen+fstat, as well as avoiding
- failure when we lack "x" access to the virtual cwd. */
- if ( ! i_ring_empty (&sp->fts_fd_ring))
- {
- int parent_fd;
- fd_ring_print (sp, stderr, "pre-pop");
- parent_fd = i_ring_pop (&sp->fts_fd_ring);
- is_dotdot = true;
- if (0 <= parent_fd)
- {
- fd = parent_fd;
- dir = NULL;
- }
- }
- }
-
- newfd = fd;
- if (fd < 0 && (newfd = diropen (sp, dir)) < 0)
- return -1;
-
- /* The following dev/inode check is necessary if we're doing a
- `logical' traversal (through symlinks, a la chown -L), if the
- system lacks O_NOFOLLOW support, or if we're changing to ".."
- (but not via a popped file descriptor). When changing to the
- name "..", O_NOFOLLOW can't help. In general, when the target is
- not "..", diropen's use of O_NOFOLLOW ensures we don't mistakenly
- follow a symlink, so we can avoid the expense of this fstat. */
- if (ISSET(FTS_LOGICAL) || ! HAVE_WORKING_O_NOFOLLOW
- || (dir && STREQ (dir, "..")))
- {
- struct stat sb;
- if (fstat(newfd, &sb))
- {
- ret = -1;
- goto bail;
- }
- if (p->fts_statp->st_dev != sb.st_dev
- || p->fts_statp->st_ino != sb.st_ino)
- {
- __set_errno (ENOENT); /* disinformation */
- ret = -1;
- goto bail;
- }
- }
-
- if (ISSET(FTS_CWDFD))
- {
- cwd_advance_fd (sp, newfd, ! is_dotdot);
- return 0;
- }
-
- ret = fchdir(newfd);
+ int ret;
+ bool is_dotdot = dir && STREQ (dir, "..");
+ int newfd;
+
+ /* This clause handles the unusual case in which FTS_NOCHDIR
+ is specified, along with FTS_CWDFD. In that case, there is
+ no need to change even the virtual cwd file descriptor.
+ However, if FD is non-negative, we do close it here. */
+ if (ISSET (FTS_NOCHDIR))
+ {
+ if (ISSET (FTS_CWDFD) && 0 <= fd)
+ close (fd);
+ return 0;
+ }
+
+ if (fd < 0 && is_dotdot && ISSET (FTS_CWDFD))
+ {
+ /* When possible, skip the diropen and subsequent fstat+dev/ino
+ comparison. I.e., when changing to parent directory
+ (chdir ("..")), use a file descriptor from the ring and
+ save the overhead of diropen+fstat, as well as avoiding
+ failure when we lack "x" access to the virtual cwd. */
+ if ( ! i_ring_empty (&sp->fts_fd_ring))
+ {
+ int parent_fd;
+ fd_ring_print (sp, stderr, "pre-pop");
+ parent_fd = i_ring_pop (&sp->fts_fd_ring);
+ is_dotdot = true;
+ if (0 <= parent_fd)
+ {
+ fd = parent_fd;
+ dir = NULL;
+ }
+ }
+ }
+
+ newfd = fd;
+ if (fd < 0 && (newfd = diropen (sp, dir)) < 0)
+ return -1;
+
+ /* The following dev/inode check is necessary if we're doing a
+ "logical" traversal (through symlinks, a la chown -L), if the
+ system lacks O_NOFOLLOW support, or if we're changing to ".."
+ (but not via a popped file descriptor). When changing to the
+ name "..", O_NOFOLLOW can't help. In general, when the target is
+ not "..", diropen's use of O_NOFOLLOW ensures we don't mistakenly
+ follow a symlink, so we can avoid the expense of this fstat. */
+ if (ISSET(FTS_LOGICAL) || ! HAVE_WORKING_O_NOFOLLOW
+ || (dir && STREQ (dir, "..")))
+ {
+ struct stat sb;
+ if (fstat(newfd, &sb))
+ {
+ ret = -1;
+ goto bail;
+ }
+ if (p->fts_statp->st_dev != sb.st_dev
+ || p->fts_statp->st_ino != sb.st_ino)
+ {
+ __set_errno (ENOENT); /* disinformation */
+ ret = -1;
+ goto bail;
+ }
+ }
+
+ if (ISSET(FTS_CWDFD))
+ {
+ cwd_advance_fd (sp, newfd, ! is_dotdot);
+ return 0;
+ }
+
+ ret = fchdir(newfd);
bail:
- if (fd < 0)
- {
- int oerrno = errno;
- (void)close(newfd);
- __set_errno (oerrno);
- }
- return ret;
+ if (fd < 0)
+ {
+ int oerrno = errno;
+ (void)close(newfd);
+ __set_errno (oerrno);
+ }
+ return ret;
}
diff --git a/lib/fts_.h b/lib/fts_.h
index a8a52d2..9cd46e2 100644
--- a/lib/fts_.h
+++ b/lib/fts_.h
@@ -1,11 +1,11 @@
/* Traverse a file hierarchy.
- Copyright (C) 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
+ Copyright (C) 2004-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,12 +13,11 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/*
* Copyright (c) 1989, 1993
- * The Regents of the University of California. All rights reserved.
+ * The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -32,7 +31,7 @@
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
@@ -44,57 +43,69 @@
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
- * @(#)fts.h 8.3 (Berkeley) 8/14/94
+ * @(#)fts.h 8.3 (Berkeley) 8/14/94
*/
-#ifndef _FTS_H
+#ifndef _FTS_H
# define _FTS_H 1
# ifdef _LIBC
# include <features.h>
+# if __STDC_VERSION__ < 199901L
+# define __FLEXIBLE_ARRAY_MEMBER 1
+# else
+# define __FLEXIBLE_ARRAY_MEMBER
+# endif
# else
+# define __FLEXIBLE_ARRAY_MEMBER FLEXIBLE_ARRAY_MEMBER
# undef __THROW
# define __THROW
# undef __BEGIN_DECLS
-# define __BEGIN_DECLS
# undef __END_DECLS
-# define __END_DECLS
+# ifdef __cplusplus
+# define __BEGIN_DECLS extern "C" {
+# define __END_DECLS }
+# else
+# define __BEGIN_DECLS
+# define __END_DECLS
+# endif
# endif
# include <stddef.h>
# include <sys/types.h>
+# include <dirent.h>
# include <sys/stat.h>
# include "i-ring.h"
typedef struct {
- struct _ftsent *fts_cur; /* current node */
- struct _ftsent *fts_child; /* linked list of children */
- struct _ftsent **fts_array; /* sort array */
- dev_t fts_dev; /* starting device # */
- char *fts_path; /* file name for this descent */
- int fts_rfd; /* fd for root */
- int fts_cwd_fd; /* the file descriptor on which the
- virtual cwd is open, or AT_FDCWD */
- size_t fts_pathlen; /* sizeof(path) */
- size_t fts_nitems; /* elements in the sort array */
- int (*fts_compar) (struct _ftsent const **, struct _ftsent const **);
- /* compare fn */
-
-# define FTS_COMFOLLOW 0x0001 /* follow command line symlinks */
-# define FTS_LOGICAL 0x0002 /* logical walk */
-# define FTS_NOCHDIR 0x0004 /* don't change directories */
-# define FTS_NOSTAT 0x0008 /* don't get stat info */
-# define FTS_PHYSICAL 0x0010 /* physical walk */
-# define FTS_SEEDOT 0x0020 /* return dot and dot-dot */
-# define FTS_XDEV 0x0040 /* don't cross devices */
-# define FTS_WHITEOUT 0x0080 /* return whiteout information */
+ struct _ftsent *fts_cur; /* current node */
+ struct _ftsent *fts_child; /* linked list of children */
+ struct _ftsent **fts_array; /* sort array */
+ dev_t fts_dev; /* starting device # */
+ char *fts_path; /* file name for this descent */
+ int fts_rfd; /* fd for root */
+ int fts_cwd_fd; /* the file descriptor on which the
+ virtual cwd is open, or AT_FDCWD */
+ size_t fts_pathlen; /* sizeof(path) */
+ size_t fts_nitems; /* elements in the sort array */
+ int (*fts_compar) (struct _ftsent const **, struct _ftsent const **);
+ /* compare fn */
+
+# define FTS_COMFOLLOW 0x0001 /* follow command line symlinks */
+# define FTS_LOGICAL 0x0002 /* logical walk */
+# define FTS_NOCHDIR 0x0004 /* don't change directories */
+# define FTS_NOSTAT 0x0008 /* don't get stat info */
+# define FTS_PHYSICAL 0x0010 /* physical walk */
+# define FTS_SEEDOT 0x0020 /* return dot and dot-dot */
+# define FTS_XDEV 0x0040 /* don't cross devices */
+# define FTS_WHITEOUT 0x0080 /* return whiteout information */
/* There are two ways to detect cycles.
The lazy way (which works only with FTS_PHYSICAL),
with which one may process a directory that is a
part of the cycle several times before detecting the cycle.
- The `tight' way, whereby fts uses more memory (proportional
- to number of `active' directories, aka distance from root
+ The "tight" way, whereby fts uses more memory (proportional
+ to number of "active" directories, aka distance from root
of current tree to current directory -- see active_dir_ht)
to detect any cycle right away. For example, du must use
this option to avoid counting disk space in a cycle multiple
@@ -112,7 +123,7 @@ typedef struct {
slink -> dir
So, when FTS_LOGICAL is selected, we have to use a different
mode of cycle detection: FTS_TIGHT_CYCLE_CHECK. */
-# define FTS_TIGHT_CYCLE_CHECK 0x0100
+# define FTS_TIGHT_CYCLE_CHECK 0x0100
/* Use this flag to enable semantics with which the parent
application may be made both more efficient and more robust.
@@ -121,7 +132,7 @@ typedef struct {
working directory is never changed. Instead, these functions
perform the traversal via a virtual working directory, maintained
through the file descriptor member, fts_cwd_fd. */
-# define FTS_CWDFD 0x0200
+# define FTS_CWDFD 0x0200
/* Historically, for each directory that fts initially encounters, it would
open it, read all entries, and stat each entry, storing the results, and
@@ -130,104 +141,142 @@ typedef struct {
file systems like FAT, CIFS, FUSE-based ones, etc., when entries from
their name/inode cache are flushed too early.
Use this flag to make fts_open and fts_read defer the stat/lstat/fststat
- of each entry until it actually processed. However, note that if you use
- this option and also specify a comparison function, that function may not
- examine any data via fts_statp. */
-# define FTS_DEFER_STAT 0x0400
-
-# define FTS_OPTIONMASK 0x07ff /* valid user option mask */
-
-# define FTS_NAMEONLY 0x1000 /* (private) child names only */
-# define FTS_STOP 0x2000 /* (private) unrecoverable error */
- int fts_options; /* fts_open options, global flags */
-
-# if GNULIB_FTS
- union {
- /* This data structure is used if FTS_TIGHT_CYCLE_CHECK is
- specified. It records the directories between a starting
- point and the current directory. I.e., a directory is
- recorded here IFF we have visited it once, but we have not
- yet completed processing of all its entries. Every time we
- visit a new directory, we add that directory to this set.
- When we finish with a directory (usually by visiting it a
- second time), we remove it from this set. Each entry in
- this data structure is a device/inode pair. This data
- structure is used to detect directory cycles efficiently and
- promptly even when the depth of a hierarchy is in the tens
- of thousands. */
- struct hash_table *ht;
-
- /* FIXME: rename these two members to have the fts_ prefix */
- /* This data structure uses a lazy cycle-detection algorithm,
- as done by rm via cycle-check.c. It's the default,
- but it's not appropriate for programs like du. */
- struct cycle_check_state *state;
- } fts_cycle;
+ of each entry until it is actually processed. However, note that if you
+ use this option and also specify a comparison function, that function may
+ not examine any data via fts_statp. However, when fts_statp->st_mode is
+ nonzero, the S_IFMT type bits are valid, with mapped dirent.d_type data.
+ Of course, that happens only on file systems that provide useful
+ dirent.d_type data. */
+# define FTS_DEFER_STAT 0x0400
-# endif
- /* A stack of the file descriptors corresponding to the
- most-recently traversed parent directories.
- Currently used only in FTS_CWDFD mode. */
- I_ring fts_fd_ring;
+# define FTS_NOATIME 0x0800 /* use O_NOATIME during traversal */
+
+ /* Use this flag to disable stripping of trailing slashes
+ from input path names during fts_open initialization. */
+# define FTS_VERBATIM 0x1000
+
+# define FTS_OPTIONMASK 0x1fff /* valid user option mask */
+
+# define FTS_NAMEONLY 0x2000 /* (private) child names only */
+# define FTS_STOP 0x4000 /* (private) unrecoverable error */
+ int fts_options; /* fts_open options, global flags */
+
+ /* Map a directory's device number to a boolean. The boolean is
+ true if for that file system (type determined by a single fstatfs
+ call per FS) st_nlink can be used to calculate the number of
+ sub-directory entries in a directory.
+ Using this table is an optimization that permits us to look up
+ file system type on a per-inode basis at the minimal cost of
+ calling fstatfs only once per traversed device. */
+ struct hash_table *fts_leaf_optimization_works_ht;
+
+ union {
+ /* This data structure is used if FTS_TIGHT_CYCLE_CHECK is
+ specified. It records the directories between a starting
+ point and the current directory. I.e., a directory is
+ recorded here IFF we have visited it once, but we have not
+ yet completed processing of all its entries. Every time we
+ visit a new directory, we add that directory to this set.
+ When we finish with a directory (usually by visiting it a
+ second time), we remove it from this set. Each entry in
+ this data structure is a device/inode pair. This data
+ structure is used to detect directory cycles efficiently and
+ promptly even when the depth of a hierarchy is in the tens
+ of thousands. */
+ struct hash_table *ht;
+
+ /* FIXME: rename these two members to have the fts_ prefix */
+ /* This data structure uses a lazy cycle-detection algorithm,
+ as done by rm via cycle-check.c. It's the default,
+ but it's not appropriate for programs like du. */
+ struct cycle_check_state *state;
+ } fts_cycle;
+
+ /* A stack of the file descriptors corresponding to the
+ most-recently traversed parent directories.
+ Currently used only in FTS_CWDFD mode. */
+ I_ring fts_fd_ring;
} FTS;
typedef struct _ftsent {
- struct _ftsent *fts_cycle; /* cycle node */
- struct _ftsent *fts_parent; /* parent directory */
- struct _ftsent *fts_link; /* next file in directory */
- long fts_number; /* local numeric value */
- void *fts_pointer; /* local address value */
- char *fts_accpath; /* access file name */
- char *fts_path; /* root name; == fts_fts->fts_path */
- int fts_errno; /* errno for this node */
- int fts_symfd; /* fd for symlink */
- size_t fts_pathlen; /* strlen(fts_path) */
-
- FTS *fts_fts; /* the file hierarchy itself */
-
-# define FTS_ROOTPARENTLEVEL (-1)
-# define FTS_ROOTLEVEL 0
- ptrdiff_t fts_level; /* depth (-1 to N) */
-
- size_t fts_namelen; /* strlen(fts_name) */
-
-# define FTS_D 1 /* preorder directory */
-# define FTS_DC 2 /* directory that causes cycles */
-# define FTS_DEFAULT 3 /* none of the above */
-# define FTS_DNR 4 /* unreadable directory */
-# define FTS_DOT 5 /* dot or dot-dot */
-# define FTS_DP 6 /* postorder directory */
-# define FTS_ERR 7 /* error; errno is set */
-# define FTS_F 8 /* regular file */
-# define FTS_INIT 9 /* initialized only */
-# define FTS_NS 10 /* stat(2) failed */
-# define FTS_NSOK 11 /* no stat(2) requested */
-# define FTS_SL 12 /* symbolic link */
-# define FTS_SLNONE 13 /* symbolic link without target */
-# define FTS_W 14 /* whiteout object */
- unsigned short int fts_info; /* user flags for FTSENT structure */
-
-# define FTS_DONTCHDIR 0x01 /* don't chdir .. to the parent */
-# define FTS_SYMFOLLOW 0x02 /* followed a symlink to get here */
- unsigned short int fts_flags; /* private flags for FTSENT structure */
-
-# define FTS_AGAIN 1 /* read node again */
-# define FTS_FOLLOW 2 /* follow symbolic link */
-# define FTS_NOINSTR 3 /* no instructions */
-# define FTS_SKIP 4 /* discard node */
- unsigned short int fts_instr; /* fts_set() instructions */
-
- struct stat fts_statp[1]; /* stat(2) information */
- char fts_name[1]; /* file name */
+ struct _ftsent *fts_cycle; /* cycle node */
+ struct _ftsent *fts_parent; /* parent directory */
+ struct _ftsent *fts_link; /* next file in directory */
+ DIR *fts_dirp; /* Dir pointer for any directory
+ containing more entries than we
+ read at one time. */
+ long fts_number; /* local numeric value */
+ void *fts_pointer; /* local address value */
+ char *fts_accpath; /* access file name */
+ char *fts_path; /* root name; == fts_fts->fts_path */
+ int fts_errno; /* errno for this node */
+ int fts_symfd; /* fd for symlink */
+ size_t fts_pathlen; /* strlen(fts_path) */
+
+ FTS *fts_fts; /* the file hierarchy itself */
+
+# define FTS_ROOTPARENTLEVEL (-1)
+# define FTS_ROOTLEVEL 0
+ ptrdiff_t fts_level; /* depth (-1 to N) */
+
+ size_t fts_namelen; /* strlen(fts_name) */
+ nlink_t fts_n_dirs_remaining; /* count down from st_nlink */
+
+# define FTS_D 1 /* preorder directory */
+# define FTS_DC 2 /* directory that causes cycles */
+# define FTS_DEFAULT 3 /* none of the above */
+# define FTS_DNR 4 /* unreadable directory */
+# define FTS_DOT 5 /* dot or dot-dot */
+# define FTS_DP 6 /* postorder directory */
+# define FTS_ERR 7 /* error; errno is set */
+# define FTS_F 8 /* regular file */
+# define FTS_INIT 9 /* initialized only */
+# define FTS_NS 10 /* stat(2) failed */
+# define FTS_NSOK 11 /* no stat(2) requested */
+# define FTS_SL 12 /* symbolic link */
+# define FTS_SLNONE 13 /* symbolic link without target */
+# define FTS_W 14 /* whiteout object */
+ unsigned short int fts_info; /* user flags for FTSENT structure */
+
+# define FTS_DONTCHDIR 0x01 /* don't chdir .. to the parent */
+# define FTS_SYMFOLLOW 0x02 /* followed a symlink to get here */
+ unsigned short int fts_flags; /* private flags for FTSENT structure */
+
+# define FTS_AGAIN 1 /* read node again */
+# define FTS_FOLLOW 2 /* follow symbolic link */
+# define FTS_NOINSTR 3 /* no instructions */
+# define FTS_SKIP 4 /* discard node */
+ unsigned short int fts_instr; /* fts_set() instructions */
+
+ struct stat fts_statp[1]; /* stat(2) information */
+ char fts_name[__FLEXIBLE_ARRAY_MEMBER]; /* file name */
} FTSENT;
+#ifndef __GNUC_PREREQ
+# if defined __GNUC__ && defined __GNUC_MINOR__
+# define __GNUC_PREREQ(maj, min) \
+ ((__GNUC__ << 16) + __GNUC_MINOR__ >= ((maj) << 16) + (min))
+# else
+# define __GNUC_PREREQ(maj, min) 0
+# endif
+#endif
+
+#if __GNUC_PREREQ (3,4)
+# undef __attribute_warn_unused_result__
+# define __attribute_warn_unused_result__ \
+ __attribute__ ((__warn_unused_result__))
+#else
+# define __attribute_warn_unused_result__ /* empty */
+#endif
+
__BEGIN_DECLS
-FTSENT *fts_children (FTS *, int) __THROW;
-int fts_close (FTS *) __THROW;
-FTS *fts_open (char * const *, int,
- int (*)(const FTSENT **, const FTSENT **)) __THROW;
-FTSENT *fts_read (FTS *) __THROW;
-int fts_set (FTS *, FTSENT *, int) __THROW;
+FTSENT *fts_children (FTS *, int) __THROW __attribute_warn_unused_result__;
+int fts_close (FTS *) __THROW __attribute_warn_unused_result__;
+FTS *fts_open (char * const *, int,
+ int (*)(const FTSENT **, const FTSENT **))
+ __THROW __attribute_warn_unused_result__;
+FTSENT *fts_read (FTS *) __THROW __attribute_warn_unused_result__;
+int fts_set (FTS *, FTSENT *, int) __THROW;
__END_DECLS
#endif /* fts.h */
diff --git a/lib/full-read.c b/lib/full-read.c
index 8c3472a..d49e16a 100644
--- a/lib/full-read.c
+++ b/lib/full-read.c
@@ -1,10 +1,10 @@
/* An interface to read that retries after partial reads and interrupts.
- Copyright (C) 2002, 2003 Free Software Foundation, Inc.
+ Copyright (C) 2002-2003, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -12,8 +12,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#define FULL_READ
#include "full-write.c"
diff --git a/lib/full-read.h b/lib/full-read.h
index 05d83a7..ebd887a 100644
--- a/lib/full-read.h
+++ b/lib/full-read.h
@@ -1,11 +1,11 @@
/* An interface to read() that reads all it is asked to read.
- Copyright (C) 2002 Free Software Foundation, Inc.
+ Copyright (C) 2002, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, read to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <stddef.h>
diff --git a/lib/full-write.c b/lib/full-write.c
index cc16872..08248ad 100644
--- a/lib/full-write.c
+++ b/lib/full-write.c
@@ -1,12 +1,11 @@
/* An interface to read and write that retries (if necessary) until complete.
- Copyright (C) 1993, 1994, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
- 2004, 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 1993-1994, 1997-2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
@@ -66,12 +64,12 @@ full_rw (int fd, const void *buf, size_t count)
{
size_t n_rw = safe_rw (fd, ptr, count);
if (n_rw == (size_t) -1)
- break;
+ break;
if (n_rw == 0)
- {
- errno = ZERO_BYTE_TRANSFER_ERRNO;
- break;
- }
+ {
+ errno = ZERO_BYTE_TRANSFER_ERRNO;
+ break;
+ }
total += n_rw;
ptr += n_rw;
count -= n_rw;
diff --git a/lib/full-write.h b/lib/full-write.h
index d20d2fe..586d0b5 100644
--- a/lib/full-write.h
+++ b/lib/full-write.h
@@ -1,11 +1,11 @@
/* An interface to write() that writes all it is asked to write.
- Copyright (C) 2002-2003 Free Software Foundation, Inc.
+ Copyright (C) 2002-2003, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <stddef.h>
diff --git a/lib/futimens.c b/lib/futimens.c
new file mode 100644
index 0000000..3b110fe
--- /dev/null
+++ b/lib/futimens.c
@@ -0,0 +1,37 @@
+/* Set the access and modification time of an open fd.
+ Copyright (C) 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* written by Eric Blake */
+
+#include <config.h>
+
+#include <sys/stat.h>
+
+#include "utimens.h"
+
+/* Set the access and modification time stamps of FD to be
+ TIMESPEC[0] and TIMESPEC[1], respectively.
+ Fail with ENOSYS on systems without futimes (or equivalent).
+ If TIMESPEC is null, set the time stamps to the current time.
+ Return 0 on success, -1 (setting errno) on failure. */
+int
+futimens (int fd, struct timespec const times[2])
+{
+ /* fdutimens also works around bugs in native futimens, when running
+ with glibc compiled against newer headers but on a Linux kernel
+ older than 2.6.32. */
+ return fdutimens (fd, NULL, times);
+}
diff --git a/lib/gai_strerror.c b/lib/gai_strerror.c
index aa733d6..a6cae08 100644
--- a/lib/gai_strerror.c
+++ b/lib/gai_strerror.c
@@ -1,10 +1,11 @@
-/* Copyright (C) 1997, 2001, 2002, 2004, 2005, 2006 Free Software Foundation, Inc.
+/* Copyright (C) 1997, 2001-2002, 2004-2006, 2008-2016 Free Software
+ Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Philip Blundell <pjb27@cam.ac.uk>, 1997.
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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -13,18 +14,14 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program; if not, see <http://www.gnu.org/licenses/>. */
#ifndef _LIBC
# include <config.h>
-# include "getaddrinfo.h"
#endif
#include <stdio.h>
-#ifdef HAVE_NETDB_H
-# include <netdb.h>
-#endif
+#include <netdb.h>
#ifdef _LIBC
# include <libintl.h>
@@ -34,6 +31,22 @@
# define N_(String) String
#endif
+#if HAVE_DECL_GAI_STRERROR
+
+# include <sys/socket.h>
+# undef gai_strerror
+# if HAVE_DECL_GAI_STRERRORA
+# define gai_strerror gai_strerrorA
+# endif
+
+const char *
+rpl_gai_strerror (int code)
+{
+ return gai_strerror (code);
+}
+
+#else /* !HAVE_DECL_GAI_STRERROR */
+
static struct
{
int code;
@@ -53,7 +66,7 @@ values[] =
{ EAI_SOCKTYPE, N_("ai_socktype not supported") },
{ EAI_SYSTEM, N_("System error") },
{ EAI_OVERFLOW, N_("Argument buffer too small") },
-#ifdef __USE_GNU
+#ifdef EAI_INPROGRESS
{ EAI_INPROGRESS, N_("Processing request in progress") },
{ EAI_CANCELED, N_("Request canceled") },
{ EAI_NOTCANCELED, N_("Request not canceled") },
@@ -73,6 +86,7 @@ gai_strerror (int code)
return _("Unknown error");
}
-#ifdef _LIBC
+# ifdef _LIBC
libc_hidden_def (gai_strerror)
-#endif
+# endif
+#endif /* !HAVE_DECL_GAI_STRERROR */
diff --git a/lib/get-permissions.c b/lib/get-permissions.c
new file mode 100644
index 0000000..8c70df1
--- /dev/null
+++ b/lib/get-permissions.c
@@ -0,0 +1,291 @@
+/* Get permissions of a file. -*- coding: utf-8 -*-
+
+ Copyright (C) 2002-2003, 2005-2016 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 <http://www.gnu.org/licenses/>.
+
+ Written by Paul Eggert, Andreas Grünbacher, and Bruno Haible. */
+
+#include <config.h>
+
+#include <string.h>
+#include "acl.h"
+
+#include "acl-internal.h"
+
+/* Read the permissions of a file into CTX. If DESC is a valid file descriptor,
+ use file descriptor operations, else use filename based operations on NAME.
+ MODE is the file mode obtained from a previous stat call.
+ Return 0 if successful. Return -1 and set errno upon failure. */
+
+int
+get_permissions (const char *name, int desc, mode_t mode,
+ struct permission_context *ctx)
+{
+ memset (ctx, 0, sizeof *ctx);
+ ctx->mode = mode;
+
+#if USE_ACL && HAVE_ACL_GET_FILE
+ /* POSIX 1003.1e (draft 17 -- abandoned) specific version. */
+ /* Linux, FreeBSD, Mac OS X, IRIX, Tru64 */
+# if !HAVE_ACL_TYPE_EXTENDED
+ /* Linux, FreeBSD, IRIX, Tru64 */
+
+ if (HAVE_ACL_GET_FD && desc != -1)
+ ctx->acl = acl_get_fd (desc);
+ else
+ ctx->acl = acl_get_file (name, ACL_TYPE_ACCESS);
+ if (ctx->acl == NULL)
+ return acl_errno_valid (errno) ? -1 : 0;
+
+ /* With POSIX ACLs, a file cannot have "no" acl; a file without
+ extended permissions has a "minimal" acl which is equivalent to the
+ file mode. */
+
+ if (S_ISDIR (mode))
+ {
+ ctx->default_acl = acl_get_file (name, ACL_TYPE_DEFAULT);
+ if (ctx->default_acl == NULL)
+ return -1;
+ }
+
+# if HAVE_ACL_TYPE_NFS4 /* FreeBSD */
+
+ /* TODO (see set_permissions). */
+
+# endif
+
+# else /* HAVE_ACL_TYPE_EXTENDED */
+ /* Mac OS X */
+
+ /* On Mac OS X, acl_get_file (name, ACL_TYPE_ACCESS)
+ and acl_get_file (name, ACL_TYPE_DEFAULT)
+ always return NULL / EINVAL. You have to use
+ acl_get_file (name, ACL_TYPE_EXTENDED)
+ or acl_get_fd (open (name, ...))
+ to retrieve an ACL.
+ On the other hand,
+ acl_set_file (name, ACL_TYPE_ACCESS, acl)
+ and acl_set_file (name, ACL_TYPE_DEFAULT, acl)
+ have the same effect as
+ acl_set_file (name, ACL_TYPE_EXTENDED, acl):
+ Each of these calls sets the file's ACL. */
+
+ if (HAVE_ACL_GET_FD && desc != -1)
+ ctx->acl = acl_get_fd (desc);
+ else
+ ctx->acl = acl_get_file (name, ACL_TYPE_EXTENDED);
+ if (ctx->acl == NULL)
+ return acl_errno_valid (errno) ? -1 : 0;
+
+# endif
+
+#elif USE_ACL && defined GETACL /* Solaris, Cygwin, not HP-UX */
+
+ /* Solaris 2.5 through Solaris 10, Cygwin, and contemporaneous versions
+ of Unixware. The acl() call returns the access and default ACL both
+ at once. */
+# ifdef ACE_GETACL
+ /* Solaris also has a different variant of ACLs, used in ZFS and NFSv4
+ file systems (whereas the other ones are used in UFS file systems).
+ There is an API
+ pathconf (name, _PC_ACL_ENABLED)
+ fpathconf (desc, _PC_ACL_ENABLED)
+ that allows to determine which of the two kinds of ACLs is supported
+ for the given file. But some file systems may implement this call
+ incorrectly, so better not use it.
+ When fetching the source ACL, we simply fetch both ACL types.
+ When setting the destination ACL, we try either ACL types, assuming
+ that the kernel will translate the ACL from one form to the other.
+ (See in <http://docs.sun.com/app/docs/doc/819-2241/6n4huc7ia?l=en&a=view>
+ the description of ENOTSUP.) */
+ for (;;)
+ {
+ int ret;
+
+ if (desc != -1)
+ ret = facl (desc, ACE_GETACLCNT, 0, NULL);
+ else
+ ret = acl (name, ACE_GETACLCNT, 0, NULL);
+ if (ret < 0)
+ {
+ if (errno == ENOSYS || errno == EINVAL)
+ ret = 0;
+ else
+ return -1;
+ }
+ ctx->ace_count = ret;
+
+ if (ctx->ace_count == 0)
+ break;
+
+ ctx->ace_entries = (ace_t *) malloc (ctx->ace_count * sizeof (ace_t));
+ if (ctx->ace_entries == NULL)
+ {
+ errno = ENOMEM;
+ return -1;
+ }
+
+ if (desc != -1)
+ ret = facl (desc, ACE_GETACL, ctx->ace_count, ctx->ace_entries);
+ else
+ ret = acl (name, ACE_GETACL, ctx->ace_count, ctx->ace_entries);
+ if (ret < 0)
+ {
+ if (errno == ENOSYS || errno == EINVAL)
+ {
+ free (ctx->ace_entries);
+ ctx->ace_entries = NULL;
+ ctx->ace_count = 0;
+ break;
+ }
+ else
+ return -1;
+ }
+ if (ret <= ctx->ace_count)
+ {
+ ctx->ace_count = ret;
+ break;
+ }
+ /* Huh? The number of ACL entries has increased since the last call.
+ Repeat. */
+ free (ctx->ace_entries);
+ ctx->ace_entries = NULL;
+ }
+# endif
+
+ for (;;)
+ {
+ int ret;
+
+ if (desc != -1)
+ ret = facl (desc, GETACLCNT, 0, NULL);
+ else
+ ret = acl (name, GETACLCNT, 0, NULL);
+ if (ret < 0)
+ {
+ if (errno == ENOSYS || errno == ENOTSUP || errno == EOPNOTSUPP)
+ ret = 0;
+ else
+ return -1;
+ }
+ ctx->count = ret;
+
+ if (ctx->count == 0)
+ break;
+
+ ctx->entries = (aclent_t *) malloc (ctx->count * sizeof (aclent_t));
+ if (ctx->entries == NULL)
+ {
+ errno = ENOMEM;
+ return -1;
+ }
+
+ if (desc != -1)
+ ret = facl (desc, GETACL, ctx->count, ctx->entries);
+ else
+ ret = acl (name, GETACL, ctx->count, ctx->entries);
+ if (ret < 0)
+ {
+ if (errno == ENOSYS || errno == ENOTSUP || errno == EOPNOTSUPP)
+ {
+ free (ctx->entries);
+ ctx->entries = NULL;
+ ctx->count = 0;
+ break;
+ }
+ else
+ return -1;
+ }
+ if (ret <= ctx->count)
+ {
+ ctx->count = ret;
+ break;
+ }
+ /* Huh? The number of ACL entries has increased since the last call.
+ Repeat. */
+ free (ctx->entries);
+ ctx->entries = NULL;
+ }
+
+#elif USE_ACL && HAVE_GETACL /* HP-UX */
+
+ {
+ int ret;
+
+ if (desc != -1)
+ ret = fgetacl (desc, NACLENTRIES, ctx->entries);
+ else
+ ret = getacl (name, NACLENTRIES, ctx->entries);
+ if (ret < 0)
+ {
+ if (errno == ENOSYS || errno == EOPNOTSUPP || errno == ENOTSUP)
+ ret = 0;
+ else
+ return -1;
+ }
+ else if (ret > NACLENTRIES)
+ /* If NACLENTRIES cannot be trusted, use dynamic memory allocation. */
+ abort ();
+ ctx->count = ret;
+
+# if HAVE_ACLV_H
+ ret = acl ((char *) name, ACL_GET, NACLVENTRIES, ctx->aclv_entries);
+ if (ret < 0)
+ {
+ if (errno == ENOSYS || errno == EOPNOTSUPP || errno == EINVAL)
+ ret = 0;
+ else
+ return -2;
+ }
+ else if (ret > NACLVENTRIES)
+ /* If NACLVENTRIES cannot be trusted, use dynamic memory allocation. */
+ abort ();
+ ctx->aclv_count = ret;
+# endif
+ }
+
+#elif USE_ACL && HAVE_ACLX_GET && ACL_AIX_WIP /* AIX */
+
+ /* TODO (see set_permissions). */
+
+#elif USE_ACL && HAVE_STATACL /* older AIX */
+
+ {
+ int ret;
+ if (desc != -1)
+ ret = fstatacl (desc, STX_NORMAL, &ctx->u.a, sizeof ctx->u);
+ else
+ ret = statacl ((char *) name, STX_NORMAL, &ctx->u.a, sizeof ctx->u);
+ if (ret == 0)
+ ctx->have_u = true;
+ }
+
+#elif USE_ACL && HAVE_ACLSORT /* NonStop Kernel */
+
+ {
+ int ret = acl ((char *) name, ACL_GET, NACLENTRIES, ctx->entries);
+ if (ret < 0)
+ return -1;
+ else if (ret > NACLENTRIES)
+ /* If NACLENTRIES cannot be trusted, use dynamic memory allocation. */
+ abort ();
+ ctx->count = ret;
+ }
+
+#endif
+
+ return 0;
+
+}
diff --git a/lib/getaddrinfo.c b/lib/getaddrinfo.c
index cc718bc..32d1f32 100644
--- a/lib/getaddrinfo.c
+++ b/lib/getaddrinfo.c
@@ -1,11 +1,10 @@
/* Get address information (partial implementation).
- Copyright (C) 1997, 2001, 2002, 2004, 2005, 2006, 2007 Free Software
- Foundation, Inc.
+ Copyright (C) 1997, 2001-2002, 2004-2016 Free Software Foundation, Inc.
Contributed by Simon Josefsson <simon@josefsson.org>.
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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -14,17 +13,23 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program; if not, see <http://www.gnu.org/licenses/>. */
+
+/* Don't use __attribute__ __nonnull__ in this compilation unit. Otherwise gcc
+ optimizes away the sa == NULL test below. */
+#define _GL_ARG_NONNULL(params)
#include <config.h>
-#include "getaddrinfo.h"
+#include <netdb.h>
#if HAVE_NETINET_IN_H
# include <netinet/in.h>
#endif
+/* Get inet_ntop. */
+#include <arpa/inet.h>
+
/* Get calloc. */
#include <stdlib.h>
@@ -40,8 +45,6 @@
#define _(String) gettext (String)
#define N_(String) String
-#include "inet_ntop.h"
-
/* BeOS has AF_INET, but not PF_INET. */
#ifndef PF_INET
# define PF_INET AF_INET
@@ -52,17 +55,20 @@
#endif
#if defined _WIN32 || defined __WIN32__
-# define WIN32_NATIVE
+# define WINDOWS_NATIVE
#endif
-#ifdef WIN32_NATIVE
+/* gl_sockets_startup */
+#include "sockets.h"
+
+#ifdef WINDOWS_NATIVE
typedef int (WSAAPI *getaddrinfo_func) (const char*, const char*,
- const struct addrinfo*,
- struct addrinfo**);
+ const struct addrinfo*,
+ struct addrinfo**);
typedef void (WSAAPI *freeaddrinfo_func) (struct addrinfo*);
typedef int (WSAAPI *getnameinfo_func) (const struct sockaddr*,
- socklen_t, char*, DWORD,
- char*, DWORD, int);
+ socklen_t, char*, DWORD,
+ char*, DWORD, int);
static getaddrinfo_func getaddrinfo_ptr = NULL;
static freeaddrinfo_func freeaddrinfo_ptr = NULL;
@@ -97,11 +103,13 @@ use_win32_p (void)
return 0;
}
+ gl_sockets_startup (SOCKETS_1_1);
+
return 1;
}
#endif
-static inline bool
+static bool
validate_family (int family)
{
/* FIXME: Support more families. */
@@ -122,9 +130,9 @@ validate_family (int family)
socket addresses. */
int
getaddrinfo (const char *restrict nodename,
- const char *restrict servname,
- const struct addrinfo *restrict hints,
- struct addrinfo **restrict res)
+ const char *restrict servname,
+ const struct addrinfo *restrict hints,
+ struct addrinfo **restrict res)
{
struct addrinfo *tmp;
int port = 0;
@@ -144,7 +152,7 @@ getaddrinfo (const char *restrict nodename,
};
#endif
-#ifdef WIN32_NATIVE
+#ifdef WINDOWS_NATIVE
if (use_win32_p ())
return getaddrinfo_ptr (nodename, servname, hints, res);
#endif
@@ -164,7 +172,7 @@ getaddrinfo (const char *restrict nodename,
if (!nodename)
{
if (!(hints->ai_flags & AI_PASSIVE))
- return EAI_NONAME;
+ return EAI_NONAME;
#ifdef HAVE_IPV6
nodename = (hints->ai_family == AF_INET6) ? "::" : "0.0.0.0";
@@ -177,24 +185,24 @@ getaddrinfo (const char *restrict nodename,
{
struct servent *se = NULL;
const char *proto =
- (hints && hints->ai_socktype == SOCK_DGRAM) ? "udp" : "tcp";
+ (hints && hints->ai_socktype == SOCK_DGRAM) ? "udp" : "tcp";
- if (!(hints->ai_flags & AI_NUMERICSERV))
- /* FIXME: Use getservbyname_r if available. */
- se = getservbyname (servname, proto);
+ if (hints == NULL || !(hints->ai_flags & AI_NUMERICSERV))
+ /* FIXME: Use getservbyname_r if available. */
+ se = getservbyname (servname, proto);
if (!se)
- {
- char *c;
- if (!(*servname >= '0' && *servname <= '9'))
- return EAI_NONAME;
- port = strtoul (servname, &c, 10);
- if (*c || port > 0xffff)
- return EAI_NONAME;
- port = htons (port);
- }
+ {
+ char *c;
+ if (!(*servname >= '0' && *servname <= '9'))
+ return EAI_NONAME;
+ port = strtoul (servname, &c, 10);
+ if (*c || port > 0xffff)
+ return EAI_NONAME;
+ port = htons (port);
+ }
else
- port = se->s_port;
+ port = se->s_port;
}
/* FIXME: Use gethostbyname_r if available. */
@@ -229,23 +237,23 @@ getaddrinfo (const char *restrict nodename,
#if HAVE_IPV6
case PF_INET6:
{
- struct v6_pair *p = storage;
- struct sockaddr_in6 *sinp = &p->sockaddr_in6;
- tmp = &p->addrinfo;
+ struct v6_pair *p = storage;
+ struct sockaddr_in6 *sinp = &p->sockaddr_in6;
+ tmp = &p->addrinfo;
- if (port)
- sinp->sin6_port = port;
+ if (port)
+ sinp->sin6_port = port;
- if (he->h_length != sizeof (sinp->sin6_addr))
- {
- free (storage);
- return EAI_SYSTEM; /* FIXME: Better return code? Set errno? */
- }
+ if (he->h_length != sizeof (sinp->sin6_addr))
+ {
+ free (storage);
+ return EAI_SYSTEM; /* FIXME: Better return code? Set errno? */
+ }
- memcpy (&sinp->sin6_addr, he->h_addr_list[0], sizeof sinp->sin6_addr);
+ memcpy (&sinp->sin6_addr, he->h_addr_list[0], sizeof sinp->sin6_addr);
- tmp->ai_addr = (struct sockaddr *) sinp;
- tmp->ai_addrlen = sizeof *sinp;
+ tmp->ai_addr = (struct sockaddr *) sinp;
+ tmp->ai_addrlen = sizeof *sinp;
}
break;
#endif
@@ -253,23 +261,23 @@ getaddrinfo (const char *restrict nodename,
#if HAVE_IPV4
case PF_INET:
{
- struct v4_pair *p = storage;
- struct sockaddr_in *sinp = &p->sockaddr_in;
- tmp = &p->addrinfo;
+ struct v4_pair *p = storage;
+ struct sockaddr_in *sinp = &p->sockaddr_in;
+ tmp = &p->addrinfo;
- if (port)
- sinp->sin_port = port;
+ if (port)
+ sinp->sin_port = port;
- if (he->h_length != sizeof (sinp->sin_addr))
- {
- free (storage);
- return EAI_SYSTEM; /* FIXME: Better return code? Set errno? */
- }
+ if (he->h_length != sizeof (sinp->sin_addr))
+ {
+ free (storage);
+ return EAI_SYSTEM; /* FIXME: Better return code? Set errno? */
+ }
- memcpy (&sinp->sin_addr, he->h_addr_list[0], sizeof sinp->sin_addr);
+ memcpy (&sinp->sin_addr, he->h_addr_list[0], sizeof sinp->sin_addr);
- tmp->ai_addr = (struct sockaddr *) sinp;
- tmp->ai_addrlen = sizeof *sinp;
+ tmp->ai_addr = (struct sockaddr *) sinp;
+ tmp->ai_addrlen = sizeof *sinp;
}
break;
#endif
@@ -283,16 +291,16 @@ getaddrinfo (const char *restrict nodename,
{
const char *cn;
if (he->h_name)
- cn = he->h_name;
+ cn = he->h_name;
else
- cn = nodename;
+ cn = nodename;
tmp->ai_canonname = strdup (cn);
if (!tmp->ai_canonname)
- {
- free (storage);
- return EAI_MEMORY;
- }
+ {
+ free (storage);
+ return EAI_MEMORY;
+ }
}
tmp->ai_protocol = (hints) ? hints->ai_protocol : 0;
@@ -300,6 +308,22 @@ getaddrinfo (const char *restrict nodename,
tmp->ai_addr->sa_family = he->h_addrtype;
tmp->ai_family = he->h_addrtype;
+#ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
+ switch (he->h_addrtype)
+ {
+#if HAVE_IPV4
+ case AF_INET:
+ tmp->ai_addr->sa_len = sizeof (struct sockaddr_in);
+ break;
+#endif
+#if HAVE_IPV6
+ case AF_INET6:
+ tmp->ai_addr->sa_len = sizeof (struct sockaddr_in6);
+ break;
+#endif
+ }
+#endif
+
/* FIXME: If more than one address, create linked list of addrinfo's. */
*res = tmp;
@@ -307,11 +331,11 @@ getaddrinfo (const char *restrict nodename,
return 0;
}
-/* Free `addrinfo' structure AI including associated storage. */
+/* Free 'addrinfo' structure AI including associated storage. */
void
freeaddrinfo (struct addrinfo *ai)
{
-#ifdef WIN32_NATIVE
+#ifdef WINDOWS_NATIVE
if (use_win32_p ())
{
freeaddrinfo_ptr (ai);
@@ -326,20 +350,21 @@ freeaddrinfo (struct addrinfo *ai)
cur = ai;
ai = ai->ai_next;
- if (cur->ai_canonname) free (cur->ai_canonname);
+ free (cur->ai_canonname);
free (cur);
}
}
-int getnameinfo(const struct sockaddr *restrict sa, socklen_t salen,
- char *restrict node, socklen_t nodelen,
- char *restrict service, socklen_t servicelen,
- int flags)
+int
+getnameinfo (const struct sockaddr *restrict sa, socklen_t salen,
+ char *restrict node, socklen_t nodelen,
+ char *restrict service, socklen_t servicelen,
+ int flags)
{
-#ifdef WIN32_NATIVE
+#ifdef WINDOWS_NATIVE
if (use_win32_p ())
return getnameinfo_ptr (sa, salen, node, nodelen,
- service, servicelen, flags);
+ service, servicelen, flags);
#endif
/* FIXME: Support other flags. */
@@ -356,13 +381,13 @@ int getnameinfo(const struct sockaddr *restrict sa, socklen_t salen,
#if HAVE_IPV4
case AF_INET:
if (salen < sizeof (struct sockaddr_in))
- return EAI_FAMILY;
+ return EAI_FAMILY;
break;
#endif
#if HAVE_IPV6
case AF_INET6:
if (salen < sizeof (struct sockaddr_in6))
- return EAI_FAMILY;
+ return EAI_FAMILY;
break;
#endif
default:
@@ -372,28 +397,28 @@ int getnameinfo(const struct sockaddr *restrict sa, socklen_t salen,
if (node && nodelen > 0 && flags & NI_NUMERICHOST)
{
switch (sa->sa_family)
- {
+ {
#if HAVE_IPV4
- case AF_INET:
- if (!inet_ntop (AF_INET,
- &(((const struct sockaddr_in *) sa)->sin_addr),
- node, nodelen))
- return EAI_SYSTEM;
- break;
+ case AF_INET:
+ if (!inet_ntop (AF_INET,
+ &(((const struct sockaddr_in *) sa)->sin_addr),
+ node, nodelen))
+ return EAI_SYSTEM;
+ break;
#endif
#if HAVE_IPV6
- case AF_INET6:
- if (!inet_ntop (AF_INET6,
- &(((const struct sockaddr_in6 *) sa)->sin6_addr),
- node, nodelen))
- return EAI_SYSTEM;
- break;
+ case AF_INET6:
+ if (!inet_ntop (AF_INET6,
+ &(((const struct sockaddr_in6 *) sa)->sin6_addr),
+ node, nodelen))
+ return EAI_SYSTEM;
+ break;
#endif
- default:
- return EAI_FAMILY;
- }
+ default:
+ return EAI_FAMILY;
+ }
}
if (service && servicelen > 0 && flags & NI_NUMERICSERV)
@@ -405,13 +430,13 @@ int getnameinfo(const struct sockaddr *restrict sa, socklen_t salen,
#if HAVE_IPV6
case AF_INET6:
#endif
- {
- unsigned short int port
- = ntohs (((const struct sockaddr_in *) sa)->sin_port);
- if (servicelen <= snprintf (service, servicelen, "%u", port))
- return EAI_OVERFLOW;
- }
- break;
+ {
+ unsigned short int port
+ = ntohs (((const struct sockaddr_in *) sa)->sin_port);
+ if (servicelen <= snprintf (service, servicelen, "%u", port))
+ return EAI_OVERFLOW;
+ }
+ break;
}
return 0;
diff --git a/lib/getaddrinfo.h b/lib/getaddrinfo.h
deleted file mode 100644
index b4ef242..0000000
--- a/lib/getaddrinfo.h
+++ /dev/null
@@ -1,155 +0,0 @@
-/* Get address information.
- Copyright (C) 1996-2002, 2003, 2004, 2005, 2006
- Free Software Foundation, Inc.
- Contributed by Simon Josefsson <simon@josefsson.org>.
-
- 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-#ifndef GETADDRINFO_H
-#define GETADDRINFO_H
-
-/* sys/socket.h in i386-unknown-freebsd4.10 and
- powerpc-apple-darwin5.5 require sys/types.h, so include it first.
- Then we'll also get 'socklen_t' and 'struct sockaddr' which are
- used below. */
-#include <sys/types.h>
-/* Get all getaddrinfo related declarations, if available. */
-#include <sys/socket.h>
-#ifdef HAVE_NETDB_H
-# include <netdb.h>
-#endif
-
-#ifndef HAVE_STRUCT_ADDRINFO
-
-/* Structure to contain information about address of a service provider. */
-struct addrinfo
-{
- int ai_flags; /* Input flags. */
- int ai_family; /* Protocol family for socket. */
- int ai_socktype; /* Socket type. */
- int ai_protocol; /* Protocol for socket. */
- socklen_t ai_addrlen; /* Length of socket address. */
- struct sockaddr *ai_addr; /* Socket address for socket. */
- char *ai_canonname; /* Canonical name for service location. */
- struct addrinfo *ai_next; /* Pointer to next in list. */
-};
-#endif
-
-/* Possible values for `ai_flags' field in `addrinfo' structure. */
-#ifndef AI_PASSIVE
-# define AI_PASSIVE 0x0001 /* Socket address is intended for `bind'. */
-#endif
-#ifndef AI_CANONNAME
-# define AI_CANONNAME 0x0002 /* Request for canonical name. */
-#endif
-#ifndef AI_NUMERICSERV
-# define AI_NUMERICSERV 0x0400 /* Don't use name resolution. */
-#endif
-
-#if 0
-/* The commented out definitions below are not yet implemented in the
- GNULIB getaddrinfo() replacement, so are not yet needed and may, in fact,
- cause conflicts on systems with a getaddrinfo() function which does not
- define them.
-
- If they are restored, be sure to protect the definitions with #ifndef. */
-#define AI_NUMERICHOST 0x0004 /* Don't use name resolution. */
-#define AI_V4MAPPED 0x0008 /* IPv4 mapped addresses are acceptable. */
-#define AI_ALL 0x0010 /* Return IPv4 mapped and IPv6 addresses. */
-#define AI_ADDRCONFIG 0x0020 /* Use configuration of this host to choose
- returned address type.. */
-#endif /* 0 */
-
-/* Error values for `getaddrinfo' function. */
-#ifndef EAI_BADFLAGS
-# define EAI_BADFLAGS -1 /* Invalid value for `ai_flags' field. */
-# define EAI_NONAME -2 /* NAME or SERVICE is unknown. */
-# define EAI_AGAIN -3 /* Temporary failure in name resolution. */
-# define EAI_FAIL -4 /* Non-recoverable failure in name res. */
-# define EAI_NODATA -5 /* No address associated with NAME. */
-# define EAI_FAMILY -6 /* `ai_family' not supported. */
-# define EAI_SOCKTYPE -7 /* `ai_socktype' not supported. */
-# define EAI_SERVICE -8 /* SERVICE not supported for `ai_socktype'. */
-# define EAI_MEMORY -10 /* Memory allocation failure. */
-#endif
-#ifndef EAI_OVERFLOW
-/* Not defined on mingw32. */
-# define EAI_OVERFLOW -12 /* Argument buffer overflow. */
-#endif
-#ifndef EAI_ADDRFAMILY
-/* Not defined on mingw32. */
-# define EAI_ADDRFAMILY -9 /* Address family for NAME not supported. */
-#endif
-#ifndef EAI_SYSTEM
-/* Not defined on mingw32. */
-# define EAI_SYSTEM -11 /* System error returned in `errno'. */
-#endif
-
-#ifdef __USE_GNU
-# ifndef EAI_INPROGRESS
-# define EAI_INPROGRESS -100 /* Processing request in progress. */
-# define EAI_CANCELED -101 /* Request canceled. */
-# define EAI_NOTCANCELED -102 /* Request not canceled. */
-# define EAI_ALLDONE -103 /* All requests done. */
-# define EAI_INTR -104 /* Interrupted by a signal. */
-# define EAI_IDN_ENCODE -105 /* IDN encoding failed. */
-# endif
-#endif
-
-#if !HAVE_DECL_GETADDRINFO
-/* Translate name of a service location and/or a service name to set of
- socket addresses.
- For more details, see the POSIX:2001 specification
- <http://www.opengroup.org/susv3xsh/getaddrinfo.html>. */
-extern int getaddrinfo (const char *restrict nodename,
- const char *restrict servname,
- const struct addrinfo *restrict hints,
- struct addrinfo **restrict res);
-#endif
-
-#if !HAVE_DECL_FREEADDRINFO
-/* Free `addrinfo' structure AI including associated storage.
- For more details, see the POSIX:2001 specification
- <http://www.opengroup.org/susv3xsh/getaddrinfo.html>. */
-extern void freeaddrinfo (struct addrinfo *ai);
-#endif
-
-#if !HAVE_DECL_GAI_STRERROR
-/* Convert error return from getaddrinfo() to a string.
- For more details, see the POSIX:2001 specification
- <http://www.opengroup.org/susv3xsh/gai_strerror.html>. */
-extern const char *gai_strerror (int ecode);
-#endif
-
-#if !HAVE_DECL_GETNAMEINFO
-/* Convert socket address to printable node and service names.
- For more details, see the POSIX:2001 specification
- <http://www.opengroup.org/susv3xsh/getnameinfo.html>. */
-extern int getnameinfo(const struct sockaddr *restrict sa, socklen_t salen,
- char *restrict node, socklen_t nodelen,
- char *restrict service, socklen_t servicelen,
- int flags);
-
-#endif
-
-/* Possible flags for getnameinfo. */
-#ifndef NI_NUMERICHOST
-# define NI_NUMERICHOST 1
-#endif
-#ifndef NI_NUMERICSERV
-# define NI_NUMERICSERV 2
-#endif
-
-#endif /* GETADDRINFO_H */
diff --git a/lib/getcwd-lgpl.c b/lib/getcwd-lgpl.c
new file mode 100644
index 0000000..c553f7b
--- /dev/null
+++ b/lib/getcwd-lgpl.c
@@ -0,0 +1,126 @@
+/* Copyright (C) 2011-2016 Free Software Foundation, Inc.
+ This file is part of gnulib.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification */
+#include <unistd.h>
+
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+
+#if GNULIB_GETCWD
+/* Favor GPL getcwd.c if both getcwd and getcwd-lgpl modules are in use. */
+typedef int dummy;
+#else
+
+/* Get the name of the current working directory, and put it in SIZE
+ bytes of BUF. Returns NULL if the directory couldn't be determined
+ (perhaps because the absolute name was longer than PATH_MAX, or
+ because of missing read/search permissions on parent directories)
+ or SIZE was too small. If successful, returns BUF. If BUF is
+ NULL, an array is allocated with 'malloc'; the array is SIZE bytes
+ long, unless SIZE == 0, in which case it is as big as
+ necessary. */
+
+# undef getcwd
+char *
+rpl_getcwd (char *buf, size_t size)
+{
+ char *ptr;
+ char *result;
+
+ /* Handle single size operations. */
+ if (buf)
+ {
+ if (!size)
+ {
+ errno = EINVAL;
+ return NULL;
+ }
+ return getcwd (buf, size);
+ }
+
+ if (size)
+ {
+ buf = malloc (size);
+ if (!buf)
+ {
+ errno = ENOMEM;
+ return NULL;
+ }
+ result = getcwd (buf, size);
+ if (!result)
+ {
+ int saved_errno = errno;
+ free (buf);
+ errno = saved_errno;
+ }
+ return result;
+ }
+
+ /* Flexible sizing requested. Avoid over-allocation for the common
+ case of a name that fits within a 4k page, minus some space for
+ local variables, to be sure we don't skip over a guard page. */
+ {
+ char tmp[4032];
+ size = sizeof tmp;
+ ptr = getcwd (tmp, size);
+ if (ptr)
+ {
+ result = strdup (ptr);
+ if (!result)
+ errno = ENOMEM;
+ return result;
+ }
+ if (errno != ERANGE)
+ return NULL;
+ }
+
+ /* My what a large directory name we have. */
+ do
+ {
+ size <<= 1;
+ ptr = realloc (buf, size);
+ if (ptr == NULL)
+ {
+ free (buf);
+ errno = ENOMEM;
+ return NULL;
+ }
+ buf = ptr;
+ result = getcwd (buf, size);
+ }
+ while (!result && errno == ERANGE);
+
+ if (!result)
+ {
+ int saved_errno = errno;
+ free (buf);
+ errno = saved_errno;
+ }
+ else
+ {
+ /* Trim to fit, if possible. */
+ result = realloc (buf, strlen (buf) + 1);
+ if (!result)
+ result = buf;
+ }
+ return result;
+}
+
+#endif
diff --git a/lib/getcwd.c b/lib/getcwd.c
index 23b35de..e1265fd 100644
--- a/lib/getcwd.c
+++ b/lib/getcwd.c
@@ -1,25 +1,22 @@
-/* Copyright (C) 1991,92,93,94,95,96,97,98,99,2004,2005,2006,2007 Free Software
- Foundation, Inc.
+/* Copyright (C) 1991-1999, 2004-2016 Free Software Foundation, Inc.
This file is part of the GNU C Library.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#if !_LIBC
# include <config.h>
# include <unistd.h>
-# include "dirfd.h"
#endif
#include <errno.h>
@@ -30,6 +27,15 @@
#include <fcntl.h> /* For AT_FDCWD on Solaris 9. */
+/* If this host provides the openat function or if we're using the
+ gnulib replacement function with a native fdopendir, then enable
+ code below to make getcwd more efficient and robust. */
+#if defined HAVE_OPENAT || (defined GNULIB_OPENAT && defined HAVE_FDOPENDIR)
+# define HAVE_OPENAT_SUPPORT 1
+#else
+# define HAVE_OPENAT_SUPPORT 0
+#endif
+
#ifndef __set_errno
# define __set_errno(val) (errno = (val))
#endif
@@ -52,22 +58,6 @@
# endif
#endif
-#include <limits.h>
-
-/* Work around a bug in Solaris 9 and 10: AT_FDCWD is positive. Its
- value exceeds INT_MAX, so its use as an int doesn't conform to the
- C standard, and GCC and Sun C complain in some cases. */
-#if 0 < AT_FDCWD && AT_FDCWD == 0xffd19553
-# undef AT_FDCWD
-# define AT_FDCWD (-3041965)
-#endif
-
-#ifdef ENAMETOOLONG
-# define is_ENAMETOOLONG(x) ((x) == ENAMETOOLONG)
-#else
-# define is_ENAMETOOLONG(x) 0
-#endif
-
#ifndef MAX
# define MAX(a, b) ((a) < (b) ? (b) : (a))
#endif
@@ -75,12 +65,12 @@
# define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif
+#include "pathmax.h"
+
+/* In this file, PATH_MAX only serves as a threshold for choosing among two
+ algorithms. */
#ifndef PATH_MAX
-# ifdef MAXPATHLEN
-# define PATH_MAX MAXPATHLEN
-# else
-# define PATH_MAX 1024
-# endif
+# define PATH_MAX 8192
#endif
#if D_INO_IN_DIRENT
@@ -90,7 +80,7 @@
#endif
#if !_LIBC
-# define __getcwd getcwd
+# define __getcwd rpl_getcwd
# define __lstat lstat
# define __closedir closedir
# define __opendir opendir
@@ -98,14 +88,22 @@
#endif
/* The results of opendir() in this file are not used with dirfd and fchdir,
- therefore save some unnecessary recursion in fchdir.c. */
-#undef opendir
-#undef closedir
+ and we do not leak fds to any single-threaded code that could use stdio,
+ therefore save some unnecessary recursion in fchdir.c.
+ FIXME - if the kernel ever adds support for multi-thread safety for
+ avoiding standard fds, then we should use opendir_safer and
+ openat_safer. */
+#ifdef GNULIB_defined_opendir
+# undef opendir
+#endif
+#ifdef GNULIB_defined_closedir
+# undef closedir
+#endif
/* Get the name of the current working directory, and put it in SIZE
bytes of BUF. Returns NULL if the directory couldn't be determined or
SIZE was too small. If successful, returns BUF. In GNU, if BUF is
- NULL, an array is allocated with `malloc'; the array is SIZE bytes long,
+ NULL, an array is allocated with 'malloc'; the array is SIZE bytes long,
unless SIZE == 0, in which case it is as big as necessary. */
char *
@@ -123,7 +121,7 @@ __getcwd (char *buf, size_t size)
DEEP_NESTING = 100
};
-#ifdef AT_FDCWD
+#if HAVE_OPENAT_SUPPORT
int fd = AT_FDCWD;
bool fd_needs_closing = false;
#else
@@ -141,31 +139,53 @@ __getcwd (char *buf, size_t size)
size_t allocated = size;
size_t used;
-#if HAVE_PARTLY_WORKING_GETCWD
- /* The system getcwd works, except it sometimes fails when it
- shouldn't, setting errno to ERANGE, ENAMETOOLONG, or ENOENT. If
- AT_FDCWD is not defined, the algorithm below is O(N**2) and this
- is much slower than the system getcwd (at least on GNU/Linux).
- So trust the system getcwd's results unless they look
- suspicious.
+#if HAVE_MINIMALLY_WORKING_GETCWD
+ /* If AT_FDCWD is not defined, the algorithm below is O(N**2) and
+ this is much slower than the system getcwd (at least on
+ GNU/Linux). So trust the system getcwd's results unless they
+ look suspicious.
Use the system getcwd even if we have openat support, since the
system getcwd works even when a parent is unreadable, while the
- openat-based approach does not. */
+ openat-based approach does not.
+
+ But on AIX 5.1..7.1, the system getcwd is not even minimally
+ working: If the current directory name is slightly longer than
+ PATH_MAX, it omits the first directory component and returns
+ this wrong result with errno = 0. */
# undef getcwd
dir = getcwd (buf, size);
- if (dir || (errno != ERANGE && !is_ENAMETOOLONG (errno) && errno != ENOENT))
+ if (dir || (size && errno == ERANGE))
return dir;
+
+ /* Solaris getcwd (NULL, 0) fails with errno == EINVAL, but it has
+ internal magic that lets it work even if an ancestor directory is
+ inaccessible, which is better in many cases. So in this case try
+ again with a buffer that's almost always big enough. */
+ if (errno == EINVAL && buf == NULL && size == 0)
+ {
+ char big_buffer[BIG_FILE_NAME_LENGTH + 1];
+ dir = getcwd (big_buffer, sizeof big_buffer);
+ if (dir)
+ return strdup (dir);
+ }
+
+# if HAVE_PARTLY_WORKING_GETCWD
+ /* The system getcwd works, except it sometimes fails when it
+ shouldn't, setting errno to ERANGE, ENAMETOOLONG, or ENOENT. */
+ if (errno != ERANGE && errno != ENAMETOOLONG && errno != ENOENT)
+ return NULL;
+# endif
#endif
if (size == 0)
{
if (buf != NULL)
- {
- __set_errno (EINVAL);
- return NULL;
- }
+ {
+ __set_errno (EINVAL);
+ return NULL;
+ }
allocated = BIG_FILE_NAME_LENGTH + 1;
}
@@ -174,7 +194,7 @@ __getcwd (char *buf, size_t size)
{
dir = malloc (allocated);
if (dir == NULL)
- return NULL;
+ return NULL;
}
else
dir = buf;
@@ -204,10 +224,10 @@ __getcwd (char *buf, size_t size)
bool use_d_ino = true;
/* Look at the parent directory. */
-#ifdef AT_FDCWD
+#if HAVE_OPENAT_SUPPORT
fd = openat (fd, "..", O_RDONLY);
if (fd < 0)
- goto lose;
+ goto lose;
fd_needs_closing = true;
parent_status = fstat (fd, &st);
#else
@@ -217,13 +237,13 @@ __getcwd (char *buf, size_t size)
parent_status = __lstat (dotlist, &st);
#endif
if (parent_status != 0)
- goto lose;
+ goto lose;
if (dirstream && __closedir (dirstream) != 0)
- {
- dirstream = NULL;
- goto lose;
- }
+ {
+ dirstream = NULL;
+ goto lose;
+ }
/* Figure out if this directory is a mount point. */
dotdev = st.st_dev;
@@ -231,141 +251,139 @@ __getcwd (char *buf, size_t size)
mount_point = dotdev != thisdev;
/* Search for the last directory. */
-#ifdef AT_FDCWD
+#if HAVE_OPENAT_SUPPORT
dirstream = fdopendir (fd);
if (dirstream == NULL)
- goto lose;
- /* Reset fd. It may have been closed by fdopendir. */
- fd = dirfd (dirstream);
+ goto lose;
fd_needs_closing = false;
#else
dirstream = __opendir (dotlist);
if (dirstream == NULL)
- goto lose;
+ goto lose;
dotlist[dotlen++] = '/';
#endif
for (;;)
- {
- /* Clear errno to distinguish EOF from error if readdir returns
- NULL. */
- __set_errno (0);
- d = __readdir (dirstream);
-
- /* When we've iterated through all directory entries without finding
- one with a matching d_ino, rewind the stream and consider each
- name again, but this time, using lstat. This is necessary in a
- chroot on at least one system (glibc-2.3.6 + linux 2.6.12), where
- .., ../.., ../../.., etc. all had the same device number, yet the
- d_ino values for entries in / did not match those obtained
- via lstat. */
- if (d == NULL && errno == 0 && use_d_ino)
- {
- use_d_ino = false;
- rewinddir (dirstream);
- d = __readdir (dirstream);
- }
-
- if (d == NULL)
- {
- if (errno == 0)
- /* EOF on dirstream, which can mean e.g., that the current
- directory has been removed. */
- __set_errno (ENOENT);
- goto lose;
- }
- if (d->d_name[0] == '.' &&
- (d->d_name[1] == '\0' ||
- (d->d_name[1] == '.' && d->d_name[2] == '\0')))
- continue;
-
- if (use_d_ino)
- {
- bool match = (MATCHING_INO (d, thisino) || mount_point);
- if (! match)
- continue;
- }
-
- {
- int entry_status;
-#ifdef AT_FDCWD
- entry_status = fstatat (fd, d->d_name, &st, AT_SYMLINK_NOFOLLOW);
+ {
+ /* Clear errno to distinguish EOF from error if readdir returns
+ NULL. */
+ __set_errno (0);
+ d = __readdir (dirstream);
+
+ /* When we've iterated through all directory entries without finding
+ one with a matching d_ino, rewind the stream and consider each
+ name again, but this time, using lstat. This is necessary in a
+ chroot on at least one system (glibc-2.3.6 + linux 2.6.12), where
+ .., ../.., ../../.., etc. all had the same device number, yet the
+ d_ino values for entries in / did not match those obtained
+ via lstat. */
+ if (d == NULL && errno == 0 && use_d_ino)
+ {
+ use_d_ino = false;
+ rewinddir (dirstream);
+ d = __readdir (dirstream);
+ }
+
+ if (d == NULL)
+ {
+ if (errno == 0)
+ /* EOF on dirstream, which can mean e.g., that the current
+ directory has been removed. */
+ __set_errno (ENOENT);
+ goto lose;
+ }
+ if (d->d_name[0] == '.' &&
+ (d->d_name[1] == '\0' ||
+ (d->d_name[1] == '.' && d->d_name[2] == '\0')))
+ continue;
+
+ if (use_d_ino)
+ {
+ bool match = (MATCHING_INO (d, thisino) || mount_point);
+ if (! match)
+ continue;
+ }
+
+ {
+ int entry_status;
+#if HAVE_OPENAT_SUPPORT
+ entry_status = fstatat (fd, d->d_name, &st, AT_SYMLINK_NOFOLLOW);
#else
- /* Compute size needed for this file name, or for the file
- name ".." in the same directory, whichever is larger.
- Room for ".." might be needed the next time through
- the outer loop. */
- size_t name_alloc = _D_ALLOC_NAMLEN (d);
- size_t filesize = dotlen + MAX (sizeof "..", name_alloc);
-
- if (filesize < dotlen)
- goto memory_exhausted;
-
- if (dotsize < filesize)
- {
- /* My, what a deep directory tree you have, Grandma. */
- size_t newsize = MAX (filesize, dotsize * 2);
- size_t i;
- if (newsize < dotsize)
- goto memory_exhausted;
- if (dotlist != dots)
- free (dotlist);
- dotlist = malloc (newsize);
- if (dotlist == NULL)
- goto lose;
- dotsize = newsize;
-
- i = 0;
- do
- {
- dotlist[i++] = '.';
- dotlist[i++] = '.';
- dotlist[i++] = '/';
- }
- while (i < dotlen);
- }
-
- memcpy (dotlist + dotlen, d->d_name, _D_ALLOC_NAMLEN (d));
- entry_status = __lstat (dotlist, &st);
+ /* Compute size needed for this file name, or for the file
+ name ".." in the same directory, whichever is larger.
+ Room for ".." might be needed the next time through
+ the outer loop. */
+ size_t name_alloc = _D_ALLOC_NAMLEN (d);
+ size_t filesize = dotlen + MAX (sizeof "..", name_alloc);
+
+ if (filesize < dotlen)
+ goto memory_exhausted;
+
+ if (dotsize < filesize)
+ {
+ /* My, what a deep directory tree you have, Grandma. */
+ size_t newsize = MAX (filesize, dotsize * 2);
+ size_t i;
+ if (newsize < dotsize)
+ goto memory_exhausted;
+ if (dotlist != dots)
+ free (dotlist);
+ dotlist = malloc (newsize);
+ if (dotlist == NULL)
+ goto lose;
+ dotsize = newsize;
+
+ i = 0;
+ do
+ {
+ dotlist[i++] = '.';
+ dotlist[i++] = '.';
+ dotlist[i++] = '/';
+ }
+ while (i < dotlen);
+ }
+
+ memcpy (dotlist + dotlen, d->d_name, _D_ALLOC_NAMLEN (d));
+ entry_status = __lstat (dotlist, &st);
#endif
- /* We don't fail here if we cannot stat() a directory entry.
- This can happen when (network) file systems fail. If this
- entry is in fact the one we are looking for we will find
- out soon as we reach the end of the directory without
- having found anything. */
- if (entry_status == 0 && S_ISDIR (st.st_mode)
- && st.st_dev == thisdev && st.st_ino == thisino)
- break;
- }
- }
+ /* We don't fail here if we cannot stat() a directory entry.
+ This can happen when (network) file systems fail. If this
+ entry is in fact the one we are looking for we will find
+ out soon as we reach the end of the directory without
+ having found anything. */
+ if (entry_status == 0 && S_ISDIR (st.st_mode)
+ && st.st_dev == thisdev && st.st_ino == thisino)
+ break;
+ }
+ }
dirroom = dirp - dir;
namlen = _D_EXACT_NAMLEN (d);
if (dirroom <= namlen)
- {
- if (size != 0)
- {
- __set_errno (ERANGE);
- goto lose;
- }
- else
- {
- char *tmp;
- size_t oldsize = allocated;
-
- allocated += MAX (allocated, namlen);
- if (allocated < oldsize
- || ! (tmp = realloc (dir, allocated)))
- goto memory_exhausted;
-
- /* Move current contents up to the end of the buffer.
- This is guaranteed to be non-overlapping. */
- dirp = memcpy (tmp + allocated - (oldsize - dirroom),
- tmp + dirroom,
- oldsize - dirroom);
- dir = tmp;
- }
- }
+ {
+ if (size != 0)
+ {
+ __set_errno (ERANGE);
+ goto lose;
+ }
+ else
+ {
+ char *tmp;
+ size_t oldsize = allocated;
+
+ allocated += MAX (allocated, namlen);
+ if (allocated < oldsize
+ || ! (tmp = realloc (dir, allocated)))
+ goto memory_exhausted;
+
+ /* Move current contents up to the end of the buffer.
+ This is guaranteed to be non-overlapping. */
+ dirp = memcpy (tmp + allocated - (oldsize - dirroom),
+ tmp + dirroom,
+ oldsize - dirroom);
+ dir = tmp;
+ }
+ }
dirp -= namlen;
memcpy (dirp, d->d_name, namlen);
*--dirp = '/';
@@ -383,7 +401,7 @@ __getcwd (char *buf, size_t size)
if (dirp == &dir[allocated - 1])
*--dirp = '/';
-#ifndef AT_FDCWD
+#if ! HAVE_OPENAT_SUPPORT
if (dotlist != dots)
free (dotlist);
#endif
@@ -396,7 +414,7 @@ __getcwd (char *buf, size_t size)
buf = realloc (dir, used);
if (buf == NULL)
- /* Either buf was NULL all along, or `realloc' failed but
+ /* Either buf was NULL all along, or 'realloc' failed but
we still have the original string. */
buf = dir;
@@ -409,7 +427,7 @@ __getcwd (char *buf, size_t size)
int save = errno;
if (dirstream)
__closedir (dirstream);
-#ifdef AT_FDCWD
+#if HAVE_OPENAT_SUPPORT
if (fd_needs_closing)
close (fd);
#else
diff --git a/lib/getdate.c b/lib/getdate.c
deleted file mode 100644
index 5b07884..0000000
--- a/lib/getdate.c
+++ /dev/null
@@ -1,3359 +0,0 @@
-/* A Bison parser, made by GNU Bison 2.3a. */
-
-/* Skeleton implementation for Bison's Yacc-like parsers in C
-
- Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006
- 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 2, 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, write to the Free Software
- Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA. */
-
-/* As a special exception, you may create a larger work that contains
- part or all of the Bison parser skeleton and distribute that work
- under terms of your choice, so long as that work isn't itself a
- parser generator using the skeleton or a modified version thereof
- as a parser skeleton. Alternatively, if you modify or redistribute
- the parser skeleton itself, you may (at your option) remove this
- special exception, which will cause the skeleton and the resulting
- Bison output files to be licensed under the GNU General Public
- License without this special exception.
-
- This special exception was added by the Free Software Foundation in
- version 2.2 of Bison. */
-
-/* C LALR(1) parser skeleton written by Richard Stallman, by
- simplifying the original so-called "semantic" parser. */
-
-/* All symbols defined below should begin with yy or YY, to avoid
- infringing on user name space. This should be done even for local
- variables, as they might otherwise be expanded by user macros.
- There are some unavoidable exceptions within include files to
- define necessary library symbols; they are noted "INFRINGES ON
- USER NAME SPACE" below. */
-
-/* Identify Bison output. */
-#define YYBISON 1
-
-/* Bison version. */
-#define YYBISON_VERSION "2.3a"
-
-/* Skeleton name. */
-#define YYSKELETON_NAME "yacc.c"
-
-/* Pure parsers. */
-#define YYPURE 1
-
-/* Using locations. */
-#define YYLSP_NEEDED 0
-
-
-
-/* Copy the first part of user declarations. */
-/* Line 164 of yacc.c. */
-#line 1 "getdate.y"
-
-/* Parse a string into an internal time stamp.
-
- Copyright (C) 1999, 2000, 2002, 2003, 2004, 2005, 2006, 2007 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-/* Originally written by Steven M. Bellovin <smb@research.att.com> while
- at the University of North Carolina at Chapel Hill. Later tweaked by
- a couple of people on Usenet. Completely overhauled by Rich $alz
- <rsalz@bbn.com> and Jim Berets <jberets@bbn.com> in August, 1990.
-
- Modified by Paul Eggert <eggert@twinsun.com> in August 1999 to do
- the right thing about local DST. Also modified by Paul Eggert
- <eggert@cs.ucla.edu> in February 2004 to support
- nanosecond-resolution time stamps, and in October 2004 to support
- TZ strings in dates. */
-
-/* FIXME: Check for arithmetic overflow in all cases, not just
- some of them. */
-
-#include <config.h>
-
-#include "getdate.h"
-#include "timespec.h"
-
-/* There's no need to extend the stack, so there's no need to involve
- alloca. */
-#define YYSTACK_USE_ALLOCA 0
-
-/* Tell Bison how much stack space is needed. 20 should be plenty for
- this grammar, which is not right recursive. Beware setting it too
- high, since that might cause problems on machines whose
- implementations have lame stack-overflow checking. */
-#define YYMAXDEPTH 20
-#define YYINITDEPTH YYMAXDEPTH
-
-/* Since the code of getdate.y is not included in the Emacs executable
- itself, there is no need to #define static in this file. Even if
- the code were included in the Emacs executable, it probably
- wouldn't do any harm to #undef it here; this will only cause
- problems if we try to write to a static variable, which I don't
- think this code needs to do. */
-#ifdef emacs
-# undef static
-#endif
-
-#include <ctype.h>
-#include <limits.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "setenv.h"
-#include "xalloc.h"
-
-
-/* ISDIGIT differs from isdigit, as follows:
- - Its arg may be any int or unsigned int; it need not be an unsigned char
- or EOF.
- - It's typically faster.
- POSIX says that only '0' through '9' are digits. Prefer ISDIGIT to
- isdigit unless it's important to use the locale's definition
- of `digit' even when the host does not conform to POSIX. */
-#define ISDIGIT(c) ((unsigned int) (c) - '0' <= 9)
-
-#ifndef __attribute__
-# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 8) || __STRICT_ANSI__
-# define __attribute__(x)
-# endif
-#endif
-
-#ifndef ATTRIBUTE_UNUSED
-# define ATTRIBUTE_UNUSED __attribute__ ((__unused__))
-#endif
-
-/* Shift A right by B bits portably, by dividing A by 2**B and
- truncating towards minus infinity. A and B should be free of side
- effects, and B should be in the range 0 <= B <= INT_BITS - 2, where
- INT_BITS is the number of useful bits in an int. GNU code can
- assume that INT_BITS is at least 32.
-
- ISO C99 says that A >> B is implementation-defined if A < 0. Some
- implementations (e.g., UNICOS 9.0 on a Cray Y-MP EL) don't shift
- right in the usual way when A < 0, so SHR falls back on division if
- ordinary A >> B doesn't seem to be the usual signed shift. */
-#define SHR(a, b) \
- (-1 >> 1 == -1 \
- ? (a) >> (b) \
- : (a) / (1 << (b)) - ((a) % (1 << (b)) < 0))
-
-#define EPOCH_YEAR 1970
-#define TM_YEAR_BASE 1900
-
-#define HOUR(x) ((x) * 60)
-
-/* An integer value, and the number of digits in its textual
- representation. */
-typedef struct
-{
- bool negative;
- long int value;
- size_t digits;
-} textint;
-
-/* An entry in the lexical lookup table. */
-typedef struct
-{
- char const *name;
- int type;
- int value;
-} table;
-
-/* Meridian: am, pm, or 24-hour style. */
-enum { MERam, MERpm, MER24 };
-
-enum { BILLION = 1000000000, LOG10_BILLION = 9 };
-
-/* Relative times. */
-typedef struct
-{
- /* Relative year, month, day, hour, minutes, seconds, and nanoseconds. */
- long int year;
- long int month;
- long int day;
- long int hour;
- long int minutes;
- long int seconds;
- long int ns;
-} relative_time;
-
-#if HAVE_COMPOUND_LITERALS
-# define RELATIVE_TIME_0 ((relative_time) { 0, 0, 0, 0, 0, 0, 0 })
-#else
-static relative_time const RELATIVE_TIME_0;
-#endif
-
-/* Information passed to and from the parser. */
-typedef struct
-{
- /* The input string remaining to be parsed. */
- const char *input;
-
- /* N, if this is the Nth Tuesday. */
- long int day_ordinal;
-
- /* Day of week; Sunday is 0. */
- int day_number;
-
- /* tm_isdst flag for the local zone. */
- int local_isdst;
-
- /* Time zone, in minutes east of UTC. */
- long int time_zone;
-
- /* Style used for time. */
- int meridian;
-
- /* Gregorian year, month, day, hour, minutes, seconds, and nanoseconds. */
- textint year;
- long int month;
- long int day;
- long int hour;
- long int minutes;
- struct timespec seconds; /* includes nanoseconds */
-
- /* Relative year, month, day, hour, minutes, seconds, and nanoseconds. */
- relative_time rel;
-
- /* Presence or counts of nonterminals of various flavors parsed so far. */
- bool timespec_seen;
- bool rels_seen;
- size_t dates_seen;
- size_t days_seen;
- size_t local_zones_seen;
- size_t dsts_seen;
- size_t times_seen;
- size_t zones_seen;
-
- /* Table of local time zone abbrevations, terminated by a null entry. */
- table local_time_zone_table[3];
-} parser_control;
-
-union YYSTYPE;
-static int yylex (union YYSTYPE *, parser_control *);
-static int yyerror (parser_control const *, char const *);
-static long int time_zone_hhmm (textint, long int);
-
-
-
-/* Enabling traces. */
-#ifndef YYDEBUG
-# define YYDEBUG 0
-#endif
-
-/* Enabling verbose error messages. */
-#ifdef YYERROR_VERBOSE
-# undef YYERROR_VERBOSE
-# define YYERROR_VERBOSE 1
-#else
-# define YYERROR_VERBOSE 0
-#endif
-
-/* Enabling the token table. */
-#ifndef YYTOKEN_TABLE
-# define YYTOKEN_TABLE 0
-#endif
-
-
-/* Tokens. */
-#ifndef YYTOKENTYPE
-# define YYTOKENTYPE
- /* Put the tokens into the symbol table, so that GDB and other debuggers
- know about them. */
- enum yytokentype {
- tAGO = 258,
- tDST = 259,
- tYEAR_UNIT = 260,
- tMONTH_UNIT = 261,
- tHOUR_UNIT = 262,
- tMINUTE_UNIT = 263,
- tSEC_UNIT = 264,
- tDAY_UNIT = 265,
- tDAY = 266,
- tDAYZONE = 267,
- tLOCAL_ZONE = 268,
- tMERIDIAN = 269,
- tMONTH = 270,
- tORDINAL = 271,
- tZONE = 272,
- tSNUMBER = 273,
- tUNUMBER = 274,
- tSDECIMAL_NUMBER = 275,
- tUDECIMAL_NUMBER = 276
- };
-#endif
-/* Tokens. */
-#define tAGO 258
-#define tDST 259
-#define tYEAR_UNIT 260
-#define tMONTH_UNIT 261
-#define tHOUR_UNIT 262
-#define tMINUTE_UNIT 263
-#define tSEC_UNIT 264
-#define tDAY_UNIT 265
-#define tDAY 266
-#define tDAYZONE 267
-#define tLOCAL_ZONE 268
-#define tMERIDIAN 269
-#define tMONTH 270
-#define tORDINAL 271
-#define tZONE 272
-#define tSNUMBER 273
-#define tUNUMBER 274
-#define tSDECIMAL_NUMBER 275
-#define tUDECIMAL_NUMBER 276
-
-
-
-
-#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
-typedef union YYSTYPE
-{/* Line 191 of yacc.c. */
-#line 214 "getdate.y"
-
- long int intval;
- textint textintval;
- struct timespec timespec;
- relative_time rel;
-}
-/* Line 191 of yacc.c. */
-#line 351 "getdate.c"
- YYSTYPE;
-# define YYSTYPE_IS_TRIVIAL 1
-# define yystype YYSTYPE /* obsolescent; will be withdrawn */
-# define YYSTYPE_IS_DECLARED 1
-#endif
-
-
-
-
-/* Copy the second part of user declarations. */
-
-/* Line 221 of yacc.c. */
-#line 364 "getdate.c"
-
-#ifdef short
-# undef short
-#endif
-
-#ifdef YYTYPE_UINT8
-typedef YYTYPE_UINT8 yytype_uint8;
-#else
-typedef unsigned char yytype_uint8;
-#endif
-
-#ifdef YYTYPE_INT8
-typedef YYTYPE_INT8 yytype_int8;
-#elif (defined __STDC__ || defined __C99__FUNC__ \
- || defined __cplusplus || defined _MSC_VER)
-typedef signed char yytype_int8;
-#else
-typedef short int yytype_int8;
-#endif
-
-#ifdef YYTYPE_UINT16
-typedef YYTYPE_UINT16 yytype_uint16;
-#else
-typedef unsigned short int yytype_uint16;
-#endif
-
-#ifdef YYTYPE_INT16
-typedef YYTYPE_INT16 yytype_int16;
-#else
-typedef short int yytype_int16;
-#endif
-
-#ifndef YYSIZE_T
-# ifdef __SIZE_TYPE__
-# define YYSIZE_T __SIZE_TYPE__
-# elif defined size_t
-# define YYSIZE_T size_t
-# elif ! defined YYSIZE_T && (defined __STDC__ || defined __C99__FUNC__ \
- || defined __cplusplus || defined _MSC_VER)
-# include <stddef.h> /* INFRINGES ON USER NAME SPACE */
-# define YYSIZE_T size_t
-# else
-# define YYSIZE_T unsigned int
-# endif
-#endif
-
-#define YYSIZE_MAXIMUM ((YYSIZE_T) -1)
-
-#ifndef YY_
-# if YYENABLE_NLS
-# if ENABLE_NLS
-# include <libintl.h> /* INFRINGES ON USER NAME SPACE */
-# define YY_(msgid) dgettext ("bison-runtime", msgid)
-# endif
-# endif
-# ifndef YY_
-# define YY_(msgid) msgid
-# endif
-#endif
-
-/* Suppress unused-variable warnings by "using" E. */
-#if ! defined lint || defined __GNUC__
-# define YYUSE(e) ((void) (e))
-#else
-# define YYUSE(e) /* empty */
-#endif
-
-/* Identity function, used to suppress warnings about constant conditions. */
-#ifndef lint
-# define YYID(n) (n)
-#else
-#if (defined __STDC__ || defined __C99__FUNC__ \
- || defined __cplusplus || defined _MSC_VER)
-static int
-YYID (int yyi)
-#else
-static int
-YYID (yyi)
- int yyi;
-#endif
-{
- return yyi;
-}
-#endif
-
-#if ! defined yyoverflow || YYERROR_VERBOSE
-
-/* The parser invokes alloca or malloc; define the necessary symbols. */
-
-# ifdef YYSTACK_USE_ALLOCA
-# if YYSTACK_USE_ALLOCA
-# ifdef __GNUC__
-# define YYSTACK_ALLOC __builtin_alloca
-# elif defined __BUILTIN_VA_ARG_INCR
-# include <alloca.h> /* INFRINGES ON USER NAME SPACE */
-# elif defined _AIX
-# define YYSTACK_ALLOC __alloca
-# elif defined _MSC_VER
-# include <malloc.h> /* INFRINGES ON USER NAME SPACE */
-# define alloca _alloca
-# else
-# define YYSTACK_ALLOC alloca
-# if ! defined _ALLOCA_H && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \
- || defined __cplusplus || defined _MSC_VER)
-# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
-# ifndef _STDLIB_H
-# define _STDLIB_H 1
-# endif
-# endif
-# endif
-# endif
-# endif
-
-# ifdef YYSTACK_ALLOC
- /* Pacify GCC's `empty if-body' warning. */
-# define YYSTACK_FREE(Ptr) do { /* empty */; } while (YYID (0))
-# ifndef YYSTACK_ALLOC_MAXIMUM
- /* The OS might guarantee only one guard page at the bottom of the stack,
- and a page size can be as small as 4096 bytes. So we cannot safely
- invoke alloca (N) if N exceeds 4096. Use a slightly smaller number
- to allow for a few compiler-allocated temporary stack slots. */
-# define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */
-# endif
-# else
-# define YYSTACK_ALLOC YYMALLOC
-# define YYSTACK_FREE YYFREE
-# ifndef YYSTACK_ALLOC_MAXIMUM
-# define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM
-# endif
-# if (defined __cplusplus && ! defined _STDLIB_H \
- && ! ((defined YYMALLOC || defined malloc) \
- && (defined YYFREE || defined free)))
-# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
-# ifndef _STDLIB_H
-# define _STDLIB_H 1
-# endif
-# endif
-# ifndef YYMALLOC
-# define YYMALLOC malloc
-# if ! defined malloc && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \
- || defined __cplusplus || defined _MSC_VER)
-void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */
-# endif
-# endif
-# ifndef YYFREE
-# define YYFREE free
-# if ! defined free && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \
- || defined __cplusplus || defined _MSC_VER)
-void free (void *); /* INFRINGES ON USER NAME SPACE */
-# endif
-# endif
-# endif
-#endif /* ! defined yyoverflow || YYERROR_VERBOSE */
-
-
-#if (! defined yyoverflow \
- && (! defined __cplusplus \
- || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL)))
-
-/* A type that is properly aligned for any stack member. */
-union yyalloc
-{
- yytype_int16 yyss;
- YYSTYPE yyvs;
- };
-
-/* The size of the maximum gap between one aligned stack and the next. */
-# define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1)
-
-/* The size of an array large to enough to hold all stacks, each with
- N elements. */
-# define YYSTACK_BYTES(N) \
- ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \
- + YYSTACK_GAP_MAXIMUM)
-
-/* Copy COUNT objects from FROM to TO. The source and destination do
- not overlap. */
-# ifndef YYCOPY
-# if defined __GNUC__ && 1 < __GNUC__
-# define YYCOPY(To, From, Count) \
- __builtin_memcpy (To, From, (Count) * sizeof (*(From)))
-# else
-# define YYCOPY(To, From, Count) \
- do \
- { \
- YYSIZE_T yyi; \
- for (yyi = 0; yyi < (Count); yyi++) \
- (To)[yyi] = (From)[yyi]; \
- } \
- while (YYID (0))
-# endif
-# endif
-
-/* Relocate STACK from its old location to the new one. The
- local variables YYSIZE and YYSTACKSIZE give the old and new number of
- elements in the stack, and YYPTR gives the new location of the
- stack. Advance YYPTR to a properly aligned location for the next
- stack. */
-# define YYSTACK_RELOCATE(Stack) \
- do \
- { \
- YYSIZE_T yynewbytes; \
- YYCOPY (&yyptr->Stack, Stack, yysize); \
- Stack = &yyptr->Stack; \
- yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \
- yyptr += yynewbytes / sizeof (*yyptr); \
- } \
- while (YYID (0))
-
-#endif
-
-/* YYFINAL -- State number of the termination state. */
-#define YYFINAL 12
-/* YYLAST -- Last index in YYTABLE. */
-#define YYLAST 91
-
-/* YYNTOKENS -- Number of terminals. */
-#define YYNTOKENS 26
-/* YYNNTS -- Number of nonterminals. */
-#define YYNNTS 19
-/* YYNRULES -- Number of rules. */
-#define YYNRULES 78
-/* YYNRULES -- Number of states. */
-#define YYNSTATES 96
-
-/* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX. */
-#define YYUNDEFTOK 2
-#define YYMAXUTOK 276
-
-#define YYTRANSLATE(YYX) \
- ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK)
-
-/* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX. */
-static const yytype_uint8 yytranslate[] =
-{
- 0, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 24, 2, 2, 25, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 23, 2,
- 2, 2, 2, 2, 22, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 1, 2, 3, 4,
- 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
- 15, 16, 17, 18, 19, 20, 21
-};
-
-#if YYDEBUG
-/* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in
- YYRHS. */
-static const yytype_uint8 yyprhs[] =
-{
- 0, 0, 3, 5, 7, 10, 11, 14, 16, 18,
- 20, 22, 24, 26, 28, 31, 36, 42, 49, 57,
- 59, 62, 64, 67, 71, 73, 76, 78, 81, 84,
- 87, 91, 97, 101, 105, 109, 112, 117, 120, 124,
- 127, 129, 132, 135, 137, 140, 143, 145, 148, 151,
- 153, 156, 159, 161, 164, 167, 169, 172, 175, 178,
- 181, 183, 185, 188, 191, 194, 197, 200, 203, 205,
- 207, 209, 211, 213, 215, 217, 218, 221, 222
-};
-
-/* YYRHS -- A `-1'-separated list of the rules' RHS. */
-static const yytype_int8 yyrhs[] =
-{
- 27, 0, -1, 28, -1, 29, -1, 22, 39, -1,
- -1, 29, 30, -1, 31, -1, 32, -1, 33, -1,
- 35, -1, 34, -1, 36, -1, 42, -1, 19, 14,
- -1, 19, 23, 19, 44, -1, 19, 23, 19, 18,
- 43, -1, 19, 23, 19, 23, 41, 44, -1, 19,
- 23, 19, 23, 41, 18, 43, -1, 13, -1, 13,
- 4, -1, 17, -1, 17, 38, -1, 17, 18, 43,
- -1, 12, -1, 17, 4, -1, 11, -1, 11, 24,
- -1, 16, 11, -1, 19, 11, -1, 19, 25, 19,
- -1, 19, 25, 19, 25, 19, -1, 19, 18, 18,
- -1, 19, 15, 18, -1, 15, 18, 18, -1, 15,
- 19, -1, 15, 19, 24, 19, -1, 19, 15, -1,
- 19, 15, 19, -1, 37, 3, -1, 37, -1, 16,
- 5, -1, 19, 5, -1, 5, -1, 16, 6, -1,
- 19, 6, -1, 6, -1, 16, 10, -1, 19, 10,
- -1, 10, -1, 16, 7, -1, 19, 7, -1, 7,
- -1, 16, 8, -1, 19, 8, -1, 8, -1, 16,
- 9, -1, 19, 9, -1, 20, 9, -1, 21, 9,
- -1, 9, -1, 38, -1, 18, 5, -1, 18, 6,
- -1, 18, 10, -1, 18, 7, -1, 18, 8, -1,
- 18, 9, -1, 40, -1, 41, -1, 20, -1, 18,
- -1, 21, -1, 19, -1, 19, -1, -1, 23, 19,
- -1, -1, 14, -1
-};
-
-/* YYRLINE[YYN] -- source line where rule number YYN was defined. */
-static const yytype_uint16 yyrline[] =
-{
- 0, 240, 240, 241, 245, 252, 254, 258, 260, 262,
- 264, 266, 268, 270, 274, 282, 290, 300, 307, 319,
- 324, 332, 334, 344, 346, 348, 353, 358, 363, 368,
- 376, 381, 401, 408, 416, 424, 429, 435, 440, 449,
- 459, 472, 474, 476, 478, 480, 482, 484, 486, 488,
- 490, 492, 494, 496, 498, 500, 502, 504, 506, 508,
- 510, 512, 516, 518, 520, 522, 524, 526, 530, 530,
- 533, 534, 539, 540, 545, 583, 584, 590, 591
-};
-#endif
-
-#if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE
-/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
- First, the terminals, then, starting at YYNTOKENS, nonterminals. */
-static const char *const yytname[] =
-{
- "$end", "error", "$undefined", "tAGO", "tDST", "tYEAR_UNIT",
- "tMONTH_UNIT", "tHOUR_UNIT", "tMINUTE_UNIT", "tSEC_UNIT", "tDAY_UNIT",
- "tDAY", "tDAYZONE", "tLOCAL_ZONE", "tMERIDIAN", "tMONTH", "tORDINAL",
- "tZONE", "tSNUMBER", "tUNUMBER", "tSDECIMAL_NUMBER", "tUDECIMAL_NUMBER",
- "'@'", "':'", "','", "'/'", "$accept", "spec", "timespec", "items",
- "item", "time", "local_zone", "zone", "day", "date", "rel", "relunit",
- "relunit_snumber", "seconds", "signed_seconds", "unsigned_seconds",
- "number", "o_colon_minutes", "o_merid", 0
-};
-#endif
-
-# ifdef YYPRINT
-/* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to
- token YYLEX-NUM. */
-static const yytype_uint16 yytoknum[] =
-{
- 0, 256, 257, 258, 259, 260, 261, 262, 263, 264,
- 265, 266, 267, 268, 269, 270, 271, 272, 273, 274,
- 275, 276, 64, 58, 44, 47
-};
-# endif
-
-/* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */
-static const yytype_uint8 yyr1[] =
-{
- 0, 26, 27, 27, 28, 29, 29, 30, 30, 30,
- 30, 30, 30, 30, 31, 31, 31, 31, 31, 32,
- 32, 33, 33, 33, 33, 33, 34, 34, 34, 34,
- 35, 35, 35, 35, 35, 35, 35, 35, 35, 36,
- 36, 37, 37, 37, 37, 37, 37, 37, 37, 37,
- 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
- 37, 37, 38, 38, 38, 38, 38, 38, 39, 39,
- 40, 40, 41, 41, 42, 43, 43, 44, 44
-};
-
-/* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */
-static const yytype_uint8 yyr2[] =
-{
- 0, 2, 1, 1, 2, 0, 2, 1, 1, 1,
- 1, 1, 1, 1, 2, 4, 5, 6, 7, 1,
- 2, 1, 2, 3, 1, 2, 1, 2, 2, 2,
- 3, 5, 3, 3, 3, 2, 4, 2, 3, 2,
- 1, 2, 2, 1, 2, 2, 1, 2, 2, 1,
- 2, 2, 1, 2, 2, 1, 2, 2, 2, 2,
- 1, 1, 2, 2, 2, 2, 2, 2, 1, 1,
- 1, 1, 1, 1, 1, 0, 2, 0, 1
-};
-
-/* YYDEFACT[STATE-NAME] -- Default rule to reduce with in state
- STATE-NUM when YYTABLE doesn't specify something else to do. Zero
- means the default is an error. */
-static const yytype_uint8 yydefact[] =
-{
- 5, 0, 0, 2, 3, 71, 73, 70, 72, 4,
- 68, 69, 1, 43, 46, 52, 55, 60, 49, 26,
- 24, 19, 0, 0, 21, 0, 74, 0, 0, 6,
- 7, 8, 9, 11, 10, 12, 40, 61, 13, 27,
- 20, 0, 35, 41, 44, 50, 53, 56, 47, 28,
- 25, 75, 22, 62, 63, 65, 66, 67, 64, 42,
- 45, 51, 54, 57, 48, 29, 14, 37, 0, 0,
- 0, 58, 59, 39, 34, 0, 0, 23, 33, 38,
- 32, 77, 30, 36, 76, 78, 75, 0, 15, 0,
- 16, 77, 31, 75, 17, 18
-};
-
-/* YYDEFGOTO[NTERM-NUM]. */
-static const yytype_int8 yydefgoto[] =
-{
- -1, 2, 3, 4, 29, 30, 31, 32, 33, 34,
- 35, 36, 37, 9, 10, 11, 38, 77, 88
-};
-
-/* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
- STATE-NUM. */
-#define YYPACT_NINF -79
-static const yytype_int8 yypact[] =
-{
- -10, 47, 27, -79, 25, -79, -79, -79, -79, -79,
- -79, -79, -79, -79, -79, -79, -79, -79, -79, 5,
- -79, 59, 43, 42, 10, 49, -5, 62, 63, -79,
- -79, -79, -79, -79, -79, -79, 70, -79, -79, -79,
- -79, 56, 52, -79, -79, -79, -79, -79, -79, -79,
- -79, 16, -79, -79, -79, -79, -79, -79, -79, -79,
- -79, -79, -79, -79, -79, -79, -79, 51, 57, 58,
- 60, -79, -79, -79, -79, 61, 64, -79, -79, -79,
- -79, -7, 53, -79, -79, -79, 65, -2, -79, 66,
- -79, 46, -79, 65, -79, -79
-};
-
-/* YYPGOTO[NTERM-NUM]. */
-static const yytype_int8 yypgoto[] =
-{
- -79, -79, -79, -79, -79, -79, -79, -79, -79, -79,
- -79, -79, 67, -79, -79, -6, -79, -78, -9
-};
-
-/* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If
- positive, shift that token. If negative, reduce the rule which
- number is the opposite. If zero, do what YYDEFACT says.
- If YYTABLE_NINF, syntax error. */
-#define YYTABLE_NINF -1
-static const yytype_uint8 yytable[] =
-{
- 59, 60, 61, 62, 63, 64, 65, 85, 90, 66,
- 67, 86, 1, 68, 50, 95, 87, 6, 69, 8,
- 70, 53, 54, 55, 56, 57, 58, 12, 51, 39,
- 13, 14, 15, 16, 17, 18, 19, 20, 21, 76,
- 22, 23, 24, 25, 26, 27, 28, 43, 44, 45,
- 46, 47, 48, 49, 53, 54, 55, 56, 57, 58,
- 85, 41, 42, 40, 93, 5, 6, 7, 8, 78,
- 79, 71, 72, 73, 74, 80, 75, 81, 89, 82,
- 83, 91, 94, 84, 0, 92, 0, 0, 76, 0,
- 0, 52
-};
-
-static const yytype_int8 yycheck[] =
-{
- 5, 6, 7, 8, 9, 10, 11, 14, 86, 14,
- 15, 18, 22, 18, 4, 93, 23, 19, 23, 21,
- 25, 5, 6, 7, 8, 9, 10, 0, 18, 24,
- 5, 6, 7, 8, 9, 10, 11, 12, 13, 23,
- 15, 16, 17, 18, 19, 20, 21, 5, 6, 7,
- 8, 9, 10, 11, 5, 6, 7, 8, 9, 10,
- 14, 18, 19, 4, 18, 18, 19, 20, 21, 18,
- 19, 9, 9, 3, 18, 18, 24, 19, 25, 19,
- 19, 87, 91, 19, -1, 19, -1, -1, 23, -1,
- -1, 24
-};
-
-/* YYSTOS[STATE-NUM] -- The (internal number of the) accessing
- symbol of state STATE-NUM. */
-static const yytype_uint8 yystos[] =
-{
- 0, 22, 27, 28, 29, 18, 19, 20, 21, 39,
- 40, 41, 0, 5, 6, 7, 8, 9, 10, 11,
- 12, 13, 15, 16, 17, 18, 19, 20, 21, 30,
- 31, 32, 33, 34, 35, 36, 37, 38, 42, 24,
- 4, 18, 19, 5, 6, 7, 8, 9, 10, 11,
- 4, 18, 38, 5, 6, 7, 8, 9, 10, 5,
- 6, 7, 8, 9, 10, 11, 14, 15, 18, 23,
- 25, 9, 9, 3, 18, 24, 23, 43, 18, 19,
- 18, 19, 19, 19, 19, 14, 18, 23, 44, 25,
- 43, 41, 19, 18, 44, 43
-};
-
-#define yyerrok (yyerrstatus = 0)
-#define yyclearin (yychar = YYEMPTY)
-#define YYEMPTY (-2)
-#define YYEOF 0
-
-#define YYACCEPT goto yyacceptlab
-#define YYABORT goto yyabortlab
-#define YYERROR goto yyerrorlab
-
-
-/* Like YYERROR except do call yyerror. This remains here temporarily
- to ease the transition to the new meaning of YYERROR, for GCC.
- Once GCC version 2 has supplanted version 1, this can go. */
-
-#define YYFAIL goto yyerrlab
-
-#define YYRECOVERING() (!!yyerrstatus)
-
-#define YYBACKUP(Token, Value) \
-do \
- if (yychar == YYEMPTY && yylen == 1) \
- { \
- yychar = (Token); \
- yylval = (Value); \
- yytoken = YYTRANSLATE (yychar); \
- YYPOPSTACK (1); \
- goto yybackup; \
- } \
- else \
- { \
- yyerror (pc, YY_("syntax error: cannot back up")); \
- YYERROR; \
- } \
-while (YYID (0))
-
-
-#define YYTERROR 1
-#define YYERRCODE 256
-
-
-/* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N].
- If N is 0, then set CURRENT to the empty location which ends
- the previous symbol: RHS[0] (always defined). */
-
-#define YYRHSLOC(Rhs, K) ((Rhs)[K])
-#ifndef YYLLOC_DEFAULT
-# define YYLLOC_DEFAULT(Current, Rhs, N) \
- do \
- if (YYID (N)) \
- { \
- (Current).first_line = YYRHSLOC (Rhs, 1).first_line; \
- (Current).first_column = YYRHSLOC (Rhs, 1).first_column; \
- (Current).last_line = YYRHSLOC (Rhs, N).last_line; \
- (Current).last_column = YYRHSLOC (Rhs, N).last_column; \
- } \
- else \
- { \
- (Current).first_line = (Current).last_line = \
- YYRHSLOC (Rhs, 0).last_line; \
- (Current).first_column = (Current).last_column = \
- YYRHSLOC (Rhs, 0).last_column; \
- } \
- while (YYID (0))
-#endif
-
-
-/* YY_LOCATION_PRINT -- Print the location on the stream.
- This macro was not mandated originally: define only if we know
- we won't break user code: when these are the locations we know. */
-
-#ifndef YY_LOCATION_PRINT
-# if YYLTYPE_IS_TRIVIAL
-# define YY_LOCATION_PRINT(File, Loc) \
- fprintf (File, "%d.%d-%d.%d", \
- (Loc).first_line, (Loc).first_column, \
- (Loc).last_line, (Loc).last_column)
-# else
-# define YY_LOCATION_PRINT(File, Loc) ((void) 0)
-# endif
-#endif
-
-
-/* YYLEX -- calling `yylex' with the right arguments. */
-
-#ifdef YYLEX_PARAM
-# define YYLEX yylex (&yylval, YYLEX_PARAM)
-#else
-# define YYLEX yylex (&yylval, pc)
-#endif
-
-/* Enable debugging if requested. */
-#if YYDEBUG
-
-# ifndef YYFPRINTF
-# include <stdio.h> /* INFRINGES ON USER NAME SPACE */
-# define YYFPRINTF fprintf
-# endif
-
-# define YYDPRINTF(Args) \
-do { \
- if (yydebug) \
- YYFPRINTF Args; \
-} while (YYID (0))
-
-# define YY_SYMBOL_PRINT(Title, Type, Value, Location) \
-do { \
- if (yydebug) \
- { \
- YYFPRINTF (stderr, "%s ", Title); \
- yy_symbol_print (stderr, \
- Type, Value, pc); \
- YYFPRINTF (stderr, "\n"); \
- } \
-} while (YYID (0))
-
-
-/*--------------------------------.
-| Print this symbol on YYOUTPUT. |
-`--------------------------------*/
-
-/*ARGSUSED*/
-#if (defined __STDC__ || defined __C99__FUNC__ \
- || defined __cplusplus || defined _MSC_VER)
-static void
-yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, parser_control *pc)
-#else
-static void
-yy_symbol_value_print (yyoutput, yytype, yyvaluep, pc)
- FILE *yyoutput;
- int yytype;
- YYSTYPE const * const yyvaluep;
- parser_control *pc;
-#endif
-{
- if (!yyvaluep)
- return;
- YYUSE (pc);
-# ifdef YYPRINT
- if (yytype < YYNTOKENS)
- YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep);
-# else
- YYUSE (yyoutput);
-# endif
- switch (yytype)
- {
- default:
- break;
- }
-}
-
-
-/*--------------------------------.
-| Print this symbol on YYOUTPUT. |
-`--------------------------------*/
-
-#if (defined __STDC__ || defined __C99__FUNC__ \
- || defined __cplusplus || defined _MSC_VER)
-static void
-yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, parser_control *pc)
-#else
-static void
-yy_symbol_print (yyoutput, yytype, yyvaluep, pc)
- FILE *yyoutput;
- int yytype;
- YYSTYPE const * const yyvaluep;
- parser_control *pc;
-#endif
-{
- if (yytype < YYNTOKENS)
- YYFPRINTF (yyoutput, "token %s (", yytname[yytype]);
- else
- YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]);
-
- yy_symbol_value_print (yyoutput, yytype, yyvaluep, pc);
- YYFPRINTF (yyoutput, ")");
-}
-
-/*------------------------------------------------------------------.
-| yy_stack_print -- Print the state stack from its BOTTOM up to its |
-| TOP (included). |
-`------------------------------------------------------------------*/
-
-#if (defined __STDC__ || defined __C99__FUNC__ \
- || defined __cplusplus || defined _MSC_VER)
-static void
-yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop)
-#else
-static void
-yy_stack_print (yybottom, yytop)
- yytype_int16 *yybottom;
- yytype_int16 *yytop;
-#endif
-{
- YYFPRINTF (stderr, "Stack now");
- for (; yybottom <= yytop; yybottom++)
- {
- int yybot = *yybottom;
- YYFPRINTF (stderr, " %d", yybot);
- }
- YYFPRINTF (stderr, "\n");
-}
-
-# define YY_STACK_PRINT(Bottom, Top) \
-do { \
- if (yydebug) \
- yy_stack_print ((Bottom), (Top)); \
-} while (YYID (0))
-
-
-/*------------------------------------------------.
-| Report that the YYRULE is going to be reduced. |
-`------------------------------------------------*/
-
-#if (defined __STDC__ || defined __C99__FUNC__ \
- || defined __cplusplus || defined _MSC_VER)
-static void
-yy_reduce_print (YYSTYPE *yyvsp, int yyrule, parser_control *pc)
-#else
-static void
-yy_reduce_print (yyvsp, yyrule, pc)
- YYSTYPE *yyvsp;
- int yyrule;
- parser_control *pc;
-#endif
-{
- int yynrhs = yyr2[yyrule];
- int yyi;
- unsigned long int yylno = yyrline[yyrule];
- YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n",
- yyrule - 1, yylno);
- /* The symbols being reduced. */
- for (yyi = 0; yyi < yynrhs; yyi++)
- {
- fprintf (stderr, " $%d = ", yyi + 1);
- yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi],
- &(yyvsp[(yyi + 1) - (yynrhs)])
- , pc);
- fprintf (stderr, "\n");
- }
-}
-
-# define YY_REDUCE_PRINT(Rule) \
-do { \
- if (yydebug) \
- yy_reduce_print (yyvsp, Rule, pc); \
-} while (YYID (0))
-
-/* Nonzero means print parse trace. It is left uninitialized so that
- multiple parsers can coexist. */
-int yydebug;
-#else /* !YYDEBUG */
-# define YYDPRINTF(Args)
-# define YY_SYMBOL_PRINT(Title, Type, Value, Location)
-# define YY_STACK_PRINT(Bottom, Top)
-# define YY_REDUCE_PRINT(Rule)
-#endif /* !YYDEBUG */
-
-
-/* YYINITDEPTH -- initial size of the parser's stacks. */
-#ifndef YYINITDEPTH
-# define YYINITDEPTH 200
-#endif
-
-/* YYMAXDEPTH -- maximum size the stacks can grow to (effective only
- if the built-in stack extension method is used).
-
- Do not make this value too large; the results are undefined if
- YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH)
- evaluated with infinite-precision integer arithmetic. */
-
-#ifndef YYMAXDEPTH
-# define YYMAXDEPTH 10000
-#endif
-
-
-
-#if YYERROR_VERBOSE
-
-# ifndef yystrlen
-# if defined __GLIBC__ && defined _STRING_H
-# define yystrlen strlen
-# else
-/* Return the length of YYSTR. */
-#if (defined __STDC__ || defined __C99__FUNC__ \
- || defined __cplusplus || defined _MSC_VER)
-static YYSIZE_T
-yystrlen (const char *yystr)
-#else
-static YYSIZE_T
-yystrlen (yystr)
- const char *yystr;
-#endif
-{
- YYSIZE_T yylen;
- for (yylen = 0; yystr[yylen]; yylen++)
- continue;
- return yylen;
-}
-# endif
-# endif
-
-# ifndef yystpcpy
-# if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE
-# define yystpcpy stpcpy
-# else
-/* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in
- YYDEST. */
-#if (defined __STDC__ || defined __C99__FUNC__ \
- || defined __cplusplus || defined _MSC_VER)
-static char *
-yystpcpy (char *yydest, const char *yysrc)
-#else
-static char *
-yystpcpy (yydest, yysrc)
- char *yydest;
- const char *yysrc;
-#endif
-{
- char *yyd = yydest;
- const char *yys = yysrc;
-
- while ((*yyd++ = *yys++) != '\0')
- continue;
-
- return yyd - 1;
-}
-# endif
-# endif
-
-# ifndef yytnamerr
-/* Copy to YYRES the contents of YYSTR after stripping away unnecessary
- quotes and backslashes, so that it's suitable for yyerror. The
- heuristic is that double-quoting is unnecessary unless the string
- contains an apostrophe, a comma, or backslash (other than
- backslash-backslash). YYSTR is taken from yytname. If YYRES is
- null, do not copy; instead, return the length of what the result
- would have been. */
-static YYSIZE_T
-yytnamerr (char *yyres, const char *yystr)
-{
- if (*yystr == '"')
- {
- YYSIZE_T yyn = 0;
- char const *yyp = yystr;
-
- for (;;)
- switch (*++yyp)
- {
- case '\'':
- case ',':
- goto do_not_strip_quotes;
-
- case '\\':
- if (*++yyp != '\\')
- goto do_not_strip_quotes;
- /* Fall through. */
- default:
- if (yyres)
- yyres[yyn] = *yyp;
- yyn++;
- break;
-
- case '"':
- if (yyres)
- yyres[yyn] = '\0';
- return yyn;
- }
- do_not_strip_quotes: ;
- }
-
- if (! yyres)
- return yystrlen (yystr);
-
- return yystpcpy (yyres, yystr) - yyres;
-}
-# endif
-
-/* Copy into YYRESULT an error message about the unexpected token
- YYCHAR while in state YYSTATE. Return the number of bytes copied,
- including the terminating null byte. If YYRESULT is null, do not
- copy anything; just return the number of bytes that would be
- copied. As a special case, return 0 if an ordinary "syntax error"
- message will do. Return YYSIZE_MAXIMUM if overflow occurs during
- size calculation. */
-static YYSIZE_T
-yysyntax_error (char *yyresult, int yystate, int yychar)
-{
- int yyn = yypact[yystate];
-
- if (! (YYPACT_NINF < yyn && yyn <= YYLAST))
- return 0;
- else
- {
- int yytype = YYTRANSLATE (yychar);
- YYSIZE_T yysize0 = yytnamerr (0, yytname[yytype]);
- YYSIZE_T yysize = yysize0;
- YYSIZE_T yysize1;
- int yysize_overflow = 0;
- enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 };
- char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM];
- int yyx;
-
-# if 0
- /* This is so xgettext sees the translatable formats that are
- constructed on the fly. */
- YY_("syntax error, unexpected %s");
- YY_("syntax error, unexpected %s, expecting %s");
- YY_("syntax error, unexpected %s, expecting %s or %s");
- YY_("syntax error, unexpected %s, expecting %s or %s or %s");
- YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s");
-# endif
- char *yyfmt;
- char const *yyf;
- static char const yyunexpected[] = "syntax error, unexpected %s";
- static char const yyexpecting[] = ", expecting %s";
- static char const yyor[] = " or %s";
- char yyformat[sizeof yyunexpected
- + sizeof yyexpecting - 1
- + ((YYERROR_VERBOSE_ARGS_MAXIMUM - 2)
- * (sizeof yyor - 1))];
- char const *yyprefix = yyexpecting;
-
- /* Start YYX at -YYN if negative to avoid negative indexes in
- YYCHECK. */
- int yyxbegin = yyn < 0 ? -yyn : 0;
-
- /* Stay within bounds of both yycheck and yytname. */
- int yychecklim = YYLAST - yyn + 1;
- int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS;
- int yycount = 1;
-
- yyarg[0] = yytname[yytype];
- yyfmt = yystpcpy (yyformat, yyunexpected);
-
- for (yyx = yyxbegin; yyx < yyxend; ++yyx)
- if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR)
- {
- if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM)
- {
- yycount = 1;
- yysize = yysize0;
- yyformat[sizeof yyunexpected - 1] = '\0';
- break;
- }
- yyarg[yycount++] = yytname[yyx];
- yysize1 = yysize + yytnamerr (0, yytname[yyx]);
- yysize_overflow |= (yysize1 < yysize);
- yysize = yysize1;
- yyfmt = yystpcpy (yyfmt, yyprefix);
- yyprefix = yyor;
- }
-
- yyf = YY_(yyformat);
- yysize1 = yysize + yystrlen (yyf);
- yysize_overflow |= (yysize1 < yysize);
- yysize = yysize1;
-
- if (yysize_overflow)
- return YYSIZE_MAXIMUM;
-
- if (yyresult)
- {
- /* Avoid sprintf, as that infringes on the user's name space.
- Don't have undefined behavior even if the translation
- produced a string with the wrong number of "%s"s. */
- char *yyp = yyresult;
- int yyi = 0;
- while ((*yyp = *yyf) != '\0')
- {
- if (*yyp == '%' && yyf[1] == 's' && yyi < yycount)
- {
- yyp += yytnamerr (yyp, yyarg[yyi++]);
- yyf += 2;
- }
- else
- {
- yyp++;
- yyf++;
- }
- }
- }
- return yysize;
- }
-}
-#endif /* YYERROR_VERBOSE */
-
-
-/*-----------------------------------------------.
-| Release the memory associated to this symbol. |
-`-----------------------------------------------*/
-
-/*ARGSUSED*/
-#if (defined __STDC__ || defined __C99__FUNC__ \
- || defined __cplusplus || defined _MSC_VER)
-static void
-yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, parser_control *pc)
-#else
-static void
-yydestruct (yymsg, yytype, yyvaluep, pc)
- const char *yymsg;
- int yytype;
- YYSTYPE *yyvaluep;
- parser_control *pc;
-#endif
-{
- YYUSE (yyvaluep);
- YYUSE (pc);
-
- if (!yymsg)
- yymsg = "Deleting";
- YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp);
-
- switch (yytype)
- {
-
- default:
- break;
- }
-}
-
-
-/* Prevent warnings from -Wmissing-prototypes. */
-
-#ifdef YYPARSE_PARAM
-#if defined __STDC__ || defined __cplusplus
-int yyparse (void *YYPARSE_PARAM);
-#else
-int yyparse ();
-#endif
-#else /* ! YYPARSE_PARAM */
-#if defined __STDC__ || defined __cplusplus
-int yyparse (parser_control *pc);
-#else
-int yyparse ();
-#endif
-#endif /* ! YYPARSE_PARAM */
-
-
-
-
-
-
-/*----------.
-| yyparse. |
-`----------*/
-
-#ifdef YYPARSE_PARAM
-#if (defined __STDC__ || defined __C99__FUNC__ \
- || defined __cplusplus || defined _MSC_VER)
-int
-yyparse (void *YYPARSE_PARAM)
-#else
-int
-yyparse (YYPARSE_PARAM)
- void *YYPARSE_PARAM;
-#endif
-#else /* ! YYPARSE_PARAM */
-#if (defined __STDC__ || defined __C99__FUNC__ \
- || defined __cplusplus || defined _MSC_VER)
-int
-yyparse (parser_control *pc)
-#else
-int
-yyparse (pc)
- parser_control *pc;
-#endif
-#endif
-{
- /* The lookahead symbol. */
-int yychar;
-
-/* The semantic value of the lookahead symbol. */
-YYSTYPE yylval;
-
-/* Number of syntax errors so far. */
-int yynerrs;
-
- int yystate;
- int yyn;
- int yyresult;
- /* Number of tokens to shift before error messages enabled. */
- int yyerrstatus;
- /* Lookahead token as an internal (translated) token number. */
- int yytoken = 0;
-#if YYERROR_VERBOSE
- /* Buffer for error messages, and its allocated size. */
- char yymsgbuf[128];
- char *yymsg = yymsgbuf;
- YYSIZE_T yymsg_alloc = sizeof yymsgbuf;
-#endif
-
- /* Three stacks and their tools:
- `yyss': related to states,
- `yyvs': related to semantic values,
- `yyls': related to locations.
-
- Refer to the stacks thru separate pointers, to allow yyoverflow
- to reallocate them elsewhere. */
-
- /* The state stack. */
- yytype_int16 yyssa[YYINITDEPTH];
- yytype_int16 *yyss = yyssa;
- yytype_int16 *yyssp;
-
- /* The semantic value stack. */
- YYSTYPE yyvsa[YYINITDEPTH];
- YYSTYPE *yyvs = yyvsa;
- YYSTYPE *yyvsp;
-
-
-
-#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N))
-
- YYSIZE_T yystacksize = YYINITDEPTH;
-
- /* The variables used to return semantic value and location from the
- action routines. */
- YYSTYPE yyval;
-
-
- /* The number of symbols on the RHS of the reduced rule.
- Keep to zero when no symbol should be popped. */
- int yylen = 0;
-
- YYDPRINTF ((stderr, "Starting parse\n"));
-
- yystate = 0;
- yyerrstatus = 0;
- yynerrs = 0;
- yychar = YYEMPTY; /* Cause a token to be read. */
-
- /* Initialize stack pointers.
- Waste one element of value and location stack
- so that they stay on the same level as the state stack.
- The wasted elements are never initialized. */
-
- yyssp = yyss;
- yyvsp = yyvs;
-
- goto yysetstate;
-
-/*------------------------------------------------------------.
-| yynewstate -- Push a new state, which is found in yystate. |
-`------------------------------------------------------------*/
- yynewstate:
- /* In all cases, when you get here, the value and location stacks
- have just been pushed. So pushing a state here evens the stacks. */
- yyssp++;
-
- yysetstate:
- *yyssp = yystate;
-
- if (yyss + yystacksize - 1 <= yyssp)
- {
- /* Get the current used size of the three stacks, in elements. */
- YYSIZE_T yysize = yyssp - yyss + 1;
-
-#ifdef yyoverflow
- {
- /* Give user a chance to reallocate the stack. Use copies of
- these so that the &'s don't force the real ones into
- memory. */
- YYSTYPE *yyvs1 = yyvs;
- yytype_int16 *yyss1 = yyss;
-
-
- /* Each stack pointer address is followed by the size of the
- data in use in that stack, in bytes. This used to be a
- conditional around just the two extra args, but that might
- be undefined if yyoverflow is a macro. */
- yyoverflow (YY_("memory exhausted"),
- &yyss1, yysize * sizeof (*yyssp),
- &yyvs1, yysize * sizeof (*yyvsp),
-
- &yystacksize);
-
- yyss = yyss1;
- yyvs = yyvs1;
- }
-#else /* no yyoverflow */
-# ifndef YYSTACK_RELOCATE
- goto yyexhaustedlab;
-# else
- /* Extend the stack our own way. */
- if (YYMAXDEPTH <= yystacksize)
- goto yyexhaustedlab;
- yystacksize *= 2;
- if (YYMAXDEPTH < yystacksize)
- yystacksize = YYMAXDEPTH;
-
- {
- yytype_int16 *yyss1 = yyss;
- union yyalloc *yyptr =
- (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));
- if (! yyptr)
- goto yyexhaustedlab;
- YYSTACK_RELOCATE (yyss);
- YYSTACK_RELOCATE (yyvs);
-
-# undef YYSTACK_RELOCATE
- if (yyss1 != yyssa)
- YYSTACK_FREE (yyss1);
- }
-# endif
-#endif /* no yyoverflow */
-
- yyssp = yyss + yysize - 1;
- yyvsp = yyvs + yysize - 1;
-
-
- YYDPRINTF ((stderr, "Stack size increased to %lu\n",
- (unsigned long int) yystacksize));
-
- if (yyss + yystacksize - 1 <= yyssp)
- YYABORT;
- }
-
- YYDPRINTF ((stderr, "Entering state %d\n", yystate));
-
- if (yystate == YYFINAL)
- YYACCEPT;
-
- goto yybackup;
-
-/*-----------.
-| yybackup. |
-`-----------*/
-yybackup:
-
- /* Do appropriate processing given the current state. Read a
- lookahead token if we need one and don't already have one. */
-
- /* First try to decide what to do without reference to lookahead token. */
- yyn = yypact[yystate];
- if (yyn == YYPACT_NINF)
- goto yydefault;
-
- /* Not known => get a lookahead token if don't already have one. */
-
- /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */
- if (yychar == YYEMPTY)
- {
- YYDPRINTF ((stderr, "Reading a token: "));
- yychar = YYLEX;
- }
-
- if (yychar <= YYEOF)
- {
- yychar = yytoken = YYEOF;
- YYDPRINTF ((stderr, "Now at end of input.\n"));
- }
- else
- {
- yytoken = YYTRANSLATE (yychar);
- YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc);
- }
-
- /* If the proper action on seeing token YYTOKEN is to reduce or to
- detect an error, take that action. */
- yyn += yytoken;
- if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken)
- goto yydefault;
- yyn = yytable[yyn];
- if (yyn <= 0)
- {
- if (yyn == 0 || yyn == YYTABLE_NINF)
- goto yyerrlab;
- yyn = -yyn;
- goto yyreduce;
- }
-
- /* Count tokens shifted since error; after three, turn off error
- status. */
- if (yyerrstatus)
- yyerrstatus--;
-
- /* Shift the lookahead token. */
- YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc);
-
- /* Discard the shifted token. */
- yychar = YYEMPTY;
-
- yystate = yyn;
- *++yyvsp = yylval;
-
- goto yynewstate;
-
-
-/*-----------------------------------------------------------.
-| yydefault -- do the default action for the current state. |
-`-----------------------------------------------------------*/
-yydefault:
- yyn = yydefact[yystate];
- if (yyn == 0)
- goto yyerrlab;
- goto yyreduce;
-
-
-/*-----------------------------.
-| yyreduce -- Do a reduction. |
-`-----------------------------*/
-yyreduce:
- /* yyn is the number of a rule to reduce with. */
- yylen = yyr2[yyn];
-
- /* If YYLEN is nonzero, implement the default value of the action:
- `$$ = $1'.
-
- Otherwise, the following line sets YYVAL to garbage.
- This behavior is undocumented and Bison
- users should not rely upon it. Assigning to YYVAL
- unconditionally makes the parser a bit smaller, and it avoids a
- GCC warning that YYVAL may be used uninitialized. */
- yyval = yyvsp[1-yylen];
-
-
- YY_REDUCE_PRINT (yyn);
- switch (yyn)
- {
- case 4:
-/* Line 1269 of yacc.c. */
-#line 246 "getdate.y"
- {
- pc->seconds = (yyvsp[(2) - (2)].timespec);
- pc->timespec_seen = true;
- }
- break;
-
- case 7:
-/* Line 1269 of yacc.c. */
-#line 259 "getdate.y"
- { pc->times_seen++; }
- break;
-
- case 8:
-/* Line 1269 of yacc.c. */
-#line 261 "getdate.y"
- { pc->local_zones_seen++; }
- break;
-
- case 9:
-/* Line 1269 of yacc.c. */
-#line 263 "getdate.y"
- { pc->zones_seen++; }
- break;
-
- case 10:
-/* Line 1269 of yacc.c. */
-#line 265 "getdate.y"
- { pc->dates_seen++; }
- break;
-
- case 11:
-/* Line 1269 of yacc.c. */
-#line 267 "getdate.y"
- { pc->days_seen++; }
- break;
-
- case 12:
-/* Line 1269 of yacc.c. */
-#line 269 "getdate.y"
- { pc->rels_seen = true; }
- break;
-
- case 14:
-/* Line 1269 of yacc.c. */
-#line 275 "getdate.y"
- {
- pc->hour = (yyvsp[(1) - (2)].textintval).value;
- pc->minutes = 0;
- pc->seconds.tv_sec = 0;
- pc->seconds.tv_nsec = 0;
- pc->meridian = (yyvsp[(2) - (2)].intval);
- }
- break;
-
- case 15:
-/* Line 1269 of yacc.c. */
-#line 283 "getdate.y"
- {
- pc->hour = (yyvsp[(1) - (4)].textintval).value;
- pc->minutes = (yyvsp[(3) - (4)].textintval).value;
- pc->seconds.tv_sec = 0;
- pc->seconds.tv_nsec = 0;
- pc->meridian = (yyvsp[(4) - (4)].intval);
- }
- break;
-
- case 16:
-/* Line 1269 of yacc.c. */
-#line 291 "getdate.y"
- {
- pc->hour = (yyvsp[(1) - (5)].textintval).value;
- pc->minutes = (yyvsp[(3) - (5)].textintval).value;
- pc->seconds.tv_sec = 0;
- pc->seconds.tv_nsec = 0;
- pc->meridian = MER24;
- pc->zones_seen++;
- pc->time_zone = time_zone_hhmm ((yyvsp[(4) - (5)].textintval), (yyvsp[(5) - (5)].intval));
- }
- break;
-
- case 17:
-/* Line 1269 of yacc.c. */
-#line 301 "getdate.y"
- {
- pc->hour = (yyvsp[(1) - (6)].textintval).value;
- pc->minutes = (yyvsp[(3) - (6)].textintval).value;
- pc->seconds = (yyvsp[(5) - (6)].timespec);
- pc->meridian = (yyvsp[(6) - (6)].intval);
- }
- break;
-
- case 18:
-/* Line 1269 of yacc.c. */
-#line 308 "getdate.y"
- {
- pc->hour = (yyvsp[(1) - (7)].textintval).value;
- pc->minutes = (yyvsp[(3) - (7)].textintval).value;
- pc->seconds = (yyvsp[(5) - (7)].timespec);
- pc->meridian = MER24;
- pc->zones_seen++;
- pc->time_zone = time_zone_hhmm ((yyvsp[(6) - (7)].textintval), (yyvsp[(7) - (7)].intval));
- }
- break;
-
- case 19:
-/* Line 1269 of yacc.c. */
-#line 320 "getdate.y"
- {
- pc->local_isdst = (yyvsp[(1) - (1)].intval);
- pc->dsts_seen += (0 < (yyvsp[(1) - (1)].intval));
- }
- break;
-
- case 20:
-/* Line 1269 of yacc.c. */
-#line 325 "getdate.y"
- {
- pc->local_isdst = 1;
- pc->dsts_seen += (0 < (yyvsp[(1) - (2)].intval)) + 1;
- }
- break;
-
- case 21:
-/* Line 1269 of yacc.c. */
-#line 333 "getdate.y"
- { pc->time_zone = (yyvsp[(1) - (1)].intval); }
- break;
-
- case 22:
-/* Line 1269 of yacc.c. */
-#line 335 "getdate.y"
- { pc->time_zone = (yyvsp[(1) - (2)].intval);
- pc->rel.ns += (yyvsp[(2) - (2)].rel).ns;
- pc->rel.seconds += (yyvsp[(2) - (2)].rel).seconds;
- pc->rel.minutes += (yyvsp[(2) - (2)].rel).minutes;
- pc->rel.hour += (yyvsp[(2) - (2)].rel).hour;
- pc->rel.day += (yyvsp[(2) - (2)].rel).day;
- pc->rel.month += (yyvsp[(2) - (2)].rel).month;
- pc->rel.year += (yyvsp[(2) - (2)].rel).year;
- pc->rels_seen = true; }
- break;
-
- case 23:
-/* Line 1269 of yacc.c. */
-#line 345 "getdate.y"
- { pc->time_zone = (yyvsp[(1) - (3)].intval) + time_zone_hhmm ((yyvsp[(2) - (3)].textintval), (yyvsp[(3) - (3)].intval)); }
- break;
-
- case 24:
-/* Line 1269 of yacc.c. */
-#line 347 "getdate.y"
- { pc->time_zone = (yyvsp[(1) - (1)].intval) + 60; }
- break;
-
- case 25:
-/* Line 1269 of yacc.c. */
-#line 349 "getdate.y"
- { pc->time_zone = (yyvsp[(1) - (2)].intval) + 60; }
- break;
-
- case 26:
-/* Line 1269 of yacc.c. */
-#line 354 "getdate.y"
- {
- pc->day_ordinal = 1;
- pc->day_number = (yyvsp[(1) - (1)].intval);
- }
- break;
-
- case 27:
-/* Line 1269 of yacc.c. */
-#line 359 "getdate.y"
- {
- pc->day_ordinal = 1;
- pc->day_number = (yyvsp[(1) - (2)].intval);
- }
- break;
-
- case 28:
-/* Line 1269 of yacc.c. */
-#line 364 "getdate.y"
- {
- pc->day_ordinal = (yyvsp[(1) - (2)].intval);
- pc->day_number = (yyvsp[(2) - (2)].intval);
- }
- break;
-
- case 29:
-/* Line 1269 of yacc.c. */
-#line 369 "getdate.y"
- {
- pc->day_ordinal = (yyvsp[(1) - (2)].textintval).value;
- pc->day_number = (yyvsp[(2) - (2)].intval);
- }
- break;
-
- case 30:
-/* Line 1269 of yacc.c. */
-#line 377 "getdate.y"
- {
- pc->month = (yyvsp[(1) - (3)].textintval).value;
- pc->day = (yyvsp[(3) - (3)].textintval).value;
- }
- break;
-
- case 31:
-/* Line 1269 of yacc.c. */
-#line 382 "getdate.y"
- {
- /* Interpret as YYYY/MM/DD if the first value has 4 or more digits,
- otherwise as MM/DD/YY.
- The goal in recognizing YYYY/MM/DD is solely to support legacy
- machine-generated dates like those in an RCS log listing. If
- you want portability, use the ISO 8601 format. */
- if (4 <= (yyvsp[(1) - (5)].textintval).digits)
- {
- pc->year = (yyvsp[(1) - (5)].textintval);
- pc->month = (yyvsp[(3) - (5)].textintval).value;
- pc->day = (yyvsp[(5) - (5)].textintval).value;
- }
- else
- {
- pc->month = (yyvsp[(1) - (5)].textintval).value;
- pc->day = (yyvsp[(3) - (5)].textintval).value;
- pc->year = (yyvsp[(5) - (5)].textintval);
- }
- }
- break;
-
- case 32:
-/* Line 1269 of yacc.c. */
-#line 402 "getdate.y"
- {
- /* ISO 8601 format. YYYY-MM-DD. */
- pc->year = (yyvsp[(1) - (3)].textintval);
- pc->month = -(yyvsp[(2) - (3)].textintval).value;
- pc->day = -(yyvsp[(3) - (3)].textintval).value;
- }
- break;
-
- case 33:
-/* Line 1269 of yacc.c. */
-#line 409 "getdate.y"
- {
- /* e.g. 17-JUN-1992. */
- pc->day = (yyvsp[(1) - (3)].textintval).value;
- pc->month = (yyvsp[(2) - (3)].intval);
- pc->year.value = -(yyvsp[(3) - (3)].textintval).value;
- pc->year.digits = (yyvsp[(3) - (3)].textintval).digits;
- }
- break;
-
- case 34:
-/* Line 1269 of yacc.c. */
-#line 417 "getdate.y"
- {
- /* e.g. JUN-17-1992. */
- pc->month = (yyvsp[(1) - (3)].intval);
- pc->day = -(yyvsp[(2) - (3)].textintval).value;
- pc->year.value = -(yyvsp[(3) - (3)].textintval).value;
- pc->year.digits = (yyvsp[(3) - (3)].textintval).digits;
- }
- break;
-
- case 35:
-/* Line 1269 of yacc.c. */
-#line 425 "getdate.y"
- {
- pc->month = (yyvsp[(1) - (2)].intval);
- pc->day = (yyvsp[(2) - (2)].textintval).value;
- }
- break;
-
- case 36:
-/* Line 1269 of yacc.c. */
-#line 430 "getdate.y"
- {
- pc->month = (yyvsp[(1) - (4)].intval);
- pc->day = (yyvsp[(2) - (4)].textintval).value;
- pc->year = (yyvsp[(4) - (4)].textintval);
- }
- break;
-
- case 37:
-/* Line 1269 of yacc.c. */
-#line 436 "getdate.y"
- {
- pc->day = (yyvsp[(1) - (2)].textintval).value;
- pc->month = (yyvsp[(2) - (2)].intval);
- }
- break;
-
- case 38:
-/* Line 1269 of yacc.c. */
-#line 441 "getdate.y"
- {
- pc->day = (yyvsp[(1) - (3)].textintval).value;
- pc->month = (yyvsp[(2) - (3)].intval);
- pc->year = (yyvsp[(3) - (3)].textintval);
- }
- break;
-
- case 39:
-/* Line 1269 of yacc.c. */
-#line 450 "getdate.y"
- {
- pc->rel.ns -= (yyvsp[(1) - (2)].rel).ns;
- pc->rel.seconds -= (yyvsp[(1) - (2)].rel).seconds;
- pc->rel.minutes -= (yyvsp[(1) - (2)].rel).minutes;
- pc->rel.hour -= (yyvsp[(1) - (2)].rel).hour;
- pc->rel.day -= (yyvsp[(1) - (2)].rel).day;
- pc->rel.month -= (yyvsp[(1) - (2)].rel).month;
- pc->rel.year -= (yyvsp[(1) - (2)].rel).year;
- }
- break;
-
- case 40:
-/* Line 1269 of yacc.c. */
-#line 460 "getdate.y"
- {
- pc->rel.ns += (yyvsp[(1) - (1)].rel).ns;
- pc->rel.seconds += (yyvsp[(1) - (1)].rel).seconds;
- pc->rel.minutes += (yyvsp[(1) - (1)].rel).minutes;
- pc->rel.hour += (yyvsp[(1) - (1)].rel).hour;
- pc->rel.day += (yyvsp[(1) - (1)].rel).day;
- pc->rel.month += (yyvsp[(1) - (1)].rel).month;
- pc->rel.year += (yyvsp[(1) - (1)].rel).year;
- }
- break;
-
- case 41:
-/* Line 1269 of yacc.c. */
-#line 473 "getdate.y"
- { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).year = (yyvsp[(1) - (2)].intval); }
- break;
-
- case 42:
-/* Line 1269 of yacc.c. */
-#line 475 "getdate.y"
- { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).year = (yyvsp[(1) - (2)].textintval).value; }
- break;
-
- case 43:
-/* Line 1269 of yacc.c. */
-#line 477 "getdate.y"
- { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).year = 1; }
- break;
-
- case 44:
-/* Line 1269 of yacc.c. */
-#line 479 "getdate.y"
- { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).month = (yyvsp[(1) - (2)].intval); }
- break;
-
- case 45:
-/* Line 1269 of yacc.c. */
-#line 481 "getdate.y"
- { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).month = (yyvsp[(1) - (2)].textintval).value; }
- break;
-
- case 46:
-/* Line 1269 of yacc.c. */
-#line 483 "getdate.y"
- { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).month = 1; }
- break;
-
- case 47:
-/* Line 1269 of yacc.c. */
-#line 485 "getdate.y"
- { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).day = (yyvsp[(1) - (2)].intval) * (yyvsp[(2) - (2)].intval); }
- break;
-
- case 48:
-/* Line 1269 of yacc.c. */
-#line 487 "getdate.y"
- { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).day = (yyvsp[(1) - (2)].textintval).value * (yyvsp[(2) - (2)].intval); }
- break;
-
- case 49:
-/* Line 1269 of yacc.c. */
-#line 489 "getdate.y"
- { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).day = (yyvsp[(1) - (1)].intval); }
- break;
-
- case 50:
-/* Line 1269 of yacc.c. */
-#line 491 "getdate.y"
- { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).hour = (yyvsp[(1) - (2)].intval); }
- break;
-
- case 51:
-/* Line 1269 of yacc.c. */
-#line 493 "getdate.y"
- { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).hour = (yyvsp[(1) - (2)].textintval).value; }
- break;
-
- case 52:
-/* Line 1269 of yacc.c. */
-#line 495 "getdate.y"
- { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).hour = 1; }
- break;
-
- case 53:
-/* Line 1269 of yacc.c. */
-#line 497 "getdate.y"
- { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).minutes = (yyvsp[(1) - (2)].intval); }
- break;
-
- case 54:
-/* Line 1269 of yacc.c. */
-#line 499 "getdate.y"
- { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).minutes = (yyvsp[(1) - (2)].textintval).value; }
- break;
-
- case 55:
-/* Line 1269 of yacc.c. */
-#line 501 "getdate.y"
- { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).minutes = 1; }
- break;
-
- case 56:
-/* Line 1269 of yacc.c. */
-#line 503 "getdate.y"
- { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).seconds = (yyvsp[(1) - (2)].intval); }
- break;
-
- case 57:
-/* Line 1269 of yacc.c. */
-#line 505 "getdate.y"
- { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).seconds = (yyvsp[(1) - (2)].textintval).value; }
- break;
-
- case 58:
-/* Line 1269 of yacc.c. */
-#line 507 "getdate.y"
- { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).seconds = (yyvsp[(1) - (2)].timespec).tv_sec; (yyval.rel).ns = (yyvsp[(1) - (2)].timespec).tv_nsec; }
- break;
-
- case 59:
-/* Line 1269 of yacc.c. */
-#line 509 "getdate.y"
- { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).seconds = (yyvsp[(1) - (2)].timespec).tv_sec; (yyval.rel).ns = (yyvsp[(1) - (2)].timespec).tv_nsec; }
- break;
-
- case 60:
-/* Line 1269 of yacc.c. */
-#line 511 "getdate.y"
- { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).seconds = 1; }
- break;
-
- case 62:
-/* Line 1269 of yacc.c. */
-#line 517 "getdate.y"
- { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).year = (yyvsp[(1) - (2)].textintval).value; }
- break;
-
- case 63:
-/* Line 1269 of yacc.c. */
-#line 519 "getdate.y"
- { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).month = (yyvsp[(1) - (2)].textintval).value; }
- break;
-
- case 64:
-/* Line 1269 of yacc.c. */
-#line 521 "getdate.y"
- { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).day = (yyvsp[(1) - (2)].textintval).value * (yyvsp[(2) - (2)].intval); }
- break;
-
- case 65:
-/* Line 1269 of yacc.c. */
-#line 523 "getdate.y"
- { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).hour = (yyvsp[(1) - (2)].textintval).value; }
- break;
-
- case 66:
-/* Line 1269 of yacc.c. */
-#line 525 "getdate.y"
- { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).minutes = (yyvsp[(1) - (2)].textintval).value; }
- break;
-
- case 67:
-/* Line 1269 of yacc.c. */
-#line 527 "getdate.y"
- { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).seconds = (yyvsp[(1) - (2)].textintval).value; }
- break;
-
- case 71:
-/* Line 1269 of yacc.c. */
-#line 535 "getdate.y"
- { (yyval.timespec).tv_sec = (yyvsp[(1) - (1)].textintval).value; (yyval.timespec).tv_nsec = 0; }
- break;
-
- case 73:
-/* Line 1269 of yacc.c. */
-#line 541 "getdate.y"
- { (yyval.timespec).tv_sec = (yyvsp[(1) - (1)].textintval).value; (yyval.timespec).tv_nsec = 0; }
- break;
-
- case 74:
-/* Line 1269 of yacc.c. */
-#line 546 "getdate.y"
- {
- if (pc->dates_seen && ! pc->year.digits
- && ! pc->rels_seen && (pc->times_seen || 2 < (yyvsp[(1) - (1)].textintval).digits))
- pc->year = (yyvsp[(1) - (1)].textintval);
- else
- {
- if (4 < (yyvsp[(1) - (1)].textintval).digits)
- {
- pc->dates_seen++;
- pc->day = (yyvsp[(1) - (1)].textintval).value % 100;
- pc->month = ((yyvsp[(1) - (1)].textintval).value / 100) % 100;
- pc->year.value = (yyvsp[(1) - (1)].textintval).value / 10000;
- pc->year.digits = (yyvsp[(1) - (1)].textintval).digits - 4;
- }
- else
- {
- pc->times_seen++;
- if ((yyvsp[(1) - (1)].textintval).digits <= 2)
- {
- pc->hour = (yyvsp[(1) - (1)].textintval).value;
- pc->minutes = 0;
- }
- else
- {
- pc->hour = (yyvsp[(1) - (1)].textintval).value / 100;
- pc->minutes = (yyvsp[(1) - (1)].textintval).value % 100;
- }
- pc->seconds.tv_sec = 0;
- pc->seconds.tv_nsec = 0;
- pc->meridian = MER24;
- }
- }
- }
- break;
-
- case 75:
-/* Line 1269 of yacc.c. */
-#line 583 "getdate.y"
- { (yyval.intval) = -1; }
- break;
-
- case 76:
-/* Line 1269 of yacc.c. */
-#line 585 "getdate.y"
- { (yyval.intval) = (yyvsp[(2) - (2)].textintval).value; }
- break;
-
- case 77:
-/* Line 1269 of yacc.c. */
-#line 590 "getdate.y"
- { (yyval.intval) = MER24; }
- break;
-
- case 78:
-/* Line 1269 of yacc.c. */
-#line 592 "getdate.y"
- { (yyval.intval) = (yyvsp[(1) - (1)].intval); }
- break;
-
-
-/* Line 1269 of yacc.c. */
-#line 2221 "getdate.c"
- default: break;
- }
- YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc);
-
- YYPOPSTACK (yylen);
- yylen = 0;
- YY_STACK_PRINT (yyss, yyssp);
-
- *++yyvsp = yyval;
-
-
- /* Now `shift' the result of the reduction. Determine what state
- that goes to, based on the state we popped back to and the rule
- number reduced by. */
-
- yyn = yyr1[yyn];
-
- yystate = yypgoto[yyn - YYNTOKENS] + *yyssp;
- if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp)
- yystate = yytable[yystate];
- else
- yystate = yydefgoto[yyn - YYNTOKENS];
-
- goto yynewstate;
-
-
-/*------------------------------------.
-| yyerrlab -- here on detecting error |
-`------------------------------------*/
-yyerrlab:
- /* If not already recovering from an error, report this error. */
- if (!yyerrstatus)
- {
- ++yynerrs;
-#if ! YYERROR_VERBOSE
- yyerror (pc, YY_("syntax error"));
-#else
- {
- YYSIZE_T yysize = yysyntax_error (0, yystate, yychar);
- if (yymsg_alloc < yysize && yymsg_alloc < YYSTACK_ALLOC_MAXIMUM)
- {
- YYSIZE_T yyalloc = 2 * yysize;
- if (! (yysize <= yyalloc && yyalloc <= YYSTACK_ALLOC_MAXIMUM))
- yyalloc = YYSTACK_ALLOC_MAXIMUM;
- if (yymsg != yymsgbuf)
- YYSTACK_FREE (yymsg);
- yymsg = (char *) YYSTACK_ALLOC (yyalloc);
- if (yymsg)
- yymsg_alloc = yyalloc;
- else
- {
- yymsg = yymsgbuf;
- yymsg_alloc = sizeof yymsgbuf;
- }
- }
-
- if (0 < yysize && yysize <= yymsg_alloc)
- {
- (void) yysyntax_error (yymsg, yystate, yychar);
- yyerror (pc, yymsg);
- }
- else
- {
- yyerror (pc, YY_("syntax error"));
- if (yysize != 0)
- goto yyexhaustedlab;
- }
- }
-#endif
- }
-
-
-
- if (yyerrstatus == 3)
- {
- /* If just tried and failed to reuse lookahead token after an
- error, discard it. */
-
- if (yychar <= YYEOF)
- {
- /* Return failure if at end of input. */
- if (yychar == YYEOF)
- YYABORT;
- }
- else
- {
- yydestruct ("Error: discarding",
- yytoken, &yylval, pc);
- yychar = YYEMPTY;
- }
- }
-
- /* Else will try to reuse lookahead token after shifting the error
- token. */
- goto yyerrlab1;
-
-
-/*---------------------------------------------------.
-| yyerrorlab -- error raised explicitly by YYERROR. |
-`---------------------------------------------------*/
-yyerrorlab:
-
- /* Pacify compilers like GCC when the user code never invokes
- YYERROR and the label yyerrorlab therefore never appears in user
- code. */
- if (/*CONSTCOND*/ 0)
- goto yyerrorlab;
-
- /* Do not reclaim the symbols of the rule which action triggered
- this YYERROR. */
- YYPOPSTACK (yylen);
- yylen = 0;
- YY_STACK_PRINT (yyss, yyssp);
- yystate = *yyssp;
- goto yyerrlab1;
-
-
-/*-------------------------------------------------------------.
-| yyerrlab1 -- common code for both syntax error and YYERROR. |
-`-------------------------------------------------------------*/
-yyerrlab1:
- yyerrstatus = 3; /* Each real token shifted decrements this. */
-
- for (;;)
- {
- yyn = yypact[yystate];
- if (yyn != YYPACT_NINF)
- {
- yyn += YYTERROR;
- if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR)
- {
- yyn = yytable[yyn];
- if (0 < yyn)
- break;
- }
- }
-
- /* Pop the current state because it cannot handle the error token. */
- if (yyssp == yyss)
- YYABORT;
-
-
- yydestruct ("Error: popping",
- yystos[yystate], yyvsp, pc);
- YYPOPSTACK (1);
- yystate = *yyssp;
- YY_STACK_PRINT (yyss, yyssp);
- }
-
- *++yyvsp = yylval;
-
-
- /* Shift the error token. */
- YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp);
-
- yystate = yyn;
- goto yynewstate;
-
-
-/*-------------------------------------.
-| yyacceptlab -- YYACCEPT comes here. |
-`-------------------------------------*/
-yyacceptlab:
- yyresult = 0;
- goto yyreturn;
-
-/*-----------------------------------.
-| yyabortlab -- YYABORT comes here. |
-`-----------------------------------*/
-yyabortlab:
- yyresult = 1;
- goto yyreturn;
-
-#ifndef yyoverflow
-/*-------------------------------------------------.
-| yyexhaustedlab -- memory exhaustion comes here. |
-`-------------------------------------------------*/
-yyexhaustedlab:
- yyerror (pc, YY_("memory exhausted"));
- yyresult = 2;
- /* Fall through. */
-#endif
-
-yyreturn:
- if (yychar != YYEMPTY)
- yydestruct ("Cleanup: discarding lookahead",
- yytoken, &yylval, pc);
- /* Do not reclaim the symbols of the rule which action triggered
- this YYABORT or YYACCEPT. */
- YYPOPSTACK (yylen);
- YY_STACK_PRINT (yyss, yyssp);
- while (yyssp != yyss)
- {
- yydestruct ("Cleanup: popping",
- yystos[*yyssp], yyvsp, pc);
- YYPOPSTACK (1);
- }
-#ifndef yyoverflow
- if (yyss != yyssa)
- YYSTACK_FREE (yyss);
-#endif
-#if YYERROR_VERBOSE
- if (yymsg != yymsgbuf)
- YYSTACK_FREE (yymsg);
-#endif
- /* Make sure YYID is used. */
- return YYID (yyresult);
-}
-
-
-/* Line 1486 of yacc.c. */
-#line 595 "getdate.y"
-
-
-static table const meridian_table[] =
-{
- { "AM", tMERIDIAN, MERam },
- { "A.M.", tMERIDIAN, MERam },
- { "PM", tMERIDIAN, MERpm },
- { "P.M.", tMERIDIAN, MERpm },
- { NULL, 0, 0 }
-};
-
-static table const dst_table[] =
-{
- { "DST", tDST, 0 }
-};
-
-static table const month_and_day_table[] =
-{
- { "JANUARY", tMONTH, 1 },
- { "FEBRUARY", tMONTH, 2 },
- { "MARCH", tMONTH, 3 },
- { "APRIL", tMONTH, 4 },
- { "MAY", tMONTH, 5 },
- { "JUNE", tMONTH, 6 },
- { "JULY", tMONTH, 7 },
- { "AUGUST", tMONTH, 8 },
- { "SEPTEMBER",tMONTH, 9 },
- { "SEPT", tMONTH, 9 },
- { "OCTOBER", tMONTH, 10 },
- { "NOVEMBER", tMONTH, 11 },
- { "DECEMBER", tMONTH, 12 },
- { "SUNDAY", tDAY, 0 },
- { "MONDAY", tDAY, 1 },
- { "TUESDAY", tDAY, 2 },
- { "TUES", tDAY, 2 },
- { "WEDNESDAY",tDAY, 3 },
- { "WEDNES", tDAY, 3 },
- { "THURSDAY", tDAY, 4 },
- { "THUR", tDAY, 4 },
- { "THURS", tDAY, 4 },
- { "FRIDAY", tDAY, 5 },
- { "SATURDAY", tDAY, 6 },
- { NULL, 0, 0 }
-};
-
-static table const time_units_table[] =
-{
- { "YEAR", tYEAR_UNIT, 1 },
- { "MONTH", tMONTH_UNIT, 1 },
- { "FORTNIGHT",tDAY_UNIT, 14 },
- { "WEEK", tDAY_UNIT, 7 },
- { "DAY", tDAY_UNIT, 1 },
- { "HOUR", tHOUR_UNIT, 1 },
- { "MINUTE", tMINUTE_UNIT, 1 },
- { "MIN", tMINUTE_UNIT, 1 },
- { "SECOND", tSEC_UNIT, 1 },
- { "SEC", tSEC_UNIT, 1 },
- { NULL, 0, 0 }
-};
-
-/* Assorted relative-time words. */
-static table const relative_time_table[] =
-{
- { "TOMORROW", tDAY_UNIT, 1 },
- { "YESTERDAY",tDAY_UNIT, -1 },
- { "TODAY", tDAY_UNIT, 0 },
- { "NOW", tDAY_UNIT, 0 },
- { "LAST", tORDINAL, -1 },
- { "THIS", tORDINAL, 0 },
- { "NEXT", tORDINAL, 1 },
- { "FIRST", tORDINAL, 1 },
-/*{ "SECOND", tORDINAL, 2 }, */
- { "THIRD", tORDINAL, 3 },
- { "FOURTH", tORDINAL, 4 },
- { "FIFTH", tORDINAL, 5 },
- { "SIXTH", tORDINAL, 6 },
- { "SEVENTH", tORDINAL, 7 },
- { "EIGHTH", tORDINAL, 8 },
- { "NINTH", tORDINAL, 9 },
- { "TENTH", tORDINAL, 10 },
- { "ELEVENTH", tORDINAL, 11 },
- { "TWELFTH", tORDINAL, 12 },
- { "AGO", tAGO, 1 },
- { NULL, 0, 0 }
-};
-
-/* The universal time zone table. These labels can be used even for
- time stamps that would not otherwise be valid, e.g., GMT time
- stamps in London during summer. */
-static table const universal_time_zone_table[] =
-{
- { "GMT", tZONE, HOUR ( 0) }, /* Greenwich Mean */
- { "UT", tZONE, HOUR ( 0) }, /* Universal (Coordinated) */
- { "UTC", tZONE, HOUR ( 0) },
- { NULL, 0, 0 }
-};
-
-/* The time zone table. This table is necessarily incomplete, as time
- zone abbreviations are ambiguous; e.g. Australians interpret "EST"
- as Eastern time in Australia, not as US Eastern Standard Time.
- You cannot rely on getdate to handle arbitrary time zone
- abbreviations; use numeric abbreviations like `-0500' instead. */
-static table const time_zone_table[] =
-{
- { "WET", tZONE, HOUR ( 0) }, /* Western European */
- { "WEST", tDAYZONE, HOUR ( 0) }, /* Western European Summer */
- { "BST", tDAYZONE, HOUR ( 0) }, /* British Summer */
- { "ART", tZONE, -HOUR ( 3) }, /* Argentina */
- { "BRT", tZONE, -HOUR ( 3) }, /* Brazil */
- { "BRST", tDAYZONE, -HOUR ( 3) }, /* Brazil Summer */
- { "NST", tZONE, -(HOUR ( 3) + 30) }, /* Newfoundland Standard */
- { "NDT", tDAYZONE,-(HOUR ( 3) + 30) }, /* Newfoundland Daylight */
- { "AST", tZONE, -HOUR ( 4) }, /* Atlantic Standard */
- { "ADT", tDAYZONE, -HOUR ( 4) }, /* Atlantic Daylight */
- { "CLT", tZONE, -HOUR ( 4) }, /* Chile */
- { "CLST", tDAYZONE, -HOUR ( 4) }, /* Chile Summer */
- { "EST", tZONE, -HOUR ( 5) }, /* Eastern Standard */
- { "EDT", tDAYZONE, -HOUR ( 5) }, /* Eastern Daylight */
- { "CST", tZONE, -HOUR ( 6) }, /* Central Standard */
- { "CDT", tDAYZONE, -HOUR ( 6) }, /* Central Daylight */
- { "MST", tZONE, -HOUR ( 7) }, /* Mountain Standard */
- { "MDT", tDAYZONE, -HOUR ( 7) }, /* Mountain Daylight */
- { "PST", tZONE, -HOUR ( 8) }, /* Pacific Standard */
- { "PDT", tDAYZONE, -HOUR ( 8) }, /* Pacific Daylight */
- { "AKST", tZONE, -HOUR ( 9) }, /* Alaska Standard */
- { "AKDT", tDAYZONE, -HOUR ( 9) }, /* Alaska Daylight */
- { "HST", tZONE, -HOUR (10) }, /* Hawaii Standard */
- { "HAST", tZONE, -HOUR (10) }, /* Hawaii-Aleutian Standard */
- { "HADT", tDAYZONE, -HOUR (10) }, /* Hawaii-Aleutian Daylight */
- { "SST", tZONE, -HOUR (12) }, /* Samoa Standard */
- { "WAT", tZONE, HOUR ( 1) }, /* West Africa */
- { "CET", tZONE, HOUR ( 1) }, /* Central European */
- { "CEST", tDAYZONE, HOUR ( 1) }, /* Central European Summer */
- { "MET", tZONE, HOUR ( 1) }, /* Middle European */
- { "MEZ", tZONE, HOUR ( 1) }, /* Middle European */
- { "MEST", tDAYZONE, HOUR ( 1) }, /* Middle European Summer */
- { "MESZ", tDAYZONE, HOUR ( 1) }, /* Middle European Summer */
- { "EET", tZONE, HOUR ( 2) }, /* Eastern European */
- { "EEST", tDAYZONE, HOUR ( 2) }, /* Eastern European Summer */
- { "CAT", tZONE, HOUR ( 2) }, /* Central Africa */
- { "SAST", tZONE, HOUR ( 2) }, /* South Africa Standard */
- { "EAT", tZONE, HOUR ( 3) }, /* East Africa */
- { "MSK", tZONE, HOUR ( 3) }, /* Moscow */
- { "MSD", tDAYZONE, HOUR ( 3) }, /* Moscow Daylight */
- { "IST", tZONE, (HOUR ( 5) + 30) }, /* India Standard */
- { "SGT", tZONE, HOUR ( 8) }, /* Singapore */
- { "KST", tZONE, HOUR ( 9) }, /* Korea Standard */
- { "JST", tZONE, HOUR ( 9) }, /* Japan Standard */
- { "GST", tZONE, HOUR (10) }, /* Guam Standard */
- { "NZST", tZONE, HOUR (12) }, /* New Zealand Standard */
- { "NZDT", tDAYZONE, HOUR (12) }, /* New Zealand Daylight */
- { NULL, 0, 0 }
-};
-
-/* Military time zone table. */
-static table const military_table[] =
-{
- { "A", tZONE, -HOUR ( 1) },
- { "B", tZONE, -HOUR ( 2) },
- { "C", tZONE, -HOUR ( 3) },
- { "D", tZONE, -HOUR ( 4) },
- { "E", tZONE, -HOUR ( 5) },
- { "F", tZONE, -HOUR ( 6) },
- { "G", tZONE, -HOUR ( 7) },
- { "H", tZONE, -HOUR ( 8) },
- { "I", tZONE, -HOUR ( 9) },
- { "K", tZONE, -HOUR (10) },
- { "L", tZONE, -HOUR (11) },
- { "M", tZONE, -HOUR (12) },
- { "N", tZONE, HOUR ( 1) },
- { "O", tZONE, HOUR ( 2) },
- { "P", tZONE, HOUR ( 3) },
- { "Q", tZONE, HOUR ( 4) },
- { "R", tZONE, HOUR ( 5) },
- { "S", tZONE, HOUR ( 6) },
- { "T", tZONE, HOUR ( 7) },
- { "U", tZONE, HOUR ( 8) },
- { "V", tZONE, HOUR ( 9) },
- { "W", tZONE, HOUR (10) },
- { "X", tZONE, HOUR (11) },
- { "Y", tZONE, HOUR (12) },
- { "Z", tZONE, HOUR ( 0) },
- { NULL, 0, 0 }
-};
-
-
-
-/* Convert a time zone expressed as HH:MM into an integer count of
- minutes. If MM is negative, then S is of the form HHMM and needs
- to be picked apart; otherwise, S is of the form HH. */
-
-static long int
-time_zone_hhmm (textint s, long int mm)
-{
- if (mm < 0)
- return (s.value / 100) * 60 + s.value % 100;
- else
- return s.value * 60 + (s.negative ? -mm : mm);
-}
-
-static int
-to_hour (long int hours, int meridian)
-{
- switch (meridian)
- {
- default: /* Pacify GCC. */
- case MER24:
- return 0 <= hours && hours < 24 ? hours : -1;
- case MERam:
- return 0 < hours && hours < 12 ? hours : hours == 12 ? 0 : -1;
- case MERpm:
- return 0 < hours && hours < 12 ? hours + 12 : hours == 12 ? 12 : -1;
- }
-}
-
-static long int
-to_year (textint textyear)
-{
- long int year = textyear.value;
-
- if (year < 0)
- year = -year;
-
- /* XPG4 suggests that years 00-68 map to 2000-2068, and
- years 69-99 map to 1969-1999. */
- else if (textyear.digits == 2)
- year += year < 69 ? 2000 : 1900;
-
- return year;
-}
-
-static table const *
-lookup_zone (parser_control const *pc, char const *name)
-{
- table const *tp;
-
- for (tp = universal_time_zone_table; tp->name; tp++)
- if (strcmp (name, tp->name) == 0)
- return tp;
-
- /* Try local zone abbreviations before those in time_zone_table, as
- the local ones are more likely to be right. */
- for (tp = pc->local_time_zone_table; tp->name; tp++)
- if (strcmp (name, tp->name) == 0)
- return tp;
-
- for (tp = time_zone_table; tp->name; tp++)
- if (strcmp (name, tp->name) == 0)
- return tp;
-
- return NULL;
-}
-
-#if ! HAVE_TM_GMTOFF
-/* Yield the difference between *A and *B,
- measured in seconds, ignoring leap seconds.
- The body of this function is taken directly from the GNU C Library;
- see src/strftime.c. */
-static long int
-tm_diff (struct tm const *a, struct tm const *b)
-{
- /* Compute intervening leap days correctly even if year is negative.
- Take care to avoid int overflow in leap day calculations. */
- int a4 = SHR (a->tm_year, 2) + SHR (TM_YEAR_BASE, 2) - ! (a->tm_year & 3);
- int b4 = SHR (b->tm_year, 2) + SHR (TM_YEAR_BASE, 2) - ! (b->tm_year & 3);
- int a100 = a4 / 25 - (a4 % 25 < 0);
- int b100 = b4 / 25 - (b4 % 25 < 0);
- int a400 = SHR (a100, 2);
- int b400 = SHR (b100, 2);
- int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
- long int ayear = a->tm_year;
- long int years = ayear - b->tm_year;
- long int days = (365 * years + intervening_leap_days
- + (a->tm_yday - b->tm_yday));
- return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
- + (a->tm_min - b->tm_min))
- + (a->tm_sec - b->tm_sec));
-}
-#endif /* ! HAVE_TM_GMTOFF */
-
-static table const *
-lookup_word (parser_control const *pc, char *word)
-{
- char *p;
- char *q;
- size_t wordlen;
- table const *tp;
- bool period_found;
- bool abbrev;
-
- /* Make it uppercase. */
- for (p = word; *p; p++)
- {
- unsigned char ch = *p;
- *p = toupper (ch);
- }
-
- for (tp = meridian_table; tp->name; tp++)
- if (strcmp (word, tp->name) == 0)
- return tp;
-
- /* See if we have an abbreviation for a month. */
- wordlen = strlen (word);
- abbrev = wordlen == 3 || (wordlen == 4 && word[3] == '.');
-
- for (tp = month_and_day_table; tp->name; tp++)
- if ((abbrev ? strncmp (word, tp->name, 3) : strcmp (word, tp->name)) == 0)
- return tp;
-
- if ((tp = lookup_zone (pc, word)))
- return tp;
-
- if (strcmp (word, dst_table[0].name) == 0)
- return dst_table;
-
- for (tp = time_units_table; tp->name; tp++)
- if (strcmp (word, tp->name) == 0)
- return tp;
-
- /* Strip off any plural and try the units table again. */
- if (word[wordlen - 1] == 'S')
- {
- word[wordlen - 1] = '\0';
- for (tp = time_units_table; tp->name; tp++)
- if (strcmp (word, tp->name) == 0)
- return tp;
- word[wordlen - 1] = 'S'; /* For "this" in relative_time_table. */
- }
-
- for (tp = relative_time_table; tp->name; tp++)
- if (strcmp (word, tp->name) == 0)
- return tp;
-
- /* Military time zones. */
- if (wordlen == 1)
- for (tp = military_table; tp->name; tp++)
- if (word[0] == tp->name[0])
- return tp;
-
- /* Drop out any periods and try the time zone table again. */
- for (period_found = false, p = q = word; (*p = *q); q++)
- if (*q == '.')
- period_found = true;
- else
- p++;
- if (period_found && (tp = lookup_zone (pc, word)))
- return tp;
-
- return NULL;
-}
-
-static int
-yylex (YYSTYPE *lvalp, parser_control *pc)
-{
- unsigned char c;
- size_t count;
-
- for (;;)
- {
- while (c = *pc->input, isspace (c))
- pc->input++;
-
- if (ISDIGIT (c) || c == '-' || c == '+')
- {
- char const *p;
- int sign;
- unsigned long int value;
- if (c == '-' || c == '+')
- {
- sign = c == '-' ? -1 : 1;
- while (c = *++pc->input, isspace (c))
- continue;
- if (! ISDIGIT (c))
- /* skip the '-' sign */
- continue;
- }
- else
- sign = 0;
- p = pc->input;
- for (value = 0; ; value *= 10)
- {
- unsigned long int value1 = value + (c - '0');
- if (value1 < value)
- return '?';
- value = value1;
- c = *++p;
- if (! ISDIGIT (c))
- break;
- if (ULONG_MAX / 10 < value)
- return '?';
- }
- if ((c == '.' || c == ',') && ISDIGIT (p[1]))
- {
- time_t s;
- int ns;
- int digits;
- unsigned long int value1;
-
- /* Check for overflow when converting value to time_t. */
- if (sign < 0)
- {
- s = - value;
- if (0 < s)
- return '?';
- value1 = -s;
- }
- else
- {
- s = value;
- if (s < 0)
- return '?';
- value1 = s;
- }
- if (value != value1)
- return '?';
-
- /* Accumulate fraction, to ns precision. */
- p++;
- ns = *p++ - '0';
- for (digits = 2; digits <= LOG10_BILLION; digits++)
- {
- ns *= 10;
- if (ISDIGIT (*p))
- ns += *p++ - '0';
- }
-
- /* Skip excess digits, truncating toward -Infinity. */
- if (sign < 0)
- for (; ISDIGIT (*p); p++)
- if (*p != '0')
- {
- ns++;
- break;
- }
- while (ISDIGIT (*p))
- p++;
-
- /* Adjust to the timespec convention, which is that
- tv_nsec is always a positive offset even if tv_sec is
- negative. */
- if (sign < 0 && ns)
- {
- s--;
- if (! (s < 0))
- return '?';
- ns = BILLION - ns;
- }
-
- lvalp->timespec.tv_sec = s;
- lvalp->timespec.tv_nsec = ns;
- pc->input = p;
- return sign ? tSDECIMAL_NUMBER : tUDECIMAL_NUMBER;
- }
- else
- {
- lvalp->textintval.negative = sign < 0;
- if (sign < 0)
- {
- lvalp->textintval.value = - value;
- if (0 < lvalp->textintval.value)
- return '?';
- }
- else
- {
- lvalp->textintval.value = value;
- if (lvalp->textintval.value < 0)
- return '?';
- }
- lvalp->textintval.digits = p - pc->input;
- pc->input = p;
- return sign ? tSNUMBER : tUNUMBER;
- }
- }
-
- if (isalpha (c))
- {
- char buff[20];
- char *p = buff;
- table const *tp;
-
- do
- {
- if (p < buff + sizeof buff - 1)
- *p++ = c;
- c = *++pc->input;
- }
- while (isalpha (c) || c == '.');
-
- *p = '\0';
- tp = lookup_word (pc, buff);
- if (! tp)
- return '?';
- lvalp->intval = tp->value;
- return tp->type;
- }
-
- if (c != '(')
- return *pc->input++;
- count = 0;
- do
- {
- c = *pc->input++;
- if (c == '\0')
- return c;
- if (c == '(')
- count++;
- else if (c == ')')
- count--;
- }
- while (count != 0);
- }
-}
-
-/* Do nothing if the parser reports an error. */
-static int
-yyerror (parser_control const *pc ATTRIBUTE_UNUSED,
- char const *s ATTRIBUTE_UNUSED)
-{
- return 0;
-}
-
-/* If *TM0 is the old and *TM1 is the new value of a struct tm after
- passing it to mktime, return true if it's OK that mktime returned T.
- It's not OK if *TM0 has out-of-range members. */
-
-static bool
-mktime_ok (struct tm const *tm0, struct tm const *tm1, time_t t)
-{
- if (t == (time_t) -1)
- {
- /* Guard against falsely reporting an error when parsing a time
- stamp that happens to equal (time_t) -1, on a host that
- supports such a time stamp. */
- tm1 = localtime (&t);
- if (!tm1)
- return false;
- }
-
- return ! ((tm0->tm_sec ^ tm1->tm_sec)
- | (tm0->tm_min ^ tm1->tm_min)
- | (tm0->tm_hour ^ tm1->tm_hour)
- | (tm0->tm_mday ^ tm1->tm_mday)
- | (tm0->tm_mon ^ tm1->tm_mon)
- | (tm0->tm_year ^ tm1->tm_year));
-}
-
-/* A reasonable upper bound for the size of ordinary TZ strings.
- Use heap allocation if TZ's length exceeds this. */
-enum { TZBUFSIZE = 100 };
-
-/* Return a copy of TZ, stored in TZBUF if it fits, and heap-allocated
- otherwise. */
-static char *
-get_tz (char tzbuf[TZBUFSIZE])
-{
- char *tz = getenv ("TZ");
- if (tz)
- {
- size_t tzsize = strlen (tz) + 1;
- tz = (tzsize <= TZBUFSIZE
- ? memcpy (tzbuf, tz, tzsize)
- : xmemdup (tz, tzsize));
- }
- return tz;
-}
-
-/* Parse a date/time string, storing the resulting time value into *RESULT.
- The string itself is pointed to by P. Return true if successful.
- P can be an incomplete or relative time specification; if so, use
- *NOW as the basis for the returned time. */
-bool
-get_date (struct timespec *result, char const *p, struct timespec const *now)
-{
- time_t Start;
- long int Start_ns;
- struct tm const *tmp;
- struct tm tm;
- struct tm tm0;
- parser_control pc;
- struct timespec gettime_buffer;
- unsigned char c;
- bool tz_was_altered = false;
- char *tz0 = NULL;
- char tz0buf[TZBUFSIZE];
- bool ok = true;
-
- if (! now)
- {
- gettime (&gettime_buffer);
- now = &gettime_buffer;
- }
-
- Start = now->tv_sec;
- Start_ns = now->tv_nsec;
-
- tmp = localtime (&now->tv_sec);
- if (! tmp)
- return false;
-
- while (c = *p, isspace (c))
- p++;
-
- if (strncmp (p, "TZ=\"", 4) == 0)
- {
- char const *tzbase = p + 4;
- size_t tzsize = 1;
- char const *s;
-
- for (s = tzbase; *s; s++, tzsize++)
- if (*s == '\\')
- {
- s++;
- if (! (*s == '\\' || *s == '"'))
- break;
- }
- else if (*s == '"')
- {
- char *z;
- char *tz1;
- char tz1buf[TZBUFSIZE];
- bool large_tz = TZBUFSIZE < tzsize;
- bool setenv_ok;
- tz0 = get_tz (tz0buf);
- z = tz1 = large_tz ? xmalloc (tzsize) : tz1buf;
- for (s = tzbase; *s != '"'; s++)
- *z++ = *(s += *s == '\\');
- *z = '\0';
- setenv_ok = setenv ("TZ", tz1, 1) == 0;
- if (large_tz)
- free (tz1);
- if (!setenv_ok)
- goto fail;
- tz_was_altered = true;
- p = s + 1;
- }
- }
-
- pc.input = p;
- pc.year.value = tmp->tm_year;
- pc.year.value += TM_YEAR_BASE;
- pc.year.digits = 0;
- pc.month = tmp->tm_mon + 1;
- pc.day = tmp->tm_mday;
- pc.hour = tmp->tm_hour;
- pc.minutes = tmp->tm_min;
- pc.seconds.tv_sec = tmp->tm_sec;
- pc.seconds.tv_nsec = Start_ns;
- tm.tm_isdst = tmp->tm_isdst;
-
- pc.meridian = MER24;
- pc.rel = RELATIVE_TIME_0;
- pc.timespec_seen = false;
- pc.rels_seen = false;
- pc.dates_seen = 0;
- pc.days_seen = 0;
- pc.times_seen = 0;
- pc.local_zones_seen = 0;
- pc.dsts_seen = 0;
- pc.zones_seen = 0;
-
-#if HAVE_STRUCT_TM_TM_ZONE
- pc.local_time_zone_table[0].name = tmp->tm_zone;
- pc.local_time_zone_table[0].type = tLOCAL_ZONE;
- pc.local_time_zone_table[0].value = tmp->tm_isdst;
- pc.local_time_zone_table[1].name = NULL;
-
- /* Probe the names used in the next three calendar quarters, looking
- for a tm_isdst different from the one we already have. */
- {
- int quarter;
- for (quarter = 1; quarter <= 3; quarter++)
- {
- time_t probe = Start + quarter * (90 * 24 * 60 * 60);
- struct tm const *probe_tm = localtime (&probe);
- if (probe_tm && probe_tm->tm_zone
- && probe_tm->tm_isdst != pc.local_time_zone_table[0].value)
- {
- {
- pc.local_time_zone_table[1].name = probe_tm->tm_zone;
- pc.local_time_zone_table[1].type = tLOCAL_ZONE;
- pc.local_time_zone_table[1].value = probe_tm->tm_isdst;
- pc.local_time_zone_table[2].name = NULL;
- }
- break;
- }
- }
- }
-#else
-#if HAVE_TZNAME
- {
-# ifndef tzname
- extern char *tzname[];
-# endif
- int i;
- for (i = 0; i < 2; i++)
- {
- pc.local_time_zone_table[i].name = tzname[i];
- pc.local_time_zone_table[i].type = tLOCAL_ZONE;
- pc.local_time_zone_table[i].value = i;
- }
- pc.local_time_zone_table[i].name = NULL;
- }
-#else
- pc.local_time_zone_table[0].name = NULL;
-#endif
-#endif
-
- if (pc.local_time_zone_table[0].name && pc.local_time_zone_table[1].name
- && ! strcmp (pc.local_time_zone_table[0].name,
- pc.local_time_zone_table[1].name))
- {
- /* This locale uses the same abbrevation for standard and
- daylight times. So if we see that abbreviation, we don't
- know whether it's daylight time. */
- pc.local_time_zone_table[0].value = -1;
- pc.local_time_zone_table[1].name = NULL;
- }
-
- if (yyparse (&pc) != 0)
- goto fail;
-
- if (pc.timespec_seen)
- *result = pc.seconds;
- else
- {
- if (1 < (pc.times_seen | pc.dates_seen | pc.days_seen | pc.dsts_seen
- | (pc.local_zones_seen + pc.zones_seen)))
- goto fail;
-
- tm.tm_year = to_year (pc.year) - TM_YEAR_BASE;
- tm.tm_mon = pc.month - 1;
- tm.tm_mday = pc.day;
- if (pc.times_seen || (pc.rels_seen && ! pc.dates_seen && ! pc.days_seen))
- {
- tm.tm_hour = to_hour (pc.hour, pc.meridian);
- if (tm.tm_hour < 0)
- goto fail;
- tm.tm_min = pc.minutes;
- tm.tm_sec = pc.seconds.tv_sec;
- }
- else
- {
- tm.tm_hour = tm.tm_min = tm.tm_sec = 0;
- pc.seconds.tv_nsec = 0;
- }
-
- /* Let mktime deduce tm_isdst if we have an absolute time stamp. */
- if (pc.dates_seen | pc.days_seen | pc.times_seen)
- tm.tm_isdst = -1;
-
- /* But if the input explicitly specifies local time with or without
- DST, give mktime that information. */
- if (pc.local_zones_seen)
- tm.tm_isdst = pc.local_isdst;
-
- tm0 = tm;
-
- Start = mktime (&tm);
-
- if (! mktime_ok (&tm0, &tm, Start))
- {
- if (! pc.zones_seen)
- goto fail;
- else
- {
- /* Guard against falsely reporting errors near the time_t
- boundaries when parsing times in other time zones. For
- example, suppose the input string "1969-12-31 23:00:00 -0100",
- the current time zone is 8 hours ahead of UTC, and the min
- time_t value is 1970-01-01 00:00:00 UTC. Then the min
- localtime value is 1970-01-01 08:00:00, and mktime will
- therefore fail on 1969-12-31 23:00:00. To work around the
- problem, set the time zone to 1 hour behind UTC temporarily
- by setting TZ="XXX1:00" and try mktime again. */
-
- long int time_zone = pc.time_zone;
- long int abs_time_zone = time_zone < 0 ? - time_zone : time_zone;
- long int abs_time_zone_hour = abs_time_zone / 60;
- int abs_time_zone_min = abs_time_zone % 60;
- char tz1buf[sizeof "XXX+0:00"
- + sizeof pc.time_zone * CHAR_BIT / 3];
- if (!tz_was_altered)
- tz0 = get_tz (tz0buf);
- sprintf (tz1buf, "XXX%s%ld:%02d", "-" + (time_zone < 0),
- abs_time_zone_hour, abs_time_zone_min);
- if (setenv ("TZ", tz1buf, 1) != 0)
- goto fail;
- tz_was_altered = true;
- tm = tm0;
- Start = mktime (&tm);
- if (! mktime_ok (&tm0, &tm, Start))
- goto fail;
- }
- }
-
- if (pc.days_seen && ! pc.dates_seen)
- {
- tm.tm_mday += ((pc.day_number - tm.tm_wday + 7) % 7
- + 7 * (pc.day_ordinal - (0 < pc.day_ordinal)));
- tm.tm_isdst = -1;
- Start = mktime (&tm);
- if (Start == (time_t) -1)
- goto fail;
- }
-
- if (pc.zones_seen)
- {
- long int delta = pc.time_zone * 60;
- time_t t1;
-#ifdef HAVE_TM_GMTOFF
- delta -= tm.tm_gmtoff;
-#else
- time_t t = Start;
- struct tm const *gmt = gmtime (&t);
- if (! gmt)
- goto fail;
- delta -= tm_diff (&tm, gmt);
-#endif
- t1 = Start - delta;
- if ((Start < t1) != (delta < 0))
- goto fail; /* time_t overflow */
- Start = t1;
- }
-
- /* Add relative date. */
- if (pc.rel.year | pc.rel.month | pc.rel.day)
- {
- int year = tm.tm_year + pc.rel.year;
- int month = tm.tm_mon + pc.rel.month;
- int day = tm.tm_mday + pc.rel.day;
- if (((year < tm.tm_year) ^ (pc.rel.year < 0))
- | ((month < tm.tm_mon) ^ (pc.rel.month < 0))
- | ((day < tm.tm_mday) ^ (pc.rel.day < 0)))
- goto fail;
- tm.tm_year = year;
- tm.tm_mon = month;
- tm.tm_mday = day;
- tm.tm_hour = tm0.tm_hour;
- tm.tm_min = tm0.tm_min;
- tm.tm_sec = tm0.tm_sec;
- tm.tm_isdst = tm0.tm_isdst;
- Start = mktime (&tm);
- if (Start == (time_t) -1)
- goto fail;
- }
-
- /* Add relative hours, minutes, and seconds. On hosts that support
- leap seconds, ignore the possibility of leap seconds; e.g.,
- "+ 10 minutes" adds 600 seconds, even if one of them is a
- leap second. Typically this is not what the user wants, but it's
- too hard to do it the other way, because the time zone indicator
- must be applied before relative times, and if mktime is applied
- again the time zone will be lost. */
- {
- long int sum_ns = pc.seconds.tv_nsec + pc.rel.ns;
- long int normalized_ns = (sum_ns % BILLION + BILLION) % BILLION;
- time_t t0 = Start;
- long int d1 = 60 * 60 * pc.rel.hour;
- time_t t1 = t0 + d1;
- long int d2 = 60 * pc.rel.minutes;
- time_t t2 = t1 + d2;
- long int d3 = pc.rel.seconds;
- time_t t3 = t2 + d3;
- long int d4 = (sum_ns - normalized_ns) / BILLION;
- time_t t4 = t3 + d4;
-
- if ((d1 / (60 * 60) ^ pc.rel.hour)
- | (d2 / 60 ^ pc.rel.minutes)
- | ((t1 < t0) ^ (d1 < 0))
- | ((t2 < t1) ^ (d2 < 0))
- | ((t3 < t2) ^ (d3 < 0))
- | ((t4 < t3) ^ (d4 < 0)))
- goto fail;
-
- result->tv_sec = t4;
- result->tv_nsec = normalized_ns;
- }
- }
-
- goto done;
-
- fail:
- ok = false;
- done:
- if (tz_was_altered)
- ok &= (tz0 ? setenv ("TZ", tz0, 1) : unsetenv ("TZ")) == 0;
- if (tz0 != tz0buf)
- free (tz0);
- return ok;
-}
-
-#if TEST
-
-int
-main (int ac, char **av)
-{
- char buff[BUFSIZ];
-
- printf ("Enter date, or blank line to exit.\n\t> ");
- fflush (stdout);
-
- buff[BUFSIZ - 1] = '\0';
- while (fgets (buff, BUFSIZ - 1, stdin) && buff[0])
- {
- struct timespec d;
- struct tm const *tm;
- if (! get_date (&d, buff, NULL))
- printf ("Bad format - couldn't convert.\n");
- else if (! (tm = localtime (&d.tv_sec)))
- {
- long int sec = d.tv_sec;
- printf ("localtime (%ld) failed\n", sec);
- }
- else
- {
- int ns = d.tv_nsec;
- printf ("%04ld-%02d-%02d %02d:%02d:%02d.%09d\n",
- tm->tm_year + 1900L, tm->tm_mon + 1, tm->tm_mday,
- tm->tm_hour, tm->tm_min, tm->tm_sec, ns);
- }
- printf ("\t> ");
- fflush (stdout);
- }
- return 0;
-}
-#endif /* TEST */
-
diff --git a/lib/getdate.y b/lib/getdate.y
deleted file mode 100644
index cbf3ca1..0000000
--- a/lib/getdate.y
+++ /dev/null
@@ -1,1520 +0,0 @@
-%{
-/* Parse a string into an internal time stamp.
-
- Copyright (C) 1999, 2000, 2002, 2003, 2004, 2005, 2006, 2007 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-/* Originally written by Steven M. Bellovin <smb@research.att.com> while
- at the University of North Carolina at Chapel Hill. Later tweaked by
- a couple of people on Usenet. Completely overhauled by Rich $alz
- <rsalz@bbn.com> and Jim Berets <jberets@bbn.com> in August, 1990.
-
- Modified by Paul Eggert <eggert@twinsun.com> in August 1999 to do
- the right thing about local DST. Also modified by Paul Eggert
- <eggert@cs.ucla.edu> in February 2004 to support
- nanosecond-resolution time stamps, and in October 2004 to support
- TZ strings in dates. */
-
-/* FIXME: Check for arithmetic overflow in all cases, not just
- some of them. */
-
-#include <config.h>
-
-#include "getdate.h"
-#include "timespec.h"
-
-/* There's no need to extend the stack, so there's no need to involve
- alloca. */
-#define YYSTACK_USE_ALLOCA 0
-
-/* Tell Bison how much stack space is needed. 20 should be plenty for
- this grammar, which is not right recursive. Beware setting it too
- high, since that might cause problems on machines whose
- implementations have lame stack-overflow checking. */
-#define YYMAXDEPTH 20
-#define YYINITDEPTH YYMAXDEPTH
-
-/* Since the code of getdate.y is not included in the Emacs executable
- itself, there is no need to #define static in this file. Even if
- the code were included in the Emacs executable, it probably
- wouldn't do any harm to #undef it here; this will only cause
- problems if we try to write to a static variable, which I don't
- think this code needs to do. */
-#ifdef emacs
-# undef static
-#endif
-
-#include <ctype.h>
-#include <limits.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "setenv.h"
-#include "xalloc.h"
-
-
-/* ISDIGIT differs from isdigit, as follows:
- - Its arg may be any int or unsigned int; it need not be an unsigned char
- or EOF.
- - It's typically faster.
- POSIX says that only '0' through '9' are digits. Prefer ISDIGIT to
- isdigit unless it's important to use the locale's definition
- of `digit' even when the host does not conform to POSIX. */
-#define ISDIGIT(c) ((unsigned int) (c) - '0' <= 9)
-
-#ifndef __attribute__
-# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 8) || __STRICT_ANSI__
-# define __attribute__(x)
-# endif
-#endif
-
-#ifndef ATTRIBUTE_UNUSED
-# define ATTRIBUTE_UNUSED __attribute__ ((__unused__))
-#endif
-
-/* Shift A right by B bits portably, by dividing A by 2**B and
- truncating towards minus infinity. A and B should be free of side
- effects, and B should be in the range 0 <= B <= INT_BITS - 2, where
- INT_BITS is the number of useful bits in an int. GNU code can
- assume that INT_BITS is at least 32.
-
- ISO C99 says that A >> B is implementation-defined if A < 0. Some
- implementations (e.g., UNICOS 9.0 on a Cray Y-MP EL) don't shift
- right in the usual way when A < 0, so SHR falls back on division if
- ordinary A >> B doesn't seem to be the usual signed shift. */
-#define SHR(a, b) \
- (-1 >> 1 == -1 \
- ? (a) >> (b) \
- : (a) / (1 << (b)) - ((a) % (1 << (b)) < 0))
-
-#define EPOCH_YEAR 1970
-#define TM_YEAR_BASE 1900
-
-#define HOUR(x) ((x) * 60)
-
-/* An integer value, and the number of digits in its textual
- representation. */
-typedef struct
-{
- bool negative;
- long int value;
- size_t digits;
-} textint;
-
-/* An entry in the lexical lookup table. */
-typedef struct
-{
- char const *name;
- int type;
- int value;
-} table;
-
-/* Meridian: am, pm, or 24-hour style. */
-enum { MERam, MERpm, MER24 };
-
-enum { BILLION = 1000000000, LOG10_BILLION = 9 };
-
-/* Relative times. */
-typedef struct
-{
- /* Relative year, month, day, hour, minutes, seconds, and nanoseconds. */
- long int year;
- long int month;
- long int day;
- long int hour;
- long int minutes;
- long int seconds;
- long int ns;
-} relative_time;
-
-#if HAVE_COMPOUND_LITERALS
-# define RELATIVE_TIME_0 ((relative_time) { 0, 0, 0, 0, 0, 0, 0 })
-#else
-static relative_time const RELATIVE_TIME_0;
-#endif
-
-/* Information passed to and from the parser. */
-typedef struct
-{
- /* The input string remaining to be parsed. */
- const char *input;
-
- /* N, if this is the Nth Tuesday. */
- long int day_ordinal;
-
- /* Day of week; Sunday is 0. */
- int day_number;
-
- /* tm_isdst flag for the local zone. */
- int local_isdst;
-
- /* Time zone, in minutes east of UTC. */
- long int time_zone;
-
- /* Style used for time. */
- int meridian;
-
- /* Gregorian year, month, day, hour, minutes, seconds, and nanoseconds. */
- textint year;
- long int month;
- long int day;
- long int hour;
- long int minutes;
- struct timespec seconds; /* includes nanoseconds */
-
- /* Relative year, month, day, hour, minutes, seconds, and nanoseconds. */
- relative_time rel;
-
- /* Presence or counts of nonterminals of various flavors parsed so far. */
- bool timespec_seen;
- bool rels_seen;
- size_t dates_seen;
- size_t days_seen;
- size_t local_zones_seen;
- size_t dsts_seen;
- size_t times_seen;
- size_t zones_seen;
-
- /* Table of local time zone abbrevations, terminated by a null entry. */
- table local_time_zone_table[3];
-} parser_control;
-
-union YYSTYPE;
-static int yylex (union YYSTYPE *, parser_control *);
-static int yyerror (parser_control const *, char const *);
-static long int time_zone_hhmm (textint, long int);
-
-%}
-
-/* We want a reentrant parser, even if the TZ manipulation and the calls to
- localtime and gmtime are not reentrant. */
-%pure-parser
-%parse-param { parser_control *pc }
-%lex-param { parser_control *pc }
-
-/* This grammar has 20 shift/reduce conflicts. */
-%expect 20
-
-%union
-{
- long int intval;
- textint textintval;
- struct timespec timespec;
- relative_time rel;
-}
-
-%token tAGO tDST
-
-%token tYEAR_UNIT tMONTH_UNIT tHOUR_UNIT tMINUTE_UNIT tSEC_UNIT
-%token <intval> tDAY_UNIT
-
-%token <intval> tDAY tDAYZONE tLOCAL_ZONE tMERIDIAN
-%token <intval> tMONTH tORDINAL tZONE
-
-%token <textintval> tSNUMBER tUNUMBER
-%token <timespec> tSDECIMAL_NUMBER tUDECIMAL_NUMBER
-
-%type <intval> o_colon_minutes o_merid
-%type <timespec> seconds signed_seconds unsigned_seconds
-
-%type <rel> relunit relunit_snumber
-
-%%
-
-spec:
- timespec
- | items
- ;
-
-timespec:
- '@' seconds
- {
- pc->seconds = $2;
- pc->timespec_seen = true;
- }
- ;
-
-items:
- /* empty */
- | items item
- ;
-
-item:
- time
- { pc->times_seen++; }
- | local_zone
- { pc->local_zones_seen++; }
- | zone
- { pc->zones_seen++; }
- | date
- { pc->dates_seen++; }
- | day
- { pc->days_seen++; }
- | rel
- { pc->rels_seen = true; }
- | number
- ;
-
-time:
- tUNUMBER tMERIDIAN
- {
- pc->hour = $1.value;
- pc->minutes = 0;
- pc->seconds.tv_sec = 0;
- pc->seconds.tv_nsec = 0;
- pc->meridian = $2;
- }
- | tUNUMBER ':' tUNUMBER o_merid
- {
- pc->hour = $1.value;
- pc->minutes = $3.value;
- pc->seconds.tv_sec = 0;
- pc->seconds.tv_nsec = 0;
- pc->meridian = $4;
- }
- | tUNUMBER ':' tUNUMBER tSNUMBER o_colon_minutes
- {
- pc->hour = $1.value;
- pc->minutes = $3.value;
- pc->seconds.tv_sec = 0;
- pc->seconds.tv_nsec = 0;
- pc->meridian = MER24;
- pc->zones_seen++;
- pc->time_zone = time_zone_hhmm ($4, $5);
- }
- | tUNUMBER ':' tUNUMBER ':' unsigned_seconds o_merid
- {
- pc->hour = $1.value;
- pc->minutes = $3.value;
- pc->seconds = $5;
- pc->meridian = $6;
- }
- | tUNUMBER ':' tUNUMBER ':' unsigned_seconds tSNUMBER o_colon_minutes
- {
- pc->hour = $1.value;
- pc->minutes = $3.value;
- pc->seconds = $5;
- pc->meridian = MER24;
- pc->zones_seen++;
- pc->time_zone = time_zone_hhmm ($6, $7);
- }
- ;
-
-local_zone:
- tLOCAL_ZONE
- {
- pc->local_isdst = $1;
- pc->dsts_seen += (0 < $1);
- }
- | tLOCAL_ZONE tDST
- {
- pc->local_isdst = 1;
- pc->dsts_seen += (0 < $1) + 1;
- }
- ;
-
-zone:
- tZONE
- { pc->time_zone = $1; }
- | tZONE relunit_snumber
- { pc->time_zone = $1;
- pc->rel.ns += $2.ns;
- pc->rel.seconds += $2.seconds;
- pc->rel.minutes += $2.minutes;
- pc->rel.hour += $2.hour;
- pc->rel.day += $2.day;
- pc->rel.month += $2.month;
- pc->rel.year += $2.year;
- pc->rels_seen = true; }
- | tZONE tSNUMBER o_colon_minutes
- { pc->time_zone = $1 + time_zone_hhmm ($2, $3); }
- | tDAYZONE
- { pc->time_zone = $1 + 60; }
- | tZONE tDST
- { pc->time_zone = $1 + 60; }
- ;
-
-day:
- tDAY
- {
- pc->day_ordinal = 1;
- pc->day_number = $1;
- }
- | tDAY ','
- {
- pc->day_ordinal = 1;
- pc->day_number = $1;
- }
- | tORDINAL tDAY
- {
- pc->day_ordinal = $1;
- pc->day_number = $2;
- }
- | tUNUMBER tDAY
- {
- pc->day_ordinal = $1.value;
- pc->day_number = $2;
- }
- ;
-
-date:
- tUNUMBER '/' tUNUMBER
- {
- pc->month = $1.value;
- pc->day = $3.value;
- }
- | tUNUMBER '/' tUNUMBER '/' tUNUMBER
- {
- /* Interpret as YYYY/MM/DD if the first value has 4 or more digits,
- otherwise as MM/DD/YY.
- The goal in recognizing YYYY/MM/DD is solely to support legacy
- machine-generated dates like those in an RCS log listing. If
- you want portability, use the ISO 8601 format. */
- if (4 <= $1.digits)
- {
- pc->year = $1;
- pc->month = $3.value;
- pc->day = $5.value;
- }
- else
- {
- pc->month = $1.value;
- pc->day = $3.value;
- pc->year = $5;
- }
- }
- | tUNUMBER tSNUMBER tSNUMBER
- {
- /* ISO 8601 format. YYYY-MM-DD. */
- pc->year = $1;
- pc->month = -$2.value;
- pc->day = -$3.value;
- }
- | tUNUMBER tMONTH tSNUMBER
- {
- /* e.g. 17-JUN-1992. */
- pc->day = $1.value;
- pc->month = $2;
- pc->year.value = -$3.value;
- pc->year.digits = $3.digits;
- }
- | tMONTH tSNUMBER tSNUMBER
- {
- /* e.g. JUN-17-1992. */
- pc->month = $1;
- pc->day = -$2.value;
- pc->year.value = -$3.value;
- pc->year.digits = $3.digits;
- }
- | tMONTH tUNUMBER
- {
- pc->month = $1;
- pc->day = $2.value;
- }
- | tMONTH tUNUMBER ',' tUNUMBER
- {
- pc->month = $1;
- pc->day = $2.value;
- pc->year = $4;
- }
- | tUNUMBER tMONTH
- {
- pc->day = $1.value;
- pc->month = $2;
- }
- | tUNUMBER tMONTH tUNUMBER
- {
- pc->day = $1.value;
- pc->month = $2;
- pc->year = $3;
- }
- ;
-
-rel:
- relunit tAGO
- {
- pc->rel.ns -= $1.ns;
- pc->rel.seconds -= $1.seconds;
- pc->rel.minutes -= $1.minutes;
- pc->rel.hour -= $1.hour;
- pc->rel.day -= $1.day;
- pc->rel.month -= $1.month;
- pc->rel.year -= $1.year;
- }
- | relunit
- {
- pc->rel.ns += $1.ns;
- pc->rel.seconds += $1.seconds;
- pc->rel.minutes += $1.minutes;
- pc->rel.hour += $1.hour;
- pc->rel.day += $1.day;
- pc->rel.month += $1.month;
- pc->rel.year += $1.year;
- }
- ;
-
-relunit:
- tORDINAL tYEAR_UNIT
- { $$ = RELATIVE_TIME_0; $$.year = $1; }
- | tUNUMBER tYEAR_UNIT
- { $$ = RELATIVE_TIME_0; $$.year = $1.value; }
- | tYEAR_UNIT
- { $$ = RELATIVE_TIME_0; $$.year = 1; }
- | tORDINAL tMONTH_UNIT
- { $$ = RELATIVE_TIME_0; $$.month = $1; }
- | tUNUMBER tMONTH_UNIT
- { $$ = RELATIVE_TIME_0; $$.month = $1.value; }
- | tMONTH_UNIT
- { $$ = RELATIVE_TIME_0; $$.month = 1; }
- | tORDINAL tDAY_UNIT
- { $$ = RELATIVE_TIME_0; $$.day = $1 * $2; }
- | tUNUMBER tDAY_UNIT
- { $$ = RELATIVE_TIME_0; $$.day = $1.value * $2; }
- | tDAY_UNIT
- { $$ = RELATIVE_TIME_0; $$.day = $1; }
- | tORDINAL tHOUR_UNIT
- { $$ = RELATIVE_TIME_0; $$.hour = $1; }
- | tUNUMBER tHOUR_UNIT
- { $$ = RELATIVE_TIME_0; $$.hour = $1.value; }
- | tHOUR_UNIT
- { $$ = RELATIVE_TIME_0; $$.hour = 1; }
- | tORDINAL tMINUTE_UNIT
- { $$ = RELATIVE_TIME_0; $$.minutes = $1; }
- | tUNUMBER tMINUTE_UNIT
- { $$ = RELATIVE_TIME_0; $$.minutes = $1.value; }
- | tMINUTE_UNIT
- { $$ = RELATIVE_TIME_0; $$.minutes = 1; }
- | tORDINAL tSEC_UNIT
- { $$ = RELATIVE_TIME_0; $$.seconds = $1; }
- | tUNUMBER tSEC_UNIT
- { $$ = RELATIVE_TIME_0; $$.seconds = $1.value; }
- | tSDECIMAL_NUMBER tSEC_UNIT
- { $$ = RELATIVE_TIME_0; $$.seconds = $1.tv_sec; $$.ns = $1.tv_nsec; }
- | tUDECIMAL_NUMBER tSEC_UNIT
- { $$ = RELATIVE_TIME_0; $$.seconds = $1.tv_sec; $$.ns = $1.tv_nsec; }
- | tSEC_UNIT
- { $$ = RELATIVE_TIME_0; $$.seconds = 1; }
- | relunit_snumber
- ;
-
-relunit_snumber:
- tSNUMBER tYEAR_UNIT
- { $$ = RELATIVE_TIME_0; $$.year = $1.value; }
- | tSNUMBER tMONTH_UNIT
- { $$ = RELATIVE_TIME_0; $$.month = $1.value; }
- | tSNUMBER tDAY_UNIT
- { $$ = RELATIVE_TIME_0; $$.day = $1.value * $2; }
- | tSNUMBER tHOUR_UNIT
- { $$ = RELATIVE_TIME_0; $$.hour = $1.value; }
- | tSNUMBER tMINUTE_UNIT
- { $$ = RELATIVE_TIME_0; $$.minutes = $1.value; }
- | tSNUMBER tSEC_UNIT
- { $$ = RELATIVE_TIME_0; $$.seconds = $1.value; }
- ;
-
-seconds: signed_seconds | unsigned_seconds;
-
-signed_seconds:
- tSDECIMAL_NUMBER
- | tSNUMBER
- { $$.tv_sec = $1.value; $$.tv_nsec = 0; }
- ;
-
-unsigned_seconds:
- tUDECIMAL_NUMBER
- | tUNUMBER
- { $$.tv_sec = $1.value; $$.tv_nsec = 0; }
- ;
-
-number:
- tUNUMBER
- {
- if (pc->dates_seen && ! pc->year.digits
- && ! pc->rels_seen && (pc->times_seen || 2 < $1.digits))
- pc->year = $1;
- else
- {
- if (4 < $1.digits)
- {
- pc->dates_seen++;
- pc->day = $1.value % 100;
- pc->month = ($1.value / 100) % 100;
- pc->year.value = $1.value / 10000;
- pc->year.digits = $1.digits - 4;
- }
- else
- {
- pc->times_seen++;
- if ($1.digits <= 2)
- {
- pc->hour = $1.value;
- pc->minutes = 0;
- }
- else
- {
- pc->hour = $1.value / 100;
- pc->minutes = $1.value % 100;
- }
- pc->seconds.tv_sec = 0;
- pc->seconds.tv_nsec = 0;
- pc->meridian = MER24;
- }
- }
- }
- ;
-
-o_colon_minutes:
- /* empty */
- { $$ = -1; }
- | ':' tUNUMBER
- { $$ = $2.value; }
- ;
-
-o_merid:
- /* empty */
- { $$ = MER24; }
- | tMERIDIAN
- { $$ = $1; }
- ;
-
-%%
-
-static table const meridian_table[] =
-{
- { "AM", tMERIDIAN, MERam },
- { "A.M.", tMERIDIAN, MERam },
- { "PM", tMERIDIAN, MERpm },
- { "P.M.", tMERIDIAN, MERpm },
- { NULL, 0, 0 }
-};
-
-static table const dst_table[] =
-{
- { "DST", tDST, 0 }
-};
-
-static table const month_and_day_table[] =
-{
- { "JANUARY", tMONTH, 1 },
- { "FEBRUARY", tMONTH, 2 },
- { "MARCH", tMONTH, 3 },
- { "APRIL", tMONTH, 4 },
- { "MAY", tMONTH, 5 },
- { "JUNE", tMONTH, 6 },
- { "JULY", tMONTH, 7 },
- { "AUGUST", tMONTH, 8 },
- { "SEPTEMBER",tMONTH, 9 },
- { "SEPT", tMONTH, 9 },
- { "OCTOBER", tMONTH, 10 },
- { "NOVEMBER", tMONTH, 11 },
- { "DECEMBER", tMONTH, 12 },
- { "SUNDAY", tDAY, 0 },
- { "MONDAY", tDAY, 1 },
- { "TUESDAY", tDAY, 2 },
- { "TUES", tDAY, 2 },
- { "WEDNESDAY",tDAY, 3 },
- { "WEDNES", tDAY, 3 },
- { "THURSDAY", tDAY, 4 },
- { "THUR", tDAY, 4 },
- { "THURS", tDAY, 4 },
- { "FRIDAY", tDAY, 5 },
- { "SATURDAY", tDAY, 6 },
- { NULL, 0, 0 }
-};
-
-static table const time_units_table[] =
-{
- { "YEAR", tYEAR_UNIT, 1 },
- { "MONTH", tMONTH_UNIT, 1 },
- { "FORTNIGHT",tDAY_UNIT, 14 },
- { "WEEK", tDAY_UNIT, 7 },
- { "DAY", tDAY_UNIT, 1 },
- { "HOUR", tHOUR_UNIT, 1 },
- { "MINUTE", tMINUTE_UNIT, 1 },
- { "MIN", tMINUTE_UNIT, 1 },
- { "SECOND", tSEC_UNIT, 1 },
- { "SEC", tSEC_UNIT, 1 },
- { NULL, 0, 0 }
-};
-
-/* Assorted relative-time words. */
-static table const relative_time_table[] =
-{
- { "TOMORROW", tDAY_UNIT, 1 },
- { "YESTERDAY",tDAY_UNIT, -1 },
- { "TODAY", tDAY_UNIT, 0 },
- { "NOW", tDAY_UNIT, 0 },
- { "LAST", tORDINAL, -1 },
- { "THIS", tORDINAL, 0 },
- { "NEXT", tORDINAL, 1 },
- { "FIRST", tORDINAL, 1 },
-/*{ "SECOND", tORDINAL, 2 }, */
- { "THIRD", tORDINAL, 3 },
- { "FOURTH", tORDINAL, 4 },
- { "FIFTH", tORDINAL, 5 },
- { "SIXTH", tORDINAL, 6 },
- { "SEVENTH", tORDINAL, 7 },
- { "EIGHTH", tORDINAL, 8 },
- { "NINTH", tORDINAL, 9 },
- { "TENTH", tORDINAL, 10 },
- { "ELEVENTH", tORDINAL, 11 },
- { "TWELFTH", tORDINAL, 12 },
- { "AGO", tAGO, 1 },
- { NULL, 0, 0 }
-};
-
-/* The universal time zone table. These labels can be used even for
- time stamps that would not otherwise be valid, e.g., GMT time
- stamps in London during summer. */
-static table const universal_time_zone_table[] =
-{
- { "GMT", tZONE, HOUR ( 0) }, /* Greenwich Mean */
- { "UT", tZONE, HOUR ( 0) }, /* Universal (Coordinated) */
- { "UTC", tZONE, HOUR ( 0) },
- { NULL, 0, 0 }
-};
-
-/* The time zone table. This table is necessarily incomplete, as time
- zone abbreviations are ambiguous; e.g. Australians interpret "EST"
- as Eastern time in Australia, not as US Eastern Standard Time.
- You cannot rely on getdate to handle arbitrary time zone
- abbreviations; use numeric abbreviations like `-0500' instead. */
-static table const time_zone_table[] =
-{
- { "WET", tZONE, HOUR ( 0) }, /* Western European */
- { "WEST", tDAYZONE, HOUR ( 0) }, /* Western European Summer */
- { "BST", tDAYZONE, HOUR ( 0) }, /* British Summer */
- { "ART", tZONE, -HOUR ( 3) }, /* Argentina */
- { "BRT", tZONE, -HOUR ( 3) }, /* Brazil */
- { "BRST", tDAYZONE, -HOUR ( 3) }, /* Brazil Summer */
- { "NST", tZONE, -(HOUR ( 3) + 30) }, /* Newfoundland Standard */
- { "NDT", tDAYZONE,-(HOUR ( 3) + 30) }, /* Newfoundland Daylight */
- { "AST", tZONE, -HOUR ( 4) }, /* Atlantic Standard */
- { "ADT", tDAYZONE, -HOUR ( 4) }, /* Atlantic Daylight */
- { "CLT", tZONE, -HOUR ( 4) }, /* Chile */
- { "CLST", tDAYZONE, -HOUR ( 4) }, /* Chile Summer */
- { "EST", tZONE, -HOUR ( 5) }, /* Eastern Standard */
- { "EDT", tDAYZONE, -HOUR ( 5) }, /* Eastern Daylight */
- { "CST", tZONE, -HOUR ( 6) }, /* Central Standard */
- { "CDT", tDAYZONE, -HOUR ( 6) }, /* Central Daylight */
- { "MST", tZONE, -HOUR ( 7) }, /* Mountain Standard */
- { "MDT", tDAYZONE, -HOUR ( 7) }, /* Mountain Daylight */
- { "PST", tZONE, -HOUR ( 8) }, /* Pacific Standard */
- { "PDT", tDAYZONE, -HOUR ( 8) }, /* Pacific Daylight */
- { "AKST", tZONE, -HOUR ( 9) }, /* Alaska Standard */
- { "AKDT", tDAYZONE, -HOUR ( 9) }, /* Alaska Daylight */
- { "HST", tZONE, -HOUR (10) }, /* Hawaii Standard */
- { "HAST", tZONE, -HOUR (10) }, /* Hawaii-Aleutian Standard */
- { "HADT", tDAYZONE, -HOUR (10) }, /* Hawaii-Aleutian Daylight */
- { "SST", tZONE, -HOUR (12) }, /* Samoa Standard */
- { "WAT", tZONE, HOUR ( 1) }, /* West Africa */
- { "CET", tZONE, HOUR ( 1) }, /* Central European */
- { "CEST", tDAYZONE, HOUR ( 1) }, /* Central European Summer */
- { "MET", tZONE, HOUR ( 1) }, /* Middle European */
- { "MEZ", tZONE, HOUR ( 1) }, /* Middle European */
- { "MEST", tDAYZONE, HOUR ( 1) }, /* Middle European Summer */
- { "MESZ", tDAYZONE, HOUR ( 1) }, /* Middle European Summer */
- { "EET", tZONE, HOUR ( 2) }, /* Eastern European */
- { "EEST", tDAYZONE, HOUR ( 2) }, /* Eastern European Summer */
- { "CAT", tZONE, HOUR ( 2) }, /* Central Africa */
- { "SAST", tZONE, HOUR ( 2) }, /* South Africa Standard */
- { "EAT", tZONE, HOUR ( 3) }, /* East Africa */
- { "MSK", tZONE, HOUR ( 3) }, /* Moscow */
- { "MSD", tDAYZONE, HOUR ( 3) }, /* Moscow Daylight */
- { "IST", tZONE, (HOUR ( 5) + 30) }, /* India Standard */
- { "SGT", tZONE, HOUR ( 8) }, /* Singapore */
- { "KST", tZONE, HOUR ( 9) }, /* Korea Standard */
- { "JST", tZONE, HOUR ( 9) }, /* Japan Standard */
- { "GST", tZONE, HOUR (10) }, /* Guam Standard */
- { "NZST", tZONE, HOUR (12) }, /* New Zealand Standard */
- { "NZDT", tDAYZONE, HOUR (12) }, /* New Zealand Daylight */
- { NULL, 0, 0 }
-};
-
-/* Military time zone table. */
-static table const military_table[] =
-{
- { "A", tZONE, -HOUR ( 1) },
- { "B", tZONE, -HOUR ( 2) },
- { "C", tZONE, -HOUR ( 3) },
- { "D", tZONE, -HOUR ( 4) },
- { "E", tZONE, -HOUR ( 5) },
- { "F", tZONE, -HOUR ( 6) },
- { "G", tZONE, -HOUR ( 7) },
- { "H", tZONE, -HOUR ( 8) },
- { "I", tZONE, -HOUR ( 9) },
- { "K", tZONE, -HOUR (10) },
- { "L", tZONE, -HOUR (11) },
- { "M", tZONE, -HOUR (12) },
- { "N", tZONE, HOUR ( 1) },
- { "O", tZONE, HOUR ( 2) },
- { "P", tZONE, HOUR ( 3) },
- { "Q", tZONE, HOUR ( 4) },
- { "R", tZONE, HOUR ( 5) },
- { "S", tZONE, HOUR ( 6) },
- { "T", tZONE, HOUR ( 7) },
- { "U", tZONE, HOUR ( 8) },
- { "V", tZONE, HOUR ( 9) },
- { "W", tZONE, HOUR (10) },
- { "X", tZONE, HOUR (11) },
- { "Y", tZONE, HOUR (12) },
- { "Z", tZONE, HOUR ( 0) },
- { NULL, 0, 0 }
-};
-
-
-
-/* Convert a time zone expressed as HH:MM into an integer count of
- minutes. If MM is negative, then S is of the form HHMM and needs
- to be picked apart; otherwise, S is of the form HH. */
-
-static long int
-time_zone_hhmm (textint s, long int mm)
-{
- if (mm < 0)
- return (s.value / 100) * 60 + s.value % 100;
- else
- return s.value * 60 + (s.negative ? -mm : mm);
-}
-
-static int
-to_hour (long int hours, int meridian)
-{
- switch (meridian)
- {
- default: /* Pacify GCC. */
- case MER24:
- return 0 <= hours && hours < 24 ? hours : -1;
- case MERam:
- return 0 < hours && hours < 12 ? hours : hours == 12 ? 0 : -1;
- case MERpm:
- return 0 < hours && hours < 12 ? hours + 12 : hours == 12 ? 12 : -1;
- }
-}
-
-static long int
-to_year (textint textyear)
-{
- long int year = textyear.value;
-
- if (year < 0)
- year = -year;
-
- /* XPG4 suggests that years 00-68 map to 2000-2068, and
- years 69-99 map to 1969-1999. */
- else if (textyear.digits == 2)
- year += year < 69 ? 2000 : 1900;
-
- return year;
-}
-
-static table const *
-lookup_zone (parser_control const *pc, char const *name)
-{
- table const *tp;
-
- for (tp = universal_time_zone_table; tp->name; tp++)
- if (strcmp (name, tp->name) == 0)
- return tp;
-
- /* Try local zone abbreviations before those in time_zone_table, as
- the local ones are more likely to be right. */
- for (tp = pc->local_time_zone_table; tp->name; tp++)
- if (strcmp (name, tp->name) == 0)
- return tp;
-
- for (tp = time_zone_table; tp->name; tp++)
- if (strcmp (name, tp->name) == 0)
- return tp;
-
- return NULL;
-}
-
-#if ! HAVE_TM_GMTOFF
-/* Yield the difference between *A and *B,
- measured in seconds, ignoring leap seconds.
- The body of this function is taken directly from the GNU C Library;
- see src/strftime.c. */
-static long int
-tm_diff (struct tm const *a, struct tm const *b)
-{
- /* Compute intervening leap days correctly even if year is negative.
- Take care to avoid int overflow in leap day calculations. */
- int a4 = SHR (a->tm_year, 2) + SHR (TM_YEAR_BASE, 2) - ! (a->tm_year & 3);
- int b4 = SHR (b->tm_year, 2) + SHR (TM_YEAR_BASE, 2) - ! (b->tm_year & 3);
- int a100 = a4 / 25 - (a4 % 25 < 0);
- int b100 = b4 / 25 - (b4 % 25 < 0);
- int a400 = SHR (a100, 2);
- int b400 = SHR (b100, 2);
- int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
- long int ayear = a->tm_year;
- long int years = ayear - b->tm_year;
- long int days = (365 * years + intervening_leap_days
- + (a->tm_yday - b->tm_yday));
- return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
- + (a->tm_min - b->tm_min))
- + (a->tm_sec - b->tm_sec));
-}
-#endif /* ! HAVE_TM_GMTOFF */
-
-static table const *
-lookup_word (parser_control const *pc, char *word)
-{
- char *p;
- char *q;
- size_t wordlen;
- table const *tp;
- bool period_found;
- bool abbrev;
-
- /* Make it uppercase. */
- for (p = word; *p; p++)
- {
- unsigned char ch = *p;
- *p = toupper (ch);
- }
-
- for (tp = meridian_table; tp->name; tp++)
- if (strcmp (word, tp->name) == 0)
- return tp;
-
- /* See if we have an abbreviation for a month. */
- wordlen = strlen (word);
- abbrev = wordlen == 3 || (wordlen == 4 && word[3] == '.');
-
- for (tp = month_and_day_table; tp->name; tp++)
- if ((abbrev ? strncmp (word, tp->name, 3) : strcmp (word, tp->name)) == 0)
- return tp;
-
- if ((tp = lookup_zone (pc, word)))
- return tp;
-
- if (strcmp (word, dst_table[0].name) == 0)
- return dst_table;
-
- for (tp = time_units_table; tp->name; tp++)
- if (strcmp (word, tp->name) == 0)
- return tp;
-
- /* Strip off any plural and try the units table again. */
- if (word[wordlen - 1] == 'S')
- {
- word[wordlen - 1] = '\0';
- for (tp = time_units_table; tp->name; tp++)
- if (strcmp (word, tp->name) == 0)
- return tp;
- word[wordlen - 1] = 'S'; /* For "this" in relative_time_table. */
- }
-
- for (tp = relative_time_table; tp->name; tp++)
- if (strcmp (word, tp->name) == 0)
- return tp;
-
- /* Military time zones. */
- if (wordlen == 1)
- for (tp = military_table; tp->name; tp++)
- if (word[0] == tp->name[0])
- return tp;
-
- /* Drop out any periods and try the time zone table again. */
- for (period_found = false, p = q = word; (*p = *q); q++)
- if (*q == '.')
- period_found = true;
- else
- p++;
- if (period_found && (tp = lookup_zone (pc, word)))
- return tp;
-
- return NULL;
-}
-
-static int
-yylex (YYSTYPE *lvalp, parser_control *pc)
-{
- unsigned char c;
- size_t count;
-
- for (;;)
- {
- while (c = *pc->input, isspace (c))
- pc->input++;
-
- if (ISDIGIT (c) || c == '-' || c == '+')
- {
- char const *p;
- int sign;
- unsigned long int value;
- if (c == '-' || c == '+')
- {
- sign = c == '-' ? -1 : 1;
- while (c = *++pc->input, isspace (c))
- continue;
- if (! ISDIGIT (c))
- /* skip the '-' sign */
- continue;
- }
- else
- sign = 0;
- p = pc->input;
- for (value = 0; ; value *= 10)
- {
- unsigned long int value1 = value + (c - '0');
- if (value1 < value)
- return '?';
- value = value1;
- c = *++p;
- if (! ISDIGIT (c))
- break;
- if (ULONG_MAX / 10 < value)
- return '?';
- }
- if ((c == '.' || c == ',') && ISDIGIT (p[1]))
- {
- time_t s;
- int ns;
- int digits;
- unsigned long int value1;
-
- /* Check for overflow when converting value to time_t. */
- if (sign < 0)
- {
- s = - value;
- if (0 < s)
- return '?';
- value1 = -s;
- }
- else
- {
- s = value;
- if (s < 0)
- return '?';
- value1 = s;
- }
- if (value != value1)
- return '?';
-
- /* Accumulate fraction, to ns precision. */
- p++;
- ns = *p++ - '0';
- for (digits = 2; digits <= LOG10_BILLION; digits++)
- {
- ns *= 10;
- if (ISDIGIT (*p))
- ns += *p++ - '0';
- }
-
- /* Skip excess digits, truncating toward -Infinity. */
- if (sign < 0)
- for (; ISDIGIT (*p); p++)
- if (*p != '0')
- {
- ns++;
- break;
- }
- while (ISDIGIT (*p))
- p++;
-
- /* Adjust to the timespec convention, which is that
- tv_nsec is always a positive offset even if tv_sec is
- negative. */
- if (sign < 0 && ns)
- {
- s--;
- if (! (s < 0))
- return '?';
- ns = BILLION - ns;
- }
-
- lvalp->timespec.tv_sec = s;
- lvalp->timespec.tv_nsec = ns;
- pc->input = p;
- return sign ? tSDECIMAL_NUMBER : tUDECIMAL_NUMBER;
- }
- else
- {
- lvalp->textintval.negative = sign < 0;
- if (sign < 0)
- {
- lvalp->textintval.value = - value;
- if (0 < lvalp->textintval.value)
- return '?';
- }
- else
- {
- lvalp->textintval.value = value;
- if (lvalp->textintval.value < 0)
- return '?';
- }
- lvalp->textintval.digits = p - pc->input;
- pc->input = p;
- return sign ? tSNUMBER : tUNUMBER;
- }
- }
-
- if (isalpha (c))
- {
- char buff[20];
- char *p = buff;
- table const *tp;
-
- do
- {
- if (p < buff + sizeof buff - 1)
- *p++ = c;
- c = *++pc->input;
- }
- while (isalpha (c) || c == '.');
-
- *p = '\0';
- tp = lookup_word (pc, buff);
- if (! tp)
- return '?';
- lvalp->intval = tp->value;
- return tp->type;
- }
-
- if (c != '(')
- return *pc->input++;
- count = 0;
- do
- {
- c = *pc->input++;
- if (c == '\0')
- return c;
- if (c == '(')
- count++;
- else if (c == ')')
- count--;
- }
- while (count != 0);
- }
-}
-
-/* Do nothing if the parser reports an error. */
-static int
-yyerror (parser_control const *pc ATTRIBUTE_UNUSED,
- char const *s ATTRIBUTE_UNUSED)
-{
- return 0;
-}
-
-/* If *TM0 is the old and *TM1 is the new value of a struct tm after
- passing it to mktime, return true if it's OK that mktime returned T.
- It's not OK if *TM0 has out-of-range members. */
-
-static bool
-mktime_ok (struct tm const *tm0, struct tm const *tm1, time_t t)
-{
- if (t == (time_t) -1)
- {
- /* Guard against falsely reporting an error when parsing a time
- stamp that happens to equal (time_t) -1, on a host that
- supports such a time stamp. */
- tm1 = localtime (&t);
- if (!tm1)
- return false;
- }
-
- return ! ((tm0->tm_sec ^ tm1->tm_sec)
- | (tm0->tm_min ^ tm1->tm_min)
- | (tm0->tm_hour ^ tm1->tm_hour)
- | (tm0->tm_mday ^ tm1->tm_mday)
- | (tm0->tm_mon ^ tm1->tm_mon)
- | (tm0->tm_year ^ tm1->tm_year));
-}
-
-/* A reasonable upper bound for the size of ordinary TZ strings.
- Use heap allocation if TZ's length exceeds this. */
-enum { TZBUFSIZE = 100 };
-
-/* Return a copy of TZ, stored in TZBUF if it fits, and heap-allocated
- otherwise. */
-static char *
-get_tz (char tzbuf[TZBUFSIZE])
-{
- char *tz = getenv ("TZ");
- if (tz)
- {
- size_t tzsize = strlen (tz) + 1;
- tz = (tzsize <= TZBUFSIZE
- ? memcpy (tzbuf, tz, tzsize)
- : xmemdup (tz, tzsize));
- }
- return tz;
-}
-
-/* Parse a date/time string, storing the resulting time value into *RESULT.
- The string itself is pointed to by P. Return true if successful.
- P can be an incomplete or relative time specification; if so, use
- *NOW as the basis for the returned time. */
-bool
-get_date (struct timespec *result, char const *p, struct timespec const *now)
-{
- time_t Start;
- long int Start_ns;
- struct tm const *tmp;
- struct tm tm;
- struct tm tm0;
- parser_control pc;
- struct timespec gettime_buffer;
- unsigned char c;
- bool tz_was_altered = false;
- char *tz0 = NULL;
- char tz0buf[TZBUFSIZE];
- bool ok = true;
-
- if (! now)
- {
- gettime (&gettime_buffer);
- now = &gettime_buffer;
- }
-
- Start = now->tv_sec;
- Start_ns = now->tv_nsec;
-
- tmp = localtime (&now->tv_sec);
- if (! tmp)
- return false;
-
- while (c = *p, isspace (c))
- p++;
-
- if (strncmp (p, "TZ=\"", 4) == 0)
- {
- char const *tzbase = p + 4;
- size_t tzsize = 1;
- char const *s;
-
- for (s = tzbase; *s; s++, tzsize++)
- if (*s == '\\')
- {
- s++;
- if (! (*s == '\\' || *s == '"'))
- break;
- }
- else if (*s == '"')
- {
- char *z;
- char *tz1;
- char tz1buf[TZBUFSIZE];
- bool large_tz = TZBUFSIZE < tzsize;
- bool setenv_ok;
- tz0 = get_tz (tz0buf);
- z = tz1 = large_tz ? xmalloc (tzsize) : tz1buf;
- for (s = tzbase; *s != '"'; s++)
- *z++ = *(s += *s == '\\');
- *z = '\0';
- setenv_ok = setenv ("TZ", tz1, 1) == 0;
- if (large_tz)
- free (tz1);
- if (!setenv_ok)
- goto fail;
- tz_was_altered = true;
- p = s + 1;
- }
- }
-
- pc.input = p;
- pc.year.value = tmp->tm_year;
- pc.year.value += TM_YEAR_BASE;
- pc.year.digits = 0;
- pc.month = tmp->tm_mon + 1;
- pc.day = tmp->tm_mday;
- pc.hour = tmp->tm_hour;
- pc.minutes = tmp->tm_min;
- pc.seconds.tv_sec = tmp->tm_sec;
- pc.seconds.tv_nsec = Start_ns;
- tm.tm_isdst = tmp->tm_isdst;
-
- pc.meridian = MER24;
- pc.rel = RELATIVE_TIME_0;
- pc.timespec_seen = false;
- pc.rels_seen = false;
- pc.dates_seen = 0;
- pc.days_seen = 0;
- pc.times_seen = 0;
- pc.local_zones_seen = 0;
- pc.dsts_seen = 0;
- pc.zones_seen = 0;
-
-#if HAVE_STRUCT_TM_TM_ZONE
- pc.local_time_zone_table[0].name = tmp->tm_zone;
- pc.local_time_zone_table[0].type = tLOCAL_ZONE;
- pc.local_time_zone_table[0].value = tmp->tm_isdst;
- pc.local_time_zone_table[1].name = NULL;
-
- /* Probe the names used in the next three calendar quarters, looking
- for a tm_isdst different from the one we already have. */
- {
- int quarter;
- for (quarter = 1; quarter <= 3; quarter++)
- {
- time_t probe = Start + quarter * (90 * 24 * 60 * 60);
- struct tm const *probe_tm = localtime (&probe);
- if (probe_tm && probe_tm->tm_zone
- && probe_tm->tm_isdst != pc.local_time_zone_table[0].value)
- {
- {
- pc.local_time_zone_table[1].name = probe_tm->tm_zone;
- pc.local_time_zone_table[1].type = tLOCAL_ZONE;
- pc.local_time_zone_table[1].value = probe_tm->tm_isdst;
- pc.local_time_zone_table[2].name = NULL;
- }
- break;
- }
- }
- }
-#else
-#if HAVE_TZNAME
- {
-# ifndef tzname
- extern char *tzname[];
-# endif
- int i;
- for (i = 0; i < 2; i++)
- {
- pc.local_time_zone_table[i].name = tzname[i];
- pc.local_time_zone_table[i].type = tLOCAL_ZONE;
- pc.local_time_zone_table[i].value = i;
- }
- pc.local_time_zone_table[i].name = NULL;
- }
-#else
- pc.local_time_zone_table[0].name = NULL;
-#endif
-#endif
-
- if (pc.local_time_zone_table[0].name && pc.local_time_zone_table[1].name
- && ! strcmp (pc.local_time_zone_table[0].name,
- pc.local_time_zone_table[1].name))
- {
- /* This locale uses the same abbrevation for standard and
- daylight times. So if we see that abbreviation, we don't
- know whether it's daylight time. */
- pc.local_time_zone_table[0].value = -1;
- pc.local_time_zone_table[1].name = NULL;
- }
-
- if (yyparse (&pc) != 0)
- goto fail;
-
- if (pc.timespec_seen)
- *result = pc.seconds;
- else
- {
- if (1 < (pc.times_seen | pc.dates_seen | pc.days_seen | pc.dsts_seen
- | (pc.local_zones_seen + pc.zones_seen)))
- goto fail;
-
- tm.tm_year = to_year (pc.year) - TM_YEAR_BASE;
- tm.tm_mon = pc.month - 1;
- tm.tm_mday = pc.day;
- if (pc.times_seen || (pc.rels_seen && ! pc.dates_seen && ! pc.days_seen))
- {
- tm.tm_hour = to_hour (pc.hour, pc.meridian);
- if (tm.tm_hour < 0)
- goto fail;
- tm.tm_min = pc.minutes;
- tm.tm_sec = pc.seconds.tv_sec;
- }
- else
- {
- tm.tm_hour = tm.tm_min = tm.tm_sec = 0;
- pc.seconds.tv_nsec = 0;
- }
-
- /* Let mktime deduce tm_isdst if we have an absolute time stamp. */
- if (pc.dates_seen | pc.days_seen | pc.times_seen)
- tm.tm_isdst = -1;
-
- /* But if the input explicitly specifies local time with or without
- DST, give mktime that information. */
- if (pc.local_zones_seen)
- tm.tm_isdst = pc.local_isdst;
-
- tm0 = tm;
-
- Start = mktime (&tm);
-
- if (! mktime_ok (&tm0, &tm, Start))
- {
- if (! pc.zones_seen)
- goto fail;
- else
- {
- /* Guard against falsely reporting errors near the time_t
- boundaries when parsing times in other time zones. For
- example, suppose the input string "1969-12-31 23:00:00 -0100",
- the current time zone is 8 hours ahead of UTC, and the min
- time_t value is 1970-01-01 00:00:00 UTC. Then the min
- localtime value is 1970-01-01 08:00:00, and mktime will
- therefore fail on 1969-12-31 23:00:00. To work around the
- problem, set the time zone to 1 hour behind UTC temporarily
- by setting TZ="XXX1:00" and try mktime again. */
-
- long int time_zone = pc.time_zone;
- long int abs_time_zone = time_zone < 0 ? - time_zone : time_zone;
- long int abs_time_zone_hour = abs_time_zone / 60;
- int abs_time_zone_min = abs_time_zone % 60;
- char tz1buf[sizeof "XXX+0:00"
- + sizeof pc.time_zone * CHAR_BIT / 3];
- if (!tz_was_altered)
- tz0 = get_tz (tz0buf);
- sprintf (tz1buf, "XXX%s%ld:%02d", "-" + (time_zone < 0),
- abs_time_zone_hour, abs_time_zone_min);
- if (setenv ("TZ", tz1buf, 1) != 0)
- goto fail;
- tz_was_altered = true;
- tm = tm0;
- Start = mktime (&tm);
- if (! mktime_ok (&tm0, &tm, Start))
- goto fail;
- }
- }
-
- if (pc.days_seen && ! pc.dates_seen)
- {
- tm.tm_mday += ((pc.day_number - tm.tm_wday + 7) % 7
- + 7 * (pc.day_ordinal - (0 < pc.day_ordinal)));
- tm.tm_isdst = -1;
- Start = mktime (&tm);
- if (Start == (time_t) -1)
- goto fail;
- }
-
- if (pc.zones_seen)
- {
- long int delta = pc.time_zone * 60;
- time_t t1;
-#ifdef HAVE_TM_GMTOFF
- delta -= tm.tm_gmtoff;
-#else
- time_t t = Start;
- struct tm const *gmt = gmtime (&t);
- if (! gmt)
- goto fail;
- delta -= tm_diff (&tm, gmt);
-#endif
- t1 = Start - delta;
- if ((Start < t1) != (delta < 0))
- goto fail; /* time_t overflow */
- Start = t1;
- }
-
- /* Add relative date. */
- if (pc.rel.year | pc.rel.month | pc.rel.day)
- {
- int year = tm.tm_year + pc.rel.year;
- int month = tm.tm_mon + pc.rel.month;
- int day = tm.tm_mday + pc.rel.day;
- if (((year < tm.tm_year) ^ (pc.rel.year < 0))
- | ((month < tm.tm_mon) ^ (pc.rel.month < 0))
- | ((day < tm.tm_mday) ^ (pc.rel.day < 0)))
- goto fail;
- tm.tm_year = year;
- tm.tm_mon = month;
- tm.tm_mday = day;
- tm.tm_hour = tm0.tm_hour;
- tm.tm_min = tm0.tm_min;
- tm.tm_sec = tm0.tm_sec;
- tm.tm_isdst = tm0.tm_isdst;
- Start = mktime (&tm);
- if (Start == (time_t) -1)
- goto fail;
- }
-
- /* Add relative hours, minutes, and seconds. On hosts that support
- leap seconds, ignore the possibility of leap seconds; e.g.,
- "+ 10 minutes" adds 600 seconds, even if one of them is a
- leap second. Typically this is not what the user wants, but it's
- too hard to do it the other way, because the time zone indicator
- must be applied before relative times, and if mktime is applied
- again the time zone will be lost. */
- {
- long int sum_ns = pc.seconds.tv_nsec + pc.rel.ns;
- long int normalized_ns = (sum_ns % BILLION + BILLION) % BILLION;
- time_t t0 = Start;
- long int d1 = 60 * 60 * pc.rel.hour;
- time_t t1 = t0 + d1;
- long int d2 = 60 * pc.rel.minutes;
- time_t t2 = t1 + d2;
- long int d3 = pc.rel.seconds;
- time_t t3 = t2 + d3;
- long int d4 = (sum_ns - normalized_ns) / BILLION;
- time_t t4 = t3 + d4;
-
- if ((d1 / (60 * 60) ^ pc.rel.hour)
- | (d2 / 60 ^ pc.rel.minutes)
- | ((t1 < t0) ^ (d1 < 0))
- | ((t2 < t1) ^ (d2 < 0))
- | ((t3 < t2) ^ (d3 < 0))
- | ((t4 < t3) ^ (d4 < 0)))
- goto fail;
-
- result->tv_sec = t4;
- result->tv_nsec = normalized_ns;
- }
- }
-
- goto done;
-
- fail:
- ok = false;
- done:
- if (tz_was_altered)
- ok &= (tz0 ? setenv ("TZ", tz0, 1) : unsetenv ("TZ")) == 0;
- if (tz0 != tz0buf)
- free (tz0);
- return ok;
-}
-
-#if TEST
-
-int
-main (int ac, char **av)
-{
- char buff[BUFSIZ];
-
- printf ("Enter date, or blank line to exit.\n\t> ");
- fflush (stdout);
-
- buff[BUFSIZ - 1] = '\0';
- while (fgets (buff, BUFSIZ - 1, stdin) && buff[0])
- {
- struct timespec d;
- struct tm const *tm;
- if (! get_date (&d, buff, NULL))
- printf ("Bad format - couldn't convert.\n");
- else if (! (tm = localtime (&d.tv_sec)))
- {
- long int sec = d.tv_sec;
- printf ("localtime (%ld) failed\n", sec);
- }
- else
- {
- int ns = d.tv_nsec;
- printf ("%04ld-%02d-%02d %02d:%02d:%02d.%09d\n",
- tm->tm_year + 1900L, tm->tm_mon + 1, tm->tm_mday,
- tm->tm_hour, tm->tm_min, tm->tm_sec, ns);
- }
- printf ("\t> ");
- fflush (stdout);
- }
- return 0;
-}
-#endif /* TEST */
diff --git a/lib/getdelim.c b/lib/getdelim.c
index e0b8a70..e316c91 100644
--- a/lib/getdelim.c
+++ b/lib/getdelim.c
@@ -1,10 +1,10 @@
/* getdelim.c --- Implementation of replacement getdelim function.
- Copyright (C) 1994, 1996, 1997, 1998, 2001, 2003, 2005, 2006 Free
- Software Foundation, Inc.
+ Copyright (C) 1994, 1996-1998, 2001, 2003, 2005-2016 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 2, or (at
+ published by the Free Software Foundation; either version 3, or (at
your option) any later version.
This program is distributed in the hope that it will be useful, but
@@ -13,33 +13,38 @@
General Public License for more details.
You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- 02110-1301, USA. */
+ along with this program; if not, see <http://www.gnu.org/licenses/>. */
/* Ported from glibc by Simon Josefsson. */
+/* Don't use __attribute__ __nonnull__ in this compilation unit. Otherwise gcc
+ optimizes away the lineptr == NULL || n == NULL || fp == NULL tests below. */
+#define _GL_ARG_NONNULL(params)
+
#include <config.h>
-#include "getdelim.h"
+#include <stdio.h>
#include <limits.h>
+#include <stdint.h>
#include <stdlib.h>
#include <errno.h>
-#ifndef SIZE_MAX
-# define SIZE_MAX ((size_t) -1)
-#endif
#ifndef SSIZE_MAX
# define SSIZE_MAX ((ssize_t) (SIZE_MAX / 2))
#endif
-#if !HAVE_FLOCKFILE
+
+#if USE_UNLOCKED_IO
+# include "unlocked-io.h"
+# define getc_maybe_unlocked(fp) getc(fp)
+#elif !HAVE_FLOCKFILE || !HAVE_FUNLOCKFILE || !HAVE_DECL_GETC_UNLOCKED
# undef flockfile
-# define flockfile(x) ((void) 0)
-#endif
-#if !HAVE_FUNLOCKFILE
# undef funlockfile
+# define flockfile(x) ((void) 0)
# define funlockfile(x) ((void) 0)
+# define getc_maybe_unlocked(fp) getc(fp)
+#else
+# define getc_maybe_unlocked(fp) getc_unlocked(fp)
#endif
/* Read up to (and including) a DELIMITER from FP into *LINEPTR (and
@@ -64,63 +69,67 @@ getdelim (char **lineptr, size_t *n, int delimiter, FILE *fp)
if (*lineptr == NULL || *n == 0)
{
+ char *new_lineptr;
*n = 120;
- *lineptr = (char *) malloc (*n);
- if (*lineptr == NULL)
- {
- result = -1;
- goto unlock_return;
- }
+ new_lineptr = (char *) realloc (*lineptr, *n);
+ if (new_lineptr == NULL)
+ {
+ result = -1;
+ goto unlock_return;
+ }
+ *lineptr = new_lineptr;
}
for (;;)
{
int i;
- i = getc (fp);
+ i = getc_maybe_unlocked (fp);
if (i == EOF)
- {
- result = -1;
- break;
- }
+ {
+ result = -1;
+ break;
+ }
/* Make enough space for len+1 (for final NUL) bytes. */
if (cur_len + 1 >= *n)
- {
- size_t needed_max =
- SSIZE_MAX < SIZE_MAX ? (size_t) SSIZE_MAX + 1 : SIZE_MAX;
- size_t needed = 2 * *n + 1; /* Be generous. */
- char *new_lineptr;
-
- if (needed_max < needed)
- needed = needed_max;
- if (cur_len + 1 >= needed)
- {
- result = -1;
- goto unlock_return;
- }
-
- new_lineptr = (char *) realloc (*lineptr, needed);
- if (new_lineptr == NULL)
- {
- result = -1;
- goto unlock_return;
- }
-
- *lineptr = new_lineptr;
- *n = needed;
- }
+ {
+ size_t needed_max =
+ SSIZE_MAX < SIZE_MAX ? (size_t) SSIZE_MAX + 1 : SIZE_MAX;
+ size_t needed = 2 * *n + 1; /* Be generous. */
+ char *new_lineptr;
+
+ if (needed_max < needed)
+ needed = needed_max;
+ if (cur_len + 1 >= needed)
+ {
+ result = -1;
+ errno = EOVERFLOW;
+ goto unlock_return;
+ }
+
+ new_lineptr = (char *) realloc (*lineptr, needed);
+ if (new_lineptr == NULL)
+ {
+ result = -1;
+ goto unlock_return;
+ }
+
+ *lineptr = new_lineptr;
+ *n = needed;
+ }
(*lineptr)[cur_len] = i;
cur_len++;
if (i == delimiter)
- break;
+ break;
}
(*lineptr)[cur_len] = '\0';
result = cur_len ? cur_len : result;
unlock_return:
- funlockfile (fp);
+ funlockfile (fp); /* doesn't set errno */
+
return result;
}
diff --git a/lib/getdelim.h b/lib/getdelim.h
deleted file mode 100644
index 8bc6130..0000000
--- a/lib/getdelim.h
+++ /dev/null
@@ -1,28 +0,0 @@
-/* getdelim.h --- Prototype for replacement getdelim function.
- Copyright (C) 2005 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 2, 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, write to the Free Software
- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- 02110-1301, USA. */
-
-/* Written by Simon Josefsson. */
-
-/* Get size_t, FILE, ssize_t. And getdelim, if available. */
-# include <stddef.h>
-# include <stdio.h>
-# include <sys/types.h>
-
-#if !HAVE_DECL_GETDELIM
-ssize_t getdelim (char **lineptr, size_t *n, int delimiter, FILE *stream);
-#endif /* !HAVE_GETDELIM */
diff --git a/lib/getdtablesize.c b/lib/getdtablesize.c
new file mode 100644
index 0000000..d234055
--- /dev/null
+++ b/lib/getdtablesize.c
@@ -0,0 +1,121 @@
+/* getdtablesize() function for platforms that don't have it.
+ Copyright (C) 2008-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2008.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <unistd.h>
+
+#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+
+# include <stdio.h>
+
+# include "msvc-inval.h"
+
+# if HAVE_MSVC_INVALID_PARAMETER_HANDLER
+static int
+_setmaxstdio_nothrow (int newmax)
+{
+ int result;
+
+ TRY_MSVC_INVAL
+ {
+ result = _setmaxstdio (newmax);
+ }
+ CATCH_MSVC_INVAL
+ {
+ result = -1;
+ }
+ DONE_MSVC_INVAL;
+
+ return result;
+}
+# define _setmaxstdio _setmaxstdio_nothrow
+# endif
+
+/* Cache for the previous getdtablesize () result. Safe to cache because
+ Windows also lacks setrlimit. */
+static int dtablesize;
+
+int
+getdtablesize (void)
+{
+ if (dtablesize == 0)
+ {
+ /* We are looking for the number N such that the valid file descriptors
+ are 0..N-1. It can be obtained through a loop as follows:
+ {
+ int fd;
+ for (fd = 3; fd < 65536; fd++)
+ if (dup2 (0, fd) == -1)
+ break;
+ return fd;
+ }
+ On Windows XP, the result is 2048.
+ The drawback of this loop is that it allocates memory for a libc
+ internal array that is never freed.
+
+ The number N can also be obtained as the upper bound for
+ _getmaxstdio (). _getmaxstdio () returns the maximum number of open
+ FILE objects. The sanity check in _setmaxstdio reveals the maximum
+ number of file descriptors. This too allocates memory, but it is
+ freed when we call _setmaxstdio with the original value. */
+ int orig_max_stdio = _getmaxstdio ();
+ unsigned int bound;
+ for (bound = 0x10000; _setmaxstdio (bound) < 0; bound = bound / 2)
+ ;
+ _setmaxstdio (orig_max_stdio);
+ dtablesize = bound;
+ }
+ return dtablesize;
+}
+
+#else
+
+# include <limits.h>
+# include <sys/resource.h>
+
+# ifndef RLIM_SAVED_CUR
+# define RLIM_SAVED_CUR RLIM_INFINITY
+# endif
+# ifndef RLIM_SAVED_MAX
+# define RLIM_SAVED_MAX RLIM_INFINITY
+# endif
+
+# ifdef __CYGWIN__
+ /* Cygwin 1.7.25 auto-increases the RLIMIT_NOFILE soft limit until it
+ hits the compile-time constant hard limit of 3200. We might as
+ well just report the hard limit. */
+# define rlim_cur rlim_max
+# endif
+
+int
+getdtablesize (void)
+{
+ struct rlimit lim;
+
+ if (getrlimit (RLIMIT_NOFILE, &lim) == 0
+ && 0 <= lim.rlim_cur && lim.rlim_cur <= INT_MAX
+ && lim.rlim_cur != RLIM_INFINITY
+ && lim.rlim_cur != RLIM_SAVED_CUR
+ && lim.rlim_cur != RLIM_SAVED_MAX)
+ return lim.rlim_cur;
+
+ return INT_MAX;
+}
+
+#endif
diff --git a/lib/getfilecon.c b/lib/getfilecon.c
new file mode 100644
index 0000000..a124071
--- /dev/null
+++ b/lib/getfilecon.c
@@ -0,0 +1,87 @@
+/* wrap getfilecon, lgetfilecon, and fgetfilecon
+ Copyright (C) 2009-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+/* written by Jim Meyering */
+
+#include <config.h>
+
+#include <selinux/selinux.h>
+
+#include <sys/types.h>
+#include <errno.h>
+#include <string.h>
+
+/* FIXME: remove this once there is an errno-gnu module
+ that guarantees the definition of ENODATA. */
+#ifndef ENODATA
+# define ENODATA ENOTSUP
+#endif
+
+#undef getfilecon
+#undef lgetfilecon
+#undef fgetfilecon
+int getfilecon (char const *file, security_context_t *con);
+int lgetfilecon (char const *file, security_context_t *con);
+int fgetfilecon (int fd, security_context_t *con);
+
+/* getfilecon, lgetfilecon, and fgetfilecon can all misbehave, be it
+ via an old version of libselinux where these would return 0 and set the
+ result context to NULL, or via a modern kernel+lib operating on a file
+ from a disk whose attributes were set by a kernel from around 2006.
+ In that latter case, the functions return a length of 10 for the
+ "unlabeled" context. Map both failures to a return value of -1, and
+ set errno to ENOTSUP in the first case, and ENODATA in the latter. */
+
+static int
+map_to_failure (int ret, security_context_t *con)
+{
+ if (ret == 0)
+ {
+ errno = ENOTSUP;
+ return -1;
+ }
+
+ if (ret == 10 && strcmp (*con, "unlabeled") == 0)
+ {
+ freecon (*con);
+ *con = NULL;
+ errno = ENODATA;
+ return -1;
+ }
+
+ return ret;
+}
+
+int
+rpl_getfilecon (char const *file, security_context_t *con)
+{
+ int ret = getfilecon (file, con);
+ return map_to_failure (ret, con);
+}
+
+int
+rpl_lgetfilecon (char const *file, security_context_t *con)
+{
+ int ret = lgetfilecon (file, con);
+ return map_to_failure (ret, con);
+}
+
+int
+rpl_fgetfilecon (int fd, security_context_t *con)
+{
+ int ret = fgetfilecon (fd, con);
+ return map_to_failure (ret, con);
+}
diff --git a/lib/getgroups.c b/lib/getgroups.c
index 615bd4f..b040505 100644
--- a/lib/getgroups.c
+++ b/lib/getgroups.c
@@ -1,11 +1,11 @@
/* provide consistent interface to getgroups for systems that don't allow N==0
- Copyright (C) 1996, 1999, 2003, 2006 Free Software Foundation, Inc.
+ Copyright (C) 1996, 1999, 2003, 2006-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,49 +13,112 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* written by Jim Meyering */
#include <config.h>
-#include <stdio.h>
-#include <sys/types.h>
+#include <unistd.h>
+
#include <errno.h>
#include <stdlib.h>
+#include <stdint.h>
+
+#if !HAVE_GETGROUPS
+
+/* Provide a stub that fails with ENOSYS, since there is no group
+ information available on mingw. */
+int
+getgroups (int n _GL_UNUSED, GETGROUPS_T *groups _GL_UNUSED)
+{
+ errno = ENOSYS;
+ return -1;
+}
+
+#else /* HAVE_GETGROUPS */
+
+# undef getgroups
+# ifndef GETGROUPS_ZERO_BUG
+# define GETGROUPS_ZERO_BUG 0
+# endif
-#include "xalloc.h"
+/* On OS X 10.6 and later, use the usual getgroups, not the one
+ supplied when _DARWIN_C_SOURCE is defined. _DARWIN_C_SOURCE is
+ normally defined, since it means "conform to POSIX, but add
+ non-POSIX extensions even if that violates the POSIX namespace
+ rules", which is what we normally want. But with getgroups there
+ is an inconsistency, and _DARWIN_C_SOURCE means "change getgroups()
+ so that it no longer works right". The BUGS section of compat(5)
+ says that the behavior is dubious if you compile different sections
+ of a program with different _DARWIN_C_SOURCE settings, so fix only
+ the offending symbol. */
+# ifdef __APPLE__
+int posix_getgroups (int, gid_t []) __asm ("_getgroups");
+# define getgroups posix_getgroups
+# endif
-/* On at least Ultrix 4.3 and NextStep 3.2, getgroups (0, 0) always fails.
- On other systems, it returns the number of supplemental groups for the
- process. This function handles that special case and lets the system-
- provided function handle all others. */
+/* On at least Ultrix 4.3 and NextStep 3.2, getgroups (0, NULL) always
+ fails. On other systems, it returns the number of supplemental
+ groups for the process. This function handles that special case
+ and lets the system-provided function handle all others. However,
+ it can fail with ENOMEM if memory is tight. It is unspecified
+ whether the effective group id is included in the list. */
int
-getgroups (int n, GETGROUPS_T *group)
+rpl_getgroups (int n, gid_t *group)
{
int n_groups;
GETGROUPS_T *gbuf;
int saved_errno;
-#undef getgroups
+ if (n < 0)
+ {
+ errno = EINVAL;
+ return -1;
+ }
- if (n != 0)
- return getgroups (n, group);
+ if (n != 0 || !GETGROUPS_ZERO_BUG)
+ {
+ int result;
+ if (sizeof *group == sizeof *gbuf)
+ return getgroups (n, (GETGROUPS_T *) group);
+
+ if (SIZE_MAX / sizeof *gbuf <= n)
+ {
+ errno = ENOMEM;
+ return -1;
+ }
+ gbuf = malloc (n * sizeof *gbuf);
+ if (!gbuf)
+ return -1;
+ result = getgroups (n, gbuf);
+ if (0 <= result)
+ {
+ n = result;
+ while (n--)
+ group[n] = gbuf[n];
+ }
+ saved_errno = errno;
+ free (gbuf);
+ errno = saved_errno;
+ return result;
+ }
n = 20;
while (1)
{
/* No need to worry about address arithmetic overflow here,
- since the ancient systems that we're running on have low
- limits on the number of secondary groups. */
- gbuf = xmalloc (n * sizeof *gbuf);
+ since the ancient systems that we're running on have low
+ limits on the number of secondary groups. */
+ gbuf = malloc (n * sizeof *gbuf);
+ if (!gbuf)
+ return -1;
n_groups = getgroups (n, gbuf);
- if (n_groups < n)
- break;
+ if (n_groups == -1 ? errno != EINVAL : n_groups < n)
+ break;
free (gbuf);
- n += 10;
+ n *= 2;
}
saved_errno = errno;
@@ -64,3 +127,5 @@ getgroups (int n, GETGROUPS_T *group)
return n_groups;
}
+
+#endif /* HAVE_GETGROUPS */
diff --git a/lib/gethostname.c b/lib/gethostname.c
index eedc40e..c4b64a2 100644
--- a/lib/gethostname.c
+++ b/lib/gethostname.c
@@ -1,11 +1,11 @@
/* gethostname emulation for SysV and POSIX.1.
- Copyright (C) 1992, 2003, 2006 Free Software Foundation, Inc.
+ Copyright (C) 1992, 2003, 2006, 2008-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,17 +13,25 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
-/* David MacKenzie <djm@gnu.ai.mit.edu> */
+/* David MacKenzie <djm@gnu.ai.mit.edu>
+ Windows port by Simon Josefsson <simon@josefsson.org> */
#include <config.h>
+#if !((defined _WIN32 || defined __WIN32__) && !defined __CYGWIN__)
+/* Unix API. */
+
+/* Specification. */
+#include <unistd.h>
+
#ifdef HAVE_UNAME
# include <sys/utsname.h>
#endif
+#include <string.h>
+
/* Put up to LEN chars of the host name into NAME.
Null terminate it if the name is shorter than LEN.
Return 0 if ok, -1 if error. */
@@ -46,7 +54,51 @@ gethostname (char *name, size_t len)
}
strncpy (name, uts.nodename, len);
#else
- strcpy (name, ""); /* Hardcode your system name if you want. */
+ strcpy (name, ""); /* Hardcode your system name if you want. */
#endif
return 0;
}
+
+#else
+/* Native Windows API. Which primitive to choose?
+ - gethostname() requires linking with -lws2_32.
+ - GetComputerName() does not return the right kind of hostname.
+ - GetComputerNameEx(ComputerNameDnsHostname,...) returns the right hostname,
+ but it is hard to use portably:
+ - It requires defining _WIN32_WINNT to at least 0x0500.
+ - With mingw, it also requires
+ "#define GetComputerNameEx GetComputerNameExA".
+ - With older versions of mingw, none of the declarations are present at
+ all, not even of the enum value ComputerNameDnsHostname.
+ So we use gethostname(). Linking with -lws2_32 is the least evil. */
+
+#define WIN32_LEAN_AND_MEAN
+/* Get winsock2.h. */
+#include <unistd.h>
+
+/* Get INT_MAX. */
+#include <limits.h>
+
+/* Get set_winsock_errno. */
+#include "w32sock.h"
+
+#include "sockets.h"
+
+#undef gethostname
+
+int
+rpl_gethostname (char *name, size_t len)
+{
+ int r;
+
+ if (len > INT_MAX)
+ len = INT_MAX;
+ gl_sockets_startup (SOCKETS_1_1);
+ r = gethostname (name, (int) len);
+ if (r < 0)
+ set_winsock_errno ();
+
+ return r;
+}
+
+#endif
diff --git a/lib/gethrxtime.c b/lib/gethrxtime.c
index 2046e06..fa356e8 100644
--- a/lib/gethrxtime.c
+++ b/lib/gethrxtime.c
@@ -1,11 +1,11 @@
/* gethrxtime -- get high resolution real time
- Copyright (C) 2005, 2006, 2007 Free Software Foundation, Inc.
+ Copyright (C) 2005-2007, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,15 +13,17 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
#include <config.h>
+#define GETHRXTIME_INLINE _GL_EXTERN_INLINE
#include "gethrxtime.h"
+#if ! (HAVE_ARITHMETIC_HRTIME_T && HAVE_DECL_GETHRTIME)
+
#include <sys/time.h>
#include "timespec.h"
@@ -33,30 +35,30 @@
xtime_t
gethrxtime (void)
{
-#if HAVE_NANOUPTIME
+# if HAVE_NANOUPTIME
{
struct timespec ts;
nanouptime (&ts);
return xtime_make (ts.tv_sec, ts.tv_nsec);
}
-#else
+# else
-# if defined CLOCK_MONOTONIC && HAVE_CLOCK_GETTIME
+# if defined CLOCK_MONOTONIC && HAVE_CLOCK_GETTIME
{
struct timespec ts;
if (clock_gettime (CLOCK_MONOTONIC, &ts) == 0)
return xtime_make (ts.tv_sec, ts.tv_nsec);
}
-# endif
+# endif
-# if HAVE_MICROUPTIME
+# if HAVE_MICROUPTIME
{
struct timeval tv;
microuptime (&tv);
return xtime_make (tv.tv_sec, 1000 * tv.tv_usec);
}
-# else
+# else
/* No monotonically increasing clocks are available; fall back on a
clock that might jump backwards, since it's the best we can do. */
{
@@ -64,6 +66,8 @@ gethrxtime (void)
gettime (&ts);
return xtime_make (ts.tv_sec, ts.tv_nsec);
}
+# endif
# endif
-#endif
}
+
+#endif
diff --git a/lib/gethrxtime.h b/lib/gethrxtime.h
index 2247f96..d69b6df 100644
--- a/lib/gethrxtime.h
+++ b/lib/gethrxtime.h
@@ -1,11 +1,11 @@
/* gethrxtime -- get high resolution real time
- Copyright (C) 2005 Free Software Foundation, Inc.
+ Copyright (C) 2005, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,26 +13,43 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
#ifndef GETHRXTIME_H_
-# define GETHRXTIME_H_ 1
+#define GETHRXTIME_H_ 1
-# include "xtime.h"
+#include "xtime.h"
+
+#ifndef _GL_INLINE_HEADER_BEGIN
+ #error "Please include config.h first."
+#endif
+_GL_INLINE_HEADER_BEGIN
+#ifndef GETHRXTIME_INLINE
+# define GETHRXTIME_INLINE _GL_INLINE
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
/* Get the current time, as a count of the number of nanoseconds since
an arbitrary epoch (e.g., the system boot time). Prefer a
high-resolution clock that is not subject to resetting or
drifting. */
-# if HAVE_ARITHMETIC_HRTIME_T && HAVE_DECL_GETHRTIME
-# include <time.h>
-static inline xtime_t gethrxtime (void) { return gethrtime (); }
+#if HAVE_ARITHMETIC_HRTIME_T && HAVE_DECL_GETHRTIME
+# include <time.h>
+GETHRXTIME_INLINE xtime_t gethrxtime (void) { return gethrtime (); }
# else
xtime_t gethrxtime (void);
-# endif
+#endif
+
+_GL_INLINE_HEADER_END
+
+#ifdef __cplusplus
+}
+#endif
#endif
diff --git a/lib/getline.c b/lib/getline.c
index c8c9244..dfc679a 100644
--- a/lib/getline.c
+++ b/lib/getline.c
@@ -1,9 +1,9 @@
/* getline.c --- Implementation of replacement getline function.
- Copyright (C) 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2005-2007, 2009-2016 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 2, or (at
+ published by the Free Software Foundation; either version 3, or (at
your option) any later version.
This program is distributed in the hope that it will be useful, but
@@ -12,16 +12,13 @@
General Public License for more details.
You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- 02110-1301, USA. */
+ along with this program; if not, see <http://www.gnu.org/licenses/>. */
/* Written by Simon Josefsson. */
#include <config.h>
-#include "getdelim.h"
-#include "getline.h"
+#include <stdio.h>
ssize_t
getline (char **lineptr, size_t *n, FILE *stream)
diff --git a/lib/getline.h b/lib/getline.h
deleted file mode 100644
index f0f61c4..0000000
--- a/lib/getline.h
+++ /dev/null
@@ -1,28 +0,0 @@
-/* getline.h --- Prototype for replacement getline function.
- Copyright (C) 2005 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 2, 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, write to the Free Software
- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- 02110-1301, USA. */
-
-/* Written by Simon Josefsson. */
-
-/* Get size_t, FILE, ssize_t. And getline, if available. */
-# include <stddef.h>
-# include <stdio.h>
-# include <sys/types.h>
-
-#if !HAVE_DECL_GETLINE
-ssize_t getline (char **lineptr, size_t *n, FILE *stream);
-#endif /* !HAVE_GETLINE */
diff --git a/lib/getloadavg.c b/lib/getloadavg.c
index cfa6273..a7ffd06 100644
--- a/lib/getloadavg.c
+++ b/lib/getloadavg.c
@@ -1,16 +1,15 @@
/* Get the system load averages.
- Copyright (C) 1985, 1986, 1987, 1988, 1989, 1991, 1992, 1993, 1994,
- 1995, 1997, 1999, 2000, 2003, 2004, 2005, 2006 Free Software
+ Copyright (C) 1985-1989, 1991-1995, 1997, 1999-2000, 2003-2016 Free Software
Foundation, Inc.
NOTE: The canonical source of this file is maintained with gnulib.
Bugs can be reported to bug-gnulib@gnu.org.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -18,62 +17,62 @@
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, write to the Free Software
- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
- USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Compile-time symbols that this file uses:
- HAVE_PSTAT_GETDYNAMIC Define this if your system has the
+ HAVE_PSTAT_GETDYNAMIC Define this if your system has the
pstat_getdynamic function. I think it
- is unique to HPUX9. The best way to get the
- definition is through the AC_FUNC_GETLOADAVG
- macro that comes with autoconf 2.13 or newer.
- If that isn't an option, then just put
- AC_CHECK_FUNCS(pstat_getdynamic) in your
- configure.in file.
- FIXUP_KERNEL_SYMBOL_ADDR() Adjust address in returned struct nlist.
- KERNEL_FILE Name of the kernel file to nlist.
- LDAV_CVT() Scale the load average from the kernel.
- Returns a double.
- LDAV_SYMBOL Name of kernel symbol giving load average.
- LOAD_AVE_TYPE Type of the load average array in the kernel.
- Must be defined unless one of
- apollo, DGUX, NeXT, or UMAX is defined;
+ is unique to HPUX9. The best way to get the
+ definition is through the AC_FUNC_GETLOADAVG
+ macro that comes with autoconf 2.13 or newer.
+ If that isn't an option, then just put
+ AC_CHECK_FUNCS(pstat_getdynamic) in your
+ configure.ac file.
+ HAVE_LIBPERFSTAT Define this if your system has the
+ perfstat_cpu_total function in libperfstat (AIX).
+ FIXUP_KERNEL_SYMBOL_ADDR() Adjust address in returned struct nlist.
+ KERNEL_FILE Name of the kernel file to nlist.
+ LDAV_CVT() Scale the load average from the kernel.
+ Returns a double.
+ LDAV_SYMBOL Name of kernel symbol giving load average.
+ LOAD_AVE_TYPE Type of the load average array in the kernel.
+ Must be defined unless one of
+ apollo, DGUX, NeXT, or UMAX is defined;
or we have libkstat;
- otherwise, no load average is available.
+ otherwise, no load average is available.
HAVE_NLIST_H nlist.h is available. NLIST_STRUCT defaults
to this.
- NLIST_STRUCT Include nlist.h, not a.out.h, and
- the nlist n_name element is a pointer,
- not an array.
- HAVE_STRUCT_NLIST_N_UN_N_NAME `n_un.n_name' is member of `struct nlist'.
- LINUX_LDAV_FILE [__linux__, __CYGWIN__]: File containing
- load averages.
+ NLIST_STRUCT Include nlist.h, not a.out.h.
+ N_NAME_POINTER The nlist n_name element is a pointer,
+ not an array.
+ HAVE_STRUCT_NLIST_N_UN_N_NAME 'n_un.n_name' is member of 'struct nlist'.
+ LINUX_LDAV_FILE [__linux__, __CYGWIN__]: File containing
+ load averages.
Specific system predefines this file uses, aside from setting
default values if not emacs:
apollo
- BSD Real BSD, not just BSD-like.
+ BSD Real BSD, not just BSD-like.
convex
DGUX
- eunice UNIX emulator under VMS.
+ eunice UNIX emulator under VMS.
hpux
- __MSDOS__ No-op for MSDOS.
+ __MSDOS__ No-op for MSDOS.
NeXT
sgi
- sequent Sequent Dynix 3.x.x (BSD)
- _SEQUENT_ Sequent DYNIX/ptx 1.x.x (SYSV)
+ sequent Sequent Dynix 3.x.x (BSD)
+ _SEQUENT_ Sequent DYNIX/ptx 1.x.x (SYSV)
sony_news NEWS-OS (works at least for 4.1C)
UMAX
UMAX4_3
VMS
- WINDOWS32 No-op for Windows95/NT.
- __linux__ Linux: assumes /proc file system mounted.
- Support from Michael K. Johnson.
- __CYGWIN__ Cygwin emulates linux /proc/loadavg.
- __NetBSD__ NetBSD: assumes /kern file system mounted.
+ WINDOWS32 No-op for Windows95/NT.
+ __linux__ Linux: assumes /proc file system mounted.
+ Support from Michael K. Johnson.
+ __CYGWIN__ Cygwin emulates linux /proc/loadavg.
+ __NetBSD__ NetBSD: assumes /kern file system mounted.
In addition, to avoid nesting many #ifdefs, we internally set
LDAV_DONE to indicate that the load average has been computed.
@@ -81,50 +80,22 @@
We also #define LDAV_PRIVILEGED if a program will require
special installation to be able to call getloadavg. */
-/* "configure" defines CONFIGURING_GETLOADAVG to sidestep problems
- with partially-configured source directories. */
+#include <config.h>
-#ifndef CONFIGURING_GETLOADAVG
-# include <config.h>
-# include <stdbool.h>
-#endif
+/* Specification. */
+#include <stdlib.h>
#include <errno.h>
+#include <stdbool.h>
#include <stdio.h>
-#include <stdlib.h>
-
-/* Exclude all the code except the test program at the end
- if the system has its own `getloadavg' function. */
-
-#ifndef HAVE_GETLOADAVG
# include <sys/types.h>
-/* Both the Emacs and non-Emacs sections want this. Some
- configuration files' definitions for the LOAD_AVE_CVT macro (like
- sparc.h's) use macros like FSCALE, defined here. */
-# if defined (unix) || defined (__unix)
+# if HAVE_SYS_PARAM_H
# include <sys/param.h>
# endif
-# include "c-strtod.h"
-# include "cloexec.h"
# include "intprops.h"
-# include "xalloc.h"
-
-/* The existing Emacs configuration files define a macro called
- LOAD_AVE_CVT, which accepts a value of type LOAD_AVE_TYPE, and
- returns the load average multiplied by 100. What we actually want
- is a macro called LDAV_CVT, which returns the load average as an
- unmultiplied double.
-
- For backwards compatibility, we'll define LDAV_CVT in terms of
- LOAD_AVE_CVT, but future machine config files should just define
- LDAV_CVT directly. */
-
-# if !defined (LDAV_CVT) && defined (LOAD_AVE_CVT)
-# define LDAV_CVT(n) (LOAD_AVE_CVT (n) / 100.0)
-# endif
# if !defined (BSD) && defined (ultrix)
/* Ultrix behaves like BSD on Vaxen. */
@@ -188,6 +159,8 @@
# include <sys/socket.h>
# include <net/route.h>
# include <sys/table.h>
+/* Tru64 4.0D's table.h redefines sys */
+# undef sys
# endif
# if defined (__osf__) && (defined (mips) || defined (__mips__))
@@ -199,7 +172,7 @@
default, but _MACH_IND_SYS_TYPES is defined in <sys/types.h>. Combine
that with a couple of other things and we'll have a unique match. */
# if !defined (tek4300) && defined (unix) && defined (m68k) && defined (mc68000) && defined (mc68020) && defined (_MACH_IND_SYS_TYPES)
-# define tek4300 /* Define by emacs, but not by other users. */
+# define tek4300 /* Define by emacs, but not by other users. */
# endif
@@ -254,7 +227,7 @@
# define LOAD_AVE_TYPE long
# endif
-# ifdef _AIX
+# if defined _AIX && ! defined HAVE_LIBPERFSTAT
# define LOAD_AVE_TYPE long
# endif
@@ -309,11 +282,11 @@
# define FSCALE 100.0
# endif
-# ifdef _AIX
+# if defined _AIX && !defined HAVE_LIBPERFSTAT
# define FSCALE 65536.0
# endif
-# endif /* Not FSCALE. */
+# endif /* Not FSCALE. */
# if !defined (LDAV_CVT) && defined (FSCALE)
# define LDAV_CVT(n) (((double) (n)) / FSCALE)
@@ -347,7 +320,7 @@
# define LDAV_SYMBOL "_Loadavg"
# endif
-# if !defined (LDAV_SYMBOL) && ((defined (hpux) && !defined (hp9000s300)) || defined (_SEQUENT_) || defined (SVR4) || defined (ISC) || defined (sgi) || (defined (ardent) && defined (titan)) || defined (_AIX))
+# if !defined (LDAV_SYMBOL) && ((defined (hpux) && !defined (hp9000s300)) || defined (_SEQUENT_) || defined (SVR4) || defined (ISC) || defined (sgi) || (defined (ardent) && defined (titan)) || (defined (_AIX) && !defined(HAVE_LIBPERFSTAT)))
# define LDAV_SYMBOL "avenrun"
# endif
@@ -370,7 +343,6 @@
# endif /* NLIST_STRUCT */
# ifdef SUNOS_5
-# include <fcntl.h>
# include <kvm.h>
# include <kstat.h>
# endif
@@ -404,6 +376,15 @@
# endif /* LOAD_AVE_TYPE */
+# if defined HAVE_LIBPERFSTAT
+# include <sys/protosw.h>
+# include <libperfstat.h>
+# include <sys/proc.h>
+# ifndef SBITS
+# define SBITS 16
+# endif
+# endif
+
# if defined (__GNU__) && !defined (NeXT)
/* Note that NeXT Openstep defines __GNU__ even though it should not. */
/* GNU system acts much like NeXT, for load average purposes,
@@ -450,7 +431,10 @@
# include <sys/dg_sys_info.h>
# endif
-# include "fcntl--.h"
+# if (defined __linux__ || defined __CYGWIN__ || defined SUNOS_5 \
+ || (defined LOAD_AVE_TYPE && ! defined __VMS))
+# include <fcntl.h>
+# endif
/* Avoid static vars inside a function since in HPUX they dump as pure. */
@@ -465,19 +449,19 @@ static unsigned int samples;
# endif /* UMAX */
# ifdef DGUX
-static struct dg_sys_info_load_info load_info; /* what-a-mouthful! */
+static struct dg_sys_info_load_info load_info; /* what-a-mouthful! */
# endif /* DGUX */
# if !defined (HAVE_LIBKSTAT) && defined (LOAD_AVE_TYPE)
/* File descriptor open to /dev/kmem or VMS load ave driver. */
static int channel;
-/* True iff channel is valid. */
+/* True if channel is valid. */
static bool getloadavg_initialized;
/* Offset in kmem to seek to read load average, or 0 means invalid. */
static long offset;
# if ! defined __VMS && ! defined sgi && ! defined __linux__
-static struct nlist nl[2];
+static struct nlist name_list[2];
# endif
# ifdef SUNOS_5
@@ -489,27 +473,26 @@ static kvm_t *kd;
/* Put the 1 minute, 5 minute and 15 minute load averages
into the first NELEM elements of LOADAVG.
Return the number written (never more than 3, but may be less than NELEM),
- or -1 if an error occurred. */
+ or -1 (setting errno) if an error occurred. */
int
getloadavg (double loadavg[], int nelem)
{
- int elem = 0; /* Return value. */
+ int elem = 0; /* Return value. */
# ifdef NO_GET_LOAD_AVG
# define LDAV_DONE
- /* Set errno to zero to indicate that there was no particular error;
- this function just can't work at all on this system. */
- errno = 0;
+ errno = ENOSYS;
elem = -1;
# endif
-# if !defined (LDAV_DONE) && defined (HAVE_LIBKSTAT)
+# if !defined (LDAV_DONE) && defined (HAVE_LIBKSTAT) /* Solaris <= 2.6 */
/* Use libkstat because we don't have to be root. */
# define LDAV_DONE
kstat_ctl_t *kc;
kstat_t *ksp;
kstat_named_t *kn;
+ int saved_errno;
kc = kstat_open ();
if (kc == 0)
@@ -536,22 +519,25 @@ getloadavg (double loadavg[], int nelem)
{
kn = kstat_data_lookup (ksp, "avenrun_5min");
if (kn != 0)
- {
- loadavg[elem++] = (double) kn->value.ul / FSCALE;
-
- if (nelem >= 3)
- {
- kn = kstat_data_lookup (ksp, "avenrun_15min");
- if (kn != 0)
- loadavg[elem++] = (double) kn->value.ul / FSCALE;
- }
- }
+ {
+ loadavg[elem++] = (double) kn->value.ul / FSCALE;
+
+ if (nelem >= 3)
+ {
+ kn = kstat_data_lookup (ksp, "avenrun_15min");
+ if (kn != 0)
+ loadavg[elem++] = (double) kn->value.ul / FSCALE;
+ }
+ }
}
+ saved_errno = errno;
kstat_close (kc);
+ errno = saved_errno;
# endif /* HAVE_LIBKSTAT */
# if !defined (LDAV_DONE) && defined (hpux) && defined (HAVE_PSTAT_GETDYNAMIC)
+ /* HP-UX */
/* Use pstat_getdynamic() because we don't have to be root. */
# define LDAV_DONE
# undef LOAD_AVE_TYPE
@@ -568,7 +554,24 @@ getloadavg (double loadavg[], int nelem)
# endif /* hpux && HAVE_PSTAT_GETDYNAMIC */
+# if ! defined LDAV_DONE && defined HAVE_LIBPERFSTAT /* AIX */
+# define LDAV_DONE
+# undef LOAD_AVE_TYPE
+/* Use perfstat_cpu_total because we don't have to be root. */
+ {
+ perfstat_cpu_total_t cpu_stats;
+ int result = perfstat_cpu_total (NULL, &cpu_stats, sizeof cpu_stats, 1);
+ if (result == -1)
+ return result;
+ loadavg[0] = cpu_stats.loadavg[0] / (double)(1 << SBITS);
+ loadavg[1] = cpu_stats.loadavg[1] / (double)(1 << SBITS);
+ loadavg[2] = cpu_stats.loadavg[2] / (double)(1 << SBITS);
+ elem = 3;
+ }
+# endif
+
# if !defined (LDAV_DONE) && (defined (__linux__) || defined (__CYGWIN__))
+ /* Linux without glibc, Cygwin */
# define LDAV_DONE
# undef LOAD_AVE_TYPE
@@ -578,36 +581,54 @@ getloadavg (double loadavg[], int nelem)
char ldavgbuf[3 * (INT_STRLEN_BOUND (int) + sizeof ".00 ")];
char const *ptr = ldavgbuf;
- int fd, count;
+ int fd, count, saved_errno;
fd = open (LINUX_LDAV_FILE, O_RDONLY);
if (fd == -1)
return -1;
count = read (fd, ldavgbuf, sizeof ldavgbuf - 1);
+ saved_errno = errno;
(void) close (fd);
+ errno = saved_errno;
if (count <= 0)
return -1;
ldavgbuf[count] = '\0';
for (elem = 0; elem < nelem; elem++)
{
- char *endptr;
- double d = c_strtod (ptr, &endptr);
- if (ptr == endptr)
- {
- if (elem == 0)
- return -1;
- break;
- }
- loadavg[elem] = d;
- ptr = endptr;
+ double numerator = 0;
+ double denominator = 1;
+
+ while (*ptr == ' ')
+ ptr++;
+
+ /* Finish if this number is missing, and report an error if all
+ were missing. */
+ if (! ('0' <= *ptr && *ptr <= '9'))
+ {
+ if (elem == 0)
+ {
+ errno = ENOTSUP;
+ return -1;
+ }
+ break;
+ }
+
+ while ('0' <= *ptr && *ptr <= '9')
+ numerator = 10 * numerator + (*ptr++ - '0');
+
+ if (*ptr == '.')
+ for (ptr++; '0' <= *ptr && *ptr <= '9'; ptr++)
+ numerator = 10 * numerator + (*ptr - '0'), denominator *= 10;
+
+ loadavg[elem++] = numerator / denominator;
}
return elem;
# endif /* __linux__ || __CYGWIN__ */
-# if !defined (LDAV_DONE) && defined (__NetBSD__)
+# if !defined (LDAV_DONE) && defined (__NetBSD__) /* NetBSD < 0.9 */
# define LDAV_DONE
# undef LOAD_AVE_TYPE
@@ -623,11 +644,14 @@ getloadavg (double loadavg[], int nelem)
if (fp == NULL)
return -1;
count = fscanf (fp, "%lu %lu %lu %lu\n",
- &load_ave[0], &load_ave[1], &load_ave[2],
- &scale);
+ &load_ave[0], &load_ave[1], &load_ave[2],
+ &scale);
(void) fclose (fp);
if (count != 4)
- return -1;
+ {
+ errno = ENOTSUP;
+ return -1;
+ }
for (elem = 0; elem < nelem; elem++)
loadavg[elem] = (double) load_ave[elem] / (double) scale;
@@ -636,7 +660,7 @@ getloadavg (double loadavg[], int nelem)
# endif /* __NetBSD__ */
-# if !defined (LDAV_DONE) && defined (NeXT)
+# if !defined (LDAV_DONE) && defined (NeXT) /* NeXTStep */
# define LDAV_DONE
/* The NeXT code was adapted from iscreen 3.2. */
@@ -650,25 +674,28 @@ getloadavg (double loadavg[], int nelem)
if (!getloadavg_initialized)
{
if (processor_set_default (host_self (), &default_set) == KERN_SUCCESS)
- getloadavg_initialized = true;
+ getloadavg_initialized = true;
}
if (getloadavg_initialized)
{
info_count = PROCESSOR_SET_BASIC_INFO_COUNT;
if (processor_set_info (default_set, PROCESSOR_SET_BASIC_INFO, &host,
- (processor_set_info_t) &info, &info_count)
- != KERN_SUCCESS)
- getloadavg_initialized = false;
+ (processor_set_info_t) &info, &info_count)
+ != KERN_SUCCESS)
+ getloadavg_initialized = false;
else
- {
- if (nelem > 0)
- loadavg[elem++] = (double) info.load_average / LOAD_SCALE;
- }
+ {
+ if (nelem > 0)
+ loadavg[elem++] = (double) info.load_average / LOAD_SCALE;
+ }
}
if (!getloadavg_initialized)
- return -1;
+ {
+ errno = ENOTSUP;
+ return -1;
+ }
# endif /* NeXT */
# if !defined (LDAV_DONE) && defined (UMAX)
@@ -696,24 +723,24 @@ getloadavg (double loadavg[], int nelem)
desc.sd_size = sizeof conf;
if (inq_stats (1, &desc))
- return -1;
+ return -1;
c = 0;
for (i = 0; i < conf.config_maxclass; ++i)
- {
- struct class_stats stats;
- bzero ((char *) &stats, sizeof stats);
+ {
+ struct class_stats stats;
+ memset (&stats, 0, sizeof stats);
- desc.sd_type = CPUTYPE_CLASS;
- desc.sd_objid = i;
- desc.sd_addr = (char *) &stats;
- desc.sd_size = sizeof stats;
+ desc.sd_type = CPUTYPE_CLASS;
+ desc.sd_objid = i;
+ desc.sd_addr = (char *) &stats;
+ desc.sd_size = sizeof stats;
- if (inq_stats (1, &desc))
- return -1;
+ if (inq_stats (1, &desc))
+ return -1;
- c += stats.class_numcpus;
- }
+ c += stats.class_numcpus;
+ }
cpus = c;
samples = cpus < 2 ? 3 : (2 * cpus / 3);
}
@@ -734,7 +761,7 @@ getloadavg (double loadavg[], int nelem)
{
load += proc_sum_data.ps_nrun[j];
if (j++ == PS_NRUNSIZE)
- j = 0;
+ j = 0;
}
if (nelem > 0)
@@ -745,10 +772,10 @@ getloadavg (double loadavg[], int nelem)
# define LDAV_DONE
/* This call can return -1 for an error, but with good args
it's not supposed to fail. The first argument is for no
- apparent reason of type `long int *'. */
+ apparent reason of type 'long int *'. */
dg_sys_info ((long int *) &load_info,
- DG_SYS_INFO_LOAD_INFO_TYPE,
- DG_SYS_INFO_LOAD_VERSION_0);
+ DG_SYS_INFO_LOAD_INFO_TYPE,
+ DG_SYS_INFO_LOAD_VERSION_0);
if (nelem > 0)
loadavg[elem++] = load_info.one_minute;
@@ -792,9 +819,10 @@ getloadavg (double loadavg[], int nelem)
= (load_ave.tl_lscale == 0
? load_ave.tl_avenrun.d[0]
: (load_ave.tl_avenrun.l[0] / (double) load_ave.tl_lscale));
-# endif /* OSF_MIPS */
+# endif /* OSF_MIPS */
# if !defined (LDAV_DONE) && (defined (__MSDOS__) || defined (WINDOWS32))
+ /* DJGPP */
# define LDAV_DONE
/* A faithful emulation is going to have to be saved for a rainy day. */
@@ -804,7 +832,7 @@ getloadavg (double loadavg[], int nelem)
}
# endif /* __MSDOS__ || WINDOWS32 */
-# if !defined (LDAV_DONE) && defined (OSF_ALPHA)
+# if !defined (LDAV_DONE) && defined (OSF_ALPHA) /* OSF/1 */
# define LDAV_DONE
struct tbl_loadavg load_ave;
@@ -812,11 +840,11 @@ getloadavg (double loadavg[], int nelem)
for (elem = 0; elem < nelem; elem++)
loadavg[elem]
= (load_ave.tl_lscale == 0
- ? load_ave.tl_avenrun.d[elem]
- : (load_ave.tl_avenrun.l[elem] / (double) load_ave.tl_lscale));
+ ? load_ave.tl_avenrun.d[elem]
+ : (load_ave.tl_avenrun.l[elem] / (double) load_ave.tl_lscale));
# endif /* OSF_ALPHA */
-# if ! defined LDAV_DONE && defined __VMS
+# if ! defined LDAV_DONE && defined __VMS /* VMS */
/* VMS specific code -- read from the Load Ave driver. */
LOAD_AVE_TYPE load_ave[3];
@@ -840,27 +868,31 @@ getloadavg (double loadavg[], int nelem)
$DESCRIPTOR (descriptor, "LAV0:");
# endif
if (sys$assign (&descriptor, &channel, 0, 0) & 1)
- getloadavg_initialized = true;
+ getloadavg_initialized = true;
}
/* Read the load average vector. */
if (getloadavg_initialized
&& !(sys$qiow (0, channel, IO$_READVBLK, 0, 0, 0,
- load_ave, 12, 0, 0, 0, 0) & 1))
+ load_ave, 12, 0, 0, 0, 0) & 1))
{
sys$dassgn (channel);
getloadavg_initialized = false;
}
if (!getloadavg_initialized)
- return -1;
+ {
+ errno = ENOTSUP;
+ return -1;
+ }
# endif /* ! defined LDAV_DONE && defined __VMS */
# if ! defined LDAV_DONE && defined LOAD_AVE_TYPE && ! defined __VMS
+ /* IRIX, other old systems */
/* UNIX-specific code -- read the average from /dev/kmem. */
-# define LDAV_PRIVILEGED /* This code requires special installation. */
+# define LDAV_PRIVILEGED /* This code requires special installation. */
LOAD_AVE_TYPE load_ave[3];
@@ -868,41 +900,39 @@ getloadavg (double loadavg[], int nelem)
if (offset == 0)
{
# ifndef sgi
-# ifndef NLIST_STRUCT
- strcpy (nl[0].n_name, LDAV_SYMBOL);
- strcpy (nl[1].n_name, "");
+# if ! defined NLIST_STRUCT || ! defined N_NAME_POINTER
+ strcpy (name_list[0].n_name, LDAV_SYMBOL);
+ strcpy (name_list[1].n_name, "");
# else /* NLIST_STRUCT */
# ifdef HAVE_STRUCT_NLIST_N_UN_N_NAME
- nl[0].n_un.n_name = LDAV_SYMBOL;
- nl[1].n_un.n_name = 0;
+ name_list[0].n_un.n_name = LDAV_SYMBOL;
+ name_list[1].n_un.n_name = 0;
# else /* not HAVE_STRUCT_NLIST_N_UN_N_NAME */
- nl[0].n_name = LDAV_SYMBOL;
- nl[1].n_name = 0;
+ name_list[0].n_name = LDAV_SYMBOL;
+ name_list[1].n_name = 0;
# endif /* not HAVE_STRUCT_NLIST_N_UN_N_NAME */
# endif /* NLIST_STRUCT */
# ifndef SUNOS_5
if (
# if !(defined (_AIX) && !defined (ps2))
- nlist (KERNEL_FILE, nl)
+ nlist (KERNEL_FILE, name_list)
# else /* _AIX */
- knlist (nl, 1, sizeof (nl[0]))
+ knlist (name_list, 1, sizeof (name_list[0]))
# endif
- >= 0)
- /* Omit "&& nl[0].n_type != 0 " -- it breaks on Sun386i. */
- {
+ >= 0)
+ /* Omit "&& name_list[0].n_type != 0 " -- it breaks on Sun386i. */
+ {
# ifdef FIXUP_KERNEL_SYMBOL_ADDR
- FIXUP_KERNEL_SYMBOL_ADDR (nl);
+ FIXUP_KERNEL_SYMBOL_ADDR (name_list);
# endif
- offset = nl[0].n_value;
- }
+ offset = name_list[0].n_value;
+ }
# endif /* !SUNOS_5 */
# else /* sgi */
- int ldav_off;
-
- ldav_off = sysmp (MP_KERNADDR, MPKA_AVENRUN);
+ ptrdiff_t ldav_off = sysmp (MP_KERNADDR, MPKA_AVENRUN);
if (ldav_off != -1)
- offset = (long int) ldav_off & 0x7fffffff;
+ offset = (long int) ldav_off & 0x7fffffff;
# endif /* sgi */
}
@@ -910,25 +940,39 @@ getloadavg (double loadavg[], int nelem)
if (!getloadavg_initialized)
{
# ifndef SUNOS_5
- channel = open ("/dev/kmem", O_RDONLY);
- if (channel >= 0)
- {
- /* Set the channel to close on exec, so it does not
- litter any child's descriptor table. */
- set_cloexec_flag (channel, true);
- getloadavg_initialized = true;
- }
+ /* Set the channel to close on exec, so it does not
+ litter any child's descriptor table. */
+# ifndef O_CLOEXEC
+# define O_CLOEXEC 0
+# endif
+ int fd = open ("/dev/kmem", O_RDONLY | O_CLOEXEC);
+ if (0 <= fd)
+ {
+# if F_DUPFD_CLOEXEC
+ if (fd <= STDERR_FILENO)
+ {
+ int fd1 = fcntl (fd, F_DUPFD_CLOEXEC, STDERR_FILENO + 1);
+ close (fd);
+ fd = fd1;
+ }
+# endif
+ if (0 <= fd)
+ {
+ channel = fd;
+ getloadavg_initialized = true;
+ }
+ }
# else /* SUNOS_5 */
/* We pass 0 for the kernel, corefile, and swapfile names
- to use the currently running kernel. */
+ to use the currently running kernel. */
kd = kvm_open (0, 0, 0, O_RDONLY, 0);
if (kd != 0)
- {
- /* nlist the currently running kernel. */
- kvm_nlist (kd, nl);
- offset = nl[0].n_value;
- getloadavg_initialized = true;
- }
+ {
+ /* nlist the currently running kernel. */
+ kvm_nlist (kd, name_list);
+ offset = name_list[0].n_value;
+ getloadavg_initialized = true;
+ }
# endif /* SUNOS_5 */
}
@@ -938,24 +982,27 @@ getloadavg (double loadavg[], int nelem)
/* Try to read the load. */
# ifndef SUNOS_5
if (lseek (channel, offset, 0) == -1L
- || read (channel, (char *) load_ave, sizeof (load_ave))
- != sizeof (load_ave))
- {
- close (channel);
- getloadavg_initialized = false;
- }
+ || read (channel, (char *) load_ave, sizeof (load_ave))
+ != sizeof (load_ave))
+ {
+ close (channel);
+ getloadavg_initialized = false;
+ }
# else /* SUNOS_5 */
if (kvm_read (kd, offset, (char *) load_ave, sizeof (load_ave))
- != sizeof (load_ave))
- {
- kvm_close (kd);
- getloadavg_initialized = false;
- }
+ != sizeof (load_ave))
+ {
+ kvm_close (kd);
+ getloadavg_initialized = false;
+ }
# endif /* SUNOS_5 */
}
if (offset == 0 || !getloadavg_initialized)
- return -1;
+ {
+ errno = ENOTSUP;
+ return -1;
+ }
# endif /* ! defined LDAV_DONE && defined LOAD_AVE_TYPE && ! defined __VMS */
# if !defined (LDAV_DONE) && defined (LOAD_AVE_TYPE) /* Including VMS. */
@@ -970,51 +1017,8 @@ getloadavg (double loadavg[], int nelem)
# endif /* !LDAV_DONE && LOAD_AVE_TYPE */
# if !defined LDAV_DONE
- /* Set errno to zero to indicate that there was no particular error;
- this function just can't work at all on this system. */
- errno = 0;
+ errno = ENOSYS;
elem = -1;
# endif
return elem;
}
-
-#endif /* ! HAVE_GETLOADAVG */
-
-#ifdef TEST
-int
-main (int argc, char **argv)
-{
- int naptime = 0;
-
- if (argc > 1)
- naptime = atoi (argv[1]);
-
- while (1)
- {
- double avg[3];
- int loads;
-
- errno = 0; /* Don't be misled if it doesn't set errno. */
- loads = getloadavg (avg, 3);
- if (loads == -1)
- {
- perror ("Error getting load average");
- return EXIT_FAILURE;
- }
- if (loads > 0)
- printf ("1-minute: %f ", avg[0]);
- if (loads > 1)
- printf ("5-minute: %f ", avg[1]);
- if (loads > 2)
- printf ("15-minute: %f ", avg[2]);
- if (loads > 0)
- putchar ('\n');
-
- if (naptime == 0)
- break;
- sleep (naptime);
- }
-
- return EXIT_SUCCESS;
-}
-#endif /* TEST */
diff --git a/lib/getlogin.c b/lib/getlogin.c
new file mode 100644
index 0000000..3bbf2ea
--- /dev/null
+++ b/lib/getlogin.c
@@ -0,0 +1,41 @@
+/* Provide a working getlogin for systems which lack it.
+
+ Copyright (C) 2010-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Bruno Haible, 2010. */
+
+#include <config.h>
+
+/* Specification. */
+#include <unistd.h>
+
+#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+# define WIN32_LEAN_AND_MEAN
+# include <windows.h>
+#endif
+
+char *
+getlogin (void)
+{
+#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+ static char login_name[1024];
+ DWORD sz = sizeof (login_name);
+
+ if (GetUserName (login_name, &sz))
+ return login_name;
+#endif
+ return NULL;
+}
diff --git a/lib/getndelim2.c b/lib/getndelim2.c
index 9a9e6e7..b8bc98f 100644
--- a/lib/getndelim2.c
+++ b/lib/getndelim2.c
@@ -1,13 +1,13 @@
/* getndelim2 - Read a line from a stream, stopping at one of 2 delimiters,
with bounded memory allocation.
- Copyright (C) 1993, 1996, 1997, 1998, 2000, 2003, 2004, 2006 Free
+ Copyright (C) 1993, 1996-1998, 2000, 2003-2004, 2006, 2008-2016 Free
Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -15,8 +15,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Originally written by Jan Brittenson, bson@gnu.ai.mit.edu. */
@@ -24,20 +23,41 @@
#include "getndelim2.h"
-#include <stdlib.h>
+#include <stdbool.h>
#include <stddef.h>
+#include <stdlib.h>
+#include <string.h>
#if USE_UNLOCKED_IO
# include "unlocked-io.h"
#endif
+#if !HAVE_FLOCKFILE
+# undef flockfile
+# define flockfile(x) ((void) 0)
+#endif
+#if !HAVE_FUNLOCKFILE
+# undef funlockfile
+# define funlockfile(x) ((void) 0)
+#endif
#include <limits.h>
#include <stdint.h>
+#include "freadptr.h"
+#include "freadseek.h"
+#include "memchr2.h"
+
#ifndef SSIZE_MAX
# define SSIZE_MAX ((ssize_t) (SIZE_MAX / 2))
#endif
+/* Use this to suppress gcc's "...may be used before initialized" warnings. */
+#ifdef lint
+# define IF_LINT(Code) Code
+#else
+# define IF_LINT(Code) /* empty */
+#endif
+
/* The maximum value that getndelim2 can return without suffering from
overflow problems, either internally (because of pointer
subtraction overflow) or due to the API (because of ssize_t). */
@@ -51,18 +71,19 @@ ssize_t
getndelim2 (char **lineptr, size_t *linesize, size_t offset, size_t nmax,
int delim1, int delim2, FILE *stream)
{
- size_t nbytes_avail; /* Allocated but unused bytes in *LINEPTR. */
- char *read_pos; /* Where we're reading into *LINEPTR. */
+ size_t nbytes_avail; /* Allocated but unused bytes in *LINEPTR. */
+ char *read_pos; /* Where we're reading into *LINEPTR. */
ssize_t bytes_stored = -1;
char *ptr = *lineptr;
size_t size = *linesize;
+ bool found_delimiter;
if (!ptr)
{
size = nmax < MIN_CHUNK ? nmax : MIN_CHUNK;
ptr = malloc (size);
if (!ptr)
- return -1;
+ return -1;
}
if (size < offset)
@@ -74,61 +95,111 @@ getndelim2 (char **lineptr, size_t *linesize, size_t offset, size_t nmax,
if (nbytes_avail == 0 && nmax <= size)
goto done;
- for (;;)
- {
- /* Here always ptr + size == read_pos + nbytes_avail. */
+ /* Normalize delimiters, since memchr2 doesn't handle EOF. */
+ if (delim1 == EOF)
+ delim1 = delim2;
+ else if (delim2 == EOF)
+ delim2 = delim1;
- int c;
+ flockfile (stream);
+
+ found_delimiter = false;
+ do
+ {
+ /* Here always ptr + size == read_pos + nbytes_avail.
+ Also nbytes_avail > 0 || size < nmax. */
+
+ int c IF_LINT (= 0);
+ const char *buffer;
+ size_t buffer_len;
+
+ buffer = freadptr (stream, &buffer_len);
+ if (buffer)
+ {
+ if (delim1 != EOF)
+ {
+ const char *end = memchr2 (buffer, delim1, delim2, buffer_len);
+ if (end)
+ {
+ buffer_len = end - buffer + 1;
+ found_delimiter = true;
+ }
+ }
+ }
+ else
+ {
+ c = getc (stream);
+ if (c == EOF)
+ {
+ /* Return partial line, if any. */
+ if (read_pos == ptr)
+ goto unlock_done;
+ else
+ break;
+ }
+ if (c == delim1 || c == delim2)
+ found_delimiter = true;
+ buffer_len = 1;
+ }
/* We always want at least one byte left in the buffer, since we
- always (unless we get an error while reading the first byte)
- NUL-terminate the line buffer. */
-
- if (nbytes_avail < 2 && size < nmax)
- {
- size_t newsize = size < MIN_CHUNK ? size + MIN_CHUNK : 2 * size;
- char *newptr;
-
- if (! (size < newsize && newsize <= nmax))
- newsize = nmax;
-
- if (GETNDELIM2_MAXIMUM < newsize - offset)
- {
- size_t newsizemax = offset + GETNDELIM2_MAXIMUM + 1;
- if (size == newsizemax)
- goto done;
- newsize = newsizemax;
- }
-
- nbytes_avail = newsize - (read_pos - ptr);
- newptr = realloc (ptr, newsize);
- if (!newptr)
- goto done;
- ptr = newptr;
- size = newsize;
- read_pos = size - nbytes_avail + ptr;
- }
-
- c = getc (stream);
- if (c == EOF)
- {
- /* Return partial line, if any. */
- if (read_pos == ptr)
- goto done;
- else
- break;
- }
-
- if (nbytes_avail >= 2)
- {
- *read_pos++ = c;
- nbytes_avail--;
- }
-
- if (c == delim1 || c == delim2)
- /* Return the line. */
- break;
+ always (unless we get an error while reading the first byte)
+ NUL-terminate the line buffer. */
+
+ if (nbytes_avail < buffer_len + 1 && size < nmax)
+ {
+ /* Grow size proportionally, not linearly, to avoid O(n^2)
+ running time. */
+ size_t newsize = size < MIN_CHUNK ? size + MIN_CHUNK : 2 * size;
+ char *newptr;
+
+ /* Increase newsize so that it becomes
+ >= (read_pos - ptr) + buffer_len. */
+ if (newsize - (read_pos - ptr) < buffer_len + 1)
+ newsize = (read_pos - ptr) + buffer_len + 1;
+ /* Respect nmax. This handles possible integer overflow. */
+ if (! (size < newsize && newsize <= nmax))
+ newsize = nmax;
+
+ if (GETNDELIM2_MAXIMUM < newsize - offset)
+ {
+ size_t newsizemax = offset + GETNDELIM2_MAXIMUM + 1;
+ if (size == newsizemax)
+ goto unlock_done;
+ newsize = newsizemax;
+ }
+
+ nbytes_avail = newsize - (read_pos - ptr);
+ newptr = realloc (ptr, newsize);
+ if (!newptr)
+ goto unlock_done;
+ ptr = newptr;
+ size = newsize;
+ read_pos = size - nbytes_avail + ptr;
+ }
+
+ /* Here, if size < nmax, nbytes_avail >= buffer_len + 1.
+ If size == nmax, nbytes_avail > 0. */
+
+ if (1 < nbytes_avail)
+ {
+ size_t copy_len = nbytes_avail - 1;
+ if (buffer_len < copy_len)
+ copy_len = buffer_len;
+ if (buffer)
+ memcpy (read_pos, buffer, copy_len);
+ else
+ *read_pos = c;
+ read_pos += copy_len;
+ nbytes_avail -= copy_len;
+ }
+
+ /* Here still nbytes_avail > 0. */
+
+ if (buffer && freadseek (stream, buffer_len))
+ goto unlock_done;
}
+ while (!found_delimiter);
/* Done - NUL terminate and return the number of bytes read.
At this point we know that nbytes_avail >= 1. */
@@ -136,8 +207,11 @@ getndelim2 (char **lineptr, size_t *linesize, size_t offset, size_t nmax,
bytes_stored = read_pos - (ptr + offset);
+ unlock_done:
+ funlockfile (stream);
+
done:
*lineptr = ptr;
*linesize = size;
- return bytes_stored;
+ return bytes_stored ? bytes_stored : -1;
}
diff --git a/lib/getndelim2.h b/lib/getndelim2.h
index 37a597f..2a8df86 100644
--- a/lib/getndelim2.h
+++ b/lib/getndelim2.h
@@ -1,12 +1,12 @@
/* getndelim2 - Read a line from a stream, stopping at one of 2 delimiters,
with bounded memory allocation.
- Copyright (C) 2003, 2004, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2003-2004, 2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifndef GETNDELIM2_H
#define GETNDELIM2_H 1
diff --git a/lib/getopt.c b/lib/getopt.c
index 3580ad8..8ccb901 100644
--- a/lib/getopt.c
+++ b/lib/getopt.c
@@ -1,24 +1,23 @@
/* Getopt for GNU.
- NOTE: getopt is now part of the C library, so if you don't know what
+ NOTE: getopt is part of the C library, so if you don't know what
"Keep this file name-space clean" means, talk to drepper@gnu.org
before changing it!
- Copyright (C) 1987,88,89,90,91,92,93,94,95,96,98,99,2000,2001,2002,2003,2004,2006
- Free Software Foundation, Inc.
+ Copyright (C) 1987-1996, 1998-2004, 2006, 2008-2016 Free Software
+ Foundation, Inc.
This file is part of the GNU C Library.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifndef _LIBC
# include <config.h>
@@ -31,10 +30,6 @@
#include <string.h>
#include <unistd.h>
-#ifdef __VMS
-# include <unixlib.h>
-#endif
-
#ifdef _LIBC
# include <libintl.h>
#else
@@ -46,44 +41,41 @@
# include <wchar.h>
#endif
-#ifndef attribute_hidden
-# define attribute_hidden
-#endif
-
-/* Unlike standard Unix `getopt', functions like `getopt_long'
- let the user intersperse the options with the other arguments.
+/* This version of 'getopt' appears to the caller like standard Unix 'getopt'
+ but it behaves differently for the user, since it allows the user
+ to intersperse the options with the other arguments.
- As `getopt_long' works, it permutes the elements of ARGV so that,
+ As 'getopt_long' works, it permutes the elements of ARGV so that,
when it is done, all the options precede everything else. Thus
all application programs are extended to handle flexible argument order.
- Using `getopt' or setting the environment variable POSIXLY_CORRECT
+ Using 'getopt' or setting the environment variable POSIXLY_CORRECT
disables permutation.
- Then the application's behavior is completely standard.
+ Then the behavior is completely standard.
GNU application programs can use a third alternative mode in which
they can distinguish the relative order of options and other arguments. */
#include "getopt_int.h"
-/* For communication from `getopt' to the caller.
- When `getopt' finds an option that takes an argument,
+/* For communication from 'getopt' to the caller.
+ When 'getopt' finds an option that takes an argument,
the argument value is returned here.
- Also, when `ordering' is RETURN_IN_ORDER,
+ Also, when 'ordering' is RETURN_IN_ORDER,
each non-option ARGV-element is returned here. */
char *optarg;
/* Index in ARGV of the next element to be scanned.
This is used for communication to and from the caller
- and for communication between successive calls to `getopt'.
+ and for communication between successive calls to 'getopt'.
- On entry to `getopt', zero means this is the first call; initialize.
+ On entry to 'getopt', zero means this is the first call; initialize.
- When `getopt' returns -1, this is the index of the first of the
+ When 'getopt' returns -1, this is the index of the first of the
non-option elements that the caller should itself scan.
- Otherwise, `optind' communicates from one call to the next
+ Otherwise, 'optind' communicates from one call to the next
how much of ARGV has been scanned so far. */
/* 1003.2 says this must be 1 before any call. */
@@ -126,18 +118,18 @@ extern char *__getopt_nonoption_flags;
# ifdef USE_NONOPTION_FLAGS
# define SWAP_FLAGS(ch1, ch2) \
- if (d->__nonoption_flags_len > 0) \
- { \
- char __tmp = __getopt_nonoption_flags[ch1]; \
- __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \
- __getopt_nonoption_flags[ch2] = __tmp; \
+ if (d->__nonoption_flags_len > 0) \
+ { \
+ char __tmp = __getopt_nonoption_flags[ch1]; \
+ __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \
+ __getopt_nonoption_flags[ch2] = __tmp; \
}
# else
# define SWAP_FLAGS(ch1, ch2)
# endif
-#else /* !_LIBC */
+#else /* !_LIBC */
# define SWAP_FLAGS(ch1, ch2)
-#endif /* _LIBC */
+#endif /* _LIBC */
/* Exchange two adjacent subsequences of ARGV.
One subsequence is elements [first_nonopt,last_nonopt)
@@ -145,7 +137,7 @@ extern char *__getopt_nonoption_flags;
The other is elements [last_nonopt,optind), which contains all
the options processed since those non-options were skipped.
- `first_nonopt' and `last_nonopt' are relocated so that they describe
+ 'first_nonopt' and 'last_nonopt' are relocated so that they describe
the new indices of the non-options in ARGV after they are moved. */
static void
@@ -162,63 +154,63 @@ exchange (char **argv, struct _getopt_data *d)
but it consists of two parts that need to be swapped next. */
#if defined _LIBC && defined USE_NONOPTION_FLAGS
- /* First make sure the handling of the `__getopt_nonoption_flags'
+ /* First make sure the handling of the '__getopt_nonoption_flags'
string can work normally. Our top argument must be in the range
of the string. */
if (d->__nonoption_flags_len > 0 && top >= d->__nonoption_flags_max_len)
{
/* We must extend the array. The user plays games with us and
- presents new arguments. */
+ presents new arguments. */
char *new_str = malloc (top + 1);
if (new_str == NULL)
- d->__nonoption_flags_len = d->__nonoption_flags_max_len = 0;
+ d->__nonoption_flags_len = d->__nonoption_flags_max_len = 0;
else
- {
- memset (__mempcpy (new_str, __getopt_nonoption_flags,
- d->__nonoption_flags_max_len),
- '\0', top + 1 - d->__nonoption_flags_max_len);
- d->__nonoption_flags_max_len = top + 1;
- __getopt_nonoption_flags = new_str;
- }
+ {
+ memset (__mempcpy (new_str, __getopt_nonoption_flags,
+ d->__nonoption_flags_max_len),
+ '\0', top + 1 - d->__nonoption_flags_max_len);
+ d->__nonoption_flags_max_len = top + 1;
+ __getopt_nonoption_flags = new_str;
+ }
}
#endif
while (top > middle && middle > bottom)
{
if (top - middle > middle - bottom)
- {
- /* Bottom segment is the short one. */
- int len = middle - bottom;
- register int i;
-
- /* Swap it with the top part of the top segment. */
- for (i = 0; i < len; i++)
- {
- tem = argv[bottom + i];
- argv[bottom + i] = argv[top - (middle - bottom) + i];
- argv[top - (middle - bottom) + i] = tem;
- SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
- }
- /* Exclude the moved bottom segment from further swapping. */
- top -= len;
- }
+ {
+ /* Bottom segment is the short one. */
+ int len = middle - bottom;
+ register int i;
+
+ /* Swap it with the top part of the top segment. */
+ for (i = 0; i < len; i++)
+ {
+ tem = argv[bottom + i];
+ argv[bottom + i] = argv[top - (middle - bottom) + i];
+ argv[top - (middle - bottom) + i] = tem;
+ SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
+ }
+ /* Exclude the moved bottom segment from further swapping. */
+ top -= len;
+ }
else
- {
- /* Top segment is the short one. */
- int len = top - middle;
- register int i;
-
- /* Swap it with the bottom part of the bottom segment. */
- for (i = 0; i < len; i++)
- {
- tem = argv[bottom + i];
- argv[bottom + i] = argv[middle + i];
- argv[middle + i] = tem;
- SWAP_FLAGS (bottom + i, middle + i);
- }
- /* Exclude the moved top segment from further swapping. */
- bottom += len;
- }
+ {
+ /* Top segment is the short one. */
+ int len = top - middle;
+ register int i;
+
+ /* Swap it with the bottom part of the bottom segment. */
+ for (i = 0; i < len; i++)
+ {
+ tem = argv[bottom + i];
+ argv[bottom + i] = argv[middle + i];
+ argv[middle + i] = tem;
+ SWAP_FLAGS (bottom + i, middle + i);
+ }
+ /* Exclude the moved top segment from further swapping. */
+ bottom += len;
+ }
}
/* Update records for the slots the non-options now occupy. */
@@ -230,8 +222,9 @@ exchange (char **argv, struct _getopt_data *d)
/* Initialize the internal data when the first call is made. */
static const char *
-_getopt_initialize (int argc, char **argv, const char *optstring,
- int posixly_correct, struct _getopt_data *d)
+_getopt_initialize (int argc _GL_UNUSED,
+ char **argv _GL_UNUSED, const char *optstring,
+ struct _getopt_data *d, int posixly_correct)
{
/* Start processing options with ARGV-element 1 (since ARGV-element 0
is the program name); the sequence of previously skipped
@@ -265,25 +258,25 @@ _getopt_initialize (int argc, char **argv, const char *optstring,
&& argc == __libc_argc && argv == __libc_argv)
{
if (d->__nonoption_flags_max_len == 0)
- {
- if (__getopt_nonoption_flags == NULL
- || __getopt_nonoption_flags[0] == '\0')
- d->__nonoption_flags_max_len = -1;
- else
- {
- const char *orig_str = __getopt_nonoption_flags;
- int len = d->__nonoption_flags_max_len = strlen (orig_str);
- if (d->__nonoption_flags_max_len < argc)
- d->__nonoption_flags_max_len = argc;
- __getopt_nonoption_flags =
- (char *) malloc (d->__nonoption_flags_max_len);
- if (__getopt_nonoption_flags == NULL)
- d->__nonoption_flags_max_len = -1;
- else
- memset (__mempcpy (__getopt_nonoption_flags, orig_str, len),
- '\0', d->__nonoption_flags_max_len - len);
- }
- }
+ {
+ if (__getopt_nonoption_flags == NULL
+ || __getopt_nonoption_flags[0] == '\0')
+ d->__nonoption_flags_max_len = -1;
+ else
+ {
+ const char *orig_str = __getopt_nonoption_flags;
+ int len = d->__nonoption_flags_max_len = strlen (orig_str);
+ if (d->__nonoption_flags_max_len < argc)
+ d->__nonoption_flags_max_len = argc;
+ __getopt_nonoption_flags =
+ (char *) malloc (d->__nonoption_flags_max_len);
+ if (__getopt_nonoption_flags == NULL)
+ d->__nonoption_flags_max_len = -1;
+ else
+ memset (__mempcpy (__getopt_nonoption_flags, orig_str, len),
+ '\0', d->__nonoption_flags_max_len - len);
+ }
+ }
d->__nonoption_flags_len = d->__nonoption_flags_max_len;
}
else
@@ -298,44 +291,48 @@ _getopt_initialize (int argc, char **argv, const char *optstring,
If an element of ARGV starts with '-', and is not exactly "-" or "--",
then it is an option element. The characters of this element
- (aside from the initial '-') are option characters. If `getopt'
+ (aside from the initial '-') are option characters. If 'getopt'
is called repeatedly, it returns successively each of the option characters
from each of the option elements.
- If `getopt' finds another option character, it returns that character,
- updating `optind' and `nextchar' so that the next call to `getopt' can
+ If 'getopt' finds another option character, it returns that character,
+ updating 'optind' and 'nextchar' so that the next call to 'getopt' can
resume the scan with the following option character or ARGV-element.
- If there are no more option characters, `getopt' returns -1.
- Then `optind' is the index in ARGV of the first ARGV-element
+ If there are no more option characters, 'getopt' returns -1.
+ Then 'optind' is the index in ARGV of the first ARGV-element
that is not an option. (The ARGV-elements have been permuted
so that those that are not options now come last.)
OPTSTRING is a string containing the legitimate option characters.
If an option character is seen that is not listed in OPTSTRING,
- return '?' after printing an error message. If you set `opterr' to
+ return '?' after printing an error message. If you set 'opterr' to
zero, the error message is suppressed but we still return '?'.
If a char in OPTSTRING is followed by a colon, that means it wants an arg,
so the following text in the same ARGV-element, or the text of the following
- ARGV-element, is returned in `optarg'. Two colons mean an option that
+ ARGV-element, is returned in 'optarg'. Two colons mean an option that
wants an optional arg; if there is text in the current ARGV-element,
- it is returned in `optarg', otherwise `optarg' is set to zero.
+ it is returned in 'optarg', otherwise 'optarg' is set to zero.
- If OPTSTRING starts with `-' or `+', it requests different methods of
+ If OPTSTRING starts with '-' or '+', it requests different methods of
handling the non-option ARGV-elements.
See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
- Long-named options begin with `--' instead of `-'.
+ Long-named options begin with '--' instead of '-'.
Their names may be abbreviated as long as the abbreviation is unique
or is an exact match for some defined option. If they have an
argument, it follows the option name in the same ARGV-element, separated
- from the option name by a `=', or else the in next ARGV-element.
- When `getopt' finds a long-named option, it returns 0 if that option's
- `flag' field is nonzero, the value of the option's `val' field
- if the `flag' field is zero.
+ from the option name by a '=', or else the in next ARGV-element.
+ When 'getopt' finds a long-named option, it returns 0 if that option's
+ 'flag' field is nonzero, the value of the option's 'val' field
+ if the 'flag' field is zero.
- LONGOPTS is a vector of `struct option' terminated by an
+ The elements of ARGV aren't really const, because we permute them.
+ But we pretend they're const in the prototype to be compatible
+ with other systems.
+
+ LONGOPTS is a vector of 'struct option' terminated by an
element containing a name which is zero.
LONGIND returns the index in LONGOPT of the long-named option found.
@@ -343,19 +340,14 @@ _getopt_initialize (int argc, char **argv, const char *optstring,
recent call.
If LONG_ONLY is nonzero, '-' as well as '--' can introduce
- long-named options.
-
- If POSIXLY_CORRECT is nonzero, behave as if the POSIXLY_CORRECT
- environment variable were set. */
+ long-named options. */
int
_getopt_internal_r (int argc, char **argv, const char *optstring,
- const struct option *longopts, int *longind,
- int long_only, int posixly_correct, struct _getopt_data *d)
+ const struct option *longopts, int *longind,
+ int long_only, struct _getopt_data *d, int posixly_correct)
{
int print_errors = d->opterr;
- if (optstring[0] == ':')
- print_errors = 0;
if (argc < 1)
return -1;
@@ -365,11 +357,15 @@ _getopt_internal_r (int argc, char **argv, const char *optstring,
if (d->optind == 0 || !d->__initialized)
{
if (d->optind == 0)
- d->optind = 1; /* Don't scan ARGV[0], the program name. */
- optstring = _getopt_initialize (argc, argv, optstring,
- posixly_correct, d);
+ d->optind = 1; /* Don't scan ARGV[0], the program name. */
+ optstring = _getopt_initialize (argc, argv, optstring, d,
+ posixly_correct);
d->__initialized = 1;
}
+ else if (optstring[0] == '-' || optstring[0] == '+')
+ optstring++;
+ if (optstring[0] == ':')
+ print_errors = 0;
/* Test whether ARGV[optind] points to a non-option argument.
Either it does not have option syntax, or there is an environment flag
@@ -377,8 +373,8 @@ _getopt_internal_r (int argc, char **argv, const char *optstring,
is only used when the used in the GNU libc. */
#if defined _LIBC && defined USE_NONOPTION_FLAGS
# define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0' \
- || (d->optind < d->__nonoption_flags_len \
- && __getopt_nonoption_flags[d->optind] == '1'))
+ || (d->optind < d->__nonoption_flags_len \
+ && __getopt_nonoption_flags[d->optind] == '1'))
#else
# define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0')
#endif
@@ -388,78 +384,78 @@ _getopt_internal_r (int argc, char **argv, const char *optstring,
/* Advance to the next ARGV-element. */
/* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
- moved back by the user (who may also have changed the arguments). */
+ moved back by the user (who may also have changed the arguments). */
if (d->__last_nonopt > d->optind)
- d->__last_nonopt = d->optind;
+ d->__last_nonopt = d->optind;
if (d->__first_nonopt > d->optind)
- d->__first_nonopt = d->optind;
+ d->__first_nonopt = d->optind;
if (d->__ordering == PERMUTE)
- {
- /* If we have just processed some options following some non-options,
- exchange them so that the options come first. */
+ {
+ /* If we have just processed some options following some non-options,
+ exchange them so that the options come first. */
- if (d->__first_nonopt != d->__last_nonopt
- && d->__last_nonopt != d->optind)
- exchange ((char **) argv, d);
- else if (d->__last_nonopt != d->optind)
- d->__first_nonopt = d->optind;
+ if (d->__first_nonopt != d->__last_nonopt
+ && d->__last_nonopt != d->optind)
+ exchange ((char **) argv, d);
+ else if (d->__last_nonopt != d->optind)
+ d->__first_nonopt = d->optind;
- /* Skip any additional non-options
- and extend the range of non-options previously skipped. */
+ /* Skip any additional non-options
+ and extend the range of non-options previously skipped. */
- while (d->optind < argc && NONOPTION_P)
- d->optind++;
- d->__last_nonopt = d->optind;
- }
+ while (d->optind < argc && NONOPTION_P)
+ d->optind++;
+ d->__last_nonopt = d->optind;
+ }
- /* The special ARGV-element `--' means premature end of options.
- Skip it like a null option,
- then exchange with previous non-options as if it were an option,
- then skip everything else like a non-option. */
+ /* The special ARGV-element '--' means premature end of options.
+ Skip it like a null option,
+ then exchange with previous non-options as if it were an option,
+ then skip everything else like a non-option. */
if (d->optind != argc && !strcmp (argv[d->optind], "--"))
- {
- d->optind++;
+ {
+ d->optind++;
- if (d->__first_nonopt != d->__last_nonopt
- && d->__last_nonopt != d->optind)
- exchange ((char **) argv, d);
- else if (d->__first_nonopt == d->__last_nonopt)
- d->__first_nonopt = d->optind;
- d->__last_nonopt = argc;
+ if (d->__first_nonopt != d->__last_nonopt
+ && d->__last_nonopt != d->optind)
+ exchange ((char **) argv, d);
+ else if (d->__first_nonopt == d->__last_nonopt)
+ d->__first_nonopt = d->optind;
+ d->__last_nonopt = argc;
- d->optind = argc;
- }
+ d->optind = argc;
+ }
/* If we have done all the ARGV-elements, stop the scan
- and back over any non-options that we skipped and permuted. */
+ and back over any non-options that we skipped and permuted. */
if (d->optind == argc)
- {
- /* Set the next-arg-index to point at the non-options
- that we previously skipped, so the caller will digest them. */
- if (d->__first_nonopt != d->__last_nonopt)
- d->optind = d->__first_nonopt;
- return -1;
- }
+ {
+ /* Set the next-arg-index to point at the non-options
+ that we previously skipped, so the caller will digest them. */
+ if (d->__first_nonopt != d->__last_nonopt)
+ d->optind = d->__first_nonopt;
+ return -1;
+ }
/* If we have come to a non-option and did not permute it,
- either stop the scan or describe it to the caller and pass it by. */
+ either stop the scan or describe it to the caller and pass it by. */
if (NONOPTION_P)
- {
- if (d->__ordering == REQUIRE_ORDER)
- return -1;
- d->optarg = argv[d->optind++];
- return 1;
- }
+ {
+ if (d->__ordering == REQUIRE_ORDER)
+ return -1;
+ d->optarg = argv[d->optind++];
+ return 1;
+ }
/* We have found another option-ARGV-element.
- Skip the initial punctuation. */
+ Skip the initial punctuation. */
d->__nextchar = (argv[d->optind] + 1
- + (longopts != NULL && argv[d->optind][1] == '-'));
+ + (longopts != NULL && argv[d->optind][1] == '-'));
}
/* Decode the current option-ARGV-element. */
@@ -479,606 +475,680 @@ _getopt_internal_r (int argc, char **argv, const char *optstring,
if (longopts != NULL
&& (argv[d->optind][1] == '-'
- || (long_only && (argv[d->optind][2]
- || !strchr (optstring, argv[d->optind][1])))))
+ || (long_only && (argv[d->optind][2]
+ || !strchr (optstring, argv[d->optind][1])))))
{
char *nameend;
+ unsigned int namelen;
const struct option *p;
const struct option *pfound = NULL;
+ struct option_list
+ {
+ const struct option *p;
+ struct option_list *next;
+ } *ambig_list = NULL;
+#ifdef _LIBC
+/* malloc() not used for _LIBC to simplify failure messages. */
+# define free_option_list(l)
+#else
+# define free_option_list(l) \
+ while (l != NULL) \
+ { \
+ struct option_list *pn = l->next; \
+ free (l); \
+ l = pn; \
+ }
+#endif
int exact = 0;
int ambig = 0;
int indfound = -1;
int option_index;
for (nameend = d->__nextchar; *nameend && *nameend != '='; nameend++)
- /* Do nothing. */ ;
+ /* Do nothing. */ ;
+ namelen = nameend - d->__nextchar;
/* Test all long options for either exact match
- or abbreviated matches. */
+ or abbreviated matches. */
for (p = longopts, option_index = 0; p->name; p++, option_index++)
- if (!strncmp (p->name, d->__nextchar, nameend - d->__nextchar))
- {
- if ((unsigned int) (nameend - d->__nextchar)
- == (unsigned int) strlen (p->name))
- {
- /* Exact match found. */
- pfound = p;
- indfound = option_index;
- exact = 1;
- break;
- }
- else if (pfound == NULL)
- {
- /* First nonexact match found. */
- pfound = p;
- indfound = option_index;
- }
- else if (long_only
- || pfound->has_arg != p->has_arg
- || pfound->flag != p->flag
- || pfound->val != p->val)
- /* Second or later nonexact match found. */
- ambig = 1;
- }
-
- if (ambig && !exact)
- {
- if (print_errors)
- {
+ if (!strncmp (p->name, d->__nextchar, namelen))
+ {
+ if (namelen == (unsigned int) strlen (p->name))
+ {
+ /* Exact match found. */
+ pfound = p;
+ indfound = option_index;
+ exact = 1;
+ break;
+ }
+ else if (pfound == NULL)
+ {
+ /* First nonexact match found. */
+ pfound = p;
+ indfound = option_index;
+ }
+ else if (ambig)
+ ; /* Taking simpler path to handling ambiguities. */
+ else if (long_only
+ || pfound->has_arg != p->has_arg
+ || pfound->flag != p->flag
+ || pfound->val != p->val)
+ {
+ /* Second or later nonexact match found. */
+#ifdef _LIBC
+ struct option_list *newp = alloca (sizeof (*newp));
+#else
+ struct option_list *newp = malloc (sizeof (*newp));
+ if (newp == NULL)
+ {
+ free_option_list (ambig_list);
+ ambig_list = NULL;
+ ambig = 1; /* Use simpler fallback message. */
+ }
+ else
+#endif
+ {
+ newp->p = p;
+ newp->next = ambig_list;
+ ambig_list = newp;
+ }
+ }
+ }
+
+ if ((ambig || ambig_list) && !exact)
+ {
+ if (print_errors && ambig_list)
+ {
+ struct option_list first;
+ first.p = pfound;
+ first.next = ambig_list;
+ ambig_list = &first;
+
#if defined _LIBC && defined USE_IN_LIBIO
- char *buf;
+ char *buf = NULL;
+ size_t buflen = 0;
+
+ FILE *fp = open_memstream (&buf, &buflen);
+ if (fp != NULL)
+ {
+ fprintf (fp,
+ _("%s: option '%s' is ambiguous; possibilities:"),
+ argv[0], argv[d->optind]);
- if (__asprintf (&buf, _("%s: option `%s' is ambiguous\n"),
- argv[0], argv[d->optind]) >= 0)
- {
- _IO_flockfile (stderr);
+ do
+ {
+ fprintf (fp, " '--%s'", ambig_list->p->name);
+ ambig_list = ambig_list->next;
+ }
+ while (ambig_list != NULL);
- int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
- ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
+ fputc_unlocked ('\n', fp);
- __fxprintf (NULL, "%s", buf);
+ if (__builtin_expect (fclose (fp) != EOF, 1))
+ {
+ _IO_flockfile (stderr);
- ((_IO_FILE *) stderr)->_flags2 = old_flags2;
- _IO_funlockfile (stderr);
+ int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
+ ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
- free (buf);
- }
+ __fxprintf (NULL, "%s", buf);
+
+ ((_IO_FILE *) stderr)->_flags2 = old_flags2;
+ _IO_funlockfile (stderr);
+
+ free (buf);
+ }
+ }
#else
- fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
- argv[0], argv[d->optind]);
+ fprintf (stderr,
+ _("%s: option '%s' is ambiguous; possibilities:"),
+ argv[0], argv[d->optind]);
+ do
+ {
+ fprintf (stderr, " '--%s'", ambig_list->p->name);
+ ambig_list = ambig_list->next;
+ }
+ while (ambig_list != NULL);
+
+ fputc ('\n', stderr);
#endif
- }
- d->__nextchar += strlen (d->__nextchar);
- d->optind++;
- d->optopt = 0;
- return '?';
- }
+ }
+ else if (print_errors && ambig)
+ {
+ fprintf (stderr,
+ _("%s: option '%s' is ambiguous\n"),
+ argv[0], argv[d->optind]);
+ }
+ d->__nextchar += strlen (d->__nextchar);
+ d->optind++;
+ d->optopt = 0;
+ free_option_list (ambig_list);
+ return '?';
+ }
+
+ free_option_list (ambig_list);
if (pfound != NULL)
- {
- option_index = indfound;
- d->optind++;
- if (*nameend)
- {
- /* Don't test has_arg with >, because some C compilers don't
- allow it to be used on enums. */
- if (pfound->has_arg)
- d->optarg = nameend + 1;
- else
- {
- if (print_errors)
- {
+ {
+ option_index = indfound;
+ d->optind++;
+ if (*nameend)
+ {
+ /* Don't test has_arg with >, because some C compilers don't
+ allow it to be used on enums. */
+ if (pfound->has_arg)
+ d->optarg = nameend + 1;
+ else
+ {
+ if (print_errors)
+ {
#if defined _LIBC && defined USE_IN_LIBIO
- char *buf;
- int n;
+ char *buf;
+ int n;
#endif
- if (argv[d->optind - 1][1] == '-')
- {
- /* --option */
+ if (argv[d->optind - 1][1] == '-')
+ {
+ /* --option */
#if defined _LIBC && defined USE_IN_LIBIO
- n = __asprintf (&buf, _("\
-%s: option `--%s' doesn't allow an argument\n"),
- argv[0], pfound->name);
+ n = __asprintf (&buf, _("\
+%s: option '--%s' doesn't allow an argument\n"),
+ argv[0], pfound->name);
#else
- fprintf (stderr, _("\
-%s: option `--%s' doesn't allow an argument\n"),
- argv[0], pfound->name);
+ fprintf (stderr, _("\
+%s: option '--%s' doesn't allow an argument\n"),
+ argv[0], pfound->name);
#endif
- }
- else
- {
- /* +option or -option */
+ }
+ else
+ {
+ /* +option or -option */
#if defined _LIBC && defined USE_IN_LIBIO
- n = __asprintf (&buf, _("\
-%s: option `%c%s' doesn't allow an argument\n"),
- argv[0], argv[d->optind - 1][0],
- pfound->name);
+ n = __asprintf (&buf, _("\
+%s: option '%c%s' doesn't allow an argument\n"),
+ argv[0], argv[d->optind - 1][0],
+ pfound->name);
#else
- fprintf (stderr, _("\
-%s: option `%c%s' doesn't allow an argument\n"),
- argv[0], argv[d->optind - 1][0],
- pfound->name);
+ fprintf (stderr, _("\
+%s: option '%c%s' doesn't allow an argument\n"),
+ argv[0], argv[d->optind - 1][0],
+ pfound->name);
#endif
- }
+ }
#if defined _LIBC && defined USE_IN_LIBIO
- if (n >= 0)
- {
- _IO_flockfile (stderr);
+ if (n >= 0)
+ {
+ _IO_flockfile (stderr);
- int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
- ((_IO_FILE *) stderr)->_flags2
- |= _IO_FLAGS2_NOTCANCEL;
+ int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
+ ((_IO_FILE *) stderr)->_flags2
+ |= _IO_FLAGS2_NOTCANCEL;
- __fxprintf (NULL, "%s", buf);
+ __fxprintf (NULL, "%s", buf);
- ((_IO_FILE *) stderr)->_flags2 = old_flags2;
- _IO_funlockfile (stderr);
+ ((_IO_FILE *) stderr)->_flags2 = old_flags2;
+ _IO_funlockfile (stderr);
- free (buf);
- }
+ free (buf);
+ }
#endif
- }
-
- d->__nextchar += strlen (d->__nextchar);
-
- d->optopt = pfound->val;
- return '?';
- }
- }
- else if (pfound->has_arg == 1)
- {
- if (d->optind < argc)
- d->optarg = argv[d->optind++];
- else
- {
- if (print_errors)
- {
+ }
+
+ d->__nextchar += strlen (d->__nextchar);
+
+ d->optopt = pfound->val;
+ return '?';
+ }
+ }
+ else if (pfound->has_arg == 1)
+ {
+ if (d->optind < argc)
+ d->optarg = argv[d->optind++];
+ else
+ {
+ if (print_errors)
+ {
#if defined _LIBC && defined USE_IN_LIBIO
- char *buf;
+ char *buf;
- if (__asprintf (&buf, _("\
-%s: option `%s' requires an argument\n"),
- argv[0], argv[d->optind - 1]) >= 0)
- {
- _IO_flockfile (stderr);
+ if (__asprintf (&buf, _("\
+%s: option '--%s' requires an argument\n"),
+ argv[0], pfound->name) >= 0)
+ {
+ _IO_flockfile (stderr);
- int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
- ((_IO_FILE *) stderr)->_flags2
- |= _IO_FLAGS2_NOTCANCEL;
+ int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
+ ((_IO_FILE *) stderr)->_flags2
+ |= _IO_FLAGS2_NOTCANCEL;
- __fxprintf (NULL, "%s", buf);
+ __fxprintf (NULL, "%s", buf);
- ((_IO_FILE *) stderr)->_flags2 = old_flags2;
- _IO_funlockfile (stderr);
+ ((_IO_FILE *) stderr)->_flags2 = old_flags2;
+ _IO_funlockfile (stderr);
- free (buf);
- }
+ free (buf);
+ }
#else
- fprintf (stderr,
- _("%s: option `%s' requires an argument\n"),
- argv[0], argv[d->optind - 1]);
+ fprintf (stderr,
+ _("%s: option '--%s' requires an argument\n"),
+ argv[0], pfound->name);
#endif
- }
- d->__nextchar += strlen (d->__nextchar);
- d->optopt = pfound->val;
- return optstring[0] == ':' ? ':' : '?';
- }
- }
- d->__nextchar += strlen (d->__nextchar);
- if (longind != NULL)
- *longind = option_index;
- if (pfound->flag)
- {
- *(pfound->flag) = pfound->val;
- return 0;
- }
- return pfound->val;
- }
+ }
+ d->__nextchar += strlen (d->__nextchar);
+ d->optopt = pfound->val;
+ return optstring[0] == ':' ? ':' : '?';
+ }
+ }
+ d->__nextchar += strlen (d->__nextchar);
+ if (longind != NULL)
+ *longind = option_index;
+ if (pfound->flag)
+ {
+ *(pfound->flag) = pfound->val;
+ return 0;
+ }
+ return pfound->val;
+ }
/* Can't find it as a long option. If this is not getopt_long_only,
- or the option starts with '--' or is not a valid short
- option, then it's an error.
- Otherwise interpret it as a short option. */
+ or the option starts with '--' or is not a valid short
+ option, then it's an error.
+ Otherwise interpret it as a short option. */
if (!long_only || argv[d->optind][1] == '-'
- || strchr (optstring, *d->__nextchar) == NULL)
- {
- if (print_errors)
- {
+ || strchr (optstring, *d->__nextchar) == NULL)
+ {
+ if (print_errors)
+ {
#if defined _LIBC && defined USE_IN_LIBIO
- char *buf;
- int n;
+ char *buf;
+ int n;
#endif
- if (argv[d->optind][1] == '-')
- {
- /* --option */
+ if (argv[d->optind][1] == '-')
+ {
+ /* --option */
#if defined _LIBC && defined USE_IN_LIBIO
- n = __asprintf (&buf, _("%s: unrecognized option `--%s'\n"),
- argv[0], d->__nextchar);
+ n = __asprintf (&buf, _("%s: unrecognized option '--%s'\n"),
+ argv[0], d->__nextchar);
#else
- fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
- argv[0], d->__nextchar);
+ fprintf (stderr, _("%s: unrecognized option '--%s'\n"),
+ argv[0], d->__nextchar);
#endif
- }
- else
- {
- /* +option or -option */
+ }
+ else
+ {
+ /* +option or -option */
#if defined _LIBC && defined USE_IN_LIBIO
- n = __asprintf (&buf, _("%s: unrecognized option `%c%s'\n"),
- argv[0], argv[d->optind][0], d->__nextchar);
+ n = __asprintf (&buf, _("%s: unrecognized option '%c%s'\n"),
+ argv[0], argv[d->optind][0], d->__nextchar);
#else
- fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
- argv[0], argv[d->optind][0], d->__nextchar);
+ fprintf (stderr, _("%s: unrecognized option '%c%s'\n"),
+ argv[0], argv[d->optind][0], d->__nextchar);
#endif
- }
+ }
#if defined _LIBC && defined USE_IN_LIBIO
- if (n >= 0)
- {
- _IO_flockfile (stderr);
+ if (n >= 0)
+ {
+ _IO_flockfile (stderr);
- int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
- ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
+ int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
+ ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
- __fxprintf (NULL, "%s", buf);
+ __fxprintf (NULL, "%s", buf);
- ((_IO_FILE *) stderr)->_flags2 = old_flags2;
- _IO_funlockfile (stderr);
+ ((_IO_FILE *) stderr)->_flags2 = old_flags2;
+ _IO_funlockfile (stderr);
- free (buf);
- }
+ free (buf);
+ }
#endif
- }
- d->__nextchar = (char *) "";
- d->optind++;
- d->optopt = 0;
- return '?';
- }
+ }
+ d->__nextchar = (char *) "";
+ d->optind++;
+ d->optopt = 0;
+ return '?';
+ }
}
/* Look at and handle the next short option-character. */
{
char c = *d->__nextchar++;
- char *temp = strchr (optstring, c);
+ const char *temp = strchr (optstring, c);
- /* Increment `optind' when we start to process its last character. */
+ /* Increment 'optind' when we start to process its last character. */
if (*d->__nextchar == '\0')
++d->optind;
- if (temp == NULL || c == ':')
+ if (temp == NULL || c == ':' || c == ';')
{
- if (print_errors)
- {
+ if (print_errors)
+ {
#if defined _LIBC && defined USE_IN_LIBIO
- char *buf;
- int n;
+ char *buf;
+ int n;
#endif
- if (d->__posixly_correct)
- {
- /* 1003.2 specifies the format of this message. */
#if defined _LIBC && defined USE_IN_LIBIO
- n = __asprintf (&buf, _("%s: illegal option -- %c\n"),
- argv[0], c);
+ n = __asprintf (&buf, _("%s: invalid option -- '%c'\n"),
+ argv[0], c);
#else
- fprintf (stderr, _("%s: illegal option -- %c\n"), argv[0], c);
+ fprintf (stderr, _("%s: invalid option -- '%c'\n"), argv[0], c);
#endif
- }
- else
- {
-#if defined _LIBC && defined USE_IN_LIBIO
- n = __asprintf (&buf, _("%s: invalid option -- %c\n"),
- argv[0], c);
-#else
- fprintf (stderr, _("%s: invalid option -- %c\n"), argv[0], c);
-#endif
- }
#if defined _LIBC && defined USE_IN_LIBIO
- if (n >= 0)
- {
- _IO_flockfile (stderr);
+ if (n >= 0)
+ {
+ _IO_flockfile (stderr);
- int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
- ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
+ int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
+ ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
- __fxprintf (NULL, "%s", buf);
+ __fxprintf (NULL, "%s", buf);
- ((_IO_FILE *) stderr)->_flags2 = old_flags2;
- _IO_funlockfile (stderr);
+ ((_IO_FILE *) stderr)->_flags2 = old_flags2;
+ _IO_funlockfile (stderr);
- free (buf);
- }
+ free (buf);
+ }
#endif
- }
- d->optopt = c;
- return '?';
+ }
+ d->optopt = c;
+ return '?';
}
/* Convenience. Treat POSIX -W foo same as long option --foo */
if (temp[0] == 'W' && temp[1] == ';')
{
- char *nameend;
- const struct option *p;
- const struct option *pfound = NULL;
- int exact = 0;
- int ambig = 0;
- int indfound = 0;
- int option_index;
-
- /* This is an option that requires an argument. */
- if (*d->__nextchar != '\0')
- {
- d->optarg = d->__nextchar;
- /* If we end this ARGV-element by taking the rest as an arg,
- we must advance to the next element now. */
- d->optind++;
- }
- else if (d->optind == argc)
- {
- if (print_errors)
- {
- /* 1003.2 specifies the format of this message. */
+ char *nameend;
+ const struct option *p;
+ const struct option *pfound = NULL;
+ int exact = 0;
+ int ambig = 0;
+ int indfound = 0;
+ int option_index;
+
+ if (longopts == NULL)
+ goto no_longs;
+
+ /* This is an option that requires an argument. */
+ if (*d->__nextchar != '\0')
+ {
+ d->optarg = d->__nextchar;
+ /* If we end this ARGV-element by taking the rest as an arg,
+ we must advance to the next element now. */
+ d->optind++;
+ }
+ else if (d->optind == argc)
+ {
+ if (print_errors)
+ {
#if defined _LIBC && defined USE_IN_LIBIO
- char *buf;
+ char *buf;
- if (__asprintf (&buf,
- _("%s: option requires an argument -- %c\n"),
- argv[0], c) >= 0)
- {
- _IO_flockfile (stderr);
+ if (__asprintf (&buf,
+ _("%s: option requires an argument -- '%c'\n"),
+ argv[0], c) >= 0)
+ {
+ _IO_flockfile (stderr);
- int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
- ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
+ int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
+ ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
- __fxprintf (NULL, "%s", buf);
+ __fxprintf (NULL, "%s", buf);
- ((_IO_FILE *) stderr)->_flags2 = old_flags2;
- _IO_funlockfile (stderr);
+ ((_IO_FILE *) stderr)->_flags2 = old_flags2;
+ _IO_funlockfile (stderr);
- free (buf);
- }
+ free (buf);
+ }
#else
- fprintf (stderr, _("%s: option requires an argument -- %c\n"),
- argv[0], c);
+ fprintf (stderr,
+ _("%s: option requires an argument -- '%c'\n"),
+ argv[0], c);
#endif
- }
- d->optopt = c;
- if (optstring[0] == ':')
- c = ':';
- else
- c = '?';
- return c;
- }
- else
- /* We already incremented `d->optind' once;
- increment it again when taking next ARGV-elt as argument. */
- d->optarg = argv[d->optind++];
-
- /* optarg is now the argument, see if it's in the
- table of longopts. */
-
- for (d->__nextchar = nameend = d->optarg; *nameend && *nameend != '=';
- nameend++)
- /* Do nothing. */ ;
-
- /* Test all long options for either exact match
- or abbreviated matches. */
- for (p = longopts, option_index = 0; p->name; p++, option_index++)
- if (!strncmp (p->name, d->__nextchar, nameend - d->__nextchar))
- {
- if ((unsigned int) (nameend - d->__nextchar) == strlen (p->name))
- {
- /* Exact match found. */
- pfound = p;
- indfound = option_index;
- exact = 1;
- break;
- }
- else if (pfound == NULL)
- {
- /* First nonexact match found. */
- pfound = p;
- indfound = option_index;
- }
- else
- /* Second or later nonexact match found. */
- ambig = 1;
- }
- if (ambig && !exact)
- {
- if (print_errors)
- {
+ }
+ d->optopt = c;
+ if (optstring[0] == ':')
+ c = ':';
+ else
+ c = '?';
+ return c;
+ }
+ else
+ /* We already incremented 'd->optind' once;
+ increment it again when taking next ARGV-elt as argument. */
+ d->optarg = argv[d->optind++];
+
+ /* optarg is now the argument, see if it's in the
+ table of longopts. */
+
+ for (d->__nextchar = nameend = d->optarg; *nameend && *nameend != '=';
+ nameend++)
+ /* Do nothing. */ ;
+
+ /* Test all long options for either exact match
+ or abbreviated matches. */
+ for (p = longopts, option_index = 0; p->name; p++, option_index++)
+ if (!strncmp (p->name, d->__nextchar, nameend - d->__nextchar))
+ {
+ if ((unsigned int) (nameend - d->__nextchar) == strlen (p->name))
+ {
+ /* Exact match found. */
+ pfound = p;
+ indfound = option_index;
+ exact = 1;
+ break;
+ }
+ else if (pfound == NULL)
+ {
+ /* First nonexact match found. */
+ pfound = p;
+ indfound = option_index;
+ }
+ else if (long_only
+ || pfound->has_arg != p->has_arg
+ || pfound->flag != p->flag
+ || pfound->val != p->val)
+ /* Second or later nonexact match found. */
+ ambig = 1;
+ }
+ if (ambig && !exact)
+ {
+ if (print_errors)
+ {
#if defined _LIBC && defined USE_IN_LIBIO
- char *buf;
+ char *buf;
- if (__asprintf (&buf, _("%s: option `-W %s' is ambiguous\n"),
- argv[0], argv[d->optind]) >= 0)
- {
- _IO_flockfile (stderr);
+ if (__asprintf (&buf, _("%s: option '-W %s' is ambiguous\n"),
+ argv[0], d->optarg) >= 0)
+ {
+ _IO_flockfile (stderr);
- int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
- ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
+ int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
+ ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
- __fxprintf (NULL, "%s", buf);
+ __fxprintf (NULL, "%s", buf);
- ((_IO_FILE *) stderr)->_flags2 = old_flags2;
- _IO_funlockfile (stderr);
+ ((_IO_FILE *) stderr)->_flags2 = old_flags2;
+ _IO_funlockfile (stderr);
- free (buf);
- }
+ free (buf);
+ }
#else
- fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"),
- argv[0], argv[d->optind]);
+ fprintf (stderr, _("%s: option '-W %s' is ambiguous\n"),
+ argv[0], d->optarg);
#endif
- }
- d->__nextchar += strlen (d->__nextchar);
- d->optind++;
- return '?';
- }
- if (pfound != NULL)
- {
- option_index = indfound;
- if (*nameend)
- {
- /* Don't test has_arg with >, because some C compilers don't
- allow it to be used on enums. */
- if (pfound->has_arg)
- d->optarg = nameend + 1;
- else
- {
- if (print_errors)
- {
+ }
+ d->__nextchar += strlen (d->__nextchar);
+ d->optind++;
+ return '?';
+ }
+ if (pfound != NULL)
+ {
+ option_index = indfound;
+ if (*nameend)
+ {
+ /* Don't test has_arg with >, because some C compilers don't
+ allow it to be used on enums. */
+ if (pfound->has_arg)
+ d->optarg = nameend + 1;
+ else
+ {
+ if (print_errors)
+ {
#if defined _LIBC && defined USE_IN_LIBIO
- char *buf;
+ char *buf;
- if (__asprintf (&buf, _("\
-%s: option `-W %s' doesn't allow an argument\n"),
- argv[0], pfound->name) >= 0)
- {
- _IO_flockfile (stderr);
+ if (__asprintf (&buf, _("\
+%s: option '-W %s' doesn't allow an argument\n"),
+ argv[0], pfound->name) >= 0)
+ {
+ _IO_flockfile (stderr);
- int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
- ((_IO_FILE *) stderr)->_flags2
- |= _IO_FLAGS2_NOTCANCEL;
+ int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
+ ((_IO_FILE *) stderr)->_flags2
+ |= _IO_FLAGS2_NOTCANCEL;
- __fxprintf (NULL, "%s", buf);
+ __fxprintf (NULL, "%s", buf);
- ((_IO_FILE *) stderr)->_flags2 = old_flags2;
- _IO_funlockfile (stderr);
+ ((_IO_FILE *) stderr)->_flags2 = old_flags2;
+ _IO_funlockfile (stderr);
- free (buf);
- }
+ free (buf);
+ }
#else
- fprintf (stderr, _("\
-%s: option `-W %s' doesn't allow an argument\n"),
- argv[0], pfound->name);
+ fprintf (stderr, _("\
+%s: option '-W %s' doesn't allow an argument\n"),
+ argv[0], pfound->name);
#endif
- }
-
- d->__nextchar += strlen (d->__nextchar);
- return '?';
- }
- }
- else if (pfound->has_arg == 1)
- {
- if (d->optind < argc)
- d->optarg = argv[d->optind++];
- else
- {
- if (print_errors)
- {
+ }
+
+ d->__nextchar += strlen (d->__nextchar);
+ return '?';
+ }
+ }
+ else if (pfound->has_arg == 1)
+ {
+ if (d->optind < argc)
+ d->optarg = argv[d->optind++];
+ else
+ {
+ if (print_errors)
+ {
#if defined _LIBC && defined USE_IN_LIBIO
- char *buf;
+ char *buf;
- if (__asprintf (&buf, _("\
-%s: option `%s' requires an argument\n"),
- argv[0], argv[d->optind - 1]) >= 0)
- {
- _IO_flockfile (stderr);
+ if (__asprintf (&buf, _("\
+%s: option '-W %s' requires an argument\n"),
+ argv[0], pfound->name) >= 0)
+ {
+ _IO_flockfile (stderr);
- int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
- ((_IO_FILE *) stderr)->_flags2
- |= _IO_FLAGS2_NOTCANCEL;
+ int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
+ ((_IO_FILE *) stderr)->_flags2
+ |= _IO_FLAGS2_NOTCANCEL;
- __fxprintf (NULL, "%s", buf);
+ __fxprintf (NULL, "%s", buf);
- ((_IO_FILE *) stderr)->_flags2 = old_flags2;
- _IO_funlockfile (stderr);
+ ((_IO_FILE *) stderr)->_flags2 = old_flags2;
+ _IO_funlockfile (stderr);
- free (buf);
- }
+ free (buf);
+ }
#else
- fprintf (stderr,
- _("%s: option `%s' requires an argument\n"),
- argv[0], argv[d->optind - 1]);
+ fprintf (stderr, _("\
+%s: option '-W %s' requires an argument\n"),
+ argv[0], pfound->name);
#endif
- }
- d->__nextchar += strlen (d->__nextchar);
- return optstring[0] == ':' ? ':' : '?';
- }
- }
- d->__nextchar += strlen (d->__nextchar);
- if (longind != NULL)
- *longind = option_index;
- if (pfound->flag)
- {
- *(pfound->flag) = pfound->val;
- return 0;
- }
- return pfound->val;
- }
- d->__nextchar = NULL;
- return 'W'; /* Let the application handle it. */
+ }
+ d->__nextchar += strlen (d->__nextchar);
+ return optstring[0] == ':' ? ':' : '?';
+ }
+ }
+ else
+ d->optarg = NULL;
+ d->__nextchar += strlen (d->__nextchar);
+ if (longind != NULL)
+ *longind = option_index;
+ if (pfound->flag)
+ {
+ *(pfound->flag) = pfound->val;
+ return 0;
+ }
+ return pfound->val;
+ }
+
+ no_longs:
+ d->__nextchar = NULL;
+ return 'W'; /* Let the application handle it. */
}
if (temp[1] == ':')
{
- if (temp[2] == ':')
- {
- /* This is an option that accepts an argument optionally. */
- if (*d->__nextchar != '\0')
- {
- d->optarg = d->__nextchar;
- d->optind++;
- }
- else
- d->optarg = NULL;
- d->__nextchar = NULL;
- }
- else
- {
- /* This is an option that requires an argument. */
- if (*d->__nextchar != '\0')
- {
- d->optarg = d->__nextchar;
- /* If we end this ARGV-element by taking the rest as an arg,
- we must advance to the next element now. */
- d->optind++;
- }
- else if (d->optind == argc)
- {
- if (print_errors)
- {
- /* 1003.2 specifies the format of this message. */
+ if (temp[2] == ':')
+ {
+ /* This is an option that accepts an argument optionally. */
+ if (*d->__nextchar != '\0')
+ {
+ d->optarg = d->__nextchar;
+ d->optind++;
+ }
+ else
+ d->optarg = NULL;
+ d->__nextchar = NULL;
+ }
+ else
+ {
+ /* This is an option that requires an argument. */
+ if (*d->__nextchar != '\0')
+ {
+ d->optarg = d->__nextchar;
+ /* If we end this ARGV-element by taking the rest as an arg,
+ we must advance to the next element now. */
+ d->optind++;
+ }
+ else if (d->optind == argc)
+ {
+ if (print_errors)
+ {
#if defined _LIBC && defined USE_IN_LIBIO
- char *buf;
+ char *buf;
- if (__asprintf (&buf, _("\
-%s: option requires an argument -- %c\n"),
- argv[0], c) >= 0)
- {
- _IO_flockfile (stderr);
+ if (__asprintf (&buf, _("\
+%s: option requires an argument -- '%c'\n"),
+ argv[0], c) >= 0)
+ {
+ _IO_flockfile (stderr);
- int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
- ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
+ int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
+ ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
- __fxprintf (NULL, "%s", buf);
+ __fxprintf (NULL, "%s", buf);
- ((_IO_FILE *) stderr)->_flags2 = old_flags2;
- _IO_funlockfile (stderr);
+ ((_IO_FILE *) stderr)->_flags2 = old_flags2;
+ _IO_funlockfile (stderr);
- free (buf);
- }
+ free (buf);
+ }
#else
- fprintf (stderr,
- _("%s: option requires an argument -- %c\n"),
- argv[0], c);
+ fprintf (stderr,
+ _("%s: option requires an argument -- '%c'\n"),
+ argv[0], c);
#endif
- }
- d->optopt = c;
- if (optstring[0] == ':')
- c = ':';
- else
- c = '?';
- }
- else
- /* We already incremented `optind' once;
- increment it again when taking next ARGV-elt as argument. */
- d->optarg = argv[d->optind++];
- d->__nextchar = NULL;
- }
+ }
+ d->optopt = c;
+ if (optstring[0] == ':')
+ c = ':';
+ else
+ c = '?';
+ }
+ else
+ /* We already incremented 'optind' once;
+ increment it again when taking next ARGV-elt as argument. */
+ d->optarg = argv[d->optind++];
+ d->__nextchar = NULL;
+ }
}
return c;
}
@@ -1086,16 +1156,17 @@ _getopt_internal_r (int argc, char **argv, const char *optstring,
int
_getopt_internal (int argc, char **argv, const char *optstring,
- const struct option *longopts, int *longind,
- int long_only, int posixly_correct)
+ const struct option *longopts, int *longind, int long_only,
+ int posixly_correct)
{
int result;
getopt_data.optind = optind;
getopt_data.opterr = opterr;
- result = _getopt_internal_r (argc, argv, optstring, longopts, longind,
- long_only, posixly_correct, &getopt_data);
+ result = _getopt_internal_r (argc, argv, optstring, longopts,
+ longind, long_only, &getopt_data,
+ posixly_correct);
optind = getopt_data.optind;
optarg = getopt_data.optarg;
@@ -1115,15 +1186,28 @@ enum { POSIXLY_CORRECT = 1 };
int
getopt (int argc, char *const *argv, const char *optstring)
{
- return _getopt_internal (argc, (char **) argv, optstring, NULL, NULL, 0,
- POSIXLY_CORRECT);
+ return _getopt_internal (argc, (char **) argv, optstring,
+ (const struct option *) 0,
+ (int *) 0,
+ 0, POSIXLY_CORRECT);
}
+#ifdef _LIBC
+int
+__posix_getopt (int argc, char *const *argv, const char *optstring)
+{
+ return _getopt_internal (argc, argv, optstring,
+ (const struct option *) 0,
+ (int *) 0,
+ 0, 1);
+}
+#endif
+
#ifdef TEST
/* Compile with -DTEST to make an executable for use in testing
- the above definition of `getopt'. */
+ the above definition of 'getopt'. */
int
main (int argc, char **argv)
@@ -1137,51 +1221,51 @@ main (int argc, char **argv)
c = getopt (argc, argv, "abc:d:0123456789");
if (c == -1)
- break;
+ break;
switch (c)
- {
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- if (digit_optind != 0 && digit_optind != this_option_optind)
- printf ("digits occur in two different argv-elements.\n");
- digit_optind = this_option_optind;
- printf ("option %c\n", c);
- break;
-
- case 'a':
- printf ("option a\n");
- break;
-
- case 'b':
- printf ("option b\n");
- break;
-
- case 'c':
- printf ("option c with value `%s'\n", optarg);
- break;
-
- case '?':
- break;
-
- default:
- printf ("?? getopt returned character code 0%o ??\n", c);
- }
+ {
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ if (digit_optind != 0 && digit_optind != this_option_optind)
+ printf ("digits occur in two different argv-elements.\n");
+ digit_optind = this_option_optind;
+ printf ("option %c\n", c);
+ break;
+
+ case 'a':
+ printf ("option a\n");
+ break;
+
+ case 'b':
+ printf ("option b\n");
+ break;
+
+ case 'c':
+ printf ("option c with value '%s'\n", optarg);
+ break;
+
+ case '?':
+ break;
+
+ default:
+ printf ("?? getopt returned character code 0%o ??\n", c);
+ }
}
if (optind < argc)
{
printf ("non-option ARGV-elements: ");
while (optind < argc)
- printf ("%s ", argv[optind++]);
+ printf ("%s ", argv[optind++]);
printf ("\n");
}
diff --git a/lib/getopt_.h b/lib/getopt.in.h
index 615ef9a..0f72182 100644
--- a/lib/getopt_.h
+++ b/lib/getopt.in.h
@@ -1,40 +1,60 @@
/* Declarations for getopt.
- Copyright (C) 1989-1994,1996-1999,2001,2003,2004,2005,2006,2007
- Free Software Foundation, Inc.
+ Copyright (C) 1989-1994, 1996-1999, 2001, 2003-2007, 2009-2016 Free Software
+ Foundation, Inc.
This file is part of the GNU C Library.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
-#ifndef _GETOPT_H
+#ifndef _@GUARD_PREFIX@_GETOPT_H
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+/* The include_next requires a split double-inclusion guard. We must
+ also inform the replacement unistd.h to not recursively use
+ <getopt.h>; our definitions will be present soon enough. */
+#if @HAVE_GETOPT_H@
+# define _GL_SYSTEM_GETOPT
+# @INCLUDE_NEXT@ @NEXT_GETOPT_H@
+# undef _GL_SYSTEM_GETOPT
+#endif
+
+#ifndef _@GUARD_PREFIX@_GETOPT_H
#ifndef __need_getopt
-# define _GETOPT_H 1
+# define _@GUARD_PREFIX@_GETOPT_H 1
#endif
/* Standalone applications should #define __GETOPT_PREFIX to an
identifier that prefixes the external functions and variables
defined in this header. When this happens, include the
headers that might declare getopt so that they will not cause
- confusion if included after this file. Then systematically rename
+ confusion if included after this file (if the system had <getopt.h>,
+ we have already included it). Then systematically rename
identifiers so that they do not collide with the system functions
and variables. Renaming avoids problems with some compilers and
linkers. */
#if defined __GETOPT_PREFIX && !defined __need_getopt
-# include <stdlib.h>
-# include <stdio.h>
-# include <unistd.h>
+# if !@HAVE_GETOPT_H@
+# define __need_system_stdlib_h
+# include <stdlib.h>
+# undef __need_system_stdlib_h
+# include <stdio.h>
+# include <unistd.h>
+# endif
# undef __need_getopt
# undef getopt
# undef getopt_long
@@ -43,6 +63,7 @@
# undef opterr
# undef optind
# undef optopt
+# undef option
# define __GETOPT_CONCAT(x, y) x ## y
# define __GETOPT_XCONCAT(x, y) __GETOPT_CONCAT (x, y)
# define __GETOPT_ID(y) __GETOPT_XCONCAT (__GETOPT_PREFIX, y)
@@ -53,6 +74,8 @@
# define opterr __GETOPT_ID (opterr)
# define optind __GETOPT_ID (optind)
# define optopt __GETOPT_ID (optopt)
+# define option __GETOPT_ID (option)
+# define _getopt_internal __GETOPT_ID (getopt_internal)
#endif
/* Standalone applications get correct prototypes for getopt_long and
@@ -61,7 +84,7 @@
getopt_long_only can permute argv; this is required for backward
compatibility (e.g., for LSB 2.0.1).
- This used to be `#if defined __GETOPT_PREFIX && !defined __need_getopt',
+ This used to be '#if defined __GETOPT_PREFIX && !defined __need_getopt',
but it caused redefinition warnings if both unistd.h and getopt.h were
included, since unistd.h includes getopt.h having previously defined
__need_getopt.
@@ -95,39 +118,41 @@
# define __GNUC_PREREQ(maj, min) (0)
# endif
# if defined __cplusplus && __GNUC_PREREQ (2,8)
-# define __THROW throw ()
+# define __THROW throw ()
# else
# define __THROW
# endif
#endif
+/* The definition of _GL_ARG_NONNULL is copied here. */
+
#ifdef __cplusplus
extern "C" {
#endif
-/* For communication from `getopt' to the caller.
- When `getopt' finds an option that takes an argument,
+/* For communication from 'getopt' to the caller.
+ When 'getopt' finds an option that takes an argument,
the argument value is returned here.
- Also, when `ordering' is RETURN_IN_ORDER,
+ Also, when 'ordering' is RETURN_IN_ORDER,
each non-option ARGV-element is returned here. */
extern char *optarg;
/* Index in ARGV of the next element to be scanned.
This is used for communication to and from the caller
- and for communication between successive calls to `getopt'.
+ and for communication between successive calls to 'getopt'.
- On entry to `getopt', zero means this is the first call; initialize.
+ On entry to 'getopt', zero means this is the first call; initialize.
- When `getopt' returns -1, this is the index of the first of the
+ When 'getopt' returns -1, this is the index of the first of the
non-option elements that the caller should itself scan.
- Otherwise, `optind' communicates from one call to the next
+ Otherwise, 'optind' communicates from one call to the next
how much of ARGV has been scanned so far. */
extern int optind;
-/* Callers store zero here to inhibit the error message `getopt' prints
+/* Callers store zero here to inhibit the error message 'getopt' prints
for unrecognized options. */
extern int opterr;
@@ -139,25 +164,26 @@ extern int optopt;
#ifndef __need_getopt
/* Describe the long-named options requested by the application.
The LONG_OPTIONS argument to getopt_long or getopt_long_only is a vector
- of `struct option' terminated by an element containing a name which is
+ of 'struct option' terminated by an element containing a name which is
zero.
- The field `has_arg' is:
- no_argument (or 0) if the option does not take an argument,
- required_argument (or 1) if the option requires an argument,
- optional_argument (or 2) if the option takes an optional argument.
+ The field 'has_arg' is:
+ no_argument (or 0) if the option does not take an argument,
+ required_argument (or 1) if the option requires an argument,
+ optional_argument (or 2) if the option takes an optional argument.
- If the field `flag' is not NULL, it points to a variable that is set
- to the value given in the field `val' when the option is found, but
+ If the field 'flag' is not NULL, it points to a variable that is set
+ to the value given in the field 'val' when the option is found, but
left unchanged if the option is not found.
- To have a long-named option do something other than set an `int' to
- a compiled-in constant, such as set a value from `optarg', set the
- option's `flag' field to zero and its `val' field to a nonzero
+ To have a long-named option do something other than set an 'int' to
+ a compiled-in constant, such as set a value from 'optarg', set the
+ option's 'flag' field to zero and its 'val' field to a nonzero
value (the equivalent single-letter option character, if there is
- one). For long options that have a zero `flag' field, `getopt'
- returns the contents of the `val' field. */
+ one). For long options that have a zero 'flag' field, 'getopt'
+ returns the contents of the 'val' field. */
+# if !GNULIB_defined_struct_option
struct option
{
const char *name;
@@ -167,13 +193,15 @@ struct option
int *flag;
int val;
};
+# define GNULIB_defined_struct_option 1
+# endif
-/* Names for the values of the `has_arg' field of `struct option'. */
+/* Names for the values of the 'has_arg' field of 'struct option'. */
-# define no_argument 0
-# define required_argument 1
-# define optional_argument 2
-#endif /* need getopt */
+# define no_argument 0
+# define required_argument 1
+# define optional_argument 2
+#endif /* need getopt */
/* Get definitions and prototypes for functions to process the
@@ -182,37 +210,37 @@ struct option
Return the option character from OPTS just read. Return -1 when
there are no more options. For unrecognized options, or options
- missing arguments, `optopt' is set to the option letter, and '?' is
+ missing arguments, 'optopt' is set to the option letter, and '?' is
returned.
The OPTS string is a list of characters which are recognized option
letters, optionally followed by colons, specifying that that letter
- takes an argument, to be placed in `optarg'.
+ takes an argument, to be placed in 'optarg'.
If a letter in OPTS is followed by two colons, its argument is
- optional. This behavior is specific to the GNU `getopt'.
+ optional. This behavior is specific to the GNU 'getopt'.
- The argument `--' causes premature termination of argument
- scanning, explicitly telling `getopt' that there are no more
+ The argument '--' causes premature termination of argument
+ scanning, explicitly telling 'getopt' that there are no more
options.
- If OPTS begins with `-', then non-option arguments are treated as
+ If OPTS begins with '-', then non-option arguments are treated as
arguments to the option '\1'. This behavior is specific to the GNU
- `getopt'. If OPTS begins with `+', or POSIXLY_CORRECT is set in
+ 'getopt'. If OPTS begins with '+', or POSIXLY_CORRECT is set in
the environment, then do not permute arguments. */
extern int getopt (int ___argc, char *const *___argv, const char *__shortopts)
- __THROW;
+ __THROW _GL_ARG_NONNULL ((2, 3));
#ifndef __need_getopt
extern int getopt_long (int ___argc, char *__getopt_argv_const *___argv,
- const char *__shortopts,
- const struct option *__longopts, int *__longind)
- __THROW;
+ const char *__shortopts,
+ const struct option *__longopts, int *__longind)
+ __THROW _GL_ARG_NONNULL ((2, 3));
extern int getopt_long_only (int ___argc, char *__getopt_argv_const *___argv,
- const char *__shortopts,
- const struct option *__longopts, int *__longind)
- __THROW;
+ const char *__shortopts,
+ const struct option *__longopts, int *__longind)
+ __THROW _GL_ARG_NONNULL ((2, 3));
#endif
@@ -223,4 +251,5 @@ extern int getopt_long_only (int ___argc, char *__getopt_argv_const *___argv,
/* Make sure we later can get all the definitions and declarations. */
#undef __need_getopt
-#endif /* getopt.h */
+#endif /* _@GUARD_PREFIX@_GETOPT_H */
+#endif /* _@GUARD_PREFIX@_GETOPT_H */
diff --git a/lib/getopt1.c b/lib/getopt1.c
index cc0746e..63db74f 100644
--- a/lib/getopt1.c
+++ b/lib/getopt1.c
@@ -1,21 +1,20 @@
/* getopt_long and getopt_long_only entry points for GNU getopt.
- Copyright (C) 1987,88,89,90,91,92,93,94,96,97,98,2004,2006
- Free Software Foundation, Inc.
+ Copyright (C) 1987-1994, 1996-1998, 2004, 2006, 2009-2016 Free Software
+ Foundation, Inc.
This file is part of the GNU C Library.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifdef _LIBC
# include <getopt.h>
@@ -33,25 +32,25 @@
#include <stdlib.h>
#endif
-#ifndef NULL
+#ifndef NULL
#define NULL 0
#endif
int
getopt_long (int argc, char *__getopt_argv_const *argv, const char *options,
- const struct option *long_options, int *opt_index)
+ const struct option *long_options, int *opt_index)
{
return _getopt_internal (argc, (char **) argv, options, long_options,
- opt_index, 0, 0);
+ opt_index, 0, 0);
}
int
_getopt_long_r (int argc, char **argv, const char *options,
- const struct option *long_options, int *opt_index,
- struct _getopt_data *d)
+ const struct option *long_options, int *opt_index,
+ struct _getopt_data *d)
{
return _getopt_internal_r (argc, argv, options, long_options, opt_index,
- 0, 0, d);
+ 0, d, 0);
}
/* Like getopt_long, but '-' as well as '--' can indicate a long option.
@@ -61,20 +60,20 @@ _getopt_long_r (int argc, char **argv, const char *options,
int
getopt_long_only (int argc, char *__getopt_argv_const *argv,
- const char *options,
- const struct option *long_options, int *opt_index)
+ const char *options,
+ const struct option *long_options, int *opt_index)
{
return _getopt_internal (argc, (char **) argv, options, long_options,
- opt_index, 1, 0);
+ opt_index, 1, 0);
}
int
_getopt_long_only_r (int argc, char **argv, const char *options,
- const struct option *long_options, int *opt_index,
- struct _getopt_data *d)
+ const struct option *long_options, int *opt_index,
+ struct _getopt_data *d)
{
return _getopt_internal_r (argc, argv, options, long_options, opt_index,
- 1, 0, d);
+ 1, d, 0);
}
@@ -92,76 +91,76 @@ main (int argc, char **argv)
{
int this_option_optind = optind ? optind : 1;
int option_index = 0;
- static struct option long_options[] =
+ static const struct option long_options[] =
{
- {"add", 1, 0, 0},
- {"append", 0, 0, 0},
- {"delete", 1, 0, 0},
- {"verbose", 0, 0, 0},
- {"create", 0, 0, 0},
- {"file", 1, 0, 0},
- {0, 0, 0, 0}
+ {"add", 1, 0, 0},
+ {"append", 0, 0, 0},
+ {"delete", 1, 0, 0},
+ {"verbose", 0, 0, 0},
+ {"create", 0, 0, 0},
+ {"file", 1, 0, 0},
+ {0, 0, 0, 0}
};
c = getopt_long (argc, argv, "abc:d:0123456789",
- long_options, &option_index);
+ long_options, &option_index);
if (c == -1)
- break;
+ break;
switch (c)
- {
- case 0:
- printf ("option %s", long_options[option_index].name);
- if (optarg)
- printf (" with arg %s", optarg);
- printf ("\n");
- break;
-
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- if (digit_optind != 0 && digit_optind != this_option_optind)
- printf ("digits occur in two different argv-elements.\n");
- digit_optind = this_option_optind;
- printf ("option %c\n", c);
- break;
-
- case 'a':
- printf ("option a\n");
- break;
-
- case 'b':
- printf ("option b\n");
- break;
-
- case 'c':
- printf ("option c with value `%s'\n", optarg);
- break;
-
- case 'd':
- printf ("option d with value `%s'\n", optarg);
- break;
-
- case '?':
- break;
-
- default:
- printf ("?? getopt returned character code 0%o ??\n", c);
- }
+ {
+ case 0:
+ printf ("option %s", long_options[option_index].name);
+ if (optarg)
+ printf (" with arg %s", optarg);
+ printf ("\n");
+ break;
+
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ if (digit_optind != 0 && digit_optind != this_option_optind)
+ printf ("digits occur in two different argv-elements.\n");
+ digit_optind = this_option_optind;
+ printf ("option %c\n", c);
+ break;
+
+ case 'a':
+ printf ("option a\n");
+ break;
+
+ case 'b':
+ printf ("option b\n");
+ break;
+
+ case 'c':
+ printf ("option c with value '%s'\n", optarg);
+ break;
+
+ case 'd':
+ printf ("option d with value '%s'\n", optarg);
+ break;
+
+ case '?':
+ break;
+
+ default:
+ printf ("?? getopt returned character code 0%o ??\n", c);
+ }
}
if (optind < argc)
{
printf ("non-option ARGV-elements: ");
while (optind < argc)
- printf ("%s ", argv[optind++]);
+ printf ("%s ", argv[optind++]);
printf ("\n");
}
diff --git a/lib/getopt_int.h b/lib/getopt_int.h
index 401579f..be4c22e 100644
--- a/lib/getopt_int.h
+++ b/lib/getopt_int.h
@@ -1,34 +1,69 @@
/* Internal declarations for getopt.
- Copyright (C) 1989-1994,1996-1999,2001,2003,2004
- Free Software Foundation, Inc.
+ Copyright (C) 1989-1994, 1996-1999, 2001, 2003-2004, 2009-2016 Free Software
+ Foundation, Inc.
This file is part of the GNU C Library.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifndef _GETOPT_INT_H
-#define _GETOPT_INT_H 1
+#define _GETOPT_INT_H 1
+
+#include <getopt.h>
extern int _getopt_internal (int ___argc, char **___argv,
- const char *__shortopts,
- const struct option *__longopts, int *__longind,
- int __long_only, int __posixly_correct);
+ const char *__shortopts,
+ const struct option *__longopts, int *__longind,
+ int __long_only, int __posixly_correct);
/* Reentrant versions which can handle parsing multiple argument
vectors at the same time. */
+/* Describe how to deal with options that follow non-option ARGV-elements.
+
+ If the caller did not specify anything,
+ the default is REQUIRE_ORDER if the environment variable
+ POSIXLY_CORRECT is defined, PERMUTE otherwise.
+
+ REQUIRE_ORDER means don't recognize them as options;
+ stop option processing when the first non-option is seen.
+ This is what Unix does.
+ This mode of operation is selected by either setting the environment
+ variable POSIXLY_CORRECT, or using '+' as the first character
+ of the list of option characters, or by calling getopt.
+
+ PERMUTE is the default. We permute the contents of ARGV as we
+ scan, so that eventually all the non-options are at the end.
+ This allows options to be given in any order, even with programs
+ that were not written to expect this.
+
+ RETURN_IN_ORDER is an option available to programs that were
+ written to expect options and other ARGV-elements in any order
+ and that care about the ordering of the two. We describe each
+ non-option ARGV-element as if it were the argument of an option
+ with character code 1. Using '-' as the first character of the
+ list of option characters selects this mode of operation.
+
+ The special argument '--' forces an end of option-scanning regardless
+ of the value of 'ordering'. In the case of RETURN_IN_ORDER, only
+ '--' can cause 'getopt' to return -1 with 'optind' != ARGC. */
+
+enum __ord
+ {
+ REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
+ };
+
/* Data type for reentrant functions. */
struct _getopt_data
{
@@ -53,39 +88,8 @@ struct _getopt_data
by advancing to the next ARGV-element. */
char *__nextchar;
- /* Describe how to deal with options that follow non-option ARGV-elements.
-
- If the caller did not specify anything,
- the default is REQUIRE_ORDER if the environment variable
- POSIXLY_CORRECT is defined, PERMUTE otherwise.
-
- REQUIRE_ORDER means don't recognize them as options;
- stop option processing when the first non-option is seen.
- This is what Unix does.
- This mode of operation is selected by either setting the environment
- variable POSIXLY_CORRECT, or using `+' as the first character
- of the list of option characters, or by calling getopt.
-
- PERMUTE is the default. We permute the contents of ARGV as we
- scan, so that eventually all the non-options are at the end.
- This allows options to be given in any order, even with programs
- that were not written to expect this.
-
- RETURN_IN_ORDER is an option available to programs that were
- written to expect options and other ARGV-elements in any order
- and that care about the ordering of the two. We describe each
- non-option ARGV-element as if it were the argument of an option
- with character code 1. Using `-' as the first character of the
- list of option characters selects this mode of operation.
-
- The special argument `--' forces an end of option-scanning regardless
- of the value of `ordering'. In the case of RETURN_IN_ORDER, only
- `--' can cause `getopt' to return -1 with `optind' != ARGC. */
-
- enum
- {
- REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
- } __ordering;
+ /* See __ord above. */
+ enum __ord __ordering;
/* If the POSIXLY_CORRECT environment variable is set
or getopt was called. */
@@ -95,8 +99,8 @@ struct _getopt_data
/* Handle permutation of arguments. */
/* Describe the part of ARGV that contains non-options that have
- been skipped. `first_nonopt' is the index in ARGV of the first
- of them; `last_nonopt' is the index after the last of them. */
+ been skipped. 'first_nonopt' is the index in ARGV of the first
+ of them; 'last_nonopt' is the index after the last of them. */
int __first_nonopt;
int __last_nonopt;
@@ -104,28 +108,28 @@ struct _getopt_data
#if defined _LIBC && defined USE_NONOPTION_FLAGS
int __nonoption_flags_max_len;
int __nonoption_flags_len;
-# endif
+#endif
};
/* The initializer is necessary to set OPTIND and OPTERR to their
default values and to clear the initialization flag. */
-#define _GETOPT_DATA_INITIALIZER { 1, 1 }
+#define _GETOPT_DATA_INITIALIZER { 1, 1 }
extern int _getopt_internal_r (int ___argc, char **___argv,
- const char *__shortopts,
- const struct option *__longopts, int *__longind,
- int __long_only, int __posixly_correct,
- struct _getopt_data *__data);
+ const char *__shortopts,
+ const struct option *__longopts, int *__longind,
+ int __long_only, struct _getopt_data *__data,
+ int __posixly_correct);
extern int _getopt_long_r (int ___argc, char **___argv,
- const char *__shortopts,
- const struct option *__longopts, int *__longind,
- struct _getopt_data *__data);
+ const char *__shortopts,
+ const struct option *__longopts, int *__longind,
+ struct _getopt_data *__data);
extern int _getopt_long_only_r (int ___argc, char **___argv,
- const char *__shortopts,
- const struct option *__longopts,
- int *__longind,
- struct _getopt_data *__data);
+ const char *__shortopts,
+ const struct option *__longopts,
+ int *__longind,
+ struct _getopt_data *__data);
#endif /* getopt_int.h */
diff --git a/lib/getpagesize.c b/lib/getpagesize.c
new file mode 100644
index 0000000..dc4a200
--- /dev/null
+++ b/lib/getpagesize.c
@@ -0,0 +1,39 @@
+/* getpagesize emulation for systems where it cannot be done in a C macro.
+
+ Copyright (C) 2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Bruno Haible and Martin Lambers. */
+
+#include <config.h>
+
+/* Specification. */
+#include <unistd.h>
+
+/* This implementation is only for native Windows systems. */
+#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+
+# define WIN32_LEAN_AND_MEAN
+# include <windows.h>
+
+int
+getpagesize (void)
+{
+ SYSTEM_INFO system_info;
+ GetSystemInfo (&system_info);
+ return system_info.dwPageSize;
+}
+
+#endif
diff --git a/lib/getpagesize.h b/lib/getpagesize.h
deleted file mode 100644
index 8863336..0000000
--- a/lib/getpagesize.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/* Emulate getpagesize on systems that lack it.
- Copyright (C) 1999, 2000, 2004, 2005 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 2, 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, write to the Free Software
- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
- USA. */
-
-#ifndef HAVE_GETPAGESIZE
-
-#include <unistd.h>
-
-#if !defined getpagesize && defined _SC_PAGESIZE
-# if ! (defined __VMS && __VMS_VER < 70000000)
-# define getpagesize() sysconf (_SC_PAGESIZE)
-# endif
-#endif
-
-#if !defined getpagesize && defined __VMS
-# ifdef __ALPHA
-# define getpagesize() 8192
-# else
-# define getpagesize() 512
-# endif
-#endif
-
-/* This is for BeOS. */
-#if !defined getpagesize && HAVE_OS_H
-# include <OS.h>
-# if defined B_PAGE_SIZE
-# define getpagesize() B_PAGE_SIZE
-# endif
-#endif
-
-/* This is for AmigaOS4.0. */
-#if !defined getpagesize && defined __amigaos4__
-# define getpagesize() 2048
-#endif
-
-#if !defined getpagesize && HAVE_SYS_PARAM_H
-# include <sys/param.h>
-# ifdef EXEC_PAGESIZE
-# define getpagesize() EXEC_PAGESIZE
-# else
-# ifdef NBPG
-# ifndef CLSIZE
-# define CLSIZE 1
-# endif
-# define getpagesize() (NBPG * CLSIZE)
-# else
-# ifdef NBPC
-# define getpagesize() NBPC
-# endif
-# endif
-# endif
-#endif
-
-#endif /* not HAVE_GETPAGESIZE */
diff --git a/lib/getpass.c b/lib/getpass.c
index 5b39b6d..3360fa2 100644
--- a/lib/getpass.c
+++ b/lib/getpass.c
@@ -1,11 +1,10 @@
-/* Copyright (C) 1992-2001, 2003, 2004, 2005, 2006 Free Software
- Foundation, Inc.
+/* Copyright (C) 1992-2001, 2003-2007, 2009-2016 Free Software Foundation, Inc.
This file is part of the GNU C Library.
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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -14,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ with this program; if not, see <http://www.gnu.org/licenses/>. */
#ifndef _LIBC
# include <config.h>
@@ -27,55 +25,53 @@
#if !((defined _WIN32 || defined __WIN32__) && !defined __CYGWIN__)
-#include <stdbool.h>
+# include <stdbool.h>
-#if HAVE_DECL___FSETLOCKING && HAVE___FSETLOCKING
-# if HAVE_STDIO_EXT_H
-# include <stdio_ext.h>
+# if HAVE_DECL___FSETLOCKING && HAVE___FSETLOCKING
+# if HAVE_STDIO_EXT_H
+# include <stdio_ext.h>
+# endif
+# else
+# define __fsetlocking(stream, type) /* empty */
# endif
-#else
-# define __fsetlocking(stream, type) /* empty */
-#endif
-
-#if HAVE_TERMIOS_H
-# include <termios.h>
-#endif
-#include "getline.h"
-
-#if USE_UNLOCKED_IO
-# include "unlocked-io.h"
-#else
-# if !HAVE_DECL_FFLUSH_UNLOCKED
-# undef fflush_unlocked
-# define fflush_unlocked(x) fflush (x)
-# endif
-# if !HAVE_DECL_FLOCKFILE
-# undef flockfile
-# define flockfile(x) ((void) 0)
+# if HAVE_TERMIOS_H
+# include <termios.h>
# endif
-# if !HAVE_DECL_FUNLOCKFILE
-# undef funlockfile
-# define funlockfile(x) ((void) 0)
-# endif
-# if !HAVE_DECL_FPUTS_UNLOCKED
-# undef fputs_unlocked
-# define fputs_unlocked(str,stream) fputs (str, stream)
-# endif
-# if !HAVE_DECL_PUTC_UNLOCKED
-# undef putc_unlocked
-# define putc_unlocked(c,stream) putc (c, stream)
+
+# if USE_UNLOCKED_IO
+# include "unlocked-io.h"
+# else
+# if !HAVE_DECL_FFLUSH_UNLOCKED
+# undef fflush_unlocked
+# define fflush_unlocked(x) fflush (x)
+# endif
+# if !HAVE_DECL_FLOCKFILE
+# undef flockfile
+# define flockfile(x) ((void) 0)
+# endif
+# if !HAVE_DECL_FUNLOCKFILE
+# undef funlockfile
+# define funlockfile(x) ((void) 0)
+# endif
+# if !HAVE_DECL_FPUTS_UNLOCKED
+# undef fputs_unlocked
+# define fputs_unlocked(str,stream) fputs (str, stream)
+# endif
+# if !HAVE_DECL_PUTC_UNLOCKED
+# undef putc_unlocked
+# define putc_unlocked(c,stream) putc (c, stream)
+# endif
# endif
-#endif
/* It is desirable to use this bit on systems that have it.
The only bit of terminal state we want to twiddle is echoing, which is
done in software; there is no need to change the state of the terminal
hardware. */
-#ifndef TCSASOFT
-# define TCSASOFT 0
-#endif
+# ifndef TCSASOFT
+# define TCSASOFT 0
+# endif
static void
call_fclose (void *arg)
@@ -89,7 +85,9 @@ getpass (const char *prompt)
{
FILE *tty;
FILE *in, *out;
+# if HAVE_TCGETATTR
struct termios s, t;
+# endif
bool tty_changed = false;
static char *buf;
static size_t bufsize;
@@ -115,7 +113,7 @@ getpass (const char *prompt)
flockfile (out);
/* Turn echoing off if it is on now. */
-#if HAVE_TCGETATTR
+# if HAVE_TCGETATTR
if (tcgetattr (fileno (in), &t) == 0)
{
/* Save the old one. */
@@ -124,7 +122,7 @@ getpass (const char *prompt)
t.c_lflag &= ~(ECHO | ISIG);
tty_changed = (tcsetattr (fileno (in), TCSAFLUSH | TCSASOFT, &t) == 0);
}
-#endif
+# endif
/* Write the prompt. */
fputs_unlocked (prompt, out);
@@ -142,29 +140,29 @@ getpass (const char *prompt)
== fileno (out). The POSIX restrictions are tricky and change
from POSIX version to POSIX version, so play it safe and invoke
fseek even if in != out. */
- fseek (out, 0, SEEK_CUR);
+ fseeko (out, 0, SEEK_CUR);
if (buf != NULL)
{
if (nread < 0)
- buf[0] = '\0';
+ buf[0] = '\0';
else if (buf[nread - 1] == '\n')
- {
- /* Remove the newline. */
- buf[nread - 1] = '\0';
- if (tty_changed)
- {
- /* Write the newline that was not echoed. */
- putc_unlocked ('\n', out);
- }
- }
+ {
+ /* Remove the newline. */
+ buf[nread - 1] = '\0';
+ if (tty_changed)
+ {
+ /* Write the newline that was not echoed. */
+ putc_unlocked ('\n', out);
+ }
+ }
}
/* Restore the original setting. */
-#if HAVE_TCSETATTR
+# if HAVE_TCSETATTR
if (tty_changed)
tcsetattr (fileno (in), TCSAFLUSH | TCSASOFT, &s);
-#endif
+# endif
funlockfile (out);
@@ -179,15 +177,15 @@ getpass (const char *prompt)
improved by Simon Josefsson. */
/* For PASS_MAX. */
-#include <limits.h>
+# include <limits.h>
/* For _getch(). */
-#include <conio.h>
+# include <conio.h>
/* For strdup(). */
-#include <string.h>
+# include <string.h>
-#ifndef PASS_MAX
-# define PASS_MAX 512
-#endif
+# ifndef PASS_MAX
+# define PASS_MAX 512
+# endif
char *
getpass (const char *prompt)
@@ -206,20 +204,20 @@ getpass (const char *prompt)
{
c = _getch ();
if (c == '\r')
- {
- getpassbuf[i] = '\0';
- break;
- }
+ {
+ getpassbuf[i] = '\0';
+ break;
+ }
else if (i < PASS_MAX)
- {
- getpassbuf[i++] = c;
- }
+ {
+ getpassbuf[i++] = c;
+ }
if (i >= PASS_MAX)
- {
- getpassbuf[i] = '\0';
- break;
- }
+ {
+ getpassbuf[i] = '\0';
+ break;
+ }
}
if (prompt)
diff --git a/lib/getpass.h b/lib/getpass.h
index bdff875..785fe00 100644
--- a/lib/getpass.h
+++ b/lib/getpass.h
@@ -1,10 +1,10 @@
/* getpass.h -- Read a password of arbitrary length from /dev/tty or stdin.
- Copyright (C) 2004 Free Software Foundation, Inc.
+ Copyright (C) 2004, 2009-2016 Free Software Foundation, Inc.
Contributed by Simon Josefsson <jas@extundo.com>, 2004.
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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program; if not, see <http://www.gnu.org/licenses/>. */
#ifndef GETPASS_H
# define GETPASS_H
@@ -22,7 +21,7 @@
/* Get getpass declaration, if available. */
# include <unistd.h>
-# if defined HAVE_DECL_GETPASS && !HAVE_DECL_GETPASS
+# if !HAVE_DECL_GETPASS
/* Read a password of arbitrary length from /dev/tty or stdin. */
char *getpass (const char *prompt);
diff --git a/lib/gettext.h b/lib/gettext.h
index 9d76ec9..00af872 100644
--- a/lib/gettext.h
+++ b/lib/gettext.h
@@ -1,9 +1,10 @@
/* Convenience header for conditional use of GNU <libintl.h>.
- Copyright (C) 1995-1998, 2000-2002, 2004-2006 Free Software Foundation, Inc.
+ Copyright (C) 1995-1998, 2000-2002, 2004-2006, 2009-2016 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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -12,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ with this program; if not, see <http://www.gnu.org/licenses/>. */
#ifndef _LIBGETTEXT_H
#define _LIBGETTEXT_H 1
@@ -53,7 +53,7 @@
it now, to make later inclusions of <libintl.h> a NOP. */
#if defined(__cplusplus) && defined(__GNUG__) && (__GNUC__ >= 3)
# include <cstdlib>
-# if (__GLIBC__ >= 2) || _GLIBCXX_HAVE_LIBINTL_H
+# if (__GLIBC__ >= 2 && !defined __UCLIBC__) || _GLIBCXX_HAVE_LIBINTL_H
# include <libintl.h>
# endif
#endif
@@ -63,26 +63,41 @@
for invalid uses of the value returned from these functions.
On pre-ANSI systems without 'const', the config.h file is supposed to
contain "#define const". */
+# undef gettext
# define gettext(Msgid) ((const char *) (Msgid))
+# undef dgettext
# define dgettext(Domainname, Msgid) ((void) (Domainname), gettext (Msgid))
+# undef dcgettext
# define dcgettext(Domainname, Msgid, Category) \
((void) (Category), dgettext (Domainname, Msgid))
+# undef ngettext
# define ngettext(Msgid1, Msgid2, N) \
((N) == 1 \
? ((void) (Msgid2), (const char *) (Msgid1)) \
: ((void) (Msgid1), (const char *) (Msgid2)))
+# undef dngettext
# define dngettext(Domainname, Msgid1, Msgid2, N) \
((void) (Domainname), ngettext (Msgid1, Msgid2, N))
+# undef dcngettext
# define dcngettext(Domainname, Msgid1, Msgid2, N, Category) \
- ((void) (Category), dngettext(Domainname, Msgid1, Msgid2, N))
+ ((void) (Category), dngettext (Domainname, Msgid1, Msgid2, N))
+# undef textdomain
# define textdomain(Domainname) ((const char *) (Domainname))
+# undef bindtextdomain
# define bindtextdomain(Domainname, Dirname) \
((void) (Domainname), (const char *) (Dirname))
+# undef bind_textdomain_codeset
# define bind_textdomain_codeset(Domainname, Codeset) \
((void) (Domainname), (const char *) (Codeset))
#endif
+/* Prefer gnulib's setlocale override over libintl's setlocale override. */
+#ifdef GNULIB_defined_setlocale
+# undef setlocale
+# define setlocale rpl_setlocale
+#endif
+
/* A pseudo function call that serves as a marker for the automated
extraction of messages, but does not call gettext(). The run-time
translation is done at a different place in the code.
@@ -131,8 +146,8 @@ inline
#endif
static const char *
pgettext_aux (const char *domain,
- const char *msg_ctxt_id, const char *msgid,
- int category)
+ const char *msg_ctxt_id, const char *msgid,
+ int category)
{
const char *translation = dcgettext (domain, msg_ctxt_id, category);
if (translation == msg_ctxt_id)
@@ -150,9 +165,9 @@ inline
#endif
static const char *
npgettext_aux (const char *domain,
- const char *msg_ctxt_id, const char *msgid,
- const char *msgid_plural, unsigned long int n,
- int category)
+ const char *msg_ctxt_id, const char *msgid,
+ const char *msgid_plural, unsigned long int n,
+ int category)
{
const char *translation =
dcngettext (domain, msg_ctxt_id, msgid_plural, n, category);
@@ -168,9 +183,12 @@ npgettext_aux (const char *domain,
#include <string.h>
-#define _LIBGETTEXT_HAVE_VARIABLE_SIZE_ARRAYS \
- (((__GNUC__ >= 3 || __GNUG__ >= 2) && !__STRICT_ANSI__) \
- /* || __STDC_VERSION__ >= 199901L */ )
+#if (((__GNUC__ >= 3 || __GNUG__ >= 2) && !defined __STRICT_ANSI__) \
+ /* || __STDC_VERSION__ >= 199901L */ )
+# define _LIBGETTEXT_HAVE_VARIABLE_SIZE_ARRAYS 1
+#else
+# define _LIBGETTEXT_HAVE_VARIABLE_SIZE_ARRAYS 0
+#endif
#if !_LIBGETTEXT_HAVE_VARIABLE_SIZE_ARRAYS
#include <stdlib.h>
@@ -190,8 +208,8 @@ inline
#endif
static const char *
dcpgettext_expr (const char *domain,
- const char *msgctxt, const char *msgid,
- int category)
+ const char *msgctxt, const char *msgid,
+ int category)
{
size_t msgctxt_len = strlen (msgctxt) + 1;
size_t msgid_len = strlen (msgid) + 1;
@@ -213,10 +231,10 @@ dcpgettext_expr (const char *domain,
translation = dcgettext (domain, msg_ctxt_id, category);
#if !_LIBGETTEXT_HAVE_VARIABLE_SIZE_ARRAYS
if (msg_ctxt_id != buf)
- free (msg_ctxt_id);
+ free (msg_ctxt_id);
#endif
if (translation != msg_ctxt_id)
- return translation;
+ return translation;
}
return msgid;
}
@@ -235,9 +253,9 @@ inline
#endif
static const char *
dcnpgettext_expr (const char *domain,
- const char *msgctxt, const char *msgid,
- const char *msgid_plural, unsigned long int n,
- int category)
+ const char *msgctxt, const char *msgid,
+ const char *msgid_plural, unsigned long int n,
+ int category)
{
size_t msgctxt_len = strlen (msgctxt) + 1;
size_t msgid_len = strlen (msgid) + 1;
@@ -259,10 +277,10 @@ dcnpgettext_expr (const char *domain,
translation = dcngettext (domain, msg_ctxt_id, msgid_plural, n, category);
#if !_LIBGETTEXT_HAVE_VARIABLE_SIZE_ARRAYS
if (msg_ctxt_id != buf)
- free (msg_ctxt_id);
+ free (msg_ctxt_id);
#endif
if (!(translation == msg_ctxt_id || translation == msgid_plural))
- return translation;
+ return translation;
}
return (n == 1 ? msgid : msgid_plural);
}
diff --git a/lib/gettime.c b/lib/gettime.c
index 86bd325..ea58eb0 100644
--- a/lib/gettime.c
+++ b/lib/gettime.c
@@ -1,11 +1,11 @@
/* gettime -- get the system clock
- Copyright (C) 2002, 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
+ Copyright (C) 2002, 2004-2007, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
diff --git a/lib/gettimeofday.c b/lib/gettimeofday.c
index bd5576c..224ca6a 100644
--- a/lib/gettimeofday.c
+++ b/lib/gettimeofday.c
@@ -1,11 +1,10 @@
/* Provide gettimeofday for systems that don't have it or for which it's broken.
- Copyright (C) 2001, 2002, 2003, 2005, 2006, 2007 Free Software
- Foundation, Inc.
+ Copyright (C) 2001-2003, 2005-2007, 2009-2016 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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -14,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program; if not, see <http://www.gnu.org/licenses/>. */
/* written by Jim Meyering */
@@ -41,6 +39,12 @@
static struct tm tm_zero_buffer;
static struct tm *localtime_buffer_addr = &tm_zero_buffer;
+# undef localtime
+extern struct tm *localtime (time_t const *);
+
+# undef gmtime
+extern struct tm *gmtime (time_t const *);
+
/* This is a wrapper for localtime. It is used only on systems for which
gettimeofday clobbers the static buffer used for localtime's result.
@@ -48,10 +52,8 @@ static struct tm *localtime_buffer_addr = &tm_zero_buffer;
localtime uses for its result. */
struct tm *
-localtime (time_t const *timep)
+rpl_localtime (time_t const *timep)
{
-#undef localtime
- extern struct tm *localtime (time_t const *);
struct tm *tm = localtime (timep);
if (localtime_buffer_addr == &tm_zero_buffer)
@@ -62,10 +64,8 @@ localtime (time_t const *timep)
/* Same as above, since gmtime and localtime use the same buffer. */
struct tm *
-gmtime (time_t const *timep)
+rpl_gmtime (time_t const *timep)
{
-#undef gmtime
- extern struct tm *gmtime (time_t const *);
struct tm *tm = gmtime (timep);
if (localtime_buffer_addr == &tm_zero_buffer)
@@ -77,14 +77,15 @@ gmtime (time_t const *timep)
#endif /* GETTIMEOFDAY_CLOBBERS_LOCALTIME || TZSET_CLOBBERS_LOCALTIME */
#if TZSET_CLOBBERS_LOCALTIME
+
+# undef tzset
+extern void tzset (void);
+
/* This is a wrapper for tzset, for systems on which tzset may clobber
the static buffer used for localtime's result. */
void
-tzset (void)
+rpl_tzset (void)
{
-#undef tzset
- extern void tzset (void);
-
/* Save and restore the contents of the buffer used for localtime's
result around the call to tzset. */
struct tm save = *localtime_buffer_addr;
@@ -98,7 +99,7 @@ tzset (void)
causes problems. */
int
-rpl_gettimeofday (struct timeval *restrict tv, void *restrict tz)
+gettimeofday (struct timeval *restrict tv, void *restrict tz)
{
#undef gettimeofday
#if HAVE_GETTIMEOFDAY
@@ -108,7 +109,18 @@ rpl_gettimeofday (struct timeval *restrict tv, void *restrict tz)
struct tm save = *localtime_buffer_addr;
# endif
- int result = gettimeofday (tv, tz);
+# if defined timeval /* 'struct timeval' overridden by gnulib? */
+# undef timeval
+ struct timeval otv;
+ int result = gettimeofday (&otv, (struct timezone *) tz);
+ if (result == 0)
+ {
+ tv->tv_sec = otv.tv_sec;
+ tv->tv_usec = otv.tv_usec;
+ }
+# else
+ int result = gettimeofday (tv, (struct timezone *) tz);
+# endif
# if GETTIMEOFDAY_CLOBBERS_LOCALTIME
*localtime_buffer_addr = save;
diff --git a/lib/getugroups.c b/lib/getugroups.c
index 970192e..96b84cb 100644
--- a/lib/getugroups.c
+++ b/lib/getugroups.c
@@ -1,12 +1,11 @@
/* getugroups.c -- return a list of the groups a user is in
- Copyright (C) 1990, 1991, 1998, 1999, 2000, 2003, 2004, 2005, 2006
- Free Software Foundation.
+ Copyright (C) 1990-1991, 1998-2000, 2003-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,91 +13,116 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by David MacKenzie. */
#include <config.h>
-#include <sys/types.h>
-#include <stdio.h> /* grp.h on alpha OSF1 V2.0 uses "FILE *". */
-#include <grp.h>
+#include "getugroups.h"
+#include <errno.h>
+#include <limits.h>
+#include <stdio.h> /* grp.h on alpha OSF1 V2.0 uses "FILE *". */
+#include <string.h>
#include <unistd.h>
-#include <errno.h>
-#ifndef EOVERFLOW
-# define EOVERFLOW EINVAL
-#endif
+#if !HAVE_GRP_H || defined __ANDROID__
-/* Some old header files might not declare setgrent, getgrent, and endgrent.
- If you don't have them at all, we can't implement this function.
- You lose! */
-struct group *getgrent ();
+/* Mingw lacks all things related to group management. The best we
+ can do is fail with ENOSYS.
-#include <string.h>
+ Bionic declares e.g. getgrent() in <grp.h> but it isn't actually
+ defined in the library. */
+
+int
+getugroups (int maxcount _GL_UNUSED,
+ gid_t *grouplist _GL_UNUSED,
+ char const *username _GL_UNUSED,
+ gid_t gid _GL_UNUSED)
+{
+ errno = ENOSYS;
+ return -1;
+}
-#define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
+#else /* HAVE_GRP_H */
+# include <grp.h>
-/* Like `getgroups', but for user USERNAME instead of for the current
+# define STREQ(a, b) (strcmp (a, b) == 0)
+
+/* Like 'getgroups', but for user USERNAME instead of for the current
process. Store at most MAXCOUNT group IDs in the GROUPLIST array.
If GID is not -1, store it first (if possible). GID should be the
group ID (pw_gid) obtained from getpwuid, in case USERNAME is not
- listed in /etc/groups.
- Always return the number of groups of which USERNAME is a member. */
+ listed in /etc/groups. Upon failure, set errno and return -1.
+ Otherwise, return the number of IDs we've written into GROUPLIST. */
int
-getugroups (int maxcount, GETGROUPS_T *grouplist, char *username, gid_t gid)
+getugroups (int maxcount, gid_t *grouplist, char const *username,
+ gid_t gid)
{
- struct group *grp;
- register char **cp;
- register int count = 0;
+ int count = 0;
if (gid != (gid_t) -1)
{
if (maxcount != 0)
- grouplist[count] = gid;
+ grouplist[count] = gid;
++count;
}
setgrent ();
- while ((grp = getgrent ()) != 0)
+ while (1)
{
+ char **cp;
+ struct group *grp;
+
+ errno = 0;
+ grp = getgrent ();
+ if (grp == NULL)
+ break;
+
for (cp = grp->gr_mem; *cp; ++cp)
- {
- int n;
-
- if ( ! STREQ (username, *cp))
- continue;
-
- /* See if this group number is already on the list. */
- for (n = 0; n < count; ++n)
- if (grouplist && grouplist[n] == grp->gr_gid)
- break;
-
- /* If it's a new group number, then try to add it to the list. */
- if (n == count)
- {
- if (maxcount != 0)
- {
- if (count >= maxcount)
- {
- endgrent ();
- return count;
- }
- grouplist[count] = grp->gr_gid;
- }
- count++;
- if (count < 0)
- {
- errno = EOVERFLOW;
- return -1;
- }
- }
- }
+ {
+ int n;
+
+ if ( ! STREQ (username, *cp))
+ continue;
+
+ /* See if this group number is already on the list. */
+ for (n = 0; n < count; ++n)
+ if (grouplist && grouplist[n] == grp->gr_gid)
+ break;
+
+ /* If it's a new group number, then try to add it to the list. */
+ if (n == count)
+ {
+ if (maxcount != 0)
+ {
+ if (count >= maxcount)
+ goto done;
+ grouplist[count] = grp->gr_gid;
+ }
+ if (count == INT_MAX)
+ {
+ errno = EOVERFLOW;
+ goto done;
+ }
+ count++;
+ }
+ }
}
- endgrent ();
+
+ if (errno != 0)
+ count = -1;
+
+ done:
+ {
+ int saved_errno = errno;
+ endgrent ();
+ errno = saved_errno;
+ }
return count;
}
+
+#endif /* HAVE_GRP_H */
diff --git a/lib/getugroups.h b/lib/getugroups.h
new file mode 100644
index 0000000..a183ccd
--- /dev/null
+++ b/lib/getugroups.h
@@ -0,0 +1,19 @@
+/* Get a list of group IDs associated with a specified user ID.
+ Copyright (C) 2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <sys/types.h>
+int getugroups (int maxcount, gid_t *grouplist, char const *username,
+ gid_t gid);
diff --git a/lib/getusershell.c b/lib/getusershell.c
index 6e7a443..6e069a9 100644
--- a/lib/getusershell.c
+++ b/lib/getusershell.c
@@ -1,12 +1,12 @@
/* getusershell.c -- Return names of valid user shells.
- Copyright (C) 1991, 1997, 2000, 2001, 2003, 2004, 2005, 2006 Free
- Software Foundation, Inc.
+ Copyright (C) 1991, 1997, 2000-2001, 2003-2006, 2008-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,13 +14,15 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by David MacKenzie <djm@gnu.ai.mit.edu> */
#include <config.h>
+/* Specification. */
+#include <unistd.h>
+
#ifndef SHELLS_FILE
# ifndef __DJGPP__
/* File containing a list of nonrestricted shells, one per line. */
@@ -57,8 +59,8 @@ static char const* const default_shells[] =
"/bin/sh", "/bin/csh", "/usr/bin/sh", "/usr/bin/csh", NULL
};
-/* Index of the next shell in `default_shells' to return.
- 0 means we are not using `default_shells'. */
+/* Index of the next shell in 'default_shells' to return.
+ 0 means we are not using 'default_shells'. */
static size_t default_index = 0;
/* Input stream from the shells file. */
@@ -67,7 +69,7 @@ static FILE *shellstream = NULL;
/* Line of input from the shells file. */
static char *line = NULL;
-/* Number of bytes allocated for `line'. */
+/* Number of bytes allocated for 'line'. */
static size_t line_size = 0;
/* Return an entry from the shells file, ignoring comment lines.
@@ -81,8 +83,8 @@ getusershell (void)
if (default_index > 0)
{
if (default_shells[default_index])
- /* Not at the end of the list yet. */
- return xstrdup (default_shells[default_index++]);
+ /* Not at the end of the list yet. */
+ return xstrdup (default_shells[default_index++]);
return NULL;
}
@@ -90,19 +92,19 @@ getusershell (void)
{
shellstream = fopen (SHELLS_FILE, "r");
if (shellstream == NULL)
- {
- /* No shells file. Use the default list. */
- default_index = 1;
- return xstrdup (default_shells[0]);
- }
+ {
+ /* No shells file. Use the default list. */
+ default_index = 1;
+ return xstrdup (default_shells[0]);
+ }
}
while (readname (&line, &line_size, shellstream))
{
if (*line != '#')
- return line;
+ return line;
}
- return NULL; /* End of file. */
+ return NULL; /* End of file. */
}
/* Rewind the shells file. */
@@ -148,9 +150,9 @@ readname (char **name, size_t *size, FILE *stream)
for (;;)
{
if (*size <= name_index)
- *name = x2nrealloc (*name, size, sizeof **name);
+ *name = x2nrealloc (*name, size, sizeof **name);
if (c == EOF || isspace (c))
- break;
+ break;
(*name)[name_index++] = c;
c = getc (stream);
}
diff --git a/lib/gl_openssl.h b/lib/gl_openssl.h
new file mode 100644
index 0000000..d612eca
--- /dev/null
+++ b/lib/gl_openssl.h
@@ -0,0 +1,116 @@
+/* Wrap openssl crypto hash routines in gnulib interface. -*- coding: utf-8 -*-
+
+ Copyright (C) 2013-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Pádraig Brady */
+
+#ifndef GL_OPENSSL_NAME
+# error "Please define GL_OPENSSL_NAME to 1,5,256 etc."
+#endif
+
+#ifndef _GL_INLINE_HEADER_BEGIN
+# error "Please include config.h first."
+#endif
+_GL_INLINE_HEADER_BEGIN
+#ifndef GL_OPENSSL_INLINE
+# define GL_OPENSSL_INLINE _GL_INLINE
+#endif
+
+/* Concatenate two preprocessor tokens. */
+#define _GLCRYPTO_CONCAT_(prefix, suffix) prefix##suffix
+#define _GLCRYPTO_CONCAT(prefix, suffix) _GLCRYPTO_CONCAT_ (prefix, suffix)
+
+#if GL_OPENSSL_NAME == 5
+# define OPENSSL_ALG md5
+#else
+# define OPENSSL_ALG _GLCRYPTO_CONCAT (sha, GL_OPENSSL_NAME)
+#endif
+
+/* Context type mappings. */
+#if BASE_OPENSSL_TYPE != GL_OPENSSL_NAME
+# undef BASE_OPENSSL_TYPE
+# if GL_OPENSSL_NAME == 224
+# define BASE_OPENSSL_TYPE 256
+# elif GL_OPENSSL_NAME == 384
+# define BASE_OPENSSL_TYPE 512
+# endif
+# define md5_CTX MD5_CTX
+# define sha1_CTX SHA_CTX
+# define sha224_CTX SHA256_CTX
+# define sha224_ctx sha256_ctx
+# define sha256_CTX SHA256_CTX
+# define sha384_CTX SHA512_CTX
+# define sha384_ctx sha512_ctx
+# define sha512_CTX SHA512_CTX
+# undef _gl_CTX
+# undef _gl_ctx
+# define _gl_CTX _GLCRYPTO_CONCAT (OPENSSL_ALG, _CTX) /* openssl type. */
+# define _gl_ctx _GLCRYPTO_CONCAT (OPENSSL_ALG, _ctx) /* gnulib type. */
+
+struct _gl_ctx { _gl_CTX CTX; };
+#endif
+
+/* Function name mappings. */
+#define md5_prefix MD5
+#define sha1_prefix SHA1
+#define sha224_prefix SHA224
+#define sha256_prefix SHA256
+#define sha384_prefix SHA384
+#define sha512_prefix SHA512
+#define _GLCRYPTO_PREFIX _GLCRYPTO_CONCAT (OPENSSL_ALG, _prefix)
+#define OPENSSL_FN(suffix) _GLCRYPTO_CONCAT (_GLCRYPTO_PREFIX, suffix)
+#define GL_CRYPTO_FN(suffix) _GLCRYPTO_CONCAT (OPENSSL_ALG, suffix)
+
+GL_OPENSSL_INLINE void
+GL_CRYPTO_FN (_init_ctx) (struct _gl_ctx *ctx)
+{ (void) OPENSSL_FN (_Init) ((_gl_CTX *) ctx); }
+
+/* These were never exposed by gnulib. */
+#if ! (GL_OPENSSL_NAME == 224 || GL_OPENSSL_NAME == 384)
+GL_OPENSSL_INLINE void
+GL_CRYPTO_FN (_process_bytes) (const void *buf, size_t len, struct _gl_ctx *ctx)
+{ OPENSSL_FN (_Update) ((_gl_CTX *) ctx, buf, len); }
+
+GL_OPENSSL_INLINE void
+GL_CRYPTO_FN (_process_block) (const void *buf, size_t len, struct _gl_ctx *ctx)
+{ GL_CRYPTO_FN (_process_bytes) (buf, len, ctx); }
+#endif
+
+GL_OPENSSL_INLINE void *
+GL_CRYPTO_FN (_finish_ctx) (struct _gl_ctx *ctx, void *res)
+{ OPENSSL_FN (_Final) ((unsigned char *) res, (_gl_CTX *) ctx); return res; }
+
+GL_OPENSSL_INLINE void *
+GL_CRYPTO_FN (_buffer) (const char *buf, size_t len, void *res)
+{ return OPENSSL_FN () ((const unsigned char *) buf, len, (unsigned char *) res); }
+
+GL_OPENSSL_INLINE void *
+GL_CRYPTO_FN (_read_ctx) (const struct _gl_ctx *ctx, void *res)
+{
+ /* Assume any unprocessed bytes in ctx are not to be ignored. */
+ _gl_CTX tmp_ctx = *(_gl_CTX *) ctx;
+ OPENSSL_FN (_Final) ((unsigned char *) res, &tmp_ctx);
+ return res;
+}
+
+/* Undef so we can include multiple times. */
+#undef GL_CRYPTO_FN
+#undef OPENSSL_FN
+#undef _GLCRYPTO_PREFIX
+#undef OPENSSL_ALG
+#undef GL_OPENSSL_NAME
+
+_GL_INLINE_HEADER_END
diff --git a/lib/glthread/lock.c b/lib/glthread/lock.c
new file mode 100644
index 0000000..935043b
--- /dev/null
+++ b/lib/glthread/lock.c
@@ -0,0 +1,1057 @@
+/* Locking in multithreaded situations.
+ Copyright (C) 2005-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Bruno Haible <bruno@clisp.org>, 2005.
+ Based on GCC's gthr-posix.h, gthr-posix95.h, gthr-solaris.h,
+ gthr-win32.h. */
+
+#include <config.h>
+
+#include "glthread/lock.h"
+
+/* ========================================================================= */
+
+#if USE_POSIX_THREADS
+
+/* -------------------------- gl_lock_t datatype -------------------------- */
+
+/* ------------------------- gl_rwlock_t datatype ------------------------- */
+
+# if HAVE_PTHREAD_RWLOCK
+
+# if !defined PTHREAD_RWLOCK_INITIALIZER
+
+int
+glthread_rwlock_init_multithreaded (gl_rwlock_t *lock)
+{
+ int err;
+
+ err = pthread_rwlock_init (&lock->rwlock, NULL);
+ if (err != 0)
+ return err;
+ lock->initialized = 1;
+ return 0;
+}
+
+int
+glthread_rwlock_rdlock_multithreaded (gl_rwlock_t *lock)
+{
+ if (!lock->initialized)
+ {
+ int err;
+
+ err = pthread_mutex_lock (&lock->guard);
+ if (err != 0)
+ return err;
+ if (!lock->initialized)
+ {
+ err = glthread_rwlock_init_multithreaded (lock);
+ if (err != 0)
+ {
+ pthread_mutex_unlock (&lock->guard);
+ return err;
+ }
+ }
+ err = pthread_mutex_unlock (&lock->guard);
+ if (err != 0)
+ return err;
+ }
+ return pthread_rwlock_rdlock (&lock->rwlock);
+}
+
+int
+glthread_rwlock_wrlock_multithreaded (gl_rwlock_t *lock)
+{
+ if (!lock->initialized)
+ {
+ int err;
+
+ err = pthread_mutex_lock (&lock->guard);
+ if (err != 0)
+ return err;
+ if (!lock->initialized)
+ {
+ err = glthread_rwlock_init_multithreaded (lock);
+ if (err != 0)
+ {
+ pthread_mutex_unlock (&lock->guard);
+ return err;
+ }
+ }
+ err = pthread_mutex_unlock (&lock->guard);
+ if (err != 0)
+ return err;
+ }
+ return pthread_rwlock_wrlock (&lock->rwlock);
+}
+
+int
+glthread_rwlock_unlock_multithreaded (gl_rwlock_t *lock)
+{
+ if (!lock->initialized)
+ return EINVAL;
+ return pthread_rwlock_unlock (&lock->rwlock);
+}
+
+int
+glthread_rwlock_destroy_multithreaded (gl_rwlock_t *lock)
+{
+ int err;
+
+ if (!lock->initialized)
+ return EINVAL;
+ err = pthread_rwlock_destroy (&lock->rwlock);
+ if (err != 0)
+ return err;
+ lock->initialized = 0;
+ return 0;
+}
+
+# endif
+
+# else
+
+int
+glthread_rwlock_init_multithreaded (gl_rwlock_t *lock)
+{
+ int err;
+
+ err = pthread_mutex_init (&lock->lock, NULL);
+ if (err != 0)
+ return err;
+ err = pthread_cond_init (&lock->waiting_readers, NULL);
+ if (err != 0)
+ return err;
+ err = pthread_cond_init (&lock->waiting_writers, NULL);
+ if (err != 0)
+ return err;
+ lock->waiting_writers_count = 0;
+ lock->runcount = 0;
+ return 0;
+}
+
+int
+glthread_rwlock_rdlock_multithreaded (gl_rwlock_t *lock)
+{
+ int err;
+
+ err = pthread_mutex_lock (&lock->lock);
+ if (err != 0)
+ return err;
+ /* Test whether only readers are currently running, and whether the runcount
+ field will not overflow. */
+ /* POSIX says: "It is implementation-defined whether the calling thread
+ acquires the lock when a writer does not hold the lock and there are
+ writers blocked on the lock." Let's say, no: give the writers a higher
+ priority. */
+ while (!(lock->runcount + 1 > 0 && lock->waiting_writers_count == 0))
+ {
+ /* This thread has to wait for a while. Enqueue it among the
+ waiting_readers. */
+ err = pthread_cond_wait (&lock->waiting_readers, &lock->lock);
+ if (err != 0)
+ {
+ pthread_mutex_unlock (&lock->lock);
+ return err;
+ }
+ }
+ lock->runcount++;
+ return pthread_mutex_unlock (&lock->lock);
+}
+
+int
+glthread_rwlock_wrlock_multithreaded (gl_rwlock_t *lock)
+{
+ int err;
+
+ err = pthread_mutex_lock (&lock->lock);
+ if (err != 0)
+ return err;
+ /* Test whether no readers or writers are currently running. */
+ while (!(lock->runcount == 0))
+ {
+ /* This thread has to wait for a while. Enqueue it among the
+ waiting_writers. */
+ lock->waiting_writers_count++;
+ err = pthread_cond_wait (&lock->waiting_writers, &lock->lock);
+ if (err != 0)
+ {
+ lock->waiting_writers_count--;
+ pthread_mutex_unlock (&lock->lock);
+ return err;
+ }
+ lock->waiting_writers_count--;
+ }
+ lock->runcount--; /* runcount becomes -1 */
+ return pthread_mutex_unlock (&lock->lock);
+}
+
+int
+glthread_rwlock_unlock_multithreaded (gl_rwlock_t *lock)
+{
+ int err;
+
+ err = pthread_mutex_lock (&lock->lock);
+ if (err != 0)
+ return err;
+ if (lock->runcount < 0)
+ {
+ /* Drop a writer lock. */
+ if (!(lock->runcount == -1))
+ {
+ pthread_mutex_unlock (&lock->lock);
+ return EINVAL;
+ }
+ lock->runcount = 0;
+ }
+ else
+ {
+ /* Drop a reader lock. */
+ if (!(lock->runcount > 0))
+ {
+ pthread_mutex_unlock (&lock->lock);
+ return EINVAL;
+ }
+ lock->runcount--;
+ }
+ if (lock->runcount == 0)
+ {
+ /* POSIX recommends that "write locks shall take precedence over read
+ locks", to avoid "writer starvation". */
+ if (lock->waiting_writers_count > 0)
+ {
+ /* Wake up one of the waiting writers. */
+ err = pthread_cond_signal (&lock->waiting_writers);
+ if (err != 0)
+ {
+ pthread_mutex_unlock (&lock->lock);
+ return err;
+ }
+ }
+ else
+ {
+ /* Wake up all waiting readers. */
+ err = pthread_cond_broadcast (&lock->waiting_readers);
+ if (err != 0)
+ {
+ pthread_mutex_unlock (&lock->lock);
+ return err;
+ }
+ }
+ }
+ return pthread_mutex_unlock (&lock->lock);
+}
+
+int
+glthread_rwlock_destroy_multithreaded (gl_rwlock_t *lock)
+{
+ int err;
+
+ err = pthread_mutex_destroy (&lock->lock);
+ if (err != 0)
+ return err;
+ err = pthread_cond_destroy (&lock->waiting_readers);
+ if (err != 0)
+ return err;
+ err = pthread_cond_destroy (&lock->waiting_writers);
+ if (err != 0)
+ return err;
+ return 0;
+}
+
+# endif
+
+/* --------------------- gl_recursive_lock_t datatype --------------------- */
+
+# if HAVE_PTHREAD_MUTEX_RECURSIVE
+
+# if defined PTHREAD_RECURSIVE_MUTEX_INITIALIZER || defined PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
+
+int
+glthread_recursive_lock_init_multithreaded (gl_recursive_lock_t *lock)
+{
+ pthread_mutexattr_t attributes;
+ int err;
+
+ err = pthread_mutexattr_init (&attributes);
+ if (err != 0)
+ return err;
+ err = pthread_mutexattr_settype (&attributes, PTHREAD_MUTEX_RECURSIVE);
+ if (err != 0)
+ {
+ pthread_mutexattr_destroy (&attributes);
+ return err;
+ }
+ err = pthread_mutex_init (lock, &attributes);
+ if (err != 0)
+ {
+ pthread_mutexattr_destroy (&attributes);
+ return err;
+ }
+ err = pthread_mutexattr_destroy (&attributes);
+ if (err != 0)
+ return err;
+ return 0;
+}
+
+# else
+
+int
+glthread_recursive_lock_init_multithreaded (gl_recursive_lock_t *lock)
+{
+ pthread_mutexattr_t attributes;
+ int err;
+
+ err = pthread_mutexattr_init (&attributes);
+ if (err != 0)
+ return err;
+ err = pthread_mutexattr_settype (&attributes, PTHREAD_MUTEX_RECURSIVE);
+ if (err != 0)
+ {
+ pthread_mutexattr_destroy (&attributes);
+ return err;
+ }
+ err = pthread_mutex_init (&lock->recmutex, &attributes);
+ if (err != 0)
+ {
+ pthread_mutexattr_destroy (&attributes);
+ return err;
+ }
+ err = pthread_mutexattr_destroy (&attributes);
+ if (err != 0)
+ return err;
+ lock->initialized = 1;
+ return 0;
+}
+
+int
+glthread_recursive_lock_lock_multithreaded (gl_recursive_lock_t *lock)
+{
+ if (!lock->initialized)
+ {
+ int err;
+
+ err = pthread_mutex_lock (&lock->guard);
+ if (err != 0)
+ return err;
+ if (!lock->initialized)
+ {
+ err = glthread_recursive_lock_init_multithreaded (lock);
+ if (err != 0)
+ {
+ pthread_mutex_unlock (&lock->guard);
+ return err;
+ }
+ }
+ err = pthread_mutex_unlock (&lock->guard);
+ if (err != 0)
+ return err;
+ }
+ return pthread_mutex_lock (&lock->recmutex);
+}
+
+int
+glthread_recursive_lock_unlock_multithreaded (gl_recursive_lock_t *lock)
+{
+ if (!lock->initialized)
+ return EINVAL;
+ return pthread_mutex_unlock (&lock->recmutex);
+}
+
+int
+glthread_recursive_lock_destroy_multithreaded (gl_recursive_lock_t *lock)
+{
+ int err;
+
+ if (!lock->initialized)
+ return EINVAL;
+ err = pthread_mutex_destroy (&lock->recmutex);
+ if (err != 0)
+ return err;
+ lock->initialized = 0;
+ return 0;
+}
+
+# endif
+
+# else
+
+int
+glthread_recursive_lock_init_multithreaded (gl_recursive_lock_t *lock)
+{
+ int err;
+
+ err = pthread_mutex_init (&lock->mutex, NULL);
+ if (err != 0)
+ return err;
+ lock->owner = (pthread_t) 0;
+ lock->depth = 0;
+ return 0;
+}
+
+int
+glthread_recursive_lock_lock_multithreaded (gl_recursive_lock_t *lock)
+{
+ pthread_t self = pthread_self ();
+ if (lock->owner != self)
+ {
+ int err;
+
+ err = pthread_mutex_lock (&lock->mutex);
+ if (err != 0)
+ return err;
+ lock->owner = self;
+ }
+ if (++(lock->depth) == 0) /* wraparound? */
+ {
+ lock->depth--;
+ return EAGAIN;
+ }
+ return 0;
+}
+
+int
+glthread_recursive_lock_unlock_multithreaded (gl_recursive_lock_t *lock)
+{
+ if (lock->owner != pthread_self ())
+ return EPERM;
+ if (lock->depth == 0)
+ return EINVAL;
+ if (--(lock->depth) == 0)
+ {
+ lock->owner = (pthread_t) 0;
+ return pthread_mutex_unlock (&lock->mutex);
+ }
+ else
+ return 0;
+}
+
+int
+glthread_recursive_lock_destroy_multithreaded (gl_recursive_lock_t *lock)
+{
+ if (lock->owner != (pthread_t) 0)
+ return EBUSY;
+ return pthread_mutex_destroy (&lock->mutex);
+}
+
+# endif
+
+/* -------------------------- gl_once_t datatype -------------------------- */
+
+static const pthread_once_t fresh_once = PTHREAD_ONCE_INIT;
+
+int
+glthread_once_singlethreaded (pthread_once_t *once_control)
+{
+ /* We don't know whether pthread_once_t is an integer type, a floating-point
+ type, a pointer type, or a structure type. */
+ char *firstbyte = (char *)once_control;
+ if (*firstbyte == *(const char *)&fresh_once)
+ {
+ /* First time use of once_control. Invert the first byte. */
+ *firstbyte = ~ *(const char *)&fresh_once;
+ return 1;
+ }
+ else
+ return 0;
+}
+
+#endif
+
+/* ========================================================================= */
+
+#if USE_PTH_THREADS
+
+/* Use the GNU Pth threads library. */
+
+/* -------------------------- gl_lock_t datatype -------------------------- */
+
+/* ------------------------- gl_rwlock_t datatype ------------------------- */
+
+/* --------------------- gl_recursive_lock_t datatype --------------------- */
+
+/* -------------------------- gl_once_t datatype -------------------------- */
+
+static void
+glthread_once_call (void *arg)
+{
+ void (**gl_once_temp_addr) (void) = (void (**) (void)) arg;
+ void (*initfunction) (void) = *gl_once_temp_addr;
+ initfunction ();
+}
+
+int
+glthread_once_multithreaded (pth_once_t *once_control, void (*initfunction) (void))
+{
+ void (*temp) (void) = initfunction;
+ return (!pth_once (once_control, glthread_once_call, &temp) ? errno : 0);
+}
+
+int
+glthread_once_singlethreaded (pth_once_t *once_control)
+{
+ /* We know that pth_once_t is an integer type. */
+ if (*once_control == PTH_ONCE_INIT)
+ {
+ /* First time use of once_control. Invert the marker. */
+ *once_control = ~ PTH_ONCE_INIT;
+ return 1;
+ }
+ else
+ return 0;
+}
+
+#endif
+
+/* ========================================================================= */
+
+#if USE_SOLARIS_THREADS
+
+/* Use the old Solaris threads library. */
+
+/* -------------------------- gl_lock_t datatype -------------------------- */
+
+/* ------------------------- gl_rwlock_t datatype ------------------------- */
+
+/* --------------------- gl_recursive_lock_t datatype --------------------- */
+
+int
+glthread_recursive_lock_init_multithreaded (gl_recursive_lock_t *lock)
+{
+ int err;
+
+ err = mutex_init (&lock->mutex, USYNC_THREAD, NULL);
+ if (err != 0)
+ return err;
+ lock->owner = (thread_t) 0;
+ lock->depth = 0;
+ return 0;
+}
+
+int
+glthread_recursive_lock_lock_multithreaded (gl_recursive_lock_t *lock)
+{
+ thread_t self = thr_self ();
+ if (lock->owner != self)
+ {
+ int err;
+
+ err = mutex_lock (&lock->mutex);
+ if (err != 0)
+ return err;
+ lock->owner = self;
+ }
+ if (++(lock->depth) == 0) /* wraparound? */
+ {
+ lock->depth--;
+ return EAGAIN;
+ }
+ return 0;
+}
+
+int
+glthread_recursive_lock_unlock_multithreaded (gl_recursive_lock_t *lock)
+{
+ if (lock->owner != thr_self ())
+ return EPERM;
+ if (lock->depth == 0)
+ return EINVAL;
+ if (--(lock->depth) == 0)
+ {
+ lock->owner = (thread_t) 0;
+ return mutex_unlock (&lock->mutex);
+ }
+ else
+ return 0;
+}
+
+int
+glthread_recursive_lock_destroy_multithreaded (gl_recursive_lock_t *lock)
+{
+ if (lock->owner != (thread_t) 0)
+ return EBUSY;
+ return mutex_destroy (&lock->mutex);
+}
+
+/* -------------------------- gl_once_t datatype -------------------------- */
+
+int
+glthread_once_multithreaded (gl_once_t *once_control, void (*initfunction) (void))
+{
+ if (!once_control->inited)
+ {
+ int err;
+
+ /* Use the mutex to guarantee that if another thread is already calling
+ the initfunction, this thread waits until it's finished. */
+ err = mutex_lock (&once_control->mutex);
+ if (err != 0)
+ return err;
+ if (!once_control->inited)
+ {
+ once_control->inited = 1;
+ initfunction ();
+ }
+ return mutex_unlock (&once_control->mutex);
+ }
+ else
+ return 0;
+}
+
+int
+glthread_once_singlethreaded (gl_once_t *once_control)
+{
+ /* We know that gl_once_t contains an integer type. */
+ if (!once_control->inited)
+ {
+ /* First time use of once_control. Invert the marker. */
+ once_control->inited = ~ 0;
+ return 1;
+ }
+ else
+ return 0;
+}
+
+#endif
+
+/* ========================================================================= */
+
+#if USE_WINDOWS_THREADS
+
+/* -------------------------- gl_lock_t datatype -------------------------- */
+
+void
+glthread_lock_init_func (gl_lock_t *lock)
+{
+ InitializeCriticalSection (&lock->lock);
+ lock->guard.done = 1;
+}
+
+int
+glthread_lock_lock_func (gl_lock_t *lock)
+{
+ if (!lock->guard.done)
+ {
+ if (InterlockedIncrement (&lock->guard.started) == 0)
+ /* This thread is the first one to need this lock. Initialize it. */
+ glthread_lock_init (lock);
+ else
+ /* Yield the CPU while waiting for another thread to finish
+ initializing this lock. */
+ while (!lock->guard.done)
+ Sleep (0);
+ }
+ EnterCriticalSection (&lock->lock);
+ return 0;
+}
+
+int
+glthread_lock_unlock_func (gl_lock_t *lock)
+{
+ if (!lock->guard.done)
+ return EINVAL;
+ LeaveCriticalSection (&lock->lock);
+ return 0;
+}
+
+int
+glthread_lock_destroy_func (gl_lock_t *lock)
+{
+ if (!lock->guard.done)
+ return EINVAL;
+ DeleteCriticalSection (&lock->lock);
+ lock->guard.done = 0;
+ return 0;
+}
+
+/* ------------------------- gl_rwlock_t datatype ------------------------- */
+
+/* In this file, the waitqueues are implemented as circular arrays. */
+#define gl_waitqueue_t gl_carray_waitqueue_t
+
+static void
+gl_waitqueue_init (gl_waitqueue_t *wq)
+{
+ wq->array = NULL;
+ wq->count = 0;
+ wq->alloc = 0;
+ wq->offset = 0;
+}
+
+/* Enqueues the current thread, represented by an event, in a wait queue.
+ Returns INVALID_HANDLE_VALUE if an allocation failure occurs. */
+static HANDLE
+gl_waitqueue_add (gl_waitqueue_t *wq)
+{
+ HANDLE event;
+ unsigned int index;
+
+ if (wq->count == wq->alloc)
+ {
+ unsigned int new_alloc = 2 * wq->alloc + 1;
+ HANDLE *new_array =
+ (HANDLE *) realloc (wq->array, new_alloc * sizeof (HANDLE));
+ if (new_array == NULL)
+ /* No more memory. */
+ return INVALID_HANDLE_VALUE;
+ /* Now is a good opportunity to rotate the array so that its contents
+ starts at offset 0. */
+ if (wq->offset > 0)
+ {
+ unsigned int old_count = wq->count;
+ unsigned int old_alloc = wq->alloc;
+ unsigned int old_offset = wq->offset;
+ unsigned int i;
+ if (old_offset + old_count > old_alloc)
+ {
+ unsigned int limit = old_offset + old_count - old_alloc;
+ for (i = 0; i < limit; i++)
+ new_array[old_alloc + i] = new_array[i];
+ }
+ for (i = 0; i < old_count; i++)
+ new_array[i] = new_array[old_offset + i];
+ wq->offset = 0;
+ }
+ wq->array = new_array;
+ wq->alloc = new_alloc;
+ }
+ /* Whether the created event is a manual-reset one or an auto-reset one,
+ does not matter, since we will wait on it only once. */
+ event = CreateEvent (NULL, TRUE, FALSE, NULL);
+ if (event == INVALID_HANDLE_VALUE)
+ /* No way to allocate an event. */
+ return INVALID_HANDLE_VALUE;
+ index = wq->offset + wq->count;
+ if (index >= wq->alloc)
+ index -= wq->alloc;
+ wq->array[index] = event;
+ wq->count++;
+ return event;
+}
+
+/* Notifies the first thread from a wait queue and dequeues it. */
+static void
+gl_waitqueue_notify_first (gl_waitqueue_t *wq)
+{
+ SetEvent (wq->array[wq->offset + 0]);
+ wq->offset++;
+ wq->count--;
+ if (wq->count == 0 || wq->offset == wq->alloc)
+ wq->offset = 0;
+}
+
+/* Notifies all threads from a wait queue and dequeues them all. */
+static void
+gl_waitqueue_notify_all (gl_waitqueue_t *wq)
+{
+ unsigned int i;
+
+ for (i = 0; i < wq->count; i++)
+ {
+ unsigned int index = wq->offset + i;
+ if (index >= wq->alloc)
+ index -= wq->alloc;
+ SetEvent (wq->array[index]);
+ }
+ wq->count = 0;
+ wq->offset = 0;
+}
+
+void
+glthread_rwlock_init_func (gl_rwlock_t *lock)
+{
+ InitializeCriticalSection (&lock->lock);
+ gl_waitqueue_init (&lock->waiting_readers);
+ gl_waitqueue_init (&lock->waiting_writers);
+ lock->runcount = 0;
+ lock->guard.done = 1;
+}
+
+int
+glthread_rwlock_rdlock_func (gl_rwlock_t *lock)
+{
+ if (!lock->guard.done)
+ {
+ if (InterlockedIncrement (&lock->guard.started) == 0)
+ /* This thread is the first one to need this lock. Initialize it. */
+ glthread_rwlock_init (lock);
+ else
+ /* Yield the CPU while waiting for another thread to finish
+ initializing this lock. */
+ while (!lock->guard.done)
+ Sleep (0);
+ }
+ EnterCriticalSection (&lock->lock);
+ /* Test whether only readers are currently running, and whether the runcount
+ field will not overflow. */
+ if (!(lock->runcount + 1 > 0))
+ {
+ /* This thread has to wait for a while. Enqueue it among the
+ waiting_readers. */
+ HANDLE event = gl_waitqueue_add (&lock->waiting_readers);
+ if (event != INVALID_HANDLE_VALUE)
+ {
+ DWORD result;
+ LeaveCriticalSection (&lock->lock);
+ /* Wait until another thread signals this event. */
+ result = WaitForSingleObject (event, INFINITE);
+ if (result == WAIT_FAILED || result == WAIT_TIMEOUT)
+ abort ();
+ CloseHandle (event);
+ /* The thread which signalled the event already did the bookkeeping:
+ removed us from the waiting_readers, incremented lock->runcount. */
+ if (!(lock->runcount > 0))
+ abort ();
+ return 0;
+ }
+ else
+ {
+ /* Allocation failure. Weird. */
+ do
+ {
+ LeaveCriticalSection (&lock->lock);
+ Sleep (1);
+ EnterCriticalSection (&lock->lock);
+ }
+ while (!(lock->runcount + 1 > 0));
+ }
+ }
+ lock->runcount++;
+ LeaveCriticalSection (&lock->lock);
+ return 0;
+}
+
+int
+glthread_rwlock_wrlock_func (gl_rwlock_t *lock)
+{
+ if (!lock->guard.done)
+ {
+ if (InterlockedIncrement (&lock->guard.started) == 0)
+ /* This thread is the first one to need this lock. Initialize it. */
+ glthread_rwlock_init (lock);
+ else
+ /* Yield the CPU while waiting for another thread to finish
+ initializing this lock. */
+ while (!lock->guard.done)
+ Sleep (0);
+ }
+ EnterCriticalSection (&lock->lock);
+ /* Test whether no readers or writers are currently running. */
+ if (!(lock->runcount == 0))
+ {
+ /* This thread has to wait for a while. Enqueue it among the
+ waiting_writers. */
+ HANDLE event = gl_waitqueue_add (&lock->waiting_writers);
+ if (event != INVALID_HANDLE_VALUE)
+ {
+ DWORD result;
+ LeaveCriticalSection (&lock->lock);
+ /* Wait until another thread signals this event. */
+ result = WaitForSingleObject (event, INFINITE);
+ if (result == WAIT_FAILED || result == WAIT_TIMEOUT)
+ abort ();
+ CloseHandle (event);
+ /* The thread which signalled the event already did the bookkeeping:
+ removed us from the waiting_writers, set lock->runcount = -1. */
+ if (!(lock->runcount == -1))
+ abort ();
+ return 0;
+ }
+ else
+ {
+ /* Allocation failure. Weird. */
+ do
+ {
+ LeaveCriticalSection (&lock->lock);
+ Sleep (1);
+ EnterCriticalSection (&lock->lock);
+ }
+ while (!(lock->runcount == 0));
+ }
+ }
+ lock->runcount--; /* runcount becomes -1 */
+ LeaveCriticalSection (&lock->lock);
+ return 0;
+}
+
+int
+glthread_rwlock_unlock_func (gl_rwlock_t *lock)
+{
+ if (!lock->guard.done)
+ return EINVAL;
+ EnterCriticalSection (&lock->lock);
+ if (lock->runcount < 0)
+ {
+ /* Drop a writer lock. */
+ if (!(lock->runcount == -1))
+ abort ();
+ lock->runcount = 0;
+ }
+ else
+ {
+ /* Drop a reader lock. */
+ if (!(lock->runcount > 0))
+ {
+ LeaveCriticalSection (&lock->lock);
+ return EPERM;
+ }
+ lock->runcount--;
+ }
+ if (lock->runcount == 0)
+ {
+ /* POSIX recommends that "write locks shall take precedence over read
+ locks", to avoid "writer starvation". */
+ if (lock->waiting_writers.count > 0)
+ {
+ /* Wake up one of the waiting writers. */
+ lock->runcount--;
+ gl_waitqueue_notify_first (&lock->waiting_writers);
+ }
+ else
+ {
+ /* Wake up all waiting readers. */
+ lock->runcount += lock->waiting_readers.count;
+ gl_waitqueue_notify_all (&lock->waiting_readers);
+ }
+ }
+ LeaveCriticalSection (&lock->lock);
+ return 0;
+}
+
+int
+glthread_rwlock_destroy_func (gl_rwlock_t *lock)
+{
+ if (!lock->guard.done)
+ return EINVAL;
+ if (lock->runcount != 0)
+ return EBUSY;
+ DeleteCriticalSection (&lock->lock);
+ if (lock->waiting_readers.array != NULL)
+ free (lock->waiting_readers.array);
+ if (lock->waiting_writers.array != NULL)
+ free (lock->waiting_writers.array);
+ lock->guard.done = 0;
+ return 0;
+}
+
+/* --------------------- gl_recursive_lock_t datatype --------------------- */
+
+void
+glthread_recursive_lock_init_func (gl_recursive_lock_t *lock)
+{
+ lock->owner = 0;
+ lock->depth = 0;
+ InitializeCriticalSection (&lock->lock);
+ lock->guard.done = 1;
+}
+
+int
+glthread_recursive_lock_lock_func (gl_recursive_lock_t *lock)
+{
+ if (!lock->guard.done)
+ {
+ if (InterlockedIncrement (&lock->guard.started) == 0)
+ /* This thread is the first one to need this lock. Initialize it. */
+ glthread_recursive_lock_init (lock);
+ else
+ /* Yield the CPU while waiting for another thread to finish
+ initializing this lock. */
+ while (!lock->guard.done)
+ Sleep (0);
+ }
+ {
+ DWORD self = GetCurrentThreadId ();
+ if (lock->owner != self)
+ {
+ EnterCriticalSection (&lock->lock);
+ lock->owner = self;
+ }
+ if (++(lock->depth) == 0) /* wraparound? */
+ {
+ lock->depth--;
+ return EAGAIN;
+ }
+ }
+ return 0;
+}
+
+int
+glthread_recursive_lock_unlock_func (gl_recursive_lock_t *lock)
+{
+ if (lock->owner != GetCurrentThreadId ())
+ return EPERM;
+ if (lock->depth == 0)
+ return EINVAL;
+ if (--(lock->depth) == 0)
+ {
+ lock->owner = 0;
+ LeaveCriticalSection (&lock->lock);
+ }
+ return 0;
+}
+
+int
+glthread_recursive_lock_destroy_func (gl_recursive_lock_t *lock)
+{
+ if (lock->owner != 0)
+ return EBUSY;
+ DeleteCriticalSection (&lock->lock);
+ lock->guard.done = 0;
+ return 0;
+}
+
+/* -------------------------- gl_once_t datatype -------------------------- */
+
+void
+glthread_once_func (gl_once_t *once_control, void (*initfunction) (void))
+{
+ if (once_control->inited <= 0)
+ {
+ if (InterlockedIncrement (&once_control->started) == 0)
+ {
+ /* This thread is the first one to come to this once_control. */
+ InitializeCriticalSection (&once_control->lock);
+ EnterCriticalSection (&once_control->lock);
+ once_control->inited = 0;
+ initfunction ();
+ once_control->inited = 1;
+ LeaveCriticalSection (&once_control->lock);
+ }
+ else
+ {
+ /* Undo last operation. */
+ InterlockedDecrement (&once_control->started);
+ /* Some other thread has already started the initialization.
+ Yield the CPU while waiting for the other thread to finish
+ initializing and taking the lock. */
+ while (once_control->inited < 0)
+ Sleep (0);
+ if (once_control->inited <= 0)
+ {
+ /* Take the lock. This blocks until the other thread has
+ finished calling the initfunction. */
+ EnterCriticalSection (&once_control->lock);
+ LeaveCriticalSection (&once_control->lock);
+ if (!(once_control->inited > 0))
+ abort ();
+ }
+ }
+ }
+}
+
+#endif
+
+/* ========================================================================= */
diff --git a/lib/glthread/lock.h b/lib/glthread/lock.h
new file mode 100644
index 0000000..e64506b
--- /dev/null
+++ b/lib/glthread/lock.h
@@ -0,0 +1,927 @@
+/* Locking in multithreaded situations.
+ Copyright (C) 2005-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Bruno Haible <bruno@clisp.org>, 2005.
+ Based on GCC's gthr-posix.h, gthr-posix95.h, gthr-solaris.h,
+ gthr-win32.h. */
+
+/* This file contains locking primitives for use with a given thread library.
+ It does not contain primitives for creating threads or for other
+ synchronization primitives.
+
+ Normal (non-recursive) locks:
+ Type: gl_lock_t
+ Declaration: gl_lock_define(extern, name)
+ Initializer: gl_lock_define_initialized(, name)
+ Initialization: gl_lock_init (name);
+ Taking the lock: gl_lock_lock (name);
+ Releasing the lock: gl_lock_unlock (name);
+ De-initialization: gl_lock_destroy (name);
+ Equivalent functions with control of error handling:
+ Initialization: err = glthread_lock_init (&name);
+ Taking the lock: err = glthread_lock_lock (&name);
+ Releasing the lock: err = glthread_lock_unlock (&name);
+ De-initialization: err = glthread_lock_destroy (&name);
+
+ Read-Write (non-recursive) locks:
+ Type: gl_rwlock_t
+ Declaration: gl_rwlock_define(extern, name)
+ Initializer: gl_rwlock_define_initialized(, name)
+ Initialization: gl_rwlock_init (name);
+ Taking the lock: gl_rwlock_rdlock (name);
+ gl_rwlock_wrlock (name);
+ Releasing the lock: gl_rwlock_unlock (name);
+ De-initialization: gl_rwlock_destroy (name);
+ Equivalent functions with control of error handling:
+ Initialization: err = glthread_rwlock_init (&name);
+ Taking the lock: err = glthread_rwlock_rdlock (&name);
+ err = glthread_rwlock_wrlock (&name);
+ Releasing the lock: err = glthread_rwlock_unlock (&name);
+ De-initialization: err = glthread_rwlock_destroy (&name);
+
+ Recursive locks:
+ Type: gl_recursive_lock_t
+ Declaration: gl_recursive_lock_define(extern, name)
+ Initializer: gl_recursive_lock_define_initialized(, name)
+ Initialization: gl_recursive_lock_init (name);
+ Taking the lock: gl_recursive_lock_lock (name);
+ Releasing the lock: gl_recursive_lock_unlock (name);
+ De-initialization: gl_recursive_lock_destroy (name);
+ Equivalent functions with control of error handling:
+ Initialization: err = glthread_recursive_lock_init (&name);
+ Taking the lock: err = glthread_recursive_lock_lock (&name);
+ Releasing the lock: err = glthread_recursive_lock_unlock (&name);
+ De-initialization: err = glthread_recursive_lock_destroy (&name);
+
+ Once-only execution:
+ Type: gl_once_t
+ Initializer: gl_once_define(extern, name)
+ Execution: gl_once (name, initfunction);
+ Equivalent functions with control of error handling:
+ Execution: err = glthread_once (&name, initfunction);
+*/
+
+
+#ifndef _LOCK_H
+#define _LOCK_H
+
+#include <errno.h>
+#include <stdlib.h>
+
+/* ========================================================================= */
+
+#if USE_POSIX_THREADS
+
+/* Use the POSIX threads library. */
+
+# include <pthread.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# if PTHREAD_IN_USE_DETECTION_HARD
+
+/* The pthread_in_use() detection needs to be done at runtime. */
+# define pthread_in_use() \
+ glthread_in_use ()
+extern int glthread_in_use (void);
+
+# endif
+
+# if USE_POSIX_THREADS_WEAK
+
+/* Use weak references to the POSIX threads library. */
+
+/* Weak references avoid dragging in external libraries if the other parts
+ of the program don't use them. Here we use them, because we don't want
+ every program that uses libintl to depend on libpthread. This assumes
+ that libpthread would not be loaded after libintl; i.e. if libintl is
+ loaded first, by an executable that does not depend on libpthread, and
+ then a module is dynamically loaded that depends on libpthread, libintl
+ will not be multithread-safe. */
+
+/* The way to test at runtime whether libpthread is present is to test
+ whether a function pointer's value, such as &pthread_mutex_init, is
+ non-NULL. However, some versions of GCC have a bug through which, in
+ PIC mode, &foo != NULL always evaluates to true if there is a direct
+ call to foo(...) in the same function. To avoid this, we test the
+ address of a function in libpthread that we don't use. */
+
+# pragma weak pthread_mutex_init
+# pragma weak pthread_mutex_lock
+# pragma weak pthread_mutex_unlock
+# pragma weak pthread_mutex_destroy
+# pragma weak pthread_rwlock_init
+# pragma weak pthread_rwlock_rdlock
+# pragma weak pthread_rwlock_wrlock
+# pragma weak pthread_rwlock_unlock
+# pragma weak pthread_rwlock_destroy
+# pragma weak pthread_once
+# pragma weak pthread_cond_init
+# pragma weak pthread_cond_wait
+# pragma weak pthread_cond_signal
+# pragma weak pthread_cond_broadcast
+# pragma weak pthread_cond_destroy
+# pragma weak pthread_mutexattr_init
+# pragma weak pthread_mutexattr_settype
+# pragma weak pthread_mutexattr_destroy
+# ifndef pthread_self
+# pragma weak pthread_self
+# endif
+
+# if !PTHREAD_IN_USE_DETECTION_HARD
+# pragma weak pthread_cancel
+# define pthread_in_use() (pthread_cancel != NULL)
+# endif
+
+# else
+
+# if !PTHREAD_IN_USE_DETECTION_HARD
+# define pthread_in_use() 1
+# endif
+
+# endif
+
+/* -------------------------- gl_lock_t datatype -------------------------- */
+
+typedef pthread_mutex_t gl_lock_t;
+# define gl_lock_define(STORAGECLASS, NAME) \
+ STORAGECLASS pthread_mutex_t NAME;
+# define gl_lock_define_initialized(STORAGECLASS, NAME) \
+ STORAGECLASS pthread_mutex_t NAME = gl_lock_initializer;
+# define gl_lock_initializer \
+ PTHREAD_MUTEX_INITIALIZER
+# define glthread_lock_init(LOCK) \
+ (pthread_in_use () ? pthread_mutex_init (LOCK, NULL) : 0)
+# define glthread_lock_lock(LOCK) \
+ (pthread_in_use () ? pthread_mutex_lock (LOCK) : 0)
+# define glthread_lock_unlock(LOCK) \
+ (pthread_in_use () ? pthread_mutex_unlock (LOCK) : 0)
+# define glthread_lock_destroy(LOCK) \
+ (pthread_in_use () ? pthread_mutex_destroy (LOCK) : 0)
+
+/* ------------------------- gl_rwlock_t datatype ------------------------- */
+
+# if HAVE_PTHREAD_RWLOCK
+
+# ifdef PTHREAD_RWLOCK_INITIALIZER
+
+typedef pthread_rwlock_t gl_rwlock_t;
+# define gl_rwlock_define(STORAGECLASS, NAME) \
+ STORAGECLASS pthread_rwlock_t NAME;
+# define gl_rwlock_define_initialized(STORAGECLASS, NAME) \
+ STORAGECLASS pthread_rwlock_t NAME = gl_rwlock_initializer;
+# define gl_rwlock_initializer \
+ PTHREAD_RWLOCK_INITIALIZER
+# define glthread_rwlock_init(LOCK) \
+ (pthread_in_use () ? pthread_rwlock_init (LOCK, NULL) : 0)
+# define glthread_rwlock_rdlock(LOCK) \
+ (pthread_in_use () ? pthread_rwlock_rdlock (LOCK) : 0)
+# define glthread_rwlock_wrlock(LOCK) \
+ (pthread_in_use () ? pthread_rwlock_wrlock (LOCK) : 0)
+# define glthread_rwlock_unlock(LOCK) \
+ (pthread_in_use () ? pthread_rwlock_unlock (LOCK) : 0)
+# define glthread_rwlock_destroy(LOCK) \
+ (pthread_in_use () ? pthread_rwlock_destroy (LOCK) : 0)
+
+# else
+
+typedef struct
+ {
+ int initialized;
+ pthread_mutex_t guard; /* protects the initialization */
+ pthread_rwlock_t rwlock; /* read-write lock */
+ }
+ gl_rwlock_t;
+# define gl_rwlock_define(STORAGECLASS, NAME) \
+ STORAGECLASS gl_rwlock_t NAME;
+# define gl_rwlock_define_initialized(STORAGECLASS, NAME) \
+ STORAGECLASS gl_rwlock_t NAME = gl_rwlock_initializer;
+# define gl_rwlock_initializer \
+ { 0, PTHREAD_MUTEX_INITIALIZER }
+# define glthread_rwlock_init(LOCK) \
+ (pthread_in_use () ? glthread_rwlock_init_multithreaded (LOCK) : 0)
+# define glthread_rwlock_rdlock(LOCK) \
+ (pthread_in_use () ? glthread_rwlock_rdlock_multithreaded (LOCK) : 0)
+# define glthread_rwlock_wrlock(LOCK) \
+ (pthread_in_use () ? glthread_rwlock_wrlock_multithreaded (LOCK) : 0)
+# define glthread_rwlock_unlock(LOCK) \
+ (pthread_in_use () ? glthread_rwlock_unlock_multithreaded (LOCK) : 0)
+# define glthread_rwlock_destroy(LOCK) \
+ (pthread_in_use () ? glthread_rwlock_destroy_multithreaded (LOCK) : 0)
+extern int glthread_rwlock_init_multithreaded (gl_rwlock_t *lock);
+extern int glthread_rwlock_rdlock_multithreaded (gl_rwlock_t *lock);
+extern int glthread_rwlock_wrlock_multithreaded (gl_rwlock_t *lock);
+extern int glthread_rwlock_unlock_multithreaded (gl_rwlock_t *lock);
+extern int glthread_rwlock_destroy_multithreaded (gl_rwlock_t *lock);
+
+# endif
+
+# else
+
+typedef struct
+ {
+ pthread_mutex_t lock; /* protects the remaining fields */
+ pthread_cond_t waiting_readers; /* waiting readers */
+ pthread_cond_t waiting_writers; /* waiting writers */
+ unsigned int waiting_writers_count; /* number of waiting writers */
+ int runcount; /* number of readers running, or -1 when a writer runs */
+ }
+ gl_rwlock_t;
+# define gl_rwlock_define(STORAGECLASS, NAME) \
+ STORAGECLASS gl_rwlock_t NAME;
+# define gl_rwlock_define_initialized(STORAGECLASS, NAME) \
+ STORAGECLASS gl_rwlock_t NAME = gl_rwlock_initializer;
+# define gl_rwlock_initializer \
+ { PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, PTHREAD_COND_INITIALIZER, 0, 0 }
+# define glthread_rwlock_init(LOCK) \
+ (pthread_in_use () ? glthread_rwlock_init_multithreaded (LOCK) : 0)
+# define glthread_rwlock_rdlock(LOCK) \
+ (pthread_in_use () ? glthread_rwlock_rdlock_multithreaded (LOCK) : 0)
+# define glthread_rwlock_wrlock(LOCK) \
+ (pthread_in_use () ? glthread_rwlock_wrlock_multithreaded (LOCK) : 0)
+# define glthread_rwlock_unlock(LOCK) \
+ (pthread_in_use () ? glthread_rwlock_unlock_multithreaded (LOCK) : 0)
+# define glthread_rwlock_destroy(LOCK) \
+ (pthread_in_use () ? glthread_rwlock_destroy_multithreaded (LOCK) : 0)
+extern int glthread_rwlock_init_multithreaded (gl_rwlock_t *lock);
+extern int glthread_rwlock_rdlock_multithreaded (gl_rwlock_t *lock);
+extern int glthread_rwlock_wrlock_multithreaded (gl_rwlock_t *lock);
+extern int glthread_rwlock_unlock_multithreaded (gl_rwlock_t *lock);
+extern int glthread_rwlock_destroy_multithreaded (gl_rwlock_t *lock);
+
+# endif
+
+/* --------------------- gl_recursive_lock_t datatype --------------------- */
+
+# if HAVE_PTHREAD_MUTEX_RECURSIVE
+
+# if defined PTHREAD_RECURSIVE_MUTEX_INITIALIZER || defined PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
+
+typedef pthread_mutex_t gl_recursive_lock_t;
+# define gl_recursive_lock_define(STORAGECLASS, NAME) \
+ STORAGECLASS pthread_mutex_t NAME;
+# define gl_recursive_lock_define_initialized(STORAGECLASS, NAME) \
+ STORAGECLASS pthread_mutex_t NAME = gl_recursive_lock_initializer;
+# ifdef PTHREAD_RECURSIVE_MUTEX_INITIALIZER
+# define gl_recursive_lock_initializer \
+ PTHREAD_RECURSIVE_MUTEX_INITIALIZER
+# else
+# define gl_recursive_lock_initializer \
+ PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
+# endif
+# define glthread_recursive_lock_init(LOCK) \
+ (pthread_in_use () ? glthread_recursive_lock_init_multithreaded (LOCK) : 0)
+# define glthread_recursive_lock_lock(LOCK) \
+ (pthread_in_use () ? pthread_mutex_lock (LOCK) : 0)
+# define glthread_recursive_lock_unlock(LOCK) \
+ (pthread_in_use () ? pthread_mutex_unlock (LOCK) : 0)
+# define glthread_recursive_lock_destroy(LOCK) \
+ (pthread_in_use () ? pthread_mutex_destroy (LOCK) : 0)
+extern int glthread_recursive_lock_init_multithreaded (gl_recursive_lock_t *lock);
+
+# else
+
+typedef struct
+ {
+ pthread_mutex_t recmutex; /* recursive mutex */
+ pthread_mutex_t guard; /* protects the initialization */
+ int initialized;
+ }
+ gl_recursive_lock_t;
+# define gl_recursive_lock_define(STORAGECLASS, NAME) \
+ STORAGECLASS gl_recursive_lock_t NAME;
+# define gl_recursive_lock_define_initialized(STORAGECLASS, NAME) \
+ STORAGECLASS gl_recursive_lock_t NAME = gl_recursive_lock_initializer;
+# define gl_recursive_lock_initializer \
+ { PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER, 0 }
+# define glthread_recursive_lock_init(LOCK) \
+ (pthread_in_use () ? glthread_recursive_lock_init_multithreaded (LOCK) : 0)
+# define glthread_recursive_lock_lock(LOCK) \
+ (pthread_in_use () ? glthread_recursive_lock_lock_multithreaded (LOCK) : 0)
+# define glthread_recursive_lock_unlock(LOCK) \
+ (pthread_in_use () ? glthread_recursive_lock_unlock_multithreaded (LOCK) : 0)
+# define glthread_recursive_lock_destroy(LOCK) \
+ (pthread_in_use () ? glthread_recursive_lock_destroy_multithreaded (LOCK) : 0)
+extern int glthread_recursive_lock_init_multithreaded (gl_recursive_lock_t *lock);
+extern int glthread_recursive_lock_lock_multithreaded (gl_recursive_lock_t *lock);
+extern int glthread_recursive_lock_unlock_multithreaded (gl_recursive_lock_t *lock);
+extern int glthread_recursive_lock_destroy_multithreaded (gl_recursive_lock_t *lock);
+
+# endif
+
+# else
+
+/* Old versions of POSIX threads on Solaris did not have recursive locks.
+ We have to implement them ourselves. */
+
+typedef struct
+ {
+ pthread_mutex_t mutex;
+ pthread_t owner;
+ unsigned long depth;
+ }
+ gl_recursive_lock_t;
+# define gl_recursive_lock_define(STORAGECLASS, NAME) \
+ STORAGECLASS gl_recursive_lock_t NAME;
+# define gl_recursive_lock_define_initialized(STORAGECLASS, NAME) \
+ STORAGECLASS gl_recursive_lock_t NAME = gl_recursive_lock_initializer;
+# define gl_recursive_lock_initializer \
+ { PTHREAD_MUTEX_INITIALIZER, (pthread_t) 0, 0 }
+# define glthread_recursive_lock_init(LOCK) \
+ (pthread_in_use () ? glthread_recursive_lock_init_multithreaded (LOCK) : 0)
+# define glthread_recursive_lock_lock(LOCK) \
+ (pthread_in_use () ? glthread_recursive_lock_lock_multithreaded (LOCK) : 0)
+# define glthread_recursive_lock_unlock(LOCK) \
+ (pthread_in_use () ? glthread_recursive_lock_unlock_multithreaded (LOCK) : 0)
+# define glthread_recursive_lock_destroy(LOCK) \
+ (pthread_in_use () ? glthread_recursive_lock_destroy_multithreaded (LOCK) : 0)
+extern int glthread_recursive_lock_init_multithreaded (gl_recursive_lock_t *lock);
+extern int glthread_recursive_lock_lock_multithreaded (gl_recursive_lock_t *lock);
+extern int glthread_recursive_lock_unlock_multithreaded (gl_recursive_lock_t *lock);
+extern int glthread_recursive_lock_destroy_multithreaded (gl_recursive_lock_t *lock);
+
+# endif
+
+/* -------------------------- gl_once_t datatype -------------------------- */
+
+typedef pthread_once_t gl_once_t;
+# define gl_once_define(STORAGECLASS, NAME) \
+ STORAGECLASS pthread_once_t NAME = PTHREAD_ONCE_INIT;
+# define glthread_once(ONCE_CONTROL, INITFUNCTION) \
+ (pthread_in_use () \
+ ? pthread_once (ONCE_CONTROL, INITFUNCTION) \
+ : (glthread_once_singlethreaded (ONCE_CONTROL) ? (INITFUNCTION (), 0) : 0))
+extern int glthread_once_singlethreaded (pthread_once_t *once_control);
+
+# ifdef __cplusplus
+}
+# endif
+
+#endif
+
+/* ========================================================================= */
+
+#if USE_PTH_THREADS
+
+/* Use the GNU Pth threads library. */
+
+# include <pth.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# if USE_PTH_THREADS_WEAK
+
+/* Use weak references to the GNU Pth threads library. */
+
+# pragma weak pth_mutex_init
+# pragma weak pth_mutex_acquire
+# pragma weak pth_mutex_release
+# pragma weak pth_rwlock_init
+# pragma weak pth_rwlock_acquire
+# pragma weak pth_rwlock_release
+# pragma weak pth_once
+
+# pragma weak pth_cancel
+# define pth_in_use() (pth_cancel != NULL)
+
+# else
+
+# define pth_in_use() 1
+
+# endif
+
+/* -------------------------- gl_lock_t datatype -------------------------- */
+
+typedef pth_mutex_t gl_lock_t;
+# define gl_lock_define(STORAGECLASS, NAME) \
+ STORAGECLASS pth_mutex_t NAME;
+# define gl_lock_define_initialized(STORAGECLASS, NAME) \
+ STORAGECLASS pth_mutex_t NAME = gl_lock_initializer;
+# define gl_lock_initializer \
+ PTH_MUTEX_INIT
+# define glthread_lock_init(LOCK) \
+ (pth_in_use () && !pth_mutex_init (LOCK) ? errno : 0)
+# define glthread_lock_lock(LOCK) \
+ (pth_in_use () && !pth_mutex_acquire (LOCK, 0, NULL) ? errno : 0)
+# define glthread_lock_unlock(LOCK) \
+ (pth_in_use () && !pth_mutex_release (LOCK) ? errno : 0)
+# define glthread_lock_destroy(LOCK) \
+ ((void)(LOCK), 0)
+
+/* ------------------------- gl_rwlock_t datatype ------------------------- */
+
+typedef pth_rwlock_t gl_rwlock_t;
+# define gl_rwlock_define(STORAGECLASS, NAME) \
+ STORAGECLASS pth_rwlock_t NAME;
+# define gl_rwlock_define_initialized(STORAGECLASS, NAME) \
+ STORAGECLASS pth_rwlock_t NAME = gl_rwlock_initializer;
+# define gl_rwlock_initializer \
+ PTH_RWLOCK_INIT
+# define glthread_rwlock_init(LOCK) \
+ (pth_in_use () && !pth_rwlock_init (LOCK) ? errno : 0)
+# define glthread_rwlock_rdlock(LOCK) \
+ (pth_in_use () && !pth_rwlock_acquire (LOCK, PTH_RWLOCK_RD, 0, NULL) ? errno : 0)
+# define glthread_rwlock_wrlock(LOCK) \
+ (pth_in_use () && !pth_rwlock_acquire (LOCK, PTH_RWLOCK_RW, 0, NULL) ? errno : 0)
+# define glthread_rwlock_unlock(LOCK) \
+ (pth_in_use () && !pth_rwlock_release (LOCK) ? errno : 0)
+# define glthread_rwlock_destroy(LOCK) \
+ ((void)(LOCK), 0)
+
+/* --------------------- gl_recursive_lock_t datatype --------------------- */
+
+/* In Pth, mutexes are recursive by default. */
+typedef pth_mutex_t gl_recursive_lock_t;
+# define gl_recursive_lock_define(STORAGECLASS, NAME) \
+ STORAGECLASS pth_mutex_t NAME;
+# define gl_recursive_lock_define_initialized(STORAGECLASS, NAME) \
+ STORAGECLASS pth_mutex_t NAME = gl_recursive_lock_initializer;
+# define gl_recursive_lock_initializer \
+ PTH_MUTEX_INIT
+# define glthread_recursive_lock_init(LOCK) \
+ (pth_in_use () && !pth_mutex_init (LOCK) ? errno : 0)
+# define glthread_recursive_lock_lock(LOCK) \
+ (pth_in_use () && !pth_mutex_acquire (LOCK, 0, NULL) ? errno : 0)
+# define glthread_recursive_lock_unlock(LOCK) \
+ (pth_in_use () && !pth_mutex_release (LOCK) ? errno : 0)
+# define glthread_recursive_lock_destroy(LOCK) \
+ ((void)(LOCK), 0)
+
+/* -------------------------- gl_once_t datatype -------------------------- */
+
+typedef pth_once_t gl_once_t;
+# define gl_once_define(STORAGECLASS, NAME) \
+ STORAGECLASS pth_once_t NAME = PTH_ONCE_INIT;
+# define glthread_once(ONCE_CONTROL, INITFUNCTION) \
+ (pth_in_use () \
+ ? glthread_once_multithreaded (ONCE_CONTROL, INITFUNCTION) \
+ : (glthread_once_singlethreaded (ONCE_CONTROL) ? (INITFUNCTION (), 0) : 0))
+extern int glthread_once_multithreaded (pth_once_t *once_control, void (*initfunction) (void));
+extern int glthread_once_singlethreaded (pth_once_t *once_control);
+
+# ifdef __cplusplus
+}
+# endif
+
+#endif
+
+/* ========================================================================= */
+
+#if USE_SOLARIS_THREADS
+
+/* Use the old Solaris threads library. */
+
+# include <thread.h>
+# include <synch.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# if USE_SOLARIS_THREADS_WEAK
+
+/* Use weak references to the old Solaris threads library. */
+
+# pragma weak mutex_init
+# pragma weak mutex_lock
+# pragma weak mutex_unlock
+# pragma weak mutex_destroy
+# pragma weak rwlock_init
+# pragma weak rw_rdlock
+# pragma weak rw_wrlock
+# pragma weak rw_unlock
+# pragma weak rwlock_destroy
+# pragma weak thr_self
+
+# pragma weak thr_suspend
+# define thread_in_use() (thr_suspend != NULL)
+
+# else
+
+# define thread_in_use() 1
+
+# endif
+
+/* -------------------------- gl_lock_t datatype -------------------------- */
+
+typedef mutex_t gl_lock_t;
+# define gl_lock_define(STORAGECLASS, NAME) \
+ STORAGECLASS mutex_t NAME;
+# define gl_lock_define_initialized(STORAGECLASS, NAME) \
+ STORAGECLASS mutex_t NAME = gl_lock_initializer;
+# define gl_lock_initializer \
+ DEFAULTMUTEX
+# define glthread_lock_init(LOCK) \
+ (thread_in_use () ? mutex_init (LOCK, USYNC_THREAD, NULL) : 0)
+# define glthread_lock_lock(LOCK) \
+ (thread_in_use () ? mutex_lock (LOCK) : 0)
+# define glthread_lock_unlock(LOCK) \
+ (thread_in_use () ? mutex_unlock (LOCK) : 0)
+# define glthread_lock_destroy(LOCK) \
+ (thread_in_use () ? mutex_destroy (LOCK) : 0)
+
+/* ------------------------- gl_rwlock_t datatype ------------------------- */
+
+typedef rwlock_t gl_rwlock_t;
+# define gl_rwlock_define(STORAGECLASS, NAME) \
+ STORAGECLASS rwlock_t NAME;
+# define gl_rwlock_define_initialized(STORAGECLASS, NAME) \
+ STORAGECLASS rwlock_t NAME = gl_rwlock_initializer;
+# define gl_rwlock_initializer \
+ DEFAULTRWLOCK
+# define glthread_rwlock_init(LOCK) \
+ (thread_in_use () ? rwlock_init (LOCK, USYNC_THREAD, NULL) : 0)
+# define glthread_rwlock_rdlock(LOCK) \
+ (thread_in_use () ? rw_rdlock (LOCK) : 0)
+# define glthread_rwlock_wrlock(LOCK) \
+ (thread_in_use () ? rw_wrlock (LOCK) : 0)
+# define glthread_rwlock_unlock(LOCK) \
+ (thread_in_use () ? rw_unlock (LOCK) : 0)
+# define glthread_rwlock_destroy(LOCK) \
+ (thread_in_use () ? rwlock_destroy (LOCK) : 0)
+
+/* --------------------- gl_recursive_lock_t datatype --------------------- */
+
+/* Old Solaris threads did not have recursive locks.
+ We have to implement them ourselves. */
+
+typedef struct
+ {
+ mutex_t mutex;
+ thread_t owner;
+ unsigned long depth;
+ }
+ gl_recursive_lock_t;
+# define gl_recursive_lock_define(STORAGECLASS, NAME) \
+ STORAGECLASS gl_recursive_lock_t NAME;
+# define gl_recursive_lock_define_initialized(STORAGECLASS, NAME) \
+ STORAGECLASS gl_recursive_lock_t NAME = gl_recursive_lock_initializer;
+# define gl_recursive_lock_initializer \
+ { DEFAULTMUTEX, (thread_t) 0, 0 }
+# define glthread_recursive_lock_init(LOCK) \
+ (thread_in_use () ? glthread_recursive_lock_init_multithreaded (LOCK) : 0)
+# define glthread_recursive_lock_lock(LOCK) \
+ (thread_in_use () ? glthread_recursive_lock_lock_multithreaded (LOCK) : 0)
+# define glthread_recursive_lock_unlock(LOCK) \
+ (thread_in_use () ? glthread_recursive_lock_unlock_multithreaded (LOCK) : 0)
+# define glthread_recursive_lock_destroy(LOCK) \
+ (thread_in_use () ? glthread_recursive_lock_destroy_multithreaded (LOCK) : 0)
+extern int glthread_recursive_lock_init_multithreaded (gl_recursive_lock_t *lock);
+extern int glthread_recursive_lock_lock_multithreaded (gl_recursive_lock_t *lock);
+extern int glthread_recursive_lock_unlock_multithreaded (gl_recursive_lock_t *lock);
+extern int glthread_recursive_lock_destroy_multithreaded (gl_recursive_lock_t *lock);
+
+/* -------------------------- gl_once_t datatype -------------------------- */
+
+typedef struct
+ {
+ volatile int inited;
+ mutex_t mutex;
+ }
+ gl_once_t;
+# define gl_once_define(STORAGECLASS, NAME) \
+ STORAGECLASS gl_once_t NAME = { 0, DEFAULTMUTEX };
+# define glthread_once(ONCE_CONTROL, INITFUNCTION) \
+ (thread_in_use () \
+ ? glthread_once_multithreaded (ONCE_CONTROL, INITFUNCTION) \
+ : (glthread_once_singlethreaded (ONCE_CONTROL) ? (INITFUNCTION (), 0) : 0))
+extern int glthread_once_multithreaded (gl_once_t *once_control, void (*initfunction) (void));
+extern int glthread_once_singlethreaded (gl_once_t *once_control);
+
+# ifdef __cplusplus
+}
+# endif
+
+#endif
+
+/* ========================================================================= */
+
+#if USE_WINDOWS_THREADS
+
+# define WIN32_LEAN_AND_MEAN /* avoid including junk */
+# include <windows.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+/* We can use CRITICAL_SECTION directly, rather than the native Windows Event,
+ Mutex, Semaphore types, because
+ - we need only to synchronize inside a single process (address space),
+ not inter-process locking,
+ - we don't need to support trylock operations. (TryEnterCriticalSection
+ does not work on Windows 95/98/ME. Packages that need trylock usually
+ define their own mutex type.) */
+
+/* There is no way to statically initialize a CRITICAL_SECTION. It needs
+ to be done lazily, once only. For this we need spinlocks. */
+
+typedef struct { volatile int done; volatile long started; } gl_spinlock_t;
+
+/* -------------------------- gl_lock_t datatype -------------------------- */
+
+typedef struct
+ {
+ gl_spinlock_t guard; /* protects the initialization */
+ CRITICAL_SECTION lock;
+ }
+ gl_lock_t;
+# define gl_lock_define(STORAGECLASS, NAME) \
+ STORAGECLASS gl_lock_t NAME;
+# define gl_lock_define_initialized(STORAGECLASS, NAME) \
+ STORAGECLASS gl_lock_t NAME = gl_lock_initializer;
+# define gl_lock_initializer \
+ { { 0, -1 } }
+# define glthread_lock_init(LOCK) \
+ (glthread_lock_init_func (LOCK), 0)
+# define glthread_lock_lock(LOCK) \
+ glthread_lock_lock_func (LOCK)
+# define glthread_lock_unlock(LOCK) \
+ glthread_lock_unlock_func (LOCK)
+# define glthread_lock_destroy(LOCK) \
+ glthread_lock_destroy_func (LOCK)
+extern void glthread_lock_init_func (gl_lock_t *lock);
+extern int glthread_lock_lock_func (gl_lock_t *lock);
+extern int glthread_lock_unlock_func (gl_lock_t *lock);
+extern int glthread_lock_destroy_func (gl_lock_t *lock);
+
+/* ------------------------- gl_rwlock_t datatype ------------------------- */
+
+/* It is impossible to implement read-write locks using plain locks, without
+ introducing an extra thread dedicated to managing read-write locks.
+ Therefore here we need to use the low-level Event type. */
+
+typedef struct
+ {
+ HANDLE *array; /* array of waiting threads, each represented by an event */
+ unsigned int count; /* number of waiting threads */
+ unsigned int alloc; /* length of allocated array */
+ unsigned int offset; /* index of first waiting thread in array */
+ }
+ gl_carray_waitqueue_t;
+typedef struct
+ {
+ gl_spinlock_t guard; /* protects the initialization */
+ CRITICAL_SECTION lock; /* protects the remaining fields */
+ gl_carray_waitqueue_t waiting_readers; /* waiting readers */
+ gl_carray_waitqueue_t waiting_writers; /* waiting writers */
+ int runcount; /* number of readers running, or -1 when a writer runs */
+ }
+ gl_rwlock_t;
+# define gl_rwlock_define(STORAGECLASS, NAME) \
+ STORAGECLASS gl_rwlock_t NAME;
+# define gl_rwlock_define_initialized(STORAGECLASS, NAME) \
+ STORAGECLASS gl_rwlock_t NAME = gl_rwlock_initializer;
+# define gl_rwlock_initializer \
+ { { 0, -1 } }
+# define glthread_rwlock_init(LOCK) \
+ (glthread_rwlock_init_func (LOCK), 0)
+# define glthread_rwlock_rdlock(LOCK) \
+ glthread_rwlock_rdlock_func (LOCK)
+# define glthread_rwlock_wrlock(LOCK) \
+ glthread_rwlock_wrlock_func (LOCK)
+# define glthread_rwlock_unlock(LOCK) \
+ glthread_rwlock_unlock_func (LOCK)
+# define glthread_rwlock_destroy(LOCK) \
+ glthread_rwlock_destroy_func (LOCK)
+extern void glthread_rwlock_init_func (gl_rwlock_t *lock);
+extern int glthread_rwlock_rdlock_func (gl_rwlock_t *lock);
+extern int glthread_rwlock_wrlock_func (gl_rwlock_t *lock);
+extern int glthread_rwlock_unlock_func (gl_rwlock_t *lock);
+extern int glthread_rwlock_destroy_func (gl_rwlock_t *lock);
+
+/* --------------------- gl_recursive_lock_t datatype --------------------- */
+
+/* The native Windows documentation says that CRITICAL_SECTION already
+ implements a recursive lock. But we need not rely on it: It's easy to
+ implement a recursive lock without this assumption. */
+
+typedef struct
+ {
+ gl_spinlock_t guard; /* protects the initialization */
+ DWORD owner;
+ unsigned long depth;
+ CRITICAL_SECTION lock;
+ }
+ gl_recursive_lock_t;
+# define gl_recursive_lock_define(STORAGECLASS, NAME) \
+ STORAGECLASS gl_recursive_lock_t NAME;
+# define gl_recursive_lock_define_initialized(STORAGECLASS, NAME) \
+ STORAGECLASS gl_recursive_lock_t NAME = gl_recursive_lock_initializer;
+# define gl_recursive_lock_initializer \
+ { { 0, -1 }, 0, 0 }
+# define glthread_recursive_lock_init(LOCK) \
+ (glthread_recursive_lock_init_func (LOCK), 0)
+# define glthread_recursive_lock_lock(LOCK) \
+ glthread_recursive_lock_lock_func (LOCK)
+# define glthread_recursive_lock_unlock(LOCK) \
+ glthread_recursive_lock_unlock_func (LOCK)
+# define glthread_recursive_lock_destroy(LOCK) \
+ glthread_recursive_lock_destroy_func (LOCK)
+extern void glthread_recursive_lock_init_func (gl_recursive_lock_t *lock);
+extern int glthread_recursive_lock_lock_func (gl_recursive_lock_t *lock);
+extern int glthread_recursive_lock_unlock_func (gl_recursive_lock_t *lock);
+extern int glthread_recursive_lock_destroy_func (gl_recursive_lock_t *lock);
+
+/* -------------------------- gl_once_t datatype -------------------------- */
+
+typedef struct
+ {
+ volatile int inited;
+ volatile long started;
+ CRITICAL_SECTION lock;
+ }
+ gl_once_t;
+# define gl_once_define(STORAGECLASS, NAME) \
+ STORAGECLASS gl_once_t NAME = { -1, -1 };
+# define glthread_once(ONCE_CONTROL, INITFUNCTION) \
+ (glthread_once_func (ONCE_CONTROL, INITFUNCTION), 0)
+extern void glthread_once_func (gl_once_t *once_control, void (*initfunction) (void));
+
+# ifdef __cplusplus
+}
+# endif
+
+#endif
+
+/* ========================================================================= */
+
+#if !(USE_POSIX_THREADS || USE_PTH_THREADS || USE_SOLARIS_THREADS || USE_WINDOWS_THREADS)
+
+/* Provide dummy implementation if threads are not supported. */
+
+/* -------------------------- gl_lock_t datatype -------------------------- */
+
+typedef int gl_lock_t;
+# define gl_lock_define(STORAGECLASS, NAME)
+# define gl_lock_define_initialized(STORAGECLASS, NAME)
+# define glthread_lock_init(NAME) 0
+# define glthread_lock_lock(NAME) 0
+# define glthread_lock_unlock(NAME) 0
+# define glthread_lock_destroy(NAME) 0
+
+/* ------------------------- gl_rwlock_t datatype ------------------------- */
+
+typedef int gl_rwlock_t;
+# define gl_rwlock_define(STORAGECLASS, NAME)
+# define gl_rwlock_define_initialized(STORAGECLASS, NAME)
+# define glthread_rwlock_init(NAME) 0
+# define glthread_rwlock_rdlock(NAME) 0
+# define glthread_rwlock_wrlock(NAME) 0
+# define glthread_rwlock_unlock(NAME) 0
+# define glthread_rwlock_destroy(NAME) 0
+
+/* --------------------- gl_recursive_lock_t datatype --------------------- */
+
+typedef int gl_recursive_lock_t;
+# define gl_recursive_lock_define(STORAGECLASS, NAME)
+# define gl_recursive_lock_define_initialized(STORAGECLASS, NAME)
+# define glthread_recursive_lock_init(NAME) 0
+# define glthread_recursive_lock_lock(NAME) 0
+# define glthread_recursive_lock_unlock(NAME) 0
+# define glthread_recursive_lock_destroy(NAME) 0
+
+/* -------------------------- gl_once_t datatype -------------------------- */
+
+typedef int gl_once_t;
+# define gl_once_define(STORAGECLASS, NAME) \
+ STORAGECLASS gl_once_t NAME = 0;
+# define glthread_once(ONCE_CONTROL, INITFUNCTION) \
+ (*(ONCE_CONTROL) == 0 ? (*(ONCE_CONTROL) = ~ 0, INITFUNCTION (), 0) : 0)
+
+#endif
+
+/* ========================================================================= */
+
+/* Macros with built-in error handling. */
+
+/* -------------------------- gl_lock_t datatype -------------------------- */
+
+#define gl_lock_init(NAME) \
+ do \
+ { \
+ if (glthread_lock_init (&NAME)) \
+ abort (); \
+ } \
+ while (0)
+#define gl_lock_lock(NAME) \
+ do \
+ { \
+ if (glthread_lock_lock (&NAME)) \
+ abort (); \
+ } \
+ while (0)
+#define gl_lock_unlock(NAME) \
+ do \
+ { \
+ if (glthread_lock_unlock (&NAME)) \
+ abort (); \
+ } \
+ while (0)
+#define gl_lock_destroy(NAME) \
+ do \
+ { \
+ if (glthread_lock_destroy (&NAME)) \
+ abort (); \
+ } \
+ while (0)
+
+/* ------------------------- gl_rwlock_t datatype ------------------------- */
+
+#define gl_rwlock_init(NAME) \
+ do \
+ { \
+ if (glthread_rwlock_init (&NAME)) \
+ abort (); \
+ } \
+ while (0)
+#define gl_rwlock_rdlock(NAME) \
+ do \
+ { \
+ if (glthread_rwlock_rdlock (&NAME)) \
+ abort (); \
+ } \
+ while (0)
+#define gl_rwlock_wrlock(NAME) \
+ do \
+ { \
+ if (glthread_rwlock_wrlock (&NAME)) \
+ abort (); \
+ } \
+ while (0)
+#define gl_rwlock_unlock(NAME) \
+ do \
+ { \
+ if (glthread_rwlock_unlock (&NAME)) \
+ abort (); \
+ } \
+ while (0)
+#define gl_rwlock_destroy(NAME) \
+ do \
+ { \
+ if (glthread_rwlock_destroy (&NAME)) \
+ abort (); \
+ } \
+ while (0)
+
+/* --------------------- gl_recursive_lock_t datatype --------------------- */
+
+#define gl_recursive_lock_init(NAME) \
+ do \
+ { \
+ if (glthread_recursive_lock_init (&NAME)) \
+ abort (); \
+ } \
+ while (0)
+#define gl_recursive_lock_lock(NAME) \
+ do \
+ { \
+ if (glthread_recursive_lock_lock (&NAME)) \
+ abort (); \
+ } \
+ while (0)
+#define gl_recursive_lock_unlock(NAME) \
+ do \
+ { \
+ if (glthread_recursive_lock_unlock (&NAME)) \
+ abort (); \
+ } \
+ while (0)
+#define gl_recursive_lock_destroy(NAME) \
+ do \
+ { \
+ if (glthread_recursive_lock_destroy (&NAME)) \
+ abort (); \
+ } \
+ while (0)
+
+/* -------------------------- gl_once_t datatype -------------------------- */
+
+#define gl_once(NAME, INITFUNCTION) \
+ do \
+ { \
+ if (glthread_once (&NAME, INITFUNCTION)) \
+ abort (); \
+ } \
+ while (0)
+
+/* ========================================================================= */
+
+#endif /* _LOCK_H */
diff --git a/lib/glthread/threadlib.c b/lib/glthread/threadlib.c
new file mode 100644
index 0000000..be63713
--- /dev/null
+++ b/lib/glthread/threadlib.c
@@ -0,0 +1,73 @@
+/* Multithreading primitives.
+ Copyright (C) 2005-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Bruno Haible <bruno@clisp.org>, 2005. */
+
+#include <config.h>
+
+/* ========================================================================= */
+
+#if USE_POSIX_THREADS
+
+/* Use the POSIX threads library. */
+
+# include <pthread.h>
+# include <stdlib.h>
+
+# if PTHREAD_IN_USE_DETECTION_HARD
+
+/* The function to be executed by a dummy thread. */
+static void *
+dummy_thread_func (void *arg)
+{
+ return arg;
+}
+
+int
+glthread_in_use (void)
+{
+ static int tested;
+ static int result; /* 1: linked with -lpthread, 0: only with libc */
+
+ if (!tested)
+ {
+ pthread_t thread;
+
+ if (pthread_create (&thread, NULL, dummy_thread_func, NULL) != 0)
+ /* Thread creation failed. */
+ result = 0;
+ else
+ {
+ /* Thread creation works. */
+ void *retval;
+ if (pthread_join (thread, &retval) != 0)
+ abort ();
+ result = 1;
+ }
+ tested = 1;
+ }
+ return result;
+}
+
+# endif
+
+#endif
+
+/* ========================================================================= */
+
+/* This declaration is solely to ensure that after preprocessing
+ this file is never empty. */
+typedef int dummy;
diff --git a/lib/glthread/tls.c b/lib/glthread/tls.c
new file mode 100644
index 0000000..7c1916a
--- /dev/null
+++ b/lib/glthread/tls.c
@@ -0,0 +1,61 @@
+/* Thread-local storage in multithreaded situations.
+ Copyright (C) 2005-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Bruno Haible <bruno@clisp.org>, 2005. */
+
+#include <config.h>
+
+#include "glthread/tls.h"
+
+/* ========================================================================= */
+
+#if USE_POSIX_THREADS
+
+#endif
+
+/* ========================================================================= */
+
+#if USE_PTH_THREADS
+
+#endif
+
+/* ========================================================================= */
+
+#if USE_SOLARIS_THREADS
+
+/* Use the old Solaris threads library. */
+
+/* ------------------------- gl_tls_key_t datatype ------------------------- */
+
+void *
+glthread_tls_get_multithreaded (thread_key_t key)
+{
+ void *value;
+
+ if (thr_getspecific (key, &value) != 0)
+ abort ();
+ return value;
+}
+
+#endif
+
+/* ========================================================================= */
+
+#if USE_WINDOWS_THREADS
+
+#endif
+
+/* ========================================================================= */
diff --git a/lib/glthread/tls.h b/lib/glthread/tls.h
new file mode 100644
index 0000000..63955a2
--- /dev/null
+++ b/lib/glthread/tls.h
@@ -0,0 +1,299 @@
+/* Thread-local storage in multithreaded situations.
+ Copyright (C) 2005, 2007-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Bruno Haible <bruno@clisp.org>, 2005. */
+
+/* This file contains thread-local storage primitives for use with a given
+ thread library. It does not contain primitives for creating threads or
+ for other multithreading primitives.
+
+ Type: gl_tls_key_t
+ Initialization: gl_tls_key_init (name, destructor);
+ Getting per-thread value: gl_tls_get (name)
+ Setting per-thread value: gl_tls_set (name, pointer);
+ De-initialization: gl_tls_key_destroy (name);
+ Equivalent functions with control of error handling:
+ Initialization: err = glthread_tls_key_init (&name, destructor);
+ Setting per-thread value: err = glthread_tls_set (&name, pointer);
+ De-initialization: err = glthread_tls_key_destroy (&name);
+
+ A per-thread value is of type 'void *'.
+
+ A destructor is a function pointer of type 'void (*) (void *)', called
+ when a thread exits, and taking the last per-thread value as argument. It
+ is unspecified whether the destructor function is called when the last
+ per-thread value is NULL. On some platforms, the destructor function is
+ not called at all.
+*/
+
+
+#ifndef _TLS_H
+#define _TLS_H
+
+#include <errno.h>
+#include <stdlib.h>
+
+/* ========================================================================= */
+
+#if USE_POSIX_THREADS
+
+/* Use the POSIX threads library. */
+
+# include <pthread.h>
+
+# if PTHREAD_IN_USE_DETECTION_HARD
+
+/* The pthread_in_use() detection needs to be done at runtime. */
+# define pthread_in_use() \
+ glthread_in_use ()
+extern int glthread_in_use (void);
+
+# endif
+
+# if USE_POSIX_THREADS_WEAK
+
+/* Use weak references to the POSIX threads library. */
+
+# pragma weak pthread_key_create
+# pragma weak pthread_getspecific
+# pragma weak pthread_setspecific
+# pragma weak pthread_key_delete
+# ifndef pthread_self
+# pragma weak pthread_self
+# endif
+
+# if !PTHREAD_IN_USE_DETECTION_HARD
+# pragma weak pthread_cancel
+# define pthread_in_use() (pthread_cancel != NULL)
+# endif
+
+# else
+
+# if !PTHREAD_IN_USE_DETECTION_HARD
+# define pthread_in_use() 1
+# endif
+
+# endif
+
+/* ------------------------- gl_tls_key_t datatype ------------------------- */
+
+typedef union
+ {
+ void *singlethread_value;
+ pthread_key_t key;
+ }
+ gl_tls_key_t;
+# define glthread_tls_key_init(KEY, DESTRUCTOR) \
+ (pthread_in_use () \
+ ? pthread_key_create (&(KEY)->key, DESTRUCTOR) \
+ : ((KEY)->singlethread_value = NULL, 0))
+# define gl_tls_get(NAME) \
+ (pthread_in_use () \
+ ? pthread_getspecific ((NAME).key) \
+ : (NAME).singlethread_value)
+# define glthread_tls_set(KEY, POINTER) \
+ (pthread_in_use () \
+ ? pthread_setspecific ((KEY)->key, (POINTER)) \
+ : ((KEY)->singlethread_value = (POINTER), 0))
+# define glthread_tls_key_destroy(KEY) \
+ (pthread_in_use () ? pthread_key_delete ((KEY)->key) : 0)
+
+#endif
+
+/* ========================================================================= */
+
+#if USE_PTH_THREADS
+
+/* Use the GNU Pth threads library. */
+
+# include <pth.h>
+
+# if USE_PTH_THREADS_WEAK
+
+/* Use weak references to the GNU Pth threads library. */
+
+# pragma weak pth_key_create
+# pragma weak pth_key_getdata
+# pragma weak pth_key_setdata
+# pragma weak pth_key_delete
+
+# pragma weak pth_cancel
+# define pth_in_use() (pth_cancel != NULL)
+
+# else
+
+# define pth_in_use() 1
+
+# endif
+
+/* ------------------------- gl_tls_key_t datatype ------------------------- */
+
+typedef union
+ {
+ void *singlethread_value;
+ pth_key_t key;
+ }
+ gl_tls_key_t;
+# define glthread_tls_key_init(KEY, DESTRUCTOR) \
+ (pth_in_use () \
+ ? (!pth_key_create (&(KEY)->key, DESTRUCTOR) ? errno : 0) \
+ : ((KEY)->singlethread_value = NULL, 0))
+# define gl_tls_get(NAME) \
+ (pth_in_use () \
+ ? pth_key_getdata ((NAME).key) \
+ : (NAME).singlethread_value)
+# define glthread_tls_set(KEY, POINTER) \
+ (pth_in_use () \
+ ? (!pth_key_setdata ((KEY)->key, (POINTER)) ? errno : 0) \
+ : ((KEY)->singlethread_value = (POINTER), 0))
+# define glthread_tls_key_destroy(KEY) \
+ (pth_in_use () \
+ ? (!pth_key_delete ((KEY)->key) ? errno : 0) \
+ : 0)
+
+#endif
+
+/* ========================================================================= */
+
+#if USE_SOLARIS_THREADS
+
+/* Use the old Solaris threads library. */
+
+# include <thread.h>
+
+# if USE_SOLARIS_THREADS_WEAK
+
+/* Use weak references to the old Solaris threads library. */
+
+# pragma weak thr_keycreate
+# pragma weak thr_getspecific
+# pragma weak thr_setspecific
+
+# pragma weak thr_suspend
+# define thread_in_use() (thr_suspend != NULL)
+
+# else
+
+# define thread_in_use() 1
+
+# endif
+
+/* ------------------------- gl_tls_key_t datatype ------------------------- */
+
+typedef union
+ {
+ void *singlethread_value;
+ thread_key_t key;
+ }
+ gl_tls_key_t;
+# define glthread_tls_key_init(KEY, DESTRUCTOR) \
+ (thread_in_use () \
+ ? thr_keycreate (&(KEY)->key, DESTRUCTOR) \
+ : ((KEY)->singlethread_value = NULL, 0))
+# define gl_tls_get(NAME) \
+ (thread_in_use () \
+ ? glthread_tls_get_multithreaded ((NAME).key) \
+ : (NAME).singlethread_value)
+extern void *glthread_tls_get_multithreaded (thread_key_t key);
+# define glthread_tls_set(KEY, POINTER) \
+ (thread_in_use () \
+ ? thr_setspecific ((KEY)->key, (POINTER)) \
+ : ((KEY)->singlethread_value = (POINTER), 0))
+# define glthread_tls_key_destroy(KEY) \
+ /* Unsupported. */ \
+ 0
+
+#endif
+
+/* ========================================================================= */
+
+#if USE_WINDOWS_THREADS
+
+# define WIN32_LEAN_AND_MEAN /* avoid including junk */
+# include <windows.h>
+
+/* ------------------------- gl_tls_key_t datatype ------------------------- */
+
+typedef DWORD gl_tls_key_t;
+# define glthread_tls_key_init(KEY, DESTRUCTOR) \
+ /* The destructor is unsupported. */ \
+ ((*(KEY) = TlsAlloc ()) == (DWORD)-1 ? EAGAIN : ((void) (DESTRUCTOR), 0))
+# define gl_tls_get(NAME) \
+ TlsGetValue (NAME)
+# define glthread_tls_set(KEY, POINTER) \
+ (!TlsSetValue (*(KEY), POINTER) ? EINVAL : 0)
+# define glthread_tls_key_destroy(KEY) \
+ (!TlsFree (*(KEY)) ? EINVAL : 0)
+
+#endif
+
+/* ========================================================================= */
+
+#if !(USE_POSIX_THREADS || USE_PTH_THREADS || USE_SOLARIS_THREADS || USE_WINDOWS_THREADS)
+
+/* Provide dummy implementation if threads are not supported. */
+
+/* ------------------------- gl_tls_key_t datatype ------------------------- */
+
+typedef struct
+ {
+ void *singlethread_value;
+ }
+ gl_tls_key_t;
+# define glthread_tls_key_init(KEY, DESTRUCTOR) \
+ ((KEY)->singlethread_value = NULL, \
+ (void) (DESTRUCTOR), \
+ 0)
+# define gl_tls_get(NAME) \
+ (NAME).singlethread_value
+# define glthread_tls_set(KEY, POINTER) \
+ ((KEY)->singlethread_value = (POINTER), 0)
+# define glthread_tls_key_destroy(KEY) \
+ 0
+
+#endif
+
+/* ========================================================================= */
+
+/* Macros with built-in error handling. */
+
+/* ------------------------- gl_tls_key_t datatype ------------------------- */
+
+#define gl_tls_key_init(NAME, DESTRUCTOR) \
+ do \
+ { \
+ if (glthread_tls_key_init (&NAME, DESTRUCTOR)) \
+ abort (); \
+ } \
+ while (0)
+#define gl_tls_set(NAME, POINTER) \
+ do \
+ { \
+ if (glthread_tls_set (&NAME, POINTER)) \
+ abort (); \
+ } \
+ while (0)
+#define gl_tls_key_destroy(NAME) \
+ do \
+ { \
+ if (glthread_tls_key_destroy (&NAME)) \
+ abort (); \
+ } \
+ while (0)
+
+/* ========================================================================= */
+
+#endif /* _TLS_H */
diff --git a/lib/gnulib.mk b/lib/gnulib.mk
index e833d14..c6a476e 100644
--- a/lib/gnulib.mk
+++ b/lib/gnulib.mk
@@ -1,57 +1,79 @@
## DO NOT EDIT! GENERATED AUTOMATICALLY!
## Process this file with automake to produce Makefile.in.
-# Copyright (C) 2004-2007 Free Software Foundation, Inc.
+# Copyright (C) 2002-2016 Free Software Foundation, Inc.
#
-# This file is free software, distributed under the terms of the GNU
-# General Public License. As a special exception to the GNU General
-# Public License, this file may be distributed as part of a program
-# that contains a configuration script generated by Autoconf, under
+# This file 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 file 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 file. If not, see <http://www.gnu.org/licenses/>.
+#
+# As a special exception to the GNU General Public License,
+# this file may be distributed as part of a program that
+# contains a configuration script generated by Autoconf, under
# the same distribution terms as the rest of that program.
#
# Generated by gnulib-tool.
-# Reproduce by: gnulib-tool --import --dir=. --local-dir=gl --lib=libcoreutils --source-base=lib --m4-base=m4 --doc-base=doc --aux-dir=build-aux --avoid=lock --avoid=size_max --avoid=xsize --avoid=canonicalize-lgpl --no-libtool --macro-prefix=gl acl alloca announce-gen argmatch assert atexit backupfile base64 c-strcase c-strtod c-strtold calloc canon-host canonicalize chown cloexec closeout config-h configmake cycle-check d-ino d-type diacrit dirfd dirname dup2 error euidaccess exclude exitfail fchdir fcntl fcntl-safer fdl file-type fileblocks filemode filenamecat fnmatch-gnu fopen-safer fprintftime free fsusage ftruncate fts getdate getgroups gethrxtime getline getloadavg getndelim2 getopt getpagesize getpass-gnu gettext gettime gettimeofday getugroups getusershell gnupload group-member hard-locale hash hash-pjw host-os human idcache inttostr inttypes isapipe lchmod lchown lib-ignore linebuffer link-follow long-options lstat malloc mbswidth md5 memcasecmp memchr memcmp memcpy memmove mempcpy memrchr memset mkancesdirs mkdir mkdir-p mkstemp mktime modechange mountlist mpsort obstack pathmax perl physmem posixtm posixver putenv quote quotearg raise readlink readtokens readtokens0 readutmp realloc regex rename rename-dest-slash rmdir rmdir-errno root-dev-ino rpmatch safe-read same save-cwd savedir savewd settime sha1 sig2str ssize_t stat-macros stat-time stdbool stdlib-safer stpcpy strcspn strftime strpbrk strtod strtoimax strtol strtoumax strverscmp sys_stat timespec tzset unicodeio unistd-safer unlink-busy unlinkdir unlocked-io uptime userspec utime utimecmp utimens vasprintf verify version-etc-fsf wcwidth winsz-ioctl winsz-termios xalloc xgetcwd xgethostname xmemcoll xnanosleep xreadlink xreadlink-with-size xstrtod xstrtoimax xstrtol xstrtold xstrtoumax yesno
+# Reproduce by: gnulib-tool --import --local-dir=gl --lib=libcoreutils --source-base=lib --m4-base=m4 --doc-base=doc --tests-base=gnulib-tests --aux-dir=build-aux --with-tests --avoid=canonicalize-lgpl --avoid=dummy --makefile-name=gnulib.mk --no-conditional-dependencies --no-libtool --macro-prefix=gl acl alignof alloca announce-gen areadlink-with-size argmatch argv-iter assert autobuild backupfile base32 base64 buffer-lcm c-strcase c-strtod c-strtold calloc-gnu canon-host canonicalize chown cloexec closein closeout config-h configmake crypto/md5 crypto/sha1 crypto/sha256 crypto/sha512 cycle-check d-ino d-type di-set diacrit dirfd dirname do-release-commit-and-tag dtoastr dup2 environ error euidaccess exclude exitfail faccessat fadvise fchdir fchmodat fchownat fclose fcntl fcntl-safer fd-reopen fdatasync fdl fdopen fdutimensat file-has-acl file-type fileblocks filemode filenamecat filevercmp fnmatch-gnu fopen-safer fprintftime freopen freopen-safer fseeko fstatat fsusage fsync ftello ftoastr ftruncate fts full-read full-write getgroups gethrxtime getline getloadavg getlogin getndelim2 getopt-gnu getpagesize getpass-gnu gettext-h gettime gettimeofday getugroups getusershell git-version-gen gitlog-to-changelog gnu-make gnu-web-doc-update gnumakefile gnupload group-member hard-locale hash hash-pjw heap host-os human idcache ignore-value inttostr inttypes isapipe isatty isblank largefile lchmod lchown ldtoastr lib-ignore linebuffer link link-follow linkat long-options lstat maintainer-makefile malloc-gnu manywarnings mbrlen mbrtowc mbsalign mbswidth memcasecmp memchr memcmp2 mempcpy memrchr mgetgroups mkancesdirs mkdir mkdir-p mkfifo mknod mkstemp mktime modechange mountlist mpsort netinet_in non-recursive-gnulib-prefix-hack nproc obstack parse-datetime pathmax perl physmem pipe-posix posix-shell posixtm posixver priv-set progname propername pthread putenv quote quotearg randint randperm read-file readlink readtokens readtokens0 readutmp realloc-gnu regex remove rename rmdir root-dev-ino rpmatch safe-read same save-cwd savedir savewd selinux-at setenv settime sig2str sigaction smack ssize_t stat-macros stat-size stat-time statat stdbool stdlib-safer stpcpy stpncpy strdup-posix strftime strncat strnumcmp strpbrk strsignal strtod strtoimax strtoumax symlink sys_ioctl sys_resource sys_stat sys_wait tempname termios time_rz timer-time timespec tzset uname unicodeio unistd-safer unlink-busy unlinkat unlocked-io unsetenv update-copyright uptime useless-if-before-free userspec utimecmp utimens vasprintf-posix vc-list-files verify verror version-etc-fsf wcswidth wcwidth winsz-ioctl winsz-termios write-any-file xalloc xdectoint xfreopen xfts xgetcwd xgetgroups xgethostname xmemcoll xnanosleep xprintf xprintf-posix xreadlink xstrtod xstrtoimax xstrtol xstrtold xstrtoumax yesno
-AUTOMAKE_OPTIONS = 1.5 gnits
-noinst_HEADERS =
-noinst_LIBRARIES =
-noinst_LTLIBRARIES =
-EXTRA_DIST =
-BUILT_SOURCES =
-SUFFIXES =
-MOSTLYCLEANFILES = core *.stackdump
-MOSTLYCLEANDIRS =
-CLEANFILES =
-DISTCLEANFILES =
-MAINTAINERCLEANFILES =
+MOSTLYCLEANFILES += lib/core lib/*.stackdump
-AM_CPPFLAGS =
+noinst_LIBRARIES += lib/libcoreutils.a
-noinst_LIBRARIES += libcoreutils.a
+lib_libcoreutils_a_SOURCES =
+lib_libcoreutils_a_LIBADD = $(gl_LIBOBJS)
+lib_libcoreutils_a_DEPENDENCIES = $(gl_LIBOBJS)
+EXTRA_lib_libcoreutils_a_SOURCES =
-libcoreutils_a_SOURCES =
-libcoreutils_a_LIBADD = $(gl_LIBOBJS)
-libcoreutils_a_DEPENDENCIES = $(gl_LIBOBJS)
-EXTRA_libcoreutils_a_SOURCES =
+## begin gnulib module absolute-header
-## begin gnulib module acl
+# Use this preprocessor expression to decide whether #include_next works.
+# Do not rely on a 'configure'-time test for this, since the expression
+# might appear in an installed header, which is used by some other compiler.
+HAVE_INCLUDE_NEXT = lib/(__GNUC__ lib/|| lib/60000000 lib/<= lib/__DECC_VER)
+## end gnulib module absolute-header
-EXTRA_DIST += acl-internal.h acl.c acl.h acl_entries.c file-has-acl.c
+## begin gnulib module acl
-EXTRA_libcoreutils_a_SOURCES += acl.c acl_entries.c file-has-acl.c
+lib_libcoreutils_a_SOURCES += lib/copy-acl.c lib/set-acl.c
## end gnulib module acl
+## begin gnulib module acl-permissions
+
+lib_libcoreutils_a_SOURCES += lib/acl-errno-valid.c lib/acl-internal.c lib/get-permissions.c lib/set-permissions.c
+
+EXTRA_DIST += lib/acl-internal.h lib/acl.h lib/acl_entries.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/acl_entries.c
+
+## end gnulib module acl-permissions
+
+## begin gnulib module alignof
+
+
+EXTRA_DIST += lib/alignof.h
+
+## end gnulib module alignof
+
## begin gnulib module alloca
-EXTRA_DIST += alloca.c
+lib_libcoreutils_a_LIBADD += @ALLOCA@
+lib_libcoreutils_a_DEPENDENCIES += @ALLOCA@
+EXTRA_DIST += lib/alloca.c
-EXTRA_libcoreutils_a_SOURCES += alloca.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/alloca.c
-libcoreutils_a_LIBADD += @ALLOCA@
-libcoreutils_a_DEPENDENCIES += @ALLOCA@
## end gnulib module alloca
## begin gnulib module alloca-opt
@@ -60,199 +82,326 @@ BUILT_SOURCES += $(ALLOCA_H)
# We need the following in order to create <alloca.h> when the system
# doesn't have one that works with the given compiler.
-alloca.h: alloca_.h
+if GL_GENERATE_ALLOCA_H
+lib/alloca.h: lib/alloca.in.h $(top_builddir)/config.status
+ $(AM_V_GEN)rm -f $@-t $@ && \
{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
- cat $(srcdir)/alloca_.h; \
- } > $@-t
+ cat $(top_srcdir)/lib/alloca.in.h; \
+ } > $@-t && \
mv -f $@-t $@
-MOSTLYCLEANFILES += alloca.h alloca.h-t
+else
+lib/alloca.h: $(top_builddir)/config.status
+ rm -f $@
+endif
+MOSTLYCLEANFILES += lib/alloca.h lib/alloca.h-t
-EXTRA_DIST += alloca_.h
+EXTRA_DIST += lib/alloca.in.h
## end gnulib module alloca-opt
-## begin gnulib module allocsa
+## begin gnulib module allocator
-libcoreutils_a_SOURCES += allocsa.h allocsa.c
+lib_libcoreutils_a_SOURCES += lib/allocator.c
-EXTRA_DIST += allocsa.valgrind
+EXTRA_DIST += lib/allocator.h
-## end gnulib module allocsa
+## end gnulib module allocator
-## begin gnulib module argmatch
+## begin gnulib module announce-gen
+
+
+EXTRA_DIST += $(top_srcdir)/build-aux/announce-gen
+
+## end gnulib module announce-gen
+
+## begin gnulib module areadlink
+lib_libcoreutils_a_SOURCES += lib/areadlink.c
-EXTRA_DIST += argmatch.c argmatch.h
+EXTRA_DIST += lib/areadlink.h
-EXTRA_libcoreutils_a_SOURCES += argmatch.c
+## end gnulib module areadlink
+
+## begin gnulib module areadlink-with-size
+
+lib_libcoreutils_a_SOURCES += lib/areadlink-with-size.c
+
+EXTRA_DIST += lib/areadlink.h
+
+## end gnulib module areadlink-with-size
+
+## begin gnulib module areadlinkat
+
+lib_libcoreutils_a_SOURCES += lib/areadlinkat.c
+
+EXTRA_DIST += lib/areadlink.h lib/at-func.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/at-func.c
+
+## end gnulib module areadlinkat
+
+## begin gnulib module argmatch
+
+lib_libcoreutils_a_SOURCES += lib/argmatch.c
+
+EXTRA_DIST += lib/argmatch.h
## end gnulib module argmatch
+## begin gnulib module argv-iter
+
+lib_libcoreutils_a_SOURCES += lib/argv-iter.c lib/argv-iter.h
+
+## end gnulib module argv-iter
+
## begin gnulib module arpa_inet
-BUILT_SOURCES += $(ARPA_INET_H)
+BUILT_SOURCES += lib/arpa/inet.h
# We need the following in order to create <arpa/inet.h> when the system
# doesn't have one.
-arpa/inet.h:
- @MKDIR_P@ arpa
- rm -f $@-t $@
+lib/arpa/inet.h: lib/arpa_inet.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(WARN_ON_USE_H) $(ARG_NONNULL_H)
+ $(AM_V_at)$(MKDIR_P) lib/arpa
+ $(AM_V_GEN)rm -f $@-t $@ && \
{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
- echo '#include <sys/socket.h>'; \
- } > $@-t
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''HAVE_FEATURES_H''@|$(HAVE_FEATURES_H)|g' \
+ -e 's|@''NEXT_ARPA_INET_H''@|$(NEXT_ARPA_INET_H)|g' \
+ -e 's|@''HAVE_ARPA_INET_H''@|$(HAVE_ARPA_INET_H)|g' \
+ -e 's/@''GNULIB_INET_NTOP''@/$(GNULIB_INET_NTOP)/g' \
+ -e 's/@''GNULIB_INET_PTON''@/$(GNULIB_INET_PTON)/g' \
+ -e 's|@''HAVE_DECL_INET_NTOP''@|$(HAVE_DECL_INET_NTOP)|g' \
+ -e 's|@''HAVE_DECL_INET_PTON''@|$(HAVE_DECL_INET_PTON)|g' \
+ -e 's|@''REPLACE_INET_NTOP''@|$(REPLACE_INET_NTOP)|g' \
+ -e 's|@''REPLACE_INET_PTON''@|$(REPLACE_INET_PTON)|g' \
+ -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
+ -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
+ -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
+ < $(top_srcdir)/lib/arpa_inet.in.h; \
+ } > $@-t && \
mv $@-t $@
-MOSTLYCLEANFILES += arpa/inet.h arpa/inet.h-t
-MOSTLYCLEANDIRS += arpa
+MOSTLYCLEANFILES += lib/arpa/inet.h lib/arpa/inet.h-t
+MOSTLYCLEANDIRS += lib/arpa
+
+EXTRA_DIST += lib/arpa_inet.in.h
## end gnulib module arpa_inet
-## begin gnulib module atexit
+## begin gnulib module assure
-EXTRA_DIST += atexit.c
+EXTRA_DIST += lib/assure.h
-EXTRA_libcoreutils_a_SOURCES += atexit.c
+## end gnulib module assure
-## end gnulib module atexit
+## begin gnulib module at-internal
-## begin gnulib module backupfile
+EXTRA_DIST += lib/openat-priv.h lib/openat-proc.c
-EXTRA_DIST += backupfile.c backupfile.h
+EXTRA_lib_libcoreutils_a_SOURCES += lib/openat-proc.c
-EXTRA_libcoreutils_a_SOURCES += backupfile.c
+## end gnulib module at-internal
+
+## begin gnulib module backupfile
+
+lib_libcoreutils_a_SOURCES += lib/backupfile.c
+
+EXTRA_DIST += lib/backupfile.h
## end gnulib module backupfile
+## begin gnulib module base32
+
+lib_libcoreutils_a_SOURCES += lib/base32.h lib/base32.c
+
+## end gnulib module base32
+
## begin gnulib module base64
-libcoreutils_a_SOURCES += base64.h base64.c
+lib_libcoreutils_a_SOURCES += lib/base64.h lib/base64.c
## end gnulib module base64
+## begin gnulib module bitrotate
+
+lib_libcoreutils_a_SOURCES += lib/bitrotate.h lib/bitrotate.c
+
+## end gnulib module bitrotate
+
+## begin gnulib module btowc
+
+
+EXTRA_DIST += lib/btowc.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/btowc.c
+
+## end gnulib module btowc
+
+## begin gnulib module buffer-lcm
+
+lib_libcoreutils_a_SOURCES += lib/buffer-lcm.c lib/buffer-lcm.h
+
+## end gnulib module buffer-lcm
+
## begin gnulib module c-ctype
-libcoreutils_a_SOURCES += c-ctype.h c-ctype.c
+lib_libcoreutils_a_SOURCES += lib/c-ctype.h lib/c-ctype.c
## end gnulib module c-ctype
## begin gnulib module c-strcase
-libcoreutils_a_SOURCES += c-strcase.h c-strcasecmp.c c-strncasecmp.c
+lib_libcoreutils_a_SOURCES += lib/c-strcase.h lib/c-strcasecmp.c lib/c-strncasecmp.c
## end gnulib module c-strcase
-## begin gnulib module c-strtod
+## begin gnulib module c-strcaseeq
+
+
+EXTRA_DIST += lib/c-strcaseeq.h
+## end gnulib module c-strcaseeq
+
+## begin gnulib module c-strtod
-EXTRA_DIST += c-strtod.c c-strtod.h
+lib_libcoreutils_a_SOURCES += lib/c-strtod.c
-EXTRA_libcoreutils_a_SOURCES += c-strtod.c
+EXTRA_DIST += lib/c-strtod.h
## end gnulib module c-strtod
## begin gnulib module c-strtold
+lib_libcoreutils_a_SOURCES += lib/c-strtold.c
-EXTRA_DIST += c-strtod.c c-strtod.h c-strtold.c
+EXTRA_DIST += lib/c-strtod.c lib/c-strtod.h
-EXTRA_libcoreutils_a_SOURCES += c-strtod.c c-strtold.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/c-strtod.c
## end gnulib module c-strtold
-## begin gnulib module calloc
+## begin gnulib module calloc-gnu
-EXTRA_DIST += calloc.c
+EXTRA_DIST += lib/calloc.c
-EXTRA_libcoreutils_a_SOURCES += calloc.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/calloc.c
-## end gnulib module calloc
+## end gnulib module calloc-gnu
-## begin gnulib module canon-host
+## begin gnulib module calloc-posix
+
+
+EXTRA_DIST += lib/calloc.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/calloc.c
+## end gnulib module calloc-posix
-EXTRA_DIST += canon-host.c canon-host.h
+## begin gnulib module canon-host
+
+lib_libcoreutils_a_SOURCES += lib/canon-host.c
-EXTRA_libcoreutils_a_SOURCES += canon-host.c
+EXTRA_DIST += lib/canon-host.h
## end gnulib module canon-host
## begin gnulib module canonicalize
+lib_libcoreutils_a_SOURCES += lib/canonicalize.c
-EXTRA_DIST += canonicalize.c canonicalize.h pathmax.h
-
-EXTRA_libcoreutils_a_SOURCES += canonicalize.c
+EXTRA_DIST += lib/canonicalize.h
## end gnulib module canonicalize
+## begin gnulib module careadlinkat
+
+lib_libcoreutils_a_SOURCES += lib/careadlinkat.c
+
+EXTRA_DIST += lib/careadlinkat.h
+
+## end gnulib module careadlinkat
+
## begin gnulib module chdir-long
-EXTRA_DIST += chdir-long.c chdir-long.h
+EXTRA_DIST += lib/chdir-long.c lib/chdir-long.h
-EXTRA_libcoreutils_a_SOURCES += chdir-long.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/chdir-long.c
## end gnulib module chdir-long
## begin gnulib module chown
-EXTRA_DIST += chown.c fchown-stub.c
+EXTRA_DIST += lib/chown.c lib/fchown-stub.c
-EXTRA_libcoreutils_a_SOURCES += chown.c fchown-stub.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/chown.c lib/fchown-stub.c
## end gnulib module chown
## begin gnulib module cloexec
+lib_libcoreutils_a_SOURCES += lib/cloexec.c
-EXTRA_DIST += cloexec.c cloexec.h
-
-EXTRA_libcoreutils_a_SOURCES += cloexec.c
+EXTRA_DIST += lib/cloexec.h
## end gnulib module cloexec
-## begin gnulib module close-stream
+## begin gnulib module close
-EXTRA_DIST += close-stream.c close-stream.h
+EXTRA_DIST += lib/close.c
-EXTRA_libcoreutils_a_SOURCES += close-stream.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/close.c
+
+## end gnulib module close
+
+## begin gnulib module close-stream
+
+lib_libcoreutils_a_SOURCES += lib/close-stream.c
+
+EXTRA_DIST += lib/close-stream.h
## end gnulib module close-stream
-## begin gnulib module closeout
+## begin gnulib module closedir
+
+
+EXTRA_DIST += lib/closedir.c lib/dirent-private.h
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/closedir.c
+## end gnulib module closedir
-EXTRA_DIST += closeout.c closeout.h
+## begin gnulib module closein
-EXTRA_libcoreutils_a_SOURCES += closeout.c
+lib_libcoreutils_a_SOURCES += lib/closein.c
+
+EXTRA_DIST += lib/closein.h
+
+## end gnulib module closein
+
+## begin gnulib module closeout
+
+lib_libcoreutils_a_SOURCES += lib/closeout.c
+
+EXTRA_DIST += lib/closeout.h
## end gnulib module closeout
## begin gnulib module configmake
-# Retrieve values of the variables through 'configure' followed by
-# 'make', not directly through 'configure', so that a user who
-# sets some of these variables consistently on the 'make' command
-# line gets correct results.
-#
-# One advantage of this approach, compared to the classical
-# approach of adding -DLIBDIR=\"$(libdir)\" etc. to AM_CPPFLAGS,
-# is that it protects against the use of undefined variables.
-# If, say, $(libdir) is not set in the Makefile, LIBDIR is not
-# defined by this module, and code using LIBDIR gives a
-# compilation error.
-#
-# Another advantage is that 'make' output is shorter.
-#
-# Listed in the same order as the GNU makefile conventions.
+# Listed in the same order as the GNU makefile conventions, and
+# provided by autoconf 2.59c+ or 2.70.
# The Automake-defined pkg* macros are appended, in the order
# listed in the Automake 1.10a+ documentation.
-configmake.h: Makefile
- rm -f $@-t $@
+lib/configmake.h: Makefile
+ $(AM_V_GEN)rm -f $@-t && \
{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
echo '#define PREFIX "$(prefix)"'; \
echo '#define EXEC_PREFIX "$(exec_prefix)"'; \
@@ -264,6 +413,7 @@ configmake.h: Makefile
echo '#define SYSCONFDIR "$(sysconfdir)"'; \
echo '#define SHAREDSTATEDIR "$(sharedstatedir)"'; \
echo '#define LOCALSTATEDIR "$(localstatedir)"'; \
+ echo '#define RUNSTATEDIR "$(runstatedir)"'; \
echo '#define INCLUDEDIR "$(includedir)"'; \
echo '#define OLDINCLUDEDIR "$(oldincludedir)"'; \
echo '#define DOCDIR "$(docdir)"'; \
@@ -281,558 +431,1295 @@ configmake.h: Makefile
echo '#define PKGINCLUDEDIR "$(pkgincludedir)"'; \
echo '#define PKGLIBDIR "$(pkglibdir)"'; \
echo '#define PKGLIBEXECDIR "$(pkglibexecdir)"'; \
- } | sed '/""/d' > $@-t
- mv $@-t $@
-BUILT_SOURCES += configmake.h
-CLEANFILES += configmake.h configmake.h-t
+ } | sed '/""/d' > $@-t && \
+ mv -f $@-t $@
+
+BUILT_SOURCES += lib/configmake.h
+CLEANFILES += lib/configmake.h lib/configmake.h-t
## end gnulib module configmake
-## begin gnulib module cycle-check
+## begin gnulib module crypto/md5
+
+lib_libcoreutils_a_SOURCES += lib/md5.c
+
+EXTRA_DIST += lib/gl_openssl.h lib/md5.h
+
+## end gnulib module crypto/md5
+
+## begin gnulib module crypto/sha1
+
+lib_libcoreutils_a_SOURCES += lib/sha1.c
+
+EXTRA_DIST += lib/gl_openssl.h lib/sha1.h
+
+## end gnulib module crypto/sha1
+
+## begin gnulib module crypto/sha256
+
+lib_libcoreutils_a_SOURCES += lib/sha256.c
+
+EXTRA_DIST += lib/gl_openssl.h lib/sha256.h
+
+## end gnulib module crypto/sha256
+
+## begin gnulib module crypto/sha512
+
+lib_libcoreutils_a_SOURCES += lib/sha512.c
+
+EXTRA_DIST += lib/gl_openssl.h lib/sha512.h
+## end gnulib module crypto/sha512
-EXTRA_DIST += cycle-check.c cycle-check.h
+## begin gnulib module ctype
-EXTRA_libcoreutils_a_SOURCES += cycle-check.c
+BUILT_SOURCES += lib/ctype.h
+
+# We need the following in order to create <ctype.h> when the system
+# doesn't have one that works with the given compiler.
+lib/ctype.h: lib/ctype.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(WARN_ON_USE_H)
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_CTYPE_H''@|$(NEXT_CTYPE_H)|g' \
+ -e 's/@''GNULIB_ISBLANK''@/$(GNULIB_ISBLANK)/g' \
+ -e 's/@''HAVE_ISBLANK''@/$(HAVE_ISBLANK)/g' \
+ -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
+ -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
+ < $(top_srcdir)/lib/ctype.in.h; \
+ } > $@-t && \
+ mv $@-t $@
+MOSTLYCLEANFILES += lib/ctype.h lib/ctype.h-t
+
+EXTRA_DIST += lib/ctype.in.h
+
+## end gnulib module ctype
+
+## begin gnulib module cycle-check
+
+lib_libcoreutils_a_SOURCES += lib/cycle-check.c
+
+EXTRA_DIST += lib/cycle-check.h
## end gnulib module cycle-check
## begin gnulib module dev-ino
-EXTRA_DIST += dev-ino.h
+EXTRA_DIST += lib/dev-ino.h
## end gnulib module dev-ino
+## begin gnulib module di-set
+
+lib_libcoreutils_a_SOURCES += lib/di-set.c lib/di-set.h
+
+## end gnulib module di-set
+
## begin gnulib module diacrit
-libcoreutils_a_SOURCES += diacrit.h diacrit.c
+lib_libcoreutils_a_SOURCES += lib/diacrit.h lib/diacrit.c
## end gnulib module diacrit
+## begin gnulib module dirent
+
+BUILT_SOURCES += lib/dirent.h
+
+# We need the following in order to create <dirent.h> when the system
+# doesn't have one that works with the given compiler.
+lib/dirent.h: lib/dirent.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(ARG_NONNULL_H) $(WARN_ON_USE_H)
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''HAVE_DIRENT_H''@|$(HAVE_DIRENT_H)|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_DIRENT_H''@|$(NEXT_DIRENT_H)|g' \
+ -e 's/@''GNULIB_OPENDIR''@/$(GNULIB_OPENDIR)/g' \
+ -e 's/@''GNULIB_READDIR''@/$(GNULIB_READDIR)/g' \
+ -e 's/@''GNULIB_REWINDDIR''@/$(GNULIB_REWINDDIR)/g' \
+ -e 's/@''GNULIB_CLOSEDIR''@/$(GNULIB_CLOSEDIR)/g' \
+ -e 's/@''GNULIB_DIRFD''@/$(GNULIB_DIRFD)/g' \
+ -e 's/@''GNULIB_FDOPENDIR''@/$(GNULIB_FDOPENDIR)/g' \
+ -e 's/@''GNULIB_SCANDIR''@/$(GNULIB_SCANDIR)/g' \
+ -e 's/@''GNULIB_ALPHASORT''@/$(GNULIB_ALPHASORT)/g' \
+ -e 's/@''HAVE_OPENDIR''@/$(HAVE_OPENDIR)/g' \
+ -e 's/@''HAVE_READDIR''@/$(HAVE_READDIR)/g' \
+ -e 's/@''HAVE_REWINDDIR''@/$(HAVE_REWINDDIR)/g' \
+ -e 's/@''HAVE_CLOSEDIR''@/$(HAVE_CLOSEDIR)/g' \
+ -e 's|@''HAVE_DECL_DIRFD''@|$(HAVE_DECL_DIRFD)|g' \
+ -e 's|@''HAVE_DECL_FDOPENDIR''@|$(HAVE_DECL_FDOPENDIR)|g' \
+ -e 's|@''HAVE_FDOPENDIR''@|$(HAVE_FDOPENDIR)|g' \
+ -e 's|@''HAVE_SCANDIR''@|$(HAVE_SCANDIR)|g' \
+ -e 's|@''HAVE_ALPHASORT''@|$(HAVE_ALPHASORT)|g' \
+ -e 's|@''REPLACE_OPENDIR''@|$(REPLACE_OPENDIR)|g' \
+ -e 's|@''REPLACE_CLOSEDIR''@|$(REPLACE_CLOSEDIR)|g' \
+ -e 's|@''REPLACE_DIRFD''@|$(REPLACE_DIRFD)|g' \
+ -e 's|@''REPLACE_FDOPENDIR''@|$(REPLACE_FDOPENDIR)|g' \
+ -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
+ -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
+ -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
+ < $(top_srcdir)/lib/dirent.in.h; \
+ } > $@-t && \
+ mv $@-t $@
+MOSTLYCLEANFILES += lib/dirent.h lib/dirent.h-t
+
+EXTRA_DIST += lib/dirent.in.h
+
+## end gnulib module dirent
+
+## begin gnulib module dirent-safer
+
+lib_libcoreutils_a_SOURCES += lib/opendir-safer.c
+
+EXTRA_DIST += lib/dirent--.h lib/dirent-safer.h
+
+## end gnulib module dirent-safer
+
## begin gnulib module dirfd
-EXTRA_DIST += dirfd.c dirfd.h
+EXTRA_DIST += lib/dirfd.c
-EXTRA_libcoreutils_a_SOURCES += dirfd.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/dirfd.c
## end gnulib module dirfd
## begin gnulib module dirname
+lib_libcoreutils_a_SOURCES += lib/dirname.c lib/basename.c
-EXTRA_DIST += basename.c dirname.c dirname.h stripslash.c
+EXTRA_DIST += lib/stripslash.c
-EXTRA_libcoreutils_a_SOURCES += basename.c dirname.c stripslash.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/stripslash.c
## end gnulib module dirname
+## begin gnulib module dirname-lgpl
+
+lib_libcoreutils_a_SOURCES += lib/dirname-lgpl.c lib/basename-lgpl.c lib/stripslash.c
+
+EXTRA_DIST += lib/dirname.h
+
+## end gnulib module dirname-lgpl
+
+## begin gnulib module do-release-commit-and-tag
+
+
+EXTRA_DIST += $(top_srcdir)/build-aux/do-release-commit-and-tag
+
+## end gnulib module do-release-commit-and-tag
+
+## begin gnulib module dosname
+
+
+EXTRA_DIST += lib/dosname.h
+
+## end gnulib module dosname
+
+## begin gnulib module dtoastr
+
+lib_libcoreutils_a_SOURCES += lib/dtoastr.c
+
+EXTRA_DIST += lib/ftoastr.c lib/ftoastr.h
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/ftoastr.c
+
+## end gnulib module dtoastr
+
+## begin gnulib module dtotimespec
+
+lib_libcoreutils_a_SOURCES += lib/dtotimespec.c
+
+## end gnulib module dtotimespec
+
+## begin gnulib module dup
+
+
+EXTRA_DIST += lib/dup.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/dup.c
+
+## end gnulib module dup
+
## begin gnulib module dup2
-EXTRA_DIST += dup2.c
+EXTRA_DIST += lib/dup2.c
-EXTRA_libcoreutils_a_SOURCES += dup2.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/dup2.c
## end gnulib module dup2
+## begin gnulib module errno
+
+BUILT_SOURCES += $(ERRNO_H)
+
+# We need the following in order to create <errno.h> when the system
+# doesn't have one that is POSIX compliant.
+if GL_GENERATE_ERRNO_H
+lib/errno.h: lib/errno.in.h $(top_builddir)/config.status
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */' && \
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_ERRNO_H''@|$(NEXT_ERRNO_H)|g' \
+ -e 's|@''EMULTIHOP_HIDDEN''@|$(EMULTIHOP_HIDDEN)|g' \
+ -e 's|@''EMULTIHOP_VALUE''@|$(EMULTIHOP_VALUE)|g' \
+ -e 's|@''ENOLINK_HIDDEN''@|$(ENOLINK_HIDDEN)|g' \
+ -e 's|@''ENOLINK_VALUE''@|$(ENOLINK_VALUE)|g' \
+ -e 's|@''EOVERFLOW_HIDDEN''@|$(EOVERFLOW_HIDDEN)|g' \
+ -e 's|@''EOVERFLOW_VALUE''@|$(EOVERFLOW_VALUE)|g' \
+ < $(top_srcdir)/lib/errno.in.h; \
+ } > $@-t && \
+ mv $@-t $@
+else
+lib/errno.h: $(top_builddir)/config.status
+ rm -f $@
+endif
+MOSTLYCLEANFILES += lib/errno.h lib/errno.h-t
+
+EXTRA_DIST += lib/errno.in.h
+
+## end gnulib module errno
+
## begin gnulib module error
-EXTRA_DIST += error.c error.h
+EXTRA_DIST += lib/error.c lib/error.h
-EXTRA_libcoreutils_a_SOURCES += error.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/error.c
## end gnulib module error
## begin gnulib module euidaccess
-EXTRA_DIST += euidaccess.c euidaccess.h
+EXTRA_DIST += lib/euidaccess.c
-EXTRA_libcoreutils_a_SOURCES += euidaccess.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/euidaccess.c
## end gnulib module euidaccess
## begin gnulib module exclude
+lib_libcoreutils_a_SOURCES += lib/exclude.c
-EXTRA_DIST += exclude.c exclude.h
-
-EXTRA_libcoreutils_a_SOURCES += exclude.c
+EXTRA_DIST += lib/exclude.h
## end gnulib module exclude
## begin gnulib module exitfail
+lib_libcoreutils_a_SOURCES += lib/exitfail.c
-EXTRA_DIST += exitfail.c exitfail.h
-
-EXTRA_libcoreutils_a_SOURCES += exitfail.c
+EXTRA_DIST += lib/exitfail.h
## end gnulib module exitfail
-## begin gnulib module fchdir
+## begin gnulib module faccessat
-BUILT_SOURCES += $(DIRENT_H)
-# We need the following in order to create <dirent.h> when the system
-# doesn't have one that works with the given compiler.
-dirent.h: dirent_.h
- rm -f $@-t $@
- { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
- sed -e 's|@''ABSOLUTE_DIRENT_H''@|$(ABSOLUTE_DIRENT_H)|g' \
- -e 's|@''REPLACE_FCHDIR''@|$(REPLACE_FCHDIR)|g' \
- < $(srcdir)/dirent_.h; \
- } > $@-t
- mv $@-t $@
-MOSTLYCLEANFILES += dirent.h dirent.h-t
+EXTRA_DIST += lib/at-func.c lib/faccessat.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/at-func.c lib/faccessat.c
+
+## end gnulib module faccessat
+
+## begin gnulib module fadvise
+
+lib_libcoreutils_a_SOURCES += lib/fadvise.c lib/fadvise.h
+
+## end gnulib module fadvise
+
+## begin gnulib module fchdir
-EXTRA_DIST += dirent_.h fchdir.c
-EXTRA_libcoreutils_a_SOURCES += fchdir.c
+EXTRA_DIST += lib/fchdir.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/fchdir.c
## end gnulib module fchdir
+## begin gnulib module fchmodat
+
+lib_libcoreutils_a_SOURCES += lib/chmodat.c
+
+EXTRA_DIST += lib/at-func.c lib/fchmodat.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/at-func.c lib/fchmodat.c
+
+## end gnulib module fchmodat
+
+## begin gnulib module fchownat
+
+lib_libcoreutils_a_SOURCES += lib/chownat.c
+
+EXTRA_DIST += lib/at-func.c lib/fchownat.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/at-func.c lib/fchownat.c
+
+## end gnulib module fchownat
+
+## begin gnulib module fclose
+
+
+EXTRA_DIST += lib/fclose.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/fclose.c
+
+## end gnulib module fclose
+
## begin gnulib module fcntl
-BUILT_SOURCES += $(FCNTL_H)
+
+EXTRA_DIST += lib/fcntl.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/fcntl.c
+
+## end gnulib module fcntl
+
+## begin gnulib module fcntl-h
+
+BUILT_SOURCES += lib/fcntl.h
# We need the following in order to create <fcntl.h> when the system
# doesn't have one that works with the given compiler.
-fcntl.h: fcntl_.h
- rm -f $@-t $@
+lib/fcntl.h: lib/fcntl.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(ARG_NONNULL_H) $(WARN_ON_USE_H)
+ $(AM_V_GEN)rm -f $@-t $@ && \
{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
- sed -e 's|@''ABSOLUTE_FCNTL_H''@|$(ABSOLUTE_FCNTL_H)|g' \
- < $(srcdir)/fcntl_.h; \
- } > $@-t
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_FCNTL_H''@|$(NEXT_FCNTL_H)|g' \
+ -e 's/@''GNULIB_FCNTL''@/$(GNULIB_FCNTL)/g' \
+ -e 's/@''GNULIB_NONBLOCKING''@/$(GNULIB_NONBLOCKING)/g' \
+ -e 's/@''GNULIB_OPEN''@/$(GNULIB_OPEN)/g' \
+ -e 's/@''GNULIB_OPENAT''@/$(GNULIB_OPENAT)/g' \
+ -e 's|@''HAVE_FCNTL''@|$(HAVE_FCNTL)|g' \
+ -e 's|@''HAVE_OPENAT''@|$(HAVE_OPENAT)|g' \
+ -e 's|@''REPLACE_FCNTL''@|$(REPLACE_FCNTL)|g' \
+ -e 's|@''REPLACE_OPEN''@|$(REPLACE_OPEN)|g' \
+ -e 's|@''REPLACE_OPENAT''@|$(REPLACE_OPENAT)|g' \
+ -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
+ -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
+ -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
+ < $(top_srcdir)/lib/fcntl.in.h; \
+ } > $@-t && \
mv $@-t $@
-MOSTLYCLEANFILES += fcntl.h fcntl.h-t
+MOSTLYCLEANFILES += lib/fcntl.h lib/fcntl.h-t
-EXTRA_DIST += fcntl_.h
+EXTRA_DIST += lib/fcntl.in.h
-## end gnulib module fcntl
+## end gnulib module fcntl-h
## begin gnulib module fcntl-safer
+lib_libcoreutils_a_SOURCES += lib/creat-safer.c lib/open-safer.c
-EXTRA_DIST += creat-safer.c fcntl--.h fcntl-safer.h open-safer.c
-
-EXTRA_libcoreutils_a_SOURCES += creat-safer.c open-safer.c
+EXTRA_DIST += lib/fcntl--.h lib/fcntl-safer.h
## end gnulib module fcntl-safer
-## begin gnulib module file-type
+## begin gnulib module fd-hook
+
+lib_libcoreutils_a_SOURCES += lib/fd-hook.c
+
+EXTRA_DIST += lib/fd-hook.h
+
+## end gnulib module fd-hook
+
+## begin gnulib module fd-reopen
+
+lib_libcoreutils_a_SOURCES += lib/fd-reopen.c lib/fd-reopen.h
+
+## end gnulib module fd-reopen
+
+## begin gnulib module fd-safer-flag
+
+lib_libcoreutils_a_SOURCES += lib/fd-safer-flag.c lib/dup-safer-flag.c
+
+## end gnulib module fd-safer-flag
+
+## begin gnulib module fdatasync
+
+EXTRA_DIST += lib/fdatasync.c
-EXTRA_DIST += file-type.c file-type.h
+EXTRA_lib_libcoreutils_a_SOURCES += lib/fdatasync.c
-EXTRA_libcoreutils_a_SOURCES += file-type.c
+## end gnulib module fdatasync
+
+## begin gnulib module fdopen
+
+
+EXTRA_DIST += lib/fdopen.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/fdopen.c
+
+## end gnulib module fdopen
+
+## begin gnulib module fdopendir
+
+
+EXTRA_DIST += lib/fdopendir.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/fdopendir.c
+
+## end gnulib module fdopendir
+
+## begin gnulib module fdutimensat
+
+lib_libcoreutils_a_SOURCES += lib/fdutimensat.c
+
+EXTRA_DIST += lib/utimens.h
+
+## end gnulib module fdutimensat
+
+## begin gnulib module fflush
+
+
+EXTRA_DIST += lib/fflush.c lib/stdio-impl.h
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/fflush.c
+
+## end gnulib module fflush
+
+## begin gnulib module file-has-acl
+
+lib_libcoreutils_a_SOURCES += lib/file-has-acl.c
+
+## end gnulib module file-has-acl
+
+## begin gnulib module file-set
+
+lib_libcoreutils_a_SOURCES += lib/file-set.c
+
+EXTRA_DIST += lib/file-set.h
+
+## end gnulib module file-set
+
+## begin gnulib module file-type
+
+lib_libcoreutils_a_SOURCES += lib/file-type.c
+
+EXTRA_DIST += lib/file-type.h
## end gnulib module file-type
## begin gnulib module fileblocks
-EXTRA_DIST += fileblocks.c
+EXTRA_DIST += lib/fileblocks.c
-EXTRA_libcoreutils_a_SOURCES += fileblocks.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/fileblocks.c
## end gnulib module fileblocks
## begin gnulib module filemode
+lib_libcoreutils_a_SOURCES += lib/filemode.c
-EXTRA_DIST += filemode.c filemode.h
-
-EXTRA_libcoreutils_a_SOURCES += filemode.c
+EXTRA_DIST += lib/filemode.h
## end gnulib module filemode
-## begin gnulib module filenamecat
+## begin gnulib module filename
-EXTRA_DIST += filenamecat.c filenamecat.h
+EXTRA_DIST += lib/filename.h
-EXTRA_libcoreutils_a_SOURCES += filenamecat.c
+## end gnulib module filename
+
+## begin gnulib module filenamecat
+
+lib_libcoreutils_a_SOURCES += lib/filenamecat.c
## end gnulib module filenamecat
+## begin gnulib module filenamecat-lgpl
+
+lib_libcoreutils_a_SOURCES += lib/filenamecat-lgpl.c
+
+EXTRA_DIST += lib/filenamecat.h
+
+## end gnulib module filenamecat-lgpl
+
+## begin gnulib module filevercmp
+
+lib_libcoreutils_a_SOURCES += lib/filevercmp.c
+
+EXTRA_DIST += lib/filevercmp.h
+
+## end gnulib module filevercmp
+
+## begin gnulib module float
+
+BUILT_SOURCES += $(FLOAT_H)
+
+# We need the following in order to create <float.h> when the system
+# doesn't have one that works with the given compiler.
+if GL_GENERATE_FLOAT_H
+lib/float.h: lib/float.in.h $(top_builddir)/config.status
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */' && \
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_FLOAT_H''@|$(NEXT_FLOAT_H)|g' \
+ -e 's|@''REPLACE_ITOLD''@|$(REPLACE_ITOLD)|g' \
+ < $(top_srcdir)/lib/float.in.h; \
+ } > $@-t && \
+ mv $@-t $@
+else
+lib/float.h: $(top_builddir)/config.status
+ rm -f $@
+endif
+MOSTLYCLEANFILES += lib/float.h lib/float.h-t
+
+EXTRA_DIST += lib/float.c lib/float.in.h lib/itold.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/float.c lib/itold.c
+
+## end gnulib module float
+
## begin gnulib module fnmatch
BUILT_SOURCES += $(FNMATCH_H)
# We need the following in order to create <fnmatch.h> when the system
# doesn't have one that supports the required API.
-fnmatch.h: fnmatch_.h
+if GL_GENERATE_FNMATCH_H
+lib/fnmatch.h: lib/fnmatch.in.h $(top_builddir)/config.status $(ARG_NONNULL_H)
+ $(AM_V_GEN)rm -f $@-t $@ && \
{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
- cat $(srcdir)/fnmatch_.h; \
- } > $@-t
+ sed -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
+ < $(top_srcdir)/lib/fnmatch.in.h; \
+ } > $@-t && \
mv -f $@-t $@
-MOSTLYCLEANFILES += fnmatch.h fnmatch.h-t
+else
+lib/fnmatch.h: $(top_builddir)/config.status
+ rm -f $@
+endif
+MOSTLYCLEANFILES += lib/fnmatch.h lib/fnmatch.h-t
-EXTRA_DIST += fnmatch.c fnmatch_.h fnmatch_loop.c
+EXTRA_DIST += lib/fnmatch.c lib/fnmatch.in.h lib/fnmatch_loop.c
-EXTRA_libcoreutils_a_SOURCES += fnmatch.c fnmatch_loop.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/fnmatch.c lib/fnmatch_loop.c
## end gnulib module fnmatch
-## begin gnulib module fopen-safer
+## begin gnulib module fopen
+
+EXTRA_DIST += lib/fopen.c
-EXTRA_DIST += fopen-safer.c stdio--.h stdio-safer.h
+EXTRA_lib_libcoreutils_a_SOURCES += lib/fopen.c
-EXTRA_libcoreutils_a_SOURCES += fopen-safer.c
+## end gnulib module fopen
+
+## begin gnulib module fopen-safer
+
+lib_libcoreutils_a_SOURCES += lib/fopen-safer.c
+
+EXTRA_DIST += lib/stdio--.h lib/stdio-safer.h
## end gnulib module fopen-safer
## begin gnulib module fpending
-EXTRA_DIST += __fpending.c __fpending.h
+EXTRA_DIST += lib/fpending.c lib/fpending.h
-EXTRA_libcoreutils_a_SOURCES += __fpending.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/fpending.c
## end gnulib module fpending
## begin gnulib module fprintftime
+lib_libcoreutils_a_SOURCES += lib/fprintftime.c
-EXTRA_DIST += fprintftime.c fprintftime.h
-
-EXTRA_libcoreutils_a_SOURCES += fprintftime.c
+EXTRA_DIST += lib/fprintftime.h
## end gnulib module fprintftime
-## begin gnulib module free
+## begin gnulib module fpucw
+
+
+EXTRA_DIST += lib/fpucw.h
+
+## end gnulib module fpucw
+
+## begin gnulib module fpurge
+
+
+EXTRA_DIST += lib/fpurge.c lib/stdio-impl.h
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/fpurge.c
+
+## end gnulib module fpurge
+
+## begin gnulib module freadahead
+
+
+EXTRA_DIST += lib/freadahead.c lib/freadahead.h lib/stdio-impl.h
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/freadahead.c
+
+## end gnulib module freadahead
+## begin gnulib module freading
-EXTRA_DIST += free.c
+lib_libcoreutils_a_SOURCES += lib/freading.c
-EXTRA_libcoreutils_a_SOURCES += free.c
+EXTRA_DIST += lib/freading.h lib/stdio-impl.h
-## end gnulib module free
+## end gnulib module freading
+
+## begin gnulib module freadptr
+
+
+EXTRA_DIST += lib/freadptr.c lib/freadptr.h lib/stdio-impl.h
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/freadptr.c
+
+## end gnulib module freadptr
+
+## begin gnulib module freadseek
+
+lib_libcoreutils_a_SOURCES += lib/freadseek.c
+
+EXTRA_DIST += lib/freadseek.h lib/stdio-impl.h
+
+## end gnulib module freadseek
+
+## begin gnulib module freopen
+
+
+EXTRA_DIST += lib/freopen.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/freopen.c
+
+## end gnulib module freopen
+
+## begin gnulib module freopen-safer
+
+lib_libcoreutils_a_SOURCES += lib/freopen-safer.c
+
+EXTRA_DIST += lib/stdio--.h lib/stdio-safer.h
+
+## end gnulib module freopen-safer
+
+## begin gnulib module frexp-nolibm
+
+
+EXTRA_DIST += lib/frexp.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/frexp.c
+
+## end gnulib module frexp-nolibm
+
+## begin gnulib module frexpl-nolibm
+
+
+EXTRA_DIST += lib/frexp.c lib/frexpl.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/frexp.c lib/frexpl.c
+
+## end gnulib module frexpl-nolibm
+
+## begin gnulib module fseek
+
+
+EXTRA_DIST += lib/fseek.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/fseek.c
+
+## end gnulib module fseek
+
+## begin gnulib module fseeko
+
+
+EXTRA_DIST += lib/fseeko.c lib/stdio-impl.h
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/fseeko.c
+
+## end gnulib module fseeko
+
+## begin gnulib module fseterr
+
+
+EXTRA_DIST += lib/fseterr.c lib/fseterr.h lib/stdio-impl.h
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/fseterr.c
+
+## end gnulib module fseterr
+
+## begin gnulib module fstat
+
+
+EXTRA_DIST += lib/fstat.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/fstat.c
+
+## end gnulib module fstat
+
+## begin gnulib module fstatat
+
+
+EXTRA_DIST += lib/at-func.c lib/fstatat.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/at-func.c lib/fstatat.c
+
+## end gnulib module fstatat
## begin gnulib module fsusage
-EXTRA_DIST += fsusage.c fsusage.h
+EXTRA_DIST += lib/fsusage.c lib/fsusage.h
-EXTRA_libcoreutils_a_SOURCES += fsusage.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/fsusage.c
## end gnulib module fsusage
+## begin gnulib module fsync
+
+
+EXTRA_DIST += lib/fsync.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/fsync.c
+
+## end gnulib module fsync
+
+## begin gnulib module ftell
+
+
+EXTRA_DIST += lib/ftell.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/ftell.c
+
+## end gnulib module ftell
+
+## begin gnulib module ftello
+
+
+EXTRA_DIST += lib/ftello.c lib/stdio-impl.h
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/ftello.c
+
+## end gnulib module ftello
+
+## begin gnulib module ftoastr
+
+lib_libcoreutils_a_SOURCES += lib/ftoastr.c
+
+EXTRA_DIST += lib/ftoastr.h
+
+## end gnulib module ftoastr
+
## begin gnulib module ftruncate
-EXTRA_DIST += ftruncate.c
+EXTRA_DIST += lib/ftruncate.c
-EXTRA_libcoreutils_a_SOURCES += ftruncate.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/ftruncate.c
## end gnulib module ftruncate
## begin gnulib module fts
-EXTRA_DIST += fts-cycle.c fts.c fts_.h
+EXTRA_DIST += lib/fts-cycle.c lib/fts.c lib/fts_.h
-EXTRA_libcoreutils_a_SOURCES += fts-cycle.c fts.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/fts-cycle.c lib/fts.c
## end gnulib module fts
## begin gnulib module full-read
-libcoreutils_a_SOURCES += full-read.h full-read.c
+lib_libcoreutils_a_SOURCES += lib/full-read.h lib/full-read.c
+
+EXTRA_DIST += lib/full-write.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/full-write.c
## end gnulib module full-read
## begin gnulib module full-write
-libcoreutils_a_SOURCES += full-write.h full-write.c
+lib_libcoreutils_a_SOURCES += lib/full-write.h lib/full-write.c
## end gnulib module full-write
+## begin gnulib module futimens
+
+
+EXTRA_DIST += lib/futimens.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/futimens.c
+
+## end gnulib module futimens
+
+## begin gnulib module gendocs
+
+
+EXTRA_DIST += $(top_srcdir)/build-aux/gendocs.sh
+
+## end gnulib module gendocs
+
## begin gnulib module getaddrinfo
-EXTRA_DIST += gai_strerror.c getaddrinfo.c getaddrinfo.h
+EXTRA_DIST += lib/gai_strerror.c lib/getaddrinfo.c
-EXTRA_libcoreutils_a_SOURCES += gai_strerror.c getaddrinfo.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/gai_strerror.c lib/getaddrinfo.c
## end gnulib module getaddrinfo
## begin gnulib module getcwd
-EXTRA_DIST += getcwd.c
+EXTRA_DIST += lib/getcwd.c
-EXTRA_libcoreutils_a_SOURCES += getcwd.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/getcwd.c
## end gnulib module getcwd
-## begin gnulib module getdate
+## begin gnulib module getcwd-lgpl
+
-libcoreutils_a_SOURCES += getdate.y
-BUILT_SOURCES += getdate.c
-MAINTAINERCLEANFILES += getdate.c
-EXTRA_DIST += getdate.c
+EXTRA_DIST += lib/getcwd-lgpl.c
-EXTRA_DIST += getdate.h
+EXTRA_lib_libcoreutils_a_SOURCES += lib/getcwd-lgpl.c
-## end gnulib module getdate
+## end gnulib module getcwd-lgpl
## begin gnulib module getdelim
-EXTRA_DIST += getdelim.c getdelim.h
+EXTRA_DIST += lib/getdelim.c
-EXTRA_libcoreutils_a_SOURCES += getdelim.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/getdelim.c
## end gnulib module getdelim
+## begin gnulib module getdtablesize
+
+
+EXTRA_DIST += lib/getdtablesize.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/getdtablesize.c
+
+## end gnulib module getdtablesize
+
## begin gnulib module getgroups
-EXTRA_DIST += getgroups.c
+EXTRA_DIST += lib/getgroups.c
-EXTRA_libcoreutils_a_SOURCES += getgroups.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/getgroups.c
## end gnulib module getgroups
## begin gnulib module gethostname
-EXTRA_DIST += gethostname.c
+EXTRA_DIST += lib/gethostname.c lib/w32sock.h
-EXTRA_libcoreutils_a_SOURCES += gethostname.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/gethostname.c
## end gnulib module gethostname
## begin gnulib module gethrxtime
+lib_libcoreutils_a_SOURCES += lib/gethrxtime.c lib/xtime.c
-EXTRA_DIST += gethrxtime.c gethrxtime.h xtime.h
-
-EXTRA_libcoreutils_a_SOURCES += gethrxtime.c
+EXTRA_DIST += lib/gethrxtime.h lib/xtime.h
## end gnulib module gethrxtime
## begin gnulib module getline
-EXTRA_DIST += getline.c getline.h
+EXTRA_DIST += lib/getline.c
-EXTRA_libcoreutils_a_SOURCES += getline.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/getline.c
## end gnulib module getline
## begin gnulib module getloadavg
-EXTRA_DIST += getloadavg.c
+EXTRA_DIST += lib/getloadavg.c
-EXTRA_libcoreutils_a_SOURCES += getloadavg.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/getloadavg.c
## end gnulib module getloadavg
-## begin gnulib module getndelim2
+## begin gnulib module getlogin
-EXTRA_DIST += getndelim2.c getndelim2.h
+EXTRA_DIST += lib/getlogin.c
-EXTRA_libcoreutils_a_SOURCES += getndelim2.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/getlogin.c
+
+## end gnulib module getlogin
+
+## begin gnulib module getndelim2
+
+lib_libcoreutils_a_SOURCES += lib/getndelim2.c
+
+EXTRA_DIST += lib/getndelim2.h
## end gnulib module getndelim2
-## begin gnulib module getopt
+## begin gnulib module getopt-posix
BUILT_SOURCES += $(GETOPT_H)
# We need the following in order to create <getopt.h> when the system
# doesn't have one that works with the given compiler.
-getopt.h: getopt_.h
+lib/getopt.h: lib/getopt.in.h $(top_builddir)/config.status $(ARG_NONNULL_H)
+ $(AM_V_GEN)rm -f $@-t $@ && \
{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
- cat $(srcdir)/getopt_.h; \
- } > $@-t
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''HAVE_GETOPT_H''@|$(HAVE_GETOPT_H)|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_GETOPT_H''@|$(NEXT_GETOPT_H)|g' \
+ -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
+ < $(top_srcdir)/lib/getopt.in.h; \
+ } > $@-t && \
mv -f $@-t $@
-MOSTLYCLEANFILES += getopt.h getopt.h-t
+MOSTLYCLEANFILES += lib/getopt.h lib/getopt.h-t
-EXTRA_DIST += getopt.c getopt1.c getopt_.h getopt_int.h
+EXTRA_DIST += lib/getopt.c lib/getopt.in.h lib/getopt1.c lib/getopt_int.h
-EXTRA_libcoreutils_a_SOURCES += getopt.c getopt1.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/getopt.c lib/getopt1.c
-## end gnulib module getopt
+## end gnulib module getopt-posix
## begin gnulib module getpagesize
-EXTRA_DIST += getpagesize.h
+EXTRA_DIST += lib/getpagesize.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/getpagesize.c
## end gnulib module getpagesize
## begin gnulib module getpass-gnu
-EXTRA_DIST += getpass.c getpass.h
+EXTRA_DIST += lib/getpass.c lib/getpass.h
-EXTRA_libcoreutils_a_SOURCES += getpass.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/getpass.c
## end gnulib module getpass-gnu
-## begin gnulib module gettext
-
-# This is for those projects which use "gettextize --intl" to put a source-code
-# copy of libintl into their package. In such projects, every Makefile.am needs
-# -I$(top_builddir)/intl, so that <libintl.h> can be found in this directory.
-# For the Makefile.ams in other directories it is the maintainer's
-# responsibility; for the one from gnulib we do it here.
-# This option has no effect when the user disables NLS (because then the intl
-# directory contains no libintl.h file) or when the project does not use
-# "gettextize --intl".
-#AM_CPPFLAGS += -I$(top_builddir)/intl
-
-## end gnulib module gettext
-
## begin gnulib module gettext-h
-libcoreutils_a_SOURCES += gettext.h
+lib_libcoreutils_a_SOURCES += lib/gettext.h
## end gnulib module gettext-h
## begin gnulib module gettime
-
-EXTRA_DIST += gettime.c
-
-EXTRA_libcoreutils_a_SOURCES += gettime.c
+lib_libcoreutils_a_SOURCES += lib/gettime.c
## end gnulib module gettime
## begin gnulib module gettimeofday
-EXTRA_DIST += gettimeofday.c
+EXTRA_DIST += lib/gettimeofday.c
-EXTRA_libcoreutils_a_SOURCES += gettimeofday.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/gettimeofday.c
## end gnulib module gettimeofday
## begin gnulib module getugroups
+lib_libcoreutils_a_SOURCES += lib/getugroups.c
-EXTRA_DIST += getugroups.c
-
-EXTRA_libcoreutils_a_SOURCES += getugroups.c
+EXTRA_DIST += lib/getugroups.h
## end gnulib module getugroups
## begin gnulib module getusershell
-EXTRA_DIST += getusershell.c
+EXTRA_DIST += lib/getusershell.c
-EXTRA_libcoreutils_a_SOURCES += getusershell.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/getusershell.c
## end gnulib module getusershell
+## begin gnulib module git-version-gen
+
+
+EXTRA_DIST += $(top_srcdir)/build-aux/git-version-gen
+
+## end gnulib module git-version-gen
+
+## begin gnulib module gitlog-to-changelog
+
+
+EXTRA_DIST += $(top_srcdir)/build-aux/gitlog-to-changelog
+
+## end gnulib module gitlog-to-changelog
+
+## begin gnulib module gnu-make
+
+##Sample usage of gnu-make module:
+#if GNU_MAKE
+# [nicer features that work only with GNU Make]
+#else
+# [fallback features that work in any 'make' implementation; see
+# http://www.opengroup.org/susv3/utilities/make.html
+# for the 2004 POSIX specification]
+#endif
+
+## end gnulib module gnu-make
+
+## begin gnulib module gnu-web-doc-update
+
+
+EXTRA_DIST += $(top_srcdir)/build-aux/gnu-web-doc-update
+
+## end gnulib module gnu-web-doc-update
+
+## begin gnulib module gnumakefile
+
+distclean-local: clean-GNUmakefile
+clean-GNUmakefile:
+ test '$(srcdir)' = . || rm -f $(top_builddir)/GNUmakefile
+
+EXTRA_DIST += $(top_srcdir)/GNUmakefile
+
+## end gnulib module gnumakefile
+
+## begin gnulib module gnupload
+
+
+EXTRA_DIST += $(top_srcdir)/build-aux/gnupload
+
+## end gnulib module gnupload
+
+## begin gnulib module gperf
+
+GPERF = gperf
+V_GPERF = $(V_GPERF_@AM_V@)
+V_GPERF_ = $(V_GPERF_@AM_DEFAULT_V@)
+V_GPERF_0 = @echo " GPERF " $@;
+
+## end gnulib module gperf
+
## begin gnulib module group-member
-EXTRA_DIST += group-member.c group-member.h
+EXTRA_DIST += lib/group-member.c
-EXTRA_libcoreutils_a_SOURCES += group-member.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/group-member.c
## end gnulib module group-member
## begin gnulib module hard-locale
+lib_libcoreutils_a_SOURCES += lib/hard-locale.c
-EXTRA_DIST += hard-locale.c hard-locale.h
-
-EXTRA_libcoreutils_a_SOURCES += hard-locale.c
+EXTRA_DIST += lib/hard-locale.h
## end gnulib module hard-locale
## begin gnulib module hash
+lib_libcoreutils_a_SOURCES += lib/hash.c
-EXTRA_DIST += hash.c hash.h
-
-EXTRA_libcoreutils_a_SOURCES += hash.c
+EXTRA_DIST += lib/hash.h
## end gnulib module hash
## begin gnulib module hash-pjw
-libcoreutils_a_SOURCES += hash-pjw.h hash-pjw.c
+lib_libcoreutils_a_SOURCES += lib/hash-pjw.h lib/hash-pjw.c
## end gnulib module hash-pjw
-## begin gnulib module human
+## begin gnulib module hash-triple
+
+lib_libcoreutils_a_SOURCES += lib/hash-triple.c
+
+EXTRA_DIST += lib/hash-triple.h
+
+## end gnulib module hash-triple
+
+## begin gnulib module havelib
-EXTRA_DIST += human.c human.h
+EXTRA_DIST += $(top_srcdir)/build-aux/config.rpath
-EXTRA_libcoreutils_a_SOURCES += human.c
+## end gnulib module havelib
+
+## begin gnulib module heap
+
+lib_libcoreutils_a_SOURCES += lib/heap.c lib/heap.h
+
+## end gnulib module heap
+
+## begin gnulib module human
+
+lib_libcoreutils_a_SOURCES += lib/human.c
+
+EXTRA_DIST += lib/human.h
## end gnulib module human
## begin gnulib module i-ring
+lib_libcoreutils_a_SOURCES += lib/i-ring.c
-EXTRA_DIST += i-ring.c i-ring.h
-
-EXTRA_libcoreutils_a_SOURCES += i-ring.c
+EXTRA_DIST += lib/i-ring.h
## end gnulib module i-ring
-## begin gnulib module idcache
+## begin gnulib module iconv-h
+BUILT_SOURCES += $(ICONV_H)
-EXTRA_DIST += idcache.c
+# We need the following in order to create <iconv.h> when the system
+# doesn't have one that works with the given compiler.
+if GL_GENERATE_ICONV_H
+lib/iconv.h: lib/iconv.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(ARG_NONNULL_H) $(WARN_ON_USE_H)
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */' && \
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_ICONV_H''@|$(NEXT_ICONV_H)|g' \
+ -e 's/@''GNULIB_ICONV''@/$(GNULIB_ICONV)/g' \
+ -e 's|@''ICONV_CONST''@|$(ICONV_CONST)|g' \
+ -e 's|@''REPLACE_ICONV''@|$(REPLACE_ICONV)|g' \
+ -e 's|@''REPLACE_ICONV_OPEN''@|$(REPLACE_ICONV_OPEN)|g' \
+ -e 's|@''REPLACE_ICONV_UTF''@|$(REPLACE_ICONV_UTF)|g' \
+ -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
+ -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
+ -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
+ < $(top_srcdir)/lib/iconv.in.h; \
+ } > $@-t && \
+ mv $@-t $@
+else
+lib/iconv.h: $(top_builddir)/config.status
+ rm -f $@
+endif
+MOSTLYCLEANFILES += lib/iconv.h lib/iconv.h-t
+
+EXTRA_DIST += lib/iconv.in.h
+
+## end gnulib module iconv-h
+
+## begin gnulib module iconv_open
+
+lib/iconv_open-aix.h: lib/iconv_open-aix.gperf
+ $(V_GPERF)$(GPERF) -m 10 $(top_srcdir)/lib/iconv_open-aix.gperf > $(top_srcdir)/lib/iconv_open-aix.h-t && \
+ mv $(top_srcdir)/lib/iconv_open-aix.h-t $(top_srcdir)/lib/iconv_open-aix.h
+lib/iconv_open-hpux.h: lib/iconv_open-hpux.gperf
+ $(V_GPERF)$(GPERF) -m 10 $(top_srcdir)/lib/iconv_open-hpux.gperf > $(top_srcdir)/lib/iconv_open-hpux.h-t && \
+ mv $(top_srcdir)/lib/iconv_open-hpux.h-t $(top_srcdir)/lib/iconv_open-hpux.h
+lib/iconv_open-irix.h: lib/iconv_open-irix.gperf
+ $(V_GPERF)$(GPERF) -m 10 $(top_srcdir)/lib/iconv_open-irix.gperf > $(top_srcdir)/lib/iconv_open-irix.h-t && \
+ mv $(top_srcdir)/lib/iconv_open-irix.h-t $(top_srcdir)/lib/iconv_open-irix.h
+lib/iconv_open-osf.h: lib/iconv_open-osf.gperf
+ $(V_GPERF)$(GPERF) -m 10 $(top_srcdir)/lib/iconv_open-osf.gperf > $(top_srcdir)/lib/iconv_open-osf.h-t && \
+ mv $(top_srcdir)/lib/iconv_open-osf.h-t $(top_srcdir)/lib/iconv_open-osf.h
+lib/iconv_open-solaris.h: lib/iconv_open-solaris.gperf
+ $(V_GPERF)$(GPERF) -m 10 $(top_srcdir)/lib/iconv_open-solaris.gperf > $(top_srcdir)/lib/iconv_open-solaris.h-t && \
+ mv $(top_srcdir)/lib/iconv_open-solaris.h-t $(top_srcdir)/lib/iconv_open-solaris.h
+BUILT_SOURCES += lib/iconv_open-aix.h lib/iconv_open-hpux.h lib/iconv_open-irix.h lib/iconv_open-osf.h lib/iconv_open-solaris.h
+MOSTLYCLEANFILES += lib/iconv_open-aix.h-t lib/iconv_open-hpux.h-t lib/iconv_open-irix.h-t lib/iconv_open-osf.h-t lib/iconv_open-solaris.h-t
+MAINTAINERCLEANFILES += lib/iconv_open-aix.h lib/iconv_open-hpux.h lib/iconv_open-irix.h lib/iconv_open-osf.h lib/iconv_open-solaris.h
+EXTRA_DIST += lib/iconv_open-aix.h lib/iconv_open-hpux.h lib/iconv_open-irix.h lib/iconv_open-osf.h lib/iconv_open-solaris.h
+
+EXTRA_DIST += lib/iconv.c lib/iconv_close.c lib/iconv_open-aix.gperf lib/iconv_open-hpux.gperf lib/iconv_open-irix.gperf lib/iconv_open-osf.gperf lib/iconv_open-solaris.gperf lib/iconv_open.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/iconv.c lib/iconv_close.c lib/iconv_open.c
+
+## end gnulib module iconv_open
+
+## begin gnulib module idcache
-EXTRA_libcoreutils_a_SOURCES += idcache.c
+lib_libcoreutils_a_SOURCES += lib/idcache.c
+
+EXTRA_DIST += lib/idcache.h
## end gnulib module idcache
+## begin gnulib module ignore-value
+
+
+EXTRA_DIST += lib/ignore-value.h
+
+## end gnulib module ignore-value
+
## begin gnulib module inet_ntop
-EXTRA_DIST += inet_ntop.c inet_ntop.h
+EXTRA_DIST += lib/inet_ntop.c
-EXTRA_libcoreutils_a_SOURCES += inet_ntop.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/inet_ntop.c
## end gnulib module inet_ntop
+## begin gnulib module ino-map
+
+lib_libcoreutils_a_SOURCES += lib/ino-map.c lib/ino-map.h
+
+## end gnulib module ino-map
+
## begin gnulib module intprops
-EXTRA_DIST += intprops.h
+EXTRA_DIST += lib/intprops.h
## end gnulib module intprops
## begin gnulib module inttostr
+lib_libcoreutils_a_SOURCES += lib/imaxtostr.c lib/inttostr.c lib/offtostr.c lib/uinttostr.c lib/umaxtostr.c
-EXTRA_DIST += imaxtostr.c inttostr.c inttostr.h offtostr.c uinttostr.c umaxtostr.c
+EXTRA_DIST += lib/anytostr.c lib/inttostr.h
-EXTRA_libcoreutils_a_SOURCES += imaxtostr.c inttostr.c offtostr.c uinttostr.c umaxtostr.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/anytostr.c
## end gnulib module inttostr
-## begin gnulib module inttypes
+## begin gnulib module inttypes-incomplete
-BUILT_SOURCES += $(INTTYPES_H)
+BUILT_SOURCES += lib/inttypes.h
# We need the following in order to create <inttypes.h> when the system
# doesn't have one that works with the given compiler.
-inttypes.h: inttypes_.h
- rm -f $@-t $@
+lib/inttypes.h: lib/inttypes.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(WARN_ON_USE_H) $(ARG_NONNULL_H)
+ $(AM_V_GEN)rm -f $@-t $@ && \
{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
sed -e 's/@''HAVE_INTTYPES_H''@/$(HAVE_INTTYPES_H)/g' \
- -e 's|@''ABSOLUTE_INTTYPES_H''@|$(ABSOLUTE_INTTYPES_H)|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_INTTYPES_H''@|$(NEXT_INTTYPES_H)|g' \
-e 's/@''PRI_MACROS_BROKEN''@/$(PRI_MACROS_BROKEN)/g' \
+ -e 's/@''APPLE_UNIVERSAL_BUILD''@/$(APPLE_UNIVERSAL_BUILD)/g' \
-e 's/@''HAVE_LONG_LONG_INT''@/$(HAVE_LONG_LONG_INT)/g' \
-e 's/@''HAVE_UNSIGNED_LONG_LONG_INT''@/$(HAVE_UNSIGNED_LONG_LONG_INT)/g' \
-e 's/@''PRIPTR_PREFIX''@/$(PRIPTR_PREFIX)/g' \
@@ -844,56 +1731,166 @@ inttypes.h: inttypes_.h
-e 's/@''HAVE_DECL_IMAXDIV''@/$(HAVE_DECL_IMAXDIV)/g' \
-e 's/@''HAVE_DECL_STRTOIMAX''@/$(HAVE_DECL_STRTOIMAX)/g' \
-e 's/@''HAVE_DECL_STRTOUMAX''@/$(HAVE_DECL_STRTOUMAX)/g' \
- -e '/definition of GL_LINK_WARNING/r $(LINK_WARNING_H)' \
- < $(srcdir)/inttypes_.h; \
- } > $@-t
+ -e 's/@''REPLACE_STRTOIMAX''@/$(REPLACE_STRTOIMAX)/g' \
+ -e 's/@''REPLACE_STRTOUMAX''@/$(REPLACE_STRTOUMAX)/g' \
+ -e 's/@''INT32_MAX_LT_INTMAX_MAX''@/$(INT32_MAX_LT_INTMAX_MAX)/g' \
+ -e 's/@''INT64_MAX_EQ_LONG_MAX''@/$(INT64_MAX_EQ_LONG_MAX)/g' \
+ -e 's/@''UINT32_MAX_LT_UINTMAX_MAX''@/$(UINT32_MAX_LT_UINTMAX_MAX)/g' \
+ -e 's/@''UINT64_MAX_EQ_ULONG_MAX''@/$(UINT64_MAX_EQ_ULONG_MAX)/g' \
+ -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
+ -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
+ -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
+ < $(top_srcdir)/lib/inttypes.in.h; \
+ } > $@-t && \
mv $@-t $@
-MOSTLYCLEANFILES += inttypes.h inttypes.h-t
+MOSTLYCLEANFILES += lib/inttypes.h lib/inttypes.h-t
-EXTRA_DIST += inttypes_.h
+EXTRA_DIST += lib/inttypes.in.h
-## end gnulib module inttypes
+## end gnulib module inttypes-incomplete
## begin gnulib module isapipe
-EXTRA_DIST += isapipe.c isapipe.h
+EXTRA_DIST += lib/isapipe.c lib/isapipe.h
-EXTRA_libcoreutils_a_SOURCES += isapipe.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/isapipe.c
## end gnulib module isapipe
-## begin gnulib module lchmod
+## begin gnulib module isatty
+
+
+EXTRA_DIST += lib/isatty.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/isatty.c
+
+## end gnulib module isatty
+
+## begin gnulib module isblank
+
+
+EXTRA_DIST += lib/isblank.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/isblank.c
+
+## end gnulib module isblank
+
+## begin gnulib module isnand-nolibm
+
+
+EXTRA_DIST += lib/float+.h lib/isnan.c lib/isnand-nolibm.h lib/isnand.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/isnan.c lib/isnand.c
+
+## end gnulib module isnand-nolibm
+
+## begin gnulib module isnanf-nolibm
+
+
+EXTRA_DIST += lib/float+.h lib/isnan.c lib/isnanf-nolibm.h lib/isnanf.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/isnan.c lib/isnanf.c
+
+## end gnulib module isnanf-nolibm
+
+## begin gnulib module isnanl-nolibm
+
+
+EXTRA_DIST += lib/float+.h lib/isnan.c lib/isnanl-nolibm.h lib/isnanl.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/isnan.c lib/isnanl.c
+## end gnulib module isnanl-nolibm
-EXTRA_DIST += lchmod.h
+## begin gnulib module iswblank
-## end gnulib module lchmod
+
+EXTRA_DIST += lib/iswblank.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/iswblank.c
+
+## end gnulib module iswblank
+
+## begin gnulib module langinfo
+
+BUILT_SOURCES += lib/langinfo.h
+
+# We need the following in order to create an empty placeholder for
+# <langinfo.h> when the system doesn't have one.
+lib/langinfo.h: lib/langinfo.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(WARN_ON_USE_H)
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''HAVE_LANGINFO_H''@|$(HAVE_LANGINFO_H)|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_LANGINFO_H''@|$(NEXT_LANGINFO_H)|g' \
+ -e 's/@''GNULIB_NL_LANGINFO''@/$(GNULIB_NL_LANGINFO)/g' \
+ -e 's|@''HAVE_LANGINFO_CODESET''@|$(HAVE_LANGINFO_CODESET)|g' \
+ -e 's|@''HAVE_LANGINFO_T_FMT_AMPM''@|$(HAVE_LANGINFO_T_FMT_AMPM)|g' \
+ -e 's|@''HAVE_LANGINFO_ERA''@|$(HAVE_LANGINFO_ERA)|g' \
+ -e 's|@''HAVE_LANGINFO_YESEXPR''@|$(HAVE_LANGINFO_YESEXPR)|g' \
+ -e 's|@''HAVE_NL_LANGINFO''@|$(HAVE_NL_LANGINFO)|g' \
+ -e 's|@''REPLACE_NL_LANGINFO''@|$(REPLACE_NL_LANGINFO)|g' \
+ -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
+ -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
+ < $(top_srcdir)/lib/langinfo.in.h; \
+ } > $@-t && \
+ mv $@-t $@
+MOSTLYCLEANFILES += lib/langinfo.h lib/langinfo.h-t
+
+EXTRA_DIST += lib/langinfo.in.h
+
+## end gnulib module langinfo
## begin gnulib module lchown
-EXTRA_DIST += lchown.c lchown.h
+EXTRA_DIST += lib/lchown.c
-EXTRA_libcoreutils_a_SOURCES += lchown.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/lchown.c
## end gnulib module lchown
+## begin gnulib module ldtoastr
+
+lib_libcoreutils_a_SOURCES += lib/ldtoastr.c
+
+EXTRA_DIST += lib/ftoastr.c lib/ftoastr.h
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/ftoastr.c
+
+## end gnulib module ldtoastr
+
## begin gnulib module linebuffer
-libcoreutils_a_SOURCES += linebuffer.h linebuffer.c
+lib_libcoreutils_a_SOURCES += lib/linebuffer.h lib/linebuffer.c
## end gnulib module linebuffer
-## begin gnulib module link-warning
+## begin gnulib module link
+
+
+EXTRA_DIST += lib/link.c
-LINK_WARNING_H=$(top_srcdir)/build-aux/link-warning.h
+EXTRA_lib_libcoreutils_a_SOURCES += lib/link.c
-## end gnulib module link-warning
+## end gnulib module link
+
+## begin gnulib module linkat
+
+
+EXTRA_DIST += lib/at-func2.c lib/linkat.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/at-func2.c lib/linkat.c
+
+## end gnulib module linkat
## begin gnulib module localcharset
-libcoreutils_a_SOURCES += localcharset.h localcharset.c
+lib_libcoreutils_a_SOURCES += lib/localcharset.h lib/localcharset.c
# We need the following in order to install a simple file in $(libdir)
# which is shared with other installed packages. We use a list of referencing
@@ -902,27 +1899,43 @@ libcoreutils_a_SOURCES += localcharset.h localcharset.c
# On systems with glibc-2.1 or newer, the file is redundant, therefore we
# avoid installing it.
-all-local: charset.alias ref-add.sed ref-del.sed
+all-local: lib/charset.alias lib/ref-add.sed lib/ref-del.sed
charset_alias = $(DESTDIR)$(libdir)/charset.alias
charset_tmp = $(DESTDIR)$(libdir)/charset.tmp
-install-exec-local: all-local
- test $(GLIBC21) != no || $(mkinstalldirs) $(DESTDIR)$(libdir)
+install-exec-local: install-exec-localcharset
+install-exec-localcharset: all-local
+ if test $(GLIBC21) = no; then \
+ case '$(host_os)' in \
+ darwin[56]*) \
+ need_charset_alias=true ;; \
+ darwin* | cygwin* | mingw* | pw32* | cegcc*) \
+ need_charset_alias=false ;; \
+ *) \
+ need_charset_alias=true ;; \
+ esac ; \
+ else \
+ need_charset_alias=false ; \
+ fi ; \
+ if $$need_charset_alias; then \
+ $(mkinstalldirs) $(DESTDIR)$(libdir) ; \
+ fi ; \
if test -f $(charset_alias); then \
- sed -f ref-add.sed $(charset_alias) > $(charset_tmp) ; \
+ sed -f lib/ref-add.sed $(charset_alias) > $(charset_tmp) ; \
$(INSTALL_DATA) $(charset_tmp) $(charset_alias) ; \
rm -f $(charset_tmp) ; \
else \
- if test $(GLIBC21) = no; then \
- sed -f ref-add.sed charset.alias > $(charset_tmp) ; \
+ if $$need_charset_alias; then \
+ sed -f lib/ref-add.sed lib/charset.alias > $(charset_tmp) ; \
$(INSTALL_DATA) $(charset_tmp) $(charset_alias) ; \
rm -f $(charset_tmp) ; \
fi ; \
fi
-uninstall-local: all-local
+uninstall-local: uninstall-localcharset
+uninstall-localcharset: all-local
if test -f $(charset_alias); then \
- sed -f ref-del.sed $(charset_alias) > $(charset_tmp); \
+ sed -f lib/ref-del.sed $(charset_alias) > $(charset_tmp); \
if grep '^# Packages using this file: $$' $(charset_tmp) \
> /dev/null; then \
rm -f $(charset_alias); \
@@ -932,605 +1945,1763 @@ uninstall-local: all-local
rm -f $(charset_tmp); \
fi
-charset.alias: config.charset
- rm -f t-$@ $@
- $(SHELL) $(srcdir)/config.charset '$(host)' > t-$@
- mv t-$@ $@
+lib/charset.alias: lib/config.charset
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ $(SHELL) $(top_srcdir)/lib/config.charset '$(host)' > $@-t && \
+ mv $@-t $@
-SUFFIXES += .sed .sin
+# SUFFIXES += .sed .sin
.sin.sed:
- rm -f t-$@ $@
- sed -e '/^#/d' -e 's/@''PACKAGE''@/$(PACKAGE)/g' $< > t-$@
- mv t-$@ $@
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ sed -e '/^#/d' -e 's/@''PACKAGE''@/$(PACKAGE)/g' $< > $@-t && \
+ mv $@-t $@
-CLEANFILES += charset.alias ref-add.sed ref-del.sed
+CLEANFILES += lib/charset.alias lib/ref-add.sed lib/ref-del.sed
-EXTRA_DIST += config.charset ref-add.sin ref-del.sin
+EXTRA_DIST += lib/config.charset lib/ref-add.sin lib/ref-del.sin
## end gnulib module localcharset
-## begin gnulib module long-options
+## begin gnulib module locale
+
+BUILT_SOURCES += lib/locale.h
+
+# We need the following in order to create <locale.h> when the system
+# doesn't have one that provides all definitions.
+lib/locale.h: lib/locale.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(ARG_NONNULL_H) $(WARN_ON_USE_H)
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */' && \
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_LOCALE_H''@|$(NEXT_LOCALE_H)|g' \
+ -e 's/@''GNULIB_LOCALECONV''@/$(GNULIB_LOCALECONV)/g' \
+ -e 's/@''GNULIB_SETLOCALE''@/$(GNULIB_SETLOCALE)/g' \
+ -e 's/@''GNULIB_DUPLOCALE''@/$(GNULIB_DUPLOCALE)/g' \
+ -e 's|@''HAVE_DUPLOCALE''@|$(HAVE_DUPLOCALE)|g' \
+ -e 's|@''HAVE_XLOCALE_H''@|$(HAVE_XLOCALE_H)|g' \
+ -e 's|@''REPLACE_LOCALECONV''@|$(REPLACE_LOCALECONV)|g' \
+ -e 's|@''REPLACE_SETLOCALE''@|$(REPLACE_SETLOCALE)|g' \
+ -e 's|@''REPLACE_DUPLOCALE''@|$(REPLACE_DUPLOCALE)|g' \
+ -e 's|@''REPLACE_STRUCT_LCONV''@|$(REPLACE_STRUCT_LCONV)|g' \
+ -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
+ -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
+ -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
+ < $(top_srcdir)/lib/locale.in.h; \
+ } > $@-t && \
+ mv $@-t $@
+MOSTLYCLEANFILES += lib/locale.h lib/locale.h-t
+
+EXTRA_DIST += lib/locale.in.h
+
+## end gnulib module locale
+
+## begin gnulib module localeconv
+
+
+EXTRA_DIST += lib/localeconv.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/localeconv.c
-EXTRA_DIST += long-options.c long-options.h
+## end gnulib module localeconv
-EXTRA_libcoreutils_a_SOURCES += long-options.c
+## begin gnulib module lock
+
+lib_libcoreutils_a_SOURCES += lib/glthread/lock.h lib/glthread/lock.c
+
+## end gnulib module lock
+
+## begin gnulib module long-options
+
+lib_libcoreutils_a_SOURCES += lib/long-options.c
+
+EXTRA_DIST += lib/long-options.h
## end gnulib module long-options
+## begin gnulib module lseek
+
+
+EXTRA_DIST += lib/lseek.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/lseek.c
+
+## end gnulib module lseek
+
## begin gnulib module lstat
-EXTRA_DIST += lstat.c lstat.h
+EXTRA_DIST += lib/lstat.c
-EXTRA_libcoreutils_a_SOURCES += lstat.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/lstat.c
## end gnulib module lstat
-## begin gnulib module malloc
+## begin gnulib module maintainer-makefile
+
+EXTRA_DIST += $(top_srcdir)/maint.mk
+
+## end gnulib module maintainer-makefile
+
+## begin gnulib module malloc-gnu
+
+
+EXTRA_DIST += lib/malloc.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/malloc.c
+
+## end gnulib module malloc-gnu
+## begin gnulib module malloc-posix
-EXTRA_DIST += malloc.c
-EXTRA_libcoreutils_a_SOURCES += malloc.c
+EXTRA_DIST += lib/malloc.c
-## end gnulib module malloc
+EXTRA_lib_libcoreutils_a_SOURCES += lib/malloc.c
+
+## end gnulib module malloc-posix
+
+## begin gnulib module malloca
+
+lib_libcoreutils_a_SOURCES += lib/malloca.c
+
+EXTRA_DIST += lib/malloca.h lib/malloca.valgrind
+
+## end gnulib module malloca
+
+## begin gnulib module math
+
+BUILT_SOURCES += lib/math.h
+lib_libcoreutils_a_SOURCES += lib/math.c
+
+# We need the following in order to create <math.h> when the system
+# doesn't have one that works with the given compiler.
+lib/math.h: lib/math.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(ARG_NONNULL_H) $(WARN_ON_USE_H)
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */' && \
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''INCLUDE_NEXT_AS_FIRST_DIRECTIVE''@|$(INCLUDE_NEXT_AS_FIRST_DIRECTIVE)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_AS_FIRST_DIRECTIVE_MATH_H''@|$(NEXT_AS_FIRST_DIRECTIVE_MATH_H)|g' \
+ -e 's/@''GNULIB_ACOSF''@/$(GNULIB_ACOSF)/g' \
+ -e 's/@''GNULIB_ACOSL''@/$(GNULIB_ACOSL)/g' \
+ -e 's/@''GNULIB_ASINF''@/$(GNULIB_ASINF)/g' \
+ -e 's/@''GNULIB_ASINL''@/$(GNULIB_ASINL)/g' \
+ -e 's/@''GNULIB_ATANF''@/$(GNULIB_ATANF)/g' \
+ -e 's/@''GNULIB_ATANL''@/$(GNULIB_ATANL)/g' \
+ -e 's/@''GNULIB_ATAN2F''@/$(GNULIB_ATAN2F)/g' \
+ -e 's/@''GNULIB_CBRT''@/$(GNULIB_CBRT)/g' \
+ -e 's/@''GNULIB_CBRTF''@/$(GNULIB_CBRTF)/g' \
+ -e 's/@''GNULIB_CBRTL''@/$(GNULIB_CBRTL)/g' \
+ -e 's/@''GNULIB_CEIL''@/$(GNULIB_CEIL)/g' \
+ -e 's/@''GNULIB_CEILF''@/$(GNULIB_CEILF)/g' \
+ -e 's/@''GNULIB_CEILL''@/$(GNULIB_CEILL)/g' \
+ -e 's/@''GNULIB_COPYSIGN''@/$(GNULIB_COPYSIGN)/g' \
+ -e 's/@''GNULIB_COPYSIGNF''@/$(GNULIB_COPYSIGNF)/g' \
+ -e 's/@''GNULIB_COPYSIGNL''@/$(GNULIB_COPYSIGNL)/g' \
+ -e 's/@''GNULIB_COSF''@/$(GNULIB_COSF)/g' \
+ -e 's/@''GNULIB_COSL''@/$(GNULIB_COSL)/g' \
+ -e 's/@''GNULIB_COSHF''@/$(GNULIB_COSHF)/g' \
+ -e 's/@''GNULIB_EXPF''@/$(GNULIB_EXPF)/g' \
+ -e 's/@''GNULIB_EXPL''@/$(GNULIB_EXPL)/g' \
+ -e 's/@''GNULIB_EXP2''@/$(GNULIB_EXP2)/g' \
+ -e 's/@''GNULIB_EXP2F''@/$(GNULIB_EXP2F)/g' \
+ -e 's/@''GNULIB_EXP2L''@/$(GNULIB_EXP2L)/g' \
+ -e 's/@''GNULIB_EXPM1''@/$(GNULIB_EXPM1)/g' \
+ -e 's/@''GNULIB_EXPM1F''@/$(GNULIB_EXPM1F)/g' \
+ -e 's/@''GNULIB_EXPM1L''@/$(GNULIB_EXPM1L)/g' \
+ -e 's/@''GNULIB_FABSF''@/$(GNULIB_FABSF)/g' \
+ -e 's/@''GNULIB_FABSL''@/$(GNULIB_FABSL)/g' \
+ -e 's/@''GNULIB_FLOOR''@/$(GNULIB_FLOOR)/g' \
+ -e 's/@''GNULIB_FLOORF''@/$(GNULIB_FLOORF)/g' \
+ -e 's/@''GNULIB_FLOORL''@/$(GNULIB_FLOORL)/g' \
+ -e 's/@''GNULIB_FMA''@/$(GNULIB_FMA)/g' \
+ -e 's/@''GNULIB_FMAF''@/$(GNULIB_FMAF)/g' \
+ -e 's/@''GNULIB_FMAL''@/$(GNULIB_FMAL)/g' \
+ -e 's/@''GNULIB_FMOD''@/$(GNULIB_FMOD)/g' \
+ -e 's/@''GNULIB_FMODF''@/$(GNULIB_FMODF)/g' \
+ -e 's/@''GNULIB_FMODL''@/$(GNULIB_FMODL)/g' \
+ -e 's/@''GNULIB_FREXPF''@/$(GNULIB_FREXPF)/g' \
+ -e 's/@''GNULIB_FREXP''@/$(GNULIB_FREXP)/g' \
+ -e 's/@''GNULIB_FREXPL''@/$(GNULIB_FREXPL)/g' \
+ -e 's/@''GNULIB_HYPOT''@/$(GNULIB_HYPOT)/g' \
+ -e 's/@''GNULIB_HYPOTF''@/$(GNULIB_HYPOTF)/g' \
+ -e 's/@''GNULIB_HYPOTL''@/$(GNULIB_HYPOTL)/g' \
+ < $(top_srcdir)/lib/math.in.h | \
+ sed -e 's/@''GNULIB_ILOGB''@/$(GNULIB_ILOGB)/g' \
+ -e 's/@''GNULIB_ILOGBF''@/$(GNULIB_ILOGBF)/g' \
+ -e 's/@''GNULIB_ILOGBL''@/$(GNULIB_ILOGBL)/g' \
+ -e 's/@''GNULIB_ISFINITE''@/$(GNULIB_ISFINITE)/g' \
+ -e 's/@''GNULIB_ISINF''@/$(GNULIB_ISINF)/g' \
+ -e 's/@''GNULIB_ISNAN''@/$(GNULIB_ISNAN)/g' \
+ -e 's/@''GNULIB_ISNANF''@/$(GNULIB_ISNANF)/g' \
+ -e 's/@''GNULIB_ISNAND''@/$(GNULIB_ISNAND)/g' \
+ -e 's/@''GNULIB_ISNANL''@/$(GNULIB_ISNANL)/g' \
+ -e 's/@''GNULIB_LDEXPF''@/$(GNULIB_LDEXPF)/g' \
+ -e 's/@''GNULIB_LDEXPL''@/$(GNULIB_LDEXPL)/g' \
+ -e 's/@''GNULIB_LOG''@/$(GNULIB_LOG)/g' \
+ -e 's/@''GNULIB_LOGF''@/$(GNULIB_LOGF)/g' \
+ -e 's/@''GNULIB_LOGL''@/$(GNULIB_LOGL)/g' \
+ -e 's/@''GNULIB_LOG10''@/$(GNULIB_LOG10)/g' \
+ -e 's/@''GNULIB_LOG10F''@/$(GNULIB_LOG10F)/g' \
+ -e 's/@''GNULIB_LOG10L''@/$(GNULIB_LOG10L)/g' \
+ -e 's/@''GNULIB_LOG1P''@/$(GNULIB_LOG1P)/g' \
+ -e 's/@''GNULIB_LOG1PF''@/$(GNULIB_LOG1PF)/g' \
+ -e 's/@''GNULIB_LOG1PL''@/$(GNULIB_LOG1PL)/g' \
+ -e 's/@''GNULIB_LOG2''@/$(GNULIB_LOG2)/g' \
+ -e 's/@''GNULIB_LOG2F''@/$(GNULIB_LOG2F)/g' \
+ -e 's/@''GNULIB_LOG2L''@/$(GNULIB_LOG2L)/g' \
+ -e 's/@''GNULIB_LOGB''@/$(GNULIB_LOGB)/g' \
+ -e 's/@''GNULIB_LOGBF''@/$(GNULIB_LOGBF)/g' \
+ -e 's/@''GNULIB_LOGBL''@/$(GNULIB_LOGBL)/g' \
+ -e 's/@''GNULIB_MODF''@/$(GNULIB_MODF)/g' \
+ -e 's/@''GNULIB_MODFF''@/$(GNULIB_MODFF)/g' \
+ -e 's/@''GNULIB_MODFL''@/$(GNULIB_MODFL)/g' \
+ -e 's/@''GNULIB_POWF''@/$(GNULIB_POWF)/g' \
+ -e 's/@''GNULIB_REMAINDER''@/$(GNULIB_REMAINDER)/g' \
+ -e 's/@''GNULIB_REMAINDERF''@/$(GNULIB_REMAINDERF)/g' \
+ -e 's/@''GNULIB_REMAINDERL''@/$(GNULIB_REMAINDERL)/g' \
+ -e 's/@''GNULIB_RINT''@/$(GNULIB_RINT)/g' \
+ -e 's/@''GNULIB_RINTF''@/$(GNULIB_RINTF)/g' \
+ -e 's/@''GNULIB_RINTL''@/$(GNULIB_RINTL)/g' \
+ -e 's/@''GNULIB_ROUND''@/$(GNULIB_ROUND)/g' \
+ -e 's/@''GNULIB_ROUNDF''@/$(GNULIB_ROUNDF)/g' \
+ -e 's/@''GNULIB_ROUNDL''@/$(GNULIB_ROUNDL)/g' \
+ -e 's/@''GNULIB_SIGNBIT''@/$(GNULIB_SIGNBIT)/g' \
+ -e 's/@''GNULIB_SINF''@/$(GNULIB_SINF)/g' \
+ -e 's/@''GNULIB_SINL''@/$(GNULIB_SINL)/g' \
+ -e 's/@''GNULIB_SINHF''@/$(GNULIB_SINHF)/g' \
+ -e 's/@''GNULIB_SQRTF''@/$(GNULIB_SQRTF)/g' \
+ -e 's/@''GNULIB_SQRTL''@/$(GNULIB_SQRTL)/g' \
+ -e 's/@''GNULIB_TANF''@/$(GNULIB_TANF)/g' \
+ -e 's/@''GNULIB_TANL''@/$(GNULIB_TANL)/g' \
+ -e 's/@''GNULIB_TANHF''@/$(GNULIB_TANHF)/g' \
+ -e 's/@''GNULIB_TRUNC''@/$(GNULIB_TRUNC)/g' \
+ -e 's/@''GNULIB_TRUNCF''@/$(GNULIB_TRUNCF)/g' \
+ -e 's/@''GNULIB_TRUNCL''@/$(GNULIB_TRUNCL)/g' \
+ | \
+ sed -e 's|@''HAVE_ACOSF''@|$(HAVE_ACOSF)|g' \
+ -e 's|@''HAVE_ACOSL''@|$(HAVE_ACOSL)|g' \
+ -e 's|@''HAVE_ASINF''@|$(HAVE_ASINF)|g' \
+ -e 's|@''HAVE_ASINL''@|$(HAVE_ASINL)|g' \
+ -e 's|@''HAVE_ATANF''@|$(HAVE_ATANF)|g' \
+ -e 's|@''HAVE_ATANL''@|$(HAVE_ATANL)|g' \
+ -e 's|@''HAVE_ATAN2F''@|$(HAVE_ATAN2F)|g' \
+ -e 's|@''HAVE_CBRT''@|$(HAVE_CBRT)|g' \
+ -e 's|@''HAVE_CBRTF''@|$(HAVE_CBRTF)|g' \
+ -e 's|@''HAVE_CBRTL''@|$(HAVE_CBRTL)|g' \
+ -e 's|@''HAVE_COPYSIGN''@|$(HAVE_COPYSIGN)|g' \
+ -e 's|@''HAVE_COPYSIGNL''@|$(HAVE_COPYSIGNL)|g' \
+ -e 's|@''HAVE_COSF''@|$(HAVE_COSF)|g' \
+ -e 's|@''HAVE_COSL''@|$(HAVE_COSL)|g' \
+ -e 's|@''HAVE_COSHF''@|$(HAVE_COSHF)|g' \
+ -e 's|@''HAVE_EXPF''@|$(HAVE_EXPF)|g' \
+ -e 's|@''HAVE_EXPL''@|$(HAVE_EXPL)|g' \
+ -e 's|@''HAVE_EXPM1''@|$(HAVE_EXPM1)|g' \
+ -e 's|@''HAVE_EXPM1F''@|$(HAVE_EXPM1F)|g' \
+ -e 's|@''HAVE_FABSF''@|$(HAVE_FABSF)|g' \
+ -e 's|@''HAVE_FABSL''@|$(HAVE_FABSL)|g' \
+ -e 's|@''HAVE_FMA''@|$(HAVE_FMA)|g' \
+ -e 's|@''HAVE_FMAF''@|$(HAVE_FMAF)|g' \
+ -e 's|@''HAVE_FMAL''@|$(HAVE_FMAL)|g' \
+ -e 's|@''HAVE_FMODF''@|$(HAVE_FMODF)|g' \
+ -e 's|@''HAVE_FMODL''@|$(HAVE_FMODL)|g' \
+ -e 's|@''HAVE_FREXPF''@|$(HAVE_FREXPF)|g' \
+ -e 's|@''HAVE_HYPOTF''@|$(HAVE_HYPOTF)|g' \
+ -e 's|@''HAVE_HYPOTL''@|$(HAVE_HYPOTL)|g' \
+ -e 's|@''HAVE_ILOGB''@|$(HAVE_ILOGB)|g' \
+ -e 's|@''HAVE_ILOGBF''@|$(HAVE_ILOGBF)|g' \
+ -e 's|@''HAVE_ILOGBL''@|$(HAVE_ILOGBL)|g' \
+ -e 's|@''HAVE_ISNANF''@|$(HAVE_ISNANF)|g' \
+ -e 's|@''HAVE_ISNAND''@|$(HAVE_ISNAND)|g' \
+ -e 's|@''HAVE_ISNANL''@|$(HAVE_ISNANL)|g' \
+ -e 's|@''HAVE_LDEXPF''@|$(HAVE_LDEXPF)|g' \
+ -e 's|@''HAVE_LOGF''@|$(HAVE_LOGF)|g' \
+ -e 's|@''HAVE_LOGL''@|$(HAVE_LOGL)|g' \
+ -e 's|@''HAVE_LOG10F''@|$(HAVE_LOG10F)|g' \
+ -e 's|@''HAVE_LOG10L''@|$(HAVE_LOG10L)|g' \
+ -e 's|@''HAVE_LOG1P''@|$(HAVE_LOG1P)|g' \
+ -e 's|@''HAVE_LOG1PF''@|$(HAVE_LOG1PF)|g' \
+ -e 's|@''HAVE_LOG1PL''@|$(HAVE_LOG1PL)|g' \
+ -e 's|@''HAVE_LOGBF''@|$(HAVE_LOGBF)|g' \
+ -e 's|@''HAVE_LOGBL''@|$(HAVE_LOGBL)|g' \
+ -e 's|@''HAVE_MODFF''@|$(HAVE_MODFF)|g' \
+ -e 's|@''HAVE_MODFL''@|$(HAVE_MODFL)|g' \
+ -e 's|@''HAVE_POWF''@|$(HAVE_POWF)|g' \
+ -e 's|@''HAVE_REMAINDER''@|$(HAVE_REMAINDER)|g' \
+ -e 's|@''HAVE_REMAINDERF''@|$(HAVE_REMAINDERF)|g' \
+ -e 's|@''HAVE_RINT''@|$(HAVE_RINT)|g' \
+ -e 's|@''HAVE_RINTL''@|$(HAVE_RINTL)|g' \
+ -e 's|@''HAVE_SINF''@|$(HAVE_SINF)|g' \
+ -e 's|@''HAVE_SINL''@|$(HAVE_SINL)|g' \
+ -e 's|@''HAVE_SINHF''@|$(HAVE_SINHF)|g' \
+ -e 's|@''HAVE_SQRTF''@|$(HAVE_SQRTF)|g' \
+ -e 's|@''HAVE_SQRTL''@|$(HAVE_SQRTL)|g' \
+ -e 's|@''HAVE_TANF''@|$(HAVE_TANF)|g' \
+ -e 's|@''HAVE_TANL''@|$(HAVE_TANL)|g' \
+ -e 's|@''HAVE_TANHF''@|$(HAVE_TANHF)|g' \
+ -e 's|@''HAVE_DECL_ACOSL''@|$(HAVE_DECL_ACOSL)|g' \
+ -e 's|@''HAVE_DECL_ASINL''@|$(HAVE_DECL_ASINL)|g' \
+ -e 's|@''HAVE_DECL_ATANL''@|$(HAVE_DECL_ATANL)|g' \
+ -e 's|@''HAVE_DECL_CBRTF''@|$(HAVE_DECL_CBRTF)|g' \
+ -e 's|@''HAVE_DECL_CBRTL''@|$(HAVE_DECL_CBRTL)|g' \
+ -e 's|@''HAVE_DECL_CEILF''@|$(HAVE_DECL_CEILF)|g' \
+ -e 's|@''HAVE_DECL_CEILL''@|$(HAVE_DECL_CEILL)|g' \
+ -e 's|@''HAVE_DECL_COPYSIGNF''@|$(HAVE_DECL_COPYSIGNF)|g' \
+ -e 's|@''HAVE_DECL_COSL''@|$(HAVE_DECL_COSL)|g' \
+ -e 's|@''HAVE_DECL_EXPL''@|$(HAVE_DECL_EXPL)|g' \
+ -e 's|@''HAVE_DECL_EXP2''@|$(HAVE_DECL_EXP2)|g' \
+ -e 's|@''HAVE_DECL_EXP2F''@|$(HAVE_DECL_EXP2F)|g' \
+ -e 's|@''HAVE_DECL_EXP2L''@|$(HAVE_DECL_EXP2L)|g' \
+ -e 's|@''HAVE_DECL_EXPM1L''@|$(HAVE_DECL_EXPM1L)|g' \
+ -e 's|@''HAVE_DECL_FLOORF''@|$(HAVE_DECL_FLOORF)|g' \
+ -e 's|@''HAVE_DECL_FLOORL''@|$(HAVE_DECL_FLOORL)|g' \
+ -e 's|@''HAVE_DECL_FREXPL''@|$(HAVE_DECL_FREXPL)|g' \
+ -e 's|@''HAVE_DECL_LDEXPL''@|$(HAVE_DECL_LDEXPL)|g' \
+ -e 's|@''HAVE_DECL_LOGL''@|$(HAVE_DECL_LOGL)|g' \
+ -e 's|@''HAVE_DECL_LOG10L''@|$(HAVE_DECL_LOG10L)|g' \
+ -e 's|@''HAVE_DECL_LOG2''@|$(HAVE_DECL_LOG2)|g' \
+ -e 's|@''HAVE_DECL_LOG2F''@|$(HAVE_DECL_LOG2F)|g' \
+ -e 's|@''HAVE_DECL_LOG2L''@|$(HAVE_DECL_LOG2L)|g' \
+ -e 's|@''HAVE_DECL_LOGB''@|$(HAVE_DECL_LOGB)|g' \
+ -e 's|@''HAVE_DECL_REMAINDER''@|$(HAVE_DECL_REMAINDER)|g' \
+ -e 's|@''HAVE_DECL_REMAINDERL''@|$(HAVE_DECL_REMAINDERL)|g' \
+ -e 's|@''HAVE_DECL_RINTF''@|$(HAVE_DECL_RINTF)|g' \
+ -e 's|@''HAVE_DECL_ROUND''@|$(HAVE_DECL_ROUND)|g' \
+ -e 's|@''HAVE_DECL_ROUNDF''@|$(HAVE_DECL_ROUNDF)|g' \
+ -e 's|@''HAVE_DECL_ROUNDL''@|$(HAVE_DECL_ROUNDL)|g' \
+ -e 's|@''HAVE_DECL_SINL''@|$(HAVE_DECL_SINL)|g' \
+ -e 's|@''HAVE_DECL_SQRTL''@|$(HAVE_DECL_SQRTL)|g' \
+ -e 's|@''HAVE_DECL_TANL''@|$(HAVE_DECL_TANL)|g' \
+ -e 's|@''HAVE_DECL_TRUNC''@|$(HAVE_DECL_TRUNC)|g' \
+ -e 's|@''HAVE_DECL_TRUNCF''@|$(HAVE_DECL_TRUNCF)|g' \
+ -e 's|@''HAVE_DECL_TRUNCL''@|$(HAVE_DECL_TRUNCL)|g' \
+ | \
+ sed -e 's|@''REPLACE_CBRTF''@|$(REPLACE_CBRTF)|g' \
+ -e 's|@''REPLACE_CBRTL''@|$(REPLACE_CBRTL)|g' \
+ -e 's|@''REPLACE_CEIL''@|$(REPLACE_CEIL)|g' \
+ -e 's|@''REPLACE_CEILF''@|$(REPLACE_CEILF)|g' \
+ -e 's|@''REPLACE_CEILL''@|$(REPLACE_CEILL)|g' \
+ -e 's|@''REPLACE_EXPM1''@|$(REPLACE_EXPM1)|g' \
+ -e 's|@''REPLACE_EXPM1F''@|$(REPLACE_EXPM1F)|g' \
+ -e 's|@''REPLACE_EXP2''@|$(REPLACE_EXP2)|g' \
+ -e 's|@''REPLACE_EXP2L''@|$(REPLACE_EXP2L)|g' \
+ -e 's|@''REPLACE_FABSL''@|$(REPLACE_FABSL)|g' \
+ -e 's|@''REPLACE_FLOOR''@|$(REPLACE_FLOOR)|g' \
+ -e 's|@''REPLACE_FLOORF''@|$(REPLACE_FLOORF)|g' \
+ -e 's|@''REPLACE_FLOORL''@|$(REPLACE_FLOORL)|g' \
+ -e 's|@''REPLACE_FMA''@|$(REPLACE_FMA)|g' \
+ -e 's|@''REPLACE_FMAF''@|$(REPLACE_FMAF)|g' \
+ -e 's|@''REPLACE_FMAL''@|$(REPLACE_FMAL)|g' \
+ -e 's|@''REPLACE_FMOD''@|$(REPLACE_FMOD)|g' \
+ -e 's|@''REPLACE_FMODF''@|$(REPLACE_FMODF)|g' \
+ -e 's|@''REPLACE_FMODL''@|$(REPLACE_FMODL)|g' \
+ -e 's|@''REPLACE_FREXPF''@|$(REPLACE_FREXPF)|g' \
+ -e 's|@''REPLACE_FREXP''@|$(REPLACE_FREXP)|g' \
+ -e 's|@''REPLACE_FREXPL''@|$(REPLACE_FREXPL)|g' \
+ -e 's|@''REPLACE_HUGE_VAL''@|$(REPLACE_HUGE_VAL)|g' \
+ -e 's|@''REPLACE_HYPOT''@|$(REPLACE_HYPOT)|g' \
+ -e 's|@''REPLACE_HYPOTF''@|$(REPLACE_HYPOTF)|g' \
+ -e 's|@''REPLACE_HYPOTL''@|$(REPLACE_HYPOTL)|g' \
+ -e 's|@''REPLACE_ILOGB''@|$(REPLACE_ILOGB)|g' \
+ -e 's|@''REPLACE_ILOGBF''@|$(REPLACE_ILOGBF)|g' \
+ -e 's|@''REPLACE_ISFINITE''@|$(REPLACE_ISFINITE)|g' \
+ -e 's|@''REPLACE_ISINF''@|$(REPLACE_ISINF)|g' \
+ -e 's|@''REPLACE_ISNAN''@|$(REPLACE_ISNAN)|g' \
+ -e 's|@''REPLACE_ITOLD''@|$(REPLACE_ITOLD)|g' \
+ -e 's|@''REPLACE_LDEXPL''@|$(REPLACE_LDEXPL)|g' \
+ -e 's|@''REPLACE_LOG''@|$(REPLACE_LOG)|g' \
+ -e 's|@''REPLACE_LOGF''@|$(REPLACE_LOGF)|g' \
+ -e 's|@''REPLACE_LOGL''@|$(REPLACE_LOGL)|g' \
+ -e 's|@''REPLACE_LOG10''@|$(REPLACE_LOG10)|g' \
+ -e 's|@''REPLACE_LOG10F''@|$(REPLACE_LOG10F)|g' \
+ -e 's|@''REPLACE_LOG10L''@|$(REPLACE_LOG10L)|g' \
+ -e 's|@''REPLACE_LOG1P''@|$(REPLACE_LOG1P)|g' \
+ -e 's|@''REPLACE_LOG1PF''@|$(REPLACE_LOG1PF)|g' \
+ -e 's|@''REPLACE_LOG1PL''@|$(REPLACE_LOG1PL)|g' \
+ -e 's|@''REPLACE_LOG2''@|$(REPLACE_LOG2)|g' \
+ -e 's|@''REPLACE_LOG2F''@|$(REPLACE_LOG2F)|g' \
+ -e 's|@''REPLACE_LOG2L''@|$(REPLACE_LOG2L)|g' \
+ -e 's|@''REPLACE_LOGB''@|$(REPLACE_LOGB)|g' \
+ -e 's|@''REPLACE_LOGBF''@|$(REPLACE_LOGBF)|g' \
+ -e 's|@''REPLACE_LOGBL''@|$(REPLACE_LOGBL)|g' \
+ -e 's|@''REPLACE_MODF''@|$(REPLACE_MODF)|g' \
+ -e 's|@''REPLACE_MODFF''@|$(REPLACE_MODFF)|g' \
+ -e 's|@''REPLACE_MODFL''@|$(REPLACE_MODFL)|g' \
+ -e 's|@''REPLACE_NAN''@|$(REPLACE_NAN)|g' \
+ -e 's|@''REPLACE_REMAINDER''@|$(REPLACE_REMAINDER)|g' \
+ -e 's|@''REPLACE_REMAINDERF''@|$(REPLACE_REMAINDERF)|g' \
+ -e 's|@''REPLACE_REMAINDERL''@|$(REPLACE_REMAINDERL)|g' \
+ -e 's|@''REPLACE_ROUND''@|$(REPLACE_ROUND)|g' \
+ -e 's|@''REPLACE_ROUNDF''@|$(REPLACE_ROUNDF)|g' \
+ -e 's|@''REPLACE_ROUNDL''@|$(REPLACE_ROUNDL)|g' \
+ -e 's|@''REPLACE_SIGNBIT''@|$(REPLACE_SIGNBIT)|g' \
+ -e 's|@''REPLACE_SIGNBIT_USING_GCC''@|$(REPLACE_SIGNBIT_USING_GCC)|g' \
+ -e 's|@''REPLACE_SQRTL''@|$(REPLACE_SQRTL)|g' \
+ -e 's|@''REPLACE_TRUNC''@|$(REPLACE_TRUNC)|g' \
+ -e 's|@''REPLACE_TRUNCF''@|$(REPLACE_TRUNCF)|g' \
+ -e 's|@''REPLACE_TRUNCL''@|$(REPLACE_TRUNCL)|g' \
+ -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
+ -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
+ -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)'; \
+ } > $@-t && \
+ mv $@-t $@
+MOSTLYCLEANFILES += lib/math.h lib/math.h-t
+
+EXTRA_DIST += lib/math.in.h
+
+## end gnulib module math
## begin gnulib module mbchar
-libcoreutils_a_SOURCES += mbchar.c
+lib_libcoreutils_a_SOURCES += lib/mbchar.c
-EXTRA_DIST += mbchar.h
+EXTRA_DIST += lib/mbchar.h
## end gnulib module mbchar
+## begin gnulib module mbiter
+
+lib_libcoreutils_a_SOURCES += lib/mbiter.h lib/mbiter.c
+
+## end gnulib module mbiter
+
+## begin gnulib module mbrlen
+
+
+EXTRA_DIST += lib/mbrlen.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/mbrlen.c
+
+## end gnulib module mbrlen
+
+## begin gnulib module mbrtowc
+
+
+EXTRA_DIST += lib/mbrtowc.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/mbrtowc.c
+
+## end gnulib module mbrtowc
+
+## begin gnulib module mbsalign
+
+lib_libcoreutils_a_SOURCES += lib/mbsalign.c lib/mbsalign.h
+
+## end gnulib module mbsalign
+
## begin gnulib module mbscasecmp
-libcoreutils_a_SOURCES += mbscasecmp.c
+lib_libcoreutils_a_SOURCES += lib/mbscasecmp.c
## end gnulib module mbscasecmp
-## begin gnulib module mbswidth
+## begin gnulib module mbsinit
-libcoreutils_a_SOURCES += mbswidth.h mbswidth.c
-## end gnulib module mbswidth
+EXTRA_DIST += lib/mbsinit.c
-## begin gnulib module mbuiter
+EXTRA_lib_libcoreutils_a_SOURCES += lib/mbsinit.c
-libcoreutils_a_SOURCES += mbuiter.h
+## end gnulib module mbsinit
-## end gnulib module mbuiter
+## begin gnulib module mbslen
-## begin gnulib module md5
+lib_libcoreutils_a_SOURCES += lib/mbslen.c
+## end gnulib module mbslen
-EXTRA_DIST += md5.c md5.h
+## begin gnulib module mbsrtowcs
-EXTRA_libcoreutils_a_SOURCES += md5.c
-## end gnulib module md5
+EXTRA_DIST += lib/mbsrtowcs-impl.h lib/mbsrtowcs-state.c lib/mbsrtowcs.c
-## begin gnulib module memcasecmp
+EXTRA_lib_libcoreutils_a_SOURCES += lib/mbsrtowcs-state.c lib/mbsrtowcs.c
+## end gnulib module mbsrtowcs
-EXTRA_DIST += memcasecmp.c memcasecmp.h
+## begin gnulib module mbsstr
-EXTRA_libcoreutils_a_SOURCES += memcasecmp.c
+lib_libcoreutils_a_SOURCES += lib/mbsstr.c
-## end gnulib module memcasecmp
+EXTRA_DIST += lib/str-kmp.h
-## begin gnulib module memchr
+## end gnulib module mbsstr
+## begin gnulib module mbswidth
-EXTRA_DIST += memchr.c
+lib_libcoreutils_a_SOURCES += lib/mbswidth.h lib/mbswidth.c
-EXTRA_libcoreutils_a_SOURCES += memchr.c
+## end gnulib module mbswidth
-## end gnulib module memchr
+## begin gnulib module mbtowc
-## begin gnulib module memcmp
+EXTRA_DIST += lib/mbtowc-impl.h lib/mbtowc.c
-EXTRA_DIST += memcmp.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/mbtowc.c
-EXTRA_libcoreutils_a_SOURCES += memcmp.c
+## end gnulib module mbtowc
-## end gnulib module memcmp
+## begin gnulib module mbuiter
-## begin gnulib module memcoll
+lib_libcoreutils_a_SOURCES += lib/mbuiter.h lib/mbuiter.c
+## end gnulib module mbuiter
+
+## begin gnulib module memcasecmp
-EXTRA_DIST += memcoll.c memcoll.h
+lib_libcoreutils_a_SOURCES += lib/memcasecmp.c
-EXTRA_libcoreutils_a_SOURCES += memcoll.c
+EXTRA_DIST += lib/memcasecmp.h
-## end gnulib module memcoll
+## end gnulib module memcasecmp
+
+## begin gnulib module memchr
+
+
+EXTRA_DIST += lib/memchr.c lib/memchr.valgrind
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/memchr.c
+
+## end gnulib module memchr
+
+## begin gnulib module memchr2
-## begin gnulib module memcpy
+lib_libcoreutils_a_SOURCES += lib/memchr2.h lib/memchr2.c
+EXTRA_DIST += lib/memchr2.valgrind
-EXTRA_DIST += memcpy.c
+## end gnulib module memchr2
-EXTRA_libcoreutils_a_SOURCES += memcpy.c
+## begin gnulib module memcmp2
-## end gnulib module memcpy
+lib_libcoreutils_a_SOURCES += lib/memcmp2.c
-## begin gnulib module memmove
+EXTRA_DIST += lib/memcmp2.h
+## end gnulib module memcmp2
-EXTRA_DIST += memmove.c
+## begin gnulib module memcoll
+
+lib_libcoreutils_a_SOURCES += lib/memcoll.c
-EXTRA_libcoreutils_a_SOURCES += memmove.c
+EXTRA_DIST += lib/memcoll.h
-## end gnulib module memmove
+## end gnulib module memcoll
## begin gnulib module mempcpy
-EXTRA_DIST += mempcpy.c
+EXTRA_DIST += lib/mempcpy.c
-EXTRA_libcoreutils_a_SOURCES += mempcpy.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/mempcpy.c
## end gnulib module mempcpy
## begin gnulib module memrchr
-EXTRA_DIST += memrchr.c
+EXTRA_DIST += lib/memrchr.c
-EXTRA_libcoreutils_a_SOURCES += memrchr.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/memrchr.c
## end gnulib module memrchr
-## begin gnulib module memset
+## begin gnulib module mgetgroups
+lib_libcoreutils_a_SOURCES += lib/mgetgroups.c
-EXTRA_DIST += memset.c
+EXTRA_DIST += lib/mgetgroups.h
-EXTRA_libcoreutils_a_SOURCES += memset.c
-
-## end gnulib module memset
+## end gnulib module mgetgroups
## begin gnulib module mkancesdirs
+lib_libcoreutils_a_SOURCES += lib/mkancesdirs.c
-EXTRA_DIST += mkancesdirs.c mkancesdirs.h
-
-EXTRA_libcoreutils_a_SOURCES += mkancesdirs.c
+EXTRA_DIST += lib/mkancesdirs.h
## end gnulib module mkancesdirs
## begin gnulib module mkdir
-EXTRA_DIST += mkdir.c
+EXTRA_DIST += lib/mkdir.c
-EXTRA_libcoreutils_a_SOURCES += mkdir.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/mkdir.c
## end gnulib module mkdir
## begin gnulib module mkdir-p
+lib_libcoreutils_a_SOURCES += lib/dirchownmod.c lib/mkdir-p.c
-EXTRA_DIST += dirchownmod.c dirchownmod.h mkdir-p.c mkdir-p.h
-
-EXTRA_libcoreutils_a_SOURCES += dirchownmod.c mkdir-p.c
+EXTRA_DIST += lib/dirchownmod.h lib/mkdir-p.h
## end gnulib module mkdir-p
+## begin gnulib module mkfifo
+
+
+EXTRA_DIST += lib/mkfifo.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/mkfifo.c
+
+## end gnulib module mkfifo
+
+## begin gnulib module mknod
+
+
+EXTRA_DIST += lib/mknod.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/mknod.c
+
+## end gnulib module mknod
+
## begin gnulib module mkstemp
-EXTRA_DIST += mkstemp.c
+EXTRA_DIST += lib/mkstemp.c
-EXTRA_libcoreutils_a_SOURCES += mkstemp.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/mkstemp.c
## end gnulib module mkstemp
## begin gnulib module mktime
-EXTRA_DIST += mktime.c
+EXTRA_DIST += lib/mktime-internal.h lib/mktime.c
-EXTRA_libcoreutils_a_SOURCES += mktime.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/mktime.c
## end gnulib module mktime
-## begin gnulib module modechange
+## begin gnulib module mktime-internal
-EXTRA_DIST += modechange.c modechange.h
+EXTRA_DIST += lib/mktime-internal.h lib/mktime.c
-EXTRA_libcoreutils_a_SOURCES += modechange.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/mktime.c
+
+## end gnulib module mktime-internal
+
+## begin gnulib module modechange
+
+lib_libcoreutils_a_SOURCES += lib/modechange.c
+
+EXTRA_DIST += lib/modechange.h
## end gnulib module modechange
## begin gnulib module mountlist
-EXTRA_DIST += mountlist.c mountlist.h
+EXTRA_DIST += lib/mountlist.c lib/mountlist.h
-EXTRA_libcoreutils_a_SOURCES += mountlist.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/mountlist.c
## end gnulib module mountlist
## begin gnulib module mpsort
+lib_libcoreutils_a_SOURCES += lib/mpsort.c
-EXTRA_DIST += mpsort.c mpsort.h
-
-EXTRA_libcoreutils_a_SOURCES += mpsort.c
+EXTRA_DIST += lib/mpsort.h
## end gnulib module mpsort
+## begin gnulib module msvc-inval
+
+
+EXTRA_DIST += lib/msvc-inval.c lib/msvc-inval.h
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/msvc-inval.c
+
+## end gnulib module msvc-inval
+
+## begin gnulib module msvc-nothrow
+
+
+EXTRA_DIST += lib/msvc-nothrow.c lib/msvc-nothrow.h
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/msvc-nothrow.c
+
+## end gnulib module msvc-nothrow
+
## begin gnulib module nanosleep
-EXTRA_DIST += nanosleep.c
+EXTRA_DIST += lib/nanosleep.c
-EXTRA_libcoreutils_a_SOURCES += nanosleep.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/nanosleep.c
## end gnulib module nanosleep
+## begin gnulib module netdb
+
+BUILT_SOURCES += lib/netdb.h
+
+# We need the following in order to create <netdb.h> when the system
+# doesn't have one that works with the given compiler.
+lib/netdb.h: lib/netdb.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(ARG_NONNULL_H) $(WARN_ON_USE_H)
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_NETDB_H''@|$(NEXT_NETDB_H)|g' \
+ -e 's|@''HAVE_NETDB_H''@|$(HAVE_NETDB_H)|g' \
+ -e 's/@''GNULIB_GETADDRINFO''@/$(GNULIB_GETADDRINFO)/g' \
+ -e 's|@''HAVE_STRUCT_ADDRINFO''@|$(HAVE_STRUCT_ADDRINFO)|g' \
+ -e 's|@''HAVE_DECL_FREEADDRINFO''@|$(HAVE_DECL_FREEADDRINFO)|g' \
+ -e 's|@''HAVE_DECL_GAI_STRERROR''@|$(HAVE_DECL_GAI_STRERROR)|g' \
+ -e 's|@''HAVE_DECL_GETADDRINFO''@|$(HAVE_DECL_GETADDRINFO)|g' \
+ -e 's|@''HAVE_DECL_GETNAMEINFO''@|$(HAVE_DECL_GETNAMEINFO)|g' \
+ -e 's|@''REPLACE_GAI_STRERROR''@|$(REPLACE_GAI_STRERROR)|g' \
+ -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
+ -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
+ -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
+ < $(top_srcdir)/lib/netdb.in.h; \
+ } > $@-t && \
+ mv $@-t $@
+MOSTLYCLEANFILES += lib/netdb.h lib/netdb.h-t
+
+EXTRA_DIST += lib/netdb.in.h
+
+## end gnulib module netdb
+
## begin gnulib module netinet_in
BUILT_SOURCES += $(NETINET_IN_H)
# We need the following in order to create <netinet/in.h> when the system
# doesn't have one.
-netinet/in.h:
- @MKDIR_P@ netinet
- rm -f $@-t $@
+if GL_GENERATE_NETINET_IN_H
+lib/netinet/in.h: lib/netinet_in.in.h $(top_builddir)/config.status
+ $(AM_V_at)$(MKDIR_P) lib/netinet
+ $(AM_V_GEN)rm -f $@-t $@ && \
{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
- sed -e 's|@''ABSOLUTE_NETINET_IN_H''@|$(ABSOLUTE_NETINET_IN_H)|g' \
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_NETINET_IN_H''@|$(NEXT_NETINET_IN_H)|g' \
-e 's|@''HAVE_NETINET_IN_H''@|$(HAVE_NETINET_IN_H)|g' \
- < $(srcdir)/netinet_in_.h; \
- } > $@-t
+ < $(top_srcdir)/lib/netinet_in.in.h; \
+ } > $@-t && \
mv $@-t $@
-MOSTLYCLEANFILES += netinet/in.h netinet/in.h-t
-MOSTLYCLEANDIRS += netinet
+else
+lib/netinet/in.h: $(top_builddir)/config.status
+ rm -f $@
+endif
+MOSTLYCLEANFILES += lib/netinet/in.h lib/netinet/in.h-t
+MOSTLYCLEANDIRS += lib/netinet
-EXTRA_DIST += netinet_in_.h
+EXTRA_DIST += lib/netinet_in.in.h
## end gnulib module netinet_in
+## begin gnulib module nl_langinfo
+
+
+EXTRA_DIST += lib/nl_langinfo.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/nl_langinfo.c
+
+## end gnulib module nl_langinfo
+
+## begin gnulib module non-recursive-gnulib-prefix-hack
+
+
+EXTRA_DIST += $(top_srcdir)/build-aux/prefix-gnulib-mk
+
+## end gnulib module non-recursive-gnulib-prefix-hack
+
+## begin gnulib module nproc
+
+lib_libcoreutils_a_SOURCES += lib/nproc.c
+
+EXTRA_DIST += lib/nproc.h
+
+## end gnulib module nproc
+
## begin gnulib module obstack
-EXTRA_DIST += obstack.c obstack.h
+EXTRA_DIST += lib/obstack.c lib/obstack.h
-EXTRA_libcoreutils_a_SOURCES += obstack.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/obstack.c
## end gnulib module obstack
+## begin gnulib module open
+
+
+EXTRA_DIST += lib/open.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/open.c
+
+## end gnulib module open
+
## begin gnulib module openat
-EXTRA_DIST += at-func.c fchmodat.c fchownat.c fstatat.c mkdirat.c openat-die.c openat-priv.h openat-proc.c openat.c openat.h
+EXTRA_DIST += lib/openat.c
-EXTRA_libcoreutils_a_SOURCES += at-func.c fchmodat.c fchownat.c fstatat.c mkdirat.c openat-die.c openat-proc.c openat.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/openat.c
## end gnulib module openat
+## begin gnulib module openat-die
+
+lib_libcoreutils_a_SOURCES += lib/openat-die.c
+
+## end gnulib module openat-die
+
+## begin gnulib module openat-h
+
+
+EXTRA_DIST += lib/openat.h
+
+## end gnulib module openat-h
+
+## begin gnulib module openat-safer
+
+lib_libcoreutils_a_SOURCES += lib/openat-safer.c
+
+EXTRA_DIST += lib/fcntl--.h lib/fcntl-safer.h
+
+## end gnulib module openat-safer
+
+## begin gnulib module opendir
+
+
+EXTRA_DIST += lib/dirent-private.h lib/opendir.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/opendir.c
+
+## end gnulib module opendir
+
+## begin gnulib module parse-datetime
+
+# This rule overrides the Automake generated .y.c rule, to ensure that the
+# parse-datetime.c file gets generated in the source directory, not in the
+# build directory.
+lib/parse-datetime.c: lib/parse-datetime.y
+ $(AM_V_GEN)$(SHELL) $(YLWRAP) $(top_srcdir)/lib/parse-datetime.y \
+ y.tab.c parse-datetime.c \
+ y.tab.h parse-datetime.h \
+ y.output parse-datetime.output \
+ -- $(YACC) $(YFLAGS) $(AM_YFLAGS) && \
+ mv parse-datetime.c parse-datetime.c-t && \
+ mv parse-datetime.c-t $(top_srcdir)/lib/parse-datetime.c
+lib_libcoreutils_a_SOURCES += lib/parse-datetime.y
+BUILT_SOURCES += lib/parse-datetime.c
+MOSTLYCLEANFILES += lib/parse-datetime.c-t
+MAINTAINERCLEANFILES += lib/parse-datetime.c
+EXTRA_DIST += lib/parse-datetime.c
+
+EXTRA_DIST += lib/parse-datetime.h
+
+## end gnulib module parse-datetime
+
## begin gnulib module pathmax
-EXTRA_DIST += pathmax.h
+EXTRA_DIST += lib/pathmax.h
## end gnulib module pathmax
## begin gnulib module physmem
+lib_libcoreutils_a_SOURCES += lib/physmem.c
-EXTRA_DIST += physmem.c physmem.h
-
-EXTRA_libcoreutils_a_SOURCES += physmem.c
+EXTRA_DIST += lib/physmem.h
## end gnulib module physmem
-## begin gnulib module posixtm
+## begin gnulib module pipe-posix
+
+EXTRA_DIST += lib/pipe.c
-EXTRA_DIST += posixtm.c posixtm.h
+EXTRA_lib_libcoreutils_a_SOURCES += lib/pipe.c
-EXTRA_libcoreutils_a_SOURCES += posixtm.c
+## end gnulib module pipe-posix
+
+## begin gnulib module posix-shell
+
+##Sample usage of posix-shell module:
+#script: script.in
+# rm -f $@-t $@
+# sed -e 's#@''PREFERABLY_POSIX_SHELL''@#$(PREFERABLY_POSIX_SHELL)#g' \
+# -e 's#@''POSIX_SHELL''@#$(POSIX_SHELL)#g' \
+# -e $(top_srcdir)/lib/$@.in >$@-t
+# chmod a+x $@-t
+# mv $@-t $@
+#EXTRA_DIST += script.in
+#MOSTLYCLEANFILES += script script-t
+
+## end gnulib module posix-shell
+
+## begin gnulib module posixtm
+
+lib_libcoreutils_a_SOURCES += lib/posixtm.c
+
+EXTRA_DIST += lib/posixtm.h
## end gnulib module posixtm
## begin gnulib module posixver
+lib_libcoreutils_a_SOURCES += lib/posixver.c
-EXTRA_DIST += posixver.c posixver.h
-
-EXTRA_libcoreutils_a_SOURCES += posixver.c
+EXTRA_DIST += lib/posixver.h
## end gnulib module posixver
+## begin gnulib module printf-frexp
+
+lib_libcoreutils_a_SOURCES += lib/printf-frexp.c
+
+EXTRA_DIST += lib/printf-frexp.h
+
+## end gnulib module printf-frexp
+
+## begin gnulib module printf-frexpl
+
+lib_libcoreutils_a_SOURCES += lib/printf-frexpl.c
+
+EXTRA_DIST += lib/printf-frexp.c lib/printf-frexpl.h
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/printf-frexp.c
+
+## end gnulib module printf-frexpl
+
+## begin gnulib module priv-set
+
+lib_libcoreutils_a_SOURCES += lib/priv-set.c
+
+EXTRA_DIST += lib/priv-set.h
+
+## end gnulib module priv-set
+
+## begin gnulib module progname
+
+lib_libcoreutils_a_SOURCES += lib/progname.h lib/progname.c
+
+## end gnulib module progname
+
+## begin gnulib module propername
+
+lib_libcoreutils_a_SOURCES += lib/propername.h lib/propername.c
+
+## end gnulib module propername
+
+## begin gnulib module pthread
+
+BUILT_SOURCES += $(PTHREAD_H)
+
+# We need the following in order to create <pthread.h> when the system
+# doesn't have one that works with the given compiler.
+if GL_GENERATE_PTHREAD_H
+lib/pthread.h: lib/pthread.in.h $(top_builddir)/config.status
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''HAVE_PTHREAD_H''@|$(HAVE_PTHREAD_H)|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_PTHREAD_H''@|$(NEXT_PTHREAD_H)|g' \
+ -e 's|@''HAVE_PTHREAD_T''@|$(HAVE_PTHREAD_T)|g' \
+ -e 's|@''HAVE_PTHREAD_SPINLOCK_T''@|$(HAVE_PTHREAD_SPINLOCK_T)|g' \
+ < $(top_srcdir)/lib/pthread.in.h; \
+ } > $@-t && \
+ mv $@-t $@
+else
+lib/pthread.h: $(top_builddir)/config.status
+ rm -f $@
+endif
+MOSTLYCLEANFILES += lib/pthread.h lib/pthread.h-t
+
+EXTRA_DIST += lib/pthread.c lib/pthread.in.h
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/pthread.c
+
+## end gnulib module pthread
+
## begin gnulib module putenv
-EXTRA_DIST += putenv.c
+EXTRA_DIST += lib/putenv.c
-EXTRA_libcoreutils_a_SOURCES += putenv.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/putenv.c
## end gnulib module putenv
-## begin gnulib module quote
+## begin gnulib module qcopy-acl
+
+lib_libcoreutils_a_SOURCES += lib/qcopy-acl.c
+
+## end gnulib module qcopy-acl
+## begin gnulib module qset-acl
-EXTRA_DIST += quote.c quote.h
+lib_libcoreutils_a_SOURCES += lib/qset-acl.c
-EXTRA_libcoreutils_a_SOURCES += quote.c
+## end gnulib module qset-acl
+
+## begin gnulib module quote
+
+
+EXTRA_DIST += lib/quote.h
## end gnulib module quote
## begin gnulib module quotearg
+lib_libcoreutils_a_SOURCES += lib/quotearg.c
-EXTRA_DIST += quotearg.c quotearg.h
-
-EXTRA_libcoreutils_a_SOURCES += quotearg.c
+EXTRA_DIST += lib/quote.h lib/quotearg.h
## end gnulib module quotearg
## begin gnulib module raise
-EXTRA_DIST += raise.c
+EXTRA_DIST += lib/raise.c
-EXTRA_libcoreutils_a_SOURCES += raise.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/raise.c
## end gnulib module raise
+## begin gnulib module randint
+
+lib_libcoreutils_a_SOURCES += lib/randint.c lib/randint.h
+
+## end gnulib module randint
+
+## begin gnulib module randperm
+
+lib_libcoreutils_a_SOURCES += lib/randperm.c lib/randperm.h
+
+## end gnulib module randperm
+
+## begin gnulib module randread
+
+lib_libcoreutils_a_SOURCES += lib/randread.c lib/randread.h lib/rand-isaac.c lib/rand-isaac.h
+
+## end gnulib module randread
+
+## begin gnulib module read
+
+
+EXTRA_DIST += lib/read.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/read.c
+
+## end gnulib module read
+
+## begin gnulib module read-file
+
+lib_libcoreutils_a_SOURCES += lib/read-file.c
+
+EXTRA_DIST += lib/read-file.h
+
+## end gnulib module read-file
+
+## begin gnulib module readdir
+
+
+EXTRA_DIST += lib/dirent-private.h lib/readdir.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/readdir.c
+
+## end gnulib module readdir
+
## begin gnulib module readlink
-EXTRA_DIST += readlink.c
+EXTRA_DIST += lib/readlink.c
-EXTRA_libcoreutils_a_SOURCES += readlink.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/readlink.c
## end gnulib module readlink
-## begin gnulib module readtokens
+## begin gnulib module readlinkat
+
+
+EXTRA_DIST += lib/at-func.c lib/readlinkat.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/at-func.c lib/readlinkat.c
+
+## end gnulib module readlinkat
+## begin gnulib module readtokens
-EXTRA_DIST += readtokens.c readtokens.h
+lib_libcoreutils_a_SOURCES += lib/readtokens.c
-EXTRA_libcoreutils_a_SOURCES += readtokens.c
+EXTRA_DIST += lib/readtokens.h
## end gnulib module readtokens
## begin gnulib module readtokens0
-libcoreutils_a_SOURCES += readtokens0.h readtokens0.c
+lib_libcoreutils_a_SOURCES += lib/readtokens0.h lib/readtokens0.c
## end gnulib module readtokens0
## begin gnulib module readutmp
-EXTRA_DIST += readutmp.c readutmp.h
+EXTRA_DIST += lib/readutmp.c lib/readutmp.h
-EXTRA_libcoreutils_a_SOURCES += readutmp.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/readutmp.c
## end gnulib module readutmp
-## begin gnulib module realloc
+## begin gnulib module realloc-gnu
+
+
+EXTRA_DIST += lib/realloc.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/realloc.c
+
+## end gnulib module realloc-gnu
+## begin gnulib module realloc-posix
-EXTRA_DIST += realloc.c
-EXTRA_libcoreutils_a_SOURCES += realloc.c
+EXTRA_DIST += lib/realloc.c
-## end gnulib module realloc
+EXTRA_lib_libcoreutils_a_SOURCES += lib/realloc.c
+
+## end gnulib module realloc-posix
## begin gnulib module regex
-EXTRA_DIST += regcomp.c regex.c regex.h regex_internal.c regex_internal.h regexec.c
+EXTRA_DIST += lib/regcomp.c lib/regex.c lib/regex.h lib/regex_internal.c lib/regex_internal.h lib/regexec.c
-EXTRA_libcoreutils_a_SOURCES += regcomp.c regex.c regex_internal.c regexec.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/regcomp.c lib/regex.c lib/regex_internal.c lib/regexec.c
## end gnulib module regex
+## begin gnulib module remove
+
+
+EXTRA_DIST += lib/remove.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/remove.c
+
+## end gnulib module remove
+
## begin gnulib module rename
-EXTRA_DIST += rename.c
+EXTRA_DIST += lib/rename.c
-EXTRA_libcoreutils_a_SOURCES += rename.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/rename.c
## end gnulib module rename
-## begin gnulib module rename-dest-slash
+## begin gnulib module rewinddir
-EXTRA_DIST += rename-dest-slash.c
+EXTRA_DIST += lib/dirent-private.h lib/rewinddir.c
-EXTRA_libcoreutils_a_SOURCES += rename-dest-slash.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/rewinddir.c
-## end gnulib module rename-dest-slash
+## end gnulib module rewinddir
## begin gnulib module rmdir
-EXTRA_DIST += rmdir.c
+EXTRA_DIST += lib/rmdir.c
-EXTRA_libcoreutils_a_SOURCES += rmdir.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/rmdir.c
## end gnulib module rmdir
## begin gnulib module root-dev-ino
+lib_libcoreutils_a_SOURCES += lib/root-dev-ino.c lib/root-dev-ino.h
-EXTRA_DIST += root-dev-ino.c root-dev-ino.h
+## end gnulib module root-dev-ino
-EXTRA_libcoreutils_a_SOURCES += root-dev-ino.c
+## begin gnulib module root-uid
-## end gnulib module root-dev-ino
+
+EXTRA_DIST += lib/root-uid.h
+
+## end gnulib module root-uid
## begin gnulib module rpmatch
-EXTRA_DIST += rpmatch.c
+EXTRA_DIST += lib/rpmatch.c
-EXTRA_libcoreutils_a_SOURCES += rpmatch.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/rpmatch.c
## end gnulib module rpmatch
## begin gnulib module safe-read
+lib_libcoreutils_a_SOURCES += lib/safe-read.c
-EXTRA_DIST += safe-read.c safe-read.h
-
-EXTRA_libcoreutils_a_SOURCES += safe-read.c
+EXTRA_DIST += lib/safe-read.h
## end gnulib module safe-read
## begin gnulib module safe-write
+lib_libcoreutils_a_SOURCES += lib/safe-write.c
-EXTRA_DIST += safe-write.c safe-write.h
+EXTRA_DIST += lib/safe-read.c lib/safe-write.h
-EXTRA_libcoreutils_a_SOURCES += safe-write.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/safe-read.c
## end gnulib module safe-write
## begin gnulib module same
+lib_libcoreutils_a_SOURCES += lib/same.c
-EXTRA_DIST += same.c same.h
-
-EXTRA_libcoreutils_a_SOURCES += same.c
+EXTRA_DIST += lib/same.h
## end gnulib module same
## begin gnulib module same-inode
-EXTRA_DIST += same-inode.h
+EXTRA_DIST += lib/same-inode.h
## end gnulib module same-inode
## begin gnulib module save-cwd
+lib_libcoreutils_a_SOURCES += lib/save-cwd.c
-EXTRA_DIST += save-cwd.c save-cwd.h
-
-EXTRA_libcoreutils_a_SOURCES += save-cwd.c
+EXTRA_DIST += lib/save-cwd.h
## end gnulib module save-cwd
## begin gnulib module savedir
+lib_libcoreutils_a_SOURCES += lib/savedir.c
-EXTRA_DIST += savedir.c savedir.h
-
-EXTRA_libcoreutils_a_SOURCES += savedir.c
+EXTRA_DIST += lib/savedir.h
## end gnulib module savedir
## begin gnulib module savewd
-libcoreutils_a_SOURCES += savewd.h savewd.c
+lib_libcoreutils_a_SOURCES += lib/savewd.h lib/savewd.c
## end gnulib module savewd
+## begin gnulib module sched
+
+BUILT_SOURCES += $(SCHED_H)
+
+# We need the following in order to create a replacement for <sched.h> when
+# the system doesn't have one.
+if GL_GENERATE_SCHED_H
+lib/sched.h: lib/sched.in.h $(top_builddir)/config.status
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''HAVE_SCHED_H''@|$(HAVE_SCHED_H)|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_SCHED_H''@|$(NEXT_SCHED_H)|g' \
+ -e 's|@''HAVE_STRUCT_SCHED_PARAM''@|$(HAVE_STRUCT_SCHED_PARAM)|g' \
+ < $(top_srcdir)/lib/sched.in.h; \
+ } > $@-t && \
+ mv $@-t $@
+else
+lib/sched.h: $(top_builddir)/config.status
+ rm -f $@
+endif
+MOSTLYCLEANFILES += lib/sched.h lib/sched.h-t
+
+EXTRA_DIST += lib/sched.in.h
+
+## end gnulib module sched
+
+## begin gnulib module secure_getenv
+
+
+EXTRA_DIST += lib/secure_getenv.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/secure_getenv.c
+
+## end gnulib module secure_getenv
+
+## begin gnulib module select
+
+
+EXTRA_DIST += lib/select.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/select.c
+
+## end gnulib module select
+
+## begin gnulib module selinux-at
+
+
+EXTRA_DIST += lib/at-func.c lib/selinux-at.c lib/selinux-at.h
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/at-func.c lib/selinux-at.c
+
+## end gnulib module selinux-at
+
+## begin gnulib module selinux-h
+
+lib_libcoreutils_a_SOURCES += lib/se-context.in.h lib/se-selinux.in.h lib/se-context.c lib/se-selinux.c
+
+BUILT_SOURCES += lib/selinux/selinux.h
+lib/selinux/selinux.h: lib/se-selinux.in.h $(top_builddir)/config.status $(UNUSED_PARAMETER_H)
+ $(AM_V_at)$(MKDIR_P) lib/selinux
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */' && \
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_SELINUX_SELINUX_H''@|$(NEXT_SELINUX_SELINUX_H)|g' \
+ -e '/definition of _GL_UNUSED_PARAMETER/r $(UNUSED_PARAMETER_H)' \
+ < $(top_srcdir)/lib/se-selinux.in.h; \
+ } > $@-t && \
+ chmod a-x $@-t && \
+ mv $@-t $@
+MOSTLYCLEANFILES += lib/selinux/selinux.h lib/selinux/selinux.h-t
+
+BUILT_SOURCES += $(SELINUX_CONTEXT_H)
+if GL_GENERATE_SELINUX_CONTEXT_H
+lib/selinux/context.h: lib/se-context.in.h $(top_builddir)/config.status $(UNUSED_PARAMETER_H)
+ $(AM_V_at)$(MKDIR_P) lib/selinux
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */' && \
+ sed -e '/definition of _GL_UNUSED_PARAMETER/r $(UNUSED_PARAMETER_H)' \
+ < $(top_srcdir)/lib/se-context.in.h; \
+ } > $@-t && \
+ chmod a-x $@-t && \
+ mv $@-t $@
+else
+lib/selinux/context.h: $(top_builddir)/config.status
+ rm -f $@
+endif
+MOSTLYCLEANFILES += lib/selinux/context.h lib/selinux/context.h-t
+MOSTLYCLEANDIRS += lib/selinux
+
+EXTRA_DIST += lib/getfilecon.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/getfilecon.c
+
+## end gnulib module selinux-h
+
## begin gnulib module setenv
-EXTRA_DIST += setenv.c setenv.h unsetenv.c
+EXTRA_DIST += lib/setenv.c
-EXTRA_libcoreutils_a_SOURCES += setenv.c unsetenv.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/setenv.c
## end gnulib module setenv
## begin gnulib module settime
+lib_libcoreutils_a_SOURCES += lib/settime.c
+
+## end gnulib module settime
+
+## begin gnulib module sig2str
-EXTRA_DIST += settime.c
-EXTRA_libcoreutils_a_SOURCES += settime.c
+EXTRA_DIST += lib/sig2str.c lib/sig2str.h
-## end gnulib module settime
+EXTRA_lib_libcoreutils_a_SOURCES += lib/sig2str.c
-## begin gnulib module sha1
+## end gnulib module sig2str
+## begin gnulib module sigaction
-EXTRA_DIST += sha1.c sha1.h
+lib_libcoreutils_a_SOURCES += lib/sig-handler.c
-EXTRA_libcoreutils_a_SOURCES += sha1.c
+EXTRA_DIST += lib/sig-handler.h lib/sigaction.c
-## end gnulib module sha1
+EXTRA_lib_libcoreutils_a_SOURCES += lib/sigaction.c
-## begin gnulib module sig2str
+## end gnulib module sigaction
+## begin gnulib module signal-h
-EXTRA_DIST += sig2str.c sig2str.h
+BUILT_SOURCES += lib/signal.h
-EXTRA_libcoreutils_a_SOURCES += sig2str.c
+# We need the following in order to create <signal.h> when the system
+# doesn't have a complete one.
+lib/signal.h: lib/signal.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(ARG_NONNULL_H) $(WARN_ON_USE_H)
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */' && \
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_SIGNAL_H''@|$(NEXT_SIGNAL_H)|g' \
+ -e 's|@''GNULIB_PTHREAD_SIGMASK''@|$(GNULIB_PTHREAD_SIGMASK)|g' \
+ -e 's|@''GNULIB_RAISE''@|$(GNULIB_RAISE)|g' \
+ -e 's/@''GNULIB_SIGNAL_H_SIGPIPE''@/$(GNULIB_SIGNAL_H_SIGPIPE)/g' \
+ -e 's/@''GNULIB_SIGPROCMASK''@/$(GNULIB_SIGPROCMASK)/g' \
+ -e 's/@''GNULIB_SIGACTION''@/$(GNULIB_SIGACTION)/g' \
+ -e 's|@''HAVE_POSIX_SIGNALBLOCKING''@|$(HAVE_POSIX_SIGNALBLOCKING)|g' \
+ -e 's|@''HAVE_PTHREAD_SIGMASK''@|$(HAVE_PTHREAD_SIGMASK)|g' \
+ -e 's|@''HAVE_RAISE''@|$(HAVE_RAISE)|g' \
+ -e 's|@''HAVE_SIGSET_T''@|$(HAVE_SIGSET_T)|g' \
+ -e 's|@''HAVE_SIGINFO_T''@|$(HAVE_SIGINFO_T)|g' \
+ -e 's|@''HAVE_SIGACTION''@|$(HAVE_SIGACTION)|g' \
+ -e 's|@''HAVE_STRUCT_SIGACTION_SA_SIGACTION''@|$(HAVE_STRUCT_SIGACTION_SA_SIGACTION)|g' \
+ -e 's|@''HAVE_TYPE_VOLATILE_SIG_ATOMIC_T''@|$(HAVE_TYPE_VOLATILE_SIG_ATOMIC_T)|g' \
+ -e 's|@''HAVE_SIGHANDLER_T''@|$(HAVE_SIGHANDLER_T)|g' \
+ -e 's|@''REPLACE_PTHREAD_SIGMASK''@|$(REPLACE_PTHREAD_SIGMASK)|g' \
+ -e 's|@''REPLACE_RAISE''@|$(REPLACE_RAISE)|g' \
+ -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
+ -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
+ -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
+ < $(top_srcdir)/lib/signal.in.h; \
+ } > $@-t && \
+ mv $@-t $@
+MOSTLYCLEANFILES += lib/signal.h lib/signal.h-t
-## end gnulib module sig2str
+EXTRA_DIST += lib/signal.in.h
+
+## end gnulib module signal-h
+
+## begin gnulib module signbit
+
+
+EXTRA_DIST += lib/float+.h lib/signbitd.c lib/signbitf.c lib/signbitl.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/signbitd.c lib/signbitf.c lib/signbitl.c
+
+## end gnulib module signbit
+
+## begin gnulib module sigprocmask
+
+
+EXTRA_DIST += lib/sigprocmask.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/sigprocmask.c
+
+## end gnulib module sigprocmask
+
+## begin gnulib module size_max
+
+lib_libcoreutils_a_SOURCES += lib/size_max.h
+
+## end gnulib module size_max
+
+## begin gnulib module smack
+
+lib_libcoreutils_a_SOURCES += lib/smack.h
+
+## end gnulib module smack
+
+## begin gnulib module snippet/_Noreturn
+
+# Because this Makefile snippet defines a variable used by other
+# gnulib Makefile snippets, it must be present in all Makefile.am that
+# need it. This is ensured by the applicability 'all' defined above.
+
+_NORETURN_H=$(top_srcdir)/build-aux/snippet/_Noreturn.h
+
+EXTRA_DIST += $(top_srcdir)/build-aux/snippet/_Noreturn.h
+
+## end gnulib module snippet/_Noreturn
+
+## begin gnulib module snippet/arg-nonnull
+
+# The BUILT_SOURCES created by this Makefile snippet are not used via #include
+# statements but through direct file reference. Therefore this snippet must be
+# present in all Makefile.am that need it. This is ensured by the applicability
+# 'all' defined above.
+
+BUILT_SOURCES += lib/arg-nonnull.h
+# The arg-nonnull.h that gets inserted into generated .h files is the same as
+# build-aux/snippet/arg-nonnull.h, except that it has the copyright header cut
+# off.
+lib/arg-nonnull.h: $(top_srcdir)/build-aux/snippet/arg-nonnull.h
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ sed -n -e '/GL_ARG_NONNULL/,$$p' \
+ < $(top_srcdir)/build-aux/snippet/arg-nonnull.h \
+ > $@-t && \
+ mv $@-t $@
+MOSTLYCLEANFILES += lib/arg-nonnull.h lib/arg-nonnull.h-t
+
+ARG_NONNULL_H=lib/arg-nonnull.h
+
+EXTRA_DIST += $(top_srcdir)/build-aux/snippet/arg-nonnull.h
+
+## end gnulib module snippet/arg-nonnull
+
+## begin gnulib module snippet/c++defs
+
+# The BUILT_SOURCES created by this Makefile snippet are not used via #include
+# statements but through direct file reference. Therefore this snippet must be
+# present in all Makefile.am that need it. This is ensured by the applicability
+# 'all' defined above.
+
+BUILT_SOURCES += lib/c++defs.h
+# The c++defs.h that gets inserted into generated .h files is the same as
+# build-aux/snippet/c++defs.h, except that it has the copyright header cut off.
+lib/c++defs.h: $(top_srcdir)/build-aux/snippet/c++defs.h
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ sed -n -e '/_GL_CXXDEFS/,$$p' \
+ < $(top_srcdir)/build-aux/snippet/c++defs.h \
+ > $@-t && \
+ mv $@-t $@
+MOSTLYCLEANFILES += lib/c++defs.h lib/c++defs.h-t
+
+CXXDEFS_H=lib/c++defs.h
+
+EXTRA_DIST += $(top_srcdir)/build-aux/snippet/c++defs.h
+
+## end gnulib module snippet/c++defs
+
+## begin gnulib module snippet/unused-parameter
+
+# The BUILT_SOURCES created by this Makefile snippet are not used via #include
+# statements but through direct file reference. Therefore this snippet must be
+# present in all Makefile.am that need it. This is ensured by the applicability
+# 'all' defined above.
+
+BUILT_SOURCES += lib/unused-parameter.h
+# The unused-parameter.h that gets inserted into generated .h files is the same
+# as build-aux/snippet/unused-parameter.h, except that it has the copyright
+# header cut off.
+lib/unused-parameter.h: $(top_srcdir)/build-aux/snippet/unused-parameter.h
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ sed -n -e '/GL_UNUSED_PARAMETER/,$$p' \
+ < $(top_srcdir)/build-aux/snippet/unused-parameter.h \
+ > $@-t && \
+ mv $@-t $@
+MOSTLYCLEANFILES += lib/unused-parameter.h lib/unused-parameter.h-t
+
+UNUSED_PARAMETER_H=lib/unused-parameter.h
+
+EXTRA_DIST += $(top_srcdir)/build-aux/snippet/unused-parameter.h
+
+## end gnulib module snippet/unused-parameter
+
+## begin gnulib module snippet/warn-on-use
+
+BUILT_SOURCES += lib/warn-on-use.h
+# The warn-on-use.h that gets inserted into generated .h files is the same as
+# build-aux/snippet/warn-on-use.h, except that it has the copyright header cut
+# off.
+lib/warn-on-use.h: $(top_srcdir)/build-aux/snippet/warn-on-use.h
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ sed -n -e '/^.ifndef/,$$p' \
+ < $(top_srcdir)/build-aux/snippet/warn-on-use.h \
+ > $@-t && \
+ mv $@-t $@
+MOSTLYCLEANFILES += lib/warn-on-use.h lib/warn-on-use.h-t
+
+WARN_ON_USE_H=lib/warn-on-use.h
+
+EXTRA_DIST += $(top_srcdir)/build-aux/snippet/warn-on-use.h
+
+## end gnulib module snippet/warn-on-use
## begin gnulib module snprintf
-EXTRA_DIST += snprintf.c
+EXTRA_DIST += lib/snprintf.c
-EXTRA_libcoreutils_a_SOURCES += snprintf.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/snprintf.c
## end gnulib module snprintf
+## begin gnulib module sockets
+
+lib_libcoreutils_a_SOURCES += lib/sockets.h lib/sockets.c
+
+EXTRA_DIST += lib/w32sock.h
+
+## end gnulib module sockets
+
+## begin gnulib module stat
+
+
+EXTRA_DIST += lib/stat.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/stat.c
+
+## end gnulib module stat
+
## begin gnulib module stat-macros
-EXTRA_DIST += stat-macros.h
+EXTRA_DIST += lib/stat-macros.h
## end gnulib module stat-macros
+## begin gnulib module stat-size
+
+
+EXTRA_DIST += lib/stat-size.h
+
+## end gnulib module stat-size
+
## begin gnulib module stat-time
+lib_libcoreutils_a_SOURCES += lib/stat-time.c
-EXTRA_DIST += stat-time.h
+EXTRA_DIST += lib/stat-time.h
## end gnulib module stat-time
+## begin gnulib module statat
+
+lib_libcoreutils_a_SOURCES += lib/statat.c
+
+## end gnulib module statat
+
+## begin gnulib module stdalign
+
+BUILT_SOURCES += $(STDALIGN_H)
+
+# We need the following in order to create <stdalign.h> when the system
+# doesn't have one that works.
+if GL_GENERATE_STDALIGN_H
+lib/stdalign.h: lib/stdalign.in.h $(top_builddir)/config.status
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
+ cat $(top_srcdir)/lib/stdalign.in.h; \
+ } > $@-t && \
+ mv $@-t $@
+else
+lib/stdalign.h: $(top_builddir)/config.status
+ rm -f $@
+endif
+MOSTLYCLEANFILES += lib/stdalign.h lib/stdalign.h-t
+
+EXTRA_DIST += lib/stdalign.in.h
+
+## end gnulib module stdalign
+
+## begin gnulib module stdarg
+
+BUILT_SOURCES += $(STDARG_H)
+
+# We need the following in order to create <stdarg.h> when the system
+# doesn't have one that works with the given compiler.
+if GL_GENERATE_STDARG_H
+lib/stdarg.h: lib/stdarg.in.h $(top_builddir)/config.status
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */' && \
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_STDARG_H''@|$(NEXT_STDARG_H)|g' \
+ < $(top_srcdir)/lib/stdarg.in.h; \
+ } > $@-t && \
+ mv $@-t $@
+else
+lib/stdarg.h: $(top_builddir)/config.status
+ rm -f $@
+endif
+MOSTLYCLEANFILES += lib/stdarg.h lib/stdarg.h-t
+
+EXTRA_DIST += lib/stdarg.in.h
+
+## end gnulib module stdarg
+
## begin gnulib module stdbool
BUILT_SOURCES += $(STDBOOL_H)
# We need the following in order to create <stdbool.h> when the system
# doesn't have one that works.
-stdbool.h: stdbool_.h
- rm -f $@-t $@
+if GL_GENERATE_STDBOOL_H
+lib/stdbool.h: lib/stdbool.in.h $(top_builddir)/config.status
+ $(AM_V_GEN)rm -f $@-t $@ && \
{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
- sed -e 's/@''HAVE__BOOL''@/$(HAVE__BOOL)/g' < $(srcdir)/stdbool_.h; \
- } > $@-t
+ sed -e 's/@''HAVE__BOOL''@/$(HAVE__BOOL)/g' < $(top_srcdir)/lib/stdbool.in.h; \
+ } > $@-t && \
mv $@-t $@
-MOSTLYCLEANFILES += stdbool.h stdbool.h-t
+else
+lib/stdbool.h: $(top_builddir)/config.status
+ rm -f $@
+endif
+MOSTLYCLEANFILES += lib/stdbool.h lib/stdbool.h-t
-EXTRA_DIST += stdbool_.h
+EXTRA_DIST += lib/stdbool.in.h
## end gnulib module stdbool
+## begin gnulib module stddef
+
+BUILT_SOURCES += $(STDDEF_H)
+
+# We need the following in order to create <stddef.h> when the system
+# doesn't have one that works with the given compiler.
+if GL_GENERATE_STDDEF_H
+lib/stddef.h: lib/stddef.in.h $(top_builddir)/config.status
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */' && \
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_STDDEF_H''@|$(NEXT_STDDEF_H)|g' \
+ -e 's|@''HAVE_MAX_ALIGN_T''@|$(HAVE_MAX_ALIGN_T)|g' \
+ -e 's|@''HAVE_WCHAR_T''@|$(HAVE_WCHAR_T)|g' \
+ -e 's|@''REPLACE_NULL''@|$(REPLACE_NULL)|g' \
+ < $(top_srcdir)/lib/stddef.in.h; \
+ } > $@-t && \
+ mv $@-t $@
+else
+lib/stddef.h: $(top_builddir)/config.status
+ rm -f $@
+endif
+MOSTLYCLEANFILES += lib/stddef.h lib/stddef.h-t
+
+EXTRA_DIST += lib/stddef.in.h
+
+## end gnulib module stddef
+
## begin gnulib module stdint
BUILT_SOURCES += $(STDINT_H)
# We need the following in order to create <stdint.h> when the system
# doesn't have one that works with the given compiler.
-stdint.h: stdint_.h
- rm -f $@-t $@
+if GL_GENERATE_STDINT_H
+lib/stdint.h: lib/stdint.in.h $(top_builddir)/config.status
+ $(AM_V_GEN)rm -f $@-t $@ && \
{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
- sed -e 's/@''HAVE_STDINT_H''@/$(HAVE_STDINT_H)/g' \
- -e 's|@''ABSOLUTE_STDINT_H''@|$(ABSOLUTE_STDINT_H)|g' \
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's/@''HAVE_STDINT_H''@/$(HAVE_STDINT_H)/g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_STDINT_H''@|$(NEXT_STDINT_H)|g' \
-e 's/@''HAVE_SYS_TYPES_H''@/$(HAVE_SYS_TYPES_H)/g' \
-e 's/@''HAVE_INTTYPES_H''@/$(HAVE_INTTYPES_H)/g' \
-e 's/@''HAVE_SYS_INTTYPES_H''@/$(HAVE_SYS_INTTYPES_H)/g' \
-e 's/@''HAVE_SYS_BITYPES_H''@/$(HAVE_SYS_BITYPES_H)/g' \
+ -e 's/@''HAVE_WCHAR_H''@/$(HAVE_WCHAR_H)/g' \
-e 's/@''HAVE_LONG_LONG_INT''@/$(HAVE_LONG_LONG_INT)/g' \
-e 's/@''HAVE_UNSIGNED_LONG_LONG_INT''@/$(HAVE_UNSIGNED_LONG_LONG_INT)/g' \
+ -e 's/@''APPLE_UNIVERSAL_BUILD''@/$(APPLE_UNIVERSAL_BUILD)/g' \
-e 's/@''BITSIZEOF_PTRDIFF_T''@/$(BITSIZEOF_PTRDIFF_T)/g' \
-e 's/@''PTRDIFF_T_SUFFIX''@/$(PTRDIFF_T_SUFFIX)/g' \
-e 's/@''BITSIZEOF_SIG_ATOMIC_T''@/$(BITSIZEOF_SIG_ATOMIC_T)/g' \
@@ -1544,705 +3715,1819 @@ stdint.h: stdint_.h
-e 's/@''BITSIZEOF_WINT_T''@/$(BITSIZEOF_WINT_T)/g' \
-e 's/@''HAVE_SIGNED_WINT_T''@/$(HAVE_SIGNED_WINT_T)/g' \
-e 's/@''WINT_T_SUFFIX''@/$(WINT_T_SUFFIX)/g' \
- < $(srcdir)/stdint_.h; \
- } > $@-t
+ < $(top_srcdir)/lib/stdint.in.h; \
+ } > $@-t && \
mv $@-t $@
-MOSTLYCLEANFILES += stdint.h stdint.h-t
+else
+lib/stdint.h: $(top_builddir)/config.status
+ rm -f $@
+endif
+MOSTLYCLEANFILES += lib/stdint.h lib/stdint.h-t
-EXTRA_DIST += stdint_.h
+EXTRA_DIST += lib/stdint.in.h
## end gnulib module stdint
## begin gnulib module stdio
-BUILT_SOURCES += stdio.h
+BUILT_SOURCES += lib/stdio.h
# We need the following in order to create <stdio.h> when the system
# doesn't have one that works with the given compiler.
-stdio.h: stdio_.h
- rm -f $@-t $@
+lib/stdio.h: lib/stdio.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(ARG_NONNULL_H) $(WARN_ON_USE_H)
+ $(AM_V_GEN)rm -f $@-t $@ && \
{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */' && \
- sed -e 's|@''ABSOLUTE_STDIO_H''@|$(ABSOLUTE_STDIO_H)|g' \
- -e 's|@''GNULIB_FPRINTF_POSIX''@|$(GNULIB_FPRINTF_POSIX)|g' \
- -e 's|@''GNULIB_PRINTF_POSIX''@|$(GNULIB_PRINTF_POSIX)|g' \
- -e 's|@''GNULIB_SNPRINTF''@|$(GNULIB_SNPRINTF)|g' \
- -e 's|@''GNULIB_SPRINTF_POSIX''@|$(GNULIB_SPRINTF_POSIX)|g' \
- -e 's|@''GNULIB_VFPRINTF_POSIX''@|$(GNULIB_VFPRINTF_POSIX)|g' \
- -e 's|@''GNULIB_VPRINTF_POSIX''@|$(GNULIB_VPRINTF_POSIX)|g' \
- -e 's|@''GNULIB_VSNPRINTF''@|$(GNULIB_VSNPRINTF)|g' \
- -e 's|@''GNULIB_VSPRINTF_POSIX''@|$(GNULIB_VSPRINTF_POSIX)|g' \
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_STDIO_H''@|$(NEXT_STDIO_H)|g' \
+ -e 's/@''GNULIB_DPRINTF''@/$(GNULIB_DPRINTF)/g' \
+ -e 's/@''GNULIB_FCLOSE''@/$(GNULIB_FCLOSE)/g' \
+ -e 's/@''GNULIB_FDOPEN''@/$(GNULIB_FDOPEN)/g' \
+ -e 's/@''GNULIB_FFLUSH''@/$(GNULIB_FFLUSH)/g' \
+ -e 's/@''GNULIB_FGETC''@/$(GNULIB_FGETC)/g' \
+ -e 's/@''GNULIB_FGETS''@/$(GNULIB_FGETS)/g' \
+ -e 's/@''GNULIB_FOPEN''@/$(GNULIB_FOPEN)/g' \
+ -e 's/@''GNULIB_FPRINTF''@/$(GNULIB_FPRINTF)/g' \
+ -e 's/@''GNULIB_FPRINTF_POSIX''@/$(GNULIB_FPRINTF_POSIX)/g' \
+ -e 's/@''GNULIB_FPURGE''@/$(GNULIB_FPURGE)/g' \
+ -e 's/@''GNULIB_FPUTC''@/$(GNULIB_FPUTC)/g' \
+ -e 's/@''GNULIB_FPUTS''@/$(GNULIB_FPUTS)/g' \
+ -e 's/@''GNULIB_FREAD''@/$(GNULIB_FREAD)/g' \
+ -e 's/@''GNULIB_FREOPEN''@/$(GNULIB_FREOPEN)/g' \
+ -e 's/@''GNULIB_FSCANF''@/$(GNULIB_FSCANF)/g' \
+ -e 's/@''GNULIB_FSEEK''@/$(GNULIB_FSEEK)/g' \
+ -e 's/@''GNULIB_FSEEKO''@/$(GNULIB_FSEEKO)/g' \
+ -e 's/@''GNULIB_FTELL''@/$(GNULIB_FTELL)/g' \
+ -e 's/@''GNULIB_FTELLO''@/$(GNULIB_FTELLO)/g' \
+ -e 's/@''GNULIB_FWRITE''@/$(GNULIB_FWRITE)/g' \
+ -e 's/@''GNULIB_GETC''@/$(GNULIB_GETC)/g' \
+ -e 's/@''GNULIB_GETCHAR''@/$(GNULIB_GETCHAR)/g' \
+ -e 's/@''GNULIB_GETDELIM''@/$(GNULIB_GETDELIM)/g' \
+ -e 's/@''GNULIB_GETLINE''@/$(GNULIB_GETLINE)/g' \
+ -e 's/@''GNULIB_OBSTACK_PRINTF''@/$(GNULIB_OBSTACK_PRINTF)/g' \
+ -e 's/@''GNULIB_OBSTACK_PRINTF_POSIX''@/$(GNULIB_OBSTACK_PRINTF_POSIX)/g' \
+ -e 's/@''GNULIB_PCLOSE''@/$(GNULIB_PCLOSE)/g' \
+ -e 's/@''GNULIB_PERROR''@/$(GNULIB_PERROR)/g' \
+ -e 's/@''GNULIB_POPEN''@/$(GNULIB_POPEN)/g' \
+ -e 's/@''GNULIB_PRINTF''@/$(GNULIB_PRINTF)/g' \
+ -e 's/@''GNULIB_PRINTF_POSIX''@/$(GNULIB_PRINTF_POSIX)/g' \
+ -e 's/@''GNULIB_PUTC''@/$(GNULIB_PUTC)/g' \
+ -e 's/@''GNULIB_PUTCHAR''@/$(GNULIB_PUTCHAR)/g' \
+ -e 's/@''GNULIB_PUTS''@/$(GNULIB_PUTS)/g' \
+ -e 's/@''GNULIB_REMOVE''@/$(GNULIB_REMOVE)/g' \
+ -e 's/@''GNULIB_RENAME''@/$(GNULIB_RENAME)/g' \
+ -e 's/@''GNULIB_RENAMEAT''@/$(GNULIB_RENAMEAT)/g' \
+ -e 's/@''GNULIB_SCANF''@/$(GNULIB_SCANF)/g' \
+ -e 's/@''GNULIB_SNPRINTF''@/$(GNULIB_SNPRINTF)/g' \
+ -e 's/@''GNULIB_SPRINTF_POSIX''@/$(GNULIB_SPRINTF_POSIX)/g' \
+ -e 's/@''GNULIB_STDIO_H_NONBLOCKING''@/$(GNULIB_STDIO_H_NONBLOCKING)/g' \
+ -e 's/@''GNULIB_STDIO_H_SIGPIPE''@/$(GNULIB_STDIO_H_SIGPIPE)/g' \
+ -e 's/@''GNULIB_TMPFILE''@/$(GNULIB_TMPFILE)/g' \
+ -e 's/@''GNULIB_VASPRINTF''@/$(GNULIB_VASPRINTF)/g' \
+ -e 's/@''GNULIB_VDPRINTF''@/$(GNULIB_VDPRINTF)/g' \
+ -e 's/@''GNULIB_VFPRINTF''@/$(GNULIB_VFPRINTF)/g' \
+ -e 's/@''GNULIB_VFPRINTF_POSIX''@/$(GNULIB_VFPRINTF_POSIX)/g' \
+ -e 's/@''GNULIB_VFSCANF''@/$(GNULIB_VFSCANF)/g' \
+ -e 's/@''GNULIB_VSCANF''@/$(GNULIB_VSCANF)/g' \
+ -e 's/@''GNULIB_VPRINTF''@/$(GNULIB_VPRINTF)/g' \
+ -e 's/@''GNULIB_VPRINTF_POSIX''@/$(GNULIB_VPRINTF_POSIX)/g' \
+ -e 's/@''GNULIB_VSNPRINTF''@/$(GNULIB_VSNPRINTF)/g' \
+ -e 's/@''GNULIB_VSPRINTF_POSIX''@/$(GNULIB_VSPRINTF_POSIX)/g' \
+ < $(top_srcdir)/lib/stdio.in.h | \
+ sed -e 's|@''HAVE_DECL_FPURGE''@|$(HAVE_DECL_FPURGE)|g' \
+ -e 's|@''HAVE_DECL_FSEEKO''@|$(HAVE_DECL_FSEEKO)|g' \
+ -e 's|@''HAVE_DECL_FTELLO''@|$(HAVE_DECL_FTELLO)|g' \
+ -e 's|@''HAVE_DECL_GETDELIM''@|$(HAVE_DECL_GETDELIM)|g' \
+ -e 's|@''HAVE_DECL_GETLINE''@|$(HAVE_DECL_GETLINE)|g' \
+ -e 's|@''HAVE_DECL_OBSTACK_PRINTF''@|$(HAVE_DECL_OBSTACK_PRINTF)|g' \
+ -e 's|@''HAVE_DECL_SNPRINTF''@|$(HAVE_DECL_SNPRINTF)|g' \
+ -e 's|@''HAVE_DECL_VSNPRINTF''@|$(HAVE_DECL_VSNPRINTF)|g' \
+ -e 's|@''HAVE_DPRINTF''@|$(HAVE_DPRINTF)|g' \
+ -e 's|@''HAVE_FSEEKO''@|$(HAVE_FSEEKO)|g' \
+ -e 's|@''HAVE_FTELLO''@|$(HAVE_FTELLO)|g' \
+ -e 's|@''HAVE_PCLOSE''@|$(HAVE_PCLOSE)|g' \
+ -e 's|@''HAVE_POPEN''@|$(HAVE_POPEN)|g' \
+ -e 's|@''HAVE_RENAMEAT''@|$(HAVE_RENAMEAT)|g' \
+ -e 's|@''HAVE_VASPRINTF''@|$(HAVE_VASPRINTF)|g' \
+ -e 's|@''HAVE_VDPRINTF''@|$(HAVE_VDPRINTF)|g' \
+ -e 's|@''REPLACE_DPRINTF''@|$(REPLACE_DPRINTF)|g' \
+ -e 's|@''REPLACE_FCLOSE''@|$(REPLACE_FCLOSE)|g' \
+ -e 's|@''REPLACE_FDOPEN''@|$(REPLACE_FDOPEN)|g' \
+ -e 's|@''REPLACE_FFLUSH''@|$(REPLACE_FFLUSH)|g' \
+ -e 's|@''REPLACE_FOPEN''@|$(REPLACE_FOPEN)|g' \
-e 's|@''REPLACE_FPRINTF''@|$(REPLACE_FPRINTF)|g' \
- -e 's|@''REPLACE_VFPRINTF''@|$(REPLACE_VFPRINTF)|g' \
+ -e 's|@''REPLACE_FPURGE''@|$(REPLACE_FPURGE)|g' \
+ -e 's|@''REPLACE_FREOPEN''@|$(REPLACE_FREOPEN)|g' \
+ -e 's|@''REPLACE_FSEEK''@|$(REPLACE_FSEEK)|g' \
+ -e 's|@''REPLACE_FSEEKO''@|$(REPLACE_FSEEKO)|g' \
+ -e 's|@''REPLACE_FTELL''@|$(REPLACE_FTELL)|g' \
+ -e 's|@''REPLACE_FTELLO''@|$(REPLACE_FTELLO)|g' \
+ -e 's|@''REPLACE_GETDELIM''@|$(REPLACE_GETDELIM)|g' \
+ -e 's|@''REPLACE_GETLINE''@|$(REPLACE_GETLINE)|g' \
+ -e 's|@''REPLACE_OBSTACK_PRINTF''@|$(REPLACE_OBSTACK_PRINTF)|g' \
+ -e 's|@''REPLACE_PERROR''@|$(REPLACE_PERROR)|g' \
+ -e 's|@''REPLACE_POPEN''@|$(REPLACE_POPEN)|g' \
-e 's|@''REPLACE_PRINTF''@|$(REPLACE_PRINTF)|g' \
- -e 's|@''REPLACE_VPRINTF''@|$(REPLACE_VPRINTF)|g' \
+ -e 's|@''REPLACE_REMOVE''@|$(REPLACE_REMOVE)|g' \
+ -e 's|@''REPLACE_RENAME''@|$(REPLACE_RENAME)|g' \
+ -e 's|@''REPLACE_RENAMEAT''@|$(REPLACE_RENAMEAT)|g' \
-e 's|@''REPLACE_SNPRINTF''@|$(REPLACE_SNPRINTF)|g' \
- -e 's|@''HAVE_DECL_SNPRINTF''@|$(HAVE_DECL_SNPRINTF)|g' \
- -e 's|@''REPLACE_VSNPRINTF''@|$(REPLACE_VSNPRINTF)|g' \
- -e 's|@''HAVE_DECL_VSNPRINTF''@|$(HAVE_DECL_VSNPRINTF)|g' \
-e 's|@''REPLACE_SPRINTF''@|$(REPLACE_SPRINTF)|g' \
+ -e 's|@''REPLACE_STDIO_READ_FUNCS''@|$(REPLACE_STDIO_READ_FUNCS)|g' \
+ -e 's|@''REPLACE_STDIO_WRITE_FUNCS''@|$(REPLACE_STDIO_WRITE_FUNCS)|g' \
+ -e 's|@''REPLACE_TMPFILE''@|$(REPLACE_TMPFILE)|g' \
+ -e 's|@''REPLACE_VASPRINTF''@|$(REPLACE_VASPRINTF)|g' \
+ -e 's|@''REPLACE_VDPRINTF''@|$(REPLACE_VDPRINTF)|g' \
+ -e 's|@''REPLACE_VFPRINTF''@|$(REPLACE_VFPRINTF)|g' \
+ -e 's|@''REPLACE_VPRINTF''@|$(REPLACE_VPRINTF)|g' \
+ -e 's|@''REPLACE_VSNPRINTF''@|$(REPLACE_VSNPRINTF)|g' \
-e 's|@''REPLACE_VSPRINTF''@|$(REPLACE_VSPRINTF)|g' \
- -e '/definition of GL_LINK_WARNING/r $(LINK_WARNING_H)' \
- < $(srcdir)/stdio_.h; \
- } > $@-t
+ -e 's|@''ASM_SYMBOL_PREFIX''@|$(ASM_SYMBOL_PREFIX)|g' \
+ -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
+ -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
+ -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)'; \
+ } > $@-t && \
mv $@-t $@
-MOSTLYCLEANFILES += stdio.h stdio.h-t
+MOSTLYCLEANFILES += lib/stdio.h lib/stdio.h-t
-EXTRA_DIST += stdio_.h
+EXTRA_DIST += lib/stdio.in.h
## end gnulib module stdio
## begin gnulib module stdlib
-BUILT_SOURCES += stdlib.h
+BUILT_SOURCES += lib/stdlib.h
# We need the following in order to create <stdlib.h> when the system
# doesn't have one that works with the given compiler.
-stdlib.h: stdlib_.h
- rm -f $@-t $@
+lib/stdlib.h: lib/stdlib.in.h $(top_builddir)/config.status $(CXXDEFS_H) \
+ $(_NORETURN_H) $(ARG_NONNULL_H) $(WARN_ON_USE_H)
+ $(AM_V_GEN)rm -f $@-t $@ && \
{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */' && \
- sed -e 's|@''ABSOLUTE_STDLIB_H''@|$(ABSOLUTE_STDLIB_H)|g' \
- -e 's|@''GNULIB_GETSUBOPT''@|$(GNULIB_GETSUBOPT)|g' \
- -e 's|@''GNULIB_MKDTEMP''@|$(GNULIB_MKDTEMP)|g' \
- -e 's|@''GNULIB_MKSTEMP''@|$(GNULIB_MKSTEMP)|g' \
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_STDLIB_H''@|$(NEXT_STDLIB_H)|g' \
+ -e 's/@''GNULIB__EXIT''@/$(GNULIB__EXIT)/g' \
+ -e 's/@''GNULIB_ATOLL''@/$(GNULIB_ATOLL)/g' \
+ -e 's/@''GNULIB_CALLOC_POSIX''@/$(GNULIB_CALLOC_POSIX)/g' \
+ -e 's/@''GNULIB_CANONICALIZE_FILE_NAME''@/$(GNULIB_CANONICALIZE_FILE_NAME)/g' \
+ -e 's/@''GNULIB_GETLOADAVG''@/$(GNULIB_GETLOADAVG)/g' \
+ -e 's/@''GNULIB_GETSUBOPT''@/$(GNULIB_GETSUBOPT)/g' \
+ -e 's/@''GNULIB_GRANTPT''@/$(GNULIB_GRANTPT)/g' \
+ -e 's/@''GNULIB_MALLOC_POSIX''@/$(GNULIB_MALLOC_POSIX)/g' \
+ -e 's/@''GNULIB_MBTOWC''@/$(GNULIB_MBTOWC)/g' \
+ -e 's/@''GNULIB_MKDTEMP''@/$(GNULIB_MKDTEMP)/g' \
+ -e 's/@''GNULIB_MKOSTEMP''@/$(GNULIB_MKOSTEMP)/g' \
+ -e 's/@''GNULIB_MKOSTEMPS''@/$(GNULIB_MKOSTEMPS)/g' \
+ -e 's/@''GNULIB_MKSTEMP''@/$(GNULIB_MKSTEMP)/g' \
+ -e 's/@''GNULIB_MKSTEMPS''@/$(GNULIB_MKSTEMPS)/g' \
+ -e 's/@''GNULIB_POSIX_OPENPT''@/$(GNULIB_POSIX_OPENPT)/g' \
+ -e 's/@''GNULIB_PTSNAME''@/$(GNULIB_PTSNAME)/g' \
+ -e 's/@''GNULIB_PTSNAME_R''@/$(GNULIB_PTSNAME_R)/g' \
+ -e 's/@''GNULIB_PUTENV''@/$(GNULIB_PUTENV)/g' \
+ -e 's/@''GNULIB_QSORT_R''@/$(GNULIB_QSORT_R)/g' \
+ -e 's/@''GNULIB_RANDOM''@/$(GNULIB_RANDOM)/g' \
+ -e 's/@''GNULIB_RANDOM_R''@/$(GNULIB_RANDOM_R)/g' \
+ -e 's/@''GNULIB_REALLOC_POSIX''@/$(GNULIB_REALLOC_POSIX)/g' \
+ -e 's/@''GNULIB_REALPATH''@/$(GNULIB_REALPATH)/g' \
+ -e 's/@''GNULIB_RPMATCH''@/$(GNULIB_RPMATCH)/g' \
+ -e 's/@''GNULIB_SECURE_GETENV''@/$(GNULIB_SECURE_GETENV)/g' \
+ -e 's/@''GNULIB_SETENV''@/$(GNULIB_SETENV)/g' \
+ -e 's/@''GNULIB_STRTOD''@/$(GNULIB_STRTOD)/g' \
+ -e 's/@''GNULIB_STRTOLL''@/$(GNULIB_STRTOLL)/g' \
+ -e 's/@''GNULIB_STRTOULL''@/$(GNULIB_STRTOULL)/g' \
+ -e 's/@''GNULIB_SYSTEM_POSIX''@/$(GNULIB_SYSTEM_POSIX)/g' \
+ -e 's/@''GNULIB_UNLOCKPT''@/$(GNULIB_UNLOCKPT)/g' \
+ -e 's/@''GNULIB_UNSETENV''@/$(GNULIB_UNSETENV)/g' \
+ -e 's/@''GNULIB_WCTOMB''@/$(GNULIB_WCTOMB)/g' \
+ < $(top_srcdir)/lib/stdlib.in.h | \
+ sed -e 's|@''HAVE__EXIT''@|$(HAVE__EXIT)|g' \
+ -e 's|@''HAVE_ATOLL''@|$(HAVE_ATOLL)|g' \
+ -e 's|@''HAVE_CANONICALIZE_FILE_NAME''@|$(HAVE_CANONICALIZE_FILE_NAME)|g' \
+ -e 's|@''HAVE_DECL_GETLOADAVG''@|$(HAVE_DECL_GETLOADAVG)|g' \
-e 's|@''HAVE_GETSUBOPT''@|$(HAVE_GETSUBOPT)|g' \
+ -e 's|@''HAVE_GRANTPT''@|$(HAVE_GRANTPT)|g' \
-e 's|@''HAVE_MKDTEMP''@|$(HAVE_MKDTEMP)|g' \
+ -e 's|@''HAVE_MKOSTEMP''@|$(HAVE_MKOSTEMP)|g' \
+ -e 's|@''HAVE_MKOSTEMPS''@|$(HAVE_MKOSTEMPS)|g' \
+ -e 's|@''HAVE_MKSTEMP''@|$(HAVE_MKSTEMP)|g' \
+ -e 's|@''HAVE_MKSTEMPS''@|$(HAVE_MKSTEMPS)|g' \
+ -e 's|@''HAVE_POSIX_OPENPT''@|$(HAVE_POSIX_OPENPT)|g' \
+ -e 's|@''HAVE_PTSNAME''@|$(HAVE_PTSNAME)|g' \
+ -e 's|@''HAVE_PTSNAME_R''@|$(HAVE_PTSNAME_R)|g' \
+ -e 's|@''HAVE_RANDOM''@|$(HAVE_RANDOM)|g' \
+ -e 's|@''HAVE_RANDOM_H''@|$(HAVE_RANDOM_H)|g' \
+ -e 's|@''HAVE_RANDOM_R''@|$(HAVE_RANDOM_R)|g' \
+ -e 's|@''HAVE_REALPATH''@|$(HAVE_REALPATH)|g' \
+ -e 's|@''HAVE_RPMATCH''@|$(HAVE_RPMATCH)|g' \
+ -e 's|@''HAVE_SECURE_GETENV''@|$(HAVE_SECURE_GETENV)|g' \
+ -e 's|@''HAVE_DECL_SETENV''@|$(HAVE_DECL_SETENV)|g' \
+ -e 's|@''HAVE_STRTOD''@|$(HAVE_STRTOD)|g' \
+ -e 's|@''HAVE_STRTOLL''@|$(HAVE_STRTOLL)|g' \
+ -e 's|@''HAVE_STRTOULL''@|$(HAVE_STRTOULL)|g' \
+ -e 's|@''HAVE_STRUCT_RANDOM_DATA''@|$(HAVE_STRUCT_RANDOM_DATA)|g' \
+ -e 's|@''HAVE_SYS_LOADAVG_H''@|$(HAVE_SYS_LOADAVG_H)|g' \
+ -e 's|@''HAVE_UNLOCKPT''@|$(HAVE_UNLOCKPT)|g' \
+ -e 's|@''HAVE_DECL_UNSETENV''@|$(HAVE_DECL_UNSETENV)|g' \
+ -e 's|@''REPLACE_CALLOC''@|$(REPLACE_CALLOC)|g' \
+ -e 's|@''REPLACE_CANONICALIZE_FILE_NAME''@|$(REPLACE_CANONICALIZE_FILE_NAME)|g' \
+ -e 's|@''REPLACE_MALLOC''@|$(REPLACE_MALLOC)|g' \
+ -e 's|@''REPLACE_MBTOWC''@|$(REPLACE_MBTOWC)|g' \
-e 's|@''REPLACE_MKSTEMP''@|$(REPLACE_MKSTEMP)|g' \
- -e '/definition of GL_LINK_WARNING/r $(LINK_WARNING_H)' \
- < $(srcdir)/stdlib_.h; \
- } > $@-t
+ -e 's|@''REPLACE_PTSNAME''@|$(REPLACE_PTSNAME)|g' \
+ -e 's|@''REPLACE_PTSNAME_R''@|$(REPLACE_PTSNAME_R)|g' \
+ -e 's|@''REPLACE_PUTENV''@|$(REPLACE_PUTENV)|g' \
+ -e 's|@''REPLACE_QSORT_R''@|$(REPLACE_QSORT_R)|g' \
+ -e 's|@''REPLACE_RANDOM_R''@|$(REPLACE_RANDOM_R)|g' \
+ -e 's|@''REPLACE_REALLOC''@|$(REPLACE_REALLOC)|g' \
+ -e 's|@''REPLACE_REALPATH''@|$(REPLACE_REALPATH)|g' \
+ -e 's|@''REPLACE_SETENV''@|$(REPLACE_SETENV)|g' \
+ -e 's|@''REPLACE_STRTOD''@|$(REPLACE_STRTOD)|g' \
+ -e 's|@''REPLACE_UNSETENV''@|$(REPLACE_UNSETENV)|g' \
+ -e 's|@''REPLACE_WCTOMB''@|$(REPLACE_WCTOMB)|g' \
+ -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
+ -e '/definition of _Noreturn/r $(_NORETURN_H)' \
+ -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
+ -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)'; \
+ } > $@-t && \
mv $@-t $@
-MOSTLYCLEANFILES += stdlib.h stdlib.h-t
+MOSTLYCLEANFILES += lib/stdlib.h lib/stdlib.h-t
-EXTRA_DIST += stdlib_.h
+EXTRA_DIST += lib/stdlib.in.h
## end gnulib module stdlib
## begin gnulib module stdlib-safer
+lib_libcoreutils_a_SOURCES += lib/mkstemp-safer.c
-EXTRA_DIST += mkstemp-safer.c stdlib--.h stdlib-safer.h
-
-EXTRA_libcoreutils_a_SOURCES += mkstemp-safer.c
+EXTRA_DIST += lib/stdlib--.h lib/stdlib-safer.h
## end gnulib module stdlib-safer
## begin gnulib module stpcpy
-EXTRA_DIST += stpcpy.c
+EXTRA_DIST += lib/stpcpy.c
-EXTRA_libcoreutils_a_SOURCES += stpcpy.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/stpcpy.c
## end gnulib module stpcpy
-## begin gnulib module strcspn
+## begin gnulib module stpncpy
-EXTRA_DIST += strcspn.c
+EXTRA_DIST += lib/stpncpy.c
-EXTRA_libcoreutils_a_SOURCES += strcspn.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/stpncpy.c
-## end gnulib module strcspn
+## end gnulib module stpncpy
-## begin gnulib module strdup
+## begin gnulib module strdup-posix
-EXTRA_DIST += strdup.c
+EXTRA_DIST += lib/strdup.c
-EXTRA_libcoreutils_a_SOURCES += strdup.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/strdup.c
-## end gnulib module strdup
+## end gnulib module strdup-posix
-## begin gnulib module strftime
+## begin gnulib module streq
+
+
+EXTRA_DIST += lib/streq.h
+
+## end gnulib module streq
+
+## begin gnulib module strerror
+
+
+EXTRA_DIST += lib/strerror.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/strerror.c
+
+## end gnulib module strerror
+
+## begin gnulib module strerror-override
-EXTRA_DIST += strftime.c strftime.h
+EXTRA_DIST += lib/strerror-override.c lib/strerror-override.h
-EXTRA_libcoreutils_a_SOURCES += strftime.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/strerror-override.c
+
+## end gnulib module strerror-override
+
+## begin gnulib module strftime
+
+lib_libcoreutils_a_SOURCES += lib/strftime.c
+
+EXTRA_DIST += lib/strftime.h
## end gnulib module strftime
+## begin gnulib module striconv
+
+lib_libcoreutils_a_SOURCES += lib/striconv.h lib/striconv.c
+if GL_COND_LIBTOOL
+endif
+
+## end gnulib module striconv
+
## begin gnulib module string
-BUILT_SOURCES += string.h
+BUILT_SOURCES += lib/string.h
# We need the following in order to create <string.h> when the system
# doesn't have one that works with the given compiler.
-string.h: string_.h
- rm -f $@-t $@
+lib/string.h: lib/string.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(ARG_NONNULL_H) $(WARN_ON_USE_H)
+ $(AM_V_GEN)rm -f $@-t $@ && \
{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */' && \
- sed -e 's|@''ABSOLUTE_STRING_H''@|$(ABSOLUTE_STRING_H)|g' \
- -e 's|@''GNULIB_MBSLEN''@|$(GNULIB_MBSLEN)|g' \
- -e 's|@''GNULIB_MBSCHR''@|$(GNULIB_MBSCHR)|g' \
- -e 's|@''GNULIB_MBSRCHR''@|$(GNULIB_MBSRCHR)|g' \
- -e 's|@''GNULIB_MBSSTR''@|$(GNULIB_MBSSTR)|g' \
- -e 's|@''GNULIB_MBSCASECMP''@|$(GNULIB_MBSCASECMP)|g' \
- -e 's|@''GNULIB_MBSNCASECMP''@|$(GNULIB_MBSNCASECMP)|g' \
- -e 's|@''GNULIB_MBSPCASECMP''@|$(GNULIB_MBSPCASECMP)|g' \
- -e 's|@''GNULIB_MBSCASESTR''@|$(GNULIB_MBSCASESTR)|g' \
- -e 's|@''GNULIB_MBSCSPN''@|$(GNULIB_MBSCSPN)|g' \
- -e 's|@''GNULIB_MBSPBRK''@|$(GNULIB_MBSPBRK)|g' \
- -e 's|@''GNULIB_MBSSPN''@|$(GNULIB_MBSSPN)|g' \
- -e 's|@''GNULIB_MBSSEP''@|$(GNULIB_MBSSEP)|g' \
- -e 's|@''GNULIB_MBSTOK_R''@|$(GNULIB_MBSTOK_R)|g' \
- -e 's|@''GNULIB_MEMMEM''@|$(GNULIB_MEMMEM)|g' \
- -e 's|@''GNULIB_MEMPCPY''@|$(GNULIB_MEMPCPY)|g' \
- -e 's|@''GNULIB_MEMRCHR''@|$(GNULIB_MEMRCHR)|g' \
- -e 's|@''GNULIB_STPCPY''@|$(GNULIB_STPCPY)|g' \
- -e 's|@''GNULIB_STPNCPY''@|$(GNULIB_STPNCPY)|g' \
- -e 's|@''GNULIB_STRCHRNUL''@|$(GNULIB_STRCHRNUL)|g' \
- -e 's|@''GNULIB_STRDUP''@|$(GNULIB_STRDUP)|g' \
- -e 's|@''GNULIB_STRNDUP''@|$(GNULIB_STRNDUP)|g' \
- -e 's|@''GNULIB_STRNLEN''@|$(GNULIB_STRNLEN)|g' \
- -e 's|@''GNULIB_STRPBRK''@|$(GNULIB_STRPBRK)|g' \
- -e 's|@''GNULIB_STRSEP''@|$(GNULIB_STRSEP)|g' \
- -e 's|@''GNULIB_STRCASESTR''@|$(GNULIB_STRCASESTR)|g' \
- -e 's|@''GNULIB_STRTOK_R''@|$(GNULIB_STRTOK_R)|g' \
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_STRING_H''@|$(NEXT_STRING_H)|g' \
+ -e 's/@''GNULIB_FFSL''@/$(GNULIB_FFSL)/g' \
+ -e 's/@''GNULIB_FFSLL''@/$(GNULIB_FFSLL)/g' \
+ -e 's/@''GNULIB_MBSLEN''@/$(GNULIB_MBSLEN)/g' \
+ -e 's/@''GNULIB_MBSNLEN''@/$(GNULIB_MBSNLEN)/g' \
+ -e 's/@''GNULIB_MBSCHR''@/$(GNULIB_MBSCHR)/g' \
+ -e 's/@''GNULIB_MBSRCHR''@/$(GNULIB_MBSRCHR)/g' \
+ -e 's/@''GNULIB_MBSSTR''@/$(GNULIB_MBSSTR)/g' \
+ -e 's/@''GNULIB_MBSCASECMP''@/$(GNULIB_MBSCASECMP)/g' \
+ -e 's/@''GNULIB_MBSNCASECMP''@/$(GNULIB_MBSNCASECMP)/g' \
+ -e 's/@''GNULIB_MBSPCASECMP''@/$(GNULIB_MBSPCASECMP)/g' \
+ -e 's/@''GNULIB_MBSCASESTR''@/$(GNULIB_MBSCASESTR)/g' \
+ -e 's/@''GNULIB_MBSCSPN''@/$(GNULIB_MBSCSPN)/g' \
+ -e 's/@''GNULIB_MBSPBRK''@/$(GNULIB_MBSPBRK)/g' \
+ -e 's/@''GNULIB_MBSSPN''@/$(GNULIB_MBSSPN)/g' \
+ -e 's/@''GNULIB_MBSSEP''@/$(GNULIB_MBSSEP)/g' \
+ -e 's/@''GNULIB_MBSTOK_R''@/$(GNULIB_MBSTOK_R)/g' \
+ -e 's/@''GNULIB_MEMCHR''@/$(GNULIB_MEMCHR)/g' \
+ -e 's/@''GNULIB_MEMMEM''@/$(GNULIB_MEMMEM)/g' \
+ -e 's/@''GNULIB_MEMPCPY''@/$(GNULIB_MEMPCPY)/g' \
+ -e 's/@''GNULIB_MEMRCHR''@/$(GNULIB_MEMRCHR)/g' \
+ -e 's/@''GNULIB_RAWMEMCHR''@/$(GNULIB_RAWMEMCHR)/g' \
+ -e 's/@''GNULIB_STPCPY''@/$(GNULIB_STPCPY)/g' \
+ -e 's/@''GNULIB_STPNCPY''@/$(GNULIB_STPNCPY)/g' \
+ -e 's/@''GNULIB_STRCHRNUL''@/$(GNULIB_STRCHRNUL)/g' \
+ -e 's/@''GNULIB_STRDUP''@/$(GNULIB_STRDUP)/g' \
+ -e 's/@''GNULIB_STRNCAT''@/$(GNULIB_STRNCAT)/g' \
+ -e 's/@''GNULIB_STRNDUP''@/$(GNULIB_STRNDUP)/g' \
+ -e 's/@''GNULIB_STRNLEN''@/$(GNULIB_STRNLEN)/g' \
+ -e 's/@''GNULIB_STRPBRK''@/$(GNULIB_STRPBRK)/g' \
+ -e 's/@''GNULIB_STRSEP''@/$(GNULIB_STRSEP)/g' \
+ -e 's/@''GNULIB_STRSTR''@/$(GNULIB_STRSTR)/g' \
+ -e 's/@''GNULIB_STRCASESTR''@/$(GNULIB_STRCASESTR)/g' \
+ -e 's/@''GNULIB_STRTOK_R''@/$(GNULIB_STRTOK_R)/g' \
+ -e 's/@''GNULIB_STRERROR''@/$(GNULIB_STRERROR)/g' \
+ -e 's/@''GNULIB_STRERROR_R''@/$(GNULIB_STRERROR_R)/g' \
+ -e 's/@''GNULIB_STRSIGNAL''@/$(GNULIB_STRSIGNAL)/g' \
+ -e 's/@''GNULIB_STRVERSCMP''@/$(GNULIB_STRVERSCMP)/g' \
+ < $(top_srcdir)/lib/string.in.h | \
+ sed -e 's|@''HAVE_FFSL''@|$(HAVE_FFSL)|g' \
+ -e 's|@''HAVE_FFSLL''@|$(HAVE_FFSLL)|g' \
+ -e 's|@''HAVE_MBSLEN''@|$(HAVE_MBSLEN)|g' \
+ -e 's|@''HAVE_MEMCHR''@|$(HAVE_MEMCHR)|g' \
-e 's|@''HAVE_DECL_MEMMEM''@|$(HAVE_DECL_MEMMEM)|g' \
-e 's|@''HAVE_MEMPCPY''@|$(HAVE_MEMPCPY)|g' \
-e 's|@''HAVE_DECL_MEMRCHR''@|$(HAVE_DECL_MEMRCHR)|g' \
+ -e 's|@''HAVE_RAWMEMCHR''@|$(HAVE_RAWMEMCHR)|g' \
-e 's|@''HAVE_STPCPY''@|$(HAVE_STPCPY)|g' \
-e 's|@''HAVE_STPNCPY''@|$(HAVE_STPNCPY)|g' \
- -e 's|@''HAVE_STRCASECMP''@|$(HAVE_STRCASECMP)|g' \
- -e 's|@''HAVE_DECL_STRNCASECMP''@|$(HAVE_DECL_STRNCASECMP)|g' \
-e 's|@''HAVE_STRCHRNUL''@|$(HAVE_STRCHRNUL)|g' \
-e 's|@''HAVE_DECL_STRDUP''@|$(HAVE_DECL_STRDUP)|g' \
- -e 's|@''HAVE_STRNDUP''@|$(HAVE_STRNDUP)|g' \
-e 's|@''HAVE_DECL_STRNDUP''@|$(HAVE_DECL_STRNDUP)|g' \
-e 's|@''HAVE_DECL_STRNLEN''@|$(HAVE_DECL_STRNLEN)|g' \
-e 's|@''HAVE_STRPBRK''@|$(HAVE_STRPBRK)|g' \
-e 's|@''HAVE_STRSEP''@|$(HAVE_STRSEP)|g' \
-e 's|@''HAVE_STRCASESTR''@|$(HAVE_STRCASESTR)|g' \
-e 's|@''HAVE_DECL_STRTOK_R''@|$(HAVE_DECL_STRTOK_R)|g' \
- -e '/definition of GL_LINK_WARNING/r $(LINK_WARNING_H)' \
- < $(srcdir)/string_.h; \
- } > $@-t
+ -e 's|@''HAVE_DECL_STRERROR_R''@|$(HAVE_DECL_STRERROR_R)|g' \
+ -e 's|@''HAVE_DECL_STRSIGNAL''@|$(HAVE_DECL_STRSIGNAL)|g' \
+ -e 's|@''HAVE_STRVERSCMP''@|$(HAVE_STRVERSCMP)|g' \
+ -e 's|@''REPLACE_STPNCPY''@|$(REPLACE_STPNCPY)|g' \
+ -e 's|@''REPLACE_MEMCHR''@|$(REPLACE_MEMCHR)|g' \
+ -e 's|@''REPLACE_MEMMEM''@|$(REPLACE_MEMMEM)|g' \
+ -e 's|@''REPLACE_STRCASESTR''@|$(REPLACE_STRCASESTR)|g' \
+ -e 's|@''REPLACE_STRCHRNUL''@|$(REPLACE_STRCHRNUL)|g' \
+ -e 's|@''REPLACE_STRDUP''@|$(REPLACE_STRDUP)|g' \
+ -e 's|@''REPLACE_STRSTR''@|$(REPLACE_STRSTR)|g' \
+ -e 's|@''REPLACE_STRERROR''@|$(REPLACE_STRERROR)|g' \
+ -e 's|@''REPLACE_STRERROR_R''@|$(REPLACE_STRERROR_R)|g' \
+ -e 's|@''REPLACE_STRNCAT''@|$(REPLACE_STRNCAT)|g' \
+ -e 's|@''REPLACE_STRNDUP''@|$(REPLACE_STRNDUP)|g' \
+ -e 's|@''REPLACE_STRNLEN''@|$(REPLACE_STRNLEN)|g' \
+ -e 's|@''REPLACE_STRSIGNAL''@|$(REPLACE_STRSIGNAL)|g' \
+ -e 's|@''REPLACE_STRTOK_R''@|$(REPLACE_STRTOK_R)|g' \
+ -e 's|@''UNDEFINE_STRTOK_R''@|$(UNDEFINE_STRTOK_R)|g' \
+ -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
+ -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
+ -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)'; \
+ < $(top_srcdir)/lib/string.in.h; \
+ } > $@-t && \
mv $@-t $@
-MOSTLYCLEANFILES += string.h string.h-t
+MOSTLYCLEANFILES += lib/string.h lib/string.h-t
-EXTRA_DIST += string_.h
+EXTRA_DIST += lib/string.in.h
## end gnulib module string
+## begin gnulib module strncat
+
+
+EXTRA_DIST += lib/strncat.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/strncat.c
+
+## end gnulib module strncat
+
## begin gnulib module strndup
-EXTRA_DIST += strndup.c
+EXTRA_DIST += lib/strndup.c
-EXTRA_libcoreutils_a_SOURCES += strndup.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/strndup.c
## end gnulib module strndup
## begin gnulib module strnlen
-EXTRA_DIST += strnlen.c
+EXTRA_DIST += lib/strnlen.c
-EXTRA_libcoreutils_a_SOURCES += strnlen.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/strnlen.c
## end gnulib module strnlen
## begin gnulib module strnlen1
-libcoreutils_a_SOURCES += strnlen1.h strnlen1.c
+lib_libcoreutils_a_SOURCES += lib/strnlen1.h lib/strnlen1.c
## end gnulib module strnlen1
+## begin gnulib module strnumcmp
+
+lib_libcoreutils_a_SOURCES += lib/strintcmp.c lib/strnumcmp.c lib/strnumcmp.h
+
+EXTRA_DIST += lib/strnumcmp-in.h
+
+## end gnulib module strnumcmp
+
## begin gnulib module strpbrk
-EXTRA_DIST += strpbrk.c
+EXTRA_DIST += lib/strpbrk.c
-EXTRA_libcoreutils_a_SOURCES += strpbrk.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/strpbrk.c
## end gnulib module strpbrk
-## begin gnulib module strtod
+## begin gnulib module strsignal
-LIBS += $(POW_LIB)
-EXTRA_DIST += strtod.c
+EXTRA_DIST += lib/siglist.h lib/strsignal.c
-EXTRA_libcoreutils_a_SOURCES += strtod.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/strsignal.c
-## end gnulib module strtod
+## end gnulib module strsignal
-## begin gnulib module strtoimax
+## begin gnulib module strstr-simple
-EXTRA_DIST += strtoimax.c
+EXTRA_DIST += lib/str-two-way.h lib/strstr.c
-EXTRA_libcoreutils_a_SOURCES += strtoimax.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/strstr.c
-## end gnulib module strtoimax
+## end gnulib module strstr-simple
-## begin gnulib module strtol
+## begin gnulib module strtod
-EXTRA_DIST += strtol.c
+EXTRA_DIST += lib/strtod.c
-EXTRA_libcoreutils_a_SOURCES += strtol.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/strtod.c
-## end gnulib module strtol
+## end gnulib module strtod
-## begin gnulib module strtoll
+## begin gnulib module strtoimax
-EXTRA_DIST += strtoll.c
+EXTRA_DIST += lib/strtoimax.c
-EXTRA_libcoreutils_a_SOURCES += strtoll.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/strtoimax.c
-## end gnulib module strtoll
+## end gnulib module strtoimax
-## begin gnulib module strtoul
+## begin gnulib module strtoll
-EXTRA_DIST += strtoul.c
+EXTRA_DIST += lib/strtol.c lib/strtoll.c
-EXTRA_libcoreutils_a_SOURCES += strtoul.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/strtol.c lib/strtoll.c
-## end gnulib module strtoul
+## end gnulib module strtoll
## begin gnulib module strtoull
-EXTRA_DIST += strtoull.c
+EXTRA_DIST += lib/strtol.c lib/strtoul.c lib/strtoull.c
-EXTRA_libcoreutils_a_SOURCES += strtoull.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/strtol.c lib/strtoul.c lib/strtoull.c
## end gnulib module strtoull
## begin gnulib module strtoumax
-EXTRA_DIST += strtoumax.c
+EXTRA_DIST += lib/strtoimax.c lib/strtoumax.c
-EXTRA_libcoreutils_a_SOURCES += strtoumax.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/strtoimax.c lib/strtoumax.c
## end gnulib module strtoumax
-## begin gnulib module strverscmp
+## begin gnulib module symlink
+
+
+EXTRA_DIST += lib/symlink.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/symlink.c
+## end gnulib module symlink
-EXTRA_DIST += strverscmp.c strverscmp.h
+## begin gnulib module sys_ioctl
+
+BUILT_SOURCES += lib/sys/ioctl.h
+
+# We need the following in order to create <sys/ioctl.h> when the system
+# does not have a complete one.
+lib/sys/ioctl.h: lib/sys_ioctl.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(WARN_ON_USE_H)
+ $(AM_V_at)$(MKDIR_P) lib/sys
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''HAVE_SYS_IOCTL_H''@|$(HAVE_SYS_IOCTL_H)|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_SYS_IOCTL_H''@|$(NEXT_SYS_IOCTL_H)|g' \
+ -e 's/@''GNULIB_IOCTL''@/$(GNULIB_IOCTL)/g' \
+ -e 's|@''SYS_IOCTL_H_HAVE_WINSOCK2_H''@|$(SYS_IOCTL_H_HAVE_WINSOCK2_H)|g' \
+ -e 's|@''SYS_IOCTL_H_HAVE_WINSOCK2_H_AND_USE_SOCKETS''@|$(SYS_IOCTL_H_HAVE_WINSOCK2_H_AND_USE_SOCKETS)|g' \
+ -e 's|@''REPLACE_IOCTL''@|$(REPLACE_IOCTL)|g' \
+ -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
+ -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
+ < $(top_srcdir)/lib/sys_ioctl.in.h; \
+ } > $@-t && \
+ mv $@-t $@
+MOSTLYCLEANFILES += lib/sys/ioctl.h lib/sys/ioctl.h-t
+MOSTLYCLEANDIRS += lib/sys
-EXTRA_libcoreutils_a_SOURCES += strverscmp.c
+EXTRA_DIST += lib/sys_ioctl.in.h
-## end gnulib module strverscmp
+## end gnulib module sys_ioctl
+
+## begin gnulib module sys_resource
+
+BUILT_SOURCES += lib/sys/resource.h
+
+# We need the following in order to create <sys/resource.h> when the system
+# doesn't have one.
+lib/sys/resource.h: lib/sys_resource.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(ARG_NONNULL_H) $(WARN_ON_USE_H)
+ $(AM_V_at)$(MKDIR_P) lib/sys
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_SYS_RESOURCE_H''@|$(NEXT_SYS_RESOURCE_H)|g' \
+ -e 's|@''HAVE_SYS_RESOURCE_H''@|$(HAVE_SYS_RESOURCE_H)|g' \
+ -e 's/@''GNULIB_GETRUSAGE''@/$(GNULIB_GETRUSAGE)/g' \
+ -e 's/@''HAVE_GETRUSAGE''@/$(HAVE_GETRUSAGE)/g' \
+ -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
+ -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
+ -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
+ < $(top_srcdir)/lib/sys_resource.in.h; \
+ } > $@-t && \
+ mv -f $@-t $@
+MOSTLYCLEANFILES += lib/sys/resource.h lib/sys/resource.h-t
+MOSTLYCLEANDIRS += lib/sys
+
+EXTRA_DIST += lib/sys_resource.in.h
+
+## end gnulib module sys_resource
+
+## begin gnulib module sys_select
+
+BUILT_SOURCES += lib/sys/select.h
+
+# We need the following in order to create <sys/select.h> when the system
+# doesn't have one that works with the given compiler.
+lib/sys/select.h: lib/sys_select.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(WARN_ON_USE_H)
+ $(AM_V_at)$(MKDIR_P) lib/sys
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_SYS_SELECT_H''@|$(NEXT_SYS_SELECT_H)|g' \
+ -e 's|@''HAVE_SYS_SELECT_H''@|$(HAVE_SYS_SELECT_H)|g' \
+ -e 's/@''GNULIB_PSELECT''@/$(GNULIB_PSELECT)/g' \
+ -e 's/@''GNULIB_SELECT''@/$(GNULIB_SELECT)/g' \
+ -e 's|@''HAVE_WINSOCK2_H''@|$(HAVE_WINSOCK2_H)|g' \
+ -e 's|@''HAVE_PSELECT''@|$(HAVE_PSELECT)|g' \
+ -e 's|@''REPLACE_PSELECT''@|$(REPLACE_PSELECT)|g' \
+ -e 's|@''REPLACE_SELECT''@|$(REPLACE_SELECT)|g' \
+ -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
+ -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
+ < $(top_srcdir)/lib/sys_select.in.h; \
+ } > $@-t && \
+ mv $@-t $@
+MOSTLYCLEANFILES += lib/sys/select.h lib/sys/select.h-t
+MOSTLYCLEANDIRS += lib/sys
+
+EXTRA_DIST += lib/sys_select.in.h
+
+## end gnulib module sys_select
## begin gnulib module sys_socket
-BUILT_SOURCES += $(SYS_SOCKET_H)
+BUILT_SOURCES += lib/sys/socket.h
+lib_libcoreutils_a_SOURCES += lib/sys_socket.c
# We need the following in order to create <sys/socket.h> when the system
# doesn't have one that works with the given compiler.
-sys/socket.h: socket_.h
- @MKDIR_P@ sys
+lib/sys/socket.h: lib/sys_socket.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(WARN_ON_USE_H) $(ARG_NONNULL_H)
+ $(AM_V_at)$(MKDIR_P) lib/sys
+ $(AM_V_GEN)rm -f $@-t $@ && \
{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
- sed -e 's|@''ABSOLUTE_SYS_SOCKET_H''@|$(ABSOLUTE_SYS_SOCKET_H)|g' \
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_SYS_SOCKET_H''@|$(NEXT_SYS_SOCKET_H)|g' \
-e 's|@''HAVE_SYS_SOCKET_H''@|$(HAVE_SYS_SOCKET_H)|g' \
+ -e 's/@''GNULIB_CLOSE''@/$(GNULIB_CLOSE)/g' \
+ -e 's/@''GNULIB_SOCKET''@/$(GNULIB_SOCKET)/g' \
+ -e 's/@''GNULIB_CONNECT''@/$(GNULIB_CONNECT)/g' \
+ -e 's/@''GNULIB_ACCEPT''@/$(GNULIB_ACCEPT)/g' \
+ -e 's/@''GNULIB_BIND''@/$(GNULIB_BIND)/g' \
+ -e 's/@''GNULIB_GETPEERNAME''@/$(GNULIB_GETPEERNAME)/g' \
+ -e 's/@''GNULIB_GETSOCKNAME''@/$(GNULIB_GETSOCKNAME)/g' \
+ -e 's/@''GNULIB_GETSOCKOPT''@/$(GNULIB_GETSOCKOPT)/g' \
+ -e 's/@''GNULIB_LISTEN''@/$(GNULIB_LISTEN)/g' \
+ -e 's/@''GNULIB_RECV''@/$(GNULIB_RECV)/g' \
+ -e 's/@''GNULIB_SEND''@/$(GNULIB_SEND)/g' \
+ -e 's/@''GNULIB_RECVFROM''@/$(GNULIB_RECVFROM)/g' \
+ -e 's/@''GNULIB_SENDTO''@/$(GNULIB_SENDTO)/g' \
+ -e 's/@''GNULIB_SETSOCKOPT''@/$(GNULIB_SETSOCKOPT)/g' \
+ -e 's/@''GNULIB_SHUTDOWN''@/$(GNULIB_SHUTDOWN)/g' \
+ -e 's/@''GNULIB_ACCEPT4''@/$(GNULIB_ACCEPT4)/g' \
-e 's|@''HAVE_WINSOCK2_H''@|$(HAVE_WINSOCK2_H)|g' \
-e 's|@''HAVE_WS2TCPIP_H''@|$(HAVE_WS2TCPIP_H)|g' \
- < $(srcdir)/socket_.h; \
- } > $@-t
+ -e 's|@''HAVE_STRUCT_SOCKADDR_STORAGE''@|$(HAVE_STRUCT_SOCKADDR_STORAGE)|g' \
+ -e 's|@''HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY''@|$(HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY)|g' \
+ -e 's|@''HAVE_SA_FAMILY_T''@|$(HAVE_SA_FAMILY_T)|g' \
+ -e 's|@''HAVE_ACCEPT4''@|$(HAVE_ACCEPT4)|g' \
+ -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
+ -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
+ -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
+ < $(top_srcdir)/lib/sys_socket.in.h; \
+ } > $@-t && \
mv -f $@-t $@
-MOSTLYCLEANFILES += sys/socket.h sys/socket.h-t
-MOSTLYCLEANDIRS += sys
+MOSTLYCLEANFILES += lib/sys/socket.h lib/sys/socket.h-t
+MOSTLYCLEANDIRS += lib/sys
-EXTRA_DIST += socket_.h
+EXTRA_DIST += lib/sys_socket.in.h
## end gnulib module sys_socket
## begin gnulib module sys_stat
-BUILT_SOURCES += $(SYS_STAT_H)
+BUILT_SOURCES += lib/sys/stat.h
# We need the following in order to create <sys/stat.h> when the system
# has one that is incomplete.
-sys/stat.h: stat_.h
- @MKDIR_P@ sys
- rm -f $@-t $@
+lib/sys/stat.h: lib/sys_stat.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(ARG_NONNULL_H) $(WARN_ON_USE_H)
+ $(AM_V_at)$(MKDIR_P) lib/sys
+ $(AM_V_GEN)rm -f $@-t $@ && \
{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
- sed -e 's|@''ABSOLUTE_SYS_STAT_H''@|$(ABSOLUTE_SYS_STAT_H)|g' \
- < $(srcdir)/stat_.h; \
- } > $@-t
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_SYS_STAT_H''@|$(NEXT_SYS_STAT_H)|g' \
+ -e 's|@''WINDOWS_64_BIT_ST_SIZE''@|$(WINDOWS_64_BIT_ST_SIZE)|g' \
+ -e 's/@''GNULIB_FCHMODAT''@/$(GNULIB_FCHMODAT)/g' \
+ -e 's/@''GNULIB_FSTAT''@/$(GNULIB_FSTAT)/g' \
+ -e 's/@''GNULIB_FSTATAT''@/$(GNULIB_FSTATAT)/g' \
+ -e 's/@''GNULIB_FUTIMENS''@/$(GNULIB_FUTIMENS)/g' \
+ -e 's/@''GNULIB_LCHMOD''@/$(GNULIB_LCHMOD)/g' \
+ -e 's/@''GNULIB_LSTAT''@/$(GNULIB_LSTAT)/g' \
+ -e 's/@''GNULIB_MKDIRAT''@/$(GNULIB_MKDIRAT)/g' \
+ -e 's/@''GNULIB_MKFIFO''@/$(GNULIB_MKFIFO)/g' \
+ -e 's/@''GNULIB_MKFIFOAT''@/$(GNULIB_MKFIFOAT)/g' \
+ -e 's/@''GNULIB_MKNOD''@/$(GNULIB_MKNOD)/g' \
+ -e 's/@''GNULIB_MKNODAT''@/$(GNULIB_MKNODAT)/g' \
+ -e 's/@''GNULIB_STAT''@/$(GNULIB_STAT)/g' \
+ -e 's/@''GNULIB_UTIMENSAT''@/$(GNULIB_UTIMENSAT)/g' \
+ -e 's|@''HAVE_FCHMODAT''@|$(HAVE_FCHMODAT)|g' \
+ -e 's|@''HAVE_FSTATAT''@|$(HAVE_FSTATAT)|g' \
+ -e 's|@''HAVE_FUTIMENS''@|$(HAVE_FUTIMENS)|g' \
+ -e 's|@''HAVE_LCHMOD''@|$(HAVE_LCHMOD)|g' \
+ -e 's|@''HAVE_LSTAT''@|$(HAVE_LSTAT)|g' \
+ -e 's|@''HAVE_MKDIRAT''@|$(HAVE_MKDIRAT)|g' \
+ -e 's|@''HAVE_MKFIFO''@|$(HAVE_MKFIFO)|g' \
+ -e 's|@''HAVE_MKFIFOAT''@|$(HAVE_MKFIFOAT)|g' \
+ -e 's|@''HAVE_MKNOD''@|$(HAVE_MKNOD)|g' \
+ -e 's|@''HAVE_MKNODAT''@|$(HAVE_MKNODAT)|g' \
+ -e 's|@''HAVE_UTIMENSAT''@|$(HAVE_UTIMENSAT)|g' \
+ -e 's|@''REPLACE_FSTAT''@|$(REPLACE_FSTAT)|g' \
+ -e 's|@''REPLACE_FSTATAT''@|$(REPLACE_FSTATAT)|g' \
+ -e 's|@''REPLACE_FUTIMENS''@|$(REPLACE_FUTIMENS)|g' \
+ -e 's|@''REPLACE_LSTAT''@|$(REPLACE_LSTAT)|g' \
+ -e 's|@''REPLACE_MKDIR''@|$(REPLACE_MKDIR)|g' \
+ -e 's|@''REPLACE_MKFIFO''@|$(REPLACE_MKFIFO)|g' \
+ -e 's|@''REPLACE_MKNOD''@|$(REPLACE_MKNOD)|g' \
+ -e 's|@''REPLACE_STAT''@|$(REPLACE_STAT)|g' \
+ -e 's|@''REPLACE_UTIMENSAT''@|$(REPLACE_UTIMENSAT)|g' \
+ -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
+ -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
+ -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
+ < $(top_srcdir)/lib/sys_stat.in.h; \
+ } > $@-t && \
mv $@-t $@
-MOSTLYCLEANFILES += sys/stat.h sys/stat.h-t
-MOSTLYCLEANDIRS += sys
+MOSTLYCLEANFILES += lib/sys/stat.h lib/sys/stat.h-t
+MOSTLYCLEANDIRS += lib/sys
-EXTRA_DIST += stat_.h
+EXTRA_DIST += lib/sys_stat.in.h
## end gnulib module sys_stat
## begin gnulib module sys_time
-BUILT_SOURCES += $(SYS_TIME_H)
+BUILT_SOURCES += lib/sys/time.h
# We need the following in order to create <sys/time.h> when the system
# doesn't have one that works with the given compiler.
-sys/time.h: sys_time_.h
- @MKDIR_P@ sys
- rm -f $@-t $@
+lib/sys/time.h: lib/sys_time.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(ARG_NONNULL_H) $(WARN_ON_USE_H)
+ $(AM_V_at)$(MKDIR_P) lib/sys
+ $(AM_V_GEN)rm -f $@-t $@ && \
{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
- sed -e 's/@''HAVE_SYS_TIME_H''@/$(HAVE_SYS_TIME_H)/g' \
- -e 's|@''ABSOLUTE_SYS_TIME_H''@|$(ABSOLUTE_SYS_TIME_H)|g' \
- -e 's/@''REPLACE_GETTIMEOFDAY''@/$(REPLACE_GETTIMEOFDAY)/g' \
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's/@''HAVE_SYS_TIME_H''@/$(HAVE_SYS_TIME_H)/g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_SYS_TIME_H''@|$(NEXT_SYS_TIME_H)|g' \
+ -e 's/@''GNULIB_GETTIMEOFDAY''@/$(GNULIB_GETTIMEOFDAY)/g' \
+ -e 's|@''HAVE_WINSOCK2_H''@|$(HAVE_WINSOCK2_H)|g' \
+ -e 's/@''HAVE_GETTIMEOFDAY''@/$(HAVE_GETTIMEOFDAY)/g' \
-e 's/@''HAVE_STRUCT_TIMEVAL''@/$(HAVE_STRUCT_TIMEVAL)/g' \
- < $(srcdir)/sys_time_.h; \
- } > $@-t
+ -e 's/@''REPLACE_GETTIMEOFDAY''@/$(REPLACE_GETTIMEOFDAY)/g' \
+ -e 's/@''REPLACE_STRUCT_TIMEVAL''@/$(REPLACE_STRUCT_TIMEVAL)/g' \
+ -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
+ -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
+ -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
+ < $(top_srcdir)/lib/sys_time.in.h; \
+ } > $@-t && \
mv $@-t $@
-MOSTLYCLEANFILES += sys/time.h sys/time.h-t
+MOSTLYCLEANFILES += lib/sys/time.h lib/sys/time.h-t
-EXTRA_DIST += sys_time_.h
+EXTRA_DIST += lib/sys_time.in.h
## end gnulib module sys_time
-## begin gnulib module tempname
+## begin gnulib module sys_types
+
+BUILT_SOURCES += lib/sys/types.h
+
+# We need the following in order to create <sys/types.h> when the system
+# doesn't have one that works with the given compiler.
+lib/sys/types.h: lib/sys_types.in.h $(top_builddir)/config.status
+ $(AM_V_at)$(MKDIR_P) lib/sys
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_SYS_TYPES_H''@|$(NEXT_SYS_TYPES_H)|g' \
+ -e 's|@''WINDOWS_64_BIT_OFF_T''@|$(WINDOWS_64_BIT_OFF_T)|g' \
+ < $(top_srcdir)/lib/sys_types.in.h; \
+ } > $@-t && \
+ mv $@-t $@
+MOSTLYCLEANFILES += lib/sys/types.h lib/sys/types.h-t
+
+EXTRA_DIST += lib/sys_types.in.h
+
+## end gnulib module sys_types
+
+## begin gnulib module sys_uio
+
+BUILT_SOURCES += lib/sys/uio.h
+
+# We need the following in order to create <sys/uio.h> when the system
+# doesn't have one that works with the given compiler.
+lib/sys/uio.h: lib/sys_uio.in.h $(top_builddir)/config.status
+ $(AM_V_at)$(MKDIR_P) lib/sys
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_SYS_UIO_H''@|$(NEXT_SYS_UIO_H)|g' \
+ -e 's|@''HAVE_SYS_UIO_H''@|$(HAVE_SYS_UIO_H)|g' \
+ < $(top_srcdir)/lib/sys_uio.in.h; \
+ } > $@-t && \
+ mv -f $@-t $@
+MOSTLYCLEANFILES += lib/sys/uio.h lib/sys/uio.h-t
+MOSTLYCLEANDIRS += lib/sys
+
+EXTRA_DIST += lib/sys_uio.in.h
+
+## end gnulib module sys_uio
+## begin gnulib module sys_utsname
-EXTRA_DIST += tempname.c tempname.h
+BUILT_SOURCES += lib/sys/utsname.h
-EXTRA_libcoreutils_a_SOURCES += tempname.c
+# We need the following in order to create <sys/utsname.h> when the system
+# does not have one.
+lib/sys/utsname.h: lib/sys_utsname.in.h $(top_builddir)/config.status $(WARN_ON_USE_H) $(ARG_NONNULL_H)
+ $(AM_V_at)$(MKDIR_P) lib/sys
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's/@''HAVE_SYS_UTSNAME_H''@/$(HAVE_SYS_UTSNAME_H)/g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_SYS_UTSNAME_H''@|$(NEXT_SYS_UTSNAME_H)|g' \
+ -e 's/@''GNULIB_UNAME''@/$(GNULIB_UNAME)/g' \
+ -e 's|@''HAVE_STRUCT_UTSNAME''@|$(HAVE_STRUCT_UTSNAME)|g' \
+ -e 's|@''HAVE_UNAME''@|$(HAVE_UNAME)|g' \
+ -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
+ -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
+ < $(top_srcdir)/lib/sys_utsname.in.h; \
+ } > $@-t && \
+ mv $@-t $@
+MOSTLYCLEANFILES += lib/sys/utsname.h lib/sys/utsname.h-t
+MOSTLYCLEANDIRS += lib/sys
+
+EXTRA_DIST += lib/sys_utsname.in.h
+
+## end gnulib module sys_utsname
+
+## begin gnulib module sys_wait
+
+BUILT_SOURCES += lib/sys/wait.h
+
+# We need the following in order to create <sys/wait.h> when the system
+# has one that is incomplete.
+lib/sys/wait.h: lib/sys_wait.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(WARN_ON_USE_H)
+ $(AM_V_at)$(MKDIR_P) lib/sys
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_SYS_WAIT_H''@|$(NEXT_SYS_WAIT_H)|g' \
+ -e 's/@''GNULIB_WAITPID''@/$(GNULIB_WAITPID)/g' \
+ -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
+ -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
+ < $(top_srcdir)/lib/sys_wait.in.h; \
+ } > $@-t && \
+ mv $@-t $@
+MOSTLYCLEANFILES += lib/sys/wait.h lib/sys/wait.h-t
+MOSTLYCLEANDIRS += lib/sys
+
+EXTRA_DIST += lib/sys_wait.in.h
+
+## end gnulib module sys_wait
+
+## begin gnulib module tempname
+
+lib_libcoreutils_a_SOURCES += lib/tempname.c
+
+EXTRA_DIST += lib/tempname.h
## end gnulib module tempname
+## begin gnulib module termios
+
+BUILT_SOURCES += lib/termios.h
+
+# We need the following in order to create <termios.h> when the system
+# version does not have all declarations.
+lib/termios.h: lib/termios.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(WARN_ON_USE_H)
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_TERMIOS_H''@|$(NEXT_TERMIOS_H)|g' \
+ -e 's/@''GNULIB_TCGETSID''@/$(GNULIB_TCGETSID)/g' \
+ -e 's|@''HAVE_DECL_TCGETSID''@|$(HAVE_DECL_TCGETSID)|g' \
+ -e 's|@''HAVE_TERMIOS_H''@|$(HAVE_TERMIOS_H)|g' \
+ -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
+ -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
+ < $(top_srcdir)/lib/termios.in.h; \
+ } > $@-t && \
+ mv $@-t $@
+MOSTLYCLEANFILES += lib/termios.h lib/termios.h-t
+
+EXTRA_DIST += lib/termios.in.h
+
+## end gnulib module termios
+
+## begin gnulib module threadlib
+
+lib_libcoreutils_a_SOURCES += lib/glthread/threadlib.c
+
+EXTRA_DIST += $(top_srcdir)/build-aux/config.rpath
+
+## end gnulib module threadlib
+
## begin gnulib module time
-BUILT_SOURCES += time.h
+BUILT_SOURCES += lib/time.h
# We need the following in order to create <time.h> when the system
# doesn't have one that works with the given compiler.
-time.h: time_.h
- rm -f $@-t $@
+lib/time.h: lib/time.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(ARG_NONNULL_H) $(WARN_ON_USE_H)
+ $(AM_V_GEN)rm -f $@-t $@ && \
{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */' && \
- sed -e 's|@ABSOLUTE_TIME_H''@|$(ABSOLUTE_TIME_H)|g' \
- -e 's|@REPLACE_LOCALTIME_R''@|$(REPLACE_LOCALTIME_R)|g' \
- -e 's|@REPLACE_NANOSLEEP''@|$(REPLACE_NANOSLEEP)|g' \
- -e 's|@REPLACE_STRPTIME''@|$(REPLACE_STRPTIME)|g' \
- -e 's|@REPLACE_TIMEGM''@|$(REPLACE_TIMEGM)|g' \
- -e 's|@SYS_TIME_H_DEFINES_STRUCT_TIMESPEC''@|$(SYS_TIME_H_DEFINES_STRUCT_TIMESPEC)|g' \
- -e 's|@TIME_H_DEFINES_STRUCT_TIMESPEC''@|$(TIME_H_DEFINES_STRUCT_TIMESPEC)|g' \
- < $(srcdir)/time_.h; \
- } > $@-t
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_TIME_H''@|$(NEXT_TIME_H)|g' \
+ -e 's/@''GNULIB_GETTIMEOFDAY''@/$(GNULIB_GETTIMEOFDAY)/g' \
+ -e 's/@''GNULIB_MKTIME''@/$(GNULIB_MKTIME)/g' \
+ -e 's/@''GNULIB_NANOSLEEP''@/$(GNULIB_NANOSLEEP)/g' \
+ -e 's/@''GNULIB_STRPTIME''@/$(GNULIB_STRPTIME)/g' \
+ -e 's/@''GNULIB_TIMEGM''@/$(GNULIB_TIMEGM)/g' \
+ -e 's/@''GNULIB_TIME_R''@/$(GNULIB_TIME_R)/g' \
+ -e 's/@''GNULIB_TIME_RZ''@/$(GNULIB_TIME_RZ)/g' \
+ -e 's|@''HAVE_DECL_LOCALTIME_R''@|$(HAVE_DECL_LOCALTIME_R)|g' \
+ -e 's|@''HAVE_NANOSLEEP''@|$(HAVE_NANOSLEEP)|g' \
+ -e 's|@''HAVE_STRPTIME''@|$(HAVE_STRPTIME)|g' \
+ -e 's|@''HAVE_TIMEGM''@|$(HAVE_TIMEGM)|g' \
+ -e 's|@''HAVE_TIMEZONE_T''@|$(HAVE_TIMEZONE_T)|g' \
+ -e 's|@''REPLACE_GMTIME''@|$(REPLACE_GMTIME)|g' \
+ -e 's|@''REPLACE_LOCALTIME''@|$(REPLACE_LOCALTIME)|g' \
+ -e 's|@''REPLACE_LOCALTIME_R''@|$(REPLACE_LOCALTIME_R)|g' \
+ -e 's|@''REPLACE_MKTIME''@|$(REPLACE_MKTIME)|g' \
+ -e 's|@''REPLACE_NANOSLEEP''@|$(REPLACE_NANOSLEEP)|g' \
+ -e 's|@''REPLACE_TIMEGM''@|$(REPLACE_TIMEGM)|g' \
+ -e 's|@''PTHREAD_H_DEFINES_STRUCT_TIMESPEC''@|$(PTHREAD_H_DEFINES_STRUCT_TIMESPEC)|g' \
+ -e 's|@''SYS_TIME_H_DEFINES_STRUCT_TIMESPEC''@|$(SYS_TIME_H_DEFINES_STRUCT_TIMESPEC)|g' \
+ -e 's|@''TIME_H_DEFINES_STRUCT_TIMESPEC''@|$(TIME_H_DEFINES_STRUCT_TIMESPEC)|g' \
+ -e 's|@''UNISTD_H_DEFINES_STRUCT_TIMESPEC''@|$(UNISTD_H_DEFINES_STRUCT_TIMESPEC)|g' \
+ -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
+ -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
+ -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
+ < $(top_srcdir)/lib/time.in.h; \
+ } > $@-t && \
mv $@-t $@
-MOSTLYCLEANFILES += time.h time.h-t
+MOSTLYCLEANFILES += lib/time.h lib/time.h-t
-EXTRA_DIST += time_.h
+EXTRA_DIST += lib/time.in.h
## end gnulib module time
## begin gnulib module time_r
-EXTRA_DIST += time_r.c
+EXTRA_DIST += lib/time_r.c
-EXTRA_libcoreutils_a_SOURCES += time_r.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/time_r.c
## end gnulib module time_r
+## begin gnulib module time_rz
+
+
+EXTRA_DIST += lib/time-internal.h lib/time_rz.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/time_rz.c
+
+## end gnulib module time_rz
+
+## begin gnulib module timegm
+
+
+EXTRA_DIST += lib/mktime-internal.h lib/timegm.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/timegm.c
+
+## end gnulib module timegm
+
## begin gnulib module timespec
+lib_libcoreutils_a_SOURCES += lib/timespec.c
-EXTRA_DIST += timespec.h
+EXTRA_DIST += lib/timespec.h
## end gnulib module timespec
+## begin gnulib module tls
+
+lib_libcoreutils_a_SOURCES += lib/glthread/tls.h lib/glthread/tls.c
+
+## end gnulib module tls
+
+## begin gnulib module trim
+
+lib_libcoreutils_a_SOURCES += lib/trim.c
+
+EXTRA_DIST += lib/trim.h
+
+## end gnulib module trim
+
+## begin gnulib module u64
+
+lib_libcoreutils_a_SOURCES += lib/u64.c
+
+EXTRA_DIST += lib/u64.h
+
+## end gnulib module u64
+
+## begin gnulib module uname
+
+
+EXTRA_DIST += lib/uname.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/uname.c
+
+## end gnulib module uname
+
## begin gnulib module unicodeio
-libcoreutils_a_SOURCES += unicodeio.h unicodeio.c
+lib_libcoreutils_a_SOURCES += lib/unicodeio.h lib/unicodeio.c
## end gnulib module unicodeio
## begin gnulib module unistd
-BUILT_SOURCES += unistd.h
+BUILT_SOURCES += lib/unistd.h
+lib_libcoreutils_a_SOURCES += lib/unistd.c
# We need the following in order to create an empty placeholder for
# <unistd.h> when the system doesn't have one.
-unistd.h: unistd_.h
- rm -f $@-t $@
+lib/unistd.h: lib/unistd.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(ARG_NONNULL_H) $(WARN_ON_USE_H)
+ $(AM_V_GEN)rm -f $@-t $@ && \
{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
- sed -e 's|@''HAVE_UNISTD_H''@|$(HAVE_UNISTD_H)|g' \
- -e 's|@''ABSOLUTE_UNISTD_H''@|$(ABSOLUTE_UNISTD_H)|g' \
- -e 's|@''GNULIB_CHOWN''@|$(GNULIB_CHOWN)|g' \
- -e 's|@''GNULIB_DUP2''@|$(GNULIB_DUP2)|g' \
- -e 's|@''GNULIB_FCHDIR''@|$(GNULIB_FCHDIR)|g' \
- -e 's|@''GNULIB_FTRUNCATE''@|$(GNULIB_FTRUNCATE)|g' \
- -e 's|@''GNULIB_GETCWD''@|$(GNULIB_GETCWD)|g' \
- -e 's|@''GNULIB_GETLOGIN_R''@|$(GNULIB_GETLOGIN_R)|g' \
- -e 's|@''GNULIB_READLINK''@|$(GNULIB_READLINK)|g' \
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''HAVE_UNISTD_H''@|$(HAVE_UNISTD_H)|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_UNISTD_H''@|$(NEXT_UNISTD_H)|g' \
+ -e 's|@''WINDOWS_64_BIT_OFF_T''@|$(WINDOWS_64_BIT_OFF_T)|g' \
+ -e 's/@''GNULIB_CHDIR''@/$(GNULIB_CHDIR)/g' \
+ -e 's/@''GNULIB_CHOWN''@/$(GNULIB_CHOWN)/g' \
+ -e 's/@''GNULIB_CLOSE''@/$(GNULIB_CLOSE)/g' \
+ -e 's/@''GNULIB_DUP''@/$(GNULIB_DUP)/g' \
+ -e 's/@''GNULIB_DUP2''@/$(GNULIB_DUP2)/g' \
+ -e 's/@''GNULIB_DUP3''@/$(GNULIB_DUP3)/g' \
+ -e 's/@''GNULIB_ENVIRON''@/$(GNULIB_ENVIRON)/g' \
+ -e 's/@''GNULIB_EUIDACCESS''@/$(GNULIB_EUIDACCESS)/g' \
+ -e 's/@''GNULIB_FACCESSAT''@/$(GNULIB_FACCESSAT)/g' \
+ -e 's/@''GNULIB_FCHDIR''@/$(GNULIB_FCHDIR)/g' \
+ -e 's/@''GNULIB_FCHOWNAT''@/$(GNULIB_FCHOWNAT)/g' \
+ -e 's/@''GNULIB_FDATASYNC''@/$(GNULIB_FDATASYNC)/g' \
+ -e 's/@''GNULIB_FSYNC''@/$(GNULIB_FSYNC)/g' \
+ -e 's/@''GNULIB_FTRUNCATE''@/$(GNULIB_FTRUNCATE)/g' \
+ -e 's/@''GNULIB_GETCWD''@/$(GNULIB_GETCWD)/g' \
+ -e 's/@''GNULIB_GETDOMAINNAME''@/$(GNULIB_GETDOMAINNAME)/g' \
+ -e 's/@''GNULIB_GETDTABLESIZE''@/$(GNULIB_GETDTABLESIZE)/g' \
+ -e 's/@''GNULIB_GETGROUPS''@/$(GNULIB_GETGROUPS)/g' \
+ -e 's/@''GNULIB_GETHOSTNAME''@/$(GNULIB_GETHOSTNAME)/g' \
+ -e 's/@''GNULIB_GETLOGIN''@/$(GNULIB_GETLOGIN)/g' \
+ -e 's/@''GNULIB_GETLOGIN_R''@/$(GNULIB_GETLOGIN_R)/g' \
+ -e 's/@''GNULIB_GETPAGESIZE''@/$(GNULIB_GETPAGESIZE)/g' \
+ -e 's/@''GNULIB_GETUSERSHELL''@/$(GNULIB_GETUSERSHELL)/g' \
+ -e 's/@''GNULIB_GROUP_MEMBER''@/$(GNULIB_GROUP_MEMBER)/g' \
+ -e 's/@''GNULIB_ISATTY''@/$(GNULIB_ISATTY)/g' \
+ -e 's/@''GNULIB_LCHOWN''@/$(GNULIB_LCHOWN)/g' \
+ -e 's/@''GNULIB_LINK''@/$(GNULIB_LINK)/g' \
+ -e 's/@''GNULIB_LINKAT''@/$(GNULIB_LINKAT)/g' \
+ -e 's/@''GNULIB_LSEEK''@/$(GNULIB_LSEEK)/g' \
+ -e 's/@''GNULIB_PIPE''@/$(GNULIB_PIPE)/g' \
+ -e 's/@''GNULIB_PIPE2''@/$(GNULIB_PIPE2)/g' \
+ -e 's/@''GNULIB_PREAD''@/$(GNULIB_PREAD)/g' \
+ -e 's/@''GNULIB_PWRITE''@/$(GNULIB_PWRITE)/g' \
+ -e 's/@''GNULIB_READ''@/$(GNULIB_READ)/g' \
+ -e 's/@''GNULIB_READLINK''@/$(GNULIB_READLINK)/g' \
+ -e 's/@''GNULIB_READLINKAT''@/$(GNULIB_READLINKAT)/g' \
+ -e 's/@''GNULIB_RMDIR''@/$(GNULIB_RMDIR)/g' \
+ -e 's/@''GNULIB_SETHOSTNAME''@/$(GNULIB_SETHOSTNAME)/g' \
+ -e 's/@''GNULIB_SLEEP''@/$(GNULIB_SLEEP)/g' \
+ -e 's/@''GNULIB_SYMLINK''@/$(GNULIB_SYMLINK)/g' \
+ -e 's/@''GNULIB_SYMLINKAT''@/$(GNULIB_SYMLINKAT)/g' \
+ -e 's/@''GNULIB_TTYNAME_R''@/$(GNULIB_TTYNAME_R)/g' \
+ -e 's/@''GNULIB_UNISTD_H_GETOPT''@/0$(GNULIB_GL_UNISTD_H_GETOPT)/g' \
+ -e 's/@''GNULIB_UNISTD_H_NONBLOCKING''@/$(GNULIB_UNISTD_H_NONBLOCKING)/g' \
+ -e 's/@''GNULIB_UNISTD_H_SIGPIPE''@/$(GNULIB_UNISTD_H_SIGPIPE)/g' \
+ -e 's/@''GNULIB_UNLINK''@/$(GNULIB_UNLINK)/g' \
+ -e 's/@''GNULIB_UNLINKAT''@/$(GNULIB_UNLINKAT)/g' \
+ -e 's/@''GNULIB_USLEEP''@/$(GNULIB_USLEEP)/g' \
+ -e 's/@''GNULIB_WRITE''@/$(GNULIB_WRITE)/g' \
+ < $(top_srcdir)/lib/unistd.in.h | \
+ sed -e 's|@''HAVE_CHOWN''@|$(HAVE_CHOWN)|g' \
-e 's|@''HAVE_DUP2''@|$(HAVE_DUP2)|g' \
+ -e 's|@''HAVE_DUP3''@|$(HAVE_DUP3)|g' \
+ -e 's|@''HAVE_EUIDACCESS''@|$(HAVE_EUIDACCESS)|g' \
+ -e 's|@''HAVE_FACCESSAT''@|$(HAVE_FACCESSAT)|g' \
+ -e 's|@''HAVE_FCHDIR''@|$(HAVE_FCHDIR)|g' \
+ -e 's|@''HAVE_FCHOWNAT''@|$(HAVE_FCHOWNAT)|g' \
+ -e 's|@''HAVE_FDATASYNC''@|$(HAVE_FDATASYNC)|g' \
+ -e 's|@''HAVE_FSYNC''@|$(HAVE_FSYNC)|g' \
-e 's|@''HAVE_FTRUNCATE''@|$(HAVE_FTRUNCATE)|g' \
+ -e 's|@''HAVE_GETDTABLESIZE''@|$(HAVE_GETDTABLESIZE)|g' \
+ -e 's|@''HAVE_GETGROUPS''@|$(HAVE_GETGROUPS)|g' \
+ -e 's|@''HAVE_GETHOSTNAME''@|$(HAVE_GETHOSTNAME)|g' \
+ -e 's|@''HAVE_GETLOGIN''@|$(HAVE_GETLOGIN)|g' \
+ -e 's|@''HAVE_GETPAGESIZE''@|$(HAVE_GETPAGESIZE)|g' \
+ -e 's|@''HAVE_GROUP_MEMBER''@|$(HAVE_GROUP_MEMBER)|g' \
+ -e 's|@''HAVE_LCHOWN''@|$(HAVE_LCHOWN)|g' \
+ -e 's|@''HAVE_LINK''@|$(HAVE_LINK)|g' \
+ -e 's|@''HAVE_LINKAT''@|$(HAVE_LINKAT)|g' \
+ -e 's|@''HAVE_PIPE''@|$(HAVE_PIPE)|g' \
+ -e 's|@''HAVE_PIPE2''@|$(HAVE_PIPE2)|g' \
+ -e 's|@''HAVE_PREAD''@|$(HAVE_PREAD)|g' \
+ -e 's|@''HAVE_PWRITE''@|$(HAVE_PWRITE)|g' \
-e 's|@''HAVE_READLINK''@|$(HAVE_READLINK)|g' \
+ -e 's|@''HAVE_READLINKAT''@|$(HAVE_READLINKAT)|g' \
+ -e 's|@''HAVE_SETHOSTNAME''@|$(HAVE_SETHOSTNAME)|g' \
+ -e 's|@''HAVE_SLEEP''@|$(HAVE_SLEEP)|g' \
+ -e 's|@''HAVE_SYMLINK''@|$(HAVE_SYMLINK)|g' \
+ -e 's|@''HAVE_SYMLINKAT''@|$(HAVE_SYMLINKAT)|g' \
+ -e 's|@''HAVE_UNLINKAT''@|$(HAVE_UNLINKAT)|g' \
+ -e 's|@''HAVE_USLEEP''@|$(HAVE_USLEEP)|g' \
+ -e 's|@''HAVE_DECL_ENVIRON''@|$(HAVE_DECL_ENVIRON)|g' \
+ -e 's|@''HAVE_DECL_FCHDIR''@|$(HAVE_DECL_FCHDIR)|g' \
+ -e 's|@''HAVE_DECL_FDATASYNC''@|$(HAVE_DECL_FDATASYNC)|g' \
+ -e 's|@''HAVE_DECL_GETDOMAINNAME''@|$(HAVE_DECL_GETDOMAINNAME)|g' \
-e 's|@''HAVE_DECL_GETLOGIN_R''@|$(HAVE_DECL_GETLOGIN_R)|g' \
- -e 's|@''REPLACE_CHOWN''@|$(REPLACE_CHOWN)|g' \
- -e 's|@''REPLACE_FCHDIR''@|$(REPLACE_FCHDIR)|g' \
+ -e 's|@''HAVE_DECL_GETPAGESIZE''@|$(HAVE_DECL_GETPAGESIZE)|g' \
+ -e 's|@''HAVE_DECL_GETUSERSHELL''@|$(HAVE_DECL_GETUSERSHELL)|g' \
+ -e 's|@''HAVE_DECL_SETHOSTNAME''@|$(HAVE_DECL_SETHOSTNAME)|g' \
+ -e 's|@''HAVE_DECL_TTYNAME_R''@|$(HAVE_DECL_TTYNAME_R)|g' \
+ -e 's|@''HAVE_OS_H''@|$(HAVE_OS_H)|g' \
+ -e 's|@''HAVE_SYS_PARAM_H''@|$(HAVE_SYS_PARAM_H)|g' \
+ | \
+ sed -e 's|@''REPLACE_CHOWN''@|$(REPLACE_CHOWN)|g' \
+ -e 's|@''REPLACE_CLOSE''@|$(REPLACE_CLOSE)|g' \
+ -e 's|@''REPLACE_DUP''@|$(REPLACE_DUP)|g' \
+ -e 's|@''REPLACE_DUP2''@|$(REPLACE_DUP2)|g' \
+ -e 's|@''REPLACE_FCHOWNAT''@|$(REPLACE_FCHOWNAT)|g' \
+ -e 's|@''REPLACE_FTRUNCATE''@|$(REPLACE_FTRUNCATE)|g' \
-e 's|@''REPLACE_GETCWD''@|$(REPLACE_GETCWD)|g' \
- < $(srcdir)/unistd_.h; \
- } > $@-t
+ -e 's|@''REPLACE_GETDOMAINNAME''@|$(REPLACE_GETDOMAINNAME)|g' \
+ -e 's|@''REPLACE_GETDTABLESIZE''@|$(REPLACE_GETDTABLESIZE)|g' \
+ -e 's|@''REPLACE_GETLOGIN_R''@|$(REPLACE_GETLOGIN_R)|g' \
+ -e 's|@''REPLACE_GETGROUPS''@|$(REPLACE_GETGROUPS)|g' \
+ -e 's|@''REPLACE_GETPAGESIZE''@|$(REPLACE_GETPAGESIZE)|g' \
+ -e 's|@''REPLACE_ISATTY''@|$(REPLACE_ISATTY)|g' \
+ -e 's|@''REPLACE_LCHOWN''@|$(REPLACE_LCHOWN)|g' \
+ -e 's|@''REPLACE_LINK''@|$(REPLACE_LINK)|g' \
+ -e 's|@''REPLACE_LINKAT''@|$(REPLACE_LINKAT)|g' \
+ -e 's|@''REPLACE_LSEEK''@|$(REPLACE_LSEEK)|g' \
+ -e 's|@''REPLACE_PREAD''@|$(REPLACE_PREAD)|g' \
+ -e 's|@''REPLACE_PWRITE''@|$(REPLACE_PWRITE)|g' \
+ -e 's|@''REPLACE_READ''@|$(REPLACE_READ)|g' \
+ -e 's|@''REPLACE_READLINK''@|$(REPLACE_READLINK)|g' \
+ -e 's|@''REPLACE_READLINKAT''@|$(REPLACE_READLINKAT)|g' \
+ -e 's|@''REPLACE_RMDIR''@|$(REPLACE_RMDIR)|g' \
+ -e 's|@''REPLACE_SLEEP''@|$(REPLACE_SLEEP)|g' \
+ -e 's|@''REPLACE_SYMLINK''@|$(REPLACE_SYMLINK)|g' \
+ -e 's|@''REPLACE_SYMLINKAT''@|$(REPLACE_SYMLINKAT)|g' \
+ -e 's|@''REPLACE_TTYNAME_R''@|$(REPLACE_TTYNAME_R)|g' \
+ -e 's|@''REPLACE_UNLINK''@|$(REPLACE_UNLINK)|g' \
+ -e 's|@''REPLACE_UNLINKAT''@|$(REPLACE_UNLINKAT)|g' \
+ -e 's|@''REPLACE_USLEEP''@|$(REPLACE_USLEEP)|g' \
+ -e 's|@''REPLACE_WRITE''@|$(REPLACE_WRITE)|g' \
+ -e 's|@''UNISTD_H_HAVE_WINSOCK2_H''@|$(UNISTD_H_HAVE_WINSOCK2_H)|g' \
+ -e 's|@''UNISTD_H_HAVE_WINSOCK2_H_AND_USE_SOCKETS''@|$(UNISTD_H_HAVE_WINSOCK2_H_AND_USE_SOCKETS)|g' \
+ -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
+ -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
+ -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)'; \
+ } > $@-t && \
mv $@-t $@
-MOSTLYCLEANFILES += unistd.h unistd.h-t
+MOSTLYCLEANFILES += lib/unistd.h lib/unistd.h-t
-EXTRA_DIST += unistd_.h
+EXTRA_DIST += lib/unistd.in.h
## end gnulib module unistd
## begin gnulib module unistd-safer
+lib_libcoreutils_a_SOURCES += lib/dup-safer.c lib/fd-safer.c lib/pipe-safer.c
-EXTRA_DIST += dup-safer.c fd-safer.c pipe-safer.c unistd--.h unistd-safer.h
-
-EXTRA_libcoreutils_a_SOURCES += dup-safer.c fd-safer.c pipe-safer.c
+EXTRA_DIST += lib/unistd--.h lib/unistd-safer.h
## end gnulib module unistd-safer
-## begin gnulib module unlinkdir
+## begin gnulib module unistr/base
+
+BUILT_SOURCES += $(LIBUNISTRING_UNISTR_H)
+
+lib/unistr.h: lib/unistr.in.h
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
+ cat $(top_srcdir)/lib/unistr.in.h; \
+ } > $@-t && \
+ mv -f $@-t $@
+MOSTLYCLEANFILES += lib/unistr.h lib/unistr.h-t
+
+EXTRA_DIST += lib/unistr.in.h
+
+## end gnulib module unistr/base
+
+## begin gnulib module unistr/u8-mbtoucr
+
+if LIBUNISTRING_COMPILE_UNISTR_U8_MBTOUCR
+lib_libcoreutils_a_SOURCES += lib/unistr/u8-mbtoucr.c
+endif
+
+## end gnulib module unistr/u8-mbtoucr
+
+## begin gnulib module unistr/u8-uctomb
+
+if LIBUNISTRING_COMPILE_UNISTR_U8_UCTOMB
+lib_libcoreutils_a_SOURCES += lib/unistr/u8-uctomb.c lib/unistr/u8-uctomb-aux.c
+endif
+
+## end gnulib module unistr/u8-uctomb
+
+## begin gnulib module unitypes
+
+BUILT_SOURCES += $(LIBUNISTRING_UNITYPES_H)
+
+lib/unitypes.h: lib/unitypes.in.h
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
+ cat $(top_srcdir)/lib/unitypes.in.h; \
+ } > $@-t && \
+ mv -f $@-t $@
+MOSTLYCLEANFILES += lib/unitypes.h lib/unitypes.h-t
+
+EXTRA_DIST += lib/unitypes.in.h
+## end gnulib module unitypes
-EXTRA_DIST += unlinkdir.c unlinkdir.h
+## begin gnulib module uniwidth/base
-EXTRA_libcoreutils_a_SOURCES += unlinkdir.c
+BUILT_SOURCES += $(LIBUNISTRING_UNIWIDTH_H)
-## end gnulib module unlinkdir
+lib/uniwidth.h: lib/uniwidth.in.h
+ $(AM_V_GEN)rm -f $@-t $@ && \
+ { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
+ cat $(top_srcdir)/lib/uniwidth.in.h; \
+ } > $@-t && \
+ mv -f $@-t $@
+MOSTLYCLEANFILES += lib/uniwidth.h lib/uniwidth.h-t
+
+EXTRA_DIST += lib/localcharset.h lib/uniwidth.in.h
+
+## end gnulib module uniwidth/base
+
+## begin gnulib module uniwidth/width
+
+if LIBUNISTRING_COMPILE_UNIWIDTH_WIDTH
+lib_libcoreutils_a_SOURCES += lib/uniwidth/width.c
+endif
+
+EXTRA_DIST += lib/uniwidth/cjk.h
+
+## end gnulib module uniwidth/width
+
+## begin gnulib module unlink
+
+
+EXTRA_DIST += lib/unlink.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/unlink.c
+
+## end gnulib module unlink
+
+## begin gnulib module unlinkat
+
+
+EXTRA_DIST += lib/at-func.c lib/unlinkat.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/at-func.c lib/unlinkat.c
+
+## end gnulib module unlinkat
## begin gnulib module unlocked-io
-EXTRA_DIST += unlocked-io.h
+EXTRA_DIST += lib/unlocked-io.h
## end gnulib module unlocked-io
-## begin gnulib module userspec
+## begin gnulib module unsetenv
-EXTRA_DIST += inttostr.h userspec.c userspec.h
+EXTRA_DIST += lib/unsetenv.c
-EXTRA_libcoreutils_a_SOURCES += userspec.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/unsetenv.c
-## end gnulib module userspec
+## end gnulib module unsetenv
-## begin gnulib module utime
+## begin gnulib module update-copyright
-EXTRA_DIST += utime.c
+EXTRA_DIST += $(top_srcdir)/build-aux/update-copyright
-EXTRA_libcoreutils_a_SOURCES += utime.c
+## end gnulib module update-copyright
-## end gnulib module utime
+## begin gnulib module useless-if-before-free
-## begin gnulib module utimecmp
+EXTRA_DIST += $(top_srcdir)/build-aux/useless-if-before-free
+
+## end gnulib module useless-if-before-free
+
+## begin gnulib module userspec
+
+lib_libcoreutils_a_SOURCES += lib/userspec.c
+
+EXTRA_DIST += lib/userspec.h
+
+## end gnulib module userspec
+
+## begin gnulib module utimecmp
-EXTRA_DIST += utimecmp.c utimecmp.h
+lib_libcoreutils_a_SOURCES += lib/utimecmp.c
-EXTRA_libcoreutils_a_SOURCES += utimecmp.c
+EXTRA_DIST += lib/utimecmp.h
## end gnulib module utimecmp
## begin gnulib module utimens
+lib_libcoreutils_a_SOURCES += lib/utimens.c
-EXTRA_DIST += utimens.c utimens.h
-
-EXTRA_libcoreutils_a_SOURCES += utimens.c
+EXTRA_DIST += lib/utimens.h
## end gnulib module utimens
+## begin gnulib module utimensat
+
+
+EXTRA_DIST += lib/at-func.c lib/utimensat.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/at-func.c lib/utimensat.c
+
+## end gnulib module utimensat
+
## begin gnulib module vasnprintf
-EXTRA_DIST += asnprintf.c printf-args.c printf-args.h printf-parse.c printf-parse.h vasnprintf.c vasnprintf.h
+EXTRA_DIST += lib/asnprintf.c lib/float+.h lib/printf-args.c lib/printf-args.h lib/printf-parse.c lib/printf-parse.h lib/vasnprintf.c lib/vasnprintf.h
-EXTRA_libcoreutils_a_SOURCES += asnprintf.c printf-args.c printf-parse.c vasnprintf.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/asnprintf.c lib/printf-args.c lib/printf-parse.c lib/vasnprintf.c
## end gnulib module vasnprintf
## begin gnulib module vasprintf
-EXTRA_DIST += asprintf.c vasprintf.c vasprintf.h
+EXTRA_DIST += lib/asprintf.c lib/vasprintf.c
-EXTRA_libcoreutils_a_SOURCES += asprintf.c vasprintf.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/asprintf.c lib/vasprintf.c
## end gnulib module vasprintf
+## begin gnulib module vc-list-files
+
+
+EXTRA_DIST += $(top_srcdir)/build-aux/vc-list-files
+
+## end gnulib module vc-list-files
+
## begin gnulib module verify
-libcoreutils_a_SOURCES += verify.h
+
+EXTRA_DIST += lib/verify.h
## end gnulib module verify
+## begin gnulib module verror
+
+lib_libcoreutils_a_SOURCES += lib/verror.h lib/verror.c
+
+## end gnulib module verror
+
## begin gnulib module version-etc
-libcoreutils_a_SOURCES += version-etc.h version-etc.c
+lib_libcoreutils_a_SOURCES += lib/version-etc.h lib/version-etc.c
## end gnulib module version-etc
## begin gnulib module version-etc-fsf
-libcoreutils_a_SOURCES += version-etc-fsf.c
+lib_libcoreutils_a_SOURCES += lib/version-etc-fsf.c
## end gnulib module version-etc-fsf
+## begin gnulib module vfprintf-posix
+
+
+EXTRA_DIST += lib/vfprintf.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/vfprintf.c
+
+## end gnulib module vfprintf-posix
+
+## begin gnulib module vprintf-posix
+
+
+EXTRA_DIST += lib/vprintf.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/vprintf.c
+
+## end gnulib module vprintf-posix
+
## begin gnulib module wchar
-BUILT_SOURCES += $(WCHAR_H)
+BUILT_SOURCES += lib/wchar.h
# We need the following in order to create <wchar.h> when the system
# version does not work standalone.
-wchar.h: wchar_.h
- rm -f $@-t $@
+lib/wchar.h: lib/wchar.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(ARG_NONNULL_H) $(WARN_ON_USE_H)
+ $(AM_V_GEN)rm -f $@-t $@ && \
{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
- sed -e 's|@''ABSOLUTE_WCHAR_H''@|$(ABSOLUTE_WCHAR_H)|g' \
- < $(srcdir)/wchar_.h; \
- } > $@-t
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''HAVE_FEATURES_H''@|$(HAVE_FEATURES_H)|g' \
+ -e 's|@''NEXT_WCHAR_H''@|$(NEXT_WCHAR_H)|g' \
+ -e 's|@''HAVE_WCHAR_H''@|$(HAVE_WCHAR_H)|g' \
+ -e 's/@''GNULIB_BTOWC''@/$(GNULIB_BTOWC)/g' \
+ -e 's/@''GNULIB_WCTOB''@/$(GNULIB_WCTOB)/g' \
+ -e 's/@''GNULIB_MBSINIT''@/$(GNULIB_MBSINIT)/g' \
+ -e 's/@''GNULIB_MBRTOWC''@/$(GNULIB_MBRTOWC)/g' \
+ -e 's/@''GNULIB_MBRLEN''@/$(GNULIB_MBRLEN)/g' \
+ -e 's/@''GNULIB_MBSRTOWCS''@/$(GNULIB_MBSRTOWCS)/g' \
+ -e 's/@''GNULIB_MBSNRTOWCS''@/$(GNULIB_MBSNRTOWCS)/g' \
+ -e 's/@''GNULIB_WCRTOMB''@/$(GNULIB_WCRTOMB)/g' \
+ -e 's/@''GNULIB_WCSRTOMBS''@/$(GNULIB_WCSRTOMBS)/g' \
+ -e 's/@''GNULIB_WCSNRTOMBS''@/$(GNULIB_WCSNRTOMBS)/g' \
+ -e 's/@''GNULIB_WCWIDTH''@/$(GNULIB_WCWIDTH)/g' \
+ -e 's/@''GNULIB_WMEMCHR''@/$(GNULIB_WMEMCHR)/g' \
+ -e 's/@''GNULIB_WMEMCMP''@/$(GNULIB_WMEMCMP)/g' \
+ -e 's/@''GNULIB_WMEMCPY''@/$(GNULIB_WMEMCPY)/g' \
+ -e 's/@''GNULIB_WMEMMOVE''@/$(GNULIB_WMEMMOVE)/g' \
+ -e 's/@''GNULIB_WMEMSET''@/$(GNULIB_WMEMSET)/g' \
+ -e 's/@''GNULIB_WCSLEN''@/$(GNULIB_WCSLEN)/g' \
+ -e 's/@''GNULIB_WCSNLEN''@/$(GNULIB_WCSNLEN)/g' \
+ -e 's/@''GNULIB_WCSCPY''@/$(GNULIB_WCSCPY)/g' \
+ -e 's/@''GNULIB_WCPCPY''@/$(GNULIB_WCPCPY)/g' \
+ -e 's/@''GNULIB_WCSNCPY''@/$(GNULIB_WCSNCPY)/g' \
+ -e 's/@''GNULIB_WCPNCPY''@/$(GNULIB_WCPNCPY)/g' \
+ -e 's/@''GNULIB_WCSCAT''@/$(GNULIB_WCSCAT)/g' \
+ -e 's/@''GNULIB_WCSNCAT''@/$(GNULIB_WCSNCAT)/g' \
+ -e 's/@''GNULIB_WCSCMP''@/$(GNULIB_WCSCMP)/g' \
+ -e 's/@''GNULIB_WCSNCMP''@/$(GNULIB_WCSNCMP)/g' \
+ -e 's/@''GNULIB_WCSCASECMP''@/$(GNULIB_WCSCASECMP)/g' \
+ -e 's/@''GNULIB_WCSNCASECMP''@/$(GNULIB_WCSNCASECMP)/g' \
+ -e 's/@''GNULIB_WCSCOLL''@/$(GNULIB_WCSCOLL)/g' \
+ -e 's/@''GNULIB_WCSXFRM''@/$(GNULIB_WCSXFRM)/g' \
+ -e 's/@''GNULIB_WCSDUP''@/$(GNULIB_WCSDUP)/g' \
+ -e 's/@''GNULIB_WCSCHR''@/$(GNULIB_WCSCHR)/g' \
+ -e 's/@''GNULIB_WCSRCHR''@/$(GNULIB_WCSRCHR)/g' \
+ -e 's/@''GNULIB_WCSCSPN''@/$(GNULIB_WCSCSPN)/g' \
+ -e 's/@''GNULIB_WCSSPN''@/$(GNULIB_WCSSPN)/g' \
+ -e 's/@''GNULIB_WCSPBRK''@/$(GNULIB_WCSPBRK)/g' \
+ -e 's/@''GNULIB_WCSSTR''@/$(GNULIB_WCSSTR)/g' \
+ -e 's/@''GNULIB_WCSTOK''@/$(GNULIB_WCSTOK)/g' \
+ -e 's/@''GNULIB_WCSWIDTH''@/$(GNULIB_WCSWIDTH)/g' \
+ < $(top_srcdir)/lib/wchar.in.h | \
+ sed -e 's|@''HAVE_WINT_T''@|$(HAVE_WINT_T)|g' \
+ -e 's|@''HAVE_BTOWC''@|$(HAVE_BTOWC)|g' \
+ -e 's|@''HAVE_MBSINIT''@|$(HAVE_MBSINIT)|g' \
+ -e 's|@''HAVE_MBRTOWC''@|$(HAVE_MBRTOWC)|g' \
+ -e 's|@''HAVE_MBRLEN''@|$(HAVE_MBRLEN)|g' \
+ -e 's|@''HAVE_MBSRTOWCS''@|$(HAVE_MBSRTOWCS)|g' \
+ -e 's|@''HAVE_MBSNRTOWCS''@|$(HAVE_MBSNRTOWCS)|g' \
+ -e 's|@''HAVE_WCRTOMB''@|$(HAVE_WCRTOMB)|g' \
+ -e 's|@''HAVE_WCSRTOMBS''@|$(HAVE_WCSRTOMBS)|g' \
+ -e 's|@''HAVE_WCSNRTOMBS''@|$(HAVE_WCSNRTOMBS)|g' \
+ -e 's|@''HAVE_WMEMCHR''@|$(HAVE_WMEMCHR)|g' \
+ -e 's|@''HAVE_WMEMCMP''@|$(HAVE_WMEMCMP)|g' \
+ -e 's|@''HAVE_WMEMCPY''@|$(HAVE_WMEMCPY)|g' \
+ -e 's|@''HAVE_WMEMMOVE''@|$(HAVE_WMEMMOVE)|g' \
+ -e 's|@''HAVE_WMEMSET''@|$(HAVE_WMEMSET)|g' \
+ -e 's|@''HAVE_WCSLEN''@|$(HAVE_WCSLEN)|g' \
+ -e 's|@''HAVE_WCSNLEN''@|$(HAVE_WCSNLEN)|g' \
+ -e 's|@''HAVE_WCSCPY''@|$(HAVE_WCSCPY)|g' \
+ -e 's|@''HAVE_WCPCPY''@|$(HAVE_WCPCPY)|g' \
+ -e 's|@''HAVE_WCSNCPY''@|$(HAVE_WCSNCPY)|g' \
+ -e 's|@''HAVE_WCPNCPY''@|$(HAVE_WCPNCPY)|g' \
+ -e 's|@''HAVE_WCSCAT''@|$(HAVE_WCSCAT)|g' \
+ -e 's|@''HAVE_WCSNCAT''@|$(HAVE_WCSNCAT)|g' \
+ -e 's|@''HAVE_WCSCMP''@|$(HAVE_WCSCMP)|g' \
+ -e 's|@''HAVE_WCSNCMP''@|$(HAVE_WCSNCMP)|g' \
+ -e 's|@''HAVE_WCSCASECMP''@|$(HAVE_WCSCASECMP)|g' \
+ -e 's|@''HAVE_WCSNCASECMP''@|$(HAVE_WCSNCASECMP)|g' \
+ -e 's|@''HAVE_WCSCOLL''@|$(HAVE_WCSCOLL)|g' \
+ -e 's|@''HAVE_WCSXFRM''@|$(HAVE_WCSXFRM)|g' \
+ -e 's|@''HAVE_WCSDUP''@|$(HAVE_WCSDUP)|g' \
+ -e 's|@''HAVE_WCSCHR''@|$(HAVE_WCSCHR)|g' \
+ -e 's|@''HAVE_WCSRCHR''@|$(HAVE_WCSRCHR)|g' \
+ -e 's|@''HAVE_WCSCSPN''@|$(HAVE_WCSCSPN)|g' \
+ -e 's|@''HAVE_WCSSPN''@|$(HAVE_WCSSPN)|g' \
+ -e 's|@''HAVE_WCSPBRK''@|$(HAVE_WCSPBRK)|g' \
+ -e 's|@''HAVE_WCSSTR''@|$(HAVE_WCSSTR)|g' \
+ -e 's|@''HAVE_WCSTOK''@|$(HAVE_WCSTOK)|g' \
+ -e 's|@''HAVE_WCSWIDTH''@|$(HAVE_WCSWIDTH)|g' \
+ -e 's|@''HAVE_DECL_WCTOB''@|$(HAVE_DECL_WCTOB)|g' \
+ -e 's|@''HAVE_DECL_WCWIDTH''@|$(HAVE_DECL_WCWIDTH)|g' \
+ | \
+ sed -e 's|@''REPLACE_MBSTATE_T''@|$(REPLACE_MBSTATE_T)|g' \
+ -e 's|@''REPLACE_BTOWC''@|$(REPLACE_BTOWC)|g' \
+ -e 's|@''REPLACE_WCTOB''@|$(REPLACE_WCTOB)|g' \
+ -e 's|@''REPLACE_MBSINIT''@|$(REPLACE_MBSINIT)|g' \
+ -e 's|@''REPLACE_MBRTOWC''@|$(REPLACE_MBRTOWC)|g' \
+ -e 's|@''REPLACE_MBRLEN''@|$(REPLACE_MBRLEN)|g' \
+ -e 's|@''REPLACE_MBSRTOWCS''@|$(REPLACE_MBSRTOWCS)|g' \
+ -e 's|@''REPLACE_MBSNRTOWCS''@|$(REPLACE_MBSNRTOWCS)|g' \
+ -e 's|@''REPLACE_WCRTOMB''@|$(REPLACE_WCRTOMB)|g' \
+ -e 's|@''REPLACE_WCSRTOMBS''@|$(REPLACE_WCSRTOMBS)|g' \
+ -e 's|@''REPLACE_WCSNRTOMBS''@|$(REPLACE_WCSNRTOMBS)|g' \
+ -e 's|@''REPLACE_WCWIDTH''@|$(REPLACE_WCWIDTH)|g' \
+ -e 's|@''REPLACE_WCSWIDTH''@|$(REPLACE_WCSWIDTH)|g' \
+ -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
+ -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
+ -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)'; \
+ } > $@-t && \
mv $@-t $@
-MOSTLYCLEANFILES += wchar.h wchar.h-t
+MOSTLYCLEANFILES += lib/wchar.h lib/wchar.h-t
-EXTRA_DIST += wchar_.h
+EXTRA_DIST += lib/wchar.in.h
## end gnulib module wchar
-## begin gnulib module wctype
+## begin gnulib module wcrtomb
-BUILT_SOURCES += $(WCTYPE_H)
+
+EXTRA_DIST += lib/wcrtomb.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/wcrtomb.c
+
+## end gnulib module wcrtomb
+
+## begin gnulib module wcswidth
+
+
+EXTRA_DIST += lib/wcswidth-impl.h lib/wcswidth.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/wcswidth.c
+
+## end gnulib module wcswidth
+
+## begin gnulib module wctype-h
+
+BUILT_SOURCES += lib/wctype.h
+lib_libcoreutils_a_SOURCES += lib/wctype-h.c
# We need the following in order to create <wctype.h> when the system
# doesn't have one that works with the given compiler.
-wctype.h: wctype_.h
- rm -f $@-t $@
+lib/wctype.h: lib/wctype.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(WARN_ON_USE_H)
+ $(AM_V_GEN)rm -f $@-t $@ && \
{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
- sed -e 's/@''HAVE_WCTYPE_H''@/$(HAVE_WCTYPE_H)/g' \
- -e 's|@''ABSOLUTE_WCTYPE_H''@|$(ABSOLUTE_WCTYPE_H)|g' \
- -e 's/@''HAVE_WCTYPE_CTMP_BUG''@/$(HAVE_WCTYPE_CTMP_BUG)/g' \
+ sed -e 's|@''GUARD_PREFIX''@|GL|g' \
+ -e 's/@''HAVE_WCTYPE_H''@/$(HAVE_WCTYPE_H)/g' \
+ -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
+ -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
+ -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
+ -e 's|@''NEXT_WCTYPE_H''@|$(NEXT_WCTYPE_H)|g' \
+ -e 's/@''GNULIB_ISWBLANK''@/$(GNULIB_ISWBLANK)/g' \
+ -e 's/@''GNULIB_WCTYPE''@/$(GNULIB_WCTYPE)/g' \
+ -e 's/@''GNULIB_ISWCTYPE''@/$(GNULIB_ISWCTYPE)/g' \
+ -e 's/@''GNULIB_WCTRANS''@/$(GNULIB_WCTRANS)/g' \
+ -e 's/@''GNULIB_TOWCTRANS''@/$(GNULIB_TOWCTRANS)/g' \
+ -e 's/@''HAVE_ISWBLANK''@/$(HAVE_ISWBLANK)/g' \
+ -e 's/@''HAVE_ISWCNTRL''@/$(HAVE_ISWCNTRL)/g' \
+ -e 's/@''HAVE_WCTYPE_T''@/$(HAVE_WCTYPE_T)/g' \
+ -e 's/@''HAVE_WCTRANS_T''@/$(HAVE_WCTRANS_T)/g' \
-e 's/@''HAVE_WINT_T''@/$(HAVE_WINT_T)/g' \
- < $(srcdir)/wctype_.h; \
- } > $@-t
+ -e 's/@''REPLACE_ISWBLANK''@/$(REPLACE_ISWBLANK)/g' \
+ -e 's/@''REPLACE_ISWCNTRL''@/$(REPLACE_ISWCNTRL)/g' \
+ -e 's/@''REPLACE_TOWLOWER''@/$(REPLACE_TOWLOWER)/g' \
+ -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
+ -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
+ < $(top_srcdir)/lib/wctype.in.h; \
+ } > $@-t && \
mv $@-t $@
-MOSTLYCLEANFILES += wctype.h wctype.h-t
+MOSTLYCLEANFILES += lib/wctype.h lib/wctype.h-t
-EXTRA_DIST += wctype_.h
+EXTRA_DIST += lib/wctype.in.h
-## end gnulib module wctype
+## end gnulib module wctype-h
## begin gnulib module wcwidth
-libcoreutils_a_SOURCES += wcwidth.h
+
+EXTRA_DIST += lib/wcwidth.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/wcwidth.c
## end gnulib module wcwidth
-## begin gnulib module xalloc
+## begin gnulib module write
+
+
+EXTRA_DIST += lib/write.c
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/write.c
+
+## end gnulib module write
+
+## begin gnulib module write-any-file
+lib_libcoreutils_a_SOURCES += lib/write-any-file.c
-EXTRA_DIST += xalloc.h xmalloc.c
+EXTRA_DIST += lib/write-any-file.h
-EXTRA_libcoreutils_a_SOURCES += xmalloc.c
+## end gnulib module write-any-file
+
+## begin gnulib module xalloc
+
+lib_libcoreutils_a_SOURCES += lib/xmalloc.c
+
+EXTRA_DIST += lib/xalloc.h
## end gnulib module xalloc
## begin gnulib module xalloc-die
-libcoreutils_a_SOURCES += xalloc-die.c
+lib_libcoreutils_a_SOURCES += lib/xalloc-die.c
## end gnulib module xalloc-die
-## begin gnulib module xgetcwd
+## begin gnulib module xalloc-oversized
+
+
+EXTRA_DIST += lib/xalloc-oversized.h
+
+## end gnulib module xalloc-oversized
+
+## begin gnulib module xdectoint
+
+lib_libcoreutils_a_SOURCES += lib/xdectoimax.c lib/xdectoumax.c
+
+EXTRA_DIST += lib/xdectoint.c lib/xdectoint.h
+
+EXTRA_lib_libcoreutils_a_SOURCES += lib/xdectoint.c
+
+## end gnulib module xdectoint
+
+## begin gnulib module xfreopen
+
+lib_libcoreutils_a_SOURCES += lib/xfreopen.c lib/xfreopen.h
+
+## end gnulib module xfreopen
+
+## begin gnulib module xfts
+
+lib_libcoreutils_a_SOURCES += lib/xfts.c lib/xfts.h
+## end gnulib module xfts
-EXTRA_DIST += xgetcwd.c xgetcwd.h
+## begin gnulib module xgetcwd
+
+lib_libcoreutils_a_SOURCES += lib/xgetcwd.c
-EXTRA_libcoreutils_a_SOURCES += xgetcwd.c
+EXTRA_DIST += lib/xgetcwd.h
## end gnulib module xgetcwd
+## begin gnulib module xgetgroups
+
+lib_libcoreutils_a_SOURCES += lib/xgetgroups.c
+
+## end gnulib module xgetgroups
+
## begin gnulib module xgethostname
-libcoreutils_a_SOURCES += xgethostname.h xgethostname.c
+lib_libcoreutils_a_SOURCES += lib/xgethostname.h lib/xgethostname.c
## end gnulib module xgethostname
## begin gnulib module xmemcoll
-libcoreutils_a_SOURCES += xmemcoll.h xmemcoll.c
+lib_libcoreutils_a_SOURCES += lib/xmemcoll.h lib/xmemcoll.c
## end gnulib module xmemcoll
## begin gnulib module xnanosleep
+lib_libcoreutils_a_SOURCES += lib/xnanosleep.c
-EXTRA_DIST += xnanosleep.c xnanosleep.h
-
-EXTRA_libcoreutils_a_SOURCES += xnanosleep.c
+EXTRA_DIST += lib/xnanosleep.h
## end gnulib module xnanosleep
+## begin gnulib module xprintf
+
+lib_libcoreutils_a_SOURCES += lib/xprintf.h lib/xprintf.c
+
+## end gnulib module xprintf
+
## begin gnulib module xreadlink
-libcoreutils_a_SOURCES += xreadlink.c
+lib_libcoreutils_a_SOURCES += lib/xreadlink.c
-EXTRA_DIST += xreadlink.h
+EXTRA_DIST += lib/xreadlink.h
## end gnulib module xreadlink
-## begin gnulib module xreadlink-with-size
+## begin gnulib module xsize
-libcoreutils_a_SOURCES += xreadlink-with-size.c
+lib_libcoreutils_a_SOURCES += lib/xsize.h lib/xsize.c
-EXTRA_DIST += xreadlink.h
+## end gnulib module xsize
-## end gnulib module xreadlink-with-size
+## begin gnulib module xstriconv
+
+lib_libcoreutils_a_SOURCES += lib/xstriconv.h lib/xstriconv.c
+
+## end gnulib module xstriconv
## begin gnulib module xstrndup
-libcoreutils_a_SOURCES += xstrndup.h xstrndup.c
+lib_libcoreutils_a_SOURCES += lib/xstrndup.h lib/xstrndup.c
## end gnulib module xstrndup
## begin gnulib module xstrtod
+lib_libcoreutils_a_SOURCES += lib/xstrtod.c
-EXTRA_DIST += xstrtod.c xstrtod.h
-
-EXTRA_libcoreutils_a_SOURCES += xstrtod.c
+EXTRA_DIST += lib/xstrtod.h
## end gnulib module xstrtod
## begin gnulib module xstrtoimax
-libcoreutils_a_SOURCES += xstrtoimax.c
+lib_libcoreutils_a_SOURCES += lib/xstrtoimax.c
## end gnulib module xstrtoimax
## begin gnulib module xstrtol
+lib_libcoreutils_a_SOURCES += lib/xstrtol.c lib/xstrtoul.c lib/xstrtol-error.c
-EXTRA_DIST += xstrtol.c xstrtol.h xstrtoul.c
-
-EXTRA_libcoreutils_a_SOURCES += xstrtol.c xstrtoul.c
+EXTRA_DIST += lib/xstrtol.h
## end gnulib module xstrtol
## begin gnulib module xstrtold
+lib_libcoreutils_a_SOURCES += lib/xstrtold.c
-EXTRA_DIST += xstrtod.c xstrtod.h xstrtold.c
+EXTRA_DIST += lib/xstrtod.c lib/xstrtod.h
-EXTRA_libcoreutils_a_SOURCES += xstrtod.c xstrtold.c
+EXTRA_lib_libcoreutils_a_SOURCES += lib/xstrtod.c
## end gnulib module xstrtold
## begin gnulib module xstrtoumax
-libcoreutils_a_SOURCES += xstrtoumax.c
+lib_libcoreutils_a_SOURCES += lib/xstrtoumax.c
## end gnulib module xstrtoumax
-## begin gnulib module yesno
+## begin gnulib module xvasprintf
+lib_libcoreutils_a_SOURCES += lib/xvasprintf.h lib/xvasprintf.c lib/xasprintf.c
+
+EXTRA_DIST += lib/xalloc.h
+
+## end gnulib module xvasprintf
+
+## begin gnulib module yesno
-EXTRA_DIST += yesno.c yesno.h
+lib_libcoreutils_a_SOURCES += lib/yesno.c
-EXTRA_libcoreutils_a_SOURCES += yesno.c
+EXTRA_DIST += lib/yesno.h
## end gnulib module yesno
@@ -2252,4 +5537,5 @@ mostlyclean-local: mostlyclean-generic
if test -n "$$dir" && test -d $$dir; then \
echo "rmdir $$dir"; rmdir $$dir; \
fi; \
- done
+ done; \
+ :
diff --git a/lib/group-member.c b/lib/group-member.c
index 0187026..365e166 100644
--- a/lib/group-member.c
+++ b/lib/group-member.c
@@ -1,12 +1,12 @@
/* group-member.c -- determine whether group id is in calling user's group list
- Copyright (C) 1994, 1997, 1998, 2003, 2005, 2006 Free Software
+ Copyright (C) 1994, 1997-1998, 2003, 2005-2006, 2009-2016 Free Software
Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,99 +14,85 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
-#include "group-member.h"
+/* Specification. */
+#include <unistd.h>
-#include <stdbool.h>
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
-#include <unistd.h>
+#include "xalloc-oversized.h"
-#include "xalloc.h"
+/* Most processes have no more than this many groups, and for these
+ processes we can avoid using malloc. */
+enum { GROUPBUF_SIZE = 100 };
struct group_info
{
- int n_groups;
- GETGROUPS_T *group;
+ gid_t *group;
+ gid_t groupbuf[GROUPBUF_SIZE];
};
-#if HAVE_GETGROUPS
-
static void
free_group_info (struct group_info const *g)
{
- free (g->group);
+ if (g->group != g->groupbuf)
+ free (g->group);
}
-static bool
+static int
get_group_info (struct group_info *gi)
{
- int n_groups;
- int n_group_slots = getgroups (0, NULL);
- GETGROUPS_T *group;
-
- if (n_group_slots < 0)
- return false;
+ int n_groups = getgroups (GROUPBUF_SIZE, gi->groupbuf);
+ gi->group = gi->groupbuf;
- /* Avoid xnmalloc, as it goes awry when SIZE_MAX < n_group_slots. */
- if (xalloc_oversized (n_group_slots, sizeof *group))
- xalloc_die ();
- group = xmalloc (n_group_slots * sizeof *group);
- n_groups = getgroups (n_group_slots, group);
-
- /* In case of error, the user loses. */
if (n_groups < 0)
{
- free (group);
- return false;
+ int n_group_slots = getgroups (0, NULL);
+ if (0 <= n_group_slots
+ && ! xalloc_oversized (n_group_slots, sizeof *gi->group))
+ {
+ gi->group = malloc (n_group_slots * sizeof *gi->group);
+ if (gi->group)
+ n_groups = getgroups (n_group_slots, gi->group);
+ }
}
- gi->n_groups = n_groups;
- gi->group = group;
-
- return true;
+ /* In case of error, the user loses. */
+ return n_groups;
}
-#endif /* not HAVE_GETGROUPS */
-
/* Return non-zero if GID is one that we have in our groups list.
- If there is no getgroups function, return non-zero if GID matches
- either of the current or effective group IDs. */
+ Note that the groups list is not guaranteed to contain the current
+ or effective group ID, so they should generally be checked
+ separately. */
int
group_member (gid_t gid)
{
-#ifndef HAVE_GETGROUPS
- return ((gid == getgid ()) || (gid == getegid ()));
-#else
int i;
int found;
struct group_info gi;
-
- if (! get_group_info (&gi))
- return 0;
+ int n_groups = get_group_info (&gi);
/* Search through the list looking for GID. */
found = 0;
- for (i = 0; i < gi.n_groups; i++)
+ for (i = 0; i < n_groups; i++)
{
if (gid == gi.group[i])
- {
- found = 1;
- break;
- }
+ {
+ found = 1;
+ break;
+ }
}
free_group_info (&gi);
return found;
-#endif /* HAVE_GETGROUPS */
}
#ifdef TEST
@@ -120,7 +106,7 @@ main (int argc, char **argv)
program_name = argv[0];
- for (i=1; i<argc; i++)
+ for (i = 1; i < argc; i++)
{
gid_t gid;
diff --git a/lib/group-member.h b/lib/group-member.h
deleted file mode 100644
index 30f85e9..0000000
--- a/lib/group-member.h
+++ /dev/null
@@ -1,26 +0,0 @@
-/* Determine whether group id is in calling user's group list.
-
- Copyright (C) 1994, 1997, 2003 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-#ifndef GROUP_MEMBER_H_
-# define GROUP_MEMBER_H_ 1
-
-# include <sys/types.h>
-
-int group_member (gid_t);
-
-#endif /* GROUP_MEMBER_H_ */
diff --git a/lib/hard-locale.c b/lib/hard-locale.c
index dd2ba48..c7d9da5 100644
--- a/lib/hard-locale.c
+++ b/lib/hard-locale.c
@@ -1,12 +1,12 @@
/* hard-locale.c -- Determine whether a locale is hard.
- Copyright (C) 1997, 1998, 1999, 2002, 2003, 2004, 2006, 2007 Free
- Software Foundation, Inc.
+ Copyright (C) 1997-1999, 2002-2004, 2006-2007, 2009-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
@@ -27,6 +26,8 @@
#ifdef __GLIBC__
# define GLIBC_VERSION __GLIBC__
+#elif defined __UCLIBC__
+# define GLIBC_VERSION 2
#else
# define GLIBC_VERSION 0
#endif
@@ -42,29 +43,29 @@ hard_locale (int category)
if (p)
{
if (2 <= GLIBC_VERSION)
- {
- if (strcmp (p, "C") == 0 || strcmp (p, "POSIX") == 0)
- hard = false;
- }
+ {
+ if (strcmp (p, "C") == 0 || strcmp (p, "POSIX") == 0)
+ hard = false;
+ }
else
- {
- char *locale = strdup (p);
- if (locale)
- {
- /* Temporarily set the locale to the "C" and "POSIX" locales
- to find their names, so that we can determine whether one
- or the other is the caller's locale. */
- if (((p = setlocale (category, "C"))
- && strcmp (p, locale) == 0)
- || ((p = setlocale (category, "POSIX"))
- && strcmp (p, locale) == 0))
- hard = false;
+ {
+ char *locale = strdup (p);
+ if (locale)
+ {
+ /* Temporarily set the locale to the "C" and "POSIX" locales
+ to find their names, so that we can determine whether one
+ or the other is the caller's locale. */
+ if (((p = setlocale (category, "C"))
+ && strcmp (p, locale) == 0)
+ || ((p = setlocale (category, "POSIX"))
+ && strcmp (p, locale) == 0))
+ hard = false;
- /* Restore the caller's locale. */
- setlocale (category, locale);
- free (locale);
- }
- }
+ /* Restore the caller's locale. */
+ setlocale (category, locale);
+ free (locale);
+ }
+ }
}
return hard;
diff --git a/lib/hard-locale.h b/lib/hard-locale.h
index c5cedc0..7644afa 100644
--- a/lib/hard-locale.h
+++ b/lib/hard-locale.h
@@ -1,11 +1,11 @@
/* Determine whether a locale is hard.
- Copyright (C) 1999, 2003, 2004 Free Software Foundation, Inc.
+ Copyright (C) 1999, 2003-2004, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifndef HARD_LOCALE_H_
# define HARD_LOCALE_H_ 1
diff --git a/lib/hash-pjw.c b/lib/hash-pjw.c
index bd94036..7796238 100644
--- a/lib/hash-pjw.c
+++ b/lib/hash-pjw.c
@@ -1,11 +1,11 @@
/* hash-pjw.c -- compute a hash value from a NUL-terminated string.
- Copyright (C) 2001, 2003, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2001, 2003, 2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
diff --git a/lib/hash-pjw.h b/lib/hash-pjw.h
index 44b5440..ae537d1 100644
--- a/lib/hash-pjw.h
+++ b/lib/hash-pjw.h
@@ -1,10 +1,10 @@
/* hash-pjw.h -- declaration for a simple hash function
- Copyright (C) 2001, 2003 Free Software Foundation, Inc.
+ Copyright (C) 2001, 2003, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -12,9 +12,7 @@
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with this program; see the file COPYING.
- If not, write to the Free Software Foundation,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <stddef.h>
@@ -22,4 +20,4 @@
and return the hash code modulo TABLESIZE.
The result is platform dependent: it depends on the size of the 'size_t'
type and on the signedness of the 'char' type. */
-extern size_t hash_pjw (void const *x, size_t tablesize);
+extern size_t hash_pjw (void const *x, size_t tablesize) _GL_ATTRIBUTE_PURE;
diff --git a/lib/hash-triple.c b/lib/hash-triple.c
new file mode 100644
index 0000000..008f90d
--- /dev/null
+++ b/lib/hash-triple.c
@@ -0,0 +1,77 @@
+/* Hash functions for file-related triples: name, device, inode.
+ Copyright (C) 2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* written by Jim Meyering */
+
+#include <config.h>
+
+#include "hash-triple.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+#include "hash-pjw.h"
+#include "same.h"
+#include "same-inode.h"
+
+#define STREQ(a, b) (strcmp (a, b) == 0)
+
+/* Hash an F_triple, and *do* consider the file name. */
+size_t
+triple_hash (void const *x, size_t table_size)
+{
+ struct F_triple const *p = x;
+ size_t tmp = hash_pjw (p->name, table_size);
+
+ /* Ignoring the device number here should be fine. */
+ return (tmp ^ p->st_ino) % table_size;
+}
+
+/* Hash an F_triple, without considering the file name. */
+size_t
+triple_hash_no_name (void const *x, size_t table_size)
+{
+ struct F_triple const *p = x;
+
+ /* Ignoring the device number here should be fine. */
+ return p->st_ino % table_size;
+}
+
+/* Compare two F_triple structs. */
+bool
+triple_compare (void const *x, void const *y)
+{
+ struct F_triple const *a = x;
+ struct F_triple const *b = y;
+ return (SAME_INODE (*a, *b) && same_name (a->name, b->name)) ? true : false;
+}
+
+bool
+triple_compare_ino_str (void const *x, void const *y)
+{
+ struct F_triple const *a = x;
+ struct F_triple const *b = y;
+ return (SAME_INODE (*a, *b) && STREQ (a->name, b->name)) ? true : false;
+}
+
+/* Free an F_triple. */
+void
+triple_free (void *x)
+{
+ struct F_triple *a = x;
+ free (a->name);
+ free (a);
+}
diff --git a/lib/hash-triple.h b/lib/hash-triple.h
new file mode 100644
index 0000000..0658d81
--- /dev/null
+++ b/lib/hash-triple.h
@@ -0,0 +1,24 @@
+#ifndef HASH_TRIPLE_H
+#define HASH_TRIPLE_H
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <stdbool.h>
+
+/* Describe a just-created or just-renamed destination file. */
+struct F_triple
+{
+ char *name;
+ ino_t st_ino;
+ dev_t st_dev;
+};
+
+extern size_t triple_hash (void const *x, size_t table_size) _GL_ATTRIBUTE_PURE;
+extern size_t triple_hash_no_name (void const *x, size_t table_size)
+ _GL_ATTRIBUTE_PURE;
+extern bool triple_compare (void const *x, void const *y);
+extern bool triple_compare_ino_str (void const *x, void const *y)
+ _GL_ATTRIBUTE_PURE;
+extern void triple_free (void *x);
+
+#endif
diff --git a/lib/hash.c b/lib/hash.c
index f4ab12f..f9dede0 100644
--- a/lib/hash.c
+++ b/lib/hash.c
@@ -1,14 +1,13 @@
/* hash - hashing table processing.
- Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2006 Free
- Software Foundation, Inc.
+ Copyright (C) 1998-2004, 2006-2007, 2009-2016 Free Software Foundation, Inc.
Written by Jim Meyering, 1992.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -16,8 +15,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* A generic hash table package. */
@@ -27,9 +25,11 @@
#include <config.h>
#include "hash.h"
-#include "xalloc.h"
-#include <limits.h>
+#include "bitrotate.h"
+#include "xalloc-oversized.h"
+
+#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
@@ -43,9 +43,11 @@
# endif
#endif
-#ifndef SIZE_MAX
-# define SIZE_MAX ((size_t) -1)
-#endif
+struct hash_entry
+ {
+ void *data;
+ struct hash_entry *next;
+ };
struct hash_table
{
@@ -58,10 +60,10 @@ struct hash_table
size_t n_buckets_used;
size_t n_entries;
- /* Tuning arguments, kept in a physicaly separate structure. */
+ /* Tuning arguments, kept in a physically separate structure. */
const Hash_tuning *tuning;
- /* Three functions are given to `hash_initialize', see the documentation
+ /* Three functions are given to 'hash_initialize', see the documentation
block for this function. In a word, HASHER randomizes a user entry
into a number up from 0 up to some maximum minus 1; COMPARATOR returns
true if two user entries compare equally; and DATA_FREER is the cleanup
@@ -82,26 +84,26 @@ struct hash_table
};
/* A hash table contains many internal entries, each holding a pointer to
- some user provided data (also called a user entry). An entry indistinctly
+ some user-provided data (also called a user entry). An entry indistinctly
refers to both the internal entry and its associated user entry. A user
entry contents may be hashed by a randomization function (the hashing
- function, or just `hasher' for short) into a number (or `slot') between 0
+ function, or just "hasher" for short) into a number (or "slot") between 0
and the current table size. At each slot position in the hash table,
starts a linked chain of entries for which the user data all hash to this
slot. A bucket is the collection of all entries hashing to the same slot.
- A good `hasher' function will distribute entries rather evenly in buckets.
+ A good "hasher" function will distribute entries rather evenly in buckets.
In the ideal case, the length of each bucket is roughly the number of
entries divided by the table size. Finding the slot for a data is usually
- done in constant time by the `hasher', and the later finding of a precise
+ done in constant time by the "hasher", and the later finding of a precise
entry is linear in time with the size of the bucket. Consequently, a
larger hash table size (that is, a larger number of buckets) is prone to
- yielding shorter chains, *given* the `hasher' function behaves properly.
+ yielding shorter chains, *given* the "hasher" function behaves properly.
Long buckets slow down the lookup algorithm. One might use big hash table
sizes in hope to reduce the average length of buckets, but this might
become inordinate, as unused slots in the hash table take some space. The
- best bet is to make sure you are using a good `hasher' function (beware
+ best bet is to make sure you are using a good "hasher" function (beware
that those are not that easy to write! :-), and to use a table size
larger than the actual number of entries. */
@@ -111,8 +113,8 @@ struct hash_table
1.0). The growth threshold defaults to 0.8, and the growth factor
defaults to 1.414, meaning that the table will have doubled its size
every second time 80% of the buckets get used. */
-#define DEFAULT_GROWTH_THRESHOLD 0.8
-#define DEFAULT_GROWTH_FACTOR 1.414
+#define DEFAULT_GROWTH_THRESHOLD 0.8f
+#define DEFAULT_GROWTH_FACTOR 1.414f
/* If a deletion empties a bucket and causes the ratio of used buckets to
table size to become smaller than the shrink threshold (a number between
@@ -120,8 +122,8 @@ struct hash_table
number greater than the shrink threshold but smaller than 1.0). The shrink
threshold and factor default to 0.0 and 1.0, meaning that the table never
shrinks. */
-#define DEFAULT_SHRINK_THRESHOLD 0.0
-#define DEFAULT_SHRINK_FACTOR 1.0
+#define DEFAULT_SHRINK_THRESHOLD 0.0f
+#define DEFAULT_SHRINK_FACTOR 1.0f
/* Use this to initialize or reset a TUNING structure to
some sensible values. */
@@ -177,16 +179,16 @@ hash_get_max_bucket_length (const Hash_table *table)
for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
{
if (bucket->data)
- {
- struct hash_entry const *cursor = bucket;
- size_t bucket_length = 1;
+ {
+ struct hash_entry const *cursor = bucket;
+ size_t bucket_length = 1;
- while (cursor = cursor->next, cursor)
- bucket_length++;
+ while (cursor = cursor->next, cursor)
+ bucket_length++;
- if (bucket_length > max_bucket_length)
- max_bucket_length = bucket_length;
- }
+ if (bucket_length > max_bucket_length)
+ max_bucket_length = bucket_length;
+ }
}
return max_bucket_length;
@@ -205,17 +207,17 @@ hash_table_ok (const Hash_table *table)
for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
{
if (bucket->data)
- {
- struct hash_entry const *cursor = bucket;
+ {
+ struct hash_entry const *cursor = bucket;
- /* Count bucket head. */
- n_buckets_used++;
- n_entries++;
+ /* Count bucket head. */
+ n_buckets_used++;
+ n_entries++;
- /* Count bucket overflow. */
- while (cursor = cursor->next, cursor)
- n_entries++;
- }
+ /* Count bucket overflow. */
+ while (cursor = cursor->next, cursor)
+ n_entries++;
+ }
}
if (n_buckets_used == table->n_buckets_used && n_entries == table->n_entries)
@@ -235,10 +237,21 @@ hash_print_statistics (const Hash_table *table, FILE *stream)
fprintf (stream, "# entries: %lu\n", (unsigned long int) n_entries);
fprintf (stream, "# buckets: %lu\n", (unsigned long int) n_buckets);
fprintf (stream, "# buckets used: %lu (%.2f%%)\n",
- (unsigned long int) n_buckets_used,
- (100.0 * n_buckets_used) / n_buckets);
+ (unsigned long int) n_buckets_used,
+ (100.0 * n_buckets_used) / n_buckets);
fprintf (stream, "max bucket length: %lu\n",
- (unsigned long int) max_bucket_length);
+ (unsigned long int) max_bucket_length);
+}
+
+/* Hash KEY and return a pointer to the selected bucket.
+ If TABLE->hasher misbehaves, abort. */
+static struct hash_entry *
+safe_hasher (const Hash_table *table, const void *key)
+{
+ size_t n = table->hasher (key, table->n_buckets);
+ if (! (n < table->n_buckets))
+ abort ();
+ return table->bucket + n;
}
/* If ENTRY matches an entry already in the hash table, return the
@@ -247,18 +260,14 @@ hash_print_statistics (const Hash_table *table, FILE *stream)
void *
hash_lookup (const Hash_table *table, const void *entry)
{
- struct hash_entry const *bucket
- = table->bucket + table->hasher (entry, table->n_buckets);
+ struct hash_entry const *bucket = safe_hasher (table, entry);
struct hash_entry const *cursor;
- if (! (bucket < table->bucket_limit))
- abort ();
-
if (bucket->data == NULL)
return NULL;
for (cursor = bucket; cursor; cursor = cursor->next)
- if (table->comparator (entry, cursor->data))
+ if (entry == cursor->data || table->comparator (entry, cursor->data))
return cursor->data;
return NULL;
@@ -269,7 +278,9 @@ hash_lookup (const Hash_table *table, const void *entry)
/* The functions in this page traverse the hash table and process the
contained entries. For the traversal to work properly, the hash table
should not be resized nor modified while any particular entry is being
- processed. In particular, entries should not be added or removed. */
+ processed. In particular, entries should not be added, and an entry
+ may be removed only if there is no shrink threshold and the entry being
+ removed has already been passed to hash_get_next. */
/* Return the first data in the table, or NULL if the table is empty. */
@@ -289,23 +300,24 @@ hash_get_first (const Hash_table *table)
}
/* Return the user data for the entry following ENTRY, where ENTRY has been
- returned by a previous call to either `hash_get_first' or `hash_get_next'.
+ returned by a previous call to either 'hash_get_first' or 'hash_get_next'.
Return NULL if there are no more entries. */
void *
hash_get_next (const Hash_table *table, const void *entry)
{
- struct hash_entry const *bucket
- = table->bucket + table->hasher (entry, table->n_buckets);
+ struct hash_entry const *bucket = safe_hasher (table, entry);
struct hash_entry const *cursor;
- if (! (bucket < table->bucket_limit))
- abort ();
-
/* Find next entry in the same bucket. */
- for (cursor = bucket; cursor; cursor = cursor->next)
- if (cursor->data == entry && cursor->next)
- return cursor->next->data;
+ cursor = bucket;
+ do
+ {
+ if (cursor->data == entry && cursor->next)
+ return cursor->next->data;
+ cursor = cursor->next;
+ }
+ while (cursor != NULL);
/* Find first entry in any subsequent bucket. */
while (++bucket < table->bucket_limit)
@@ -322,7 +334,7 @@ hash_get_next (const Hash_table *table, const void *entry)
size_t
hash_get_entries (const Hash_table *table, void **buffer,
- size_t buffer_size)
+ size_t buffer_size)
{
size_t counter = 0;
struct hash_entry const *bucket;
@@ -331,14 +343,14 @@ hash_get_entries (const Hash_table *table, void **buffer,
for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
{
if (bucket->data)
- {
- for (cursor = bucket; cursor; cursor = cursor->next)
- {
- if (counter >= buffer_size)
- return counter;
- buffer[counter++] = cursor->data;
- }
- }
+ {
+ for (cursor = bucket; cursor; cursor = cursor->next)
+ {
+ if (counter >= buffer_size)
+ return counter;
+ buffer[counter++] = cursor->data;
+ }
+ }
}
return counter;
@@ -354,7 +366,7 @@ hash_get_entries (const Hash_table *table, void **buffer,
size_t
hash_do_for_each (const Hash_table *table, Hash_processor processor,
- void *processor_data)
+ void *processor_data)
{
size_t counter = 0;
struct hash_entry const *bucket;
@@ -363,14 +375,14 @@ hash_do_for_each (const Hash_table *table, Hash_processor processor,
for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
{
if (bucket->data)
- {
- for (cursor = bucket; cursor; cursor = cursor->next)
- {
- if (!(*processor) (cursor->data, processor_data))
- return counter;
- counter++;
- }
- }
+ {
+ for (cursor = bucket; cursor; cursor = cursor->next)
+ {
+ if (! processor (cursor->data, processor_data))
+ return counter;
+ counter++;
+ }
+ }
}
return counter;
@@ -392,10 +404,8 @@ hash_do_for_each (const Hash_table *table, Hash_processor processor,
size_t
hash_string (const char *string, size_t n_buckets)
{
-# define ROTATE_LEFT(Value, Shift) \
- ((Value) << (Shift) | (Value) >> ((sizeof (size_t) * CHAR_BIT) - (Shift)))
# define HASH_ONE_CHAR(Value, Byte) \
- ((Byte) + ROTATE_LEFT (Value, 7))
+ ((Byte) + rotl_sz (Value, 7))
size_t value = 0;
unsigned char ch;
@@ -404,15 +414,14 @@ hash_string (const char *string, size_t n_buckets)
value = HASH_ONE_CHAR (value, ch);
return value % n_buckets;
-# undef ROTATE_LEFT
# undef HASH_ONE_CHAR
}
#else /* not USE_DIFF_HASH */
-/* This one comes from `recode', and performs a bit better than the above as
+/* This one comes from 'recode', and performs a bit better than the above as
per a few experiments. It is inspired from a hashing routine found in the
- very old Cyber `snoop', itself written in typical Greg Mansfield style.
+ very old Cyber 'snoop', itself written in typical Greg Mansfield style.
(By the way, what happened to this excellent man? Is he still alive?) */
size_t
@@ -431,7 +440,7 @@ hash_string (const char *string, size_t n_buckets)
/* Return true if CANDIDATE is a prime number. CANDIDATE should be an odd
number at least equal to 11. */
-static bool
+static bool _GL_ATTRIBUTE_CONST
is_prime (size_t candidate)
{
size_t divisor = 3;
@@ -450,7 +459,7 @@ is_prime (size_t candidate)
/* Round a given CANDIDATE number up to the nearest prime, and return that
prime. Primes lower than 10 are merely skipped. */
-static size_t
+static size_t _GL_ATTRIBUTE_CONST
next_prime (size_t candidate)
{
/* Skip small primes. */
@@ -460,7 +469,7 @@ next_prime (size_t candidate)
/* Make it definitely odd. */
candidate |= 1;
- while (!is_prime (candidate))
+ while (SIZE_MAX != candidate && !is_prime (candidate))
candidate += 2;
return candidate;
@@ -472,6 +481,27 @@ hash_reset_tuning (Hash_tuning *tuning)
*tuning = default_tuning;
}
+/* If the user passes a NULL hasher, we hash the raw pointer. */
+static size_t
+raw_hasher (const void *data, size_t n)
+{
+ /* When hashing unique pointers, it is often the case that they were
+ generated by malloc and thus have the property that the low-order
+ bits are 0. As this tends to give poorer performance with small
+ tables, we rotate the pointer value before performing division,
+ in an attempt to improve hash quality. */
+ size_t val = rotr_sz ((size_t) data, 3);
+ return val % n;
+}
+
+/* If the user passes a NULL comparator, we use pointer comparison. */
+static bool
+raw_comparator (const void *a, const void *b)
+{
+ return a == b;
+}
+
+
/* For the given hash TABLE, check the user supplied tuning structure for
reasonable values, and return true if there is no gross error with it.
Otherwise, definitively reset the TUNING field to some acceptable default
@@ -482,13 +512,16 @@ static bool
check_tuning (Hash_table *table)
{
const Hash_tuning *tuning = table->tuning;
+ float epsilon;
+ if (tuning == &default_tuning)
+ return true;
/* Be a bit stricter than mathematics would require, so that
rounding errors in size calculations do not cause allocations to
fail to grow or shrink as they should. The smallest allocation
is 11 (due to next_prime's algorithm), so an epsilon of 0.1
should be good enough. */
- float epsilon = 0.1f;
+ epsilon = 0.1f;
if (epsilon < tuning->growth_threshold
&& tuning->growth_threshold < 1 - epsilon
@@ -503,6 +536,26 @@ check_tuning (Hash_table *table)
return false;
}
+/* Compute the size of the bucket array for the given CANDIDATE and
+ TUNING, or return 0 if there is no possible way to allocate that
+ many entries. */
+
+static size_t _GL_ATTRIBUTE_PURE
+compute_bucket_size (size_t candidate, const Hash_tuning *tuning)
+{
+ if (!tuning->is_n_buckets)
+ {
+ float new_candidate = candidate / tuning->growth_threshold;
+ if (SIZE_MAX <= new_candidate)
+ return 0;
+ candidate = new_candidate;
+ }
+ candidate = next_prime (candidate);
+ if (xalloc_oversized (candidate, sizeof (struct hash_entry *)))
+ return 0;
+ return candidate;
+}
+
/* Allocate and return a new hash table, or NULL upon failure. The initial
number of buckets is automatically selected so as to _guarantee_ that you
may insert at least CANDIDATE different user entries before any growth of
@@ -514,35 +567,40 @@ check_tuning (Hash_table *table)
TUNING points to a structure of user-supplied values, in case some fine
tuning is wanted over the default behavior of the hasher. If TUNING is
- NULL, the default tuning parameters are used instead.
+ NULL, the default tuning parameters are used instead. If TUNING is
+ provided but the values requested are out of bounds or might cause
+ rounding errors, return NULL.
- The user-supplied HASHER function should be provided. It accepts two
+ The user-supplied HASHER function, when not NULL, accepts two
arguments ENTRY and TABLE_SIZE. It computes, by hashing ENTRY contents, a
slot number for that entry which should be in the range 0..TABLE_SIZE-1.
This slot number is then returned.
- The user-supplied COMPARATOR function should be provided. It accepts two
+ The user-supplied COMPARATOR function, when not NULL, accepts two
arguments pointing to user data, it then returns true for a pair of entries
that compare equal, or false otherwise. This function is internally called
- on entries which are already known to hash to the same bucket index.
+ on entries which are already known to hash to the same bucket index,
+ but which are distinct pointers.
The user-supplied DATA_FREER function, when not NULL, may be later called
with the user data as an argument, just before the entry containing the
- data gets freed. This happens from within `hash_free' or `hash_clear'.
+ data gets freed. This happens from within 'hash_free' or 'hash_clear'.
You should specify this function only if you want these functions to free
- all of your `data' data. This is typically the case when your data is
+ all of your 'data' data. This is typically the case when your data is
simply an auxiliary struct that you have malloc'd to aggregate several
values. */
Hash_table *
hash_initialize (size_t candidate, const Hash_tuning *tuning,
- Hash_hasher hasher, Hash_comparator comparator,
- Hash_data_freer data_freer)
+ Hash_hasher hasher, Hash_comparator comparator,
+ Hash_data_freer data_freer)
{
Hash_table *table;
- if (hasher == NULL || comparator == NULL)
- return NULL;
+ if (hasher == NULL)
+ hasher = raw_hasher;
+ if (comparator == NULL)
+ comparator = raw_comparator;
table = malloc (sizeof *table);
if (table == NULL)
@@ -554,28 +612,20 @@ hash_initialize (size_t candidate, const Hash_tuning *tuning,
if (!check_tuning (table))
{
/* Fail if the tuning options are invalid. This is the only occasion
- when the user gets some feedback about it. Once the table is created,
- if the user provides invalid tuning options, we silently revert to
- using the defaults, and ignore further request to change the tuning
- options. */
+ when the user gets some feedback about it. Once the table is created,
+ if the user provides invalid tuning options, we silently revert to
+ using the defaults, and ignore further request to change the tuning
+ options. */
goto fail;
}
- if (!tuning->is_n_buckets)
- {
- float new_candidate = candidate / tuning->growth_threshold;
- if (SIZE_MAX <= new_candidate)
- goto fail;
- candidate = new_candidate;
- }
-
- if (xalloc_oversized (candidate, sizeof *table->bucket))
- goto fail;
- table->n_buckets = next_prime (candidate);
- if (xalloc_oversized (table->n_buckets, sizeof *table->bucket))
+ table->n_buckets = compute_bucket_size (candidate, tuning);
+ if (!table->n_buckets)
goto fail;
table->bucket = calloc (table->n_buckets, sizeof *table->bucket);
+ if (table->bucket == NULL)
+ goto fail;
table->bucket_limit = table->bucket + table->n_buckets;
table->n_buckets_used = 0;
table->n_entries = 0;
@@ -607,30 +657,30 @@ hash_clear (Hash_table *table)
for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
{
if (bucket->data)
- {
- struct hash_entry *cursor;
- struct hash_entry *next;
-
- /* Free the bucket overflow. */
- for (cursor = bucket->next; cursor; cursor = next)
- {
- if (table->data_freer)
- (*table->data_freer) (cursor->data);
- cursor->data = NULL;
-
- next = cursor->next;
- /* Relinking is done one entry at a time, as it is to be expected
- that overflows are either rare or short. */
- cursor->next = table->free_entry_list;
- table->free_entry_list = cursor;
- }
-
- /* Free the bucket head. */
- if (table->data_freer)
- (*table->data_freer) (bucket->data);
- bucket->data = NULL;
- bucket->next = NULL;
- }
+ {
+ struct hash_entry *cursor;
+ struct hash_entry *next;
+
+ /* Free the bucket overflow. */
+ for (cursor = bucket->next; cursor; cursor = next)
+ {
+ if (table->data_freer)
+ table->data_freer (cursor->data);
+ cursor->data = NULL;
+
+ next = cursor->next;
+ /* Relinking is done one entry at a time, as it is to be expected
+ that overflows are either rare or short. */
+ cursor->next = table->free_entry_list;
+ table->free_entry_list = cursor;
+ }
+
+ /* Free the bucket head. */
+ if (table->data_freer)
+ table->data_freer (bucket->data);
+ bucket->data = NULL;
+ bucket->next = NULL;
+ }
}
table->n_buckets_used = 0;
@@ -653,15 +703,13 @@ hash_free (Hash_table *table)
if (table->data_freer && table->n_entries)
{
for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
- {
- if (bucket->data)
- {
- for (cursor = bucket; cursor; cursor = cursor->next)
- {
- (*table->data_freer) (cursor->data);
- }
- }
- }
+ {
+ if (bucket->data)
+ {
+ for (cursor = bucket; cursor; cursor = cursor->next)
+ table->data_freer (cursor->data);
+ }
+ }
}
#if USE_OBSTACK
@@ -674,10 +722,10 @@ hash_free (Hash_table *table)
for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
{
for (cursor = bucket->next; cursor; cursor = next)
- {
- next = cursor->next;
- free (cursor);
- }
+ {
+ next = cursor->next;
+ free (cursor);
+ }
}
/* Also reclaim the internal list of previously freed entries. */
@@ -696,7 +744,7 @@ hash_free (Hash_table *table)
/* Insertion and deletion. */
-/* Get a new hash entry for a bucket overflow, possibly by reclying a
+/* Get a new hash entry for a bucket overflow, possibly by recycling a
previously freed one. If this is not possible, allocate a new one. */
static struct hash_entry *
@@ -740,15 +788,11 @@ free_entry (Hash_table *table, struct hash_entry *entry)
static void *
hash_find_entry (Hash_table *table, const void *entry,
- struct hash_entry **bucket_head, bool delete)
+ struct hash_entry **bucket_head, bool delete)
{
- struct hash_entry *bucket
- = table->bucket + table->hasher (entry, table->n_buckets);
+ struct hash_entry *bucket = safe_hasher (table, entry);
struct hash_entry *cursor;
- if (! (bucket < table->bucket_limit))
- abort ();
-
*bucket_head = bucket;
/* Test for empty bucket. */
@@ -756,26 +800,26 @@ hash_find_entry (Hash_table *table, const void *entry,
return NULL;
/* See if the entry is the first in the bucket. */
- if ((*table->comparator) (entry, bucket->data))
+ if (entry == bucket->data || table->comparator (entry, bucket->data))
{
void *data = bucket->data;
if (delete)
- {
- if (bucket->next)
- {
- struct hash_entry *next = bucket->next;
-
- /* Bump the first overflow entry into the bucket head, then save
- the previous first overflow entry for later recycling. */
- *bucket = *next;
- free_entry (table, next);
- }
- else
- {
- bucket->data = NULL;
- }
- }
+ {
+ if (bucket->next)
+ {
+ struct hash_entry *next = bucket->next;
+
+ /* Bump the first overflow entry into the bucket head, then save
+ the previous first overflow entry for later recycling. */
+ *bucket = *next;
+ free_entry (table, next);
+ }
+ else
+ {
+ bucket->data = NULL;
+ }
+ }
return data;
}
@@ -783,138 +827,267 @@ hash_find_entry (Hash_table *table, const void *entry,
/* Scan the bucket overflow. */
for (cursor = bucket; cursor->next; cursor = cursor->next)
{
- if ((*table->comparator) (entry, cursor->next->data))
- {
- void *data = cursor->next->data;
-
- if (delete)
- {
- struct hash_entry *next = cursor->next;
-
- /* Unlink the entry to delete, then save the freed entry for later
- recycling. */
- cursor->next = next->next;
- free_entry (table, next);
- }
-
- return data;
- }
+ if (entry == cursor->next->data
+ || table->comparator (entry, cursor->next->data))
+ {
+ void *data = cursor->next->data;
+
+ if (delete)
+ {
+ struct hash_entry *next = cursor->next;
+
+ /* Unlink the entry to delete, then save the freed entry for later
+ recycling. */
+ cursor->next = next->next;
+ free_entry (table, next);
+ }
+
+ return data;
+ }
}
/* No entry found. */
return NULL;
}
+/* Internal helper, to move entries from SRC to DST. Both tables must
+ share the same free entry list. If SAFE, only move overflow
+ entries, saving bucket heads for later, so that no allocations will
+ occur. Return false if the free entry list is exhausted and an
+ allocation fails. */
+
+static bool
+transfer_entries (Hash_table *dst, Hash_table *src, bool safe)
+{
+ struct hash_entry *bucket;
+ struct hash_entry *cursor;
+ struct hash_entry *next;
+ for (bucket = src->bucket; bucket < src->bucket_limit; bucket++)
+ if (bucket->data)
+ {
+ void *data;
+ struct hash_entry *new_bucket;
+
+ /* Within each bucket, transfer overflow entries first and
+ then the bucket head, to minimize memory pressure. After
+ all, the only time we might allocate is when moving the
+ bucket head, but moving overflow entries first may create
+ free entries that can be recycled by the time we finally
+ get to the bucket head. */
+ for (cursor = bucket->next; cursor; cursor = next)
+ {
+ data = cursor->data;
+ new_bucket = safe_hasher (dst, data);
+
+ next = cursor->next;
+
+ if (new_bucket->data)
+ {
+ /* Merely relink an existing entry, when moving from a
+ bucket overflow into a bucket overflow. */
+ cursor->next = new_bucket->next;
+ new_bucket->next = cursor;
+ }
+ else
+ {
+ /* Free an existing entry, when moving from a bucket
+ overflow into a bucket header. */
+ new_bucket->data = data;
+ dst->n_buckets_used++;
+ free_entry (dst, cursor);
+ }
+ }
+ /* Now move the bucket head. Be sure that if we fail due to
+ allocation failure that the src table is in a consistent
+ state. */
+ data = bucket->data;
+ bucket->next = NULL;
+ if (safe)
+ continue;
+ new_bucket = safe_hasher (dst, data);
+
+ if (new_bucket->data)
+ {
+ /* Allocate or recycle an entry, when moving from a bucket
+ header into a bucket overflow. */
+ struct hash_entry *new_entry = allocate_entry (dst);
+
+ if (new_entry == NULL)
+ return false;
+
+ new_entry->data = data;
+ new_entry->next = new_bucket->next;
+ new_bucket->next = new_entry;
+ }
+ else
+ {
+ /* Move from one bucket header to another. */
+ new_bucket->data = data;
+ dst->n_buckets_used++;
+ }
+ bucket->data = NULL;
+ src->n_buckets_used--;
+ }
+ return true;
+}
+
/* For an already existing hash table, change the number of buckets through
specifying CANDIDATE. The contents of the hash table are preserved. The
new number of buckets is automatically selected so as to _guarantee_ that
the table may receive at least CANDIDATE different user entries, including
those already in the table, before any other growth of the hash table size
occurs. If TUNING->IS_N_BUCKETS is true, then CANDIDATE specifies the
- exact number of buckets desired. */
+ exact number of buckets desired. Return true iff the rehash succeeded. */
bool
hash_rehash (Hash_table *table, size_t candidate)
{
+ Hash_table storage;
Hash_table *new_table;
- struct hash_entry *bucket;
- struct hash_entry *cursor;
- struct hash_entry *next;
+ size_t new_size = compute_bucket_size (candidate, table->tuning);
- new_table = hash_initialize (candidate, table->tuning, table->hasher,
- table->comparator, table->data_freer);
- if (new_table == NULL)
+ if (!new_size)
+ return false;
+ if (new_size == table->n_buckets)
+ return true;
+ new_table = &storage;
+ new_table->bucket = calloc (new_size, sizeof *new_table->bucket);
+ if (new_table->bucket == NULL)
return false;
+ new_table->n_buckets = new_size;
+ new_table->bucket_limit = new_table->bucket + new_size;
+ new_table->n_buckets_used = 0;
+ new_table->n_entries = 0;
+ new_table->tuning = table->tuning;
+ new_table->hasher = table->hasher;
+ new_table->comparator = table->comparator;
+ new_table->data_freer = table->data_freer;
+
+ /* In order for the transfer to successfully complete, we need
+ additional overflow entries when distinct buckets in the old
+ table collide into a common bucket in the new table. The worst
+ case possible is a hasher that gives a good spread with the old
+ size, but returns a constant with the new size; if we were to
+ guarantee table->n_buckets_used-1 free entries in advance, then
+ the transfer would be guaranteed to not allocate memory.
+ However, for large tables, a guarantee of no further allocation
+ introduces a lot of extra memory pressure, all for an unlikely
+ corner case (most rehashes reduce, rather than increase, the
+ number of overflow entries needed). So, we instead ensure that
+ the transfer process can be reversed if we hit a memory
+ allocation failure mid-transfer. */
/* Merely reuse the extra old space into the new table. */
#if USE_OBSTACK
- obstack_free (&new_table->entry_stack, NULL);
new_table->entry_stack = table->entry_stack;
#endif
new_table->free_entry_list = table->free_entry_list;
- for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
- if (bucket->data)
- for (cursor = bucket; cursor; cursor = next)
- {
- void *data = cursor->data;
- struct hash_entry *new_bucket
- = (new_table->bucket
- + new_table->hasher (data, new_table->n_buckets));
-
- if (! (new_bucket < new_table->bucket_limit))
- abort ();
-
- next = cursor->next;
-
- if (new_bucket->data)
- {
- if (cursor == bucket)
- {
- /* Allocate or recycle an entry, when moving from a bucket
- header into a bucket overflow. */
- struct hash_entry *new_entry = allocate_entry (new_table);
-
- if (new_entry == NULL)
- return false;
-
- new_entry->data = data;
- new_entry->next = new_bucket->next;
- new_bucket->next = new_entry;
- }
- else
- {
- /* Merely relink an existing entry, when moving from a
- bucket overflow into a bucket overflow. */
- cursor->next = new_bucket->next;
- new_bucket->next = cursor;
- }
- }
- else
- {
- /* Free an existing entry, when moving from a bucket
- overflow into a bucket header. Also take care of the
- simple case of moving from a bucket header into a bucket
- header. */
- new_bucket->data = data;
- new_table->n_buckets_used++;
- if (cursor != bucket)
- free_entry (new_table, cursor);
- }
- }
+ if (transfer_entries (new_table, table, false))
+ {
+ /* Entries transferred successfully; tie up the loose ends. */
+ free (table->bucket);
+ table->bucket = new_table->bucket;
+ table->bucket_limit = new_table->bucket_limit;
+ table->n_buckets = new_table->n_buckets;
+ table->n_buckets_used = new_table->n_buckets_used;
+ table->free_entry_list = new_table->free_entry_list;
+ /* table->n_entries and table->entry_stack already hold their value. */
+ return true;
+ }
- free (table->bucket);
- table->bucket = new_table->bucket;
- table->bucket_limit = new_table->bucket_limit;
- table->n_buckets = new_table->n_buckets;
- table->n_buckets_used = new_table->n_buckets_used;
+ /* We've allocated new_table->bucket (and possibly some entries),
+ exhausted the free list, and moved some but not all entries into
+ new_table. We must undo the partial move before returning
+ failure. The only way to get into this situation is if new_table
+ uses fewer buckets than the old table, so we will reclaim some
+ free entries as overflows in the new table are put back into
+ distinct buckets in the old table.
+
+ There are some pathological cases where a single pass through the
+ table requires more intermediate overflow entries than using two
+ passes. Two passes give worse cache performance and takes
+ longer, but at this point, we're already out of memory, so slow
+ and safe is better than failure. */
table->free_entry_list = new_table->free_entry_list;
+ if (! (transfer_entries (table, new_table, true)
+ && transfer_entries (table, new_table, false)))
+ abort ();
/* table->n_entries already holds its value. */
-#if USE_OBSTACK
- table->entry_stack = new_table->entry_stack;
-#endif
- free (new_table);
-
- return true;
+ free (new_table->bucket);
+ return false;
}
-/* If ENTRY matches an entry already in the hash table, return the pointer
- to the entry from the table. Otherwise, insert ENTRY and return ENTRY.
- Return NULL if the storage required for insertion cannot be allocated. */
-
-void *
-hash_insert (Hash_table *table, const void *entry)
+/* Insert ENTRY into hash TABLE if there is not already a matching entry.
+
+ Return -1 upon memory allocation failure.
+ Return 1 if insertion succeeded.
+ Return 0 if there is already a matching entry in the table,
+ and in that case, if MATCHED_ENT is non-NULL, set *MATCHED_ENT
+ to that entry.
+
+ This interface is easier to use than hash_insert when you must
+ distinguish between the latter two cases. More importantly,
+ hash_insert is unusable for some types of ENTRY values. When using
+ hash_insert, the only way to distinguish those cases is to compare
+ the return value and ENTRY. That works only when you can have two
+ different ENTRY values that point to data that compares "equal". Thus,
+ when the ENTRY value is a simple scalar, you must use
+ hash_insert_if_absent. ENTRY must not be NULL. */
+int
+hash_insert_if_absent (Hash_table *table, void const *entry,
+ void const **matched_ent)
{
void *data;
struct hash_entry *bucket;
- /* The caller cannot insert a NULL entry. */
+ /* The caller cannot insert a NULL entry, since hash_lookup returns NULL
+ to indicate "not found", and hash_find_entry uses "bucket->data == NULL"
+ to indicate an empty bucket. */
if (! entry)
abort ();
/* If there's a matching entry already in the table, return that. */
if ((data = hash_find_entry (table, entry, &bucket, false)) != NULL)
- return data;
+ {
+ if (matched_ent)
+ *matched_ent = data;
+ return 0;
+ }
+
+ /* If the growth threshold of the buckets in use has been reached, increase
+ the table size and rehash. There's no point in checking the number of
+ entries: if the hashing function is ill-conditioned, rehashing is not
+ likely to improve it. */
+
+ if (table->n_buckets_used
+ > table->tuning->growth_threshold * table->n_buckets)
+ {
+ /* Check more fully, before starting real work. If tuning arguments
+ became invalid, the second check will rely on proper defaults. */
+ check_tuning (table);
+ if (table->n_buckets_used
+ > table->tuning->growth_threshold * table->n_buckets)
+ {
+ const Hash_tuning *tuning = table->tuning;
+ float candidate =
+ (tuning->is_n_buckets
+ ? (table->n_buckets * tuning->growth_factor)
+ : (table->n_buckets * tuning->growth_factor
+ * tuning->growth_threshold));
+
+ if (SIZE_MAX <= candidate)
+ return -1;
+
+ /* If the rehash fails, arrange to return NULL. */
+ if (!hash_rehash (table, candidate))
+ return -1;
+
+ /* Update the bucket we are interested in. */
+ if (hash_find_entry (table, entry, &bucket, false) != NULL)
+ abort ();
+ }
+ }
/* ENTRY is not matched, it should be inserted. */
@@ -923,7 +1096,7 @@ hash_insert (Hash_table *table, const void *entry)
struct hash_entry *new_entry = allocate_entry (table);
if (new_entry == NULL)
- return NULL;
+ return -1;
/* Add ENTRY in the overflow of the bucket. */
@@ -931,7 +1104,7 @@ hash_insert (Hash_table *table, const void *entry)
new_entry->next = bucket->next;
bucket->next = new_entry;
table->n_entries++;
- return (void *) entry;
+ return 1;
}
/* Add ENTRY right in the bucket head. */
@@ -940,37 +1113,23 @@ hash_insert (Hash_table *table, const void *entry)
table->n_entries++;
table->n_buckets_used++;
- /* If the growth threshold of the buckets in use has been reached, increase
- the table size and rehash. There's no point in checking the number of
- entries: if the hashing function is ill-conditioned, rehashing is not
- likely to improve it. */
+ return 1;
+}
- if (table->n_buckets_used
- > table->tuning->growth_threshold * table->n_buckets)
- {
- /* Check more fully, before starting real work. If tuning arguments
- became invalid, the second check will rely on proper defaults. */
- check_tuning (table);
- if (table->n_buckets_used
- > table->tuning->growth_threshold * table->n_buckets)
- {
- const Hash_tuning *tuning = table->tuning;
- float candidate =
- (tuning->is_n_buckets
- ? (table->n_buckets * tuning->growth_factor)
- : (table->n_buckets * tuning->growth_factor
- * tuning->growth_threshold));
-
- if (SIZE_MAX <= candidate)
- return NULL;
-
- /* If the rehash fails, arrange to return NULL. */
- if (!hash_rehash (table, candidate))
- entry = NULL;
- }
- }
+/* If ENTRY matches an entry already in the hash table, return the pointer
+ to the entry from the table. Otherwise, insert ENTRY and return ENTRY.
+ Return NULL if the storage required for insertion cannot be allocated.
+ This implementation does not support duplicate entries or insertion of
+ NULL. */
- return (void *) entry;
+void *
+hash_insert (Hash_table *table, void const *entry)
+{
+ void const *matched_ent;
+ int err = hash_insert_if_absent (table, entry, &matched_ent);
+ return (err == -1
+ ? NULL
+ : (void *) (err == 0 ? matched_ent : entry));
}
/* If ENTRY is already in the table, remove it and return the just-deleted
@@ -993,27 +1152,45 @@ hash_delete (Hash_table *table, const void *entry)
table->n_buckets_used--;
/* If the shrink threshold of the buckets in use has been reached,
- rehash into a smaller table. */
+ rehash into a smaller table. */
if (table->n_buckets_used
- < table->tuning->shrink_threshold * table->n_buckets)
- {
- /* Check more fully, before starting real work. If tuning arguments
- became invalid, the second check will rely on proper defaults. */
- check_tuning (table);
- if (table->n_buckets_used
- < table->tuning->shrink_threshold * table->n_buckets)
- {
- const Hash_tuning *tuning = table->tuning;
- size_t candidate =
- (tuning->is_n_buckets
- ? table->n_buckets * tuning->shrink_factor
- : (table->n_buckets * tuning->shrink_factor
- * tuning->growth_threshold));
-
- hash_rehash (table, candidate);
- }
- }
+ < table->tuning->shrink_threshold * table->n_buckets)
+ {
+ /* Check more fully, before starting real work. If tuning arguments
+ became invalid, the second check will rely on proper defaults. */
+ check_tuning (table);
+ if (table->n_buckets_used
+ < table->tuning->shrink_threshold * table->n_buckets)
+ {
+ const Hash_tuning *tuning = table->tuning;
+ size_t candidate =
+ (tuning->is_n_buckets
+ ? table->n_buckets * tuning->shrink_factor
+ : (table->n_buckets * tuning->shrink_factor
+ * tuning->growth_threshold));
+
+ if (!hash_rehash (table, candidate))
+ {
+ /* Failure to allocate memory in an attempt to
+ shrink the table is not fatal. But since memory
+ is low, we can at least be kind and free any
+ spare entries, rather than keeping them tied up
+ in the free entry list. */
+#if ! USE_OBSTACK
+ struct hash_entry *cursor = table->free_entry_list;
+ struct hash_entry *next;
+ while (cursor)
+ {
+ next = cursor->next;
+ free (cursor);
+ cursor = next;
+ }
+ table->free_entry_list = NULL;
+#endif
+ }
+ }
+ }
}
return data;
@@ -1026,22 +1203,22 @@ hash_delete (Hash_table *table, const void *entry)
void
hash_print (const Hash_table *table)
{
- struct hash_entry const *bucket;
+ struct hash_entry *bucket = (struct hash_entry *) table->bucket;
- for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
+ for ( ; bucket < table->bucket_limit; bucket++)
{
struct hash_entry *cursor;
if (bucket)
- printf ("%lu:\n", (unsigned long int) (bucket - table->bucket));
+ printf ("%lu:\n", (unsigned long int) (bucket - table->bucket));
for (cursor = bucket; cursor; cursor = cursor->next)
- {
- char const *s = cursor->data;
- /* FIXME */
- if (s)
- printf (" %s\n", s);
- }
+ {
+ char const *s = cursor->data;
+ /* FIXME */
+ if (s)
+ printf (" %s\n", s);
+ }
}
}
diff --git a/lib/hash.h b/lib/hash.h
index ab63a86..b61bee6 100644
--- a/lib/hash.h
+++ b/lib/hash.h
@@ -1,11 +1,12 @@
/* hash - hashing table processing.
- Copyright (C) 1998, 1999, 2001, 2003 Free Software Foundation, Inc.
+ Copyright (C) 1998-1999, 2001, 2003, 2009-2016 Free Software Foundation,
+ Inc.
Written by Jim Meyering <meyering@ascend.com>, 1998.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,13 +14,12 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* A generic hash table package. */
/* Make sure USE_OBSTACK is defined to 1 if you want the allocator to use
- obstacks instead of malloc, and recompile `hash.c' with same setting. */
+ obstacks instead of malloc, and recompile 'hash.c' with same setting. */
#ifndef HASH_H_
# define HASH_H_
@@ -27,27 +27,39 @@
# include <stdio.h>
# include <stdbool.h>
+/* The __attribute__ feature is available in gcc versions 2.5 and later.
+ The warn_unused_result attribute appeared first in gcc-3.4.0. */
+# if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
+# define _GL_ATTRIBUTE_WUR __attribute__ ((__warn_unused_result__))
+# else
+# define _GL_ATTRIBUTE_WUR /* empty */
+# endif
+
+# ifndef _GL_ATTRIBUTE_DEPRECATED
+/* The __attribute__((__deprecated__)) feature
+ is available in gcc versions 3.1 and newer. */
+# if __GNUC__ < 3 || (__GNUC__ == 3 && __GNUC_MINOR__ < 1)
+# define _GL_ATTRIBUTE_DEPRECATED /* empty */
+# else
+# define _GL_ATTRIBUTE_DEPRECATED __attribute__ ((__deprecated__))
+# endif
+# endif
+
typedef size_t (*Hash_hasher) (const void *, size_t);
typedef bool (*Hash_comparator) (const void *, const void *);
typedef void (*Hash_data_freer) (void *);
typedef bool (*Hash_processor) (void *, void *);
-struct hash_entry
- {
- void *data;
- struct hash_entry *next;
- };
-
struct hash_tuning
{
- /* This structure is mainly used for `hash_initialize', see the block
- documentation of `hash_reset_tuning' for more complete comments. */
-
- float shrink_threshold; /* ratio of used buckets to trigger a shrink */
- float shrink_factor; /* ratio of new smaller size to original size */
- float growth_threshold; /* ratio of used buckets to trigger a growth */
- float growth_factor; /* ratio of new bigger size to original size */
- bool is_n_buckets; /* if CANDIDATE really means table size */
+ /* This structure is mainly used for 'hash_initialize', see the block
+ documentation of 'hash_reset_tuning' for more complete comments. */
+
+ float shrink_threshold; /* ratio of used buckets to trigger a shrink */
+ float shrink_factor; /* ratio of new smaller size to original size */
+ float growth_threshold; /* ratio of used buckets to trigger a growth */
+ float growth_factor; /* ratio of new bigger size to original size */
+ bool is_n_buckets; /* if CANDIDATE really means table size */
};
typedef struct hash_tuning Hash_tuning;
@@ -57,32 +69,35 @@ struct hash_table;
typedef struct hash_table Hash_table;
/* Information and lookup. */
-size_t hash_get_n_buckets (const Hash_table *);
-size_t hash_get_n_buckets_used (const Hash_table *);
-size_t hash_get_n_entries (const Hash_table *);
-size_t hash_get_max_bucket_length (const Hash_table *);
-bool hash_table_ok (const Hash_table *);
+size_t hash_get_n_buckets (const Hash_table *) _GL_ATTRIBUTE_PURE;
+size_t hash_get_n_buckets_used (const Hash_table *) _GL_ATTRIBUTE_PURE;
+size_t hash_get_n_entries (const Hash_table *) _GL_ATTRIBUTE_PURE;
+size_t hash_get_max_bucket_length (const Hash_table *) _GL_ATTRIBUTE_PURE;
+bool hash_table_ok (const Hash_table *) _GL_ATTRIBUTE_PURE;
void hash_print_statistics (const Hash_table *, FILE *);
void *hash_lookup (const Hash_table *, const void *);
/* Walking. */
-void *hash_get_first (const Hash_table *);
+void *hash_get_first (const Hash_table *) _GL_ATTRIBUTE_PURE;
void *hash_get_next (const Hash_table *, const void *);
size_t hash_get_entries (const Hash_table *, void **, size_t);
size_t hash_do_for_each (const Hash_table *, Hash_processor, void *);
/* Allocation and clean-up. */
-size_t hash_string (const char *, size_t);
+size_t hash_string (const char *, size_t) _GL_ATTRIBUTE_PURE;
void hash_reset_tuning (Hash_tuning *);
Hash_table *hash_initialize (size_t, const Hash_tuning *,
- Hash_hasher, Hash_comparator,
- Hash_data_freer);
+ Hash_hasher, Hash_comparator,
+ Hash_data_freer) _GL_ATTRIBUTE_WUR;
void hash_clear (Hash_table *);
void hash_free (Hash_table *);
/* Insertion and deletion. */
-bool hash_rehash (Hash_table *, size_t);
-void *hash_insert (Hash_table *, const void *);
+bool hash_rehash (Hash_table *, size_t) _GL_ATTRIBUTE_WUR;
+void *hash_insert (Hash_table *, const void *) _GL_ATTRIBUTE_WUR;
+
+int hash_insert_if_absent (Hash_table *table, const void *entry,
+ const void **matched_ent);
void *hash_delete (Hash_table *, const void *);
#endif
diff --git a/lib/heap.c b/lib/heap.c
new file mode 100644
index 0000000..70aaab0
--- /dev/null
+++ b/lib/heap.c
@@ -0,0 +1,151 @@
+/* Barebones heap implementation supporting only insert and pop.
+
+ Copyright (C) 2010-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Full implementation: GDSL (http://gna.org/projects/gdsl/) by Nicolas
+ Darnis <ndarnis@free.fr>. */
+
+#include <config.h>
+
+#include "heap.h"
+#include "stdlib--.h"
+#include "xalloc.h"
+
+static int heap_default_compare (void const *, void const *);
+static size_t heapify_down (void **, size_t, size_t,
+ int (*) (void const *, void const *));
+static void heapify_up (void **, size_t,
+ int (*) (void const *, void const *));
+
+struct heap
+{
+ void **array; /* array[0] is not used */
+ size_t capacity; /* Array size */
+ size_t count; /* Used as index to last element. Also is num of items. */
+ int (*compare) (void const *, void const *);
+};
+
+/* Allocate memory for the heap. */
+
+struct heap *
+heap_alloc (int (*compare) (void const *, void const *), size_t n_reserve)
+{
+ struct heap *heap = xmalloc (sizeof *heap);
+
+ if (n_reserve == 0)
+ n_reserve = 1;
+
+ heap->array = xnmalloc (n_reserve, sizeof *(heap->array));
+
+ heap->array[0] = NULL;
+ heap->capacity = n_reserve;
+ heap->count = 0;
+ heap->compare = compare ? compare : heap_default_compare;
+
+ return heap;
+}
+
+
+static int
+heap_default_compare (void const *a, void const *b)
+{
+ return 0;
+}
+
+
+void
+heap_free (struct heap *heap)
+{
+ free (heap->array);
+ free (heap);
+}
+
+/* Insert element into heap. */
+
+int
+heap_insert (struct heap *heap, void *item)
+{
+ if (heap->capacity - 1 <= heap->count)
+ heap->array = x2nrealloc (heap->array, &heap->capacity,
+ sizeof *(heap->array));
+
+ heap->array[++heap->count] = item;
+ heapify_up (heap->array, heap->count, heap->compare);
+
+ return 0;
+}
+
+/* Pop top element off heap. */
+
+void *
+heap_remove_top (struct heap *heap)
+{
+ void *top;
+
+ if (heap->count == 0)
+ return NULL;
+
+ top = heap->array[1];
+ heap->array[1] = heap->array[heap->count--];
+ heapify_down (heap->array, heap->count, 1, heap->compare);
+
+ return top;
+}
+
+/* Move element down into appropriate position in heap. */
+
+static size_t
+heapify_down (void **array, size_t count, size_t initial,
+ int (*compare) (void const *, void const *))
+{
+ void *element = array[initial];
+
+ size_t parent = initial;
+ while (parent <= count / 2)
+ {
+ size_t child = 2 * parent;
+
+ if (child < count && compare (array[child], array[child+1]) < 0)
+ child++;
+
+ if (compare (array[child], element) <= 0)
+ break;
+
+ array[parent] = array[child];
+ parent = child;
+ }
+
+ array[parent] = element;
+ return parent;
+}
+
+/* Move element up into appropriate position in heap. */
+
+static void
+heapify_up (void **array, size_t count,
+ int (*compare) (void const *, void const *))
+{
+ size_t k = count;
+ void *new_element = array[k];
+
+ while (k != 1 && compare (array[k/2], new_element) <= 0)
+ {
+ array[k] = array[k/2];
+ k /= 2;
+ }
+
+ array[k] = new_element;
+}
diff --git a/lib/heap.h b/lib/heap.h
new file mode 100644
index 0000000..31d6e06
--- /dev/null
+++ b/lib/heap.h
@@ -0,0 +1,26 @@
+/* Barebones heap implementation supporting only insert and pop.
+
+ Copyright (C) 2010-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Full implementation: GDSL (http://gna.org/projects/gdsl/) by Nicolas
+ Darnis <ndarnis@free.fr>. Adapted by Gene Auyeung. */
+
+#include <stddef.h>
+
+struct heap *heap_alloc (int (*) (void const *, void const *), size_t);
+void heap_free (struct heap *);
+int heap_insert (struct heap *heap, void *item);
+void *heap_remove_top (struct heap *heap);
diff --git a/lib/human.c b/lib/human.c
index ecf4c97..7fc0bf2 100644
--- a/lib/human.c
+++ b/lib/human.c
@@ -1,12 +1,11 @@
/* human.c -- print human readable file size
- Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
- 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 1996-2007, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert and Larry McVoy. */
@@ -28,28 +26,24 @@
#include <stdlib.h>
#include <string.h>
-#include "gettext.h"
-#define _(msgid) gettext (msgid)
-
#include <argmatch.h>
#include <error.h>
#include <intprops.h>
-#include <xstrtol.h>
/* The maximum length of a suffix like "KiB". */
#define HUMAN_READABLE_SUFFIX_LENGTH_MAX 3
static const char power_letter[] =
{
- 0, /* not used */
- 'K', /* kibi ('k' for kilo is a special case) */
- 'M', /* mega or mebi */
- 'G', /* giga or gibi */
- 'T', /* tera or tebi */
- 'P', /* peta or pebi */
- 'E', /* exa or exbi */
- 'Z', /* zetta or 2**70 */
- 'Y' /* yotta or 2**80 */
+ 0, /* not used */
+ 'K', /* kibi ('k' for kilo is a special case) */
+ 'M', /* mega or mebi */
+ 'G', /* giga or gibi */
+ 'T', /* tera or tebi */
+ 'P', /* peta or pebi */
+ 'E', /* exa or exbi */
+ 'Z', /* zetta or 2**70 */
+ 'Y' /* yotta or 2**80 */
};
@@ -78,12 +72,12 @@ adjust_value (int inexact_style, long double value)
each byte inserted. Return the starting address of the modified
number.
- To group the digits, use GROUPING and THOUSANDS_SEP as in `struct
+ To group the digits, use GROUPING and THOUSANDS_SEP as in 'struct
lconv' from <locale.h>. */
static char *
group_number (char *number, size_t numberlen,
- char const *grouping, char const *thousands_sep)
+ char const *grouping, char const *thousands_sep)
{
register char *d;
size_t grouplen = SIZE_MAX;
@@ -102,19 +96,19 @@ group_number (char *number, size_t numberlen,
unsigned char g = *grouping;
if (g)
- {
- grouplen = g < CHAR_MAX ? g : i;
- grouping++;
- }
+ {
+ grouplen = g < CHAR_MAX ? g : i;
+ grouping++;
+ }
if (i < grouplen)
- grouplen = i;
+ grouplen = i;
d -= grouplen;
i -= grouplen;
memcpy (d, buf + i, grouplen);
if (i == 0)
- return d;
+ return d;
d -= thousands_seplen;
memcpy (d, thousands_sep, thousands_seplen);
@@ -134,7 +128,7 @@ group_number (char *number, size_t numberlen,
that cannot be expressed exactly.
If (OPTS & human_group_digits), group the thousands digits
- according to the locale, e.g., `1,000,000' in an American English
+ according to the locale, e.g., "1,000,000" in an American English
locale.
If (OPTS & human_autoscale), deduce the output block size
@@ -157,7 +151,7 @@ group_number (char *number, size_t numberlen,
char *
human_readable (uintmax_t n, char *buf, int opts,
- uintmax_t from_block_size, uintmax_t to_block_size)
+ uintmax_t from_block_size, uintmax_t to_block_size)
{
int inexact_style =
opts & (human_round_to_nearest | human_floor | human_ceiling);
@@ -191,7 +185,8 @@ human_readable (uintmax_t n, char *buf, int opts,
if (strlen (l->thousands_sep) <= MB_LEN_MAX)
thousands_sep = l->thousands_sep;
- psuffix = buf + LONGEST_HUMAN_READABLE - HUMAN_READABLE_SUFFIX_LENGTH_MAX;
+ /* Leave room for a trailing space and following suffix. */
+ psuffix = buf + LONGEST_HUMAN_READABLE - 1 - HUMAN_READABLE_SUFFIX_LENGTH_MAX;
p = psuffix;
/* Adjust AMT out of FROM_BLOCK_SIZE units and into TO_BLOCK_SIZE
@@ -200,16 +195,16 @@ human_readable (uintmax_t n, char *buf, int opts,
if (to_block_size <= from_block_size)
{
if (from_block_size % to_block_size == 0)
- {
- uintmax_t multiplier = from_block_size / to_block_size;
- amt = n * multiplier;
- if (amt / multiplier == n)
- {
- tenths = 0;
- rounding = 0;
- goto use_integer_arithmetic;
- }
- }
+ {
+ uintmax_t multiplier = from_block_size / to_block_size;
+ amt = n * multiplier;
+ if (amt / multiplier == n)
+ {
+ tenths = 0;
+ rounding = 0;
+ goto use_integer_arithmetic;
+ }
+ }
}
else if (from_block_size != 0 && to_block_size % from_block_size == 0)
{
@@ -234,37 +229,37 @@ human_readable (uintmax_t n, char *buf, int opts,
if (! (opts & human_autoscale))
{
- sprintf (buf, "%.0Lf", adjust_value (inexact_style, damt));
- buflen = strlen (buf);
- nonintegerlen = 0;
+ sprintf (buf, "%.0Lf", adjust_value (inexact_style, damt));
+ buflen = strlen (buf);
+ nonintegerlen = 0;
}
else
{
- long double e = 1;
- exponent = 0;
-
- do
- {
- e *= base;
- exponent++;
- }
- while (e * base <= damt && exponent < exponent_max);
-
- damt /= e;
-
- sprintf (buf, "%.1Lf", adjust_value (inexact_style, damt));
- buflen = strlen (buf);
- nonintegerlen = decimal_pointlen + 1;
-
- if (1 + nonintegerlen + ! (opts & human_base_1024) < buflen
- || ((opts & human_suppress_point_zero)
- && buf[buflen - 1] == '0'))
- {
- sprintf (buf, "%.0Lf",
- adjust_value (inexact_style, damt * 10) / 10);
- buflen = strlen (buf);
- nonintegerlen = 0;
- }
+ long double e = 1;
+ exponent = 0;
+
+ do
+ {
+ e *= base;
+ exponent++;
+ }
+ while (e * base <= damt && exponent < exponent_max);
+
+ damt /= e;
+
+ sprintf (buf, "%.1Lf", adjust_value (inexact_style, damt));
+ buflen = strlen (buf);
+ nonintegerlen = decimal_pointlen + 1;
+
+ if (1 + nonintegerlen + ! (opts & human_base_1024) < buflen
+ || ((opts & human_suppress_point_zero)
+ && buf[buflen - 1] == '0'))
+ {
+ sprintf (buf, "%.0Lf",
+ adjust_value (inexact_style, damt * 10) / 10);
+ buflen = strlen (buf);
+ nonintegerlen = 0;
+ }
}
p = psuffix - buflen;
@@ -282,77 +277,77 @@ human_readable (uintmax_t n, char *buf, int opts,
if (opts & human_autoscale)
{
- exponent = 0;
-
- if (base <= amt)
- {
- do
- {
- unsigned int r10 = (amt % base) * 10 + tenths;
- unsigned int r2 = (r10 % base) * 2 + (rounding >> 1);
- amt /= base;
- tenths = r10 / base;
- rounding = (r2 < base
- ? (r2 + rounding) != 0
- : 2 + (base < r2 + rounding));
- exponent++;
- }
- while (base <= amt && exponent < exponent_max);
-
- if (amt < 10)
- {
- if (inexact_style == human_round_to_nearest
- ? 2 < rounding + (tenths & 1)
- : inexact_style == human_ceiling && 0 < rounding)
- {
- tenths++;
- rounding = 0;
-
- if (tenths == 10)
- {
- amt++;
- tenths = 0;
- }
- }
-
- if (amt < 10
- && (tenths || ! (opts & human_suppress_point_zero)))
- {
- *--p = '0' + tenths;
- p -= decimal_pointlen;
- memcpy (p, decimal_point, decimal_pointlen);
- tenths = rounding = 0;
- }
- }
- }
+ exponent = 0;
+
+ if (base <= amt)
+ {
+ do
+ {
+ unsigned int r10 = (amt % base) * 10 + tenths;
+ unsigned int r2 = (r10 % base) * 2 + (rounding >> 1);
+ amt /= base;
+ tenths = r10 / base;
+ rounding = (r2 < base
+ ? (r2 + rounding) != 0
+ : 2 + (base < r2 + rounding));
+ exponent++;
+ }
+ while (base <= amt && exponent < exponent_max);
+
+ if (amt < 10)
+ {
+ if (inexact_style == human_round_to_nearest
+ ? 2 < rounding + (tenths & 1)
+ : inexact_style == human_ceiling && 0 < rounding)
+ {
+ tenths++;
+ rounding = 0;
+
+ if (tenths == 10)
+ {
+ amt++;
+ tenths = 0;
+ }
+ }
+
+ if (amt < 10
+ && (tenths || ! (opts & human_suppress_point_zero)))
+ {
+ *--p = '0' + tenths;
+ p -= decimal_pointlen;
+ memcpy (p, decimal_point, decimal_pointlen);
+ tenths = rounding = 0;
+ }
+ }
+ }
}
if (inexact_style == human_round_to_nearest
- ? 5 < tenths + (0 < rounding + (amt & 1))
- : inexact_style == human_ceiling && 0 < tenths + rounding)
+ ? 5 < tenths + (0 < rounding + (amt & 1))
+ : inexact_style == human_ceiling && 0 < tenths + rounding)
{
- amt++;
-
- if ((opts & human_autoscale)
- && amt == base && exponent < exponent_max)
- {
- exponent++;
- if (! (opts & human_suppress_point_zero))
- {
- *--p = '0';
- p -= decimal_pointlen;
- memcpy (p, decimal_point, decimal_pointlen);
- }
- amt = 1;
- }
+ amt++;
+
+ if ((opts & human_autoscale)
+ && amt == base && exponent < exponent_max)
+ {
+ exponent++;
+ if (! (opts & human_suppress_point_zero))
+ {
+ *--p = '0';
+ p -= decimal_pointlen;
+ memcpy (p, decimal_point, decimal_pointlen);
+ }
+ amt = 1;
+ }
}
integerlim = p;
do
{
- int digit = amt % 10;
- *--p = digit + '0';
+ int digit = amt % 10;
+ *--p = digit + '0';
}
while ((amt /= 10) != 0);
}
@@ -364,28 +359,28 @@ human_readable (uintmax_t n, char *buf, int opts,
if (opts & human_SI)
{
if (exponent < 0)
- {
- uintmax_t power;
- exponent = 0;
- for (power = 1; power < to_block_size; power *= base)
- if (++exponent == exponent_max)
- break;
- }
+ {
+ uintmax_t power;
+ exponent = 0;
+ for (power = 1; power < to_block_size; power *= base)
+ if (++exponent == exponent_max)
+ break;
+ }
if ((exponent | (opts & human_B)) && (opts & human_space_before_unit))
- *psuffix++ = ' ';
+ *psuffix++ = ' ';
if (exponent)
- *psuffix++ = (! (opts & human_base_1024) && exponent == 1
- ? 'k'
- : power_letter[exponent]);
+ *psuffix++ = (! (opts & human_base_1024) && exponent == 1
+ ? 'k'
+ : power_letter[exponent]);
if (opts & human_B)
- {
- if ((opts & human_base_1024) && exponent)
- *psuffix++ = 'i';
- *psuffix++ = 'B';
- }
+ {
+ if ((opts & human_base_1024) && exponent)
+ *psuffix++ = 'i';
+ *psuffix++ = 'B';
+ }
}
*psuffix = '\0';
@@ -426,54 +421,51 @@ humblock (char const *spec, uintmax_t *block_size, int *options)
else
{
if (*spec == '\'')
- {
- opts |= human_group_digits;
- spec++;
- }
+ {
+ opts |= human_group_digits;
+ spec++;
+ }
if (0 <= (i = ARGMATCH (spec, block_size_args, block_size_opts)))
- {
- opts |= block_size_opts[i];
- *block_size = 1;
- }
+ {
+ opts |= block_size_opts[i];
+ *block_size = 1;
+ }
else
- {
- char *ptr;
- strtol_error e = xstrtoumax (spec, &ptr, 0, block_size,
- "eEgGkKmMpPtTyYzZ0");
- if (e != LONGINT_OK)
- {
- *options = 0;
- return e;
- }
- for (; ! ('0' <= *spec && *spec <= '9'); spec++)
- if (spec == ptr)
- {
- opts |= human_SI;
- if (ptr[-1] == 'B')
- opts |= human_B;
- if (ptr[-1] != 'B' || ptr[-2] == 'i')
- opts |= human_base_1024;
- break;
- }
- }
+ {
+ char *ptr;
+ strtol_error e = xstrtoumax (spec, &ptr, 0, block_size,
+ "eEgGkKmMpPtTyYzZ0");
+ if (e != LONGINT_OK)
+ {
+ *options = 0;
+ return e;
+ }
+ for (; ! ('0' <= *spec && *spec <= '9'); spec++)
+ if (spec == ptr)
+ {
+ opts |= human_SI;
+ if (ptr[-1] == 'B')
+ opts |= human_B;
+ if (ptr[-1] != 'B' || ptr[-2] == 'i')
+ opts |= human_base_1024;
+ break;
+ }
+ }
}
*options = opts;
return LONGINT_OK;
}
-int
-human_options (char const *spec, bool report_errors, uintmax_t *block_size)
+enum strtol_error
+human_options (char const *spec, int *opts, uintmax_t *block_size)
{
- int opts;
- strtol_error e = humblock (spec, block_size, &opts);
+ strtol_error e = humblock (spec, block_size, opts);
if (*block_size == 0)
{
*block_size = default_block_size ();
e = LONGINT_INVALID;
}
- if (e != LONGINT_OK && report_errors)
- STRTOL_FATAL_ERROR (spec, _("block size"), e);
- return opts;
+ return e;
}
diff --git a/lib/human.h b/lib/human.h
index 44b8b36..8f1b94e 100644
--- a/lib/human.h
+++ b/lib/human.h
@@ -1,12 +1,11 @@
/* human.h -- print human readable file size
- Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
- 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 1996-2007, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert and Larry McVoy. */
@@ -27,6 +25,8 @@
# include <stdint.h>
# include <unistd.h>
+# include <xstrtol.h>
+
/* A conservative bound on the maximum length of a human-readable string.
The output can be the square of the largest uintmax_t, so double
its size before converting to a bound.
@@ -52,7 +52,7 @@ enum
/* Round to minus infinity. */
human_floor = 2,
- /* Group digits together, e.g. `1,000,000'. This uses the
+ /* Group digits together, e.g. "1,000,000". This uses the
locale-defined grouping; the traditional C locale does not group,
so this has effect only if some other locale is in use. */
human_group_digits = 4,
@@ -78,6 +78,6 @@ enum
char *human_readable (uintmax_t, char *, int, uintmax_t, uintmax_t);
-int human_options (char const *, bool, uintmax_t *);
+enum strtol_error human_options (char const *, int *, uintmax_t *);
#endif /* HUMAN_H_ */
diff --git a/lib/i-ring.c b/lib/i-ring.c
index 457b838..2915722 100644
--- a/lib/i-ring.c
+++ b/lib/i-ring.c
@@ -1,10 +1,10 @@
/* a simple ring buffer
- Copyright (C) 2006 Free Software Foundation, Inc.
+ Copyright (C) 2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -12,8 +12,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* written by Jim Meyering */
diff --git a/lib/i-ring.h b/lib/i-ring.h
index fadfa2b..0064b65 100644
--- a/lib/i-ring.h
+++ b/lib/i-ring.h
@@ -1,10 +1,10 @@
/* definitions for a simple ring buffer
- Copyright (C) 2006 Free Software Foundation, Inc.
+ Copyright (C) 2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -12,8 +12,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <stdbool.h>
#include "verify.h"
@@ -42,4 +41,4 @@ typedef struct I_ring I_ring;
void i_ring_init (I_ring *ir, int ir_default_val);
int i_ring_push (I_ring *ir, int val);
int i_ring_pop (I_ring *ir);
-bool i_ring_empty (I_ring const *ir);
+bool i_ring_empty (I_ring const *ir) _GL_ATTRIBUTE_PURE;
diff --git a/lib/iconv.c b/lib/iconv.c
new file mode 100644
index 0000000..9ce9c01
--- /dev/null
+++ b/lib/iconv.c
@@ -0,0 +1,449 @@
+/* Character set conversion.
+ Copyright (C) 1999-2001, 2007, 2009-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <iconv.h>
+
+#include <stddef.h>
+
+#if REPLACE_ICONV_UTF
+# include <errno.h>
+# include <stdint.h>
+# include <stdlib.h>
+# include "unistr.h"
+# ifndef uintptr_t
+# define uintptr_t unsigned long
+# endif
+#endif
+
+#if REPLACE_ICONV_UTF
+
+/* UTF-{16,32}{BE,LE} converters taken from GNU libiconv 1.11. */
+
+/* Return code if invalid. (xxx_mbtowc) */
+# define RET_ILSEQ -1
+/* Return code if no bytes were read. (xxx_mbtowc) */
+# define RET_TOOFEW -2
+
+/* Return code if invalid. (xxx_wctomb) */
+# define RET_ILUNI -1
+/* Return code if output buffer is too small. (xxx_wctomb, xxx_reset) */
+# define RET_TOOSMALL -2
+
+/*
+ * UTF-16BE
+ */
+
+/* Specification: RFC 2781 */
+
+static int
+utf16be_mbtowc (ucs4_t *pwc, const unsigned char *s, size_t n)
+{
+ if (n >= 2)
+ {
+ ucs4_t wc = (s[0] << 8) + s[1];
+ if (wc >= 0xd800 && wc < 0xdc00)
+ {
+ if (n >= 4)
+ {
+ ucs4_t wc2 = (s[2] << 8) + s[3];
+ if (!(wc2 >= 0xdc00 && wc2 < 0xe000))
+ return RET_ILSEQ;
+ *pwc = 0x10000 + ((wc - 0xd800) << 10) + (wc2 - 0xdc00);
+ return 4;
+ }
+ }
+ else if (wc >= 0xdc00 && wc < 0xe000)
+ {
+ return RET_ILSEQ;
+ }
+ else
+ {
+ *pwc = wc;
+ return 2;
+ }
+ }
+ return RET_TOOFEW;
+}
+
+static int
+utf16be_wctomb (unsigned char *r, ucs4_t wc, size_t n)
+{
+ if (!(wc >= 0xd800 && wc < 0xe000))
+ {
+ if (wc < 0x10000)
+ {
+ if (n >= 2)
+ {
+ r[0] = (unsigned char) (wc >> 8);
+ r[1] = (unsigned char) wc;
+ return 2;
+ }
+ else
+ return RET_TOOSMALL;
+ }
+ else if (wc < 0x110000)
+ {
+ if (n >= 4)
+ {
+ ucs4_t wc1 = 0xd800 + ((wc - 0x10000) >> 10);
+ ucs4_t wc2 = 0xdc00 + ((wc - 0x10000) & 0x3ff);
+ r[0] = (unsigned char) (wc1 >> 8);
+ r[1] = (unsigned char) wc1;
+ r[2] = (unsigned char) (wc2 >> 8);
+ r[3] = (unsigned char) wc2;
+ return 4;
+ }
+ else
+ return RET_TOOSMALL;
+ }
+ }
+ return RET_ILUNI;
+}
+
+/*
+ * UTF-16LE
+ */
+
+/* Specification: RFC 2781 */
+
+static int
+utf16le_mbtowc (ucs4_t *pwc, const unsigned char *s, size_t n)
+{
+ if (n >= 2)
+ {
+ ucs4_t wc = s[0] + (s[1] << 8);
+ if (wc >= 0xd800 && wc < 0xdc00)
+ {
+ if (n >= 4)
+ {
+ ucs4_t wc2 = s[2] + (s[3] << 8);
+ if (!(wc2 >= 0xdc00 && wc2 < 0xe000))
+ return RET_ILSEQ;
+ *pwc = 0x10000 + ((wc - 0xd800) << 10) + (wc2 - 0xdc00);
+ return 4;
+ }
+ }
+ else if (wc >= 0xdc00 && wc < 0xe000)
+ {
+ return RET_ILSEQ;
+ }
+ else
+ {
+ *pwc = wc;
+ return 2;
+ }
+ }
+ return RET_TOOFEW;
+}
+
+static int
+utf16le_wctomb (unsigned char *r, ucs4_t wc, size_t n)
+{
+ if (!(wc >= 0xd800 && wc < 0xe000))
+ {
+ if (wc < 0x10000)
+ {
+ if (n >= 2)
+ {
+ r[0] = (unsigned char) wc;
+ r[1] = (unsigned char) (wc >> 8);
+ return 2;
+ }
+ else
+ return RET_TOOSMALL;
+ }
+ else if (wc < 0x110000)
+ {
+ if (n >= 4)
+ {
+ ucs4_t wc1 = 0xd800 + ((wc - 0x10000) >> 10);
+ ucs4_t wc2 = 0xdc00 + ((wc - 0x10000) & 0x3ff);
+ r[0] = (unsigned char) wc1;
+ r[1] = (unsigned char) (wc1 >> 8);
+ r[2] = (unsigned char) wc2;
+ r[3] = (unsigned char) (wc2 >> 8);
+ return 4;
+ }
+ else
+ return RET_TOOSMALL;
+ }
+ }
+ return RET_ILUNI;
+}
+
+/*
+ * UTF-32BE
+ */
+
+/* Specification: Unicode 3.1 Standard Annex #19 */
+
+static int
+utf32be_mbtowc (ucs4_t *pwc, const unsigned char *s, size_t n)
+{
+ if (n >= 4)
+ {
+ ucs4_t wc = (s[0] << 24) + (s[1] << 16) + (s[2] << 8) + s[3];
+ if (wc < 0x110000 && !(wc >= 0xd800 && wc < 0xe000))
+ {
+ *pwc = wc;
+ return 4;
+ }
+ else
+ return RET_ILSEQ;
+ }
+ return RET_TOOFEW;
+}
+
+static int
+utf32be_wctomb (unsigned char *r, ucs4_t wc, size_t n)
+{
+ if (wc < 0x110000 && !(wc >= 0xd800 && wc < 0xe000))
+ {
+ if (n >= 4)
+ {
+ r[0] = 0;
+ r[1] = (unsigned char) (wc >> 16);
+ r[2] = (unsigned char) (wc >> 8);
+ r[3] = (unsigned char) wc;
+ return 4;
+ }
+ else
+ return RET_TOOSMALL;
+ }
+ return RET_ILUNI;
+}
+
+/*
+ * UTF-32LE
+ */
+
+/* Specification: Unicode 3.1 Standard Annex #19 */
+
+static int
+utf32le_mbtowc (ucs4_t *pwc, const unsigned char *s, size_t n)
+{
+ if (n >= 4)
+ {
+ ucs4_t wc = s[0] + (s[1] << 8) + (s[2] << 16) + (s[3] << 24);
+ if (wc < 0x110000 && !(wc >= 0xd800 && wc < 0xe000))
+ {
+ *pwc = wc;
+ return 4;
+ }
+ else
+ return RET_ILSEQ;
+ }
+ return RET_TOOFEW;
+}
+
+static int
+utf32le_wctomb (unsigned char *r, ucs4_t wc, size_t n)
+{
+ if (wc < 0x110000 && !(wc >= 0xd800 && wc < 0xe000))
+ {
+ if (n >= 4)
+ {
+ r[0] = (unsigned char) wc;
+ r[1] = (unsigned char) (wc >> 8);
+ r[2] = (unsigned char) (wc >> 16);
+ r[3] = 0;
+ return 4;
+ }
+ else
+ return RET_TOOSMALL;
+ }
+ return RET_ILUNI;
+}
+
+#endif
+
+size_t
+rpl_iconv (iconv_t cd,
+ ICONV_CONST char **inbuf, size_t *inbytesleft,
+ char **outbuf, size_t *outbytesleft)
+#undef iconv
+{
+#if REPLACE_ICONV_UTF
+ switch ((uintptr_t) cd)
+ {
+ {
+ int (*xxx_wctomb) (unsigned char *, ucs4_t, size_t);
+
+ case (uintptr_t) _ICONV_UTF8_UTF16BE:
+ xxx_wctomb = utf16be_wctomb;
+ goto loop_from_utf8;
+ case (uintptr_t) _ICONV_UTF8_UTF16LE:
+ xxx_wctomb = utf16le_wctomb;
+ goto loop_from_utf8;
+ case (uintptr_t) _ICONV_UTF8_UTF32BE:
+ xxx_wctomb = utf32be_wctomb;
+ goto loop_from_utf8;
+ case (uintptr_t) _ICONV_UTF8_UTF32LE:
+ xxx_wctomb = utf32le_wctomb;
+ goto loop_from_utf8;
+
+ loop_from_utf8:
+ if (inbuf == NULL || *inbuf == NULL)
+ return 0;
+ {
+ ICONV_CONST char *inptr = *inbuf;
+ size_t inleft = *inbytesleft;
+ char *outptr = *outbuf;
+ size_t outleft = *outbytesleft;
+ size_t res = 0;
+ while (inleft > 0)
+ {
+ ucs4_t uc;
+ int m = u8_mbtoucr (&uc, (const uint8_t *) inptr, inleft);
+ if (m <= 0)
+ {
+ if (m == -1)
+ {
+ errno = EILSEQ;
+ res = (size_t)(-1);
+ break;
+ }
+ if (m == -2)
+ {
+ errno = EINVAL;
+ res = (size_t)(-1);
+ break;
+ }
+ abort ();
+ }
+ else
+ {
+ int n = xxx_wctomb ((uint8_t *) outptr, uc, outleft);
+ if (n < 0)
+ {
+ if (n == RET_ILUNI)
+ {
+ errno = EILSEQ;
+ res = (size_t)(-1);
+ break;
+ }
+ if (n == RET_TOOSMALL)
+ {
+ errno = E2BIG;
+ res = (size_t)(-1);
+ break;
+ }
+ abort ();
+ }
+ else
+ {
+ inptr += m;
+ inleft -= m;
+ outptr += n;
+ outleft -= n;
+ }
+ }
+ }
+ *inbuf = inptr;
+ *inbytesleft = inleft;
+ *outbuf = outptr;
+ *outbytesleft = outleft;
+ return res;
+ }
+ }
+
+ {
+ int (*xxx_mbtowc) (ucs4_t *, const unsigned char *, size_t);
+
+ case (uintptr_t) _ICONV_UTF16BE_UTF8:
+ xxx_mbtowc = utf16be_mbtowc;
+ goto loop_to_utf8;
+ case (uintptr_t) _ICONV_UTF16LE_UTF8:
+ xxx_mbtowc = utf16le_mbtowc;
+ goto loop_to_utf8;
+ case (uintptr_t) _ICONV_UTF32BE_UTF8:
+ xxx_mbtowc = utf32be_mbtowc;
+ goto loop_to_utf8;
+ case (uintptr_t) _ICONV_UTF32LE_UTF8:
+ xxx_mbtowc = utf32le_mbtowc;
+ goto loop_to_utf8;
+
+ loop_to_utf8:
+ if (inbuf == NULL || *inbuf == NULL)
+ return 0;
+ {
+ ICONV_CONST char *inptr = *inbuf;
+ size_t inleft = *inbytesleft;
+ char *outptr = *outbuf;
+ size_t outleft = *outbytesleft;
+ size_t res = 0;
+ while (inleft > 0)
+ {
+ ucs4_t uc;
+ int m = xxx_mbtowc (&uc, (const uint8_t *) inptr, inleft);
+ if (m <= 0)
+ {
+ if (m == RET_ILSEQ)
+ {
+ errno = EILSEQ;
+ res = (size_t)(-1);
+ break;
+ }
+ if (m == RET_TOOFEW)
+ {
+ errno = EINVAL;
+ res = (size_t)(-1);
+ break;
+ }
+ abort ();
+ }
+ else
+ {
+ int n = u8_uctomb ((uint8_t *) outptr, uc, outleft);
+ if (n < 0)
+ {
+ if (n == -1)
+ {
+ errno = EILSEQ;
+ res = (size_t)(-1);
+ break;
+ }
+ if (n == -2)
+ {
+ errno = E2BIG;
+ res = (size_t)(-1);
+ break;
+ }
+ abort ();
+ }
+ else
+ {
+ inptr += m;
+ inleft -= m;
+ outptr += n;
+ outleft -= n;
+ }
+ }
+ }
+ *inbuf = inptr;
+ *inbytesleft = inleft;
+ *outbuf = outptr;
+ *outbytesleft = outleft;
+ return res;
+ }
+ }
+ }
+#endif
+ return iconv (cd, inbuf, inbytesleft, outbuf, outbytesleft);
+}
diff --git a/lib/iconv.in.h b/lib/iconv.in.h
new file mode 100644
index 0000000..cb1da14
--- /dev/null
+++ b/lib/iconv.in.h
@@ -0,0 +1,110 @@
+/* A GNU-like <iconv.h>.
+
+ Copyright (C) 2007-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _@GUARD_PREFIX@_ICONV_H
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+/* The include_next requires a split double-inclusion guard. */
+#@INCLUDE_NEXT@ @NEXT_ICONV_H@
+
+#ifndef _@GUARD_PREFIX@_ICONV_H
+#define _@GUARD_PREFIX@_ICONV_H
+
+/* The definitions of _GL_FUNCDECL_RPL etc. are copied here. */
+
+/* The definition of _GL_ARG_NONNULL is copied here. */
+
+/* The definition of _GL_WARN_ON_USE is copied here. */
+
+
+#if @GNULIB_ICONV@
+# if @REPLACE_ICONV_OPEN@
+/* An iconv_open wrapper that supports the IANA standardized encoding names
+ ("ISO-8859-1" etc.) as far as possible. */
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define iconv_open rpl_iconv_open
+# endif
+_GL_FUNCDECL_RPL (iconv_open, iconv_t,
+ (const char *tocode, const char *fromcode)
+ _GL_ARG_NONNULL ((1, 2)));
+_GL_CXXALIAS_RPL (iconv_open, iconv_t,
+ (const char *tocode, const char *fromcode));
+# else
+_GL_CXXALIAS_SYS (iconv_open, iconv_t,
+ (const char *tocode, const char *fromcode));
+# endif
+_GL_CXXALIASWARN (iconv_open);
+#endif
+
+#if @REPLACE_ICONV_UTF@
+/* Special constants for supporting UTF-{16,32}{BE,LE} encodings.
+ Not public. */
+# define _ICONV_UTF8_UTF16BE (iconv_t)(-161)
+# define _ICONV_UTF8_UTF16LE (iconv_t)(-162)
+# define _ICONV_UTF8_UTF32BE (iconv_t)(-163)
+# define _ICONV_UTF8_UTF32LE (iconv_t)(-164)
+# define _ICONV_UTF16BE_UTF8 (iconv_t)(-165)
+# define _ICONV_UTF16LE_UTF8 (iconv_t)(-166)
+# define _ICONV_UTF32BE_UTF8 (iconv_t)(-167)
+# define _ICONV_UTF32LE_UTF8 (iconv_t)(-168)
+#endif
+
+#if @GNULIB_ICONV@
+# if @REPLACE_ICONV@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define iconv rpl_iconv
+# endif
+_GL_FUNCDECL_RPL (iconv, size_t,
+ (iconv_t cd,
+ @ICONV_CONST@ char **inbuf, size_t *inbytesleft,
+ char **outbuf, size_t *outbytesleft));
+_GL_CXXALIAS_RPL (iconv, size_t,
+ (iconv_t cd,
+ @ICONV_CONST@ char **inbuf, size_t *inbytesleft,
+ char **outbuf, size_t *outbytesleft));
+# else
+_GL_CXXALIAS_SYS (iconv, size_t,
+ (iconv_t cd,
+ @ICONV_CONST@ char **inbuf, size_t *inbytesleft,
+ char **outbuf, size_t *outbytesleft));
+# endif
+_GL_CXXALIASWARN (iconv);
+# ifndef ICONV_CONST
+# define ICONV_CONST @ICONV_CONST@
+# endif
+#endif
+
+#if @GNULIB_ICONV@
+# if @REPLACE_ICONV@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define iconv_close rpl_iconv_close
+# endif
+_GL_FUNCDECL_RPL (iconv_close, int, (iconv_t cd));
+_GL_CXXALIAS_RPL (iconv_close, int, (iconv_t cd));
+# else
+_GL_CXXALIAS_SYS (iconv_close, int, (iconv_t cd));
+# endif
+_GL_CXXALIASWARN (iconv_close);
+#endif
+
+
+#endif /* _@GUARD_PREFIX@_ICONV_H */
+#endif /* _@GUARD_PREFIX@_ICONV_H */
diff --git a/lib/iconv_close.c b/lib/iconv_close.c
new file mode 100644
index 0000000..d1cd793
--- /dev/null
+++ b/lib/iconv_close.c
@@ -0,0 +1,46 @@
+/* Character set conversion.
+ Copyright (C) 2007, 2009-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <iconv.h>
+
+#include <stdint.h>
+#ifndef uintptr_t
+# define uintptr_t unsigned long
+#endif
+
+int
+rpl_iconv_close (iconv_t cd)
+#undef iconv_close
+{
+#if REPLACE_ICONV_UTF
+ switch ((uintptr_t) cd)
+ {
+ case (uintptr_t) _ICONV_UTF8_UTF16BE:
+ case (uintptr_t) _ICONV_UTF8_UTF16LE:
+ case (uintptr_t) _ICONV_UTF8_UTF32BE:
+ case (uintptr_t) _ICONV_UTF8_UTF32LE:
+ case (uintptr_t) _ICONV_UTF16BE_UTF8:
+ case (uintptr_t) _ICONV_UTF16LE_UTF8:
+ case (uintptr_t) _ICONV_UTF32BE_UTF8:
+ case (uintptr_t) _ICONV_UTF32LE_UTF8:
+ return 0;
+ }
+#endif
+ return iconv_close (cd);
+}
diff --git a/lib/iconv_open-aix.gperf b/lib/iconv_open-aix.gperf
new file mode 100644
index 0000000..6782b99
--- /dev/null
+++ b/lib/iconv_open-aix.gperf
@@ -0,0 +1,44 @@
+struct mapping { int standard_name; const char vendor_name[10 + 1]; };
+%struct-type
+%language=ANSI-C
+%define slot-name standard_name
+%define hash-function-name mapping_hash
+%define lookup-function-name mapping_lookup
+%readonly-tables
+%global-table
+%define word-array-name mappings
+%pic
+%%
+# On AIX 5.1, look in /usr/lib/nls/loc/uconvTable.
+ISO-8859-1, "ISO8859-1"
+ISO-8859-2, "ISO8859-2"
+ISO-8859-3, "ISO8859-3"
+ISO-8859-4, "ISO8859-4"
+ISO-8859-5, "ISO8859-5"
+ISO-8859-6, "ISO8859-6"
+ISO-8859-7, "ISO8859-7"
+ISO-8859-8, "ISO8859-8"
+ISO-8859-9, "ISO8859-9"
+ISO-8859-15, "ISO8859-15"
+CP437, "IBM-437"
+CP850, "IBM-850"
+CP852, "IBM-852"
+CP856, "IBM-856"
+CP857, "IBM-857"
+CP861, "IBM-861"
+CP865, "IBM-865"
+CP869, "IBM-869"
+ISO-8859-13, "IBM-921"
+CP922, "IBM-922"
+CP932, "IBM-932"
+CP943, "IBM-943"
+CP1046, "IBM-1046"
+CP1124, "IBM-1124"
+CP1125, "IBM-1125"
+CP1129, "IBM-1129"
+CP1252, "IBM-1252"
+GB2312, "IBM-eucCN"
+EUC-JP, "IBM-eucJP"
+EUC-KR, "IBM-eucKR"
+EUC-TW, "IBM-eucTW"
+BIG5, "big5"
diff --git a/lib/iconv_open-aix.h b/lib/iconv_open-aix.h
new file mode 100644
index 0000000..5318d88
--- /dev/null
+++ b/lib/iconv_open-aix.h
@@ -0,0 +1,256 @@
+/* ANSI-C code produced by gperf version 3.0.4 */
+/* Command-line: gperf -m 10 ./lib/iconv_open-aix.gperf */
+/* Computed positions: -k'4,$' */
+
+#if !((' ' == 32) && ('!' == 33) && ('"' == 34) && ('#' == 35) \
+ && ('%' == 37) && ('&' == 38) && ('\'' == 39) && ('(' == 40) \
+ && (')' == 41) && ('*' == 42) && ('+' == 43) && (',' == 44) \
+ && ('-' == 45) && ('.' == 46) && ('/' == 47) && ('0' == 48) \
+ && ('1' == 49) && ('2' == 50) && ('3' == 51) && ('4' == 52) \
+ && ('5' == 53) && ('6' == 54) && ('7' == 55) && ('8' == 56) \
+ && ('9' == 57) && (':' == 58) && (';' == 59) && ('<' == 60) \
+ && ('=' == 61) && ('>' == 62) && ('?' == 63) && ('A' == 65) \
+ && ('B' == 66) && ('C' == 67) && ('D' == 68) && ('E' == 69) \
+ && ('F' == 70) && ('G' == 71) && ('H' == 72) && ('I' == 73) \
+ && ('J' == 74) && ('K' == 75) && ('L' == 76) && ('M' == 77) \
+ && ('N' == 78) && ('O' == 79) && ('P' == 80) && ('Q' == 81) \
+ && ('R' == 82) && ('S' == 83) && ('T' == 84) && ('U' == 85) \
+ && ('V' == 86) && ('W' == 87) && ('X' == 88) && ('Y' == 89) \
+ && ('Z' == 90) && ('[' == 91) && ('\\' == 92) && (']' == 93) \
+ && ('^' == 94) && ('_' == 95) && ('a' == 97) && ('b' == 98) \
+ && ('c' == 99) && ('d' == 100) && ('e' == 101) && ('f' == 102) \
+ && ('g' == 103) && ('h' == 104) && ('i' == 105) && ('j' == 106) \
+ && ('k' == 107) && ('l' == 108) && ('m' == 109) && ('n' == 110) \
+ && ('o' == 111) && ('p' == 112) && ('q' == 113) && ('r' == 114) \
+ && ('s' == 115) && ('t' == 116) && ('u' == 117) && ('v' == 118) \
+ && ('w' == 119) && ('x' == 120) && ('y' == 121) && ('z' == 122) \
+ && ('{' == 123) && ('|' == 124) && ('}' == 125) && ('~' == 126))
+/* The character set is not based on ISO-646. */
+#error "gperf generated tables don't work with this execution character set. Please report a bug to <bug-gnu-gperf@gnu.org>."
+#endif
+
+#line 1 "./lib/iconv_open-aix.gperf"
+struct mapping { int standard_name; const char vendor_name[10 + 1]; };
+
+#define TOTAL_KEYWORDS 32
+#define MIN_WORD_LENGTH 4
+#define MAX_WORD_LENGTH 11
+#define MIN_HASH_VALUE 6
+#define MAX_HASH_VALUE 44
+/* maximum key range = 39, duplicates = 0 */
+
+#ifdef __GNUC__
+__inline
+#else
+#ifdef __cplusplus
+inline
+#endif
+#endif
+static unsigned int
+mapping_hash (register const char *str, register unsigned int len)
+{
+ static const unsigned char asso_values[] =
+ {
+ 45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
+ 45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
+ 45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
+ 45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
+ 45, 45, 45, 45, 45, 45, 45, 0, 4, 25,
+ 0, 11, 24, 9, 17, 3, 14, 21, 45, 45,
+ 45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
+ 45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
+ 3, 45, 1, 45, 45, 45, 45, 0, 45, 45,
+ 45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
+ 45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
+ 45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
+ 45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
+ 45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
+ 45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
+ 45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
+ 45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
+ 45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
+ 45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
+ 45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
+ 45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
+ 45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
+ 45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
+ 45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
+ 45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
+ 45, 45, 45, 45, 45, 45, 45, 45
+ };
+ return len + asso_values[(unsigned char)str[3]+2] + asso_values[(unsigned char)str[len - 1]];
+}
+
+struct stringpool_t
+ {
+ char stringpool_str6[sizeof("EUC-TW")];
+ char stringpool_str7[sizeof("EUC-KR")];
+ char stringpool_str8[sizeof("CP852")];
+ char stringpool_str9[sizeof("EUC-JP")];
+ char stringpool_str10[sizeof("ISO-8859-2")];
+ char stringpool_str11[sizeof("CP857")];
+ char stringpool_str12[sizeof("CP850")];
+ char stringpool_str13[sizeof("ISO-8859-7")];
+ char stringpool_str14[sizeof("CP932")];
+ char stringpool_str15[sizeof("GB2312")];
+ char stringpool_str16[sizeof("BIG5")];
+ char stringpool_str17[sizeof("CP437")];
+ char stringpool_str19[sizeof("ISO-8859-5")];
+ char stringpool_str20[sizeof("ISO-8859-15")];
+ char stringpool_str21[sizeof("ISO-8859-3")];
+ char stringpool_str22[sizeof("ISO-8859-13")];
+ char stringpool_str23[sizeof("CP1046")];
+ char stringpool_str24[sizeof("ISO-8859-8")];
+ char stringpool_str25[sizeof("CP856")];
+ char stringpool_str26[sizeof("CP1125")];
+ char stringpool_str27[sizeof("ISO-8859-6")];
+ char stringpool_str28[sizeof("CP865")];
+ char stringpool_str29[sizeof("CP922")];
+ char stringpool_str30[sizeof("CP1252")];
+ char stringpool_str31[sizeof("ISO-8859-9")];
+ char stringpool_str33[sizeof("CP943")];
+ char stringpool_str34[sizeof("ISO-8859-4")];
+ char stringpool_str35[sizeof("ISO-8859-1")];
+ char stringpool_str38[sizeof("CP1129")];
+ char stringpool_str40[sizeof("CP869")];
+ char stringpool_str41[sizeof("CP1124")];
+ char stringpool_str44[sizeof("CP861")];
+ };
+static const struct stringpool_t stringpool_contents =
+ {
+ "EUC-TW",
+ "EUC-KR",
+ "CP852",
+ "EUC-JP",
+ "ISO-8859-2",
+ "CP857",
+ "CP850",
+ "ISO-8859-7",
+ "CP932",
+ "GB2312",
+ "BIG5",
+ "CP437",
+ "ISO-8859-5",
+ "ISO-8859-15",
+ "ISO-8859-3",
+ "ISO-8859-13",
+ "CP1046",
+ "ISO-8859-8",
+ "CP856",
+ "CP1125",
+ "ISO-8859-6",
+ "CP865",
+ "CP922",
+ "CP1252",
+ "ISO-8859-9",
+ "CP943",
+ "ISO-8859-4",
+ "ISO-8859-1",
+ "CP1129",
+ "CP869",
+ "CP1124",
+ "CP861"
+ };
+#define stringpool ((const char *) &stringpool_contents)
+
+static const struct mapping mappings[] =
+ {
+ {-1}, {-1}, {-1}, {-1}, {-1}, {-1},
+#line 43 "./lib/iconv_open-aix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str6, "IBM-eucTW"},
+#line 42 "./lib/iconv_open-aix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str7, "IBM-eucKR"},
+#line 25 "./lib/iconv_open-aix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str8, "IBM-852"},
+#line 41 "./lib/iconv_open-aix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str9, "IBM-eucJP"},
+#line 14 "./lib/iconv_open-aix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str10, "ISO8859-2"},
+#line 27 "./lib/iconv_open-aix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str11, "IBM-857"},
+#line 24 "./lib/iconv_open-aix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str12, "IBM-850"},
+#line 19 "./lib/iconv_open-aix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str13, "ISO8859-7"},
+#line 33 "./lib/iconv_open-aix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str14, "IBM-932"},
+#line 40 "./lib/iconv_open-aix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str15, "IBM-eucCN"},
+#line 44 "./lib/iconv_open-aix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str16, "big5"},
+#line 23 "./lib/iconv_open-aix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str17, "IBM-437"},
+ {-1},
+#line 17 "./lib/iconv_open-aix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str19, "ISO8859-5"},
+#line 22 "./lib/iconv_open-aix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str20, "ISO8859-15"},
+#line 15 "./lib/iconv_open-aix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str21, "ISO8859-3"},
+#line 31 "./lib/iconv_open-aix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str22, "IBM-921"},
+#line 35 "./lib/iconv_open-aix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str23, "IBM-1046"},
+#line 20 "./lib/iconv_open-aix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str24, "ISO8859-8"},
+#line 26 "./lib/iconv_open-aix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str25, "IBM-856"},
+#line 37 "./lib/iconv_open-aix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str26, "IBM-1125"},
+#line 18 "./lib/iconv_open-aix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str27, "ISO8859-6"},
+#line 29 "./lib/iconv_open-aix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str28, "IBM-865"},
+#line 32 "./lib/iconv_open-aix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str29, "IBM-922"},
+#line 39 "./lib/iconv_open-aix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str30, "IBM-1252"},
+#line 21 "./lib/iconv_open-aix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str31, "ISO8859-9"},
+ {-1},
+#line 34 "./lib/iconv_open-aix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str33, "IBM-943"},
+#line 16 "./lib/iconv_open-aix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str34, "ISO8859-4"},
+#line 13 "./lib/iconv_open-aix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str35, "ISO8859-1"},
+ {-1}, {-1},
+#line 38 "./lib/iconv_open-aix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str38, "IBM-1129"},
+ {-1},
+#line 30 "./lib/iconv_open-aix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str40, "IBM-869"},
+#line 36 "./lib/iconv_open-aix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str41, "IBM-1124"},
+ {-1}, {-1},
+#line 28 "./lib/iconv_open-aix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str44, "IBM-861"}
+ };
+
+#ifdef __GNUC__
+__inline
+#if defined __GNUC_STDC_INLINE__ || defined __GNUC_GNU_INLINE__
+__attribute__ ((__gnu_inline__))
+#endif
+#endif
+const struct mapping *
+mapping_lookup (register const char *str, register unsigned int len)
+{
+ if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH)
+ {
+ register int key = mapping_hash (str, len);
+
+ if (key <= MAX_HASH_VALUE && key >= 0)
+ {
+ register int o = mappings[key].standard_name;
+ if (o >= 0)
+ {
+ register const char *s = o + stringpool;
+
+ if (*str == *s && !strcmp (str + 1, s + 1))
+ return &mappings[key];
+ }
+ }
+ }
+ return 0;
+}
diff --git a/lib/iconv_open-hpux.gperf b/lib/iconv_open-hpux.gperf
new file mode 100644
index 0000000..5a35c83
--- /dev/null
+++ b/lib/iconv_open-hpux.gperf
@@ -0,0 +1,56 @@
+struct mapping { int standard_name; const char vendor_name[9 + 1]; };
+%struct-type
+%language=ANSI-C
+%define slot-name standard_name
+%define hash-function-name mapping_hash
+%define lookup-function-name mapping_lookup
+%readonly-tables
+%global-table
+%define word-array-name mappings
+%pic
+%%
+# On HP-UX 11.11, look in /usr/lib/nls/iconv.
+ISO-8859-1, "iso88591"
+ISO-8859-2, "iso88592"
+ISO-8859-5, "iso88595"
+ISO-8859-6, "iso88596"
+ISO-8859-7, "iso88597"
+ISO-8859-8, "iso88598"
+ISO-8859-9, "iso88599"
+ISO-8859-15, "iso885915"
+CP437, "cp437"
+CP775, "cp775"
+CP850, "cp850"
+CP852, "cp852"
+CP855, "cp855"
+CP857, "cp857"
+CP861, "cp861"
+CP862, "cp862"
+CP864, "cp864"
+CP865, "cp865"
+CP866, "cp866"
+CP869, "cp869"
+CP874, "cp874"
+CP1250, "cp1250"
+CP1251, "cp1251"
+CP1252, "cp1252"
+CP1253, "cp1253"
+CP1254, "cp1254"
+CP1255, "cp1255"
+CP1256, "cp1256"
+CP1257, "cp1257"
+CP1258, "cp1258"
+HP-ROMAN8, "roman8"
+HP-ARABIC8, "arabic8"
+HP-GREEK8, "greek8"
+HP-HEBREW8, "hebrew8"
+HP-TURKISH8, "turkish8"
+HP-KANA8, "kana8"
+TIS-620, "tis620"
+GB2312, "hp15CN"
+EUC-JP, "eucJP"
+EUC-KR, "eucKR"
+EUC-TW, "eucTW"
+BIG5, "big5"
+SHIFT_JIS, "sjis"
+UTF-8, "utf8"
diff --git a/lib/iconv_open-hpux.h b/lib/iconv_open-hpux.h
new file mode 100644
index 0000000..49e295a
--- /dev/null
+++ b/lib/iconv_open-hpux.h
@@ -0,0 +1,299 @@
+/* ANSI-C code produced by gperf version 3.0.4 */
+/* Command-line: gperf -m 10 ./lib/iconv_open-hpux.gperf */
+/* Computed positions: -k'4,$' */
+
+#if !((' ' == 32) && ('!' == 33) && ('"' == 34) && ('#' == 35) \
+ && ('%' == 37) && ('&' == 38) && ('\'' == 39) && ('(' == 40) \
+ && (')' == 41) && ('*' == 42) && ('+' == 43) && (',' == 44) \
+ && ('-' == 45) && ('.' == 46) && ('/' == 47) && ('0' == 48) \
+ && ('1' == 49) && ('2' == 50) && ('3' == 51) && ('4' == 52) \
+ && ('5' == 53) && ('6' == 54) && ('7' == 55) && ('8' == 56) \
+ && ('9' == 57) && (':' == 58) && (';' == 59) && ('<' == 60) \
+ && ('=' == 61) && ('>' == 62) && ('?' == 63) && ('A' == 65) \
+ && ('B' == 66) && ('C' == 67) && ('D' == 68) && ('E' == 69) \
+ && ('F' == 70) && ('G' == 71) && ('H' == 72) && ('I' == 73) \
+ && ('J' == 74) && ('K' == 75) && ('L' == 76) && ('M' == 77) \
+ && ('N' == 78) && ('O' == 79) && ('P' == 80) && ('Q' == 81) \
+ && ('R' == 82) && ('S' == 83) && ('T' == 84) && ('U' == 85) \
+ && ('V' == 86) && ('W' == 87) && ('X' == 88) && ('Y' == 89) \
+ && ('Z' == 90) && ('[' == 91) && ('\\' == 92) && (']' == 93) \
+ && ('^' == 94) && ('_' == 95) && ('a' == 97) && ('b' == 98) \
+ && ('c' == 99) && ('d' == 100) && ('e' == 101) && ('f' == 102) \
+ && ('g' == 103) && ('h' == 104) && ('i' == 105) && ('j' == 106) \
+ && ('k' == 107) && ('l' == 108) && ('m' == 109) && ('n' == 110) \
+ && ('o' == 111) && ('p' == 112) && ('q' == 113) && ('r' == 114) \
+ && ('s' == 115) && ('t' == 116) && ('u' == 117) && ('v' == 118) \
+ && ('w' == 119) && ('x' == 120) && ('y' == 121) && ('z' == 122) \
+ && ('{' == 123) && ('|' == 124) && ('}' == 125) && ('~' == 126))
+/* The character set is not based on ISO-646. */
+#error "gperf generated tables don't work with this execution character set. Please report a bug to <bug-gnu-gperf@gnu.org>."
+#endif
+
+#line 1 "./lib/iconv_open-hpux.gperf"
+struct mapping { int standard_name; const char vendor_name[9 + 1]; };
+
+#define TOTAL_KEYWORDS 44
+#define MIN_WORD_LENGTH 4
+#define MAX_WORD_LENGTH 11
+#define MIN_HASH_VALUE 6
+#define MAX_HASH_VALUE 49
+/* maximum key range = 44, duplicates = 0 */
+
+#ifdef __GNUC__
+__inline
+#else
+#ifdef __cplusplus
+inline
+#endif
+#endif
+static unsigned int
+mapping_hash (register const char *str, register unsigned int len)
+{
+ static const unsigned char asso_values[] =
+ {
+ 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
+ 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
+ 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
+ 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
+ 50, 50, 50, 50, 50, 50, 50, 50, 1, 2,
+ 24, 43, 5, 10, 0, 13, 32, 3, 19, 18,
+ 50, 50, 50, 50, 50, 50, 50, 50, 50, 5,
+ 50, 50, 50, 50, 14, 5, 0, 50, 50, 0,
+ 27, 50, 12, 14, 50, 50, 0, 5, 2, 50,
+ 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
+ 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
+ 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
+ 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
+ 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
+ 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
+ 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
+ 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
+ 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
+ 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
+ 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
+ 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
+ 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
+ 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
+ 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
+ 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
+ 50, 50, 50, 50, 50, 50, 50, 50, 50, 50
+ };
+ return len + asso_values[(unsigned char)str[3]+4] + asso_values[(unsigned char)str[len - 1]];
+}
+
+struct stringpool_t
+ {
+ char stringpool_str6[sizeof("CP1256")];
+ char stringpool_str7[sizeof("CP1250")];
+ char stringpool_str8[sizeof("CP1251")];
+ char stringpool_str9[sizeof("CP850")];
+ char stringpool_str10[sizeof("TIS-620")];
+ char stringpool_str11[sizeof("CP1254")];
+ char stringpool_str12[sizeof("ISO-8859-6")];
+ char stringpool_str13[sizeof("EUC-TW")];
+ char stringpool_str14[sizeof("ISO-8859-1")];
+ char stringpool_str15[sizeof("ISO-8859-9")];
+ char stringpool_str16[sizeof("CP1255")];
+ char stringpool_str17[sizeof("BIG5")];
+ char stringpool_str18[sizeof("CP855")];
+ char stringpool_str19[sizeof("CP1257")];
+ char stringpool_str20[sizeof("EUC-KR")];
+ char stringpool_str21[sizeof("CP857")];
+ char stringpool_str22[sizeof("ISO-8859-5")];
+ char stringpool_str23[sizeof("ISO-8859-15")];
+ char stringpool_str24[sizeof("CP866")];
+ char stringpool_str25[sizeof("ISO-8859-7")];
+ char stringpool_str26[sizeof("CP861")];
+ char stringpool_str27[sizeof("CP869")];
+ char stringpool_str28[sizeof("CP874")];
+ char stringpool_str29[sizeof("CP864")];
+ char stringpool_str30[sizeof("CP1252")];
+ char stringpool_str31[sizeof("CP437")];
+ char stringpool_str32[sizeof("CP852")];
+ char stringpool_str33[sizeof("CP775")];
+ char stringpool_str34[sizeof("CP865")];
+ char stringpool_str35[sizeof("EUC-JP")];
+ char stringpool_str36[sizeof("ISO-8859-2")];
+ char stringpool_str37[sizeof("SHIFT_JIS")];
+ char stringpool_str38[sizeof("CP1258")];
+ char stringpool_str39[sizeof("UTF-8")];
+ char stringpool_str40[sizeof("HP-KANA8")];
+ char stringpool_str41[sizeof("HP-ROMAN8")];
+ char stringpool_str42[sizeof("HP-HEBREW8")];
+ char stringpool_str43[sizeof("GB2312")];
+ char stringpool_str44[sizeof("ISO-8859-8")];
+ char stringpool_str45[sizeof("HP-TURKISH8")];
+ char stringpool_str46[sizeof("HP-GREEK8")];
+ char stringpool_str47[sizeof("HP-ARABIC8")];
+ char stringpool_str48[sizeof("CP862")];
+ char stringpool_str49[sizeof("CP1253")];
+ };
+static const struct stringpool_t stringpool_contents =
+ {
+ "CP1256",
+ "CP1250",
+ "CP1251",
+ "CP850",
+ "TIS-620",
+ "CP1254",
+ "ISO-8859-6",
+ "EUC-TW",
+ "ISO-8859-1",
+ "ISO-8859-9",
+ "CP1255",
+ "BIG5",
+ "CP855",
+ "CP1257",
+ "EUC-KR",
+ "CP857",
+ "ISO-8859-5",
+ "ISO-8859-15",
+ "CP866",
+ "ISO-8859-7",
+ "CP861",
+ "CP869",
+ "CP874",
+ "CP864",
+ "CP1252",
+ "CP437",
+ "CP852",
+ "CP775",
+ "CP865",
+ "EUC-JP",
+ "ISO-8859-2",
+ "SHIFT_JIS",
+ "CP1258",
+ "UTF-8",
+ "HP-KANA8",
+ "HP-ROMAN8",
+ "HP-HEBREW8",
+ "GB2312",
+ "ISO-8859-8",
+ "HP-TURKISH8",
+ "HP-GREEK8",
+ "HP-ARABIC8",
+ "CP862",
+ "CP1253"
+ };
+#define stringpool ((const char *) &stringpool_contents)
+
+static const struct mapping mappings[] =
+ {
+ {-1}, {-1}, {-1}, {-1}, {-1}, {-1},
+#line 40 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str6, "cp1256"},
+#line 34 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str7, "cp1250"},
+#line 35 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str8, "cp1251"},
+#line 23 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str9, "cp850"},
+#line 49 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str10, "tis620"},
+#line 38 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str11, "cp1254"},
+#line 16 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str12, "iso88596"},
+#line 53 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str13, "eucTW"},
+#line 13 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str14, "iso88591"},
+#line 19 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str15, "iso88599"},
+#line 39 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str16, "cp1255"},
+#line 54 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str17, "big5"},
+#line 25 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str18, "cp855"},
+#line 41 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str19, "cp1257"},
+#line 52 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str20, "eucKR"},
+#line 26 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str21, "cp857"},
+#line 15 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str22, "iso88595"},
+#line 20 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str23, "iso885915"},
+#line 31 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str24, "cp866"},
+#line 17 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str25, "iso88597"},
+#line 27 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str26, "cp861"},
+#line 32 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str27, "cp869"},
+#line 33 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str28, "cp874"},
+#line 29 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str29, "cp864"},
+#line 36 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str30, "cp1252"},
+#line 21 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str31, "cp437"},
+#line 24 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str32, "cp852"},
+#line 22 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str33, "cp775"},
+#line 30 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str34, "cp865"},
+#line 51 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str35, "eucJP"},
+#line 14 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str36, "iso88592"},
+#line 55 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str37, "sjis"},
+#line 42 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str38, "cp1258"},
+#line 56 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str39, "utf8"},
+#line 48 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str40, "kana8"},
+#line 43 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str41, "roman8"},
+#line 46 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str42, "hebrew8"},
+#line 50 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str43, "hp15CN"},
+#line 18 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str44, "iso88598"},
+#line 47 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str45, "turkish8"},
+#line 45 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str46, "greek8"},
+#line 44 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str47, "arabic8"},
+#line 28 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str48, "cp862"},
+#line 37 "./lib/iconv_open-hpux.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str49, "cp1253"}
+ };
+
+#ifdef __GNUC__
+__inline
+#if defined __GNUC_STDC_INLINE__ || defined __GNUC_GNU_INLINE__
+__attribute__ ((__gnu_inline__))
+#endif
+#endif
+const struct mapping *
+mapping_lookup (register const char *str, register unsigned int len)
+{
+ if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH)
+ {
+ register int key = mapping_hash (str, len);
+
+ if (key <= MAX_HASH_VALUE && key >= 0)
+ {
+ register int o = mappings[key].standard_name;
+ if (o >= 0)
+ {
+ register const char *s = o + stringpool;
+
+ if (*str == *s && !strcmp (str + 1, s + 1))
+ return &mappings[key];
+ }
+ }
+ }
+ return 0;
+}
diff --git a/lib/iconv_open-irix.gperf b/lib/iconv_open-irix.gperf
new file mode 100644
index 0000000..3672a80
--- /dev/null
+++ b/lib/iconv_open-irix.gperf
@@ -0,0 +1,31 @@
+struct mapping { int standard_name; const char vendor_name[10 + 1]; };
+%struct-type
+%language=ANSI-C
+%define slot-name standard_name
+%define hash-function-name mapping_hash
+%define lookup-function-name mapping_lookup
+%readonly-tables
+%global-table
+%define word-array-name mappings
+%pic
+%%
+# On IRIX 6.5, look in /usr/lib/iconv and /usr/lib/international/encodings.
+ISO-8859-1, "ISO8859-1"
+ISO-8859-2, "ISO8859-2"
+ISO-8859-3, "ISO8859-3"
+ISO-8859-4, "ISO8859-4"
+ISO-8859-5, "ISO8859-5"
+ISO-8859-6, "ISO8859-6"
+ISO-8859-7, "ISO8859-7"
+ISO-8859-8, "ISO8859-8"
+ISO-8859-9, "ISO8859-9"
+ISO-8859-15, "ISO8859-15"
+KOI8-R, "KOI8"
+CP855, "DOS855"
+CP1251, "WIN1251"
+GB2312, "eucCN"
+EUC-JP, "eucJP"
+EUC-KR, "eucKR"
+EUC-TW, "eucTW"
+SHIFT_JIS, "sjis"
+TIS-620, "TIS620"
diff --git a/lib/iconv_open-irix.h b/lib/iconv_open-irix.h
new file mode 100644
index 0000000..9b78379
--- /dev/null
+++ b/lib/iconv_open-irix.h
@@ -0,0 +1,199 @@
+/* ANSI-C code produced by gperf version 3.0.4 */
+/* Command-line: gperf -m 10 ./lib/iconv_open-irix.gperf */
+/* Computed positions: -k'1,$' */
+
+#if !((' ' == 32) && ('!' == 33) && ('"' == 34) && ('#' == 35) \
+ && ('%' == 37) && ('&' == 38) && ('\'' == 39) && ('(' == 40) \
+ && (')' == 41) && ('*' == 42) && ('+' == 43) && (',' == 44) \
+ && ('-' == 45) && ('.' == 46) && ('/' == 47) && ('0' == 48) \
+ && ('1' == 49) && ('2' == 50) && ('3' == 51) && ('4' == 52) \
+ && ('5' == 53) && ('6' == 54) && ('7' == 55) && ('8' == 56) \
+ && ('9' == 57) && (':' == 58) && (';' == 59) && ('<' == 60) \
+ && ('=' == 61) && ('>' == 62) && ('?' == 63) && ('A' == 65) \
+ && ('B' == 66) && ('C' == 67) && ('D' == 68) && ('E' == 69) \
+ && ('F' == 70) && ('G' == 71) && ('H' == 72) && ('I' == 73) \
+ && ('J' == 74) && ('K' == 75) && ('L' == 76) && ('M' == 77) \
+ && ('N' == 78) && ('O' == 79) && ('P' == 80) && ('Q' == 81) \
+ && ('R' == 82) && ('S' == 83) && ('T' == 84) && ('U' == 85) \
+ && ('V' == 86) && ('W' == 87) && ('X' == 88) && ('Y' == 89) \
+ && ('Z' == 90) && ('[' == 91) && ('\\' == 92) && (']' == 93) \
+ && ('^' == 94) && ('_' == 95) && ('a' == 97) && ('b' == 98) \
+ && ('c' == 99) && ('d' == 100) && ('e' == 101) && ('f' == 102) \
+ && ('g' == 103) && ('h' == 104) && ('i' == 105) && ('j' == 106) \
+ && ('k' == 107) && ('l' == 108) && ('m' == 109) && ('n' == 110) \
+ && ('o' == 111) && ('p' == 112) && ('q' == 113) && ('r' == 114) \
+ && ('s' == 115) && ('t' == 116) && ('u' == 117) && ('v' == 118) \
+ && ('w' == 119) && ('x' == 120) && ('y' == 121) && ('z' == 122) \
+ && ('{' == 123) && ('|' == 124) && ('}' == 125) && ('~' == 126))
+/* The character set is not based on ISO-646. */
+#error "gperf generated tables don't work with this execution character set. Please report a bug to <bug-gnu-gperf@gnu.org>."
+#endif
+
+#line 1 "./lib/iconv_open-irix.gperf"
+struct mapping { int standard_name; const char vendor_name[10 + 1]; };
+
+#define TOTAL_KEYWORDS 19
+#define MIN_WORD_LENGTH 5
+#define MAX_WORD_LENGTH 11
+#define MIN_HASH_VALUE 5
+#define MAX_HASH_VALUE 23
+/* maximum key range = 19, duplicates = 0 */
+
+#ifdef __GNUC__
+__inline
+#else
+#ifdef __cplusplus
+inline
+#endif
+#endif
+static unsigned int
+mapping_hash (register const char *str, register unsigned int len)
+{
+ static const unsigned char asso_values[] =
+ {
+ 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+ 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+ 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+ 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+ 24, 24, 24, 24, 24, 24, 24, 24, 8, 2,
+ 5, 12, 11, 0, 10, 9, 8, 7, 24, 24,
+ 24, 24, 24, 24, 24, 24, 24, 0, 24, 0,
+ 24, 5, 24, 0, 24, 7, 24, 24, 24, 24,
+ 7, 24, 1, 0, 8, 24, 24, 0, 24, 24,
+ 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+ 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+ 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+ 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+ 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+ 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+ 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+ 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+ 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+ 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+ 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+ 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+ 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+ 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+ 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+ 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+ 24, 24, 24, 24, 24, 24
+ };
+ return len + asso_values[(unsigned char)str[len - 1]] + asso_values[(unsigned char)str[0]];
+}
+
+struct stringpool_t
+ {
+ char stringpool_str5[sizeof("CP855")];
+ char stringpool_str6[sizeof("EUC-TW")];
+ char stringpool_str7[sizeof("EUC-KR")];
+ char stringpool_str8[sizeof("CP1251")];
+ char stringpool_str9[sizeof("SHIFT_JIS")];
+ char stringpool_str10[sizeof("ISO-8859-5")];
+ char stringpool_str11[sizeof("ISO-8859-15")];
+ char stringpool_str12[sizeof("ISO-8859-1")];
+ char stringpool_str13[sizeof("EUC-JP")];
+ char stringpool_str14[sizeof("KOI8-R")];
+ char stringpool_str15[sizeof("ISO-8859-2")];
+ char stringpool_str16[sizeof("GB2312")];
+ char stringpool_str17[sizeof("ISO-8859-9")];
+ char stringpool_str18[sizeof("ISO-8859-8")];
+ char stringpool_str19[sizeof("ISO-8859-7")];
+ char stringpool_str20[sizeof("ISO-8859-6")];
+ char stringpool_str21[sizeof("ISO-8859-4")];
+ char stringpool_str22[sizeof("ISO-8859-3")];
+ char stringpool_str23[sizeof("TIS-620")];
+ };
+static const struct stringpool_t stringpool_contents =
+ {
+ "CP855",
+ "EUC-TW",
+ "EUC-KR",
+ "CP1251",
+ "SHIFT_JIS",
+ "ISO-8859-5",
+ "ISO-8859-15",
+ "ISO-8859-1",
+ "EUC-JP",
+ "KOI8-R",
+ "ISO-8859-2",
+ "GB2312",
+ "ISO-8859-9",
+ "ISO-8859-8",
+ "ISO-8859-7",
+ "ISO-8859-6",
+ "ISO-8859-4",
+ "ISO-8859-3",
+ "TIS-620"
+ };
+#define stringpool ((const char *) &stringpool_contents)
+
+static const struct mapping mappings[] =
+ {
+ {-1}, {-1}, {-1}, {-1}, {-1},
+#line 24 "./lib/iconv_open-irix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str5, "DOS855"},
+#line 29 "./lib/iconv_open-irix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str6, "eucTW"},
+#line 28 "./lib/iconv_open-irix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str7, "eucKR"},
+#line 25 "./lib/iconv_open-irix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str8, "WIN1251"},
+#line 30 "./lib/iconv_open-irix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str9, "sjis"},
+#line 17 "./lib/iconv_open-irix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str10, "ISO8859-5"},
+#line 22 "./lib/iconv_open-irix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str11, "ISO8859-15"},
+#line 13 "./lib/iconv_open-irix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str12, "ISO8859-1"},
+#line 27 "./lib/iconv_open-irix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str13, "eucJP"},
+#line 23 "./lib/iconv_open-irix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str14, "KOI8"},
+#line 14 "./lib/iconv_open-irix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str15, "ISO8859-2"},
+#line 26 "./lib/iconv_open-irix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str16, "eucCN"},
+#line 21 "./lib/iconv_open-irix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str17, "ISO8859-9"},
+#line 20 "./lib/iconv_open-irix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str18, "ISO8859-8"},
+#line 19 "./lib/iconv_open-irix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str19, "ISO8859-7"},
+#line 18 "./lib/iconv_open-irix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str20, "ISO8859-6"},
+#line 16 "./lib/iconv_open-irix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str21, "ISO8859-4"},
+#line 15 "./lib/iconv_open-irix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str22, "ISO8859-3"},
+#line 31 "./lib/iconv_open-irix.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str23, "TIS620"}
+ };
+
+#ifdef __GNUC__
+__inline
+#if defined __GNUC_STDC_INLINE__ || defined __GNUC_GNU_INLINE__
+__attribute__ ((__gnu_inline__))
+#endif
+#endif
+const struct mapping *
+mapping_lookup (register const char *str, register unsigned int len)
+{
+ if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH)
+ {
+ register int key = mapping_hash (str, len);
+
+ if (key <= MAX_HASH_VALUE && key >= 0)
+ {
+ register int o = mappings[key].standard_name;
+ if (o >= 0)
+ {
+ register const char *s = o + stringpool;
+
+ if (*str == *s && !strcmp (str + 1, s + 1))
+ return &mappings[key];
+ }
+ }
+ }
+ return 0;
+}
diff --git a/lib/iconv_open-osf.gperf b/lib/iconv_open-osf.gperf
new file mode 100644
index 0000000..f468ff6
--- /dev/null
+++ b/lib/iconv_open-osf.gperf
@@ -0,0 +1,50 @@
+struct mapping { int standard_name; const char vendor_name[10 + 1]; };
+%struct-type
+%language=ANSI-C
+%define slot-name standard_name
+%define hash-function-name mapping_hash
+%define lookup-function-name mapping_lookup
+%readonly-tables
+%global-table
+%define word-array-name mappings
+%pic
+%%
+# On OSF/1 5.1, look in /usr/lib/nls/loc/iconv.
+ISO-8859-1, "ISO8859-1"
+ISO-8859-2, "ISO8859-2"
+ISO-8859-3, "ISO8859-3"
+ISO-8859-4, "ISO8859-4"
+ISO-8859-5, "ISO8859-5"
+ISO-8859-6, "ISO8859-6"
+ISO-8859-7, "ISO8859-7"
+ISO-8859-8, "ISO8859-8"
+ISO-8859-9, "ISO8859-9"
+ISO-8859-15, "ISO8859-15"
+CP437, "cp437"
+CP775, "cp775"
+CP850, "cp850"
+CP852, "cp852"
+CP855, "cp855"
+CP857, "cp857"
+CP861, "cp861"
+CP862, "cp862"
+CP865, "cp865"
+CP866, "cp866"
+CP869, "cp869"
+CP874, "cp874"
+CP949, "KSC5601"
+CP1250, "cp1250"
+CP1251, "cp1251"
+CP1252, "cp1252"
+CP1253, "cp1253"
+CP1254, "cp1254"
+CP1255, "cp1255"
+CP1256, "cp1256"
+CP1257, "cp1257"
+CP1258, "cp1258"
+EUC-JP, "eucJP"
+EUC-KR, "eucKR"
+EUC-TW, "eucTW"
+BIG5, "big5"
+SHIFT_JIS, "SJIS"
+TIS-620, "TACTIS"
diff --git a/lib/iconv_open-osf.h b/lib/iconv_open-osf.h
new file mode 100644
index 0000000..955fe72
--- /dev/null
+++ b/lib/iconv_open-osf.h
@@ -0,0 +1,278 @@
+/* ANSI-C code produced by gperf version 3.0.4 */
+/* Command-line: gperf -m 10 ./lib/iconv_open-osf.gperf */
+/* Computed positions: -k'4,$' */
+
+#if !((' ' == 32) && ('!' == 33) && ('"' == 34) && ('#' == 35) \
+ && ('%' == 37) && ('&' == 38) && ('\'' == 39) && ('(' == 40) \
+ && (')' == 41) && ('*' == 42) && ('+' == 43) && (',' == 44) \
+ && ('-' == 45) && ('.' == 46) && ('/' == 47) && ('0' == 48) \
+ && ('1' == 49) && ('2' == 50) && ('3' == 51) && ('4' == 52) \
+ && ('5' == 53) && ('6' == 54) && ('7' == 55) && ('8' == 56) \
+ && ('9' == 57) && (':' == 58) && (';' == 59) && ('<' == 60) \
+ && ('=' == 61) && ('>' == 62) && ('?' == 63) && ('A' == 65) \
+ && ('B' == 66) && ('C' == 67) && ('D' == 68) && ('E' == 69) \
+ && ('F' == 70) && ('G' == 71) && ('H' == 72) && ('I' == 73) \
+ && ('J' == 74) && ('K' == 75) && ('L' == 76) && ('M' == 77) \
+ && ('N' == 78) && ('O' == 79) && ('P' == 80) && ('Q' == 81) \
+ && ('R' == 82) && ('S' == 83) && ('T' == 84) && ('U' == 85) \
+ && ('V' == 86) && ('W' == 87) && ('X' == 88) && ('Y' == 89) \
+ && ('Z' == 90) && ('[' == 91) && ('\\' == 92) && (']' == 93) \
+ && ('^' == 94) && ('_' == 95) && ('a' == 97) && ('b' == 98) \
+ && ('c' == 99) && ('d' == 100) && ('e' == 101) && ('f' == 102) \
+ && ('g' == 103) && ('h' == 104) && ('i' == 105) && ('j' == 106) \
+ && ('k' == 107) && ('l' == 108) && ('m' == 109) && ('n' == 110) \
+ && ('o' == 111) && ('p' == 112) && ('q' == 113) && ('r' == 114) \
+ && ('s' == 115) && ('t' == 116) && ('u' == 117) && ('v' == 118) \
+ && ('w' == 119) && ('x' == 120) && ('y' == 121) && ('z' == 122) \
+ && ('{' == 123) && ('|' == 124) && ('}' == 125) && ('~' == 126))
+/* The character set is not based on ISO-646. */
+#error "gperf generated tables don't work with this execution character set. Please report a bug to <bug-gnu-gperf@gnu.org>."
+#endif
+
+#line 1 "./lib/iconv_open-osf.gperf"
+struct mapping { int standard_name; const char vendor_name[10 + 1]; };
+
+#define TOTAL_KEYWORDS 38
+#define MIN_WORD_LENGTH 4
+#define MAX_WORD_LENGTH 11
+#define MIN_HASH_VALUE 6
+#define MAX_HASH_VALUE 47
+/* maximum key range = 42, duplicates = 0 */
+
+#ifdef __GNUC__
+__inline
+#else
+#ifdef __cplusplus
+inline
+#endif
+#endif
+static unsigned int
+mapping_hash (register const char *str, register unsigned int len)
+{
+ static const unsigned char asso_values[] =
+ {
+ 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+ 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+ 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+ 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+ 48, 48, 48, 48, 48, 48, 48, 48, 2, 29,
+ 24, 34, 31, 0, 15, 14, 10, 13, 2, 48,
+ 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+ 48, 48, 48, 7, 48, 48, 48, 48, 48, 48,
+ 11, 48, 2, 7, 48, 48, 48, 1, 48, 48,
+ 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+ 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+ 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+ 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+ 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+ 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+ 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+ 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+ 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+ 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+ 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+ 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+ 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+ 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+ 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+ 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+ 48, 48, 48, 48, 48, 48, 48, 48, 48
+ };
+ return len + asso_values[(unsigned char)str[3]+3] + asso_values[(unsigned char)str[len - 1]];
+}
+
+struct stringpool_t
+ {
+ char stringpool_str6[sizeof("CP1255")];
+ char stringpool_str7[sizeof("CP775")];
+ char stringpool_str8[sizeof("CP1250")];
+ char stringpool_str9[sizeof("EUC-TW")];
+ char stringpool_str10[sizeof("EUC-KR")];
+ char stringpool_str11[sizeof("TIS-620")];
+ char stringpool_str12[sizeof("ISO-8859-5")];
+ char stringpool_str13[sizeof("ISO-8859-15")];
+ char stringpool_str14[sizeof("BIG5")];
+ char stringpool_str15[sizeof("CP855")];
+ char stringpool_str16[sizeof("CP1258")];
+ char stringpool_str17[sizeof("CP850")];
+ char stringpool_str18[sizeof("CP865")];
+ char stringpool_str19[sizeof("EUC-JP")];
+ char stringpool_str20[sizeof("CP1257")];
+ char stringpool_str21[sizeof("CP1256")];
+ char stringpool_str22[sizeof("ISO-8859-8")];
+ char stringpool_str23[sizeof("SHIFT_JIS")];
+ char stringpool_str25[sizeof("ISO-8859-9")];
+ char stringpool_str26[sizeof("ISO-8859-7")];
+ char stringpool_str27[sizeof("ISO-8859-6")];
+ char stringpool_str29[sizeof("CP857")];
+ char stringpool_str30[sizeof("CP1252")];
+ char stringpool_str31[sizeof("CP869")];
+ char stringpool_str32[sizeof("CP949")];
+ char stringpool_str33[sizeof("CP866")];
+ char stringpool_str34[sizeof("CP437")];
+ char stringpool_str35[sizeof("CP1251")];
+ char stringpool_str36[sizeof("ISO-8859-2")];
+ char stringpool_str37[sizeof("CP1254")];
+ char stringpool_str38[sizeof("CP874")];
+ char stringpool_str39[sizeof("CP852")];
+ char stringpool_str40[sizeof("CP1253")];
+ char stringpool_str41[sizeof("ISO-8859-1")];
+ char stringpool_str42[sizeof("CP862")];
+ char stringpool_str43[sizeof("ISO-8859-4")];
+ char stringpool_str46[sizeof("ISO-8859-3")];
+ char stringpool_str47[sizeof("CP861")];
+ };
+static const struct stringpool_t stringpool_contents =
+ {
+ "CP1255",
+ "CP775",
+ "CP1250",
+ "EUC-TW",
+ "EUC-KR",
+ "TIS-620",
+ "ISO-8859-5",
+ "ISO-8859-15",
+ "BIG5",
+ "CP855",
+ "CP1258",
+ "CP850",
+ "CP865",
+ "EUC-JP",
+ "CP1257",
+ "CP1256",
+ "ISO-8859-8",
+ "SHIFT_JIS",
+ "ISO-8859-9",
+ "ISO-8859-7",
+ "ISO-8859-6",
+ "CP857",
+ "CP1252",
+ "CP869",
+ "CP949",
+ "CP866",
+ "CP437",
+ "CP1251",
+ "ISO-8859-2",
+ "CP1254",
+ "CP874",
+ "CP852",
+ "CP1253",
+ "ISO-8859-1",
+ "CP862",
+ "ISO-8859-4",
+ "ISO-8859-3",
+ "CP861"
+ };
+#define stringpool ((const char *) &stringpool_contents)
+
+static const struct mapping mappings[] =
+ {
+ {-1}, {-1}, {-1}, {-1}, {-1}, {-1},
+#line 41 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str6, "cp1255"},
+#line 24 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str7, "cp775"},
+#line 36 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str8, "cp1250"},
+#line 47 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str9, "eucTW"},
+#line 46 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str10, "eucKR"},
+#line 50 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str11, "TACTIS"},
+#line 17 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str12, "ISO8859-5"},
+#line 22 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str13, "ISO8859-15"},
+#line 48 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str14, "big5"},
+#line 27 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str15, "cp855"},
+#line 44 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str16, "cp1258"},
+#line 25 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str17, "cp850"},
+#line 31 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str18, "cp865"},
+#line 45 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str19, "eucJP"},
+#line 43 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str20, "cp1257"},
+#line 42 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str21, "cp1256"},
+#line 20 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str22, "ISO8859-8"},
+#line 49 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str23, "SJIS"},
+ {-1},
+#line 21 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str25, "ISO8859-9"},
+#line 19 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str26, "ISO8859-7"},
+#line 18 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str27, "ISO8859-6"},
+ {-1},
+#line 28 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str29, "cp857"},
+#line 38 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str30, "cp1252"},
+#line 33 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str31, "cp869"},
+#line 35 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str32, "KSC5601"},
+#line 32 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str33, "cp866"},
+#line 23 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str34, "cp437"},
+#line 37 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str35, "cp1251"},
+#line 14 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str36, "ISO8859-2"},
+#line 40 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str37, "cp1254"},
+#line 34 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str38, "cp874"},
+#line 26 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str39, "cp852"},
+#line 39 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str40, "cp1253"},
+#line 13 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str41, "ISO8859-1"},
+#line 30 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str42, "cp862"},
+#line 16 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str43, "ISO8859-4"},
+ {-1}, {-1},
+#line 15 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str46, "ISO8859-3"},
+#line 29 "./lib/iconv_open-osf.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str47, "cp861"}
+ };
+
+#ifdef __GNUC__
+__inline
+#if defined __GNUC_STDC_INLINE__ || defined __GNUC_GNU_INLINE__
+__attribute__ ((__gnu_inline__))
+#endif
+#endif
+const struct mapping *
+mapping_lookup (register const char *str, register unsigned int len)
+{
+ if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH)
+ {
+ register int key = mapping_hash (str, len);
+
+ if (key <= MAX_HASH_VALUE && key >= 0)
+ {
+ register int o = mappings[key].standard_name;
+ if (o >= 0)
+ {
+ register const char *s = o + stringpool;
+
+ if (*str == *s && !strcmp (str + 1, s + 1))
+ return &mappings[key];
+ }
+ }
+ }
+ return 0;
+}
diff --git a/lib/iconv_open-solaris.gperf b/lib/iconv_open-solaris.gperf
new file mode 100644
index 0000000..7d7da38
--- /dev/null
+++ b/lib/iconv_open-solaris.gperf
@@ -0,0 +1,30 @@
+struct mapping { int standard_name; const char vendor_name[10 + 1]; };
+%struct-type
+%language=ANSI-C
+%define slot-name standard_name
+%define hash-function-name mapping_hash
+%define lookup-function-name mapping_lookup
+%readonly-tables
+%global-table
+%define word-array-name mappings
+%pic
+%%
+# On Solaris 10, look in the "iconv -l" output. Some aliases are advertised but
+# not actually supported by the iconv() function and by the 'iconv' program.
+# For example:
+# $ echo abc | iconv -f 646 -t ISO-8859-1
+# Not supported 646 to ISO-8859-1
+# $ echo abc | iconv -f 646 -t ISO8859-1
+$ abc
+ASCII, "646"
+ISO-8859-1, "ISO8859-1"
+ISO-8859-2, "ISO8859-2"
+ISO-8859-3, "ISO8859-3"
+ISO-8859-4, "ISO8859-4"
+ISO-8859-5, "ISO8859-5"
+ISO-8859-6, "ISO8859-6"
+ISO-8859-7, "ISO8859-7"
+ISO-8859-8, "ISO8859-8"
+ISO-8859-9, "ISO8859-9"
+ISO-8859-15, "ISO8859-15"
+CP1251, "ansi-1251"
diff --git a/lib/iconv_open-solaris.h b/lib/iconv_open-solaris.h
new file mode 100644
index 0000000..dfd5a5d
--- /dev/null
+++ b/lib/iconv_open-solaris.h
@@ -0,0 +1,190 @@
+/* ANSI-C code produced by gperf version 3.0.4 */
+/* Command-line: gperf -m 10 ./lib/iconv_open-solaris.gperf */
+/* Computed positions: -k'10' */
+
+#if !((' ' == 32) && ('!' == 33) && ('"' == 34) && ('#' == 35) \
+ && ('%' == 37) && ('&' == 38) && ('\'' == 39) && ('(' == 40) \
+ && (')' == 41) && ('*' == 42) && ('+' == 43) && (',' == 44) \
+ && ('-' == 45) && ('.' == 46) && ('/' == 47) && ('0' == 48) \
+ && ('1' == 49) && ('2' == 50) && ('3' == 51) && ('4' == 52) \
+ && ('5' == 53) && ('6' == 54) && ('7' == 55) && ('8' == 56) \
+ && ('9' == 57) && (':' == 58) && (';' == 59) && ('<' == 60) \
+ && ('=' == 61) && ('>' == 62) && ('?' == 63) && ('A' == 65) \
+ && ('B' == 66) && ('C' == 67) && ('D' == 68) && ('E' == 69) \
+ && ('F' == 70) && ('G' == 71) && ('H' == 72) && ('I' == 73) \
+ && ('J' == 74) && ('K' == 75) && ('L' == 76) && ('M' == 77) \
+ && ('N' == 78) && ('O' == 79) && ('P' == 80) && ('Q' == 81) \
+ && ('R' == 82) && ('S' == 83) && ('T' == 84) && ('U' == 85) \
+ && ('V' == 86) && ('W' == 87) && ('X' == 88) && ('Y' == 89) \
+ && ('Z' == 90) && ('[' == 91) && ('\\' == 92) && (']' == 93) \
+ && ('^' == 94) && ('_' == 95) && ('a' == 97) && ('b' == 98) \
+ && ('c' == 99) && ('d' == 100) && ('e' == 101) && ('f' == 102) \
+ && ('g' == 103) && ('h' == 104) && ('i' == 105) && ('j' == 106) \
+ && ('k' == 107) && ('l' == 108) && ('m' == 109) && ('n' == 110) \
+ && ('o' == 111) && ('p' == 112) && ('q' == 113) && ('r' == 114) \
+ && ('s' == 115) && ('t' == 116) && ('u' == 117) && ('v' == 118) \
+ && ('w' == 119) && ('x' == 120) && ('y' == 121) && ('z' == 122) \
+ && ('{' == 123) && ('|' == 124) && ('}' == 125) && ('~' == 126))
+/* The character set is not based on ISO-646. */
+#error "gperf generated tables don't work with this execution character set. Please report a bug to <bug-gnu-gperf@gnu.org>."
+#endif
+
+#line 1 "./lib/iconv_open-solaris.gperf"
+struct mapping { int standard_name; const char vendor_name[10 + 1]; };
+
+#define TOTAL_KEYWORDS 13
+#define MIN_WORD_LENGTH 5
+#define MAX_WORD_LENGTH 11
+#define MIN_HASH_VALUE 5
+#define MAX_HASH_VALUE 19
+/* maximum key range = 15, duplicates = 0 */
+
+#ifdef __GNUC__
+__inline
+#else
+#ifdef __cplusplus
+inline
+#endif
+#endif
+static unsigned int
+mapping_hash (register const char *str, register unsigned int len)
+{
+ static const unsigned char asso_values[] =
+ {
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 0,
+ 9, 8, 7, 6, 5, 4, 3, 2, 20, 20,
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+ 20, 20, 20, 20, 20, 20
+ };
+ register int hval = len;
+
+ switch (hval)
+ {
+ default:
+ hval += asso_values[(unsigned char)str[9]];
+ /*FALLTHROUGH*/
+ case 9:
+ case 8:
+ case 7:
+ case 6:
+ case 5:
+ break;
+ }
+ return hval;
+}
+
+struct stringpool_t
+ {
+ char stringpool_str5[sizeof("ASCII")];
+ char stringpool_str6[sizeof("CP1251")];
+ char stringpool_str7[sizeof("$ abc")];
+ char stringpool_str10[sizeof("ISO-8859-1")];
+ char stringpool_str11[sizeof("ISO-8859-15")];
+ char stringpool_str12[sizeof("ISO-8859-9")];
+ char stringpool_str13[sizeof("ISO-8859-8")];
+ char stringpool_str14[sizeof("ISO-8859-7")];
+ char stringpool_str15[sizeof("ISO-8859-6")];
+ char stringpool_str16[sizeof("ISO-8859-5")];
+ char stringpool_str17[sizeof("ISO-8859-4")];
+ char stringpool_str18[sizeof("ISO-8859-3")];
+ char stringpool_str19[sizeof("ISO-8859-2")];
+ };
+static const struct stringpool_t stringpool_contents =
+ {
+ "ASCII",
+ "CP1251",
+ "$ abc",
+ "ISO-8859-1",
+ "ISO-8859-15",
+ "ISO-8859-9",
+ "ISO-8859-8",
+ "ISO-8859-7",
+ "ISO-8859-6",
+ "ISO-8859-5",
+ "ISO-8859-4",
+ "ISO-8859-3",
+ "ISO-8859-2"
+ };
+#define stringpool ((const char *) &stringpool_contents)
+
+static const struct mapping mappings[] =
+ {
+ {-1}, {-1}, {-1}, {-1}, {-1},
+#line 19 "./lib/iconv_open-solaris.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str5, "646"},
+#line 30 "./lib/iconv_open-solaris.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str6, "ansi-1251"},
+#line 18 "./lib/iconv_open-solaris.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str7},
+ {-1}, {-1},
+#line 20 "./lib/iconv_open-solaris.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str10, "ISO8859-1"},
+#line 29 "./lib/iconv_open-solaris.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str11, "ISO8859-15"},
+#line 28 "./lib/iconv_open-solaris.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str12, "ISO8859-9"},
+#line 27 "./lib/iconv_open-solaris.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str13, "ISO8859-8"},
+#line 26 "./lib/iconv_open-solaris.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str14, "ISO8859-7"},
+#line 25 "./lib/iconv_open-solaris.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str15, "ISO8859-6"},
+#line 24 "./lib/iconv_open-solaris.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str16, "ISO8859-5"},
+#line 23 "./lib/iconv_open-solaris.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str17, "ISO8859-4"},
+#line 22 "./lib/iconv_open-solaris.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str18, "ISO8859-3"},
+#line 21 "./lib/iconv_open-solaris.gperf"
+ {(int)(long)&((struct stringpool_t *)0)->stringpool_str19, "ISO8859-2"}
+ };
+
+#ifdef __GNUC__
+__inline
+#if defined __GNUC_STDC_INLINE__ || defined __GNUC_GNU_INLINE__
+__attribute__ ((__gnu_inline__))
+#endif
+#endif
+const struct mapping *
+mapping_lookup (register const char *str, register unsigned int len)
+{
+ if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH)
+ {
+ register int key = mapping_hash (str, len);
+
+ if (key <= MAX_HASH_VALUE && key >= 0)
+ {
+ register int o = mappings[key].standard_name;
+ if (o >= 0)
+ {
+ register const char *s = o + stringpool;
+
+ if (*str == *s && !strcmp (str + 1, s + 1))
+ return &mappings[key];
+ }
+ }
+ }
+ return 0;
+}
diff --git a/lib/iconv_open.c b/lib/iconv_open.c
new file mode 100644
index 0000000..d5c5a52
--- /dev/null
+++ b/lib/iconv_open.c
@@ -0,0 +1,172 @@
+/* Character set conversion.
+ Copyright (C) 2007, 2009-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <iconv.h>
+
+#include <errno.h>
+#include <string.h>
+#include "c-ctype.h"
+#include "c-strcase.h"
+
+#define SIZEOF(a) (sizeof(a) / sizeof(a[0]))
+
+/* Namespace cleanliness. */
+#define mapping_lookup rpl_iconv_open_mapping_lookup
+
+/* The macro ICONV_FLAVOR is defined to one of these or undefined. */
+
+#define ICONV_FLAVOR_AIX "iconv_open-aix.h"
+#define ICONV_FLAVOR_HPUX "iconv_open-hpux.h"
+#define ICONV_FLAVOR_IRIX "iconv_open-irix.h"
+#define ICONV_FLAVOR_OSF "iconv_open-osf.h"
+#define ICONV_FLAVOR_SOLARIS "iconv_open-solaris.h"
+
+#ifdef ICONV_FLAVOR
+# include ICONV_FLAVOR
+#endif
+
+iconv_t
+rpl_iconv_open (const char *tocode, const char *fromcode)
+#undef iconv_open
+{
+ char fromcode_upper[32];
+ char tocode_upper[32];
+ char *fromcode_upper_end;
+ char *tocode_upper_end;
+
+#if REPLACE_ICONV_UTF
+ /* Special handling of conversion between UTF-8 and UTF-{16,32}{BE,LE}.
+ Do this here, before calling the real iconv_open(), because OSF/1 5.1
+ iconv() to these encoding inserts a BOM, which is wrong.
+ We do not need to handle conversion between arbitrary encodings and
+ UTF-{16,32}{BE,LE}, because the 'striconveh' module implements two-step
+ conversion through UTF-8.
+ The _ICONV_* constants are chosen to be disjoint from any iconv_t
+ returned by the system's iconv_open() functions. Recall that iconv_t
+ is a scalar type. */
+ if (c_toupper (fromcode[0]) == 'U'
+ && c_toupper (fromcode[1]) == 'T'
+ && c_toupper (fromcode[2]) == 'F'
+ && fromcode[3] == '-')
+ {
+ if (c_toupper (tocode[0]) == 'U'
+ && c_toupper (tocode[1]) == 'T'
+ && c_toupper (tocode[2]) == 'F'
+ && tocode[3] == '-')
+ {
+ if (strcmp (fromcode + 4, "8") == 0)
+ {
+ if (c_strcasecmp (tocode + 4, "16BE") == 0)
+ return _ICONV_UTF8_UTF16BE;
+ if (c_strcasecmp (tocode + 4, "16LE") == 0)
+ return _ICONV_UTF8_UTF16LE;
+ if (c_strcasecmp (tocode + 4, "32BE") == 0)
+ return _ICONV_UTF8_UTF32BE;
+ if (c_strcasecmp (tocode + 4, "32LE") == 0)
+ return _ICONV_UTF8_UTF32LE;
+ }
+ else if (strcmp (tocode + 4, "8") == 0)
+ {
+ if (c_strcasecmp (fromcode + 4, "16BE") == 0)
+ return _ICONV_UTF16BE_UTF8;
+ if (c_strcasecmp (fromcode + 4, "16LE") == 0)
+ return _ICONV_UTF16LE_UTF8;
+ if (c_strcasecmp (fromcode + 4, "32BE") == 0)
+ return _ICONV_UTF32BE_UTF8;
+ if (c_strcasecmp (fromcode + 4, "32LE") == 0)
+ return _ICONV_UTF32LE_UTF8;
+ }
+ }
+ }
+#endif
+
+ /* Do *not* add special support for 8-bit encodings like ASCII or ISO-8859-1
+ here. This would lead to programs that work in some locales (such as the
+ "C" or "en_US" locales) but do not work in East Asian locales. It is
+ better if programmers make their programs depend on GNU libiconv (except
+ on glibc systems), e.g. by using the AM_ICONV macro and documenting the
+ dependency in an INSTALL or DEPENDENCIES file. */
+
+ /* Try with the original names first.
+ This covers the case when fromcode or tocode is a lowercase encoding name
+ that is understood by the system's iconv_open but not listed in our
+ mappings table. */
+ {
+ iconv_t cd = iconv_open (tocode, fromcode);
+ if (cd != (iconv_t)(-1))
+ return cd;
+ }
+
+ /* Convert the encodings to upper case, because
+ 1. in the arguments of iconv_open() on AIX, HP-UX, and OSF/1 the case
+ matters,
+ 2. it makes searching in the table faster. */
+ {
+ const char *p = fromcode;
+ char *q = fromcode_upper;
+ while ((*q = c_toupper (*p)) != '\0')
+ {
+ p++;
+ q++;
+ if (q == &fromcode_upper[SIZEOF (fromcode_upper)])
+ {
+ errno = EINVAL;
+ return (iconv_t)(-1);
+ }
+ }
+ fromcode_upper_end = q;
+ }
+
+ {
+ const char *p = tocode;
+ char *q = tocode_upper;
+ while ((*q = c_toupper (*p)) != '\0')
+ {
+ p++;
+ q++;
+ if (q == &tocode_upper[SIZEOF (tocode_upper)])
+ {
+ errno = EINVAL;
+ return (iconv_t)(-1);
+ }
+ }
+ tocode_upper_end = q;
+ }
+
+#ifdef ICONV_FLAVOR
+ /* Apply the mappings. */
+ {
+ const struct mapping *m =
+ mapping_lookup (fromcode_upper, fromcode_upper_end - fromcode_upper);
+
+ fromcode = (m != NULL ? m->vendor_name : fromcode_upper);
+ }
+ {
+ const struct mapping *m =
+ mapping_lookup (tocode_upper, tocode_upper_end - tocode_upper);
+
+ tocode = (m != NULL ? m->vendor_name : tocode_upper);
+ }
+#else
+ fromcode = fromcode_upper;
+ tocode = tocode_upper;
+#endif
+
+ return iconv_open (tocode, fromcode);
+}
diff --git a/lib/idcache.c b/lib/idcache.c
index 0706f00..a5f14ad 100644
--- a/lib/idcache.c
+++ b/lib/idcache.c
@@ -1,12 +1,12 @@
/* idcache.c -- map user and group IDs, cached for speed
- Copyright (C) 1985, 1988, 1989, 1990, 1997, 1998, 2003, 2005, 2006
- Free Software Foundation, Inc.
+ Copyright (C) 1985, 1988-1990, 1997-1998, 2003, 2005-2007, 2009-2016 Free
+ Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,15 +14,14 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
+#include "idcache.h"
#include <stddef.h>
#include <stdio.h>
#include <string.h>
-#include <sys/types.h>
#include <pwd.h>
#include <grp.h>
@@ -45,11 +44,24 @@ struct userid
char name[FLEXIBLE_ARRAY_MEMBER];
};
+/* FIXME: provide a function to free any malloc'd storage and reset lists,
+ so that an application can use code like this just before exiting:
+ #ifdef lint
+ idcache_clear ();
+ #endif
+*/
+
static struct userid *user_alist;
/* Each entry on list is a user name for which the first lookup failed. */
static struct userid *nouser_alist;
+/* Use the same struct as for userids. */
+static struct userid *group_alist;
+
+/* Each entry on list is a group name for which the first lookup failed. */
+static struct userid *nogroup_alist;
+
/* Translate UID to a login name, with cache, or NULL if unresolved. */
char *
@@ -61,10 +73,10 @@ getuser (uid_t uid)
for (tail = user_alist; tail; tail = tail->next)
{
if (tail->id.u == uid)
- {
- match = tail;
- break;
- }
+ {
+ match = tail;
+ break;
+ }
}
if (match == NULL)
@@ -111,7 +123,7 @@ getuidbyname (const char *user)
if (!pwent && strspn (user, digits) < strlen (user))
{
setenv ("USER", user, 1);
- pwent = getpwnam (user); /* now it will succeed */
+ pwent = getpwnam (user); /* now it will succeed */
}
#endif
@@ -132,12 +144,6 @@ getuidbyname (const char *user)
return NULL;
}
-/* Use the same struct as for userids. */
-static struct userid *group_alist;
-
-/* Each entry on list is a group name for which the first lookup failed. */
-static struct userid *nogroup_alist;
-
/* Translate GID to a group name, with cache, or NULL if unresolved. */
char *
@@ -149,10 +155,10 @@ getgroup (gid_t gid)
for (tail = group_alist; tail; tail = tail->next)
{
if (tail->id.g == gid)
- {
- match = tail;
- break;
- }
+ {
+ match = tail;
+ break;
+ }
}
if (match == NULL)
@@ -199,7 +205,7 @@ getgidbyname (const char *group)
if (!grent && strspn (group, digits) < strlen (group))
{
setenv ("GROUP", group, 1);
- grent = getgrnam (group); /* now it will succeed */
+ grent = getgrnam (group); /* now it will succeed */
}
#endif
diff --git a/lib/idcache.h b/lib/idcache.h
new file mode 100644
index 0000000..e7573b8
--- /dev/null
+++ b/lib/idcache.h
@@ -0,0 +1,11 @@
+#ifndef IDCACHE_H
+# define IDCACHE_H 1
+
+# include <sys/types.h>
+
+extern char *getuser (uid_t uid);
+extern char *getgroup (gid_t gid);
+extern uid_t *getuidbyname (const char *user);
+extern gid_t *getgidbyname (const char *group);
+
+#endif
diff --git a/lib/ignore-value.h b/lib/ignore-value.h
new file mode 100644
index 0000000..6713d96
--- /dev/null
+++ b/lib/ignore-value.h
@@ -0,0 +1,50 @@
+/* ignore a function return without a compiler warning. -*- coding: utf-8 -*-
+
+ Copyright (C) 2008-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Jim Meyering, Eric Blake and Pádraig Brady. */
+
+/* Use "ignore_value" to avoid a warning when using a function declared with
+ gcc's warn_unused_result attribute, but for which you really do want to
+ ignore the result. Traditionally, people have used a "(void)" cast to
+ indicate that a function's return value is deliberately unused. However,
+ if the function is declared with __attribute__((warn_unused_result)),
+ gcc issues a warning even with the cast.
+
+ Caution: most of the time, you really should heed gcc's warning, and
+ check the return value. However, in those exceptional cases in which
+ you're sure you know what you're doing, use this function.
+
+ For the record, here's one of the ignorable warnings:
+ "copy.c:233: warning: ignoring return value of 'fchown',
+ declared with attribute warn_unused_result". */
+
+#ifndef _GL_IGNORE_VALUE_H
+#define _GL_IGNORE_VALUE_H
+
+/* Normally casting an expression to void discards its value, but GCC
+ versions 3.4 and newer have __attribute__ ((__warn_unused_result__))
+ which may cause unwanted diagnostics in that case. Use __typeof__
+ and __extension__ to work around the problem, if the workaround is
+ known to be needed. */
+#if 3 < __GNUC__ + (4 <= __GNUC_MINOR__)
+# define ignore_value(x) \
+ (__extension__ ({ __typeof__ (x) __x = (x); (void) __x; }))
+#else
+# define ignore_value(x) ((void) (x))
+#endif
+
+#endif
diff --git a/lib/imaxtostr.c b/lib/imaxtostr.c
index 5e87ad5..b91ac98 100644
--- a/lib/imaxtostr.c
+++ b/lib/imaxtostr.c
@@ -1,3 +1,3 @@
-#define inttostr imaxtostr
+#define anytostr imaxtostr
#define inttype intmax_t
-#include "inttostr.c"
+#include "anytostr.c"
diff --git a/lib/inet_ntop.c b/lib/inet_ntop.c
index 537b59f..823d345 100644
--- a/lib/inet_ntop.c
+++ b/lib/inet_ntop.c
@@ -1,10 +1,10 @@
/* inet_ntop.c -- convert IPv4 and IPv6 addresses from binary to text form
- Copyright (C) 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2005-2006, 2008-2016 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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program; if not, see <http://www.gnu.org/licenses/>. */
/*
* Copyright (c) 1996-1999 by Internet Software Consortium.
@@ -36,54 +35,73 @@
#include <config.h>
/* Specification. */
-#include "inet_ntop.h"
+#include <arpa/inet.h>
-#include <stdio.h>
-#include <string.h>
-#include <errno.h>
-
-#ifndef EAFNOSUPPORT
-# define EAFNOSUPPORT EINVAL
+/* Use this to suppress gcc's "...may be used before initialized" warnings.
+ Beware: The Code argument must not contain commas. */
+#ifndef IF_LINT
+# ifdef lint
+# define IF_LINT(Code) Code
+# else
+# define IF_LINT(Code) /* empty */
+# endif
#endif
-#define NS_IN6ADDRSZ 16
-#define NS_INT16SZ 2
+#if HAVE_DECL_INET_NTOP
+
+# undef inet_ntop
+
+const char *
+rpl_inet_ntop (int af, const void *restrict src,
+ char *restrict dst, socklen_t cnt)
+{
+ return inet_ntop (af, src, dst, cnt);
+}
+
+#else
+
+# include <stdio.h>
+# include <string.h>
+# include <errno.h>
+
+# define NS_IN6ADDRSZ 16
+# define NS_INT16SZ 2
/*
* WARNING: Don't even consider trying to compile this on a system where
* sizeof(int) < 4. sizeof(int) > 4 is fine; all the world's not a VAX.
*/
-typedef int verify_int_size[2 * sizeof (int) - 7];
+typedef int verify_int_size[4 <= sizeof (int) ? 1 : -1];
static const char *inet_ntop4 (const unsigned char *src, char *dst, socklen_t size);
-#if HAVE_IPV6
+# if HAVE_IPV6
static const char *inet_ntop6 (const unsigned char *src, char *dst, socklen_t size);
-#endif
+# endif
/* char *
* inet_ntop(af, src, dst, size)
- * convert a network format address to presentation format.
+ * convert a network format address to presentation format.
* return:
- * pointer to presentation format address (`dst'), or NULL (see errno).
+ * pointer to presentation format address ('dst'), or NULL (see errno).
* author:
- * Paul Vixie, 1996.
+ * Paul Vixie, 1996.
*/
const char *
inet_ntop (int af, const void *restrict src,
- char *restrict dst, socklen_t cnt)
+ char *restrict dst, socklen_t cnt)
{
switch (af)
{
-#if HAVE_IPV4
+# if HAVE_IPV4
case AF_INET:
return (inet_ntop4 (src, dst, cnt));
-#endif
+# endif
-#if HAVE_IPV6
+# if HAVE_IPV6
case AF_INET6:
return (inet_ntop6 (src, dst, cnt));
-#endif
+# endif
default:
errno = EAFNOSUPPORT;
@@ -94,14 +112,14 @@ inet_ntop (int af, const void *restrict src,
/* const char *
* inet_ntop4(src, dst, size)
- * format an IPv4 address
+ * format an IPv4 address
* return:
- * `dst' (as a const)
+ * 'dst' (as a const)
* notes:
- * (1) uses no statics
- * (2) takes a u_char* not an in_addr as input
+ * (1) uses no statics
+ * (2) takes a u_char* not an in_addr as input
* author:
- * Paul Vixie, 1996.
+ * Paul Vixie, 1996.
*/
static const char *
inet_ntop4 (const unsigned char *src, char *dst, socklen_t size)
@@ -122,13 +140,13 @@ inet_ntop4 (const unsigned char *src, char *dst, socklen_t size)
return strcpy (dst, tmp);
}
-#if HAVE_IPV6
+# if HAVE_IPV6
/* const char *
* inet_ntop6(src, dst, size)
- * convert IPv6 binary address into presentation (printable) format
+ * convert IPv6 binary address into presentation (printable) format
* author:
- * Paul Vixie, 1996.
+ * Paul Vixie, 1996.
*/
static const char *
inet_ntop6 (const unsigned char *src, char *dst, socklen_t size)
@@ -158,29 +176,31 @@ inet_ntop6 (const unsigned char *src, char *dst, socklen_t size)
words[i / 2] = (src[i] << 8) | src[i + 1];
best.base = -1;
cur.base = -1;
+ IF_LINT(best.len = 0);
+ IF_LINT(cur.len = 0);
for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++)
{
if (words[i] == 0)
- {
- if (cur.base == -1)
- cur.base = i, cur.len = 1;
- else
- cur.len++;
- }
+ {
+ if (cur.base == -1)
+ cur.base = i, cur.len = 1;
+ else
+ cur.len++;
+ }
else
- {
- if (cur.base != -1)
- {
- if (best.base == -1 || cur.len > best.len)
- best = cur;
- cur.base = -1;
- }
- }
+ {
+ if (cur.base != -1)
+ {
+ if (best.base == -1 || cur.len > best.len)
+ best = cur;
+ cur.base = -1;
+ }
+ }
}
if (cur.base != -1)
{
if (best.base == -1 || cur.len > best.len)
- best = cur;
+ best = cur;
}
if (best.base != -1 && best.len < 2)
best.base = -1;
@@ -193,28 +213,28 @@ inet_ntop6 (const unsigned char *src, char *dst, socklen_t size)
{
/* Are we inside the best run of 0x00's? */
if (best.base != -1 && i >= best.base && i < (best.base + best.len))
- {
- if (i == best.base)
- *tp++ = ':';
- continue;
- }
+ {
+ if (i == best.base)
+ *tp++ = ':';
+ continue;
+ }
/* Are we following an initial run of 0x00s or any real hex? */
if (i != 0)
- *tp++ = ':';
+ *tp++ = ':';
/* Is this address an encapsulated IPv4? */
if (i == 6 && best.base == 0 &&
- (best.len == 6 || (best.len == 5 && words[5] == 0xffff)))
- {
- if (!inet_ntop4 (src + 12, tp, sizeof tmp - (tp - tmp)))
- return (NULL);
- tp += strlen (tp);
- break;
- }
+ (best.len == 6 || (best.len == 5 && words[5] == 0xffff)))
+ {
+ if (!inet_ntop4 (src + 12, tp, sizeof tmp - (tp - tmp)))
+ return (NULL);
+ tp += strlen (tp);
+ break;
+ }
{
- int len = sprintf (tp, "%x", words[i]);
- if (len < 0)
- return NULL;
- tp += len;
+ int len = sprintf (tp, "%x", words[i]);
+ if (len < 0)
+ return NULL;
+ tp += len;
}
}
/* Was it a trailing run of 0x00's? */
@@ -235,4 +255,6 @@ inet_ntop6 (const unsigned char *src, char *dst, socklen_t size)
return strcpy (dst, tmp);
}
+# endif
+
#endif
diff --git a/lib/inet_ntop.h b/lib/inet_ntop.h
deleted file mode 100644
index bd1e085..0000000
--- a/lib/inet_ntop.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/* Convert internet address from internal to printable, presentable format.
- Copyright (C) 2005, 2006 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
-
-/* Converts an internet address from internal format to a printable,
- presentable format.
- AF is an internet address family, such as AF_INET or AF_INET6.
- SRC points to a 'struct in_addr' (for AF_INET) or 'struct in6_addr'
- (for AF_INET6).
- DST points to a buffer having room for CNT bytes.
- The printable representation of the address (in numeric form, not
- surrounded by [...], no reverse DNS is done) is placed in DST, and
- DST is returned. If an error occurs, the return value is NULL and
- errno is set. If CNT bytes are not sufficient to hold the result,
- the return value is NULL and errno is set to ENOSPC. A good value
- for CNT is 46.
-
- For more details, see the POSIX:2001 specification
- <http://www.opengroup.org/susv3xsh/inet_ntop.html>. */
-
-#if !HAVE_DECL_INET_NTOP
-extern const char *inet_ntop (int af, const void *restrict src,
- char *restrict dst, socklen_t cnt);
-#endif
diff --git a/lib/ino-map.c b/lib/ino-map.c
new file mode 100644
index 0000000..3842301
--- /dev/null
+++ b/lib/ino-map.c
@@ -0,0 +1,164 @@
+/* Map an ino_t inode number to a small integer.
+
+ Copyright 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* written by Paul Eggert and Jim Meyering */
+
+#include <config.h>
+#include "ino-map.h"
+
+#include "hash.h"
+#include "verify.h"
+
+#include <limits.h>
+#include <stdlib.h>
+
+/* A pair that maps an inode number to a mapped inode number; the
+ latter is a small unique ID for the former. */
+struct ino_map_ent
+{
+ ino_t ino;
+ size_t mapped_ino;
+};
+
+/* A table that manages and indexes these pairs. */
+struct ino_map
+{
+ /* A table of KEY,VAL pairs, where KEY is the raw ino_t value and
+ VAL is the small number that it maps to. */
+ struct hash_table *map;
+
+ /* The next mapped inode number to hand out. */
+ size_t next_mapped_ino;
+
+ /* Cache of the most recently allocated and otherwise-unused storage
+ for probing the table. */
+ struct ino_map_ent *probe;
+};
+
+/* Hash an inode map entry. */
+static size_t
+ino_hash (void const *x, size_t table_size)
+{
+ struct ino_map_ent const *p = x;
+ ino_t ino = p->ino;
+
+ /* When INO is wider than size_t, exclusive-OR the words of INO into H.
+ This avoids loss of info, without applying % to the wider type,
+ which could be quite slow on some systems. */
+ size_t h = ino;
+ unsigned int i;
+ unsigned int n_words = sizeof ino / sizeof h + (sizeof ino % sizeof h != 0);
+ for (i = 1; i < n_words; i++)
+ h ^= ino >> CHAR_BIT * sizeof h * i;
+
+ return h % table_size;
+}
+
+/* Return true if two inode map entries are the same. */
+static bool
+ino_compare (void const *x, void const *y)
+{
+ struct ino_map_ent const *a = x;
+ struct ino_map_ent const *b = y;
+ return a->ino == b->ino;
+}
+
+/* Allocate an inode map that will hand out integers starting with
+ NEXT_MAPPED_INO. Return NULL if memory is exhausted. */
+struct ino_map *
+ino_map_alloc (size_t next_mapped_ino)
+{
+ struct ino_map *im = malloc (sizeof *im);
+
+ if (im)
+ {
+ enum { INITIAL_INO_MAP_TABLE_SIZE = 1021 };
+ im->map = hash_initialize (INITIAL_INO_MAP_TABLE_SIZE, NULL,
+ ino_hash, ino_compare, free);
+ if (! im->map)
+ {
+ free (im);
+ return NULL;
+ }
+ im->next_mapped_ino = next_mapped_ino;
+ im->probe = NULL;
+ }
+
+ return im;
+}
+
+/* Free an inode map. */
+void
+ino_map_free (struct ino_map *map)
+{
+ hash_free (map->map);
+ free (map->probe);
+ free (map);
+}
+
+
+/* Insert into MAP the inode number INO if it's not there already,
+ and return its nonnegative mapped inode number.
+ If INO is already in MAP, return the existing mapped inode number.
+ Return INO_MAP_INSERT_FAILURE on memory or counter exhaustion. */
+size_t
+ino_map_insert (struct ino_map *im, ino_t ino)
+{
+ struct ino_map_ent *ent;
+
+ /* Find space for the probe, reusing the cache if available. */
+ struct ino_map_ent *probe = im->probe;
+ if (probe)
+ {
+ /* If repeating a recent query, return the cached result. */
+ if (probe->ino == ino)
+ return probe->mapped_ino;
+ }
+ else
+ {
+ im->probe = probe = malloc (sizeof *probe);
+ if (! probe)
+ return INO_MAP_INSERT_FAILURE;
+ }
+
+ probe->ino = ino;
+ ent = hash_insert (im->map, probe);
+ if (! ent)
+ return INO_MAP_INSERT_FAILURE;
+
+ if (ent != probe)
+ {
+ /* Use the existing entry. */
+ probe->mapped_ino = ent->mapped_ino;
+ }
+ else
+ {
+ /* If adding 1 to map->next_mapped_ino would cause it to
+ overflow to zero, then it must equal INO_MAP_INSERT_FAILURE,
+ which is the value that should be returned in that case.
+ Verify that this works. */
+ verify (INO_MAP_INSERT_FAILURE + 1 == 0);
+
+ /* Prepare to allocate a new probe next time; this one is in use. */
+ im->probe = NULL;
+
+ /* INO is new; allocate a mapped inode number for it. */
+ probe->mapped_ino = im->next_mapped_ino++;
+ }
+
+ return probe->mapped_ino;
+}
diff --git a/lib/ino-map.h b/lib/ino-map.h
new file mode 100644
index 0000000..b742291
--- /dev/null
+++ b/lib/ino-map.h
@@ -0,0 +1,19 @@
+#ifndef _GL_INO_MAP_H
+# define _GL_INO_MAP_H
+
+# include <sys/types.h>
+
+# undef _GL_ATTRIBUTE_NONNULL
+# if __GNUC__ == 3 && __GNUC_MINOR__ >= 3 || 3 < __GNUC__
+# define _GL_ATTRIBUTE_NONNULL(m) __attribute__ ((__nonnull__ (m)))
+# else
+# define _GL_ATTRIBUTE_NONNULL(m)
+# endif
+
+# define INO_MAP_INSERT_FAILURE ((size_t) -1)
+
+struct ino_map *ino_map_alloc (size_t);
+void ino_map_free (struct ino_map *) _GL_ATTRIBUTE_NONNULL (1);
+size_t ino_map_insert (struct ino_map *, ino_t) _GL_ATTRIBUTE_NONNULL (1);
+
+#endif
diff --git a/lib/intprops.h b/lib/intprops.h
index 34f971c..e1a6107 100644
--- a/lib/intprops.h
+++ b/lib/intprops.h
@@ -1,11 +1,11 @@
/* intprops.h -- properties of integer types
- Copyright (C) 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
+ Copyright (C) 2001-2005, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,13 +13,22 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
+#ifndef _GL_INTPROPS_H
+#define _GL_INTPROPS_H
+
#include <limits.h>
+/* Return a value with the common real type of E and V and the value of V. */
+#define _GL_INT_CONVERT(e, v) (0 * (e) + (v))
+
+/* Act like _GL_INT_CONVERT (E, -V) but work around a bug in IRIX 6.5 cc; see
+ <http://lists.gnu.org/archive/html/bug-gnulib/2011-05/msg00406.html>. */
+#define _GL_INT_NEGATE_CONVERT(e, v) (0 * (e) - (v))
+
/* The extra casts in the following macros work around compiler bugs,
e.g., in Cray C 5.0.3.0. */
@@ -35,44 +44,386 @@
#define TYPE_ONES_COMPLEMENT(t) ((t) ~ (t) 0 == 0)
#define TYPE_SIGNED_MAGNITUDE(t) ((t) ~ (t) 0 < (t) -1)
-/* True if the arithmetic type T is signed. */
+/* True if the signed integer expression E uses two's complement. */
+#define _GL_INT_TWOS_COMPLEMENT(e) (~ _GL_INT_CONVERT (e, 0) == -1)
+
+/* True if the real type T is signed. */
#define TYPE_SIGNED(t) (! ((t) 0 < (t) -1))
-/* The maximum and minimum values for the integer type T. These
+/* Return 1 if the real expression E, after promotion, has a
+ signed or floating type. */
+#define EXPR_SIGNED(e) (_GL_INT_NEGATE_CONVERT (e, 1) < 0)
+
+
+/* Minimum and maximum values for integer types and expressions. These
macros have undefined behavior if T is signed and has padding bits.
If this is a problem for you, please let us know how to fix it for
your host. */
-#define TYPE_MINIMUM(t) \
- ((t) (! TYPE_SIGNED (t) \
- ? (t) 0 \
- : TYPE_SIGNED_MAGNITUDE (t) \
- ? ~ (t) 0 \
- : ~ (t) 0 << (sizeof (t) * CHAR_BIT - 1)))
-#define TYPE_MAXIMUM(t) \
- ((t) (! TYPE_SIGNED (t) \
- ? (t) -1 \
- : ~ (~ (t) 0 << (sizeof (t) * CHAR_BIT - 1))))
-
-/* Return zero if T can be determined to be an unsigned type.
- Otherwise, return 1.
- When compiling with GCC, INT_STRLEN_BOUND uses this macro to obtain a
- tighter bound. Otherwise, it overestimates the true bound by one byte
- when applied to unsigned types of size 2, 4, 16, ... bytes.
- The symbol signed_type_or_expr__ is private to this header file. */
-#if __GNUC__ >= 2
-# define signed_type_or_expr__(t) TYPE_SIGNED (__typeof__ (t))
+
+/* The maximum and minimum values for the integer type T. */
+#define TYPE_MINIMUM(t) \
+ ((t) (! TYPE_SIGNED (t) \
+ ? (t) 0 \
+ : TYPE_SIGNED_MAGNITUDE (t) \
+ ? ~ (t) 0 \
+ : ~ TYPE_MAXIMUM (t)))
+#define TYPE_MAXIMUM(t) \
+ ((t) (! TYPE_SIGNED (t) \
+ ? (t) -1 \
+ : ((((t) 1 << (sizeof (t) * CHAR_BIT - 2)) - 1) * 2 + 1)))
+
+/* The maximum and minimum values for the type of the expression E,
+ after integer promotion. E should not have side effects. */
+#define _GL_INT_MINIMUM(e) \
+ (EXPR_SIGNED (e) \
+ ? - _GL_INT_TWOS_COMPLEMENT (e) - _GL_SIGNED_INT_MAXIMUM (e) \
+ : _GL_INT_CONVERT (e, 0))
+#define _GL_INT_MAXIMUM(e) \
+ (EXPR_SIGNED (e) \
+ ? _GL_SIGNED_INT_MAXIMUM (e) \
+ : _GL_INT_NEGATE_CONVERT (e, 1))
+#define _GL_SIGNED_INT_MAXIMUM(e) \
+ (((_GL_INT_CONVERT (e, 1) << (sizeof ((e) + 0) * CHAR_BIT - 2)) - 1) * 2 + 1)
+
+
+/* Return 1 if the __typeof__ keyword works. This could be done by
+ 'configure', but for now it's easier to do it by hand. */
+#if (2 <= __GNUC__ || defined __IBM__TYPEOF__ \
+ || (0x5110 <= __SUNPRO_C && !__STDC__))
+# define _GL_HAVE___TYPEOF__ 1
#else
-# define signed_type_or_expr__(t) 1
+# define _GL_HAVE___TYPEOF__ 0
#endif
+/* Return 1 if the integer type or expression T might be signed. Return 0
+ if it is definitely unsigned. This macro does not evaluate its argument,
+ and expands to an integer constant expression. */
+#if _GL_HAVE___TYPEOF__
+# define _GL_SIGNED_TYPE_OR_EXPR(t) TYPE_SIGNED (__typeof__ (t))
+#else
+# define _GL_SIGNED_TYPE_OR_EXPR(t) 1
+#endif
+
+/* Bound on length of the string representing an unsigned integer
+ value representable in B bits. log10 (2.0) < 146/485. The
+ smallest value of B where this bound is not tight is 2621. */
+#define INT_BITS_STRLEN_BOUND(b) (((b) * 146 + 484) / 485)
+
/* Bound on length of the string representing an integer type or expression T.
- Subtract 1 for the sign bit if T is signed; log10 (2.0) < 146/485;
- add 1 for integer division truncation; add 1 more for a minus sign
- if needed. */
-#define INT_STRLEN_BOUND(t) \
- ((sizeof (t) * CHAR_BIT - signed_type_or_expr__ (t)) * 146 / 485 \
- + signed_type_or_expr__ (t) + 1)
+ Subtract 1 for the sign bit if T is signed, and then add 1 more for
+ a minus sign if needed.
+
+ Because _GL_SIGNED_TYPE_OR_EXPR sometimes returns 0 when its argument is
+ signed, this macro may overestimate the true bound by one byte when
+ applied to unsigned types of size 2, 4, 16, ... bytes. */
+#define INT_STRLEN_BOUND(t) \
+ (INT_BITS_STRLEN_BOUND (sizeof (t) * CHAR_BIT \
+ - _GL_SIGNED_TYPE_OR_EXPR (t)) \
+ + _GL_SIGNED_TYPE_OR_EXPR (t))
/* Bound on buffer size needed to represent an integer type or expression T,
including the terminating null. */
#define INT_BUFSIZE_BOUND(t) (INT_STRLEN_BOUND (t) + 1)
+
+
+/* Range overflow checks.
+
+ The INT_<op>_RANGE_OVERFLOW macros return 1 if the corresponding C
+ operators might not yield numerically correct answers due to
+ arithmetic overflow. They do not rely on undefined or
+ implementation-defined behavior. Their implementations are simple
+ and straightforward, but they are a bit harder to use than the
+ INT_<op>_OVERFLOW macros described below.
+
+ Example usage:
+
+ long int i = ...;
+ long int j = ...;
+ if (INT_MULTIPLY_RANGE_OVERFLOW (i, j, LONG_MIN, LONG_MAX))
+ printf ("multiply would overflow");
+ else
+ printf ("product is %ld", i * j);
+
+ Restrictions on *_RANGE_OVERFLOW macros:
+
+ These macros do not check for all possible numerical problems or
+ undefined or unspecified behavior: they do not check for division
+ by zero, for bad shift counts, or for shifting negative numbers.
+
+ These macros may evaluate their arguments zero or multiple times,
+ so the arguments should not have side effects. The arithmetic
+ arguments (including the MIN and MAX arguments) must be of the same
+ integer type after the usual arithmetic conversions, and the type
+ must have minimum value MIN and maximum MAX. Unsigned types should
+ use a zero MIN of the proper type.
+
+ These macros are tuned for constant MIN and MAX. For commutative
+ operations such as A + B, they are also tuned for constant B. */
+
+/* Return 1 if A + B would overflow in [MIN,MAX] arithmetic.
+ See above for restrictions. */
+#define INT_ADD_RANGE_OVERFLOW(a, b, min, max) \
+ ((b) < 0 \
+ ? (a) < (min) - (b) \
+ : (max) - (b) < (a))
+
+/* Return 1 if A - B would overflow in [MIN,MAX] arithmetic.
+ See above for restrictions. */
+#define INT_SUBTRACT_RANGE_OVERFLOW(a, b, min, max) \
+ ((b) < 0 \
+ ? (max) + (b) < (a) \
+ : (a) < (min) + (b))
+
+/* Return 1 if - A would overflow in [MIN,MAX] arithmetic.
+ See above for restrictions. */
+#define INT_NEGATE_RANGE_OVERFLOW(a, min, max) \
+ ((min) < 0 \
+ ? (a) < - (max) \
+ : 0 < (a))
+
+/* Return 1 if A * B would overflow in [MIN,MAX] arithmetic.
+ See above for restrictions. Avoid && and || as they tickle
+ bugs in Sun C 5.11 2010/08/13 and other compilers; see
+ <http://lists.gnu.org/archive/html/bug-gnulib/2011-05/msg00401.html>. */
+#define INT_MULTIPLY_RANGE_OVERFLOW(a, b, min, max) \
+ ((b) < 0 \
+ ? ((a) < 0 \
+ ? (a) < (max) / (b) \
+ : (b) == -1 \
+ ? 0 \
+ : (min) / (b) < (a)) \
+ : (b) == 0 \
+ ? 0 \
+ : ((a) < 0 \
+ ? (a) < (min) / (b) \
+ : (max) / (b) < (a)))
+
+/* Return 1 if A / B would overflow in [MIN,MAX] arithmetic.
+ See above for restrictions. Do not check for division by zero. */
+#define INT_DIVIDE_RANGE_OVERFLOW(a, b, min, max) \
+ ((min) < 0 && (b) == -1 && (a) < - (max))
+
+/* Return 1 if A % B would overflow in [MIN,MAX] arithmetic.
+ See above for restrictions. Do not check for division by zero.
+ Mathematically, % should never overflow, but on x86-like hosts
+ INT_MIN % -1 traps, and the C standard permits this, so treat this
+ as an overflow too. */
+#define INT_REMAINDER_RANGE_OVERFLOW(a, b, min, max) \
+ INT_DIVIDE_RANGE_OVERFLOW (a, b, min, max)
+
+/* Return 1 if A << B would overflow in [MIN,MAX] arithmetic.
+ See above for restrictions. Here, MIN and MAX are for A only, and B need
+ not be of the same type as the other arguments. The C standard says that
+ behavior is undefined for shifts unless 0 <= B < wordwidth, and that when
+ A is negative then A << B has undefined behavior and A >> B has
+ implementation-defined behavior, but do not check these other
+ restrictions. */
+#define INT_LEFT_SHIFT_RANGE_OVERFLOW(a, b, min, max) \
+ ((a) < 0 \
+ ? (a) < (min) >> (b) \
+ : (max) >> (b) < (a))
+
+
+/* The _GL*_OVERFLOW macros have the same restrictions as the
+ *_RANGE_OVERFLOW macros, except that they do not assume that operands
+ (e.g., A and B) have the same type as MIN and MAX. Instead, they assume
+ that the result (e.g., A + B) has that type. */
+#define _GL_ADD_OVERFLOW(a, b, min, max) \
+ ((min) < 0 ? INT_ADD_RANGE_OVERFLOW (a, b, min, max) \
+ : (a) < 0 ? (b) <= (a) + (b) \
+ : (b) < 0 ? (a) <= (a) + (b) \
+ : (a) + (b) < (b))
+#define _GL_SUBTRACT_OVERFLOW(a, b, min, max) \
+ ((min) < 0 ? INT_SUBTRACT_RANGE_OVERFLOW (a, b, min, max) \
+ : (a) < 0 ? 1 \
+ : (b) < 0 ? (a) - (b) <= (a) \
+ : (a) < (b))
+#define _GL_MULTIPLY_OVERFLOW(a, b, min, max) \
+ (((min) == 0 && (((a) < 0 && 0 < (b)) || ((b) < 0 && 0 < (a)))) \
+ || INT_MULTIPLY_RANGE_OVERFLOW (a, b, min, max))
+#define _GL_DIVIDE_OVERFLOW(a, b, min, max) \
+ ((min) < 0 ? (b) == _GL_INT_NEGATE_CONVERT (min, 1) && (a) < - (max) \
+ : (a) < 0 ? (b) <= (a) + (b) - 1 \
+ : (b) < 0 && (a) + (b) <= (a))
+#define _GL_REMAINDER_OVERFLOW(a, b, min, max) \
+ ((min) < 0 ? (b) == _GL_INT_NEGATE_CONVERT (min, 1) && (a) < - (max) \
+ : (a) < 0 ? (a) % (b) != ((max) - (b) + 1) % (b) \
+ : (b) < 0 && ! _GL_UNSIGNED_NEG_MULTIPLE (a, b, max))
+
+/* Return a nonzero value if A is a mathematical multiple of B, where
+ A is unsigned, B is negative, and MAX is the maximum value of A's
+ type. A's type must be the same as (A % B)'s type. Normally (A %
+ -B == 0) suffices, but things get tricky if -B would overflow. */
+#define _GL_UNSIGNED_NEG_MULTIPLE(a, b, max) \
+ (((b) < -_GL_SIGNED_INT_MAXIMUM (b) \
+ ? (_GL_SIGNED_INT_MAXIMUM (b) == (max) \
+ ? (a) \
+ : (a) % (_GL_INT_CONVERT (a, _GL_SIGNED_INT_MAXIMUM (b)) + 1)) \
+ : (a) % - (b)) \
+ == 0)
+
+/* Check for integer overflow, and report low order bits of answer.
+
+ The INT_<op>_OVERFLOW macros return 1 if the corresponding C operators
+ might not yield numerically correct answers due to arithmetic overflow.
+ The INT_<op>_WRAPV macros also store the low-order bits of the answer.
+ These macros work correctly on all known practical hosts, and do not rely
+ on undefined behavior due to signed arithmetic overflow.
+
+ Example usage, assuming A and B are long int:
+
+ if (INT_MULTIPLY_OVERFLOW (a, b))
+ printf ("result would overflow\n");
+ else
+ printf ("result is %ld (no overflow)\n", a * b);
+
+ Example usage with WRAPV flavor:
+
+ long int result;
+ bool overflow = INT_MULTIPLY_WRAPV (a, b, &result);
+ printf ("result is %ld (%s)\n", result,
+ overflow ? "after overflow" : "no overflow");
+
+ Restrictions on these macros:
+
+ These macros do not check for all possible numerical problems or
+ undefined or unspecified behavior: they do not check for division
+ by zero, for bad shift counts, or for shifting negative numbers.
+
+ These macros may evaluate their arguments zero or multiple times, so the
+ arguments should not have side effects.
+
+ The WRAPV macros are not constant expressions. They support only
+ +, binary -, and *. The result type must be signed.
+
+ These macros are tuned for their last argument being a constant.
+
+ Return 1 if the integer expressions A * B, A - B, -A, A * B, A / B,
+ A % B, and A << B would overflow, respectively. */
+
+#define INT_ADD_OVERFLOW(a, b) \
+ _GL_BINARY_OP_OVERFLOW (a, b, _GL_ADD_OVERFLOW)
+#define INT_SUBTRACT_OVERFLOW(a, b) \
+ _GL_BINARY_OP_OVERFLOW (a, b, _GL_SUBTRACT_OVERFLOW)
+#define INT_NEGATE_OVERFLOW(a) \
+ INT_NEGATE_RANGE_OVERFLOW (a, _GL_INT_MINIMUM (a), _GL_INT_MAXIMUM (a))
+#define INT_MULTIPLY_OVERFLOW(a, b) \
+ _GL_BINARY_OP_OVERFLOW (a, b, _GL_MULTIPLY_OVERFLOW)
+#define INT_DIVIDE_OVERFLOW(a, b) \
+ _GL_BINARY_OP_OVERFLOW (a, b, _GL_DIVIDE_OVERFLOW)
+#define INT_REMAINDER_OVERFLOW(a, b) \
+ _GL_BINARY_OP_OVERFLOW (a, b, _GL_REMAINDER_OVERFLOW)
+#define INT_LEFT_SHIFT_OVERFLOW(a, b) \
+ INT_LEFT_SHIFT_RANGE_OVERFLOW (a, b, \
+ _GL_INT_MINIMUM (a), _GL_INT_MAXIMUM (a))
+
+/* Return 1 if the expression A <op> B would overflow,
+ where OP_RESULT_OVERFLOW (A, B, MIN, MAX) does the actual test,
+ assuming MIN and MAX are the minimum and maximum for the result type.
+ Arguments should be free of side effects. */
+#define _GL_BINARY_OP_OVERFLOW(a, b, op_result_overflow) \
+ op_result_overflow (a, b, \
+ _GL_INT_MINIMUM (0 * (b) + (a)), \
+ _GL_INT_MAXIMUM (0 * (b) + (a)))
+
+/* Compute A + B, A - B, A * B, respectively, storing the result into *R.
+ Return 1 if the result overflows. See above for restrictions. */
+#define INT_ADD_WRAPV(a, b, r) \
+ _GL_INT_OP_WRAPV (a, b, r, +, __builtin_add_overflow, INT_ADD_OVERFLOW)
+#define INT_SUBTRACT_WRAPV(a, b, r) \
+ _GL_INT_OP_WRAPV (a, b, r, -, __builtin_sub_overflow, INT_SUBTRACT_OVERFLOW)
+#define INT_MULTIPLY_WRAPV(a, b, r) \
+ _GL_INT_OP_WRAPV (a, b, r, *, __builtin_mul_overflow, INT_MULTIPLY_OVERFLOW)
+
+#ifndef __has_builtin
+# define __has_builtin(x) 0
+#endif
+
+/* Nonzero if this compiler has GCC bug 68193 or Clang bug 25390. See:
+ https://gcc.gnu.org/bugzilla/show_bug.cgi?id=68193
+ https://llvm.org/bugs/show_bug.cgi?id=25390
+ For now, assume all versions of GCC-like compilers generate bogus
+ warnings for _Generic. This matters only for older compilers that
+ lack __builtin_add_overflow. */
+#if __GNUC__
+# define _GL__GENERIC_BOGUS 1
+#else
+# define _GL__GENERIC_BOGUS 0
+#endif
+
+/* Store A <op> B into *R, where OP specifies the operation.
+ BUILTIN is the builtin operation, and OVERFLOW the overflow predicate.
+ See above for restrictions. */
+#if 5 <= __GNUC__ || __has_builtin (__builtin_add_overflow)
+# define _GL_INT_OP_WRAPV(a, b, r, op, builtin, overflow) builtin (a, b, r)
+#elif 201112 <= __STDC_VERSION__ && !_GL__GENERIC_BOGUS
+# define _GL_INT_OP_WRAPV(a, b, r, op, builtin, overflow) \
+ (_Generic \
+ (*(r), \
+ signed char: \
+ _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned char, \
+ signed char, SCHAR_MIN, SCHAR_MAX), \
+ short int: \
+ _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned short int, \
+ short int, SHRT_MIN, SHRT_MAX), \
+ int: \
+ _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned int, \
+ int, INT_MIN, INT_MAX), \
+ long int: \
+ _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned long int, \
+ long int, LONG_MIN, LONG_MAX), \
+ long long int: \
+ _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned long long int, \
+ long long int, LLONG_MIN, LLONG_MAX)))
+#else
+# define _GL_INT_OP_WRAPV(a, b, r, op, builtin, overflow) \
+ (sizeof *(r) == sizeof (signed char) \
+ ? _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned char, \
+ signed char, SCHAR_MIN, SCHAR_MAX) \
+ : sizeof *(r) == sizeof (short int) \
+ ? _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned short int, \
+ short int, SHRT_MIN, SHRT_MAX) \
+ : sizeof *(r) == sizeof (int) \
+ ? _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned int, \
+ int, INT_MIN, INT_MAX) \
+ : _GL_INT_OP_WRAPV_LONGISH(a, b, r, op, overflow))
+# ifdef LLONG_MAX
+# define _GL_INT_OP_WRAPV_LONGISH(a, b, r, op, overflow) \
+ (sizeof *(r) == sizeof (long int) \
+ ? _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned long int, \
+ long int, LONG_MIN, LONG_MAX) \
+ : _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned long long int, \
+ long long int, LLONG_MIN, LLONG_MAX))
+# else
+# define _GL_INT_OP_WRAPV_LONGISH(a, b, r, op, overflow) \
+ _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned long int, \
+ long int, LONG_MIN, LONG_MAX))
+# endif
+#endif
+
+/* Store the low-order bits of A <op> B into *R, where the operation
+ is given by OP. Use the unsigned type UT for calculation to avoid
+ overflow problems. *R's type is T, with extremal values TMIN and
+ TMAX. T must be a signed integer type. */
+#define _GL_INT_OP_CALC(a, b, r, op, overflow, ut, t, tmin, tmax) \
+ (sizeof ((a) op (b)) < sizeof (t) \
+ ? _GL_INT_OP_CALC1 ((t) (a), (t) (b), r, op, overflow, ut, t, tmin, tmax) \
+ : _GL_INT_OP_CALC1 (a, b, r, op, overflow, ut, t, tmin, tmax))
+#define _GL_INT_OP_CALC1(a, b, r, op, overflow, ut, t, tmin, tmax) \
+ ((overflow (a, b) \
+ || (EXPR_SIGNED ((a) op (b)) && ((a) op (b)) < (tmin)) \
+ || (tmax) < ((a) op (b))) \
+ ? (*(r) = _GL_INT_OP_WRAPV_VIA_UNSIGNED (a, b, op, ut, t, tmin, tmax), 1) \
+ : (*(r) = _GL_INT_OP_WRAPV_VIA_UNSIGNED (a, b, op, ut, t, tmin, tmax), 0))
+
+/* Return A <op> B, where the operation is given by OP. Use the
+ unsigned type UT for calculation to avoid overflow problems.
+ Convert the result to type T without overflow by subtracting TMIN
+ from large values before converting, and adding it afterwards.
+ Compilers can optimize all the operations except OP. */
+#define _GL_INT_OP_WRAPV_VIA_UNSIGNED(a, b, op, ut, t, tmin, tmax) \
+ (((ut) (a) op (ut) (b)) <= (tmax) \
+ ? (t) ((ut) (a) op (ut) (b)) \
+ : ((t) (((ut) (a) op (ut) (b)) - (tmin)) + (tmin)))
+
+#endif /* _GL_INTPROPS_H */
diff --git a/lib/inttostr.c b/lib/inttostr.c
index 246d658..c96b5ca 100644
--- a/lib/inttostr.c
+++ b/lib/inttostr.c
@@ -1,51 +1,3 @@
-/* inttostr.c -- convert integers to printable strings
-
- Copyright (C) 2001, 2006 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-/* Written by Paul Eggert */
-
-#include <config.h>
-
-#include "inttostr.h"
-
-/* Convert I to a printable string in BUF, which must be at least
- INT_BUFSIZE_BOUND (INTTYPE) bytes long. Return the address of the
- printable string, which need not start at BUF. */
-
-char *
-inttostr (inttype i, char *buf)
-{
- char *p = buf + INT_STRLEN_BOUND (inttype);
- *p = 0;
-
- if (i < 0)
- {
- do
- *--p = '0' - i % 10;
- while ((i /= 10) != 0);
-
- *--p = '-';
- }
- else
- {
- do
- *--p = '0' + i % 10;
- while ((i /= 10) != 0);
- }
-
- return p;
-}
+#define anytostr inttostr
+#define inttype int
+#include "anytostr.c"
diff --git a/lib/inttostr.h b/lib/inttostr.h
index 31258ca..781ee6e 100644
--- a/lib/inttostr.h
+++ b/lib/inttostr.h
@@ -1,12 +1,11 @@
/* inttostr.h -- convert integers to printable strings
- Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006 Free Software
- Foundation, Inc.
+ Copyright (C) 2001-2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert */
@@ -24,7 +22,25 @@
#include "intprops.h"
-char *offtostr (off_t, char *);
-char *imaxtostr (intmax_t, char *);
-char *umaxtostr (uintmax_t, char *);
-char *uinttostr (unsigned int, char *);
+#ifndef __GNUC_PREREQ
+# if defined __GNUC__ && defined __GNUC_MINOR__
+# define __GNUC_PREREQ(maj, min) \
+ ((__GNUC__ << 16) + __GNUC_MINOR__ >= ((maj) << 16) + (min))
+# else
+# define __GNUC_PREREQ(maj, min) 0
+# endif
+#endif
+
+#if __GNUC_PREREQ (3,4)
+# undef __attribute_warn_unused_result__
+# define __attribute_warn_unused_result__ \
+ __attribute__ ((__warn_unused_result__))
+#else
+# define __attribute_warn_unused_result__ /* empty */
+#endif
+
+char *imaxtostr (intmax_t, char *) __attribute_warn_unused_result__;
+char *inttostr (int, char *) __attribute_warn_unused_result__;
+char *offtostr (off_t, char *) __attribute_warn_unused_result__;
+char *uinttostr (unsigned int, char *) __attribute_warn_unused_result__;
+char *umaxtostr (uintmax_t, char *) __attribute_warn_unused_result__;
diff --git a/lib/inttypes.in.h b/lib/inttypes.in.h
new file mode 100644
index 0000000..ed09db6
--- /dev/null
+++ b/lib/inttypes.in.h
@@ -0,0 +1,1144 @@
+/* Copyright (C) 2006-2016 Free Software Foundation, Inc.
+ Written by Paul Eggert, Bruno Haible, Derek Price.
+ This file is part of gnulib.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+/*
+ * ISO C 99 <inttypes.h> for platforms that lack it.
+ * <http://www.opengroup.org/susv3xbd/inttypes.h.html>
+ */
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+/* Include the original <inttypes.h> if it exists, and if this file
+ has not been included yet or if this file includes gnulib stdint.h
+ which in turn includes this file.
+ The include_next requires a split double-inclusion guard. */
+#if ! defined INTTYPES_H || defined _GL_JUST_INCLUDE_SYSTEM_INTTYPES_H
+# if @HAVE_INTTYPES_H@
+
+ /* Some pre-C++11 <stdint.h> implementations need this. */
+# if defined __cplusplus && ! defined __STDC_FORMAT_MACROS
+# define __STDC_FORMAT_MACROS 1
+# endif
+
+# @INCLUDE_NEXT@ @NEXT_INTTYPES_H@
+# endif
+#endif
+
+#if ! defined INTTYPES_H && ! defined _GL_JUST_INCLUDE_SYSTEM_INTTYPES_H
+#define INTTYPES_H
+
+/* Include <stdint.h> or the gnulib replacement.
+ But avoid namespace pollution on glibc systems. */
+#ifndef __GLIBC__
+# include <stdint.h>
+#endif
+/* Get CHAR_BIT. */
+#include <limits.h>
+/* On mingw, __USE_MINGW_ANSI_STDIO only works if <stdio.h> is also included */
+#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+# include <stdio.h>
+#endif
+
+#if !(INT_MIN == INT32_MIN && INT_MAX == INT32_MAX)
+# error "This file assumes that 'int' has exactly 32 bits. Please report your platform and compiler to <bug-gnulib@gnu.org>."
+#endif
+
+/* The definitions of _GL_FUNCDECL_RPL etc. are copied here. */
+
+/* The definition of _GL_ARG_NONNULL is copied here. */
+
+/* The definition of _GL_WARN_ON_USE is copied here. */
+
+/* 7.8.1 Macros for format specifiers */
+
+#if defined _TNS_R_TARGET
+ /* Tandem NonStop R series and compatible platforms released before
+ July 2005 support %Ld but not %lld. */
+# define _LONG_LONG_FORMAT_PREFIX "L"
+#else
+# define _LONG_LONG_FORMAT_PREFIX "ll"
+#endif
+
+#if !defined PRId8 || @PRI_MACROS_BROKEN@
+# undef PRId8
+# ifdef INT8_MAX
+# define PRId8 "d"
+# endif
+#endif
+#if !defined PRIi8 || @PRI_MACROS_BROKEN@
+# undef PRIi8
+# ifdef INT8_MAX
+# define PRIi8 "i"
+# endif
+#endif
+#if !defined PRIo8 || @PRI_MACROS_BROKEN@
+# undef PRIo8
+# ifdef UINT8_MAX
+# define PRIo8 "o"
+# endif
+#endif
+#if !defined PRIu8 || @PRI_MACROS_BROKEN@
+# undef PRIu8
+# ifdef UINT8_MAX
+# define PRIu8 "u"
+# endif
+#endif
+#if !defined PRIx8 || @PRI_MACROS_BROKEN@
+# undef PRIx8
+# ifdef UINT8_MAX
+# define PRIx8 "x"
+# endif
+#endif
+#if !defined PRIX8 || @PRI_MACROS_BROKEN@
+# undef PRIX8
+# ifdef UINT8_MAX
+# define PRIX8 "X"
+# endif
+#endif
+#if !defined PRId16 || @PRI_MACROS_BROKEN@
+# undef PRId16
+# ifdef INT16_MAX
+# define PRId16 "d"
+# endif
+#endif
+#if !defined PRIi16 || @PRI_MACROS_BROKEN@
+# undef PRIi16
+# ifdef INT16_MAX
+# define PRIi16 "i"
+# endif
+#endif
+#if !defined PRIo16 || @PRI_MACROS_BROKEN@
+# undef PRIo16
+# ifdef UINT16_MAX
+# define PRIo16 "o"
+# endif
+#endif
+#if !defined PRIu16 || @PRI_MACROS_BROKEN@
+# undef PRIu16
+# ifdef UINT16_MAX
+# define PRIu16 "u"
+# endif
+#endif
+#if !defined PRIx16 || @PRI_MACROS_BROKEN@
+# undef PRIx16
+# ifdef UINT16_MAX
+# define PRIx16 "x"
+# endif
+#endif
+#if !defined PRIX16 || @PRI_MACROS_BROKEN@
+# undef PRIX16
+# ifdef UINT16_MAX
+# define PRIX16 "X"
+# endif
+#endif
+#if !defined PRId32 || @PRI_MACROS_BROKEN@
+# undef PRId32
+# ifdef INT32_MAX
+# define PRId32 "d"
+# endif
+#endif
+#if !defined PRIi32 || @PRI_MACROS_BROKEN@
+# undef PRIi32
+# ifdef INT32_MAX
+# define PRIi32 "i"
+# endif
+#endif
+#if !defined PRIo32 || @PRI_MACROS_BROKEN@
+# undef PRIo32
+# ifdef UINT32_MAX
+# define PRIo32 "o"
+# endif
+#endif
+#if !defined PRIu32 || @PRI_MACROS_BROKEN@
+# undef PRIu32
+# ifdef UINT32_MAX
+# define PRIu32 "u"
+# endif
+#endif
+#if !defined PRIx32 || @PRI_MACROS_BROKEN@
+# undef PRIx32
+# ifdef UINT32_MAX
+# define PRIx32 "x"
+# endif
+#endif
+#if !defined PRIX32 || @PRI_MACROS_BROKEN@
+# undef PRIX32
+# ifdef UINT32_MAX
+# define PRIX32 "X"
+# endif
+#endif
+#ifdef INT64_MAX
+# if (@APPLE_UNIVERSAL_BUILD@ ? defined _LP64 : @INT64_MAX_EQ_LONG_MAX@)
+# define _PRI64_PREFIX "l"
+# elif defined _MSC_VER || defined __MINGW32__
+# define _PRI64_PREFIX "I64"
+# elif @HAVE_LONG_LONG_INT@ && LONG_MAX >> 30 == 1
+# define _PRI64_PREFIX _LONG_LONG_FORMAT_PREFIX
+# endif
+# if !defined PRId64 || @PRI_MACROS_BROKEN@
+# undef PRId64
+# define PRId64 _PRI64_PREFIX "d"
+# endif
+# if !defined PRIi64 || @PRI_MACROS_BROKEN@
+# undef PRIi64
+# define PRIi64 _PRI64_PREFIX "i"
+# endif
+#endif
+#ifdef UINT64_MAX
+# if (@APPLE_UNIVERSAL_BUILD@ ? defined _LP64 : @UINT64_MAX_EQ_ULONG_MAX@)
+# define _PRIu64_PREFIX "l"
+# elif defined _MSC_VER || defined __MINGW32__
+# define _PRIu64_PREFIX "I64"
+# elif @HAVE_UNSIGNED_LONG_LONG_INT@ && ULONG_MAX >> 31 == 1
+# define _PRIu64_PREFIX _LONG_LONG_FORMAT_PREFIX
+# endif
+# if !defined PRIo64 || @PRI_MACROS_BROKEN@
+# undef PRIo64
+# define PRIo64 _PRIu64_PREFIX "o"
+# endif
+# if !defined PRIu64 || @PRI_MACROS_BROKEN@
+# undef PRIu64
+# define PRIu64 _PRIu64_PREFIX "u"
+# endif
+# if !defined PRIx64 || @PRI_MACROS_BROKEN@
+# undef PRIx64
+# define PRIx64 _PRIu64_PREFIX "x"
+# endif
+# if !defined PRIX64 || @PRI_MACROS_BROKEN@
+# undef PRIX64
+# define PRIX64 _PRIu64_PREFIX "X"
+# endif
+#endif
+
+#if !defined PRIdLEAST8 || @PRI_MACROS_BROKEN@
+# undef PRIdLEAST8
+# define PRIdLEAST8 "d"
+#endif
+#if !defined PRIiLEAST8 || @PRI_MACROS_BROKEN@
+# undef PRIiLEAST8
+# define PRIiLEAST8 "i"
+#endif
+#if !defined PRIoLEAST8 || @PRI_MACROS_BROKEN@
+# undef PRIoLEAST8
+# define PRIoLEAST8 "o"
+#endif
+#if !defined PRIuLEAST8 || @PRI_MACROS_BROKEN@
+# undef PRIuLEAST8
+# define PRIuLEAST8 "u"
+#endif
+#if !defined PRIxLEAST8 || @PRI_MACROS_BROKEN@
+# undef PRIxLEAST8
+# define PRIxLEAST8 "x"
+#endif
+#if !defined PRIXLEAST8 || @PRI_MACROS_BROKEN@
+# undef PRIXLEAST8
+# define PRIXLEAST8 "X"
+#endif
+#if !defined PRIdLEAST16 || @PRI_MACROS_BROKEN@
+# undef PRIdLEAST16
+# define PRIdLEAST16 "d"
+#endif
+#if !defined PRIiLEAST16 || @PRI_MACROS_BROKEN@
+# undef PRIiLEAST16
+# define PRIiLEAST16 "i"
+#endif
+#if !defined PRIoLEAST16 || @PRI_MACROS_BROKEN@
+# undef PRIoLEAST16
+# define PRIoLEAST16 "o"
+#endif
+#if !defined PRIuLEAST16 || @PRI_MACROS_BROKEN@
+# undef PRIuLEAST16
+# define PRIuLEAST16 "u"
+#endif
+#if !defined PRIxLEAST16 || @PRI_MACROS_BROKEN@
+# undef PRIxLEAST16
+# define PRIxLEAST16 "x"
+#endif
+#if !defined PRIXLEAST16 || @PRI_MACROS_BROKEN@
+# undef PRIXLEAST16
+# define PRIXLEAST16 "X"
+#endif
+#if !defined PRIdLEAST32 || @PRI_MACROS_BROKEN@
+# undef PRIdLEAST32
+# define PRIdLEAST32 "d"
+#endif
+#if !defined PRIiLEAST32 || @PRI_MACROS_BROKEN@
+# undef PRIiLEAST32
+# define PRIiLEAST32 "i"
+#endif
+#if !defined PRIoLEAST32 || @PRI_MACROS_BROKEN@
+# undef PRIoLEAST32
+# define PRIoLEAST32 "o"
+#endif
+#if !defined PRIuLEAST32 || @PRI_MACROS_BROKEN@
+# undef PRIuLEAST32
+# define PRIuLEAST32 "u"
+#endif
+#if !defined PRIxLEAST32 || @PRI_MACROS_BROKEN@
+# undef PRIxLEAST32
+# define PRIxLEAST32 "x"
+#endif
+#if !defined PRIXLEAST32 || @PRI_MACROS_BROKEN@
+# undef PRIXLEAST32
+# define PRIXLEAST32 "X"
+#endif
+#ifdef INT64_MAX
+# if !defined PRIdLEAST64 || @PRI_MACROS_BROKEN@
+# undef PRIdLEAST64
+# define PRIdLEAST64 PRId64
+# endif
+# if !defined PRIiLEAST64 || @PRI_MACROS_BROKEN@
+# undef PRIiLEAST64
+# define PRIiLEAST64 PRIi64
+# endif
+#endif
+#ifdef UINT64_MAX
+# if !defined PRIoLEAST64 || @PRI_MACROS_BROKEN@
+# undef PRIoLEAST64
+# define PRIoLEAST64 PRIo64
+# endif
+# if !defined PRIuLEAST64 || @PRI_MACROS_BROKEN@
+# undef PRIuLEAST64
+# define PRIuLEAST64 PRIu64
+# endif
+# if !defined PRIxLEAST64 || @PRI_MACROS_BROKEN@
+# undef PRIxLEAST64
+# define PRIxLEAST64 PRIx64
+# endif
+# if !defined PRIXLEAST64 || @PRI_MACROS_BROKEN@
+# undef PRIXLEAST64
+# define PRIXLEAST64 PRIX64
+# endif
+#endif
+
+#if !defined PRIdFAST8 || @PRI_MACROS_BROKEN@
+# undef PRIdFAST8
+# if INT_FAST8_MAX > INT32_MAX
+# define PRIdFAST8 PRId64
+# else
+# define PRIdFAST8 "d"
+# endif
+#endif
+#if !defined PRIiFAST8 || @PRI_MACROS_BROKEN@
+# undef PRIiFAST8
+# if INT_FAST8_MAX > INT32_MAX
+# define PRIiFAST8 PRIi64
+# else
+# define PRIiFAST8 "i"
+# endif
+#endif
+#if !defined PRIoFAST8 || @PRI_MACROS_BROKEN@
+# undef PRIoFAST8
+# if UINT_FAST8_MAX > UINT32_MAX
+# define PRIoFAST8 PRIo64
+# else
+# define PRIoFAST8 "o"
+# endif
+#endif
+#if !defined PRIuFAST8 || @PRI_MACROS_BROKEN@
+# undef PRIuFAST8
+# if UINT_FAST8_MAX > UINT32_MAX
+# define PRIuFAST8 PRIu64
+# else
+# define PRIuFAST8 "u"
+# endif
+#endif
+#if !defined PRIxFAST8 || @PRI_MACROS_BROKEN@
+# undef PRIxFAST8
+# if UINT_FAST8_MAX > UINT32_MAX
+# define PRIxFAST8 PRIx64
+# else
+# define PRIxFAST8 "x"
+# endif
+#endif
+#if !defined PRIXFAST8 || @PRI_MACROS_BROKEN@
+# undef PRIXFAST8
+# if UINT_FAST8_MAX > UINT32_MAX
+# define PRIXFAST8 PRIX64
+# else
+# define PRIXFAST8 "X"
+# endif
+#endif
+#if !defined PRIdFAST16 || @PRI_MACROS_BROKEN@
+# undef PRIdFAST16
+# if INT_FAST16_MAX > INT32_MAX
+# define PRIdFAST16 PRId64
+# else
+# define PRIdFAST16 "d"
+# endif
+#endif
+#if !defined PRIiFAST16 || @PRI_MACROS_BROKEN@
+# undef PRIiFAST16
+# if INT_FAST16_MAX > INT32_MAX
+# define PRIiFAST16 PRIi64
+# else
+# define PRIiFAST16 "i"
+# endif
+#endif
+#if !defined PRIoFAST16 || @PRI_MACROS_BROKEN@
+# undef PRIoFAST16
+# if UINT_FAST16_MAX > UINT32_MAX
+# define PRIoFAST16 PRIo64
+# else
+# define PRIoFAST16 "o"
+# endif
+#endif
+#if !defined PRIuFAST16 || @PRI_MACROS_BROKEN@
+# undef PRIuFAST16
+# if UINT_FAST16_MAX > UINT32_MAX
+# define PRIuFAST16 PRIu64
+# else
+# define PRIuFAST16 "u"
+# endif
+#endif
+#if !defined PRIxFAST16 || @PRI_MACROS_BROKEN@
+# undef PRIxFAST16
+# if UINT_FAST16_MAX > UINT32_MAX
+# define PRIxFAST16 PRIx64
+# else
+# define PRIxFAST16 "x"
+# endif
+#endif
+#if !defined PRIXFAST16 || @PRI_MACROS_BROKEN@
+# undef PRIXFAST16
+# if UINT_FAST16_MAX > UINT32_MAX
+# define PRIXFAST16 PRIX64
+# else
+# define PRIXFAST16 "X"
+# endif
+#endif
+#if !defined PRIdFAST32 || @PRI_MACROS_BROKEN@
+# undef PRIdFAST32
+# if INT_FAST32_MAX > INT32_MAX
+# define PRIdFAST32 PRId64
+# else
+# define PRIdFAST32 "d"
+# endif
+#endif
+#if !defined PRIiFAST32 || @PRI_MACROS_BROKEN@
+# undef PRIiFAST32
+# if INT_FAST32_MAX > INT32_MAX
+# define PRIiFAST32 PRIi64
+# else
+# define PRIiFAST32 "i"
+# endif
+#endif
+#if !defined PRIoFAST32 || @PRI_MACROS_BROKEN@
+# undef PRIoFAST32
+# if UINT_FAST32_MAX > UINT32_MAX
+# define PRIoFAST32 PRIo64
+# else
+# define PRIoFAST32 "o"
+# endif
+#endif
+#if !defined PRIuFAST32 || @PRI_MACROS_BROKEN@
+# undef PRIuFAST32
+# if UINT_FAST32_MAX > UINT32_MAX
+# define PRIuFAST32 PRIu64
+# else
+# define PRIuFAST32 "u"
+# endif
+#endif
+#if !defined PRIxFAST32 || @PRI_MACROS_BROKEN@
+# undef PRIxFAST32
+# if UINT_FAST32_MAX > UINT32_MAX
+# define PRIxFAST32 PRIx64
+# else
+# define PRIxFAST32 "x"
+# endif
+#endif
+#if !defined PRIXFAST32 || @PRI_MACROS_BROKEN@
+# undef PRIXFAST32
+# if UINT_FAST32_MAX > UINT32_MAX
+# define PRIXFAST32 PRIX64
+# else
+# define PRIXFAST32 "X"
+# endif
+#endif
+#ifdef INT64_MAX
+# if !defined PRIdFAST64 || @PRI_MACROS_BROKEN@
+# undef PRIdFAST64
+# define PRIdFAST64 PRId64
+# endif
+# if !defined PRIiFAST64 || @PRI_MACROS_BROKEN@
+# undef PRIiFAST64
+# define PRIiFAST64 PRIi64
+# endif
+#endif
+#ifdef UINT64_MAX
+# if !defined PRIoFAST64 || @PRI_MACROS_BROKEN@
+# undef PRIoFAST64
+# define PRIoFAST64 PRIo64
+# endif
+# if !defined PRIuFAST64 || @PRI_MACROS_BROKEN@
+# undef PRIuFAST64
+# define PRIuFAST64 PRIu64
+# endif
+# if !defined PRIxFAST64 || @PRI_MACROS_BROKEN@
+# undef PRIxFAST64
+# define PRIxFAST64 PRIx64
+# endif
+# if !defined PRIXFAST64 || @PRI_MACROS_BROKEN@
+# undef PRIXFAST64
+# define PRIXFAST64 PRIX64
+# endif
+#endif
+
+#if !defined PRIdMAX || @PRI_MACROS_BROKEN@
+# undef PRIdMAX
+# if @INT32_MAX_LT_INTMAX_MAX@
+# define PRIdMAX PRId64
+# else
+# define PRIdMAX "ld"
+# endif
+#endif
+#if !defined PRIiMAX || @PRI_MACROS_BROKEN@
+# undef PRIiMAX
+# if @INT32_MAX_LT_INTMAX_MAX@
+# define PRIiMAX PRIi64
+# else
+# define PRIiMAX "li"
+# endif
+#endif
+#if !defined PRIoMAX || @PRI_MACROS_BROKEN@
+# undef PRIoMAX
+# if @UINT32_MAX_LT_UINTMAX_MAX@
+# define PRIoMAX PRIo64
+# else
+# define PRIoMAX "lo"
+# endif
+#endif
+#if !defined PRIuMAX || @PRI_MACROS_BROKEN@
+# undef PRIuMAX
+# if @UINT32_MAX_LT_UINTMAX_MAX@
+# define PRIuMAX PRIu64
+# else
+# define PRIuMAX "lu"
+# endif
+#endif
+#if !defined PRIxMAX || @PRI_MACROS_BROKEN@
+# undef PRIxMAX
+# if @UINT32_MAX_LT_UINTMAX_MAX@
+# define PRIxMAX PRIx64
+# else
+# define PRIxMAX "lx"
+# endif
+#endif
+#if !defined PRIXMAX || @PRI_MACROS_BROKEN@
+# undef PRIXMAX
+# if @UINT32_MAX_LT_UINTMAX_MAX@
+# define PRIXMAX PRIX64
+# else
+# define PRIXMAX "lX"
+# endif
+#endif
+
+#if !defined PRIdPTR || @PRI_MACROS_BROKEN@
+# undef PRIdPTR
+# ifdef INTPTR_MAX
+# define PRIdPTR @PRIPTR_PREFIX@ "d"
+# endif
+#endif
+#if !defined PRIiPTR || @PRI_MACROS_BROKEN@
+# undef PRIiPTR
+# ifdef INTPTR_MAX
+# define PRIiPTR @PRIPTR_PREFIX@ "i"
+# endif
+#endif
+#if !defined PRIoPTR || @PRI_MACROS_BROKEN@
+# undef PRIoPTR
+# ifdef UINTPTR_MAX
+# define PRIoPTR @PRIPTR_PREFIX@ "o"
+# endif
+#endif
+#if !defined PRIuPTR || @PRI_MACROS_BROKEN@
+# undef PRIuPTR
+# ifdef UINTPTR_MAX
+# define PRIuPTR @PRIPTR_PREFIX@ "u"
+# endif
+#endif
+#if !defined PRIxPTR || @PRI_MACROS_BROKEN@
+# undef PRIxPTR
+# ifdef UINTPTR_MAX
+# define PRIxPTR @PRIPTR_PREFIX@ "x"
+# endif
+#endif
+#if !defined PRIXPTR || @PRI_MACROS_BROKEN@
+# undef PRIXPTR
+# ifdef UINTPTR_MAX
+# define PRIXPTR @PRIPTR_PREFIX@ "X"
+# endif
+#endif
+
+#if !defined SCNd8 || @PRI_MACROS_BROKEN@
+# undef SCNd8
+# ifdef INT8_MAX
+# define SCNd8 "hhd"
+# endif
+#endif
+#if !defined SCNi8 || @PRI_MACROS_BROKEN@
+# undef SCNi8
+# ifdef INT8_MAX
+# define SCNi8 "hhi"
+# endif
+#endif
+#if !defined SCNo8 || @PRI_MACROS_BROKEN@
+# undef SCNo8
+# ifdef UINT8_MAX
+# define SCNo8 "hho"
+# endif
+#endif
+#if !defined SCNu8 || @PRI_MACROS_BROKEN@
+# undef SCNu8
+# ifdef UINT8_MAX
+# define SCNu8 "hhu"
+# endif
+#endif
+#if !defined SCNx8 || @PRI_MACROS_BROKEN@
+# undef SCNx8
+# ifdef UINT8_MAX
+# define SCNx8 "hhx"
+# endif
+#endif
+#if !defined SCNd16 || @PRI_MACROS_BROKEN@
+# undef SCNd16
+# ifdef INT16_MAX
+# define SCNd16 "hd"
+# endif
+#endif
+#if !defined SCNi16 || @PRI_MACROS_BROKEN@
+# undef SCNi16
+# ifdef INT16_MAX
+# define SCNi16 "hi"
+# endif
+#endif
+#if !defined SCNo16 || @PRI_MACROS_BROKEN@
+# undef SCNo16
+# ifdef UINT16_MAX
+# define SCNo16 "ho"
+# endif
+#endif
+#if !defined SCNu16 || @PRI_MACROS_BROKEN@
+# undef SCNu16
+# ifdef UINT16_MAX
+# define SCNu16 "hu"
+# endif
+#endif
+#if !defined SCNx16 || @PRI_MACROS_BROKEN@
+# undef SCNx16
+# ifdef UINT16_MAX
+# define SCNx16 "hx"
+# endif
+#endif
+#if !defined SCNd32 || @PRI_MACROS_BROKEN@
+# undef SCNd32
+# ifdef INT32_MAX
+# define SCNd32 "d"
+# endif
+#endif
+#if !defined SCNi32 || @PRI_MACROS_BROKEN@
+# undef SCNi32
+# ifdef INT32_MAX
+# define SCNi32 "i"
+# endif
+#endif
+#if !defined SCNo32 || @PRI_MACROS_BROKEN@
+# undef SCNo32
+# ifdef UINT32_MAX
+# define SCNo32 "o"
+# endif
+#endif
+#if !defined SCNu32 || @PRI_MACROS_BROKEN@
+# undef SCNu32
+# ifdef UINT32_MAX
+# define SCNu32 "u"
+# endif
+#endif
+#if !defined SCNx32 || @PRI_MACROS_BROKEN@
+# undef SCNx32
+# ifdef UINT32_MAX
+# define SCNx32 "x"
+# endif
+#endif
+#ifdef INT64_MAX
+# if (@APPLE_UNIVERSAL_BUILD@ ? defined _LP64 : @INT64_MAX_EQ_LONG_MAX@)
+# define _SCN64_PREFIX "l"
+# elif defined _MSC_VER || defined __MINGW32__
+# define _SCN64_PREFIX "I64"
+# elif @HAVE_LONG_LONG_INT@ && LONG_MAX >> 30 == 1
+# define _SCN64_PREFIX _LONG_LONG_FORMAT_PREFIX
+# endif
+# if !defined SCNd64 || @PRI_MACROS_BROKEN@
+# undef SCNd64
+# define SCNd64 _SCN64_PREFIX "d"
+# endif
+# if !defined SCNi64 || @PRI_MACROS_BROKEN@
+# undef SCNi64
+# define SCNi64 _SCN64_PREFIX "i"
+# endif
+#endif
+#ifdef UINT64_MAX
+# if (@APPLE_UNIVERSAL_BUILD@ ? defined _LP64 : @UINT64_MAX_EQ_ULONG_MAX@)
+# define _SCNu64_PREFIX "l"
+# elif defined _MSC_VER || defined __MINGW32__
+# define _SCNu64_PREFIX "I64"
+# elif @HAVE_UNSIGNED_LONG_LONG_INT@ && ULONG_MAX >> 31 == 1
+# define _SCNu64_PREFIX _LONG_LONG_FORMAT_PREFIX
+# endif
+# if !defined SCNo64 || @PRI_MACROS_BROKEN@
+# undef SCNo64
+# define SCNo64 _SCNu64_PREFIX "o"
+# endif
+# if !defined SCNu64 || @PRI_MACROS_BROKEN@
+# undef SCNu64
+# define SCNu64 _SCNu64_PREFIX "u"
+# endif
+# if !defined SCNx64 || @PRI_MACROS_BROKEN@
+# undef SCNx64
+# define SCNx64 _SCNu64_PREFIX "x"
+# endif
+#endif
+
+#if !defined SCNdLEAST8 || @PRI_MACROS_BROKEN@
+# undef SCNdLEAST8
+# define SCNdLEAST8 "hhd"
+#endif
+#if !defined SCNiLEAST8 || @PRI_MACROS_BROKEN@
+# undef SCNiLEAST8
+# define SCNiLEAST8 "hhi"
+#endif
+#if !defined SCNoLEAST8 || @PRI_MACROS_BROKEN@
+# undef SCNoLEAST8
+# define SCNoLEAST8 "hho"
+#endif
+#if !defined SCNuLEAST8 || @PRI_MACROS_BROKEN@
+# undef SCNuLEAST8
+# define SCNuLEAST8 "hhu"
+#endif
+#if !defined SCNxLEAST8 || @PRI_MACROS_BROKEN@
+# undef SCNxLEAST8
+# define SCNxLEAST8 "hhx"
+#endif
+#if !defined SCNdLEAST16 || @PRI_MACROS_BROKEN@
+# undef SCNdLEAST16
+# define SCNdLEAST16 "hd"
+#endif
+#if !defined SCNiLEAST16 || @PRI_MACROS_BROKEN@
+# undef SCNiLEAST16
+# define SCNiLEAST16 "hi"
+#endif
+#if !defined SCNoLEAST16 || @PRI_MACROS_BROKEN@
+# undef SCNoLEAST16
+# define SCNoLEAST16 "ho"
+#endif
+#if !defined SCNuLEAST16 || @PRI_MACROS_BROKEN@
+# undef SCNuLEAST16
+# define SCNuLEAST16 "hu"
+#endif
+#if !defined SCNxLEAST16 || @PRI_MACROS_BROKEN@
+# undef SCNxLEAST16
+# define SCNxLEAST16 "hx"
+#endif
+#if !defined SCNdLEAST32 || @PRI_MACROS_BROKEN@
+# undef SCNdLEAST32
+# define SCNdLEAST32 "d"
+#endif
+#if !defined SCNiLEAST32 || @PRI_MACROS_BROKEN@
+# undef SCNiLEAST32
+# define SCNiLEAST32 "i"
+#endif
+#if !defined SCNoLEAST32 || @PRI_MACROS_BROKEN@
+# undef SCNoLEAST32
+# define SCNoLEAST32 "o"
+#endif
+#if !defined SCNuLEAST32 || @PRI_MACROS_BROKEN@
+# undef SCNuLEAST32
+# define SCNuLEAST32 "u"
+#endif
+#if !defined SCNxLEAST32 || @PRI_MACROS_BROKEN@
+# undef SCNxLEAST32
+# define SCNxLEAST32 "x"
+#endif
+#ifdef INT64_MAX
+# if !defined SCNdLEAST64 || @PRI_MACROS_BROKEN@
+# undef SCNdLEAST64
+# define SCNdLEAST64 SCNd64
+# endif
+# if !defined SCNiLEAST64 || @PRI_MACROS_BROKEN@
+# undef SCNiLEAST64
+# define SCNiLEAST64 SCNi64
+# endif
+#endif
+#ifdef UINT64_MAX
+# if !defined SCNoLEAST64 || @PRI_MACROS_BROKEN@
+# undef SCNoLEAST64
+# define SCNoLEAST64 SCNo64
+# endif
+# if !defined SCNuLEAST64 || @PRI_MACROS_BROKEN@
+# undef SCNuLEAST64
+# define SCNuLEAST64 SCNu64
+# endif
+# if !defined SCNxLEAST64 || @PRI_MACROS_BROKEN@
+# undef SCNxLEAST64
+# define SCNxLEAST64 SCNx64
+# endif
+#endif
+
+#if !defined SCNdFAST8 || @PRI_MACROS_BROKEN@
+# undef SCNdFAST8
+# if INT_FAST8_MAX > INT32_MAX
+# define SCNdFAST8 SCNd64
+# elif INT_FAST8_MAX == 0x7fff
+# define SCNdFAST8 "hd"
+# elif INT_FAST8_MAX == 0x7f
+# define SCNdFAST8 "hhd"
+# else
+# define SCNdFAST8 "d"
+# endif
+#endif
+#if !defined SCNiFAST8 || @PRI_MACROS_BROKEN@
+# undef SCNiFAST8
+# if INT_FAST8_MAX > INT32_MAX
+# define SCNiFAST8 SCNi64
+# elif INT_FAST8_MAX == 0x7fff
+# define SCNiFAST8 "hi"
+# elif INT_FAST8_MAX == 0x7f
+# define SCNiFAST8 "hhi"
+# else
+# define SCNiFAST8 "i"
+# endif
+#endif
+#if !defined SCNoFAST8 || @PRI_MACROS_BROKEN@
+# undef SCNoFAST8
+# if UINT_FAST8_MAX > UINT32_MAX
+# define SCNoFAST8 SCNo64
+# elif UINT_FAST8_MAX == 0xffff
+# define SCNoFAST8 "ho"
+# elif UINT_FAST8_MAX == 0xff
+# define SCNoFAST8 "hho"
+# else
+# define SCNoFAST8 "o"
+# endif
+#endif
+#if !defined SCNuFAST8 || @PRI_MACROS_BROKEN@
+# undef SCNuFAST8
+# if UINT_FAST8_MAX > UINT32_MAX
+# define SCNuFAST8 SCNu64
+# elif UINT_FAST8_MAX == 0xffff
+# define SCNuFAST8 "hu"
+# elif UINT_FAST8_MAX == 0xff
+# define SCNuFAST8 "hhu"
+# else
+# define SCNuFAST8 "u"
+# endif
+#endif
+#if !defined SCNxFAST8 || @PRI_MACROS_BROKEN@
+# undef SCNxFAST8
+# if UINT_FAST8_MAX > UINT32_MAX
+# define SCNxFAST8 SCNx64
+# elif UINT_FAST8_MAX == 0xffff
+# define SCNxFAST8 "hx"
+# elif UINT_FAST8_MAX == 0xff
+# define SCNxFAST8 "hhx"
+# else
+# define SCNxFAST8 "x"
+# endif
+#endif
+#if !defined SCNdFAST16 || @PRI_MACROS_BROKEN@
+# undef SCNdFAST16
+# if INT_FAST16_MAX > INT32_MAX
+# define SCNdFAST16 SCNd64
+# elif INT_FAST16_MAX == 0x7fff
+# define SCNdFAST16 "hd"
+# else
+# define SCNdFAST16 "d"
+# endif
+#endif
+#if !defined SCNiFAST16 || @PRI_MACROS_BROKEN@
+# undef SCNiFAST16
+# if INT_FAST16_MAX > INT32_MAX
+# define SCNiFAST16 SCNi64
+# elif INT_FAST16_MAX == 0x7fff
+# define SCNiFAST16 "hi"
+# else
+# define SCNiFAST16 "i"
+# endif
+#endif
+#if !defined SCNoFAST16 || @PRI_MACROS_BROKEN@
+# undef SCNoFAST16
+# if UINT_FAST16_MAX > UINT32_MAX
+# define SCNoFAST16 SCNo64
+# elif UINT_FAST16_MAX == 0xffff
+# define SCNoFAST16 "ho"
+# else
+# define SCNoFAST16 "o"
+# endif
+#endif
+#if !defined SCNuFAST16 || @PRI_MACROS_BROKEN@
+# undef SCNuFAST16
+# if UINT_FAST16_MAX > UINT32_MAX
+# define SCNuFAST16 SCNu64
+# elif UINT_FAST16_MAX == 0xffff
+# define SCNuFAST16 "hu"
+# else
+# define SCNuFAST16 "u"
+# endif
+#endif
+#if !defined SCNxFAST16 || @PRI_MACROS_BROKEN@
+# undef SCNxFAST16
+# if UINT_FAST16_MAX > UINT32_MAX
+# define SCNxFAST16 SCNx64
+# elif UINT_FAST16_MAX == 0xffff
+# define SCNxFAST16 "hx"
+# else
+# define SCNxFAST16 "x"
+# endif
+#endif
+#if !defined SCNdFAST32 || @PRI_MACROS_BROKEN@
+# undef SCNdFAST32
+# if INT_FAST32_MAX > INT32_MAX
+# define SCNdFAST32 SCNd64
+# else
+# define SCNdFAST32 "d"
+# endif
+#endif
+#if !defined SCNiFAST32 || @PRI_MACROS_BROKEN@
+# undef SCNiFAST32
+# if INT_FAST32_MAX > INT32_MAX
+# define SCNiFAST32 SCNi64
+# else
+# define SCNiFAST32 "i"
+# endif
+#endif
+#if !defined SCNoFAST32 || @PRI_MACROS_BROKEN@
+# undef SCNoFAST32
+# if UINT_FAST32_MAX > UINT32_MAX
+# define SCNoFAST32 SCNo64
+# else
+# define SCNoFAST32 "o"
+# endif
+#endif
+#if !defined SCNuFAST32 || @PRI_MACROS_BROKEN@
+# undef SCNuFAST32
+# if UINT_FAST32_MAX > UINT32_MAX
+# define SCNuFAST32 SCNu64
+# else
+# define SCNuFAST32 "u"
+# endif
+#endif
+#if !defined SCNxFAST32 || @PRI_MACROS_BROKEN@
+# undef SCNxFAST32
+# if UINT_FAST32_MAX > UINT32_MAX
+# define SCNxFAST32 SCNx64
+# else
+# define SCNxFAST32 "x"
+# endif
+#endif
+#ifdef INT64_MAX
+# if !defined SCNdFAST64 || @PRI_MACROS_BROKEN@
+# undef SCNdFAST64
+# define SCNdFAST64 SCNd64
+# endif
+# if !defined SCNiFAST64 || @PRI_MACROS_BROKEN@
+# undef SCNiFAST64
+# define SCNiFAST64 SCNi64
+# endif
+#endif
+#ifdef UINT64_MAX
+# if !defined SCNoFAST64 || @PRI_MACROS_BROKEN@
+# undef SCNoFAST64
+# define SCNoFAST64 SCNo64
+# endif
+# if !defined SCNuFAST64 || @PRI_MACROS_BROKEN@
+# undef SCNuFAST64
+# define SCNuFAST64 SCNu64
+# endif
+# if !defined SCNxFAST64 || @PRI_MACROS_BROKEN@
+# undef SCNxFAST64
+# define SCNxFAST64 SCNx64
+# endif
+#endif
+
+#if !defined SCNdMAX || @PRI_MACROS_BROKEN@
+# undef SCNdMAX
+# if @INT32_MAX_LT_INTMAX_MAX@
+# define SCNdMAX SCNd64
+# else
+# define SCNdMAX "ld"
+# endif
+#endif
+#if !defined SCNiMAX || @PRI_MACROS_BROKEN@
+# undef SCNiMAX
+# if @INT32_MAX_LT_INTMAX_MAX@
+# define SCNiMAX SCNi64
+# else
+# define SCNiMAX "li"
+# endif
+#endif
+#if !defined SCNoMAX || @PRI_MACROS_BROKEN@
+# undef SCNoMAX
+# if @UINT32_MAX_LT_UINTMAX_MAX@
+# define SCNoMAX SCNo64
+# else
+# define SCNoMAX "lo"
+# endif
+#endif
+#if !defined SCNuMAX || @PRI_MACROS_BROKEN@
+# undef SCNuMAX
+# if @UINT32_MAX_LT_UINTMAX_MAX@
+# define SCNuMAX SCNu64
+# else
+# define SCNuMAX "lu"
+# endif
+#endif
+#if !defined SCNxMAX || @PRI_MACROS_BROKEN@
+# undef SCNxMAX
+# if @UINT32_MAX_LT_UINTMAX_MAX@
+# define SCNxMAX SCNx64
+# else
+# define SCNxMAX "lx"
+# endif
+#endif
+
+#if !defined SCNdPTR || @PRI_MACROS_BROKEN@
+# undef SCNdPTR
+# ifdef INTPTR_MAX
+# define SCNdPTR @PRIPTR_PREFIX@ "d"
+# endif
+#endif
+#if !defined SCNiPTR || @PRI_MACROS_BROKEN@
+# undef SCNiPTR
+# ifdef INTPTR_MAX
+# define SCNiPTR @PRIPTR_PREFIX@ "i"
+# endif
+#endif
+#if !defined SCNoPTR || @PRI_MACROS_BROKEN@
+# undef SCNoPTR
+# ifdef UINTPTR_MAX
+# define SCNoPTR @PRIPTR_PREFIX@ "o"
+# endif
+#endif
+#if !defined SCNuPTR || @PRI_MACROS_BROKEN@
+# undef SCNuPTR
+# ifdef UINTPTR_MAX
+# define SCNuPTR @PRIPTR_PREFIX@ "u"
+# endif
+#endif
+#if !defined SCNxPTR || @PRI_MACROS_BROKEN@
+# undef SCNxPTR
+# ifdef UINTPTR_MAX
+# define SCNxPTR @PRIPTR_PREFIX@ "x"
+# endif
+#endif
+
+/* 7.8.2 Functions for greatest-width integer types */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if @GNULIB_IMAXABS@
+# if !@HAVE_DECL_IMAXABS@
+extern intmax_t imaxabs (intmax_t);
+# endif
+#elif defined GNULIB_POSIXCHECK
+# undef imaxabs
+# if HAVE_RAW_DECL_IMAXABS
+_GL_WARN_ON_USE (imaxabs, "imaxabs is unportable - "
+ "use gnulib module imaxabs for portability");
+# endif
+#endif
+
+#if @GNULIB_IMAXDIV@
+# if !@HAVE_DECL_IMAXDIV@
+# if !GNULIB_defined_imaxdiv_t
+typedef struct { intmax_t quot; intmax_t rem; } imaxdiv_t;
+# define GNULIB_defined_imaxdiv_t 1
+# endif
+extern imaxdiv_t imaxdiv (intmax_t, intmax_t);
+# endif
+#elif defined GNULIB_POSIXCHECK
+# undef imaxdiv
+# if HAVE_RAW_DECL_IMAXDIV
+_GL_WARN_ON_USE (imaxdiv, "imaxdiv is unportable - "
+ "use gnulib module imaxdiv for portability");
+# endif
+#endif
+
+#if @GNULIB_STRTOIMAX@
+# if @REPLACE_STRTOIMAX@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef strtoimax
+# define strtoimax rpl_strtoimax
+# endif
+_GL_FUNCDECL_RPL (strtoimax, intmax_t,
+ (const char *, char **, int) _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (strtoimax, intmax_t, (const char *, char **, int));
+# else
+# if !@HAVE_DECL_STRTOIMAX@
+# undef strtoimax
+_GL_FUNCDECL_SYS (strtoimax, intmax_t,
+ (const char *, char **, int) _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (strtoimax, intmax_t, (const char *, char **, int));
+# endif
+_GL_CXXALIASWARN (strtoimax);
+#elif defined GNULIB_POSIXCHECK
+# undef strtoimax
+# if HAVE_RAW_DECL_STRTOIMAX
+_GL_WARN_ON_USE (strtoimax, "strtoimax is unportable - "
+ "use gnulib module strtoimax for portability");
+# endif
+#endif
+
+#if @GNULIB_STRTOUMAX@
+# if @REPLACE_STRTOUMAX@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef strtoumax
+# define strtoumax rpl_strtoumax
+# endif
+_GL_FUNCDECL_RPL (strtoumax, uintmax_t,
+ (const char *, char **, int) _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (strtoumax, uintmax_t, (const char *, char **, int));
+# else
+# if !@HAVE_DECL_STRTOUMAX@
+# undef strtoumax
+_GL_FUNCDECL_SYS (strtoumax, uintmax_t,
+ (const char *, char **, int) _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (strtoumax, uintmax_t, (const char *, char **, int));
+# endif
+_GL_CXXALIASWARN (strtoumax);
+#elif defined GNULIB_POSIXCHECK
+# undef strtoumax
+# if HAVE_RAW_DECL_STRTOUMAX
+_GL_WARN_ON_USE (strtoumax, "strtoumax is unportable - "
+ "use gnulib module strtoumax for portability");
+# endif
+#endif
+
+/* Don't bother defining or declaring wcstoimax and wcstoumax, since
+ wide-character functions like this are hardly ever useful. */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* !defined INTTYPES_H && !defined _GL_JUST_INCLUDE_SYSTEM_INTTYPES_H */
diff --git a/lib/inttypes_.h b/lib/inttypes_.h
deleted file mode 100644
index 3d3ead6..0000000
--- a/lib/inttypes_.h
+++ /dev/null
@@ -1,1095 +0,0 @@
-/* Copyright (C) 2006-2007 Free Software Foundation, Inc.
- Written by Paul Eggert, Bruno Haible, Derek Price.
- This file is part of gnulib.
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU Lesser General Public License as published by
- the Free Software Foundation; either version 2.1, 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 Lesser General Public License
- along with this program; if not, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-/* Include the original <inttypes.h> if it exists, and if this file
- has not been included yet or if this file includes gnulib stdint.h
- which in turn includes this file. */
-#if ! defined INTTYPES_H || defined _GL_JUST_INCLUDE_ABSOLUTE_INTTYPES_H
-# if @HAVE_INTTYPES_H@
-# include @ABSOLUTE_INTTYPES_H@
-# endif
-#endif
-
-#if ! defined INTTYPES_H && ! defined _GL_JUST_INCLUDE_ABSOLUTE_INTTYPES_H
-#define INTTYPES_H
-
-/*
- * ISO C 99 <inttypes.h> for platforms that lack it.
- * <http://www.opengroup.org/susv3xbd/inttypes.h.html>
- */
-
-/* Include <stdint.h> or the gnulib replacement. */
-#include <stdint.h>
-/* Get CHAR_BIT. */
-#include <limits.h>
-
-#if !(INT_MIN == INT32_MIN && INT_MAX == INT32_MAX)
-# error "This file assumes that 'int' has exactly 32 bits. Please report your platform and compiler to <bug-gnulib@gnu.org>."
-#endif
-
-/* The definition of GL_LINK_WARNING is copied here. */
-
-/* 7.8.1 Macros for format specifiers */
-
-#if ! defined __cplusplus || defined __STDC_FORMAT_MACROS
-
-# if defined _TNS_R_TARGET
- /* Tandem NonStop R series and compatible platforms released before
- July 2005 support %Ld but not %lld. */
-# define _LONG_LONG_FORMAT_PREFIX "L"
-# else
-# define _LONG_LONG_FORMAT_PREFIX "ll"
-# endif
-
-# if !defined PRId8 || @PRI_MACROS_BROKEN@
-# undef PRId8
-# ifdef INT8_MAX
-# define PRId8 "d"
-# endif
-# endif
-# if !defined PRIi8 || @PRI_MACROS_BROKEN@
-# undef PRIi8
-# ifdef INT8_MAX
-# define PRIi8 "i"
-# endif
-# endif
-# if !defined PRIo8 || @PRI_MACROS_BROKEN@
-# undef PRIo8
-# ifdef UINT8_MAX
-# define PRIo8 "o"
-# endif
-# endif
-# if !defined PRIu8 || @PRI_MACROS_BROKEN@
-# undef PRIu8
-# ifdef UINT8_MAX
-# define PRIu8 "u"
-# endif
-# endif
-# if !defined PRIx8 || @PRI_MACROS_BROKEN@
-# undef PRIx8
-# ifdef UINT8_MAX
-# define PRIx8 "x"
-# endif
-# endif
-# if !defined PRIX8 || @PRI_MACROS_BROKEN@
-# undef PRIX8
-# ifdef UINT8_MAX
-# define PRIX8 "X"
-# endif
-# endif
-# if !defined PRId16 || @PRI_MACROS_BROKEN@
-# undef PRId16
-# ifdef INT16_MAX
-# define PRId16 "d"
-# endif
-# endif
-# if !defined PRIi16 || @PRI_MACROS_BROKEN@
-# undef PRIi16
-# ifdef INT16_MAX
-# define PRIi16 "i"
-# endif
-# endif
-# if !defined PRIo16 || @PRI_MACROS_BROKEN@
-# undef PRIo16
-# ifdef UINT16_MAX
-# define PRIo16 "o"
-# endif
-# endif
-# if !defined PRIu16 || @PRI_MACROS_BROKEN@
-# undef PRIu16
-# ifdef UINT16_MAX
-# define PRIu16 "u"
-# endif
-# endif
-# if !defined PRIx16 || @PRI_MACROS_BROKEN@
-# undef PRIx16
-# ifdef UINT16_MAX
-# define PRIx16 "x"
-# endif
-# endif
-# if !defined PRIX16 || @PRI_MACROS_BROKEN@
-# undef PRIX16
-# ifdef UINT16_MAX
-# define PRIX16 "X"
-# endif
-# endif
-# if !defined PRId32 || @PRI_MACROS_BROKEN@
-# undef PRId32
-# ifdef INT32_MAX
-# define PRId32 "d"
-# endif
-# endif
-# if !defined PRIi32 || @PRI_MACROS_BROKEN@
-# undef PRIi32
-# ifdef INT32_MAX
-# define PRIi32 "i"
-# endif
-# endif
-# if !defined PRIo32 || @PRI_MACROS_BROKEN@
-# undef PRIo32
-# ifdef UINT32_MAX
-# define PRIo32 "o"
-# endif
-# endif
-# if !defined PRIu32 || @PRI_MACROS_BROKEN@
-# undef PRIu32
-# ifdef UINT32_MAX
-# define PRIu32 "u"
-# endif
-# endif
-# if !defined PRIx32 || @PRI_MACROS_BROKEN@
-# undef PRIx32
-# ifdef UINT32_MAX
-# define PRIx32 "x"
-# endif
-# endif
-# if !defined PRIX32 || @PRI_MACROS_BROKEN@
-# undef PRIX32
-# ifdef UINT32_MAX
-# define PRIX32 "X"
-# endif
-# endif
-# ifdef INT64_MAX
-# if INT64_MAX == LONG_MAX
-# define _PRI64_PREFIX "l"
-# elif defined _MSC_VER || defined __MINGW32__
-# define _PRI64_PREFIX "I64"
-# elif @HAVE_LONG_LONG_INT@ && LONG_MAX >> 30 == 1
-# define _PRI64_PREFIX _LONG_LONG_FORMAT_PREFIX
-# endif
-# if !defined PRId64 || @PRI_MACROS_BROKEN@
-# undef PRId64
-# define PRId64 _PRI64_PREFIX "d"
-# endif
-# if !defined PRIi64 || @PRI_MACROS_BROKEN@
-# undef PRIi64
-# define PRIi64 _PRI64_PREFIX "i"
-# endif
-# endif
-# ifdef UINT64_MAX
-# if UINT64_MAX == ULONG_MAX
-# define _PRIu64_PREFIX "l"
-# elif defined _MSC_VER || defined __MINGW32__
-# define _PRIu64_PREFIX "I64"
-# elif @HAVE_UNSIGNED_LONG_LONG_INT@ && ULONG_MAX >> 31 == 1
-# define _PRIu64_PREFIX _LONG_LONG_FORMAT_PREFIX
-# endif
-# if !defined PRIo64 || @PRI_MACROS_BROKEN@
-# undef PRIo64
-# define PRIo64 _PRIu64_PREFIX "o"
-# endif
-# if !defined PRIu64 || @PRI_MACROS_BROKEN@
-# undef PRIu64
-# define PRIu64 _PRIu64_PREFIX "u"
-# endif
-# if !defined PRIx64 || @PRI_MACROS_BROKEN@
-# undef PRIx64
-# define PRIx64 _PRIu64_PREFIX "x"
-# endif
-# if !defined PRIX64 || @PRI_MACROS_BROKEN@
-# undef PRIX64
-# define PRIX64 _PRIu64_PREFIX "X"
-# endif
-# endif
-
-# if !defined PRIdLEAST8 || @PRI_MACROS_BROKEN@
-# undef PRIdLEAST8
-# define PRIdLEAST8 "d"
-# endif
-# if !defined PRIiLEAST8 || @PRI_MACROS_BROKEN@
-# undef PRIiLEAST8
-# define PRIiLEAST8 "i"
-# endif
-# if !defined PRIoLEAST8 || @PRI_MACROS_BROKEN@
-# undef PRIoLEAST8
-# define PRIoLEAST8 "o"
-# endif
-# if !defined PRIuLEAST8 || @PRI_MACROS_BROKEN@
-# undef PRIuLEAST8
-# define PRIuLEAST8 "u"
-# endif
-# if !defined PRIxLEAST8 || @PRI_MACROS_BROKEN@
-# undef PRIxLEAST8
-# define PRIxLEAST8 "x"
-# endif
-# if !defined PRIXLEAST8 || @PRI_MACROS_BROKEN@
-# undef PRIXLEAST8
-# define PRIXLEAST8 "X"
-# endif
-# if !defined PRIdLEAST16 || @PRI_MACROS_BROKEN@
-# undef PRIdLEAST16
-# define PRIdLEAST16 "d"
-# endif
-# if !defined PRIiLEAST16 || @PRI_MACROS_BROKEN@
-# undef PRIiLEAST16
-# define PRIiLEAST16 "i"
-# endif
-# if !defined PRIoLEAST16 || @PRI_MACROS_BROKEN@
-# undef PRIoLEAST16
-# define PRIoLEAST16 "o"
-# endif
-# if !defined PRIuLEAST16 || @PRI_MACROS_BROKEN@
-# undef PRIuLEAST16
-# define PRIuLEAST16 "u"
-# endif
-# if !defined PRIxLEAST16 || @PRI_MACROS_BROKEN@
-# undef PRIxLEAST16
-# define PRIxLEAST16 "x"
-# endif
-# if !defined PRIXLEAST16 || @PRI_MACROS_BROKEN@
-# undef PRIXLEAST16
-# define PRIXLEAST16 "X"
-# endif
-# if !defined PRIdLEAST32 || @PRI_MACROS_BROKEN@
-# undef PRIdLEAST32
-# define PRIdLEAST32 "d"
-# endif
-# if !defined PRIiLEAST32 || @PRI_MACROS_BROKEN@
-# undef PRIiLEAST32
-# define PRIiLEAST32 "i"
-# endif
-# if !defined PRIoLEAST32 || @PRI_MACROS_BROKEN@
-# undef PRIoLEAST32
-# define PRIoLEAST32 "o"
-# endif
-# if !defined PRIuLEAST32 || @PRI_MACROS_BROKEN@
-# undef PRIuLEAST32
-# define PRIuLEAST32 "u"
-# endif
-# if !defined PRIxLEAST32 || @PRI_MACROS_BROKEN@
-# undef PRIxLEAST32
-# define PRIxLEAST32 "x"
-# endif
-# if !defined PRIXLEAST32 || @PRI_MACROS_BROKEN@
-# undef PRIXLEAST32
-# define PRIXLEAST32 "X"
-# endif
-# ifdef INT64_MAX
-# if !defined PRIdLEAST64 || @PRI_MACROS_BROKEN@
-# undef PRIdLEAST64
-# define PRIdLEAST64 PRId64
-# endif
-# if !defined PRIiLEAST64 || @PRI_MACROS_BROKEN@
-# undef PRIiLEAST64
-# define PRIiLEAST64 PRIi64
-# endif
-# endif
-# ifdef UINT64_MAX
-# if !defined PRIoLEAST64 || @PRI_MACROS_BROKEN@
-# undef PRIoLEAST64
-# define PRIoLEAST64 PRIo64
-# endif
-# if !defined PRIuLEAST64 || @PRI_MACROS_BROKEN@
-# undef PRIuLEAST64
-# define PRIuLEAST64 PRIu64
-# endif
-# if !defined PRIxLEAST64 || @PRI_MACROS_BROKEN@
-# undef PRIxLEAST64
-# define PRIxLEAST64 PRIx64
-# endif
-# if !defined PRIXLEAST64 || @PRI_MACROS_BROKEN@
-# undef PRIXLEAST64
-# define PRIXLEAST64 PRIX64
-# endif
-# endif
-
-# if !defined PRIdFAST8 || @PRI_MACROS_BROKEN@
-# undef PRIdFAST8
-# if INT_FAST8_MAX > INT32_MAX
-# define PRIdFAST8 PRId64
-# else
-# define PRIdFAST8 "d"
-# endif
-# endif
-# if !defined PRIiFAST8 || @PRI_MACROS_BROKEN@
-# undef PRIiFAST8
-# if INT_FAST8_MAX > INT32_MAX
-# define PRIiFAST8 PRIi64
-# else
-# define PRIiFAST8 "i"
-# endif
-# endif
-# if !defined PRIoFAST8 || @PRI_MACROS_BROKEN@
-# undef PRIoFAST8
-# if UINT_FAST8_MAX > UINT32_MAX
-# define PRIoFAST8 PRIo64
-# else
-# define PRIoFAST8 "o"
-# endif
-# endif
-# if !defined PRIuFAST8 || @PRI_MACROS_BROKEN@
-# undef PRIuFAST8
-# if UINT_FAST8_MAX > UINT32_MAX
-# define PRIuFAST8 PRIu64
-# else
-# define PRIuFAST8 "u"
-# endif
-# endif
-# if !defined PRIxFAST8 || @PRI_MACROS_BROKEN@
-# undef PRIxFAST8
-# if UINT_FAST8_MAX > UINT32_MAX
-# define PRIxFAST8 PRIx64
-# else
-# define PRIxFAST8 "x"
-# endif
-# endif
-# if !defined PRIXFAST8 || @PRI_MACROS_BROKEN@
-# undef PRIXFAST8
-# if UINT_FAST8_MAX > UINT32_MAX
-# define PRIXFAST8 PRIX64
-# else
-# define PRIXFAST8 "X"
-# endif
-# endif
-# if !defined PRIdFAST16 || @PRI_MACROS_BROKEN@
-# undef PRIdFAST16
-# if INT_FAST16_MAX > INT32_MAX
-# define PRIdFAST16 PRId64
-# else
-# define PRIdFAST16 "d"
-# endif
-# endif
-# if !defined PRIiFAST16 || @PRI_MACROS_BROKEN@
-# undef PRIiFAST16
-# if INT_FAST16_MAX > INT32_MAX
-# define PRIiFAST16 PRIi64
-# else
-# define PRIiFAST16 "i"
-# endif
-# endif
-# if !defined PRIoFAST16 || @PRI_MACROS_BROKEN@
-# undef PRIoFAST16
-# if UINT_FAST16_MAX > UINT32_MAX
-# define PRIoFAST16 PRIo64
-# else
-# define PRIoFAST16 "o"
-# endif
-# endif
-# if !defined PRIuFAST16 || @PRI_MACROS_BROKEN@
-# undef PRIuFAST16
-# if UINT_FAST16_MAX > UINT32_MAX
-# define PRIuFAST16 PRIu64
-# else
-# define PRIuFAST16 "u"
-# endif
-# endif
-# if !defined PRIxFAST16 || @PRI_MACROS_BROKEN@
-# undef PRIxFAST16
-# if UINT_FAST16_MAX > UINT32_MAX
-# define PRIxFAST16 PRIx64
-# else
-# define PRIxFAST16 "x"
-# endif
-# endif
-# if !defined PRIXFAST16 || @PRI_MACROS_BROKEN@
-# undef PRIXFAST16
-# if UINT_FAST16_MAX > UINT32_MAX
-# define PRIXFAST16 PRIX64
-# else
-# define PRIXFAST16 "X"
-# endif
-# endif
-# if !defined PRIdFAST32 || @PRI_MACROS_BROKEN@
-# undef PRIdFAST32
-# if INT_FAST32_MAX > INT32_MAX
-# define PRIdFAST32 PRId64
-# else
-# define PRIdFAST32 "d"
-# endif
-# endif
-# if !defined PRIiFAST32 || @PRI_MACROS_BROKEN@
-# undef PRIiFAST32
-# if INT_FAST32_MAX > INT32_MAX
-# define PRIiFAST32 PRIi64
-# else
-# define PRIiFAST32 "i"
-# endif
-# endif
-# if !defined PRIoFAST32 || @PRI_MACROS_BROKEN@
-# undef PRIoFAST32
-# if UINT_FAST32_MAX > UINT32_MAX
-# define PRIoFAST32 PRIo64
-# else
-# define PRIoFAST32 "o"
-# endif
-# endif
-# if !defined PRIuFAST32 || @PRI_MACROS_BROKEN@
-# undef PRIuFAST32
-# if UINT_FAST32_MAX > UINT32_MAX
-# define PRIuFAST32 PRIu64
-# else
-# define PRIuFAST32 "u"
-# endif
-# endif
-# if !defined PRIxFAST32 || @PRI_MACROS_BROKEN@
-# undef PRIxFAST32
-# if UINT_FAST32_MAX > UINT32_MAX
-# define PRIxFAST32 PRIx64
-# else
-# define PRIxFAST32 "x"
-# endif
-# endif
-# if !defined PRIXFAST32 || @PRI_MACROS_BROKEN@
-# undef PRIXFAST32
-# if UINT_FAST32_MAX > UINT32_MAX
-# define PRIXFAST32 PRIX64
-# else
-# define PRIXFAST32 "X"
-# endif
-# endif
-# ifdef INT64_MAX
-# if !defined PRIdFAST64 || @PRI_MACROS_BROKEN@
-# undef PRIdFAST64
-# define PRIdFAST64 PRId64
-# endif
-# if !defined PRIiFAST64 || @PRI_MACROS_BROKEN@
-# undef PRIiFAST64
-# define PRIiFAST64 PRIi64
-# endif
-# endif
-# ifdef UINT64_MAX
-# if !defined PRIoFAST64 || @PRI_MACROS_BROKEN@
-# undef PRIoFAST64
-# define PRIoFAST64 PRIo64
-# endif
-# if !defined PRIuFAST64 || @PRI_MACROS_BROKEN@
-# undef PRIuFAST64
-# define PRIuFAST64 PRIu64
-# endif
-# if !defined PRIxFAST64 || @PRI_MACROS_BROKEN@
-# undef PRIxFAST64
-# define PRIxFAST64 PRIx64
-# endif
-# if !defined PRIXFAST64 || @PRI_MACROS_BROKEN@
-# undef PRIXFAST64
-# define PRIXFAST64 PRIX64
-# endif
-# endif
-
-# if !defined PRIdMAX || @PRI_MACROS_BROKEN@
-# undef PRIdMAX
-# if INTMAX_MAX > INT32_MAX
-# define PRIdMAX PRId64
-# else
-# define PRIdMAX "ld"
-# endif
-# endif
-# if !defined PRIiMAX || @PRI_MACROS_BROKEN@
-# undef PRIiMAX
-# if INTMAX_MAX > INT32_MAX
-# define PRIiMAX PRIi64
-# else
-# define PRIiMAX "li"
-# endif
-# endif
-# if !defined PRIoMAX || @PRI_MACROS_BROKEN@
-# undef PRIoMAX
-# if UINTMAX_MAX > UINT32_MAX
-# define PRIoMAX PRIo64
-# else
-# define PRIoMAX "lo"
-# endif
-# endif
-# if !defined PRIuMAX || @PRI_MACROS_BROKEN@
-# undef PRIuMAX
-# if UINTMAX_MAX > UINT32_MAX
-# define PRIuMAX PRIu64
-# else
-# define PRIuMAX "lu"
-# endif
-# endif
-# if !defined PRIxMAX || @PRI_MACROS_BROKEN@
-# undef PRIxMAX
-# if UINTMAX_MAX > UINT32_MAX
-# define PRIxMAX PRIx64
-# else
-# define PRIxMAX "lx"
-# endif
-# endif
-# if !defined PRIXMAX || @PRI_MACROS_BROKEN@
-# undef PRIXMAX
-# if UINTMAX_MAX > UINT32_MAX
-# define PRIXMAX PRIX64
-# else
-# define PRIXMAX "lX"
-# endif
-# endif
-
-# if !defined PRIdPTR || @PRI_MACROS_BROKEN@
-# undef PRIdPTR
-# ifdef INTPTR_MAX
-# define PRIdPTR @PRIPTR_PREFIX@ "d"
-# endif
-# endif
-# if !defined PRIiPTR || @PRI_MACROS_BROKEN@
-# undef PRIiPTR
-# ifdef INTPTR_MAX
-# define PRIiPTR @PRIPTR_PREFIX@ "i"
-# endif
-# endif
-# if !defined PRIoPTR || @PRI_MACROS_BROKEN@
-# undef PRIoPTR
-# ifdef UINTPTR_MAX
-# define PRIoPTR @PRIPTR_PREFIX@ "o"
-# endif
-# endif
-# if !defined PRIuPTR || @PRI_MACROS_BROKEN@
-# undef PRIuPTR
-# ifdef UINTPTR_MAX
-# define PRIuPTR @PRIPTR_PREFIX@ "u"
-# endif
-# endif
-# if !defined PRIxPTR || @PRI_MACROS_BROKEN@
-# undef PRIxPTR
-# ifdef UINTPTR_MAX
-# define PRIxPTR @PRIPTR_PREFIX@ "x"
-# endif
-# endif
-# if !defined PRIXPTR || @PRI_MACROS_BROKEN@
-# undef PRIXPTR
-# ifdef UINTPTR_MAX
-# define PRIXPTR @PRIPTR_PREFIX@ "X"
-# endif
-# endif
-
-# if !defined SCNd8 || @PRI_MACROS_BROKEN@
-# undef SCNd8
-# ifdef INT8_MAX
-# define SCNd8 "hhd"
-# endif
-# endif
-# if !defined SCNi8 || @PRI_MACROS_BROKEN@
-# undef SCNi8
-# ifdef INT8_MAX
-# define SCNi8 "hhi"
-# endif
-# endif
-# if !defined SCNo8 || @PRI_MACROS_BROKEN@
-# undef SCNo8
-# ifdef UINT8_MAX
-# define SCNo8 "hho"
-# endif
-# endif
-# if !defined SCNu8 || @PRI_MACROS_BROKEN@
-# undef SCNu8
-# ifdef UINT8_MAX
-# define SCNu8 "hhu"
-# endif
-# endif
-# if !defined SCNx8 || @PRI_MACROS_BROKEN@
-# undef SCNx8
-# ifdef UINT8_MAX
-# define SCNx8 "hhx"
-# endif
-# endif
-# if !defined SCNd16 || @PRI_MACROS_BROKEN@
-# undef SCNd16
-# ifdef INT16_MAX
-# define SCNd16 "hd"
-# endif
-# endif
-# if !defined SCNi16 || @PRI_MACROS_BROKEN@
-# undef SCNi16
-# ifdef INT16_MAX
-# define SCNi16 "hi"
-# endif
-# endif
-# if !defined SCNo16 || @PRI_MACROS_BROKEN@
-# undef SCNo16
-# ifdef UINT16_MAX
-# define SCNo16 "ho"
-# endif
-# endif
-# if !defined SCNu16 || @PRI_MACROS_BROKEN@
-# undef SCNu16
-# ifdef UINT16_MAX
-# define SCNu16 "hu"
-# endif
-# endif
-# if !defined SCNx16 || @PRI_MACROS_BROKEN@
-# undef SCNx16
-# ifdef UINT16_MAX
-# define SCNx16 "hx"
-# endif
-# endif
-# if !defined SCNd32 || @PRI_MACROS_BROKEN@
-# undef SCNd32
-# ifdef INT32_MAX
-# define SCNd32 "d"
-# endif
-# endif
-# if !defined SCNi32 || @PRI_MACROS_BROKEN@
-# undef SCNi32
-# ifdef INT32_MAX
-# define SCNi32 "i"
-# endif
-# endif
-# if !defined SCNo32 || @PRI_MACROS_BROKEN@
-# undef SCNo32
-# ifdef UINT32_MAX
-# define SCNo32 "o"
-# endif
-# endif
-# if !defined SCNu32 || @PRI_MACROS_BROKEN@
-# undef SCNu32
-# ifdef UINT32_MAX
-# define SCNu32 "u"
-# endif
-# endif
-# if !defined SCNx32 || @PRI_MACROS_BROKEN@
-# undef SCNx32
-# ifdef UINT32_MAX
-# define SCNx32 "x"
-# endif
-# endif
-# ifdef INT64_MAX
-# if INT64_MAX == LONG_MAX
-# define _SCN64_PREFIX "l"
-# elif defined _MSC_VER || defined __MINGW32__
-# define _SCN64_PREFIX "I64"
-# elif @HAVE_LONG_LONG_INT@ && LONG_MAX >> 30 == 1
-# define _SCN64_PREFIX _LONG_LONG_FORMAT_PREFIX
-# endif
-# if !defined SCNd64 || @PRI_MACROS_BROKEN@
-# undef SCNd64
-# define SCNd64 _SCN64_PREFIX "d"
-# endif
-# if !defined SCNi64 || @PRI_MACROS_BROKEN@
-# undef SCNi64
-# define SCNi64 _SCN64_PREFIX "i"
-# endif
-# endif
-# ifdef UINT64_MAX
-# if UINT64_MAX == ULONG_MAX
-# define _SCNu64_PREFIX "l"
-# elif defined _MSC_VER || defined __MINGW32__
-# define _SCNu64_PREFIX "I64"
-# elif @HAVE_UNSIGNED_LONG_LONG_INT@ && ULONG_MAX >> 31 == 1
-# define _SCNu64_PREFIX _LONG_LONG_FORMAT_PREFIX
-# endif
-# if !defined SCNo64 || @PRI_MACROS_BROKEN@
-# undef SCNo64
-# define SCNo64 _SCNu64_PREFIX "o"
-# endif
-# if !defined SCNu64 || @PRI_MACROS_BROKEN@
-# undef SCNu64
-# define SCNu64 _SCNu64_PREFIX "u"
-# endif
-# if !defined SCNx64 || @PRI_MACROS_BROKEN@
-# undef SCNx64
-# define SCNx64 _SCNu64_PREFIX "x"
-# endif
-# endif
-
-# if !defined SCNdLEAST8 || @PRI_MACROS_BROKEN@
-# undef SCNdLEAST8
-# define SCNdLEAST8 "hhd"
-# endif
-# if !defined SCNiLEAST8 || @PRI_MACROS_BROKEN@
-# undef SCNiLEAST8
-# define SCNiLEAST8 "hhi"
-# endif
-# if !defined SCNoLEAST8 || @PRI_MACROS_BROKEN@
-# undef SCNoLEAST8
-# define SCNoLEAST8 "hho"
-# endif
-# if !defined SCNuLEAST8 || @PRI_MACROS_BROKEN@
-# undef SCNuLEAST8
-# define SCNuLEAST8 "hhu"
-# endif
-# if !defined SCNxLEAST8 || @PRI_MACROS_BROKEN@
-# undef SCNxLEAST8
-# define SCNxLEAST8 "hhx"
-# endif
-# if !defined SCNdLEAST16 || @PRI_MACROS_BROKEN@
-# undef SCNdLEAST16
-# define SCNdLEAST16 "hd"
-# endif
-# if !defined SCNiLEAST16 || @PRI_MACROS_BROKEN@
-# undef SCNiLEAST16
-# define SCNiLEAST16 "hi"
-# endif
-# if !defined SCNoLEAST16 || @PRI_MACROS_BROKEN@
-# undef SCNoLEAST16
-# define SCNoLEAST16 "ho"
-# endif
-# if !defined SCNuLEAST16 || @PRI_MACROS_BROKEN@
-# undef SCNuLEAST16
-# define SCNuLEAST16 "hu"
-# endif
-# if !defined SCNxLEAST16 || @PRI_MACROS_BROKEN@
-# undef SCNxLEAST16
-# define SCNxLEAST16 "hx"
-# endif
-# if !defined SCNdLEAST32 || @PRI_MACROS_BROKEN@
-# undef SCNdLEAST32
-# define SCNdLEAST32 "d"
-# endif
-# if !defined SCNiLEAST32 || @PRI_MACROS_BROKEN@
-# undef SCNiLEAST32
-# define SCNiLEAST32 "i"
-# endif
-# if !defined SCNoLEAST32 || @PRI_MACROS_BROKEN@
-# undef SCNoLEAST32
-# define SCNoLEAST32 "o"
-# endif
-# if !defined SCNuLEAST32 || @PRI_MACROS_BROKEN@
-# undef SCNuLEAST32
-# define SCNuLEAST32 "u"
-# endif
-# if !defined SCNxLEAST32 || @PRI_MACROS_BROKEN@
-# undef SCNxLEAST32
-# define SCNxLEAST32 "x"
-# endif
-# ifdef INT64_MAX
-# if !defined SCNdLEAST64 || @PRI_MACROS_BROKEN@
-# undef SCNdLEAST64
-# define SCNdLEAST64 SCNd64
-# endif
-# if !defined SCNiLEAST64 || @PRI_MACROS_BROKEN@
-# undef SCNiLEAST64
-# define SCNiLEAST64 SCNi64
-# endif
-# endif
-# ifdef UINT64_MAX
-# if !defined SCNoLEAST64 || @PRI_MACROS_BROKEN@
-# undef SCNoLEAST64
-# define SCNoLEAST64 SCNo64
-# endif
-# if !defined SCNuLEAST64 || @PRI_MACROS_BROKEN@
-# undef SCNuLEAST64
-# define SCNuLEAST64 SCNu64
-# endif
-# if !defined SCNxLEAST64 || @PRI_MACROS_BROKEN@
-# undef SCNxLEAST64
-# define SCNxLEAST64 SCNx64
-# endif
-# endif
-
-# if !defined SCNdFAST8 || @PRI_MACROS_BROKEN@
-# undef SCNdFAST8
-# if INT_FAST8_MAX > INT32_MAX
-# define SCNdFAST8 SCNd64
-# elif INT_FAST8_MAX == 0x7fff
-# define SCNdFAST8 "hd"
-# elif INT_FAST8_MAX == 0x7f
-# define SCNdFAST8 "hhd"
-# else
-# define SCNdFAST8 "d"
-# endif
-# endif
-# if !defined SCNiFAST8 || @PRI_MACROS_BROKEN@
-# undef SCNiFAST8
-# if INT_FAST8_MAX > INT32_MAX
-# define SCNiFAST8 SCNi64
-# elif INT_FAST8_MAX == 0x7fff
-# define SCNiFAST8 "hi"
-# elif INT_FAST8_MAX == 0x7f
-# define SCNiFAST8 "hhi"
-# else
-# define SCNiFAST8 "i"
-# endif
-# endif
-# if !defined SCNoFAST8 || @PRI_MACROS_BROKEN@
-# undef SCNoFAST8
-# if UINT_FAST8_MAX > UINT32_MAX
-# define SCNoFAST8 SCNo64
-# elif UINT_FAST8_MAX == 0xffff
-# define SCNoFAST8 "ho"
-# elif UINT_FAST8_MAX == 0xff
-# define SCNoFAST8 "hho"
-# else
-# define SCNoFAST8 "o"
-# endif
-# endif
-# if !defined SCNuFAST8 || @PRI_MACROS_BROKEN@
-# undef SCNuFAST8
-# if UINT_FAST8_MAX > UINT32_MAX
-# define SCNuFAST8 SCNu64
-# elif UINT_FAST8_MAX == 0xffff
-# define SCNuFAST8 "hu"
-# elif UINT_FAST8_MAX == 0xff
-# define SCNuFAST8 "hhu"
-# else
-# define SCNuFAST8 "u"
-# endif
-# endif
-# if !defined SCNxFAST8 || @PRI_MACROS_BROKEN@
-# undef SCNxFAST8
-# if UINT_FAST8_MAX > UINT32_MAX
-# define SCNxFAST8 SCNx64
-# elif UINT_FAST8_MAX == 0xffff
-# define SCNxFAST8 "hx"
-# elif UINT_FAST8_MAX == 0xff
-# define SCNxFAST8 "hhx"
-# else
-# define SCNxFAST8 "x"
-# endif
-# endif
-# if !defined SCNdFAST16 || @PRI_MACROS_BROKEN@
-# undef SCNdFAST16
-# if INT_FAST16_MAX > INT32_MAX
-# define SCNdFAST16 SCNd64
-# elif INT_FAST16_MAX == 0x7fff
-# define SCNdFAST16 "hd"
-# else
-# define SCNdFAST16 "d"
-# endif
-# endif
-# if !defined SCNiFAST16 || @PRI_MACROS_BROKEN@
-# undef SCNiFAST16
-# if INT_FAST16_MAX > INT32_MAX
-# define SCNiFAST16 SCNi64
-# elif INT_FAST16_MAX == 0x7fff
-# define SCNiFAST16 "hi"
-# else
-# define SCNiFAST16 "i"
-# endif
-# endif
-# if !defined SCNoFAST16 || @PRI_MACROS_BROKEN@
-# undef SCNoFAST16
-# if UINT_FAST16_MAX > UINT32_MAX
-# define SCNoFAST16 SCNo64
-# elif UINT_FAST16_MAX == 0xffff
-# define SCNoFAST16 "ho"
-# else
-# define SCNoFAST16 "o"
-# endif
-# endif
-# if !defined SCNuFAST16 || @PRI_MACROS_BROKEN@
-# undef SCNuFAST16
-# if UINT_FAST16_MAX > UINT32_MAX
-# define SCNuFAST16 SCNu64
-# elif UINT_FAST16_MAX == 0xffff
-# define SCNuFAST16 "hu"
-# else
-# define SCNuFAST16 "u"
-# endif
-# endif
-# if !defined SCNxFAST16 || @PRI_MACROS_BROKEN@
-# undef SCNxFAST16
-# if UINT_FAST16_MAX > UINT32_MAX
-# define SCNxFAST16 SCNx64
-# elif UINT_FAST16_MAX == 0xffff
-# define SCNxFAST16 "hx"
-# else
-# define SCNxFAST16 "x"
-# endif
-# endif
-# if !defined SCNdFAST32 || @PRI_MACROS_BROKEN@
-# undef SCNdFAST32
-# if INT_FAST32_MAX > INT32_MAX
-# define SCNdFAST32 SCNd64
-# else
-# define SCNdFAST32 "d"
-# endif
-# endif
-# if !defined SCNiFAST32 || @PRI_MACROS_BROKEN@
-# undef SCNiFAST32
-# if INT_FAST32_MAX > INT32_MAX
-# define SCNiFAST32 SCNi64
-# else
-# define SCNiFAST32 "i"
-# endif
-# endif
-# if !defined SCNoFAST32 || @PRI_MACROS_BROKEN@
-# undef SCNoFAST32
-# if UINT_FAST32_MAX > UINT32_MAX
-# define SCNoFAST32 SCNo64
-# else
-# define SCNoFAST32 "o"
-# endif
-# endif
-# if !defined SCNuFAST32 || @PRI_MACROS_BROKEN@
-# undef SCNuFAST32
-# if UINT_FAST32_MAX > UINT32_MAX
-# define SCNuFAST32 SCNu64
-# else
-# define SCNuFAST32 "u"
-# endif
-# endif
-# if !defined SCNxFAST32 || @PRI_MACROS_BROKEN@
-# undef SCNxFAST32
-# if UINT_FAST32_MAX > UINT32_MAX
-# define SCNxFAST32 SCNx64
-# else
-# define SCNxFAST32 "x"
-# endif
-# endif
-# ifdef INT64_MAX
-# if !defined SCNdFAST64 || @PRI_MACROS_BROKEN@
-# undef SCNdFAST64
-# define SCNdFAST64 SCNd64
-# endif
-# if !defined SCNiFAST64 || @PRI_MACROS_BROKEN@
-# undef SCNiFAST64
-# define SCNiFAST64 SCNi64
-# endif
-# endif
-# ifdef UINT64_MAX
-# if !defined SCNoFAST64 || @PRI_MACROS_BROKEN@
-# undef SCNoFAST64
-# define SCNoFAST64 SCNo64
-# endif
-# if !defined SCNuFAST64 || @PRI_MACROS_BROKEN@
-# undef SCNuFAST64
-# define SCNuFAST64 SCNu64
-# endif
-# if !defined SCNxFAST64 || @PRI_MACROS_BROKEN@
-# undef SCNxFAST64
-# define SCNxFAST64 SCNx64
-# endif
-# endif
-
-# if !defined SCNdMAX || @PRI_MACROS_BROKEN@
-# undef SCNdMAX
-# if INTMAX_MAX > INT32_MAX
-# define SCNdMAX SCNd64
-# else
-# define SCNdMAX "ld"
-# endif
-# endif
-# if !defined SCNiMAX || @PRI_MACROS_BROKEN@
-# undef SCNiMAX
-# if INTMAX_MAX > INT32_MAX
-# define SCNiMAX SCNi64
-# else
-# define SCNiMAX "li"
-# endif
-# endif
-# if !defined SCNoMAX || @PRI_MACROS_BROKEN@
-# undef SCNoMAX
-# if UINTMAX_MAX > UINT32_MAX
-# define SCNoMAX SCNo64
-# else
-# define SCNoMAX "lo"
-# endif
-# endif
-# if !defined SCNuMAX || @PRI_MACROS_BROKEN@
-# undef SCNuMAX
-# if UINTMAX_MAX > UINT32_MAX
-# define SCNuMAX SCNu64
-# else
-# define SCNuMAX "lu"
-# endif
-# endif
-# if !defined SCNxMAX || @PRI_MACROS_BROKEN@
-# undef SCNxMAX
-# if UINTMAX_MAX > UINT32_MAX
-# define SCNxMAX SCNx64
-# else
-# define SCNxMAX "lx"
-# endif
-# endif
-
-# if !defined SCNdPTR || @PRI_MACROS_BROKEN@
-# undef SCNdPTR
-# ifdef INTPTR_MAX
-# define SCNdPTR @PRIPTR_PREFIX@ "d"
-# endif
-# endif
-# if !defined SCNiPTR || @PRI_MACROS_BROKEN@
-# undef SCNiPTR
-# ifdef INTPTR_MAX
-# define SCNiPTR @PRIPTR_PREFIX@ "i"
-# endif
-# endif
-# if !defined SCNoPTR || @PRI_MACROS_BROKEN@
-# undef SCNoPTR
-# ifdef UINTPTR_MAX
-# define SCNoPTR @PRIPTR_PREFIX@ "o"
-# endif
-# endif
-# if !defined SCNuPTR || @PRI_MACROS_BROKEN@
-# undef SCNuPTR
-# ifdef UINTPTR_MAX
-# define SCNuPTR @PRIPTR_PREFIX@ "u"
-# endif
-# endif
-# if !defined SCNxPTR || @PRI_MACROS_BROKEN@
-# undef SCNxPTR
-# ifdef UINTPTR_MAX
-# define SCNxPTR @PRIPTR_PREFIX@ "x"
-# endif
-# endif
-
-#endif
-
-/* 7.8.2 Functions for greatest-width integer types */
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#if @GNULIB_IMAXABS@
-# if !@HAVE_DECL_IMAXABS@
-extern intmax_t imaxabs (intmax_t);
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef imaxabs
-# define imaxabs(a) \
- (GL_LINK_WARNING ("imaxabs is unportable - " \
- "use gnulib module imaxabs for portability"), \
- imaxabs (a))
-#endif
-
-#if @GNULIB_IMAXDIV@
-# if !@HAVE_DECL_IMAXDIV@
-typedef struct { intmax_t quot; intmax_t rem; } imaxdiv_t;
-extern imaxdiv_t imaxdiv (intmax_t, intmax_t);
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef imaxdiv
-# define imaxdiv(a,b) \
- (GL_LINK_WARNING ("imaxdiv is unportable - " \
- "use gnulib module imaxdiv for portability"), \
- imaxdiv (a, b))
-#endif
-
-#if @GNULIB_STRTOIMAX@
-# if !@HAVE_DECL_STRTOIMAX@
-extern intmax_t strtoimax (const char *, char **, int);
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef strtoimax
-# define strtoimax(p,e,b) \
- (GL_LINK_WARNING ("strtoimax is unportable - " \
- "use gnulib module strtoimax for portability"), \
- strtoimax (p, e, b))
-#endif
-
-#if @GNULIB_STRTOUMAX@
-# if !@HAVE_DECL_STRTOUMAX@
-extern uintmax_t strtoumax (const char *, char **, int);
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef strtoumax
-# define strtoumax(p,e,b) \
- (GL_LINK_WARNING ("strtoumax is unportable - " \
- "use gnulib module strtoumax for portability"), \
- strtoumax (p, e, b))
-#endif
-
-/* Don't bother defining or declaring wcstoimax and wcstoumax, since
- wide-character functions like this are hardly ever useful. */
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* INTTYPES_H */
diff --git a/lib/isapipe.c b/lib/isapipe.c
index 83a9bf2..6dcd2a5 100644
--- a/lib/isapipe.c
+++ b/lib/isapipe.c
@@ -1,11 +1,11 @@
/* Test whether a file descriptor is a pipe.
- Copyright (C) 2006 Free Software Foundation, Inc.
+ Copyright (C) 2006, 2008-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
@@ -23,15 +22,42 @@
#include "isapipe.h"
#include <errno.h>
-#include <stdbool.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <unistd.h>
+
+#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+/* Windows platforms. */
+
+/* Get GetFileType. */
+# include <windows.h>
+
+/* Get _get_osfhandle. */
+# include "msvc-nothrow.h"
+
+int
+isapipe (int fd)
+{
+ HANDLE h = (HANDLE) _get_osfhandle (fd);
+
+ if (h == INVALID_HANDLE_VALUE)
+ {
+ errno = EBADF;
+ return -1;
+ }
+
+ return (GetFileType (h) == FILE_TYPE_PIPE);
+}
+
+#else
+/* Unix platforms. */
+
+# include <stdbool.h>
+# include <sys/types.h>
+# include <sys/stat.h>
+# include <unistd.h>
/* The maximum link count for pipes; (nlink_t) -1 if not known. */
-#ifndef PIPE_LINK_COUNT_MAX
-# define PIPE_LINK_COUNT_MAX ((nlink_t) (-1))
-#endif
+# ifndef PIPE_LINK_COUNT_MAX
+# define PIPE_LINK_COUNT_MAX ((nlink_t) (-1))
+# endif
/* Return 1 if FD is a pipe, 0 if not, -1 (setting errno) on error.
@@ -61,31 +87,33 @@ isapipe (int fd)
On Darwin 7.7, pipes are sockets, so check for those instead. */
if (! ((HAVE_FIFO_PIPES == 0 || HAVE_FIFO_PIPES == 1)
- && PIPE_LINK_COUNT_MAX != (nlink_t) -1)
+ && PIPE_LINK_COUNT_MAX != (nlink_t) -1)
&& (S_ISFIFO (st.st_mode) | S_ISSOCK (st.st_mode)))
{
int fd_pair[2];
int pipe_result = pipe (fd_pair);
if (pipe_result != 0)
- return pipe_result;
+ return pipe_result;
else
- {
- struct stat pipe_st;
- int fstat_pipe_result = fstat (fd_pair[0], &pipe_st);
- int fstat_pipe_errno = errno;
- close (fd_pair[0]);
- close (fd_pair[1]);
- if (fstat_pipe_result != 0)
- {
- errno = fstat_pipe_errno;
- return fstat_pipe_result;
- }
- check_for_fifo = (S_ISFIFO (pipe_st.st_mode) != 0);
- pipe_link_count_max = pipe_st.st_nlink;
- }
+ {
+ struct stat pipe_st;
+ int fstat_pipe_result = fstat (fd_pair[0], &pipe_st);
+ int fstat_pipe_errno = errno;
+ close (fd_pair[0]);
+ close (fd_pair[1]);
+ if (fstat_pipe_result != 0)
+ {
+ errno = fstat_pipe_errno;
+ return fstat_pipe_result;
+ }
+ check_for_fifo = (S_ISFIFO (pipe_st.st_mode) != 0);
+ pipe_link_count_max = pipe_st.st_nlink;
+ }
}
return
(st.st_nlink <= pipe_link_count_max
&& (check_for_fifo ? S_ISFIFO (st.st_mode) : S_ISSOCK (st.st_mode)));
}
+
+#endif
diff --git a/lib/isatty.c b/lib/isatty.c
new file mode 100644
index 0000000..d8071fb
--- /dev/null
+++ b/lib/isatty.c
@@ -0,0 +1,83 @@
+/* isatty() replacement.
+ Copyright (C) 2012-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <unistd.h>
+
+/* This replacement is enabled on native Windows. */
+
+#include <errno.h>
+
+/* Get declarations of the Win32 API functions. */
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+
+#include "msvc-inval.h"
+
+/* Get _get_osfhandle(). */
+#include "msvc-nothrow.h"
+
+static BOOL IsConsoleHandle (HANDLE h)
+{
+ DWORD mode;
+ return GetConsoleMode (h, &mode) != 0;
+}
+
+#if HAVE_MSVC_INVALID_PARAMETER_HANDLER
+static int
+_isatty_nothrow (int fd)
+{
+ int result;
+
+ TRY_MSVC_INVAL
+ {
+ result = _isatty (fd);
+ }
+ CATCH_MSVC_INVAL
+ {
+ result = 0;
+ }
+ DONE_MSVC_INVAL;
+
+ return result;
+}
+#else
+# define _isatty_nothrow _isatty
+#endif
+
+/* Determine whether FD refers to a console device. Return 1 if yes.
+ Return 0 and set errno if no. (ptsname_r relies on the errno value.) */
+int
+isatty (int fd)
+{
+ HANDLE h = (HANDLE) _get_osfhandle (fd);
+ if (h == INVALID_HANDLE_VALUE)
+ {
+ errno = EBADF;
+ return 0;
+ }
+ /* _isatty (fd) tests whether GetFileType of the handle is FILE_TYPE_CHAR.
+ But it does not set errno when it returns 0. */
+ if (_isatty_nothrow (fd))
+ {
+ if (IsConsoleHandle (h))
+ return 1;
+ }
+ errno = ENOTTY;
+ return 0;
+}
diff --git a/lib/isblank.c b/lib/isblank.c
new file mode 100644
index 0000000..6cc7379
--- /dev/null
+++ b/lib/isblank.c
@@ -0,0 +1,33 @@
+/* Test whether a character is a blank.
+
+ Copyright (C) 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <ctype.h>
+
+int
+isblank (int c)
+{
+ /* On all known platforms, in all predefined locales, isblank(c) is likely
+ equivalent with (c == ' ' || c == '\t'). Look at the glibc definition
+ (in glibc/localedata/locales/i18n): The "blank" characters are '\t', ' ',
+ U+1680, U+180E, U+2000..U+2006, U+2008..U+200A, U+205F, U+3000, and none
+ except the first two is present in a common 8-bit encoding. Therefore
+ the substitute for other platforms is not more complicated than this. */
+ return (c == ' ' || c == '\t');
+}
diff --git a/lib/isnan.c b/lib/isnan.c
new file mode 100644
index 0000000..e1e57b2
--- /dev/null
+++ b/lib/isnan.c
@@ -0,0 +1,189 @@
+/* Test for NaN that does not need libm.
+ Copyright (C) 2007-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Bruno Haible <bruno@clisp.org>, 2007. */
+
+#include <config.h>
+
+/* Specification. */
+#ifdef USE_LONG_DOUBLE
+/* Specification found in math.h or isnanl-nolibm.h. */
+extern int rpl_isnanl (long double x) _GL_ATTRIBUTE_CONST;
+#elif ! defined USE_FLOAT
+/* Specification found in math.h or isnand-nolibm.h. */
+extern int rpl_isnand (double x);
+#else /* defined USE_FLOAT */
+/* Specification found in math.h or isnanf-nolibm.h. */
+extern int rpl_isnanf (float x);
+#endif
+
+#include <float.h>
+#include <string.h>
+
+#include "float+.h"
+
+#ifdef USE_LONG_DOUBLE
+# define FUNC rpl_isnanl
+# define DOUBLE long double
+# define MAX_EXP LDBL_MAX_EXP
+# define MIN_EXP LDBL_MIN_EXP
+# if defined LDBL_EXPBIT0_WORD && defined LDBL_EXPBIT0_BIT
+# define KNOWN_EXPBIT0_LOCATION
+# define EXPBIT0_WORD LDBL_EXPBIT0_WORD
+# define EXPBIT0_BIT LDBL_EXPBIT0_BIT
+# endif
+# define SIZE SIZEOF_LDBL
+# define L_(literal) literal##L
+#elif ! defined USE_FLOAT
+# define FUNC rpl_isnand
+# define DOUBLE double
+# define MAX_EXP DBL_MAX_EXP
+# define MIN_EXP DBL_MIN_EXP
+# if defined DBL_EXPBIT0_WORD && defined DBL_EXPBIT0_BIT
+# define KNOWN_EXPBIT0_LOCATION
+# define EXPBIT0_WORD DBL_EXPBIT0_WORD
+# define EXPBIT0_BIT DBL_EXPBIT0_BIT
+# endif
+# define SIZE SIZEOF_DBL
+# define L_(literal) literal
+#else /* defined USE_FLOAT */
+# define FUNC rpl_isnanf
+# define DOUBLE float
+# define MAX_EXP FLT_MAX_EXP
+# define MIN_EXP FLT_MIN_EXP
+# if defined FLT_EXPBIT0_WORD && defined FLT_EXPBIT0_BIT
+# define KNOWN_EXPBIT0_LOCATION
+# define EXPBIT0_WORD FLT_EXPBIT0_WORD
+# define EXPBIT0_BIT FLT_EXPBIT0_BIT
+# endif
+# define SIZE SIZEOF_FLT
+# define L_(literal) literal##f
+#endif
+
+#define EXP_MASK ((MAX_EXP - MIN_EXP) | 7)
+
+#define NWORDS \
+ ((sizeof (DOUBLE) + sizeof (unsigned int) - 1) / sizeof (unsigned int))
+typedef union { DOUBLE value; unsigned int word[NWORDS]; } memory_double;
+
+/* Most hosts nowadays use IEEE floating point, so they use IEC 60559
+ representations, have infinities and NaNs, and do not trap on
+ exceptions. Define IEEE_FLOATING_POINT if this host is one of the
+ typical ones. The C11 macro __STDC_IEC_559__ is close to what is
+ wanted here, but is not quite right because this file does not require
+ all the features of C11 Annex F (and does not require C11 at all,
+ for that matter). */
+
+#define IEEE_FLOATING_POINT (FLT_RADIX == 2 && FLT_MANT_DIG == 24 \
+ && FLT_MIN_EXP == -125 && FLT_MAX_EXP == 128)
+
+int
+FUNC (DOUBLE x)
+{
+#if defined KNOWN_EXPBIT0_LOCATION && IEEE_FLOATING_POINT
+# if defined USE_LONG_DOUBLE && ((defined __ia64 && LDBL_MANT_DIG == 64) || (defined __x86_64__ || defined __amd64__) || (defined __i386 || defined __i386__ || defined _I386 || defined _M_IX86 || defined _X86_)) && !HAVE_SAME_LONG_DOUBLE_AS_DOUBLE
+ /* Special CPU dependent code is needed to treat bit patterns outside the
+ IEEE 754 specification (such as Pseudo-NaNs, Pseudo-Infinities,
+ Pseudo-Zeroes, Unnormalized Numbers, and Pseudo-Denormals) as NaNs.
+ These bit patterns are:
+ - exponent = 0x0001..0x7FFF, mantissa bit 63 = 0,
+ - exponent = 0x0000, mantissa bit 63 = 1.
+ The NaN bit pattern is:
+ - exponent = 0x7FFF, mantissa >= 0x8000000000000001. */
+ memory_double m;
+ unsigned int exponent;
+
+ m.value = x;
+ exponent = (m.word[EXPBIT0_WORD] >> EXPBIT0_BIT) & EXP_MASK;
+# ifdef WORDS_BIGENDIAN
+ /* Big endian: EXPBIT0_WORD = 0, EXPBIT0_BIT = 16. */
+ if (exponent == 0)
+ return 1 & (m.word[0] >> 15);
+ else if (exponent == EXP_MASK)
+ return (((m.word[0] ^ 0x8000U) << 16) | m.word[1] | (m.word[2] >> 16)) != 0;
+ else
+ return 1 & ~(m.word[0] >> 15);
+# else
+ /* Little endian: EXPBIT0_WORD = 2, EXPBIT0_BIT = 0. */
+ if (exponent == 0)
+ return (m.word[1] >> 31);
+ else if (exponent == EXP_MASK)
+ return ((m.word[1] ^ 0x80000000U) | m.word[0]) != 0;
+ else
+ return (m.word[1] >> 31) ^ 1;
+# endif
+# else
+ /* Be careful to not do any floating-point operation on x, such as x == x,
+ because x may be a signaling NaN. */
+# if defined __SUNPRO_C || defined __ICC || defined _MSC_VER \
+ || defined __DECC || defined __TINYC__ \
+ || (defined __sgi && !defined __GNUC__)
+ /* The Sun C 5.0, Intel ICC 10.0, Microsoft Visual C/C++ 9.0, Compaq (ex-DEC)
+ 6.4, and TinyCC compilers don't recognize the initializers as constant
+ expressions. The Compaq compiler also fails when constant-folding
+ 0.0 / 0.0 even when constant-folding is not required. The Microsoft
+ Visual C/C++ compiler also fails when constant-folding 1.0 / 0.0 even
+ when constant-folding is not required. The SGI MIPSpro C compiler
+ complains about "floating-point operation result is out of range". */
+ static DOUBLE zero = L_(0.0);
+ memory_double nan;
+ DOUBLE plus_inf = L_(1.0) / zero;
+ DOUBLE minus_inf = -L_(1.0) / zero;
+ nan.value = zero / zero;
+# else
+ static memory_double nan = { L_(0.0) / L_(0.0) };
+ static DOUBLE plus_inf = L_(1.0) / L_(0.0);
+ static DOUBLE minus_inf = -L_(1.0) / L_(0.0);
+# endif
+ {
+ memory_double m;
+
+ /* A NaN can be recognized through its exponent. But exclude +Infinity and
+ -Infinity, which have the same exponent. */
+ m.value = x;
+ if (((m.word[EXPBIT0_WORD] ^ nan.word[EXPBIT0_WORD])
+ & (EXP_MASK << EXPBIT0_BIT))
+ == 0)
+ return (memcmp (&m.value, &plus_inf, SIZE) != 0
+ && memcmp (&m.value, &minus_inf, SIZE) != 0);
+ else
+ return 0;
+ }
+# endif
+#else
+ /* The configuration did not find sufficient information, or does
+ not use IEEE floating point. Give up about the signaling NaNs;
+ handle only the quiet NaNs. */
+ if (x == x)
+ {
+# if defined USE_LONG_DOUBLE && ((defined __ia64 && LDBL_MANT_DIG == 64) || (defined __x86_64__ || defined __amd64__) || (defined __i386 || defined __i386__ || defined _I386 || defined _M_IX86 || defined _X86_)) && !HAVE_SAME_LONG_DOUBLE_AS_DOUBLE
+ /* Detect any special bit patterns that pass ==; see comment above. */
+ memory_double m1;
+ memory_double m2;
+
+ memset (&m1.value, 0, SIZE);
+ memset (&m2.value, 0, SIZE);
+ m1.value = x;
+ m2.value = x + (x ? 0.0L : -0.0L);
+ if (memcmp (&m1.value, &m2.value, SIZE) != 0)
+ return 1;
+# endif
+ return 0;
+ }
+ else
+ return 1;
+#endif
+}
diff --git a/lib/isnand-nolibm.h b/lib/isnand-nolibm.h
new file mode 100644
index 0000000..dc47264
--- /dev/null
+++ b/lib/isnand-nolibm.h
@@ -0,0 +1,33 @@
+/* Test for NaN that does not need libm.
+ Copyright (C) 2007-2016 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 <http://www.gnu.org/licenses/>. */
+
+#if HAVE_ISNAND_IN_LIBC
+/* Get declaration of isnan macro. */
+# include <math.h>
+# if __GNUC__ >= 4
+ /* GCC 4.0 and newer provides three built-ins for isnan. */
+# undef isnand
+# define isnand(x) __builtin_isnan ((double)(x))
+# else
+# undef isnand
+# define isnand(x) isnan ((double)(x))
+# endif
+#else
+/* Test whether X is a NaN. */
+# undef isnand
+# define isnand rpl_isnand
+extern int isnand (double x);
+#endif
diff --git a/lib/isnand.c b/lib/isnand.c
new file mode 100644
index 0000000..405b23a
--- /dev/null
+++ b/lib/isnand.c
@@ -0,0 +1,19 @@
+/* Test for NaN that does not need libm.
+ Copyright (C) 2008-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Bruno Haible <bruno@clisp.org>, 2008. */
+
+#include "isnan.c"
diff --git a/lib/isnanf-nolibm.h b/lib/isnanf-nolibm.h
new file mode 100644
index 0000000..4e68cad
--- /dev/null
+++ b/lib/isnanf-nolibm.h
@@ -0,0 +1,40 @@
+/* Test for NaN that does not need libm.
+ Copyright (C) 2007-2016 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 <http://www.gnu.org/licenses/>. */
+
+#if HAVE_ISNANF_IN_LIBC
+/* Get declaration of isnan macro or (older) isnanf function. */
+# include <math.h>
+# if __GNUC__ >= 4
+ /* GCC 4.0 and newer provides three built-ins for isnan. */
+# undef isnanf
+# define isnanf(x) __builtin_isnanf ((float)(x))
+# elif defined isnan
+# undef isnanf
+# define isnanf(x) isnan ((float)(x))
+# else
+ /* Get declaration of isnanf(), if not declared in <math.h>. */
+# if defined __sgi
+ /* We can't include <ieeefp.h>, because it conflicts with our definition of
+ isnand. Therefore declare isnanf separately. */
+extern int isnanf (float x);
+# endif
+# endif
+#else
+/* Test whether X is a NaN. */
+# undef isnanf
+# define isnanf rpl_isnanf
+extern int isnanf (float x);
+#endif
diff --git a/lib/isnanf.c b/lib/isnanf.c
new file mode 100644
index 0000000..d1e3fe9
--- /dev/null
+++ b/lib/isnanf.c
@@ -0,0 +1,20 @@
+/* Test for NaN that does not need libm.
+ Copyright (C) 2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Bruno Haible <bruno@clisp.org>, 2007. */
+
+#define USE_FLOAT
+#include "isnan.c"
diff --git a/lib/isnanl-nolibm.h b/lib/isnanl-nolibm.h
new file mode 100644
index 0000000..efd9199
--- /dev/null
+++ b/lib/isnanl-nolibm.h
@@ -0,0 +1,33 @@
+/* Test for NaN that does not need libm.
+ Copyright (C) 2007-2016 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 <http://www.gnu.org/licenses/>. */
+
+#if HAVE_ISNANL_IN_LIBC
+/* Get declaration of isnan macro or (older) isnanl function. */
+# include <math.h>
+# if __GNUC__ >= 4
+ /* GCC 4.0 and newer provides three built-ins for isnan. */
+# undef isnanl
+# define isnanl(x) __builtin_isnanl ((long double)(x))
+# elif defined isnan
+# undef isnanl
+# define isnanl(x) isnan ((long double)(x))
+# endif
+#else
+/* Test whether X is a NaN. */
+# undef isnanl
+# define isnanl rpl_isnanl
+extern int isnanl (long double x);
+#endif
diff --git a/lib/isnanl.c b/lib/isnanl.c
new file mode 100644
index 0000000..67d39d1
--- /dev/null
+++ b/lib/isnanl.c
@@ -0,0 +1,20 @@
+/* Test for NaN that does not need libm.
+ Copyright (C) 2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Bruno Haible <bruno@clisp.org>, 2007. */
+
+#define USE_LONG_DOUBLE
+#include "isnan.c"
diff --git a/lib/free.c b/lib/iswblank.c
index 73a125a..8d47ee5 100644
--- a/lib/free.c
+++ b/lib/iswblank.c
@@ -1,10 +1,9 @@
-/* Work around incompatibility on older systems where free (NULL) fails.
-
- Copyright (C) 2003, 2006 Free Software Foundation, Inc.
+/* Test wide character for being blank.
+ Copyright (C) 2008-2016 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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -12,20 +11,16 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-/* written by Paul Eggert */
+ You should have received a copy of the GNU General Public License along
+ with this program; if not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
-#undef free
-#include <stdlib.h>
+/* Specification. */
+#include <wctype.h>
-void
-rpl_free (void *p)
+int
+iswblank (wint_t wc)
{
- if (p)
- free (p);
+ return wc == ' ' || wc == '\t';
}
diff --git a/lib/itold.c b/lib/itold.c
new file mode 100644
index 0000000..5533392
--- /dev/null
+++ b/lib/itold.c
@@ -0,0 +1,28 @@
+/* Replacement for 'int' to 'long double' conversion routine.
+ Copyright (C) 2011-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2011.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <float.h>
+
+void
+_Qp_itoq (long double *result, int a)
+{
+ /* Convert from 'int' to 'double', then from 'double' to 'long double'. */
+ *result = (double) a;
+}
diff --git a/lib/langinfo.in.h b/lib/langinfo.in.h
new file mode 100644
index 0000000..e11617c
--- /dev/null
+++ b/lib/langinfo.in.h
@@ -0,0 +1,194 @@
+/* Substitute for and wrapper around <langinfo.h>.
+ Copyright (C) 2009-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+/*
+ * POSIX <langinfo.h> for platforms that lack it or have an incomplete one.
+ * <http://www.opengroup.org/onlinepubs/9699919799/basedefs/langinfo.h.html>
+ */
+
+#ifndef _@GUARD_PREFIX@_LANGINFO_H
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+/* The include_next requires a split double-inclusion guard. */
+#if @HAVE_LANGINFO_H@
+# @INCLUDE_NEXT@ @NEXT_LANGINFO_H@
+#endif
+
+#ifndef _@GUARD_PREFIX@_LANGINFO_H
+#define _@GUARD_PREFIX@_LANGINFO_H
+
+
+#if !@HAVE_LANGINFO_H@
+
+/* A platform that lacks <langinfo.h>. */
+
+/* Assume that it also lacks <nl_types.h> and the nl_item type. */
+# if !GNULIB_defined_nl_item
+typedef int nl_item;
+# define GNULIB_defined_nl_item 1
+# endif
+
+/* nl_langinfo items of the LC_CTYPE category */
+# define CODESET 10000
+/* nl_langinfo items of the LC_NUMERIC category */
+# define RADIXCHAR 10001
+# define DECIMAL_POINT RADIXCHAR
+# define THOUSEP 10002
+# define THOUSANDS_SEP THOUSEP
+# define GROUPING 10114
+/* nl_langinfo items of the LC_TIME category */
+# define D_T_FMT 10003
+# define D_FMT 10004
+# define T_FMT 10005
+# define T_FMT_AMPM 10006
+# define AM_STR 10007
+# define PM_STR 10008
+# define DAY_1 10009
+# define DAY_2 (DAY_1 + 1)
+# define DAY_3 (DAY_1 + 2)
+# define DAY_4 (DAY_1 + 3)
+# define DAY_5 (DAY_1 + 4)
+# define DAY_6 (DAY_1 + 5)
+# define DAY_7 (DAY_1 + 6)
+# define ABDAY_1 10016
+# define ABDAY_2 (ABDAY_1 + 1)
+# define ABDAY_3 (ABDAY_1 + 2)
+# define ABDAY_4 (ABDAY_1 + 3)
+# define ABDAY_5 (ABDAY_1 + 4)
+# define ABDAY_6 (ABDAY_1 + 5)
+# define ABDAY_7 (ABDAY_1 + 6)
+# define MON_1 10023
+# define MON_2 (MON_1 + 1)
+# define MON_3 (MON_1 + 2)
+# define MON_4 (MON_1 + 3)
+# define MON_5 (MON_1 + 4)
+# define MON_6 (MON_1 + 5)
+# define MON_7 (MON_1 + 6)
+# define MON_8 (MON_1 + 7)
+# define MON_9 (MON_1 + 8)
+# define MON_10 (MON_1 + 9)
+# define MON_11 (MON_1 + 10)
+# define MON_12 (MON_1 + 11)
+# define ABMON_1 10035
+# define ABMON_2 (ABMON_1 + 1)
+# define ABMON_3 (ABMON_1 + 2)
+# define ABMON_4 (ABMON_1 + 3)
+# define ABMON_5 (ABMON_1 + 4)
+# define ABMON_6 (ABMON_1 + 5)
+# define ABMON_7 (ABMON_1 + 6)
+# define ABMON_8 (ABMON_1 + 7)
+# define ABMON_9 (ABMON_1 + 8)
+# define ABMON_10 (ABMON_1 + 9)
+# define ABMON_11 (ABMON_1 + 10)
+# define ABMON_12 (ABMON_1 + 11)
+# define ERA 10047
+# define ERA_D_FMT 10048
+# define ERA_D_T_FMT 10049
+# define ERA_T_FMT 10050
+# define ALT_DIGITS 10051
+/* nl_langinfo items of the LC_MONETARY category */
+# define CRNCYSTR 10052
+# define CURRENCY_SYMBOL CRNCYSTR
+# define INT_CURR_SYMBOL 10100
+# define MON_DECIMAL_POINT 10101
+# define MON_THOUSANDS_SEP 10102
+# define MON_GROUPING 10103
+# define POSITIVE_SIGN 10104
+# define NEGATIVE_SIGN 10105
+# define FRAC_DIGITS 10106
+# define INT_FRAC_DIGITS 10107
+# define P_CS_PRECEDES 10108
+# define N_CS_PRECEDES 10109
+# define P_SEP_BY_SPACE 10110
+# define N_SEP_BY_SPACE 10111
+# define P_SIGN_POSN 10112
+# define N_SIGN_POSN 10113
+/* nl_langinfo items of the LC_MESSAGES category */
+# define YESEXPR 10053
+# define NOEXPR 10054
+
+#else
+
+/* A platform that has <langinfo.h>. */
+
+# if !@HAVE_LANGINFO_CODESET@
+# define CODESET 10000
+# define GNULIB_defined_CODESET 1
+# endif
+
+# if !@HAVE_LANGINFO_T_FMT_AMPM@
+# define T_FMT_AMPM 10006
+# define GNULIB_defined_T_FMT_AMPM 1
+# endif
+
+# if !@HAVE_LANGINFO_ERA@
+# define ERA 10047
+# define ERA_D_FMT 10048
+# define ERA_D_T_FMT 10049
+# define ERA_T_FMT 10050
+# define ALT_DIGITS 10051
+# define GNULIB_defined_ERA 1
+# endif
+
+# if !@HAVE_LANGINFO_YESEXPR@
+# define YESEXPR 10053
+# define NOEXPR 10054
+# define GNULIB_defined_YESEXPR 1
+# endif
+
+#endif
+
+/* The definitions of _GL_FUNCDECL_RPL etc. are copied here. */
+
+/* The definition of _GL_WARN_ON_USE is copied here. */
+
+/* Declare overridden functions. */
+
+
+/* Return a piece of locale dependent information.
+ Note: The difference between nl_langinfo (CODESET) and locale_charset ()
+ is that the latter normalizes the encoding names to GNU conventions. */
+
+#if @GNULIB_NL_LANGINFO@
+# if @REPLACE_NL_LANGINFO@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef nl_langinfo
+# define nl_langinfo rpl_nl_langinfo
+# endif
+_GL_FUNCDECL_RPL (nl_langinfo, char *, (nl_item item));
+_GL_CXXALIAS_RPL (nl_langinfo, char *, (nl_item item));
+# else
+# if !@HAVE_NL_LANGINFO@
+_GL_FUNCDECL_SYS (nl_langinfo, char *, (nl_item item));
+# endif
+_GL_CXXALIAS_SYS (nl_langinfo, char *, (nl_item item));
+# endif
+_GL_CXXALIASWARN (nl_langinfo);
+#elif defined GNULIB_POSIXCHECK
+# undef nl_langinfo
+# if HAVE_RAW_DECL_NL_LANGINFO
+_GL_WARN_ON_USE (nl_langinfo, "nl_langinfo is not portable - "
+ "use gnulib module nl_langinfo for portability");
+# endif
+#endif
+
+
+#endif /* _@GUARD_PREFIX@_LANGINFO_H */
+#endif /* _@GUARD_PREFIX@_LANGINFO_H */
diff --git a/lib/lchmod.h b/lib/lchmod.h
deleted file mode 100644
index d12f94a..0000000
--- a/lib/lchmod.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/* Provide a replacement for lchmod on hosts that lack it.
-
- Copyright (C) 2005 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-/* Written by Paul Eggert. */
-
-#include <sys/types.h>
-#include <sys/stat.h>
-
-#ifndef HAVE_LCHMOD
-
-/* The lchmod replacement follows symbolic links. Callers should take
- this into account; lchmod should be applied only to arguments that
- are known to not be symbolic links. On hosts that lack lchmod,
- this can lead to race conditions between the check and the
- invocation of lchmod, but we know of no workarounds that are
- reliable in general. You might try requesting support for lchmod
- from your operating system supplier. */
-
-# define lchmod chmod
-#endif
diff --git a/lib/lchown.c b/lib/lchown.c
index fa0826e..5d60ba7 100644
--- a/lib/lchown.c
+++ b/lib/lchown.c
@@ -1,12 +1,12 @@
/* Provide a stub lchown function for systems that lack it.
- Copyright (C) 1998, 1999, 2002, 2004, 2006 Free Software
+ Copyright (C) 1998-1999, 2002, 2004, 2006-2007, 2009-2016 Free Software
Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,17 +14,27 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* written by Jim Meyering */
#include <config.h>
-#include "lchown.h"
+#include <unistd.h>
+#include <errno.h>
+#include <stdbool.h>
+#include <string.h>
#include <sys/stat.h>
+#if !HAVE_LCHOWN
+
+/* If the system chown does not follow symlinks, we don't want it
+ replaced by gnulib's chown, which does follow symlinks. */
+# if CHOWN_MODIFIES_SYMLINK
+# undef chown
+# endif
+
/* Work just like chown, except when FILE is a symbolic link.
In that case, set errno to EOPNOTSUPP and return -1.
But if autoconf tests determined that chown modifies
@@ -33,7 +43,8 @@
int
lchown (const char *file, uid_t uid, gid_t gid)
{
-#if ! CHOWN_MODIFIES_SYMLINK
+# if HAVE_CHOWN
+# if ! CHOWN_MODIFIES_SYMLINK
struct stat stats;
if (lstat (file, &stats) == 0 && S_ISLNK (stats.st_mode))
@@ -41,7 +52,66 @@ lchown (const char *file, uid_t uid, gid_t gid)
errno = EOPNOTSUPP;
return -1;
}
-#endif
+# endif
return chown (file, uid, gid);
+
+# else /* !HAVE_CHOWN */
+ errno = ENOSYS;
+ return -1;
+# endif
+}
+
+#else /* HAVE_LCHOWN */
+
+# undef lchown
+
+/* Work around trailing slash bugs in lchown. */
+int
+rpl_lchown (const char *file, uid_t uid, gid_t gid)
+{
+ bool stat_valid = false;
+ int result;
+
+# if CHOWN_CHANGE_TIME_BUG
+ struct stat st;
+
+ if (gid != (gid_t) -1 || uid != (uid_t) -1)
+ {
+ if (lstat (file, &st))
+ return -1;
+ stat_valid = true;
+ if (!S_ISLNK (st.st_mode))
+ return chown (file, uid, gid);
+ }
+# endif
+
+# if CHOWN_TRAILING_SLASH_BUG
+ if (!stat_valid)
+ {
+ size_t len = strlen (file);
+ if (len && file[len - 1] == '/')
+ return chown (file, uid, gid);
+ }
+# endif
+
+ result = lchown (file, uid, gid);
+
+# if CHOWN_CHANGE_TIME_BUG && HAVE_LCHMOD
+ if (result == 0 && stat_valid
+ && (uid == st.st_uid || uid == (uid_t) -1)
+ && (gid == st.st_gid || gid == (gid_t) -1))
+ {
+ /* No change in ownership, but at least one argument was not -1,
+ so we are required to update ctime. Since lchown succeeded,
+ we assume that lchmod will do likewise. But if the system
+ lacks lchmod and lutimes, we are out of luck. Oh well. */
+ result = lchmod (file, st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO
+ | S_ISUID | S_ISGID | S_ISVTX));
+ }
+# endif
+
+ return result;
}
+
+#endif /* HAVE_LCHOWN */
diff --git a/lib/lchown.h b/lib/lchown.h
deleted file mode 100644
index 6816d1f..0000000
--- a/lib/lchown.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/* Declare a replacement for lchown on hosts that lack it.
-
- Copyright (C) 2006 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-/* Written by Jim Meyering. */
-
-#include <errno.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#if HAVE_DECL_LCHOWN
-# if ! HAVE_LCHOWN
-# undef lchown
-# define lchown rpl_chown
-# endif
-#else
-int lchown (char const *, uid_t, gid_t);
-#endif
-
-/* Some systems don't have EOPNOTSUPP. */
-#ifndef EOPNOTSUPP
-# ifdef ENOTSUP
-# define EOPNOTSUPP ENOTSUP
-# else
-/* Some systems don't have ENOTSUP either. */
-# define EOPNOTSUPP EINVAL
-# endif
-#endif
diff --git a/lib/ldtoastr.c b/lib/ldtoastr.c
new file mode 100644
index 0000000..bf54a35
--- /dev/null
+++ b/lib/ldtoastr.c
@@ -0,0 +1,2 @@
+#define LENGTH 3
+#include "ftoastr.c"
diff --git a/lib/linebuffer.c b/lib/linebuffer.c
index 3f1e45b..ba0cc2c 100644
--- a/lib/linebuffer.c
+++ b/lib/linebuffer.c
@@ -1,12 +1,12 @@
/* linebuffer.c -- read arbitrarily long lines
- Copyright (C) 1986, 1991, 1998, 1999, 2001, 2003, 2004, 2006 Free
- Software Foundation, Inc.
+ Copyright (C) 1986, 1991, 1998-1999, 2001, 2003-2004, 2006-2007, 2009-2016
+ Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Richard Stallman. */
@@ -40,17 +39,25 @@ initbuffer (struct linebuffer *linebuffer)
memset (linebuffer, 0, sizeof *linebuffer);
}
+struct linebuffer *
+readlinebuffer (struct linebuffer *linebuffer, FILE *stream)
+{
+ return readlinebuffer_delim (linebuffer, stream, '\n');
+}
+
/* Read an arbitrarily long line of text from STREAM into LINEBUFFER.
- Keep the newline; append a newline if it's the last line of a file
- that ends in a non-newline character. Do not null terminate.
+ Consider lines to be terminated by DELIMITER.
+ Keep the delimiter; append DELIMITER if it's the last line of a file
+ that ends in a character other than DELIMITER. Do not NUL-terminate.
Therefore the stream can contain NUL bytes, and the length
- (including the newline) is returned in linebuffer->length.
+ (including the delimiter) is returned in linebuffer->length.
Return NULL when stream is empty. Return NULL and set errno upon
error; callers can distinguish this case from the empty case by
invoking ferror (stream).
Otherwise, return LINEBUFFER. */
struct linebuffer *
-readlinebuffer (struct linebuffer *linebuffer, FILE *stream)
+readlinebuffer_delim (struct linebuffer *linebuffer, FILE *stream,
+ char delimiter)
{
int c;
char *buffer = linebuffer->buffer;
@@ -64,24 +71,24 @@ readlinebuffer (struct linebuffer *linebuffer, FILE *stream)
{
c = getc (stream);
if (c == EOF)
- {
- if (p == buffer || ferror (stream))
- return NULL;
- if (p[-1] == '\n')
- break;
- c = '\n';
- }
+ {
+ if (p == buffer || ferror (stream))
+ return NULL;
+ if (p[-1] == delimiter)
+ break;
+ c = delimiter;
+ }
if (p == end)
- {
- size_t oldsize = linebuffer->size;
- buffer = x2realloc (buffer, &linebuffer->size);
- p = buffer + oldsize;
- linebuffer->buffer = buffer;
- end = buffer + linebuffer->size;
- }
+ {
+ size_t oldsize = linebuffer->size;
+ buffer = x2realloc (buffer, &linebuffer->size);
+ p = buffer + oldsize;
+ linebuffer->buffer = buffer;
+ end = buffer + linebuffer->size;
+ }
*p++ = c;
}
- while (c != '\n');
+ while (c != delimiter);
linebuffer->length = p - buffer;
return linebuffer;
diff --git a/lib/linebuffer.h b/lib/linebuffer.h
index 16b4b5a..64181af 100644
--- a/lib/linebuffer.h
+++ b/lib/linebuffer.h
@@ -1,12 +1,12 @@
/* linebuffer.h -- declarations for reading arbitrarily long lines
- Copyright (C) 1986, 1991, 1998, 1999, 2002, 2003 Free Software
- Foundation, Inc.
+ Copyright (C) 1986, 1991, 1998-1999, 2002-2003, 2007, 2009-2016 Free
+ Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,20 +14,19 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#if !defined LINEBUFFER_H
# define LINEBUFFER_H
# include <stdio.h>
-/* A `struct linebuffer' holds a line of text. */
+/* A 'struct linebuffer' holds a line of text. */
struct linebuffer
{
- size_t size; /* Allocated. */
- size_t length; /* Used. */
+ size_t size; /* Allocated. */
+ size_t length; /* Used. */
char *buffer;
};
@@ -35,9 +34,17 @@ struct linebuffer
void initbuffer (struct linebuffer *linebuffer);
/* Read an arbitrarily long line of text from STREAM into LINEBUFFER.
+ Consider lines to be terminated by DELIMITER.
+ Keep the delimiter; append DELIMITER if we reach EOF and it wasn't
+ the last character in the file. Do not NUL-terminate.
+ Return LINEBUFFER, except at end of file return NULL. */
+struct linebuffer *readlinebuffer_delim (struct linebuffer *linebuffer,
+ FILE *stream, char delimiter);
+
+/* Read an arbitrarily long line of text from STREAM into LINEBUFFER.
Keep the newline; append a newline if it's the last line of a file
- that ends in a non-newline character. Do not null terminate.
- Return LINEBUFFER, except at end of file return 0. */
+ that ends in a non-newline character. Do not NUL-terminate.
+ Return LINEBUFFER, except at end of file return NULL. */
struct linebuffer *readlinebuffer (struct linebuffer *linebuffer, FILE *stream);
/* Free linebuffer LINEBUFFER and its data, all allocated with malloc. */
diff --git a/lib/link.c b/lib/link.c
new file mode 100644
index 0000000..b8d7caa
--- /dev/null
+++ b/lib/link.c
@@ -0,0 +1,211 @@
+/* Emulate link on platforms that lack it, namely native Windows platforms.
+
+ Copyright (C) 2009-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+#include <unistd.h>
+
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+
+#if !HAVE_LINK
+# if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+
+# define WIN32_LEAN_AND_MEAN
+# include <windows.h>
+
+/* CreateHardLink was introduced only in Windows 2000. */
+typedef BOOL (WINAPI * CreateHardLinkFuncType) (LPCTSTR lpFileName,
+ LPCTSTR lpExistingFileName,
+ LPSECURITY_ATTRIBUTES lpSecurityAttributes);
+static CreateHardLinkFuncType CreateHardLinkFunc = NULL;
+static BOOL initialized = FALSE;
+
+static void
+initialize (void)
+{
+ HMODULE kernel32 = GetModuleHandle ("kernel32.dll");
+ if (kernel32 != NULL)
+ {
+ CreateHardLinkFunc =
+ (CreateHardLinkFuncType) GetProcAddress (kernel32, "CreateHardLinkA");
+ }
+ initialized = TRUE;
+}
+
+int
+link (const char *file1, const char *file2)
+{
+ char *dir;
+ size_t len1 = strlen (file1);
+ size_t len2 = strlen (file2);
+ if (!initialized)
+ initialize ();
+ if (CreateHardLinkFunc == NULL)
+ {
+ /* System does not support hard links. */
+ errno = EPERM;
+ return -1;
+ }
+ /* Reject trailing slashes on non-directories; mingw does not
+ support hard-linking directories. */
+ if ((len1 && (file1[len1 - 1] == '/' || file1[len1 - 1] == '\\'))
+ || (len2 && (file2[len2 - 1] == '/' || file2[len2 - 1] == '\\')))
+ {
+ struct stat st;
+ if (stat (file1, &st) == 0 && S_ISDIR (st.st_mode))
+ errno = EPERM;
+ else
+ errno = ENOTDIR;
+ return -1;
+ }
+ /* CreateHardLink("b/.","a",NULL) creates file "b", so we must check
+ that dirname(file2) exists. */
+ dir = strdup (file2);
+ if (!dir)
+ return -1;
+ {
+ struct stat st;
+ char *p = strchr (dir, '\0');
+ while (dir < p && (*--p != '/' && *p != '\\'));
+ *p = '\0';
+ if (p != dir && stat (dir, &st) == -1)
+ {
+ int saved_errno = errno;
+ free (dir);
+ errno = saved_errno;
+ return -1;
+ }
+ free (dir);
+ }
+ /* Now create the link. */
+ if (CreateHardLinkFunc (file2, file1, NULL) == 0)
+ {
+ /* It is not documented which errors CreateHardLink() can produce.
+ * The following conversions are based on tests on a Windows XP SP2
+ * system. */
+ DWORD err = GetLastError ();
+ switch (err)
+ {
+ case ERROR_ACCESS_DENIED:
+ errno = EACCES;
+ break;
+
+ case ERROR_INVALID_FUNCTION: /* fs does not support hard links */
+ errno = EPERM;
+ break;
+
+ case ERROR_NOT_SAME_DEVICE:
+ errno = EXDEV;
+ break;
+
+ case ERROR_PATH_NOT_FOUND:
+ case ERROR_FILE_NOT_FOUND:
+ errno = ENOENT;
+ break;
+
+ case ERROR_INVALID_PARAMETER:
+ errno = ENAMETOOLONG;
+ break;
+
+ case ERROR_TOO_MANY_LINKS:
+ errno = EMLINK;
+ break;
+
+ case ERROR_ALREADY_EXISTS:
+ errno = EEXIST;
+ break;
+
+ default:
+ errno = EIO;
+ }
+ return -1;
+ }
+
+ return 0;
+}
+
+# else /* !Windows */
+
+# error "This platform lacks a link function, and Gnulib doesn't provide a replacement. This is a bug in Gnulib."
+
+# endif /* !Windows */
+#else /* HAVE_LINK */
+
+# undef link
+
+/* Create a hard link from FILE1 to FILE2, working around platform bugs. */
+int
+rpl_link (char const *file1, char const *file2)
+{
+ size_t len1;
+ size_t len2;
+ struct stat st;
+
+ /* Don't allow IRIX to dereference dangling file2 symlink. */
+ if (!lstat (file2, &st))
+ {
+ errno = EEXIST;
+ return -1;
+ }
+
+ /* Reject trailing slashes on non-directories. */
+ len1 = strlen (file1);
+ len2 = strlen (file2);
+ if ((len1 && file1[len1 - 1] == '/')
+ || (len2 && file2[len2 - 1] == '/'))
+ {
+ /* Let link() decide whether hard-linking directories is legal.
+ If stat() fails, then link() should fail for the same reason
+ (although on Solaris 9, link("file/","oops") mistakenly
+ succeeds); if stat() succeeds, require a directory. */
+ if (stat (file1, &st))
+ return -1;
+ if (!S_ISDIR (st.st_mode))
+ {
+ errno = ENOTDIR;
+ return -1;
+ }
+ }
+ else
+ {
+ /* Fix Cygwin 1.5.x bug where link("a","b/.") creates file "b". */
+ char *dir = strdup (file2);
+ char *p;
+ if (!dir)
+ return -1;
+ /* We already know file2 does not end in slash. Strip off the
+ basename, then check that the dirname exists. */
+ p = strrchr (dir, '/');
+ if (p)
+ {
+ *p = '\0';
+ if (stat (dir, &st) == -1)
+ {
+ int saved_errno = errno;
+ free (dir);
+ errno = saved_errno;
+ return -1;
+ }
+ }
+ free (dir);
+ }
+ return link (file1, file2);
+}
+#endif /* HAVE_LINK */
diff --git a/lib/linkat.c b/lib/linkat.c
new file mode 100644
index 0000000..c51fb0f
--- /dev/null
+++ b/lib/linkat.c
@@ -0,0 +1,357 @@
+/* Create a hard link relative to open directories.
+ Copyright (C) 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* written by Eric Blake */
+
+#include <config.h>
+
+#include <unistd.h>
+
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+
+#include "areadlink.h"
+#include "dirname.h"
+#include "filenamecat.h"
+#include "openat-priv.h"
+
+#if HAVE_SYS_PARAM_H
+# include <sys/param.h>
+#endif
+#ifndef MAXSYMLINKS
+# ifdef SYMLOOP_MAX
+# define MAXSYMLINKS SYMLOOP_MAX
+# else
+# define MAXSYMLINKS 20
+# endif
+#endif
+
+#if !HAVE_LINKAT || LINKAT_SYMLINK_NOTSUP
+
+/* Create a link. If FILE1 is a symlink, either create a hardlink to
+ that symlink, or fake it by creating an identical symlink. */
+# if LINK_FOLLOWS_SYMLINKS == 0
+# define link_immediate link
+# else
+static int
+link_immediate (char const *file1, char const *file2)
+{
+ char *target = areadlink (file1);
+ if (target)
+ {
+ /* A symlink cannot be modified in-place. Therefore, creating
+ an identical symlink behaves like a hard link to a symlink,
+ except for incorrect st_ino and st_nlink. However, we must
+ be careful of EXDEV. */
+ struct stat st1;
+ struct stat st2;
+ char *dir = mdir_name (file2);
+ if (!dir)
+ {
+ free (target);
+ errno = ENOMEM;
+ return -1;
+ }
+ if (lstat (file1, &st1) == 0 && stat (dir, &st2) == 0)
+ {
+ if (st1.st_dev == st2.st_dev)
+ {
+ int result = symlink (target, file2);
+ int saved_errno = errno;
+ free (target);
+ free (dir);
+ errno = saved_errno;
+ return result;
+ }
+ free (target);
+ free (dir);
+ errno = EXDEV;
+ return -1;
+ }
+ free (target);
+ free (dir);
+ }
+ if (errno == ENOMEM)
+ return -1;
+ return link (file1, file2);
+}
+# endif /* LINK_FOLLOWS_SYMLINKS == 0 */
+
+/* Create a link. If FILE1 is a symlink, create a hardlink to the
+ canonicalized file. */
+# if 0 < LINK_FOLLOWS_SYMLINKS
+# define link_follow link
+# else
+static int
+link_follow (char const *file1, char const *file2)
+{
+ char *name = (char *) file1;
+ char *target;
+ int result;
+ int i = MAXSYMLINKS;
+
+ /* Using realpath or canonicalize_file_name is too heavy-handed: we
+ don't need an absolute name, and we don't need to resolve
+ intermediate symlinks, just the basename of each iteration. */
+ while (i-- && (target = areadlink (name)))
+ {
+ if (IS_ABSOLUTE_FILE_NAME (target))
+ {
+ if (name != file1)
+ free (name);
+ name = target;
+ }
+ else
+ {
+ char *dir = mdir_name (name);
+ if (name != file1)
+ free (name);
+ if (!dir)
+ {
+ free (target);
+ errno = ENOMEM;
+ return -1;
+ }
+ name = mfile_name_concat (dir, target, NULL);
+ free (dir);
+ free (target);
+ if (!name)
+ {
+ errno = ENOMEM;
+ return -1;
+ }
+ }
+ }
+ if (i < 0)
+ {
+ target = NULL;
+ errno = ELOOP;
+ }
+ if (!target && errno != EINVAL)
+ {
+ if (name != file1)
+ {
+ int saved_errno = errno;
+ free (name);
+ errno = saved_errno;
+ }
+ return -1;
+ }
+ result = link (name, file2);
+ if (name != file1)
+ {
+ int saved_errno = errno;
+ free (name);
+ errno = saved_errno;
+ }
+ return result;
+}
+# endif /* 0 < LINK_FOLLOWS_SYMLINKS */
+
+/* On Solaris, link() doesn't follow symlinks by default, but does so as soon
+ as a library or executable takes part in the program that has been compiled
+ with "c99" or "cc -xc99=all" or "cc ... /usr/lib/values-xpg4.o ...". */
+# if LINK_FOLLOWS_SYMLINKS == -1
+
+/* Reduce the penalty of link_immediate and link_follow by incorporating the
+ knowledge that link()'s behaviour depends on the __xpg4 variable. */
+extern int __xpg4;
+
+static int
+solaris_optimized_link_immediate (char const *file1, char const *file2)
+{
+ if (__xpg4 == 0)
+ return link (file1, file2);
+ return link_immediate (file1, file2);
+}
+
+static int
+solaris_optimized_link_follow (char const *file1, char const *file2)
+{
+ if (__xpg4 != 0)
+ return link (file1, file2);
+ return link_follow (file1, file2);
+}
+
+# define link_immediate solaris_optimized_link_immediate
+# define link_follow solaris_optimized_link_follow
+
+# endif
+
+#endif /* !HAVE_LINKAT || LINKAT_SYMLINK_NOTSUP */
+
+#if !HAVE_LINKAT
+
+/* Create a link to FILE1, in the directory open on descriptor FD1, to FILE2,
+ in the directory open on descriptor FD2. If FILE1 is a symlink, FLAG
+ controls whether to dereference FILE1 first. If possible, do it without
+ changing the working directory. Otherwise, resort to using
+ save_cwd/fchdir, then rename/restore_cwd. If either the save_cwd or
+ the restore_cwd fails, then give a diagnostic and exit nonzero. */
+
+int
+linkat (int fd1, char const *file1, int fd2, char const *file2, int flag)
+{
+ if (flag & ~AT_SYMLINK_FOLLOW)
+ {
+ errno = EINVAL;
+ return -1;
+ }
+ return at_func2 (fd1, file1, fd2, file2,
+ flag ? link_follow : link_immediate);
+}
+
+#else /* HAVE_LINKAT */
+
+# undef linkat
+
+/* Create a link. If FILE1 is a symlink, create a hardlink to the
+ canonicalized file. */
+
+static int
+linkat_follow (int fd1, char const *file1, int fd2, char const *file2)
+{
+ char *name = (char *) file1;
+ char *target;
+ int result;
+ int i = MAXSYMLINKS;
+
+ /* There is no realpathat. */
+ while (i-- && (target = areadlinkat (fd1, name)))
+ {
+ if (IS_ABSOLUTE_FILE_NAME (target))
+ {
+ if (name != file1)
+ free (name);
+ name = target;
+ }
+ else
+ {
+ char *dir = mdir_name (name);
+ if (name != file1)
+ free (name);
+ if (!dir)
+ {
+ free (target);
+ errno = ENOMEM;
+ return -1;
+ }
+ name = mfile_name_concat (dir, target, NULL);
+ free (dir);
+ free (target);
+ if (!name)
+ {
+ errno = ENOMEM;
+ return -1;
+ }
+ }
+ }
+ if (i < 0)
+ {
+ target = NULL;
+ errno = ELOOP;
+ }
+ if (!target && errno != EINVAL)
+ {
+ if (name != file1)
+ {
+ int saved_errno = errno;
+ free (name);
+ errno = saved_errno;
+ }
+ return -1;
+ }
+ result = linkat (fd1, name, fd2, file2, 0);
+ if (name != file1)
+ {
+ int saved_errno = errno;
+ free (name);
+ errno = saved_errno;
+ }
+ return result;
+}
+
+
+/* Like linkat, but guarantee that AT_SYMLINK_FOLLOW works even on
+ older Linux kernels. */
+
+int
+rpl_linkat (int fd1, char const *file1, int fd2, char const *file2, int flag)
+{
+ if (flag & ~AT_SYMLINK_FOLLOW)
+ {
+ errno = EINVAL;
+ return -1;
+ }
+
+# if LINKAT_TRAILING_SLASH_BUG
+ /* Reject trailing slashes on non-directories. */
+ {
+ size_t len1 = strlen (file1);
+ size_t len2 = strlen (file2);
+ if ((len1 && file1[len1 - 1] == '/')
+ || (len2 && file2[len2 - 1] == '/'))
+ {
+ /* Let linkat() decide whether hard-linking directories is legal.
+ If fstatat() fails, then linkat() should fail for the same reason;
+ if fstatat() succeeds, require a directory. */
+ struct stat st;
+ if (fstatat (fd1, file1, &st, flag ? 0 : AT_SYMLINK_NOFOLLOW))
+ return -1;
+ if (!S_ISDIR (st.st_mode))
+ {
+ errno = ENOTDIR;
+ return -1;
+ }
+ }
+ }
+# endif
+
+ if (!flag)
+ {
+ int result = linkat (fd1, file1, fd2, file2, flag);
+# if LINKAT_SYMLINK_NOTSUP
+ /* OS X 10.10 has linkat() but it doesn't support
+ hardlinks to symlinks. Fallback to our emulation
+ in that case. */
+ if (result == -1 && (errno == ENOTSUP || errno == EOPNOTSUPP))
+ return at_func2 (fd1, file1, fd2, file2, link_immediate);
+# endif
+ return result;
+ }
+
+ /* Cache the information on whether the system call really works. */
+ {
+ static int have_follow_really; /* 0 = unknown, 1 = yes, -1 = no */
+ if (0 <= have_follow_really)
+ {
+ int result = linkat (fd1, file1, fd2, file2, flag);
+ if (!(result == -1 && errno == EINVAL))
+ {
+ have_follow_really = 1;
+ return result;
+ }
+ have_follow_really = -1;
+ }
+ }
+ return linkat_follow (fd1, file1, fd2, file2);
+}
+
+#endif /* HAVE_LINKAT */
diff --git a/lib/local.mk b/lib/local.mk
new file mode 100644
index 0000000..decbad6
--- /dev/null
+++ b/lib/local.mk
@@ -0,0 +1,5 @@
+include lib/gnulib.mk
+
+# Allow "make distdir" to succeed before "make all" has run.
+dist-hook: $(noinst_LIBRARIES)
+.PHONY: dist-hook
diff --git a/lib/localcharset.c b/lib/localcharset.c
index a0f7cca..b2a0369 100644
--- a/lib/localcharset.c
+++ b/lib/localcharset.c
@@ -1,10 +1,10 @@
/* Determine a canonical name for the current locale's character encoding.
- Copyright (C) 2000-2006 Free Software Foundation, Inc.
+ Copyright (C) 2000-2006, 2008-2016 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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ with this program; if not, see <http://www.gnu.org/licenses/>. */
/* Written by Bruno Haible <bruno@clisp.org>. */
@@ -23,21 +22,30 @@
/* Specification. */
#include "localcharset.h"
+#include <fcntl.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
+#if defined __APPLE__ && defined __MACH__ && HAVE_LANGINFO_CODESET
+# define DARWIN7 /* Darwin 7 or newer, i.e. Mac OS X 10.3 or newer */
+#endif
+
#if defined _WIN32 || defined __WIN32__
-# define WIN32_NATIVE
+# define WINDOWS_NATIVE
+# include <locale.h>
#endif
#if defined __EMX__
/* Assume EMX program runs on OS/2, even if compiled under DOS. */
-# define OS2
+# ifndef OS2
+# define OS2
+# endif
#endif
-#if !defined WIN32_NATIVE
+#if !defined WINDOWS_NATIVE
+# include <unistd.h>
# if HAVE_LANGINFO_CODESET
# include <langinfo.h>
# else
@@ -49,7 +57,7 @@
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
# endif
-#elif defined WIN32_NATIVE
+#elif defined WINDOWS_NATIVE
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
#endif
@@ -58,6 +66,11 @@
# include <os2.h>
#endif
+/* For MB_CUR_MAX_L */
+#if defined DARWIN7
+# include <xlocale.h>
+#endif
+
#if ENABLE_RELOCATABLE
# include "relocatable.h"
#else
@@ -69,8 +82,13 @@
# include "configmake.h"
#endif
+/* Define O_NOFOLLOW to 0 on platforms where it does not exist. */
+#ifndef O_NOFOLLOW
+# define O_NOFOLLOW 0
+#endif
+
#if defined _WIN32 || defined __WIN32__ || defined __CYGWIN__ || defined __EMX__ || defined __DJGPP__
- /* Win32, Cygwin, OS/2, DOS */
+ /* Native Windows, Cygwin, OS/2, DOS */
# define ISSLASH(C) ((C) == '/' || (C) == '\\')
#endif
@@ -110,160 +128,249 @@ get_charset_aliases (void)
cp = charset_aliases;
if (cp == NULL)
{
-#if !(defined VMS || defined WIN32_NATIVE || defined __CYGWIN__)
- FILE *fp;
+#if !(defined DARWIN7 || defined VMS || defined WINDOWS_NATIVE || defined __CYGWIN__ || defined OS2)
const char *dir;
const char *base = "charset.alias";
char *file_name;
/* Make it possible to override the charset.alias location. This is
- necessary for running the testsuite before "make install". */
+ necessary for running the testsuite before "make install". */
dir = getenv ("CHARSETALIASDIR");
if (dir == NULL || dir[0] == '\0')
- dir = relocate (LIBDIR);
+ dir = relocate (LIBDIR);
/* Concatenate dir and base into freshly allocated file_name. */
{
- size_t dir_len = strlen (dir);
- size_t base_len = strlen (base);
- int add_slash = (dir_len > 0 && !ISSLASH (dir[dir_len - 1]));
- file_name = (char *) malloc (dir_len + add_slash + base_len + 1);
- if (file_name != NULL)
- {
- memcpy (file_name, dir, dir_len);
- if (add_slash)
- file_name[dir_len] = DIRECTORY_SEPARATOR;
- memcpy (file_name + dir_len + add_slash, base, base_len + 1);
- }
+ size_t dir_len = strlen (dir);
+ size_t base_len = strlen (base);
+ int add_slash = (dir_len > 0 && !ISSLASH (dir[dir_len - 1]));
+ file_name = (char *) malloc (dir_len + add_slash + base_len + 1);
+ if (file_name != NULL)
+ {
+ memcpy (file_name, dir, dir_len);
+ if (add_slash)
+ file_name[dir_len] = DIRECTORY_SEPARATOR;
+ memcpy (file_name + dir_len + add_slash, base, base_len + 1);
+ }
}
- if (file_name == NULL || (fp = fopen (file_name, "r")) == NULL)
- /* Out of memory or file not found, treat it as empty. */
- cp = "";
+ if (file_name == NULL)
+ /* Out of memory. Treat the file as empty. */
+ cp = "";
else
- {
- /* Parse the file's contents. */
- char *res_ptr = NULL;
- size_t res_size = 0;
-
- for (;;)
- {
- int c;
- char buf1[50+1];
- char buf2[50+1];
- size_t l1, l2;
- char *old_res_ptr;
-
- c = getc (fp);
- if (c == EOF)
- break;
- if (c == '\n' || c == ' ' || c == '\t')
- continue;
- if (c == '#')
- {
- /* Skip comment, to end of line. */
- do
- c = getc (fp);
- while (!(c == EOF || c == '\n'));
- if (c == EOF)
- break;
- continue;
- }
- ungetc (c, fp);
- if (fscanf (fp, "%50s %50s", buf1, buf2) < 2)
- break;
- l1 = strlen (buf1);
- l2 = strlen (buf2);
- old_res_ptr = res_ptr;
- if (res_size == 0)
- {
- res_size = l1 + 1 + l2 + 1;
- res_ptr = (char *) malloc (res_size + 1);
- }
- else
- {
- res_size += l1 + 1 + l2 + 1;
- res_ptr = (char *) realloc (res_ptr, res_size + 1);
- }
- if (res_ptr == NULL)
- {
- /* Out of memory. */
- res_size = 0;
- if (old_res_ptr != NULL)
- free (old_res_ptr);
- break;
- }
- strcpy (res_ptr + res_size - (l2 + 1) - (l1 + 1), buf1);
- strcpy (res_ptr + res_size - (l2 + 1), buf2);
- }
- fclose (fp);
- if (res_size == 0)
- cp = "";
- else
- {
- *(res_ptr + res_size) = '\0';
- cp = res_ptr;
- }
- }
-
- if (file_name != NULL)
- free (file_name);
+ {
+ int fd;
+
+ /* Open the file. Reject symbolic links on platforms that support
+ O_NOFOLLOW. This is a security feature. Without it, an attacker
+ could retrieve parts of the contents (namely, the tail of the
+ first line that starts with "* ") of an arbitrary file by placing
+ a symbolic link to that file under the name "charset.alias" in
+ some writable directory and defining the environment variable
+ CHARSETALIASDIR to point to that directory. */
+ fd = open (file_name,
+ O_RDONLY | (HAVE_WORKING_O_NOFOLLOW ? O_NOFOLLOW : 0));
+ if (fd < 0)
+ /* File not found. Treat it as empty. */
+ cp = "";
+ else
+ {
+ FILE *fp;
+
+ fp = fdopen (fd, "r");
+ if (fp == NULL)
+ {
+ /* Out of memory. Treat the file as empty. */
+ close (fd);
+ cp = "";
+ }
+ else
+ {
+ /* Parse the file's contents. */
+ char *res_ptr = NULL;
+ size_t res_size = 0;
+
+ for (;;)
+ {
+ int c;
+ char buf1[50+1];
+ char buf2[50+1];
+ size_t l1, l2;
+ char *old_res_ptr;
+
+ c = getc (fp);
+ if (c == EOF)
+ break;
+ if (c == '\n' || c == ' ' || c == '\t')
+ continue;
+ if (c == '#')
+ {
+ /* Skip comment, to end of line. */
+ do
+ c = getc (fp);
+ while (!(c == EOF || c == '\n'));
+ if (c == EOF)
+ break;
+ continue;
+ }
+ ungetc (c, fp);
+ if (fscanf (fp, "%50s %50s", buf1, buf2) < 2)
+ break;
+ l1 = strlen (buf1);
+ l2 = strlen (buf2);
+ old_res_ptr = res_ptr;
+ if (res_size == 0)
+ {
+ res_size = l1 + 1 + l2 + 1;
+ res_ptr = (char *) malloc (res_size + 1);
+ }
+ else
+ {
+ res_size += l1 + 1 + l2 + 1;
+ res_ptr = (char *) realloc (res_ptr, res_size + 1);
+ }
+ if (res_ptr == NULL)
+ {
+ /* Out of memory. */
+ res_size = 0;
+ free (old_res_ptr);
+ break;
+ }
+ strcpy (res_ptr + res_size - (l2 + 1) - (l1 + 1), buf1);
+ strcpy (res_ptr + res_size - (l2 + 1), buf2);
+ }
+ fclose (fp);
+ if (res_size == 0)
+ cp = "";
+ else
+ {
+ *(res_ptr + res_size) = '\0';
+ cp = res_ptr;
+ }
+ }
+ }
+
+ free (file_name);
+ }
#else
+# if defined DARWIN7
+ /* To avoid the trouble of installing a file that is shared by many
+ GNU packages -- many packaging systems have problems with this --,
+ simply inline the aliases here. */
+ cp = "ISO8859-1" "\0" "ISO-8859-1" "\0"
+ "ISO8859-2" "\0" "ISO-8859-2" "\0"
+ "ISO8859-4" "\0" "ISO-8859-4" "\0"
+ "ISO8859-5" "\0" "ISO-8859-5" "\0"
+ "ISO8859-7" "\0" "ISO-8859-7" "\0"
+ "ISO8859-9" "\0" "ISO-8859-9" "\0"
+ "ISO8859-13" "\0" "ISO-8859-13" "\0"
+ "ISO8859-15" "\0" "ISO-8859-15" "\0"
+ "KOI8-R" "\0" "KOI8-R" "\0"
+ "KOI8-U" "\0" "KOI8-U" "\0"
+ "CP866" "\0" "CP866" "\0"
+ "CP949" "\0" "CP949" "\0"
+ "CP1131" "\0" "CP1131" "\0"
+ "CP1251" "\0" "CP1251" "\0"
+ "eucCN" "\0" "GB2312" "\0"
+ "GB2312" "\0" "GB2312" "\0"
+ "eucJP" "\0" "EUC-JP" "\0"
+ "eucKR" "\0" "EUC-KR" "\0"
+ "Big5" "\0" "BIG5" "\0"
+ "Big5HKSCS" "\0" "BIG5-HKSCS" "\0"
+ "GBK" "\0" "GBK" "\0"
+ "GB18030" "\0" "GB18030" "\0"
+ "SJIS" "\0" "SHIFT_JIS" "\0"
+ "ARMSCII-8" "\0" "ARMSCII-8" "\0"
+ "PT154" "\0" "PT154" "\0"
+ /*"ISCII-DEV" "\0" "?" "\0"*/
+ "*" "\0" "UTF-8" "\0";
+# endif
+
# if defined VMS
/* To avoid the troubles of an extra file charset.alias_vms in the
- sources of many GNU packages, simply inline the aliases here. */
+ sources of many GNU packages, simply inline the aliases here. */
/* The list of encodings is taken from the OpenVMS 7.3-1 documentation
- "Compaq C Run-Time Library Reference Manual for OpenVMS systems"
- section 10.7 "Handling Different Character Sets". */
+ "Compaq C Run-Time Library Reference Manual for OpenVMS systems"
+ section 10.7 "Handling Different Character Sets". */
cp = "ISO8859-1" "\0" "ISO-8859-1" "\0"
- "ISO8859-2" "\0" "ISO-8859-2" "\0"
- "ISO8859-5" "\0" "ISO-8859-5" "\0"
- "ISO8859-7" "\0" "ISO-8859-7" "\0"
- "ISO8859-8" "\0" "ISO-8859-8" "\0"
- "ISO8859-9" "\0" "ISO-8859-9" "\0"
- /* Japanese */
- "eucJP" "\0" "EUC-JP" "\0"
- "SJIS" "\0" "SHIFT_JIS" "\0"
- "DECKANJI" "\0" "DEC-KANJI" "\0"
- "SDECKANJI" "\0" "EUC-JP" "\0"
- /* Chinese */
- "eucTW" "\0" "EUC-TW" "\0"
- "DECHANYU" "\0" "DEC-HANYU" "\0"
- "DECHANZI" "\0" "GB2312" "\0"
- /* Korean */
- "DECKOREAN" "\0" "EUC-KR" "\0";
+ "ISO8859-2" "\0" "ISO-8859-2" "\0"
+ "ISO8859-5" "\0" "ISO-8859-5" "\0"
+ "ISO8859-7" "\0" "ISO-8859-7" "\0"
+ "ISO8859-8" "\0" "ISO-8859-8" "\0"
+ "ISO8859-9" "\0" "ISO-8859-9" "\0"
+ /* Japanese */
+ "eucJP" "\0" "EUC-JP" "\0"
+ "SJIS" "\0" "SHIFT_JIS" "\0"
+ "DECKANJI" "\0" "DEC-KANJI" "\0"
+ "SDECKANJI" "\0" "EUC-JP" "\0"
+ /* Chinese */
+ "eucTW" "\0" "EUC-TW" "\0"
+ "DECHANYU" "\0" "DEC-HANYU" "\0"
+ "DECHANZI" "\0" "GB2312" "\0"
+ /* Korean */
+ "DECKOREAN" "\0" "EUC-KR" "\0";
# endif
-# if defined WIN32_NATIVE || defined __CYGWIN__
+# if defined WINDOWS_NATIVE || defined __CYGWIN__
/* To avoid the troubles of installing a separate file in the same
- directory as the DLL and of retrieving the DLL's directory at
- runtime, simply inline the aliases here. */
+ directory as the DLL and of retrieving the DLL's directory at
+ runtime, simply inline the aliases here. */
cp = "CP936" "\0" "GBK" "\0"
- "CP1361" "\0" "JOHAB" "\0"
- "CP20127" "\0" "ASCII" "\0"
- "CP20866" "\0" "KOI8-R" "\0"
- "CP20936" "\0" "GB2312" "\0"
- "CP21866" "\0" "KOI8-RU" "\0"
- "CP28591" "\0" "ISO-8859-1" "\0"
- "CP28592" "\0" "ISO-8859-2" "\0"
- "CP28593" "\0" "ISO-8859-3" "\0"
- "CP28594" "\0" "ISO-8859-4" "\0"
- "CP28595" "\0" "ISO-8859-5" "\0"
- "CP28596" "\0" "ISO-8859-6" "\0"
- "CP28597" "\0" "ISO-8859-7" "\0"
- "CP28598" "\0" "ISO-8859-8" "\0"
- "CP28599" "\0" "ISO-8859-9" "\0"
- "CP28605" "\0" "ISO-8859-15" "\0"
- "CP38598" "\0" "ISO-8859-8" "\0"
- "CP51932" "\0" "EUC-JP" "\0"
- "CP51936" "\0" "GB2312" "\0"
- "CP51949" "\0" "EUC-KR" "\0"
- "CP51950" "\0" "EUC-TW" "\0"
- "CP54936" "\0" "GB18030" "\0"
- "CP65001" "\0" "UTF-8" "\0";
+ "CP1361" "\0" "JOHAB" "\0"
+ "CP20127" "\0" "ASCII" "\0"
+ "CP20866" "\0" "KOI8-R" "\0"
+ "CP20936" "\0" "GB2312" "\0"
+ "CP21866" "\0" "KOI8-RU" "\0"
+ "CP28591" "\0" "ISO-8859-1" "\0"
+ "CP28592" "\0" "ISO-8859-2" "\0"
+ "CP28593" "\0" "ISO-8859-3" "\0"
+ "CP28594" "\0" "ISO-8859-4" "\0"
+ "CP28595" "\0" "ISO-8859-5" "\0"
+ "CP28596" "\0" "ISO-8859-6" "\0"
+ "CP28597" "\0" "ISO-8859-7" "\0"
+ "CP28598" "\0" "ISO-8859-8" "\0"
+ "CP28599" "\0" "ISO-8859-9" "\0"
+ "CP28605" "\0" "ISO-8859-15" "\0"
+ "CP38598" "\0" "ISO-8859-8" "\0"
+ "CP51932" "\0" "EUC-JP" "\0"
+ "CP51936" "\0" "GB2312" "\0"
+ "CP51949" "\0" "EUC-KR" "\0"
+ "CP51950" "\0" "EUC-TW" "\0"
+ "CP54936" "\0" "GB18030" "\0"
+ "CP65001" "\0" "UTF-8" "\0";
+# endif
+# if defined OS2
+ /* To avoid the troubles of installing a separate file in the same
+ directory as the DLL and of retrieving the DLL's directory at
+ runtime, simply inline the aliases here. */
+
+ /* The list of encodings is taken from "List of OS/2 Codepages"
+ by Alex Taylor:
+ <http://altsan.org/os2/toolkits/uls/index.html#codepages>.
+ See also "IBM Globalization - Code page identifiers":
+ <http://www-01.ibm.com/software/globalization/cp/cp_cpgid.html>. */
+ cp = "CP813" "\0" "ISO-8859-7" "\0"
+ "CP878" "\0" "KOI8-R" "\0"
+ "CP819" "\0" "ISO-8859-1" "\0"
+ "CP912" "\0" "ISO-8859-2" "\0"
+ "CP913" "\0" "ISO-8859-3" "\0"
+ "CP914" "\0" "ISO-8859-4" "\0"
+ "CP915" "\0" "ISO-8859-5" "\0"
+ "CP916" "\0" "ISO-8859-8" "\0"
+ "CP920" "\0" "ISO-8859-9" "\0"
+ "CP921" "\0" "ISO-8859-13" "\0"
+ "CP923" "\0" "ISO-8859-15" "\0"
+ "CP954" "\0" "EUC-JP" "\0"
+ "CP964" "\0" "EUC-TW" "\0"
+ "CP970" "\0" "EUC-KR" "\0"
+ "CP1089" "\0" "ISO-8859-6" "\0"
+ "CP1208" "\0" "UTF-8" "\0"
+ "CP1381" "\0" "GB2312" "\0"
+ "CP1386" "\0" "GBK" "\0"
+ "CP3372" "\0" "EUC-JP" "\0";
# endif
#endif
@@ -288,7 +395,7 @@ locale_charset (void)
const char *codeset;
const char *aliases;
-#if !(defined WIN32_NATIVE || defined OS2)
+#if !(defined WINDOWS_NATIVE || defined OS2)
# if HAVE_LANGINFO_CODESET
@@ -296,10 +403,9 @@ locale_charset (void)
codeset = nl_langinfo (CODESET);
# ifdef __CYGWIN__
- /* Cygwin 2006 does not have locales. nl_langinfo (CODESET) always
- returns "US-ASCII". As long as this is not fixed, return the suffix
- of the locale name from the environment variables (if present) or
- the codepage as a number. */
+ /* Cygwin < 1.7 does not have locales. nl_langinfo (CODESET) always
+ returns "US-ASCII". Return the suffix of the locale name from the
+ environment variables (if present) or the codepage as a number. */
if (codeset != NULL && strcmp (codeset, "US-ASCII") == 0)
{
const char *locale;
@@ -307,36 +413,46 @@ locale_charset (void)
locale = getenv ("LC_ALL");
if (locale == NULL || locale[0] == '\0')
- {
- locale = getenv ("LC_CTYPE");
- if (locale == NULL || locale[0] == '\0')
- locale = getenv ("LANG");
- }
+ {
+ locale = getenv ("LC_CTYPE");
+ if (locale == NULL || locale[0] == '\0')
+ locale = getenv ("LANG");
+ }
if (locale != NULL && locale[0] != '\0')
- {
- /* If the locale name contains an encoding after the dot, return
- it. */
- const char *dot = strchr (locale, '.');
-
- if (dot != NULL)
- {
- const char *modifier;
-
- dot++;
- /* Look for the possible @... trailer and remove it, if any. */
- modifier = strchr (dot, '@');
- if (modifier == NULL)
- return dot;
- if (modifier - dot < sizeof (buf))
- {
- memcpy (buf, dot, modifier - dot);
- buf [modifier - dot] = '\0';
- return buf;
- }
- }
- }
-
- /* Woe32 has a function returning the locale's codepage as a number. */
+ {
+ /* If the locale name contains an encoding after the dot, return
+ it. */
+ const char *dot = strchr (locale, '.');
+
+ if (dot != NULL)
+ {
+ const char *modifier;
+
+ dot++;
+ /* Look for the possible @... trailer and remove it, if any. */
+ modifier = strchr (dot, '@');
+ if (modifier == NULL)
+ return dot;
+ if (modifier - dot < sizeof (buf))
+ {
+ memcpy (buf, dot, modifier - dot);
+ buf [modifier - dot] = '\0';
+ return buf;
+ }
+ }
+ }
+
+ /* The Windows API has a function returning the locale's codepage as a
+ number: GetACP(). This encoding is used by Cygwin, unless the user
+ has set the environment variable CYGWIN=codepage:oem (which very few
+ people do).
+ Output directed to console windows needs to be converted (to
+ GetOEMCP() if the console is using a raster font, or to
+ GetConsoleOutputCP() if it is using a TrueType font). Cygwin does
+ this conversion transparently (see winsup/cygwin/fhandler_console.cc),
+ converting to GetConsoleOutputCP(). This leads to correct results,
+ except when SetConsoleOutputCP has been called and a raster font is
+ in use. */
sprintf (buf, "CP%u", GetACP ());
codeset = buf;
}
@@ -358,11 +474,11 @@ locale_charset (void)
{
locale = getenv ("LC_ALL");
if (locale == NULL || locale[0] == '\0')
- {
- locale = getenv ("LC_CTYPE");
- if (locale == NULL || locale[0] == '\0')
- locale = getenv ("LANG");
- }
+ {
+ locale = getenv ("LC_CTYPE");
+ if (locale == NULL || locale[0] == '\0')
+ locale = getenv ("LANG");
+ }
}
/* On some old systems, one used to set locale = "iso8859_1". On others,
@@ -372,12 +488,38 @@ locale_charset (void)
# endif
-#elif defined WIN32_NATIVE
+#elif defined WINDOWS_NATIVE
static char buf[2 + 10 + 1];
- /* Woe32 has a function returning the locale's codepage as a number. */
- sprintf (buf, "CP%u", GetACP ());
+ /* The Windows API has a function returning the locale's codepage as
+ a number, but the value doesn't change according to what the
+ 'setlocale' call specified. So we use it as a last resort, in
+ case the string returned by 'setlocale' doesn't specify the
+ codepage. */
+ char *current_locale = setlocale (LC_ALL, NULL);
+ char *pdot;
+
+ /* If they set different locales for different categories,
+ 'setlocale' will return a semi-colon separated list of locale
+ values. To make sure we use the correct one, we choose LC_CTYPE. */
+ if (strchr (current_locale, ';'))
+ current_locale = setlocale (LC_CTYPE, NULL);
+
+ pdot = strrchr (current_locale, '.');
+ if (pdot)
+ sprintf (buf, "CP%s", pdot + 1);
+ else
+ {
+ /* The Windows API has a function returning the locale's codepage as a
+ number: GetACP().
+ When the output goes to a console window, it needs to be provided in
+ GetOEMCP() encoding if the console is using a raster font, or in
+ GetConsoleOutputCP() encoding if it is using a TrueType font.
+ But in GUI programs and for output sent to files and pipes, GetACP()
+ encoding is the best bet. */
+ sprintf (buf, "CP%u", GetACP ());
+ }
codeset = buf;
#elif defined OS2
@@ -387,6 +529,8 @@ locale_charset (void)
ULONG cp[3];
ULONG cplen;
+ codeset = NULL;
+
/* Allow user to override the codeset, as set in the operating system,
with standard language environment variables. */
locale = getenv ("LC_ALL");
@@ -394,7 +538,7 @@ locale_charset (void)
{
locale = getenv ("LC_CTYPE");
if (locale == NULL || locale[0] == '\0')
- locale = getenv ("LANG");
+ locale = getenv ("LANG");
}
if (locale != NULL && locale[0] != '\0')
{
@@ -402,35 +546,37 @@ locale_charset (void)
const char *dot = strchr (locale, '.');
if (dot != NULL)
- {
- const char *modifier;
-
- dot++;
- /* Look for the possible @... trailer and remove it, if any. */
- modifier = strchr (dot, '@');
- if (modifier == NULL)
- return dot;
- if (modifier - dot < sizeof (buf))
- {
- memcpy (buf, dot, modifier - dot);
- buf [modifier - dot] = '\0';
- return buf;
- }
- }
-
- /* Resolve through the charset.alias file. */
- codeset = locale;
+ {
+ const char *modifier;
+
+ dot++;
+ /* Look for the possible @... trailer and remove it, if any. */
+ modifier = strchr (dot, '@');
+ if (modifier == NULL)
+ return dot;
+ if (modifier - dot < sizeof (buf))
+ {
+ memcpy (buf, dot, modifier - dot);
+ buf [modifier - dot] = '\0';
+ return buf;
+ }
+ }
+
+ /* For the POSIX locale, don't use the system's codepage. */
+ if (strcmp (locale, "C") == 0 || strcmp (locale, "POSIX") == 0)
+ codeset = "";
}
- else
+
+ if (codeset == NULL)
{
/* OS/2 has a function returning the locale's codepage as a number. */
if (DosQueryCp (sizeof (cp), cp, &cplen))
- codeset = "";
+ codeset = "";
else
- {
- sprintf (buf, "CP%u", cp[0]);
- codeset = buf;
- }
+ {
+ sprintf (buf, "CP%u", cp[0]);
+ codeset = buf;
+ }
}
#endif
@@ -444,10 +590,10 @@ locale_charset (void)
*aliases != '\0';
aliases += strlen (aliases) + 1, aliases += strlen (aliases) + 1)
if (strcmp (codeset, aliases) == 0
- || (aliases[0] == '*' && aliases[1] == '\0'))
+ || (aliases[0] == '*' && aliases[1] == '\0'))
{
- codeset = aliases + strlen (aliases) + 1;
- break;
+ codeset = aliases + strlen (aliases) + 1;
+ break;
}
/* Don't return an empty string. GNU libc and GNU libiconv interpret
@@ -456,5 +602,12 @@ locale_charset (void)
if (codeset[0] == '\0')
codeset = "ASCII";
+#ifdef DARWIN7
+ /* Mac OS X sets MB_CUR_MAX to 1 when LC_ALL=C, and "UTF-8"
+ (the default codeset) does not work when MB_CUR_MAX is 1. */
+ if (strcmp (codeset, "UTF-8") == 0 && MB_CUR_MAX_L (uselocale (NULL)) <= 1)
+ codeset = "ASCII";
+#endif
+
return codeset;
}
diff --git a/lib/localcharset.h b/lib/localcharset.h
index 5030210..915182e 100644
--- a/lib/localcharset.h
+++ b/lib/localcharset.h
@@ -1,10 +1,10 @@
/* Determine a canonical name for the current locale's character encoding.
- Copyright (C) 2000-2003 Free Software Foundation, Inc.
+ Copyright (C) 2000-2003, 2009-2016 Free Software Foundation, Inc.
This file is part of the GNU CHARSET Library.
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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ with this program; if not, see <http://www.gnu.org/licenses/>. */
#ifndef _LOCALCHARSET_H
#define _LOCALCHARSET_H
diff --git a/lib/locale.in.h b/lib/locale.in.h
new file mode 100644
index 0000000..4083507
--- /dev/null
+++ b/lib/locale.in.h
@@ -0,0 +1,216 @@
+/* A POSIX <locale.h>.
+ Copyright (C) 2007-2016 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 <http://www.gnu.org/licenses/>. */
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+#ifdef _GL_ALREADY_INCLUDING_LOCALE_H
+
+/* Special invocation conventions to handle Solaris header files
+ (through Solaris 10) when combined with gettext's libintl.h. */
+
+#@INCLUDE_NEXT@ @NEXT_LOCALE_H@
+
+#else
+/* Normal invocation convention. */
+
+#ifndef _@GUARD_PREFIX@_LOCALE_H
+
+#define _GL_ALREADY_INCLUDING_LOCALE_H
+
+/* The include_next requires a split double-inclusion guard. */
+#@INCLUDE_NEXT@ @NEXT_LOCALE_H@
+
+#undef _GL_ALREADY_INCLUDING_LOCALE_H
+
+#ifndef _@GUARD_PREFIX@_LOCALE_H
+#define _@GUARD_PREFIX@_LOCALE_H
+
+/* NetBSD 5.0 mis-defines NULL. */
+#include <stddef.h>
+
+/* Mac OS X 10.5 defines the locale_t type in <xlocale.h>. */
+#if @HAVE_XLOCALE_H@
+# include <xlocale.h>
+#endif
+
+/* The definitions of _GL_FUNCDECL_RPL etc. are copied here. */
+
+/* The definition of _GL_ARG_NONNULL is copied here. */
+
+/* The definition of _GL_WARN_ON_USE is copied here. */
+
+/* The LC_MESSAGES locale category is specified in POSIX, but not in ISO C.
+ On systems that don't define it, use the same value as GNU libintl. */
+#if !defined LC_MESSAGES
+# define LC_MESSAGES 1729
+#endif
+
+/* Bionic libc's 'struct lconv' is just a dummy. */
+#if @REPLACE_STRUCT_LCONV@
+# define lconv rpl_lconv
+struct lconv
+{
+ /* All 'char *' are actually 'const char *'. */
+
+ /* Members that depend on the LC_NUMERIC category of the locale. See
+ <http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_04> */
+
+ /* Symbol used as decimal point. */
+ char *decimal_point;
+ /* Symbol used to separate groups of digits to the left of the decimal
+ point. */
+ char *thousands_sep;
+ /* Definition of the size of groups of digits to the left of the decimal
+ point. */
+ char *grouping;
+
+ /* Members that depend on the LC_MONETARY category of the locale. See
+ <http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_03> */
+
+ /* Symbol used as decimal point. */
+ char *mon_decimal_point;
+ /* Symbol used to separate groups of digits to the left of the decimal
+ point. */
+ char *mon_thousands_sep;
+ /* Definition of the size of groups of digits to the left of the decimal
+ point. */
+ char *mon_grouping;
+ /* Sign used to indicate a value >= 0. */
+ char *positive_sign;
+ /* Sign used to indicate a value < 0. */
+ char *negative_sign;
+
+ /* For formatting local currency. */
+ /* Currency symbol (3 characters) followed by separator (1 character). */
+ char *currency_symbol;
+ /* Number of digits after the decimal point. */
+ char frac_digits;
+ /* For values >= 0: 1 if the currency symbol precedes the number, 0 if it
+ comes after the number. */
+ char p_cs_precedes;
+ /* For values >= 0: Position of the sign. */
+ char p_sign_posn;
+ /* For values >= 0: Placement of spaces between currency symbol, sign, and
+ number. */
+ char p_sep_by_space;
+ /* For values < 0: 1 if the currency symbol precedes the number, 0 if it
+ comes after the number. */
+ char n_cs_precedes;
+ /* For values < 0: Position of the sign. */
+ char n_sign_posn;
+ /* For values < 0: Placement of spaces between currency symbol, sign, and
+ number. */
+ char n_sep_by_space;
+
+ /* For formatting international currency. */
+ /* Currency symbol (3 characters) followed by separator (1 character). */
+ char *int_curr_symbol;
+ /* Number of digits after the decimal point. */
+ char int_frac_digits;
+ /* For values >= 0: 1 if the currency symbol precedes the number, 0 if it
+ comes after the number. */
+ char int_p_cs_precedes;
+ /* For values >= 0: Position of the sign. */
+ char int_p_sign_posn;
+ /* For values >= 0: Placement of spaces between currency symbol, sign, and
+ number. */
+ char int_p_sep_by_space;
+ /* For values < 0: 1 if the currency symbol precedes the number, 0 if it
+ comes after the number. */
+ char int_n_cs_precedes;
+ /* For values < 0: Position of the sign. */
+ char int_n_sign_posn;
+ /* For values < 0: Placement of spaces between currency symbol, sign, and
+ number. */
+ char int_n_sep_by_space;
+};
+#endif
+
+#if @GNULIB_LOCALECONV@
+# if @REPLACE_LOCALECONV@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef localeconv
+# define localeconv rpl_localeconv
+# endif
+_GL_FUNCDECL_RPL (localeconv, struct lconv *, (void));
+_GL_CXXALIAS_RPL (localeconv, struct lconv *, (void));
+# else
+_GL_CXXALIAS_SYS (localeconv, struct lconv *, (void));
+# endif
+_GL_CXXALIASWARN (localeconv);
+#elif @REPLACE_STRUCT_LCONV@
+# undef localeconv
+# define localeconv localeconv_used_without_requesting_gnulib_module_localeconv
+#elif defined GNULIB_POSIXCHECK
+# undef localeconv
+# if HAVE_RAW_DECL_LOCALECONV
+_GL_WARN_ON_USE (localeconv,
+ "localeconv returns too few information on some platforms - "
+ "use gnulib module localeconv for portability");
+# endif
+#endif
+
+#if @GNULIB_SETLOCALE@
+# if @REPLACE_SETLOCALE@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef setlocale
+# define setlocale rpl_setlocale
+# define GNULIB_defined_setlocale 1
+# endif
+_GL_FUNCDECL_RPL (setlocale, char *, (int category, const char *locale));
+_GL_CXXALIAS_RPL (setlocale, char *, (int category, const char *locale));
+# else
+_GL_CXXALIAS_SYS (setlocale, char *, (int category, const char *locale));
+# endif
+_GL_CXXALIASWARN (setlocale);
+#elif defined GNULIB_POSIXCHECK
+# undef setlocale
+# if HAVE_RAW_DECL_SETLOCALE
+_GL_WARN_ON_USE (setlocale, "setlocale works differently on native Windows - "
+ "use gnulib module setlocale for portability");
+# endif
+#endif
+
+#if @GNULIB_DUPLOCALE@
+# if @REPLACE_DUPLOCALE@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef duplocale
+# define duplocale rpl_duplocale
+# endif
+_GL_FUNCDECL_RPL (duplocale, locale_t, (locale_t locale) _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (duplocale, locale_t, (locale_t locale));
+# else
+# if @HAVE_DUPLOCALE@
+_GL_CXXALIAS_SYS (duplocale, locale_t, (locale_t locale));
+# endif
+# endif
+# if @HAVE_DUPLOCALE@
+_GL_CXXALIASWARN (duplocale);
+# endif
+#elif defined GNULIB_POSIXCHECK
+# undef duplocale
+# if HAVE_RAW_DECL_DUPLOCALE
+_GL_WARN_ON_USE (duplocale, "duplocale is buggy on some glibc systems - "
+ "use gnulib module duplocale for portability");
+# endif
+#endif
+
+#endif /* _@GUARD_PREFIX@_LOCALE_H */
+#endif /* ! _GL_ALREADY_INCLUDING_LOCALE_H */
+#endif /* _@GUARD_PREFIX@_LOCALE_H */
diff --git a/lib/localeconv.c b/lib/localeconv.c
new file mode 100644
index 0000000..8a1d6d7
--- /dev/null
+++ b/lib/localeconv.c
@@ -0,0 +1,103 @@
+/* Query locale dependent information for formatting numbers.
+ Copyright (C) 2012-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <locale.h>
+
+#if HAVE_STRUCT_LCONV_DECIMAL_POINT
+
+/* Override for platforms where 'struct lconv' lacks the int_p_*, int_n_*
+ members. */
+
+struct lconv *
+localeconv (void)
+{
+ static struct lconv result;
+# undef lconv
+# undef localeconv
+ struct lconv *sys_result = localeconv ();
+
+ result.decimal_point = sys_result->decimal_point;
+ result.thousands_sep = sys_result->thousands_sep;
+ result.grouping = sys_result->grouping;
+ result.mon_decimal_point = sys_result->mon_decimal_point;
+ result.mon_thousands_sep = sys_result->mon_thousands_sep;
+ result.mon_grouping = sys_result->mon_grouping;
+ result.positive_sign = sys_result->positive_sign;
+ result.negative_sign = sys_result->negative_sign;
+ result.currency_symbol = sys_result->currency_symbol;
+ result.frac_digits = sys_result->frac_digits;
+ result.p_cs_precedes = sys_result->p_cs_precedes;
+ result.p_sign_posn = sys_result->p_sign_posn;
+ result.p_sep_by_space = sys_result->p_sep_by_space;
+ result.n_cs_precedes = sys_result->n_cs_precedes;
+ result.n_sign_posn = sys_result->n_sign_posn;
+ result.n_sep_by_space = sys_result->n_sep_by_space;
+ result.int_curr_symbol = sys_result->int_curr_symbol;
+ result.int_frac_digits = sys_result->int_frac_digits;
+ result.int_p_cs_precedes = sys_result->p_cs_precedes;
+ result.int_p_sign_posn = sys_result->p_sign_posn;
+ result.int_p_sep_by_space = sys_result->p_sep_by_space;
+ result.int_n_cs_precedes = sys_result->n_cs_precedes;
+ result.int_n_sign_posn = sys_result->n_sign_posn;
+ result.int_n_sep_by_space = sys_result->n_sep_by_space;
+
+ return &result;
+}
+
+#else
+
+/* Override for platforms where 'struct lconv' is a dummy. */
+
+# include <limits.h>
+
+struct lconv *
+localeconv (void)
+{
+ static /*const*/ struct lconv result =
+ {
+ /* decimal_point */ ".",
+ /* thousands_sep */ "",
+ /* grouping */ "",
+ /* mon_decimal_point */ "",
+ /* mon_thousands_sep */ "",
+ /* mon_grouping */ "",
+ /* positive_sign */ "",
+ /* negative_sign */ "",
+ /* currency_symbol */ "",
+ /* frac_digits */ CHAR_MAX,
+ /* p_cs_precedes */ CHAR_MAX,
+ /* p_sign_posn */ CHAR_MAX,
+ /* p_sep_by_space */ CHAR_MAX,
+ /* n_cs_precedes */ CHAR_MAX,
+ /* n_sign_posn */ CHAR_MAX,
+ /* n_sep_by_space */ CHAR_MAX,
+ /* int_curr_symbol */ "",
+ /* int_frac_digits */ CHAR_MAX,
+ /* int_p_cs_precedes */ CHAR_MAX,
+ /* int_p_sign_posn */ CHAR_MAX,
+ /* int_p_sep_by_space */ CHAR_MAX,
+ /* int_n_cs_precedes */ CHAR_MAX,
+ /* int_n_sign_posn */ CHAR_MAX,
+ /* int_n_sep_by_space */ CHAR_MAX
+ };
+
+ return &result;
+}
+
+#endif
diff --git a/lib/long-options.c b/lib/long-options.c
index fb61661..e694e28 100644
--- a/lib/long-options.c
+++ b/lib/long-options.c
@@ -1,12 +1,12 @@
/* Utility to accept --help and --version options as unobtrusively as possible.
- Copyright (C) 1993, 1994, 1998, 1999, 2000, 2002, 2003, 2004, 2005,
- 2006 Free Software Foundation, Inc.
+ Copyright (C) 1993-1994, 1998-2000, 2002-2006, 2009-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Jim Meyering. */
@@ -39,16 +38,16 @@ static struct option const long_options[] =
};
/* Process long options --help and --version, but only if argc == 2.
- Be careful not to gobble up `--'. */
+ Be careful not to gobble up "--". */
void
parse_long_options (int argc,
- char **argv,
- const char *command_name,
- const char *package,
- const char *version,
- void (*usage_func) (int),
- /* const char *author1, ...*/ ...)
+ char **argv,
+ const char *command_name,
+ const char *package,
+ const char *version,
+ void (*usage_func) (int),
+ /* const char *author1, ...*/ ...)
{
int c;
int saved_opterr;
@@ -62,22 +61,22 @@ parse_long_options (int argc,
&& (c = getopt_long (argc, argv, "+", long_options, NULL)) != -1)
{
switch (c)
- {
- case 'h':
- (*usage_func) (EXIT_SUCCESS);
-
- case 'v':
- {
- va_list authors;
- va_start (authors, usage_func);
- version_etc_va (stdout, command_name, package, version, authors);
- exit (0);
- }
-
- default:
- /* Don't process any other long-named options. */
- break;
- }
+ {
+ case 'h':
+ (*usage_func) (EXIT_SUCCESS);
+
+ case 'v':
+ {
+ va_list authors;
+ va_start (authors, usage_func);
+ version_etc_va (stdout, command_name, package, version, authors);
+ exit (0);
+ }
+
+ default:
+ /* Don't process any other long-named options. */
+ break;
+ }
}
/* Restore previous value. */
diff --git a/lib/long-options.h b/lib/long-options.h
index 03106a8..317711a 100644
--- a/lib/long-options.h
+++ b/lib/long-options.h
@@ -1,10 +1,11 @@
/* long-options.h -- declaration for --help- and --version-handling function.
- Copyright (C) 1993, 1994, 1998, 1999, 2003 Free Software Foundation, Inc.
+ Copyright (C) 1993-1994, 1998-1999, 2003, 2009-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -12,15 +13,14 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Jim Meyering. */
void parse_long_options (int _argc,
- char **_argv,
- const char *_command_name,
- const char *_package,
- const char *_version,
- void (*_usage) (int),
- /* const char *author1, ...*/ ...);
+ char **_argv,
+ const char *_command_name,
+ const char *_package,
+ const char *_version,
+ void (*_usage) (int),
+ /* const char *author1, ...*/ ...);
diff --git a/lib/lseek.c b/lib/lseek.c
new file mode 100644
index 0000000..2a95a07
--- /dev/null
+++ b/lib/lseek.c
@@ -0,0 +1,67 @@
+/* An lseek() function that detects pipes.
+ Copyright (C) 2007, 2009-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <unistd.h>
+
+#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+/* Windows platforms. */
+/* Get GetFileType. */
+# include <windows.h>
+/* Get _get_osfhandle. */
+# include "msvc-nothrow.h"
+#else
+# include <sys/stat.h>
+#endif
+#include <errno.h>
+
+#undef lseek
+
+off_t
+rpl_lseek (int fd, off_t offset, int whence)
+{
+#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+ /* mingw lseek mistakenly succeeds on pipes, sockets, and terminals. */
+ HANDLE h = (HANDLE) _get_osfhandle (fd);
+ if (h == INVALID_HANDLE_VALUE)
+ {
+ errno = EBADF;
+ return -1;
+ }
+ if (GetFileType (h) != FILE_TYPE_DISK)
+ {
+ errno = ESPIPE;
+ return -1;
+ }
+#else
+ /* BeOS lseek mistakenly succeeds on pipes... */
+ struct stat statbuf;
+ if (fstat (fd, &statbuf) < 0)
+ return -1;
+ if (!S_ISREG (statbuf.st_mode))
+ {
+ errno = ESPIPE;
+ return -1;
+ }
+#endif
+#if _GL_WINDOWS_64_BIT_OFF_T
+ return _lseeki64 (fd, offset, whence);
+#else
+ return lseek (fd, offset, whence);
+#endif
+}
diff --git a/lib/lstat.c b/lib/lstat.c
index 77dd228..03b0634 100644
--- a/lib/lstat.c
+++ b/lib/lstat.c
@@ -1,12 +1,11 @@
/* Work around a bug of lstat on some systems
- Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free
- Software Foundation, Inc.
+ Copyright (C) 1997-2006, 2008-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,29 +13,49 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* written by Jim Meyering */
+/* If the user's config.h happens to include <sys/stat.h>, let it include only
+ the system's <sys/stat.h> here, so that orig_lstat doesn't recurse to
+ rpl_lstat. */
+#define __need_system_sys_stat_h
#include <config.h>
-/* The specification of these functions is in sys_stat.h. But we cannot
- include this include file here, because on some systems, a
- "#define lstat lstat64" is being used, and sys_stat.h deletes this
- definition. */
+#if !HAVE_LSTAT
+/* On systems that lack symlinks, our replacement <sys/stat.h> already
+ defined lstat as stat, so there is nothing further to do other than
+ avoid an empty file. */
+typedef int dummy;
+#else /* HAVE_LSTAT */
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <string.h>
-#include <errno.h>
+/* Get the original definition of lstat. It might be defined as a macro. */
+# include <sys/types.h>
+# include <sys/stat.h>
+# undef __need_system_sys_stat_h
+
+static int
+orig_lstat (const char *filename, struct stat *buf)
+{
+ return lstat (filename, buf);
+}
+
+/* Specification. */
+/* Write "sys/stat.h" here, not <sys/stat.h>, otherwise OSF/1 5.1 DTK cc
+ eliminates this include because of the preliminary #include <sys/stat.h>
+ above. */
+# include "sys/stat.h"
+
+# include <string.h>
+# include <errno.h>
/* lstat works differently on Linux and Solaris systems. POSIX (see
- `pathname resolution' in the glossary) requires that programs like
- `ls' take into consideration the fact that FILE has a trailing slash
+ "pathname resolution" in the glossary) requires that programs like
+ 'ls' take into consideration the fact that FILE has a trailing slash
when FILE is a symbolic link. On Linux and Solaris 10 systems, the
lstat function already has the desired semantics (in treating
- `lstat ("symlink/", sbuf)' just like `lstat ("symlink/.", sbuf)',
+ 'lstat ("symlink/", sbuf)' just like 'lstat ("symlink/.", sbuf)',
but on Solaris 9 and earlier it does not.
If FILE has a trailing slash and specifies a symbolic link,
@@ -48,29 +67,31 @@ int
rpl_lstat (const char *file, struct stat *sbuf)
{
size_t len;
- int lstat_result = lstat (file, sbuf);
+ int lstat_result = orig_lstat (file, sbuf);
- if (lstat_result != 0 || !S_ISLNK (sbuf->st_mode))
+ if (lstat_result != 0)
return lstat_result;
+ /* This replacement file can blindly check against '/' rather than
+ using the ISSLASH macro, because all platforms with '\\' either
+ lack symlinks (mingw) or have working lstat (cygwin) and thus do
+ not compile this file. 0 len should have already been filtered
+ out above, with a failure return of ENOENT. */
len = strlen (file);
- if (len == 0 || file[len - 1] != '/')
+ if (file[len - 1] != '/' || S_ISDIR (sbuf->st_mode))
return 0;
- /* FILE refers to a symbolic link and the name ends with a slash.
- Call stat() to get info about the link's referent. */
-
- /* If stat fails, then we do the same. */
- if (stat (file, sbuf) != 0)
- return -1;
-
- /* If FILE references a directory, return 0. */
- if (S_ISDIR (sbuf->st_mode))
- return 0;
-
- /* Here, we know stat succeeded and FILE references a non-directory.
- But it was specified via a name including a trailing slash.
- Fail with errno set to ENOTDIR to indicate the contradiction. */
- errno = ENOTDIR;
- return -1;
+ /* At this point, a trailing slash is only permitted on
+ symlink-to-dir; but it should have found information on the
+ directory, not the symlink. Call stat() to get info about the
+ link's referent. Our replacement stat guarantees valid results,
+ even if the symlink is not pointing to a directory. */
+ if (!S_ISLNK (sbuf->st_mode))
+ {
+ errno = ENOTDIR;
+ return -1;
+ }
+ return stat (file, sbuf);
}
+
+#endif /* HAVE_LSTAT */
diff --git a/lib/lstat.h b/lib/lstat.h
deleted file mode 100644
index 6a83fbf..0000000
--- a/lib/lstat.h
+++ /dev/null
@@ -1,24 +0,0 @@
-/* Retrieving information about files.
- Copyright (C) 2005 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-#include <sys/stat.h>
-
-#if !LSTAT_FOLLOWS_SLASHED_SYMLINK
-extern int rpl_lstat (const char *name, struct stat *buf);
-# undef lstat
-# define lstat rpl_lstat
-#endif
diff --git a/lib/malloc.c b/lib/malloc.c
index d4dae3e..e9b01d2 100644
--- a/lib/malloc.c
+++ b/lib/malloc.c
@@ -1,10 +1,10 @@
/* malloc() function that is glibc compatible.
- Copyright (C) 1997, 1998, 2006 Free Software Foundation, Inc.
+ Copyright (C) 1997-1998, 2006-2007, 2009-2016 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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -13,23 +13,44 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program; if not, see <http://www.gnu.org/licenses/>. */
-/* written by Jim Meyering */
+/* written by Jim Meyering and Bruno Haible */
+#define _GL_USE_STDLIB_ALLOC 1
#include <config.h>
-#undef malloc
+/* Only the AC_FUNC_MALLOC macro defines 'malloc' already in config.h. */
+#ifdef malloc
+# define NEED_MALLOC_GNU 1
+# undef malloc
+/* Whereas the gnulib module 'malloc-gnu' defines HAVE_MALLOC_GNU. */
+#elif GNULIB_MALLOC_GNU && !HAVE_MALLOC_GNU
+# define NEED_MALLOC_GNU 1
+#endif
#include <stdlib.h>
+#include <errno.h>
+
/* Allocate an N-byte block of memory from the heap.
If N is zero, allocate a 1-byte block. */
void *
rpl_malloc (size_t n)
{
+ void *result;
+
+#if NEED_MALLOC_GNU
if (n == 0)
n = 1;
- return malloc (n);
+#endif
+
+ result = malloc (n);
+
+#if !HAVE_MALLOC_POSIX
+ if (result == NULL)
+ errno = ENOMEM;
+#endif
+
+ return result;
}
diff --git a/lib/malloca.c b/lib/malloca.c
new file mode 100644
index 0000000..a613277
--- /dev/null
+++ b/lib/malloca.c
@@ -0,0 +1,149 @@
+/* Safe automatic memory allocation.
+ Copyright (C) 2003, 2006-2007, 2009-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2003.
+
+ 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, 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 <http://www.gnu.org/licenses/>. */
+
+#define _GL_USE_STDLIB_ALLOC 1
+#include <config.h>
+
+/* Specification. */
+#include "malloca.h"
+
+#include <stdint.h>
+
+#include "verify.h"
+
+/* The speed critical point in this file is freea() applied to an alloca()
+ result: it must be fast, to match the speed of alloca(). The speed of
+ mmalloca() and freea() in the other case are not critical, because they
+ are only invoked for big memory sizes. */
+
+#if HAVE_ALLOCA
+
+/* Store the mmalloca() results in a hash table. This is needed to reliably
+ distinguish a mmalloca() result and an alloca() result.
+
+ Although it is possible that the same pointer is returned by alloca() and
+ by mmalloca() at different times in the same application, it does not lead
+ to a bug in freea(), because:
+ - Before a pointer returned by alloca() can point into malloc()ed memory,
+ the function must return, and once this has happened the programmer must
+ not call freea() on it anyway.
+ - Before a pointer returned by mmalloca() can point into the stack, it
+ must be freed. The only function that can free it is freea(), and
+ when freea() frees it, it also removes it from the hash table. */
+
+#define MAGIC_NUMBER 0x1415fb4a
+#define MAGIC_SIZE sizeof (int)
+/* This is how the header info would look like without any alignment
+ considerations. */
+struct preliminary_header { void *next; int magic; };
+/* But the header's size must be a multiple of sa_alignment_max. */
+#define HEADER_SIZE \
+ (((sizeof (struct preliminary_header) + sa_alignment_max - 1) / sa_alignment_max) * sa_alignment_max)
+union header {
+ void *next;
+ struct {
+ char room[HEADER_SIZE - MAGIC_SIZE];
+ int word;
+ } magic;
+};
+verify (HEADER_SIZE == sizeof (union header));
+/* We make the hash table quite big, so that during lookups the probability
+ of empty hash buckets is quite high. There is no need to make the hash
+ table resizable, because when the hash table gets filled so much that the
+ lookup becomes slow, it means that the application has memory leaks. */
+#define HASH_TABLE_SIZE 257
+static void * mmalloca_results[HASH_TABLE_SIZE];
+
+#endif
+
+void *
+mmalloca (size_t n)
+{
+#if HAVE_ALLOCA
+ /* Allocate one more word, that serves as an indicator for malloc()ed
+ memory, so that freea() of an alloca() result is fast. */
+ size_t nplus = n + HEADER_SIZE;
+
+ if (nplus >= n)
+ {
+ void *p = malloc (nplus);
+
+ if (p != NULL)
+ {
+ size_t slot;
+ union header *h = p;
+
+ p = h + 1;
+
+ /* Put a magic number into the indicator word. */
+ h->magic.word = MAGIC_NUMBER;
+
+ /* Enter p into the hash table. */
+ slot = (uintptr_t) p % HASH_TABLE_SIZE;
+ h->next = mmalloca_results[slot];
+ mmalloca_results[slot] = p;
+
+ return p;
+ }
+ }
+ /* Out of memory. */
+ return NULL;
+#else
+# if !MALLOC_0_IS_NONNULL
+ if (n == 0)
+ n = 1;
+# endif
+ return malloc (n);
+#endif
+}
+
+#if HAVE_ALLOCA
+void
+freea (void *p)
+{
+ /* mmalloca() may have returned NULL. */
+ if (p != NULL)
+ {
+ /* Attempt to quickly distinguish the mmalloca() result - which has
+ a magic indicator word - and the alloca() result - which has an
+ uninitialized indicator word. It is for this test that sa_increment
+ additional bytes are allocated in the alloca() case. */
+ if (((int *) p)[-1] == MAGIC_NUMBER)
+ {
+ /* Looks like a mmalloca() result. To see whether it really is one,
+ perform a lookup in the hash table. */
+ size_t slot = (uintptr_t) p % HASH_TABLE_SIZE;
+ void **chain = &mmalloca_results[slot];
+ for (; *chain != NULL;)
+ {
+ union header *h = p;
+ if (*chain == p)
+ {
+ /* Found it. Remove it from the hash table and free it. */
+ union header *p_begin = h - 1;
+ *chain = p_begin->next;
+ free (p_begin);
+ return;
+ }
+ h = *chain;
+ chain = &h[-1].next;
+ }
+ }
+ /* At this point, we know it was not a mmalloca() result. */
+ }
+}
+#endif
diff --git a/lib/allocsa.h b/lib/malloca.h
index 3337110..fa27a9e 100644
--- a/lib/allocsa.h
+++ b/lib/malloca.h
@@ -1,10 +1,10 @@
/* Safe automatic memory allocation.
- Copyright (C) 2003-2007 Free Software Foundation, Inc.
+ Copyright (C) 2003-2007, 2009-2016 Free Software Foundation, Inc.
Written by Bruno Haible <bruno@clisp.org>, 2003.
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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -13,11 +13,10 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program; if not, see <http://www.gnu.org/licenses/>. */
-#ifndef _ALLOCSA_H
-#define _ALLOCSA_H
+#ifndef _MALLOCA_H
+#define _MALLOCA_H
#include <alloca.h>
#include <stddef.h>
@@ -43,36 +42,46 @@ extern "C" {
and a page size can be as small as 4096 bytes. So we cannot safely
allocate anything larger than 4096 bytes. Also care for the possibility
of a few compiler-allocated temporary stack slots.
- This must be a macro, not an inline function. */
+ This must be a macro, not a function. */
# define safe_alloca(N) ((N) < 4032 ? alloca (N) : NULL)
#else
-# define safe_alloca(N) ((N), NULL)
+# define safe_alloca(N) ((void) (N), NULL)
#endif
-/* allocsa(N) is a safe variant of alloca(N). It allocates N bytes of
- memory allocated on the stack, that must be freed using freesa() before
+/* malloca(N) is a safe variant of alloca(N). It allocates N bytes of
+ memory allocated on the stack, that must be freed using freea() before
the function returns. Upon failure, it returns NULL. */
#if HAVE_ALLOCA
-# define allocsa(N) \
- ((N) < 4032 - sa_increment \
+# define malloca(N) \
+ ((N) < 4032 - sa_increment \
? (void *) ((char *) alloca ((N) + sa_increment) + sa_increment) \
- : mallocsa (N))
+ : mmalloca (N))
#else
-# define allocsa(N) \
- mallocsa (N)
+# define malloca(N) \
+ mmalloca (N)
#endif
-extern void * mallocsa (size_t n);
+extern void * mmalloca (size_t n);
-/* Free a block of memory allocated through allocsa(). */
+/* Free a block of memory allocated through malloca(). */
#if HAVE_ALLOCA
-extern void freesa (void *p);
+extern void freea (void *p);
#else
-# define freesa free
+# define freea free
#endif
-/* Maybe we should also define a variant
- nallocsa (size_t n, size_t s) - behaves like allocsa (n * s)
- If this would be useful in your application. please speak up. */
+/* nmalloca(N,S) is an overflow-safe variant of malloca (N * S).
+ It allocates an array of N objects, each with S bytes of memory,
+ on the stack. S must be positive and N must be nonnegative.
+ The array must be freed using freea() before the function returns. */
+#if 1
+/* Cf. the definition of xalloc_oversized. */
+# define nmalloca(n, s) \
+ ((n) > (size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) \
+ ? NULL \
+ : malloca ((n) * (s)))
+#else
+extern void * nmalloca (size_t n, size_t s);
+#endif
#ifdef __cplusplus
@@ -83,7 +92,7 @@ extern void freesa (void *p);
/* ------------------- Auxiliary, non-public definitions ------------------- */
/* Determine the alignment of a type at compile time. */
-#if defined __GNUC__
+#if defined __GNUC__ || defined __IBM__ALIGNOF__
# define sa_alignof __alignof__
#elif defined __cplusplus
template <class type> struct sa_alignof_helper { char __slot1; type __slot2; };
@@ -109,20 +118,16 @@ enum
#if HAVE_LONG_LONG_INT
sa_alignment_longlong = sa_alignof (long long),
#endif
-#if HAVE_LONG_DOUBLE
sa_alignment_longdouble = sa_alignof (long double),
-#endif
sa_alignment_max = ((sa_alignment_long - 1) | (sa_alignment_double - 1)
#if HAVE_LONG_LONG_INT
- | (sa_alignment_longlong - 1)
-#endif
-#if HAVE_LONG_DOUBLE
- | (sa_alignment_longdouble - 1)
+ | (sa_alignment_longlong - 1)
#endif
- ) + 1,
+ | (sa_alignment_longdouble - 1)
+ ) + 1,
/* The increment that guarantees room for a magic word must be >= sizeof (int)
and a multiple of sa_alignment_max. */
sa_increment = ((sizeof (int) + sa_alignment_max - 1) / sa_alignment_max) * sa_alignment_max
};
-#endif /* _ALLOCSA_H */
+#endif /* _MALLOCA_H */
diff --git a/lib/allocsa.valgrind b/lib/malloca.valgrind
index f4c77d6..52f0a50 100644
--- a/lib/allocsa.valgrind
+++ b/lib/malloca.valgrind
@@ -1,7 +1,7 @@
-# Suppress a valgrind message about use of uninitialized memory in freesa().
+# Suppress a valgrind message about use of uninitialized memory in freea().
# This use is OK because it provides only a speedup.
{
- freesa
+ freea
Memcheck:Cond
- fun:freesa
+ fun:freea
}
diff --git a/lib/math.c b/lib/math.c
new file mode 100644
index 0000000..ba2a6ab
--- /dev/null
+++ b/lib/math.c
@@ -0,0 +1,4 @@
+#include <config.h>
+#define _GL_MATH_INLINE _GL_EXTERN_INLINE
+#include "math.h"
+typedef int dummy;
diff --git a/lib/math.in.h b/lib/math.in.h
new file mode 100644
index 0000000..736d532
--- /dev/null
+++ b/lib/math.in.h
@@ -0,0 +1,2278 @@
+/* A GNU-like <math.h>.
+
+ Copyright (C) 2002-2003, 2007-2016 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _@GUARD_PREFIX@_MATH_H
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+/* The include_next requires a split double-inclusion guard. */
+#@INCLUDE_NEXT_AS_FIRST_DIRECTIVE@ @NEXT_AS_FIRST_DIRECTIVE_MATH_H@
+
+#ifndef _@GUARD_PREFIX@_MATH_H
+#define _@GUARD_PREFIX@_MATH_H
+
+#ifndef _GL_INLINE_HEADER_BEGIN
+ #error "Please include config.h first."
+#endif
+_GL_INLINE_HEADER_BEGIN
+#ifndef _GL_MATH_INLINE
+# define _GL_MATH_INLINE _GL_INLINE
+#endif
+
+/* The definitions of _GL_FUNCDECL_RPL etc. are copied here. */
+
+/* The definition of _GL_ARG_NONNULL is copied here. */
+
+/* The definition of _GL_WARN_ON_USE is copied here. */
+
+#ifdef __cplusplus
+/* Helper macros to define type-generic function FUNC as overloaded functions,
+ rather than as macros like in C. POSIX declares these with an argument of
+ real-floating (that is, one of float, double, or long double). */
+# define _GL_MATH_CXX_REAL_FLOATING_DECL_1(func) \
+static inline int \
+_gl_cxx_ ## func ## f (float f) \
+{ \
+ return func (f); \
+} \
+static inline int \
+_gl_cxx_ ## func ## d (double d) \
+{ \
+ return func (d); \
+} \
+static inline int \
+_gl_cxx_ ## func ## l (long double l) \
+{ \
+ return func (l); \
+}
+# define _GL_MATH_CXX_REAL_FLOATING_DECL_2(func) \
+inline int \
+func (float f) \
+{ \
+ return _gl_cxx_ ## func ## f (f); \
+} \
+inline int \
+func (double d) \
+{ \
+ return _gl_cxx_ ## func ## d (d); \
+} \
+inline int \
+func (long double l) \
+{ \
+ return _gl_cxx_ ## func ## l (l); \
+}
+#endif
+
+/* Helper macros to define a portability warning for the
+ classification macro FUNC called with VALUE. POSIX declares the
+ classification macros with an argument of real-floating (that is,
+ one of float, double, or long double). */
+#define _GL_WARN_REAL_FLOATING_DECL(func) \
+_GL_MATH_INLINE int \
+rpl_ ## func ## f (float f) \
+{ \
+ return func (f); \
+} \
+_GL_MATH_INLINE int \
+rpl_ ## func ## d (double d) \
+{ \
+ return func (d); \
+} \
+_GL_MATH_INLINE int \
+rpl_ ## func ## l (long double l) \
+{ \
+ return func (l); \
+} \
+_GL_WARN_ON_USE (rpl_ ## func ## f, #func " is unportable - " \
+ "use gnulib module " #func " for portability"); \
+_GL_WARN_ON_USE (rpl_ ## func ## d, #func " is unportable - " \
+ "use gnulib module " #func " for portability"); \
+_GL_WARN_ON_USE (rpl_ ## func ## l, #func " is unportable - " \
+ "use gnulib module " #func " for portability")
+#define _GL_WARN_REAL_FLOATING_IMPL(func, value) \
+ (sizeof (value) == sizeof (float) ? rpl_ ## func ## f (value) \
+ : sizeof (value) == sizeof (double) ? rpl_ ## func ## d (value) \
+ : rpl_ ## func ## l (value))
+
+
+#if @REPLACE_ITOLD@
+/* Pull in a function that fixes the 'int' to 'long double' conversion
+ of glibc 2.7. */
+_GL_EXTERN_C void _Qp_itoq (long double *, int);
+static void (*_gl_math_fix_itold) (long double *, int) = _Qp_itoq;
+#endif
+
+
+/* POSIX allows platforms that don't support NAN. But all major
+ machines in the past 15 years have supported something close to
+ IEEE NaN, so we define this unconditionally. We also must define
+ it on platforms like Solaris 10, where NAN is present but defined
+ as a function pointer rather than a floating point constant. */
+#if !defined NAN || @REPLACE_NAN@
+# if !GNULIB_defined_NAN
+# undef NAN
+ /* The Compaq (ex-DEC) C 6.4 compiler and the Microsoft MSVC 9 compiler
+ choke on the expression 0.0 / 0.0. */
+# if defined __DECC || defined _MSC_VER
+_GL_MATH_INLINE float
+_NaN ()
+{
+ static float zero = 0.0f;
+ return zero / zero;
+}
+# define NAN (_NaN())
+# else
+# define NAN (0.0f / 0.0f)
+# endif
+# define GNULIB_defined_NAN 1
+# endif
+#endif
+
+/* Solaris 10 defines HUGE_VAL, but as a function pointer rather
+ than a floating point constant. */
+#if @REPLACE_HUGE_VAL@
+# undef HUGE_VALF
+# define HUGE_VALF (1.0f / 0.0f)
+# undef HUGE_VAL
+# define HUGE_VAL (1.0 / 0.0)
+# undef HUGE_VALL
+# define HUGE_VALL (1.0L / 0.0L)
+#endif
+
+/* HUGE_VALF is a 'float' Infinity. */
+#ifndef HUGE_VALF
+# if defined _MSC_VER
+/* The Microsoft MSVC 9 compiler chokes on the expression 1.0f / 0.0f. */
+# define HUGE_VALF (1e25f * 1e25f)
+# else
+# define HUGE_VALF (1.0f / 0.0f)
+# endif
+#endif
+
+/* HUGE_VAL is a 'double' Infinity. */
+#ifndef HUGE_VAL
+# if defined _MSC_VER
+/* The Microsoft MSVC 9 compiler chokes on the expression 1.0 / 0.0. */
+# define HUGE_VAL (1e250 * 1e250)
+# else
+# define HUGE_VAL (1.0 / 0.0)
+# endif
+#endif
+
+/* HUGE_VALL is a 'long double' Infinity. */
+#ifndef HUGE_VALL
+# if defined _MSC_VER
+/* The Microsoft MSVC 9 compiler chokes on the expression 1.0L / 0.0L. */
+# define HUGE_VALL (1e250L * 1e250L)
+# else
+# define HUGE_VALL (1.0L / 0.0L)
+# endif
+#endif
+
+
+/* Ensure FP_ILOGB0 and FP_ILOGBNAN are defined. */
+#if !(defined FP_ILOGB0 && defined FP_ILOGBNAN)
+# if defined __NetBSD__ || defined __sgi
+ /* NetBSD, IRIX 6.5: match what ilogb() does */
+# define FP_ILOGB0 (- 2147483647 - 1) /* INT_MIN */
+# define FP_ILOGBNAN (- 2147483647 - 1) /* INT_MIN */
+# elif defined _AIX
+ /* AIX 5.1: match what ilogb() does in AIX >= 5.2 */
+# define FP_ILOGB0 (- 2147483647 - 1) /* INT_MIN */
+# define FP_ILOGBNAN 2147483647 /* INT_MAX */
+# elif defined __sun
+ /* Solaris 9: match what ilogb() does */
+# define FP_ILOGB0 (- 2147483647) /* - INT_MAX */
+# define FP_ILOGBNAN 2147483647 /* INT_MAX */
+# else
+ /* Gnulib defined values. */
+# define FP_ILOGB0 (- 2147483647) /* - INT_MAX */
+# define FP_ILOGBNAN (- 2147483647 - 1) /* INT_MIN */
+# endif
+#endif
+
+
+#if @GNULIB_ACOSF@
+# if !@HAVE_ACOSF@
+# undef acosf
+_GL_FUNCDECL_SYS (acosf, float, (float x));
+# endif
+_GL_CXXALIAS_SYS (acosf, float, (float x));
+_GL_CXXALIASWARN (acosf);
+#elif defined GNULIB_POSIXCHECK
+# undef acosf
+# if HAVE_RAW_DECL_ACOSF
+_GL_WARN_ON_USE (acosf, "acosf is unportable - "
+ "use gnulib module acosf for portability");
+# endif
+#endif
+
+#if @GNULIB_ACOSL@
+# if !@HAVE_ACOSL@ || !@HAVE_DECL_ACOSL@
+# undef acosl
+_GL_FUNCDECL_SYS (acosl, long double, (long double x));
+# endif
+_GL_CXXALIAS_SYS (acosl, long double, (long double x));
+_GL_CXXALIASWARN (acosl);
+#elif defined GNULIB_POSIXCHECK
+# undef acosl
+# if HAVE_RAW_DECL_ACOSL
+_GL_WARN_ON_USE (acosl, "acosl is unportable - "
+ "use gnulib module acosl for portability");
+# endif
+#endif
+
+
+#if @GNULIB_ASINF@
+# if !@HAVE_ASINF@
+# undef asinf
+_GL_FUNCDECL_SYS (asinf, float, (float x));
+# endif
+_GL_CXXALIAS_SYS (asinf, float, (float x));
+_GL_CXXALIASWARN (asinf);
+#elif defined GNULIB_POSIXCHECK
+# undef asinf
+# if HAVE_RAW_DECL_ASINF
+_GL_WARN_ON_USE (asinf, "asinf is unportable - "
+ "use gnulib module asinf for portability");
+# endif
+#endif
+
+#if @GNULIB_ASINL@
+# if !@HAVE_ASINL@ || !@HAVE_DECL_ASINL@
+# undef asinl
+_GL_FUNCDECL_SYS (asinl, long double, (long double x));
+# endif
+_GL_CXXALIAS_SYS (asinl, long double, (long double x));
+_GL_CXXALIASWARN (asinl);
+#elif defined GNULIB_POSIXCHECK
+# undef asinl
+# if HAVE_RAW_DECL_ASINL
+_GL_WARN_ON_USE (asinl, "asinl is unportable - "
+ "use gnulib module asinl for portability");
+# endif
+#endif
+
+
+#if @GNULIB_ATANF@
+# if !@HAVE_ATANF@
+# undef atanf
+_GL_FUNCDECL_SYS (atanf, float, (float x));
+# endif
+_GL_CXXALIAS_SYS (atanf, float, (float x));
+_GL_CXXALIASWARN (atanf);
+#elif defined GNULIB_POSIXCHECK
+# undef atanf
+# if HAVE_RAW_DECL_ATANF
+_GL_WARN_ON_USE (atanf, "atanf is unportable - "
+ "use gnulib module atanf for portability");
+# endif
+#endif
+
+#if @GNULIB_ATANL@
+# if !@HAVE_ATANL@ || !@HAVE_DECL_ATANL@
+# undef atanl
+_GL_FUNCDECL_SYS (atanl, long double, (long double x));
+# endif
+_GL_CXXALIAS_SYS (atanl, long double, (long double x));
+_GL_CXXALIASWARN (atanl);
+#elif defined GNULIB_POSIXCHECK
+# undef atanl
+# if HAVE_RAW_DECL_ATANL
+_GL_WARN_ON_USE (atanl, "atanl is unportable - "
+ "use gnulib module atanl for portability");
+# endif
+#endif
+
+
+#if @GNULIB_ATAN2F@
+# if !@HAVE_ATAN2F@
+# undef atan2f
+_GL_FUNCDECL_SYS (atan2f, float, (float y, float x));
+# endif
+_GL_CXXALIAS_SYS (atan2f, float, (float y, float x));
+_GL_CXXALIASWARN (atan2f);
+#elif defined GNULIB_POSIXCHECK
+# undef atan2f
+# if HAVE_RAW_DECL_ATAN2F
+_GL_WARN_ON_USE (atan2f, "atan2f is unportable - "
+ "use gnulib module atan2f for portability");
+# endif
+#endif
+
+
+#if @GNULIB_CBRTF@
+# if @REPLACE_CBRTF@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef cbrtf
+# define cbrtf rpl_cbrtf
+# endif
+_GL_FUNCDECL_RPL (cbrtf, float, (float x));
+_GL_CXXALIAS_RPL (cbrtf, float, (float x));
+# else
+# if !@HAVE_DECL_CBRTF@
+_GL_FUNCDECL_SYS (cbrtf, float, (float x));
+# endif
+_GL_CXXALIAS_SYS (cbrtf, float, (float x));
+# endif
+_GL_CXXALIASWARN (cbrtf);
+#elif defined GNULIB_POSIXCHECK
+# undef cbrtf
+# if HAVE_RAW_DECL_CBRTF
+_GL_WARN_ON_USE (cbrtf, "cbrtf is unportable - "
+ "use gnulib module cbrtf for portability");
+# endif
+#endif
+
+#if @GNULIB_CBRT@
+# if !@HAVE_CBRT@
+_GL_FUNCDECL_SYS (cbrt, double, (double x));
+# endif
+_GL_CXXALIAS_SYS (cbrt, double, (double x));
+_GL_CXXALIASWARN (cbrt);
+#elif defined GNULIB_POSIXCHECK
+# undef cbrt
+# if HAVE_RAW_DECL_CBRT
+_GL_WARN_ON_USE (cbrt, "cbrt is unportable - "
+ "use gnulib module cbrt for portability");
+# endif
+#endif
+
+#if @GNULIB_CBRTL@
+# if @REPLACE_CBRTL@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef cbrtl
+# define cbrtl rpl_cbrtl
+# endif
+_GL_FUNCDECL_RPL (cbrtl, long double, (long double x));
+_GL_CXXALIAS_RPL (cbrtl, long double, (long double x));
+# else
+# if !@HAVE_DECL_CBRTL@
+_GL_FUNCDECL_SYS (cbrtl, long double, (long double x));
+# endif
+_GL_CXXALIAS_SYS (cbrtl, long double, (long double x));
+# endif
+_GL_CXXALIASWARN (cbrtl);
+#elif defined GNULIB_POSIXCHECK
+# undef cbrtl
+# if HAVE_RAW_DECL_CBRTL
+_GL_WARN_ON_USE (cbrtl, "cbrtl is unportable - "
+ "use gnulib module cbrtl for portability");
+# endif
+#endif
+
+
+#if @GNULIB_CEILF@
+# if @REPLACE_CEILF@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef ceilf
+# define ceilf rpl_ceilf
+# endif
+_GL_FUNCDECL_RPL (ceilf, float, (float x));
+_GL_CXXALIAS_RPL (ceilf, float, (float x));
+# else
+# if !@HAVE_DECL_CEILF@
+# undef ceilf
+_GL_FUNCDECL_SYS (ceilf, float, (float x));
+# endif
+_GL_CXXALIAS_SYS (ceilf, float, (float x));
+# endif
+_GL_CXXALIASWARN (ceilf);
+#elif defined GNULIB_POSIXCHECK
+# undef ceilf
+# if HAVE_RAW_DECL_CEILF
+_GL_WARN_ON_USE (ceilf, "ceilf is unportable - "
+ "use gnulib module ceilf for portability");
+# endif
+#endif
+
+#if @GNULIB_CEIL@
+# if @REPLACE_CEIL@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define ceil rpl_ceil
+# endif
+_GL_FUNCDECL_RPL (ceil, double, (double x));
+_GL_CXXALIAS_RPL (ceil, double, (double x));
+# else
+_GL_CXXALIAS_SYS (ceil, double, (double x));
+# endif
+_GL_CXXALIASWARN (ceil);
+#endif
+
+#if @GNULIB_CEILL@
+# if @REPLACE_CEILL@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef ceill
+# define ceill rpl_ceill
+# endif
+_GL_FUNCDECL_RPL (ceill, long double, (long double x));
+_GL_CXXALIAS_RPL (ceill, long double, (long double x));
+# else
+# if !@HAVE_DECL_CEILL@
+# undef ceill
+_GL_FUNCDECL_SYS (ceill, long double, (long double x));
+# endif
+_GL_CXXALIAS_SYS (ceill, long double, (long double x));
+# endif
+_GL_CXXALIASWARN (ceill);
+#elif defined GNULIB_POSIXCHECK
+# undef ceill
+# if HAVE_RAW_DECL_CEILL
+_GL_WARN_ON_USE (ceill, "ceill is unportable - "
+ "use gnulib module ceill for portability");
+# endif
+#endif
+
+
+#if @GNULIB_COPYSIGNF@
+# if !@HAVE_DECL_COPYSIGNF@
+_GL_FUNCDECL_SYS (copysignf, float, (float x, float y));
+# endif
+_GL_CXXALIAS_SYS (copysignf, float, (float x, float y));
+_GL_CXXALIASWARN (copysignf);
+#elif defined GNULIB_POSIXCHECK
+# undef copysignf
+# if HAVE_RAW_DECL_COPYSIGNF
+_GL_WARN_ON_USE (copysignf, "copysignf is unportable - "
+ "use gnulib module copysignf for portability");
+# endif
+#endif
+
+#if @GNULIB_COPYSIGN@
+# if !@HAVE_COPYSIGN@
+_GL_FUNCDECL_SYS (copysign, double, (double x, double y));
+# endif
+_GL_CXXALIAS_SYS (copysign, double, (double x, double y));
+_GL_CXXALIASWARN (copysign);
+#elif defined GNULIB_POSIXCHECK
+# undef copysign
+# if HAVE_RAW_DECL_COPYSIGN
+_GL_WARN_ON_USE (copysign, "copysign is unportable - "
+ "use gnulib module copysign for portability");
+# endif
+#endif
+
+#if @GNULIB_COPYSIGNL@
+# if !@HAVE_COPYSIGNL@
+_GL_FUNCDECL_SYS (copysignl, long double, (long double x, long double y));
+# endif
+_GL_CXXALIAS_SYS (copysignl, long double, (long double x, long double y));
+_GL_CXXALIASWARN (copysignl);
+#elif defined GNULIB_POSIXCHECK
+# undef copysignl
+# if HAVE_RAW_DECL_COPYSIGNL
+_GL_WARN_ON_USE (copysign, "copysignl is unportable - "
+ "use gnulib module copysignl for portability");
+# endif
+#endif
+
+
+#if @GNULIB_COSF@
+# if !@HAVE_COSF@
+# undef cosf
+_GL_FUNCDECL_SYS (cosf, float, (float x));
+# endif
+_GL_CXXALIAS_SYS (cosf, float, (float x));
+_GL_CXXALIASWARN (cosf);
+#elif defined GNULIB_POSIXCHECK
+# undef cosf
+# if HAVE_RAW_DECL_COSF
+_GL_WARN_ON_USE (cosf, "cosf is unportable - "
+ "use gnulib module cosf for portability");
+# endif
+#endif
+
+#if @GNULIB_COSL@
+# if !@HAVE_COSL@ || !@HAVE_DECL_COSL@
+# undef cosl
+_GL_FUNCDECL_SYS (cosl, long double, (long double x));
+# endif
+_GL_CXXALIAS_SYS (cosl, long double, (long double x));
+_GL_CXXALIASWARN (cosl);
+#elif defined GNULIB_POSIXCHECK
+# undef cosl
+# if HAVE_RAW_DECL_COSL
+_GL_WARN_ON_USE (cosl, "cosl is unportable - "
+ "use gnulib module cosl for portability");
+# endif
+#endif
+
+
+#if @GNULIB_COSHF@
+# if !@HAVE_COSHF@
+# undef coshf
+_GL_FUNCDECL_SYS (coshf, float, (float x));
+# endif
+_GL_CXXALIAS_SYS (coshf, float, (float x));
+_GL_CXXALIASWARN (coshf);
+#elif defined GNULIB_POSIXCHECK
+# undef coshf
+# if HAVE_RAW_DECL_COSHF
+_GL_WARN_ON_USE (coshf, "coshf is unportable - "
+ "use gnulib module coshf for portability");
+# endif
+#endif
+
+
+#if @GNULIB_EXPF@
+# if !@HAVE_EXPF@
+# undef expf
+_GL_FUNCDECL_SYS (expf, float, (float x));
+# endif
+_GL_CXXALIAS_SYS (expf, float, (float x));
+_GL_CXXALIASWARN (expf);
+#elif defined GNULIB_POSIXCHECK
+# undef expf
+# if HAVE_RAW_DECL_EXPF
+_GL_WARN_ON_USE (expf, "expf is unportable - "
+ "use gnulib module expf for portability");
+# endif
+#endif
+
+#if @GNULIB_EXPL@
+# if !@HAVE_EXPL@ || !@HAVE_DECL_EXPL@
+# undef expl
+_GL_FUNCDECL_SYS (expl, long double, (long double x));
+# endif
+_GL_CXXALIAS_SYS (expl, long double, (long double x));
+_GL_CXXALIASWARN (expl);
+#elif defined GNULIB_POSIXCHECK
+# undef expl
+# if HAVE_RAW_DECL_EXPL
+_GL_WARN_ON_USE (expl, "expl is unportable - "
+ "use gnulib module expl for portability");
+# endif
+#endif
+
+
+#if @GNULIB_EXP2F@
+# if !@HAVE_DECL_EXP2F@
+_GL_FUNCDECL_SYS (exp2f, float, (float x));
+# endif
+_GL_CXXALIAS_SYS (exp2f, float, (float x));
+_GL_CXXALIASWARN (exp2f);
+#elif defined GNULIB_POSIXCHECK
+# undef exp2f
+# if HAVE_RAW_DECL_EXP2F
+_GL_WARN_ON_USE (exp2f, "exp2f is unportable - "
+ "use gnulib module exp2f for portability");
+# endif
+#endif
+
+#if @GNULIB_EXP2@
+# if @REPLACE_EXP2@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef exp2
+# define exp2 rpl_exp2
+# endif
+_GL_FUNCDECL_RPL (exp2, double, (double x));
+_GL_CXXALIAS_RPL (exp2, double, (double x));
+# else
+# if !@HAVE_DECL_EXP2@
+_GL_FUNCDECL_SYS (exp2, double, (double x));
+# endif
+_GL_CXXALIAS_SYS (exp2, double, (double x));
+# endif
+_GL_CXXALIASWARN (exp2);
+#elif defined GNULIB_POSIXCHECK
+# undef exp2
+# if HAVE_RAW_DECL_EXP2
+_GL_WARN_ON_USE (exp2, "exp2 is unportable - "
+ "use gnulib module exp2 for portability");
+# endif
+#endif
+
+#if @GNULIB_EXP2L@
+# if @REPLACE_EXP2L@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef exp2l
+# define exp2l rpl_exp2l
+# endif
+_GL_FUNCDECL_RPL (exp2l, long double, (long double x));
+_GL_CXXALIAS_RPL (exp2l, long double, (long double x));
+# else
+# if !@HAVE_DECL_EXP2L@
+# undef exp2l
+_GL_FUNCDECL_SYS (exp2l, long double, (long double x));
+# endif
+_GL_CXXALIAS_SYS (exp2l, long double, (long double x));
+# endif
+_GL_CXXALIASWARN (exp2l);
+#elif defined GNULIB_POSIXCHECK
+# undef exp2l
+# if HAVE_RAW_DECL_EXP2L
+_GL_WARN_ON_USE (exp2l, "exp2l is unportable - "
+ "use gnulib module exp2l for portability");
+# endif
+#endif
+
+
+#if @GNULIB_EXPM1F@
+# if @REPLACE_EXPM1F@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef expm1f
+# define expm1f rpl_expm1f
+# endif
+_GL_FUNCDECL_RPL (expm1f, float, (float x));
+_GL_CXXALIAS_RPL (expm1f, float, (float x));
+# else
+# if !@HAVE_EXPM1F@
+_GL_FUNCDECL_SYS (expm1f, float, (float x));
+# endif
+_GL_CXXALIAS_SYS (expm1f, float, (float x));
+# endif
+_GL_CXXALIASWARN (expm1f);
+#elif defined GNULIB_POSIXCHECK
+# undef expm1f
+# if HAVE_RAW_DECL_EXPM1F
+_GL_WARN_ON_USE (expm1f, "expm1f is unportable - "
+ "use gnulib module expm1f for portability");
+# endif
+#endif
+
+#if @GNULIB_EXPM1@
+# if @REPLACE_EXPM1@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef expm1
+# define expm1 rpl_expm1
+# endif
+_GL_FUNCDECL_RPL (expm1, double, (double x));
+_GL_CXXALIAS_RPL (expm1, double, (double x));
+# else
+# if !@HAVE_EXPM1@
+_GL_FUNCDECL_SYS (expm1, double, (double x));
+# endif
+_GL_CXXALIAS_SYS (expm1, double, (double x));
+# endif
+_GL_CXXALIASWARN (expm1);
+#elif defined GNULIB_POSIXCHECK
+# undef expm1
+# if HAVE_RAW_DECL_EXPM1
+_GL_WARN_ON_USE (expm1, "expm1 is unportable - "
+ "use gnulib module expm1 for portability");
+# endif
+#endif
+
+#if @GNULIB_EXPM1L@
+# if !@HAVE_DECL_EXPM1L@
+# undef expm1l
+_GL_FUNCDECL_SYS (expm1l, long double, (long double x));
+# endif
+_GL_CXXALIAS_SYS (expm1l, long double, (long double x));
+_GL_CXXALIASWARN (expm1l);
+#elif defined GNULIB_POSIXCHECK
+# undef expm1l
+# if HAVE_RAW_DECL_EXPM1L
+_GL_WARN_ON_USE (expm1l, "expm1l is unportable - "
+ "use gnulib module expm1l for portability");
+# endif
+#endif
+
+
+#if @GNULIB_FABSF@
+# if !@HAVE_FABSF@
+# undef fabsf
+_GL_FUNCDECL_SYS (fabsf, float, (float x));
+# endif
+_GL_CXXALIAS_SYS (fabsf, float, (float x));
+_GL_CXXALIASWARN (fabsf);
+#elif defined GNULIB_POSIXCHECK
+# undef fabsf
+# if HAVE_RAW_DECL_FABSF
+_GL_WARN_ON_USE (fabsf, "fabsf is unportable - "
+ "use gnulib module fabsf for portability");
+# endif
+#endif
+
+#if @GNULIB_FABSL@
+# if @REPLACE_FABSL@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef fabsl
+# define fabsl rpl_fabsl
+# endif
+_GL_FUNCDECL_RPL (fabsl, long double, (long double x));
+_GL_CXXALIAS_RPL (fabsl, long double, (long double x));
+# else
+# if !@HAVE_FABSL@
+# undef fabsl
+_GL_FUNCDECL_SYS (fabsl, long double, (long double x));
+# endif
+_GL_CXXALIAS_SYS (fabsl, long double, (long double x));
+# endif
+_GL_CXXALIASWARN (fabsl);
+#elif defined GNULIB_POSIXCHECK
+# undef fabsl
+# if HAVE_RAW_DECL_FABSL
+_GL_WARN_ON_USE (fabsl, "fabsl is unportable - "
+ "use gnulib module fabsl for portability");
+# endif
+#endif
+
+
+#if @GNULIB_FLOORF@
+# if @REPLACE_FLOORF@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef floorf
+# define floorf rpl_floorf
+# endif
+_GL_FUNCDECL_RPL (floorf, float, (float x));
+_GL_CXXALIAS_RPL (floorf, float, (float x));
+# else
+# if !@HAVE_DECL_FLOORF@
+# undef floorf
+_GL_FUNCDECL_SYS (floorf, float, (float x));
+# endif
+_GL_CXXALIAS_SYS (floorf, float, (float x));
+# endif
+_GL_CXXALIASWARN (floorf);
+#elif defined GNULIB_POSIXCHECK
+# undef floorf
+# if HAVE_RAW_DECL_FLOORF
+_GL_WARN_ON_USE (floorf, "floorf is unportable - "
+ "use gnulib module floorf for portability");
+# endif
+#endif
+
+#if @GNULIB_FLOOR@
+# if @REPLACE_FLOOR@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define floor rpl_floor
+# endif
+_GL_FUNCDECL_RPL (floor, double, (double x));
+_GL_CXXALIAS_RPL (floor, double, (double x));
+# else
+_GL_CXXALIAS_SYS (floor, double, (double x));
+# endif
+_GL_CXXALIASWARN (floor);
+#endif
+
+#if @GNULIB_FLOORL@
+# if @REPLACE_FLOORL@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef floorl
+# define floorl rpl_floorl
+# endif
+_GL_FUNCDECL_RPL (floorl, long double, (long double x));
+_GL_CXXALIAS_RPL (floorl, long double, (long double x));
+# else
+# if !@HAVE_DECL_FLOORL@
+# undef floorl
+_GL_FUNCDECL_SYS (floorl, long double, (long double x));
+# endif
+_GL_CXXALIAS_SYS (floorl, long double, (long double x));
+# endif
+_GL_CXXALIASWARN (floorl);
+#elif defined GNULIB_POSIXCHECK
+# undef floorl
+# if HAVE_RAW_DECL_FLOORL
+_GL_WARN_ON_USE (floorl, "floorl is unportable - "
+ "use gnulib module floorl for portability");
+# endif
+#endif
+
+
+#if @GNULIB_FMAF@
+# if @REPLACE_FMAF@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef fmaf
+# define fmaf rpl_fmaf
+# endif
+_GL_FUNCDECL_RPL (fmaf, float, (float x, float y, float z));
+_GL_CXXALIAS_RPL (fmaf, float, (float x, float y, float z));
+# else
+# if !@HAVE_FMAF@
+_GL_FUNCDECL_SYS (fmaf, float, (float x, float y, float z));
+# endif
+_GL_CXXALIAS_SYS (fmaf, float, (float x, float y, float z));
+# endif
+_GL_CXXALIASWARN (fmaf);
+#elif defined GNULIB_POSIXCHECK
+# undef fmaf
+# if HAVE_RAW_DECL_FMAF
+_GL_WARN_ON_USE (fmaf, "fmaf is unportable - "
+ "use gnulib module fmaf for portability");
+# endif
+#endif
+
+#if @GNULIB_FMA@
+# if @REPLACE_FMA@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef fma
+# define fma rpl_fma
+# endif
+_GL_FUNCDECL_RPL (fma, double, (double x, double y, double z));
+_GL_CXXALIAS_RPL (fma, double, (double x, double y, double z));
+# else
+# if !@HAVE_FMA@
+_GL_FUNCDECL_SYS (fma, double, (double x, double y, double z));
+# endif
+_GL_CXXALIAS_SYS (fma, double, (double x, double y, double z));
+# endif
+_GL_CXXALIASWARN (fma);
+#elif defined GNULIB_POSIXCHECK
+# undef fma
+# if HAVE_RAW_DECL_FMA
+_GL_WARN_ON_USE (fma, "fma is unportable - "
+ "use gnulib module fma for portability");
+# endif
+#endif
+
+#if @GNULIB_FMAL@
+# if @REPLACE_FMAL@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef fmal
+# define fmal rpl_fmal
+# endif
+_GL_FUNCDECL_RPL (fmal, long double,
+ (long double x, long double y, long double z));
+_GL_CXXALIAS_RPL (fmal, long double,
+ (long double x, long double y, long double z));
+# else
+# if !@HAVE_FMAL@
+# undef fmal
+_GL_FUNCDECL_SYS (fmal, long double,
+ (long double x, long double y, long double z));
+# endif
+_GL_CXXALIAS_SYS (fmal, long double,
+ (long double x, long double y, long double z));
+# endif
+_GL_CXXALIASWARN (fmal);
+#elif defined GNULIB_POSIXCHECK
+# undef fmal
+# if HAVE_RAW_DECL_FMAL
+_GL_WARN_ON_USE (fmal, "fmal is unportable - "
+ "use gnulib module fmal for portability");
+# endif
+#endif
+
+
+#if @GNULIB_FMODF@
+# if @REPLACE_FMODF@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef fmodf
+# define fmodf rpl_fmodf
+# endif
+_GL_FUNCDECL_RPL (fmodf, float, (float x, float y));
+_GL_CXXALIAS_RPL (fmodf, float, (float x, float y));
+# else
+# if !@HAVE_FMODF@
+# undef fmodf
+_GL_FUNCDECL_SYS (fmodf, float, (float x, float y));
+# endif
+_GL_CXXALIAS_SYS (fmodf, float, (float x, float y));
+# endif
+_GL_CXXALIASWARN (fmodf);
+#elif defined GNULIB_POSIXCHECK
+# undef fmodf
+# if HAVE_RAW_DECL_FMODF
+_GL_WARN_ON_USE (fmodf, "fmodf is unportable - "
+ "use gnulib module fmodf for portability");
+# endif
+#endif
+
+#if @GNULIB_FMOD@
+# if @REPLACE_FMOD@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef fmod
+# define fmod rpl_fmod
+# endif
+_GL_FUNCDECL_RPL (fmod, double, (double x, double y));
+_GL_CXXALIAS_RPL (fmod, double, (double x, double y));
+# else
+_GL_CXXALIAS_SYS (fmod, double, (double x, double y));
+# endif
+_GL_CXXALIASWARN (fmod);
+#elif defined GNULIB_POSIXCHECK
+# undef fmod
+# if HAVE_RAW_DECL_FMOD
+_GL_WARN_ON_USE (fmod, "fmod has portability problems - "
+ "use gnulib module fmod for portability");
+# endif
+#endif
+
+#if @GNULIB_FMODL@
+# if @REPLACE_FMODL@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef fmodl
+# define fmodl rpl_fmodl
+# endif
+_GL_FUNCDECL_RPL (fmodl, long double, (long double x, long double y));
+_GL_CXXALIAS_RPL (fmodl, long double, (long double x, long double y));
+# else
+# if !@HAVE_FMODL@
+# undef fmodl
+_GL_FUNCDECL_SYS (fmodl, long double, (long double x, long double y));
+# endif
+_GL_CXXALIAS_SYS (fmodl, long double, (long double x, long double y));
+# endif
+_GL_CXXALIASWARN (fmodl);
+#elif defined GNULIB_POSIXCHECK
+# undef fmodl
+# if HAVE_RAW_DECL_FMODL
+_GL_WARN_ON_USE (fmodl, "fmodl is unportable - "
+ "use gnulib module fmodl for portability");
+# endif
+#endif
+
+
+/* Write x as
+ x = mantissa * 2^exp
+ where
+ If x finite and nonzero: 0.5 <= |mantissa| < 1.0.
+ If x is zero: mantissa = x, exp = 0.
+ If x is infinite or NaN: mantissa = x, exp unspecified.
+ Store exp in *EXPPTR and return mantissa. */
+#if @GNULIB_FREXPF@
+# if @REPLACE_FREXPF@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef frexpf
+# define frexpf rpl_frexpf
+# endif
+_GL_FUNCDECL_RPL (frexpf, float, (float x, int *expptr) _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_RPL (frexpf, float, (float x, int *expptr));
+# else
+# if !@HAVE_FREXPF@
+# undef frexpf
+_GL_FUNCDECL_SYS (frexpf, float, (float x, int *expptr) _GL_ARG_NONNULL ((2)));
+# endif
+_GL_CXXALIAS_SYS (frexpf, float, (float x, int *expptr));
+# endif
+_GL_CXXALIASWARN (frexpf);
+#elif defined GNULIB_POSIXCHECK
+# undef frexpf
+# if HAVE_RAW_DECL_FREXPF
+_GL_WARN_ON_USE (frexpf, "frexpf is unportable - "
+ "use gnulib module frexpf for portability");
+# endif
+#endif
+
+/* Write x as
+ x = mantissa * 2^exp
+ where
+ If x finite and nonzero: 0.5 <= |mantissa| < 1.0.
+ If x is zero: mantissa = x, exp = 0.
+ If x is infinite or NaN: mantissa = x, exp unspecified.
+ Store exp in *EXPPTR and return mantissa. */
+#if @GNULIB_FREXP@
+# if @REPLACE_FREXP@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define frexp rpl_frexp
+# endif
+_GL_FUNCDECL_RPL (frexp, double, (double x, int *expptr) _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_RPL (frexp, double, (double x, int *expptr));
+# else
+_GL_CXXALIAS_SYS (frexp, double, (double x, int *expptr));
+# endif
+_GL_CXXALIASWARN (frexp);
+#elif defined GNULIB_POSIXCHECK
+# undef frexp
+/* Assume frexp is always declared. */
+_GL_WARN_ON_USE (frexp, "frexp is unportable - "
+ "use gnulib module frexp for portability");
+#endif
+
+/* Write x as
+ x = mantissa * 2^exp
+ where
+ If x finite and nonzero: 0.5 <= |mantissa| < 1.0.
+ If x is zero: mantissa = x, exp = 0.
+ If x is infinite or NaN: mantissa = x, exp unspecified.
+ Store exp in *EXPPTR and return mantissa. */
+#if @GNULIB_FREXPL@ && @REPLACE_FREXPL@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef frexpl
+# define frexpl rpl_frexpl
+# endif
+_GL_FUNCDECL_RPL (frexpl, long double,
+ (long double x, int *expptr) _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_RPL (frexpl, long double, (long double x, int *expptr));
+#else
+# if !@HAVE_DECL_FREXPL@
+_GL_FUNCDECL_SYS (frexpl, long double,
+ (long double x, int *expptr) _GL_ARG_NONNULL ((2)));
+# endif
+# if @GNULIB_FREXPL@
+_GL_CXXALIAS_SYS (frexpl, long double, (long double x, int *expptr));
+# endif
+#endif
+#if @GNULIB_FREXPL@ && !(@REPLACE_FREXPL@ && !@HAVE_DECL_FREXPL@)
+_GL_CXXALIASWARN (frexpl);
+#endif
+#if !@GNULIB_FREXPL@ && defined GNULIB_POSIXCHECK
+# undef frexpl
+# if HAVE_RAW_DECL_FREXPL
+_GL_WARN_ON_USE (frexpl, "frexpl is unportable - "
+ "use gnulib module frexpl for portability");
+# endif
+#endif
+
+
+/* Return sqrt(x^2+y^2). */
+#if @GNULIB_HYPOTF@
+# if @REPLACE_HYPOTF@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef hypotf
+# define hypotf rpl_hypotf
+# endif
+_GL_FUNCDECL_RPL (hypotf, float, (float x, float y));
+_GL_CXXALIAS_RPL (hypotf, float, (float x, float y));
+# else
+# if !@HAVE_HYPOTF@
+_GL_FUNCDECL_SYS (hypotf, float, (float x, float y));
+# endif
+_GL_CXXALIAS_SYS (hypotf, float, (float x, float y));
+# endif
+_GL_CXXALIASWARN (hypotf);
+#elif defined GNULIB_POSIXCHECK
+# undef hypotf
+# if HAVE_RAW_DECL_HYPOTF
+_GL_WARN_ON_USE (hypotf, "hypotf is unportable - "
+ "use gnulib module hypotf for portability");
+# endif
+#endif
+
+/* Return sqrt(x^2+y^2). */
+#if @GNULIB_HYPOT@
+# if @REPLACE_HYPOT@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef hypot
+# define hypot rpl_hypot
+# endif
+_GL_FUNCDECL_RPL (hypot, double, (double x, double y));
+_GL_CXXALIAS_RPL (hypot, double, (double x, double y));
+# else
+_GL_CXXALIAS_SYS (hypot, double, (double x, double y));
+# endif
+_GL_CXXALIASWARN (hypot);
+#elif defined GNULIB_POSIXCHECK
+# undef hypot
+# if HAVE_RAW_DECL_HYPOT
+_GL_WARN_ON_USE (hypotf, "hypot has portability problems - "
+ "use gnulib module hypot for portability");
+# endif
+#endif
+
+/* Return sqrt(x^2+y^2). */
+#if @GNULIB_HYPOTL@
+# if @REPLACE_HYPOTL@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef hypotl
+# define hypotl rpl_hypotl
+# endif
+_GL_FUNCDECL_RPL (hypotl, long double, (long double x, long double y));
+_GL_CXXALIAS_RPL (hypotl, long double, (long double x, long double y));
+# else
+# if !@HAVE_HYPOTL@
+_GL_FUNCDECL_SYS (hypotl, long double, (long double x, long double y));
+# endif
+_GL_CXXALIAS_SYS (hypotl, long double, (long double x, long double y));
+# endif
+_GL_CXXALIASWARN (hypotl);
+#elif defined GNULIB_POSIXCHECK
+# undef hypotl
+# if HAVE_RAW_DECL_HYPOTL
+_GL_WARN_ON_USE (hypotl, "hypotl is unportable - "
+ "use gnulib module hypotl for portability");
+# endif
+#endif
+
+
+#if @GNULIB_ILOGBF@
+# if @REPLACE_ILOGBF@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef ilogbf
+# define ilogbf rpl_ilogbf
+# endif
+_GL_FUNCDECL_RPL (ilogbf, int, (float x));
+_GL_CXXALIAS_RPL (ilogbf, int, (float x));
+# else
+# if !@HAVE_ILOGBF@
+_GL_FUNCDECL_SYS (ilogbf, int, (float x));
+# endif
+_GL_CXXALIAS_SYS (ilogbf, int, (float x));
+# endif
+_GL_CXXALIASWARN (ilogbf);
+#elif defined GNULIB_POSIXCHECK
+# undef ilogbf
+# if HAVE_RAW_DECL_ILOGBF
+_GL_WARN_ON_USE (ilogbf, "ilogbf is unportable - "
+ "use gnulib module ilogbf for portability");
+# endif
+#endif
+
+#if @GNULIB_ILOGB@
+# if @REPLACE_ILOGB@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef ilogb
+# define ilogb rpl_ilogb
+# endif
+_GL_FUNCDECL_RPL (ilogb, int, (double x));
+_GL_CXXALIAS_RPL (ilogb, int, (double x));
+# else
+# if !@HAVE_ILOGB@
+_GL_FUNCDECL_SYS (ilogb, int, (double x));
+# endif
+_GL_CXXALIAS_SYS (ilogb, int, (double x));
+# endif
+_GL_CXXALIASWARN (ilogb);
+#elif defined GNULIB_POSIXCHECK
+# undef ilogb
+# if HAVE_RAW_DECL_ILOGB
+_GL_WARN_ON_USE (ilogb, "ilogb is unportable - "
+ "use gnulib module ilogb for portability");
+# endif
+#endif
+
+#if @GNULIB_ILOGBL@
+# if !@HAVE_ILOGBL@
+_GL_FUNCDECL_SYS (ilogbl, int, (long double x));
+# endif
+_GL_CXXALIAS_SYS (ilogbl, int, (long double x));
+_GL_CXXALIASWARN (ilogbl);
+#elif defined GNULIB_POSIXCHECK
+# undef ilogbl
+# if HAVE_RAW_DECL_ILOGBL
+_GL_WARN_ON_USE (ilogbl, "ilogbl is unportable - "
+ "use gnulib module ilogbl for portability");
+# endif
+#endif
+
+
+/* Return x * 2^exp. */
+#if @GNULIB_LDEXPF@
+# if !@HAVE_LDEXPF@
+# undef ldexpf
+_GL_FUNCDECL_SYS (ldexpf, float, (float x, int exp));
+# endif
+_GL_CXXALIAS_SYS (ldexpf, float, (float x, int exp));
+_GL_CXXALIASWARN (ldexpf);
+#elif defined GNULIB_POSIXCHECK
+# undef ldexpf
+# if HAVE_RAW_DECL_LDEXPF
+_GL_WARN_ON_USE (ldexpf, "ldexpf is unportable - "
+ "use gnulib module ldexpf for portability");
+# endif
+#endif
+
+/* Return x * 2^exp. */
+#if @GNULIB_LDEXPL@ && @REPLACE_LDEXPL@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef ldexpl
+# define ldexpl rpl_ldexpl
+# endif
+_GL_FUNCDECL_RPL (ldexpl, long double, (long double x, int exp));
+_GL_CXXALIAS_RPL (ldexpl, long double, (long double x, int exp));
+#else
+# if !@HAVE_DECL_LDEXPL@
+_GL_FUNCDECL_SYS (ldexpl, long double, (long double x, int exp));
+# endif
+# if @GNULIB_LDEXPL@
+_GL_CXXALIAS_SYS (ldexpl, long double, (long double x, int exp));
+# endif
+#endif
+#if @GNULIB_LDEXPL@
+_GL_CXXALIASWARN (ldexpl);
+#endif
+#if !@GNULIB_LDEXPL@ && defined GNULIB_POSIXCHECK
+# undef ldexpl
+# if HAVE_RAW_DECL_LDEXPL
+_GL_WARN_ON_USE (ldexpl, "ldexpl is unportable - "
+ "use gnulib module ldexpl for portability");
+# endif
+#endif
+
+
+#if @GNULIB_LOGF@
+# if @REPLACE_LOGF@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef logf
+# define logf rpl_logf
+# endif
+_GL_FUNCDECL_RPL (logf, float, (float x));
+_GL_CXXALIAS_RPL (logf, float, (float x));
+# else
+# if !@HAVE_LOGF@
+# undef logf
+_GL_FUNCDECL_SYS (logf, float, (float x));
+# endif
+_GL_CXXALIAS_SYS (logf, float, (float x));
+# endif
+_GL_CXXALIASWARN (logf);
+#elif defined GNULIB_POSIXCHECK
+# undef logf
+# if HAVE_RAW_DECL_LOGF
+_GL_WARN_ON_USE (logf, "logf is unportable - "
+ "use gnulib module logf for portability");
+# endif
+#endif
+
+#if @GNULIB_LOG@
+# if @REPLACE_LOG@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef log
+# define log rpl_log
+# endif
+_GL_FUNCDECL_RPL (log, double, (double x));
+_GL_CXXALIAS_RPL (log, double, (double x));
+# else
+_GL_CXXALIAS_SYS (log, double, (double x));
+# endif
+_GL_CXXALIASWARN (log);
+#elif defined GNULIB_POSIXCHECK
+# undef log
+# if HAVE_RAW_DECL_LOG
+_GL_WARN_ON_USE (log, "log has portability problems - "
+ "use gnulib module log for portability");
+# endif
+#endif
+
+#if @GNULIB_LOGL@
+# if @REPLACE_LOGL@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef logl
+# define logl rpl_logl
+# endif
+_GL_FUNCDECL_RPL (logl, long double, (long double x));
+_GL_CXXALIAS_RPL (logl, long double, (long double x));
+# else
+# if !@HAVE_LOGL@ || !@HAVE_DECL_LOGL@
+# undef logl
+_GL_FUNCDECL_SYS (logl, long double, (long double x));
+# endif
+_GL_CXXALIAS_SYS (logl, long double, (long double x));
+# endif
+_GL_CXXALIASWARN (logl);
+#elif defined GNULIB_POSIXCHECK
+# undef logl
+# if HAVE_RAW_DECL_LOGL
+_GL_WARN_ON_USE (logl, "logl is unportable - "
+ "use gnulib module logl for portability");
+# endif
+#endif
+
+
+#if @GNULIB_LOG10F@
+# if @REPLACE_LOG10F@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef log10f
+# define log10f rpl_log10f
+# endif
+_GL_FUNCDECL_RPL (log10f, float, (float x));
+_GL_CXXALIAS_RPL (log10f, float, (float x));
+# else
+# if !@HAVE_LOG10F@
+# undef log10f
+_GL_FUNCDECL_SYS (log10f, float, (float x));
+# endif
+_GL_CXXALIAS_SYS (log10f, float, (float x));
+# endif
+_GL_CXXALIASWARN (log10f);
+#elif defined GNULIB_POSIXCHECK
+# undef log10f
+# if HAVE_RAW_DECL_LOG10F
+_GL_WARN_ON_USE (log10f, "log10f is unportable - "
+ "use gnulib module log10f for portability");
+# endif
+#endif
+
+#if @GNULIB_LOG10@
+# if @REPLACE_LOG10@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef log10
+# define log10 rpl_log10
+# endif
+_GL_FUNCDECL_RPL (log10, double, (double x));
+_GL_CXXALIAS_RPL (log10, double, (double x));
+# else
+_GL_CXXALIAS_SYS (log10, double, (double x));
+# endif
+_GL_CXXALIASWARN (log10);
+#elif defined GNULIB_POSIXCHECK
+# undef log10
+# if HAVE_RAW_DECL_LOG10
+_GL_WARN_ON_USE (log10, "log10 has portability problems - "
+ "use gnulib module log10 for portability");
+# endif
+#endif
+
+#if @GNULIB_LOG10L@
+# if @REPLACE_LOG10L@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef log10l
+# define log10l rpl_log10l
+# endif
+_GL_FUNCDECL_RPL (log10l, long double, (long double x));
+_GL_CXXALIAS_RPL (log10l, long double, (long double x));
+# else
+# if !@HAVE_LOG10L@ || !@HAVE_DECL_LOG10L@
+# undef log10l
+_GL_FUNCDECL_SYS (log10l, long double, (long double x));
+# endif
+_GL_CXXALIAS_SYS (log10l, long double, (long double x));
+# endif
+_GL_CXXALIASWARN (log10l);
+#elif defined GNULIB_POSIXCHECK
+# undef log10l
+# if HAVE_RAW_DECL_LOG10L
+_GL_WARN_ON_USE (log10l, "log10l is unportable - "
+ "use gnulib module log10l for portability");
+# endif
+#endif
+
+
+#if @GNULIB_LOG1PF@
+# if @REPLACE_LOG1PF@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef log1pf
+# define log1pf rpl_log1pf
+# endif
+_GL_FUNCDECL_RPL (log1pf, float, (float x));
+_GL_CXXALIAS_RPL (log1pf, float, (float x));
+# else
+# if !@HAVE_LOG1PF@
+_GL_FUNCDECL_SYS (log1pf, float, (float x));
+# endif
+_GL_CXXALIAS_SYS (log1pf, float, (float x));
+# endif
+_GL_CXXALIASWARN (log1pf);
+#elif defined GNULIB_POSIXCHECK
+# undef log1pf
+# if HAVE_RAW_DECL_LOG1PF
+_GL_WARN_ON_USE (log1pf, "log1pf is unportable - "
+ "use gnulib module log1pf for portability");
+# endif
+#endif
+
+#if @GNULIB_LOG1P@
+# if @REPLACE_LOG1P@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef log1p
+# define log1p rpl_log1p
+# endif
+_GL_FUNCDECL_RPL (log1p, double, (double x));
+_GL_CXXALIAS_RPL (log1p, double, (double x));
+# else
+# if !@HAVE_LOG1P@
+_GL_FUNCDECL_SYS (log1p, double, (double x));
+# endif
+_GL_CXXALIAS_SYS (log1p, double, (double x));
+# endif
+_GL_CXXALIASWARN (log1p);
+#elif defined GNULIB_POSIXCHECK
+# undef log1p
+# if HAVE_RAW_DECL_LOG1P
+_GL_WARN_ON_USE (log1p, "log1p has portability problems - "
+ "use gnulib module log1p for portability");
+# endif
+#endif
+
+#if @GNULIB_LOG1PL@
+# if @REPLACE_LOG1PL@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef log1pl
+# define log1pl rpl_log1pl
+# endif
+_GL_FUNCDECL_RPL (log1pl, long double, (long double x));
+_GL_CXXALIAS_RPL (log1pl, long double, (long double x));
+# else
+# if !@HAVE_LOG1PL@
+_GL_FUNCDECL_SYS (log1pl, long double, (long double x));
+# endif
+_GL_CXXALIAS_SYS (log1pl, long double, (long double x));
+# endif
+_GL_CXXALIASWARN (log1pl);
+#elif defined GNULIB_POSIXCHECK
+# undef log1pl
+# if HAVE_RAW_DECL_LOG1PL
+_GL_WARN_ON_USE (log1pl, "log1pl has portability problems - "
+ "use gnulib module log1pl for portability");
+# endif
+#endif
+
+
+#if @GNULIB_LOG2F@
+# if @REPLACE_LOG2F@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef log2f
+# define log2f rpl_log2f
+# endif
+_GL_FUNCDECL_RPL (log2f, float, (float x));
+_GL_CXXALIAS_RPL (log2f, float, (float x));
+# else
+# if !@HAVE_DECL_LOG2F@
+# undef log2f
+_GL_FUNCDECL_SYS (log2f, float, (float x));
+# endif
+_GL_CXXALIAS_SYS (log2f, float, (float x));
+# endif
+_GL_CXXALIASWARN (log2f);
+#elif defined GNULIB_POSIXCHECK
+# undef log2f
+# if HAVE_RAW_DECL_LOG2F
+_GL_WARN_ON_USE (log2f, "log2f is unportable - "
+ "use gnulib module log2f for portability");
+# endif
+#endif
+
+#if @GNULIB_LOG2@
+# if @REPLACE_LOG2@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef log2
+# define log2 rpl_log2
+# endif
+_GL_FUNCDECL_RPL (log2, double, (double x));
+_GL_CXXALIAS_RPL (log2, double, (double x));
+# else
+# if !@HAVE_DECL_LOG2@
+# undef log2
+_GL_FUNCDECL_SYS (log2, double, (double x));
+# endif
+_GL_CXXALIAS_SYS (log2, double, (double x));
+# endif
+_GL_CXXALIASWARN (log2);
+#elif defined GNULIB_POSIXCHECK
+# undef log2
+# if HAVE_RAW_DECL_LOG2
+_GL_WARN_ON_USE (log2, "log2 is unportable - "
+ "use gnulib module log2 for portability");
+# endif
+#endif
+
+#if @GNULIB_LOG2L@
+# if @REPLACE_LOG2L@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef log2l
+# define log2l rpl_log2l
+# endif
+_GL_FUNCDECL_RPL (log2l, long double, (long double x));
+_GL_CXXALIAS_RPL (log2l, long double, (long double x));
+# else
+# if !@HAVE_DECL_LOG2L@
+_GL_FUNCDECL_SYS (log2l, long double, (long double x));
+# endif
+_GL_CXXALIAS_SYS (log2l, long double, (long double x));
+# endif
+_GL_CXXALIASWARN (log2l);
+#elif defined GNULIB_POSIXCHECK
+# undef log2l
+# if HAVE_RAW_DECL_LOG2L
+_GL_WARN_ON_USE (log2l, "log2l is unportable - "
+ "use gnulib module log2l for portability");
+# endif
+#endif
+
+
+#if @GNULIB_LOGBF@
+# if @REPLACE_LOGBF@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef logbf
+# define logbf rpl_logbf
+# endif
+_GL_FUNCDECL_RPL (logbf, float, (float x));
+_GL_CXXALIAS_RPL (logbf, float, (float x));
+# else
+# if !@HAVE_LOGBF@
+_GL_FUNCDECL_SYS (logbf, float, (float x));
+# endif
+_GL_CXXALIAS_SYS (logbf, float, (float x));
+# endif
+_GL_CXXALIASWARN (logbf);
+#elif defined GNULIB_POSIXCHECK
+# undef logbf
+# if HAVE_RAW_DECL_LOGBF
+_GL_WARN_ON_USE (logbf, "logbf is unportable - "
+ "use gnulib module logbf for portability");
+# endif
+#endif
+
+#if @GNULIB_LOGB@
+# if @REPLACE_LOGB@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef logb
+# define logb rpl_logb
+# endif
+_GL_FUNCDECL_RPL (logb, double, (double x));
+_GL_CXXALIAS_RPL (logb, double, (double x));
+# else
+# if !@HAVE_DECL_LOGB@
+_GL_FUNCDECL_SYS (logb, double, (double x));
+# endif
+_GL_CXXALIAS_SYS (logb, double, (double x));
+# endif
+_GL_CXXALIASWARN (logb);
+#elif defined GNULIB_POSIXCHECK
+# undef logb
+# if HAVE_RAW_DECL_LOGB
+_GL_WARN_ON_USE (logb, "logb is unportable - "
+ "use gnulib module logb for portability");
+# endif
+#endif
+
+#if @GNULIB_LOGBL@
+# if @REPLACE_LOGBL@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef logbl
+# define logbl rpl_logbl
+# endif
+_GL_FUNCDECL_RPL (logbl, long double, (long double x));
+_GL_CXXALIAS_RPL (logbl, long double, (long double x));
+# else
+# if !@HAVE_LOGBL@
+_GL_FUNCDECL_SYS (logbl, long double, (long double x));
+# endif
+_GL_CXXALIAS_SYS (logbl, long double, (long double x));
+# endif
+_GL_CXXALIASWARN (logbl);
+#elif defined GNULIB_POSIXCHECK
+# undef logbl
+# if HAVE_RAW_DECL_LOGBL
+_GL_WARN_ON_USE (logbl, "logbl is unportable - "
+ "use gnulib module logbl for portability");
+# endif
+#endif
+
+
+#if @GNULIB_MODFF@
+# if @REPLACE_MODFF@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef modff
+# define modff rpl_modff
+# endif
+_GL_FUNCDECL_RPL (modff, float, (float x, float *iptr) _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_RPL (modff, float, (float x, float *iptr));
+# else
+# if !@HAVE_MODFF@
+# undef modff
+_GL_FUNCDECL_SYS (modff, float, (float x, float *iptr) _GL_ARG_NONNULL ((2)));
+# endif
+_GL_CXXALIAS_SYS (modff, float, (float x, float *iptr));
+# endif
+_GL_CXXALIASWARN (modff);
+#elif defined GNULIB_POSIXCHECK
+# undef modff
+# if HAVE_RAW_DECL_MODFF
+_GL_WARN_ON_USE (modff, "modff is unportable - "
+ "use gnulib module modff for portability");
+# endif
+#endif
+
+#if @GNULIB_MODF@
+# if @REPLACE_MODF@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef modf
+# define modf rpl_modf
+# endif
+_GL_FUNCDECL_RPL (modf, double, (double x, double *iptr) _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_RPL (modf, double, (double x, double *iptr));
+# else
+_GL_CXXALIAS_SYS (modf, double, (double x, double *iptr));
+# endif
+_GL_CXXALIASWARN (modf);
+#elif defined GNULIB_POSIXCHECK
+# undef modf
+# if HAVE_RAW_DECL_MODF
+_GL_WARN_ON_USE (modf, "modf has portability problems - "
+ "use gnulib module modf for portability");
+# endif
+#endif
+
+#if @GNULIB_MODFL@
+# if @REPLACE_MODFL@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef modfl
+# define modfl rpl_modfl
+# endif
+_GL_FUNCDECL_RPL (modfl, long double, (long double x, long double *iptr)
+ _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_RPL (modfl, long double, (long double x, long double *iptr));
+# else
+# if !@HAVE_MODFL@
+# undef modfl
+_GL_FUNCDECL_SYS (modfl, long double, (long double x, long double *iptr)
+ _GL_ARG_NONNULL ((2)));
+# endif
+_GL_CXXALIAS_SYS (modfl, long double, (long double x, long double *iptr));
+# endif
+_GL_CXXALIASWARN (modfl);
+#elif defined GNULIB_POSIXCHECK
+# undef modfl
+# if HAVE_RAW_DECL_MODFL
+_GL_WARN_ON_USE (modfl, "modfl is unportable - "
+ "use gnulib module modfl for portability");
+# endif
+#endif
+
+
+#if @GNULIB_POWF@
+# if !@HAVE_POWF@
+# undef powf
+_GL_FUNCDECL_SYS (powf, float, (float x, float y));
+# endif
+_GL_CXXALIAS_SYS (powf, float, (float x, float y));
+_GL_CXXALIASWARN (powf);
+#elif defined GNULIB_POSIXCHECK
+# undef powf
+# if HAVE_RAW_DECL_POWF
+_GL_WARN_ON_USE (powf, "powf is unportable - "
+ "use gnulib module powf for portability");
+# endif
+#endif
+
+
+#if @GNULIB_REMAINDERF@
+# if @REPLACE_REMAINDERF@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef remainderf
+# define remainderf rpl_remainderf
+# endif
+_GL_FUNCDECL_RPL (remainderf, float, (float x, float y));
+_GL_CXXALIAS_RPL (remainderf, float, (float x, float y));
+# else
+# if !@HAVE_REMAINDERF@
+_GL_FUNCDECL_SYS (remainderf, float, (float x, float y));
+# endif
+_GL_CXXALIAS_SYS (remainderf, float, (float x, float y));
+# endif
+_GL_CXXALIASWARN (remainderf);
+#elif defined GNULIB_POSIXCHECK
+# undef remainderf
+# if HAVE_RAW_DECL_REMAINDERF
+_GL_WARN_ON_USE (remainderf, "remainderf is unportable - "
+ "use gnulib module remainderf for portability");
+# endif
+#endif
+
+#if @GNULIB_REMAINDER@
+# if @REPLACE_REMAINDER@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef remainder
+# define remainder rpl_remainder
+# endif
+_GL_FUNCDECL_RPL (remainder, double, (double x, double y));
+_GL_CXXALIAS_RPL (remainder, double, (double x, double y));
+# else
+# if !@HAVE_REMAINDER@ || !@HAVE_DECL_REMAINDER@
+_GL_FUNCDECL_SYS (remainder, double, (double x, double y));
+# endif
+_GL_CXXALIAS_SYS (remainder, double, (double x, double y));
+# endif
+_GL_CXXALIASWARN (remainder);
+#elif defined GNULIB_POSIXCHECK
+# undef remainder
+# if HAVE_RAW_DECL_REMAINDER
+_GL_WARN_ON_USE (remainder, "remainder is unportable - "
+ "use gnulib module remainder for portability");
+# endif
+#endif
+
+#if @GNULIB_REMAINDERL@
+# if @REPLACE_REMAINDERL@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef remainderl
+# define remainderl rpl_remainderl
+# endif
+_GL_FUNCDECL_RPL (remainderl, long double, (long double x, long double y));
+_GL_CXXALIAS_RPL (remainderl, long double, (long double x, long double y));
+# else
+# if !@HAVE_DECL_REMAINDERL@
+# undef remainderl
+_GL_FUNCDECL_SYS (remainderl, long double, (long double x, long double y));
+# endif
+_GL_CXXALIAS_SYS (remainderl, long double, (long double x, long double y));
+# endif
+_GL_CXXALIASWARN (remainderl);
+#elif defined GNULIB_POSIXCHECK
+# undef remainderl
+# if HAVE_RAW_DECL_REMAINDERL
+_GL_WARN_ON_USE (remainderl, "remainderl is unportable - "
+ "use gnulib module remainderl for portability");
+# endif
+#endif
+
+
+#if @GNULIB_RINTF@
+# if !@HAVE_DECL_RINTF@
+_GL_FUNCDECL_SYS (rintf, float, (float x));
+# endif
+_GL_CXXALIAS_SYS (rintf, float, (float x));
+_GL_CXXALIASWARN (rintf);
+#elif defined GNULIB_POSIXCHECK
+# undef rintf
+# if HAVE_RAW_DECL_RINTF
+_GL_WARN_ON_USE (rintf, "rintf is unportable - "
+ "use gnulib module rintf for portability");
+# endif
+#endif
+
+#if @GNULIB_RINT@
+# if !@HAVE_RINT@
+_GL_FUNCDECL_SYS (rint, double, (double x));
+# endif
+_GL_CXXALIAS_SYS (rint, double, (double x));
+_GL_CXXALIASWARN (rint);
+#elif defined GNULIB_POSIXCHECK
+# undef rint
+# if HAVE_RAW_DECL_RINT
+_GL_WARN_ON_USE (rint, "rint is unportable - "
+ "use gnulib module rint for portability");
+# endif
+#endif
+
+#if @GNULIB_RINTL@
+# if !@HAVE_RINTL@
+_GL_FUNCDECL_SYS (rintl, long double, (long double x));
+# endif
+_GL_CXXALIAS_SYS (rintl, long double, (long double x));
+_GL_CXXALIASWARN (rintl);
+#elif defined GNULIB_POSIXCHECK
+# undef rintl
+# if HAVE_RAW_DECL_RINTL
+_GL_WARN_ON_USE (rintl, "rintl is unportable - "
+ "use gnulib module rintl for portability");
+# endif
+#endif
+
+
+#if @GNULIB_ROUNDF@
+# if @REPLACE_ROUNDF@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef roundf
+# define roundf rpl_roundf
+# endif
+_GL_FUNCDECL_RPL (roundf, float, (float x));
+_GL_CXXALIAS_RPL (roundf, float, (float x));
+# else
+# if !@HAVE_DECL_ROUNDF@
+_GL_FUNCDECL_SYS (roundf, float, (float x));
+# endif
+_GL_CXXALIAS_SYS (roundf, float, (float x));
+# endif
+_GL_CXXALIASWARN (roundf);
+#elif defined GNULIB_POSIXCHECK
+# undef roundf
+# if HAVE_RAW_DECL_ROUNDF
+_GL_WARN_ON_USE (roundf, "roundf is unportable - "
+ "use gnulib module roundf for portability");
+# endif
+#endif
+
+#if @GNULIB_ROUND@
+# if @REPLACE_ROUND@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef round
+# define round rpl_round
+# endif
+_GL_FUNCDECL_RPL (round, double, (double x));
+_GL_CXXALIAS_RPL (round, double, (double x));
+# else
+# if !@HAVE_DECL_ROUND@
+_GL_FUNCDECL_SYS (round, double, (double x));
+# endif
+_GL_CXXALIAS_SYS (round, double, (double x));
+# endif
+_GL_CXXALIASWARN (round);
+#elif defined GNULIB_POSIXCHECK
+# undef round
+# if HAVE_RAW_DECL_ROUND
+_GL_WARN_ON_USE (round, "round is unportable - "
+ "use gnulib module round for portability");
+# endif
+#endif
+
+#if @GNULIB_ROUNDL@
+# if @REPLACE_ROUNDL@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef roundl
+# define roundl rpl_roundl
+# endif
+_GL_FUNCDECL_RPL (roundl, long double, (long double x));
+_GL_CXXALIAS_RPL (roundl, long double, (long double x));
+# else
+# if !@HAVE_DECL_ROUNDL@
+# undef roundl
+_GL_FUNCDECL_SYS (roundl, long double, (long double x));
+# endif
+_GL_CXXALIAS_SYS (roundl, long double, (long double x));
+# endif
+_GL_CXXALIASWARN (roundl);
+#elif defined GNULIB_POSIXCHECK
+# undef roundl
+# if HAVE_RAW_DECL_ROUNDL
+_GL_WARN_ON_USE (roundl, "roundl is unportable - "
+ "use gnulib module roundl for portability");
+# endif
+#endif
+
+
+#if @GNULIB_SINF@
+# if !@HAVE_SINF@
+# undef sinf
+_GL_FUNCDECL_SYS (sinf, float, (float x));
+# endif
+_GL_CXXALIAS_SYS (sinf, float, (float x));
+_GL_CXXALIASWARN (sinf);
+#elif defined GNULIB_POSIXCHECK
+# undef sinf
+# if HAVE_RAW_DECL_SINF
+_GL_WARN_ON_USE (sinf, "sinf is unportable - "
+ "use gnulib module sinf for portability");
+# endif
+#endif
+
+#if @GNULIB_SINL@
+# if !@HAVE_SINL@ || !@HAVE_DECL_SINL@
+# undef sinl
+_GL_FUNCDECL_SYS (sinl, long double, (long double x));
+# endif
+_GL_CXXALIAS_SYS (sinl, long double, (long double x));
+_GL_CXXALIASWARN (sinl);
+#elif defined GNULIB_POSIXCHECK
+# undef sinl
+# if HAVE_RAW_DECL_SINL
+_GL_WARN_ON_USE (sinl, "sinl is unportable - "
+ "use gnulib module sinl for portability");
+# endif
+#endif
+
+
+#if @GNULIB_SINHF@
+# if !@HAVE_SINHF@
+# undef sinhf
+_GL_FUNCDECL_SYS (sinhf, float, (float x));
+# endif
+_GL_CXXALIAS_SYS (sinhf, float, (float x));
+_GL_CXXALIASWARN (sinhf);
+#elif defined GNULIB_POSIXCHECK
+# undef sinhf
+# if HAVE_RAW_DECL_SINHF
+_GL_WARN_ON_USE (sinhf, "sinhf is unportable - "
+ "use gnulib module sinhf for portability");
+# endif
+#endif
+
+
+#if @GNULIB_SQRTF@
+# if !@HAVE_SQRTF@
+# undef sqrtf
+_GL_FUNCDECL_SYS (sqrtf, float, (float x));
+# endif
+_GL_CXXALIAS_SYS (sqrtf, float, (float x));
+_GL_CXXALIASWARN (sqrtf);
+#elif defined GNULIB_POSIXCHECK
+# undef sqrtf
+# if HAVE_RAW_DECL_SQRTF
+_GL_WARN_ON_USE (sqrtf, "sqrtf is unportable - "
+ "use gnulib module sqrtf for portability");
+# endif
+#endif
+
+#if @GNULIB_SQRTL@
+# if @REPLACE_SQRTL@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef sqrtl
+# define sqrtl rpl_sqrtl
+# endif
+_GL_FUNCDECL_RPL (sqrtl, long double, (long double x));
+_GL_CXXALIAS_RPL (sqrtl, long double, (long double x));
+# else
+# if !@HAVE_SQRTL@ || !@HAVE_DECL_SQRTL@
+# undef sqrtl
+_GL_FUNCDECL_SYS (sqrtl, long double, (long double x));
+# endif
+_GL_CXXALIAS_SYS (sqrtl, long double, (long double x));
+# endif
+_GL_CXXALIASWARN (sqrtl);
+#elif defined GNULIB_POSIXCHECK
+# undef sqrtl
+# if HAVE_RAW_DECL_SQRTL
+_GL_WARN_ON_USE (sqrtl, "sqrtl is unportable - "
+ "use gnulib module sqrtl for portability");
+# endif
+#endif
+
+
+#if @GNULIB_TANF@
+# if !@HAVE_TANF@
+# undef tanf
+_GL_FUNCDECL_SYS (tanf, float, (float x));
+# endif
+_GL_CXXALIAS_SYS (tanf, float, (float x));
+_GL_CXXALIASWARN (tanf);
+#elif defined GNULIB_POSIXCHECK
+# undef tanf
+# if HAVE_RAW_DECL_TANF
+_GL_WARN_ON_USE (tanf, "tanf is unportable - "
+ "use gnulib module tanf for portability");
+# endif
+#endif
+
+#if @GNULIB_TANL@
+# if !@HAVE_TANL@ || !@HAVE_DECL_TANL@
+# undef tanl
+_GL_FUNCDECL_SYS (tanl, long double, (long double x));
+# endif
+_GL_CXXALIAS_SYS (tanl, long double, (long double x));
+_GL_CXXALIASWARN (tanl);
+#elif defined GNULIB_POSIXCHECK
+# undef tanl
+# if HAVE_RAW_DECL_TANL
+_GL_WARN_ON_USE (tanl, "tanl is unportable - "
+ "use gnulib module tanl for portability");
+# endif
+#endif
+
+
+#if @GNULIB_TANHF@
+# if !@HAVE_TANHF@
+# undef tanhf
+_GL_FUNCDECL_SYS (tanhf, float, (float x));
+# endif
+_GL_CXXALIAS_SYS (tanhf, float, (float x));
+_GL_CXXALIASWARN (tanhf);
+#elif defined GNULIB_POSIXCHECK
+# undef tanhf
+# if HAVE_RAW_DECL_TANHF
+_GL_WARN_ON_USE (tanhf, "tanhf is unportable - "
+ "use gnulib module tanhf for portability");
+# endif
+#endif
+
+
+#if @GNULIB_TRUNCF@
+# if @REPLACE_TRUNCF@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define truncf rpl_truncf
+# endif
+_GL_FUNCDECL_RPL (truncf, float, (float x));
+_GL_CXXALIAS_RPL (truncf, float, (float x));
+# else
+# if !@HAVE_DECL_TRUNCF@
+_GL_FUNCDECL_SYS (truncf, float, (float x));
+# endif
+_GL_CXXALIAS_SYS (truncf, float, (float x));
+# endif
+_GL_CXXALIASWARN (truncf);
+#elif defined GNULIB_POSIXCHECK
+# undef truncf
+# if HAVE_RAW_DECL_TRUNCF
+_GL_WARN_ON_USE (truncf, "truncf is unportable - "
+ "use gnulib module truncf for portability");
+# endif
+#endif
+
+#if @GNULIB_TRUNC@
+# if @REPLACE_TRUNC@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define trunc rpl_trunc
+# endif
+_GL_FUNCDECL_RPL (trunc, double, (double x));
+_GL_CXXALIAS_RPL (trunc, double, (double x));
+# else
+# if !@HAVE_DECL_TRUNC@
+_GL_FUNCDECL_SYS (trunc, double, (double x));
+# endif
+_GL_CXXALIAS_SYS (trunc, double, (double x));
+# endif
+_GL_CXXALIASWARN (trunc);
+#elif defined GNULIB_POSIXCHECK
+# undef trunc
+# if HAVE_RAW_DECL_TRUNC
+_GL_WARN_ON_USE (trunc, "trunc is unportable - "
+ "use gnulib module trunc for portability");
+# endif
+#endif
+
+#if @GNULIB_TRUNCL@
+# if @REPLACE_TRUNCL@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef truncl
+# define truncl rpl_truncl
+# endif
+_GL_FUNCDECL_RPL (truncl, long double, (long double x));
+_GL_CXXALIAS_RPL (truncl, long double, (long double x));
+# else
+# if !@HAVE_DECL_TRUNCL@
+_GL_FUNCDECL_SYS (truncl, long double, (long double x));
+# endif
+_GL_CXXALIAS_SYS (truncl, long double, (long double x));
+# endif
+_GL_CXXALIASWARN (truncl);
+#elif defined GNULIB_POSIXCHECK
+# undef truncl
+# if HAVE_RAW_DECL_TRUNCL
+_GL_WARN_ON_USE (truncl, "truncl is unportable - "
+ "use gnulib module truncl for portability");
+# endif
+#endif
+
+
+/* Definitions of function-like macros come here, after the function
+ declarations. */
+
+
+#if @GNULIB_ISFINITE@
+# if @REPLACE_ISFINITE@
+_GL_EXTERN_C int gl_isfinitef (float x);
+_GL_EXTERN_C int gl_isfinited (double x);
+_GL_EXTERN_C int gl_isfinitel (long double x);
+# undef isfinite
+# define isfinite(x) \
+ (sizeof (x) == sizeof (long double) ? gl_isfinitel (x) : \
+ sizeof (x) == sizeof (double) ? gl_isfinited (x) : \
+ gl_isfinitef (x))
+# endif
+# ifdef __cplusplus
+# ifdef isfinite
+_GL_MATH_CXX_REAL_FLOATING_DECL_1 (isfinite)
+# undef isfinite
+_GL_MATH_CXX_REAL_FLOATING_DECL_2 (isfinite)
+# endif
+# endif
+#elif defined GNULIB_POSIXCHECK
+# if defined isfinite
+_GL_WARN_REAL_FLOATING_DECL (isfinite);
+# undef isfinite
+# define isfinite(x) _GL_WARN_REAL_FLOATING_IMPL (isfinite, x)
+# endif
+#endif
+
+
+#if @GNULIB_ISINF@
+# if @REPLACE_ISINF@
+_GL_EXTERN_C int gl_isinff (float x);
+_GL_EXTERN_C int gl_isinfd (double x);
+_GL_EXTERN_C int gl_isinfl (long double x);
+# undef isinf
+# define isinf(x) \
+ (sizeof (x) == sizeof (long double) ? gl_isinfl (x) : \
+ sizeof (x) == sizeof (double) ? gl_isinfd (x) : \
+ gl_isinff (x))
+# endif
+# ifdef __cplusplus
+# ifdef isinf
+_GL_MATH_CXX_REAL_FLOATING_DECL_1 (isinf)
+# undef isinf
+_GL_MATH_CXX_REAL_FLOATING_DECL_2 (isinf)
+# endif
+# endif
+#elif defined GNULIB_POSIXCHECK
+# if defined isinf
+_GL_WARN_REAL_FLOATING_DECL (isinf);
+# undef isinf
+# define isinf(x) _GL_WARN_REAL_FLOATING_IMPL (isinf, x)
+# endif
+#endif
+
+
+#if @GNULIB_ISNANF@
+/* Test for NaN for 'float' numbers. */
+# if @HAVE_ISNANF@
+/* The original <math.h> included above provides a declaration of isnan macro
+ or (older) isnanf function. */
+# if __GNUC__ >= 4
+ /* GCC 4.0 and newer provides three built-ins for isnan. */
+# undef isnanf
+# define isnanf(x) __builtin_isnanf ((float)(x))
+# elif defined isnan
+# undef isnanf
+# define isnanf(x) isnan ((float)(x))
+# endif
+# else
+/* Test whether X is a NaN. */
+# undef isnanf
+# define isnanf rpl_isnanf
+_GL_EXTERN_C int isnanf (float x);
+# endif
+#endif
+
+#if @GNULIB_ISNAND@
+/* Test for NaN for 'double' numbers.
+ This function is a gnulib extension, unlike isnan() which applied only
+ to 'double' numbers earlier but now is a type-generic macro. */
+# if @HAVE_ISNAND@
+/* The original <math.h> included above provides a declaration of isnan
+ macro. */
+# if __GNUC__ >= 4
+ /* GCC 4.0 and newer provides three built-ins for isnan. */
+# undef isnand
+# define isnand(x) __builtin_isnan ((double)(x))
+# else
+# undef isnand
+# define isnand(x) isnan ((double)(x))
+# endif
+# else
+/* Test whether X is a NaN. */
+# undef isnand
+# define isnand rpl_isnand
+_GL_EXTERN_C int isnand (double x);
+# endif
+#endif
+
+#if @GNULIB_ISNANL@
+/* Test for NaN for 'long double' numbers. */
+# if @HAVE_ISNANL@
+/* The original <math.h> included above provides a declaration of isnan
+ macro or (older) isnanl function. */
+# if __GNUC__ >= 4
+ /* GCC 4.0 and newer provides three built-ins for isnan. */
+# undef isnanl
+# define isnanl(x) __builtin_isnanl ((long double)(x))
+# elif defined isnan
+# undef isnanl
+# define isnanl(x) isnan ((long double)(x))
+# endif
+# else
+/* Test whether X is a NaN. */
+# undef isnanl
+# define isnanl rpl_isnanl
+_GL_EXTERN_C int isnanl (long double x) _GL_ATTRIBUTE_CONST;
+# endif
+#endif
+
+/* This must come *after* the snippets for GNULIB_ISNANF and GNULIB_ISNANL! */
+#if @GNULIB_ISNAN@
+# if @REPLACE_ISNAN@
+/* We can't just use the isnanf macro (e.g.) as exposed by
+ isnanf.h (e.g.) here, because those may end up being macros
+ that recursively expand back to isnan. So use the gnulib
+ replacements for them directly. */
+# if @HAVE_ISNANF@ && __GNUC__ >= 4
+# define gl_isnan_f(x) __builtin_isnanf ((float)(x))
+# else
+_GL_EXTERN_C int rpl_isnanf (float x);
+# define gl_isnan_f(x) rpl_isnanf (x)
+# endif
+# if @HAVE_ISNAND@ && __GNUC__ >= 4
+# define gl_isnan_d(x) __builtin_isnan ((double)(x))
+# else
+_GL_EXTERN_C int rpl_isnand (double x);
+# define gl_isnan_d(x) rpl_isnand (x)
+# endif
+# if @HAVE_ISNANL@ && __GNUC__ >= 4
+# define gl_isnan_l(x) __builtin_isnanl ((long double)(x))
+# else
+_GL_EXTERN_C int rpl_isnanl (long double x) _GL_ATTRIBUTE_CONST;
+# define gl_isnan_l(x) rpl_isnanl (x)
+# endif
+# undef isnan
+# define isnan(x) \
+ (sizeof (x) == sizeof (long double) ? gl_isnan_l (x) : \
+ sizeof (x) == sizeof (double) ? gl_isnan_d (x) : \
+ gl_isnan_f (x))
+# elif __GNUC__ >= 4
+# undef isnan
+# define isnan(x) \
+ (sizeof (x) == sizeof (long double) ? __builtin_isnanl ((long double)(x)) : \
+ sizeof (x) == sizeof (double) ? __builtin_isnan ((double)(x)) : \
+ __builtin_isnanf ((float)(x)))
+# endif
+# ifdef __cplusplus
+# ifdef isnan
+_GL_MATH_CXX_REAL_FLOATING_DECL_1 (isnan)
+# undef isnan
+_GL_MATH_CXX_REAL_FLOATING_DECL_2 (isnan)
+# endif
+# else
+/* Ensure isnan is a macro. */
+# ifndef isnan
+# define isnan isnan
+# endif
+# endif
+#elif defined GNULIB_POSIXCHECK
+# if defined isnan
+_GL_WARN_REAL_FLOATING_DECL (isnan);
+# undef isnan
+# define isnan(x) _GL_WARN_REAL_FLOATING_IMPL (isnan, x)
+# endif
+#endif
+
+
+#if @GNULIB_SIGNBIT@
+# if @REPLACE_SIGNBIT_USING_GCC@
+# undef signbit
+ /* GCC 4.0 and newer provides three built-ins for signbit. */
+# define signbit(x) \
+ (sizeof (x) == sizeof (long double) ? __builtin_signbitl (x) : \
+ sizeof (x) == sizeof (double) ? __builtin_signbit (x) : \
+ __builtin_signbitf (x))
+# endif
+# if @REPLACE_SIGNBIT@
+# undef signbit
+_GL_EXTERN_C int gl_signbitf (float arg);
+_GL_EXTERN_C int gl_signbitd (double arg);
+_GL_EXTERN_C int gl_signbitl (long double arg);
+# if __GNUC__ >= 2 && !defined __STRICT_ANSI__
+# define _GL_NUM_UINT_WORDS(type) \
+ ((sizeof (type) + sizeof (unsigned int) - 1) / sizeof (unsigned int))
+# if defined FLT_SIGNBIT_WORD && defined FLT_SIGNBIT_BIT && !defined gl_signbitf
+# define gl_signbitf_OPTIMIZED_MACRO
+# define gl_signbitf(arg) \
+ ({ union { float _value; \
+ unsigned int _word[_GL_NUM_UINT_WORDS (float)]; \
+ } _m; \
+ _m._value = (arg); \
+ (_m._word[FLT_SIGNBIT_WORD] >> FLT_SIGNBIT_BIT) & 1; \
+ })
+# endif
+# if defined DBL_SIGNBIT_WORD && defined DBL_SIGNBIT_BIT && !defined gl_signbitd
+# define gl_signbitd_OPTIMIZED_MACRO
+# define gl_signbitd(arg) \
+ ({ union { double _value; \
+ unsigned int _word[_GL_NUM_UINT_WORDS (double)]; \
+ } _m; \
+ _m._value = (arg); \
+ (_m._word[DBL_SIGNBIT_WORD] >> DBL_SIGNBIT_BIT) & 1; \
+ })
+# endif
+# if defined LDBL_SIGNBIT_WORD && defined LDBL_SIGNBIT_BIT && !defined gl_signbitl
+# define gl_signbitl_OPTIMIZED_MACRO
+# define gl_signbitl(arg) \
+ ({ union { long double _value; \
+ unsigned int _word[_GL_NUM_UINT_WORDS (long double)]; \
+ } _m; \
+ _m._value = (arg); \
+ (_m._word[LDBL_SIGNBIT_WORD] >> LDBL_SIGNBIT_BIT) & 1; \
+ })
+# endif
+# endif
+# define signbit(x) \
+ (sizeof (x) == sizeof (long double) ? gl_signbitl (x) : \
+ sizeof (x) == sizeof (double) ? gl_signbitd (x) : \
+ gl_signbitf (x))
+# endif
+# ifdef __cplusplus
+# ifdef signbit
+_GL_MATH_CXX_REAL_FLOATING_DECL_1 (signbit)
+# undef signbit
+_GL_MATH_CXX_REAL_FLOATING_DECL_2 (signbit)
+# endif
+# endif
+#elif defined GNULIB_POSIXCHECK
+# if defined signbit
+_GL_WARN_REAL_FLOATING_DECL (signbit);
+# undef signbit
+# define signbit(x) _GL_WARN_REAL_FLOATING_IMPL (signbit, x)
+# endif
+#endif
+
+_GL_INLINE_HEADER_END
+
+#endif /* _@GUARD_PREFIX@_MATH_H */
+#endif /* _@GUARD_PREFIX@_MATH_H */
diff --git a/lib/mbchar.c b/lib/mbchar.c
index 95373f5..27796c3 100644
--- a/lib/mbchar.c
+++ b/lib/mbchar.c
@@ -1,9 +1,9 @@
-/* Copyright (C) 2001, 2006 Free Software Foundation, Inc.
+/* Copyright (C) 2001, 2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -11,12 +11,13 @@
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, write to the Free Software Foundation,
- Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
+#define MBCHAR_INLINE _GL_EXTERN_INLINE
+
#include <limits.h>
#include "mbchar.h"
@@ -26,10 +27,10 @@
/* Bit table of characters in the ISO C "basic character set". */
const unsigned int is_basic_table [UCHAR_MAX / 32 + 1] =
{
- 0x00001a00, /* '\t' '\v' '\f' */
- 0xffffffef, /* ' '...'#' '%'...'?' */
- 0xfffffffe, /* 'A'...'Z' '[' '\\' ']' '^' '_' */
- 0x7ffffffe /* 'a'...'z' '{' '|' '}' '~' */
+ 0x00001a00, /* '\t' '\v' '\f' */
+ 0xffffffef, /* ' '...'#' '%'...'?' */
+ 0xfffffffe, /* 'A'...'Z' '[' '\\' ']' '^' '_' */
+ 0x7ffffffe /* 'a'...'z' '{' '|' '}' '~' */
/* The remaining bits are 0. */
};
diff --git a/lib/mbchar.h b/lib/mbchar.h
index f3e28ef..2017d86 100644
--- a/lib/mbchar.h
+++ b/lib/mbchar.h
@@ -1,10 +1,10 @@
/* Multibyte character data type.
- Copyright (C) 2001, 2005-2006 Free Software Foundation, Inc.
+ Copyright (C) 2001, 2005-2007, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -12,8 +12,7 @@
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, write to the Free Software Foundation,
- Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Bruno Haible <bruno@clisp.org>. */
@@ -115,31 +114,31 @@
Here are the function prototypes of the macros.
- extern const char * mb_ptr (const mbchar_t mbc);
- extern size_t mb_len (const mbchar_t mbc);
- extern bool mb_iseq (const mbchar_t mbc, char sc);
- extern bool mb_isnul (const mbchar_t mbc);
- extern int mb_cmp (const mbchar_t mbc1, const mbchar_t mbc2);
- extern int mb_casecmp (const mbchar_t mbc1, const mbchar_t mbc2);
- extern bool mb_equal (const mbchar_t mbc1, const mbchar_t mbc2);
- extern bool mb_caseequal (const mbchar_t mbc1, const mbchar_t mbc2);
- extern bool mb_isalnum (const mbchar_t mbc);
- extern bool mb_isalpha (const mbchar_t mbc);
- extern bool mb_isascii (const mbchar_t mbc);
- extern bool mb_isblank (const mbchar_t mbc);
- extern bool mb_iscntrl (const mbchar_t mbc);
- extern bool mb_isdigit (const mbchar_t mbc);
- extern bool mb_isgraph (const mbchar_t mbc);
- extern bool mb_islower (const mbchar_t mbc);
- extern bool mb_isprint (const mbchar_t mbc);
- extern bool mb_ispunct (const mbchar_t mbc);
- extern bool mb_isspace (const mbchar_t mbc);
- extern bool mb_isupper (const mbchar_t mbc);
- extern bool mb_isxdigit (const mbchar_t mbc);
- extern int mb_width (const mbchar_t mbc);
- extern void mb_putc (const mbchar_t mbc, FILE *stream);
+ extern const char * mb_ptr (const mbchar_t mbc);
+ extern size_t mb_len (const mbchar_t mbc);
+ extern bool mb_iseq (const mbchar_t mbc, char sc);
+ extern bool mb_isnul (const mbchar_t mbc);
+ extern int mb_cmp (const mbchar_t mbc1, const mbchar_t mbc2);
+ extern int mb_casecmp (const mbchar_t mbc1, const mbchar_t mbc2);
+ extern bool mb_equal (const mbchar_t mbc1, const mbchar_t mbc2);
+ extern bool mb_caseequal (const mbchar_t mbc1, const mbchar_t mbc2);
+ extern bool mb_isalnum (const mbchar_t mbc);
+ extern bool mb_isalpha (const mbchar_t mbc);
+ extern bool mb_isascii (const mbchar_t mbc);
+ extern bool mb_isblank (const mbchar_t mbc);
+ extern bool mb_iscntrl (const mbchar_t mbc);
+ extern bool mb_isdigit (const mbchar_t mbc);
+ extern bool mb_isgraph (const mbchar_t mbc);
+ extern bool mb_islower (const mbchar_t mbc);
+ extern bool mb_isprint (const mbchar_t mbc);
+ extern bool mb_ispunct (const mbchar_t mbc);
+ extern bool mb_isspace (const mbchar_t mbc);
+ extern bool mb_isupper (const mbchar_t mbc);
+ extern bool mb_isxdigit (const mbchar_t mbc);
+ extern int mb_width (const mbchar_t mbc);
+ extern void mb_putc (const mbchar_t mbc, FILE *stream);
extern void mb_setascii (mbchar_t *new, char sc);
- extern void mb_copy (mbchar_t *new, const mbchar_t *old);
+ extern void mb_copy (mbchar_t *new, const mbchar_t *old);
*/
#ifndef _MBCHAR_H
@@ -157,16 +156,22 @@
#include <wchar.h>
#include <wctype.h>
-#include "wcwidth.h"
+#ifndef _GL_INLINE_HEADER_BEGIN
+ #error "Please include config.h first."
+#endif
+_GL_INLINE_HEADER_BEGIN
+#ifndef MBCHAR_INLINE
+# define MBCHAR_INLINE _GL_INLINE
+#endif
#define MBCHAR_BUF_SIZE 24
struct mbchar
{
- const char *ptr; /* pointer to current character */
- size_t bytes; /* number of bytes of current character, > 0 */
- bool wc_valid; /* true if wc is a valid wide character */
- wchar_t wc; /* if wc_valid: the current character */
+ const char *ptr; /* pointer to current character */
+ size_t bytes; /* number of bytes of current character, > 0 */
+ bool wc_valid; /* true if wc is a valid wide character */
+ wchar_t wc; /* if wc_valid: the current character */
char buf[MBCHAR_BUF_SIZE]; /* room for the bytes, used for file input only */
};
@@ -183,38 +188,38 @@ typedef struct mbchar mbchar_t;
#define mb_iseq(mbc, sc) ((mbc).wc_valid && (mbc).wc == (sc))
#define mb_isnul(mbc) ((mbc).wc_valid && (mbc).wc == 0)
#define mb_cmp(mbc1, mbc2) \
- ((mbc1).wc_valid \
- ? ((mbc2).wc_valid \
- ? (int) (mbc1).wc - (int) (mbc2).wc \
- : -1) \
- : ((mbc2).wc_valid \
- ? 1 \
- : (mbc1).bytes == (mbc2).bytes \
- ? memcmp ((mbc1).ptr, (mbc2).ptr, (mbc1).bytes) \
- : (mbc1).bytes < (mbc2).bytes \
+ ((mbc1).wc_valid \
+ ? ((mbc2).wc_valid \
+ ? (int) (mbc1).wc - (int) (mbc2).wc \
+ : -1) \
+ : ((mbc2).wc_valid \
+ ? 1 \
+ : (mbc1).bytes == (mbc2).bytes \
+ ? memcmp ((mbc1).ptr, (mbc2).ptr, (mbc1).bytes) \
+ : (mbc1).bytes < (mbc2).bytes \
? (memcmp ((mbc1).ptr, (mbc2).ptr, (mbc1).bytes) > 0 ? 1 : -1) \
: (memcmp ((mbc1).ptr, (mbc2).ptr, (mbc2).bytes) >= 0 ? 1 : -1)))
#define mb_casecmp(mbc1, mbc2) \
- ((mbc1).wc_valid \
- ? ((mbc2).wc_valid \
- ? (int) towlower ((mbc1).wc) - (int) towlower ((mbc2).wc) \
- : -1) \
- : ((mbc2).wc_valid \
- ? 1 \
- : (mbc1).bytes == (mbc2).bytes \
- ? memcmp ((mbc1).ptr, (mbc2).ptr, (mbc1).bytes) \
- : (mbc1).bytes < (mbc2).bytes \
+ ((mbc1).wc_valid \
+ ? ((mbc2).wc_valid \
+ ? (int) towlower ((mbc1).wc) - (int) towlower ((mbc2).wc) \
+ : -1) \
+ : ((mbc2).wc_valid \
+ ? 1 \
+ : (mbc1).bytes == (mbc2).bytes \
+ ? memcmp ((mbc1).ptr, (mbc2).ptr, (mbc1).bytes) \
+ : (mbc1).bytes < (mbc2).bytes \
? (memcmp ((mbc1).ptr, (mbc2).ptr, (mbc1).bytes) > 0 ? 1 : -1) \
: (memcmp ((mbc1).ptr, (mbc2).ptr, (mbc2).bytes) >= 0 ? 1 : -1)))
#define mb_equal(mbc1, mbc2) \
- ((mbc1).wc_valid && (mbc2).wc_valid \
- ? (mbc1).wc == (mbc2).wc \
- : (mbc1).bytes == (mbc2).bytes \
+ ((mbc1).wc_valid && (mbc2).wc_valid \
+ ? (mbc1).wc == (mbc2).wc \
+ : (mbc1).bytes == (mbc2).bytes \
&& memcmp ((mbc1).ptr, (mbc2).ptr, (mbc1).bytes) == 0)
#define mb_caseequal(mbc1, mbc2) \
- ((mbc1).wc_valid && (mbc2).wc_valid \
- ? towlower ((mbc1).wc) == towlower ((mbc2).wc) \
- : (mbc1).bytes == (mbc2).bytes \
+ ((mbc1).wc_valid && (mbc2).wc_valid \
+ ? towlower ((mbc1).wc) == towlower ((mbc2).wc) \
+ : (mbc1).bytes == (mbc2).bytes \
&& memcmp ((mbc1).ptr, (mbc2).ptr, (mbc1).bytes) == 0)
/* <ctype.h>, <wctype.h> classification. */
@@ -238,7 +243,7 @@ typedef struct mbchar mbchar_t;
/* Unprintable characters appear as a small box of width 1. */
#define MB_UNPRINTABLE_WIDTH 1
-static inline int
+MBCHAR_INLINE int
mb_width_aux (wint_t wc)
{
int w = wcwidth (wc);
@@ -259,7 +264,7 @@ mb_width_aux (wint_t wc)
(mbc)->wc = (mbc)->buf[0] = (sc))
/* Copying a character. */
-static inline void
+MBCHAR_INLINE void
mb_copy (mbchar_t *new_mbc, const mbchar_t *old_mbc)
{
if (old_mbc->ptr == &old_mbc->buf[0])
@@ -307,16 +312,16 @@ mb_copy (mbchar_t *new_mbc, const mbchar_t *old_mbc)
extern const unsigned int is_basic_table[];
-static inline bool
+MBCHAR_INLINE bool
is_basic (char c)
{
return (is_basic_table [(unsigned char) c >> 5] >> ((unsigned char) c & 31))
- & 1;
+ & 1;
}
#else
-static inline bool
+MBCHAR_INLINE bool
is_basic (char c)
{
switch (c)
@@ -350,4 +355,6 @@ is_basic (char c)
#endif
+_GL_INLINE_HEADER_END
+
#endif /* _MBCHAR_H */
diff --git a/lib/mbiter.c b/lib/mbiter.c
new file mode 100644
index 0000000..22a1ff8
--- /dev/null
+++ b/lib/mbiter.c
@@ -0,0 +1,3 @@
+#include <config.h>
+#define MBITER_INLINE _GL_EXTERN_INLINE
+#include "mbiter.h"
diff --git a/lib/mbiter.h b/lib/mbiter.h
new file mode 100644
index 0000000..d72b0a7
--- /dev/null
+++ b/lib/mbiter.h
@@ -0,0 +1,225 @@
+/* Iterating through multibyte strings: macros for multi-byte encodings.
+ Copyright (C) 2001, 2005, 2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Bruno Haible <bruno@clisp.org>. */
+
+/* The macros in this file implement forward iteration through a
+ multi-byte string.
+
+ With these macros, an iteration loop that looks like
+
+ char *iter;
+ for (iter = buf; iter < buf + buflen; iter++)
+ {
+ do_something (*iter);
+ }
+
+ becomes
+
+ mbi_iterator_t iter;
+ for (mbi_init (iter, buf, buflen); mbi_avail (iter); mbi_advance (iter))
+ {
+ do_something (mbi_cur_ptr (iter), mb_len (mbi_cur (iter)));
+ }
+
+ The benefit of these macros over plain use of mbrtowc is:
+ - Handling of invalid multibyte sequences is possible without
+ making the code more complicated, while still preserving the
+ invalid multibyte sequences.
+
+ mbi_iterator_t
+ is a type usable for variable declarations.
+
+ mbi_init (iter, startptr, length)
+ initializes the iterator, starting at startptr and crossing length bytes.
+
+ mbi_avail (iter)
+ returns true if there are more multibyte characters available before
+ the end of string is reached. In this case, mbi_cur (iter) is
+ initialized to the next multibyte character.
+
+ mbi_advance (iter)
+ advances the iterator by one multibyte character.
+
+ mbi_cur (iter)
+ returns the current multibyte character, of type mbchar_t. All the
+ macros defined in mbchar.h can be used on it.
+
+ mbi_cur_ptr (iter)
+ return a pointer to the beginning of the current multibyte character.
+
+ mbi_reloc (iter, ptrdiff)
+ relocates iterator when the string is moved by ptrdiff bytes.
+
+ mbi_copy (&destiter, &srciter)
+ copies srciter to destiter.
+
+ Here are the function prototypes of the macros.
+
+ extern void mbi_init (mbi_iterator_t iter,
+ const char *startptr, size_t length);
+ extern bool mbi_avail (mbi_iterator_t iter);
+ extern void mbi_advance (mbi_iterator_t iter);
+ extern mbchar_t mbi_cur (mbi_iterator_t iter);
+ extern const char * mbi_cur_ptr (mbi_iterator_t iter);
+ extern void mbi_reloc (mbi_iterator_t iter, ptrdiff_t ptrdiff);
+ extern void mbi_copy (mbi_iterator_t *new, const mbi_iterator_t *old);
+ */
+
+#ifndef _MBITER_H
+#define _MBITER_H 1
+
+#include <assert.h>
+#include <stdbool.h>
+#include <stddef.h>
+#include <string.h>
+
+/* Tru64 with Desktop Toolkit C has a bug: <stdio.h> must be included before
+ <wchar.h>.
+ BSD/OS 4.1 has a bug: <stdio.h> and <time.h> must be included before
+ <wchar.h>. */
+#include <stdio.h>
+#include <time.h>
+#include <wchar.h>
+
+#include "mbchar.h"
+
+#ifndef _GL_INLINE_HEADER_BEGIN
+ #error "Please include config.h first."
+#endif
+_GL_INLINE_HEADER_BEGIN
+#ifndef MBITER_INLINE
+# define MBITER_INLINE _GL_INLINE
+#endif
+
+struct mbiter_multi
+{
+ const char *limit; /* pointer to end of string */
+ bool in_shift; /* true if next byte may not be interpreted as ASCII */
+ mbstate_t state; /* if in_shift: current shift state */
+ bool next_done; /* true if mbi_avail has already filled the following */
+ struct mbchar cur; /* the current character:
+ const char *cur.ptr pointer to current character
+ The following are only valid after mbi_avail.
+ size_t cur.bytes number of bytes of current character
+ bool cur.wc_valid true if wc is a valid wide character
+ wchar_t cur.wc if wc_valid: the current character
+ */
+};
+
+MBITER_INLINE void
+mbiter_multi_next (struct mbiter_multi *iter)
+{
+ if (iter->next_done)
+ return;
+ if (iter->in_shift)
+ goto with_shift;
+ /* Handle most ASCII characters quickly, without calling mbrtowc(). */
+ if (is_basic (*iter->cur.ptr))
+ {
+ /* These characters are part of the basic character set. ISO C 99
+ guarantees that their wide character code is identical to their
+ char code. */
+ iter->cur.bytes = 1;
+ iter->cur.wc = *iter->cur.ptr;
+ iter->cur.wc_valid = true;
+ }
+ else
+ {
+ assert (mbsinit (&iter->state));
+ iter->in_shift = true;
+ with_shift:
+ iter->cur.bytes = mbrtowc (&iter->cur.wc, iter->cur.ptr,
+ iter->limit - iter->cur.ptr, &iter->state);
+ if (iter->cur.bytes == (size_t) -1)
+ {
+ /* An invalid multibyte sequence was encountered. */
+ iter->cur.bytes = 1;
+ iter->cur.wc_valid = false;
+ /* Whether to set iter->in_shift = false and reset iter->state
+ or not is not very important; the string is bogus anyway. */
+ }
+ else if (iter->cur.bytes == (size_t) -2)
+ {
+ /* An incomplete multibyte character at the end. */
+ iter->cur.bytes = iter->limit - iter->cur.ptr;
+ iter->cur.wc_valid = false;
+ /* Whether to set iter->in_shift = false and reset iter->state
+ or not is not important; the string end is reached anyway. */
+ }
+ else
+ {
+ if (iter->cur.bytes == 0)
+ {
+ /* A null wide character was encountered. */
+ iter->cur.bytes = 1;
+ assert (*iter->cur.ptr == '\0');
+ assert (iter->cur.wc == 0);
+ }
+ iter->cur.wc_valid = true;
+
+ /* When in the initial state, we can go back treating ASCII
+ characters more quickly. */
+ if (mbsinit (&iter->state))
+ iter->in_shift = false;
+ }
+ }
+ iter->next_done = true;
+}
+
+MBITER_INLINE void
+mbiter_multi_reloc (struct mbiter_multi *iter, ptrdiff_t ptrdiff)
+{
+ iter->cur.ptr += ptrdiff;
+ iter->limit += ptrdiff;
+}
+
+MBITER_INLINE void
+mbiter_multi_copy (struct mbiter_multi *new_iter, const struct mbiter_multi *old_iter)
+{
+ new_iter->limit = old_iter->limit;
+ if ((new_iter->in_shift = old_iter->in_shift))
+ memcpy (&new_iter->state, &old_iter->state, sizeof (mbstate_t));
+ else
+ memset (&new_iter->state, 0, sizeof (mbstate_t));
+ new_iter->next_done = old_iter->next_done;
+ mb_copy (&new_iter->cur, &old_iter->cur);
+}
+
+/* Iteration macros. */
+typedef struct mbiter_multi mbi_iterator_t;
+#define mbi_init(iter, startptr, length) \
+ ((iter).cur.ptr = (startptr), (iter).limit = (iter).cur.ptr + (length), \
+ (iter).in_shift = false, memset (&(iter).state, '\0', sizeof (mbstate_t)), \
+ (iter).next_done = false)
+#define mbi_avail(iter) \
+ ((iter).cur.ptr < (iter).limit && (mbiter_multi_next (&(iter)), true))
+#define mbi_advance(iter) \
+ ((iter).cur.ptr += (iter).cur.bytes, (iter).next_done = false)
+
+/* Access to the current character. */
+#define mbi_cur(iter) (iter).cur
+#define mbi_cur_ptr(iter) (iter).cur.ptr
+
+/* Relocation. */
+#define mbi_reloc(iter, ptrdiff) mbiter_multi_reloc (&iter, ptrdiff)
+
+/* Copying an iterator. */
+#define mbi_copy mbiter_multi_copy
+
+_GL_INLINE_HEADER_END
+
+#endif /* _MBITER_H */
diff --git a/lib/mbrlen.c b/lib/mbrlen.c
new file mode 100644
index 0000000..3ceb156
--- /dev/null
+++ b/lib/mbrlen.c
@@ -0,0 +1,32 @@
+/* Recognize multibyte character.
+ Copyright (C) 1999-2000, 2008-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2008.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <wchar.h>
+
+
+static mbstate_t internal_state;
+
+size_t
+mbrlen (const char *s, size_t n, mbstate_t *ps)
+{
+ if (ps == NULL)
+ ps = &internal_state;
+ return mbrtowc (NULL, s, n, ps);
+}
diff --git a/lib/mbrtowc.c b/lib/mbrtowc.c
new file mode 100644
index 0000000..864e006
--- /dev/null
+++ b/lib/mbrtowc.c
@@ -0,0 +1,407 @@
+/* Convert multibyte character to wide character.
+ Copyright (C) 1999-2002, 2005-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2008.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <wchar.h>
+
+#if GNULIB_defined_mbstate_t
+/* Implement mbrtowc() on top of mbtowc(). */
+
+# include <errno.h>
+# include <stdlib.h>
+
+# include "localcharset.h"
+# include "streq.h"
+# include "verify.h"
+
+
+verify (sizeof (mbstate_t) >= 4);
+
+static char internal_state[4];
+
+size_t
+mbrtowc (wchar_t *pwc, const char *s, size_t n, mbstate_t *ps)
+{
+ char *pstate = (char *)ps;
+
+ if (s == NULL)
+ {
+ pwc = NULL;
+ s = "";
+ n = 1;
+ }
+
+ if (n == 0)
+ return (size_t)(-2);
+
+ /* Here n > 0. */
+
+ if (pstate == NULL)
+ pstate = internal_state;
+
+ {
+ size_t nstate = pstate[0];
+ char buf[4];
+ const char *p;
+ size_t m;
+
+ switch (nstate)
+ {
+ case 0:
+ p = s;
+ m = n;
+ break;
+ case 3:
+ buf[2] = pstate[3];
+ /*FALLTHROUGH*/
+ case 2:
+ buf[1] = pstate[2];
+ /*FALLTHROUGH*/
+ case 1:
+ buf[0] = pstate[1];
+ p = buf;
+ m = nstate;
+ buf[m++] = s[0];
+ if (n >= 2 && m < 4)
+ {
+ buf[m++] = s[1];
+ if (n >= 3 && m < 4)
+ buf[m++] = s[2];
+ }
+ break;
+ default:
+ errno = EINVAL;
+ return (size_t)(-1);
+ }
+
+ /* Here m > 0. */
+
+# if __GLIBC__ || defined __UCLIBC__
+ /* Work around bug <http://sourceware.org/bugzilla/show_bug.cgi?id=9674> */
+ mbtowc (NULL, NULL, 0);
+# endif
+ {
+ int res = mbtowc (pwc, p, m);
+
+ if (res >= 0)
+ {
+ if (pwc != NULL && ((*pwc == 0) != (res == 0)))
+ abort ();
+ if (nstate >= (res > 0 ? res : 1))
+ abort ();
+ res -= nstate;
+ pstate[0] = 0;
+ return res;
+ }
+
+ /* mbtowc does not distinguish between invalid and incomplete multibyte
+ sequences. But mbrtowc needs to make this distinction.
+ There are two possible approaches:
+ - Use iconv() and its return value.
+ - Use built-in knowledge about the possible encodings.
+ Given the low quality of implementation of iconv() on the systems that
+ lack mbrtowc(), we use the second approach.
+ The possible encodings are:
+ - 8-bit encodings,
+ - EUC-JP, EUC-KR, GB2312, EUC-TW, BIG5, GB18030, SJIS,
+ - UTF-8.
+ Use specialized code for each. */
+ if (m >= 4 || m >= MB_CUR_MAX)
+ goto invalid;
+ /* Here MB_CUR_MAX > 1 and 0 < m < 4. */
+ {
+ const char *encoding = locale_charset ();
+
+ if (STREQ_OPT (encoding, "UTF-8", 'U', 'T', 'F', '-', '8', 0, 0, 0, 0))
+ {
+ /* Cf. unistr/u8-mblen.c. */
+ unsigned char c = (unsigned char) p[0];
+
+ if (c >= 0xc2)
+ {
+ if (c < 0xe0)
+ {
+ if (m == 1)
+ goto incomplete;
+ }
+ else if (c < 0xf0)
+ {
+ if (m == 1)
+ goto incomplete;
+ if (m == 2)
+ {
+ unsigned char c2 = (unsigned char) p[1];
+
+ if ((c2 ^ 0x80) < 0x40
+ && (c >= 0xe1 || c2 >= 0xa0)
+ && (c != 0xed || c2 < 0xa0))
+ goto incomplete;
+ }
+ }
+ else if (c <= 0xf4)
+ {
+ if (m == 1)
+ goto incomplete;
+ else /* m == 2 || m == 3 */
+ {
+ unsigned char c2 = (unsigned char) p[1];
+
+ if ((c2 ^ 0x80) < 0x40
+ && (c >= 0xf1 || c2 >= 0x90)
+ && (c < 0xf4 || (c == 0xf4 && c2 < 0x90)))
+ {
+ if (m == 2)
+ goto incomplete;
+ else /* m == 3 */
+ {
+ unsigned char c3 = (unsigned char) p[2];
+
+ if ((c3 ^ 0x80) < 0x40)
+ goto incomplete;
+ }
+ }
+ }
+ }
+ }
+ goto invalid;
+ }
+
+ /* As a reference for this code, you can use the GNU libiconv
+ implementation. Look for uses of the RET_TOOFEW macro. */
+
+ if (STREQ_OPT (encoding,
+ "EUC-JP", 'E', 'U', 'C', '-', 'J', 'P', 0, 0, 0))
+ {
+ if (m == 1)
+ {
+ unsigned char c = (unsigned char) p[0];
+
+ if ((c >= 0xa1 && c < 0xff) || c == 0x8e || c == 0x8f)
+ goto incomplete;
+ }
+ if (m == 2)
+ {
+ unsigned char c = (unsigned char) p[0];
+
+ if (c == 0x8f)
+ {
+ unsigned char c2 = (unsigned char) p[1];
+
+ if (c2 >= 0xa1 && c2 < 0xff)
+ goto incomplete;
+ }
+ }
+ goto invalid;
+ }
+ if (STREQ_OPT (encoding,
+ "EUC-KR", 'E', 'U', 'C', '-', 'K', 'R', 0, 0, 0)
+ || STREQ_OPT (encoding,
+ "GB2312", 'G', 'B', '2', '3', '1', '2', 0, 0, 0)
+ || STREQ_OPT (encoding,
+ "BIG5", 'B', 'I', 'G', '5', 0, 0, 0, 0, 0))
+ {
+ if (m == 1)
+ {
+ unsigned char c = (unsigned char) p[0];
+
+ if (c >= 0xa1 && c < 0xff)
+ goto incomplete;
+ }
+ goto invalid;
+ }
+ if (STREQ_OPT (encoding,
+ "EUC-TW", 'E', 'U', 'C', '-', 'T', 'W', 0, 0, 0))
+ {
+ if (m == 1)
+ {
+ unsigned char c = (unsigned char) p[0];
+
+ if ((c >= 0xa1 && c < 0xff) || c == 0x8e)
+ goto incomplete;
+ }
+ else /* m == 2 || m == 3 */
+ {
+ unsigned char c = (unsigned char) p[0];
+
+ if (c == 0x8e)
+ goto incomplete;
+ }
+ goto invalid;
+ }
+ if (STREQ_OPT (encoding,
+ "GB18030", 'G', 'B', '1', '8', '0', '3', '0', 0, 0))
+ {
+ if (m == 1)
+ {
+ unsigned char c = (unsigned char) p[0];
+
+ if ((c >= 0x90 && c <= 0xe3) || (c >= 0xf8 && c <= 0xfe))
+ goto incomplete;
+ }
+ else /* m == 2 || m == 3 */
+ {
+ unsigned char c = (unsigned char) p[0];
+
+ if (c >= 0x90 && c <= 0xe3)
+ {
+ unsigned char c2 = (unsigned char) p[1];
+
+ if (c2 >= 0x30 && c2 <= 0x39)
+ {
+ if (m == 2)
+ goto incomplete;
+ else /* m == 3 */
+ {
+ unsigned char c3 = (unsigned char) p[2];
+
+ if (c3 >= 0x81 && c3 <= 0xfe)
+ goto incomplete;
+ }
+ }
+ }
+ }
+ goto invalid;
+ }
+ if (STREQ_OPT (encoding, "SJIS", 'S', 'J', 'I', 'S', 0, 0, 0, 0, 0))
+ {
+ if (m == 1)
+ {
+ unsigned char c = (unsigned char) p[0];
+
+ if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xea)
+ || (c >= 0xf0 && c <= 0xf9))
+ goto incomplete;
+ }
+ goto invalid;
+ }
+
+ /* An unknown multibyte encoding. */
+ goto incomplete;
+ }
+
+ incomplete:
+ {
+ size_t k = nstate;
+ /* Here 0 <= k < m < 4. */
+ pstate[++k] = s[0];
+ if (k < m)
+ {
+ pstate[++k] = s[1];
+ if (k < m)
+ pstate[++k] = s[2];
+ }
+ if (k != m)
+ abort ();
+ }
+ pstate[0] = m;
+ return (size_t)(-2);
+
+ invalid:
+ errno = EILSEQ;
+ /* The conversion state is undefined, says POSIX. */
+ return (size_t)(-1);
+ }
+ }
+}
+
+#else
+/* Override the system's mbrtowc() function. */
+
+# undef mbrtowc
+
+size_t
+rpl_mbrtowc (wchar_t *pwc, const char *s, size_t n, mbstate_t *ps)
+{
+# if MBRTOWC_NULL_ARG2_BUG || MBRTOWC_RETVAL_BUG || MBRTOWC_EMPTY_INPUT_BUG
+ if (s == NULL)
+ {
+ pwc = NULL;
+ s = "";
+ n = 1;
+ }
+# endif
+
+# if MBRTOWC_EMPTY_INPUT_BUG
+ if (n == 0)
+ return (size_t) -2;
+# endif
+
+# if MBRTOWC_RETVAL_BUG
+ {
+ static mbstate_t internal_state;
+
+ /* Override mbrtowc's internal state. We cannot call mbsinit() on the
+ hidden internal state, but we can call it on our variable. */
+ if (ps == NULL)
+ ps = &internal_state;
+
+ if (!mbsinit (ps))
+ {
+ /* Parse the rest of the multibyte character byte for byte. */
+ size_t count = 0;
+ for (; n > 0; s++, n--)
+ {
+ wchar_t wc;
+ size_t ret = mbrtowc (&wc, s, 1, ps);
+
+ if (ret == (size_t)(-1))
+ return (size_t)(-1);
+ count++;
+ if (ret != (size_t)(-2))
+ {
+ /* The multibyte character has been completed. */
+ if (pwc != NULL)
+ *pwc = wc;
+ return (wc == 0 ? 0 : count);
+ }
+ }
+ return (size_t)(-2);
+ }
+ }
+# endif
+
+# if MBRTOWC_NUL_RETVAL_BUG
+ {
+ wchar_t wc;
+ size_t ret = mbrtowc (&wc, s, n, ps);
+
+ if (ret != (size_t)(-1) && ret != (size_t)(-2))
+ {
+ if (pwc != NULL)
+ *pwc = wc;
+ if (wc == 0)
+ ret = 0;
+ }
+ return ret;
+ }
+# else
+ {
+# if MBRTOWC_NULL_ARG1_BUG
+ wchar_t dummy;
+
+ if (pwc == NULL)
+ pwc = &dummy;
+# endif
+
+ return mbrtowc (pwc, s, n, ps);
+ }
+# endif
+}
+
+#endif
diff --git a/lib/mbsalign.c b/lib/mbsalign.c
new file mode 100644
index 0000000..8594f60
--- /dev/null
+++ b/lib/mbsalign.c
@@ -0,0 +1,278 @@
+/* Align/Truncate a string in a given screen width
+ Copyright (C) 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Pádraig Brady. */
+
+#include <config.h>
+#include "mbsalign.h"
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include <limits.h>
+#include <wchar.h>
+#include <wctype.h>
+
+#ifndef MIN
+# define MIN(a, b) ((a) < (b) ? (a) : (b))
+#endif
+
+/* Replace non printable chars.
+ Note \t and \n etc. are non printable.
+ Return 1 if replacement made, 0 otherwise. */
+
+static bool
+wc_ensure_printable (wchar_t *wchars)
+{
+ bool replaced = false;
+ wchar_t *wc = wchars;
+ while (*wc)
+ {
+ if (!iswprint ((wint_t) *wc))
+ {
+ *wc = 0xFFFD; /* L'\uFFFD' (replacement char) */
+ replaced = true;
+ }
+ wc++;
+ }
+ return replaced;
+}
+
+/* Truncate wchar string to width cells.
+ * Returns number of cells used. */
+
+static size_t
+wc_truncate (wchar_t *wc, size_t width)
+{
+ size_t cells = 0;
+ int next_cells = 0;
+
+ while (*wc)
+ {
+ next_cells = wcwidth (*wc);
+ if (next_cells == -1) /* non printable */
+ {
+ *wc = 0xFFFD; /* L'\uFFFD' (replacement char) */
+ next_cells = 1;
+ }
+ if (cells + next_cells > width)
+ break;
+ cells += next_cells;
+ wc++;
+ }
+ *wc = L'\0';
+ return cells;
+}
+
+/* Write N_SPACES space characters to DEST while ensuring
+ nothing is written beyond DEST_END. A terminating NUL
+ is always added to DEST.
+ A pointer to the terminating NUL is returned. */
+
+static char*
+mbs_align_pad (char *dest, const char* dest_end, size_t n_spaces)
+{
+ /* FIXME: Should we pad with "figure space" (\u2007)
+ if non ascii data present? */
+ while (n_spaces-- && (dest < dest_end))
+ *dest++ = ' ';
+ *dest = '\0';
+ return dest;
+}
+
+/* Align a string, SRC, in a field of *WIDTH columns, handling multi-byte
+ characters; write the result into the DEST_SIZE-byte buffer, DEST.
+ ALIGNMENT specifies whether to left- or right-justify or to center.
+ If SRC requires more than *WIDTH columns, truncate it to fit.
+ When centering, the number of trailing spaces may be one less than the
+ number of leading spaces.
+ Return the length in bytes required for the final result, not counting
+ the trailing NUL. A return value of DEST_SIZE or larger means there
+ wasn't enough space. DEST will be NUL terminated in any case.
+ Return SIZE_MAX upon error (invalid multi-byte sequence in SRC,
+ or malloc failure), unless MBA_UNIBYTE_FALLBACK is specified.
+ Update *WIDTH to indicate how many columns were used before padding. */
+
+size_t
+mbsalign (const char *src, char *dest, size_t dest_size,
+ size_t *width, mbs_align_t align, int flags)
+{
+ size_t ret = SIZE_MAX;
+ size_t src_size = strlen (src) + 1;
+ char *newstr = NULL;
+ wchar_t *str_wc = NULL;
+ const char *str_to_print = src;
+ size_t n_cols = src_size - 1;
+ size_t n_used_bytes = n_cols; /* Not including NUL */
+ size_t n_spaces = 0;
+ bool conversion = false;
+ bool wc_enabled = false;
+
+ /* In multi-byte locales convert to wide characters
+ to allow easy truncation. Also determine number
+ of screen columns used. */
+ if (!(flags & MBA_UNIBYTE_ONLY) && MB_CUR_MAX > 1)
+ {
+ size_t src_chars = mbstowcs (NULL, src, 0);
+ if (src_chars == SIZE_MAX)
+ {
+ if (flags & MBA_UNIBYTE_FALLBACK)
+ goto mbsalign_unibyte;
+ else
+ goto mbsalign_cleanup;
+ }
+ src_chars += 1; /* make space for NUL */
+ str_wc = malloc (src_chars * sizeof (wchar_t));
+ if (str_wc == NULL)
+ {
+ if (flags & MBA_UNIBYTE_FALLBACK)
+ goto mbsalign_unibyte;
+ else
+ goto mbsalign_cleanup;
+ }
+ if (mbstowcs (str_wc, src, src_chars) != 0)
+ {
+ str_wc[src_chars - 1] = L'\0';
+ wc_enabled = true;
+ conversion = wc_ensure_printable (str_wc);
+ n_cols = wcswidth (str_wc, src_chars);
+ }
+ }
+
+ /* If we transformed or need to truncate the source string
+ then create a modified copy of it. */
+ if (wc_enabled && (conversion || (n_cols > *width)))
+ {
+ if (conversion)
+ {
+ /* May have increased the size by converting
+ \t to \uFFFD for example. */
+ src_size = wcstombs (NULL, str_wc, 0) + 1;
+ }
+ newstr = malloc (src_size);
+ if (newstr == NULL)
+ {
+ if (flags & MBA_UNIBYTE_FALLBACK)
+ goto mbsalign_unibyte;
+ else
+ goto mbsalign_cleanup;
+ }
+ str_to_print = newstr;
+ n_cols = wc_truncate (str_wc, *width);
+ n_used_bytes = wcstombs (newstr, str_wc, src_size);
+ }
+
+mbsalign_unibyte:
+
+ if (n_cols > *width) /* Unibyte truncation required. */
+ {
+ n_cols = *width;
+ n_used_bytes = n_cols;
+ }
+
+ if (*width > n_cols) /* Padding required. */
+ n_spaces = *width - n_cols;
+
+ /* indicate to caller how many cells needed (not including padding). */
+ *width = n_cols;
+
+ {
+ size_t start_spaces, end_spaces;
+
+ switch (align)
+ {
+ case MBS_ALIGN_LEFT:
+ start_spaces = 0;
+ end_spaces = n_spaces;
+ break;
+ case MBS_ALIGN_RIGHT:
+ start_spaces = n_spaces;
+ end_spaces = 0;
+ break;
+ case MBS_ALIGN_CENTER:
+ default:
+ start_spaces = n_spaces / 2 + n_spaces % 2;
+ end_spaces = n_spaces / 2;
+ break;
+ }
+
+ if (flags & MBA_NO_LEFT_PAD)
+ start_spaces = 0;
+ if (flags & MBA_NO_RIGHT_PAD)
+ end_spaces = 0;
+
+ /* Write as much NUL terminated output to DEST as possible. */
+ if (dest_size != 0)
+ {
+ size_t space_left;
+ char *dest_end = dest + dest_size - 1;
+
+ dest = mbs_align_pad (dest, dest_end, start_spaces);
+ space_left = dest_end - dest;
+ dest = mempcpy (dest, str_to_print, MIN (n_used_bytes, space_left));
+ mbs_align_pad (dest, dest_end, end_spaces);
+ }
+
+ /* indicate to caller how many bytes needed (not including NUL). */
+ ret = n_used_bytes + ((start_spaces + end_spaces) * 1);
+ }
+
+mbsalign_cleanup:
+
+ free (str_wc);
+ free (newstr);
+
+ return ret;
+}
+
+/* A wrapper around mbsalign() to dynamically allocate the
+ minimum amount of memory to store the result.
+ Return NULL on failure. */
+
+char *
+ambsalign (const char *src, size_t *width, mbs_align_t align, int flags)
+{
+ size_t orig_width = *width;
+ size_t size = *width; /* Start with enough for unibyte mode. */
+ size_t req = size;
+ char *buf = NULL;
+
+ while (req >= size)
+ {
+ char *nbuf;
+ size = req + 1; /* Space for NUL. */
+ nbuf = realloc (buf, size);
+ if (nbuf == NULL)
+ {
+ free (buf);
+ buf = NULL;
+ break;
+ }
+ buf = nbuf;
+ *width = orig_width;
+ req = mbsalign (src, buf, size, width, align, flags);
+ if (req == SIZE_MAX)
+ {
+ free (buf);
+ buf = NULL;
+ break;
+ }
+ }
+
+ return buf;
+}
diff --git a/lib/mbsalign.h b/lib/mbsalign.h
new file mode 100644
index 0000000..5f3d6a6
--- /dev/null
+++ b/lib/mbsalign.h
@@ -0,0 +1,59 @@
+/* Align/Truncate a string in a given screen width
+ Copyright (C) 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <stddef.h>
+
+typedef enum { MBS_ALIGN_LEFT, MBS_ALIGN_RIGHT, MBS_ALIGN_CENTER } mbs_align_t;
+
+enum {
+ /* Use unibyte mode for invalid multibyte strings
+ or when heap memory is exhausted. */
+ MBA_UNIBYTE_FALLBACK = 0x0001,
+
+ /* As an optimization, don't do multibyte processing
+ when we know no multibyte characters are present. */
+ MBA_UNIBYTE_ONLY = 0x0002,
+
+ /* Don't add leading padding. */
+ MBA_NO_LEFT_PAD = 0x0004,
+
+ /* Don't add trailing padding. */
+ MBA_NO_RIGHT_PAD = 0x0008
+
+#if 0 /* Other possible options. */
+ /* Skip invalid multibyte chars rather than failing. */
+ MBA_IGNORE_INVALID
+
+ /* Align multibyte strings using "figure space" (\u2007). */
+ MBA_USE_FIGURE_SPACE
+
+ /* Don't truncate. */
+ MBA_NO_TRUNCATE
+
+ /* Ensure no leading whitespace. */
+ MBA_LSTRIP
+
+ /* Ensure no trailing whitespace. */
+ MBA_RSTRIP
+#endif
+};
+
+size_t
+mbsalign (const char *src, char *dest, size_t dest_size,
+ size_t *width, mbs_align_t align, int flags);
+
+char *
+ambsalign (const char *src, size_t *width, mbs_align_t align, int flags);
diff --git a/lib/mbscasecmp.c b/lib/mbscasecmp.c
index 8a2f434..7e7c941 100644
--- a/lib/mbscasecmp.c
+++ b/lib/mbscasecmp.c
@@ -1,12 +1,12 @@
/* Case-insensitive string comparison function.
- Copyright (C) 1998-1999, 2005-2007 Free Software Foundation, Inc.
+ Copyright (C) 1998-1999, 2005-2016 Free Software Foundation, Inc.
Written by Bruno Haible <bruno@clisp.org>, 2005,
based on earlier glibc code.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
@@ -25,9 +24,7 @@
#include <ctype.h>
#include <limits.h>
-#if HAVE_MBRTOWC
-# include "mbuiter.h"
-#endif
+#include "mbuiter.h"
#define TOLOWER(Ch) (isupper (Ch) ? tolower (Ch) : (Ch))
@@ -45,7 +42,6 @@ mbscasecmp (const char *s1, const char *s2)
/* Be careful not to look at the entire extent of s1 or s2 until needed.
This is useful because when two strings differ, the difference is
most often already in the very few first characters. */
-#if HAVE_MBRTOWC
if (MB_CUR_MAX > 1)
{
mbui_iterator_t iter1;
@@ -55,49 +51,48 @@ mbscasecmp (const char *s1, const char *s2)
mbui_init (iter2, s2);
while (mbui_avail (iter1) && mbui_avail (iter2))
- {
- int cmp = mb_casecmp (mbui_cur (iter1), mbui_cur (iter2));
+ {
+ int cmp = mb_casecmp (mbui_cur (iter1), mbui_cur (iter2));
- if (cmp != 0)
- return cmp;
+ if (cmp != 0)
+ return cmp;
- mbui_advance (iter1);
- mbui_advance (iter2);
- }
+ mbui_advance (iter1);
+ mbui_advance (iter2);
+ }
if (mbui_avail (iter1))
- /* s2 terminated before s1. */
- return 1;
+ /* s2 terminated before s1. */
+ return 1;
if (mbui_avail (iter2))
- /* s1 terminated before s2. */
- return -1;
+ /* s1 terminated before s2. */
+ return -1;
return 0;
}
else
-#endif
{
const unsigned char *p1 = (const unsigned char *) s1;
const unsigned char *p2 = (const unsigned char *) s2;
unsigned char c1, c2;
do
- {
- c1 = TOLOWER (*p1);
- c2 = TOLOWER (*p2);
+ {
+ c1 = TOLOWER (*p1);
+ c2 = TOLOWER (*p2);
- if (c1 == '\0')
- break;
+ if (c1 == '\0')
+ break;
- ++p1;
- ++p2;
- }
+ ++p1;
+ ++p2;
+ }
while (c1 == c2);
if (UCHAR_MAX <= INT_MAX)
- return c1 - c2;
+ return c1 - c2;
else
- /* On machines where 'char' and 'int' are types of the same size, the
- difference of two 'unsigned char' values - including the sign bit -
- doesn't fit in an 'int'. */
- return (c1 > c2 ? 1 : c1 < c2 ? -1 : 0);
+ /* On machines where 'char' and 'int' are types of the same size, the
+ difference of two 'unsigned char' values - including the sign bit -
+ doesn't fit in an 'int'. */
+ return (c1 > c2 ? 1 : c1 < c2 ? -1 : 0);
}
}
diff --git a/lib/mbsinit.c b/lib/mbsinit.c
new file mode 100644
index 0000000..372b523
--- /dev/null
+++ b/lib/mbsinit.c
@@ -0,0 +1,61 @@
+/* Test for initial conversion state.
+ Copyright (C) 2008-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2008.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <wchar.h>
+
+#include "verify.h"
+
+#if (defined _WIN32 || defined __WIN32__) && !defined __CYGWIN__
+
+/* On native Windows, 'mbstate_t' is defined as 'int'. */
+
+int
+mbsinit (const mbstate_t *ps)
+{
+ return ps == NULL || *ps == 0;
+}
+
+#else
+
+/* Platforms that lack mbsinit() also lack mbrlen(), mbrtowc(), mbsrtowcs()
+ and wcrtomb(), wcsrtombs().
+ We assume that
+ - sizeof (mbstate_t) >= 4,
+ - only stateless encodings are supported (such as UTF-8 and EUC-JP, but
+ not ISO-2022 variants),
+ - for each encoding, the number of bytes for a wide character is <= 4.
+ (This maximum is attained for UTF-8, GB18030, EUC-TW.)
+ We define the meaning of mbstate_t as follows:
+ - In mb -> wc direction, mbstate_t's first byte contains the number of
+ buffered bytes (in the range 0..3), followed by up to 3 buffered bytes.
+ - In wc -> mb direction, mbstate_t contains no information. In other
+ words, it is always in the initial state. */
+
+verify (sizeof (mbstate_t) >= 4);
+
+int
+mbsinit (const mbstate_t *ps)
+{
+ const char *pstate = (const char *)ps;
+
+ return pstate == NULL || pstate[0] == 0;
+}
+
+#endif
diff --git a/lib/mbslen.c b/lib/mbslen.c
new file mode 100644
index 0000000..ed13a42
--- /dev/null
+++ b/lib/mbslen.c
@@ -0,0 +1,44 @@
+/* Counting the multibyte characters in a string.
+ Copyright (C) 2007-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2007.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <string.h>
+
+#include <stdlib.h>
+
+#include "mbuiter.h"
+
+/* Return the number of multibyte characters in the character string STRING. */
+size_t
+mbslen (const char *string)
+{
+ if (MB_CUR_MAX > 1)
+ {
+ size_t count;
+ mbui_iterator_t iter;
+
+ count = 0;
+ for (mbui_init (iter, string); mbui_avail (iter); mbui_advance (iter))
+ count++;
+
+ return count;
+ }
+ else
+ return strlen (string);
+}
diff --git a/lib/mbsrtowcs-impl.h b/lib/mbsrtowcs-impl.h
new file mode 100644
index 0000000..f99fa34
--- /dev/null
+++ b/lib/mbsrtowcs-impl.h
@@ -0,0 +1,122 @@
+/* Convert string to wide string.
+ Copyright (C) 2008-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2008.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+size_t
+mbsrtowcs (wchar_t *dest, const char **srcp, size_t len, mbstate_t *ps)
+{
+ if (ps == NULL)
+ ps = &_gl_mbsrtowcs_state;
+ {
+ const char *src = *srcp;
+
+ if (dest != NULL)
+ {
+ wchar_t *destptr = dest;
+
+ for (; len > 0; destptr++, len--)
+ {
+ size_t src_avail;
+ size_t ret;
+
+ /* An optimized variant of
+ src_avail = strnlen1 (src, MB_LEN_MAX); */
+ if (src[0] == '\0')
+ src_avail = 1;
+ else if (src[1] == '\0')
+ src_avail = 2;
+ else if (src[2] == '\0')
+ src_avail = 3;
+ else if (MB_LEN_MAX <= 4 || src[3] == '\0')
+ src_avail = 4;
+ else
+ src_avail = 4 + strnlen1 (src + 4, MB_LEN_MAX - 4);
+
+ /* Parse the next multibyte character. */
+ ret = mbrtowc (destptr, src, src_avail, ps);
+
+ if (ret == (size_t)(-2))
+ /* Encountered a multibyte character that extends past a '\0' byte
+ or that is longer than MB_LEN_MAX bytes. Cannot happen. */
+ abort ();
+
+ if (ret == (size_t)(-1))
+ goto bad_input;
+ if (ret == 0)
+ {
+ src = NULL;
+ /* Here mbsinit (ps). */
+ break;
+ }
+ src += ret;
+ }
+
+ *srcp = src;
+ return destptr - dest;
+ }
+ else
+ {
+ /* Ignore dest and len, don't store *srcp at the end, and
+ don't clobber *ps. */
+ mbstate_t state = *ps;
+ size_t totalcount = 0;
+
+ for (;; totalcount++)
+ {
+ size_t src_avail;
+ size_t ret;
+
+ /* An optimized variant of
+ src_avail = strnlen1 (src, MB_LEN_MAX); */
+ if (src[0] == '\0')
+ src_avail = 1;
+ else if (src[1] == '\0')
+ src_avail = 2;
+ else if (src[2] == '\0')
+ src_avail = 3;
+ else if (MB_LEN_MAX <= 4 || src[3] == '\0')
+ src_avail = 4;
+ else
+ src_avail = 4 + strnlen1 (src + 4, MB_LEN_MAX - 4);
+
+ /* Parse the next multibyte character. */
+ ret = mbrtowc (NULL, src, src_avail, &state);
+
+ if (ret == (size_t)(-2))
+ /* Encountered a multibyte character that extends past a '\0' byte
+ or that is longer than MB_LEN_MAX bytes. Cannot happen. */
+ abort ();
+
+ if (ret == (size_t)(-1))
+ goto bad_input2;
+ if (ret == 0)
+ {
+ /* Here mbsinit (&state). */
+ break;
+ }
+ src += ret;
+ }
+
+ return totalcount;
+ }
+
+ bad_input:
+ *srcp = src;
+ bad_input2:
+ errno = EILSEQ;
+ return (size_t)(-1);
+ }
+}
diff --git a/lib/mbsrtowcs-state.c b/lib/mbsrtowcs-state.c
new file mode 100644
index 0000000..905547a
--- /dev/null
+++ b/lib/mbsrtowcs-state.c
@@ -0,0 +1,37 @@
+/* Convert string to wide string.
+ Copyright (C) 2008-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2008.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+#include <wchar.h>
+
+/* Internal state used by the functions mbsrtowcs() and mbsnrtowcs(). */
+mbstate_t _gl_mbsrtowcs_state
+/* The state must initially be in the "initial state"; so, zero-initialize it.
+ On most systems, putting it into BSS is sufficient. Not so on Mac OS X 10.3,
+ see <http://lists.gnu.org/archive/html/bug-gnulib/2009-01/msg00329.html>.
+ When it needs an initializer, use 0 or {0} as initializer? 0 only works
+ when mbstate_t is a scalar type (such as when gnulib defines it, or on
+ AIX, IRIX, mingw). {0} works as an initializer in all cases: for a struct
+ or union type, but also for a scalar type (ISO C 99, 6.7.8.(11)). */
+#if defined __ELF__
+ /* On ELF systems, variables in BSS behave well. */
+#else
+ /* Use braces, to be on the safe side. */
+ = { 0 }
+#endif
+ ;
diff --git a/lib/mbsrtowcs.c b/lib/mbsrtowcs.c
new file mode 100644
index 0000000..54bf6f7
--- /dev/null
+++ b/lib/mbsrtowcs.c
@@ -0,0 +1,32 @@
+/* Convert string to wide string.
+ Copyright (C) 2008-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2008.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <wchar.h>
+
+#include <errno.h>
+#include <limits.h>
+#include <stdlib.h>
+
+#include "strnlen1.h"
+
+
+extern mbstate_t _gl_mbsrtowcs_state;
+
+#include "mbsrtowcs-impl.h"
diff --git a/lib/mbsstr.c b/lib/mbsstr.c
new file mode 100644
index 0000000..bc738d4
--- /dev/null
+++ b/lib/mbsstr.c
@@ -0,0 +1,384 @@
+/* Searching in a string. -*- coding: utf-8 -*-
+ Copyright (C) 2005-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2005.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <string.h>
+
+#include <stdbool.h>
+#include <stddef.h> /* for NULL, in case a nonstandard string.h lacks it */
+
+#include "malloca.h"
+#include "mbuiter.h"
+
+/* Knuth-Morris-Pratt algorithm. */
+#define UNIT unsigned char
+#define CANON_ELEMENT(c) c
+#include "str-kmp.h"
+
+/* Knuth-Morris-Pratt algorithm.
+ See http://en.wikipedia.org/wiki/Knuth-Morris-Pratt_algorithm
+ Return a boolean indicating success:
+ Return true and set *RESULTP if the search was completed.
+ Return false if it was aborted because not enough memory was available. */
+static bool
+knuth_morris_pratt_multibyte (const char *haystack, const char *needle,
+ const char **resultp)
+{
+ size_t m = mbslen (needle);
+ mbchar_t *needle_mbchars;
+ size_t *table;
+
+ /* Allocate room for needle_mbchars and the table. */
+ void *memory = nmalloca (m, sizeof (mbchar_t) + sizeof (size_t));
+ void *table_memory;
+ if (memory == NULL)
+ return false;
+ needle_mbchars = memory;
+ table_memory = needle_mbchars + m;
+ table = table_memory;
+
+ /* Fill needle_mbchars. */
+ {
+ mbui_iterator_t iter;
+ size_t j;
+
+ j = 0;
+ for (mbui_init (iter, needle); mbui_avail (iter); mbui_advance (iter), j++)
+ mb_copy (&needle_mbchars[j], &mbui_cur (iter));
+ }
+
+ /* Fill the table.
+ For 0 < i < m:
+ 0 < table[i] <= i is defined such that
+ forall 0 < x < table[i]: needle[x..i-1] != needle[0..i-1-x],
+ and table[i] is as large as possible with this property.
+ This implies:
+ 1) For 0 < i < m:
+ If table[i] < i,
+ needle[table[i]..i-1] = needle[0..i-1-table[i]].
+ 2) For 0 < i < m:
+ rhaystack[0..i-1] == needle[0..i-1]
+ and exists h, i <= h < m: rhaystack[h] != needle[h]
+ implies
+ forall 0 <= x < table[i]: rhaystack[x..x+m-1] != needle[0..m-1].
+ table[0] remains uninitialized. */
+ {
+ size_t i, j;
+
+ /* i = 1: Nothing to verify for x = 0. */
+ table[1] = 1;
+ j = 0;
+
+ for (i = 2; i < m; i++)
+ {
+ /* Here: j = i-1 - table[i-1].
+ The inequality needle[x..i-1] != needle[0..i-1-x] is known to hold
+ for x < table[i-1], by induction.
+ Furthermore, if j>0: needle[i-1-j..i-2] = needle[0..j-1]. */
+ mbchar_t *b = &needle_mbchars[i - 1];
+
+ for (;;)
+ {
+ /* Invariants: The inequality needle[x..i-1] != needle[0..i-1-x]
+ is known to hold for x < i-1-j.
+ Furthermore, if j>0: needle[i-1-j..i-2] = needle[0..j-1]. */
+ if (mb_equal (*b, needle_mbchars[j]))
+ {
+ /* Set table[i] := i-1-j. */
+ table[i] = i - ++j;
+ break;
+ }
+ /* The inequality needle[x..i-1] != needle[0..i-1-x] also holds
+ for x = i-1-j, because
+ needle[i-1] != needle[j] = needle[i-1-x]. */
+ if (j == 0)
+ {
+ /* The inequality holds for all possible x. */
+ table[i] = i;
+ break;
+ }
+ /* The inequality needle[x..i-1] != needle[0..i-1-x] also holds
+ for i-1-j < x < i-1-j+table[j], because for these x:
+ needle[x..i-2]
+ = needle[x-(i-1-j)..j-1]
+ != needle[0..j-1-(x-(i-1-j))] (by definition of table[j])
+ = needle[0..i-2-x],
+ hence needle[x..i-1] != needle[0..i-1-x].
+ Furthermore
+ needle[i-1-j+table[j]..i-2]
+ = needle[table[j]..j-1]
+ = needle[0..j-1-table[j]] (by definition of table[j]). */
+ j = j - table[j];
+ }
+ /* Here: j = i - table[i]. */
+ }
+ }
+
+ /* Search, using the table to accelerate the processing. */
+ {
+ size_t j;
+ mbui_iterator_t rhaystack;
+ mbui_iterator_t phaystack;
+
+ *resultp = NULL;
+ j = 0;
+ mbui_init (rhaystack, haystack);
+ mbui_init (phaystack, haystack);
+ /* Invariant: phaystack = rhaystack + j. */
+ while (mbui_avail (phaystack))
+ if (mb_equal (needle_mbchars[j], mbui_cur (phaystack)))
+ {
+ j++;
+ mbui_advance (phaystack);
+ if (j == m)
+ {
+ /* The entire needle has been found. */
+ *resultp = mbui_cur_ptr (rhaystack);
+ break;
+ }
+ }
+ else if (j > 0)
+ {
+ /* Found a match of needle[0..j-1], mismatch at needle[j]. */
+ size_t count = table[j];
+ j -= count;
+ for (; count > 0; count--)
+ {
+ if (!mbui_avail (rhaystack))
+ abort ();
+ mbui_advance (rhaystack);
+ }
+ }
+ else
+ {
+ /* Found a mismatch at needle[0] already. */
+ if (!mbui_avail (rhaystack))
+ abort ();
+ mbui_advance (rhaystack);
+ mbui_advance (phaystack);
+ }
+ }
+
+ freea (memory);
+ return true;
+}
+
+/* Find the first occurrence of the character string NEEDLE in the character
+ string HAYSTACK. Return NULL if NEEDLE is not found in HAYSTACK. */
+char *
+mbsstr (const char *haystack, const char *needle)
+{
+ /* Be careful not to look at the entire extent of haystack or needle
+ until needed. This is useful because of these two cases:
+ - haystack may be very long, and a match of needle found early,
+ - needle may be very long, and not even a short initial segment of
+ needle may be found in haystack. */
+ if (MB_CUR_MAX > 1)
+ {
+ mbui_iterator_t iter_needle;
+
+ mbui_init (iter_needle, needle);
+ if (mbui_avail (iter_needle))
+ {
+ /* Minimizing the worst-case complexity:
+ Let n = mbslen(haystack), m = mbslen(needle).
+ The naïve algorithm is O(n*m) worst-case.
+ The Knuth-Morris-Pratt algorithm is O(n) worst-case but it needs a
+ memory allocation.
+ To achieve linear complexity and yet amortize the cost of the
+ memory allocation, we activate the Knuth-Morris-Pratt algorithm
+ only once the naïve algorithm has already run for some time; more
+ precisely, when
+ - the outer loop count is >= 10,
+ - the average number of comparisons per outer loop is >= 5,
+ - the total number of comparisons is >= m.
+ But we try it only once. If the memory allocation attempt failed,
+ we don't retry it. */
+ bool try_kmp = true;
+ size_t outer_loop_count = 0;
+ size_t comparison_count = 0;
+ size_t last_ccount = 0; /* last comparison count */
+ mbui_iterator_t iter_needle_last_ccount; /* = needle + last_ccount */
+
+ mbui_iterator_t iter_haystack;
+
+ mbui_init (iter_needle_last_ccount, needle);
+ mbui_init (iter_haystack, haystack);
+ for (;; mbui_advance (iter_haystack))
+ {
+ if (!mbui_avail (iter_haystack))
+ /* No match. */
+ return NULL;
+
+ /* See whether it's advisable to use an asymptotically faster
+ algorithm. */
+ if (try_kmp
+ && outer_loop_count >= 10
+ && comparison_count >= 5 * outer_loop_count)
+ {
+ /* See if needle + comparison_count now reaches the end of
+ needle. */
+ size_t count = comparison_count - last_ccount;
+ for (;
+ count > 0 && mbui_avail (iter_needle_last_ccount);
+ count--)
+ mbui_advance (iter_needle_last_ccount);
+ last_ccount = comparison_count;
+ if (!mbui_avail (iter_needle_last_ccount))
+ {
+ /* Try the Knuth-Morris-Pratt algorithm. */
+ const char *result;
+ bool success =
+ knuth_morris_pratt_multibyte (haystack, needle,
+ &result);
+ if (success)
+ return (char *) result;
+ try_kmp = false;
+ }
+ }
+
+ outer_loop_count++;
+ comparison_count++;
+ if (mb_equal (mbui_cur (iter_haystack), mbui_cur (iter_needle)))
+ /* The first character matches. */
+ {
+ mbui_iterator_t rhaystack;
+ mbui_iterator_t rneedle;
+
+ memcpy (&rhaystack, &iter_haystack, sizeof (mbui_iterator_t));
+ mbui_advance (rhaystack);
+
+ mbui_init (rneedle, needle);
+ if (!mbui_avail (rneedle))
+ abort ();
+ mbui_advance (rneedle);
+
+ for (;; mbui_advance (rhaystack), mbui_advance (rneedle))
+ {
+ if (!mbui_avail (rneedle))
+ /* Found a match. */
+ return (char *) mbui_cur_ptr (iter_haystack);
+ if (!mbui_avail (rhaystack))
+ /* No match. */
+ return NULL;
+ comparison_count++;
+ if (!mb_equal (mbui_cur (rhaystack), mbui_cur (rneedle)))
+ /* Nothing in this round. */
+ break;
+ }
+ }
+ }
+ }
+ else
+ return (char *) haystack;
+ }
+ else
+ {
+ if (*needle != '\0')
+ {
+ /* Minimizing the worst-case complexity:
+ Let n = strlen(haystack), m = strlen(needle).
+ The naïve algorithm is O(n*m) worst-case.
+ The Knuth-Morris-Pratt algorithm is O(n) worst-case but it needs a
+ memory allocation.
+ To achieve linear complexity and yet amortize the cost of the
+ memory allocation, we activate the Knuth-Morris-Pratt algorithm
+ only once the naïve algorithm has already run for some time; more
+ precisely, when
+ - the outer loop count is >= 10,
+ - the average number of comparisons per outer loop is >= 5,
+ - the total number of comparisons is >= m.
+ But we try it only once. If the memory allocation attempt failed,
+ we don't retry it. */
+ bool try_kmp = true;
+ size_t outer_loop_count = 0;
+ size_t comparison_count = 0;
+ size_t last_ccount = 0; /* last comparison count */
+ const char *needle_last_ccount = needle; /* = needle + last_ccount */
+
+ /* Speed up the following searches of needle by caching its first
+ character. */
+ char b = *needle++;
+
+ for (;; haystack++)
+ {
+ if (*haystack == '\0')
+ /* No match. */
+ return NULL;
+
+ /* See whether it's advisable to use an asymptotically faster
+ algorithm. */
+ if (try_kmp
+ && outer_loop_count >= 10
+ && comparison_count >= 5 * outer_loop_count)
+ {
+ /* See if needle + comparison_count now reaches the end of
+ needle. */
+ if (needle_last_ccount != NULL)
+ {
+ needle_last_ccount +=
+ strnlen (needle_last_ccount,
+ comparison_count - last_ccount);
+ if (*needle_last_ccount == '\0')
+ needle_last_ccount = NULL;
+ last_ccount = comparison_count;
+ }
+ if (needle_last_ccount == NULL)
+ {
+ /* Try the Knuth-Morris-Pratt algorithm. */
+ const unsigned char *result;
+ bool success =
+ knuth_morris_pratt ((const unsigned char *) haystack,
+ (const unsigned char *) (needle - 1),
+ strlen (needle - 1),
+ &result);
+ if (success)
+ return (char *) result;
+ try_kmp = false;
+ }
+ }
+
+ outer_loop_count++;
+ comparison_count++;
+ if (*haystack == b)
+ /* The first character matches. */
+ {
+ const char *rhaystack = haystack + 1;
+ const char *rneedle = needle;
+
+ for (;; rhaystack++, rneedle++)
+ {
+ if (*rneedle == '\0')
+ /* Found a match. */
+ return (char *) haystack;
+ if (*rhaystack == '\0')
+ /* No match. */
+ return NULL;
+ comparison_count++;
+ if (*rhaystack != *rneedle)
+ /* Nothing in this round. */
+ break;
+ }
+ }
+ }
+ }
+ else
+ return (char *) haystack;
+ }
+}
diff --git a/lib/mbswidth.c b/lib/mbswidth.c
index 0bc1a68..a235bf1 100644
--- a/lib/mbswidth.c
+++ b/lib/mbswidth.c
@@ -1,10 +1,10 @@
/* Determine the number of screen columns needed for a string.
- Copyright (C) 2000-2007 Free Software Foundation, Inc.
+ Copyright (C) 2000-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -12,8 +12,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Bruno Haible <haible@clisp.cons.org>. */
@@ -30,27 +29,20 @@
/* Get isprint(). */
#include <ctype.h>
-/* Get mbstate_t, mbrtowc(), mbsinit(). */
+/* Get mbstate_t, mbrtowc(), mbsinit(), wcwidth(). */
#include <wchar.h>
-/* Get wcwidth(). */
-#include "wcwidth.h"
-
/* Get iswcntrl(). */
#include <wctype.h>
-#ifndef mbsinit
-# if !HAVE_MBSINIT
-# define mbsinit(ps) 1
-# endif
-#endif
+/* Get INT_MAX. */
+#include <limits.h>
/* Returns the number of columns needed to represent the multibyte
character string pointed to by STRING. If a non-printable character
occurs, and MBSW_REJECT_UNPRINTABLE is specified, -1 is returned.
With flags = MBSW_REJECT_INVALID | MBSW_REJECT_UNPRINTABLE, this is
- the multibyte analogue of the wcswidth function.
- If STRING is not of length < INT_MAX / 2, integer overflow can occur. */
+ the multibyte analogue of the wcswidth function. */
int
mbswidth (const char *string, int flags)
{
@@ -60,8 +52,7 @@ mbswidth (const char *string, int flags)
/* Returns the number of columns needed to represent the multibyte
character string pointed to by STRING of length NBYTES. If a
non-printable character occurs, and MBSW_REJECT_UNPRINTABLE is
- specified, -1 is returned.
- If NBYTES is not < INT_MAX / 2, integer overflow can occur. */
+ specified, -1 is returned. */
int
mbsnwidth (const char *string, size_t nbytes, int flags)
{
@@ -70,110 +61,133 @@ mbsnwidth (const char *string, size_t nbytes, int flags)
int width;
width = 0;
-#if HAVE_MBRTOWC
if (MB_CUR_MAX > 1)
{
while (p < plimit)
- switch (*p)
- {
- case ' ': case '!': case '"': case '#': case '%':
- case '&': case '\'': case '(': case ')': case '*':
- case '+': case ',': case '-': case '.': case '/':
- case '0': case '1': case '2': case '3': case '4':
- case '5': case '6': case '7': case '8': case '9':
- case ':': case ';': case '<': case '=': case '>':
- case '?':
- case 'A': case 'B': case 'C': case 'D': case 'E':
- case 'F': case 'G': case 'H': case 'I': case 'J':
- case 'K': case 'L': case 'M': case 'N': case 'O':
- case 'P': case 'Q': case 'R': case 'S': case 'T':
- case 'U': case 'V': case 'W': case 'X': case 'Y':
- case 'Z':
- case '[': case '\\': case ']': case '^': case '_':
- case 'a': case 'b': case 'c': case 'd': case 'e':
- case 'f': case 'g': case 'h': case 'i': case 'j':
- case 'k': case 'l': case 'm': case 'n': case 'o':
- case 'p': case 'q': case 'r': case 's': case 't':
- case 'u': case 'v': case 'w': case 'x': case 'y':
- case 'z': case '{': case '|': case '}': case '~':
- /* These characters are printable ASCII characters. */
- p++;
- width++;
- break;
- default:
- /* If we have a multibyte sequence, scan it up to its end. */
- {
- mbstate_t mbstate;
- memset (&mbstate, 0, sizeof mbstate);
- do
- {
- wchar_t wc;
- size_t bytes;
- int w;
-
- bytes = mbrtowc (&wc, p, plimit - p, &mbstate);
-
- if (bytes == (size_t) -1)
- /* An invalid multibyte sequence was encountered. */
- {
- if (!(flags & MBSW_REJECT_INVALID))
- {
- p++;
- width++;
- break;
- }
- else
- return -1;
- }
-
- if (bytes == (size_t) -2)
- /* An incomplete multibyte character at the end. */
- {
- if (!(flags & MBSW_REJECT_INVALID))
- {
- p = plimit;
- width++;
- break;
- }
- else
- return -1;
- }
-
- if (bytes == 0)
- /* A null wide character was encountered. */
- bytes = 1;
-
- w = wcwidth (wc);
- if (w >= 0)
- /* A printable multibyte character. */
- width += w;
- else
- /* An unprintable multibyte character. */
- if (!(flags & MBSW_REJECT_UNPRINTABLE))
- width += (iswcntrl (wc) ? 0 : 1);
- else
- return -1;
-
- p += bytes;
- }
- while (! mbsinit (&mbstate));
- }
- break;
- }
+ switch (*p)
+ {
+ case ' ': case '!': case '"': case '#': case '%':
+ case '&': case '\'': case '(': case ')': case '*':
+ case '+': case ',': case '-': case '.': case '/':
+ case '0': case '1': case '2': case '3': case '4':
+ case '5': case '6': case '7': case '8': case '9':
+ case ':': case ';': case '<': case '=': case '>':
+ case '?':
+ case 'A': case 'B': case 'C': case 'D': case 'E':
+ case 'F': case 'G': case 'H': case 'I': case 'J':
+ case 'K': case 'L': case 'M': case 'N': case 'O':
+ case 'P': case 'Q': case 'R': case 'S': case 'T':
+ case 'U': case 'V': case 'W': case 'X': case 'Y':
+ case 'Z':
+ case '[': case '\\': case ']': case '^': case '_':
+ case 'a': case 'b': case 'c': case 'd': case 'e':
+ case 'f': case 'g': case 'h': case 'i': case 'j':
+ case 'k': case 'l': case 'm': case 'n': case 'o':
+ case 'p': case 'q': case 'r': case 's': case 't':
+ case 'u': case 'v': case 'w': case 'x': case 'y':
+ case 'z': case '{': case '|': case '}': case '~':
+ /* These characters are printable ASCII characters. */
+ p++;
+ width++;
+ break;
+ default:
+ /* If we have a multibyte sequence, scan it up to its end. */
+ {
+ mbstate_t mbstate;
+ memset (&mbstate, 0, sizeof mbstate);
+ do
+ {
+ wchar_t wc;
+ size_t bytes;
+ int w;
+
+ bytes = mbrtowc (&wc, p, plimit - p, &mbstate);
+
+ if (bytes == (size_t) -1)
+ /* An invalid multibyte sequence was encountered. */
+ {
+ if (!(flags & MBSW_REJECT_INVALID))
+ {
+ p++;
+ width++;
+ break;
+ }
+ else
+ return -1;
+ }
+
+ if (bytes == (size_t) -2)
+ /* An incomplete multibyte character at the end. */
+ {
+ if (!(flags & MBSW_REJECT_INVALID))
+ {
+ p = plimit;
+ width++;
+ break;
+ }
+ else
+ return -1;
+ }
+
+ if (bytes == 0)
+ /* A null wide character was encountered. */
+ bytes = 1;
+
+ w = wcwidth (wc);
+ if (w >= 0)
+ /* A printable multibyte character. */
+ {
+ if (w > INT_MAX - width)
+ goto overflow;
+ width += w;
+ }
+ else
+ /* An unprintable multibyte character. */
+ if (!(flags & MBSW_REJECT_UNPRINTABLE))
+ {
+ if (!iswcntrl (wc))
+ {
+ if (width == INT_MAX)
+ goto overflow;
+ width++;
+ }
+ }
+ else
+ return -1;
+
+ p += bytes;
+ }
+ while (! mbsinit (&mbstate));
+ }
+ break;
+ }
return width;
}
-#endif
while (p < plimit)
{
unsigned char c = (unsigned char) *p++;
if (isprint (c))
- width++;
+ {
+ if (width == INT_MAX)
+ goto overflow;
+ width++;
+ }
else if (!(flags & MBSW_REJECT_UNPRINTABLE))
- width += (iscntrl (c) ? 0 : 1);
+ {
+ if (!iscntrl (c))
+ {
+ if (width == INT_MAX)
+ goto overflow;
+ width++;
+ }
+ }
else
- return -1;
+ return -1;
}
return width;
+
+ overflow:
+ return INT_MAX;
}
diff --git a/lib/mbswidth.h b/lib/mbswidth.h
index eec4ff6..b04cfe4 100644
--- a/lib/mbswidth.h
+++ b/lib/mbswidth.h
@@ -1,10 +1,10 @@
/* Determine the number of screen columns needed for a string.
- Copyright (C) 2000-2004, 2007 Free Software Foundation, Inc.
+ Copyright (C) 2000-2004, 2007, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -12,8 +12,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <stddef.h>
@@ -44,7 +43,7 @@ extern "C" {
/* If this bit is set, return -1 upon finding a non-printable character.
Otherwise, assume unprintable characters have width 0 if they are
control characters and 1 otherwise. */
-#define MBSW_REJECT_UNPRINTABLE 2
+#define MBSW_REJECT_UNPRINTABLE 2
/* Returns the number of screen columns needed for STRING. */
diff --git a/lib/mbtowc-impl.h b/lib/mbtowc-impl.h
new file mode 100644
index 0000000..4be2994
--- /dev/null
+++ b/lib/mbtowc-impl.h
@@ -0,0 +1,44 @@
+/* Convert multibyte character to wide character.
+ Copyright (C) 2011-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2011.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+/* We don't need a static internal state, because the encoding is not state
+ dependent, and when mbrtowc returns (size_t)(-2). we throw the result
+ away. */
+
+int
+mbtowc (wchar_t *pwc, const char *s, size_t n)
+{
+ if (s == NULL)
+ return 0;
+ else
+ {
+ mbstate_t state;
+ wchar_t wc;
+ size_t result;
+
+ memset (&state, 0, sizeof (mbstate_t));
+ result = mbrtowc (&wc, s, n, &state);
+ if (result == (size_t)-1 || result == (size_t)-2)
+ {
+ errno = EILSEQ;
+ return -1;
+ }
+ if (pwc != NULL)
+ *pwc = wc;
+ return (wc == 0 ? 0 : result);
+ }
+}
diff --git a/lib/mbtowc.c b/lib/mbtowc.c
new file mode 100644
index 0000000..fb2b651
--- /dev/null
+++ b/lib/mbtowc.c
@@ -0,0 +1,26 @@
+/* Convert multibyte character to wide character.
+ Copyright (C) 2011-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2011.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+#include <stdlib.h>
+
+#include <errno.h>
+#include <string.h>
+#include <wchar.h>
+
+#include "mbtowc-impl.h"
diff --git a/lib/mbuiter.c b/lib/mbuiter.c
new file mode 100644
index 0000000..9167580
--- /dev/null
+++ b/lib/mbuiter.c
@@ -0,0 +1,3 @@
+#include <config.h>
+#define MBUITER_INLINE _GL_EXTERN_INLINE
+#include "mbuiter.h"
diff --git a/lib/mbuiter.h b/lib/mbuiter.h
index e6ad488..aad4fea 100644
--- a/lib/mbuiter.h
+++ b/lib/mbuiter.h
@@ -1,10 +1,10 @@
/* Iterating through multibyte strings: macros for multi-byte encodings.
- Copyright (C) 2001, 2005, 2007 Free Software Foundation, Inc.
+ Copyright (C) 2001, 2005, 2007, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -12,8 +12,7 @@
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, write to the Free Software Foundation,
- Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Bruno Haible <bruno@clisp.org>. */
@@ -56,9 +55,9 @@
initializes the iterator, starting at startptr.
mbui_avail (iter)
- returns true if there are more multibyte chracters available before
+ returns true if there are more multibyte characters available before
the end of string is reached. In this case, mbui_cur (iter) is
- initialized to the next multibyte chracter.
+ initialized to the next multibyte character.
mbui_advance (iter)
advances the iterator by one multibyte character.
@@ -78,13 +77,13 @@
Here are the function prototypes of the macros.
- extern void mbui_init (mbui_iterator_t iter, const char *startptr);
- extern bool mbui_avail (mbui_iterator_t iter);
- extern void mbui_advance (mbui_iterator_t iter);
- extern mbchar_t mbui_cur (mbui_iterator_t iter);
- extern const char * mbui_cur_ptr (mbui_iterator_t iter);
- extern void mbui_reloc (mbui_iterator_t iter, ptrdiff_t ptrdiff);
- extern void mbui_copy (mbui_iterator_t *new, const mbui_iterator_t *old);
+ extern void mbui_init (mbui_iterator_t iter, const char *startptr);
+ extern bool mbui_avail (mbui_iterator_t iter);
+ extern void mbui_advance (mbui_iterator_t iter);
+ extern mbchar_t mbui_cur (mbui_iterator_t iter);
+ extern const char * mbui_cur_ptr (mbui_iterator_t iter);
+ extern void mbui_reloc (mbui_iterator_t iter, ptrdiff_t ptrdiff);
+ extern void mbui_copy (mbui_iterator_t *new, const mbui_iterator_t *old);
*/
#ifndef _MBUITER_H
@@ -92,6 +91,7 @@
#include <assert.h>
#include <stdbool.h>
+#include <stddef.h>
#include <stdlib.h>
#include <string.h>
@@ -106,21 +106,29 @@
#include "mbchar.h"
#include "strnlen1.h"
+#ifndef _GL_INLINE_HEADER_BEGIN
+ #error "Please include config.h first."
+#endif
+_GL_INLINE_HEADER_BEGIN
+#ifndef MBUITER_INLINE
+# define MBUITER_INLINE _GL_INLINE
+#endif
+
struct mbuiter_multi
{
- bool in_shift; /* true if next byte may not be interpreted as ASCII */
- mbstate_t state; /* if in_shift: current shift state */
- bool next_done; /* true if mbui_avail has already filled the following */
- struct mbchar cur; /* the current character:
- const char *cur.ptr pointer to current character
- The following are only valid after mbui_avail.
- size_t cur.bytes number of bytes of current character
- bool cur.wc_valid true if wc is a valid wide character
- wchar_t cur.wc if wc_valid: the current character
- */
+ bool in_shift; /* true if next byte may not be interpreted as ASCII */
+ mbstate_t state; /* if in_shift: current shift state */
+ bool next_done; /* true if mbui_avail has already filled the following */
+ struct mbchar cur; /* the current character:
+ const char *cur.ptr pointer to current character
+ The following are only valid after mbui_avail.
+ size_t cur.bytes number of bytes of current character
+ bool cur.wc_valid true if wc is a valid wide character
+ wchar_t cur.wc if wc_valid: the current character
+ */
};
-static inline void
+MBUITER_INLINE void
mbuiter_multi_next (struct mbuiter_multi *iter)
{
if (iter->next_done)
@@ -131,8 +139,8 @@ mbuiter_multi_next (struct mbuiter_multi *iter)
if (is_basic (*iter->cur.ptr))
{
/* These characters are part of the basic character set. ISO C 99
- guarantees that their wide character code is identical to their
- char code. */
+ guarantees that their wide character code is identical to their
+ char code. */
iter->cur.bytes = 1;
iter->cur.wc = *iter->cur.ptr;
iter->cur.wc_valid = true;
@@ -143,51 +151,51 @@ mbuiter_multi_next (struct mbuiter_multi *iter)
iter->in_shift = true;
with_shift:
iter->cur.bytes = mbrtowc (&iter->cur.wc, iter->cur.ptr,
- strnlen1 (iter->cur.ptr, MB_CUR_MAX),
- &iter->state);
+ strnlen1 (iter->cur.ptr, MB_CUR_MAX),
+ &iter->state);
if (iter->cur.bytes == (size_t) -1)
- {
- /* An invalid multibyte sequence was encountered. */
- iter->cur.bytes = 1;
- iter->cur.wc_valid = false;
- /* Whether to set iter->in_shift = false and reset iter->state
- or not is not very important; the string is bogus anyway. */
- }
+ {
+ /* An invalid multibyte sequence was encountered. */
+ iter->cur.bytes = 1;
+ iter->cur.wc_valid = false;
+ /* Whether to set iter->in_shift = false and reset iter->state
+ or not is not very important; the string is bogus anyway. */
+ }
else if (iter->cur.bytes == (size_t) -2)
- {
- /* An incomplete multibyte character at the end. */
- iter->cur.bytes = strlen (iter->cur.ptr);
- iter->cur.wc_valid = false;
- /* Whether to set iter->in_shift = false and reset iter->state
- or not is not important; the string end is reached anyway. */
- }
+ {
+ /* An incomplete multibyte character at the end. */
+ iter->cur.bytes = strlen (iter->cur.ptr);
+ iter->cur.wc_valid = false;
+ /* Whether to set iter->in_shift = false and reset iter->state
+ or not is not important; the string end is reached anyway. */
+ }
else
- {
- if (iter->cur.bytes == 0)
- {
- /* A null wide character was encountered. */
- iter->cur.bytes = 1;
- assert (*iter->cur.ptr == '\0');
- assert (iter->cur.wc == 0);
- }
- iter->cur.wc_valid = true;
-
- /* When in the initial state, we can go back treating ASCII
- characters more quickly. */
- if (mbsinit (&iter->state))
- iter->in_shift = false;
- }
+ {
+ if (iter->cur.bytes == 0)
+ {
+ /* A null wide character was encountered. */
+ iter->cur.bytes = 1;
+ assert (*iter->cur.ptr == '\0');
+ assert (iter->cur.wc == 0);
+ }
+ iter->cur.wc_valid = true;
+
+ /* When in the initial state, we can go back treating ASCII
+ characters more quickly. */
+ if (mbsinit (&iter->state))
+ iter->in_shift = false;
+ }
}
iter->next_done = true;
}
-static inline void
+MBUITER_INLINE void
mbuiter_multi_reloc (struct mbuiter_multi *iter, ptrdiff_t ptrdiff)
{
iter->cur.ptr += ptrdiff;
}
-static inline void
+MBUITER_INLINE void
mbuiter_multi_copy (struct mbuiter_multi *new_iter, const struct mbuiter_multi *old_iter)
{
if ((new_iter->in_shift = old_iter->in_shift))
@@ -219,4 +227,6 @@ typedef struct mbuiter_multi mbui_iterator_t;
/* Copying an iterator. */
#define mbui_copy mbuiter_multi_copy
+_GL_INLINE_HEADER_END
+
#endif /* _MBUITER_H */
diff --git a/lib/md5.c b/lib/md5.c
index 917a899..62d247e 100644
--- a/lib/md5.c
+++ b/lib/md5.c
@@ -1,12 +1,12 @@
/* Functions to compute MD5 message digest of files or memory blocks.
according to the definition of MD5 in RFC 1321 from April 1992.
- Copyright (C) 1995,1996,1997,1999,2000,2001,2005,2006
- Free Software Foundation, Inc.
+ Copyright (C) 1995-1997, 1999-2001, 2005-2006, 2008-2016 Free Software
+ Foundation, Inc.
This file is part of the GNU C Library.
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 2, or (at your option) any
+ Free Software Foundation; either version 3, or (at your option) any
later version.
This program is distributed in the hope that it will be useful,
@@ -15,16 +15,19 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program; if not, see <http://www.gnu.org/licenses/>. */
/* Written by Ulrich Drepper <drepper@gnu.ai.mit.edu>, 1995. */
#include <config.h>
+#if HAVE_OPENSSL_MD5
+# define GL_OPENSSL_INLINE _GL_EXTERN_INLINE
+#endif
#include "md5.h"
-#include <stddef.h>
+#include <stdalign.h>
+#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
@@ -50,17 +53,18 @@
#endif
#ifdef WORDS_BIGENDIAN
-# define SWAP(n) \
+# define SWAP(n) \
(((n) << 24) | (((n) & 0xff00) << 8) | (((n) >> 8) & 0xff00) | ((n) >> 24))
#else
# define SWAP(n) (n)
#endif
-#define BLOCKSIZE 4096
+#define BLOCKSIZE 32768
#if BLOCKSIZE % 64 != 0
# error "invalid BLOCKSIZE"
#endif
+#if ! HAVE_OPENSSL_MD5
/* This array contains the bytes used to pad the buffer to the next
64-byte boundary. (RFC 1321, 3.1: Step 1) */
static const unsigned char fillbuf[64] = { 0x80, 0 /* , 0, 0, ... */ };
@@ -80,27 +84,31 @@ md5_init_ctx (struct md5_ctx *ctx)
ctx->buflen = 0;
}
-/* Put result from CTX in first 16 bytes following RESBUF. The result
- must be in little endian byte order.
+/* Copy the 4 byte value from v into the memory location pointed to by *cp,
+ If your architecture allows unaligned access this is equivalent to
+ * (uint32_t *) cp = v */
+static void
+set_uint32 (char *cp, uint32_t v)
+{
+ memcpy (cp, &v, sizeof v);
+}
- IMPORTANT: On some systems it is required that RESBUF is correctly
- aligned for a 32-bit value. */
+/* Put result from CTX in first 16 bytes following RESBUF. The result
+ must be in little endian byte order. */
void *
md5_read_ctx (const struct md5_ctx *ctx, void *resbuf)
{
- ((uint32_t *) resbuf)[0] = SWAP (ctx->A);
- ((uint32_t *) resbuf)[1] = SWAP (ctx->B);
- ((uint32_t *) resbuf)[2] = SWAP (ctx->C);
- ((uint32_t *) resbuf)[3] = SWAP (ctx->D);
+ char *r = resbuf;
+ set_uint32 (r + 0 * sizeof ctx->A, SWAP (ctx->A));
+ set_uint32 (r + 1 * sizeof ctx->B, SWAP (ctx->B));
+ set_uint32 (r + 2 * sizeof ctx->C, SWAP (ctx->C));
+ set_uint32 (r + 3 * sizeof ctx->D, SWAP (ctx->D));
return resbuf;
}
/* Process the remaining bytes in the internal buffer and the usual
- prolog according to the standard and write the result to RESBUF.
-
- IMPORTANT: On some systems it is required that RESBUF is correctly
- aligned for a 32-bit value. */
+ prolog according to the standard and write the result to RESBUF. */
void *
md5_finish_ctx (struct md5_ctx *ctx, void *resbuf)
{
@@ -124,6 +132,7 @@ md5_finish_ctx (struct md5_ctx *ctx, void *resbuf)
return md5_read_ctx (ctx, resbuf);
}
+#endif
/* Compute MD5 message digest for bytes read from STREAM. The
resulting message digest number will be written into the 16 bytes
@@ -132,9 +141,12 @@ int
md5_stream (FILE *stream, void *resblock)
{
struct md5_ctx ctx;
- char buffer[BLOCKSIZE + 72];
size_t sum;
+ char *buffer = malloc (BLOCKSIZE + 72);
+ if (!buffer)
+ return 1;
+
/* Initialize the computation context. */
md5_init_ctx (&ctx);
@@ -149,30 +161,33 @@ md5_stream (FILE *stream, void *resblock)
/* Read block. Take care for partial reads. */
while (1)
- {
- n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
-
- sum += n;
-
- if (sum == BLOCKSIZE)
- break;
-
- if (n == 0)
- {
- /* Check for the error flag IFF N == 0, so that we don't
- exit the loop after a partial read due to e.g., EAGAIN
- or EWOULDBLOCK. */
- if (ferror (stream))
- return 1;
- goto process_partial_block;
- }
-
- /* We've read at least one byte, so ignore errors. But always
- check for EOF, since feof may be true even though N > 0.
- Otherwise, we could end up calling fread after EOF. */
- if (feof (stream))
- goto process_partial_block;
- }
+ {
+ n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
+
+ sum += n;
+
+ if (sum == BLOCKSIZE)
+ break;
+
+ if (n == 0)
+ {
+ /* Check for the error flag IFF N == 0, so that we don't
+ exit the loop after a partial read due to e.g., EAGAIN
+ or EWOULDBLOCK. */
+ if (ferror (stream))
+ {
+ free (buffer);
+ return 1;
+ }
+ goto process_partial_block;
+ }
+
+ /* We've read at least one byte, so ignore errors. But always
+ check for EOF, since feof may be true even though N > 0.
+ Otherwise, we could end up calling fread after EOF. */
+ if (feof (stream))
+ goto process_partial_block;
+ }
/* Process buffer with BLOCKSIZE bytes. Note that
BLOCKSIZE % 64 == 0
@@ -188,9 +203,11 @@ process_partial_block:
/* Construct result in desired memory. */
md5_finish_ctx (&ctx, resblock);
+ free (buffer);
return 0;
}
+#if ! HAVE_OPENSSL_MD5
/* Compute MD5 message digest for LEN bytes beginning at BUFFER. The
result is always in little endian byte order, so that a byte-wise
output yields to the wanted ASCII representation of the message
@@ -225,15 +242,15 @@ md5_process_bytes (const void *buffer, size_t len, struct md5_ctx *ctx)
ctx->buflen += add;
if (ctx->buflen > 64)
- {
- md5_process_block (ctx->buffer, ctx->buflen & ~63, ctx);
+ {
+ md5_process_block (ctx->buffer, ctx->buflen & ~63, ctx);
- ctx->buflen &= 63;
- /* The regions in the following copy operation cannot overlap. */
- memcpy (ctx->buffer,
- &((char *) ctx->buffer)[(left_over + add) & ~63],
- ctx->buflen);
- }
+ ctx->buflen &= 63;
+ /* The regions in the following copy operation cannot overlap. */
+ memcpy (ctx->buffer,
+ &((char *) ctx->buffer)[(left_over + add) & ~63],
+ ctx->buflen);
+ }
buffer = (const char *) buffer + add;
len -= add;
@@ -243,22 +260,21 @@ md5_process_bytes (const void *buffer, size_t len, struct md5_ctx *ctx)
if (len >= 64)
{
#if !_STRING_ARCH_unaligned
-# define alignof(type) offsetof (struct { char c; type x; }, x)
-# define UNALIGNED_P(p) (((size_t) p) % alignof (uint32_t) != 0)
+# define UNALIGNED_P(p) ((uintptr_t) (p) % alignof (uint32_t) != 0)
if (UNALIGNED_P (buffer))
- while (len > 64)
- {
- md5_process_block (memcpy (ctx->buffer, buffer, 64), 64, ctx);
- buffer = (const char *) buffer + 64;
- len -= 64;
- }
+ while (len > 64)
+ {
+ md5_process_block (memcpy (ctx->buffer, buffer, 64), 64, ctx);
+ buffer = (const char *) buffer + 64;
+ len -= 64;
+ }
else
#endif
- {
- md5_process_block (buffer, len & ~63, ctx);
- buffer = (const char *) buffer + (len & ~63);
- len &= 63;
- }
+ {
+ md5_process_block (buffer, len & ~63, ctx);
+ buffer = (const char *) buffer + (len & ~63);
+ len &= 63;
+ }
}
/* Move remaining bytes in internal buffer. */
@@ -269,11 +285,11 @@ md5_process_bytes (const void *buffer, size_t len, struct md5_ctx *ctx)
memcpy (&((char *) ctx->buffer)[left_over], buffer, len);
left_over += len;
if (left_over >= 64)
- {
- md5_process_block (ctx->buffer, 64, ctx);
- left_over -= 64;
- memcpy (ctx->buffer, &ctx->buffer[16], left_over);
- }
+ {
+ md5_process_block (ctx->buffer, 64, ctx);
+ left_over -= 64;
+ memcpy (ctx->buffer, &ctx->buffer[16], left_over);
+ }
ctx->buflen = left_over;
}
}
@@ -302,13 +318,13 @@ md5_process_block (const void *buffer, size_t len, struct md5_ctx *ctx)
uint32_t B = ctx->B;
uint32_t C = ctx->C;
uint32_t D = ctx->D;
+ uint32_t lolen = len;
/* First increment the byte count. RFC 1321 specifies the possible
length of the file up to 2^64 bits. Here we only compute the
number of bytes. Do a double word increment. */
- ctx->total[0] += len;
- if (ctx->total[0] < len)
- ++ctx->total[1];
+ ctx->total[0] += lolen;
+ ctx->total[1] += (len >> 31 >> 1) + (ctx->total[0] < lolen);
/* Process all bytes in the buffer with 64 bytes in each round of
the loop. */
@@ -327,14 +343,14 @@ md5_process_block (const void *buffer, size_t len, struct md5_ctx *ctx)
before the computation. To reduce the work for the next steps
we store the swapped words in the array CORRECT_WORDS. */
-#define OP(a, b, c, d, s, T) \
- do \
- { \
- a += FF (b, c, d) + (*cwp++ = SWAP (*words)) + T; \
- ++words; \
- CYCLIC (a, s); \
- a += b; \
- } \
+#define OP(a, b, c, d, s, T) \
+ do \
+ { \
+ a += FF (b, c, d) + (*cwp++ = SWAP (*words)) + T; \
+ ++words; \
+ CYCLIC (a, s); \
+ a += b; \
+ } \
while (0)
/* It is unfortunate that C does not provide an operator for
@@ -373,13 +389,13 @@ md5_process_block (const void *buffer, size_t len, struct md5_ctx *ctx)
in CORRECT_WORDS. Redefine the macro to take an additional first
argument specifying the function to use. */
#undef OP
-#define OP(f, a, b, c, d, k, s, T) \
- do \
- { \
- a += f (b, c, d) + correct_words[k] + T; \
- CYCLIC (a, s); \
- a += b; \
- } \
+#define OP(f, a, b, c, d, k, s, T) \
+ do \
+ { \
+ a += f (b, c, d) + correct_words[k] + T; \
+ CYCLIC (a, s); \
+ a += b; \
+ } \
while (0)
/* Round 2. */
@@ -449,3 +465,4 @@ md5_process_block (const void *buffer, size_t len, struct md5_ctx *ctx)
ctx->C = C;
ctx->D = D;
}
+#endif
diff --git a/lib/md5.h b/lib/md5.h
index c737040..a0a8c5e 100644
--- a/lib/md5.h
+++ b/lib/md5.h
@@ -1,12 +1,12 @@
/* Declaration of functions and data types used for MD5 sum computing
library functions.
- Copyright (C) 1995-1997,1999,2000,2001,2004,2005,2006
- Free Software Foundation, Inc.
+ Copyright (C) 1995-1997, 1999-2001, 2004-2006, 2008-2016 Free Software
+ Foundation, Inc.
This file is part of the GNU C Library.
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 2, or (at your option) any
+ Free Software Foundation; either version 3, or (at your option) any
later version.
This program is distributed in the hope that it will be useful,
@@ -15,8 +15,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program; if not, see <http://www.gnu.org/licenses/>. */
#ifndef _MD5_H
#define _MD5_H 1
@@ -24,12 +23,16 @@
#include <stdio.h>
#include <stdint.h>
+# if HAVE_OPENSSL_MD5
+# include <openssl/md5.h>
+# endif
+
#define MD5_DIGEST_SIZE 16
#define MD5_BLOCK_SIZE 64
#ifndef __GNUC_PREREQ
# if defined __GNUC__ && defined __GNUC_MINOR__
-# define __GNUC_PREREQ(maj, min) \
+# define __GNUC_PREREQ(maj, min) \
((__GNUC__ << 16) + __GNUC_MINOR__ >= ((maj) << 16) + (min))
# else
# define __GNUC_PREREQ(maj, min) 0
@@ -38,7 +41,7 @@
#ifndef __THROW
# if defined __cplusplus && __GNUC_PREREQ (2,8)
-# define __THROW throw ()
+# define __THROW throw ()
# else
# define __THROW
# endif
@@ -54,6 +57,14 @@
# define __md5_stream md5_stream
#endif
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# if HAVE_OPENSSL_MD5
+# define GL_OPENSSL_NAME 5
+# include "gl_openssl.h"
+# else
/* Structure to save state of computation between the single steps. */
struct md5_ctx
{
@@ -69,7 +80,7 @@ struct md5_ctx
/*
* The following three functions are build up the low level used in
- * the functions `md5_stream' and `md5_buffer'.
+ * the functions 'md5_stream' and 'md5_buffer'.
*/
/* Initialize structure containing state of computation.
@@ -81,44 +92,44 @@ extern void __md5_init_ctx (struct md5_ctx *ctx) __THROW;
starting at BUFFER.
It is necessary that LEN is a multiple of 64!!! */
extern void __md5_process_block (const void *buffer, size_t len,
- struct md5_ctx *ctx) __THROW;
+ struct md5_ctx *ctx) __THROW;
/* Starting with the result of former calls of this function (or the
initialization function update the context for the next LEN bytes
starting at BUFFER.
It is NOT required that LEN is a multiple of 64. */
extern void __md5_process_bytes (const void *buffer, size_t len,
- struct md5_ctx *ctx) __THROW;
+ struct md5_ctx *ctx) __THROW;
/* Process the remaining bytes in the buffer and put result from CTX
in first 16 bytes following RESBUF. The result is always in little
endian byte order, so that a byte-wise output yields to the wanted
- ASCII representation of the message digest.
-
- IMPORTANT: On some systems, RESBUF must be aligned to a 32-bit
- boundary. */
+ ASCII representation of the message digest. */
extern void *__md5_finish_ctx (struct md5_ctx *ctx, void *resbuf) __THROW;
/* Put result from CTX in first 16 bytes following RESBUF. The result is
always in little endian byte order, so that a byte-wise output yields
- to the wanted ASCII representation of the message digest.
-
- IMPORTANT: On some systems, RESBUF must be aligned to a 32-bit
- boundary. */
+ to the wanted ASCII representation of the message digest. */
extern void *__md5_read_ctx (const struct md5_ctx *ctx, void *resbuf) __THROW;
-/* Compute MD5 message digest for bytes read from STREAM. The
- resulting message digest number will be written into the 16 bytes
- beginning at RESBLOCK. */
-extern int __md5_stream (FILE *stream, void *resblock) __THROW;
-
/* Compute MD5 message digest for LEN bytes beginning at BUFFER. The
result is always in little endian byte order, so that a byte-wise
output yields to the wanted ASCII representation of the message
digest. */
extern void *__md5_buffer (const char *buffer, size_t len,
- void *resblock) __THROW;
+ void *resblock) __THROW;
+
+# endif
+/* Compute MD5 message digest for bytes read from STREAM. The
+ resulting message digest number will be written into the 16 bytes
+ beginning at RESBLOCK. */
+extern int __md5_stream (FILE *stream, void *resblock) __THROW;
+
+
+# ifdef __cplusplus
+}
+# endif
#endif /* md5.h */
diff --git a/lib/memcasecmp.c b/lib/memcasecmp.c
index cddf76a..497858e 100644
--- a/lib/memcasecmp.c
+++ b/lib/memcasecmp.c
@@ -1,10 +1,11 @@
/* Case-insensitive buffer comparator.
- Copyright (C) 1996, 1997, 2000, 2003, 2006 Free Software Foundation, Inc.
+ Copyright (C) 1996-1997, 2000, 2003, 2006, 2009-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -12,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Jim Meyering. */
@@ -41,9 +41,9 @@ memcasecmp (const void *vs1, const void *vs2, size_t n)
int U1 = toupper (u1);
int U2 = toupper (u2);
int diff = (UCHAR_MAX <= INT_MAX ? U1 - U2
- : U1 < U2 ? -1 : U2 < U1);
+ : U1 < U2 ? -1 : U2 < U1);
if (diff)
- return diff;
+ return diff;
}
return 0;
}
diff --git a/lib/memcasecmp.h b/lib/memcasecmp.h
index 5c8b1f1..2ca0cb2 100644
--- a/lib/memcasecmp.h
+++ b/lib/memcasecmp.h
@@ -1,11 +1,11 @@
/* Case-insensitive buffer comparator.
- Copyright (C) 1996, 1998, 2003 Free Software Foundation, Inc.
+ Copyright (C) 1996, 1998, 2003, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,11 +13,10 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Jim Meyering. */
#include <stddef.h>
-int memcasecmp (const void *vs1, const void *vs2, size_t n);
+int memcasecmp (const void *vs1, const void *vs2, size_t n) _GL_ATTRIBUTE_PURE;
diff --git a/lib/memchr.c b/lib/memchr.c
index d44ad6d..b565542 100644
--- a/lib/memchr.c
+++ b/lib/memchr.c
@@ -1,5 +1,5 @@
-/* Copyright (C) 1991, 1993, 1996, 1997, 1999, 2000, 2003, 2004, 2006 Free
- Software Foundation, Inc.
+/* Copyright (C) 1991, 1993, 1996-1997, 1999-2000, 2003-2004, 2006, 2008-2016
+ Free Software Foundation, Inc.
Based on strlen implementation by Torbjorn Granlund (tege@sics.se),
with help from Dan Sahlin (dan@sics.se) and
@@ -10,9 +10,9 @@
NOTE: The canonical source of this file is maintained with the GNU C Library.
Bugs can be reported to bug-glibc@prep.ai.mit.edu.
-This program is free software; you can redistribute it and/or modify it
+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 2, or (at your option) any
+Free Software Foundation; either version 3 of the License, or any
later version.
This program is distributed in the hope that it will be useful,
@@ -21,8 +21,7 @@ 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, write to the Free Software Foundation,
-Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifndef _LIBC
# include <config.h>
@@ -46,155 +45,127 @@ Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
# define BP_SYM(sym) sym
#endif
-#undef memchr
#undef __memchr
+#ifdef _LIBC
+# undef memchr
+#endif
+
+#ifndef weak_alias
+# define __memchr memchr
+#endif
/* Search no more than N bytes of S for C. */
void *
__memchr (void const *s, int c_in, size_t n)
{
+ /* On 32-bit hardware, choosing longword to be a 32-bit unsigned
+ long instead of a 64-bit uintmax_t tends to give better
+ performance. On 64-bit hardware, unsigned long is generally 64
+ bits already. Change this typedef to experiment with
+ performance. */
+ typedef unsigned long int longword;
+
const unsigned char *char_ptr;
- const unsigned long int *longword_ptr;
- unsigned long int longword, magic_bits, charmask;
+ const longword *longword_ptr;
+ longword repeated_one;
+ longword repeated_c;
unsigned reg_char c;
- int i;
c = (unsigned char) c_in;
- /* Handle the first few characters by reading one character at a time.
+ /* Handle the first few bytes by reading one byte at a time.
Do this until CHAR_PTR is aligned on a longword boundary. */
for (char_ptr = (const unsigned char *) s;
- n > 0 && (size_t) char_ptr % sizeof longword != 0;
+ n > 0 && (size_t) char_ptr % sizeof (longword) != 0;
--n, ++char_ptr)
if (*char_ptr == c)
return (void *) char_ptr;
+ longword_ptr = (const longword *) char_ptr;
+
/* All these elucidatory comments refer to 4-byte longwords,
but the theory applies equally well to any size longwords. */
- longword_ptr = (const unsigned long int *) char_ptr;
-
- /* Bits 31, 24, 16, and 8 of this number are zero. Call these bits
- the "holes." Note that there is a hole just to the left of
- each byte, with an extra at the end:
-
- bits: 01111110 11111110 11111110 11111111
- bytes: AAAAAAAA BBBBBBBB CCCCCCCC DDDDDDDD
-
- The 1-bits make sure that carries propagate to the next 0-bit.
- The 0-bits provide holes for carries to fall into. */
-
- /* Set MAGIC_BITS to be this pattern of 1 and 0 bits.
- Set CHARMASK to be a longword, each of whose bytes is C. */
-
- magic_bits = 0xfefefefe;
- charmask = c | (c << 8);
- charmask |= charmask << 16;
-#if 0xffffffffU < ULONG_MAX
- magic_bits |= magic_bits << 32;
- charmask |= charmask << 32;
- if (8 < sizeof longword)
- for (i = 64; i < sizeof longword * 8; i *= 2)
- {
- magic_bits |= magic_bits << i;
- charmask |= charmask << i;
- }
-#endif
- magic_bits = (ULONG_MAX >> 1) & (magic_bits | 1);
+ /* Compute auxiliary longword values:
+ repeated_one is a value which has a 1 in every byte.
+ repeated_c has c in every byte. */
+ repeated_one = 0x01010101;
+ repeated_c = c | (c << 8);
+ repeated_c |= repeated_c << 16;
+ if (0xffffffffU < (longword) -1)
+ {
+ repeated_one |= repeated_one << 31 << 1;
+ repeated_c |= repeated_c << 31 << 1;
+ if (8 < sizeof (longword))
+ {
+ size_t i;
+
+ for (i = 64; i < sizeof (longword) * 8; i *= 2)
+ {
+ repeated_one |= repeated_one << i;
+ repeated_c |= repeated_c << i;
+ }
+ }
+ }
- /* Instead of the traditional loop which tests each character,
- we will test a longword at a time. The tricky part is testing
- if *any of the four* bytes in the longword in question are zero. */
- while (n >= sizeof longword)
+ /* Instead of the traditional loop which tests each byte, we will test a
+ longword at a time. The tricky part is testing if *any of the four*
+ bytes in the longword in question are equal to c. We first use an xor
+ with repeated_c. This reduces the task to testing whether *any of the
+ four* bytes in longword1 is zero.
+
+ We compute tmp =
+ ((longword1 - repeated_one) & ~longword1) & (repeated_one << 7).
+ That is, we perform the following operations:
+ 1. Subtract repeated_one.
+ 2. & ~longword1.
+ 3. & a mask consisting of 0x80 in every byte.
+ Consider what happens in each byte:
+ - If a byte of longword1 is zero, step 1 and 2 transform it into 0xff,
+ and step 3 transforms it into 0x80. A carry can also be propagated
+ to more significant bytes.
+ - If a byte of longword1 is nonzero, let its lowest 1 bit be at
+ position k (0 <= k <= 7); so the lowest k bits are 0. After step 1,
+ the byte ends in a single bit of value 0 and k bits of value 1.
+ After step 2, the result is just k bits of value 1: 2^k - 1. After
+ step 3, the result is 0. And no carry is produced.
+ So, if longword1 has only non-zero bytes, tmp is zero.
+ Whereas if longword1 has a zero byte, call j the position of the least
+ significant zero byte. Then the result has a zero at positions 0, ...,
+ j-1 and a 0x80 at position j. We cannot predict the result at the more
+ significant bytes (positions j+1..3), but it does not matter since we
+ already have a non-zero bit at position 8*j+7.
+
+ So, the test whether any byte in longword1 is zero is equivalent to
+ testing whether tmp is nonzero. */
+
+ while (n >= sizeof (longword))
{
- /* We tentatively exit the loop if adding MAGIC_BITS to
- LONGWORD fails to change any of the hole bits of LONGWORD.
-
- 1) Is this safe? Will it catch all the zero bytes?
- Suppose there is a byte with all zeros. Any carry bits
- propagating from its left will fall into the hole at its
- least significant bit and stop. Since there will be no
- carry from its most significant bit, the LSB of the
- byte to the left will be unchanged, and the zero will be
- detected.
-
- 2) Is this worthwhile? Will it ignore everything except
- zero bytes? Suppose every byte of LONGWORD has a bit set
- somewhere. There will be a carry into bit 8. If bit 8
- is set, this will carry into bit 16. If bit 8 is clear,
- one of bits 9-15 must be set, so there will be a carry
- into bit 16. Similarly, there will be a carry into bit
- 24. If one of bits 24-30 is set, there will be a carry
- into bit 31, so all of the hole bits will be changed.
-
- The one misfire occurs when bits 24-30 are clear and bit
- 31 is set; in this case, the hole at bit 31 is not
- changed. If we had access to the processor carry flag,
- we could close this loophole by putting the fourth hole
- at bit 32!
-
- So it ignores everything except 128's, when they're aligned
- properly.
-
- 3) But wait! Aren't we looking for C, not zero?
- Good point. So what we do is XOR LONGWORD with a longword,
- each of whose bytes is C. This turns each byte that is C
- into a zero. */
-
- longword = *longword_ptr++ ^ charmask;
-
- /* Add MAGIC_BITS to LONGWORD. */
- if ((((longword + magic_bits)
-
- /* Set those bits that were unchanged by the addition. */
- ^ ~longword)
-
- /* Look at only the hole bits. If any of the hole bits
- are unchanged, most likely one of the bytes was a
- zero. */
- & ~magic_bits) != 0)
- {
- /* Which of the bytes was C? If none of them were, it was
- a misfire; continue the search. */
-
- const unsigned char *cp = (const unsigned char *) (longword_ptr - 1);
-
- if (cp[0] == c)
- return (void *) cp;
- if (cp[1] == c)
- return (void *) &cp[1];
- if (cp[2] == c)
- return (void *) &cp[2];
- if (cp[3] == c)
- return (void *) &cp[3];
- if (4 < sizeof longword && cp[4] == c)
- return (void *) &cp[4];
- if (5 < sizeof longword && cp[5] == c)
- return (void *) &cp[5];
- if (6 < sizeof longword && cp[6] == c)
- return (void *) &cp[6];
- if (7 < sizeof longword && cp[7] == c)
- return (void *) &cp[7];
- if (8 < sizeof longword)
- for (i = 8; i < sizeof longword; i++)
- if (cp[i] == c)
- return (void *) &cp[i];
- }
-
- n -= sizeof longword;
+ longword longword1 = *longword_ptr ^ repeated_c;
+
+ if ((((longword1 - repeated_one) & ~longword1)
+ & (repeated_one << 7)) != 0)
+ break;
+ longword_ptr++;
+ n -= sizeof (longword);
}
char_ptr = (const unsigned char *) longword_ptr;
- while (n-- > 0)
+ /* At this point, we know that either n < sizeof (longword), or one of the
+ sizeof (longword) bytes starting at char_ptr is == c. On little-endian
+ machines, we could determine the first such byte without any further
+ memory accesses, just by looking at the tmp result from the last loop
+ iteration. But this does not work on big-endian machines. Choose code
+ that works in both cases. */
+
+ for (; n > 0; --n, ++char_ptr)
{
if (*char_ptr == c)
- return (void *) char_ptr;
- else
- ++char_ptr;
+ return (void *) char_ptr;
}
- return 0;
+ return NULL;
}
#ifdef weak_alias
weak_alias (__memchr, BP_SYM (memchr))
diff --git a/lib/memchr.valgrind b/lib/memchr.valgrind
new file mode 100644
index 0000000..60f247e
--- /dev/null
+++ b/lib/memchr.valgrind
@@ -0,0 +1,14 @@
+# Suppress a valgrind message about use of uninitialized memory in memchr().
+# POSIX states that when the character is found, memchr must not read extra
+# bytes in an overestimated length (for example, where memchr is used to
+# implement strnlen). However, we use a safe word read to provide a speedup.
+{
+ memchr-value4
+ Memcheck:Value4
+ fun:rpl_memchr
+}
+{
+ memchr-value8
+ Memcheck:Value8
+ fun:rpl_memchr
+}
diff --git a/lib/memchr2.c b/lib/memchr2.c
new file mode 100644
index 0000000..66a217d
--- /dev/null
+++ b/lib/memchr2.c
@@ -0,0 +1,169 @@
+/* Copyright (C) 1991, 1993, 1996-1997, 1999-2000, 2003-2004, 2006, 2008-2016
+ Free Software Foundation, Inc.
+
+ Based on strlen implementation by Torbjorn Granlund (tege@sics.se),
+ with help from Dan Sahlin (dan@sics.se) and
+ commentary by Jim Blandy (jimb@ai.mit.edu);
+ adaptation to memchr suggested by Dick Karpinski (dick@cca.ucsf.edu),
+ and implemented in glibc by Roland McGrath (roland@ai.mit.edu).
+ Extension to memchr2 implemented by Eric Blake (ebb9@byu.net).
+
+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 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+#include "memchr2.h"
+
+#include <limits.h>
+#include <stdint.h>
+#include <string.h>
+
+/* Return the first address of either C1 or C2 (treated as unsigned
+ char) that occurs within N bytes of the memory region S. If
+ neither byte appears, return NULL. */
+void *
+memchr2 (void const *s, int c1_in, int c2_in, size_t n)
+{
+ /* On 32-bit hardware, choosing longword to be a 32-bit unsigned
+ long instead of a 64-bit uintmax_t tends to give better
+ performance. On 64-bit hardware, unsigned long is generally 64
+ bits already. Change this typedef to experiment with
+ performance. */
+ typedef unsigned long int longword;
+
+ const unsigned char *char_ptr;
+ void const *void_ptr;
+ const longword *longword_ptr;
+ longword repeated_one;
+ longword repeated_c1;
+ longword repeated_c2;
+ unsigned char c1;
+ unsigned char c2;
+
+ c1 = (unsigned char) c1_in;
+ c2 = (unsigned char) c2_in;
+
+ if (c1 == c2)
+ return memchr (s, c1, n);
+
+ /* Handle the first few bytes by reading one byte at a time.
+ Do this until VOID_PTR is aligned on a longword boundary. */
+ for (void_ptr = s;
+ n > 0 && (uintptr_t) void_ptr % sizeof (longword) != 0;
+ --n)
+ {
+ char_ptr = void_ptr;
+ if (*char_ptr == c1 || *char_ptr == c2)
+ return (void *) void_ptr;
+ void_ptr = char_ptr + 1;
+ }
+
+ longword_ptr = void_ptr;
+
+ /* All these elucidatory comments refer to 4-byte longwords,
+ but the theory applies equally well to any size longwords. */
+
+ /* Compute auxiliary longword values:
+ repeated_one is a value which has a 1 in every byte.
+ repeated_c1 has c1 in every byte.
+ repeated_c2 has c2 in every byte. */
+ repeated_one = 0x01010101;
+ repeated_c1 = c1 | (c1 << 8);
+ repeated_c2 = c2 | (c2 << 8);
+ repeated_c1 |= repeated_c1 << 16;
+ repeated_c2 |= repeated_c2 << 16;
+ if (0xffffffffU < (longword) -1)
+ {
+ repeated_one |= repeated_one << 31 << 1;
+ repeated_c1 |= repeated_c1 << 31 << 1;
+ repeated_c2 |= repeated_c2 << 31 << 1;
+ if (8 < sizeof (longword))
+ {
+ size_t i;
+
+ for (i = 64; i < sizeof (longword) * 8; i *= 2)
+ {
+ repeated_one |= repeated_one << i;
+ repeated_c1 |= repeated_c1 << i;
+ repeated_c2 |= repeated_c2 << i;
+ }
+ }
+ }
+
+ /* Instead of the traditional loop which tests each byte, we will test a
+ longword at a time. The tricky part is testing if *any of the four*
+ bytes in the longword in question are equal to c1 or c2. We first use
+ an xor with repeated_c1 and repeated_c2, respectively. This reduces
+ the task to testing whether *any of the four* bytes in longword1 or
+ longword2 is zero.
+
+ Let's consider longword1. We compute tmp1 =
+ ((longword1 - repeated_one) & ~longword1) & (repeated_one << 7).
+ That is, we perform the following operations:
+ 1. Subtract repeated_one.
+ 2. & ~longword1.
+ 3. & a mask consisting of 0x80 in every byte.
+ Consider what happens in each byte:
+ - If a byte of longword1 is zero, step 1 and 2 transform it into 0xff,
+ and step 3 transforms it into 0x80. A carry can also be propagated
+ to more significant bytes.
+ - If a byte of longword1 is nonzero, let its lowest 1 bit be at
+ position k (0 <= k <= 7); so the lowest k bits are 0. After step 1,
+ the byte ends in a single bit of value 0 and k bits of value 1.
+ After step 2, the result is just k bits of value 1: 2^k - 1. After
+ step 3, the result is 0. And no carry is produced.
+ So, if longword1 has only non-zero bytes, tmp1 is zero.
+ Whereas if longword1 has a zero byte, call j the position of the least
+ significant zero byte. Then the result has a zero at positions 0, ...,
+ j-1 and a 0x80 at position j. We cannot predict the result at the more
+ significant bytes (positions j+1..3), but it does not matter since we
+ already have a non-zero bit at position 8*j+7.
+
+ Similarly, we compute tmp2 =
+ ((longword2 - repeated_one) & ~longword2) & (repeated_one << 7).
+
+ The test whether any byte in longword1 or longword2 is zero is equivalent
+ to testing whether tmp1 is nonzero or tmp2 is nonzero. We can combine
+ this into a single test, whether (tmp1 | tmp2) is nonzero. */
+
+ while (n >= sizeof (longword))
+ {
+ longword longword1 = *longword_ptr ^ repeated_c1;
+ longword longword2 = *longword_ptr ^ repeated_c2;
+
+ if (((((longword1 - repeated_one) & ~longword1)
+ | ((longword2 - repeated_one) & ~longword2))
+ & (repeated_one << 7)) != 0)
+ break;
+ longword_ptr++;
+ n -= sizeof (longword);
+ }
+
+ char_ptr = (const unsigned char *) longword_ptr;
+
+ /* At this point, we know that either n < sizeof (longword), or one of the
+ sizeof (longword) bytes starting at char_ptr is == c1 or == c2. On
+ little-endian machines, we could determine the first such byte without
+ any further memory accesses, just by looking at the (tmp1 | tmp2) result
+ from the last loop iteration. But this does not work on big-endian
+ machines. Choose code that works in both cases. */
+
+ for (; n > 0; --n, ++char_ptr)
+ {
+ if (*char_ptr == c1 || *char_ptr == c2)
+ return (void *) char_ptr;
+ }
+
+ return NULL;
+}
diff --git a/lib/memchr2.h b/lib/memchr2.h
new file mode 100644
index 0000000..27f2c86
--- /dev/null
+++ b/lib/memchr2.h
@@ -0,0 +1,32 @@
+/* Scan memory for the first of two bytes.
+ Copyright (C) 2008-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <stddef.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Return the first address of either C1 or C2 (treated as unsigned
+ char) that occurs within N bytes of the memory region S. If
+ neither byte appears, return NULL. */
+
+extern void *memchr2 (void const *s, int c1, int c2, size_t n)
+ _GL_ATTRIBUTE_PURE;
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/lib/memchr2.valgrind b/lib/memchr2.valgrind
new file mode 100644
index 0000000..778fe86
--- /dev/null
+++ b/lib/memchr2.valgrind
@@ -0,0 +1,14 @@
+# Suppress a valgrind message about use of uninitialized memory in memchr2().
+# Like memchr, it is safe to overestimate the length when the terminator
+# is guaranteed to be found. In this case, we may end up reading a word
+# that is partially uninitialized, but this use is OK for a speedup.
+{
+ memchr2-value4
+ Memcheck:Value4
+ fun:memchr2
+}
+{
+ memchr2-value8
+ Memcheck:Value8
+ fun:memchr2
+}
diff --git a/lib/memcmp.c b/lib/memcmp.c
deleted file mode 100644
index cf98bfa..0000000
--- a/lib/memcmp.c
+++ /dev/null
@@ -1,363 +0,0 @@
-/* Copyright (C) 1991, 1993, 1995, 1997, 1998, 2003, 2006 Free Software
- Foundation, Inc.
-
- Contributed by Torbjorn Granlund (tege@sics.se).
-
- NOTE: The canonical source of this file is maintained with the GNU C Library.
- Bugs can be reported to bug-glibc@prep.ai.mit.edu.
-
- 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 2, 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, write to the Free Software
- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
- USA. */
-
-#ifndef _LIBC
-# include <config.h>
-#endif
-
-#include <string.h>
-
-#undef memcmp
-
-#ifdef _LIBC
-
-# include <memcopy.h>
-# include <endian.h>
-
-# if __BYTE_ORDER == __BIG_ENDIAN
-# define WORDS_BIGENDIAN
-# endif
-
-#else /* Not in the GNU C library. */
-
-# include <sys/types.h>
-
-/* Type to use for aligned memory operations.
- This should normally be the biggest type supported by a single load
- and store. Must be an unsigned type. */
-# define op_t unsigned long int
-# define OPSIZ (sizeof(op_t))
-
-/* Threshold value for when to enter the unrolled loops. */
-# define OP_T_THRES 16
-
-/* Type to use for unaligned operations. */
-typedef unsigned char byte;
-
-# ifndef WORDS_BIGENDIAN
-# define MERGE(w0, sh_1, w1, sh_2) (((w0) >> (sh_1)) | ((w1) << (sh_2)))
-# else
-# define MERGE(w0, sh_1, w1, sh_2) (((w0) << (sh_1)) | ((w1) >> (sh_2)))
-# endif
-
-#endif /* In the GNU C library. */
-
-#ifdef WORDS_BIGENDIAN
-# define CMP_LT_OR_GT(a, b) ((a) > (b) ? 1 : -1)
-#else
-# define CMP_LT_OR_GT(a, b) memcmp_bytes ((a), (b))
-#endif
-
-/* BE VERY CAREFUL IF YOU CHANGE THIS CODE! */
-
-/* The strategy of this memcmp is:
-
- 1. Compare bytes until one of the block pointers is aligned.
-
- 2. Compare using memcmp_common_alignment or
- memcmp_not_common_alignment, regarding the alignment of the other
- block after the initial byte operations. The maximum number of
- full words (of type op_t) are compared in this way.
-
- 3. Compare the few remaining bytes. */
-
-#ifndef WORDS_BIGENDIAN
-/* memcmp_bytes -- Compare A and B bytewise in the byte order of the machine.
- A and B are known to be different.
- This is needed only on little-endian machines. */
-
-# ifdef __GNUC__
-__inline
-# endif
-static int
-memcmp_bytes (long unsigned int a, long unsigned int b)
-{
- long int srcp1 = (long int) &a;
- long int srcp2 = (long int) &b;
- op_t a0, b0;
-
- do
- {
- a0 = ((byte *) srcp1)[0];
- b0 = ((byte *) srcp2)[0];
- srcp1 += 1;
- srcp2 += 1;
- }
- while (a0 == b0);
- return a0 - b0;
-}
-#endif
-
-/* memcmp_common_alignment -- Compare blocks at SRCP1 and SRCP2 with LEN `op_t'
- objects (not LEN bytes!). Both SRCP1 and SRCP2 should be aligned for
- memory operations on `op_t's. */
-#ifdef __GNUC__
-__inline
-#endif
-static int
-memcmp_common_alignment (long int srcp1, long int srcp2, size_t len)
-{
- op_t a0, a1;
- op_t b0, b1;
-
- switch (len % 4)
- {
- default: /* Avoid warning about uninitialized local variables. */
- case 2:
- a0 = ((op_t *) srcp1)[0];
- b0 = ((op_t *) srcp2)[0];
- srcp1 -= 2 * OPSIZ;
- srcp2 -= 2 * OPSIZ;
- len += 2;
- goto do1;
- case 3:
- a1 = ((op_t *) srcp1)[0];
- b1 = ((op_t *) srcp2)[0];
- srcp1 -= OPSIZ;
- srcp2 -= OPSIZ;
- len += 1;
- goto do2;
- case 0:
- if (OP_T_THRES <= 3 * OPSIZ && len == 0)
- return 0;
- a0 = ((op_t *) srcp1)[0];
- b0 = ((op_t *) srcp2)[0];
- goto do3;
- case 1:
- a1 = ((op_t *) srcp1)[0];
- b1 = ((op_t *) srcp2)[0];
- srcp1 += OPSIZ;
- srcp2 += OPSIZ;
- len -= 1;
- if (OP_T_THRES <= 3 * OPSIZ && len == 0)
- goto do0;
- /* Fall through. */
- }
-
- do
- {
- a0 = ((op_t *) srcp1)[0];
- b0 = ((op_t *) srcp2)[0];
- if (a1 != b1)
- return CMP_LT_OR_GT (a1, b1);
-
- do3:
- a1 = ((op_t *) srcp1)[1];
- b1 = ((op_t *) srcp2)[1];
- if (a0 != b0)
- return CMP_LT_OR_GT (a0, b0);
-
- do2:
- a0 = ((op_t *) srcp1)[2];
- b0 = ((op_t *) srcp2)[2];
- if (a1 != b1)
- return CMP_LT_OR_GT (a1, b1);
-
- do1:
- a1 = ((op_t *) srcp1)[3];
- b1 = ((op_t *) srcp2)[3];
- if (a0 != b0)
- return CMP_LT_OR_GT (a0, b0);
-
- srcp1 += 4 * OPSIZ;
- srcp2 += 4 * OPSIZ;
- len -= 4;
- }
- while (len != 0);
-
- /* This is the right position for do0. Please don't move
- it into the loop. */
- do0:
- if (a1 != b1)
- return CMP_LT_OR_GT (a1, b1);
- return 0;
-}
-
-/* memcmp_not_common_alignment -- Compare blocks at SRCP1 and SRCP2 with LEN
- `op_t' objects (not LEN bytes!). SRCP2 should be aligned for memory
- operations on `op_t', but SRCP1 *should be unaligned*. */
-#ifdef __GNUC__
-__inline
-#endif
-static int
-memcmp_not_common_alignment (long int srcp1, long int srcp2, size_t len)
-{
- op_t a0, a1, a2, a3;
- op_t b0, b1, b2, b3;
- op_t x;
- int shl, shr;
-
- /* Calculate how to shift a word read at the memory operation
- aligned srcp1 to make it aligned for comparison. */
-
- shl = 8 * (srcp1 % OPSIZ);
- shr = 8 * OPSIZ - shl;
-
- /* Make SRCP1 aligned by rounding it down to the beginning of the `op_t'
- it points in the middle of. */
- srcp1 &= -OPSIZ;
-
- switch (len % 4)
- {
- default: /* Avoid warning about uninitialized local variables. */
- case 2:
- a1 = ((op_t *) srcp1)[0];
- a2 = ((op_t *) srcp1)[1];
- b2 = ((op_t *) srcp2)[0];
- srcp1 -= 1 * OPSIZ;
- srcp2 -= 2 * OPSIZ;
- len += 2;
- goto do1;
- case 3:
- a0 = ((op_t *) srcp1)[0];
- a1 = ((op_t *) srcp1)[1];
- b1 = ((op_t *) srcp2)[0];
- srcp2 -= 1 * OPSIZ;
- len += 1;
- goto do2;
- case 0:
- if (OP_T_THRES <= 3 * OPSIZ && len == 0)
- return 0;
- a3 = ((op_t *) srcp1)[0];
- a0 = ((op_t *) srcp1)[1];
- b0 = ((op_t *) srcp2)[0];
- srcp1 += 1 * OPSIZ;
- goto do3;
- case 1:
- a2 = ((op_t *) srcp1)[0];
- a3 = ((op_t *) srcp1)[1];
- b3 = ((op_t *) srcp2)[0];
- srcp1 += 2 * OPSIZ;
- srcp2 += 1 * OPSIZ;
- len -= 1;
- if (OP_T_THRES <= 3 * OPSIZ && len == 0)
- goto do0;
- /* Fall through. */
- }
-
- do
- {
- a0 = ((op_t *) srcp1)[0];
- b0 = ((op_t *) srcp2)[0];
- x = MERGE(a2, shl, a3, shr);
- if (x != b3)
- return CMP_LT_OR_GT (x, b3);
-
- do3:
- a1 = ((op_t *) srcp1)[1];
- b1 = ((op_t *) srcp2)[1];
- x = MERGE(a3, shl, a0, shr);
- if (x != b0)
- return CMP_LT_OR_GT (x, b0);
-
- do2:
- a2 = ((op_t *) srcp1)[2];
- b2 = ((op_t *) srcp2)[2];
- x = MERGE(a0, shl, a1, shr);
- if (x != b1)
- return CMP_LT_OR_GT (x, b1);
-
- do1:
- a3 = ((op_t *) srcp1)[3];
- b3 = ((op_t *) srcp2)[3];
- x = MERGE(a1, shl, a2, shr);
- if (x != b2)
- return CMP_LT_OR_GT (x, b2);
-
- srcp1 += 4 * OPSIZ;
- srcp2 += 4 * OPSIZ;
- len -= 4;
- }
- while (len != 0);
-
- /* This is the right position for do0. Please don't move
- it into the loop. */
- do0:
- x = MERGE(a2, shl, a3, shr);
- if (x != b3)
- return CMP_LT_OR_GT (x, b3);
- return 0;
-}
-
-int
-rpl_memcmp (const void *s1, const void *s2, size_t len)
-{
- op_t a0;
- op_t b0;
- long int srcp1 = (long int) s1;
- long int srcp2 = (long int) s2;
- op_t res;
-
- if (len >= OP_T_THRES)
- {
- /* There are at least some bytes to compare. No need to test
- for LEN == 0 in this alignment loop. */
- while (srcp2 % OPSIZ != 0)
- {
- a0 = ((byte *) srcp1)[0];
- b0 = ((byte *) srcp2)[0];
- srcp1 += 1;
- srcp2 += 1;
- res = a0 - b0;
- if (res != 0)
- return res;
- len -= 1;
- }
-
- /* SRCP2 is now aligned for memory operations on `op_t'.
- SRCP1 alignment determines if we can do a simple,
- aligned compare or need to shuffle bits. */
-
- if (srcp1 % OPSIZ == 0)
- res = memcmp_common_alignment (srcp1, srcp2, len / OPSIZ);
- else
- res = memcmp_not_common_alignment (srcp1, srcp2, len / OPSIZ);
- if (res != 0)
- return res;
-
- /* Number of bytes remaining in the interval [0..OPSIZ-1]. */
- srcp1 += len & -OPSIZ;
- srcp2 += len & -OPSIZ;
- len %= OPSIZ;
- }
-
- /* There are just a few bytes to compare. Use byte memory operations. */
- while (len != 0)
- {
- a0 = ((byte *) srcp1)[0];
- b0 = ((byte *) srcp2)[0];
- srcp1 += 1;
- srcp2 += 1;
- res = a0 - b0;
- if (res != 0)
- return res;
- len -= 1;
- }
-
- return 0;
-}
-
-#ifdef weak_alias
-# undef bcmp
-weak_alias (memcmp, bcmp)
-#endif
diff --git a/lib/memcmp2.c b/lib/memcmp2.c
new file mode 100644
index 0000000..71ac448
--- /dev/null
+++ b/lib/memcmp2.c
@@ -0,0 +1,36 @@
+/* Compare two memory areas with possibly different lengths.
+ Copyright (C) 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include "memcmp2.h"
+
+#include <string.h>
+
+int
+memcmp2 (const char *s1, size_t n1, const char *s2, size_t n2)
+{
+ int cmp = memcmp (s1, s2, n1 <= n2 ? n1 : n2);
+ if (cmp == 0)
+ {
+ if (n1 < n2)
+ cmp = -1;
+ else if (n1 > n2)
+ cmp = 1;
+ }
+ return cmp;
+}
diff --git a/lib/memcmp2.h b/lib/memcmp2.h
new file mode 100644
index 0000000..fe3f5a2
--- /dev/null
+++ b/lib/memcmp2.h
@@ -0,0 +1,40 @@
+/* Compare two memory areas with possibly different lengths.
+ Copyright (C) 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef MEMCMP2_H
+#define MEMCMP2_H
+
+#include <stddef.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/* Compare the memory regions S1 = [s1..s1+N1-1], S2 = [s2..s2+n2-1],
+ lexicographically.
+ This function's result is locale independent, unlike memcoll()'s.
+ Return a negative number if S1 < S2, a positive number if S1 > S2, or
+ 0 if S1 and S2 have the same contents. */
+extern int memcmp2 (const char *s1, size_t n1, const char *s2, size_t n2)
+ _GL_ATTRIBUTE_PURE;
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* MEMCMP2_H */
diff --git a/lib/memcoll.c b/lib/memcoll.c
index e5ef363..89efaf2 100644
--- a/lib/memcoll.c
+++ b/lib/memcoll.c
@@ -1,11 +1,12 @@
/* Locale-specific memory comparison.
- Copyright (C) 1999, 2002, 2003, 2004, 2006 Free Software Foundation, Inc.
+ Copyright (C) 1999, 2002-2004, 2006, 2009-2016 Free Software Foundation,
+ Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Contributed by Paul Eggert <eggert@twinsun.com>. */
@@ -23,8 +23,40 @@
#include "memcoll.h"
#include <errno.h>
+#include <stdlib.h>
#include <string.h>
+/* Compare S1 (with size S1SIZE) and S2 (with length S2SIZE) according
+ to the LC_COLLATE locale. S1 and S2 are both blocks of memory with
+ nonzero sizes, and the last byte in each block must be a null byte.
+ Set errno to an error number if there is an error, and to zero
+ otherwise. */
+static int
+strcoll_loop (char const *s1, size_t s1size, char const *s2, size_t s2size)
+{
+ int diff;
+
+ while (! (errno = 0, (diff = strcoll (s1, s2)) || errno))
+ {
+ /* strcoll found no difference, but perhaps it was fooled by NUL
+ characters in the data. Work around this problem by advancing
+ past the NUL chars. */
+ size_t size1 = strlen (s1) + 1;
+ size_t size2 = strlen (s2) + 1;
+ s1 += size1;
+ s2 += size2;
+ s1size -= size1;
+ s2size -= size2;
+
+ if (s1size == 0)
+ return - (s2size != 0);
+ if (s2size == 0)
+ return 1;
+ }
+
+ return diff;
+}
+
/* Compare S1 (with length S1LEN) and S2 (with length S2LEN) according
to the LC_COLLATE locale. S1 and S2 do not overlap, and are not
adjacent. Perhaps temporarily modify the bytes after S1 and S2,
@@ -35,8 +67,6 @@ memcoll (char *s1, size_t s1len, char *s2, size_t s2len)
{
int diff;
-#if HAVE_STRCOLL
-
/* strcoll is slow on many platforms, so check for the common case
where the arguments are bytewise equal. Otherwise, walk through
the buffers using strcoll on each substring. */
@@ -51,46 +81,31 @@ memcoll (char *s1, size_t s1len, char *s2, size_t s2len)
char n1 = s1[s1len];
char n2 = s2[s2len];
- s1[s1len++] = '\0';
- s2[s2len++] = '\0';
-
- while (! (errno = 0, (diff = strcoll (s1, s2)) || errno))
- {
- /* strcoll found no difference, but perhaps it was fooled by NUL
- characters in the data. Work around this problem by advancing
- past the NUL chars. */
- size_t size1 = strlen (s1) + 1;
- size_t size2 = strlen (s2) + 1;
- s1 += size1;
- s2 += size2;
- s1len -= size1;
- s2len -= size2;
-
- if (s1len == 0)
- {
- if (s2len != 0)
- diff = -1;
- break;
- }
- else if (s2len == 0)
- {
- diff = 1;
- break;
- }
- }
-
- s1[s1len - 1] = n1;
- s2[s2len - 1] = n2;
- }
+ s1[s1len] = '\0';
+ s2[s2len] = '\0';
-#else
+ diff = strcoll_loop (s1, s1len + 1, s2, s2len + 1);
- diff = memcmp (s1, s2, s1len < s2len ? s1len : s2len);
- if (! diff)
- diff = s1len < s2len ? -1 : s1len != s2len;
- errno = 0;
-
-#endif
+ s1[s1len] = n1;
+ s2[s2len] = n2;
+ }
return diff;
}
+
+/* Compare S1 (a memory block of size S1SIZE, with a NUL as last byte)
+ and S2 (a memory block of size S2SIZE, with a NUL as last byte)
+ according to the LC_COLLATE locale. S1SIZE and S2SIZE must be > 0.
+ Set errno to an error number if there is an error, and to zero
+ otherwise. */
+int
+memcoll0 (char const *s1, size_t s1size, char const *s2, size_t s2size)
+{
+ if (s1size == s2size && memcmp (s1, s2, s1size) == 0)
+ {
+ errno = 0;
+ return 0;
+ }
+ else
+ return strcoll_loop (s1, s1size, s2, s2size);
+}
diff --git a/lib/memcoll.h b/lib/memcoll.h
index 9b61ce9..ef746db 100644
--- a/lib/memcoll.h
+++ b/lib/memcoll.h
@@ -1,11 +1,11 @@
/* Locale-specific memory comparison.
- Copyright (C) 1999, 2003 Free Software Foundation, Inc.
+ Copyright (C) 1999, 2003, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Contributed by Paul Eggert <eggert@twinsun.com>. */
@@ -24,5 +23,6 @@
# include <stddef.h>
int memcoll (char *, size_t, char *, size_t);
+int memcoll0 (char const *, size_t, char const *, size_t);
#endif /* MEMCOLL_H_ */
diff --git a/lib/memcpy.c b/lib/memcpy.c
deleted file mode 100644
index d1e49c6..0000000
--- a/lib/memcpy.c
+++ /dev/null
@@ -1,36 +0,0 @@
-/* Copyright (C) 1995, 1997, 2000, 2003, 2006 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-/* Written by Jim Meyering <meyering@na-net.ornl.gov>. */
-
-#include <config.h>
-
-#include <stddef.h>
-
-/* Copy LEN bytes starting at SRCADDR to DESTADDR. Result undefined
- if the source overlaps with the destination.
- Return DESTADDR. */
-
-void *
-memcpy (void *destaddr, void const *srcaddr, size_t len)
-{
- char *dest = destaddr;
- char const *src = srcaddr;
-
- while (len-- > 0)
- *dest++ = *src++;
- return destaddr;
-}
diff --git a/lib/memmove.c b/lib/memmove.c
deleted file mode 100644
index c5ff8b5..0000000
--- a/lib/memmove.c
+++ /dev/null
@@ -1,26 +0,0 @@
-/* memmove.c -- copy memory.
- Copy LENGTH bytes from SOURCE to DEST. Does not null-terminate.
- In the public domain.
- By David MacKenzie <djm@gnu.ai.mit.edu>. */
-
-#include <config.h>
-
-#include <stddef.h>
-
-void *
-memmove (void *dest0, void const *source0, size_t length)
-{
- char *dest = dest0;
- char const *source = source0;
- if (source < dest)
- /* Moving from low mem to hi mem; start at end. */
- for (source += length, dest += length; length; --length)
- *--dest = *--source;
- else if (source != dest)
- {
- /* Moving from hi mem to low mem; start at beginning. */
- for (; length; --length)
- *dest++ = *source++;
- }
- return dest0;
-}
diff --git a/lib/mempcpy.c b/lib/mempcpy.c
index 1c702c7..d579f64 100644
--- a/lib/mempcpy.c
+++ b/lib/mempcpy.c
@@ -1,9 +1,9 @@
/* Copy memory area and return pointer after last written byte.
- Copyright (C) 2003, 2007 Free Software Foundation, Inc.
+ Copyright (C) 2003, 2007, 2009-2016 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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -12,8 +12,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program; if not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
diff --git a/lib/memrchr.c b/lib/memrchr.c
index 29fd531..e6212e5 100644
--- a/lib/memrchr.c
+++ b/lib/memrchr.c
@@ -1,7 +1,7 @@
/* memrchr -- find the last occurrence of a byte in a memory block
- Copyright (C) 1991, 1993, 1996, 1997, 1999, 2000, 2003, 2004, 2005,
- 2006, 2007 Free Software Foundation, Inc.
+ Copyright (C) 1991, 1993, 1996-1997, 1999-2000, 2003-2016 Free Software
+ Foundation, Inc.
Based on strlen implementation by Torbjorn Granlund (tege@sics.se),
with help from Dan Sahlin (dan@sics.se) and
@@ -9,19 +9,18 @@
adaptation to memchr suggested by Dick Karpinski (dick@cca.ucsf.edu),
and implemented by Roland McGrath (roland@ai.mit.edu).
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#if defined _LIBC
# include <memcopy.h>
@@ -34,7 +33,9 @@
#include <limits.h>
#undef __memrchr
-#undef memrchr
+#ifdef _LIBC
+# undef memrchr
+#endif
#ifndef weak_alias
# define __memrchr memrchr
@@ -44,146 +45,116 @@
void *
__memrchr (void const *s, int c_in, size_t n)
{
+ /* On 32-bit hardware, choosing longword to be a 32-bit unsigned
+ long instead of a 64-bit uintmax_t tends to give better
+ performance. On 64-bit hardware, unsigned long is generally 64
+ bits already. Change this typedef to experiment with
+ performance. */
+ typedef unsigned long int longword;
+
const unsigned char *char_ptr;
- const unsigned long int *longword_ptr;
- unsigned long int longword, magic_bits, charmask;
+ const longword *longword_ptr;
+ longword repeated_one;
+ longword repeated_c;
unsigned reg_char c;
- int i;
c = (unsigned char) c_in;
- /* Handle the last few characters by reading one character at a time.
+ /* Handle the last few bytes by reading one byte at a time.
Do this until CHAR_PTR is aligned on a longword boundary. */
for (char_ptr = (const unsigned char *) s + n;
- n > 0 && (size_t) char_ptr % sizeof longword != 0;
+ n > 0 && (size_t) char_ptr % sizeof (longword) != 0;
--n)
if (*--char_ptr == c)
return (void *) char_ptr;
+ longword_ptr = (const longword *) char_ptr;
+
/* All these elucidatory comments refer to 4-byte longwords,
but the theory applies equally well to any size longwords. */
- longword_ptr = (const unsigned long int *) char_ptr;
-
- /* Bits 31, 24, 16, and 8 of this number are zero. Call these bits
- the "holes." Note that there is a hole just to the left of
- each byte, with an extra at the end:
-
- bits: 01111110 11111110 11111110 11111111
- bytes: AAAAAAAA BBBBBBBB CCCCCCCC DDDDDDDD
-
- The 1-bits make sure that carries propagate to the next 0-bit.
- The 0-bits provide holes for carries to fall into. */
-
- /* Set MAGIC_BITS to be this pattern of 1 and 0 bits.
- Set CHARMASK to be a longword, each of whose bytes is C. */
-
- magic_bits = 0xfefefefe;
- charmask = c | (c << 8);
- charmask |= charmask << 16;
-#if 0xffffffffU < ULONG_MAX
- magic_bits |= magic_bits << 32;
- charmask |= charmask << 32;
- if (8 < sizeof longword)
- for (i = 64; i < sizeof longword * 8; i *= 2)
- {
- magic_bits |= magic_bits << i;
- charmask |= charmask << i;
- }
-#endif
- magic_bits = (ULONG_MAX >> 1) & (magic_bits | 1);
+ /* Compute auxiliary longword values:
+ repeated_one is a value which has a 1 in every byte.
+ repeated_c has c in every byte. */
+ repeated_one = 0x01010101;
+ repeated_c = c | (c << 8);
+ repeated_c |= repeated_c << 16;
+ if (0xffffffffU < (longword) -1)
+ {
+ repeated_one |= repeated_one << 31 << 1;
+ repeated_c |= repeated_c << 31 << 1;
+ if (8 < sizeof (longword))
+ {
+ size_t i;
+
+ for (i = 64; i < sizeof (longword) * 8; i *= 2)
+ {
+ repeated_one |= repeated_one << i;
+ repeated_c |= repeated_c << i;
+ }
+ }
+ }
- /* Instead of the traditional loop which tests each character,
- we will test a longword at a time. The tricky part is testing
- if *any of the four* bytes in the longword in question are zero. */
- while (n >= sizeof longword)
+ /* Instead of the traditional loop which tests each byte, we will test a
+ longword at a time. The tricky part is testing if *any of the four*
+ bytes in the longword in question are equal to c. We first use an xor
+ with repeated_c. This reduces the task to testing whether *any of the
+ four* bytes in longword1 is zero.
+
+ We compute tmp =
+ ((longword1 - repeated_one) & ~longword1) & (repeated_one << 7).
+ That is, we perform the following operations:
+ 1. Subtract repeated_one.
+ 2. & ~longword1.
+ 3. & a mask consisting of 0x80 in every byte.
+ Consider what happens in each byte:
+ - If a byte of longword1 is zero, step 1 and 2 transform it into 0xff,
+ and step 3 transforms it into 0x80. A carry can also be propagated
+ to more significant bytes.
+ - If a byte of longword1 is nonzero, let its lowest 1 bit be at
+ position k (0 <= k <= 7); so the lowest k bits are 0. After step 1,
+ the byte ends in a single bit of value 0 and k bits of value 1.
+ After step 2, the result is just k bits of value 1: 2^k - 1. After
+ step 3, the result is 0. And no carry is produced.
+ So, if longword1 has only non-zero bytes, tmp is zero.
+ Whereas if longword1 has a zero byte, call j the position of the least
+ significant zero byte. Then the result has a zero at positions 0, ...,
+ j-1 and a 0x80 at position j. We cannot predict the result at the more
+ significant bytes (positions j+1..3), but it does not matter since we
+ already have a non-zero bit at position 8*j+7.
+
+ So, the test whether any byte in longword1 is zero is equivalent to
+ testing whether tmp is nonzero. */
+
+ while (n >= sizeof (longword))
{
- /* We tentatively exit the loop if adding MAGIC_BITS to
- LONGWORD fails to change any of the hole bits of LONGWORD.
-
- 1) Is this safe? Will it catch all the zero bytes?
- Suppose there is a byte with all zeros. Any carry bits
- propagating from its left will fall into the hole at its
- least significant bit and stop. Since there will be no
- carry from its most significant bit, the LSB of the
- byte to the left will be unchanged, and the zero will be
- detected.
-
- 2) Is this worthwhile? Will it ignore everything except
- zero bytes? Suppose every byte of LONGWORD has a bit set
- somewhere. There will be a carry into bit 8. If bit 8
- is set, this will carry into bit 16. If bit 8 is clear,
- one of bits 9-15 must be set, so there will be a carry
- into bit 16. Similarly, there will be a carry into bit
- 24. If one of bits 24-30 is set, there will be a carry
- into bit 31, so all of the hole bits will be changed.
-
- The one misfire occurs when bits 24-30 are clear and bit
- 31 is set; in this case, the hole at bit 31 is not
- changed. If we had access to the processor carry flag,
- we could close this loophole by putting the fourth hole
- at bit 32!
-
- So it ignores everything except 128's, when they're aligned
- properly.
-
- 3) But wait! Aren't we looking for C, not zero?
- Good point. So what we do is XOR LONGWORD with a longword,
- each of whose bytes is C. This turns each byte that is C
- into a zero. */
-
- longword = *--longword_ptr ^ charmask;
-
- /* Add MAGIC_BITS to LONGWORD. */
- if ((((longword + magic_bits)
-
- /* Set those bits that were unchanged by the addition. */
- ^ ~longword)
-
- /* Look at only the hole bits. If any of the hole bits
- are unchanged, most likely one of the bytes was a
- zero. */
- & ~magic_bits) != 0)
- {
- /* Which of the bytes was C? If none of them were, it was
- a misfire; continue the search. */
-
- const unsigned char *cp = (const unsigned char *) longword_ptr;
-
- if (8 < sizeof longword)
- for (i = sizeof longword - 1; 8 <= i; i--)
- if (cp[i] == c)
- return (void *) &cp[i];
- if (7 < sizeof longword && cp[7] == c)
- return (void *) &cp[7];
- if (6 < sizeof longword && cp[6] == c)
- return (void *) &cp[6];
- if (5 < sizeof longword && cp[5] == c)
- return (void *) &cp[5];
- if (4 < sizeof longword && cp[4] == c)
- return (void *) &cp[4];
- if (cp[3] == c)
- return (void *) &cp[3];
- if (cp[2] == c)
- return (void *) &cp[2];
- if (cp[1] == c)
- return (void *) &cp[1];
- if (cp[0] == c)
- return (void *) cp;
- }
-
- n -= sizeof longword;
+ longword longword1 = *--longword_ptr ^ repeated_c;
+
+ if ((((longword1 - repeated_one) & ~longword1)
+ & (repeated_one << 7)) != 0)
+ {
+ longword_ptr++;
+ break;
+ }
+ n -= sizeof (longword);
}
char_ptr = (const unsigned char *) longword_ptr;
+ /* At this point, we know that either n < sizeof (longword), or one of the
+ sizeof (longword) bytes starting at char_ptr is == c. On little-endian
+ machines, we could determine the first such byte without any further
+ memory accesses, just by looking at the tmp result from the last loop
+ iteration. But this does not work on big-endian machines. Choose code
+ that works in both cases. */
+
while (n-- > 0)
{
if (*--char_ptr == c)
- return (void *) char_ptr;
+ return (void *) char_ptr;
}
- return 0;
+ return NULL;
}
#ifdef weak_alias
weak_alias (__memrchr, memrchr)
diff --git a/lib/memset.c b/lib/memset.c
deleted file mode 100644
index 890cbf1..0000000
--- a/lib/memset.c
+++ /dev/null
@@ -1,28 +0,0 @@
-/* memset.c -- set an area of memory to a given value
- Copyright (C) 1991, 2003 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-#include <stddef.h>
-
-void *
-memset (void *str, int c, size_t len)
-{
- register char *st = str;
-
- while (len-- > 0)
- *st++ = c;
- return str;
-}
diff --git a/lib/memxfrm.c b/lib/memxfrm.c
deleted file mode 100644
index 09bb5f4..0000000
--- a/lib/memxfrm.c
+++ /dev/null
@@ -1,106 +0,0 @@
-/* Locale-specific memory transformation
-
- Copyright (C) 2006 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-/* Written by Paul Eggert <eggert@cs.ucla.edu>. */
-
-#include <config.h>
-
-#include "memxfrm.h"
-
-#include <errno.h>
-#include <stdlib.h>
-#include <string.h>
-
-/* Store into DEST (of size DESTSIZE) the text in SRC (of size SRCSIZE)
- transformed so that the result of memcmp on two transformed texts
- (with ties going to the longer text) is the same as the result of
- memcoll on the two texts before their transformation. Perhaps
- temporarily modify the byte after SRC, but restore its original
- contents before returning.
-
- Return the size of the resulting text, or an indeterminate value if
- there is an error. Set errno to an error number if there is an
- error, and to zero otherwise. DEST contains an indeterminate value
- if there is an error or if the resulting size is greater than
- DESTSIZE. */
-
-size_t
-memxfrm (char *restrict dest, size_t destsize,
- char *restrict src, size_t srcsize)
-{
-#if HAVE_STRXFRM
-
- size_t di = 0;
- size_t si = 0;
- size_t result = 0;
-
- char ch = src[srcsize];
- src[srcsize] = '\0';
-
- while (si < srcsize)
- {
- size_t slen = strlen (src + si);
-
- size_t result0 = result;
- errno = 0;
- result += strxfrm (dest + di, src + si, destsize - di) + 1;
- if (errno != 0)
- break;
- if (result <= result0)
- {
- errno = ERANGE;
- break;
- }
-
- if (result == destsize + 1 && si + slen == srcsize)
- {
- /* The destination is exactly the right size, but strxfrm wants
- room for a trailing null. Work around the problem with a
- temporary buffer. */
- size_t bufsize = destsize - di + 1;
- char stackbuf[4000];
- char *buf = stackbuf;
- if (sizeof stackbuf < bufsize)
- {
- buf = malloc (bufsize);
- if (! buf)
- break;
- }
- strxfrm (buf, src + si, bufsize);
- memcpy (dest + di, buf, destsize - di);
- if (sizeof stackbuf < bufsize)
- free (buf);
- errno = 0;
- }
-
- di = (result < destsize ? result : destsize);
- si += slen + 1;
- }
-
- src[srcsize] = ch;
- return result - (si != srcsize);
-
-#else
-
- if (srcsize < destsize)
- memcpy (dest, src, srcsize);
- errno = 0;
- return srcsize;
-
-#endif
-}
diff --git a/lib/memxfrm.h b/lib/memxfrm.h
deleted file mode 100644
index 605421d..0000000
--- a/lib/memxfrm.h
+++ /dev/null
@@ -1,2 +0,0 @@
-#include <stddef.h>
-size_t memxfrm (char *restrict, size_t, char *restrict, size_t);
diff --git a/lib/mgetgroups.c b/lib/mgetgroups.c
new file mode 100644
index 0000000..334ab68
--- /dev/null
+++ b/lib/mgetgroups.c
@@ -0,0 +1,201 @@
+/* mgetgroups.c -- return a list of the groups a user or current process is in
+
+ Copyright (C) 2007-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Extracted from coreutils' src/id.c. */
+
+#include <config.h>
+
+#include "mgetgroups.h"
+
+#include <stdlib.h>
+#include <unistd.h>
+#include <stdint.h>
+#include <string.h>
+#include <errno.h>
+#if HAVE_GETGROUPLIST
+# include <grp.h>
+#endif
+
+#include "getugroups.h"
+#include "xalloc-oversized.h"
+
+/* Work around an incompatibility of OS X 10.11: getgrouplist
+ accepts int *, not gid_t *, and int and gid_t differ in sign. */
+#if 4 < __GNUC__ + (3 <= __GNUC_MINOR__)
+# pragma GCC diagnostic ignored "-Wpointer-sign"
+#endif
+
+static gid_t *
+realloc_groupbuf (gid_t *g, size_t num)
+{
+ if (xalloc_oversized (num, sizeof *g))
+ {
+ errno = ENOMEM;
+ return NULL;
+ }
+
+ return realloc (g, num * sizeof *g);
+}
+
+/* Like getugroups, but store the result in malloc'd storage.
+ Set *GROUPS to the malloc'd list of all group IDs of which USERNAME
+ is a member. If GID is not -1, store it first. GID should be the
+ group ID (pw_gid) obtained from getpwuid, in case USERNAME is not
+ listed in the groups database (e.g., /etc/groups). If USERNAME is
+ NULL, store the supplementary groups of the current process, and GID
+ should be -1 or the effective group ID (getegid). Upon failure,
+ don't modify *GROUPS, set errno, and return -1. Otherwise, return
+ the number of groups. The resulting list may contain duplicates,
+ but adjacent members will be distinct. */
+
+int
+mgetgroups (char const *username, gid_t gid, gid_t **groups)
+{
+ int max_n_groups;
+ int ng;
+ gid_t *g;
+
+#if HAVE_GETGROUPLIST
+ /* We prefer to use getgrouplist if available, because it has better
+ performance characteristics.
+
+ In glibc 2.3.2, getgrouplist is buggy. If you pass a zero as the
+ length of the output buffer, getgrouplist will still write to the
+ buffer. Contrary to what some versions of the getgrouplist
+ manpage say, this doesn't happen with nonzero buffer sizes.
+ Therefore our usage here just avoids a zero sized buffer. */
+ if (username)
+ {
+ enum { N_GROUPS_INIT = 10 };
+ max_n_groups = N_GROUPS_INIT;
+
+ g = realloc_groupbuf (NULL, max_n_groups);
+ if (g == NULL)
+ return -1;
+
+ while (1)
+ {
+ gid_t *h;
+ int last_n_groups = max_n_groups;
+
+ /* getgrouplist updates max_n_groups to num required. */
+ ng = getgrouplist (username, gid, g, &max_n_groups);
+
+ /* Some systems (like Darwin) have a bug where they
+ never increase max_n_groups. */
+ if (ng < 0 && last_n_groups == max_n_groups)
+ max_n_groups *= 2;
+
+ if ((h = realloc_groupbuf (g, max_n_groups)) == NULL)
+ {
+ int saved_errno = errno;
+ free (g);
+ errno = saved_errno;
+ return -1;
+ }
+ g = h;
+
+ if (0 <= ng)
+ {
+ *groups = g;
+ /* On success some systems just return 0 from getgrouplist,
+ so return max_n_groups rather than ng. */
+ return max_n_groups;
+ }
+ }
+ }
+ /* else no username, so fall through and use getgroups. */
+#endif
+
+ max_n_groups = (username
+ ? getugroups (0, NULL, username, gid)
+ : getgroups (0, NULL));
+
+ /* If we failed to count groups because there is no supplemental
+ group support, then return an array containing just GID.
+ Otherwise, we fail for the same reason. */
+ if (max_n_groups < 0)
+ {
+ if (errno == ENOSYS && (g = realloc_groupbuf (NULL, 1)))
+ {
+ *groups = g;
+ *g = gid;
+ return gid != (gid_t) -1;
+ }
+ return -1;
+ }
+
+ if (max_n_groups == 0 || (!username && gid != (gid_t) -1))
+ max_n_groups++;
+ g = realloc_groupbuf (NULL, max_n_groups);
+ if (g == NULL)
+ return -1;
+
+ ng = (username
+ ? getugroups (max_n_groups, g, username, gid)
+ : getgroups (max_n_groups - (gid != (gid_t) -1),
+ g + (gid != (gid_t) -1)));
+
+ if (ng < 0)
+ {
+ /* Failure is unexpected, but handle it anyway. */
+ int saved_errno = errno;
+ free (g);
+ errno = saved_errno;
+ return -1;
+ }
+
+ if (!username && gid != (gid_t) -1)
+ {
+ *g = gid;
+ ng++;
+ }
+ *groups = g;
+
+ /* Reduce the number of duplicates. On some systems, getgroups
+ returns the effective gid twice: once as the first element, and
+ once in its position within the supplementary groups. On other
+ systems, getgroups does not return the effective gid at all,
+ which is why we provide a GID argument. Meanwhile, the GID
+ argument, if provided, is typically any member of the
+ supplementary groups, and not necessarily the effective gid. So,
+ the most likely duplicates are the first element with an
+ arbitrary other element, or pair-wise duplication between the
+ first and second elements returned by getgroups. It is possible
+ that this O(n) pass will not remove all duplicates, but it is not
+ worth the effort to slow down to an O(n log n) algorithm that
+ sorts the array in place, nor the extra memory needed for
+ duplicate removal via an O(n) hash-table. Hence, this function
+ is only documented as guaranteeing no pair-wise duplicates,
+ rather than returning the minimal set. */
+ if (1 < ng)
+ {
+ gid_t first = *g;
+ gid_t *next;
+ gid_t *groups_end = g + ng;
+
+ for (next = g + 1; next < groups_end; next++)
+ {
+ if (*next == first || *next == *g)
+ ng--;
+ else
+ *++g = *next;
+ }
+ }
+
+ return ng;
+}
diff --git a/lib/mgetgroups.h b/lib/mgetgroups.h
new file mode 100644
index 0000000..072d673
--- /dev/null
+++ b/lib/mgetgroups.h
@@ -0,0 +1,22 @@
+/* Get a list of all group IDs associated with a specified user ID.
+ Copyright (C) 2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <sys/types.h>
+
+int mgetgroups (const char *username, gid_t gid, gid_t **groups);
+#if GNULIB_XGETGROUPS
+int xgetgroups (const char *username, gid_t gid, gid_t **groups);
+#endif
diff --git a/lib/mkancesdirs.c b/lib/mkancesdirs.c
index 19f7dca..7a8173f 100644
--- a/lib/mkancesdirs.c
+++ b/lib/mkancesdirs.c
@@ -1,11 +1,11 @@
/* Make a file's ancestor directories.
- Copyright (C) 2006 Free Software Foundation, Inc.
+ Copyright (C) 2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
@@ -43,11 +42,9 @@
Create any ancestor directories that don't already exist, by
invoking MAKE_DIR (FILE, COMPONENT, MAKE_DIR_ARG). This function
- should return 0 if successful and the resulting directory is
- readable, 1 if successful but the resulting directory might not be
- readable, -1 (setting errno) otherwise. If COMPONENT is relative,
- it is relative to the temporary working directory, which may differ
- from *WD.
+ should return 0 if successful, -1 (setting errno) otherwise. If
+ COMPONENT is relative, it is relative to the temporary working
+ directory, which may differ from *WD.
Ordinarily MAKE_DIR is executed with the working directory changed
to reflect the already-made prefix, and mkancesdirs returns with
@@ -66,8 +63,8 @@
ptrdiff_t
mkancesdirs (char *file, struct savewd *wd,
- int (*make_dir) (char const *, char const *, void *),
- void *make_dir_arg)
+ int (*make_dir) (char const *, char const *, void *),
+ void *make_dir_arg)
{
/* Address of the previous directory separator that follows an
ordinary byte in a file name in the left-to-right scan, or NULL
@@ -91,63 +88,53 @@ mkancesdirs (char *file, struct savewd *wd,
while ((c = *p++))
if (ISSLASH (*p))
{
- if (! ISSLASH (c))
- sep = p;
+ if (! ISSLASH (c))
+ sep = p;
}
else if (ISSLASH (c) && *p && sep)
{
- /* Don't bother to make or test for "." since it does not
- affect the algorithm. */
- if (! (sep - component == 1 && component[0] == '.'))
- {
- int make_dir_errno = 0;
- int savewd_chdir_options = 0;
- int chdir_result;
-
- /* Temporarily modify FILE to isolate this file name
- component. */
- *sep = '\0';
-
- /* Invoke MAKE_DIR on this component, except don't bother
- with ".." since it must exist if its "parent" does. */
- if (sep - component == 2
- && component[0] == '.' && component[1] == '.')
- made_dir = false;
- else
- switch (make_dir (file, component, make_dir_arg))
- {
- case -1:
- make_dir_errno = errno;
- break;
-
- case 0:
- savewd_chdir_options |= SAVEWD_CHDIR_READABLE;
- /* Fall through. */
- case 1:
- made_dir = true;
- break;
- }
-
- if (made_dir)
- savewd_chdir_options |= SAVEWD_CHDIR_NOFOLLOW;
-
- chdir_result =
- savewd_chdir (wd, component, savewd_chdir_options, NULL);
-
- /* Undo the temporary modification to FILE, unless there
- was a failure. */
- if (chdir_result != -1)
- *sep = '/';
-
- if (chdir_result != 0)
- {
- if (make_dir_errno != 0 && errno == ENOENT)
- errno = make_dir_errno;
- return chdir_result;
- }
- }
-
- component = p;
+ /* Don't bother to make or test for "." since it does not
+ affect the algorithm. */
+ if (! (sep - component == 1 && component[0] == '.'))
+ {
+ int make_dir_errno = 0;
+ int savewd_chdir_options = 0;
+ int chdir_result;
+
+ /* Temporarily modify FILE to isolate this file name
+ component. */
+ *sep = '\0';
+
+ /* Invoke MAKE_DIR on this component, except don't bother
+ with ".." since it must exist if its "parent" does. */
+ if (sep - component == 2
+ && component[0] == '.' && component[1] == '.')
+ made_dir = false;
+ else if (make_dir (file, component, make_dir_arg) < 0)
+ make_dir_errno = errno;
+ else
+ made_dir = true;
+
+ if (made_dir)
+ savewd_chdir_options |= SAVEWD_CHDIR_NOFOLLOW;
+
+ chdir_result =
+ savewd_chdir (wd, component, savewd_chdir_options, NULL);
+
+ /* Undo the temporary modification to FILE, unless there
+ was a failure. */
+ if (chdir_result != -1)
+ *sep = '/';
+
+ if (chdir_result != 0)
+ {
+ if (make_dir_errno != 0 && errno == ENOENT)
+ errno = make_dir_errno;
+ return chdir_result;
+ }
+ }
+
+ component = p;
}
return component - file;
diff --git a/lib/mkancesdirs.h b/lib/mkancesdirs.h
index 08fb50c..5f7b2d6 100644
--- a/lib/mkancesdirs.h
+++ b/lib/mkancesdirs.h
@@ -1,4 +1,4 @@
#include <stddef.h>
struct savewd;
ptrdiff_t mkancesdirs (char *, struct savewd *,
- int (*) (char const *, char const *, void *), void *);
+ int (*) (char const *, char const *, void *), void *);
diff --git a/lib/mkdir-p.c b/lib/mkdir-p.c
index 6f71ec8..1f90185 100644
--- a/lib/mkdir-p.c
+++ b/lib/mkdir-p.c
@@ -1,12 +1,12 @@
/* mkdir-p.c -- Ensure that a directory and its parents exist.
- Copyright (C) 1990, 1997, 1998, 1999, 2000, 2002, 2003, 2004, 2005,
- 2006, 2007 Free Software Foundation, Inc.
+ Copyright (C) 1990, 1997-2000, 2002-2007, 2009-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert, David MacKenzie, and Jim Meyering. */
@@ -53,9 +52,9 @@
is retained on return if the ancestor directories could not be
created.
- Create DIR as a new directory with using mkdir with permissions
- MODE. It is also OK if MAKE_ANCESTOR is not null and a
- directory DIR already exists.
+ Create DIR as a new directory, using mkdir with permissions MODE;
+ here, MODE is affected by the umask in the usual way. It is also
+ OK if MAKE_ANCESTOR is not null and a directory DIR already exists.
Call ANNOUNCE (DIR, OPTIONS) just after successfully making DIR,
even if some of the following actions fail.
@@ -66,16 +65,15 @@
Set DIR's mode bits to MODE, except preserve any of the bits that
correspond to zero bits in MODE_BITS. In other words, MODE_BITS is
a mask that specifies which of DIR's mode bits should be set or
- cleared. MODE should be a subset of MODE_BITS, which in turn
- should be a subset of CHMOD_MODE_BITS. Changing the mode in this
- way is necessary if DIR already existed or if MODE and MODE_BITS
- specify non-permissions bits like S_ISUID.
+ cleared. Changing the mode in this way is necessary if DIR already
+ existed, if MODE and MODE_BITS specify non-permissions bits like
+ S_ISUID, or if MODE and MODE_BITS specify permissions bits that are
+ masked out by the umask. MODE_BITS should be a subset of
+ CHMOD_MODE_BITS.
However, if PRESERVE_EXISTING is true and DIR already exists,
do not attempt to set DIR's ownership and file mode bits.
- This implementation assumes the current umask is zero.
-
Return true if DIR exists as a directory with the proper ownership
and file mode bits when done, or if a child process has been
dispatched to do the real work (though the child process may not
@@ -85,15 +83,15 @@
bool
make_dir_parents (char *dir,
- struct savewd *wd,
- int (*make_ancestor) (char const *, char const *, void *),
- void *options,
- mode_t mode,
- void (*announce) (char const *, void *),
- mode_t mode_bits,
- uid_t owner,
- gid_t group,
- bool preserve_existing)
+ struct savewd *wd,
+ int (*make_ancestor) (char const *, char const *, void *),
+ void *options,
+ mode_t mode,
+ void (*announce) (char const *, void *),
+ mode_t mode_bits,
+ uid_t owner,
+ gid_t group,
+ bool preserve_existing)
{
int mkdir_errno = (IS_ABSOLUTE_FILE_NAME (dir) ? 0 : savewd_errno (wd));
@@ -103,105 +101,89 @@ make_dir_parents (char *dir,
int savewd_chdir_options = (HAVE_FCHMOD ? SAVEWD_CHDIR_SKIP_READABLE : 0);
if (make_ancestor)
- {
- prefix_len = mkancesdirs (dir, wd, make_ancestor, options);
- if (prefix_len < 0)
- {
- if (prefix_len < -1)
- return true;
- mkdir_errno = errno;
- }
- }
+ {
+ prefix_len = mkancesdirs (dir, wd, make_ancestor, options);
+ if (prefix_len < 0)
+ {
+ if (prefix_len < -1)
+ return true;
+ mkdir_errno = errno;
+ }
+ }
if (0 <= prefix_len)
- {
- /* If the ownership might change, or if the directory will be
- writeable to other users and its special mode bits may
- change after the directory is created, create it with
- more restrictive permissions at first, so unauthorized
- users cannot nip in before the directory is ready. */
- bool keep_owner = owner == (uid_t) -1 && group == (gid_t) -1;
- bool keep_special_mode_bits =
- ((mode_bits & (S_ISUID | S_ISGID)) | (mode & S_ISVTX)) == 0;
- mode_t mkdir_mode = mode;
- if (! keep_owner)
- mkdir_mode &= ~ (S_IRWXG | S_IRWXO);
- else if (! keep_special_mode_bits)
- mkdir_mode &= ~ (S_IWGRP | S_IWOTH);
-
- if (mkdir (dir + prefix_len, mkdir_mode) == 0)
- {
- announce (dir, options);
- preserve_existing = keep_owner & keep_special_mode_bits;
- savewd_chdir_options |=
- (SAVEWD_CHDIR_NOFOLLOW
- | (mode & S_IRUSR ? SAVEWD_CHDIR_READABLE : 0));
- }
- else
- {
- mkdir_errno = errno;
- mkdir_mode = -1;
- }
-
- if (preserve_existing)
- {
- struct stat st;
- if (mkdir_errno == 0
- || (mkdir_errno != ENOENT && make_ancestor
- && stat (dir + prefix_len, &st) == 0
- && S_ISDIR (st.st_mode)))
- return true;
- }
- else
- {
- int open_result[2];
- int chdir_result =
- savewd_chdir (wd, dir + prefix_len,
- savewd_chdir_options, open_result);
- if (chdir_result < -1)
- return true;
- else
- {
- bool chdir_ok = (chdir_result == 0);
- int chdir_errno = errno;
- int fd = open_result[0];
- bool chdir_failed_unexpectedly =
- (mkdir_errno == 0
- && ((! chdir_ok && (mode & S_IXUSR))
- || (fd < 0 && (mode & S_IRUSR))));
-
- if (chdir_failed_unexpectedly)
- {
- /* No need to save errno here; it's irrelevant. */
- if (0 <= fd)
- close (fd);
- }
- else
- {
- char const *subdir = (chdir_ok ? "." : dir + prefix_len);
- if (dirchownmod (fd, subdir, mkdir_mode, owner, group,
- mode, mode_bits)
- == 0)
- return true;
- }
-
- if (mkdir_errno == 0
- || (mkdir_errno != ENOENT && make_ancestor
- && errno != ENOTDIR))
- {
- error (0,
- (! chdir_failed_unexpectedly ? errno
- : ! chdir_ok && (mode & S_IXUSR) ? chdir_errno
- : open_result[1]),
- _(keep_owner
- ? "cannot change permissions of %s"
- : "cannot change owner and permissions of %s"),
- quote (dir));
- return false;
- }
- }
- }
- }
+ {
+ /* If the ownership might change, or if the directory will be
+ writable to other users and its special mode bits may
+ change after the directory is created, create it with
+ more restrictive permissions at first, so unauthorized
+ users cannot nip in before the directory is ready. */
+ bool keep_owner = owner == (uid_t) -1 && group == (gid_t) -1;
+ bool keep_special_mode_bits =
+ ((mode_bits & (S_ISUID | S_ISGID)) | (mode & S_ISVTX)) == 0;
+ mode_t mkdir_mode = mode;
+ if (! keep_owner)
+ mkdir_mode &= ~ (S_IRWXG | S_IRWXO);
+ else if (! keep_special_mode_bits)
+ mkdir_mode &= ~ (S_IWGRP | S_IWOTH);
+
+ if (mkdir (dir + prefix_len, mkdir_mode) == 0)
+ {
+ /* True if the caller does not care about the umask's
+ effect on the permissions. */
+ bool umask_must_be_ok = (mode & mode_bits & S_IRWXUGO) == 0;
+
+ announce (dir, options);
+ preserve_existing = (keep_owner & keep_special_mode_bits
+ & umask_must_be_ok);
+ savewd_chdir_options |= SAVEWD_CHDIR_NOFOLLOW;
+ }
+ else
+ {
+ mkdir_errno = errno;
+ mkdir_mode = -1;
+ }
+
+ if (preserve_existing)
+ {
+ struct stat st;
+ if (mkdir_errno == 0
+ || (mkdir_errno != ENOENT && make_ancestor
+ && stat (dir + prefix_len, &st) == 0
+ && S_ISDIR (st.st_mode)))
+ return true;
+ }
+ else
+ {
+ int open_result[2];
+ int chdir_result =
+ savewd_chdir (wd, dir + prefix_len,
+ savewd_chdir_options, open_result);
+ if (chdir_result < -1)
+ return true;
+ else
+ {
+ bool chdir_ok = (chdir_result == 0);
+ char const *subdir = (chdir_ok ? "." : dir + prefix_len);
+ if (dirchownmod (open_result[0], subdir, mkdir_mode,
+ owner, group, mode, mode_bits)
+ == 0)
+ return true;
+
+ if (mkdir_errno == 0
+ || (mkdir_errno != ENOENT && make_ancestor
+ && errno != ENOTDIR))
+ {
+ error (0, errno,
+ _(keep_owner
+ ? "cannot change permissions of %s"
+ : "cannot change owner and permissions of %s"),
+ quote (dir));
+ return false;
+ }
+ }
+ }
+ }
}
error (0, mkdir_errno, _("cannot create directory %s"), quote (dir));
diff --git a/lib/mkdir-p.h b/lib/mkdir-p.h
index 7353182..d07c607 100644
--- a/lib/mkdir-p.h
+++ b/lib/mkdir-p.h
@@ -1,12 +1,12 @@
/* mkdir-p.h -- Ensure that a directory and its parents exist.
- Copyright (C) 1994, 1995, 1996, 1997, 2000, 2003, 2004, 2005, 2006
- Free Software Foundation, Inc.
+ Copyright (C) 1994-1997, 2000, 2003-2006, 2009-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert, David MacKenzie, and Jim Meyering. */
@@ -24,13 +23,13 @@
struct savewd;
bool make_dir_parents (char *dir,
- struct savewd *wd,
- int (*make_ancestor) (char const *, char const *,
- void *),
- void *options,
- mode_t mode,
- void (*announce) (char const *, void *),
- mode_t mode_bits,
- uid_t owner,
- gid_t group,
- bool preserve_existing);
+ struct savewd *wd,
+ int (*make_ancestor) (char const *, char const *,
+ void *),
+ void *options,
+ mode_t mode,
+ void (*announce) (char const *, void *),
+ mode_t mode_bits,
+ uid_t owner,
+ gid_t group,
+ bool preserve_existing);
diff --git a/lib/mkdir.c b/lib/mkdir.c
index 5a0c4b0..59bdea1 100644
--- a/lib/mkdir.c
+++ b/lib/mkdir.c
@@ -1,12 +1,12 @@
/* On some systems, mkdir ("foo/", 0700) fails because of the trailing
slash. On those systems, this wrapper removes the trailing slash.
- Copyright (C) 2001, 2003, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2001, 2003, 2006, 2008-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,31 +14,41 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* written by Jim Meyering */
#include <config.h>
-/* Disable the definition of mkdir to rpl_mkdir (from config.h) in this
- file. Otherwise, we'd get conflicting prototypes for rpl_mkdir on
- most systems. */
-#undef mkdir
-
-#include <sys/types.h>
+/* Specification. */
#include <sys/stat.h>
+
+#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "dirname.h"
-#include "xalloc.h"
+
+/* Disable the definition of mkdir to rpl_mkdir (from the <sys/stat.h>
+ substitute) in this file. Otherwise, we'd get an endless recursion. */
+#undef mkdir
+
+/* mingw's _mkdir() function has 1 argument, but we pass 2 arguments.
+ Additionally, it declares _mkdir (and depending on compile flags, an
+ alias mkdir), only in the nonstandard includes <direct.h> and <io.h>,
+ which are included in the <sys/stat.h> override. */
+#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+# define mkdir(name,mode) _mkdir (name)
+# define maybe_unused _GL_UNUSED
+#else
+# define maybe_unused /* empty */
+#endif
/* This function is required at least for NetBSD 1.5.2. */
int
-rpl_mkdir (char const *dir, mode_t mode)
+rpl_mkdir (char const *dir, mode_t mode maybe_unused)
{
int ret_val;
char *tmp_dir;
@@ -46,13 +56,33 @@ rpl_mkdir (char const *dir, mode_t mode)
if (len && dir[len - 1] == '/')
{
- tmp_dir = xstrdup (dir);
+ tmp_dir = strdup (dir);
+ if (!tmp_dir)
+ {
+ /* Rather than rely on strdup-posix, we set errno ourselves. */
+ errno = ENOMEM;
+ return -1;
+ }
strip_trailing_slashes (tmp_dir);
}
else
{
tmp_dir = (char *) dir;
}
+#if FUNC_MKDIR_DOT_BUG
+ /* Additionally, cygwin 1.5 mistakenly creates a directory "d/./". */
+ {
+ char *last = last_component (tmp_dir);
+ if (*last == '.' && (last[1] == '\0'
+ || (last[1] == '.' && last[2] == '\0')))
+ {
+ struct stat st;
+ if (stat (tmp_dir, &st) == 0)
+ errno = EEXIST;
+ return -1;
+ }
+ }
+#endif /* FUNC_MKDIR_DOT_BUG */
ret_val = mkdir (tmp_dir, mode);
diff --git a/lib/mkdirat.c b/lib/mkdirat.c
deleted file mode 100644
index da0b262..0000000
--- a/lib/mkdirat.c
+++ /dev/null
@@ -1,43 +0,0 @@
-/* fd-relative mkdir
- Copyright (C) 2005, 2006 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-/* written by Jim Meyering */
-
-#include <config.h>
-
-#include "openat.h"
-
-#include <unistd.h>
-
-#include "dirname.h" /* solely for definition of IS_ABSOLUTE_FILE_NAME */
-#include "save-cwd.h"
-#include "openat-priv.h"
-
-/* Solaris 10 has no function like this.
- Create a subdirectory, FILE, with mode MODE, in the directory
- open on descriptor FD. If possible, do it without changing the
- working directory. Otherwise, resort to using save_cwd/fchdir,
- then mkdir/restore_cwd. If either the save_cwd or the restore_cwd
- fails, then give a diagnostic and exit nonzero. */
-
-#define AT_FUNC_NAME mkdirat
-#define AT_FUNC_F1 mkdir
-#define AT_FUNC_F2 mkdir
-#define AT_FUNC_USE_F1_COND 1
-#define AT_FUNC_POST_FILE_PARAM_DECLS , mode_t mode
-#define AT_FUNC_POST_FILE_ARGS , mode
-#include "at-func.c"
diff --git a/lib/mkfifo.c b/lib/mkfifo.c
new file mode 100644
index 0000000..6f94a9e
--- /dev/null
+++ b/lib/mkfifo.c
@@ -0,0 +1,58 @@
+/* Create a named fifo.
+ Copyright (C) 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* written by Eric Blake */
+
+#include <config.h>
+
+#include <sys/stat.h>
+
+#include <errno.h>
+#include <string.h>
+
+#if !HAVE_MKFIFO
+/* Mingw lacks mkfifo; always fail with ENOSYS. */
+
+int
+mkfifo (char const *name _GL_UNUSED, mode_t mode _GL_UNUSED)
+{
+ errno = ENOSYS;
+ return -1;
+}
+
+#else /* HAVE_MKFIFO */
+
+# undef mkfifo
+
+/* Create a named fifo FILE, with access permissions in MODE. Work
+around trailing slash bugs. */
+
+int
+rpl_mkfifo (char const *name, mode_t mode)
+{
+# if MKFIFO_TRAILING_SLASH_BUG
+ size_t len = strlen (name);
+ if (len && name[len - 1] == '/')
+ {
+ struct stat st;
+ if (stat (name, &st) == 0)
+ errno = EEXIST;
+ return -1;
+ }
+# endif
+ return mkfifo (name, mode);
+}
+#endif /* HAVE_MKFIFO */
diff --git a/lib/mknod.c b/lib/mknod.c
new file mode 100644
index 0000000..26e80cc
--- /dev/null
+++ b/lib/mknod.c
@@ -0,0 +1,74 @@
+/* Create a device inode.
+ Copyright (C) 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* written by Eric Blake */
+
+#include <config.h>
+
+#include <sys/stat.h>
+
+#include <errno.h>
+#include <string.h>
+
+#if !HAVE_MKNOD
+/* Mingw lacks mknod; always fail with ENOSYS. */
+
+int
+mknod (char const *name _GL_UNUSED, mode_t mode _GL_UNUSED,
+ dev_t dev _GL_UNUSED)
+{
+ errno = ENOSYS;
+ return -1;
+}
+
+#else /* HAVE_MKNOD */
+
+# undef mknod
+
+/* Create a file system node FILE, with access permissions and file
+ type in MODE, and device type in DEV. Usually, non-root
+ applications can only create named fifos (mode includes S_IFIFO),
+ with DEV set to 0. Also work around trailing slash bugs. */
+
+int
+rpl_mknod (char const *name, mode_t mode, dev_t dev)
+{
+# if MKFIFO_TRAILING_SLASH_BUG
+ /* Trailing slash only makes sense for directories. Of course,
+ using mknod to create a directory is not very portable, so it may
+ still fail later on. */
+ if (!S_ISDIR (mode))
+ {
+ size_t len = strlen (name);
+ if (len && name[len - 1] == '/')
+ {
+ struct stat st;
+ if (stat (name, &st) == 0)
+ errno = EEXIST;
+ return -1;
+ }
+ }
+# endif
+# if MKNOD_FIFO_BUG
+ /* POSIX requires mknod to create fifos for non-privileged
+ processes, but BSD implementations fail with EPERM. */
+ if (S_ISFIFO (mode) && dev == 0)
+ return mkfifo (name, mode & ~S_IFIFO);
+# endif
+ return mknod (name, mode, dev);
+}
+
+#endif /* HAVE_MKNOD */
diff --git a/lib/mkstemp-safer.c b/lib/mkstemp-safer.c
index ff1c0d4..c800904 100644
--- a/lib/mkstemp-safer.c
+++ b/lib/mkstemp-safer.c
@@ -1,11 +1,11 @@
/* Invoke mkstemp, but avoid some glitches.
- Copyright (C) 2005, 2006, 2007 Free Software Foundation, Inc.
+ Copyright (C) 2005-2007, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
@@ -33,3 +32,32 @@ mkstemp_safer (char *templ)
{
return fd_safer (mkstemp (templ));
}
+
+#if GNULIB_MKOSTEMP
+/* Like mkostemp, but do not return STDIN_FILENO, STDOUT_FILENO, or
+ STDERR_FILENO. */
+int
+mkostemp_safer (char *templ, int flags)
+{
+ return fd_safer_flag (mkostemp (templ, flags), flags);
+}
+#endif
+
+#if GNULIB_MKOSTEMPS
+/* Like mkostemps, but do not return STDIN_FILENO, STDOUT_FILENO, or
+ STDERR_FILENO. */
+int
+mkostemps_safer (char *templ, int suffixlen, int flags)
+{
+ return fd_safer_flag (mkostemps (templ, suffixlen, flags), flags);
+}
+#endif
+
+#if GNULIB_MKSTEMPS
+/* Like mkstemps, but do not return STDIN_FILENO, STDOUT_FILENO, or
+ STDERR_FILENO. */
+int mkstemps_safer (char *templ, int suffixlen)
+{
+ return fd_safer (mkstemps (templ, suffixlen));
+}
+#endif
diff --git a/lib/mkstemp.c b/lib/mkstemp.c
index 57ee228..90ed78e 100644
--- a/lib/mkstemp.c
+++ b/lib/mkstemp.c
@@ -1,19 +1,19 @@
-/* Copyright (C) 1998, 1999, 2001, 2005, 2006, 2007 Free Software Foundation, Inc.
+/* Copyright (C) 1998-1999, 2001, 2005-2007, 2009-2016 Free Software
+ Foundation, Inc.
This file is derived from the one in the GNU C Library.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#if !_LIBC
# include <config.h>
@@ -24,7 +24,9 @@
#if !_LIBC
# include "tempname.h"
# define __gen_tempname gen_tempname
-# define __GT_FILE GT_FILE
+# ifndef __GT_FILE
+# define __GT_FILE GT_FILE
+# endif
#endif
#include <stdio.h>
@@ -33,13 +35,16 @@
# define __GT_FILE 0
#endif
-/* Generate a unique temporary file name from TEMPLATE.
- The last six characters of TEMPLATE must be "XXXXXX";
+/* Generate a unique temporary file name from XTEMPLATE.
+ The last six characters of XTEMPLATE must be "XXXXXX";
they are replaced with a string that makes the file name unique.
- Then open the file and return a fd. */
+ Then open the file and return a fd.
+
+ If you are creating temporary files which will later be removed,
+ consider using the clean-temp module, which avoids several pitfalls
+ of using mkstemp directly. */
int
-mkstemp (template)
- char *template;
+mkstemp (char *xtemplate)
{
- return __gen_tempname (template, __GT_FILE);
+ return __gen_tempname (xtemplate, 0, 0, __GT_FILE);
}
diff --git a/lib/mktime-internal.h b/lib/mktime-internal.h
new file mode 100644
index 0000000..4287acf
--- /dev/null
+++ b/lib/mktime-internal.h
@@ -0,0 +1,4 @@
+#include <time.h>
+time_t mktime_internal (struct tm *,
+ struct tm * (*) (time_t const *, struct tm *),
+ time_t *);
diff --git a/lib/mktime.c b/lib/mktime.c
index a91fb20..c9738d0 100644
--- a/lib/mktime.c
+++ b/lib/mktime.c
@@ -1,32 +1,32 @@
-/* Convert a `struct tm' to a time_t value.
- Copyright (C) 1993-1999, 2002-2005, 2006, 2007 Free Software Foundation, Inc.
+/* Convert a 'struct tm' to a time_t value.
+ Copyright (C) 1993-2016 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Paul Eggert <eggert@twinsun.com>.
- 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 2, or (at your option)
- any later version.
+ The GNU C Library 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,
+ The GNU C Library 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.
+ 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ You should have received a copy of the GNU General Public
+ License along with the GNU C Library; if not, see
+ <http://www.gnu.org/licenses/>. */
/* Define this to have a standalone program to test this implementation of
mktime. */
-/* #define DEBUG 1 */
+/* #define DEBUG_MKTIME 1 */
#ifndef _LIBC
# include <config.h>
#endif
/* Assume that leap seconds are possible, unless told otherwise.
- If the host has a `zic' command with a `-L leapsecondfilename' option,
+ If the host has a 'zic' command with a '-L leapsecondfilename' option,
then it supports leap seconds; otherwise it probably doesn't. */
#ifndef LEAP_SECONDS_POSSIBLE
# define LEAP_SECONDS_POSSIBLE 1
@@ -38,12 +38,46 @@
#include <string.h> /* For the real memcpy prototype. */
-#if DEBUG
+#if defined DEBUG_MKTIME && DEBUG_MKTIME
# include <stdio.h>
# include <stdlib.h>
/* Make it work even if the system's libc has its own mktime routine. */
+# undef mktime
# define mktime my_mktime
-#endif /* DEBUG */
+#endif /* DEBUG_MKTIME */
+
+/* Some of the code in this file assumes that signed integer overflow
+ silently wraps around. This assumption can't easily be programmed
+ around, nor can it be checked for portably at compile-time or
+ easily eliminated at run-time.
+
+ Define WRAPV to 1 if the assumption is valid and if
+ #pragma GCC optimize ("wrapv")
+ does not trigger GCC bug 51793
+ <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=51793>.
+ Otherwise, define it to 0; this forces the use of slower code that,
+ while not guaranteed by the C Standard, works on all production
+ platforms that we know about. */
+#ifndef WRAPV
+# if (((__GNUC__ == 4 && 4 <= __GNUC_MINOR__) || 4 < __GNUC__) \
+ && defined __GLIBC__)
+# pragma GCC optimize ("wrapv")
+# define WRAPV 1
+# else
+# define WRAPV 0
+# endif
+#endif
+
+/* Verify a requirement at compile-time (unlike assert, which is runtime). */
+#define verify(name, assertion) struct name { char a[(assertion) ? 1 : -1]; }
+
+/* A signed type that is at least one bit wider than int. */
+#if INT_MAX <= LONG_MAX / 2
+typedef long int long_int;
+#else
+typedef long long int long_int;
+#endif
+verify (long_int_is_wide_enough, INT_MAX == INT_MAX * (long_int) 2 / 2);
/* Shift A right by B bits portably, by dividing A by 2**B and
truncating towards minus infinity. A and B should be free of side
@@ -55,9 +89,11 @@
implementations (e.g., UNICOS 9.0 on a Cray Y-MP EL) don't shift
right in the usual way when A < 0, so SHR falls back on division if
ordinary A >> B doesn't seem to be the usual signed shift. */
-#define SHR(a, b) \
- (-1 >> 1 == -1 \
- ? (a) >> (b) \
+#define SHR(a, b) \
+ ((-1 >> 1 == -1 \
+ && (long_int) -1 >> 1 == -1 \
+ && ((time_t) -1 >> 1 == -1 || ! TYPE_SIGNED (time_t))) \
+ ? (a) >> (b) \
: (a) / (1 << (b)) - ((a) % (1 << (b)) < 0))
/* The extra casts in the following macros work around compiler bugs,
@@ -68,12 +104,8 @@
#define TYPE_IS_INTEGER(t) ((t) 1.5 == 1)
/* True if negative values of the signed integer type T use two's
- complement, ones' complement, or signed magnitude representation,
- respectively. Much GNU code assumes two's complement, but some
- people like to be portable to all possible C hosts. */
+ complement, or if T is an unsigned integer type. */
#define TYPE_TWOS_COMPLEMENT(t) ((t) ~ (t) 0 == (t) -1)
-#define TYPE_ONES_COMPLEMENT(t) ((t) ~ (t) 0 == 0)
-#define TYPE_SIGNED_MAGNITUDE(t) ((t) ~ (t) 0 < (t) -1)
/* True if the arithmetic type T is signed. */
#define TYPE_SIGNED(t) (! ((t) 0 < (t) -1))
@@ -85,13 +117,11 @@
#define TYPE_MINIMUM(t) \
((t) (! TYPE_SIGNED (t) \
? (t) 0 \
- : TYPE_SIGNED_MAGNITUDE (t) \
- ? ~ (t) 0 \
- : ~ (t) 0 << (sizeof (t) * CHAR_BIT - 1)))
+ : ~ TYPE_MAXIMUM (t)))
#define TYPE_MAXIMUM(t) \
((t) (! TYPE_SIGNED (t) \
? (t) -1 \
- : ~ (~ (t) 0 << (sizeof (t) * CHAR_BIT - 1))))
+ : ((((t) 1 << (sizeof (t) * CHAR_BIT - 2)) - 1) * 2 + 1)))
#ifndef TIME_T_MIN
# define TIME_T_MIN TYPE_MINIMUM (time_t)
@@ -101,22 +131,19 @@
#endif
#define TIME_T_MIDPOINT (SHR (TIME_T_MIN + TIME_T_MAX, 1) + 1)
-/* Verify a requirement at compile-time (unlike assert, which is runtime). */
-#define verify(name, assertion) struct name { char a[(assertion) ? 1 : -1]; }
-
verify (time_t_is_integer, TYPE_IS_INTEGER (time_t));
-verify (twos_complement_arithmetic, TYPE_TWOS_COMPLEMENT (int));
-/* The code also assumes that signed integer overflow silently wraps
- around, but this assumption can't be stated without causing a
- diagnostic on some hosts. */
+verify (twos_complement_arithmetic,
+ (TYPE_TWOS_COMPLEMENT (int)
+ && TYPE_TWOS_COMPLEMENT (long_int)
+ && TYPE_TWOS_COMPLEMENT (time_t)));
#define EPOCH_YEAR 1970
#define TM_YEAR_BASE 1900
verify (base_year_is_a_multiple_of_100, TM_YEAR_BASE % 100 == 0);
/* Return 1 if YEAR + TM_YEAR_BASE is a leap year. */
-static inline int
-leapyear (long int year)
+static int
+leapyear (long_int year)
{
/* Don't add YEAR to TM_YEAR_BASE, as that might overflow.
Also, work even if YEAR is negative. */
@@ -147,8 +174,17 @@ const unsigned short int __mon_yday[2][13] =
# undef __localtime_r
# define __localtime_r localtime_r
# define __mktime_internal mktime_internal
+# include "mktime-internal.h"
#endif
+/* Return 1 if the values A and B differ according to the rules for
+ tm_isdst: A and B differ if one is zero and the other positive. */
+static int
+isdst_differ (int a, int b)
+{
+ return (!a != !b) && (0 <= a) && (0 <= b);
+}
+
/* Return an integer value measuring (YEAR1-YDAY1 HOUR1:MIN1:SEC1) -
(YEAR0-YDAY0 HOUR0:MIN0:SEC0) in seconds, assuming that the clocks
were not adjusted between the time stamps.
@@ -160,13 +196,11 @@ const unsigned short int __mon_yday[2][13] =
The result may overflow. It is the caller's responsibility to
detect overflow. */
-static inline time_t
-ydhms_diff (long int year1, long int yday1, int hour1, int min1, int sec1,
+static time_t
+ydhms_diff (long_int year1, long_int yday1, int hour1, int min1, int sec1,
int year0, int yday0, int hour0, int min0, int sec0)
{
verify (C99_integer_division, -1 / 2 == 0);
- verify (long_int_year_and_yday_are_wide_enough,
- INT_MAX <= LONG_MAX / 2 || TIME_T_MAX <= UINT_MAX);
/* Compute intervening leap days correctly even if year is negative.
Take care to avoid integer overflow here. */
@@ -189,6 +223,53 @@ ydhms_diff (long int year1, long int yday1, int hour1, int min1, int sec1,
return seconds;
}
+/* Return the average of A and B, even if A + B would overflow. */
+static time_t
+time_t_avg (time_t a, time_t b)
+{
+ return SHR (a, 1) + SHR (b, 1) + (a & b & 1);
+}
+
+/* Return 1 if A + B does not overflow. If time_t is unsigned and if
+ B's top bit is set, assume that the sum represents A - -B, and
+ return 1 if the subtraction does not wrap around. */
+static int
+time_t_add_ok (time_t a, time_t b)
+{
+ if (! TYPE_SIGNED (time_t))
+ {
+ time_t sum = a + b;
+ return (sum < a) == (TIME_T_MIDPOINT <= b);
+ }
+ else if (WRAPV)
+ {
+ time_t sum = a + b;
+ return (sum < a) == (b < 0);
+ }
+ else
+ {
+ time_t avg = time_t_avg (a, b);
+ return TIME_T_MIN / 2 <= avg && avg <= TIME_T_MAX / 2;
+ }
+}
+
+/* Return 1 if A + B does not overflow. */
+static int
+time_t_int_add_ok (time_t a, int b)
+{
+ verify (int_no_wider_than_time_t, INT_MAX <= TIME_T_MAX);
+ if (WRAPV)
+ {
+ time_t sum = a + b;
+ return (sum < a) == (b < 0);
+ }
+ else
+ {
+ int a_odd = a & 1;
+ time_t avg = SHR (a, 1) + (SHR (b, 1) + (a_odd & b));
+ return TIME_T_MIN / 2 <= avg && avg <= TIME_T_MAX / 2;
+ }
+}
/* Return a time_t value corresponding to (YEAR-YDAY HOUR:MIN:SEC),
assuming that *T corresponds to *TP and that no clock adjustments
@@ -197,7 +278,7 @@ ydhms_diff (long int year1, long int yday1, int hour1, int min1, int sec1,
If overflow occurs, yield the minimal or maximal value, except do not
yield a value equal to *T. */
static time_t
-guess_time_tm (long int year, long int yday, int hour, int min, int sec,
+guess_time_tm (long_int year, long_int yday, int hour, int min, int sec,
const time_t *t, const struct tm *tp)
{
if (tp)
@@ -205,9 +286,8 @@ guess_time_tm (long int year, long int yday, int hour, int min, int sec,
time_t d = ydhms_diff (year, yday, hour, min, sec,
tp->tm_year, tp->tm_yday,
tp->tm_hour, tp->tm_min, tp->tm_sec);
- time_t t1 = *t + d;
- if ((t1 < *t) == (TYPE_SIGNED (time_t) ? d < 0 : TIME_T_MAX / 2 < d))
- return t1;
+ if (time_t_add_ok (*t, d))
+ return *t + d;
}
/* Overflow occurred one way or another. Return the nearest result
@@ -239,9 +319,7 @@ ranged_convert (struct tm *(*convert) (const time_t *, struct tm *),
they differ by 1. */
while (bad != ok + (bad < 0 ? -1 : 1))
{
- time_t mid = *t = (bad < 0
- ? bad + ((ok - bad) >> 1)
- : ok + ((bad - ok) >> 1));
+ time_t mid = *t = time_t_avg (ok, bad);
r = convert (t, tp);
if (r)
ok = mid;
@@ -299,8 +377,8 @@ __mktime_internal (struct tm *tp,
int mon_remainder = mon % 12;
int negative_mon_remainder = mon_remainder < 0;
int mon_years = mon / 12 - negative_mon_remainder;
- long int lyear_requested = year_requested;
- long int year = lyear_requested + mon_years;
+ long_int lyear_requested = year_requested;
+ long_int year = lyear_requested + mon_years;
/* The other values need not be in range:
the remaining code handles minor overflows correctly,
@@ -312,8 +390,8 @@ __mktime_internal (struct tm *tp,
int mon_yday = ((__mon_yday[leapyear (year)]
[mon_remainder + 12 * negative_mon_remainder])
- 1);
- long int lmday = mday;
- long int yday = mon_yday + lmday;
+ long_int lmday = mday;
+ long_int yday = mon_yday + lmday;
time_t guessed_offset = *offset;
@@ -367,9 +445,9 @@ __mktime_internal (struct tm *tp,
int approx_biennia = SHR (t0, ALOG2_SECONDS_PER_BIENNIUM);
int diff = approx_biennia - approx_requested_biennia;
- int abs_diff = diff < 0 ? - diff : diff;
+ int approx_abs_diff = diff < 0 ? -1 - diff : diff;
- /* IRIX 4.0.5 cc miscaculates TIME_T_MIN / 3: it erroneously
+ /* IRIX 4.0.5 cc miscalculates TIME_T_MIN / 3: it erroneously
gives a positive value of 715827882. Setting a variable
first then doing math on it seems to work.
(ghazi@caip.rutgers.edu) */
@@ -378,15 +456,15 @@ __mktime_internal (struct tm *tp,
time_t overflow_threshold =
(time_t_max / 3 - time_t_min / 3) >> ALOG2_SECONDS_PER_BIENNIUM;
- if (overflow_threshold < abs_diff)
+ if (overflow_threshold < approx_abs_diff)
{
/* Overflow occurred. Try repairing it; this might work if
the time zone offset is enough to undo the overflow. */
time_t repaired_t0 = -1 - t0;
approx_biennia = SHR (repaired_t0, ALOG2_SECONDS_PER_BIENNIUM);
diff = approx_biennia - approx_requested_biennia;
- abs_diff = diff < 0 ? - diff : diff;
- if (overflow_threshold < abs_diff)
+ approx_abs_diff = diff < 0 ? -1 - diff : diff;
+ if (overflow_threshold < approx_abs_diff)
return -1;
guessed_offset += repaired_t0 - t0;
t0 = repaired_t0;
@@ -420,7 +498,7 @@ __mktime_internal (struct tm *tp,
/* We have a match. Check whether tm.tm_isdst has the requested
value, if any. */
- if (isdst != tm.tm_isdst && 0 <= isdst && 0 <= tm.tm_isdst)
+ if (isdst_differ (isdst, tm.tm_isdst))
{
/* tm.tm_isdst has the wrong value. Look for a neighboring
time with the right value, and use its UTC offset.
@@ -453,22 +531,20 @@ __mktime_internal (struct tm *tp,
for (delta = stride; delta < delta_bound; delta += stride)
for (direction = -1; direction <= 1; direction += 2)
- {
- time_t ot = t + delta * direction;
- if ((ot < t) == (direction < 0))
- {
- struct tm otm;
- ranged_convert (convert, &ot, &otm);
- if (otm.tm_isdst == isdst)
- {
- /* We found the desired tm_isdst.
- Extrapolate back to the desired time. */
- t = guess_time_tm (year, yday, hour, min, sec, &ot, &otm);
- ranged_convert (convert, &t, &tm);
- goto offset_found;
- }
- }
- }
+ if (time_t_int_add_ok (t, delta * direction))
+ {
+ time_t ot = t + delta * direction;
+ struct tm otm;
+ ranged_convert (convert, &ot, &otm);
+ if (! isdst_differ (isdst, otm.tm_isdst))
+ {
+ /* We found the desired tm_isdst.
+ Extrapolate back to the desired time. */
+ t = guess_time_tm (year, yday, hour, min, sec, &ot, &otm);
+ ranged_convert (convert, &t, &tm);
+ goto offset_found;
+ }
+ }
}
offset_found:
@@ -479,11 +555,13 @@ __mktime_internal (struct tm *tp,
/* Adjust time to reflect the tm_sec requested, not the normalized value.
Also, repair any damage from a false match due to a leap second. */
int sec_adjustment = (sec == 0 && tm.tm_sec == 60) - sec;
+ if (! time_t_int_add_ok (t, sec_requested))
+ return -1;
t1 = t + sec_requested;
+ if (! time_t_int_add_ok (t1, sec_adjustment))
+ return -1;
t2 = t1 + sec_adjustment;
- if (((t1 < t) != (sec_requested < 0))
- | ((t2 < t1) != (sec_adjustment < 0))
- | ! convert (&t2, &tm))
+ if (! convert (&t2, &tm))
return -1;
t = t2;
}
@@ -505,7 +583,7 @@ mktime (struct tm *tp)
{
#ifdef _LIBC
/* POSIX.1 8.1.1 requires that whenever mktime() is called, the
- time zone names contained in the external variable `tzname' shall
+ time zone names contained in the external variable 'tzname' shall
be set as if the tzset() function had been called. */
__tzset ();
#endif
@@ -522,7 +600,7 @@ libc_hidden_def (mktime)
libc_hidden_weak (timelocal)
#endif
-#if DEBUG
+#if defined DEBUG_MKTIME && DEBUG_MKTIME
static int
not_equal_tm (const struct tm *a, const struct tm *b)
@@ -534,7 +612,7 @@ not_equal_tm (const struct tm *a, const struct tm *b)
| (a->tm_mon ^ b->tm_mon)
| (a->tm_year ^ b->tm_year)
| (a->tm_yday ^ b->tm_yday)
- | (a->tm_isdst ^ b->tm_isdst));
+ | isdst_differ (a->tm_isdst, b->tm_isdst));
}
static void
@@ -654,10 +732,10 @@ main (int argc, char **argv)
return status;
}
-#endif /* DEBUG */
+#endif /* DEBUG_MKTIME */
/*
Local Variables:
-compile-command: "gcc -DDEBUG -Wall -W -O -g mktime.c -o mktime"
+compile-command: "gcc -DDEBUG_MKTIME -I. -Wall -W -O2 -g mktime.c -o mktime"
End:
*/
diff --git a/lib/modechange.c b/lib/modechange.c
index e1f7ceb..971a9b3 100644
--- a/lib/modechange.c
+++ b/lib/modechange.c
@@ -1,12 +1,12 @@
/* modechange.c -- file mode manipulation
- Copyright (C) 1989, 1990, 1997, 1998, 1999, 2001, 2003, 2004, 2005,
- 2006 Free Software Foundation, Inc.
+ Copyright (C) 1989-1990, 1997-1999, 2001, 2003-2006, 2009-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,12 +14,11 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by David MacKenzie <djm@ai.mit.edu> */
-/* The ASCII mode string is compiled into an array of `struct
+/* The ASCII mode string is compiled into an array of 'struct
modechange', which can then be applied to each file to be changed.
We do this instead of re-parsing the ASCII string for each file
because the compiled form requires less computation to use; when
@@ -57,22 +56,22 @@ octal_to_mode (unsigned int octal)
/* Help the compiler optimize the usual case where mode_t uses
the traditional octal representation. */
return ((S_ISUID == SUID && S_ISGID == SGID && S_ISVTX == SVTX
- && S_IRUSR == RUSR && S_IWUSR == WUSR && S_IXUSR == XUSR
- && S_IRGRP == RGRP && S_IWGRP == WGRP && S_IXGRP == XGRP
- && S_IROTH == ROTH && S_IWOTH == WOTH && S_IXOTH == XOTH)
- ? octal
- : (mode_t) ((octal & SUID ? S_ISUID : 0)
- | (octal & SGID ? S_ISGID : 0)
- | (octal & SVTX ? S_ISVTX : 0)
- | (octal & RUSR ? S_IRUSR : 0)
- | (octal & WUSR ? S_IWUSR : 0)
- | (octal & XUSR ? S_IXUSR : 0)
- | (octal & RGRP ? S_IRGRP : 0)
- | (octal & WGRP ? S_IWGRP : 0)
- | (octal & XGRP ? S_IXGRP : 0)
- | (octal & ROTH ? S_IROTH : 0)
- | (octal & WOTH ? S_IWOTH : 0)
- | (octal & XOTH ? S_IXOTH : 0)));
+ && S_IRUSR == RUSR && S_IWUSR == WUSR && S_IXUSR == XUSR
+ && S_IRGRP == RGRP && S_IWGRP == WGRP && S_IXGRP == XGRP
+ && S_IROTH == ROTH && S_IWOTH == WOTH && S_IXOTH == XOTH)
+ ? octal
+ : (mode_t) ((octal & SUID ? S_ISUID : 0)
+ | (octal & SGID ? S_ISGID : 0)
+ | (octal & SVTX ? S_ISVTX : 0)
+ | (octal & RUSR ? S_IRUSR : 0)
+ | (octal & WUSR ? S_IWUSR : 0)
+ | (octal & XUSR ? S_IXUSR : 0)
+ | (octal & RGRP ? S_IRGRP : 0)
+ | (octal & WGRP ? S_IWGRP : 0)
+ | (octal & XGRP ? S_IXGRP : 0)
+ | (octal & ROTH ? S_IROTH : 0)
+ | (octal & WOTH ? S_IWOTH : 0)
+ | (octal & XOTH ? S_IXOTH : 0)));
}
/* Special operations flags. */
@@ -91,22 +90,22 @@ enum
/* Instead of the typical case, copy some existing permissions for
u, g, or o onto the other two. Which of u, g, or o is copied
- is determined by which bits are set in the `value' field. */
+ is determined by which bits are set in the 'value' field. */
MODE_COPY_EXISTING
};
/* Description of a mode change. */
struct mode_change
{
- char op; /* One of "=+-". */
- char flag; /* Special operations flag. */
- mode_t affected; /* Set for u, g, o, or a. */
- mode_t value; /* Bits to add/remove. */
- mode_t mentioned; /* Bits explicitly mentioned. */
+ char op; /* One of "=+-". */
+ char flag; /* Special operations flag. */
+ mode_t affected; /* Set for u, g, o, or a. */
+ mode_t value; /* Bits to add/remove. */
+ mode_t mentioned; /* Bits explicitly mentioned. */
};
-/* Return a mode_change array with the specified `=ddd'-style
- mode change operation, where NEW_MODE is `ddd' and MENTIONED
+/* Return a mode_change array with the specified "=ddd"-style
+ mode change operation, where NEW_MODE is "ddd" and MENTIONED
contains the bits explicitly mentioned in the mode are MENTIONED. */
static struct mode_change *
@@ -128,7 +127,7 @@ make_node_op_equals (mode_t new_mode, mode_t mentioned)
the form:
[ugoa...][[+-=][rwxXstugo...]...][,...]
- Return NULL if `mode_string' does not contain a valid
+ Return NULL if 'mode_string' does not contain a valid
representation of file mode change operations. */
struct mode_change *
@@ -137,6 +136,7 @@ mode_compile (char const *mode_string)
/* The array of mode-change directives to be returned. */
struct mode_change *mc;
size_t used = 0;
+ char const *p;
if ('0' <= *mode_string && *mode_string < '8')
{
@@ -144,133 +144,161 @@ mode_compile (char const *mode_string)
mode_t mode;
mode_t mentioned;
+ p = mode_string;
do
- {
- octal_mode = 8 * octal_mode + *mode_string++ - '0';
- if (ALLM < octal_mode)
- return NULL;
- }
- while ('0' <= *mode_string && *mode_string < '8');
+ {
+ octal_mode = 8 * octal_mode + *p++ - '0';
+ if (ALLM < octal_mode)
+ return NULL;
+ }
+ while ('0' <= *p && *p < '8');
- if (*mode_string)
- return NULL;
+ if (*p)
+ return NULL;
mode = octal_to_mode (octal_mode);
- mentioned = (mode & (S_ISUID | S_ISGID)) | S_ISVTX | S_IRWXUGO;
+ mentioned = (p - mode_string < 5
+ ? (mode & (S_ISUID | S_ISGID)) | S_ISVTX | S_IRWXUGO
+ : CHMOD_MODE_BITS);
return make_node_op_equals (mode, mentioned);
}
/* Allocate enough space to hold the result. */
{
size_t needed = 1;
- char const *p;
for (p = mode_string; *p; p++)
needed += (*p == '=' || *p == '+' || *p == '-');
mc = xnmalloc (needed, sizeof *mc);
}
- /* One loop iteration for each `[ugoa]*([-+=]([rwxXst]*|[ugo]))+'. */
- for (;; mode_string++)
+ /* One loop iteration for each
+ '[ugoa]*([-+=]([rwxXst]*|[ugo]))+|[-+=][0-7]+'. */
+ for (p = mode_string; ; p++)
{
/* Which bits in the mode are operated on. */
mode_t affected = 0;
- /* Turn on all the bits in `affected' for each group given. */
- for (;; mode_string++)
- switch (*mode_string)
- {
- default:
- goto invalid;
- case 'u':
- affected |= S_ISUID | S_IRWXU;
- break;
- case 'g':
- affected |= S_ISGID | S_IRWXG;
- break;
- case 'o':
- affected |= S_ISVTX | S_IRWXO;
- break;
- case 'a':
- affected |= CHMOD_MODE_BITS;
- break;
- case '=': case '+': case '-':
- goto no_more_affected;
- }
+ /* Turn on all the bits in 'affected' for each group given. */
+ for (;; p++)
+ switch (*p)
+ {
+ default:
+ goto invalid;
+ case 'u':
+ affected |= S_ISUID | S_IRWXU;
+ break;
+ case 'g':
+ affected |= S_ISGID | S_IRWXG;
+ break;
+ case 'o':
+ affected |= S_ISVTX | S_IRWXO;
+ break;
+ case 'a':
+ affected |= CHMOD_MODE_BITS;
+ break;
+ case '=': case '+': case '-':
+ goto no_more_affected;
+ }
no_more_affected:;
do
- {
- char op = *mode_string++;
- mode_t value;
- char flag = MODE_COPY_EXISTING;
- struct mode_change *change;
-
- switch (*mode_string++)
- {
- case 'u':
- /* Set the affected bits to the value of the `u' bits
- on the same file. */
- value = S_IRWXU;
- break;
- case 'g':
- /* Set the affected bits to the value of the `g' bits
- on the same file. */
- value = S_IRWXG;
- break;
- case 'o':
- /* Set the affected bits to the value of the `o' bits
- on the same file. */
- value = S_IRWXO;
- break;
-
- default:
- value = 0;
- flag = MODE_ORDINARY_CHANGE;
-
- for (mode_string--;; mode_string++)
- switch (*mode_string)
- {
- case 'r':
- value |= S_IRUSR | S_IRGRP | S_IROTH;
- break;
- case 'w':
- value |= S_IWUSR | S_IWGRP | S_IWOTH;
- break;
- case 'x':
- value |= S_IXUSR | S_IXGRP | S_IXOTH;
- break;
- case 'X':
- flag = MODE_X_IF_ANY_X;
- break;
- case 's':
- /* Set the setuid/gid bits if `u' or `g' is selected. */
- value |= S_ISUID | S_ISGID;
- break;
- case 't':
- /* Set the "save text image" bit if `o' is selected. */
- value |= S_ISVTX;
- break;
- default:
- goto no_more_values;
- }
- no_more_values:;
- }
-
- change = &mc[used++];
- change->op = op;
- change->flag = flag;
- change->affected = affected;
- change->value = value;
- change->mentioned = (affected ? affected & value : value);
- }
- while (*mode_string == '=' || *mode_string == '+'
- || *mode_string == '-');
-
- if (*mode_string != ',')
- break;
+ {
+ char op = *p++;
+ mode_t value;
+ mode_t mentioned = 0;
+ char flag = MODE_COPY_EXISTING;
+ struct mode_change *change;
+
+ switch (*p)
+ {
+ case '0': case '1': case '2': case '3':
+ case '4': case '5': case '6': case '7':
+ {
+ unsigned int octal_mode = 0;
+
+ do
+ {
+ octal_mode = 8 * octal_mode + *p++ - '0';
+ if (ALLM < octal_mode)
+ goto invalid;
+ }
+ while ('0' <= *p && *p < '8');
+
+ if (affected || (*p && *p != ','))
+ goto invalid;
+ affected = mentioned = CHMOD_MODE_BITS;
+ value = octal_to_mode (octal_mode);
+ flag = MODE_ORDINARY_CHANGE;
+ break;
+ }
+
+ case 'u':
+ /* Set the affected bits to the value of the "u" bits
+ on the same file. */
+ value = S_IRWXU;
+ p++;
+ break;
+ case 'g':
+ /* Set the affected bits to the value of the "g" bits
+ on the same file. */
+ value = S_IRWXG;
+ p++;
+ break;
+ case 'o':
+ /* Set the affected bits to the value of the "o" bits
+ on the same file. */
+ value = S_IRWXO;
+ p++;
+ break;
+
+ default:
+ value = 0;
+ flag = MODE_ORDINARY_CHANGE;
+
+ for (;; p++)
+ switch (*p)
+ {
+ case 'r':
+ value |= S_IRUSR | S_IRGRP | S_IROTH;
+ break;
+ case 'w':
+ value |= S_IWUSR | S_IWGRP | S_IWOTH;
+ break;
+ case 'x':
+ value |= S_IXUSR | S_IXGRP | S_IXOTH;
+ break;
+ case 'X':
+ flag = MODE_X_IF_ANY_X;
+ break;
+ case 's':
+ /* Set the setuid/gid bits if 'u' or 'g' is selected. */
+ value |= S_ISUID | S_ISGID;
+ break;
+ case 't':
+ /* Set the "save text image" bit if 'o' is selected. */
+ value |= S_ISVTX;
+ break;
+ default:
+ goto no_more_values;
+ }
+ no_more_values:;
+ }
+
+ change = &mc[used++];
+ change->op = op;
+ change->flag = flag;
+ change->affected = affected;
+ change->value = value;
+ change->mentioned =
+ (mentioned ? mentioned : affected ? affected & value : value);
+ }
+ while (*p == '=' || *p == '+' || *p == '-');
+
+ if (*p != ',')
+ break;
}
- if (*mode_string == 0)
+ if (*p == 0)
{
mc[used].flag = MODE_DONE;
return mc;
@@ -309,7 +337,7 @@ mode_create_from_ref (const char *ref_file)
mode_t
mode_adjust (mode_t oldmode, bool dir, mode_t umask_value,
- struct mode_change const *changes, mode_t *pmode_bits)
+ struct mode_change const *changes, mode_t *pmode_bits)
{
/* The adjusted mode. */
mode_t newmode = oldmode & CHMOD_MODE_BITS;
@@ -321,63 +349,63 @@ mode_adjust (mode_t oldmode, bool dir, mode_t umask_value,
{
mode_t affected = changes->affected;
mode_t omit_change =
- (dir ? S_ISUID | S_ISGID : 0) & ~ changes->mentioned;
+ (dir ? S_ISUID | S_ISGID : 0) & ~ changes->mentioned;
mode_t value = changes->value;
switch (changes->flag)
- {
- case MODE_ORDINARY_CHANGE:
- break;
-
- case MODE_COPY_EXISTING:
- /* Isolate in `value' the bits in `newmode' to copy. */
- value &= newmode;
-
- /* Copy the isolated bits to the other two parts. */
- value |= ((value & (S_IRUSR | S_IRGRP | S_IROTH)
- ? S_IRUSR | S_IRGRP | S_IROTH : 0)
- | (value & (S_IWUSR | S_IWGRP | S_IWOTH)
- ? S_IWUSR | S_IWGRP | S_IWOTH : 0)
- | (value & (S_IXUSR | S_IXGRP | S_IXOTH)
- ? S_IXUSR | S_IXGRP | S_IXOTH : 0));
- break;
-
- case MODE_X_IF_ANY_X:
- /* Affect the execute bits if execute bits are already set
- or if the file is a directory. */
- if ((newmode & (S_IXUSR | S_IXGRP | S_IXOTH)) | dir)
- value |= S_IXUSR | S_IXGRP | S_IXOTH;
- break;
- }
+ {
+ case MODE_ORDINARY_CHANGE:
+ break;
+
+ case MODE_COPY_EXISTING:
+ /* Isolate in 'value' the bits in 'newmode' to copy. */
+ value &= newmode;
+
+ /* Copy the isolated bits to the other two parts. */
+ value |= ((value & (S_IRUSR | S_IRGRP | S_IROTH)
+ ? S_IRUSR | S_IRGRP | S_IROTH : 0)
+ | (value & (S_IWUSR | S_IWGRP | S_IWOTH)
+ ? S_IWUSR | S_IWGRP | S_IWOTH : 0)
+ | (value & (S_IXUSR | S_IXGRP | S_IXOTH)
+ ? S_IXUSR | S_IXGRP | S_IXOTH : 0));
+ break;
+
+ case MODE_X_IF_ANY_X:
+ /* Affect the execute bits if execute bits are already set
+ or if the file is a directory. */
+ if ((newmode & (S_IXUSR | S_IXGRP | S_IXOTH)) | dir)
+ value |= S_IXUSR | S_IXGRP | S_IXOTH;
+ break;
+ }
/* If WHO was specified, limit the change to the affected bits.
- Otherwise, apply the umask. Either way, omit changes as
- requested. */
+ Otherwise, apply the umask. Either way, omit changes as
+ requested. */
value &= (affected ? affected : ~umask_value) & ~ omit_change;
switch (changes->op)
- {
- case '=':
- /* If WHO was specified, preserve the previous values of
- bits that are not affected by this change operation.
- Otherwise, clear all the bits. */
- {
- mode_t preserved = (affected ? ~affected : 0) | omit_change;
- mode_bits |= CHMOD_MODE_BITS & ~preserved;
- newmode = (newmode & preserved) | value;
- break;
- }
-
- case '+':
- mode_bits |= value;
- newmode |= value;
- break;
-
- case '-':
- mode_bits |= value;
- newmode &= ~value;
- break;
- }
+ {
+ case '=':
+ /* If WHO was specified, preserve the previous values of
+ bits that are not affected by this change operation.
+ Otherwise, clear all the bits. */
+ {
+ mode_t preserved = (affected ? ~affected : 0) | omit_change;
+ mode_bits |= CHMOD_MODE_BITS & ~preserved;
+ newmode = (newmode & preserved) | value;
+ break;
+ }
+
+ case '+':
+ mode_bits |= value;
+ newmode |= value;
+ break;
+
+ case '-':
+ mode_bits |= value;
+ newmode &= ~value;
+ break;
+ }
}
if (pmode_bits)
diff --git a/lib/modechange.h b/lib/modechange.h
index 76e0178..f30277e 100644
--- a/lib/modechange.h
+++ b/lib/modechange.h
@@ -1,12 +1,12 @@
/* modechange.h -- definitions for file mode manipulation
- Copyright (C) 1989, 1990, 1997, 2003, 2004, 2005, 2006 Free
- Software Foundation, Inc.
+ Copyright (C) 1989-1990, 1997, 2003-2006, 2009-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#if ! defined MODECHANGE_H_
# define MODECHANGE_H_
@@ -26,6 +25,6 @@
struct mode_change *mode_compile (const char *);
struct mode_change *mode_create_from_ref (const char *);
mode_t mode_adjust (mode_t, bool, mode_t, struct mode_change const *,
- mode_t *);
+ mode_t *);
#endif
diff --git a/lib/mountlist.c b/lib/mountlist.c
index a50828e..1e592d2 100644
--- a/lib/mountlist.c
+++ b/lib/mountlist.c
@@ -1,12 +1,11 @@
/* mountlist.c -- return a list of mounted file systems
- Copyright (C) 1991, 1992, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
- 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
+ Copyright (C) 1991-1992, 1997-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
@@ -25,6 +23,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#include <stdint.h>
#include "xalloc.h"
@@ -38,10 +37,10 @@
# include <sys/param.h>
#endif
-#if defined MOUNTED_GETFSSTAT /* OSF_1 and Darwin1.3.x */
+#if defined MOUNTED_GETFSSTAT /* OSF_1 and Darwin1.3.x */
# if HAVE_SYS_UCRED_H
# include <grp.h> /* needed on OSF V4.0 for definition of NGROUPS,
- NGROUPS is used as an array dimension in ucred.h */
+ NGROUPS is used as an array dimension in ucred.h */
# include <sys/ucred.h> /* needed by powerpc-apple-darwin1.3.7 */
# endif
# if HAVE_SYS_MOUNT_H
@@ -57,44 +56,45 @@
# endif
#endif /* MOUNTED_GETFSSTAT */
-#ifdef MOUNTED_GETMNTENT1 /* 4.3BSD, SunOS, HP-UX, Dynix, Irix. */
+#ifdef MOUNTED_GETMNTENT1 /* 4.3BSD, SunOS, HP-UX, Dynix, Irix. */
# include <mntent.h>
+# include <sys/types.h>
# if !defined MOUNTED
-# if defined _PATH_MOUNTED /* GNU libc */
+# if defined _PATH_MOUNTED /* GNU libc */
# define MOUNTED _PATH_MOUNTED
# endif
-# if defined MNT_MNTTAB /* HP-UX. */
+# if defined MNT_MNTTAB /* HP-UX. */
# define MOUNTED MNT_MNTTAB
# endif
-# if defined MNTTABNAME /* Dynix. */
+# if defined MNTTABNAME /* Dynix. */
# define MOUNTED MNTTABNAME
# endif
# endif
#endif
-#ifdef MOUNTED_GETMNTINFO /* 4.4BSD. */
+#ifdef MOUNTED_GETMNTINFO /* 4.4BSD. */
# include <sys/mount.h>
#endif
-#ifdef MOUNTED_GETMNTINFO2 /* NetBSD 3.0. */
+#ifdef MOUNTED_GETMNTINFO2 /* NetBSD 3.0. */
# include <sys/statvfs.h>
#endif
-#ifdef MOUNTED_GETMNT /* Ultrix. */
+#ifdef MOUNTED_GETMNT /* Ultrix. */
# include <sys/mount.h>
# include <sys/fs_types.h>
#endif
-#ifdef MOUNTED_FS_STAT_DEV /* BeOS. */
+#ifdef MOUNTED_FS_STAT_DEV /* BeOS. */
# include <fs_info.h>
# include <dirent.h>
#endif
-#ifdef MOUNTED_FREAD /* SVR2. */
+#ifdef MOUNTED_FREAD /* SVR2. */
# include <mnttab.h>
#endif
-#ifdef MOUNTED_FREAD_FSTYP /* SVR3. */
+#ifdef MOUNTED_FREAD_FSTYP /* SVR3. */
# include <mnttab.h>
# include <sys/fstyp.h>
# include <sys/statfs.h>
@@ -104,15 +104,20 @@
# include <mntent.h>
#endif
-#ifdef MOUNTED_GETMNTENT2 /* SVR4. */
+#ifdef MOUNTED_GETMNTENT2 /* SVR4. */
# include <sys/mnttab.h>
#endif
-#ifdef MOUNTED_VMOUNT /* AIX. */
+#ifdef MOUNTED_VMOUNT /* AIX. */
# include <fshelp.h>
# include <sys/vfs.h>
#endif
+#ifdef MOUNTED_INTERIX_STATVFS /* Interix. */
+# include <sys/statvfs.h>
+# include <dirent.h>
+#endif
+
#ifdef DOLPHIN
/* So special that it's not worth putting this in autoconf. */
# undef MOUNTED_FREAD_FSTYP
@@ -124,9 +129,19 @@
# include <sys/mntent.h>
#endif
+#ifndef HAVE_HASMNTOPT
+# define hasmntopt(mnt, opt) ((char *) 0)
+#endif
+
#undef MNT_IGNORE
-#if defined MNTOPT_IGNORE && defined HAVE_HASMNTOPT
-# define MNT_IGNORE(M) hasmntopt ((M), MNTOPT_IGNORE)
+#ifdef MNTOPT_IGNORE
+# if defined __sun && defined __SVR4
+/* Solaris defines hasmntopt(struct mnttab *, char *)
+ while it is otherwise hasmntopt(struct mnttab *, const char *). */
+# define MNT_IGNORE(M) hasmntopt (M, (char *) MNTOPT_IGNORE)
+# else
+# define MNT_IGNORE(M) hasmntopt (M, MNTOPT_IGNORE)
+# endif
#else
# define MNT_IGNORE(M) 0
#endif
@@ -135,41 +150,80 @@
# include "unlocked-io.h"
#endif
-#ifndef SIZE_MAX
-# define SIZE_MAX ((size_t) -1)
-#endif
-
-/* The results of open() in this file are not used with fchdir,
- therefore save some unnecessary work in fchdir.c. */
-#undef open
-#undef close
-
/* The results of opendir() in this file are not used with dirfd and fchdir,
therefore save some unnecessary work in fchdir.c. */
-#undef opendir
-#undef closedir
+#ifdef GNULIB_defined_opendir
+# undef opendir
+#endif
+#ifdef GNULIB_defined_closedir
+# undef closedir
+#endif
-#ifndef ME_DUMMY
+#define ME_DUMMY_0(Fs_name, Fs_type) \
+ (strcmp (Fs_type, "autofs") == 0 \
+ || strcmp (Fs_type, "proc") == 0 \
+ || strcmp (Fs_type, "subfs") == 0 \
+ /* for Linux 2.6/3.x */ \
+ || strcmp (Fs_type, "debugfs") == 0 \
+ || strcmp (Fs_type, "devpts") == 0 \
+ || strcmp (Fs_type, "fusectl") == 0 \
+ || strcmp (Fs_type, "mqueue") == 0 \
+ || strcmp (Fs_type, "rpc_pipefs") == 0 \
+ || strcmp (Fs_type, "sysfs") == 0 \
+ /* FreeBSD, Linux 2.4 */ \
+ || strcmp (Fs_type, "devfs") == 0 \
+ /* for NetBSD 3.0 */ \
+ || strcmp (Fs_type, "kernfs") == 0 \
+ /* for Irix 6.5 */ \
+ || strcmp (Fs_type, "ignore") == 0)
+
+/* Historically, we have marked as "dummy" any file system of type "none",
+ but now that programs like du need to know about bind-mounted directories,
+ we grant an exception to any with "bind" in its list of mount options.
+ I.e., those are *not* dummy entries. */
+#ifdef MOUNTED_GETMNTENT1
+# define ME_DUMMY(Fs_name, Fs_type, Bind) \
+ (ME_DUMMY_0 (Fs_name, Fs_type) \
+ || (strcmp (Fs_type, "none") == 0 && !Bind))
+#else
# define ME_DUMMY(Fs_name, Fs_type) \
- (strcmp (Fs_type, "autofs") == 0 \
- || strcmp (Fs_type, "none") == 0 \
- || strcmp (Fs_type, "proc") == 0 \
- || strcmp (Fs_type, "subfs") == 0 \
- /* for NetBSD 3.0 */ \
- || strcmp (Fs_type, "kernfs") == 0 \
- /* for Irix 6.5 */ \
- || strcmp (Fs_type, "ignore") == 0)
+ (ME_DUMMY_0 (Fs_name, Fs_type) || strcmp (Fs_type, "none") == 0)
+#endif
+
+#ifdef __CYGWIN__
+# include <windows.h>
+# define ME_REMOTE me_remote
+/* All cygwin mount points include ':' or start with '//'; so it
+ requires a native Windows call to determine remote disks. */
+static bool
+me_remote (char const *fs_name, char const *fs_type _GL_UNUSED)
+{
+ if (fs_name[0] && fs_name[1] == ':')
+ {
+ char drive[4];
+ sprintf (drive, "%c:\\", fs_name[0]);
+ switch (GetDriveType (drive))
+ {
+ case DRIVE_REMOVABLE:
+ case DRIVE_FIXED:
+ case DRIVE_CDROM:
+ case DRIVE_RAMDISK:
+ return false;
+ }
+ }
+ return true;
+}
#endif
#ifndef ME_REMOTE
-/* A file system is `remote' if its Fs_name contains a `:'
- or if (it is of type (smbfs or cifs) and its Fs_name starts with `//'). */
-# define ME_REMOTE(Fs_name, Fs_type) \
- (strchr (Fs_name, ':') != NULL \
- || ((Fs_name)[0] == '/' \
- && (Fs_name)[1] == '/' \
- && (strcmp (Fs_type, "smbfs") == 0 \
- || strcmp (Fs_type, "cifs") == 0)))
+/* A file system is "remote" if its Fs_name contains a ':'
+ or if (it is of type (smbfs or cifs) and its Fs_name starts with '//'). */
+# define ME_REMOTE(Fs_name, Fs_type) \
+ (strchr (Fs_name, ':') != NULL \
+ || ((Fs_name)[0] == '/' \
+ && (Fs_name)[1] == '/' \
+ && (strcmp (Fs_type, "smbfs") == 0 \
+ || strcmp (Fs_type, "cifs") == 0)))
#endif
#if MOUNTED_GETMNTINFO
@@ -282,7 +336,7 @@ fsp_to_string (const struct statfs *fsp)
#endif /* MOUNTED_GETMNTINFO */
-#ifdef MOUNTED_VMOUNT /* AIX. */
+#ifdef MOUNTED_VMOUNT /* AIX. */
static char *
fstype_to_string (int t)
{
@@ -301,7 +355,6 @@ fstype_to_string (int t)
/* Return the device number from MOUNT_OPTIONS, if possible.
Otherwise return (dev_t) -1. */
-
static dev_t
dev_from_mount_options (char const *mount_options)
{
@@ -321,19 +374,47 @@ dev_from_mount_options (char const *mount_options)
errno = 0;
dev = strtoul (optval, &optvalend, 16);
if (optval != optvalend
- && (*optvalend == '\0' || *optvalend == ',')
- && ! (dev == ULONG_MAX && errno == ERANGE)
- && dev == (dev_t) dev)
- return dev;
+ && (*optvalend == '\0' || *optvalend == ',')
+ && ! (dev == ULONG_MAX && errno == ERANGE)
+ && dev == (dev_t) dev)
+ return dev;
}
# endif
-
+ (void) mount_options;
return -1;
}
#endif
+#if defined MOUNTED_GETMNTENT1 && defined __linux__
+
+/* Unescape the paths in mount tables.
+ STR is updated in place. */
+
+static void
+unescape_tab (char *str)
+{
+ size_t i, j = 0;
+ size_t len = strlen (str) + 1;
+ for (i = 0; i < len; i++)
+ {
+ if (str[i] == '\\' && (i + 4 < len)
+ && str[i + 1] >= '0' && str[i + 1] <= '3'
+ && str[i + 2] >= '0' && str[i + 2] <= '7'
+ && str[i + 3] >= '0' && str[i + 3] <= '7')
+ {
+ str[j++] = (str[i + 1] - '0') * 64 +
+ (str[i + 2] - '0') * 8 +
+ (str[i + 3] - '0');
+ i += 3;
+ }
+ else
+ str[j++] = str[i];
+ }
+}
+#endif
+
/* Return a list of the currently mounted file systems, or NULL on error.
Add each entry to the tail of the list so that they stay in order.
If NEED_FS_TYPE is true, ensure that the file system type fields in
@@ -345,12 +426,12 @@ read_file_system_list (bool need_fs_type)
struct mount_entry *mount_list;
struct mount_entry *me;
struct mount_entry **mtail = &mount_list;
+ (void) need_fs_type;
#ifdef MOUNTED_LISTMNTENT
{
struct tabmntent *mntlist, *p;
struct mntent *mnt;
- struct mount_entry *me;
/* the third and fourth arguments could be used to filter mounts,
but Crays doesn't seem to have any mounts that we want to
@@ -359,55 +440,157 @@ read_file_system_list (bool need_fs_type)
if (listmntent (&mntlist, KMTAB, NULL, NULL) < 0)
return NULL;
- for (p = mntlist; p; p = p->next) {
- mnt = p->ment;
- me = xmalloc (sizeof *me);
- me->me_devname = xstrdup (mnt->mnt_fsname);
- me->me_mountdir = xstrdup (mnt->mnt_dir);
- me->me_type = xstrdup (mnt->mnt_type);
- me->me_type_malloced = 1;
- me->me_dummy = ME_DUMMY (me->me_devname, me->me_type);
- me->me_remote = ME_REMOTE (me->me_devname, me->me_type);
- me->me_dev = -1;
- *mtail = me;
- mtail = &me->me_next;
- }
+ for (p = mntlist; p; p = p->next)
+ {
+ mnt = p->ment;
+ me = xmalloc (sizeof *me);
+ me->me_devname = xstrdup (mnt->mnt_fsname);
+ me->me_mountdir = xstrdup (mnt->mnt_dir);
+ me->me_mntroot = NULL;
+ me->me_type = xstrdup (mnt->mnt_type);
+ me->me_type_malloced = 1;
+ me->me_dummy = ME_DUMMY (me->me_devname, me->me_type);
+ me->me_remote = ME_REMOTE (me->me_devname, me->me_type);
+ me->me_dev = -1;
+ *mtail = me;
+ mtail = &me->me_next;
+ }
freemntlist (mntlist);
}
#endif
#ifdef MOUNTED_GETMNTENT1 /* GNU/Linux, 4.3BSD, SunOS, HP-UX, Dynix, Irix. */
{
- struct mntent *mnt;
- char *table = MOUNTED;
FILE *fp;
- fp = setmntent (table, "r");
- if (fp == NULL)
- return NULL;
-
- while ((mnt = getmntent (fp)))
+#ifdef __linux__
+ /* Try parsing mountinfo first, as that make device IDs available.
+ Note we could use libmount routines to simplify this parsing a little
+ (and that code is in previous versions of this function), however
+ libmount depends on libselinux which pulls in many dependencies. */
+ char const *mountinfo = "/proc/self/mountinfo";
+ fp = fopen (mountinfo, "r");
+ if (fp != NULL)
{
- me = xmalloc (sizeof *me);
- me->me_devname = xstrdup (mnt->mnt_fsname);
- me->me_mountdir = xstrdup (mnt->mnt_dir);
- me->me_type = xstrdup (mnt->mnt_type);
- me->me_type_malloced = 1;
- me->me_dummy = ME_DUMMY (me->me_devname, me->me_type);
- me->me_remote = ME_REMOTE (me->me_devname, me->me_type);
- me->me_dev = dev_from_mount_options (mnt->mnt_opts);
-
- /* Add to the linked list. */
- *mtail = me;
- mtail = &me->me_next;
+ char *line = NULL;
+ size_t buf_size = 0;
+
+ while (getline (&line, &buf_size, fp) != -1)
+ {
+ unsigned int devmaj, devmin;
+ int target_s, target_e, type_s, type_e;
+ int source_s, source_e, mntroot_s, mntroot_e;
+ char test;
+ char *dash;
+ int rc;
+
+ rc = sscanf(line, "%*u " /* id - discarded */
+ "%*u " /* parent - discarded */
+ "%u:%u " /* dev major:minor */
+ "%n%*s%n " /* mountroot */
+ "%n%*s%n" /* target, start and end */
+ "%c", /* more data... */
+ &devmaj, &devmin,
+ &mntroot_s, &mntroot_e,
+ &target_s, &target_e,
+ &test);
+
+ if (rc != 3 && rc != 7) /* 7 if %n included in count. */
+ continue;
+
+ /* skip optional fields, terminated by " - " */
+ dash = strstr (line + target_e, " - ");
+ if (! dash)
+ continue;
+
+ rc = sscanf(dash, " - "
+ "%n%*s%n " /* FS type, start and end */
+ "%n%*s%n " /* source, start and end */
+ "%c", /* more data... */
+ &type_s, &type_e,
+ &source_s, &source_e,
+ &test);
+ if (rc != 1 && rc != 5) /* 5 if %n included in count. */
+ continue;
+
+ /* manipulate the sub-strings in place. */
+ line[mntroot_e] = '\0';
+ line[target_e] = '\0';
+ dash[type_e] = '\0';
+ dash[source_e] = '\0';
+ unescape_tab (dash + source_s);
+ unescape_tab (line + target_s);
+ unescape_tab (line + mntroot_s);
+
+ me = xmalloc (sizeof *me);
+
+ me->me_devname = xstrdup (dash + source_s);
+ me->me_mountdir = xstrdup (line + target_s);
+ me->me_mntroot = xstrdup (line + mntroot_s);
+ me->me_type = xstrdup (dash + type_s);
+ me->me_type_malloced = 1;
+ me->me_dev = makedev (devmaj, devmin);
+ /* we pass "false" for the "Bind" option as that's only
+ significant when the Fs_type is "none" which will not be
+ the case when parsing "/proc/self/mountinfo", and only
+ applies for static /etc/mtab files. */
+ me->me_dummy = ME_DUMMY (me->me_devname, me->me_type, false);
+ me->me_remote = ME_REMOTE (me->me_devname, me->me_type);
+
+ /* Add to the linked list. */
+ *mtail = me;
+ mtail = &me->me_next;
+ }
+
+ free (line);
+
+ if (ferror (fp))
+ {
+ int saved_errno = errno;
+ fclose (fp);
+ errno = saved_errno;
+ goto free_then_fail;
+ }
+
+ if (fclose (fp) == EOF)
+ goto free_then_fail;
}
+ else /* fallback to /proc/self/mounts (/etc/mtab). */
+#endif /* __linux __ */
+ {
+ struct mntent *mnt;
+ char const *table = MOUNTED;
- if (endmntent (fp) == 0)
- goto free_then_fail;
+ fp = setmntent (table, "r");
+ if (fp == NULL)
+ return NULL;
+
+ while ((mnt = getmntent (fp)))
+ {
+ bool bind = hasmntopt (mnt, "bind");
+
+ me = xmalloc (sizeof *me);
+ me->me_devname = xstrdup (mnt->mnt_fsname);
+ me->me_mountdir = xstrdup (mnt->mnt_dir);
+ me->me_mntroot = NULL;
+ me->me_type = xstrdup (mnt->mnt_type);
+ me->me_type_malloced = 1;
+ me->me_dummy = ME_DUMMY (me->me_devname, me->me_type, bind);
+ me->me_remote = ME_REMOTE (me->me_devname, me->me_type);
+ me->me_dev = dev_from_mount_options (mnt->mnt_opts);
+
+ /* Add to the linked list. */
+ *mtail = me;
+ mtail = &me->me_next;
+ }
+
+ if (endmntent (fp) == 0)
+ goto free_then_fail;
+ }
}
#endif /* MOUNTED_GETMNTENT1. */
-#ifdef MOUNTED_GETMNTINFO /* 4.4BSD. */
+#ifdef MOUNTED_GETMNTINFO /* 4.4BSD. */
{
struct statfs *fsp;
int entries;
@@ -417,25 +600,26 @@ read_file_system_list (bool need_fs_type)
return NULL;
for (; entries-- > 0; fsp++)
{
- char *fs_type = fsp_to_string (fsp);
-
- me = xmalloc (sizeof *me);
- me->me_devname = xstrdup (fsp->f_mntfromname);
- me->me_mountdir = xstrdup (fsp->f_mntonname);
- me->me_type = fs_type;
- me->me_type_malloced = 0;
- me->me_dummy = ME_DUMMY (me->me_devname, me->me_type);
- me->me_remote = ME_REMOTE (me->me_devname, me->me_type);
- me->me_dev = (dev_t) -1; /* Magic; means not known yet. */
-
- /* Add to the linked list. */
- *mtail = me;
- mtail = &me->me_next;
+ char *fs_type = fsp_to_string (fsp);
+
+ me = xmalloc (sizeof *me);
+ me->me_devname = xstrdup (fsp->f_mntfromname);
+ me->me_mountdir = xstrdup (fsp->f_mntonname);
+ me->me_mntroot = NULL;
+ me->me_type = fs_type;
+ me->me_type_malloced = 0;
+ me->me_dummy = ME_DUMMY (me->me_devname, me->me_type);
+ me->me_remote = ME_REMOTE (me->me_devname, me->me_type);
+ me->me_dev = (dev_t) -1; /* Magic; means not known yet. */
+
+ /* Add to the linked list. */
+ *mtail = me;
+ mtail = &me->me_next;
}
}
#endif /* MOUNTED_GETMNTINFO */
-#ifdef MOUNTED_GETMNTINFO2 /* NetBSD 3.0. */
+#ifdef MOUNTED_GETMNTINFO2 /* NetBSD 3.0. */
{
struct statvfs *fsp;
int entries;
@@ -445,44 +629,46 @@ read_file_system_list (bool need_fs_type)
return NULL;
for (; entries-- > 0; fsp++)
{
- me = xmalloc (sizeof *me);
- me->me_devname = xstrdup (fsp->f_mntfromname);
- me->me_mountdir = xstrdup (fsp->f_mntonname);
- me->me_type = xstrdup (fsp->f_fstypename);
- me->me_type_malloced = 1;
- me->me_dummy = ME_DUMMY (me->me_devname, me->me_type);
- me->me_remote = ME_REMOTE (me->me_devname, me->me_type);
- me->me_dev = (dev_t) -1; /* Magic; means not known yet. */
-
- /* Add to the linked list. */
- *mtail = me;
- mtail = &me->me_next;
+ me = xmalloc (sizeof *me);
+ me->me_devname = xstrdup (fsp->f_mntfromname);
+ me->me_mountdir = xstrdup (fsp->f_mntonname);
+ me->me_mntroot = NULL;
+ me->me_type = xstrdup (fsp->f_fstypename);
+ me->me_type_malloced = 1;
+ me->me_dummy = ME_DUMMY (me->me_devname, me->me_type);
+ me->me_remote = ME_REMOTE (me->me_devname, me->me_type);
+ me->me_dev = (dev_t) -1; /* Magic; means not known yet. */
+
+ /* Add to the linked list. */
+ *mtail = me;
+ mtail = &me->me_next;
}
}
#endif /* MOUNTED_GETMNTINFO2 */
-#ifdef MOUNTED_GETMNT /* Ultrix. */
+#ifdef MOUNTED_GETMNT /* Ultrix. */
{
int offset = 0;
int val;
struct fs_data fsd;
while (errno = 0,
- 0 < (val = getmnt (&offset, &fsd, sizeof (fsd), NOSTAT_MANY,
- (char *) 0)))
+ 0 < (val = getmnt (&offset, &fsd, sizeof (fsd), NOSTAT_MANY,
+ (char *) 0)))
{
- me = xmalloc (sizeof *me);
- me->me_devname = xstrdup (fsd.fd_req.devname);
- me->me_mountdir = xstrdup (fsd.fd_req.path);
- me->me_type = gt_names[fsd.fd_req.fstype];
- me->me_type_malloced = 0;
- me->me_dummy = ME_DUMMY (me->me_devname, me->me_type);
- me->me_remote = ME_REMOTE (me->me_devname, me->me_type);
- me->me_dev = fsd.fd_req.dev;
-
- /* Add to the linked list. */
- *mtail = me;
- mtail = &me->me_next;
+ me = xmalloc (sizeof *me);
+ me->me_devname = xstrdup (fsd.fd_req.devname);
+ me->me_mountdir = xstrdup (fsd.fd_req.path);
+ me->me_mntroot = NULL;
+ me->me_type = gt_names[fsd.fd_req.fstype];
+ me->me_type_malloced = 0;
+ me->me_dummy = ME_DUMMY (me->me_devname, me->me_type);
+ me->me_remote = ME_REMOTE (me->me_devname, me->me_type);
+ me->me_dev = fsd.fd_req.dev;
+
+ /* Add to the linked list. */
+ *mtail = me;
+ mtail = &me->me_next;
}
if (val < 0)
goto free_then_fail;
@@ -542,7 +728,7 @@ read_file_system_list (bool need_fs_type)
if (lstat (name, &statbuf) >= 0 && S_ISDIR (statbuf.st_mode))
{
- struct rootdir_entry *re = xmalloc (sizeof *re);
+ struct rootdir_entry *re = xmalloc (sizeof *re);
re->name = name;
re->dev = statbuf.st_dev;
re->ino = statbuf.st_ino;
@@ -568,11 +754,13 @@ read_file_system_list (bool need_fs_type)
if (re->dev == fi.dev && re->ino == fi.root)
break;
- me = xmalloc (sizeof *me);
- me->me_devname = xstrdup (fi.device_name[0] != '\0' ? fi.device_name : fi.fsh_name);
+ me = xmalloc (sizeof *me);
+ me->me_devname = xstrdup (fi.device_name[0] != '\0'
+ ? fi.device_name : fi.fsh_name);
me->me_mountdir = xstrdup (re != NULL ? re->name : fi.fsh_name);
+ me->me_mntroot = NULL;
me->me_type = xstrdup (fi.fsh_name);
- me->me_type_malloced = 1;
+ me->me_type_malloced = 1;
me->me_dev = fi.dev;
me->me_dummy = 0;
me->me_remote = (fi.flags & B_FS_IS_SHARED) != 0;
@@ -593,15 +781,15 @@ read_file_system_list (bool need_fs_type)
}
#endif /* MOUNTED_FS_STAT_DEV */
-#if defined MOUNTED_GETFSSTAT /* __alpha running OSF_1 */
+#if defined MOUNTED_GETFSSTAT /* __alpha running OSF_1 */
{
int numsys, counter;
size_t bufsize;
struct statfs *stats;
- numsys = getfsstat ((struct statfs *)0, 0L, MNT_NOWAIT);
+ numsys = getfsstat (NULL, 0L, MNT_NOWAIT);
if (numsys < 0)
- return (NULL);
+ return NULL;
if (SIZE_MAX / sizeof *stats <= numsys)
xalloc_die ();
@@ -611,24 +799,25 @@ read_file_system_list (bool need_fs_type)
if (numsys < 0)
{
- free (stats);
- return (NULL);
+ free (stats);
+ return NULL;
}
for (counter = 0; counter < numsys; counter++)
{
- me = xmalloc (sizeof *me);
- me->me_devname = xstrdup (stats[counter].f_mntfromname);
- me->me_mountdir = xstrdup (stats[counter].f_mntonname);
- me->me_type = xstrdup (FS_TYPE (stats[counter]));
- me->me_type_malloced = 1;
- me->me_dummy = ME_DUMMY (me->me_devname, me->me_type);
- me->me_remote = ME_REMOTE (me->me_devname, me->me_type);
- me->me_dev = (dev_t) -1; /* Magic; means not known yet. */
-
- /* Add to the linked list. */
- *mtail = me;
- mtail = &me->me_next;
+ me = xmalloc (sizeof *me);
+ me->me_devname = xstrdup (stats[counter].f_mntfromname);
+ me->me_mountdir = xstrdup (stats[counter].f_mntonname);
+ me->me_mntroot = NULL;
+ me->me_type = xstrdup (FS_TYPE (stats[counter]));
+ me->me_type_malloced = 1;
+ me->me_dummy = ME_DUMMY (me->me_devname, me->me_type);
+ me->me_remote = ME_REMOTE (me->me_devname, me->me_type);
+ me->me_dev = (dev_t) -1; /* Magic; means not known yet. */
+
+ /* Add to the linked list. */
+ *mtail = me;
+ mtail = &me->me_next;
}
free (stats);
@@ -647,47 +836,48 @@ read_file_system_list (bool need_fs_type)
while (fread (&mnt, sizeof mnt, 1, fp) > 0)
{
- me = xmalloc (sizeof *me);
-# ifdef GETFSTYP /* SVR3. */
- me->me_devname = xstrdup (mnt.mt_dev);
+ me = xmalloc (sizeof *me);
+# ifdef GETFSTYP /* SVR3. */
+ me->me_devname = xstrdup (mnt.mt_dev);
# else
- me->me_devname = xmalloc (strlen (mnt.mt_dev) + 6);
- strcpy (me->me_devname, "/dev/");
- strcpy (me->me_devname + 5, mnt.mt_dev);
+ me->me_devname = xmalloc (strlen (mnt.mt_dev) + 6);
+ strcpy (me->me_devname, "/dev/");
+ strcpy (me->me_devname + 5, mnt.mt_dev);
# endif
- me->me_mountdir = xstrdup (mnt.mt_filsys);
- me->me_dev = (dev_t) -1; /* Magic; means not known yet. */
- me->me_type = "";
- me->me_type_malloced = 0;
-# ifdef GETFSTYP /* SVR3. */
- if (need_fs_type)
- {
- struct statfs fsd;
- char typebuf[FSTYPSZ];
-
- if (statfs (me->me_mountdir, &fsd, sizeof fsd, 0) != -1
- && sysfs (GETFSTYP, fsd.f_fstyp, typebuf) != -1)
- {
- me->me_type = xstrdup (typebuf);
- me->me_type_malloced = 1;
- }
- }
+ me->me_mountdir = xstrdup (mnt.mt_filsys);
+ me->me_mntroot = NULL;
+ me->me_dev = (dev_t) -1; /* Magic; means not known yet. */
+ me->me_type = "";
+ me->me_type_malloced = 0;
+# ifdef GETFSTYP /* SVR3. */
+ if (need_fs_type)
+ {
+ struct statfs fsd;
+ char typebuf[FSTYPSZ];
+
+ if (statfs (me->me_mountdir, &fsd, sizeof fsd, 0) != -1
+ && sysfs (GETFSTYP, fsd.f_fstyp, typebuf) != -1)
+ {
+ me->me_type = xstrdup (typebuf);
+ me->me_type_malloced = 1;
+ }
+ }
# endif
- me->me_dummy = ME_DUMMY (me->me_devname, me->me_type);
- me->me_remote = ME_REMOTE (me->me_devname, me->me_type);
+ me->me_dummy = ME_DUMMY (me->me_devname, me->me_type);
+ me->me_remote = ME_REMOTE (me->me_devname, me->me_type);
- /* Add to the linked list. */
- *mtail = me;
- mtail = &me->me_next;
+ /* Add to the linked list. */
+ *mtail = me;
+ mtail = &me->me_next;
}
if (ferror (fp))
{
- /* The last fread() call must have failed. */
- int saved_errno = errno;
- fclose (fp);
- errno = saved_errno;
- goto free_then_fail;
+ /* The last fread() call must have failed. */
+ int saved_errno = errno;
+ fclose (fp);
+ errno = saved_errno;
+ goto free_then_fail;
}
if (fclose (fp) == EOF)
@@ -695,29 +885,30 @@ read_file_system_list (bool need_fs_type)
}
#endif /* MOUNTED_FREAD || MOUNTED_FREAD_FSTYP. */
-#ifdef MOUNTED_GETMNTTBL /* DolphinOS goes its own way. */
+#ifdef MOUNTED_GETMNTTBL /* DolphinOS goes its own way. */
{
struct mntent **mnttbl = getmnttbl (), **ent;
- for (ent=mnttbl;*ent;ent++)
+ for (ent = mnttbl; *ent; ent++)
{
- me = xmalloc (sizeof *me);
- me->me_devname = xstrdup ( (*ent)->mt_resource);
- me->me_mountdir = xstrdup ( (*ent)->mt_directory);
- me->me_type = xstrdup ((*ent)->mt_fstype);
- me->me_type_malloced = 1;
- me->me_dummy = ME_DUMMY (me->me_devname, me->me_type);
- me->me_remote = ME_REMOTE (me->me_devname, me->me_type);
- me->me_dev = (dev_t) -1; /* Magic; means not known yet. */
-
- /* Add to the linked list. */
- *mtail = me;
- mtail = &me->me_next;
+ me = xmalloc (sizeof *me);
+ me->me_devname = xstrdup ((*ent)->mt_resource);
+ me->me_mountdir = xstrdup ((*ent)->mt_directory);
+ me->me_mntroot = NULL;
+ me->me_type = xstrdup ((*ent)->mt_fstype);
+ me->me_type_malloced = 1;
+ me->me_dummy = ME_DUMMY (me->me_devname, me->me_type);
+ me->me_remote = ME_REMOTE (me->me_devname, me->me_type);
+ me->me_dev = (dev_t) -1; /* Magic; means not known yet. */
+
+ /* Add to the linked list. */
+ *mtail = me;
+ mtail = &me->me_next;
}
endmnttbl ();
}
#endif
-#ifdef MOUNTED_GETMNTENT2 /* SVR4. */
+#ifdef MOUNTED_GETMNTENT2 /* SVR4. */
{
struct mnttab mnt;
char *table = MNTTAB;
@@ -736,19 +927,19 @@ read_file_system_list (bool need_fs_type)
lockfd = open (MNTTAB_LOCK, O_RDONLY);
if (0 <= lockfd)
{
- struct flock flock;
- flock.l_type = F_RDLCK;
- flock.l_whence = SEEK_SET;
- flock.l_start = 0;
- flock.l_len = 0;
- while (fcntl (lockfd, F_SETLKW, &flock) == -1)
- if (errno != EINTR)
- {
- int saved_errno = errno;
- close (lockfd);
- errno = saved_errno;
- return NULL;
- }
+ struct flock flock;
+ flock.l_type = F_RDLCK;
+ flock.l_whence = SEEK_SET;
+ flock.l_start = 0;
+ flock.l_len = 0;
+ while (fcntl (lockfd, F_SETLKW, &flock) == -1)
+ if (errno != EINTR)
+ {
+ int saved_errno = errno;
+ close (lockfd);
+ errno = saved_errno;
+ return NULL;
+ }
}
else if (errno != ENOENT)
return NULL;
@@ -760,23 +951,24 @@ read_file_system_list (bool need_fs_type)
ret = errno;
else
{
- while ((ret = getmntent (fp, &mnt)) == 0)
- {
- me = xmalloc (sizeof *me);
- me->me_devname = xstrdup (mnt.mnt_special);
- me->me_mountdir = xstrdup (mnt.mnt_mountp);
- me->me_type = xstrdup (mnt.mnt_fstype);
- me->me_type_malloced = 1;
- me->me_dummy = MNT_IGNORE (&mnt) != 0;
- me->me_remote = ME_REMOTE (me->me_devname, me->me_type);
- me->me_dev = dev_from_mount_options (mnt.mnt_mntopts);
-
- /* Add to the linked list. */
- *mtail = me;
- mtail = &me->me_next;
- }
-
- ret = fclose (fp) == EOF ? errno : 0 < ret ? 0 : -1;
+ while ((ret = getmntent (fp, &mnt)) == 0)
+ {
+ me = xmalloc (sizeof *me);
+ me->me_devname = xstrdup (mnt.mnt_special);
+ me->me_mountdir = xstrdup (mnt.mnt_mountp);
+ me->me_mntroot = NULL;
+ me->me_type = xstrdup (mnt.mnt_fstype);
+ me->me_type_malloced = 1;
+ me->me_dummy = MNT_IGNORE (&mnt) != 0;
+ me->me_remote = ME_REMOTE (me->me_devname, me->me_type);
+ me->me_dev = dev_from_mount_options (mnt.mnt_mntopts);
+
+ /* Add to the linked list. */
+ *mtail = me;
+ mtail = &me->me_next;
+ }
+
+ ret = fclose (fp) == EOF ? errno : 0 < ret ? 0 : -1;
}
if (0 <= lockfd && close (lockfd) != 0)
@@ -784,102 +976,154 @@ read_file_system_list (bool need_fs_type)
if (0 <= ret)
{
- errno = ret;
- goto free_then_fail;
+ errno = ret;
+ goto free_then_fail;
}
}
#endif /* MOUNTED_GETMNTENT2. */
-#ifdef MOUNTED_VMOUNT /* AIX. */
+#ifdef MOUNTED_VMOUNT /* AIX. */
{
int bufsize;
- char *entries, *thisent;
+ void *entries;
+ char *thisent;
struct vmount *vmp;
int n_entries;
int i;
/* Ask how many bytes to allocate for the mounted file system info. */
- if (mntctl (MCTL_QUERY, sizeof bufsize, (struct vmount *) &bufsize) != 0)
+ entries = &bufsize;
+ if (mntctl (MCTL_QUERY, sizeof bufsize, entries) != 0)
return NULL;
entries = xmalloc (bufsize);
/* Get the list of mounted file systems. */
- n_entries = mntctl (MCTL_QUERY, bufsize, (struct vmount *) entries);
+ n_entries = mntctl (MCTL_QUERY, bufsize, entries);
if (n_entries < 0)
{
- int saved_errno = errno;
- free (entries);
- errno = saved_errno;
- return NULL;
+ int saved_errno = errno;
+ free (entries);
+ errno = saved_errno;
+ return NULL;
}
for (i = 0, thisent = entries;
- i < n_entries;
- i++, thisent += vmp->vmt_length)
+ i < n_entries;
+ i++, thisent += vmp->vmt_length)
{
- char *options, *ignore;
-
- vmp = (struct vmount *) thisent;
- me = xmalloc (sizeof *me);
- if (vmp->vmt_flags & MNT_REMOTE)
- {
- char *host, *dir;
-
- me->me_remote = 1;
- /* Prepend the remote dirname. */
- host = thisent + vmp->vmt_data[VMT_HOSTNAME].vmt_off;
- dir = thisent + vmp->vmt_data[VMT_OBJECT].vmt_off;
- me->me_devname = xmalloc (strlen (host) + strlen (dir) + 2);
- strcpy (me->me_devname, host);
- strcat (me->me_devname, ":");
- strcat (me->me_devname, dir);
- }
- else
- {
- me->me_remote = 0;
- me->me_devname = xstrdup (thisent +
- vmp->vmt_data[VMT_OBJECT].vmt_off);
- }
- me->me_mountdir = xstrdup (thisent + vmp->vmt_data[VMT_STUB].vmt_off);
- me->me_type = xstrdup (fstype_to_string (vmp->vmt_gfstype));
- me->me_type_malloced = 1;
- options = thisent + vmp->vmt_data[VMT_ARGS].vmt_off;
- ignore = strstr (options, "ignore");
- me->me_dummy = (ignore
- && (ignore == options || ignore[-1] == ',')
- && (ignore[sizeof "ignore" - 1] == ','
- || ignore[sizeof "ignore" - 1] == '\0'));
- me->me_dev = (dev_t) -1; /* vmt_fsid might be the info we want. */
-
- /* Add to the linked list. */
- *mtail = me;
- mtail = &me->me_next;
+ char *options, *ignore;
+
+ vmp = (struct vmount *) thisent;
+ me = xmalloc (sizeof *me);
+ if (vmp->vmt_flags & MNT_REMOTE)
+ {
+ char *host, *dir;
+
+ me->me_remote = 1;
+ /* Prepend the remote dirname. */
+ host = thisent + vmp->vmt_data[VMT_HOSTNAME].vmt_off;
+ dir = thisent + vmp->vmt_data[VMT_OBJECT].vmt_off;
+ me->me_devname = xmalloc (strlen (host) + strlen (dir) + 2);
+ strcpy (me->me_devname, host);
+ strcat (me->me_devname, ":");
+ strcat (me->me_devname, dir);
+ }
+ else
+ {
+ me->me_remote = 0;
+ me->me_devname = xstrdup (thisent +
+ vmp->vmt_data[VMT_OBJECT].vmt_off);
+ }
+ me->me_mountdir = xstrdup (thisent + vmp->vmt_data[VMT_STUB].vmt_off);
+ me->me_mntroot = NULL;
+ me->me_type = xstrdup (fstype_to_string (vmp->vmt_gfstype));
+ me->me_type_malloced = 1;
+ options = thisent + vmp->vmt_data[VMT_ARGS].vmt_off;
+ ignore = strstr (options, "ignore");
+ me->me_dummy = (ignore
+ && (ignore == options || ignore[-1] == ',')
+ && (ignore[sizeof "ignore" - 1] == ','
+ || ignore[sizeof "ignore" - 1] == '\0'));
+ me->me_dev = (dev_t) -1; /* vmt_fsid might be the info we want. */
+
+ /* Add to the linked list. */
+ *mtail = me;
+ mtail = &me->me_next;
}
free (entries);
}
#endif /* MOUNTED_VMOUNT. */
+#ifdef MOUNTED_INTERIX_STATVFS
+ {
+ DIR *dirp = opendir ("/dev/fs");
+ char node[9 + NAME_MAX];
+
+ if (!dirp)
+ goto free_then_fail;
+
+ while (1)
+ {
+ struct statvfs dev;
+ struct dirent entry;
+ struct dirent *result;
+
+ if (readdir_r (dirp, &entry, &result) || result == NULL)
+ break;
+
+ strcpy (node, "/dev/fs/");
+ strcat (node, entry.d_name);
+
+ if (statvfs (node, &dev) == 0)
+ {
+ me = xmalloc (sizeof *me);
+ me->me_devname = xstrdup (dev.f_mntfromname);
+ me->me_mountdir = xstrdup (dev.f_mntonname);
+ me->me_mntroot = NULL;
+ me->me_type = xstrdup (dev.f_fstypename);
+ me->me_type_malloced = 1;
+ me->me_dummy = ME_DUMMY (me->me_devname, me->me_type);
+ me->me_remote = ME_REMOTE (me->me_devname, me->me_type);
+ me->me_dev = (dev_t) -1; /* Magic; means not known yet. */
+
+ /* Add to the linked list. */
+ *mtail = me;
+ mtail = &me->me_next;
+ }
+ }
+ closedir (dirp);
+ }
+#endif /* MOUNTED_INTERIX_STATVFS */
+
*mtail = NULL;
return mount_list;
- free_then_fail:
+ free_then_fail: _GL_UNUSED_LABEL
{
int saved_errno = errno;
*mtail = NULL;
while (mount_list)
{
- me = mount_list->me_next;
- free (mount_list->me_devname);
- free (mount_list->me_mountdir);
- if (mount_list->me_type_malloced)
- free (mount_list->me_type);
- free (mount_list);
- mount_list = me;
+ me = mount_list->me_next;
+ free_mount_entry (mount_list);
+ mount_list = me;
}
errno = saved_errno;
return NULL;
}
}
+
+/* Free a mount entry as returned from read_file_system_list (). */
+
+void free_mount_entry (struct mount_entry *me)
+{
+ free (me->me_devname);
+ free (me->me_mountdir);
+ free (me->me_mntroot);
+ if (me->me_type_malloced)
+ free (me->me_type);
+ free (me);
+}
diff --git a/lib/mountlist.h b/lib/mountlist.h
index 7f5a6f7..7a4f3ec 100644
--- a/lib/mountlist.h
+++ b/lib/mountlist.h
@@ -1,12 +1,12 @@
/* mountlist.h -- declarations for list of mounted file systems
- Copyright (C) 1991, 1992, 1998, 2000, 2001, 2002, 2003, 2004, 2005
- Free Software Foundation, Inc.
+ Copyright (C) 1991-1992, 1998, 2000-2005, 2009-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifndef MOUNTLIST_H_
# define MOUNTLIST_H_
@@ -26,16 +25,19 @@
/* A mount table entry. */
struct mount_entry
{
- char *me_devname; /* Device node name, including "/dev/". */
- char *me_mountdir; /* Mount point directory name. */
- char *me_type; /* "nfs", "4.2", etc. */
- dev_t me_dev; /* Device number of me_mountdir. */
- unsigned int me_dummy : 1; /* Nonzero for dummy file systems. */
- unsigned int me_remote : 1; /* Nonzero for remote fileystems. */
+ char *me_devname; /* Device node name, including "/dev/". */
+ char *me_mountdir; /* Mount point directory name. */
+ char *me_mntroot; /* Directory on filesystem of device used */
+ /* as root for the (bind) mount. */
+ char *me_type; /* "nfs", "4.2", etc. */
+ dev_t me_dev; /* Device number of me_mountdir. */
+ unsigned int me_dummy : 1; /* Nonzero for dummy file systems. */
+ unsigned int me_remote : 1; /* Nonzero for remote fileystems. */
unsigned int me_type_malloced : 1; /* Nonzero if me_type was malloced. */
struct mount_entry *me_next;
};
struct mount_entry *read_file_system_list (bool need_fs_type);
+void free_mount_entry (struct mount_entry *entry);
#endif
diff --git a/lib/mpsort.c b/lib/mpsort.c
index d6b1e0e..eba13e2 100644
--- a/lib/mpsort.c
+++ b/lib/mpsort.c
@@ -1,20 +1,19 @@
/* Sort a vector of pointers to data.
- Copyright (C) 2007 Free Software Foundation, Inc.
+ Copyright (C) 2007, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
@@ -29,15 +28,15 @@
typedef int (*comparison_function) (void const *, void const *);
static void mpsort_with_tmp (void const **restrict, size_t,
- void const **restrict, comparison_function);
+ void const **restrict, comparison_function);
/* Sort a vector BASE containing N pointers, placing the sorted array
into TMP. Compare pointers with CMP. N must be at least 2. */
static void
mpsort_into_tmp (void const **restrict base, size_t n,
- void const **restrict tmp,
- comparison_function cmp)
+ void const **restrict tmp,
+ comparison_function cmp)
{
size_t n1 = n / 2;
size_t n2 = n - n1;
@@ -57,23 +56,23 @@ mpsort_into_tmp (void const **restrict base, size_t n,
for (;;)
if (cmp (ba, bb) <= 0)
{
- *tmp++ = ba;
- a++;
- if (a == alim)
- {
- a = b;
- alim = blim;
- break;
- }
- ba = base[a];
+ *tmp++ = ba;
+ a++;
+ if (a == alim)
+ {
+ a = b;
+ alim = blim;
+ break;
+ }
+ ba = base[a];
}
else
{
- *tmp++ = bb;
- b++;
- if (b == blim)
- break;
- bb = base[b];
+ *tmp++ = bb;
+ b++;
+ if (b == blim)
+ break;
+ bb = base[b];
}
memcpy (tmp, base + a, (alim - a) * sizeof *base);
@@ -85,21 +84,21 @@ mpsort_into_tmp (void const **restrict base, size_t n,
static void
mpsort_with_tmp (void const **restrict base, size_t n,
- void const **restrict tmp,
- comparison_function cmp)
+ void const **restrict tmp,
+ comparison_function cmp)
{
if (n <= 2)
{
if (n == 2)
- {
- void const *p0 = base[0];
- void const *p1 = base[1];
- if (! (cmp (p0, p1) <= 0))
- {
- base[0] = p1;
- base[1] = p0;
- }
- }
+ {
+ void const *p0 = base[0];
+ void const *p1 = base[1];
+ if (! (cmp (p0, p1) <= 0))
+ {
+ base[0] = p1;
+ base[1] = p0;
+ }
+ }
}
else
{
@@ -116,33 +115,33 @@ mpsort_with_tmp (void const **restrict base, size_t n,
mpsort_with_tmp (base + n1, n2, tmp, cmp);
if (n1 < 2)
- tmp[0] = base[0];
+ tmp[0] = base[0];
else
- mpsort_into_tmp (base, n1, tmp, cmp);
+ mpsort_into_tmp (base, n1, tmp, cmp);
tt = tmp[t];
bb = base[b];
for (i = 0; ; )
- if (cmp (tt, bb) <= 0)
- {
- base[i++] = tt;
- t++;
- if (t == tlim)
- break;
- tt = tmp[t];
- }
- else
- {
- base[i++] = bb;
- b++;
- if (b == blim)
- {
- memcpy (base + i, tmp + t, (tlim - t) * sizeof *base);
- break;
- }
- bb = base[b];
- }
+ if (cmp (tt, bb) <= 0)
+ {
+ base[i++] = tt;
+ t++;
+ if (t == tlim)
+ break;
+ tt = tmp[t];
+ }
+ else
+ {
+ base[i++] = bb;
+ b++;
+ if (b == blim)
+ {
+ memcpy (base + i, tmp + t, (tlim - t) * sizeof *base);
+ break;
+ }
+ bb = base[b];
+ }
}
}
diff --git a/lib/msvc-inval.c b/lib/msvc-inval.c
new file mode 100644
index 0000000..baaf39e
--- /dev/null
+++ b/lib/msvc-inval.c
@@ -0,0 +1,129 @@
+/* Invalid parameter handler for MSVC runtime libraries.
+ Copyright (C) 2011-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include "msvc-inval.h"
+
+#if HAVE_MSVC_INVALID_PARAMETER_HANDLER \
+ && !(MSVC_INVALID_PARAMETER_HANDLING == SANE_LIBRARY_HANDLING)
+
+/* Get _invalid_parameter_handler type and _set_invalid_parameter_handler
+ declaration. */
+# include <stdlib.h>
+
+# if MSVC_INVALID_PARAMETER_HANDLING == DEFAULT_HANDLING
+
+static void __cdecl
+gl_msvc_invalid_parameter_handler (const wchar_t *expression,
+ const wchar_t *function,
+ const wchar_t *file,
+ unsigned int line,
+ uintptr_t dummy)
+{
+}
+
+# else
+
+/* Get declarations of the native Windows API functions. */
+# define WIN32_LEAN_AND_MEAN
+# include <windows.h>
+
+# if defined _MSC_VER
+
+static void __cdecl
+gl_msvc_invalid_parameter_handler (const wchar_t *expression,
+ const wchar_t *function,
+ const wchar_t *file,
+ unsigned int line,
+ uintptr_t dummy)
+{
+ RaiseException (STATUS_GNULIB_INVALID_PARAMETER, 0, 0, NULL);
+}
+
+# else
+
+/* An index to thread-local storage. */
+static DWORD tls_index;
+static int tls_initialized /* = 0 */;
+
+/* Used as a fallback only. */
+static struct gl_msvc_inval_per_thread not_per_thread;
+
+struct gl_msvc_inval_per_thread *
+gl_msvc_inval_current (void)
+{
+ if (!tls_initialized)
+ {
+ tls_index = TlsAlloc ();
+ tls_initialized = 1;
+ }
+ if (tls_index == TLS_OUT_OF_INDEXES)
+ /* TlsAlloc had failed. */
+ return &not_per_thread;
+ else
+ {
+ struct gl_msvc_inval_per_thread *pointer =
+ (struct gl_msvc_inval_per_thread *) TlsGetValue (tls_index);
+ if (pointer == NULL)
+ {
+ /* First call. Allocate a new 'struct gl_msvc_inval_per_thread'. */
+ pointer =
+ (struct gl_msvc_inval_per_thread *)
+ malloc (sizeof (struct gl_msvc_inval_per_thread));
+ if (pointer == NULL)
+ /* Could not allocate memory. Use the global storage. */
+ pointer = &not_per_thread;
+ TlsSetValue (tls_index, pointer);
+ }
+ return pointer;
+ }
+}
+
+static void __cdecl
+gl_msvc_invalid_parameter_handler (const wchar_t *expression,
+ const wchar_t *function,
+ const wchar_t *file,
+ unsigned int line,
+ uintptr_t dummy)
+{
+ struct gl_msvc_inval_per_thread *current = gl_msvc_inval_current ();
+ if (current->restart_valid)
+ longjmp (current->restart, 1);
+ else
+ /* An invalid parameter notification from outside the gnulib code.
+ Give the caller a chance to intervene. */
+ RaiseException (STATUS_GNULIB_INVALID_PARAMETER, 0, 0, NULL);
+}
+
+# endif
+
+# endif
+
+static int gl_msvc_inval_initialized /* = 0 */;
+
+void
+gl_msvc_inval_ensure_handler (void)
+{
+ if (gl_msvc_inval_initialized == 0)
+ {
+ _set_invalid_parameter_handler (gl_msvc_invalid_parameter_handler);
+ gl_msvc_inval_initialized = 1;
+ }
+}
+
+#endif
diff --git a/lib/msvc-inval.h b/lib/msvc-inval.h
new file mode 100644
index 0000000..027c949
--- /dev/null
+++ b/lib/msvc-inval.h
@@ -0,0 +1,222 @@
+/* Invalid parameter handler for MSVC runtime libraries.
+ Copyright (C) 2011-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _MSVC_INVAL_H
+#define _MSVC_INVAL_H
+
+/* With MSVC runtime libraries with the "invalid parameter handler" concept,
+ functions like fprintf(), dup2(), or close() crash when the caller passes
+ an invalid argument. But POSIX wants error codes (such as EINVAL or EBADF)
+ instead.
+ This file defines macros that turn such an invalid parameter notification
+ into a non-local exit. An error code can then be produced at the target
+ of this exit. You can thus write code like
+
+ TRY_MSVC_INVAL
+ {
+ <Code that can trigger an invalid parameter notification
+ but does not do 'return', 'break', 'continue', nor 'goto'.>
+ }
+ CATCH_MSVC_INVAL
+ {
+ <Code that handles an invalid parameter notification
+ but does not do 'return', 'break', 'continue', nor 'goto'.>
+ }
+ DONE_MSVC_INVAL;
+
+ This entire block expands to a single statement.
+
+ The handling of invalid parameters can be done in three ways:
+
+ * The default way, which is reasonable for programs (not libraries):
+ AC_DEFINE([MSVC_INVALID_PARAMETER_HANDLING], [DEFAULT_HANDLING])
+
+ * The way for libraries that make "hairy" calls (like close(-1), or
+ fclose(fp) where fileno(fp) is closed, or simply getdtablesize()):
+ AC_DEFINE([MSVC_INVALID_PARAMETER_HANDLING], [HAIRY_LIBRARY_HANDLING])
+
+ * The way for libraries that make no "hairy" calls:
+ AC_DEFINE([MSVC_INVALID_PARAMETER_HANDLING], [SANE_LIBRARY_HANDLING])
+ */
+
+#define DEFAULT_HANDLING 0
+#define HAIRY_LIBRARY_HANDLING 1
+#define SANE_LIBRARY_HANDLING 2
+
+#if HAVE_MSVC_INVALID_PARAMETER_HANDLER \
+ && !(MSVC_INVALID_PARAMETER_HANDLING == SANE_LIBRARY_HANDLING)
+/* A native Windows platform with the "invalid parameter handler" concept,
+ and either DEFAULT_HANDLING or HAIRY_LIBRARY_HANDLING. */
+
+# if MSVC_INVALID_PARAMETER_HANDLING == DEFAULT_HANDLING
+/* Default handling. */
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+/* Ensure that the invalid parameter handler in installed that just returns.
+ Because we assume no other part of the program installs a different
+ invalid parameter handler, this solution is multithread-safe. */
+extern void gl_msvc_inval_ensure_handler (void);
+
+# ifdef __cplusplus
+}
+# endif
+
+# define TRY_MSVC_INVAL \
+ do \
+ { \
+ gl_msvc_inval_ensure_handler (); \
+ if (1)
+# define CATCH_MSVC_INVAL \
+ else
+# define DONE_MSVC_INVAL \
+ } \
+ while (0)
+
+# else
+/* Handling for hairy libraries. */
+
+# include <excpt.h>
+
+/* Gnulib can define its own status codes, as described in the page
+ "Raising Software Exceptions" on microsoft.com
+ <http://msdn.microsoft.com/en-us/library/het71c37.aspx>.
+ Our status codes are composed of
+ - 0xE0000000, mandatory for all user-defined status codes,
+ - 0x474E550, a API identifier ("GNU"),
+ - 0, 1, 2, ..., used to distinguish different status codes from the
+ same API. */
+# define STATUS_GNULIB_INVALID_PARAMETER (0xE0000000 + 0x474E550 + 0)
+
+# if defined _MSC_VER
+/* A compiler that supports __try/__except, as described in the page
+ "try-except statement" on microsoft.com
+ <http://msdn.microsoft.com/en-us/library/s58ftw19.aspx>.
+ With __try/__except, we can use the multithread-safe exception handling. */
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+/* Ensure that the invalid parameter handler in installed that raises a
+ software exception with code STATUS_GNULIB_INVALID_PARAMETER.
+ Because we assume no other part of the program installs a different
+ invalid parameter handler, this solution is multithread-safe. */
+extern void gl_msvc_inval_ensure_handler (void);
+
+# ifdef __cplusplus
+}
+# endif
+
+# define TRY_MSVC_INVAL \
+ do \
+ { \
+ gl_msvc_inval_ensure_handler (); \
+ __try
+# define CATCH_MSVC_INVAL \
+ __except (GetExceptionCode () == STATUS_GNULIB_INVALID_PARAMETER \
+ ? EXCEPTION_EXECUTE_HANDLER \
+ : EXCEPTION_CONTINUE_SEARCH)
+# define DONE_MSVC_INVAL \
+ } \
+ while (0)
+
+# else
+/* Any compiler.
+ We can only use setjmp/longjmp. */
+
+# include <setjmp.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+struct gl_msvc_inval_per_thread
+{
+ /* The restart that will resume execution at the code between
+ CATCH_MSVC_INVAL and DONE_MSVC_INVAL. It is enabled only between
+ TRY_MSVC_INVAL and CATCH_MSVC_INVAL. */
+ jmp_buf restart;
+
+ /* Tells whether the contents of restart is valid. */
+ int restart_valid;
+};
+
+/* Ensure that the invalid parameter handler in installed that passes
+ control to the gl_msvc_inval_restart if it is valid, or raises a
+ software exception with code STATUS_GNULIB_INVALID_PARAMETER otherwise.
+ Because we assume no other part of the program installs a different
+ invalid parameter handler, this solution is multithread-safe. */
+extern void gl_msvc_inval_ensure_handler (void);
+
+/* Return a pointer to the per-thread data for the current thread. */
+extern struct gl_msvc_inval_per_thread *gl_msvc_inval_current (void);
+
+# ifdef __cplusplus
+}
+# endif
+
+# define TRY_MSVC_INVAL \
+ do \
+ { \
+ struct gl_msvc_inval_per_thread *msvc_inval_current; \
+ gl_msvc_inval_ensure_handler (); \
+ msvc_inval_current = gl_msvc_inval_current (); \
+ /* First, initialize gl_msvc_inval_restart. */ \
+ if (setjmp (msvc_inval_current->restart) == 0) \
+ { \
+ /* Then, mark it as valid. */ \
+ msvc_inval_current->restart_valid = 1;
+# define CATCH_MSVC_INVAL \
+ /* Execution completed. \
+ Mark gl_msvc_inval_restart as invalid. */ \
+ msvc_inval_current->restart_valid = 0; \
+ } \
+ else \
+ { \
+ /* Execution triggered an invalid parameter notification. \
+ Mark gl_msvc_inval_restart as invalid. */ \
+ msvc_inval_current->restart_valid = 0;
+# define DONE_MSVC_INVAL \
+ } \
+ } \
+ while (0)
+
+# endif
+
+# endif
+
+#else
+/* A platform that does not need to the invalid parameter handler,
+ or when SANE_LIBRARY_HANDLING is desired. */
+
+/* The braces here avoid GCC warnings like
+ "warning: suggest explicit braces to avoid ambiguous 'else'". */
+# define TRY_MSVC_INVAL \
+ do \
+ { \
+ if (1)
+# define CATCH_MSVC_INVAL \
+ else
+# define DONE_MSVC_INVAL \
+ } \
+ while (0)
+
+#endif
+
+#endif /* _MSVC_INVAL_H */
diff --git a/lib/msvc-nothrow.c b/lib/msvc-nothrow.c
new file mode 100644
index 0000000..ba75bbf
--- /dev/null
+++ b/lib/msvc-nothrow.c
@@ -0,0 +1,49 @@
+/* Wrappers that don't throw invalid parameter notifications
+ with MSVC runtime libraries.
+ Copyright (C) 2011-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include "msvc-nothrow.h"
+
+/* Get declarations of the native Windows API functions. */
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+
+#include "msvc-inval.h"
+
+#undef _get_osfhandle
+
+#if HAVE_MSVC_INVALID_PARAMETER_HANDLER
+intptr_t
+_gl_nothrow_get_osfhandle (int fd)
+{
+ intptr_t result;
+
+ TRY_MSVC_INVAL
+ {
+ result = _get_osfhandle (fd);
+ }
+ CATCH_MSVC_INVAL
+ {
+ result = (intptr_t) INVALID_HANDLE_VALUE;
+ }
+ DONE_MSVC_INVAL;
+
+ return result;
+}
+#endif
diff --git a/lib/msvc-nothrow.h b/lib/msvc-nothrow.h
new file mode 100644
index 0000000..3493b84
--- /dev/null
+++ b/lib/msvc-nothrow.h
@@ -0,0 +1,43 @@
+/* Wrappers that don't throw invalid parameter notifications
+ with MSVC runtime libraries.
+ Copyright (C) 2011-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _MSVC_NOTHROW_H
+#define _MSVC_NOTHROW_H
+
+/* With MSVC runtime libraries with the "invalid parameter handler" concept,
+ functions like fprintf(), dup2(), or close() crash when the caller passes
+ an invalid argument. But POSIX wants error codes (such as EINVAL or EBADF)
+ instead.
+ This file defines wrappers that turn such an invalid parameter notification
+ into an error code. */
+
+#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+
+/* Get original declaration of _get_osfhandle. */
+# include <io.h>
+
+# if HAVE_MSVC_INVALID_PARAMETER_HANDLER
+
+/* Override _get_osfhandle. */
+extern intptr_t _gl_nothrow_get_osfhandle (int fd);
+# define _get_osfhandle _gl_nothrow_get_osfhandle
+
+# endif
+
+#endif
+
+#endif /* _MSVC_NOTHROW_H */
diff --git a/lib/nanosleep.c b/lib/nanosleep.c
index 89c5512..a3116c2 100644
--- a/lib/nanosleep.c
+++ b/lib/nanosleep.c
@@ -1,12 +1,11 @@
/* Provide a replacement for the POSIX nanosleep function.
- Copyright (C) 1999, 2000, 2002, 2004, 2005, 2006, 2007 Free
- Software Foundation, Inc.
+ Copyright (C) 1999-2000, 2002, 2004-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,23 +13,23 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
-/* written by Jim Meyering */
+/* written by Jim Meyering
+ and Bruno Haible for the native Windows part */
#include <config.h>
#include <time.h>
-#include "timespec.h"
+#include "intprops.h"
+#include "sig-handler.h"
+#include "verify.h"
#include <stdbool.h>
#include <stdio.h>
#include <sys/types.h>
-#if HAVE_SYS_SELECT_H
-# include <sys/select.h>
-#endif
+#include <sys/select.h>
#include <signal.h>
#include <sys/time.h>
@@ -38,65 +37,151 @@
#include <unistd.h>
-#undef nanosleep
enum { BILLION = 1000 * 1000 * 1000 };
#if HAVE_BUG_BIG_NANOSLEEP
-void
-getnow (struct timespec *t)
+int
+nanosleep (const struct timespec *requested_delay,
+ struct timespec *remaining_delay)
+# undef nanosleep
{
-# if defined CLOCK_MONOTONIC && HAVE_CLOCK_GETTIME
- if (clock_gettime (CLOCK_MONOTONIC, t) == 0)
- return;
-# endif
- gettime (t);
+ /* nanosleep mishandles large sleeps due to internal overflow problems.
+ The worst known case of this is Linux 2.6.9 with glibc 2.3.4, which
+ can't sleep more than 24.85 days (2^31 milliseconds). Similarly,
+ cygwin 1.5.x, which can't sleep more than 49.7 days (2^32 milliseconds).
+ Solve this by breaking the sleep up into smaller chunks. */
+
+ if (requested_delay->tv_nsec < 0 || BILLION <= requested_delay->tv_nsec)
+ {
+ errno = EINVAL;
+ return -1;
+ }
+
+ {
+ /* Verify that time_t is large enough. */
+ verify (TYPE_MAXIMUM (time_t) / 24 / 24 / 60 / 60);
+ const time_t limit = 24 * 24 * 60 * 60;
+ time_t seconds = requested_delay->tv_sec;
+ struct timespec intermediate;
+ intermediate.tv_nsec = requested_delay->tv_nsec;
+
+ while (limit < seconds)
+ {
+ int result;
+ intermediate.tv_sec = limit;
+ result = nanosleep (&intermediate, remaining_delay);
+ seconds -= limit;
+ if (result)
+ {
+ if (remaining_delay)
+ remaining_delay->tv_sec += seconds;
+ return result;
+ }
+ intermediate.tv_nsec = 0;
+ }
+ intermediate.tv_sec = seconds;
+ return nanosleep (&intermediate, remaining_delay);
+ }
}
+#elif (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+/* Native Windows platforms. */
+
+# define WIN32_LEAN_AND_MEAN
+# include <windows.h>
+
+/* The Windows API function Sleep() has a resolution of about 15 ms and takes
+ at least 5 ms to execute. We use this function for longer time periods.
+ Additionally, we use busy-looping over short time periods, to get a
+ resolution of about 0.01 ms. In order to measure such short timespans,
+ we use the QueryPerformanceCounter() function. */
+
int
-rpl_nanosleep (const struct timespec *requested_delay,
- struct timespec *remaining_delay)
+nanosleep (const struct timespec *requested_delay,
+ struct timespec *remaining_delay)
{
- /* nanosleep mishandles large sleeps due to internal overflow
- problems, so check that the proper amount of time has actually
- elapsed. */
+ static bool initialized;
+ /* Number of performance counter increments per nanosecond,
+ or zero if it could not be determined. */
+ static double ticks_per_nanosecond;
- struct timespec delay = *requested_delay;
- struct timespec t0;
- getnow (&t0);
+ if (requested_delay->tv_nsec < 0 || BILLION <= requested_delay->tv_nsec)
+ {
+ errno = EINVAL;
+ return -1;
+ }
- for (;;)
+ /* For requested delays of one second or more, 15ms resolution is
+ sufficient. */
+ if (requested_delay->tv_sec == 0)
{
- int r = nanosleep (&delay, remaining_delay);
- if (r == 0)
- {
- time_t secs_sofar;
- struct timespec now;
- getnow (&now);
-
- secs_sofar = now.tv_sec - t0.tv_sec;
- if (requested_delay->tv_sec < secs_sofar)
- return 0;
- delay.tv_sec = requested_delay->tv_sec - secs_sofar;
- delay.tv_nsec = requested_delay->tv_nsec - (now.tv_nsec - t0.tv_nsec);
- if (delay.tv_nsec < 0)
- {
- if (delay.tv_sec == 0)
- return 0;
- delay.tv_nsec += BILLION;
- delay.tv_sec--;
- }
- else if (BILLION <= delay.tv_nsec)
- {
- delay.tv_nsec -= BILLION;
- delay.tv_sec++;
- }
- }
+ if (!initialized)
+ {
+ /* Initialize ticks_per_nanosecond. */
+ LARGE_INTEGER ticks_per_second;
+
+ if (QueryPerformanceFrequency (&ticks_per_second))
+ ticks_per_nanosecond =
+ (double) ticks_per_second.QuadPart / 1000000000.0;
+
+ initialized = true;
+ }
+ if (ticks_per_nanosecond)
+ {
+ /* QueryPerformanceFrequency worked. We can use
+ QueryPerformanceCounter. Use a combination of Sleep and
+ busy-looping. */
+ /* Number of milliseconds to pass to the Sleep function.
+ Since Sleep can take up to 8 ms less or 8 ms more than requested
+ (or maybe more if the system is loaded), we subtract 10 ms. */
+ int sleep_millis = (int) requested_delay->tv_nsec / 1000000 - 10;
+ /* Determine how many ticks to delay. */
+ LONGLONG wait_ticks = requested_delay->tv_nsec * ticks_per_nanosecond;
+ /* Start. */
+ LARGE_INTEGER counter_before;
+ if (QueryPerformanceCounter (&counter_before))
+ {
+ /* Wait until the performance counter has reached this value.
+ We don't need to worry about overflow, because the performance
+ counter is reset at reboot, and with a frequency of 3.6E6
+ ticks per second 63 bits suffice for over 80000 years. */
+ LONGLONG wait_until = counter_before.QuadPart + wait_ticks;
+ /* Use Sleep for the longest part. */
+ if (sleep_millis > 0)
+ Sleep (sleep_millis);
+ /* Busy-loop for the rest. */
+ for (;;)
+ {
+ LARGE_INTEGER counter_after;
+ if (!QueryPerformanceCounter (&counter_after))
+ /* QueryPerformanceCounter failed, but succeeded earlier.
+ Should not happen. */
+ break;
+ if (counter_after.QuadPart >= wait_until)
+ /* The requested time has elapsed. */
+ break;
+ }
+ goto done;
+ }
+ }
}
+ /* Implementation for long delays and as fallback. */
+ Sleep (requested_delay->tv_sec * 1000 + requested_delay->tv_nsec / 1000000);
+
+ done:
+ /* Sleep is not interruptible. So there is no remaining delay. */
+ if (remaining_delay != NULL)
+ {
+ remaining_delay->tv_sec = 0;
+ remaining_delay->tv_nsec = 0;
+ }
+ return 0;
}
#else
+/* Unix platforms lacking nanosleep. */
/* Some systems (MSDOS) don't have SIGCONT.
Using SIGTERM here turns the signal-handling code below
@@ -105,10 +190,6 @@ rpl_nanosleep (const struct timespec *requested_delay,
# define SIGCONT SIGTERM
# endif
-# if ! HAVE_SIGINTERRUPT
-# define siginterrupt(sig, flag) /* empty */
-# endif
-
static sig_atomic_t volatile suspended;
/* Handle SIGCONT. */
@@ -121,7 +202,7 @@ sighandler (int sig)
/* Suspend execution for at least *TS_DELAY seconds. */
-static void
+static int
my_usleep (const struct timespec *ts_delay)
{
struct timeval tv_delay;
@@ -129,64 +210,67 @@ my_usleep (const struct timespec *ts_delay)
tv_delay.tv_usec = (ts_delay->tv_nsec + 999) / 1000;
if (tv_delay.tv_usec == 1000000)
{
- time_t t1 = tv_delay.tv_sec + 1;
- if (t1 < tv_delay.tv_sec)
- tv_delay.tv_usec = 1000000 - 1; /* close enough */
+ if (tv_delay.tv_sec == TYPE_MAXIMUM (time_t))
+ tv_delay.tv_usec = 1000000 - 1; /* close enough */
else
- {
- tv_delay.tv_sec = t1;
- tv_delay.tv_usec = 0;
- }
+ {
+ tv_delay.tv_sec++;
+ tv_delay.tv_usec = 0;
+ }
}
- select (0, NULL, NULL, NULL, &tv_delay);
+ return select (0, NULL, NULL, NULL, &tv_delay);
}
/* Suspend execution for at least *REQUESTED_DELAY seconds. The
*REMAINING_DELAY part isn't implemented yet. */
int
-rpl_nanosleep (const struct timespec *requested_delay,
- struct timespec *remaining_delay)
+nanosleep (const struct timespec *requested_delay,
+ struct timespec *remaining_delay)
{
static bool initialized;
+ if (requested_delay->tv_nsec < 0 || BILLION <= requested_delay->tv_nsec)
+ {
+ errno = EINVAL;
+ return -1;
+ }
+
/* set up sig handler */
if (! initialized)
{
-# ifdef SA_NOCLDSTOP
- struct sigaction oldact, newact;
- newact.sa_handler = sighandler;
- sigemptyset (&newact.sa_mask);
- newact.sa_flags = 0;
+ struct sigaction oldact;
sigaction (SIGCONT, NULL, &oldact);
- if (oldact.sa_handler != SIG_IGN)
- sigaction (SIGCONT, &newact, NULL);
-# else
- if (signal (SIGCONT, SIG_IGN) != SIG_IGN)
- {
- signal (SIGCONT, sighandler);
- siginterrupt (SIGCONT, 1);
- }
-# endif
+ if (get_handler (&oldact) != SIG_IGN)
+ {
+ struct sigaction newact;
+
+ newact.sa_handler = sighandler;
+ sigemptyset (&newact.sa_mask);
+ newact.sa_flags = 0;
+ sigaction (SIGCONT, &newact, NULL);
+ }
initialized = true;
}
suspended = 0;
- my_usleep (requested_delay);
-
- if (suspended)
+ if (my_usleep (requested_delay) == -1)
{
- /* Calculate time remaining. */
- /* FIXME: the code in sleep doesn't use this, so there's no
- rush to implement it. */
-
- errno = EINTR;
+ if (suspended)
+ {
+ /* Calculate time remaining. */
+ /* FIXME: the code in sleep doesn't use this, so there's no
+ rush to implement it. */
+
+ errno = EINTR;
+ }
+ return -1;
}
/* FIXME: Restore sig handler? */
- return suspended;
+ return 0;
}
#endif
diff --git a/lib/netdb.in.h b/lib/netdb.in.h
new file mode 100644
index 0000000..5e2c035
--- /dev/null
+++ b/lib/netdb.in.h
@@ -0,0 +1,265 @@
+/* Provide a netdb.h header file for systems lacking it (read: MinGW).
+ Copyright (C) 2008-2016 Free Software Foundation, Inc.
+ Written by Simon Josefsson.
+
+ 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, 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 <http://www.gnu.org/licenses/>. */
+
+/* This file is supposed to be used on platforms that lack <netdb.h>.
+ It is intended to provide definitions and prototypes needed by an
+ application. */
+
+#ifndef _@GUARD_PREFIX@_NETDB_H
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+#if @HAVE_NETDB_H@
+
+/* The include_next requires a split double-inclusion guard. */
+# @INCLUDE_NEXT@ @NEXT_NETDB_H@
+
+#endif
+
+#ifndef _@GUARD_PREFIX@_NETDB_H
+#define _@GUARD_PREFIX@_NETDB_H
+
+/* Get <netdb.h> definitions such as 'socklen_t' on IRIX 6.5 and OSF/1 4.0 and
+ 'struct hostent' on MinGW. */
+#include <sys/socket.h>
+
+/* The definitions of _GL_FUNCDECL_RPL etc. are copied here. */
+
+/* The definition of _GL_ARG_NONNULL is copied here. */
+
+/* The definition of _GL_WARN_ON_USE is copied here. */
+
+/* Declarations for a platform that lacks <netdb.h>, or where it is
+ incomplete. */
+
+#if @GNULIB_GETADDRINFO@
+
+# if !@HAVE_STRUCT_ADDRINFO@
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# if !GNULIB_defined_struct_addrinfo
+/* Structure to contain information about address of a service provider. */
+struct addrinfo
+{
+ int ai_flags; /* Input flags. */
+ int ai_family; /* Protocol family for socket. */
+ int ai_socktype; /* Socket type. */
+ int ai_protocol; /* Protocol for socket. */
+ socklen_t ai_addrlen; /* Length of socket address. */
+ struct sockaddr *ai_addr; /* Socket address for socket. */
+ char *ai_canonname; /* Canonical name for service location. */
+ struct addrinfo *ai_next; /* Pointer to next in list. */
+};
+# define GNULIB_defined_struct_addrinfo 1
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+
+# endif
+
+/* Possible values for 'ai_flags' field in 'addrinfo' structure. */
+# ifndef AI_PASSIVE
+# define AI_PASSIVE 0x0001 /* Socket address is intended for 'bind'. */
+# endif
+# ifndef AI_CANONNAME
+# define AI_CANONNAME 0x0002 /* Request for canonical name. */
+# endif
+# ifndef AI_NUMERICSERV
+# define AI_NUMERICSERV 0x0400 /* Don't use name resolution. */
+# endif
+
+# if 0
+# define AI_NUMERICHOST 0x0004 /* Don't use name resolution. */
+# endif
+
+/* These symbolic constants are required to be present by POSIX, but
+ our getaddrinfo replacement doesn't use them (yet). Setting them
+ to 0 on systems that doesn't have them avoids causing problems for
+ system getaddrinfo implementations that would be confused by
+ unknown values. */
+# ifndef AI_V4MAPPED
+# define AI_V4MAPPED 0 /* 0x0008: IPv4 mapped addresses are acceptable. */
+# endif
+# ifndef AI_ALL
+# define AI_ALL 0 /* 0x0010: Return IPv4 mapped and IPv6 addresses. */
+# endif
+# ifndef AI_ADDRCONFIG
+# define AI_ADDRCONFIG 0 /* 0x0020: Use configuration of this host to choose
+ returned address type. */
+# endif
+
+/* Error values for 'getaddrinfo' function. */
+# ifndef EAI_BADFLAGS
+# define EAI_BADFLAGS -1 /* Invalid value for 'ai_flags' field. */
+# define EAI_NONAME -2 /* NAME or SERVICE is unknown. */
+# define EAI_AGAIN -3 /* Temporary failure in name resolution. */
+# define EAI_FAIL -4 /* Non-recoverable failure in name res. */
+# define EAI_NODATA -5 /* No address associated with NAME. */
+# define EAI_FAMILY -6 /* 'ai_family' not supported. */
+# define EAI_SOCKTYPE -7 /* 'ai_socktype' not supported. */
+# define EAI_SERVICE -8 /* SERVICE not supported for 'ai_socktype'. */
+# define EAI_MEMORY -10 /* Memory allocation failure. */
+# endif
+
+/* Since EAI_NODATA is deprecated by RFC3493, some systems (at least
+ FreeBSD, which does define EAI_BADFLAGS) have removed the definition
+ in favor of EAI_NONAME. */
+# if !defined EAI_NODATA && defined EAI_NONAME
+# define EAI_NODATA EAI_NONAME
+# endif
+
+# ifndef EAI_OVERFLOW
+/* Not defined on mingw32 and Haiku. */
+# define EAI_OVERFLOW -12 /* Argument buffer overflow. */
+# endif
+# ifndef EAI_ADDRFAMILY
+/* Not defined on mingw32. */
+# define EAI_ADDRFAMILY -9 /* Address family for NAME not supported. */
+# endif
+# ifndef EAI_SYSTEM
+/* Not defined on mingw32. */
+# define EAI_SYSTEM -11 /* System error returned in 'errno'. */
+# endif
+
+# if 0
+/* The commented out definitions below are not yet implemented in the
+ GNULIB getaddrinfo() replacement, so are not yet needed.
+
+ If they are restored, be sure to protect the definitions with #ifndef. */
+# ifndef EAI_INPROGRESS
+# define EAI_INPROGRESS -100 /* Processing request in progress. */
+# define EAI_CANCELED -101 /* Request canceled. */
+# define EAI_NOTCANCELED -102 /* Request not canceled. */
+# define EAI_ALLDONE -103 /* All requests done. */
+# define EAI_INTR -104 /* Interrupted by a signal. */
+# define EAI_IDN_ENCODE -105 /* IDN encoding failed. */
+# endif
+# endif
+
+# if !@HAVE_DECL_GETADDRINFO@
+/* Translate name of a service location and/or a service name to set of
+ socket addresses.
+ For more details, see the POSIX:2001 specification
+ <http://www.opengroup.org/susv3xsh/getaddrinfo.html>. */
+_GL_FUNCDECL_SYS (getaddrinfo, int,
+ (const char *restrict nodename,
+ const char *restrict servname,
+ const struct addrinfo *restrict hints,
+ struct addrinfo **restrict res)
+ _GL_ARG_NONNULL ((4)));
+# endif
+_GL_CXXALIAS_SYS (getaddrinfo, int,
+ (const char *restrict nodename,
+ const char *restrict servname,
+ const struct addrinfo *restrict hints,
+ struct addrinfo **restrict res));
+_GL_CXXALIASWARN (getaddrinfo);
+
+# if !@HAVE_DECL_FREEADDRINFO@
+/* Free 'addrinfo' structure AI including associated storage.
+ For more details, see the POSIX:2001 specification
+ <http://www.opengroup.org/susv3xsh/getaddrinfo.html>. */
+_GL_FUNCDECL_SYS (freeaddrinfo, void, (struct addrinfo *ai)
+ _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (freeaddrinfo, void, (struct addrinfo *ai));
+_GL_CXXALIASWARN (freeaddrinfo);
+
+# if @REPLACE_GAI_STRERROR@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef gai_strerror
+# define gai_strerror rpl_gai_strerror
+# endif
+_GL_FUNCDECL_RPL (gai_strerror, const char *, (int ecode));
+_GL_CXXALIAS_RPL (gai_strerror, const char *, (int ecode));
+# else
+# if !@HAVE_DECL_GAI_STRERROR@
+/* Convert error return from getaddrinfo() to a string.
+ For more details, see the POSIX:2001 specification
+ <http://www.opengroup.org/susv3xsh/gai_strerror.html>. */
+_GL_FUNCDECL_SYS (gai_strerror, const char *, (int ecode));
+# endif
+_GL_CXXALIAS_SYS (gai_strerror, const char *, (int ecode));
+# endif
+_GL_CXXALIASWARN (gai_strerror);
+
+# if !@HAVE_DECL_GETNAMEINFO@
+/* Convert socket address to printable node and service names.
+ For more details, see the POSIX:2001 specification
+ <http://www.opengroup.org/susv3xsh/getnameinfo.html>. */
+_GL_FUNCDECL_SYS (getnameinfo, int,
+ (const struct sockaddr *restrict sa, socklen_t salen,
+ char *restrict node, socklen_t nodelen,
+ char *restrict service, socklen_t servicelen,
+ int flags)
+ _GL_ARG_NONNULL ((1)));
+# endif
+/* Need to cast, because on glibc systems, the seventh parameter is
+ unsigned int flags. */
+_GL_CXXALIAS_SYS_CAST (getnameinfo, int,
+ (const struct sockaddr *restrict sa, socklen_t salen,
+ char *restrict node, socklen_t nodelen,
+ char *restrict service, socklen_t servicelen,
+ int flags));
+_GL_CXXALIASWARN (getnameinfo);
+
+/* Possible flags for getnameinfo. */
+# ifndef NI_NUMERICHOST
+# define NI_NUMERICHOST 1
+# endif
+# ifndef NI_NUMERICSERV
+# define NI_NUMERICSERV 2
+# endif
+
+#elif defined GNULIB_POSIXCHECK
+
+# undef getaddrinfo
+# if HAVE_RAW_DECL_GETADDRINFO
+_GL_WARN_ON_USE (getaddrinfo, "getaddrinfo is unportable - "
+ "use gnulib module getaddrinfo for portability");
+# endif
+
+# undef freeaddrinfo
+# if HAVE_RAW_DECL_FREEADDRINFO
+_GL_WARN_ON_USE (freeaddrinfo, "freeaddrinfo is unportable - "
+ "use gnulib module getaddrinfo for portability");
+# endif
+
+# undef gai_strerror
+# if HAVE_RAW_DECL_GAI_STRERROR
+_GL_WARN_ON_USE (gai_strerror, "gai_strerror is unportable - "
+ "use gnulib module getaddrinfo for portability");
+# endif
+
+# undef getnameinfo
+# if HAVE_RAW_DECL_GETNAMEINFO
+_GL_WARN_ON_USE (getnameinfo, "getnameinfo is unportable - "
+ "use gnulib module getaddrinfo for portability");
+# endif
+
+#endif
+
+#endif /* _@GUARD_PREFIX@_NETDB_H */
+#endif /* _@GUARD_PREFIX@_NETDB_H */
diff --git a/lib/netinet_in_.h b/lib/netinet_in.in.h
index 4a53605..54e1ec0 100644
--- a/lib/netinet_in_.h
+++ b/lib/netinet_in.in.h
@@ -1,9 +1,9 @@
/* Substitute for <netinet/in.h>.
- Copyright (C) 2007 Free Software Foundation, Inc.
+ Copyright (C) 2007-2016 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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -12,21 +12,30 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program; if not, see <http://www.gnu.org/licenses/>. */
-#ifndef _GL_NETINET_IN_H
-#define _GL_NETINET_IN_H
+#ifndef _@GUARD_PREFIX@_NETINET_IN_H
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
#if @HAVE_NETINET_IN_H@
/* On many platforms, <netinet/in.h> assumes prior inclusion of
<sys/types.h>. */
-
# include <sys/types.h>
-# include @ABSOLUTE_NETINET_IN_H@
-#else
+/* The include_next requires a split double-inclusion guard. */
+# @INCLUDE_NEXT@ @NEXT_NETINET_IN_H@
+
+#endif
+
+#ifndef _@GUARD_PREFIX@_NETINET_IN_H
+#define _@GUARD_PREFIX@_NETINET_IN_H
+
+#if !@HAVE_NETINET_IN_H@
/* A platform that lacks <netinet/in.h>. */
@@ -34,4 +43,5 @@
#endif
-#endif /* _GL_NETINET_IN_H */
+#endif /* _@GUARD_PREFIX@_NETINET_IN_H */
+#endif /* _@GUARD_PREFIX@_NETINET_IN_H */
diff --git a/lib/nl_langinfo.c b/lib/nl_langinfo.c
new file mode 100644
index 0000000..699511a
--- /dev/null
+++ b/lib/nl_langinfo.c
@@ -0,0 +1,322 @@
+/* nl_langinfo() replacement: query locale dependent information.
+
+ Copyright (C) 2007-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <langinfo.h>
+
+#include <locale.h>
+#include <string.h>
+#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+# define WIN32_LEAN_AND_MEAN /* avoid including junk */
+# include <windows.h>
+# include <stdio.h>
+#endif
+
+/* Return the codeset of the current locale, if this is easily deducible.
+ Otherwise, return "". */
+static char *
+ctype_codeset (void)
+{
+ static char buf[2 + 10 + 1];
+ size_t buflen = 0;
+ char const *locale = setlocale (LC_CTYPE, NULL);
+ char *codeset = buf;
+ size_t codesetlen;
+ codeset[0] = '\0';
+
+ if (locale && locale[0])
+ {
+ /* If the locale name contains an encoding after the dot, return it. */
+ char *dot = strchr (locale, '.');
+
+ if (dot)
+ {
+ /* Look for the possible @... trailer and remove it, if any. */
+ char *codeset_start = dot + 1;
+ char const *modifier = strchr (codeset_start, '@');
+
+ if (! modifier)
+ codeset = codeset_start;
+ else
+ {
+ codesetlen = modifier - codeset_start;
+ if (codesetlen < sizeof buf)
+ {
+ codeset = memcpy (buf, codeset_start, codesetlen);
+ codeset[codesetlen] = '\0';
+ }
+ }
+ }
+ }
+
+#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+ /* If setlocale is successful, it returns the number of the
+ codepage, as a string. Otherwise, fall back on Windows API
+ GetACP, which returns the locale's codepage as a number (although
+ this doesn't change according to what the 'setlocale' call specified).
+ Either way, prepend "CP" to make it a valid codeset name. */
+ codesetlen = strlen (codeset);
+ if (0 < codesetlen && codesetlen < sizeof buf - 2)
+ memmove (buf + 2, codeset, codesetlen + 1);
+ else
+ sprintf (buf + 2, "%u", GetACP ());
+ codeset = memcpy (buf, "CP", 2);
+#endif
+ return codeset;
+}
+
+
+#if REPLACE_NL_LANGINFO
+
+/* Override nl_langinfo with support for added nl_item values. */
+
+# undef nl_langinfo
+
+char *
+rpl_nl_langinfo (nl_item item)
+{
+ switch (item)
+ {
+# if GNULIB_defined_CODESET
+ case CODESET:
+ return ctype_codeset ();
+# endif
+# if GNULIB_defined_T_FMT_AMPM
+ case T_FMT_AMPM:
+ return "%I:%M:%S %p";
+# endif
+# if GNULIB_defined_ERA
+ case ERA:
+ /* The format is not standardized. In glibc it is a sequence of strings
+ of the form "direction:offset:start_date:end_date:era_name:era_format"
+ with an empty string at the end. */
+ return "";
+ case ERA_D_FMT:
+ /* The %Ex conversion in strftime behaves like %x if the locale does not
+ have an alternative time format. */
+ item = D_FMT;
+ break;
+ case ERA_D_T_FMT:
+ /* The %Ec conversion in strftime behaves like %c if the locale does not
+ have an alternative time format. */
+ item = D_T_FMT;
+ break;
+ case ERA_T_FMT:
+ /* The %EX conversion in strftime behaves like %X if the locale does not
+ have an alternative time format. */
+ item = T_FMT;
+ break;
+ case ALT_DIGITS:
+ /* The format is not standardized. In glibc it is a sequence of 10
+ strings, appended in memory. */
+ return "\0\0\0\0\0\0\0\0\0\0";
+# endif
+# if GNULIB_defined_YESEXPR || !FUNC_NL_LANGINFO_YESEXPR_WORKS
+ case YESEXPR:
+ return "^[yY]";
+ case NOEXPR:
+ return "^[nN]";
+# endif
+ default:
+ break;
+ }
+ return nl_langinfo (item);
+}
+
+#else
+
+/* Provide nl_langinfo from scratch, either for native MS-Windows, or
+ for old Unix platforms without locales, such as Linux libc5 or
+ BeOS. */
+
+# include <time.h>
+
+char *
+nl_langinfo (nl_item item)
+{
+ static char nlbuf[100];
+ struct tm tmm = { 0 };
+
+ switch (item)
+ {
+ /* nl_langinfo items of the LC_CTYPE category */
+ case CODESET:
+ {
+ char *codeset = ctype_codeset ();
+ if (*codeset)
+ return codeset;
+ }
+# ifdef __BEOS__
+ return "UTF-8";
+# else
+ return "ISO-8859-1";
+# endif
+ /* nl_langinfo items of the LC_NUMERIC category */
+ case RADIXCHAR:
+ return localeconv () ->decimal_point;
+ case THOUSEP:
+ return localeconv () ->thousands_sep;
+ case GROUPING:
+ return localeconv () ->grouping;
+ /* nl_langinfo items of the LC_TIME category.
+ TODO: Really use the locale. */
+ case D_T_FMT:
+ case ERA_D_T_FMT:
+ return "%a %b %e %H:%M:%S %Y";
+ case D_FMT:
+ case ERA_D_FMT:
+ return "%m/%d/%y";
+ case T_FMT:
+ case ERA_T_FMT:
+ return "%H:%M:%S";
+ case T_FMT_AMPM:
+ return "%I:%M:%S %p";
+ case AM_STR:
+ if (!strftime (nlbuf, sizeof nlbuf, "%p", &tmm))
+ return "AM";
+ return nlbuf;
+ case PM_STR:
+ tmm.tm_hour = 12;
+ if (!strftime (nlbuf, sizeof nlbuf, "%p", &tmm))
+ return "PM";
+ return nlbuf;
+ case DAY_1:
+ case DAY_2:
+ case DAY_3:
+ case DAY_4:
+ case DAY_5:
+ case DAY_6:
+ case DAY_7:
+ {
+ static char const days[][sizeof "Wednesday"] = {
+ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
+ "Friday", "Saturday"
+ };
+ tmm.tm_wday = item - DAY_1;
+ if (!strftime (nlbuf, sizeof nlbuf, "%A", &tmm))
+ return (char *) days[item - DAY_1];
+ return nlbuf;
+ }
+ case ABDAY_1:
+ case ABDAY_2:
+ case ABDAY_3:
+ case ABDAY_4:
+ case ABDAY_5:
+ case ABDAY_6:
+ case ABDAY_7:
+ {
+ static char const abdays[][sizeof "Sun"] = {
+ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
+ };
+ tmm.tm_wday = item - ABDAY_1;
+ if (!strftime (nlbuf, sizeof nlbuf, "%a", &tmm))
+ return (char *) abdays[item - ABDAY_1];
+ return nlbuf;
+ }
+ case MON_1:
+ case MON_2:
+ case MON_3:
+ case MON_4:
+ case MON_5:
+ case MON_6:
+ case MON_7:
+ case MON_8:
+ case MON_9:
+ case MON_10:
+ case MON_11:
+ case MON_12:
+ {
+ static char const months[][sizeof "September"] = {
+ "January", "February", "March", "April", "May", "June", "July",
+ "September", "October", "November", "December"
+ };
+ tmm.tm_mon = item - MON_1;
+ if (!strftime (nlbuf, sizeof nlbuf, "%B", &tmm))
+ return (char *) months[item - MON_1];
+ return nlbuf;
+ }
+ case ABMON_1:
+ case ABMON_2:
+ case ABMON_3:
+ case ABMON_4:
+ case ABMON_5:
+ case ABMON_6:
+ case ABMON_7:
+ case ABMON_8:
+ case ABMON_9:
+ case ABMON_10:
+ case ABMON_11:
+ case ABMON_12:
+ {
+ static char const abmonths[][sizeof "Jan"] = {
+ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
+ "Sep", "Oct", "Nov", "Dec"
+ };
+ tmm.tm_mon = item - ABMON_1;
+ if (!strftime (nlbuf, sizeof nlbuf, "%b", &tmm))
+ return (char *) abmonths[item - ABMON_1];
+ return nlbuf;
+ }
+ case ERA:
+ return "";
+ case ALT_DIGITS:
+ return "\0\0\0\0\0\0\0\0\0\0";
+ /* nl_langinfo items of the LC_MONETARY category. */
+ case CRNCYSTR:
+ return localeconv () ->currency_symbol;
+ case INT_CURR_SYMBOL:
+ return localeconv () ->int_curr_symbol;
+ case MON_DECIMAL_POINT:
+ return localeconv () ->mon_decimal_point;
+ case MON_THOUSANDS_SEP:
+ return localeconv () ->mon_thousands_sep;
+ case MON_GROUPING:
+ return localeconv () ->mon_grouping;
+ case POSITIVE_SIGN:
+ return localeconv () ->positive_sign;
+ case NEGATIVE_SIGN:
+ return localeconv () ->negative_sign;
+ case FRAC_DIGITS:
+ return & localeconv () ->frac_digits;
+ case INT_FRAC_DIGITS:
+ return & localeconv () ->int_frac_digits;
+ case P_CS_PRECEDES:
+ return & localeconv () ->p_cs_precedes;
+ case N_CS_PRECEDES:
+ return & localeconv () ->n_cs_precedes;
+ case P_SEP_BY_SPACE:
+ return & localeconv () ->p_sep_by_space;
+ case N_SEP_BY_SPACE:
+ return & localeconv () ->n_sep_by_space;
+ case P_SIGN_POSN:
+ return & localeconv () ->p_sign_posn;
+ case N_SIGN_POSN:
+ return & localeconv () ->n_sign_posn;
+ /* nl_langinfo items of the LC_MESSAGES category
+ TODO: Really use the locale. */
+ case YESEXPR:
+ return "^[yY]";
+ case NOEXPR:
+ return "^[nN]";
+ default:
+ return "";
+ }
+}
+
+#endif
diff --git a/lib/nproc.c b/lib/nproc.c
new file mode 100644
index 0000000..c7e93cd
--- /dev/null
+++ b/lib/nproc.c
@@ -0,0 +1,357 @@
+/* Detect the number of processors.
+
+ Copyright (C) 2009-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Glen Lenker and Bruno Haible. */
+
+#include <config.h>
+#include "nproc.h"
+
+#include <stdlib.h>
+#include <unistd.h>
+
+#if HAVE_PTHREAD_GETAFFINITY_NP && 0
+# include <pthread.h>
+# include <sched.h>
+#endif
+#if HAVE_SCHED_GETAFFINITY_LIKE_GLIBC || HAVE_SCHED_GETAFFINITY_NP
+# include <sched.h>
+#endif
+
+#include <sys/types.h>
+
+#if HAVE_SYS_PSTAT_H
+# include <sys/pstat.h>
+#endif
+
+#if HAVE_SYS_SYSMP_H
+# include <sys/sysmp.h>
+#endif
+
+#if HAVE_SYS_PARAM_H
+# include <sys/param.h>
+#endif
+
+#if HAVE_SYS_SYSCTL_H
+# include <sys/sysctl.h>
+#endif
+
+#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+# define WIN32_LEAN_AND_MEAN
+# include <windows.h>
+#endif
+
+#include "c-ctype.h"
+
+#define ARRAY_SIZE(a) (sizeof (a) / sizeof ((a)[0]))
+
+/* Return the number of processors available to the current process, based
+ on a modern system call that returns the "affinity" between the current
+ process and each CPU. Return 0 if unknown or if such a system call does
+ not exist. */
+static unsigned long
+num_processors_via_affinity_mask (void)
+{
+ /* glibc >= 2.3.3 with NPTL and NetBSD 5 have pthread_getaffinity_np,
+ but with different APIs. Also it requires linking with -lpthread.
+ Therefore this code is not enabled.
+ glibc >= 2.3.4 has sched_getaffinity whereas NetBSD 5 has
+ sched_getaffinity_np. */
+#if HAVE_PTHREAD_GETAFFINITY_NP && defined __GLIBC__ && 0
+ {
+ cpu_set_t set;
+
+ if (pthread_getaffinity_np (pthread_self (), sizeof (set), &set) == 0)
+ {
+ unsigned long count;
+
+# ifdef CPU_COUNT
+ /* glibc >= 2.6 has the CPU_COUNT macro. */
+ count = CPU_COUNT (&set);
+# else
+ size_t i;
+
+ count = 0;
+ for (i = 0; i < CPU_SETSIZE; i++)
+ if (CPU_ISSET (i, &set))
+ count++;
+# endif
+ if (count > 0)
+ return count;
+ }
+ }
+#elif HAVE_PTHREAD_GETAFFINITY_NP && defined __NetBSD__ && 0
+ {
+ cpuset_t *set;
+
+ set = cpuset_create ();
+ if (set != NULL)
+ {
+ unsigned long count = 0;
+
+ if (pthread_getaffinity_np (pthread_self (), cpuset_size (set), set)
+ == 0)
+ {
+ cpuid_t i;
+
+ for (i = 0;; i++)
+ {
+ int ret = cpuset_isset (i, set);
+ if (ret < 0)
+ break;
+ if (ret > 0)
+ count++;
+ }
+ }
+ cpuset_destroy (set);
+ if (count > 0)
+ return count;
+ }
+ }
+#elif HAVE_SCHED_GETAFFINITY_LIKE_GLIBC /* glibc >= 2.3.4 */
+ {
+ cpu_set_t set;
+
+ if (sched_getaffinity (0, sizeof (set), &set) == 0)
+ {
+ unsigned long count;
+
+# ifdef CPU_COUNT
+ /* glibc >= 2.6 has the CPU_COUNT macro. */
+ count = CPU_COUNT (&set);
+# else
+ size_t i;
+
+ count = 0;
+ for (i = 0; i < CPU_SETSIZE; i++)
+ if (CPU_ISSET (i, &set))
+ count++;
+# endif
+ if (count > 0)
+ return count;
+ }
+ }
+#elif HAVE_SCHED_GETAFFINITY_NP /* NetBSD >= 5 */
+ {
+ cpuset_t *set;
+
+ set = cpuset_create ();
+ if (set != NULL)
+ {
+ unsigned long count = 0;
+
+ if (sched_getaffinity_np (getpid (), cpuset_size (set), set) == 0)
+ {
+ cpuid_t i;
+
+ for (i = 0;; i++)
+ {
+ int ret = cpuset_isset (i, set);
+ if (ret < 0)
+ break;
+ if (ret > 0)
+ count++;
+ }
+ }
+ cpuset_destroy (set);
+ if (count > 0)
+ return count;
+ }
+ }
+#endif
+
+#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+ { /* This works on native Windows platforms. */
+ DWORD_PTR process_mask;
+ DWORD_PTR system_mask;
+
+ if (GetProcessAffinityMask (GetCurrentProcess (),
+ &process_mask, &system_mask))
+ {
+ DWORD_PTR mask = process_mask;
+ unsigned long count = 0;
+
+ for (; mask != 0; mask = mask >> 1)
+ if (mask & 1)
+ count++;
+ if (count > 0)
+ return count;
+ }
+ }
+#endif
+
+ return 0;
+}
+
+unsigned long int
+num_processors (enum nproc_query query)
+{
+ if (query == NPROC_CURRENT_OVERRIDABLE)
+ {
+ /* Test the environment variable OMP_NUM_THREADS, recognized also by all
+ programs that are based on OpenMP. The OpenMP spec says that the
+ value assigned to the environment variable "may have leading and
+ trailing white space". */
+ const char *envvalue = getenv ("OMP_NUM_THREADS");
+
+ if (envvalue != NULL)
+ {
+ while (*envvalue != '\0' && c_isspace (*envvalue))
+ envvalue++;
+ /* Convert it from decimal to 'unsigned long'. */
+ if (c_isdigit (*envvalue))
+ {
+ char *endptr = NULL;
+ unsigned long int value = strtoul (envvalue, &endptr, 10);
+
+ if (endptr != NULL)
+ {
+ while (*endptr != '\0' && c_isspace (*endptr))
+ endptr++;
+ if (*endptr == '\0')
+ return (value > 0 ? value : 1);
+ }
+ }
+ }
+
+ query = NPROC_CURRENT;
+ }
+ /* Here query is one of NPROC_ALL, NPROC_CURRENT. */
+
+ /* On systems with a modern affinity mask system call, we have
+ sysconf (_SC_NPROCESSORS_CONF)
+ >= sysconf (_SC_NPROCESSORS_ONLN)
+ >= num_processors_via_affinity_mask ()
+ The first number is the number of CPUs configured in the system.
+ The second number is the number of CPUs available to the scheduler.
+ The third number is the number of CPUs available to the current process.
+
+ Note! On Linux systems with glibc, the first and second number come from
+ the /sys and /proc file systems (see
+ glibc/sysdeps/unix/sysv/linux/getsysstats.c).
+ In some situations these file systems are not mounted, and the sysconf
+ call returns 1, which does not reflect the reality. */
+
+ if (query == NPROC_CURRENT)
+ {
+ /* Try the modern affinity mask system call. */
+ {
+ unsigned long nprocs = num_processors_via_affinity_mask ();
+
+ if (nprocs > 0)
+ return nprocs;
+ }
+
+#if defined _SC_NPROCESSORS_ONLN
+ { /* This works on glibc, Mac OS X 10.5, FreeBSD, AIX, OSF/1, Solaris,
+ Cygwin, Haiku. */
+ long int nprocs = sysconf (_SC_NPROCESSORS_ONLN);
+ if (nprocs > 0)
+ return nprocs;
+ }
+#endif
+ }
+ else /* query == NPROC_ALL */
+ {
+#if defined _SC_NPROCESSORS_CONF
+ { /* This works on glibc, Mac OS X 10.5, FreeBSD, AIX, OSF/1, Solaris,
+ Cygwin, Haiku. */
+ long int nprocs = sysconf (_SC_NPROCESSORS_CONF);
+
+# if __GLIBC__ >= 2 && defined __linux__
+ /* On Linux systems with glibc, this information comes from the /sys and
+ /proc file systems (see glibc/sysdeps/unix/sysv/linux/getsysstats.c).
+ In some situations these file systems are not mounted, and the
+ sysconf call returns 1. But we wish to guarantee that
+ num_processors (NPROC_ALL) >= num_processors (NPROC_CURRENT). */
+ if (nprocs == 1)
+ {
+ unsigned long nprocs_current = num_processors_via_affinity_mask ();
+
+ if (nprocs_current > 0)
+ nprocs = nprocs_current;
+ }
+# endif
+
+ if (nprocs > 0)
+ return nprocs;
+ }
+#endif
+ }
+
+#if HAVE_PSTAT_GETDYNAMIC
+ { /* This works on HP-UX. */
+ struct pst_dynamic psd;
+ if (pstat_getdynamic (&psd, sizeof psd, 1, 0) >= 0)
+ {
+ /* The field psd_proc_cnt contains the number of active processors.
+ In newer releases of HP-UX 11, the field psd_max_proc_cnt includes
+ deactivated processors. */
+ if (query == NPROC_CURRENT)
+ {
+ if (psd.psd_proc_cnt > 0)
+ return psd.psd_proc_cnt;
+ }
+ else
+ {
+ if (psd.psd_max_proc_cnt > 0)
+ return psd.psd_max_proc_cnt;
+ }
+ }
+ }
+#endif
+
+#if HAVE_SYSMP && defined MP_NAPROCS && defined MP_NPROCS
+ { /* This works on IRIX. */
+ /* MP_NPROCS yields the number of installed processors.
+ MP_NAPROCS yields the number of processors available to unprivileged
+ processes. */
+ int nprocs =
+ sysmp (query == NPROC_CURRENT && getpid () != 0
+ ? MP_NAPROCS
+ : MP_NPROCS);
+ if (nprocs > 0)
+ return nprocs;
+ }
+#endif
+
+ /* Finally, as fallback, use the APIs that don't distinguish between
+ NPROC_CURRENT and NPROC_ALL. */
+
+#if HAVE_SYSCTL && defined HW_NCPU
+ { /* This works on Mac OS X, FreeBSD, NetBSD, OpenBSD. */
+ int nprocs;
+ size_t len = sizeof (nprocs);
+ static int mib[2] = { CTL_HW, HW_NCPU };
+
+ if (sysctl (mib, ARRAY_SIZE (mib), &nprocs, &len, NULL, 0) == 0
+ && len == sizeof (nprocs)
+ && 0 < nprocs)
+ return nprocs;
+ }
+#endif
+
+#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+ { /* This works on native Windows platforms. */
+ SYSTEM_INFO system_info;
+ GetSystemInfo (&system_info);
+ if (0 < system_info.dwNumberOfProcessors)
+ return system_info.dwNumberOfProcessors;
+ }
+#endif
+
+ return 1;
+}
diff --git a/lib/nproc.h b/lib/nproc.h
new file mode 100644
index 0000000..2058887
--- /dev/null
+++ b/lib/nproc.h
@@ -0,0 +1,46 @@
+/* Detect the number of processors.
+
+ Copyright (C) 2009-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Glen Lenker and Bruno Haible. */
+
+/* Allow the use in C++ code. */
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* A "processor" in this context means a thread execution unit, that is either
+ - an execution core in a (possibly multi-core) chip, in a (possibly multi-
+ chip) module, in a single computer, or
+ - a thread execution unit inside a core
+ (hyper-threading, see <http://en.wikipedia.org/wiki/Hyper-threading>).
+ Which of the two definitions is used, is unspecified. */
+
+enum nproc_query
+{
+ NPROC_ALL, /* total number of processors */
+ NPROC_CURRENT, /* processors available to the current process */
+ NPROC_CURRENT_OVERRIDABLE /* likewise, but overridable through the
+ OMP_NUM_THREADS environment variable */
+};
+
+/* Return the total number of processors. The result is guaranteed to
+ be at least 1. */
+extern unsigned long int num_processors (enum nproc_query query);
+
+#ifdef __cplusplus
+}
+#endif /* C++ */
diff --git a/lib/obstack.c b/lib/obstack.c
index 5cd0b7a..24b67a5 100644
--- a/lib/obstack.c
+++ b/lib/obstack.c
@@ -1,35 +1,32 @@
/* obstack.c - subroutines used implicitly by object stack macros
+ Copyright (C) 1988-2016 Free Software Foundation, Inc.
+ This file is part of the GNU C Library.
- Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1996, 1997,
- 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software
- Foundation, Inc.
+ The GNU C Library 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 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 2, or (at your option)
- any later version.
-
- This program is distributed in the hope that it will be useful,
+ The GNU C Library 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.
+ 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 the GNU C Library; if not, see
+ <http://www.gnu.org/licenses/>. */
- You should have received a copy of the GNU General Public License along
- with this program; if not, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
#ifdef _LIBC
# include <obstack.h>
-# include <shlib-compat.h>
#else
# include <config.h>
# include "obstack.h"
#endif
-/* NOTE BEFORE MODIFYING THIS FILE: This version number must be
- incremented whenever callers compiled using an old obstack.h can no
- longer properly call the functions in this obstack.c. */
-#define OBSTACK_INTERFACE_VERSION 1
+/* NOTE BEFORE MODIFYING THIS FILE: _OBSTACK_INTERFACE_VERSION in
+ obstack.h must be incremented whenever callers compiled using an old
+ obstack.h can no longer properly call the functions in this file. */
/* Comment out all this code if we are using the GNU C Library, and are not
actually compiling the library itself, and the installed library
@@ -37,116 +34,82 @@
C Library, but also included in many other GNU distributions. Compiling
and linking in this code is a waste when using the GNU C library
(especially if it is a shared library). Rather than having every GNU
- program understand `configure --with-gnu-libc' and omit the object
+ program understand 'configure --with-gnu-libc' and omit the object
files, it is simpler to just do this in the source for each such file. */
-
-#include <stdio.h> /* Random thing to get __GNU_LIBRARY__. */
#if !defined _LIBC && defined __GNU_LIBRARY__ && __GNU_LIBRARY__ > 1
# include <gnu-versions.h>
-# if _GNU_OBSTACK_INTERFACE_VERSION == OBSTACK_INTERFACE_VERSION
-# define ELIDE_CODE
+# if (_GNU_OBSTACK_INTERFACE_VERSION == _OBSTACK_INTERFACE_VERSION \
+ || (_GNU_OBSTACK_INTERFACE_VERSION == 1 \
+ && _OBSTACK_INTERFACE_VERSION == 2 \
+ && defined SIZEOF_INT && defined SIZEOF_SIZE_T \
+ && SIZEOF_INT == SIZEOF_SIZE_T))
+# define _OBSTACK_ELIDE_CODE
# endif
#endif
-#include <stddef.h>
-
-#ifndef ELIDE_CODE
-
+#ifndef _OBSTACK_ELIDE_CODE
+/* If GCC, or if an oddball (testing?) host that #defines __alignof__,
+ use the already-supplied __alignof__. Otherwise, this must be Gnulib
+ (as glibc assumes GCC); defer to Gnulib's alignof_type. */
+# if !defined __GNUC__ && !defined __alignof__
+# include <alignof.h>
+# define __alignof__(type) alignof_type (type)
+# endif
+# include <stdlib.h>
# include <stdint.h>
-/* Determine default alignment. */
-union fooround
-{
- uintmax_t i;
- long double d;
- void *p;
-};
-struct fooalign
-{
- char c;
- union fooround u;
-};
-/* If malloc were really smart, it would round addresses to DEFAULT_ALIGNMENT.
- But in fact it might be less smart and round addresses to as much as
- DEFAULT_ROUNDING. So we prepare for it to do that. */
-enum
- {
- DEFAULT_ALIGNMENT = offsetof (struct fooalign, u),
- DEFAULT_ROUNDING = sizeof (union fooround)
- };
-
-/* When we copy a long block of data, this is the unit to do it with.
- On some machines, copying successive ints does not work;
- in such a case, redefine COPYING_UNIT to `long' (if that works)
- or `char' as a last resort. */
-# ifndef COPYING_UNIT
-# define COPYING_UNIT int
+# ifndef MAX
+# define MAX(a,b) ((a) > (b) ? (a) : (b))
# endif
+/* Determine default alignment. */
-/* The functions allocating more room by calling `obstack_chunk_alloc'
- jump to the handler pointed to by `obstack_alloc_failed_handler'.
- This can be set to a user defined function which should either
- abort gracefully or use longjump - but shouldn't return. This
- variable by default points to the internal function
- `print_and_abort'. */
-static void print_and_abort (void);
-void (*obstack_alloc_failed_handler) (void) = print_and_abort;
+/* If malloc were really smart, it would round addresses to DEFAULT_ALIGNMENT.
+ But in fact it might be less smart and round addresses to as much as
+ DEFAULT_ROUNDING. So we prepare for it to do that.
+
+ DEFAULT_ALIGNMENT cannot be an enum constant; see gnulib's alignof.h. */
+#define DEFAULT_ALIGNMENT MAX (__alignof__ (long double), \
+ MAX (__alignof__ (uintmax_t), \
+ __alignof__ (void *)))
+#define DEFAULT_ROUNDING MAX (sizeof (long double), \
+ MAX (sizeof (uintmax_t), \
+ sizeof (void *)))
+
+/* Call functions with either the traditional malloc/free calling
+ interface, or the mmalloc/mfree interface (that adds an extra first
+ argument), based on the value of use_extra_arg. */
+
+static void *
+call_chunkfun (struct obstack *h, size_t size)
+{
+ if (h->use_extra_arg)
+ return h->chunkfun.extra (h->extra_arg, size);
+ else
+ return h->chunkfun.plain (size);
+}
-/* Exit value used when `print_and_abort' is used. */
-# include <stdlib.h>
-# ifdef _LIBC
-int obstack_exit_failure = EXIT_FAILURE;
-# else
-# include "exitfail.h"
-# define obstack_exit_failure exit_failure
-# endif
+static void
+call_freefun (struct obstack *h, void *old_chunk)
+{
+ if (h->use_extra_arg)
+ h->freefun.extra (h->extra_arg, old_chunk);
+ else
+ h->freefun.plain (old_chunk);
+}
-# ifdef _LIBC
-# if SHLIB_COMPAT (libc, GLIBC_2_0, GLIBC_2_3_4)
-/* A looong time ago (before 1994, anyway; we're not sure) this global variable
- was used by non-GNU-C macros to avoid multiple evaluation. The GNU C
- library still exports it because somebody might use it. */
-struct obstack *_obstack_compat;
-compat_symbol (libc, _obstack_compat, _obstack, GLIBC_2_0);
-# endif
-# endif
-/* Define a macro that either calls functions with the traditional malloc/free
- calling interface, or calls functions with the mmalloc/mfree interface
- (that adds an extra first argument), based on the state of use_extra_arg.
- For free, do not use ?:, since some compilers, like the MIPS compilers,
- do not allow (expr) ? void : void. */
-
-# define CALL_CHUNKFUN(h, size) \
- (((h) -> use_extra_arg) \
- ? (*(h)->chunkfun) ((h)->extra_arg, (size)) \
- : (*(struct _obstack_chunk *(*) (long)) (h)->chunkfun) ((size)))
-
-# define CALL_FREEFUN(h, old_chunk) \
- do { \
- if ((h) -> use_extra_arg) \
- (*(h)->freefun) ((h)->extra_arg, (old_chunk)); \
- else \
- (*(void (*) (void *)) (h)->freefun) ((old_chunk)); \
- } while (0)
-
-
/* Initialize an obstack H for use. Specify chunk size SIZE (0 means default).
Objects start on multiples of ALIGNMENT (0 means use default).
- CHUNKFUN is the function to use to allocate chunks,
- and FREEFUN the function to free them.
Return nonzero if successful, calls obstack_alloc_failed_handler if
allocation fails. */
-int
-_obstack_begin (struct obstack *h,
- int size, int alignment,
- void *(*chunkfun) (long),
- void (*freefun) (void *))
+static int
+_obstack_begin_worker (struct obstack *h,
+ _OBSTACK_SIZE_T size, _OBSTACK_SIZE_T alignment)
{
- register struct _obstack_chunk *chunk; /* points to new chunk */
+ struct _obstack_chunk *chunk; /* points to new chunk */
if (alignment == 0)
alignment = DEFAULT_ALIGNMENT;
@@ -154,32 +117,28 @@ _obstack_begin (struct obstack *h,
/* Default size is what GNU malloc can fit in a 4096-byte block. */
{
/* 12 is sizeof (mhead) and 4 is EXTRA from GNU malloc.
- Use the values for range checking, because if range checking is off,
- the extra bytes won't be missed terribly, but if range checking is on
- and we used a larger request, a whole extra 4096 bytes would be
- allocated.
+ Use the values for range checking, because if range checking is off,
+ the extra bytes won't be missed terribly, but if range checking is on
+ and we used a larger request, a whole extra 4096 bytes would be
+ allocated.
- These number are irrelevant to the new GNU malloc. I suspect it is
- less sensitive to the size of the request. */
+ These number are irrelevant to the new GNU malloc. I suspect it is
+ less sensitive to the size of the request. */
int extra = ((((12 + DEFAULT_ROUNDING - 1) & ~(DEFAULT_ROUNDING - 1))
- + 4 + DEFAULT_ROUNDING - 1)
- & ~(DEFAULT_ROUNDING - 1));
+ + 4 + DEFAULT_ROUNDING - 1)
+ & ~(DEFAULT_ROUNDING - 1));
size = 4096 - extra;
}
- h->chunkfun = (struct _obstack_chunk * (*)(void *, long)) chunkfun;
- h->freefun = (void (*) (void *, struct _obstack_chunk *)) freefun;
h->chunk_size = size;
h->alignment_mask = alignment - 1;
- h->use_extra_arg = 0;
- chunk = h->chunk = CALL_CHUNKFUN (h, h -> chunk_size);
+ chunk = h->chunk = call_chunkfun (h, h->chunk_size);
if (!chunk)
(*obstack_alloc_failed_handler) ();
h->next_free = h->object_base = __PTR_ALIGN ((char *) chunk, chunk->contents,
- alignment - 1);
- h->chunk_limit = chunk->limit
- = (char *) chunk + h->chunk_size;
+ alignment - 1);
+ h->chunk_limit = chunk->limit = (char *) chunk + h->chunk_size;
chunk->prev = 0;
/* The initial chunk now contains no empty object. */
h->maybe_empty_object = 0;
@@ -188,51 +147,29 @@ _obstack_begin (struct obstack *h,
}
int
-_obstack_begin_1 (struct obstack *h, int size, int alignment,
- void *(*chunkfun) (void *, long),
- void (*freefun) (void *, void *),
- void *arg)
+_obstack_begin (struct obstack *h,
+ _OBSTACK_SIZE_T size, _OBSTACK_SIZE_T alignment,
+ void *(*chunkfun) (size_t),
+ void (*freefun) (void *))
{
- register struct _obstack_chunk *chunk; /* points to new chunk */
-
- if (alignment == 0)
- alignment = DEFAULT_ALIGNMENT;
- if (size == 0)
- /* Default size is what GNU malloc can fit in a 4096-byte block. */
- {
- /* 12 is sizeof (mhead) and 4 is EXTRA from GNU malloc.
- Use the values for range checking, because if range checking is off,
- the extra bytes won't be missed terribly, but if range checking is on
- and we used a larger request, a whole extra 4096 bytes would be
- allocated.
-
- These number are irrelevant to the new GNU malloc. I suspect it is
- less sensitive to the size of the request. */
- int extra = ((((12 + DEFAULT_ROUNDING - 1) & ~(DEFAULT_ROUNDING - 1))
- + 4 + DEFAULT_ROUNDING - 1)
- & ~(DEFAULT_ROUNDING - 1));
- size = 4096 - extra;
- }
+ h->chunkfun.plain = chunkfun;
+ h->freefun.plain = freefun;
+ h->use_extra_arg = 0;
+ return _obstack_begin_worker (h, size, alignment);
+}
- h->chunkfun = (struct _obstack_chunk * (*)(void *,long)) chunkfun;
- h->freefun = (void (*) (void *, struct _obstack_chunk *)) freefun;
- h->chunk_size = size;
- h->alignment_mask = alignment - 1;
+int
+_obstack_begin_1 (struct obstack *h,
+ _OBSTACK_SIZE_T size, _OBSTACK_SIZE_T alignment,
+ void *(*chunkfun) (void *, size_t),
+ void (*freefun) (void *, void *),
+ void *arg)
+{
+ h->chunkfun.extra = chunkfun;
+ h->freefun.extra = freefun;
h->extra_arg = arg;
h->use_extra_arg = 1;
-
- chunk = h->chunk = CALL_CHUNKFUN (h, h -> chunk_size);
- if (!chunk)
- (*obstack_alloc_failed_handler) ();
- h->next_free = h->object_base = __PTR_ALIGN ((char *) chunk, chunk->contents,
- alignment - 1);
- h->chunk_limit = chunk->limit
- = (char *) chunk + h->chunk_size;
- chunk->prev = 0;
- /* The initial chunk now contains no empty object. */
- h->maybe_empty_object = 0;
- h->alloc_failed = 0;
- return 1;
+ return _obstack_begin_worker (h, size, alignment);
}
/* Allocate a new current chunk for the obstack *H
@@ -242,25 +179,27 @@ _obstack_begin_1 (struct obstack *h, int size, int alignment,
to the beginning of the new one. */
void
-_obstack_newchunk (struct obstack *h, int length)
+_obstack_newchunk (struct obstack *h, _OBSTACK_SIZE_T length)
{
- register struct _obstack_chunk *old_chunk = h->chunk;
- register struct _obstack_chunk *new_chunk;
- register long new_size;
- register long obj_size = h->next_free - h->object_base;
- register long i;
- long already;
+ struct _obstack_chunk *old_chunk = h->chunk;
+ struct _obstack_chunk *new_chunk = 0;
+ size_t obj_size = h->next_free - h->object_base;
char *object_base;
/* Compute size for new chunk. */
- new_size = (obj_size + length) + (obj_size >> 3) + h->alignment_mask + 100;
+ size_t sum1 = obj_size + length;
+ size_t sum2 = sum1 + h->alignment_mask;
+ size_t new_size = sum2 + (obj_size >> 3) + 100;
+ if (new_size < sum2)
+ new_size = sum2;
if (new_size < h->chunk_size)
new_size = h->chunk_size;
/* Allocate and initialize the new chunk. */
- new_chunk = CALL_CHUNKFUN (h, new_size);
+ if (obj_size <= sum1 && sum1 <= sum2)
+ new_chunk = call_chunkfun (h, new_size);
if (!new_chunk)
- (*obstack_alloc_failed_handler) ();
+ (*obstack_alloc_failed_handler)();
h->chunk = new_chunk;
new_chunk->prev = old_chunk;
new_chunk->limit = h->chunk_limit = (char *) new_chunk + new_size;
@@ -269,36 +208,19 @@ _obstack_newchunk (struct obstack *h, int length)
object_base =
__PTR_ALIGN ((char *) new_chunk, new_chunk->contents, h->alignment_mask);
- /* Move the existing object to the new chunk.
- Word at a time is fast and is safe if the object
- is sufficiently aligned. */
- if (h->alignment_mask + 1 >= DEFAULT_ALIGNMENT)
- {
- for (i = obj_size / sizeof (COPYING_UNIT) - 1;
- i >= 0; i--)
- ((COPYING_UNIT *)object_base)[i]
- = ((COPYING_UNIT *)h->object_base)[i];
- /* We used to copy the odd few remaining bytes as one extra COPYING_UNIT,
- but that can cross a page boundary on a machine
- which does not do strict alignment for COPYING_UNITS. */
- already = obj_size / sizeof (COPYING_UNIT) * sizeof (COPYING_UNIT);
- }
- else
- already = 0;
- /* Copy remaining bytes one by one. */
- for (i = already; i < obj_size; i++)
- object_base[i] = h->object_base[i];
+ /* Move the existing object to the new chunk. */
+ memcpy (object_base, h->object_base, obj_size);
/* If the object just copied was the only data in OLD_CHUNK,
free that chunk and remove it from the chain.
But not if that chunk might contain an empty object. */
- if (! h->maybe_empty_object
+ if (!h->maybe_empty_object
&& (h->object_base
- == __PTR_ALIGN ((char *) old_chunk, old_chunk->contents,
- h->alignment_mask)))
+ == __PTR_ALIGN ((char *) old_chunk, old_chunk->contents,
+ h->alignment_mask)))
{
new_chunk->prev = old_chunk->prev;
- CALL_FREEFUN (h, old_chunk);
+ call_freefun (h, old_chunk);
}
h->object_base = object_base;
@@ -306,9 +228,6 @@ _obstack_newchunk (struct obstack *h, int length)
/* The new chunk certainly contains no empty object yet. */
h->maybe_empty_object = 0;
}
-# ifdef _LIBC
-libc_hidden_def (_obstack_newchunk)
-# endif
/* Return nonzero if object OBJ has been allocated from obstack H.
This is here for debugging.
@@ -316,13 +235,13 @@ libc_hidden_def (_obstack_newchunk)
/* Suppress -Wmissing-prototypes warning. We don't want to declare this in
obstack.h because it is just for debugging. */
-int _obstack_allocated_p (struct obstack *h, void *obj);
+int _obstack_allocated_p (struct obstack *h, void *obj) __attribute_pure__;
int
_obstack_allocated_p (struct obstack *h, void *obj)
{
- register struct _obstack_chunk *lp; /* below addr of any objects in this chunk */
- register struct _obstack_chunk *plp; /* point to previous chunk if any */
+ struct _obstack_chunk *lp; /* below addr of any objects in this chunk */
+ struct _obstack_chunk *plp; /* point to previous chunk if any */
lp = (h)->chunk;
/* We use >= rather than > since the object cannot be exactly at
@@ -335,17 +254,15 @@ _obstack_allocated_p (struct obstack *h, void *obj)
}
return lp != 0;
}
-
+
/* Free objects in obstack H, including OBJ and everything allocate
more recently than OBJ. If OBJ is zero, free everything in H. */
-# undef obstack_free
-
void
-__obstack_free (struct obstack *h, void *obj)
+_obstack_free (struct obstack *h, void *obj)
{
- register struct _obstack_chunk *lp; /* below addr of any objects in this chunk */
- register struct _obstack_chunk *plp; /* point to previous chunk if any */
+ struct _obstack_chunk *lp; /* below addr of any objects in this chunk */
+ struct _obstack_chunk *plp; /* point to previous chunk if any */
lp = h->chunk;
/* We use >= because there cannot be an object at the beginning of a chunk.
@@ -354,10 +271,10 @@ __obstack_free (struct obstack *h, void *obj)
while (lp != 0 && ((void *) lp >= obj || (void *) (lp)->limit < obj))
{
plp = lp->prev;
- CALL_FREEFUN (h, lp);
+ call_freefun (h, lp);
lp = plp;
/* If we switch chunks, we can't tell whether the new current
- chunk contains an empty object, so assume that it may. */
+ chunk contains an empty object, so assume that it may. */
h->maybe_empty_object = 1;
}
if (lp)
@@ -371,17 +288,11 @@ __obstack_free (struct obstack *h, void *obj)
abort ();
}
-# ifdef _LIBC
-/* Older versions of libc used a function _obstack_free intended to be
- called by non-GCC compilers. */
-strong_alias (obstack_free, _obstack_free)
-# endif
-
-int
+_OBSTACK_SIZE_T
_obstack_memory_used (struct obstack *h)
{
- register struct _obstack_chunk* lp;
- register int nbytes = 0;
+ struct _obstack_chunk *lp;
+ _OBSTACK_SIZE_T nbytes = 0;
for (lp = h->chunk; lp != 0; lp = lp->prev)
{
@@ -389,30 +300,33 @@ _obstack_memory_used (struct obstack *h)
}
return nbytes;
}
-
+
+# ifndef _OBSTACK_NO_ERROR_HANDLER
/* Define the error handler. */
-# ifdef _LIBC
-# include <libintl.h>
-# else
-# include "gettext.h"
-# endif
-# ifndef _
-# define _(msgid) gettext (msgid)
-# endif
+# include <stdio.h>
-# ifdef _LIBC
-# include <libio/iolibio.h>
-# endif
+/* Exit value used when 'print_and_abort' is used. */
+# ifdef _LIBC
+int obstack_exit_failure = EXIT_FAILURE;
+# else
+# include "exitfail.h"
+# define obstack_exit_failure exit_failure
+# endif
-# ifndef __attribute__
-/* This feature is available in gcc versions 2.5 and later. */
-# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 5)
-# define __attribute__(Spec) /* empty */
+# ifdef _LIBC
+# include <libintl.h>
+# else
+# include "gettext.h"
+# endif
+# ifndef _
+# define _(msgid) gettext (msgid)
# endif
-# endif
-static void
-__attribute__ ((noreturn))
+# ifdef _LIBC
+# include <libio/iolibio.h>
+# endif
+
+static _Noreturn void
print_and_abort (void)
{
/* Don't change any of these strings. Yes, it would be possible to add
@@ -420,12 +334,20 @@ print_and_abort (void)
happen because the "memory exhausted" message appears in other places
like this and the translation should be reused instead of creating
a very similar string which requires a separate translation. */
-# ifdef _LIBC
+# ifdef _LIBC
(void) __fxprintf (NULL, "%s\n", _("memory exhausted"));
-# else
+# else
fprintf (stderr, "%s\n", _("memory exhausted"));
-# endif
+# endif
exit (obstack_exit_failure);
}
-#endif /* !ELIDE_CODE */
+/* The functions allocating more room by calling 'obstack_chunk_alloc'
+ jump to the handler pointed to by 'obstack_alloc_failed_handler'.
+ This can be set to a user defined function which should either
+ abort gracefully or use longjump - but shouldn't return. This
+ variable by default points to the internal function
+ 'print_and_abort'. */
+void (*obstack_alloc_failed_handler) (void) = print_and_abort;
+# endif /* !_OBSTACK_NO_ERROR_HANDLER */
+#endif /* !_OBSTACK_ELIDE_CODE */
diff --git a/lib/obstack.h b/lib/obstack.h
index 3315dfe..e8ac8c2 100644
--- a/lib/obstack.h
+++ b/lib/obstack.h
@@ -1,103 +1,102 @@
/* obstack.h - object stack macros
- Copyright (C) 1988-1994,1996-1999,2003,2004,2005,2006
- Free Software Foundation, Inc.
+ Copyright (C) 1988-2016 Free Software Foundation, Inc.
This file is part of the GNU C Library.
- 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 2, or (at your option)
- any later version.
+ The GNU C Library 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,
+ The GNU C Library 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.
+ 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ You should have received a copy of the GNU General Public
+ License along with the GNU C Library; if not, see
+ <http://www.gnu.org/licenses/>. */
/* Summary:
-All the apparent functions defined here are macros. The idea
-is that you would use these pre-tested macros to solve a
-very specific set of problems, and they would run fast.
-Caution: no side-effects in arguments please!! They may be
-evaluated MANY times!!
-
-These macros operate a stack of objects. Each object starts life
-small, and may grow to maturity. (Consider building a word syllable
-by syllable.) An object can move while it is growing. Once it has
-been "finished" it never changes address again. So the "top of the
-stack" is typically an immature growing object, while the rest of the
-stack is of mature, fixed size and fixed address objects.
-
-These routines grab large chunks of memory, using a function you
-supply, called `obstack_chunk_alloc'. On occasion, they free chunks,
-by calling `obstack_chunk_free'. You must define them and declare
-them before using any obstack macros.
-
-Each independent stack is represented by a `struct obstack'.
-Each of the obstack macros expects a pointer to such a structure
-as the first argument.
-
-One motivation for this package is the problem of growing char strings
-in symbol tables. Unless you are "fascist pig with a read-only mind"
---Gosper's immortal quote from HAKMEM item 154, out of context--you
-would not like to put any arbitrary upper limit on the length of your
-symbols.
-
-In practice this often means you will build many short symbols and a
-few long symbols. At the time you are reading a symbol you don't know
-how long it is. One traditional method is to read a symbol into a
-buffer, realloc()ating the buffer every time you try to read a symbol
-that is longer than the buffer. This is beaut, but you still will
-want to copy the symbol from the buffer to a more permanent
-symbol-table entry say about half the time.
-
-With obstacks, you can work differently. Use one obstack for all symbol
-names. As you read a symbol, grow the name in the obstack gradually.
-When the name is complete, finalize it. Then, if the symbol exists already,
-free the newly read name.
-
-The way we do this is to take a large chunk, allocating memory from
-low addresses. When you want to build a symbol in the chunk you just
-add chars above the current "high water mark" in the chunk. When you
-have finished adding chars, because you got to the end of the symbol,
-you know how long the chars are, and you can create a new object.
-Mostly the chars will not burst over the highest address of the chunk,
-because you would typically expect a chunk to be (say) 100 times as
-long as an average object.
-
-In case that isn't clear, when we have enough chars to make up
-the object, THEY ARE ALREADY CONTIGUOUS IN THE CHUNK (guaranteed)
-so we just point to it where it lies. No moving of chars is
-needed and this is the second win: potentially long strings need
-never be explicitly shuffled. Once an object is formed, it does not
-change its address during its lifetime.
-
-When the chars burst over a chunk boundary, we allocate a larger
-chunk, and then copy the partly formed object from the end of the old
-chunk to the beginning of the new larger chunk. We then carry on
-accreting characters to the end of the object as we normally would.
-
-A special macro is provided to add a single char at a time to a
-growing object. This allows the use of register variables, which
-break the ordinary 'growth' macro.
-
-Summary:
- We allocate large chunks.
- We carve out one object at a time from the current chunk.
- Once carved, an object never moves.
- We are free to append data of any size to the currently
- growing object.
- Exactly one object is growing in an obstack at any one time.
- You can run one obstack per control block.
- You may have as many control blocks as you dare.
- Because of the way we do it, you can `unwind' an obstack
- back to a previous state. (You may remove objects much
- as you would with a stack.)
-*/
+ All the apparent functions defined here are macros. The idea
+ is that you would use these pre-tested macros to solve a
+ very specific set of problems, and they would run fast.
+ Caution: no side-effects in arguments please!! They may be
+ evaluated MANY times!!
+
+ These macros operate a stack of objects. Each object starts life
+ small, and may grow to maturity. (Consider building a word syllable
+ by syllable.) An object can move while it is growing. Once it has
+ been "finished" it never changes address again. So the "top of the
+ stack" is typically an immature growing object, while the rest of the
+ stack is of mature, fixed size and fixed address objects.
+
+ These routines grab large chunks of memory, using a function you
+ supply, called 'obstack_chunk_alloc'. On occasion, they free chunks,
+ by calling 'obstack_chunk_free'. You must define them and declare
+ them before using any obstack macros.
+
+ Each independent stack is represented by a 'struct obstack'.
+ Each of the obstack macros expects a pointer to such a structure
+ as the first argument.
+
+ One motivation for this package is the problem of growing char strings
+ in symbol tables. Unless you are "fascist pig with a read-only mind"
+ --Gosper's immortal quote from HAKMEM item 154, out of context--you
+ would not like to put any arbitrary upper limit on the length of your
+ symbols.
+
+ In practice this often means you will build many short symbols and a
+ few long symbols. At the time you are reading a symbol you don't know
+ how long it is. One traditional method is to read a symbol into a
+ buffer, realloc()ating the buffer every time you try to read a symbol
+ that is longer than the buffer. This is beaut, but you still will
+ want to copy the symbol from the buffer to a more permanent
+ symbol-table entry say about half the time.
+
+ With obstacks, you can work differently. Use one obstack for all symbol
+ names. As you read a symbol, grow the name in the obstack gradually.
+ When the name is complete, finalize it. Then, if the symbol exists already,
+ free the newly read name.
+
+ The way we do this is to take a large chunk, allocating memory from
+ low addresses. When you want to build a symbol in the chunk you just
+ add chars above the current "high water mark" in the chunk. When you
+ have finished adding chars, because you got to the end of the symbol,
+ you know how long the chars are, and you can create a new object.
+ Mostly the chars will not burst over the highest address of the chunk,
+ because you would typically expect a chunk to be (say) 100 times as
+ long as an average object.
+
+ In case that isn't clear, when we have enough chars to make up
+ the object, THEY ARE ALREADY CONTIGUOUS IN THE CHUNK (guaranteed)
+ so we just point to it where it lies. No moving of chars is
+ needed and this is the second win: potentially long strings need
+ never be explicitly shuffled. Once an object is formed, it does not
+ change its address during its lifetime.
+
+ When the chars burst over a chunk boundary, we allocate a larger
+ chunk, and then copy the partly formed object from the end of the old
+ chunk to the beginning of the new larger chunk. We then carry on
+ accreting characters to the end of the object as we normally would.
+
+ A special macro is provided to add a single char at a time to a
+ growing object. This allows the use of register variables, which
+ break the ordinary 'growth' macro.
+
+ Summary:
+ We allocate large chunks.
+ We carve out one object at a time from the current chunk.
+ Once carved, an object never moves.
+ We are free to append data of any size to the currently
+ growing object.
+ Exactly one object is growing in an obstack at any one time.
+ You can run one obstack per control block.
+ You may have as many control blocks as you dare.
+ Because of the way we do it, you can "unwind" an obstack
+ back to a previous state. (You may remove objects much
+ as you would with a stack.)
+ */
/* Don't do the contents of this file more than once. */
@@ -105,20 +104,24 @@ Summary:
#ifndef _OBSTACK_H
#define _OBSTACK_H 1
-#ifdef __cplusplus
-extern "C" {
+#ifndef _OBSTACK_INTERFACE_VERSION
+# define _OBSTACK_INTERFACE_VERSION 2
#endif
-
-/* We need the type of a pointer subtraction. If __PTRDIFF_TYPE__ is
- defined, as with GNU C, use that; that way we don't pollute the
- namespace with <stddef.h>'s symbols. Otherwise, include <stddef.h>
- and use ptrdiff_t. */
-
-#ifdef __PTRDIFF_TYPE__
-# define PTR_INT_TYPE __PTRDIFF_TYPE__
+
+#include <stddef.h> /* For size_t and ptrdiff_t. */
+#include <string.h> /* For __GNU_LIBRARY__, and memcpy. */
+
+#if _OBSTACK_INTERFACE_VERSION == 1
+/* For binary compatibility with obstack version 1, which used "int"
+ and "long" for these two types. */
+# define _OBSTACK_SIZE_T unsigned int
+# define _CHUNK_SIZE_T unsigned long
+# define _OBSTACK_CAST(type, expr) ((type) (expr))
#else
-# include <stddef.h>
-# define PTR_INT_TYPE ptrdiff_t
+/* Version 2 with sane types, especially for 64-bit hosts. */
+# define _OBSTACK_SIZE_T size_t
+# define _CHUNK_SIZE_T size_t
+# define _OBSTACK_CAST(type, expr) (expr)
#endif
/* If B is the base of an object addressed by P, return the result of
@@ -127,82 +130,93 @@ extern "C" {
#define __BPTR_ALIGN(B, P, A) ((B) + (((P) - (B) + (A)) & ~(A)))
-/* Similiar to _BPTR_ALIGN (B, P, A), except optimize the common case
+/* Similar to __BPTR_ALIGN (B, P, A), except optimize the common case
where pointers can be converted to integers, aligned as integers,
- and converted back again. If PTR_INT_TYPE is narrower than a
+ and converted back again. If ptrdiff_t is narrower than a
pointer (e.g., the AS/400), play it safe and compute the alignment
relative to B. Otherwise, use the faster strategy of computing the
alignment relative to 0. */
-#define __PTR_ALIGN(B, P, A) \
- __BPTR_ALIGN (sizeof (PTR_INT_TYPE) < sizeof (void *) ? (B) : (char *) 0, \
- P, A)
+#define __PTR_ALIGN(B, P, A) \
+ __BPTR_ALIGN (sizeof (ptrdiff_t) < sizeof (void *) ? (B) : (char *) 0, \
+ P, A)
-#include <string.h>
+#ifndef __attribute_pure__
+# define __attribute_pure__ _GL_ATTRIBUTE_PURE
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
-struct _obstack_chunk /* Lives at front of each chunk. */
+struct _obstack_chunk /* Lives at front of each chunk. */
{
- char *limit; /* 1 past end of this chunk */
- struct _obstack_chunk *prev; /* address of prior chunk or NULL */
- char contents[4]; /* objects begin here */
+ char *limit; /* 1 past end of this chunk */
+ struct _obstack_chunk *prev; /* address of prior chunk or NULL */
+ char contents[4]; /* objects begin here */
};
-struct obstack /* control current object in current chunk */
+struct obstack /* control current object in current chunk */
{
- long chunk_size; /* preferred size to allocate chunks in */
- struct _obstack_chunk *chunk; /* address of current struct obstack_chunk */
- char *object_base; /* address of object we are building */
- char *next_free; /* where to add next char to current object */
- char *chunk_limit; /* address of char after current chunk */
+ _CHUNK_SIZE_T chunk_size; /* preferred size to allocate chunks in */
+ struct _obstack_chunk *chunk; /* address of current struct obstack_chunk */
+ char *object_base; /* address of object we are building */
+ char *next_free; /* where to add next char to current object */
+ char *chunk_limit; /* address of char after current chunk */
union
{
- PTR_INT_TYPE tempint;
- void *tempptr;
- } temp; /* Temporary for some macros. */
- int alignment_mask; /* Mask of alignment for each object. */
- /* These prototypes vary based on `use_extra_arg', and we use
- casts to the prototypeless function type in all assignments,
- but having prototypes here quiets -Wstrict-prototypes. */
- struct _obstack_chunk *(*chunkfun) (void *, long);
- void (*freefun) (void *, struct _obstack_chunk *);
- void *extra_arg; /* first arg for chunk alloc/dealloc funcs */
- unsigned use_extra_arg:1; /* chunk alloc/dealloc funcs take extra arg */
- unsigned maybe_empty_object:1;/* There is a possibility that the current
- chunk contains a zero-length object. This
- prevents freeing the chunk if we allocate
- a bigger chunk to replace it. */
- unsigned alloc_failed:1; /* No longer used, as we now call the failed
- handler on error, but retained for binary
- compatibility. */
+ _OBSTACK_SIZE_T i;
+ void *p;
+ } temp; /* Temporary for some macros. */
+ _OBSTACK_SIZE_T alignment_mask; /* Mask of alignment for each object. */
+
+ /* These prototypes vary based on 'use_extra_arg'. */
+ union
+ {
+ void *(*plain) (size_t);
+ void *(*extra) (void *, size_t);
+ } chunkfun;
+ union
+ {
+ void (*plain) (void *);
+ void (*extra) (void *, void *);
+ } freefun;
+
+ void *extra_arg; /* first arg for chunk alloc/dealloc funcs */
+ unsigned use_extra_arg : 1; /* chunk alloc/dealloc funcs take extra arg */
+ unsigned maybe_empty_object : 1; /* There is a possibility that the current
+ chunk contains a zero-length object. This
+ prevents freeing the chunk if we allocate
+ a bigger chunk to replace it. */
+ unsigned alloc_failed : 1; /* No longer used, as we now call the failed
+ handler on error, but retained for binary
+ compatibility. */
};
/* Declare the external functions we use; they are in obstack.c. */
-extern void _obstack_newchunk (struct obstack *, int);
-extern int _obstack_begin (struct obstack *, int, int,
- void *(*) (long), void (*) (void *));
-extern int _obstack_begin_1 (struct obstack *, int, int,
- void *(*) (void *, long),
- void (*) (void *, void *), void *);
-extern int _obstack_memory_used (struct obstack *);
-
-/* The default name of the function for freeing a chunk is 'obstack_free',
- but gnulib users can override this by defining '__obstack_free'. */
-#ifndef __obstack_free
-# define __obstack_free obstack_free
-#endif
-extern void __obstack_free (struct obstack *obstack, void *block);
+extern void _obstack_newchunk (struct obstack *, _OBSTACK_SIZE_T);
+extern void _obstack_free (struct obstack *, void *);
+extern int _obstack_begin (struct obstack *,
+ _OBSTACK_SIZE_T, _OBSTACK_SIZE_T,
+ void *(*) (size_t), void (*) (void *));
+extern int _obstack_begin_1 (struct obstack *,
+ _OBSTACK_SIZE_T, _OBSTACK_SIZE_T,
+ void *(*) (void *, size_t),
+ void (*) (void *, void *), void *);
+extern _OBSTACK_SIZE_T _obstack_memory_used (struct obstack *)
+ __attribute_pure__;
+
-
-/* Error handler called when `obstack_chunk_alloc' failed to allocate
+/* Error handler called when 'obstack_chunk_alloc' failed to allocate
more memory. This can be set to a user defined function which
should either abort gracefully or use longjump - but shouldn't
return. The default action is to print a message and abort. */
extern void (*obstack_alloc_failed_handler) (void);
-/* Exit value used when `print_and_abort' is used. */
+/* Exit value used when 'print_and_abort' is used. */
extern int obstack_exit_failure;
-
+
/* Pointer to beginning of object being allocated or to be allocated next.
Note that this might not be the final address of the object
because a new chunk might be needed to hold the final size. */
@@ -215,210 +229,210 @@ extern int obstack_exit_failure;
/* Pointer to next byte not yet allocated in current chunk. */
-#define obstack_next_free(h) ((h)->next_free)
+#define obstack_next_free(h) ((void *) (h)->next_free)
/* Mask specifying low bits that should be clear in address of an object. */
#define obstack_alignment_mask(h) ((h)->alignment_mask)
/* To prevent prototype warnings provide complete argument list. */
-#define obstack_init(h) \
- _obstack_begin ((h), 0, 0, \
- (void *(*) (long)) obstack_chunk_alloc, \
- (void (*) (void *)) obstack_chunk_free)
+#define obstack_init(h) \
+ _obstack_begin ((h), 0, 0, \
+ _OBSTACK_CAST (void *(*) (size_t), obstack_chunk_alloc), \
+ _OBSTACK_CAST (void (*) (void *), obstack_chunk_free))
-#define obstack_begin(h, size) \
- _obstack_begin ((h), (size), 0, \
- (void *(*) (long)) obstack_chunk_alloc, \
- (void (*) (void *)) obstack_chunk_free)
+#define obstack_begin(h, size) \
+ _obstack_begin ((h), (size), 0, \
+ _OBSTACK_CAST (void *(*) (size_t), obstack_chunk_alloc), \
+ _OBSTACK_CAST (void (*) (void *), obstack_chunk_free))
-#define obstack_specify_allocation(h, size, alignment, chunkfun, freefun) \
- _obstack_begin ((h), (size), (alignment), \
- (void *(*) (long)) (chunkfun), \
- (void (*) (void *)) (freefun))
+#define obstack_specify_allocation(h, size, alignment, chunkfun, freefun) \
+ _obstack_begin ((h), (size), (alignment), \
+ _OBSTACK_CAST (void *(*) (size_t), chunkfun), \
+ _OBSTACK_CAST (void (*) (void *), freefun))
#define obstack_specify_allocation_with_arg(h, size, alignment, chunkfun, freefun, arg) \
- _obstack_begin_1 ((h), (size), (alignment), \
- (void *(*) (void *, long)) (chunkfun), \
- (void (*) (void *, void *)) (freefun), (arg))
+ _obstack_begin_1 ((h), (size), (alignment), \
+ _OBSTACK_CAST (void *(*) (void *, size_t), chunkfun), \
+ _OBSTACK_CAST (void (*) (void *, void *), freefun), arg)
-#define obstack_chunkfun(h, newchunkfun) \
- ((h) -> chunkfun = (struct _obstack_chunk *(*)(void *, long)) (newchunkfun))
+#define obstack_chunkfun(h, newchunkfun) \
+ ((void) ((h)->chunkfun.extra = (void *(*) (void *, size_t)) (newchunkfun)))
-#define obstack_freefun(h, newfreefun) \
- ((h) -> freefun = (void (*)(void *, struct _obstack_chunk *)) (newfreefun))
+#define obstack_freefun(h, newfreefun) \
+ ((void) ((h)->freefun.extra = (void *(*) (void *, void *)) (newfreefun)))
-#define obstack_1grow_fast(h,achar) (*((h)->next_free)++ = (achar))
+#define obstack_1grow_fast(h, achar) ((void) (*((h)->next_free)++ = (achar)))
-#define obstack_blank_fast(h,n) ((h)->next_free += (n))
+#define obstack_blank_fast(h, n) ((void) ((h)->next_free += (n)))
#define obstack_memory_used(h) _obstack_memory_used (h)
-
-#if defined __GNUC__ && defined __STDC__ && __STDC__
-/* NextStep 2.0 cc is really gcc 1.93 but it defines __GNUC__ = 2 and
- does not implement __extension__. But that compiler doesn't define
- __GNUC_MINOR__. */
-# if __GNUC__ < 2 || (__NeXT__ && !__GNUC_MINOR__)
+
+#if defined __GNUC__
+# if !defined __GNUC_MINOR__ || __GNUC__ * 1000 + __GNUC_MINOR__ < 2008
# define __extension__
# endif
/* For GNU C, if not -traditional,
we can define these macros to compute all args only once
without using a global variable.
- Also, we can avoid using the `temp' slot, to make faster code. */
-
-# define obstack_object_size(OBSTACK) \
- __extension__ \
- ({ struct obstack const *__o = (OBSTACK); \
- (unsigned) (__o->next_free - __o->object_base); })
-
-# define obstack_room(OBSTACK) \
- __extension__ \
- ({ struct obstack const *__o = (OBSTACK); \
- (unsigned) (__o->chunk_limit - __o->next_free); })
-
-# define obstack_make_room(OBSTACK,length) \
-__extension__ \
-({ struct obstack *__o = (OBSTACK); \
- int __len = (length); \
- if (__o->chunk_limit - __o->next_free < __len) \
- _obstack_newchunk (__o, __len); \
- (void) 0; })
-
-# define obstack_empty_p(OBSTACK) \
- __extension__ \
- ({ struct obstack const *__o = (OBSTACK); \
- (__o->chunk->prev == 0 \
- && __o->next_free == __PTR_ALIGN ((char *) __o->chunk, \
- __o->chunk->contents, \
- __o->alignment_mask)); })
-
-# define obstack_grow(OBSTACK,where,length) \
-__extension__ \
-({ struct obstack *__o = (OBSTACK); \
- int __len = (length); \
- if (__o->next_free + __len > __o->chunk_limit) \
- _obstack_newchunk (__o, __len); \
- memcpy (__o->next_free, where, __len); \
- __o->next_free += __len; \
- (void) 0; })
-
-# define obstack_grow0(OBSTACK,where,length) \
-__extension__ \
-({ struct obstack *__o = (OBSTACK); \
- int __len = (length); \
- if (__o->next_free + __len + 1 > __o->chunk_limit) \
- _obstack_newchunk (__o, __len + 1); \
- memcpy (__o->next_free, where, __len); \
- __o->next_free += __len; \
- *(__o->next_free)++ = 0; \
- (void) 0; })
-
-# define obstack_1grow(OBSTACK,datum) \
-__extension__ \
-({ struct obstack *__o = (OBSTACK); \
- if (__o->next_free + 1 > __o->chunk_limit) \
- _obstack_newchunk (__o, 1); \
- obstack_1grow_fast (__o, datum); \
- (void) 0; })
+ Also, we can avoid using the 'temp' slot, to make faster code. */
+
+# define obstack_object_size(OBSTACK) \
+ __extension__ \
+ ({ struct obstack const *__o = (OBSTACK); \
+ (_OBSTACK_SIZE_T) (__o->next_free - __o->object_base); })
+
+/* The local variable is named __o1 to avoid a shadowed variable
+ warning when invoked from other obstack macros. */
+# define obstack_room(OBSTACK) \
+ __extension__ \
+ ({ struct obstack const *__o1 = (OBSTACK); \
+ (_OBSTACK_SIZE_T) (__o1->chunk_limit - __o1->next_free); })
+
+# define obstack_make_room(OBSTACK, length) \
+ __extension__ \
+ ({ struct obstack *__o = (OBSTACK); \
+ _OBSTACK_SIZE_T __len = (length); \
+ if (obstack_room (__o) < __len) \
+ _obstack_newchunk (__o, __len); \
+ (void) 0; })
+
+# define obstack_empty_p(OBSTACK) \
+ __extension__ \
+ ({ struct obstack const *__o = (OBSTACK); \
+ (__o->chunk->prev == 0 \
+ && __o->next_free == __PTR_ALIGN ((char *) __o->chunk, \
+ __o->chunk->contents, \
+ __o->alignment_mask)); })
+
+# define obstack_grow(OBSTACK, where, length) \
+ __extension__ \
+ ({ struct obstack *__o = (OBSTACK); \
+ _OBSTACK_SIZE_T __len = (length); \
+ if (obstack_room (__o) < __len) \
+ _obstack_newchunk (__o, __len); \
+ memcpy (__o->next_free, where, __len); \
+ __o->next_free += __len; \
+ (void) 0; })
+
+# define obstack_grow0(OBSTACK, where, length) \
+ __extension__ \
+ ({ struct obstack *__o = (OBSTACK); \
+ _OBSTACK_SIZE_T __len = (length); \
+ if (obstack_room (__o) < __len + 1) \
+ _obstack_newchunk (__o, __len + 1); \
+ memcpy (__o->next_free, where, __len); \
+ __o->next_free += __len; \
+ *(__o->next_free)++ = 0; \
+ (void) 0; })
+
+# define obstack_1grow(OBSTACK, datum) \
+ __extension__ \
+ ({ struct obstack *__o = (OBSTACK); \
+ if (obstack_room (__o) < 1) \
+ _obstack_newchunk (__o, 1); \
+ obstack_1grow_fast (__o, datum); })
/* These assume that the obstack alignment is good enough for pointers
or ints, and that the data added so far to the current object
shares that much alignment. */
-# define obstack_ptr_grow(OBSTACK,datum) \
-__extension__ \
-({ struct obstack *__o = (OBSTACK); \
- if (__o->next_free + sizeof (void *) > __o->chunk_limit) \
- _obstack_newchunk (__o, sizeof (void *)); \
- obstack_ptr_grow_fast (__o, datum); }) \
-
-# define obstack_int_grow(OBSTACK,datum) \
-__extension__ \
-({ struct obstack *__o = (OBSTACK); \
- if (__o->next_free + sizeof (int) > __o->chunk_limit) \
- _obstack_newchunk (__o, sizeof (int)); \
- obstack_int_grow_fast (__o, datum); })
-
-# define obstack_ptr_grow_fast(OBSTACK,aptr) \
-__extension__ \
-({ struct obstack *__o1 = (OBSTACK); \
- *(const void **) __o1->next_free = (aptr); \
- __o1->next_free += sizeof (const void *); \
- (void) 0; })
-
-# define obstack_int_grow_fast(OBSTACK,aint) \
-__extension__ \
-({ struct obstack *__o1 = (OBSTACK); \
- *(int *) __o1->next_free = (aint); \
- __o1->next_free += sizeof (int); \
- (void) 0; })
-
-# define obstack_blank(OBSTACK,length) \
-__extension__ \
-({ struct obstack *__o = (OBSTACK); \
- int __len = (length); \
- if (__o->chunk_limit - __o->next_free < __len) \
- _obstack_newchunk (__o, __len); \
- obstack_blank_fast (__o, __len); \
- (void) 0; })
-
-# define obstack_alloc(OBSTACK,length) \
-__extension__ \
-({ struct obstack *__h = (OBSTACK); \
- obstack_blank (__h, (length)); \
- obstack_finish (__h); })
-
-# define obstack_copy(OBSTACK,where,length) \
-__extension__ \
-({ struct obstack *__h = (OBSTACK); \
- obstack_grow (__h, (where), (length)); \
- obstack_finish (__h); })
-
-# define obstack_copy0(OBSTACK,where,length) \
-__extension__ \
-({ struct obstack *__h = (OBSTACK); \
- obstack_grow0 (__h, (where), (length)); \
- obstack_finish (__h); })
-
-/* The local variable is named __o1 to avoid a name conflict
- when obstack_blank is called. */
-# define obstack_finish(OBSTACK) \
-__extension__ \
-({ struct obstack *__o1 = (OBSTACK); \
- void *__value = (void *) __o1->object_base; \
- if (__o1->next_free == __value) \
- __o1->maybe_empty_object = 1; \
- __o1->next_free \
- = __PTR_ALIGN (__o1->object_base, __o1->next_free, \
- __o1->alignment_mask); \
- if (__o1->next_free - (char *)__o1->chunk \
- > __o1->chunk_limit - (char *)__o1->chunk) \
- __o1->next_free = __o1->chunk_limit; \
- __o1->object_base = __o1->next_free; \
- __value; })
-
-# define obstack_free(OBSTACK, OBJ) \
-__extension__ \
-({ struct obstack *__o = (OBSTACK); \
- void *__obj = (OBJ); \
- if (__obj > (void *)__o->chunk && __obj < (void *)__o->chunk_limit) \
- __o->next_free = __o->object_base = (char *)__obj; \
- else (__obstack_free) (__o, __obj); })
-
-#else /* not __GNUC__ or not __STDC__ */
-
-# define obstack_object_size(h) \
- (unsigned) ((h)->next_free - (h)->object_base)
-
-# define obstack_room(h) \
- (unsigned) ((h)->chunk_limit - (h)->next_free)
-
-# define obstack_empty_p(h) \
- ((h)->chunk->prev == 0 \
- && (h)->next_free == __PTR_ALIGN ((char *) (h)->chunk, \
- (h)->chunk->contents, \
- (h)->alignment_mask))
+# define obstack_ptr_grow(OBSTACK, datum) \
+ __extension__ \
+ ({ struct obstack *__o = (OBSTACK); \
+ if (obstack_room (__o) < sizeof (void *)) \
+ _obstack_newchunk (__o, sizeof (void *)); \
+ obstack_ptr_grow_fast (__o, datum); })
+
+# define obstack_int_grow(OBSTACK, datum) \
+ __extension__ \
+ ({ struct obstack *__o = (OBSTACK); \
+ if (obstack_room (__o) < sizeof (int)) \
+ _obstack_newchunk (__o, sizeof (int)); \
+ obstack_int_grow_fast (__o, datum); })
+
+# define obstack_ptr_grow_fast(OBSTACK, aptr) \
+ __extension__ \
+ ({ struct obstack *__o1 = (OBSTACK); \
+ void *__p1 = __o1->next_free; \
+ *(const void **) __p1 = (aptr); \
+ __o1->next_free += sizeof (const void *); \
+ (void) 0; })
+
+# define obstack_int_grow_fast(OBSTACK, aint) \
+ __extension__ \
+ ({ struct obstack *__o1 = (OBSTACK); \
+ void *__p1 = __o1->next_free; \
+ *(int *) __p1 = (aint); \
+ __o1->next_free += sizeof (int); \
+ (void) 0; })
+
+# define obstack_blank(OBSTACK, length) \
+ __extension__ \
+ ({ struct obstack *__o = (OBSTACK); \
+ _OBSTACK_SIZE_T __len = (length); \
+ if (obstack_room (__o) < __len) \
+ _obstack_newchunk (__o, __len); \
+ obstack_blank_fast (__o, __len); })
+
+# define obstack_alloc(OBSTACK, length) \
+ __extension__ \
+ ({ struct obstack *__h = (OBSTACK); \
+ obstack_blank (__h, (length)); \
+ obstack_finish (__h); })
+
+# define obstack_copy(OBSTACK, where, length) \
+ __extension__ \
+ ({ struct obstack *__h = (OBSTACK); \
+ obstack_grow (__h, (where), (length)); \
+ obstack_finish (__h); })
+
+# define obstack_copy0(OBSTACK, where, length) \
+ __extension__ \
+ ({ struct obstack *__h = (OBSTACK); \
+ obstack_grow0 (__h, (where), (length)); \
+ obstack_finish (__h); })
+
+/* The local variable is named __o1 to avoid a shadowed variable
+ warning when invoked from other obstack macros, typically obstack_free. */
+# define obstack_finish(OBSTACK) \
+ __extension__ \
+ ({ struct obstack *__o1 = (OBSTACK); \
+ void *__value = (void *) __o1->object_base; \
+ if (__o1->next_free == __value) \
+ __o1->maybe_empty_object = 1; \
+ __o1->next_free \
+ = __PTR_ALIGN (__o1->object_base, __o1->next_free, \
+ __o1->alignment_mask); \
+ if ((size_t) (__o1->next_free - (char *) __o1->chunk) \
+ > (size_t) (__o1->chunk_limit - (char *) __o1->chunk)) \
+ __o1->next_free = __o1->chunk_limit; \
+ __o1->object_base = __o1->next_free; \
+ __value; })
+
+# define obstack_free(OBSTACK, OBJ) \
+ __extension__ \
+ ({ struct obstack *__o = (OBSTACK); \
+ void *__obj = (void *) (OBJ); \
+ if (__obj > (void *) __o->chunk && __obj < (void *) __o->chunk_limit) \
+ __o->next_free = __o->object_base = (char *) __obj; \
+ else \
+ _obstack_free (__o, __obj); })
+
+#else /* not __GNUC__ */
+
+# define obstack_object_size(h) \
+ ((_OBSTACK_SIZE_T) ((h)->next_free - (h)->object_base))
+
+# define obstack_room(h) \
+ ((_OBSTACK_SIZE_T) ((h)->chunk_limit - (h)->next_free))
+
+# define obstack_empty_p(h) \
+ ((h)->chunk->prev == 0 \
+ && (h)->next_free == __PTR_ALIGN ((char *) (h)->chunk, \
+ (h)->chunk->contents, \
+ (h)->alignment_mask))
/* Note that the call to _obstack_newchunk is enclosed in (..., 0)
so that we can avoid having void expressions
@@ -426,88 +440,92 @@ __extension__ \
Casting the third operand to void was tried before,
but some compilers won't accept it. */
-# define obstack_make_room(h,length) \
-( (h)->temp.tempint = (length), \
- (((h)->next_free + (h)->temp.tempint > (h)->chunk_limit) \
- ? (_obstack_newchunk ((h), (h)->temp.tempint), 0) : 0))
-
-# define obstack_grow(h,where,length) \
-( (h)->temp.tempint = (length), \
- (((h)->next_free + (h)->temp.tempint > (h)->chunk_limit) \
- ? (_obstack_newchunk ((h), (h)->temp.tempint), 0) : 0), \
- memcpy ((h)->next_free, where, (h)->temp.tempint), \
- (h)->next_free += (h)->temp.tempint)
-
-# define obstack_grow0(h,where,length) \
-( (h)->temp.tempint = (length), \
- (((h)->next_free + (h)->temp.tempint + 1 > (h)->chunk_limit) \
- ? (_obstack_newchunk ((h), (h)->temp.tempint + 1), 0) : 0), \
- memcpy ((h)->next_free, where, (h)->temp.tempint), \
- (h)->next_free += (h)->temp.tempint, \
- *((h)->next_free)++ = 0)
-
-# define obstack_1grow(h,datum) \
-( (((h)->next_free + 1 > (h)->chunk_limit) \
- ? (_obstack_newchunk ((h), 1), 0) : 0), \
- obstack_1grow_fast (h, datum))
-
-# define obstack_ptr_grow(h,datum) \
-( (((h)->next_free + sizeof (char *) > (h)->chunk_limit) \
- ? (_obstack_newchunk ((h), sizeof (char *)), 0) : 0), \
- obstack_ptr_grow_fast (h, datum))
-
-# define obstack_int_grow(h,datum) \
-( (((h)->next_free + sizeof (int) > (h)->chunk_limit) \
- ? (_obstack_newchunk ((h), sizeof (int)), 0) : 0), \
- obstack_int_grow_fast (h, datum))
-
-# define obstack_ptr_grow_fast(h,aptr) \
- (((const void **) ((h)->next_free += sizeof (void *)))[-1] = (aptr))
-
-# define obstack_int_grow_fast(h,aint) \
- (((int *) ((h)->next_free += sizeof (int)))[-1] = (aint))
-
-# define obstack_blank(h,length) \
-( (h)->temp.tempint = (length), \
- (((h)->chunk_limit - (h)->next_free < (h)->temp.tempint) \
- ? (_obstack_newchunk ((h), (h)->temp.tempint), 0) : 0), \
- obstack_blank_fast (h, (h)->temp.tempint))
-
-# define obstack_alloc(h,length) \
- (obstack_blank ((h), (length)), obstack_finish ((h)))
-
-# define obstack_copy(h,where,length) \
- (obstack_grow ((h), (where), (length)), obstack_finish ((h)))
-
-# define obstack_copy0(h,where,length) \
- (obstack_grow0 ((h), (where), (length)), obstack_finish ((h)))
-
-# define obstack_finish(h) \
-( ((h)->next_free == (h)->object_base \
- ? (((h)->maybe_empty_object = 1), 0) \
- : 0), \
- (h)->temp.tempptr = (h)->object_base, \
- (h)->next_free \
- = __PTR_ALIGN ((h)->object_base, (h)->next_free, \
- (h)->alignment_mask), \
- (((h)->next_free - (char *) (h)->chunk \
- > (h)->chunk_limit - (char *) (h)->chunk) \
- ? ((h)->next_free = (h)->chunk_limit) : 0), \
- (h)->object_base = (h)->next_free, \
- (h)->temp.tempptr)
-
-# define obstack_free(h,obj) \
-( (h)->temp.tempint = (char *) (obj) - (char *) (h)->chunk, \
- ((((h)->temp.tempint > 0 \
- && (h)->temp.tempint < (h)->chunk_limit - (char *) (h)->chunk)) \
- ? (int) ((h)->next_free = (h)->object_base \
- = (h)->temp.tempint + (char *) (h)->chunk) \
- : (((__obstack_free) ((h), (h)->temp.tempint + (char *) (h)->chunk), 0), 0)))
-
-#endif /* not __GNUC__ or not __STDC__ */
+# define obstack_make_room(h, length) \
+ ((h)->temp.i = (length), \
+ ((obstack_room (h) < (h)->temp.i) \
+ ? (_obstack_newchunk (h, (h)->temp.i), 0) : 0), \
+ (void) 0)
+
+# define obstack_grow(h, where, length) \
+ ((h)->temp.i = (length), \
+ ((obstack_room (h) < (h)->temp.i) \
+ ? (_obstack_newchunk ((h), (h)->temp.i), 0) : 0), \
+ memcpy ((h)->next_free, where, (h)->temp.i), \
+ (h)->next_free += (h)->temp.i, \
+ (void) 0)
+
+# define obstack_grow0(h, where, length) \
+ ((h)->temp.i = (length), \
+ ((obstack_room (h) < (h)->temp.i + 1) \
+ ? (_obstack_newchunk ((h), (h)->temp.i + 1), 0) : 0), \
+ memcpy ((h)->next_free, where, (h)->temp.i), \
+ (h)->next_free += (h)->temp.i, \
+ *((h)->next_free)++ = 0, \
+ (void) 0)
+
+# define obstack_1grow(h, datum) \
+ (((obstack_room (h) < 1) \
+ ? (_obstack_newchunk ((h), 1), 0) : 0), \
+ obstack_1grow_fast (h, datum))
+
+# define obstack_ptr_grow(h, datum) \
+ (((obstack_room (h) < sizeof (char *)) \
+ ? (_obstack_newchunk ((h), sizeof (char *)), 0) : 0), \
+ obstack_ptr_grow_fast (h, datum))
+
+# define obstack_int_grow(h, datum) \
+ (((obstack_room (h) < sizeof (int)) \
+ ? (_obstack_newchunk ((h), sizeof (int)), 0) : 0), \
+ obstack_int_grow_fast (h, datum))
+
+# define obstack_ptr_grow_fast(h, aptr) \
+ (((const void **) ((h)->next_free += sizeof (void *)))[-1] = (aptr), \
+ (void) 0)
+
+# define obstack_int_grow_fast(h, aint) \
+ (((int *) ((h)->next_free += sizeof (int)))[-1] = (aint), \
+ (void) 0)
+
+# define obstack_blank(h, length) \
+ ((h)->temp.i = (length), \
+ ((obstack_room (h) < (h)->temp.i) \
+ ? (_obstack_newchunk ((h), (h)->temp.i), 0) : 0), \
+ obstack_blank_fast (h, (h)->temp.i))
+
+# define obstack_alloc(h, length) \
+ (obstack_blank ((h), (length)), obstack_finish ((h)))
+
+# define obstack_copy(h, where, length) \
+ (obstack_grow ((h), (where), (length)), obstack_finish ((h)))
+
+# define obstack_copy0(h, where, length) \
+ (obstack_grow0 ((h), (where), (length)), obstack_finish ((h)))
+
+# define obstack_finish(h) \
+ (((h)->next_free == (h)->object_base \
+ ? (((h)->maybe_empty_object = 1), 0) \
+ : 0), \
+ (h)->temp.p = (h)->object_base, \
+ (h)->next_free \
+ = __PTR_ALIGN ((h)->object_base, (h)->next_free, \
+ (h)->alignment_mask), \
+ (((size_t) ((h)->next_free - (char *) (h)->chunk) \
+ > (size_t) ((h)->chunk_limit - (char *) (h)->chunk)) \
+ ? ((h)->next_free = (h)->chunk_limit) : 0), \
+ (h)->object_base = (h)->next_free, \
+ (h)->temp.p)
+
+# define obstack_free(h, obj) \
+ ((h)->temp.p = (void *) (obj), \
+ (((h)->temp.p > (void *) (h)->chunk \
+ && (h)->temp.p < (void *) (h)->chunk_limit) \
+ ? (void) ((h)->next_free = (h)->object_base = (char *) (h)->temp.p) \
+ : _obstack_free ((h), (h)->temp.p)))
+
+#endif /* not __GNUC__ */
#ifdef __cplusplus
-} /* C++ */
+} /* C++ */
#endif
-#endif /* obstack.h */
+#endif /* _OBSTACK_H */
diff --git a/lib/offtostr.c b/lib/offtostr.c
index 45196e2..96082aa 100644
--- a/lib/offtostr.c
+++ b/lib/offtostr.c
@@ -1,3 +1,3 @@
-#define inttostr offtostr
+#define anytostr offtostr
#define inttype off_t
-#include "inttostr.c"
+#include "anytostr.c"
diff --git a/lib/open-safer.c b/lib/open-safer.c
index 04a72eb..2d49b05 100644
--- a/lib/open-safer.c
+++ b/lib/open-safer.c
@@ -1,11 +1,11 @@
/* Invoke open, but avoid some glitches.
- Copyright (C) 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2005-2006, 2008-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
@@ -36,12 +35,9 @@ open_safer (char const *file, int flags, ...)
va_list ap;
va_start (ap, flags);
- /* Assume mode_t promotes to int if and only if it is smaller.
- This assumption isn't guaranteed by the C standard, but we
- don't know of any real-world counterexamples. */
- mode = (sizeof (mode_t) < sizeof (int)
- ? va_arg (ap, int)
- : va_arg (ap, mode_t));
+ /* We have to use PROMOTED_MODE_T instead of mode_t, otherwise GCC 4
+ creates crashing code when 'mode_t' is smaller than 'int'. */
+ mode = va_arg (ap, PROMOTED_MODE_T);
va_end (ap);
}
diff --git a/lib/open.c b/lib/open.c
new file mode 100644
index 0000000..e9c3120
--- /dev/null
+++ b/lib/open.c
@@ -0,0 +1,181 @@
+/* Open a descriptor to a file.
+ Copyright (C) 2007-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Bruno Haible <bruno@clisp.org>, 2007. */
+
+/* If the user's config.h happens to include <fcntl.h>, let it include only
+ the system's <fcntl.h> here, so that orig_open doesn't recurse to
+ rpl_open. */
+#define __need_system_fcntl_h
+#include <config.h>
+
+/* Get the original definition of open. It might be defined as a macro. */
+#include <fcntl.h>
+#include <sys/types.h>
+#undef __need_system_fcntl_h
+
+static int
+orig_open (const char *filename, int flags, mode_t mode)
+{
+ return open (filename, flags, mode);
+}
+
+/* Specification. */
+/* Write "fcntl.h" here, not <fcntl.h>, otherwise OSF/1 5.1 DTK cc eliminates
+ this include because of the preliminary #include <fcntl.h> above. */
+#include "fcntl.h"
+
+#include <errno.h>
+#include <stdarg.h>
+#include <string.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#ifndef REPLACE_OPEN_DIRECTORY
+# define REPLACE_OPEN_DIRECTORY 0
+#endif
+
+int
+open (const char *filename, int flags, ...)
+{
+ mode_t mode;
+ int fd;
+
+ mode = 0;
+ if (flags & O_CREAT)
+ {
+ va_list arg;
+ va_start (arg, flags);
+
+ /* We have to use PROMOTED_MODE_T instead of mode_t, otherwise GCC 4
+ creates crashing code when 'mode_t' is smaller than 'int'. */
+ mode = va_arg (arg, PROMOTED_MODE_T);
+
+ va_end (arg);
+ }
+
+#if GNULIB_defined_O_NONBLOCK
+ /* The only known platform that lacks O_NONBLOCK is mingw, but it
+ also lacks named pipes and Unix sockets, which are the only two
+ file types that require non-blocking handling in open().
+ Therefore, it is safe to ignore O_NONBLOCK here. It is handy
+ that mingw also lacks openat(), so that is also covered here. */
+ flags &= ~O_NONBLOCK;
+#endif
+
+#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+ if (strcmp (filename, "/dev/null") == 0)
+ filename = "NUL";
+#endif
+
+#if OPEN_TRAILING_SLASH_BUG
+ /* If the filename ends in a slash and one of O_CREAT, O_WRONLY, O_RDWR
+ is specified, then fail.
+ Rationale: POSIX <http://www.opengroup.org/susv3/basedefs/xbd_chap04.html>
+ says that
+ "A pathname that contains at least one non-slash character and that
+ ends with one or more trailing slashes shall be resolved as if a
+ single dot character ( '.' ) were appended to the pathname."
+ and
+ "The special filename dot shall refer to the directory specified by
+ its predecessor."
+ If the named file already exists as a directory, then
+ - if O_CREAT is specified, open() must fail because of the semantics
+ of O_CREAT,
+ - if O_WRONLY or O_RDWR is specified, open() must fail because POSIX
+ <http://www.opengroup.org/susv3/functions/open.html> says that it
+ fails with errno = EISDIR in this case.
+ If the named file does not exist or does not name a directory, then
+ - if O_CREAT is specified, open() must fail since open() cannot create
+ directories,
+ - if O_WRONLY or O_RDWR is specified, open() must fail because the
+ file does not contain a '.' directory. */
+ if (flags & (O_CREAT | O_WRONLY | O_RDWR))
+ {
+ size_t len = strlen (filename);
+ if (len > 0 && filename[len - 1] == '/')
+ {
+ errno = EISDIR;
+ return -1;
+ }
+ }
+#endif
+
+ fd = orig_open (filename, flags, mode);
+
+#if REPLACE_FCHDIR
+ /* Implementing fchdir and fdopendir requires the ability to open a
+ directory file descriptor. If open doesn't support that (as on
+ mingw), we use a dummy file that behaves the same as directories
+ on Linux (ie. always reports EOF on attempts to read()), and
+ override fstat() in fchdir.c to hide the fact that we have a
+ dummy. */
+ if (REPLACE_OPEN_DIRECTORY && fd < 0 && errno == EACCES
+ && ((flags & O_ACCMODE) == O_RDONLY
+ || (O_SEARCH != O_RDONLY && (flags & O_ACCMODE) == O_SEARCH)))
+ {
+ struct stat statbuf;
+ if (stat (filename, &statbuf) == 0 && S_ISDIR (statbuf.st_mode))
+ {
+ /* Maximum recursion depth of 1. */
+ fd = open ("/dev/null", flags, mode);
+ if (0 <= fd)
+ fd = _gl_register_fd (fd, filename);
+ }
+ else
+ errno = EACCES;
+ }
+#endif
+
+#if OPEN_TRAILING_SLASH_BUG
+ /* If the filename ends in a slash and fd does not refer to a directory,
+ then fail.
+ Rationale: POSIX <http://www.opengroup.org/susv3/basedefs/xbd_chap04.html>
+ says that
+ "A pathname that contains at least one non-slash character and that
+ ends with one or more trailing slashes shall be resolved as if a
+ single dot character ( '.' ) were appended to the pathname."
+ and
+ "The special filename dot shall refer to the directory specified by
+ its predecessor."
+ If the named file without the slash is not a directory, open() must fail
+ with ENOTDIR. */
+ if (fd >= 0)
+ {
+ /* We know len is positive, since open did not fail with ENOENT. */
+ size_t len = strlen (filename);
+ if (filename[len - 1] == '/')
+ {
+ struct stat statbuf;
+
+ if (fstat (fd, &statbuf) >= 0 && !S_ISDIR (statbuf.st_mode))
+ {
+ close (fd);
+ errno = ENOTDIR;
+ return -1;
+ }
+ }
+ }
+#endif
+
+#if REPLACE_FCHDIR
+ if (!REPLACE_OPEN_DIRECTORY && 0 <= fd)
+ fd = _gl_register_fd (fd, filename);
+#endif
+
+ return fd;
+}
diff --git a/lib/openat-die.c b/lib/openat-die.c
index 7a28570..7ab3860 100644
--- a/lib/openat-die.c
+++ b/lib/openat-die.c
@@ -1,11 +1,11 @@
/* Report a save- or restore-cwd failure in our openat replacement and then exit.
- Copyright (C) 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2005-2006, 2008-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,38 +13,49 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
+#include "openat.h"
+
#include <stdlib.h>
-#include "error.h"
+#ifndef GNULIB_LIBPOSIX
+# include "error.h"
+#endif
+
#include "exitfail.h"
#include "gettext.h"
#define _(msgid) gettext (msgid)
-#define N_(msgid) msgid
-void
-openat_save_fail (int errno)
+_Noreturn void
+openat_save_fail (int errnum)
{
- error (exit_failure, errno,
- _("unable to record current working directory"));
-
- /* The `noreturn' attribute cannot be applied to error, since it returns
+#ifndef GNULIB_LIBPOSIX
+ error (exit_failure, errnum,
+ _("unable to record current working directory"));
+#endif
+ /* _Noreturn cannot be applied to error, since it returns
when its first argument is 0. To help compilers understand that this
function does not return, call abort. Also, the abort is a
safety feature if exit_failure is 0 (which shouldn't happen). */
abort ();
}
-void
-openat_restore_fail (int errno)
+
+/* Exit with an error about failure to restore the working directory
+ during an openat emulation. The caller must ensure that fd 2 is
+ not a just-opened fd, even when openat_safer is not in use. */
+
+_Noreturn void
+openat_restore_fail (int errnum)
{
- error (exit_failure, errno,
- _("failed to return to initial working directory"));
+#ifndef GNULIB_LIBPOSIX
+ error (exit_failure, errnum,
+ _("failed to return to initial working directory"));
+#endif
/* As above. */
abort ();
diff --git a/lib/openat-priv.h b/lib/openat-priv.h
index 2d98821..ed763db 100644
--- a/lib/openat-priv.h
+++ b/lib/openat-priv.h
@@ -1,11 +1,11 @@
/* Internals for openat-like functions.
- Copyright (C) 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2005-2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,43 +13,52 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* written by Jim Meyering */
+#ifndef _GL_HEADER_OPENAT_PRIV
+#define _GL_HEADER_OPENAT_PRIV
+
#include <errno.h>
+#include <limits.h>
#include <stdlib.h>
-#define OPENAT_BUFFER_SIZE 512
-char *openat_proc_name (char buf[OPENAT_BUFFER_SIZE], int fd, char const *file);
+/* Maximum number of bytes that it is safe to allocate as a single
+ array on the stack, and that is known as a compile-time constant.
+ The assumption is that we'll touch the array very quickly, or a
+ temporary very near the array, provoking an out-of-memory trap. On
+ some operating systems, there is only one guard page for the stack,
+ and a page size can be as small as 4096 bytes. Subtract 64 in the
+ hope that this will let the compiler touch a nearby temporary and
+ provoke a trap. */
+#define SAFER_ALLOCA_MAX (4096 - 64)
-/* Some systems don't have ENOSYS. */
-#ifndef ENOSYS
-# ifdef ENOTSUP
-# define ENOSYS ENOTSUP
-# else
-/* Some systems don't have ENOTSUP either. */
-# define ENOSYS EINVAL
-# endif
-#endif
+#define SAFER_ALLOCA(m) ((m) < SAFER_ALLOCA_MAX ? (m) : SAFER_ALLOCA_MAX)
-/* Some systems don't have EOPNOTSUPP. */
-#ifndef EOPNOTSUPP
-# ifdef ENOTSUP
-# define EOPNOTSUPP ENOTSUP
-# else
-/* Some systems don't have ENOTSUP either. */
-# define EOPNOTSUPP EINVAL
-# endif
+#if defined PATH_MAX
+# define OPENAT_BUFFER_SIZE SAFER_ALLOCA (PATH_MAX)
+#elif defined _XOPEN_PATH_MAX
+# define OPENAT_BUFFER_SIZE SAFER_ALLOCA (_XOPEN_PATH_MAX)
+#else
+# define OPENAT_BUFFER_SIZE SAFER_ALLOCA (1024)
#endif
+char *openat_proc_name (char buf[OPENAT_BUFFER_SIZE], int fd, char const *file);
+
/* Trying to access a BUILD_PROC_NAME file will fail on systems without
/proc support, and even on systems *with* ProcFS support. Return
nonzero if the failure may be legitimate, e.g., because /proc is not
readable, or the particular .../fd/N directory is not present. */
-#define EXPECTED_ERRNO(Errno) \
- ((Errno) == ENOTDIR || (Errno) == ENOENT \
- || (Errno) == EPERM || (Errno) == EACCES \
- || (Errno) == ENOSYS /* Solaris 8 */ \
+#define EXPECTED_ERRNO(Errno) \
+ ((Errno) == ENOTDIR || (Errno) == ENOENT \
+ || (Errno) == EPERM || (Errno) == EACCES \
+ || (Errno) == ENOSYS /* Solaris 8 */ \
|| (Errno) == EOPNOTSUPP /* FreeBSD */)
+
+/* Wrapper function shared among linkat and renameat. */
+int at_func2 (int fd1, char const *file1,
+ int fd2, char const *file2,
+ int (*func) (char const *file1, char const *file2));
+
+#endif /* _GL_HEADER_OPENAT_PRIV */
diff --git a/lib/openat-proc.c b/lib/openat-proc.c
index ff2fff0..6fba6c2 100644
--- a/lib/openat-proc.c
+++ b/lib/openat-proc.c
@@ -1,11 +1,11 @@
/* Create /proc/self/fd-related names for subfiles of open directories.
- Copyright (C) 2006 Free Software Foundation, Inc.
+ Copyright (C) 2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
@@ -27,69 +26,109 @@
#include <fcntl.h>
#include <stdio.h>
+#include <stdlib.h>
#include <string.h>
+#include <unistd.h>
-#include "dirname.h"
-#include "intprops.h"
-#include "same-inode.h"
-#include "xalloc.h"
-
-/* The results of open() in this file are not used with fchdir,
- therefore save some unnecessary work in fchdir.c. */
-#undef open
-#undef close
-
-#define PROC_SELF_FD_FORMAT "/proc/self/fd/%d/%s"
-
-#define PROC_SELF_FD_NAME_SIZE_BOUND(len) \
- (sizeof PROC_SELF_FD_FORMAT - sizeof "%d%s" \
- + INT_STRLEN_BOUND (int) + (len) + 1)
+#ifdef __KLIBC__
+# include <InnoTekLIBC/backend.h>
+#endif
+#include "intprops.h"
-/* Set BUF to the expansion of PROC_SELF_FD_FORMAT, using FD and FILE
- respectively for %d and %s. If successful, return BUF if the
- result fits in BUF, dynamically allocated memory otherwise. But
- return NULL if /proc is not reliable. */
+/* Set BUF to the name of the subfile of the directory identified by
+ FD, where the subfile is named FILE. If successful, return BUF if
+ the result fits in BUF, dynamically allocated memory otherwise.
+ Return NULL (setting errno) on error. */
char *
openat_proc_name (char buf[OPENAT_BUFFER_SIZE], int fd, char const *file)
{
- static int proc_status = 0;
+ char *result = buf;
+ int dirlen;
- if (! proc_status)
+ /* Make sure the caller gets ENOENT when appropriate. */
+ if (!*file)
{
- /* Set PROC_STATUS to a positive value if /proc/self/fd is
- reliable, and a negative value otherwise. Solaris 10
- /proc/self/fd mishandles "..", and any file name might expand
- to ".." after symbolic link expansion, so avoid /proc/self/fd
- if it mishandles "..". Solaris 10 has openat, but this
- problem is exhibited on code that built on Solaris 8 and
- running on Solaris 10. */
-
- int proc_self_fd = open ("/proc/self/fd", O_RDONLY);
- if (proc_self_fd < 0)
- proc_status = -1;
- else
- {
- struct stat proc_self_fd_dotdot_st;
- struct stat proc_self_st;
- char dotdot_buf[PROC_SELF_FD_NAME_SIZE_BOUND (sizeof ".." - 1)];
- sprintf (dotdot_buf, PROC_SELF_FD_FORMAT, proc_self_fd, "..");
- proc_status =
- ((stat (dotdot_buf, &proc_self_fd_dotdot_st) == 0
- && stat ("/proc/self", &proc_self_st) == 0
- && SAME_INODE (proc_self_fd_dotdot_st, proc_self_st))
- ? 1 : -1);
- close (proc_self_fd);
- }
+ buf[0] = '\0';
+ return buf;
}
- if (proc_status < 0)
- return NULL;
- else
- {
- size_t bufsize = PROC_SELF_FD_NAME_SIZE_BOUND (strlen (file));
- char *result = (bufsize < OPENAT_BUFFER_SIZE ? buf : xmalloc (bufsize));
- sprintf (result, PROC_SELF_FD_FORMAT, fd, file);
- return result;
- }
+#ifndef __KLIBC__
+# define PROC_SELF_FD_FORMAT "/proc/self/fd/%d/"
+ {
+ enum {
+ PROC_SELF_FD_DIR_SIZE_BOUND
+ = (sizeof PROC_SELF_FD_FORMAT - (sizeof "%d" - 1)
+ + INT_STRLEN_BOUND (int))
+ };
+
+ static int proc_status = 0;
+ if (! proc_status)
+ {
+ /* Set PROC_STATUS to a positive value if /proc/self/fd is
+ reliable, and a negative value otherwise. Solaris 10
+ /proc/self/fd mishandles "..", and any file name might expand
+ to ".." after symbolic link expansion, so avoid /proc/self/fd
+ if it mishandles "..". Solaris 10 has openat, but this
+ problem is exhibited on code that built on Solaris 8 and
+ running on Solaris 10. */
+
+ int proc_self_fd = open ("/proc/self/fd",
+ O_SEARCH | O_DIRECTORY | O_NOCTTY | O_NONBLOCK);
+ if (proc_self_fd < 0)
+ proc_status = -1;
+ else
+ {
+ /* Detect whether /proc/self/fd/%i/../fd exists, where %i is the
+ number of a file descriptor open on /proc/self/fd. On Linux,
+ that name resolves to /proc/self/fd, which was opened above.
+ However, on Solaris, it may resolve to /proc/self/fd/fd, which
+ cannot exist, since all names in /proc/self/fd are numeric. */
+ char dotdot_buf[PROC_SELF_FD_DIR_SIZE_BOUND + sizeof "../fd" - 1];
+ sprintf (dotdot_buf, PROC_SELF_FD_FORMAT "../fd", proc_self_fd);
+ proc_status = access (dotdot_buf, F_OK) ? -1 : 1;
+ close (proc_self_fd);
+ }
+ }
+
+ if (proc_status < 0)
+ return NULL;
+ else
+ {
+ size_t bufsize = PROC_SELF_FD_DIR_SIZE_BOUND + strlen (file);
+ if (OPENAT_BUFFER_SIZE < bufsize)
+ {
+ result = malloc (bufsize);
+ if (! result)
+ return NULL;
+ }
+
+ dirlen = sprintf (result, PROC_SELF_FD_FORMAT, fd);
+ }
+ }
+#else
+ /* OS/2 kLIBC provides a function to retrieve a path from a fd. */
+ {
+ char dir[_MAX_PATH];
+ size_t bufsize;
+
+ if (__libc_Back_ioFHToPath (fd, dir, sizeof dir))
+ return NULL;
+
+ dirlen = strlen (dir);
+ bufsize = dirlen + 1 + strlen (file) + 1; /* 1 for '/', 1 for null */
+ if (OPENAT_BUFFER_SIZE < bufsize)
+ {
+ result = malloc (bufsize);
+ if (! result)
+ return NULL;
+ }
+
+ strcpy (result, dir);
+ result[dirlen] = '/';
+ }
+#endif
+
+ strcpy (result + dirlen, file);
+ return result;
}
diff --git a/lib/openat-safer.c b/lib/openat-safer.c
new file mode 100644
index 0000000..5a957d0
--- /dev/null
+++ b/lib/openat-safer.c
@@ -0,0 +1,46 @@
+/* Invoke openat, but avoid some glitches.
+
+ Copyright (C) 2005-2006, 2008-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Paul Eggert for open, ported by Eric Blake for openat. */
+
+#include <config.h>
+
+#include "fcntl-safer.h"
+
+#include <fcntl.h>
+#include <stdarg.h>
+#include "unistd-safer.h"
+
+int
+openat_safer (int fd, char const *file, int flags, ...)
+{
+ mode_t mode = 0;
+
+ if (flags & O_CREAT)
+ {
+ va_list ap;
+ va_start (ap, flags);
+
+ /* We have to use PROMOTED_MODE_T instead of mode_t, otherwise GCC 4
+ creates crashing code when 'mode_t' is smaller than 'int'. */
+ mode = va_arg (ap, PROMOTED_MODE_T);
+
+ va_end (ap);
+ }
+
+ return fd_safer (openat (fd, file, flags, mode));
+}
diff --git a/lib/openat.c b/lib/openat.c
index cd49654..acbf7e3 100644
--- a/lib/openat.c
+++ b/lib/openat.c
@@ -1,10 +1,10 @@
/* provide a replacement openat function
- Copyright (C) 2004, 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2004-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -12,24 +12,138 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* written by Jim Meyering */
+/* If the user's config.h happens to include <fcntl.h>, let it include only
+ the system's <fcntl.h> here, so that orig_openat doesn't recurse to
+ rpl_openat. */
+#define __need_system_fcntl_h
#include <config.h>
+/* Get the original definition of open. It might be defined as a macro. */
+#include <fcntl.h>
+#include <sys/types.h>
+#undef __need_system_fcntl_h
+
+#if HAVE_OPENAT
+static int
+orig_openat (int fd, char const *filename, int flags, mode_t mode)
+{
+ return openat (fd, filename, flags, mode);
+}
+#endif
+
+/* Write "fcntl.h" here, not <fcntl.h>, otherwise OSF/1 5.1 DTK cc eliminates
+ this include because of the preliminary #include <fcntl.h> above. */
+#include "fcntl.h"
+
#include "openat.h"
#include <stdarg.h>
+#include <stdbool.h>
#include <stddef.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <errno.h>
+
+#if HAVE_OPENAT
+
+/* Like openat, but work around Solaris 9 bugs with trailing slash. */
+int
+rpl_openat (int dfd, char const *filename, int flags, ...)
+{
+ mode_t mode;
+ int fd;
+
+ mode = 0;
+ if (flags & O_CREAT)
+ {
+ va_list arg;
+ va_start (arg, flags);
-#include "dirname.h" /* solely for definition of IS_ABSOLUTE_FILE_NAME */
-#include "fcntl--.h"
-#include "lchown.h"
-#include "lstat.h"
-#include "openat-priv.h"
-#include "save-cwd.h"
+ /* We have to use PROMOTED_MODE_T instead of mode_t, otherwise GCC 4
+ creates crashing code when 'mode_t' is smaller than 'int'. */
+ mode = va_arg (arg, PROMOTED_MODE_T);
+
+ va_end (arg);
+ }
+
+# if OPEN_TRAILING_SLASH_BUG
+ /* If the filename ends in a slash and one of O_CREAT, O_WRONLY, O_RDWR
+ is specified, then fail.
+ Rationale: POSIX <http://www.opengroup.org/susv3/basedefs/xbd_chap04.html>
+ says that
+ "A pathname that contains at least one non-slash character and that
+ ends with one or more trailing slashes shall be resolved as if a
+ single dot character ( '.' ) were appended to the pathname."
+ and
+ "The special filename dot shall refer to the directory specified by
+ its predecessor."
+ If the named file already exists as a directory, then
+ - if O_CREAT is specified, open() must fail because of the semantics
+ of O_CREAT,
+ - if O_WRONLY or O_RDWR is specified, open() must fail because POSIX
+ <http://www.opengroup.org/susv3/functions/open.html> says that it
+ fails with errno = EISDIR in this case.
+ If the named file does not exist or does not name a directory, then
+ - if O_CREAT is specified, open() must fail since open() cannot create
+ directories,
+ - if O_WRONLY or O_RDWR is specified, open() must fail because the
+ file does not contain a '.' directory. */
+ if (flags & (O_CREAT | O_WRONLY | O_RDWR))
+ {
+ size_t len = strlen (filename);
+ if (len > 0 && filename[len - 1] == '/')
+ {
+ errno = EISDIR;
+ return -1;
+ }
+ }
+# endif
+
+ fd = orig_openat (dfd, filename, flags, mode);
+
+# if OPEN_TRAILING_SLASH_BUG
+ /* If the filename ends in a slash and fd does not refer to a directory,
+ then fail.
+ Rationale: POSIX <http://www.opengroup.org/susv3/basedefs/xbd_chap04.html>
+ says that
+ "A pathname that contains at least one non-slash character and that
+ ends with one or more trailing slashes shall be resolved as if a
+ single dot character ( '.' ) were appended to the pathname."
+ and
+ "The special filename dot shall refer to the directory specified by
+ its predecessor."
+ If the named file without the slash is not a directory, open() must fail
+ with ENOTDIR. */
+ if (fd >= 0)
+ {
+ /* We know len is positive, since open did not fail with ENOENT. */
+ size_t len = strlen (filename);
+ if (filename[len - 1] == '/')
+ {
+ struct stat statbuf;
+
+ if (fstat (fd, &statbuf) >= 0 && !S_ISDIR (statbuf.st_mode))
+ {
+ close (fd);
+ errno = ENOTDIR;
+ return -1;
+ }
+ }
+ }
+# endif
+
+ return fd;
+}
+
+#else /* !HAVE_OPENAT */
+
+# include "dosname.h" /* solely for definition of IS_ABSOLUTE_FILE_NAME */
+# include "openat-priv.h"
+# include "save-cwd.h"
/* Replacement for Solaris' openat function.
<http://www.google.com/search?q=openat+site:docs.sun.com>
@@ -49,12 +163,9 @@ openat (int fd, char const *file, int flags, ...)
va_list arg;
va_start (arg, flags);
- /* If mode_t is narrower than int, use the promoted type (int),
- not mode_t. Use sizeof to guess whether mode_t is narrower;
- we don't know of any practical counterexamples. */
- mode = (sizeof (mode_t) < sizeof (int)
- ? va_arg (arg, int)
- : va_arg (arg, mode_t));
+ /* We have to use PROMOTED_MODE_T instead of mode_t, otherwise GCC 4
+ creates crashing code when 'mode_t' is smaller than 'int'. */
+ mode = va_arg (arg, PROMOTED_MODE_T);
va_end (arg);
}
@@ -69,13 +180,13 @@ openat (int fd, char const *file, int flags, ...)
directory argument.
If a previous attempt to restore the current working directory
- failed, then we must not even try to access a `.'-relative name.
+ failed, then we must not even try to access a '.'-relative name.
It is the caller's responsibility not to call this function
in that case. */
int
openat_permissive (int fd, char const *file, int flags, mode_t mode,
- int *cwd_errno)
+ int *cwd_errno)
{
struct saved_cwd saved_cwd;
int saved_errno;
@@ -90,18 +201,18 @@ openat_permissive (int fd, char const *file, int flags, mode_t mode,
char *proc_file = openat_proc_name (buf, fd, file);
if (proc_file)
{
- int open_result = open (proc_file, flags, mode);
- int open_errno = errno;
- if (proc_file != buf)
- free (proc_file);
- /* If the syscall succeeds, or if it fails with an unexpected
- errno value, then return right away. Otherwise, fall through
- and resort to using save_cwd/restore_cwd. */
- if (0 <= open_result || ! EXPECTED_ERRNO (open_errno))
- {
- errno = open_errno;
- return open_result;
- }
+ int open_result = open (proc_file, flags, mode);
+ int open_errno = errno;
+ if (proc_file != buf)
+ free (proc_file);
+ /* If the syscall succeeds, or if it fails with an unexpected
+ errno value, then return right away. Otherwise, fall through
+ and resort to using save_cwd/restore_cwd. */
+ if (0 <= open_result || ! EXPECTED_ERRNO (open_errno))
+ {
+ errno = open_errno;
+ return open_result;
+ }
}
}
@@ -109,9 +220,18 @@ openat_permissive (int fd, char const *file, int flags, mode_t mode,
if (! save_ok)
{
if (! cwd_errno)
- openat_save_fail (errno);
+ openat_save_fail (errno);
*cwd_errno = errno;
}
+ if (0 <= fd && fd == saved_cwd.desc)
+ {
+ /* If saving the working directory collides with the user's
+ requested fd, then the user's fd must have been closed to
+ begin with. */
+ free_cwd (&saved_cwd);
+ errno = EBADF;
+ return -1;
+ }
err = fchdir (fd);
saved_errno = errno;
@@ -121,11 +241,17 @@ openat_permissive (int fd, char const *file, int flags, mode_t mode,
err = open (file, flags, mode);
saved_errno = errno;
if (save_ok && restore_cwd (&saved_cwd) != 0)
- {
- if (! cwd_errno)
- openat_restore_fail (errno);
- *cwd_errno = errno;
- }
+ {
+ if (! cwd_errno)
+ {
+ /* Don't write a message to just-created fd 2. */
+ saved_errno = errno;
+ if (err == STDERR_FILENO)
+ close (err);
+ openat_restore_fail (saved_errno);
+ }
+ *cwd_errno = errno;
+ }
}
free_cwd (&saved_cwd);
@@ -139,132 +265,22 @@ bool
openat_needs_fchdir (void)
{
bool needs_fchdir = true;
- int fd = open ("/", O_RDONLY);
+ int fd = open ("/", O_SEARCH);
if (0 <= fd)
{
char buf[OPENAT_BUFFER_SIZE];
char *proc_file = openat_proc_name (buf, fd, ".");
if (proc_file)
- {
- needs_fchdir = false;
- if (proc_file != buf)
- free (proc_file);
- }
+ {
+ needs_fchdir = false;
+ if (proc_file != buf)
+ free (proc_file);
+ }
close (fd);
}
return needs_fchdir;
}
-#if !HAVE_FDOPENDIR
-
-/* Replacement for Solaris' function by the same name.
- <http://www.google.com/search?q=fdopendir+site:docs.sun.com>
- First, try to simulate it via opendir ("/proc/self/fd/FD"). Failing
- that, simulate it by doing save_cwd/fchdir/opendir(".")/restore_cwd.
- If either the save_cwd or the restore_cwd fails (relatively unlikely),
- then give a diagnostic and exit nonzero.
- Otherwise, this function works just like Solaris' fdopendir.
-
- W A R N I N G:
- Unlike the other fd-related functions here, this one
- effectively consumes its FD parameter. The caller should not
- close or otherwise manipulate FD if this function returns successfully. */
-DIR *
-fdopendir (int fd)
-{
- struct saved_cwd saved_cwd;
- int saved_errno;
- DIR *dir;
-
- char buf[OPENAT_BUFFER_SIZE];
- char *proc_file = openat_proc_name (buf, fd, ".");
- if (proc_file)
- {
- dir = opendir (proc_file);
- saved_errno = errno;
- }
- else
- {
- dir = NULL;
- saved_errno = EOPNOTSUPP;
- }
-
- /* If the syscall fails with an expected errno value, resort to
- save_cwd/restore_cwd. */
- if (! dir && EXPECTED_ERRNO (saved_errno))
- {
- if (save_cwd (&saved_cwd) != 0)
- openat_save_fail (errno);
-
- if (fchdir (fd) != 0)
- {
- dir = NULL;
- saved_errno = errno;
- }
- else
- {
- dir = opendir (".");
- saved_errno = errno;
-
- if (restore_cwd (&saved_cwd) != 0)
- openat_restore_fail (errno);
- }
-
- free_cwd (&saved_cwd);
- }
-
- if (dir)
- close (fd);
- if (proc_file != buf)
- free (proc_file);
- errno = saved_errno;
- return dir;
-}
-
-#endif
-
-/* Replacement for Solaris' function by the same name.
- <http://www.google.com/search?q=fstatat+site:docs.sun.com>
- First, try to simulate it via l?stat ("/proc/self/fd/FD/FILE").
- Failing that, simulate it via save_cwd/fchdir/(stat|lstat)/restore_cwd.
- If either the save_cwd or the restore_cwd fails (relatively unlikely),
- then give a diagnostic and exit nonzero.
- Otherwise, this function works just like Solaris' fstatat. */
-
-#define AT_FUNC_NAME fstatat
-#define AT_FUNC_F1 lstat
-#define AT_FUNC_F2 stat
-#define AT_FUNC_USE_F1_COND flag == AT_SYMLINK_NOFOLLOW
-#define AT_FUNC_POST_FILE_PARAM_DECLS , struct stat *st, int flag
-#define AT_FUNC_POST_FILE_ARGS , st
-#include "at-func.c"
-#undef AT_FUNC_NAME
-#undef AT_FUNC_F1
-#undef AT_FUNC_F2
-#undef AT_FUNC_USE_F1_COND
-#undef AT_FUNC_POST_FILE_PARAM_DECLS
-#undef AT_FUNC_POST_FILE_ARGS
-
-/* Replacement for Solaris' function by the same name.
- <http://www.google.com/search?q=unlinkat+site:docs.sun.com>
- First, try to simulate it via (unlink|rmdir) ("/proc/self/fd/FD/FILE").
- Failing that, simulate it via save_cwd/fchdir/(unlink|rmdir)/restore_cwd.
- If either the save_cwd or the restore_cwd fails (relatively unlikely),
- then give a diagnostic and exit nonzero.
- Otherwise, this function works just like Solaris' unlinkat. */
-
-#define AT_FUNC_NAME unlinkat
-#define AT_FUNC_F1 rmdir
-#define AT_FUNC_F2 unlink
-#define AT_FUNC_USE_F1_COND flag == AT_REMOVEDIR
-#define AT_FUNC_POST_FILE_PARAM_DECLS , int flag
-#define AT_FUNC_POST_FILE_ARGS /* empty */
-#include "at-func.c"
-#undef AT_FUNC_NAME
-#undef AT_FUNC_F1
-#undef AT_FUNC_F2
-#undef AT_FUNC_USE_F1_COND
-#undef AT_FUNC_POST_FILE_PARAM_DECLS
-#undef AT_FUNC_POST_FILE_ARGS
+#endif /* !HAVE_OPENAT */
diff --git a/lib/openat.h b/lib/openat.h
index f8333f0..edee6c5 100644
--- a/lib/openat.h
+++ b/lib/openat.h
@@ -1,10 +1,10 @@
/* provide a replacement openat function
- Copyright (C) 2004, 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2004-2006, 2008-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -12,69 +12,29 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* written by Jim Meyering */
+#ifndef _GL_HEADER_OPENAT
+#define _GL_HEADER_OPENAT
+
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
-#include <dirent.h>
#include <unistd.h>
#include <stdbool.h>
-#ifndef __attribute__
-# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 8) || __STRICT_ANSI__
-# define __attribute__(x) /* empty */
-# endif
-#endif
-
-#ifndef ATTRIBUTE_NORETURN
-# define ATTRIBUTE_NORETURN __attribute__ ((__noreturn__))
-#endif
-
-/* Work around a bug in Solaris 9 and 10: AT_FDCWD is positive. Its
- value exceeds INT_MAX, so its use as an int doesn't conform to the
- C standard, and GCC and Sun C complain in some cases. If the bug
- is present, undef AT_FDCWD here, so it can be redefined below. */
-#if 0 < AT_FDCWD && AT_FDCWD == 0xffd19553
-# undef AT_FDCWD
-#endif
-
-/* Use the same bit pattern as Solaris 9, but with the proper
- signedness. The bit pattern is important, in case this actually is
- Solaris with the above workaround. */
-#ifndef AT_FDCWD
-# define AT_FDCWD (-3041965)
-#endif
-
-/* Use the same values as Solaris 9. This shouldn't matter, but
- there's no real reason to differ. */
-#ifndef AT_SYMLINK_NOFOLLOW
-# define AT_SYMLINK_NOFOLLOW 4096
-# define AT_REMOVEDIR 1
+#ifndef _GL_INLINE_HEADER_BEGIN
+ #error "Please include config.h first."
#endif
+_GL_INLINE_HEADER_BEGIN
-#ifdef __OPENAT_PREFIX
+#if !HAVE_OPENAT
-# undef openat
-# define __OPENAT_CONCAT(x, y) x ## y
-# define __OPENAT_XCONCAT(x, y) __OPENAT_CONCAT (x, y)
-# define __OPENAT_ID(y) __OPENAT_XCONCAT (__OPENAT_PREFIX, y)
-# define openat __OPENAT_ID (openat)
-int openat (int fd, char const *file, int flags, /* mode_t mode */ ...);
int openat_permissive (int fd, char const *file, int flags, mode_t mode,
- int *cwd_errno);
-# if ! HAVE_FDOPENDIR
-# define fdopendir __OPENAT_ID (fdopendir)
-# endif
-DIR *fdopendir (int fd);
-# define fstatat __OPENAT_ID (fstatat)
-int fstatat (int fd, char const *file, struct stat *st, int flag);
-# define unlinkat __OPENAT_ID (unlinkat)
-int unlinkat (int fd, char const *file, int flag);
+ int *cwd_errno);
bool openat_needs_fchdir (void);
#else
@@ -85,43 +45,79 @@ bool openat_needs_fchdir (void);
#endif
-#if HAVE_OPENAT && ! LSTAT_FOLLOWS_SLASHED_SYMLINK
-int rpl_fstatat (int fd, char const *file, struct stat *st, int flag);
-# if !COMPILING_FSTATAT
-# undef fstatat
-# define fstatat rpl_fstatat
-# endif
-#endif
-
-int mkdirat (int fd, char const *file, mode_t mode);
-void openat_restore_fail (int) ATTRIBUTE_NORETURN;
-void openat_save_fail (int) ATTRIBUTE_NORETURN;
-int fchmodat (int fd, char const *file, mode_t mode, int flag);
-int fchownat (int fd, char const *file, uid_t owner, gid_t group, int flag);
+_Noreturn void openat_restore_fail (int);
+_Noreturn void openat_save_fail (int);
/* Using these function names makes application code
slightly more readable than it would be with
fchownat (..., 0) or fchownat (..., AT_SYMLINK_NOFOLLOW). */
-static inline int
+
+#if GNULIB_FCHOWNAT
+
+# ifndef FCHOWNAT_INLINE
+# define FCHOWNAT_INLINE _GL_INLINE
+# endif
+
+FCHOWNAT_INLINE int
chownat (int fd, char const *file, uid_t owner, gid_t group)
{
return fchownat (fd, file, owner, group, 0);
}
-static inline int
+FCHOWNAT_INLINE int
lchownat (int fd, char const *file, uid_t owner, gid_t group)
{
return fchownat (fd, file, owner, group, AT_SYMLINK_NOFOLLOW);
}
-static inline int
+#endif
+
+#if GNULIB_FCHMODAT
+
+# ifndef FCHMODAT_INLINE
+# define FCHMODAT_INLINE _GL_INLINE
+# endif
+
+FCHMODAT_INLINE int
chmodat (int fd, char const *file, mode_t mode)
{
return fchmodat (fd, file, mode, 0);
}
-static inline int
+FCHMODAT_INLINE int
lchmodat (int fd, char const *file, mode_t mode)
{
return fchmodat (fd, file, mode, AT_SYMLINK_NOFOLLOW);
}
+
+#endif
+
+#if GNULIB_STATAT
+
+# ifndef STATAT_INLINE
+# define STATAT_INLINE _GL_INLINE
+# endif
+
+STATAT_INLINE int
+statat (int fd, char const *name, struct stat *st)
+{
+ return fstatat (fd, name, st, 0);
+}
+
+STATAT_INLINE int
+lstatat (int fd, char const *name, struct stat *st)
+{
+ return fstatat (fd, name, st, AT_SYMLINK_NOFOLLOW);
+}
+
+#endif
+
+/* For now, there are no wrappers named laccessat or leuidaccessat,
+ since gnulib doesn't support faccessat(,AT_SYMLINK_NOFOLLOW) and
+ since access rights on symlinks are of limited utility. Likewise,
+ wrappers are not provided for accessat or euidaccessat, so as to
+ avoid dragging in -lgen on some platforms. */
+
+_GL_INLINE_HEADER_END
+
+#endif /* _GL_HEADER_OPENAT */
diff --git a/lib/opendir-safer.c b/lib/opendir-safer.c
new file mode 100644
index 0000000..8af9847
--- /dev/null
+++ b/lib/opendir-safer.c
@@ -0,0 +1,76 @@
+/* Invoke opendir, but avoid some glitches.
+
+ Copyright (C) 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Eric Blake. */
+
+#include <config.h>
+
+#include "dirent-safer.h"
+
+#include <errno.h>
+#include <unistd.h>
+#include "unistd-safer.h"
+
+/* Like opendir, but do not clobber stdin, stdout, or stderr. */
+
+DIR *
+opendir_safer (char const *name)
+{
+ DIR *dp = opendir (name);
+
+ if (dp)
+ {
+ int fd = dirfd (dp);
+
+ if (0 <= fd && fd <= STDERR_FILENO)
+ {
+ /* If fdopendir is native (as on Linux), then it is safe to
+ assume dirfd(fdopendir(n))==n. If we are using the
+ gnulib module fdopendir, then this guarantee is not met,
+ but fdopendir recursively calls opendir_safer up to 3
+ times to at least get a safe fd. If fdopendir is not
+ present but dirfd is accurate (as on cygwin 1.5.x), then
+ we recurse up to 3 times ourselves. Finally, if dirfd
+ always fails (as on mingw), then we are already safe. */
+ DIR *newdp;
+ int e;
+#if HAVE_FDOPENDIR || GNULIB_FDOPENDIR
+ int f = dup_safer (fd);
+ if (f < 0)
+ {
+ e = errno;
+ newdp = NULL;
+ }
+ else
+ {
+ newdp = fdopendir (f);
+ e = errno;
+ if (! newdp)
+ close (f);
+ }
+#else /* !FDOPENDIR */
+ newdp = opendir_safer (name);
+ e = errno;
+#endif
+ closedir (dp);
+ errno = e;
+ dp = newdp;
+ }
+ }
+
+ return dp;
+}
diff --git a/lib/opendir.c b/lib/opendir.c
new file mode 100644
index 0000000..a135fd8
--- /dev/null
+++ b/lib/opendir.c
@@ -0,0 +1,169 @@
+/* Start reading the entries of a directory.
+ Copyright (C) 2006-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <dirent.h>
+
+#include <errno.h>
+#include <stddef.h>
+
+#if HAVE_OPENDIR
+
+/* Override opendir(), to keep track of the open file descriptors.
+ Needed because there is a function dirfd(). */
+
+#else
+
+# include <stdlib.h>
+
+# include "dirent-private.h"
+# include "filename.h"
+
+#endif
+
+#if REPLACE_FCHDIR
+# include <unistd.h>
+#endif
+
+#ifdef __KLIBC__
+# include <io.h>
+# include <fcntl.h>
+#endif
+
+DIR *
+opendir (const char *dir_name)
+{
+#if HAVE_OPENDIR
+# undef opendir
+ DIR *dirp;
+
+ dirp = opendir (dir_name);
+ if (dirp == NULL)
+ return NULL;
+
+# ifdef __KLIBC__
+ {
+ int fd = open (dir_name, O_RDONLY);
+ if (fd == -1 || _gl_register_dirp_fd (fd, dirp))
+ {
+ int saved_errno = errno;
+
+ close (fd);
+ closedir (dirp);
+
+ errno = saved_errno;
+
+ return NULL;
+ }
+ }
+# endif
+#else
+
+ char dir_name_mask[MAX_PATH + 1 + 1 + 1];
+ int status;
+ HANDLE current;
+ WIN32_FIND_DATA entry;
+ struct gl_directory *dirp;
+
+ if (dir_name[0] == '\0')
+ {
+ errno = ENOENT;
+ return NULL;
+ }
+
+ /* Make the dir_name absolute, so that we continue reading the same
+ directory if the current directory changed between this opendir()
+ call and a subsequent rewinddir() call. */
+ if (!GetFullPathName (dir_name, MAX_PATH, dir_name_mask, NULL))
+ {
+ errno = EINVAL;
+ return NULL;
+ }
+
+ /* Append the mask.
+ "*" and "*.*" appear to be equivalent. */
+ {
+ char *p;
+
+ p = dir_name_mask + strlen (dir_name_mask);
+ if (p > dir_name_mask && !ISSLASH (p[-1]))
+ *p++ = '\\';
+ *p++ = '*';
+ *p = '\0';
+ }
+
+ /* Start searching the directory. */
+ status = -1;
+ current = FindFirstFile (dir_name_mask, &entry);
+ if (current == INVALID_HANDLE_VALUE)
+ {
+ switch (GetLastError ())
+ {
+ case ERROR_FILE_NOT_FOUND:
+ status = -2;
+ break;
+ case ERROR_PATH_NOT_FOUND:
+ errno = ENOENT;
+ return NULL;
+ case ERROR_DIRECTORY:
+ errno = ENOTDIR;
+ return NULL;
+ case ERROR_ACCESS_DENIED:
+ errno = EACCES;
+ return NULL;
+ default:
+ errno = EIO;
+ return NULL;
+ }
+ }
+
+ /* Allocate the result. */
+ dirp =
+ (struct gl_directory *)
+ malloc (offsetof (struct gl_directory, dir_name_mask[0])
+ + strlen (dir_name_mask) + 1);
+ if (dirp == NULL)
+ {
+ if (current != INVALID_HANDLE_VALUE)
+ FindClose (current);
+ errno = ENOMEM;
+ return NULL;
+ }
+ dirp->status = status;
+ dirp->current = current;
+ if (status == -1)
+ memcpy (&dirp->entry, &entry, sizeof (WIN32_FIND_DATA));
+ strcpy (dirp->dir_name_mask, dir_name_mask);
+
+#endif
+
+#if REPLACE_FCHDIR
+ {
+ int fd = dirfd (dirp);
+ if (0 <= fd && _gl_register_fd (fd, dir_name) != fd)
+ {
+ int saved_errno = errno;
+ closedir (dirp);
+ errno = saved_errno;
+ return NULL;
+ }
+ }
+#endif
+
+ return dirp;
+}
diff --git a/lib/parse-datetime.c b/lib/parse-datetime.c
new file mode 100644
index 0000000..0cbeb72
--- /dev/null
+++ b/lib/parse-datetime.c
@@ -0,0 +1,3350 @@
+/* A Bison parser, made by GNU Bison 3.0.4. */
+
+/* Bison implementation for Yacc-like parsers in C
+
+ Copyright (C) 1984, 1989-1990, 2000-2015 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 <http://www.gnu.org/licenses/>. */
+
+/* As a special exception, you may create a larger work that contains
+ part or all of the Bison parser skeleton and distribute that work
+ under terms of your choice, so long as that work isn't itself a
+ parser generator using the skeleton or a modified version thereof
+ as a parser skeleton. Alternatively, if you modify or redistribute
+ the parser skeleton itself, you may (at your option) remove this
+ special exception, which will cause the skeleton and the resulting
+ Bison output files to be licensed under the GNU General Public
+ License without this special exception.
+
+ This special exception was added by the Free Software Foundation in
+ version 2.2 of Bison. */
+
+/* C LALR(1) parser skeleton written by Richard Stallman, by
+ simplifying the original so-called "semantic" parser. */
+
+/* All symbols defined below should begin with yy or YY, to avoid
+ infringing on user name space. This should be done even for local
+ variables, as they might otherwise be expanded by user macros.
+ There are some unavoidable exceptions within include files to
+ define necessary library symbols; they are noted "INFRINGES ON
+ USER NAME SPACE" below. */
+
+/* Identify Bison output. */
+#define YYBISON 1
+
+/* Bison version. */
+#define YYBISON_VERSION "3.0.4"
+
+/* Skeleton name. */
+#define YYSKELETON_NAME "yacc.c"
+
+/* Pure parsers. */
+#define YYPURE 1
+
+/* Push parsers. */
+#define YYPUSH 0
+
+/* Pull parsers. */
+#define YYPULL 1
+
+
+
+
+/* Copy the first part of user declarations. */
+#line 1 "./lib/parse-datetime.y" /* yacc.c:339 */
+
+/* Parse a string into an internal time stamp.
+
+ Copyright (C) 1999-2000, 2002-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Originally written by Steven M. Bellovin <smb@research.att.com> while
+ at the University of North Carolina at Chapel Hill. Later tweaked by
+ a couple of people on Usenet. Completely overhauled by Rich $alz
+ <rsalz@bbn.com> and Jim Berets <jberets@bbn.com> in August, 1990.
+
+ Modified by Paul Eggert <eggert@twinsun.com> in August 1999 to do
+ the right thing about local DST. Also modified by Paul Eggert
+ <eggert@cs.ucla.edu> in February 2004 to support
+ nanosecond-resolution time stamps, and in October 2004 to support
+ TZ strings in dates. */
+
+/* FIXME: Check for arithmetic overflow in all cases, not just
+ some of them. */
+
+#include <config.h>
+
+#include "parse-datetime.h"
+
+#include "intprops.h"
+#include "timespec.h"
+#include "verify.h"
+
+/* There's no need to extend the stack, so there's no need to involve
+ alloca. */
+#define YYSTACK_USE_ALLOCA 0
+
+/* Tell Bison how much stack space is needed. 20 should be plenty for
+ this grammar, which is not right recursive. Beware setting it too
+ high, since that might cause problems on machines whose
+ implementations have lame stack-overflow checking. */
+#define YYMAXDEPTH 20
+#define YYINITDEPTH YYMAXDEPTH
+
+/* Since the code of parse-datetime.y is not included in the Emacs executable
+ itself, there is no need to #define static in this file. Even if
+ the code were included in the Emacs executable, it probably
+ wouldn't do any harm to #undef it here; this will only cause
+ problems if we try to write to a static variable, which I don't
+ think this code needs to do. */
+#ifdef emacs
+# undef static
+#endif
+
+#include <c-ctype.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "xalloc.h"
+
+/* Bison's skeleton tests _STDLIB_H, while some stdlib.h headers
+ use _STDLIB_H_ as witness. Map the latter to the one bison uses. */
+/* FIXME: this is temporary. Remove when we have a mechanism to ensure
+ that the version we're using is fixed, too. */
+#ifdef _STDLIB_H_
+# undef _STDLIB_H
+# define _STDLIB_H 1
+#endif
+
+/* ISDIGIT differs from isdigit, as follows:
+ - Its arg may be any int or unsigned int; it need not be an unsigned char
+ or EOF.
+ - It's typically faster.
+ POSIX says that only '0' through '9' are digits. Prefer ISDIGIT to
+ isdigit unless it's important to use the locale's definition
+ of "digit" even when the host does not conform to POSIX. */
+#define ISDIGIT(c) ((unsigned int) (c) - '0' <= 9)
+
+/* Shift A right by B bits portably, by dividing A by 2**B and
+ truncating towards minus infinity. A and B should be free of side
+ effects, and B should be in the range 0 <= B <= INT_BITS - 2, where
+ INT_BITS is the number of useful bits in an int. GNU code can
+ assume that INT_BITS is at least 32.
+
+ ISO C99 says that A >> B is implementation-defined if A < 0. Some
+ implementations (e.g., UNICOS 9.0 on a Cray Y-MP EL) don't shift
+ right in the usual way when A < 0, so SHR falls back on division if
+ ordinary A >> B doesn't seem to be the usual signed shift. */
+#define SHR(a, b) \
+ (-1 >> 1 == -1 \
+ ? (a) >> (b) \
+ : (a) / (1 << (b)) - ((a) % (1 << (b)) < 0))
+
+#define EPOCH_YEAR 1970
+#define TM_YEAR_BASE 1900
+
+#define HOUR(x) ((x) * 60)
+
+/* long_time_t is a signed integer type that contains all time_t values. */
+verify (TYPE_IS_INTEGER (time_t));
+#if TIME_T_FITS_IN_LONG_INT
+typedef long int long_time_t;
+#else
+typedef time_t long_time_t;
+#endif
+
+/* Convert a possibly-signed character to an unsigned character. This is
+ a bit safer than casting to unsigned char, since it catches some type
+ errors that the cast doesn't. */
+static unsigned char to_uchar (char ch) { return ch; }
+
+/* Lots of this code assumes time_t and time_t-like values fit into
+ long_time_t. */
+verify (TYPE_MINIMUM (long_time_t) <= TYPE_MINIMUM (time_t)
+ && TYPE_MAXIMUM (time_t) <= TYPE_MAXIMUM (long_time_t));
+
+/* FIXME: It also assumes that signed integer overflow silently wraps around,
+ but this is not true any more with recent versions of GCC 4. */
+
+/* An integer value, and the number of digits in its textual
+ representation. */
+typedef struct
+{
+ bool negative;
+ long int value;
+ size_t digits;
+} textint;
+
+/* An entry in the lexical lookup table. */
+typedef struct
+{
+ char const *name;
+ int type;
+ int value;
+} table;
+
+/* Meridian: am, pm, or 24-hour style. */
+enum { MERam, MERpm, MER24 };
+
+enum { BILLION = 1000000000, LOG10_BILLION = 9 };
+
+/* Relative times. */
+typedef struct
+{
+ /* Relative year, month, day, hour, minutes, seconds, and nanoseconds. */
+ long int year;
+ long int month;
+ long int day;
+ long int hour;
+ long int minutes;
+ long_time_t seconds;
+ long int ns;
+} relative_time;
+
+#if HAVE_COMPOUND_LITERALS
+# define RELATIVE_TIME_0 ((relative_time) { 0, 0, 0, 0, 0, 0, 0 })
+#else
+static relative_time const RELATIVE_TIME_0;
+#endif
+
+/* Information passed to and from the parser. */
+typedef struct
+{
+ /* The input string remaining to be parsed. */
+ const char *input;
+
+ /* N, if this is the Nth Tuesday. */
+ long int day_ordinal;
+
+ /* Day of week; Sunday is 0. */
+ int day_number;
+
+ /* tm_isdst flag for the local zone. */
+ int local_isdst;
+
+ /* Time zone, in minutes east of UTC. */
+ long int time_zone;
+
+ /* Style used for time. */
+ int meridian;
+
+ /* Gregorian year, month, day, hour, minutes, seconds, and nanoseconds. */
+ textint year;
+ long int month;
+ long int day;
+ long int hour;
+ long int minutes;
+ struct timespec seconds; /* includes nanoseconds */
+
+ /* Relative year, month, day, hour, minutes, seconds, and nanoseconds. */
+ relative_time rel;
+
+ /* Presence or counts of nonterminals of various flavors parsed so far. */
+ bool timespec_seen;
+ bool rels_seen;
+ size_t dates_seen;
+ size_t days_seen;
+ size_t local_zones_seen;
+ size_t dsts_seen;
+ size_t times_seen;
+ size_t zones_seen;
+
+ /* Table of local time zone abbreviations, terminated by a null entry. */
+ table local_time_zone_table[3];
+} parser_control;
+
+union YYSTYPE;
+static int yylex (union YYSTYPE *, parser_control *);
+static int yyerror (parser_control const *, char const *);
+static long int time_zone_hhmm (parser_control *, textint, long int);
+
+/* Extract into *PC any date and time info from a string of digits
+ of the form e.g., YYYYMMDD, YYMMDD, HHMM, HH (and sometimes YYY,
+ YYYY, ...). */
+static void
+digits_to_date_time (parser_control *pc, textint text_int)
+{
+ if (pc->dates_seen && ! pc->year.digits
+ && ! pc->rels_seen && (pc->times_seen || 2 < text_int.digits))
+ pc->year = text_int;
+ else
+ {
+ if (4 < text_int.digits)
+ {
+ pc->dates_seen++;
+ pc->day = text_int.value % 100;
+ pc->month = (text_int.value / 100) % 100;
+ pc->year.value = text_int.value / 10000;
+ pc->year.digits = text_int.digits - 4;
+ }
+ else
+ {
+ pc->times_seen++;
+ if (text_int.digits <= 2)
+ {
+ pc->hour = text_int.value;
+ pc->minutes = 0;
+ }
+ else
+ {
+ pc->hour = text_int.value / 100;
+ pc->minutes = text_int.value % 100;
+ }
+ pc->seconds.tv_sec = 0;
+ pc->seconds.tv_nsec = 0;
+ pc->meridian = MER24;
+ }
+ }
+}
+
+/* Increment PC->rel by FACTOR * REL (FACTOR is 1 or -1). */
+static void
+apply_relative_time (parser_control *pc, relative_time rel, int factor)
+{
+ pc->rel.ns += factor * rel.ns;
+ pc->rel.seconds += factor * rel.seconds;
+ pc->rel.minutes += factor * rel.minutes;
+ pc->rel.hour += factor * rel.hour;
+ pc->rel.day += factor * rel.day;
+ pc->rel.month += factor * rel.month;
+ pc->rel.year += factor * rel.year;
+ pc->rels_seen = true;
+}
+
+/* Set PC-> hour, minutes, seconds and nanoseconds members from arguments. */
+static void
+set_hhmmss (parser_control *pc, long int hour, long int minutes,
+ time_t sec, long int nsec)
+{
+ pc->hour = hour;
+ pc->minutes = minutes;
+ pc->seconds.tv_sec = sec;
+ pc->seconds.tv_nsec = nsec;
+}
+
+
+#line 352 "parse-datetime.c" /* yacc.c:339 */
+
+# ifndef YY_NULLPTR
+# if defined __cplusplus && 201103L <= __cplusplus
+# define YY_NULLPTR nullptr
+# else
+# define YY_NULLPTR 0
+# endif
+# endif
+
+/* Enabling verbose error messages. */
+#ifdef YYERROR_VERBOSE
+# undef YYERROR_VERBOSE
+# define YYERROR_VERBOSE 1
+#else
+# define YYERROR_VERBOSE 0
+#endif
+
+
+/* Debug traces. */
+#ifndef YYDEBUG
+# define YYDEBUG 0
+#endif
+#if YYDEBUG
+extern int yydebug;
+#endif
+
+/* Token type. */
+#ifndef YYTOKENTYPE
+# define YYTOKENTYPE
+ enum yytokentype
+ {
+ tAGO = 258,
+ tDST = 259,
+ tYEAR_UNIT = 260,
+ tMONTH_UNIT = 261,
+ tHOUR_UNIT = 262,
+ tMINUTE_UNIT = 263,
+ tSEC_UNIT = 264,
+ tDAY_UNIT = 265,
+ tDAY_SHIFT = 266,
+ tDAY = 267,
+ tDAYZONE = 268,
+ tLOCAL_ZONE = 269,
+ tMERIDIAN = 270,
+ tMONTH = 271,
+ tORDINAL = 272,
+ tZONE = 273,
+ tSNUMBER = 274,
+ tUNUMBER = 275,
+ tSDECIMAL_NUMBER = 276,
+ tUDECIMAL_NUMBER = 277
+ };
+#endif
+/* Tokens. */
+#define tAGO 258
+#define tDST 259
+#define tYEAR_UNIT 260
+#define tMONTH_UNIT 261
+#define tHOUR_UNIT 262
+#define tMINUTE_UNIT 263
+#define tSEC_UNIT 264
+#define tDAY_UNIT 265
+#define tDAY_SHIFT 266
+#define tDAY 267
+#define tDAYZONE 268
+#define tLOCAL_ZONE 269
+#define tMERIDIAN 270
+#define tMONTH 271
+#define tORDINAL 272
+#define tZONE 273
+#define tSNUMBER 274
+#define tUNUMBER 275
+#define tSDECIMAL_NUMBER 276
+#define tUDECIMAL_NUMBER 277
+
+/* Value type. */
+#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
+
+union YYSTYPE
+{
+#line 297 "./lib/parse-datetime.y" /* yacc.c:355 */
+
+ long int intval;
+ textint textintval;
+ struct timespec timespec;
+ relative_time rel;
+
+#line 440 "parse-datetime.c" /* yacc.c:355 */
+};
+
+typedef union YYSTYPE YYSTYPE;
+# define YYSTYPE_IS_TRIVIAL 1
+# define YYSTYPE_IS_DECLARED 1
+#endif
+
+
+
+int yyparse (parser_control *pc);
+
+
+
+/* Copy the second part of user declarations. */
+
+#line 456 "parse-datetime.c" /* yacc.c:358 */
+
+#ifdef short
+# undef short
+#endif
+
+#ifdef YYTYPE_UINT8
+typedef YYTYPE_UINT8 yytype_uint8;
+#else
+typedef unsigned char yytype_uint8;
+#endif
+
+#ifdef YYTYPE_INT8
+typedef YYTYPE_INT8 yytype_int8;
+#else
+typedef signed char yytype_int8;
+#endif
+
+#ifdef YYTYPE_UINT16
+typedef YYTYPE_UINT16 yytype_uint16;
+#else
+typedef unsigned short int yytype_uint16;
+#endif
+
+#ifdef YYTYPE_INT16
+typedef YYTYPE_INT16 yytype_int16;
+#else
+typedef short int yytype_int16;
+#endif
+
+#ifndef YYSIZE_T
+# ifdef __SIZE_TYPE__
+# define YYSIZE_T __SIZE_TYPE__
+# elif defined size_t
+# define YYSIZE_T size_t
+# elif ! defined YYSIZE_T
+# include <stddef.h> /* INFRINGES ON USER NAME SPACE */
+# define YYSIZE_T size_t
+# else
+# define YYSIZE_T unsigned int
+# endif
+#endif
+
+#define YYSIZE_MAXIMUM ((YYSIZE_T) -1)
+
+#ifndef YY_
+# if defined YYENABLE_NLS && YYENABLE_NLS
+# if ENABLE_NLS
+# include <libintl.h> /* INFRINGES ON USER NAME SPACE */
+# define YY_(Msgid) dgettext ("bison-runtime", Msgid)
+# endif
+# endif
+# ifndef YY_
+# define YY_(Msgid) Msgid
+# endif
+#endif
+
+#ifndef YY_ATTRIBUTE
+# if (defined __GNUC__ \
+ && (2 < __GNUC__ || (__GNUC__ == 2 && 96 <= __GNUC_MINOR__))) \
+ || defined __SUNPRO_C && 0x5110 <= __SUNPRO_C
+# define YY_ATTRIBUTE(Spec) __attribute__(Spec)
+# else
+# define YY_ATTRIBUTE(Spec) /* empty */
+# endif
+#endif
+
+#ifndef YY_ATTRIBUTE_PURE
+# define YY_ATTRIBUTE_PURE YY_ATTRIBUTE ((__pure__))
+#endif
+
+#ifndef YY_ATTRIBUTE_UNUSED
+# define YY_ATTRIBUTE_UNUSED YY_ATTRIBUTE ((__unused__))
+#endif
+
+#if !defined _Noreturn \
+ && (!defined __STDC_VERSION__ || __STDC_VERSION__ < 201112)
+# if defined _MSC_VER && 1200 <= _MSC_VER
+# define _Noreturn __declspec (noreturn)
+# else
+# define _Noreturn YY_ATTRIBUTE ((__noreturn__))
+# endif
+#endif
+
+/* Suppress unused-variable warnings by "using" E. */
+#if ! defined lint || defined __GNUC__
+# define YYUSE(E) ((void) (E))
+#else
+# define YYUSE(E) /* empty */
+#endif
+
+#if defined __GNUC__ && 407 <= __GNUC__ * 100 + __GNUC_MINOR__
+/* Suppress an incorrect diagnostic about yylval being uninitialized. */
+# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \
+ _Pragma ("GCC diagnostic push") \
+ _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"")\
+ _Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"")
+# define YY_IGNORE_MAYBE_UNINITIALIZED_END \
+ _Pragma ("GCC diagnostic pop")
+#else
+# define YY_INITIAL_VALUE(Value) Value
+#endif
+#ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
+# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
+# define YY_IGNORE_MAYBE_UNINITIALIZED_END
+#endif
+#ifndef YY_INITIAL_VALUE
+# define YY_INITIAL_VALUE(Value) /* Nothing. */
+#endif
+
+
+#if ! defined yyoverflow || YYERROR_VERBOSE
+
+/* The parser invokes alloca or malloc; define the necessary symbols. */
+
+# ifdef YYSTACK_USE_ALLOCA
+# if YYSTACK_USE_ALLOCA
+# ifdef __GNUC__
+# define YYSTACK_ALLOC __builtin_alloca
+# elif defined __BUILTIN_VA_ARG_INCR
+# include <alloca.h> /* INFRINGES ON USER NAME SPACE */
+# elif defined _AIX
+# define YYSTACK_ALLOC __alloca
+# elif defined _MSC_VER
+# include <malloc.h> /* INFRINGES ON USER NAME SPACE */
+# define alloca _alloca
+# else
+# define YYSTACK_ALLOC alloca
+# if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS
+# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
+ /* Use EXIT_SUCCESS as a witness for stdlib.h. */
+# ifndef EXIT_SUCCESS
+# define EXIT_SUCCESS 0
+# endif
+# endif
+# endif
+# endif
+# endif
+
+# ifdef YYSTACK_ALLOC
+ /* Pacify GCC's 'empty if-body' warning. */
+# define YYSTACK_FREE(Ptr) do { /* empty */; } while (0)
+# ifndef YYSTACK_ALLOC_MAXIMUM
+ /* The OS might guarantee only one guard page at the bottom of the stack,
+ and a page size can be as small as 4096 bytes. So we cannot safely
+ invoke alloca (N) if N exceeds 4096. Use a slightly smaller number
+ to allow for a few compiler-allocated temporary stack slots. */
+# define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */
+# endif
+# else
+# define YYSTACK_ALLOC YYMALLOC
+# define YYSTACK_FREE YYFREE
+# ifndef YYSTACK_ALLOC_MAXIMUM
+# define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM
+# endif
+# if (defined __cplusplus && ! defined EXIT_SUCCESS \
+ && ! ((defined YYMALLOC || defined malloc) \
+ && (defined YYFREE || defined free)))
+# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
+# ifndef EXIT_SUCCESS
+# define EXIT_SUCCESS 0
+# endif
+# endif
+# ifndef YYMALLOC
+# define YYMALLOC malloc
+# if ! defined malloc && ! defined EXIT_SUCCESS
+void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */
+# endif
+# endif
+# ifndef YYFREE
+# define YYFREE free
+# if ! defined free && ! defined EXIT_SUCCESS
+void free (void *); /* INFRINGES ON USER NAME SPACE */
+# endif
+# endif
+# endif
+#endif /* ! defined yyoverflow || YYERROR_VERBOSE */
+
+
+#if (! defined yyoverflow \
+ && (! defined __cplusplus \
+ || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL)))
+
+/* A type that is properly aligned for any stack member. */
+union yyalloc
+{
+ yytype_int16 yyss_alloc;
+ YYSTYPE yyvs_alloc;
+};
+
+/* The size of the maximum gap between one aligned stack and the next. */
+# define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1)
+
+/* The size of an array large to enough to hold all stacks, each with
+ N elements. */
+# define YYSTACK_BYTES(N) \
+ ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \
+ + YYSTACK_GAP_MAXIMUM)
+
+# define YYCOPY_NEEDED 1
+
+/* Relocate STACK from its old location to the new one. The
+ local variables YYSIZE and YYSTACKSIZE give the old and new number of
+ elements in the stack, and YYPTR gives the new location of the
+ stack. Advance YYPTR to a properly aligned location for the next
+ stack. */
+# define YYSTACK_RELOCATE(Stack_alloc, Stack) \
+ do \
+ { \
+ YYSIZE_T yynewbytes; \
+ YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \
+ Stack = &yyptr->Stack_alloc; \
+ yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \
+ yyptr += yynewbytes / sizeof (*yyptr); \
+ } \
+ while (0)
+
+#endif
+
+#if defined YYCOPY_NEEDED && YYCOPY_NEEDED
+/* Copy COUNT objects from SRC to DST. The source and destination do
+ not overlap. */
+# ifndef YYCOPY
+# if defined __GNUC__ && 1 < __GNUC__
+# define YYCOPY(Dst, Src, Count) \
+ __builtin_memcpy (Dst, Src, (Count) * sizeof (*(Src)))
+# else
+# define YYCOPY(Dst, Src, Count) \
+ do \
+ { \
+ YYSIZE_T yyi; \
+ for (yyi = 0; yyi < (Count); yyi++) \
+ (Dst)[yyi] = (Src)[yyi]; \
+ } \
+ while (0)
+# endif
+# endif
+#endif /* !YYCOPY_NEEDED */
+
+/* YYFINAL -- State number of the termination state. */
+#define YYFINAL 12
+/* YYLAST -- Last index in YYTABLE. */
+#define YYLAST 112
+
+/* YYNTOKENS -- Number of terminals. */
+#define YYNTOKENS 28
+/* YYNNTS -- Number of nonterminals. */
+#define YYNNTS 26
+/* YYNRULES -- Number of rules. */
+#define YYNRULES 91
+/* YYNSTATES -- Number of states. */
+#define YYNSTATES 114
+
+/* YYTRANSLATE[YYX] -- Symbol number corresponding to YYX as returned
+ by yylex, with out-of-bounds checking. */
+#define YYUNDEFTOK 2
+#define YYMAXUTOK 277
+
+#define YYTRANSLATE(YYX) \
+ ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK)
+
+/* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM
+ as returned by yylex, without out-of-bounds checking. */
+static const yytype_uint8 yytranslate[] =
+{
+ 0, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 26, 2, 2, 27, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 25, 2,
+ 2, 2, 2, 2, 23, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 24, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 1, 2, 3, 4,
+ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
+ 15, 16, 17, 18, 19, 20, 21, 22
+};
+
+#if YYDEBUG
+ /* YYRLINE[YYN] -- Source line where rule number YYN was defined. */
+static const yytype_uint16 yyrline[] =
+{
+ 0, 324, 324, 325, 329, 336, 338, 342, 344, 346,
+ 348, 350, 352, 354, 355, 356, 360, 364, 368, 373,
+ 378, 383, 387, 392, 397, 404, 406, 410, 418, 423,
+ 433, 435, 437, 440, 443, 445, 447, 452, 457, 462,
+ 467, 475, 480, 500, 508, 516, 521, 527, 532, 538,
+ 542, 552, 554, 556, 561, 563, 565, 567, 569, 571,
+ 573, 575, 577, 579, 581, 583, 585, 587, 589, 591,
+ 593, 595, 597, 599, 601, 605, 607, 609, 611, 613,
+ 615, 620, 624, 624, 627, 628, 633, 634, 639, 644,
+ 655, 656
+};
+#endif
+
+#if YYDEBUG || YYERROR_VERBOSE || 0
+/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
+ First, the terminals, then, starting at YYNTOKENS, nonterminals. */
+static const char *const yytname[] =
+{
+ "$end", "error", "$undefined", "tAGO", "tDST", "tYEAR_UNIT",
+ "tMONTH_UNIT", "tHOUR_UNIT", "tMINUTE_UNIT", "tSEC_UNIT", "tDAY_UNIT",
+ "tDAY_SHIFT", "tDAY", "tDAYZONE", "tLOCAL_ZONE", "tMERIDIAN", "tMONTH",
+ "tORDINAL", "tZONE", "tSNUMBER", "tUNUMBER", "tSDECIMAL_NUMBER",
+ "tUDECIMAL_NUMBER", "'@'", "'T'", "':'", "','", "'/'", "$accept", "spec",
+ "timespec", "items", "item", "datetime", "iso_8601_datetime", "time",
+ "iso_8601_time", "o_zone_offset", "zone_offset", "local_zone", "zone",
+ "day", "date", "iso_8601_date", "rel", "relunit", "relunit_snumber",
+ "dayshift", "seconds", "signed_seconds", "unsigned_seconds", "number",
+ "hybrid", "o_colon_minutes", YY_NULLPTR
+};
+#endif
+
+# ifdef YYPRINT
+/* YYTOKNUM[NUM] -- (External) token number corresponding to the
+ (internal) symbol number NUM (which must be that of a token). */
+static const yytype_uint16 yytoknum[] =
+{
+ 0, 256, 257, 258, 259, 260, 261, 262, 263, 264,
+ 265, 266, 267, 268, 269, 270, 271, 272, 273, 274,
+ 275, 276, 277, 64, 84, 58, 44, 47
+};
+# endif
+
+#define YYPACT_NINF -93
+
+#define yypact_value_is_default(Yystate) \
+ (!!((Yystate) == (-93)))
+
+#define YYTABLE_NINF -1
+
+#define yytable_value_is_error(Yytable_value) \
+ 0
+
+ /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
+ STATE-NUM. */
+static const yytype_int8 yypact[] =
+{
+ 38, 27, 77, -93, 46, -93, -93, -93, -93, -93,
+ -93, -93, -93, -93, -93, -93, -93, -93, -93, -93,
+ 62, -93, 82, -3, 66, 3, 74, -4, 83, 84,
+ 75, -93, -93, -93, -93, -93, -93, -93, -93, -93,
+ 71, -93, 93, -93, -93, -93, -93, -93, -93, 78,
+ 72, -93, -93, -93, -93, -93, -93, -93, -93, 25,
+ -93, -93, -93, -93, -93, -93, -93, -93, -93, -93,
+ -93, -93, -93, -93, -93, 21, 19, 79, 80, -93,
+ -93, -93, -93, -93, 81, -93, -93, 85, 86, -93,
+ -93, -93, -93, -93, -6, 76, 17, -93, -93, -93,
+ -93, 87, 69, -93, -93, 88, 89, -1, -93, 18,
+ -93, -93, 69, 91
+};
+
+ /* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM.
+ Performed when YYTABLE does not specify something else to do. Zero
+ means the default is an error. */
+static const yytype_uint8 yydefact[] =
+{
+ 5, 0, 0, 2, 3, 85, 87, 84, 86, 4,
+ 82, 83, 1, 56, 59, 65, 68, 73, 62, 81,
+ 37, 35, 28, 0, 0, 30, 0, 88, 0, 0,
+ 31, 6, 7, 16, 8, 21, 9, 10, 12, 11,
+ 49, 13, 52, 74, 53, 14, 15, 38, 29, 0,
+ 45, 54, 57, 63, 66, 69, 60, 39, 36, 90,
+ 32, 75, 76, 78, 79, 80, 77, 55, 58, 64,
+ 67, 70, 61, 40, 18, 47, 90, 0, 0, 22,
+ 89, 71, 72, 33, 0, 51, 44, 0, 0, 34,
+ 43, 48, 50, 27, 25, 41, 0, 17, 46, 91,
+ 19, 90, 0, 23, 26, 0, 0, 25, 42, 25,
+ 20, 24, 0, 25
+};
+
+ /* YYPGOTO[NTERM-NUM]. */
+static const yytype_int8 yypgoto[] =
+{
+ -93, -93, -93, -93, -93, -93, -93, -93, 20, -68,
+ -27, -93, -93, -93, -93, -93, -93, -93, 60, -93,
+ -93, -93, -92, -93, -93, 43
+};
+
+ /* YYDEFGOTO[NTERM-NUM]. */
+static const yytype_int8 yydefgoto[] =
+{
+ -1, 2, 3, 4, 31, 32, 33, 34, 35, 103,
+ 104, 36, 37, 38, 39, 40, 41, 42, 43, 44,
+ 9, 10, 11, 45, 46, 93
+};
+
+ /* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If
+ positive, shift that token. If negative, reduce the rule whose
+ number is the opposite. If YYTABLE_NINF, syntax error. */
+static const yytype_uint8 yytable[] =
+{
+ 79, 67, 68, 69, 70, 71, 72, 58, 73, 100,
+ 107, 74, 75, 101, 110, 76, 49, 50, 101, 102,
+ 113, 77, 59, 78, 61, 62, 63, 64, 65, 66,
+ 61, 62, 63, 64, 65, 66, 101, 101, 92, 111,
+ 90, 91, 106, 112, 88, 111, 5, 6, 7, 8,
+ 88, 13, 14, 15, 16, 17, 18, 19, 20, 21,
+ 22, 1, 23, 24, 25, 26, 27, 28, 29, 79,
+ 30, 51, 52, 53, 54, 55, 56, 12, 57, 61,
+ 62, 63, 64, 65, 66, 60, 48, 80, 47, 6,
+ 83, 8, 81, 82, 26, 84, 85, 86, 87, 94,
+ 95, 96, 89, 105, 97, 98, 99, 0, 108, 109,
+ 101, 0, 88
+};
+
+static const yytype_int8 yycheck[] =
+{
+ 27, 5, 6, 7, 8, 9, 10, 4, 12, 15,
+ 102, 15, 16, 19, 15, 19, 19, 20, 19, 25,
+ 112, 25, 19, 27, 5, 6, 7, 8, 9, 10,
+ 5, 6, 7, 8, 9, 10, 19, 19, 19, 107,
+ 19, 20, 25, 25, 25, 113, 19, 20, 21, 22,
+ 25, 5, 6, 7, 8, 9, 10, 11, 12, 13,
+ 14, 23, 16, 17, 18, 19, 20, 21, 22, 96,
+ 24, 5, 6, 7, 8, 9, 10, 0, 12, 5,
+ 6, 7, 8, 9, 10, 25, 4, 27, 26, 20,
+ 30, 22, 9, 9, 19, 24, 3, 19, 26, 20,
+ 20, 20, 59, 27, 84, 20, 20, -1, 20, 20,
+ 19, -1, 25
+};
+
+ /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing
+ symbol of state STATE-NUM. */
+static const yytype_uint8 yystos[] =
+{
+ 0, 23, 29, 30, 31, 19, 20, 21, 22, 48,
+ 49, 50, 0, 5, 6, 7, 8, 9, 10, 11,
+ 12, 13, 14, 16, 17, 18, 19, 20, 21, 22,
+ 24, 32, 33, 34, 35, 36, 39, 40, 41, 42,
+ 43, 44, 45, 46, 47, 51, 52, 26, 4, 19,
+ 20, 5, 6, 7, 8, 9, 10, 12, 4, 19,
+ 46, 5, 6, 7, 8, 9, 10, 5, 6, 7,
+ 8, 9, 10, 12, 15, 16, 19, 25, 27, 38,
+ 46, 9, 9, 46, 24, 3, 19, 26, 25, 53,
+ 19, 20, 19, 53, 20, 20, 20, 36, 20, 20,
+ 15, 19, 25, 37, 38, 27, 25, 50, 20, 20,
+ 15, 37, 25, 50
+};
+
+ /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */
+static const yytype_uint8 yyr1[] =
+{
+ 0, 28, 29, 29, 30, 31, 31, 32, 32, 32,
+ 32, 32, 32, 32, 32, 32, 33, 34, 35, 35,
+ 35, 35, 36, 36, 36, 37, 37, 38, 39, 39,
+ 40, 40, 40, 40, 40, 40, 40, 41, 41, 41,
+ 41, 42, 42, 42, 42, 42, 42, 42, 42, 42,
+ 43, 44, 44, 44, 45, 45, 45, 45, 45, 45,
+ 45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
+ 45, 45, 45, 45, 45, 46, 46, 46, 46, 46,
+ 46, 47, 48, 48, 49, 49, 50, 50, 51, 52,
+ 53, 53
+};
+
+ /* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN. */
+static const yytype_uint8 yyr2[] =
+{
+ 0, 2, 1, 1, 2, 0, 2, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 3, 2, 4,
+ 6, 1, 2, 4, 6, 0, 1, 2, 1, 2,
+ 1, 1, 2, 2, 3, 1, 2, 1, 2, 2,
+ 2, 3, 5, 3, 3, 2, 4, 2, 3, 1,
+ 3, 2, 1, 1, 2, 2, 1, 2, 2, 1,
+ 2, 2, 1, 2, 2, 1, 2, 2, 1, 2,
+ 2, 2, 2, 1, 1, 2, 2, 2, 2, 2,
+ 2, 1, 1, 1, 1, 1, 1, 1, 1, 2,
+ 0, 2
+};
+
+
+#define yyerrok (yyerrstatus = 0)
+#define yyclearin (yychar = YYEMPTY)
+#define YYEMPTY (-2)
+#define YYEOF 0
+
+#define YYACCEPT goto yyacceptlab
+#define YYABORT goto yyabortlab
+#define YYERROR goto yyerrorlab
+
+
+#define YYRECOVERING() (!!yyerrstatus)
+
+#define YYBACKUP(Token, Value) \
+do \
+ if (yychar == YYEMPTY) \
+ { \
+ yychar = (Token); \
+ yylval = (Value); \
+ YYPOPSTACK (yylen); \
+ yystate = *yyssp; \
+ goto yybackup; \
+ } \
+ else \
+ { \
+ yyerror (pc, YY_("syntax error: cannot back up")); \
+ YYERROR; \
+ } \
+while (0)
+
+/* Error token number */
+#define YYTERROR 1
+#define YYERRCODE 256
+
+
+
+/* Enable debugging if requested. */
+#if YYDEBUG
+
+# ifndef YYFPRINTF
+# include <stdio.h> /* INFRINGES ON USER NAME SPACE */
+# define YYFPRINTF fprintf
+# endif
+
+# define YYDPRINTF(Args) \
+do { \
+ if (yydebug) \
+ YYFPRINTF Args; \
+} while (0)
+
+/* This macro is provided for backward compatibility. */
+#ifndef YY_LOCATION_PRINT
+# define YY_LOCATION_PRINT(File, Loc) ((void) 0)
+#endif
+
+
+# define YY_SYMBOL_PRINT(Title, Type, Value, Location) \
+do { \
+ if (yydebug) \
+ { \
+ YYFPRINTF (stderr, "%s ", Title); \
+ yy_symbol_print (stderr, \
+ Type, Value, pc); \
+ YYFPRINTF (stderr, "\n"); \
+ } \
+} while (0)
+
+
+/*----------------------------------------.
+| Print this symbol's value on YYOUTPUT. |
+`----------------------------------------*/
+
+static void
+yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, parser_control *pc)
+{
+ FILE *yyo = yyoutput;
+ YYUSE (yyo);
+ YYUSE (pc);
+ if (!yyvaluep)
+ return;
+# ifdef YYPRINT
+ if (yytype < YYNTOKENS)
+ YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep);
+# endif
+ YYUSE (yytype);
+}
+
+
+/*--------------------------------.
+| Print this symbol on YYOUTPUT. |
+`--------------------------------*/
+
+static void
+yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, parser_control *pc)
+{
+ YYFPRINTF (yyoutput, "%s %s (",
+ yytype < YYNTOKENS ? "token" : "nterm", yytname[yytype]);
+
+ yy_symbol_value_print (yyoutput, yytype, yyvaluep, pc);
+ YYFPRINTF (yyoutput, ")");
+}
+
+/*------------------------------------------------------------------.
+| yy_stack_print -- Print the state stack from its BOTTOM up to its |
+| TOP (included). |
+`------------------------------------------------------------------*/
+
+static void
+yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop)
+{
+ YYFPRINTF (stderr, "Stack now");
+ for (; yybottom <= yytop; yybottom++)
+ {
+ int yybot = *yybottom;
+ YYFPRINTF (stderr, " %d", yybot);
+ }
+ YYFPRINTF (stderr, "\n");
+}
+
+# define YY_STACK_PRINT(Bottom, Top) \
+do { \
+ if (yydebug) \
+ yy_stack_print ((Bottom), (Top)); \
+} while (0)
+
+
+/*------------------------------------------------.
+| Report that the YYRULE is going to be reduced. |
+`------------------------------------------------*/
+
+static void
+yy_reduce_print (yytype_int16 *yyssp, YYSTYPE *yyvsp, int yyrule, parser_control *pc)
+{
+ unsigned long int yylno = yyrline[yyrule];
+ int yynrhs = yyr2[yyrule];
+ int yyi;
+ YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n",
+ yyrule - 1, yylno);
+ /* The symbols being reduced. */
+ for (yyi = 0; yyi < yynrhs; yyi++)
+ {
+ YYFPRINTF (stderr, " $%d = ", yyi + 1);
+ yy_symbol_print (stderr,
+ yystos[yyssp[yyi + 1 - yynrhs]],
+ &(yyvsp[(yyi + 1) - (yynrhs)])
+ , pc);
+ YYFPRINTF (stderr, "\n");
+ }
+}
+
+# define YY_REDUCE_PRINT(Rule) \
+do { \
+ if (yydebug) \
+ yy_reduce_print (yyssp, yyvsp, Rule, pc); \
+} while (0)
+
+/* Nonzero means print parse trace. It is left uninitialized so that
+ multiple parsers can coexist. */
+int yydebug;
+#else /* !YYDEBUG */
+# define YYDPRINTF(Args)
+# define YY_SYMBOL_PRINT(Title, Type, Value, Location)
+# define YY_STACK_PRINT(Bottom, Top)
+# define YY_REDUCE_PRINT(Rule)
+#endif /* !YYDEBUG */
+
+
+/* YYINITDEPTH -- initial size of the parser's stacks. */
+#ifndef YYINITDEPTH
+# define YYINITDEPTH 200
+#endif
+
+/* YYMAXDEPTH -- maximum size the stacks can grow to (effective only
+ if the built-in stack extension method is used).
+
+ Do not make this value too large; the results are undefined if
+ YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH)
+ evaluated with infinite-precision integer arithmetic. */
+
+#ifndef YYMAXDEPTH
+# define YYMAXDEPTH 10000
+#endif
+
+
+#if YYERROR_VERBOSE
+
+# ifndef yystrlen
+# if defined __GLIBC__ && defined _STRING_H
+# define yystrlen strlen
+# else
+/* Return the length of YYSTR. */
+static YYSIZE_T
+yystrlen (const char *yystr)
+{
+ YYSIZE_T yylen;
+ for (yylen = 0; yystr[yylen]; yylen++)
+ continue;
+ return yylen;
+}
+# endif
+# endif
+
+# ifndef yystpcpy
+# if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE
+# define yystpcpy stpcpy
+# else
+/* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in
+ YYDEST. */
+static char *
+yystpcpy (char *yydest, const char *yysrc)
+{
+ char *yyd = yydest;
+ const char *yys = yysrc;
+
+ while ((*yyd++ = *yys++) != '\0')
+ continue;
+
+ return yyd - 1;
+}
+# endif
+# endif
+
+# ifndef yytnamerr
+/* Copy to YYRES the contents of YYSTR after stripping away unnecessary
+ quotes and backslashes, so that it's suitable for yyerror. The
+ heuristic is that double-quoting is unnecessary unless the string
+ contains an apostrophe, a comma, or backslash (other than
+ backslash-backslash). YYSTR is taken from yytname. If YYRES is
+ null, do not copy; instead, return the length of what the result
+ would have been. */
+static YYSIZE_T
+yytnamerr (char *yyres, const char *yystr)
+{
+ if (*yystr == '"')
+ {
+ YYSIZE_T yyn = 0;
+ char const *yyp = yystr;
+
+ for (;;)
+ switch (*++yyp)
+ {
+ case '\'':
+ case ',':
+ goto do_not_strip_quotes;
+
+ case '\\':
+ if (*++yyp != '\\')
+ goto do_not_strip_quotes;
+ /* Fall through. */
+ default:
+ if (yyres)
+ yyres[yyn] = *yyp;
+ yyn++;
+ break;
+
+ case '"':
+ if (yyres)
+ yyres[yyn] = '\0';
+ return yyn;
+ }
+ do_not_strip_quotes: ;
+ }
+
+ if (! yyres)
+ return yystrlen (yystr);
+
+ return yystpcpy (yyres, yystr) - yyres;
+}
+# endif
+
+/* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message
+ about the unexpected token YYTOKEN for the state stack whose top is
+ YYSSP.
+
+ Return 0 if *YYMSG was successfully written. Return 1 if *YYMSG is
+ not large enough to hold the message. In that case, also set
+ *YYMSG_ALLOC to the required number of bytes. Return 2 if the
+ required number of bytes is too large to store. */
+static int
+yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg,
+ yytype_int16 *yyssp, int yytoken)
+{
+ YYSIZE_T yysize0 = yytnamerr (YY_NULLPTR, yytname[yytoken]);
+ YYSIZE_T yysize = yysize0;
+ enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 };
+ /* Internationalized format string. */
+ const char *yyformat = YY_NULLPTR;
+ /* Arguments of yyformat. */
+ char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM];
+ /* Number of reported tokens (one for the "unexpected", one per
+ "expected"). */
+ int yycount = 0;
+
+ /* There are many possibilities here to consider:
+ - If this state is a consistent state with a default action, then
+ the only way this function was invoked is if the default action
+ is an error action. In that case, don't check for expected
+ tokens because there are none.
+ - The only way there can be no lookahead present (in yychar) is if
+ this state is a consistent state with a default action. Thus,
+ detecting the absence of a lookahead is sufficient to determine
+ that there is no unexpected or expected token to report. In that
+ case, just report a simple "syntax error".
+ - Don't assume there isn't a lookahead just because this state is a
+ consistent state with a default action. There might have been a
+ previous inconsistent state, consistent state with a non-default
+ action, or user semantic action that manipulated yychar.
+ - Of course, the expected token list depends on states to have
+ correct lookahead information, and it depends on the parser not
+ to perform extra reductions after fetching a lookahead from the
+ scanner and before detecting a syntax error. Thus, state merging
+ (from LALR or IELR) and default reductions corrupt the expected
+ token list. However, the list is correct for canonical LR with
+ one exception: it will still contain any token that will not be
+ accepted due to an error action in a later state.
+ */
+ if (yytoken != YYEMPTY)
+ {
+ int yyn = yypact[*yyssp];
+ yyarg[yycount++] = yytname[yytoken];
+ if (!yypact_value_is_default (yyn))
+ {
+ /* Start YYX at -YYN if negative to avoid negative indexes in
+ YYCHECK. In other words, skip the first -YYN actions for
+ this state because they are default actions. */
+ int yyxbegin = yyn < 0 ? -yyn : 0;
+ /* Stay within bounds of both yycheck and yytname. */
+ int yychecklim = YYLAST - yyn + 1;
+ int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS;
+ int yyx;
+
+ for (yyx = yyxbegin; yyx < yyxend; ++yyx)
+ if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR
+ && !yytable_value_is_error (yytable[yyx + yyn]))
+ {
+ if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM)
+ {
+ yycount = 1;
+ yysize = yysize0;
+ break;
+ }
+ yyarg[yycount++] = yytname[yyx];
+ {
+ YYSIZE_T yysize1 = yysize + yytnamerr (YY_NULLPTR, yytname[yyx]);
+ if (! (yysize <= yysize1
+ && yysize1 <= YYSTACK_ALLOC_MAXIMUM))
+ return 2;
+ yysize = yysize1;
+ }
+ }
+ }
+ }
+
+ switch (yycount)
+ {
+# define YYCASE_(N, S) \
+ case N: \
+ yyformat = S; \
+ break
+ YYCASE_(0, YY_("syntax error"));
+ YYCASE_(1, YY_("syntax error, unexpected %s"));
+ YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s"));
+ YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s"));
+ YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s"));
+ YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s"));
+# undef YYCASE_
+ }
+
+ {
+ YYSIZE_T yysize1 = yysize + yystrlen (yyformat);
+ if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM))
+ return 2;
+ yysize = yysize1;
+ }
+
+ if (*yymsg_alloc < yysize)
+ {
+ *yymsg_alloc = 2 * yysize;
+ if (! (yysize <= *yymsg_alloc
+ && *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM))
+ *yymsg_alloc = YYSTACK_ALLOC_MAXIMUM;
+ return 1;
+ }
+
+ /* Avoid sprintf, as that infringes on the user's name space.
+ Don't have undefined behavior even if the translation
+ produced a string with the wrong number of "%s"s. */
+ {
+ char *yyp = *yymsg;
+ int yyi = 0;
+ while ((*yyp = *yyformat) != '\0')
+ if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount)
+ {
+ yyp += yytnamerr (yyp, yyarg[yyi++]);
+ yyformat += 2;
+ }
+ else
+ {
+ yyp++;
+ yyformat++;
+ }
+ }
+ return 0;
+}
+#endif /* YYERROR_VERBOSE */
+
+/*-----------------------------------------------.
+| Release the memory associated to this symbol. |
+`-----------------------------------------------*/
+
+static void
+yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, parser_control *pc)
+{
+ YYUSE (yyvaluep);
+ YYUSE (pc);
+ if (!yymsg)
+ yymsg = "Deleting";
+ YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp);
+
+ YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
+ YYUSE (yytype);
+ YY_IGNORE_MAYBE_UNINITIALIZED_END
+}
+
+
+
+
+/*----------.
+| yyparse. |
+`----------*/
+
+int
+yyparse (parser_control *pc)
+{
+/* The lookahead symbol. */
+int yychar;
+
+
+/* The semantic value of the lookahead symbol. */
+/* Default value used for initialization, for pacifying older GCCs
+ or non-GCC compilers. */
+YY_INITIAL_VALUE (static YYSTYPE yyval_default;)
+YYSTYPE yylval YY_INITIAL_VALUE (= yyval_default);
+
+ /* Number of syntax errors so far. */
+ int yynerrs;
+
+ int yystate;
+ /* Number of tokens to shift before error messages enabled. */
+ int yyerrstatus;
+
+ /* The stacks and their tools:
+ 'yyss': related to states.
+ 'yyvs': related to semantic values.
+
+ Refer to the stacks through separate pointers, to allow yyoverflow
+ to reallocate them elsewhere. */
+
+ /* The state stack. */
+ yytype_int16 yyssa[YYINITDEPTH];
+ yytype_int16 *yyss;
+ yytype_int16 *yyssp;
+
+ /* The semantic value stack. */
+ YYSTYPE yyvsa[YYINITDEPTH];
+ YYSTYPE *yyvs;
+ YYSTYPE *yyvsp;
+
+ YYSIZE_T yystacksize;
+
+ int yyn;
+ int yyresult;
+ /* Lookahead token as an internal (translated) token number. */
+ int yytoken = 0;
+ /* The variables used to return semantic value and location from the
+ action routines. */
+ YYSTYPE yyval;
+
+#if YYERROR_VERBOSE
+ /* Buffer for error messages, and its allocated size. */
+ char yymsgbuf[128];
+ char *yymsg = yymsgbuf;
+ YYSIZE_T yymsg_alloc = sizeof yymsgbuf;
+#endif
+
+#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N))
+
+ /* The number of symbols on the RHS of the reduced rule.
+ Keep to zero when no symbol should be popped. */
+ int yylen = 0;
+
+ yyssp = yyss = yyssa;
+ yyvsp = yyvs = yyvsa;
+ yystacksize = YYINITDEPTH;
+
+ YYDPRINTF ((stderr, "Starting parse\n"));
+
+ yystate = 0;
+ yyerrstatus = 0;
+ yynerrs = 0;
+ yychar = YYEMPTY; /* Cause a token to be read. */
+ goto yysetstate;
+
+/*------------------------------------------------------------.
+| yynewstate -- Push a new state, which is found in yystate. |
+`------------------------------------------------------------*/
+ yynewstate:
+ /* In all cases, when you get here, the value and location stacks
+ have just been pushed. So pushing a state here evens the stacks. */
+ yyssp++;
+
+ yysetstate:
+ *yyssp = yystate;
+
+ if (yyss + yystacksize - 1 <= yyssp)
+ {
+ /* Get the current used size of the three stacks, in elements. */
+ YYSIZE_T yysize = yyssp - yyss + 1;
+
+#ifdef yyoverflow
+ {
+ /* Give user a chance to reallocate the stack. Use copies of
+ these so that the &'s don't force the real ones into
+ memory. */
+ YYSTYPE *yyvs1 = yyvs;
+ yytype_int16 *yyss1 = yyss;
+
+ /* Each stack pointer address is followed by the size of the
+ data in use in that stack, in bytes. This used to be a
+ conditional around just the two extra args, but that might
+ be undefined if yyoverflow is a macro. */
+ yyoverflow (YY_("memory exhausted"),
+ &yyss1, yysize * sizeof (*yyssp),
+ &yyvs1, yysize * sizeof (*yyvsp),
+ &yystacksize);
+
+ yyss = yyss1;
+ yyvs = yyvs1;
+ }
+#else /* no yyoverflow */
+# ifndef YYSTACK_RELOCATE
+ goto yyexhaustedlab;
+# else
+ /* Extend the stack our own way. */
+ if (YYMAXDEPTH <= yystacksize)
+ goto yyexhaustedlab;
+ yystacksize *= 2;
+ if (YYMAXDEPTH < yystacksize)
+ yystacksize = YYMAXDEPTH;
+
+ {
+ yytype_int16 *yyss1 = yyss;
+ union yyalloc *yyptr =
+ (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));
+ if (! yyptr)
+ goto yyexhaustedlab;
+ YYSTACK_RELOCATE (yyss_alloc, yyss);
+ YYSTACK_RELOCATE (yyvs_alloc, yyvs);
+# undef YYSTACK_RELOCATE
+ if (yyss1 != yyssa)
+ YYSTACK_FREE (yyss1);
+ }
+# endif
+#endif /* no yyoverflow */
+
+ yyssp = yyss + yysize - 1;
+ yyvsp = yyvs + yysize - 1;
+
+ YYDPRINTF ((stderr, "Stack size increased to %lu\n",
+ (unsigned long int) yystacksize));
+
+ if (yyss + yystacksize - 1 <= yyssp)
+ YYABORT;
+ }
+
+ YYDPRINTF ((stderr, "Entering state %d\n", yystate));
+
+ if (yystate == YYFINAL)
+ YYACCEPT;
+
+ goto yybackup;
+
+/*-----------.
+| yybackup. |
+`-----------*/
+yybackup:
+
+ /* Do appropriate processing given the current state. Read a
+ lookahead token if we need one and don't already have one. */
+
+ /* First try to decide what to do without reference to lookahead token. */
+ yyn = yypact[yystate];
+ if (yypact_value_is_default (yyn))
+ goto yydefault;
+
+ /* Not known => get a lookahead token if don't already have one. */
+
+ /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */
+ if (yychar == YYEMPTY)
+ {
+ YYDPRINTF ((stderr, "Reading a token: "));
+ yychar = yylex (&yylval, pc);
+ }
+
+ if (yychar <= YYEOF)
+ {
+ yychar = yytoken = YYEOF;
+ YYDPRINTF ((stderr, "Now at end of input.\n"));
+ }
+ else
+ {
+ yytoken = YYTRANSLATE (yychar);
+ YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc);
+ }
+
+ /* If the proper action on seeing token YYTOKEN is to reduce or to
+ detect an error, take that action. */
+ yyn += yytoken;
+ if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken)
+ goto yydefault;
+ yyn = yytable[yyn];
+ if (yyn <= 0)
+ {
+ if (yytable_value_is_error (yyn))
+ goto yyerrlab;
+ yyn = -yyn;
+ goto yyreduce;
+ }
+
+ /* Count tokens shifted since error; after three, turn off error
+ status. */
+ if (yyerrstatus)
+ yyerrstatus--;
+
+ /* Shift the lookahead token. */
+ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc);
+
+ /* Discard the shifted token. */
+ yychar = YYEMPTY;
+
+ yystate = yyn;
+ YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
+ *++yyvsp = yylval;
+ YY_IGNORE_MAYBE_UNINITIALIZED_END
+
+ goto yynewstate;
+
+
+/*-----------------------------------------------------------.
+| yydefault -- do the default action for the current state. |
+`-----------------------------------------------------------*/
+yydefault:
+ yyn = yydefact[yystate];
+ if (yyn == 0)
+ goto yyerrlab;
+ goto yyreduce;
+
+
+/*-----------------------------.
+| yyreduce -- Do a reduction. |
+`-----------------------------*/
+yyreduce:
+ /* yyn is the number of a rule to reduce with. */
+ yylen = yyr2[yyn];
+
+ /* If YYLEN is nonzero, implement the default value of the action:
+ '$$ = $1'.
+
+ Otherwise, the following line sets YYVAL to garbage.
+ This behavior is undocumented and Bison
+ users should not rely upon it. Assigning to YYVAL
+ unconditionally makes the parser a bit smaller, and it avoids a
+ GCC warning that YYVAL may be used uninitialized. */
+ yyval = yyvsp[1-yylen];
+
+
+ YY_REDUCE_PRINT (yyn);
+ switch (yyn)
+ {
+ case 4:
+#line 330 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ {
+ pc->seconds = (yyvsp[0].timespec);
+ pc->timespec_seen = true;
+ }
+#line 1628 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 7:
+#line 343 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { pc->times_seen++; pc->dates_seen++; }
+#line 1634 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 8:
+#line 345 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { pc->times_seen++; }
+#line 1640 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 9:
+#line 347 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { pc->local_zones_seen++; }
+#line 1646 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 10:
+#line 349 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { pc->zones_seen++; }
+#line 1652 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 11:
+#line 351 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { pc->dates_seen++; }
+#line 1658 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 12:
+#line 353 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { pc->days_seen++; }
+#line 1664 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 18:
+#line 369 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ {
+ set_hhmmss (pc, (yyvsp[-1].textintval).value, 0, 0, 0);
+ pc->meridian = (yyvsp[0].intval);
+ }
+#line 1673 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 19:
+#line 374 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ {
+ set_hhmmss (pc, (yyvsp[-3].textintval).value, (yyvsp[-1].textintval).value, 0, 0);
+ pc->meridian = (yyvsp[0].intval);
+ }
+#line 1682 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 20:
+#line 379 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ {
+ set_hhmmss (pc, (yyvsp[-5].textintval).value, (yyvsp[-3].textintval).value, (yyvsp[-1].timespec).tv_sec, (yyvsp[-1].timespec).tv_nsec);
+ pc->meridian = (yyvsp[0].intval);
+ }
+#line 1691 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 22:
+#line 388 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ {
+ set_hhmmss (pc, (yyvsp[-1].textintval).value, 0, 0, 0);
+ pc->meridian = MER24;
+ }
+#line 1700 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 23:
+#line 393 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ {
+ set_hhmmss (pc, (yyvsp[-3].textintval).value, (yyvsp[-1].textintval).value, 0, 0);
+ pc->meridian = MER24;
+ }
+#line 1709 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 24:
+#line 398 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ {
+ set_hhmmss (pc, (yyvsp[-5].textintval).value, (yyvsp[-3].textintval).value, (yyvsp[-1].timespec).tv_sec, (yyvsp[-1].timespec).tv_nsec);
+ pc->meridian = MER24;
+ }
+#line 1718 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 27:
+#line 411 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ {
+ pc->zones_seen++;
+ pc->time_zone = time_zone_hhmm (pc, (yyvsp[-1].textintval), (yyvsp[0].intval));
+ }
+#line 1727 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 28:
+#line 419 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ {
+ pc->local_isdst = (yyvsp[0].intval);
+ pc->dsts_seen += (0 < (yyvsp[0].intval));
+ }
+#line 1736 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 29:
+#line 424 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ {
+ pc->local_isdst = 1;
+ pc->dsts_seen += (0 < (yyvsp[-1].intval)) + 1;
+ }
+#line 1745 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 30:
+#line 434 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { pc->time_zone = (yyvsp[0].intval); }
+#line 1751 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 31:
+#line 436 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { pc->time_zone = HOUR(7); }
+#line 1757 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 32:
+#line 438 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { pc->time_zone = (yyvsp[-1].intval);
+ apply_relative_time (pc, (yyvsp[0].rel), 1); }
+#line 1764 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 33:
+#line 441 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { pc->time_zone = HOUR(7);
+ apply_relative_time (pc, (yyvsp[0].rel), 1); }
+#line 1771 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 34:
+#line 444 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { pc->time_zone = (yyvsp[-2].intval) + time_zone_hhmm (pc, (yyvsp[-1].textintval), (yyvsp[0].intval)); }
+#line 1777 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 35:
+#line 446 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { pc->time_zone = (yyvsp[0].intval) + 60; }
+#line 1783 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 36:
+#line 448 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { pc->time_zone = (yyvsp[-1].intval) + 60; }
+#line 1789 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 37:
+#line 453 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ {
+ pc->day_ordinal = 0;
+ pc->day_number = (yyvsp[0].intval);
+ }
+#line 1798 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 38:
+#line 458 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ {
+ pc->day_ordinal = 0;
+ pc->day_number = (yyvsp[-1].intval);
+ }
+#line 1807 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 39:
+#line 463 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ {
+ pc->day_ordinal = (yyvsp[-1].intval);
+ pc->day_number = (yyvsp[0].intval);
+ }
+#line 1816 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 40:
+#line 468 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ {
+ pc->day_ordinal = (yyvsp[-1].textintval).value;
+ pc->day_number = (yyvsp[0].intval);
+ }
+#line 1825 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 41:
+#line 476 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ {
+ pc->month = (yyvsp[-2].textintval).value;
+ pc->day = (yyvsp[0].textintval).value;
+ }
+#line 1834 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 42:
+#line 481 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ {
+ /* Interpret as YYYY/MM/DD if the first value has 4 or more digits,
+ otherwise as MM/DD/YY.
+ The goal in recognizing YYYY/MM/DD is solely to support legacy
+ machine-generated dates like those in an RCS log listing. If
+ you want portability, use the ISO 8601 format. */
+ if (4 <= (yyvsp[-4].textintval).digits)
+ {
+ pc->year = (yyvsp[-4].textintval);
+ pc->month = (yyvsp[-2].textintval).value;
+ pc->day = (yyvsp[0].textintval).value;
+ }
+ else
+ {
+ pc->month = (yyvsp[-4].textintval).value;
+ pc->day = (yyvsp[-2].textintval).value;
+ pc->year = (yyvsp[0].textintval);
+ }
+ }
+#line 1858 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 43:
+#line 501 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ {
+ /* e.g. 17-JUN-1992. */
+ pc->day = (yyvsp[-2].textintval).value;
+ pc->month = (yyvsp[-1].intval);
+ pc->year.value = -(yyvsp[0].textintval).value;
+ pc->year.digits = (yyvsp[0].textintval).digits;
+ }
+#line 1870 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 44:
+#line 509 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ {
+ /* e.g. JUN-17-1992. */
+ pc->month = (yyvsp[-2].intval);
+ pc->day = -(yyvsp[-1].textintval).value;
+ pc->year.value = -(yyvsp[0].textintval).value;
+ pc->year.digits = (yyvsp[0].textintval).digits;
+ }
+#line 1882 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 45:
+#line 517 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ {
+ pc->month = (yyvsp[-1].intval);
+ pc->day = (yyvsp[0].textintval).value;
+ }
+#line 1891 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 46:
+#line 522 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ {
+ pc->month = (yyvsp[-3].intval);
+ pc->day = (yyvsp[-2].textintval).value;
+ pc->year = (yyvsp[0].textintval);
+ }
+#line 1901 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 47:
+#line 528 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ {
+ pc->day = (yyvsp[-1].textintval).value;
+ pc->month = (yyvsp[0].intval);
+ }
+#line 1910 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 48:
+#line 533 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ {
+ pc->day = (yyvsp[-2].textintval).value;
+ pc->month = (yyvsp[-1].intval);
+ pc->year = (yyvsp[0].textintval);
+ }
+#line 1920 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 50:
+#line 543 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ {
+ /* ISO 8601 format. YYYY-MM-DD. */
+ pc->year = (yyvsp[-2].textintval);
+ pc->month = -(yyvsp[-1].textintval).value;
+ pc->day = -(yyvsp[0].textintval).value;
+ }
+#line 1931 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 51:
+#line 553 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { apply_relative_time (pc, (yyvsp[-1].rel), (yyvsp[0].intval)); }
+#line 1937 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 52:
+#line 555 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { apply_relative_time (pc, (yyvsp[0].rel), 1); }
+#line 1943 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 53:
+#line 557 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { apply_relative_time (pc, (yyvsp[0].rel), 1); }
+#line 1949 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 54:
+#line 562 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).year = (yyvsp[-1].intval); }
+#line 1955 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 55:
+#line 564 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).year = (yyvsp[-1].textintval).value; }
+#line 1961 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 56:
+#line 566 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).year = 1; }
+#line 1967 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 57:
+#line 568 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).month = (yyvsp[-1].intval); }
+#line 1973 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 58:
+#line 570 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).month = (yyvsp[-1].textintval).value; }
+#line 1979 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 59:
+#line 572 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).month = 1; }
+#line 1985 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 60:
+#line 574 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).day = (yyvsp[-1].intval) * (yyvsp[0].intval); }
+#line 1991 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 61:
+#line 576 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).day = (yyvsp[-1].textintval).value * (yyvsp[0].intval); }
+#line 1997 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 62:
+#line 578 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).day = (yyvsp[0].intval); }
+#line 2003 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 63:
+#line 580 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).hour = (yyvsp[-1].intval); }
+#line 2009 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 64:
+#line 582 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).hour = (yyvsp[-1].textintval).value; }
+#line 2015 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 65:
+#line 584 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).hour = 1; }
+#line 2021 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 66:
+#line 586 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).minutes = (yyvsp[-1].intval); }
+#line 2027 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 67:
+#line 588 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).minutes = (yyvsp[-1].textintval).value; }
+#line 2033 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 68:
+#line 590 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).minutes = 1; }
+#line 2039 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 69:
+#line 592 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).seconds = (yyvsp[-1].intval); }
+#line 2045 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 70:
+#line 594 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).seconds = (yyvsp[-1].textintval).value; }
+#line 2051 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 71:
+#line 596 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).seconds = (yyvsp[-1].timespec).tv_sec; (yyval.rel).ns = (yyvsp[-1].timespec).tv_nsec; }
+#line 2057 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 72:
+#line 598 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).seconds = (yyvsp[-1].timespec).tv_sec; (yyval.rel).ns = (yyvsp[-1].timespec).tv_nsec; }
+#line 2063 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 73:
+#line 600 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).seconds = 1; }
+#line 2069 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 75:
+#line 606 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).year = (yyvsp[-1].textintval).value; }
+#line 2075 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 76:
+#line 608 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).month = (yyvsp[-1].textintval).value; }
+#line 2081 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 77:
+#line 610 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).day = (yyvsp[-1].textintval).value * (yyvsp[0].intval); }
+#line 2087 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 78:
+#line 612 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).hour = (yyvsp[-1].textintval).value; }
+#line 2093 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 79:
+#line 614 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).minutes = (yyvsp[-1].textintval).value; }
+#line 2099 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 80:
+#line 616 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).seconds = (yyvsp[-1].textintval).value; }
+#line 2105 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 81:
+#line 621 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).day = (yyvsp[0].intval); }
+#line 2111 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 85:
+#line 629 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { (yyval.timespec).tv_sec = (yyvsp[0].textintval).value; (yyval.timespec).tv_nsec = 0; }
+#line 2117 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 87:
+#line 635 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { (yyval.timespec).tv_sec = (yyvsp[0].textintval).value; (yyval.timespec).tv_nsec = 0; }
+#line 2123 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 88:
+#line 640 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { digits_to_date_time (pc, (yyvsp[0].textintval)); }
+#line 2129 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 89:
+#line 645 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ {
+ /* Hybrid all-digit and relative offset, so that we accept e.g.,
+ "YYYYMMDD +N days" as well as "YYYYMMDD N days". */
+ digits_to_date_time (pc, (yyvsp[-1].textintval));
+ apply_relative_time (pc, (yyvsp[0].rel), 1);
+ }
+#line 2140 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 90:
+#line 655 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { (yyval.intval) = -1; }
+#line 2146 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+ case 91:
+#line 657 "./lib/parse-datetime.y" /* yacc.c:1646 */
+ { (yyval.intval) = (yyvsp[0].textintval).value; }
+#line 2152 "parse-datetime.c" /* yacc.c:1646 */
+ break;
+
+
+#line 2156 "parse-datetime.c" /* yacc.c:1646 */
+ default: break;
+ }
+ /* User semantic actions sometimes alter yychar, and that requires
+ that yytoken be updated with the new translation. We take the
+ approach of translating immediately before every use of yytoken.
+ One alternative is translating here after every semantic action,
+ but that translation would be missed if the semantic action invokes
+ YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or
+ if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an
+ incorrect destructor might then be invoked immediately. In the
+ case of YYERROR or YYBACKUP, subsequent parser actions might lead
+ to an incorrect destructor call or verbose syntax error message
+ before the lookahead is translated. */
+ YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc);
+
+ YYPOPSTACK (yylen);
+ yylen = 0;
+ YY_STACK_PRINT (yyss, yyssp);
+
+ *++yyvsp = yyval;
+
+ /* Now 'shift' the result of the reduction. Determine what state
+ that goes to, based on the state we popped back to and the rule
+ number reduced by. */
+
+ yyn = yyr1[yyn];
+
+ yystate = yypgoto[yyn - YYNTOKENS] + *yyssp;
+ if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp)
+ yystate = yytable[yystate];
+ else
+ yystate = yydefgoto[yyn - YYNTOKENS];
+
+ goto yynewstate;
+
+
+/*--------------------------------------.
+| yyerrlab -- here on detecting error. |
+`--------------------------------------*/
+yyerrlab:
+ /* Make sure we have latest lookahead translation. See comments at
+ user semantic actions for why this is necessary. */
+ yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar);
+
+ /* If not already recovering from an error, report this error. */
+ if (!yyerrstatus)
+ {
+ ++yynerrs;
+#if ! YYERROR_VERBOSE
+ yyerror (pc, YY_("syntax error"));
+#else
+# define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \
+ yyssp, yytoken)
+ {
+ char const *yymsgp = YY_("syntax error");
+ int yysyntax_error_status;
+ yysyntax_error_status = YYSYNTAX_ERROR;
+ if (yysyntax_error_status == 0)
+ yymsgp = yymsg;
+ else if (yysyntax_error_status == 1)
+ {
+ if (yymsg != yymsgbuf)
+ YYSTACK_FREE (yymsg);
+ yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc);
+ if (!yymsg)
+ {
+ yymsg = yymsgbuf;
+ yymsg_alloc = sizeof yymsgbuf;
+ yysyntax_error_status = 2;
+ }
+ else
+ {
+ yysyntax_error_status = YYSYNTAX_ERROR;
+ yymsgp = yymsg;
+ }
+ }
+ yyerror (pc, yymsgp);
+ if (yysyntax_error_status == 2)
+ goto yyexhaustedlab;
+ }
+# undef YYSYNTAX_ERROR
+#endif
+ }
+
+
+
+ if (yyerrstatus == 3)
+ {
+ /* If just tried and failed to reuse lookahead token after an
+ error, discard it. */
+
+ if (yychar <= YYEOF)
+ {
+ /* Return failure if at end of input. */
+ if (yychar == YYEOF)
+ YYABORT;
+ }
+ else
+ {
+ yydestruct ("Error: discarding",
+ yytoken, &yylval, pc);
+ yychar = YYEMPTY;
+ }
+ }
+
+ /* Else will try to reuse lookahead token after shifting the error
+ token. */
+ goto yyerrlab1;
+
+
+/*---------------------------------------------------.
+| yyerrorlab -- error raised explicitly by YYERROR. |
+`---------------------------------------------------*/
+yyerrorlab:
+
+ /* Pacify compilers like GCC when the user code never invokes
+ YYERROR and the label yyerrorlab therefore never appears in user
+ code. */
+ if (/*CONSTCOND*/ 0)
+ goto yyerrorlab;
+
+ /* Do not reclaim the symbols of the rule whose action triggered
+ this YYERROR. */
+ YYPOPSTACK (yylen);
+ yylen = 0;
+ YY_STACK_PRINT (yyss, yyssp);
+ yystate = *yyssp;
+ goto yyerrlab1;
+
+
+/*-------------------------------------------------------------.
+| yyerrlab1 -- common code for both syntax error and YYERROR. |
+`-------------------------------------------------------------*/
+yyerrlab1:
+ yyerrstatus = 3; /* Each real token shifted decrements this. */
+
+ for (;;)
+ {
+ yyn = yypact[yystate];
+ if (!yypact_value_is_default (yyn))
+ {
+ yyn += YYTERROR;
+ if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR)
+ {
+ yyn = yytable[yyn];
+ if (0 < yyn)
+ break;
+ }
+ }
+
+ /* Pop the current state because it cannot handle the error token. */
+ if (yyssp == yyss)
+ YYABORT;
+
+
+ yydestruct ("Error: popping",
+ yystos[yystate], yyvsp, pc);
+ YYPOPSTACK (1);
+ yystate = *yyssp;
+ YY_STACK_PRINT (yyss, yyssp);
+ }
+
+ YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
+ *++yyvsp = yylval;
+ YY_IGNORE_MAYBE_UNINITIALIZED_END
+
+
+ /* Shift the error token. */
+ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp);
+
+ yystate = yyn;
+ goto yynewstate;
+
+
+/*-------------------------------------.
+| yyacceptlab -- YYACCEPT comes here. |
+`-------------------------------------*/
+yyacceptlab:
+ yyresult = 0;
+ goto yyreturn;
+
+/*-----------------------------------.
+| yyabortlab -- YYABORT comes here. |
+`-----------------------------------*/
+yyabortlab:
+ yyresult = 1;
+ goto yyreturn;
+
+#if !defined yyoverflow || YYERROR_VERBOSE
+/*-------------------------------------------------.
+| yyexhaustedlab -- memory exhaustion comes here. |
+`-------------------------------------------------*/
+yyexhaustedlab:
+ yyerror (pc, YY_("memory exhausted"));
+ yyresult = 2;
+ /* Fall through. */
+#endif
+
+yyreturn:
+ if (yychar != YYEMPTY)
+ {
+ /* Make sure we have latest lookahead translation. See comments at
+ user semantic actions for why this is necessary. */
+ yytoken = YYTRANSLATE (yychar);
+ yydestruct ("Cleanup: discarding lookahead",
+ yytoken, &yylval, pc);
+ }
+ /* Do not reclaim the symbols of the rule whose action triggered
+ this YYABORT or YYACCEPT. */
+ YYPOPSTACK (yylen);
+ YY_STACK_PRINT (yyss, yyssp);
+ while (yyssp != yyss)
+ {
+ yydestruct ("Cleanup: popping",
+ yystos[*yyssp], yyvsp, pc);
+ YYPOPSTACK (1);
+ }
+#ifndef yyoverflow
+ if (yyss != yyssa)
+ YYSTACK_FREE (yyss);
+#endif
+#if YYERROR_VERBOSE
+ if (yymsg != yymsgbuf)
+ YYSTACK_FREE (yymsg);
+#endif
+ return yyresult;
+}
+#line 660 "./lib/parse-datetime.y" /* yacc.c:1906 */
+
+
+static table const meridian_table[] =
+{
+ { "AM", tMERIDIAN, MERam },
+ { "A.M.", tMERIDIAN, MERam },
+ { "PM", tMERIDIAN, MERpm },
+ { "P.M.", tMERIDIAN, MERpm },
+ { NULL, 0, 0 }
+};
+
+static table const dst_table[] =
+{
+ { "DST", tDST, 0 }
+};
+
+static table const month_and_day_table[] =
+{
+ { "JANUARY", tMONTH, 1 },
+ { "FEBRUARY", tMONTH, 2 },
+ { "MARCH", tMONTH, 3 },
+ { "APRIL", tMONTH, 4 },
+ { "MAY", tMONTH, 5 },
+ { "JUNE", tMONTH, 6 },
+ { "JULY", tMONTH, 7 },
+ { "AUGUST", tMONTH, 8 },
+ { "SEPTEMBER",tMONTH, 9 },
+ { "SEPT", tMONTH, 9 },
+ { "OCTOBER", tMONTH, 10 },
+ { "NOVEMBER", tMONTH, 11 },
+ { "DECEMBER", tMONTH, 12 },
+ { "SUNDAY", tDAY, 0 },
+ { "MONDAY", tDAY, 1 },
+ { "TUESDAY", tDAY, 2 },
+ { "TUES", tDAY, 2 },
+ { "WEDNESDAY",tDAY, 3 },
+ { "WEDNES", tDAY, 3 },
+ { "THURSDAY", tDAY, 4 },
+ { "THUR", tDAY, 4 },
+ { "THURS", tDAY, 4 },
+ { "FRIDAY", tDAY, 5 },
+ { "SATURDAY", tDAY, 6 },
+ { NULL, 0, 0 }
+};
+
+static table const time_units_table[] =
+{
+ { "YEAR", tYEAR_UNIT, 1 },
+ { "MONTH", tMONTH_UNIT, 1 },
+ { "FORTNIGHT",tDAY_UNIT, 14 },
+ { "WEEK", tDAY_UNIT, 7 },
+ { "DAY", tDAY_UNIT, 1 },
+ { "HOUR", tHOUR_UNIT, 1 },
+ { "MINUTE", tMINUTE_UNIT, 1 },
+ { "MIN", tMINUTE_UNIT, 1 },
+ { "SECOND", tSEC_UNIT, 1 },
+ { "SEC", tSEC_UNIT, 1 },
+ { NULL, 0, 0 }
+};
+
+/* Assorted relative-time words. */
+static table const relative_time_table[] =
+{
+ { "TOMORROW", tDAY_SHIFT, 1 },
+ { "YESTERDAY",tDAY_SHIFT, -1 },
+ { "TODAY", tDAY_SHIFT, 0 },
+ { "NOW", tDAY_SHIFT, 0 },
+ { "LAST", tORDINAL, -1 },
+ { "THIS", tORDINAL, 0 },
+ { "NEXT", tORDINAL, 1 },
+ { "FIRST", tORDINAL, 1 },
+/*{ "SECOND", tORDINAL, 2 }, */
+ { "THIRD", tORDINAL, 3 },
+ { "FOURTH", tORDINAL, 4 },
+ { "FIFTH", tORDINAL, 5 },
+ { "SIXTH", tORDINAL, 6 },
+ { "SEVENTH", tORDINAL, 7 },
+ { "EIGHTH", tORDINAL, 8 },
+ { "NINTH", tORDINAL, 9 },
+ { "TENTH", tORDINAL, 10 },
+ { "ELEVENTH", tORDINAL, 11 },
+ { "TWELFTH", tORDINAL, 12 },
+ { "AGO", tAGO, -1 },
+ { "HENCE", tAGO, 1 },
+ { NULL, 0, 0 }
+};
+
+/* The universal time zone table. These labels can be used even for
+ time stamps that would not otherwise be valid, e.g., GMT time
+ stamps in London during summer. */
+static table const universal_time_zone_table[] =
+{
+ { "GMT", tZONE, HOUR ( 0) }, /* Greenwich Mean */
+ { "UT", tZONE, HOUR ( 0) }, /* Universal (Coordinated) */
+ { "UTC", tZONE, HOUR ( 0) },
+ { NULL, 0, 0 }
+};
+
+/* The time zone table. This table is necessarily incomplete, as time
+ zone abbreviations are ambiguous; e.g. Australians interpret "EST"
+ as Eastern time in Australia, not as US Eastern Standard Time.
+ You cannot rely on parse_datetime to handle arbitrary time zone
+ abbreviations; use numeric abbreviations like "-0500" instead. */
+static table const time_zone_table[] =
+{
+ { "WET", tZONE, HOUR ( 0) }, /* Western European */
+ { "WEST", tDAYZONE, HOUR ( 0) }, /* Western European Summer */
+ { "BST", tDAYZONE, HOUR ( 0) }, /* British Summer */
+ { "ART", tZONE, -HOUR ( 3) }, /* Argentina */
+ { "BRT", tZONE, -HOUR ( 3) }, /* Brazil */
+ { "BRST", tDAYZONE, -HOUR ( 3) }, /* Brazil Summer */
+ { "NST", tZONE, -(HOUR ( 3) + 30) }, /* Newfoundland Standard */
+ { "NDT", tDAYZONE,-(HOUR ( 3) + 30) }, /* Newfoundland Daylight */
+ { "AST", tZONE, -HOUR ( 4) }, /* Atlantic Standard */
+ { "ADT", tDAYZONE, -HOUR ( 4) }, /* Atlantic Daylight */
+ { "CLT", tZONE, -HOUR ( 4) }, /* Chile */
+ { "CLST", tDAYZONE, -HOUR ( 4) }, /* Chile Summer */
+ { "EST", tZONE, -HOUR ( 5) }, /* Eastern Standard */
+ { "EDT", tDAYZONE, -HOUR ( 5) }, /* Eastern Daylight */
+ { "CST", tZONE, -HOUR ( 6) }, /* Central Standard */
+ { "CDT", tDAYZONE, -HOUR ( 6) }, /* Central Daylight */
+ { "MST", tZONE, -HOUR ( 7) }, /* Mountain Standard */
+ { "MDT", tDAYZONE, -HOUR ( 7) }, /* Mountain Daylight */
+ { "PST", tZONE, -HOUR ( 8) }, /* Pacific Standard */
+ { "PDT", tDAYZONE, -HOUR ( 8) }, /* Pacific Daylight */
+ { "AKST", tZONE, -HOUR ( 9) }, /* Alaska Standard */
+ { "AKDT", tDAYZONE, -HOUR ( 9) }, /* Alaska Daylight */
+ { "HST", tZONE, -HOUR (10) }, /* Hawaii Standard */
+ { "HAST", tZONE, -HOUR (10) }, /* Hawaii-Aleutian Standard */
+ { "HADT", tDAYZONE, -HOUR (10) }, /* Hawaii-Aleutian Daylight */
+ { "SST", tZONE, -HOUR (12) }, /* Samoa Standard */
+ { "WAT", tZONE, HOUR ( 1) }, /* West Africa */
+ { "CET", tZONE, HOUR ( 1) }, /* Central European */
+ { "CEST", tDAYZONE, HOUR ( 1) }, /* Central European Summer */
+ { "MET", tZONE, HOUR ( 1) }, /* Middle European */
+ { "MEZ", tZONE, HOUR ( 1) }, /* Middle European */
+ { "MEST", tDAYZONE, HOUR ( 1) }, /* Middle European Summer */
+ { "MESZ", tDAYZONE, HOUR ( 1) }, /* Middle European Summer */
+ { "EET", tZONE, HOUR ( 2) }, /* Eastern European */
+ { "EEST", tDAYZONE, HOUR ( 2) }, /* Eastern European Summer */
+ { "CAT", tZONE, HOUR ( 2) }, /* Central Africa */
+ { "SAST", tZONE, HOUR ( 2) }, /* South Africa Standard */
+ { "EAT", tZONE, HOUR ( 3) }, /* East Africa */
+ { "MSK", tZONE, HOUR ( 3) }, /* Moscow */
+ { "MSD", tDAYZONE, HOUR ( 3) }, /* Moscow Daylight */
+ { "IST", tZONE, (HOUR ( 5) + 30) }, /* India Standard */
+ { "SGT", tZONE, HOUR ( 8) }, /* Singapore */
+ { "KST", tZONE, HOUR ( 9) }, /* Korea Standard */
+ { "JST", tZONE, HOUR ( 9) }, /* Japan Standard */
+ { "GST", tZONE, HOUR (10) }, /* Guam Standard */
+ { "NZST", tZONE, HOUR (12) }, /* New Zealand Standard */
+ { "NZDT", tDAYZONE, HOUR (12) }, /* New Zealand Daylight */
+ { NULL, 0, 0 }
+};
+
+/* Military time zone table.
+
+ Note 'T' is a special case, as it is used as the separator in ISO
+ 8601 date and time of day representation. */
+static table const military_table[] =
+{
+ { "A", tZONE, -HOUR ( 1) },
+ { "B", tZONE, -HOUR ( 2) },
+ { "C", tZONE, -HOUR ( 3) },
+ { "D", tZONE, -HOUR ( 4) },
+ { "E", tZONE, -HOUR ( 5) },
+ { "F", tZONE, -HOUR ( 6) },
+ { "G", tZONE, -HOUR ( 7) },
+ { "H", tZONE, -HOUR ( 8) },
+ { "I", tZONE, -HOUR ( 9) },
+ { "K", tZONE, -HOUR (10) },
+ { "L", tZONE, -HOUR (11) },
+ { "M", tZONE, -HOUR (12) },
+ { "N", tZONE, HOUR ( 1) },
+ { "O", tZONE, HOUR ( 2) },
+ { "P", tZONE, HOUR ( 3) },
+ { "Q", tZONE, HOUR ( 4) },
+ { "R", tZONE, HOUR ( 5) },
+ { "S", tZONE, HOUR ( 6) },
+ { "T", 'T', 0 },
+ { "U", tZONE, HOUR ( 8) },
+ { "V", tZONE, HOUR ( 9) },
+ { "W", tZONE, HOUR (10) },
+ { "X", tZONE, HOUR (11) },
+ { "Y", tZONE, HOUR (12) },
+ { "Z", tZONE, HOUR ( 0) },
+ { NULL, 0, 0 }
+};
+
+
+
+/* Convert a time zone expressed as HH:MM into an integer count of
+ minutes. If MM is negative, then S is of the form HHMM and needs
+ to be picked apart; otherwise, S is of the form HH. As specified in
+ http://www.opengroup.org/susv3xbd/xbd_chap08.html#tag_08_03, allow
+ only valid TZ range, and consider first two digits as hours, if no
+ minutes specified. */
+
+static long int
+time_zone_hhmm (parser_control *pc, textint s, long int mm)
+{
+ long int n_minutes;
+
+ /* If the length of S is 1 or 2 and no minutes are specified,
+ interpret it as a number of hours. */
+ if (s.digits <= 2 && mm < 0)
+ s.value *= 100;
+
+ if (mm < 0)
+ n_minutes = (s.value / 100) * 60 + s.value % 100;
+ else
+ n_minutes = s.value * 60 + (s.negative ? -mm : mm);
+
+ /* If the absolute number of minutes is larger than 24 hours,
+ arrange to reject it by incrementing pc->zones_seen. Thus,
+ we allow only values in the range UTC-24:00 to UTC+24:00. */
+ if (24 * 60 < abs (n_minutes))
+ pc->zones_seen++;
+
+ return n_minutes;
+}
+
+static int
+to_hour (long int hours, int meridian)
+{
+ switch (meridian)
+ {
+ default: /* Pacify GCC. */
+ case MER24:
+ return 0 <= hours && hours < 24 ? hours : -1;
+ case MERam:
+ return 0 < hours && hours < 12 ? hours : hours == 12 ? 0 : -1;
+ case MERpm:
+ return 0 < hours && hours < 12 ? hours + 12 : hours == 12 ? 12 : -1;
+ }
+}
+
+static long int
+to_year (textint textyear)
+{
+ long int year = textyear.value;
+
+ if (year < 0)
+ year = -year;
+
+ /* XPG4 suggests that years 00-68 map to 2000-2068, and
+ years 69-99 map to 1969-1999. */
+ else if (textyear.digits == 2)
+ year += year < 69 ? 2000 : 1900;
+
+ return year;
+}
+
+static table const * _GL_ATTRIBUTE_PURE
+lookup_zone (parser_control const *pc, char const *name)
+{
+ table const *tp;
+
+ for (tp = universal_time_zone_table; tp->name; tp++)
+ if (strcmp (name, tp->name) == 0)
+ return tp;
+
+ /* Try local zone abbreviations before those in time_zone_table, as
+ the local ones are more likely to be right. */
+ for (tp = pc->local_time_zone_table; tp->name; tp++)
+ if (strcmp (name, tp->name) == 0)
+ return tp;
+
+ for (tp = time_zone_table; tp->name; tp++)
+ if (strcmp (name, tp->name) == 0)
+ return tp;
+
+ return NULL;
+}
+
+#if ! HAVE_TM_GMTOFF
+/* Yield the difference between *A and *B,
+ measured in seconds, ignoring leap seconds.
+ The body of this function is taken directly from the GNU C Library;
+ see src/strftime.c. */
+static long int
+tm_diff (struct tm const *a, struct tm const *b)
+{
+ /* Compute intervening leap days correctly even if year is negative.
+ Take care to avoid int overflow in leap day calculations. */
+ int a4 = SHR (a->tm_year, 2) + SHR (TM_YEAR_BASE, 2) - ! (a->tm_year & 3);
+ int b4 = SHR (b->tm_year, 2) + SHR (TM_YEAR_BASE, 2) - ! (b->tm_year & 3);
+ int a100 = a4 / 25 - (a4 % 25 < 0);
+ int b100 = b4 / 25 - (b4 % 25 < 0);
+ int a400 = SHR (a100, 2);
+ int b400 = SHR (b100, 2);
+ int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
+ long int ayear = a->tm_year;
+ long int years = ayear - b->tm_year;
+ long int days = (365 * years + intervening_leap_days
+ + (a->tm_yday - b->tm_yday));
+ return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
+ + (a->tm_min - b->tm_min))
+ + (a->tm_sec - b->tm_sec));
+}
+#endif /* ! HAVE_TM_GMTOFF */
+
+static table const *
+lookup_word (parser_control const *pc, char *word)
+{
+ char *p;
+ char *q;
+ size_t wordlen;
+ table const *tp;
+ bool period_found;
+ bool abbrev;
+
+ /* Make it uppercase. */
+ for (p = word; *p; p++)
+ {
+ unsigned char ch = *p;
+ *p = c_toupper (ch);
+ }
+
+ for (tp = meridian_table; tp->name; tp++)
+ if (strcmp (word, tp->name) == 0)
+ return tp;
+
+ /* See if we have an abbreviation for a month. */
+ wordlen = strlen (word);
+ abbrev = wordlen == 3 || (wordlen == 4 && word[3] == '.');
+
+ for (tp = month_and_day_table; tp->name; tp++)
+ if ((abbrev ? strncmp (word, tp->name, 3) : strcmp (word, tp->name)) == 0)
+ return tp;
+
+ if ((tp = lookup_zone (pc, word)))
+ return tp;
+
+ if (strcmp (word, dst_table[0].name) == 0)
+ return dst_table;
+
+ for (tp = time_units_table; tp->name; tp++)
+ if (strcmp (word, tp->name) == 0)
+ return tp;
+
+ /* Strip off any plural and try the units table again. */
+ if (word[wordlen - 1] == 'S')
+ {
+ word[wordlen - 1] = '\0';
+ for (tp = time_units_table; tp->name; tp++)
+ if (strcmp (word, tp->name) == 0)
+ return tp;
+ word[wordlen - 1] = 'S'; /* For "this" in relative_time_table. */
+ }
+
+ for (tp = relative_time_table; tp->name; tp++)
+ if (strcmp (word, tp->name) == 0)
+ return tp;
+
+ /* Military time zones. */
+ if (wordlen == 1)
+ for (tp = military_table; tp->name; tp++)
+ if (word[0] == tp->name[0])
+ return tp;
+
+ /* Drop out any periods and try the time zone table again. */
+ for (period_found = false, p = q = word; (*p = *q); q++)
+ if (*q == '.')
+ period_found = true;
+ else
+ p++;
+ if (period_found && (tp = lookup_zone (pc, word)))
+ return tp;
+
+ return NULL;
+}
+
+static int
+yylex (union YYSTYPE *lvalp, parser_control *pc)
+{
+ unsigned char c;
+ size_t count;
+
+ for (;;)
+ {
+ while (c = *pc->input, c_isspace (c))
+ pc->input++;
+
+ if (ISDIGIT (c) || c == '-' || c == '+')
+ {
+ char const *p;
+ int sign;
+ unsigned long int value;
+ if (c == '-' || c == '+')
+ {
+ sign = c == '-' ? -1 : 1;
+ while (c = *++pc->input, c_isspace (c))
+ continue;
+ if (! ISDIGIT (c))
+ /* skip the '-' sign */
+ continue;
+ }
+ else
+ sign = 0;
+ p = pc->input;
+ for (value = 0; ; value *= 10)
+ {
+ unsigned long int value1 = value + (c - '0');
+ if (value1 < value)
+ return '?';
+ value = value1;
+ c = *++p;
+ if (! ISDIGIT (c))
+ break;
+ if (ULONG_MAX / 10 < value)
+ return '?';
+ }
+ if ((c == '.' || c == ',') && ISDIGIT (p[1]))
+ {
+ time_t s;
+ int ns;
+ int digits;
+ unsigned long int value1;
+
+ /* Check for overflow when converting value to time_t. */
+ if (sign < 0)
+ {
+ s = - value;
+ if (0 < s)
+ return '?';
+ value1 = -s;
+ }
+ else
+ {
+ s = value;
+ if (s < 0)
+ return '?';
+ value1 = s;
+ }
+ if (value != value1)
+ return '?';
+
+ /* Accumulate fraction, to ns precision. */
+ p++;
+ ns = *p++ - '0';
+ for (digits = 2; digits <= LOG10_BILLION; digits++)
+ {
+ ns *= 10;
+ if (ISDIGIT (*p))
+ ns += *p++ - '0';
+ }
+
+ /* Skip excess digits, truncating toward -Infinity. */
+ if (sign < 0)
+ for (; ISDIGIT (*p); p++)
+ if (*p != '0')
+ {
+ ns++;
+ break;
+ }
+ while (ISDIGIT (*p))
+ p++;
+
+ /* Adjust to the timespec convention, which is that
+ tv_nsec is always a positive offset even if tv_sec is
+ negative. */
+ if (sign < 0 && ns)
+ {
+ s--;
+ if (! (s < 0))
+ return '?';
+ ns = BILLION - ns;
+ }
+
+ lvalp->timespec.tv_sec = s;
+ lvalp->timespec.tv_nsec = ns;
+ pc->input = p;
+ return sign ? tSDECIMAL_NUMBER : tUDECIMAL_NUMBER;
+ }
+ else
+ {
+ lvalp->textintval.negative = sign < 0;
+ if (sign < 0)
+ {
+ lvalp->textintval.value = - value;
+ if (0 < lvalp->textintval.value)
+ return '?';
+ }
+ else
+ {
+ lvalp->textintval.value = value;
+ if (lvalp->textintval.value < 0)
+ return '?';
+ }
+ lvalp->textintval.digits = p - pc->input;
+ pc->input = p;
+ return sign ? tSNUMBER : tUNUMBER;
+ }
+ }
+
+ if (c_isalpha (c))
+ {
+ char buff[20];
+ char *p = buff;
+ table const *tp;
+
+ do
+ {
+ if (p < buff + sizeof buff - 1)
+ *p++ = c;
+ c = *++pc->input;
+ }
+ while (c_isalpha (c) || c == '.');
+
+ *p = '\0';
+ tp = lookup_word (pc, buff);
+ if (! tp)
+ return '?';
+ lvalp->intval = tp->value;
+ return tp->type;
+ }
+
+ if (c != '(')
+ return to_uchar (*pc->input++);
+
+ count = 0;
+ do
+ {
+ c = *pc->input++;
+ if (c == '\0')
+ return c;
+ if (c == '(')
+ count++;
+ else if (c == ')')
+ count--;
+ }
+ while (count != 0);
+ }
+}
+
+/* Do nothing if the parser reports an error. */
+static int
+yyerror (parser_control const *pc _GL_UNUSED,
+ char const *s _GL_UNUSED)
+{
+ return 0;
+}
+
+/* If *TM0 is the old and *TM1 is the new value of a struct tm after
+ passing it to mktime, return true if it's OK that mktime returned T.
+ It's not OK if *TM0 has out-of-range members. */
+
+static bool
+mktime_ok (struct tm const *tm0, struct tm const *tm1, time_t t)
+{
+ if (t == (time_t) -1)
+ {
+ /* Guard against falsely reporting an error when parsing a time
+ stamp that happens to equal (time_t) -1, on a host that
+ supports such a time stamp. */
+ tm1 = localtime (&t);
+ if (!tm1)
+ return false;
+ }
+
+ return ! ((tm0->tm_sec ^ tm1->tm_sec)
+ | (tm0->tm_min ^ tm1->tm_min)
+ | (tm0->tm_hour ^ tm1->tm_hour)
+ | (tm0->tm_mday ^ tm1->tm_mday)
+ | (tm0->tm_mon ^ tm1->tm_mon)
+ | (tm0->tm_year ^ tm1->tm_year));
+}
+
+/* A reasonable upper bound for the size of ordinary TZ strings.
+ Use heap allocation if TZ's length exceeds this. */
+enum { TZBUFSIZE = 100 };
+
+/* Return a copy of TZ, stored in TZBUF if it fits, and heap-allocated
+ otherwise. */
+static char *
+get_tz (char tzbuf[TZBUFSIZE])
+{
+ char *tz = getenv ("TZ");
+ if (tz)
+ {
+ size_t tzsize = strlen (tz) + 1;
+ tz = (tzsize <= TZBUFSIZE
+ ? memcpy (tzbuf, tz, tzsize)
+ : xmemdup (tz, tzsize));
+ }
+ return tz;
+}
+
+/* Parse a date/time string, storing the resulting time value into *RESULT.
+ The string itself is pointed to by P. Return true if successful.
+ P can be an incomplete or relative time specification; if so, use
+ *NOW as the basis for the returned time. */
+bool
+parse_datetime (struct timespec *result, char const *p,
+ struct timespec const *now)
+{
+ time_t Start;
+ long int Start_ns;
+ struct tm const *tmp;
+ struct tm tm;
+ struct tm tm0;
+ parser_control pc;
+ struct timespec gettime_buffer;
+ unsigned char c;
+ bool tz_was_altered = false;
+ char *tz0 = NULL;
+ char tz0buf[TZBUFSIZE];
+ bool ok = true;
+
+ if (! now)
+ {
+ gettime (&gettime_buffer);
+ now = &gettime_buffer;
+ }
+
+ Start = now->tv_sec;
+ Start_ns = now->tv_nsec;
+
+ tmp = localtime (&now->tv_sec);
+ if (! tmp)
+ return false;
+
+ while (c = *p, c_isspace (c))
+ p++;
+
+ if (strncmp (p, "TZ=\"", 4) == 0)
+ {
+ char const *tzbase = p + 4;
+ size_t tzsize = 1;
+ char const *s;
+
+ for (s = tzbase; *s; s++, tzsize++)
+ if (*s == '\\')
+ {
+ s++;
+ if (! (*s == '\\' || *s == '"'))
+ break;
+ }
+ else if (*s == '"')
+ {
+ char *z;
+ char *tz1;
+ char tz1buf[TZBUFSIZE];
+ bool large_tz = TZBUFSIZE < tzsize;
+ bool setenv_ok;
+ tz0 = get_tz (tz0buf);
+ z = tz1 = large_tz ? xmalloc (tzsize) : tz1buf;
+ for (s = tzbase; *s != '"'; s++)
+ *z++ = *(s += *s == '\\');
+ *z = '\0';
+ setenv_ok = setenv ("TZ", tz1, 1) == 0;
+ if (large_tz)
+ free (tz1);
+ if (!setenv_ok)
+ goto fail;
+ tz_was_altered = true;
+
+ p = s + 1;
+ while (c = *p, c_isspace (c))
+ p++;
+
+ break;
+ }
+ }
+
+ /* As documented, be careful to treat the empty string just like
+ a date string of "0". Without this, an empty string would be
+ declared invalid when parsed during a DST transition. */
+ if (*p == '\0')
+ p = "0";
+
+ pc.input = p;
+ pc.year.value = tmp->tm_year;
+ pc.year.value += TM_YEAR_BASE;
+ pc.year.digits = 0;
+ pc.month = tmp->tm_mon + 1;
+ pc.day = tmp->tm_mday;
+ pc.hour = tmp->tm_hour;
+ pc.minutes = tmp->tm_min;
+ pc.seconds.tv_sec = tmp->tm_sec;
+ pc.seconds.tv_nsec = Start_ns;
+ tm.tm_isdst = tmp->tm_isdst;
+
+ pc.meridian = MER24;
+ pc.rel = RELATIVE_TIME_0;
+ pc.timespec_seen = false;
+ pc.rels_seen = false;
+ pc.dates_seen = 0;
+ pc.days_seen = 0;
+ pc.times_seen = 0;
+ pc.local_zones_seen = 0;
+ pc.dsts_seen = 0;
+ pc.zones_seen = 0;
+
+#if HAVE_STRUCT_TM_TM_ZONE
+ pc.local_time_zone_table[0].name = tmp->tm_zone;
+ pc.local_time_zone_table[0].type = tLOCAL_ZONE;
+ pc.local_time_zone_table[0].value = tmp->tm_isdst;
+ pc.local_time_zone_table[1].name = NULL;
+
+ /* Probe the names used in the next three calendar quarters, looking
+ for a tm_isdst different from the one we already have. */
+ {
+ int quarter;
+ for (quarter = 1; quarter <= 3; quarter++)
+ {
+ time_t probe = Start + quarter * (90 * 24 * 60 * 60);
+ struct tm const *probe_tm = localtime (&probe);
+ if (probe_tm && probe_tm->tm_zone
+ && probe_tm->tm_isdst != pc.local_time_zone_table[0].value)
+ {
+ {
+ pc.local_time_zone_table[1].name = probe_tm->tm_zone;
+ pc.local_time_zone_table[1].type = tLOCAL_ZONE;
+ pc.local_time_zone_table[1].value = probe_tm->tm_isdst;
+ pc.local_time_zone_table[2].name = NULL;
+ }
+ break;
+ }
+ }
+ }
+#else
+#if HAVE_TZNAME
+ {
+# if !HAVE_DECL_TZNAME
+ extern char *tzname[];
+# endif
+ int i;
+ for (i = 0; i < 2; i++)
+ {
+ pc.local_time_zone_table[i].name = tzname[i];
+ pc.local_time_zone_table[i].type = tLOCAL_ZONE;
+ pc.local_time_zone_table[i].value = i;
+ }
+ pc.local_time_zone_table[i].name = NULL;
+ }
+#else
+ pc.local_time_zone_table[0].name = NULL;
+#endif
+#endif
+
+ if (pc.local_time_zone_table[0].name && pc.local_time_zone_table[1].name
+ && ! strcmp (pc.local_time_zone_table[0].name,
+ pc.local_time_zone_table[1].name))
+ {
+ /* This locale uses the same abbreviation for standard and
+ daylight times. So if we see that abbreviation, we don't
+ know whether it's daylight time. */
+ pc.local_time_zone_table[0].value = -1;
+ pc.local_time_zone_table[1].name = NULL;
+ }
+
+ if (yyparse (&pc) != 0)
+ goto fail;
+
+ if (pc.timespec_seen)
+ *result = pc.seconds;
+ else
+ {
+ if (1 < (pc.times_seen | pc.dates_seen | pc.days_seen | pc.dsts_seen
+ | (pc.local_zones_seen + pc.zones_seen)))
+ goto fail;
+
+ tm.tm_year = to_year (pc.year) - TM_YEAR_BASE;
+ tm.tm_mon = pc.month - 1;
+ tm.tm_mday = pc.day;
+ if (pc.times_seen || (pc.rels_seen && ! pc.dates_seen && ! pc.days_seen))
+ {
+ tm.tm_hour = to_hour (pc.hour, pc.meridian);
+ if (tm.tm_hour < 0)
+ goto fail;
+ tm.tm_min = pc.minutes;
+ tm.tm_sec = pc.seconds.tv_sec;
+ }
+ else
+ {
+ tm.tm_hour = tm.tm_min = tm.tm_sec = 0;
+ pc.seconds.tv_nsec = 0;
+ }
+
+ /* Let mktime deduce tm_isdst if we have an absolute time stamp. */
+ if (pc.dates_seen | pc.days_seen | pc.times_seen)
+ tm.tm_isdst = -1;
+
+ /* But if the input explicitly specifies local time with or without
+ DST, give mktime that information. */
+ if (pc.local_zones_seen)
+ tm.tm_isdst = pc.local_isdst;
+
+ tm0 = tm;
+
+ Start = mktime (&tm);
+
+ if (! mktime_ok (&tm0, &tm, Start))
+ {
+ if (! pc.zones_seen)
+ goto fail;
+ else
+ {
+ /* Guard against falsely reporting errors near the time_t
+ boundaries when parsing times in other time zones. For
+ example, suppose the input string "1969-12-31 23:00:00 -0100",
+ the current time zone is 8 hours ahead of UTC, and the min
+ time_t value is 1970-01-01 00:00:00 UTC. Then the min
+ localtime value is 1970-01-01 08:00:00, and mktime will
+ therefore fail on 1969-12-31 23:00:00. To work around the
+ problem, set the time zone to 1 hour behind UTC temporarily
+ by setting TZ="XXX1:00" and try mktime again. */
+
+ long int time_zone = pc.time_zone;
+ long int abs_time_zone = time_zone < 0 ? - time_zone : time_zone;
+ long int abs_time_zone_hour = abs_time_zone / 60;
+ int abs_time_zone_min = abs_time_zone % 60;
+ char tz1buf[sizeof "XXX+0:00"
+ + sizeof pc.time_zone * CHAR_BIT / 3];
+ if (!tz_was_altered)
+ tz0 = get_tz (tz0buf);
+ sprintf (tz1buf, "XXX%s%ld:%02d", &"-"[time_zone < 0],
+ abs_time_zone_hour, abs_time_zone_min);
+ if (setenv ("TZ", tz1buf, 1) != 0)
+ goto fail;
+ tz_was_altered = true;
+ tm = tm0;
+ Start = mktime (&tm);
+ if (! mktime_ok (&tm0, &tm, Start))
+ goto fail;
+ }
+ }
+
+ if (pc.days_seen && ! pc.dates_seen)
+ {
+ tm.tm_mday += ((pc.day_number - tm.tm_wday + 7) % 7
+ + 7 * (pc.day_ordinal
+ - (0 < pc.day_ordinal
+ && tm.tm_wday != pc.day_number)));
+ tm.tm_isdst = -1;
+ Start = mktime (&tm);
+ if (Start == (time_t) -1)
+ goto fail;
+ }
+
+ /* Add relative date. */
+ if (pc.rel.year | pc.rel.month | pc.rel.day)
+ {
+ int year = tm.tm_year + pc.rel.year;
+ int month = tm.tm_mon + pc.rel.month;
+ int day = tm.tm_mday + pc.rel.day;
+ if (((year < tm.tm_year) ^ (pc.rel.year < 0))
+ | ((month < tm.tm_mon) ^ (pc.rel.month < 0))
+ | ((day < tm.tm_mday) ^ (pc.rel.day < 0)))
+ goto fail;
+ tm.tm_year = year;
+ tm.tm_mon = month;
+ tm.tm_mday = day;
+ tm.tm_hour = tm0.tm_hour;
+ tm.tm_min = tm0.tm_min;
+ tm.tm_sec = tm0.tm_sec;
+ tm.tm_isdst = tm0.tm_isdst;
+ Start = mktime (&tm);
+ if (Start == (time_t) -1)
+ goto fail;
+ }
+
+ /* The only "output" of this if-block is an updated Start value,
+ so this block must follow others that clobber Start. */
+ if (pc.zones_seen)
+ {
+ long int delta = pc.time_zone * 60;
+ time_t t1;
+#ifdef HAVE_TM_GMTOFF
+ delta -= tm.tm_gmtoff;
+#else
+ time_t t = Start;
+ struct tm const *gmt = gmtime (&t);
+ if (! gmt)
+ goto fail;
+ delta -= tm_diff (&tm, gmt);
+#endif
+ t1 = Start - delta;
+ if ((Start < t1) != (delta < 0))
+ goto fail; /* time_t overflow */
+ Start = t1;
+ }
+
+ /* Add relative hours, minutes, and seconds. On hosts that support
+ leap seconds, ignore the possibility of leap seconds; e.g.,
+ "+ 10 minutes" adds 600 seconds, even if one of them is a
+ leap second. Typically this is not what the user wants, but it's
+ too hard to do it the other way, because the time zone indicator
+ must be applied before relative times, and if mktime is applied
+ again the time zone will be lost. */
+ {
+ long int sum_ns = pc.seconds.tv_nsec + pc.rel.ns;
+ long int normalized_ns = (sum_ns % BILLION + BILLION) % BILLION;
+ time_t t0 = Start;
+ long int d1 = 60 * 60 * pc.rel.hour;
+ time_t t1 = t0 + d1;
+ long int d2 = 60 * pc.rel.minutes;
+ time_t t2 = t1 + d2;
+ long_time_t d3 = pc.rel.seconds;
+ long_time_t t3 = t2 + d3;
+ long int d4 = (sum_ns - normalized_ns) / BILLION;
+ long_time_t t4 = t3 + d4;
+ time_t t5 = t4;
+
+ if ((d1 / (60 * 60) ^ pc.rel.hour)
+ | (d2 / 60 ^ pc.rel.minutes)
+ | ((t1 < t0) ^ (d1 < 0))
+ | ((t2 < t1) ^ (d2 < 0))
+ | ((t3 < t2) ^ (d3 < 0))
+ | ((t4 < t3) ^ (d4 < 0))
+ | (t5 != t4))
+ goto fail;
+
+ result->tv_sec = t5;
+ result->tv_nsec = normalized_ns;
+ }
+ }
+
+ goto done;
+
+ fail:
+ ok = false;
+ done:
+ if (tz_was_altered)
+ ok &= (tz0 ? setenv ("TZ", tz0, 1) : unsetenv ("TZ")) == 0;
+ if (tz0 != tz0buf)
+ free (tz0);
+ return ok;
+}
+
+#if TEST
+
+int
+main (int ac, char **av)
+{
+ char buff[BUFSIZ];
+
+ printf ("Enter date, or blank line to exit.\n\t> ");
+ fflush (stdout);
+
+ buff[BUFSIZ - 1] = '\0';
+ while (fgets (buff, BUFSIZ - 1, stdin) && buff[0])
+ {
+ struct timespec d;
+ struct tm const *tm;
+ if (! parse_datetime (&d, buff, NULL))
+ printf ("Bad format - couldn't convert.\n");
+ else if (! (tm = localtime (&d.tv_sec)))
+ {
+ long int sec = d.tv_sec;
+ printf ("localtime (%ld) failed\n", sec);
+ }
+ else
+ {
+ int ns = d.tv_nsec;
+ printf ("%04ld-%02d-%02d %02d:%02d:%02d.%09d\n",
+ tm->tm_year + 1900L, tm->tm_mon + 1, tm->tm_mday,
+ tm->tm_hour, tm->tm_min, tm->tm_sec, ns);
+ }
+ printf ("\t> ");
+ fflush (stdout);
+ }
+ return 0;
+}
+#endif /* TEST */
diff --git a/lib/getdate.h b/lib/parse-datetime.h
index 142231e..c38b000 100644
--- a/lib/getdate.h
+++ b/lib/parse-datetime.h
@@ -1,12 +1,12 @@
/* Parse a string into an internal time stamp.
- Copyright (C) 1995, 1997, 1998, 2003, 2004, 2007 Free Software
+ Copyright (C) 1995, 1997-1998, 2003-2004, 2007, 2009-2016 Free Software
Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,10 +14,9 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <stdbool.h>
#include <time.h>
-bool get_date (struct timespec *, char const *, struct timespec const *);
+bool parse_datetime (struct timespec *, char const *, struct timespec const *);
diff --git a/lib/parse-datetime.y b/lib/parse-datetime.y
new file mode 100644
index 0000000..163a0ea
--- /dev/null
+++ b/lib/parse-datetime.y
@@ -0,0 +1,1626 @@
+%{
+/* Parse a string into an internal time stamp.
+
+ Copyright (C) 1999-2000, 2002-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Originally written by Steven M. Bellovin <smb@research.att.com> while
+ at the University of North Carolina at Chapel Hill. Later tweaked by
+ a couple of people on Usenet. Completely overhauled by Rich $alz
+ <rsalz@bbn.com> and Jim Berets <jberets@bbn.com> in August, 1990.
+
+ Modified by Paul Eggert <eggert@twinsun.com> in August 1999 to do
+ the right thing about local DST. Also modified by Paul Eggert
+ <eggert@cs.ucla.edu> in February 2004 to support
+ nanosecond-resolution time stamps, and in October 2004 to support
+ TZ strings in dates. */
+
+/* FIXME: Check for arithmetic overflow in all cases, not just
+ some of them. */
+
+#include <config.h>
+
+#include "parse-datetime.h"
+
+#include "intprops.h"
+#include "timespec.h"
+#include "verify.h"
+
+/* There's no need to extend the stack, so there's no need to involve
+ alloca. */
+#define YYSTACK_USE_ALLOCA 0
+
+/* Tell Bison how much stack space is needed. 20 should be plenty for
+ this grammar, which is not right recursive. Beware setting it too
+ high, since that might cause problems on machines whose
+ implementations have lame stack-overflow checking. */
+#define YYMAXDEPTH 20
+#define YYINITDEPTH YYMAXDEPTH
+
+/* Since the code of parse-datetime.y is not included in the Emacs executable
+ itself, there is no need to #define static in this file. Even if
+ the code were included in the Emacs executable, it probably
+ wouldn't do any harm to #undef it here; this will only cause
+ problems if we try to write to a static variable, which I don't
+ think this code needs to do. */
+#ifdef emacs
+# undef static
+#endif
+
+#include <c-ctype.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "xalloc.h"
+
+/* Bison's skeleton tests _STDLIB_H, while some stdlib.h headers
+ use _STDLIB_H_ as witness. Map the latter to the one bison uses. */
+/* FIXME: this is temporary. Remove when we have a mechanism to ensure
+ that the version we're using is fixed, too. */
+#ifdef _STDLIB_H_
+# undef _STDLIB_H
+# define _STDLIB_H 1
+#endif
+
+/* ISDIGIT differs from isdigit, as follows:
+ - Its arg may be any int or unsigned int; it need not be an unsigned char
+ or EOF.
+ - It's typically faster.
+ POSIX says that only '0' through '9' are digits. Prefer ISDIGIT to
+ isdigit unless it's important to use the locale's definition
+ of "digit" even when the host does not conform to POSIX. */
+#define ISDIGIT(c) ((unsigned int) (c) - '0' <= 9)
+
+/* Shift A right by B bits portably, by dividing A by 2**B and
+ truncating towards minus infinity. A and B should be free of side
+ effects, and B should be in the range 0 <= B <= INT_BITS - 2, where
+ INT_BITS is the number of useful bits in an int. GNU code can
+ assume that INT_BITS is at least 32.
+
+ ISO C99 says that A >> B is implementation-defined if A < 0. Some
+ implementations (e.g., UNICOS 9.0 on a Cray Y-MP EL) don't shift
+ right in the usual way when A < 0, so SHR falls back on division if
+ ordinary A >> B doesn't seem to be the usual signed shift. */
+#define SHR(a, b) \
+ (-1 >> 1 == -1 \
+ ? (a) >> (b) \
+ : (a) / (1 << (b)) - ((a) % (1 << (b)) < 0))
+
+#define EPOCH_YEAR 1970
+#define TM_YEAR_BASE 1900
+
+#define HOUR(x) ((x) * 60)
+
+/* long_time_t is a signed integer type that contains all time_t values. */
+verify (TYPE_IS_INTEGER (time_t));
+#if TIME_T_FITS_IN_LONG_INT
+typedef long int long_time_t;
+#else
+typedef time_t long_time_t;
+#endif
+
+/* Convert a possibly-signed character to an unsigned character. This is
+ a bit safer than casting to unsigned char, since it catches some type
+ errors that the cast doesn't. */
+static unsigned char to_uchar (char ch) { return ch; }
+
+/* Lots of this code assumes time_t and time_t-like values fit into
+ long_time_t. */
+verify (TYPE_MINIMUM (long_time_t) <= TYPE_MINIMUM (time_t)
+ && TYPE_MAXIMUM (time_t) <= TYPE_MAXIMUM (long_time_t));
+
+/* FIXME: It also assumes that signed integer overflow silently wraps around,
+ but this is not true any more with recent versions of GCC 4. */
+
+/* An integer value, and the number of digits in its textual
+ representation. */
+typedef struct
+{
+ bool negative;
+ long int value;
+ size_t digits;
+} textint;
+
+/* An entry in the lexical lookup table. */
+typedef struct
+{
+ char const *name;
+ int type;
+ int value;
+} table;
+
+/* Meridian: am, pm, or 24-hour style. */
+enum { MERam, MERpm, MER24 };
+
+enum { BILLION = 1000000000, LOG10_BILLION = 9 };
+
+/* Relative times. */
+typedef struct
+{
+ /* Relative year, month, day, hour, minutes, seconds, and nanoseconds. */
+ long int year;
+ long int month;
+ long int day;
+ long int hour;
+ long int minutes;
+ long_time_t seconds;
+ long int ns;
+} relative_time;
+
+#if HAVE_COMPOUND_LITERALS
+# define RELATIVE_TIME_0 ((relative_time) { 0, 0, 0, 0, 0, 0, 0 })
+#else
+static relative_time const RELATIVE_TIME_0;
+#endif
+
+/* Information passed to and from the parser. */
+typedef struct
+{
+ /* The input string remaining to be parsed. */
+ const char *input;
+
+ /* N, if this is the Nth Tuesday. */
+ long int day_ordinal;
+
+ /* Day of week; Sunday is 0. */
+ int day_number;
+
+ /* tm_isdst flag for the local zone. */
+ int local_isdst;
+
+ /* Time zone, in minutes east of UTC. */
+ long int time_zone;
+
+ /* Style used for time. */
+ int meridian;
+
+ /* Gregorian year, month, day, hour, minutes, seconds, and nanoseconds. */
+ textint year;
+ long int month;
+ long int day;
+ long int hour;
+ long int minutes;
+ struct timespec seconds; /* includes nanoseconds */
+
+ /* Relative year, month, day, hour, minutes, seconds, and nanoseconds. */
+ relative_time rel;
+
+ /* Presence or counts of nonterminals of various flavors parsed so far. */
+ bool timespec_seen;
+ bool rels_seen;
+ size_t dates_seen;
+ size_t days_seen;
+ size_t local_zones_seen;
+ size_t dsts_seen;
+ size_t times_seen;
+ size_t zones_seen;
+
+ /* Table of local time zone abbreviations, terminated by a null entry. */
+ table local_time_zone_table[3];
+} parser_control;
+
+union YYSTYPE;
+static int yylex (union YYSTYPE *, parser_control *);
+static int yyerror (parser_control const *, char const *);
+static long int time_zone_hhmm (parser_control *, textint, long int);
+
+/* Extract into *PC any date and time info from a string of digits
+ of the form e.g., YYYYMMDD, YYMMDD, HHMM, HH (and sometimes YYY,
+ YYYY, ...). */
+static void
+digits_to_date_time (parser_control *pc, textint text_int)
+{
+ if (pc->dates_seen && ! pc->year.digits
+ && ! pc->rels_seen && (pc->times_seen || 2 < text_int.digits))
+ pc->year = text_int;
+ else
+ {
+ if (4 < text_int.digits)
+ {
+ pc->dates_seen++;
+ pc->day = text_int.value % 100;
+ pc->month = (text_int.value / 100) % 100;
+ pc->year.value = text_int.value / 10000;
+ pc->year.digits = text_int.digits - 4;
+ }
+ else
+ {
+ pc->times_seen++;
+ if (text_int.digits <= 2)
+ {
+ pc->hour = text_int.value;
+ pc->minutes = 0;
+ }
+ else
+ {
+ pc->hour = text_int.value / 100;
+ pc->minutes = text_int.value % 100;
+ }
+ pc->seconds.tv_sec = 0;
+ pc->seconds.tv_nsec = 0;
+ pc->meridian = MER24;
+ }
+ }
+}
+
+/* Increment PC->rel by FACTOR * REL (FACTOR is 1 or -1). */
+static void
+apply_relative_time (parser_control *pc, relative_time rel, int factor)
+{
+ pc->rel.ns += factor * rel.ns;
+ pc->rel.seconds += factor * rel.seconds;
+ pc->rel.minutes += factor * rel.minutes;
+ pc->rel.hour += factor * rel.hour;
+ pc->rel.day += factor * rel.day;
+ pc->rel.month += factor * rel.month;
+ pc->rel.year += factor * rel.year;
+ pc->rels_seen = true;
+}
+
+/* Set PC-> hour, minutes, seconds and nanoseconds members from arguments. */
+static void
+set_hhmmss (parser_control *pc, long int hour, long int minutes,
+ time_t sec, long int nsec)
+{
+ pc->hour = hour;
+ pc->minutes = minutes;
+ pc->seconds.tv_sec = sec;
+ pc->seconds.tv_nsec = nsec;
+}
+
+%}
+
+/* We want a reentrant parser, even if the TZ manipulation and the calls to
+ localtime and gmtime are not reentrant. */
+%pure-parser
+%parse-param { parser_control *pc }
+%lex-param { parser_control *pc }
+
+/* This grammar has 31 shift/reduce conflicts. */
+%expect 31
+
+%union
+{
+ long int intval;
+ textint textintval;
+ struct timespec timespec;
+ relative_time rel;
+}
+
+%token <intval> tAGO
+%token tDST
+
+%token tYEAR_UNIT tMONTH_UNIT tHOUR_UNIT tMINUTE_UNIT tSEC_UNIT
+%token <intval> tDAY_UNIT tDAY_SHIFT
+
+%token <intval> tDAY tDAYZONE tLOCAL_ZONE tMERIDIAN
+%token <intval> tMONTH tORDINAL tZONE
+
+%token <textintval> tSNUMBER tUNUMBER
+%token <timespec> tSDECIMAL_NUMBER tUDECIMAL_NUMBER
+
+%type <intval> o_colon_minutes
+%type <timespec> seconds signed_seconds unsigned_seconds
+
+%type <rel> relunit relunit_snumber dayshift
+
+%%
+
+spec:
+ timespec
+ | items
+ ;
+
+timespec:
+ '@' seconds
+ {
+ pc->seconds = $2;
+ pc->timespec_seen = true;
+ }
+ ;
+
+items:
+ /* empty */
+ | items item
+ ;
+
+item:
+ datetime
+ { pc->times_seen++; pc->dates_seen++; }
+ | time
+ { pc->times_seen++; }
+ | local_zone
+ { pc->local_zones_seen++; }
+ | zone
+ { pc->zones_seen++; }
+ | date
+ { pc->dates_seen++; }
+ | day
+ { pc->days_seen++; }
+ | rel
+ | number
+ | hybrid
+ ;
+
+datetime:
+ iso_8601_datetime
+ ;
+
+iso_8601_datetime:
+ iso_8601_date 'T' iso_8601_time
+ ;
+
+time:
+ tUNUMBER tMERIDIAN
+ {
+ set_hhmmss (pc, $1.value, 0, 0, 0);
+ pc->meridian = $2;
+ }
+ | tUNUMBER ':' tUNUMBER tMERIDIAN
+ {
+ set_hhmmss (pc, $1.value, $3.value, 0, 0);
+ pc->meridian = $4;
+ }
+ | tUNUMBER ':' tUNUMBER ':' unsigned_seconds tMERIDIAN
+ {
+ set_hhmmss (pc, $1.value, $3.value, $5.tv_sec, $5.tv_nsec);
+ pc->meridian = $6;
+ }
+ | iso_8601_time
+ ;
+
+iso_8601_time:
+ tUNUMBER zone_offset
+ {
+ set_hhmmss (pc, $1.value, 0, 0, 0);
+ pc->meridian = MER24;
+ }
+ | tUNUMBER ':' tUNUMBER o_zone_offset
+ {
+ set_hhmmss (pc, $1.value, $3.value, 0, 0);
+ pc->meridian = MER24;
+ }
+ | tUNUMBER ':' tUNUMBER ':' unsigned_seconds o_zone_offset
+ {
+ set_hhmmss (pc, $1.value, $3.value, $5.tv_sec, $5.tv_nsec);
+ pc->meridian = MER24;
+ }
+ ;
+
+o_zone_offset:
+ /* empty */
+ | zone_offset
+ ;
+
+zone_offset:
+ tSNUMBER o_colon_minutes
+ {
+ pc->zones_seen++;
+ pc->time_zone = time_zone_hhmm (pc, $1, $2);
+ }
+ ;
+
+local_zone:
+ tLOCAL_ZONE
+ {
+ pc->local_isdst = $1;
+ pc->dsts_seen += (0 < $1);
+ }
+ | tLOCAL_ZONE tDST
+ {
+ pc->local_isdst = 1;
+ pc->dsts_seen += (0 < $1) + 1;
+ }
+ ;
+
+/* Note 'T' is a special case, as it is used as the separator in ISO
+ 8601 date and time of day representation. */
+zone:
+ tZONE
+ { pc->time_zone = $1; }
+ | 'T'
+ { pc->time_zone = HOUR(7); }
+ | tZONE relunit_snumber
+ { pc->time_zone = $1;
+ apply_relative_time (pc, $2, 1); }
+ | 'T' relunit_snumber
+ { pc->time_zone = HOUR(7);
+ apply_relative_time (pc, $2, 1); }
+ | tZONE tSNUMBER o_colon_minutes
+ { pc->time_zone = $1 + time_zone_hhmm (pc, $2, $3); }
+ | tDAYZONE
+ { pc->time_zone = $1 + 60; }
+ | tZONE tDST
+ { pc->time_zone = $1 + 60; }
+ ;
+
+day:
+ tDAY
+ {
+ pc->day_ordinal = 0;
+ pc->day_number = $1;
+ }
+ | tDAY ','
+ {
+ pc->day_ordinal = 0;
+ pc->day_number = $1;
+ }
+ | tORDINAL tDAY
+ {
+ pc->day_ordinal = $1;
+ pc->day_number = $2;
+ }
+ | tUNUMBER tDAY
+ {
+ pc->day_ordinal = $1.value;
+ pc->day_number = $2;
+ }
+ ;
+
+date:
+ tUNUMBER '/' tUNUMBER
+ {
+ pc->month = $1.value;
+ pc->day = $3.value;
+ }
+ | tUNUMBER '/' tUNUMBER '/' tUNUMBER
+ {
+ /* Interpret as YYYY/MM/DD if the first value has 4 or more digits,
+ otherwise as MM/DD/YY.
+ The goal in recognizing YYYY/MM/DD is solely to support legacy
+ machine-generated dates like those in an RCS log listing. If
+ you want portability, use the ISO 8601 format. */
+ if (4 <= $1.digits)
+ {
+ pc->year = $1;
+ pc->month = $3.value;
+ pc->day = $5.value;
+ }
+ else
+ {
+ pc->month = $1.value;
+ pc->day = $3.value;
+ pc->year = $5;
+ }
+ }
+ | tUNUMBER tMONTH tSNUMBER
+ {
+ /* e.g. 17-JUN-1992. */
+ pc->day = $1.value;
+ pc->month = $2;
+ pc->year.value = -$3.value;
+ pc->year.digits = $3.digits;
+ }
+ | tMONTH tSNUMBER tSNUMBER
+ {
+ /* e.g. JUN-17-1992. */
+ pc->month = $1;
+ pc->day = -$2.value;
+ pc->year.value = -$3.value;
+ pc->year.digits = $3.digits;
+ }
+ | tMONTH tUNUMBER
+ {
+ pc->month = $1;
+ pc->day = $2.value;
+ }
+ | tMONTH tUNUMBER ',' tUNUMBER
+ {
+ pc->month = $1;
+ pc->day = $2.value;
+ pc->year = $4;
+ }
+ | tUNUMBER tMONTH
+ {
+ pc->day = $1.value;
+ pc->month = $2;
+ }
+ | tUNUMBER tMONTH tUNUMBER
+ {
+ pc->day = $1.value;
+ pc->month = $2;
+ pc->year = $3;
+ }
+ | iso_8601_date
+ ;
+
+iso_8601_date:
+ tUNUMBER tSNUMBER tSNUMBER
+ {
+ /* ISO 8601 format. YYYY-MM-DD. */
+ pc->year = $1;
+ pc->month = -$2.value;
+ pc->day = -$3.value;
+ }
+ ;
+
+rel:
+ relunit tAGO
+ { apply_relative_time (pc, $1, $2); }
+ | relunit
+ { apply_relative_time (pc, $1, 1); }
+ | dayshift
+ { apply_relative_time (pc, $1, 1); }
+ ;
+
+relunit:
+ tORDINAL tYEAR_UNIT
+ { $$ = RELATIVE_TIME_0; $$.year = $1; }
+ | tUNUMBER tYEAR_UNIT
+ { $$ = RELATIVE_TIME_0; $$.year = $1.value; }
+ | tYEAR_UNIT
+ { $$ = RELATIVE_TIME_0; $$.year = 1; }
+ | tORDINAL tMONTH_UNIT
+ { $$ = RELATIVE_TIME_0; $$.month = $1; }
+ | tUNUMBER tMONTH_UNIT
+ { $$ = RELATIVE_TIME_0; $$.month = $1.value; }
+ | tMONTH_UNIT
+ { $$ = RELATIVE_TIME_0; $$.month = 1; }
+ | tORDINAL tDAY_UNIT
+ { $$ = RELATIVE_TIME_0; $$.day = $1 * $2; }
+ | tUNUMBER tDAY_UNIT
+ { $$ = RELATIVE_TIME_0; $$.day = $1.value * $2; }
+ | tDAY_UNIT
+ { $$ = RELATIVE_TIME_0; $$.day = $1; }
+ | tORDINAL tHOUR_UNIT
+ { $$ = RELATIVE_TIME_0; $$.hour = $1; }
+ | tUNUMBER tHOUR_UNIT
+ { $$ = RELATIVE_TIME_0; $$.hour = $1.value; }
+ | tHOUR_UNIT
+ { $$ = RELATIVE_TIME_0; $$.hour = 1; }
+ | tORDINAL tMINUTE_UNIT
+ { $$ = RELATIVE_TIME_0; $$.minutes = $1; }
+ | tUNUMBER tMINUTE_UNIT
+ { $$ = RELATIVE_TIME_0; $$.minutes = $1.value; }
+ | tMINUTE_UNIT
+ { $$ = RELATIVE_TIME_0; $$.minutes = 1; }
+ | tORDINAL tSEC_UNIT
+ { $$ = RELATIVE_TIME_0; $$.seconds = $1; }
+ | tUNUMBER tSEC_UNIT
+ { $$ = RELATIVE_TIME_0; $$.seconds = $1.value; }
+ | tSDECIMAL_NUMBER tSEC_UNIT
+ { $$ = RELATIVE_TIME_0; $$.seconds = $1.tv_sec; $$.ns = $1.tv_nsec; }
+ | tUDECIMAL_NUMBER tSEC_UNIT
+ { $$ = RELATIVE_TIME_0; $$.seconds = $1.tv_sec; $$.ns = $1.tv_nsec; }
+ | tSEC_UNIT
+ { $$ = RELATIVE_TIME_0; $$.seconds = 1; }
+ | relunit_snumber
+ ;
+
+relunit_snumber:
+ tSNUMBER tYEAR_UNIT
+ { $$ = RELATIVE_TIME_0; $$.year = $1.value; }
+ | tSNUMBER tMONTH_UNIT
+ { $$ = RELATIVE_TIME_0; $$.month = $1.value; }
+ | tSNUMBER tDAY_UNIT
+ { $$ = RELATIVE_TIME_0; $$.day = $1.value * $2; }
+ | tSNUMBER tHOUR_UNIT
+ { $$ = RELATIVE_TIME_0; $$.hour = $1.value; }
+ | tSNUMBER tMINUTE_UNIT
+ { $$ = RELATIVE_TIME_0; $$.minutes = $1.value; }
+ | tSNUMBER tSEC_UNIT
+ { $$ = RELATIVE_TIME_0; $$.seconds = $1.value; }
+ ;
+
+dayshift:
+ tDAY_SHIFT
+ { $$ = RELATIVE_TIME_0; $$.day = $1; }
+ ;
+
+seconds: signed_seconds | unsigned_seconds;
+
+signed_seconds:
+ tSDECIMAL_NUMBER
+ | tSNUMBER
+ { $$.tv_sec = $1.value; $$.tv_nsec = 0; }
+ ;
+
+unsigned_seconds:
+ tUDECIMAL_NUMBER
+ | tUNUMBER
+ { $$.tv_sec = $1.value; $$.tv_nsec = 0; }
+ ;
+
+number:
+ tUNUMBER
+ { digits_to_date_time (pc, $1); }
+ ;
+
+hybrid:
+ tUNUMBER relunit_snumber
+ {
+ /* Hybrid all-digit and relative offset, so that we accept e.g.,
+ "YYYYMMDD +N days" as well as "YYYYMMDD N days". */
+ digits_to_date_time (pc, $1);
+ apply_relative_time (pc, $2, 1);
+ }
+ ;
+
+o_colon_minutes:
+ /* empty */
+ { $$ = -1; }
+ | ':' tUNUMBER
+ { $$ = $2.value; }
+ ;
+
+%%
+
+static table const meridian_table[] =
+{
+ { "AM", tMERIDIAN, MERam },
+ { "A.M.", tMERIDIAN, MERam },
+ { "PM", tMERIDIAN, MERpm },
+ { "P.M.", tMERIDIAN, MERpm },
+ { NULL, 0, 0 }
+};
+
+static table const dst_table[] =
+{
+ { "DST", tDST, 0 }
+};
+
+static table const month_and_day_table[] =
+{
+ { "JANUARY", tMONTH, 1 },
+ { "FEBRUARY", tMONTH, 2 },
+ { "MARCH", tMONTH, 3 },
+ { "APRIL", tMONTH, 4 },
+ { "MAY", tMONTH, 5 },
+ { "JUNE", tMONTH, 6 },
+ { "JULY", tMONTH, 7 },
+ { "AUGUST", tMONTH, 8 },
+ { "SEPTEMBER",tMONTH, 9 },
+ { "SEPT", tMONTH, 9 },
+ { "OCTOBER", tMONTH, 10 },
+ { "NOVEMBER", tMONTH, 11 },
+ { "DECEMBER", tMONTH, 12 },
+ { "SUNDAY", tDAY, 0 },
+ { "MONDAY", tDAY, 1 },
+ { "TUESDAY", tDAY, 2 },
+ { "TUES", tDAY, 2 },
+ { "WEDNESDAY",tDAY, 3 },
+ { "WEDNES", tDAY, 3 },
+ { "THURSDAY", tDAY, 4 },
+ { "THUR", tDAY, 4 },
+ { "THURS", tDAY, 4 },
+ { "FRIDAY", tDAY, 5 },
+ { "SATURDAY", tDAY, 6 },
+ { NULL, 0, 0 }
+};
+
+static table const time_units_table[] =
+{
+ { "YEAR", tYEAR_UNIT, 1 },
+ { "MONTH", tMONTH_UNIT, 1 },
+ { "FORTNIGHT",tDAY_UNIT, 14 },
+ { "WEEK", tDAY_UNIT, 7 },
+ { "DAY", tDAY_UNIT, 1 },
+ { "HOUR", tHOUR_UNIT, 1 },
+ { "MINUTE", tMINUTE_UNIT, 1 },
+ { "MIN", tMINUTE_UNIT, 1 },
+ { "SECOND", tSEC_UNIT, 1 },
+ { "SEC", tSEC_UNIT, 1 },
+ { NULL, 0, 0 }
+};
+
+/* Assorted relative-time words. */
+static table const relative_time_table[] =
+{
+ { "TOMORROW", tDAY_SHIFT, 1 },
+ { "YESTERDAY",tDAY_SHIFT, -1 },
+ { "TODAY", tDAY_SHIFT, 0 },
+ { "NOW", tDAY_SHIFT, 0 },
+ { "LAST", tORDINAL, -1 },
+ { "THIS", tORDINAL, 0 },
+ { "NEXT", tORDINAL, 1 },
+ { "FIRST", tORDINAL, 1 },
+/*{ "SECOND", tORDINAL, 2 }, */
+ { "THIRD", tORDINAL, 3 },
+ { "FOURTH", tORDINAL, 4 },
+ { "FIFTH", tORDINAL, 5 },
+ { "SIXTH", tORDINAL, 6 },
+ { "SEVENTH", tORDINAL, 7 },
+ { "EIGHTH", tORDINAL, 8 },
+ { "NINTH", tORDINAL, 9 },
+ { "TENTH", tORDINAL, 10 },
+ { "ELEVENTH", tORDINAL, 11 },
+ { "TWELFTH", tORDINAL, 12 },
+ { "AGO", tAGO, -1 },
+ { "HENCE", tAGO, 1 },
+ { NULL, 0, 0 }
+};
+
+/* The universal time zone table. These labels can be used even for
+ time stamps that would not otherwise be valid, e.g., GMT time
+ stamps in London during summer. */
+static table const universal_time_zone_table[] =
+{
+ { "GMT", tZONE, HOUR ( 0) }, /* Greenwich Mean */
+ { "UT", tZONE, HOUR ( 0) }, /* Universal (Coordinated) */
+ { "UTC", tZONE, HOUR ( 0) },
+ { NULL, 0, 0 }
+};
+
+/* The time zone table. This table is necessarily incomplete, as time
+ zone abbreviations are ambiguous; e.g. Australians interpret "EST"
+ as Eastern time in Australia, not as US Eastern Standard Time.
+ You cannot rely on parse_datetime to handle arbitrary time zone
+ abbreviations; use numeric abbreviations like "-0500" instead. */
+static table const time_zone_table[] =
+{
+ { "WET", tZONE, HOUR ( 0) }, /* Western European */
+ { "WEST", tDAYZONE, HOUR ( 0) }, /* Western European Summer */
+ { "BST", tDAYZONE, HOUR ( 0) }, /* British Summer */
+ { "ART", tZONE, -HOUR ( 3) }, /* Argentina */
+ { "BRT", tZONE, -HOUR ( 3) }, /* Brazil */
+ { "BRST", tDAYZONE, -HOUR ( 3) }, /* Brazil Summer */
+ { "NST", tZONE, -(HOUR ( 3) + 30) }, /* Newfoundland Standard */
+ { "NDT", tDAYZONE,-(HOUR ( 3) + 30) }, /* Newfoundland Daylight */
+ { "AST", tZONE, -HOUR ( 4) }, /* Atlantic Standard */
+ { "ADT", tDAYZONE, -HOUR ( 4) }, /* Atlantic Daylight */
+ { "CLT", tZONE, -HOUR ( 4) }, /* Chile */
+ { "CLST", tDAYZONE, -HOUR ( 4) }, /* Chile Summer */
+ { "EST", tZONE, -HOUR ( 5) }, /* Eastern Standard */
+ { "EDT", tDAYZONE, -HOUR ( 5) }, /* Eastern Daylight */
+ { "CST", tZONE, -HOUR ( 6) }, /* Central Standard */
+ { "CDT", tDAYZONE, -HOUR ( 6) }, /* Central Daylight */
+ { "MST", tZONE, -HOUR ( 7) }, /* Mountain Standard */
+ { "MDT", tDAYZONE, -HOUR ( 7) }, /* Mountain Daylight */
+ { "PST", tZONE, -HOUR ( 8) }, /* Pacific Standard */
+ { "PDT", tDAYZONE, -HOUR ( 8) }, /* Pacific Daylight */
+ { "AKST", tZONE, -HOUR ( 9) }, /* Alaska Standard */
+ { "AKDT", tDAYZONE, -HOUR ( 9) }, /* Alaska Daylight */
+ { "HST", tZONE, -HOUR (10) }, /* Hawaii Standard */
+ { "HAST", tZONE, -HOUR (10) }, /* Hawaii-Aleutian Standard */
+ { "HADT", tDAYZONE, -HOUR (10) }, /* Hawaii-Aleutian Daylight */
+ { "SST", tZONE, -HOUR (12) }, /* Samoa Standard */
+ { "WAT", tZONE, HOUR ( 1) }, /* West Africa */
+ { "CET", tZONE, HOUR ( 1) }, /* Central European */
+ { "CEST", tDAYZONE, HOUR ( 1) }, /* Central European Summer */
+ { "MET", tZONE, HOUR ( 1) }, /* Middle European */
+ { "MEZ", tZONE, HOUR ( 1) }, /* Middle European */
+ { "MEST", tDAYZONE, HOUR ( 1) }, /* Middle European Summer */
+ { "MESZ", tDAYZONE, HOUR ( 1) }, /* Middle European Summer */
+ { "EET", tZONE, HOUR ( 2) }, /* Eastern European */
+ { "EEST", tDAYZONE, HOUR ( 2) }, /* Eastern European Summer */
+ { "CAT", tZONE, HOUR ( 2) }, /* Central Africa */
+ { "SAST", tZONE, HOUR ( 2) }, /* South Africa Standard */
+ { "EAT", tZONE, HOUR ( 3) }, /* East Africa */
+ { "MSK", tZONE, HOUR ( 3) }, /* Moscow */
+ { "MSD", tDAYZONE, HOUR ( 3) }, /* Moscow Daylight */
+ { "IST", tZONE, (HOUR ( 5) + 30) }, /* India Standard */
+ { "SGT", tZONE, HOUR ( 8) }, /* Singapore */
+ { "KST", tZONE, HOUR ( 9) }, /* Korea Standard */
+ { "JST", tZONE, HOUR ( 9) }, /* Japan Standard */
+ { "GST", tZONE, HOUR (10) }, /* Guam Standard */
+ { "NZST", tZONE, HOUR (12) }, /* New Zealand Standard */
+ { "NZDT", tDAYZONE, HOUR (12) }, /* New Zealand Daylight */
+ { NULL, 0, 0 }
+};
+
+/* Military time zone table.
+
+ Note 'T' is a special case, as it is used as the separator in ISO
+ 8601 date and time of day representation. */
+static table const military_table[] =
+{
+ { "A", tZONE, -HOUR ( 1) },
+ { "B", tZONE, -HOUR ( 2) },
+ { "C", tZONE, -HOUR ( 3) },
+ { "D", tZONE, -HOUR ( 4) },
+ { "E", tZONE, -HOUR ( 5) },
+ { "F", tZONE, -HOUR ( 6) },
+ { "G", tZONE, -HOUR ( 7) },
+ { "H", tZONE, -HOUR ( 8) },
+ { "I", tZONE, -HOUR ( 9) },
+ { "K", tZONE, -HOUR (10) },
+ { "L", tZONE, -HOUR (11) },
+ { "M", tZONE, -HOUR (12) },
+ { "N", tZONE, HOUR ( 1) },
+ { "O", tZONE, HOUR ( 2) },
+ { "P", tZONE, HOUR ( 3) },
+ { "Q", tZONE, HOUR ( 4) },
+ { "R", tZONE, HOUR ( 5) },
+ { "S", tZONE, HOUR ( 6) },
+ { "T", 'T', 0 },
+ { "U", tZONE, HOUR ( 8) },
+ { "V", tZONE, HOUR ( 9) },
+ { "W", tZONE, HOUR (10) },
+ { "X", tZONE, HOUR (11) },
+ { "Y", tZONE, HOUR (12) },
+ { "Z", tZONE, HOUR ( 0) },
+ { NULL, 0, 0 }
+};
+
+
+
+/* Convert a time zone expressed as HH:MM into an integer count of
+ minutes. If MM is negative, then S is of the form HHMM and needs
+ to be picked apart; otherwise, S is of the form HH. As specified in
+ http://www.opengroup.org/susv3xbd/xbd_chap08.html#tag_08_03, allow
+ only valid TZ range, and consider first two digits as hours, if no
+ minutes specified. */
+
+static long int
+time_zone_hhmm (parser_control *pc, textint s, long int mm)
+{
+ long int n_minutes;
+
+ /* If the length of S is 1 or 2 and no minutes are specified,
+ interpret it as a number of hours. */
+ if (s.digits <= 2 && mm < 0)
+ s.value *= 100;
+
+ if (mm < 0)
+ n_minutes = (s.value / 100) * 60 + s.value % 100;
+ else
+ n_minutes = s.value * 60 + (s.negative ? -mm : mm);
+
+ /* If the absolute number of minutes is larger than 24 hours,
+ arrange to reject it by incrementing pc->zones_seen. Thus,
+ we allow only values in the range UTC-24:00 to UTC+24:00. */
+ if (24 * 60 < abs (n_minutes))
+ pc->zones_seen++;
+
+ return n_minutes;
+}
+
+static int
+to_hour (long int hours, int meridian)
+{
+ switch (meridian)
+ {
+ default: /* Pacify GCC. */
+ case MER24:
+ return 0 <= hours && hours < 24 ? hours : -1;
+ case MERam:
+ return 0 < hours && hours < 12 ? hours : hours == 12 ? 0 : -1;
+ case MERpm:
+ return 0 < hours && hours < 12 ? hours + 12 : hours == 12 ? 12 : -1;
+ }
+}
+
+static long int
+to_year (textint textyear)
+{
+ long int year = textyear.value;
+
+ if (year < 0)
+ year = -year;
+
+ /* XPG4 suggests that years 00-68 map to 2000-2068, and
+ years 69-99 map to 1969-1999. */
+ else if (textyear.digits == 2)
+ year += year < 69 ? 2000 : 1900;
+
+ return year;
+}
+
+static table const * _GL_ATTRIBUTE_PURE
+lookup_zone (parser_control const *pc, char const *name)
+{
+ table const *tp;
+
+ for (tp = universal_time_zone_table; tp->name; tp++)
+ if (strcmp (name, tp->name) == 0)
+ return tp;
+
+ /* Try local zone abbreviations before those in time_zone_table, as
+ the local ones are more likely to be right. */
+ for (tp = pc->local_time_zone_table; tp->name; tp++)
+ if (strcmp (name, tp->name) == 0)
+ return tp;
+
+ for (tp = time_zone_table; tp->name; tp++)
+ if (strcmp (name, tp->name) == 0)
+ return tp;
+
+ return NULL;
+}
+
+#if ! HAVE_TM_GMTOFF
+/* Yield the difference between *A and *B,
+ measured in seconds, ignoring leap seconds.
+ The body of this function is taken directly from the GNU C Library;
+ see src/strftime.c. */
+static long int
+tm_diff (struct tm const *a, struct tm const *b)
+{
+ /* Compute intervening leap days correctly even if year is negative.
+ Take care to avoid int overflow in leap day calculations. */
+ int a4 = SHR (a->tm_year, 2) + SHR (TM_YEAR_BASE, 2) - ! (a->tm_year & 3);
+ int b4 = SHR (b->tm_year, 2) + SHR (TM_YEAR_BASE, 2) - ! (b->tm_year & 3);
+ int a100 = a4 / 25 - (a4 % 25 < 0);
+ int b100 = b4 / 25 - (b4 % 25 < 0);
+ int a400 = SHR (a100, 2);
+ int b400 = SHR (b100, 2);
+ int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
+ long int ayear = a->tm_year;
+ long int years = ayear - b->tm_year;
+ long int days = (365 * years + intervening_leap_days
+ + (a->tm_yday - b->tm_yday));
+ return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
+ + (a->tm_min - b->tm_min))
+ + (a->tm_sec - b->tm_sec));
+}
+#endif /* ! HAVE_TM_GMTOFF */
+
+static table const *
+lookup_word (parser_control const *pc, char *word)
+{
+ char *p;
+ char *q;
+ size_t wordlen;
+ table const *tp;
+ bool period_found;
+ bool abbrev;
+
+ /* Make it uppercase. */
+ for (p = word; *p; p++)
+ {
+ unsigned char ch = *p;
+ *p = c_toupper (ch);
+ }
+
+ for (tp = meridian_table; tp->name; tp++)
+ if (strcmp (word, tp->name) == 0)
+ return tp;
+
+ /* See if we have an abbreviation for a month. */
+ wordlen = strlen (word);
+ abbrev = wordlen == 3 || (wordlen == 4 && word[3] == '.');
+
+ for (tp = month_and_day_table; tp->name; tp++)
+ if ((abbrev ? strncmp (word, tp->name, 3) : strcmp (word, tp->name)) == 0)
+ return tp;
+
+ if ((tp = lookup_zone (pc, word)))
+ return tp;
+
+ if (strcmp (word, dst_table[0].name) == 0)
+ return dst_table;
+
+ for (tp = time_units_table; tp->name; tp++)
+ if (strcmp (word, tp->name) == 0)
+ return tp;
+
+ /* Strip off any plural and try the units table again. */
+ if (word[wordlen - 1] == 'S')
+ {
+ word[wordlen - 1] = '\0';
+ for (tp = time_units_table; tp->name; tp++)
+ if (strcmp (word, tp->name) == 0)
+ return tp;
+ word[wordlen - 1] = 'S'; /* For "this" in relative_time_table. */
+ }
+
+ for (tp = relative_time_table; tp->name; tp++)
+ if (strcmp (word, tp->name) == 0)
+ return tp;
+
+ /* Military time zones. */
+ if (wordlen == 1)
+ for (tp = military_table; tp->name; tp++)
+ if (word[0] == tp->name[0])
+ return tp;
+
+ /* Drop out any periods and try the time zone table again. */
+ for (period_found = false, p = q = word; (*p = *q); q++)
+ if (*q == '.')
+ period_found = true;
+ else
+ p++;
+ if (period_found && (tp = lookup_zone (pc, word)))
+ return tp;
+
+ return NULL;
+}
+
+static int
+yylex (union YYSTYPE *lvalp, parser_control *pc)
+{
+ unsigned char c;
+ size_t count;
+
+ for (;;)
+ {
+ while (c = *pc->input, c_isspace (c))
+ pc->input++;
+
+ if (ISDIGIT (c) || c == '-' || c == '+')
+ {
+ char const *p;
+ int sign;
+ unsigned long int value;
+ if (c == '-' || c == '+')
+ {
+ sign = c == '-' ? -1 : 1;
+ while (c = *++pc->input, c_isspace (c))
+ continue;
+ if (! ISDIGIT (c))
+ /* skip the '-' sign */
+ continue;
+ }
+ else
+ sign = 0;
+ p = pc->input;
+ for (value = 0; ; value *= 10)
+ {
+ unsigned long int value1 = value + (c - '0');
+ if (value1 < value)
+ return '?';
+ value = value1;
+ c = *++p;
+ if (! ISDIGIT (c))
+ break;
+ if (ULONG_MAX / 10 < value)
+ return '?';
+ }
+ if ((c == '.' || c == ',') && ISDIGIT (p[1]))
+ {
+ time_t s;
+ int ns;
+ int digits;
+ unsigned long int value1;
+
+ /* Check for overflow when converting value to time_t. */
+ if (sign < 0)
+ {
+ s = - value;
+ if (0 < s)
+ return '?';
+ value1 = -s;
+ }
+ else
+ {
+ s = value;
+ if (s < 0)
+ return '?';
+ value1 = s;
+ }
+ if (value != value1)
+ return '?';
+
+ /* Accumulate fraction, to ns precision. */
+ p++;
+ ns = *p++ - '0';
+ for (digits = 2; digits <= LOG10_BILLION; digits++)
+ {
+ ns *= 10;
+ if (ISDIGIT (*p))
+ ns += *p++ - '0';
+ }
+
+ /* Skip excess digits, truncating toward -Infinity. */
+ if (sign < 0)
+ for (; ISDIGIT (*p); p++)
+ if (*p != '0')
+ {
+ ns++;
+ break;
+ }
+ while (ISDIGIT (*p))
+ p++;
+
+ /* Adjust to the timespec convention, which is that
+ tv_nsec is always a positive offset even if tv_sec is
+ negative. */
+ if (sign < 0 && ns)
+ {
+ s--;
+ if (! (s < 0))
+ return '?';
+ ns = BILLION - ns;
+ }
+
+ lvalp->timespec.tv_sec = s;
+ lvalp->timespec.tv_nsec = ns;
+ pc->input = p;
+ return sign ? tSDECIMAL_NUMBER : tUDECIMAL_NUMBER;
+ }
+ else
+ {
+ lvalp->textintval.negative = sign < 0;
+ if (sign < 0)
+ {
+ lvalp->textintval.value = - value;
+ if (0 < lvalp->textintval.value)
+ return '?';
+ }
+ else
+ {
+ lvalp->textintval.value = value;
+ if (lvalp->textintval.value < 0)
+ return '?';
+ }
+ lvalp->textintval.digits = p - pc->input;
+ pc->input = p;
+ return sign ? tSNUMBER : tUNUMBER;
+ }
+ }
+
+ if (c_isalpha (c))
+ {
+ char buff[20];
+ char *p = buff;
+ table const *tp;
+
+ do
+ {
+ if (p < buff + sizeof buff - 1)
+ *p++ = c;
+ c = *++pc->input;
+ }
+ while (c_isalpha (c) || c == '.');
+
+ *p = '\0';
+ tp = lookup_word (pc, buff);
+ if (! tp)
+ return '?';
+ lvalp->intval = tp->value;
+ return tp->type;
+ }
+
+ if (c != '(')
+ return to_uchar (*pc->input++);
+
+ count = 0;
+ do
+ {
+ c = *pc->input++;
+ if (c == '\0')
+ return c;
+ if (c == '(')
+ count++;
+ else if (c == ')')
+ count--;
+ }
+ while (count != 0);
+ }
+}
+
+/* Do nothing if the parser reports an error. */
+static int
+yyerror (parser_control const *pc _GL_UNUSED,
+ char const *s _GL_UNUSED)
+{
+ return 0;
+}
+
+/* If *TM0 is the old and *TM1 is the new value of a struct tm after
+ passing it to mktime, return true if it's OK that mktime returned T.
+ It's not OK if *TM0 has out-of-range members. */
+
+static bool
+mktime_ok (struct tm const *tm0, struct tm const *tm1, time_t t)
+{
+ if (t == (time_t) -1)
+ {
+ /* Guard against falsely reporting an error when parsing a time
+ stamp that happens to equal (time_t) -1, on a host that
+ supports such a time stamp. */
+ tm1 = localtime (&t);
+ if (!tm1)
+ return false;
+ }
+
+ return ! ((tm0->tm_sec ^ tm1->tm_sec)
+ | (tm0->tm_min ^ tm1->tm_min)
+ | (tm0->tm_hour ^ tm1->tm_hour)
+ | (tm0->tm_mday ^ tm1->tm_mday)
+ | (tm0->tm_mon ^ tm1->tm_mon)
+ | (tm0->tm_year ^ tm1->tm_year));
+}
+
+/* A reasonable upper bound for the size of ordinary TZ strings.
+ Use heap allocation if TZ's length exceeds this. */
+enum { TZBUFSIZE = 100 };
+
+/* Return a copy of TZ, stored in TZBUF if it fits, and heap-allocated
+ otherwise. */
+static char *
+get_tz (char tzbuf[TZBUFSIZE])
+{
+ char *tz = getenv ("TZ");
+ if (tz)
+ {
+ size_t tzsize = strlen (tz) + 1;
+ tz = (tzsize <= TZBUFSIZE
+ ? memcpy (tzbuf, tz, tzsize)
+ : xmemdup (tz, tzsize));
+ }
+ return tz;
+}
+
+/* Parse a date/time string, storing the resulting time value into *RESULT.
+ The string itself is pointed to by P. Return true if successful.
+ P can be an incomplete or relative time specification; if so, use
+ *NOW as the basis for the returned time. */
+bool
+parse_datetime (struct timespec *result, char const *p,
+ struct timespec const *now)
+{
+ time_t Start;
+ long int Start_ns;
+ struct tm const *tmp;
+ struct tm tm;
+ struct tm tm0;
+ parser_control pc;
+ struct timespec gettime_buffer;
+ unsigned char c;
+ bool tz_was_altered = false;
+ char *tz0 = NULL;
+ char tz0buf[TZBUFSIZE];
+ bool ok = true;
+
+ if (! now)
+ {
+ gettime (&gettime_buffer);
+ now = &gettime_buffer;
+ }
+
+ Start = now->tv_sec;
+ Start_ns = now->tv_nsec;
+
+ tmp = localtime (&now->tv_sec);
+ if (! tmp)
+ return false;
+
+ while (c = *p, c_isspace (c))
+ p++;
+
+ if (strncmp (p, "TZ=\"", 4) == 0)
+ {
+ char const *tzbase = p + 4;
+ size_t tzsize = 1;
+ char const *s;
+
+ for (s = tzbase; *s; s++, tzsize++)
+ if (*s == '\\')
+ {
+ s++;
+ if (! (*s == '\\' || *s == '"'))
+ break;
+ }
+ else if (*s == '"')
+ {
+ char *z;
+ char *tz1;
+ char tz1buf[TZBUFSIZE];
+ bool large_tz = TZBUFSIZE < tzsize;
+ bool setenv_ok;
+ tz0 = get_tz (tz0buf);
+ z = tz1 = large_tz ? xmalloc (tzsize) : tz1buf;
+ for (s = tzbase; *s != '"'; s++)
+ *z++ = *(s += *s == '\\');
+ *z = '\0';
+ setenv_ok = setenv ("TZ", tz1, 1) == 0;
+ if (large_tz)
+ free (tz1);
+ if (!setenv_ok)
+ goto fail;
+ tz_was_altered = true;
+
+ p = s + 1;
+ while (c = *p, c_isspace (c))
+ p++;
+
+ break;
+ }
+ }
+
+ /* As documented, be careful to treat the empty string just like
+ a date string of "0". Without this, an empty string would be
+ declared invalid when parsed during a DST transition. */
+ if (*p == '\0')
+ p = "0";
+
+ pc.input = p;
+ pc.year.value = tmp->tm_year;
+ pc.year.value += TM_YEAR_BASE;
+ pc.year.digits = 0;
+ pc.month = tmp->tm_mon + 1;
+ pc.day = tmp->tm_mday;
+ pc.hour = tmp->tm_hour;
+ pc.minutes = tmp->tm_min;
+ pc.seconds.tv_sec = tmp->tm_sec;
+ pc.seconds.tv_nsec = Start_ns;
+ tm.tm_isdst = tmp->tm_isdst;
+
+ pc.meridian = MER24;
+ pc.rel = RELATIVE_TIME_0;
+ pc.timespec_seen = false;
+ pc.rels_seen = false;
+ pc.dates_seen = 0;
+ pc.days_seen = 0;
+ pc.times_seen = 0;
+ pc.local_zones_seen = 0;
+ pc.dsts_seen = 0;
+ pc.zones_seen = 0;
+
+#if HAVE_STRUCT_TM_TM_ZONE
+ pc.local_time_zone_table[0].name = tmp->tm_zone;
+ pc.local_time_zone_table[0].type = tLOCAL_ZONE;
+ pc.local_time_zone_table[0].value = tmp->tm_isdst;
+ pc.local_time_zone_table[1].name = NULL;
+
+ /* Probe the names used in the next three calendar quarters, looking
+ for a tm_isdst different from the one we already have. */
+ {
+ int quarter;
+ for (quarter = 1; quarter <= 3; quarter++)
+ {
+ time_t probe = Start + quarter * (90 * 24 * 60 * 60);
+ struct tm const *probe_tm = localtime (&probe);
+ if (probe_tm && probe_tm->tm_zone
+ && probe_tm->tm_isdst != pc.local_time_zone_table[0].value)
+ {
+ {
+ pc.local_time_zone_table[1].name = probe_tm->tm_zone;
+ pc.local_time_zone_table[1].type = tLOCAL_ZONE;
+ pc.local_time_zone_table[1].value = probe_tm->tm_isdst;
+ pc.local_time_zone_table[2].name = NULL;
+ }
+ break;
+ }
+ }
+ }
+#else
+#if HAVE_TZNAME
+ {
+# if !HAVE_DECL_TZNAME
+ extern char *tzname[];
+# endif
+ int i;
+ for (i = 0; i < 2; i++)
+ {
+ pc.local_time_zone_table[i].name = tzname[i];
+ pc.local_time_zone_table[i].type = tLOCAL_ZONE;
+ pc.local_time_zone_table[i].value = i;
+ }
+ pc.local_time_zone_table[i].name = NULL;
+ }
+#else
+ pc.local_time_zone_table[0].name = NULL;
+#endif
+#endif
+
+ if (pc.local_time_zone_table[0].name && pc.local_time_zone_table[1].name
+ && ! strcmp (pc.local_time_zone_table[0].name,
+ pc.local_time_zone_table[1].name))
+ {
+ /* This locale uses the same abbreviation for standard and
+ daylight times. So if we see that abbreviation, we don't
+ know whether it's daylight time. */
+ pc.local_time_zone_table[0].value = -1;
+ pc.local_time_zone_table[1].name = NULL;
+ }
+
+ if (yyparse (&pc) != 0)
+ goto fail;
+
+ if (pc.timespec_seen)
+ *result = pc.seconds;
+ else
+ {
+ if (1 < (pc.times_seen | pc.dates_seen | pc.days_seen | pc.dsts_seen
+ | (pc.local_zones_seen + pc.zones_seen)))
+ goto fail;
+
+ tm.tm_year = to_year (pc.year) - TM_YEAR_BASE;
+ tm.tm_mon = pc.month - 1;
+ tm.tm_mday = pc.day;
+ if (pc.times_seen || (pc.rels_seen && ! pc.dates_seen && ! pc.days_seen))
+ {
+ tm.tm_hour = to_hour (pc.hour, pc.meridian);
+ if (tm.tm_hour < 0)
+ goto fail;
+ tm.tm_min = pc.minutes;
+ tm.tm_sec = pc.seconds.tv_sec;
+ }
+ else
+ {
+ tm.tm_hour = tm.tm_min = tm.tm_sec = 0;
+ pc.seconds.tv_nsec = 0;
+ }
+
+ /* Let mktime deduce tm_isdst if we have an absolute time stamp. */
+ if (pc.dates_seen | pc.days_seen | pc.times_seen)
+ tm.tm_isdst = -1;
+
+ /* But if the input explicitly specifies local time with or without
+ DST, give mktime that information. */
+ if (pc.local_zones_seen)
+ tm.tm_isdst = pc.local_isdst;
+
+ tm0 = tm;
+
+ Start = mktime (&tm);
+
+ if (! mktime_ok (&tm0, &tm, Start))
+ {
+ if (! pc.zones_seen)
+ goto fail;
+ else
+ {
+ /* Guard against falsely reporting errors near the time_t
+ boundaries when parsing times in other time zones. For
+ example, suppose the input string "1969-12-31 23:00:00 -0100",
+ the current time zone is 8 hours ahead of UTC, and the min
+ time_t value is 1970-01-01 00:00:00 UTC. Then the min
+ localtime value is 1970-01-01 08:00:00, and mktime will
+ therefore fail on 1969-12-31 23:00:00. To work around the
+ problem, set the time zone to 1 hour behind UTC temporarily
+ by setting TZ="XXX1:00" and try mktime again. */
+
+ long int time_zone = pc.time_zone;
+ long int abs_time_zone = time_zone < 0 ? - time_zone : time_zone;
+ long int abs_time_zone_hour = abs_time_zone / 60;
+ int abs_time_zone_min = abs_time_zone % 60;
+ char tz1buf[sizeof "XXX+0:00"
+ + sizeof pc.time_zone * CHAR_BIT / 3];
+ if (!tz_was_altered)
+ tz0 = get_tz (tz0buf);
+ sprintf (tz1buf, "XXX%s%ld:%02d", &"-"[time_zone < 0],
+ abs_time_zone_hour, abs_time_zone_min);
+ if (setenv ("TZ", tz1buf, 1) != 0)
+ goto fail;
+ tz_was_altered = true;
+ tm = tm0;
+ Start = mktime (&tm);
+ if (! mktime_ok (&tm0, &tm, Start))
+ goto fail;
+ }
+ }
+
+ if (pc.days_seen && ! pc.dates_seen)
+ {
+ tm.tm_mday += ((pc.day_number - tm.tm_wday + 7) % 7
+ + 7 * (pc.day_ordinal
+ - (0 < pc.day_ordinal
+ && tm.tm_wday != pc.day_number)));
+ tm.tm_isdst = -1;
+ Start = mktime (&tm);
+ if (Start == (time_t) -1)
+ goto fail;
+ }
+
+ /* Add relative date. */
+ if (pc.rel.year | pc.rel.month | pc.rel.day)
+ {
+ int year = tm.tm_year + pc.rel.year;
+ int month = tm.tm_mon + pc.rel.month;
+ int day = tm.tm_mday + pc.rel.day;
+ if (((year < tm.tm_year) ^ (pc.rel.year < 0))
+ | ((month < tm.tm_mon) ^ (pc.rel.month < 0))
+ | ((day < tm.tm_mday) ^ (pc.rel.day < 0)))
+ goto fail;
+ tm.tm_year = year;
+ tm.tm_mon = month;
+ tm.tm_mday = day;
+ tm.tm_hour = tm0.tm_hour;
+ tm.tm_min = tm0.tm_min;
+ tm.tm_sec = tm0.tm_sec;
+ tm.tm_isdst = tm0.tm_isdst;
+ Start = mktime (&tm);
+ if (Start == (time_t) -1)
+ goto fail;
+ }
+
+ /* The only "output" of this if-block is an updated Start value,
+ so this block must follow others that clobber Start. */
+ if (pc.zones_seen)
+ {
+ long int delta = pc.time_zone * 60;
+ time_t t1;
+#ifdef HAVE_TM_GMTOFF
+ delta -= tm.tm_gmtoff;
+#else
+ time_t t = Start;
+ struct tm const *gmt = gmtime (&t);
+ if (! gmt)
+ goto fail;
+ delta -= tm_diff (&tm, gmt);
+#endif
+ t1 = Start - delta;
+ if ((Start < t1) != (delta < 0))
+ goto fail; /* time_t overflow */
+ Start = t1;
+ }
+
+ /* Add relative hours, minutes, and seconds. On hosts that support
+ leap seconds, ignore the possibility of leap seconds; e.g.,
+ "+ 10 minutes" adds 600 seconds, even if one of them is a
+ leap second. Typically this is not what the user wants, but it's
+ too hard to do it the other way, because the time zone indicator
+ must be applied before relative times, and if mktime is applied
+ again the time zone will be lost. */
+ {
+ long int sum_ns = pc.seconds.tv_nsec + pc.rel.ns;
+ long int normalized_ns = (sum_ns % BILLION + BILLION) % BILLION;
+ time_t t0 = Start;
+ long int d1 = 60 * 60 * pc.rel.hour;
+ time_t t1 = t0 + d1;
+ long int d2 = 60 * pc.rel.minutes;
+ time_t t2 = t1 + d2;
+ long_time_t d3 = pc.rel.seconds;
+ long_time_t t3 = t2 + d3;
+ long int d4 = (sum_ns - normalized_ns) / BILLION;
+ long_time_t t4 = t3 + d4;
+ time_t t5 = t4;
+
+ if ((d1 / (60 * 60) ^ pc.rel.hour)
+ | (d2 / 60 ^ pc.rel.minutes)
+ | ((t1 < t0) ^ (d1 < 0))
+ | ((t2 < t1) ^ (d2 < 0))
+ | ((t3 < t2) ^ (d3 < 0))
+ | ((t4 < t3) ^ (d4 < 0))
+ | (t5 != t4))
+ goto fail;
+
+ result->tv_sec = t5;
+ result->tv_nsec = normalized_ns;
+ }
+ }
+
+ goto done;
+
+ fail:
+ ok = false;
+ done:
+ if (tz_was_altered)
+ ok &= (tz0 ? setenv ("TZ", tz0, 1) : unsetenv ("TZ")) == 0;
+ if (tz0 != tz0buf)
+ free (tz0);
+ return ok;
+}
+
+#if TEST
+
+int
+main (int ac, char **av)
+{
+ char buff[BUFSIZ];
+
+ printf ("Enter date, or blank line to exit.\n\t> ");
+ fflush (stdout);
+
+ buff[BUFSIZ - 1] = '\0';
+ while (fgets (buff, BUFSIZ - 1, stdin) && buff[0])
+ {
+ struct timespec d;
+ struct tm const *tm;
+ if (! parse_datetime (&d, buff, NULL))
+ printf ("Bad format - couldn't convert.\n");
+ else if (! (tm = localtime (&d.tv_sec)))
+ {
+ long int sec = d.tv_sec;
+ printf ("localtime (%ld) failed\n", sec);
+ }
+ else
+ {
+ int ns = d.tv_nsec;
+ printf ("%04ld-%02d-%02d %02d:%02d:%02d.%09d\n",
+ tm->tm_year + 1900L, tm->tm_mon + 1, tm->tm_mday,
+ tm->tm_hour, tm->tm_min, tm->tm_sec, ns);
+ }
+ printf ("\t> ");
+ fflush (stdout);
+ }
+ return 0;
+}
+#endif /* TEST */
diff --git a/lib/pathmax.h b/lib/pathmax.h
index 6941e45..aee22f8 100644
--- a/lib/pathmax.h
+++ b/lib/pathmax.h
@@ -1,9 +1,10 @@
/* Define PATH_MAX somehow. Requires sys/types.h.
- Copyright (C) 1992, 1999, 2001, 2003, 2005 Free Software Foundation, Inc.
+ Copyright (C) 1992, 1999, 2001, 2003, 2005, 2009-2016 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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -12,12 +13,32 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program; if not, see <http://www.gnu.org/licenses/>. */
#ifndef _PATHMAX_H
# define _PATHMAX_H
+/* POSIX:2008 defines PATH_MAX to be the maximum number of bytes in a filename,
+ including the terminating NUL byte.
+ <http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/limits.h.html>
+ PATH_MAX is not defined on systems which have no limit on filename length,
+ such as GNU/Hurd.
+
+ This file does *not* define PATH_MAX always. Programs that use this file
+ can handle the GNU/Hurd case in several ways:
+ - Either with a package-wide handling, or with a per-file handling,
+ - Either through a
+ #ifdef PATH_MAX
+ or through a fallback like
+ #ifndef PATH_MAX
+ # define PATH_MAX 8192
+ #endif
+ or through a fallback like
+ #ifndef PATH_MAX
+ # define PATH_MAX pathconf ("/", _PC_PATH_MAX)
+ #endif
+ */
+
# include <unistd.h>
# include <limits.h>
@@ -26,11 +47,6 @@
# define _POSIX_PATH_MAX 256
# endif
-# if !defined PATH_MAX && defined _PC_PATH_MAX
-# define PATH_MAX (pathconf ("/", _PC_PATH_MAX) < 1 ? 1024 \
- : pathconf ("/", _PC_PATH_MAX))
-# endif
-
/* Don't include sys/param.h if it already has been. */
# if defined HAVE_SYS_PARAM_H && !defined PATH_MAX && !defined MAXPATHLEN
# include <sys/param.h>
@@ -40,8 +56,28 @@
# define PATH_MAX MAXPATHLEN
# endif
-# ifndef PATH_MAX
-# define PATH_MAX _POSIX_PATH_MAX
+# ifdef __hpux
+/* On HP-UX, PATH_MAX designates the maximum number of bytes in a filename,
+ *not* including the terminating NUL byte, and is set to 1023.
+ Additionally, when _XOPEN_SOURCE is defined to 500 or more, PATH_MAX is
+ not defined at all any more. */
+# undef PATH_MAX
+# define PATH_MAX 1024
+# endif
+
+# if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+/* The page "Naming Files, Paths, and Namespaces" on msdn.microsoft.com,
+ section "Maximum Path Length Limitation",
+ <http://msdn.microsoft.com/en-us/library/aa365247(v=vs.85).aspx#maxpath>
+ explains that the maximum size of a filename, including the terminating
+ NUL byte, is 260 = 3 + 256 + 1.
+ This is the same value as
+ - FILENAME_MAX in <stdio.h>,
+ - _MAX_PATH in <stdlib.h>,
+ - MAX_PATH in <windef.h>.
+ Undefine the original value, because mingw's <limits.h> gets it wrong. */
+# undef PATH_MAX
+# define PATH_MAX 260
# endif
#endif /* _PATHMAX_H */
diff --git a/lib/physmem.c b/lib/physmem.c
index 844817b..6d405f7 100644
--- a/lib/physmem.c
+++ b/lib/physmem.c
@@ -1,12 +1,12 @@
/* Calculate the size of physical memory.
- Copyright (C) 2000, 2001, 2003, 2005, 2006 Free Software
+ Copyright (C) 2000-2001, 2003, 2005-2006, 2009-2016 Free Software
Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
@@ -33,8 +32,11 @@
# include <sys/sysmp.h>
#endif
-#if HAVE_SYS_SYSINFO_H && HAVE_MACHINE_HAL_SYSINFO_H
+#if HAVE_SYS_SYSINFO_H
# include <sys/sysinfo.h>
+#endif
+
+#if HAVE_MACHINE_HAL_SYSINFO_H
# include <machine/hal_sysinfo.h>
#endif
@@ -91,15 +93,23 @@ physmem_total (void)
}
#endif
+#if HAVE_SYSINFO && HAVE_STRUCT_SYSINFO_MEM_UNIT
+ { /* This works on linux. */
+ struct sysinfo si;
+ if (sysinfo(&si) == 0)
+ return (double) si.totalram * si.mem_unit;
+ }
+#endif
+
#if HAVE_PSTAT_GETSTATIC
{ /* This works on hpux11. */
struct pst_static pss;
if (0 <= pstat_getstatic (&pss, sizeof pss, 1, 0))
{
- double pages = pss.physical_memory;
- double pagesize = pss.page_size;
- if (0 <= pages && 0 <= pagesize)
- return pages * pagesize;
+ double pages = pss.physical_memory;
+ double pagesize = pss.page_size;
+ if (0 <= pages && 0 <= pagesize)
+ return pages * pagesize;
}
}
#endif
@@ -109,10 +119,10 @@ physmem_total (void)
struct rminfo realmem;
if (sysmp (MP_SAGET, MPSA_RMINFO, &realmem, sizeof realmem) == 0)
{
- double pagesize = sysconf (_SC_PAGESIZE);
- double pages = realmem.physmem;
- if (0 <= pages && 0 <= pagesize)
- return pages * pagesize;
+ double pagesize = sysconf (_SC_PAGESIZE);
+ double pages = realmem.physmem;
+ if (0 <= pages && 0 <= pagesize)
+ return pages * pagesize;
}
}
#endif
@@ -122,12 +132,12 @@ physmem_total (void)
int physmem;
if (getsysinfo (GSI_PHYSMEM, (caddr_t) &physmem, sizeof (physmem),
- NULL, NULL, NULL) == 1)
+ NULL, NULL, NULL) == 1)
{
- double kbytes = physmem;
+ double kbytes = physmem;
- if (0 <= kbytes)
- return kbytes * 1024.0;
+ if (0 <= kbytes)
+ return kbytes * 1024.0;
}
}
#endif
@@ -139,7 +149,7 @@ physmem_total (void)
static int mib[2] = { CTL_HW, HW_PHYSMEM };
if (sysctl (mib, ARRAY_SIZE (mib), &physmem, &len, NULL, 0) == 0
- && len == sizeof (physmem))
+ && len == sizeof (physmem))
return (double) physmem;
}
#endif
@@ -160,20 +170,20 @@ physmem_total (void)
/* Use GlobalMemoryStatusEx if available. */
if ((pfnex = (PFN_MS_EX) GetProcAddress (h, "GlobalMemoryStatusEx")))
{
- lMEMORYSTATUSEX lms_ex;
- lms_ex.dwLength = sizeof lms_ex;
- if (!pfnex (&lms_ex))
- return 0.0;
- return (double) lms_ex.ullTotalPhys;
+ lMEMORYSTATUSEX lms_ex;
+ lms_ex.dwLength = sizeof lms_ex;
+ if (!pfnex (&lms_ex))
+ return 0.0;
+ return (double) lms_ex.ullTotalPhys;
}
/* Fall back to GlobalMemoryStatus which is always available.
but returns wrong results for physical memory > 4GB. */
else
{
- MEMORYSTATUS ms;
- GlobalMemoryStatus (&ms);
- return (double) ms.dwTotalPhys;
+ MEMORYSTATUS ms;
+ GlobalMemoryStatus (&ms);
+ return (double) ms.dwTotalPhys;
}
}
#endif
@@ -195,17 +205,25 @@ physmem_available (void)
}
#endif
+#if HAVE_SYSINFO && HAVE_STRUCT_SYSINFO_MEM_UNIT
+ { /* This works on linux. */
+ struct sysinfo si;
+ if (sysinfo(&si) == 0)
+ return ((double) si.freeram + si.bufferram) * si.mem_unit;
+ }
+#endif
+
#if HAVE_PSTAT_GETSTATIC && HAVE_PSTAT_GETDYNAMIC
{ /* This works on hpux11. */
struct pst_static pss;
struct pst_dynamic psd;
if (0 <= pstat_getstatic (&pss, sizeof pss, 1, 0)
- && 0 <= pstat_getdynamic (&psd, sizeof psd, 1, 0))
+ && 0 <= pstat_getdynamic (&psd, sizeof psd, 1, 0))
{
- double pages = psd.psd_free;
- double pagesize = pss.page_size;
- if (0 <= pages && 0 <= pagesize)
- return pages * pagesize;
+ double pages = psd.psd_free;
+ double pagesize = pss.page_size;
+ if (0 <= pages && 0 <= pagesize)
+ return pages * pagesize;
}
}
#endif
@@ -215,10 +233,10 @@ physmem_available (void)
struct rminfo realmem;
if (sysmp (MP_SAGET, MPSA_RMINFO, &realmem, sizeof realmem) == 0)
{
- double pagesize = sysconf (_SC_PAGESIZE);
- double pages = realmem.availrmem;
- if (0 <= pages && 0 <= pagesize)
- return pages * pagesize;
+ double pagesize = sysconf (_SC_PAGESIZE);
+ double pages = realmem.availrmem;
+ if (0 <= pages && 0 <= pagesize)
+ return pages * pagesize;
}
}
#endif
@@ -229,11 +247,11 @@ physmem_available (void)
if (table (TBL_VMSTATS, 0, &vmstats, 1, sizeof (vmstats)) == 1)
{
- double pages = vmstats.free_count;
- double pagesize = vmstats.pagesize;
+ double pages = vmstats.free_count;
+ double pagesize = vmstats.pagesize;
- if (0 <= pages && 0 <= pagesize)
- return pages * pagesize;
+ if (0 <= pages && 0 <= pagesize)
+ return pages * pagesize;
}
}
#endif
@@ -245,7 +263,7 @@ physmem_available (void)
static int mib[2] = { CTL_HW, HW_USERMEM };
if (sysctl (mib, ARRAY_SIZE (mib), &usermem, &len, NULL, 0) == 0
- && len == sizeof (usermem))
+ && len == sizeof (usermem))
return (double) usermem;
}
#endif
@@ -261,20 +279,20 @@ physmem_available (void)
/* Use GlobalMemoryStatusEx if available. */
if ((pfnex = (PFN_MS_EX) GetProcAddress (h, "GlobalMemoryStatusEx")))
{
- lMEMORYSTATUSEX lms_ex;
- lms_ex.dwLength = sizeof lms_ex;
- if (!pfnex (&lms_ex))
- return 0.0;
- return (double) lms_ex.ullAvailPhys;
+ lMEMORYSTATUSEX lms_ex;
+ lms_ex.dwLength = sizeof lms_ex;
+ if (!pfnex (&lms_ex))
+ return 0.0;
+ return (double) lms_ex.ullAvailPhys;
}
/* Fall back to GlobalMemoryStatus which is always available.
but returns wrong results for physical memory > 4GB */
else
{
- MEMORYSTATUS ms;
- GlobalMemoryStatus (&ms);
- return (double) ms.dwAvailPhys;
+ MEMORYSTATUS ms;
+ GlobalMemoryStatus (&ms);
+ return (double) ms.dwAvailPhys;
}
}
#endif
diff --git a/lib/physmem.h b/lib/physmem.h
index 931aede..73ed0b4 100644
--- a/lib/physmem.h
+++ b/lib/physmem.h
@@ -1,11 +1,11 @@
/* Calculate the size of physical memory.
- Copyright (C) 2000, 2003 Free Software Foundation, Inc.
+ Copyright (C) 2000, 2003, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
diff --git a/lib/pipe-safer.c b/lib/pipe-safer.c
index e4431b3..fc6144e 100644
--- a/lib/pipe-safer.c
+++ b/lib/pipe-safer.c
@@ -1,10 +1,10 @@
/* Invoke pipe, but avoid some glitches.
- Copyright (C) 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2005-2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -12,8 +12,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Jim Meyering. */
@@ -36,16 +35,16 @@ pipe_safer (int fd[2])
{
int i;
for (i = 0; i < 2; i++)
- {
- fd[i] = fd_safer (fd[i]);
- if (fd[i] < 0)
- {
- int e = errno;
- close (fd[1 - i]);
- errno = e;
- return -1;
- }
- }
+ {
+ fd[i] = fd_safer (fd[i]);
+ if (fd[i] < 0)
+ {
+ int e = errno;
+ close (fd[1 - i]);
+ errno = e;
+ return -1;
+ }
+ }
return 0;
}
diff --git a/lib/pipe.c b/lib/pipe.c
new file mode 100644
index 0000000..cc8e184
--- /dev/null
+++ b/lib/pipe.c
@@ -0,0 +1,50 @@
+/* Create a pipe.
+ Copyright (C) 2009-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <unistd.h>
+
+#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+/* Native Windows API. */
+
+/* Get _pipe(). */
+# include <io.h>
+
+/* Get _O_BINARY. */
+# include <fcntl.h>
+
+int
+pipe (int fd[2])
+{
+ /* Mingw changes fd to {-1,-1} on failure, but this violates
+ http://austingroupbugs.net/view.php?id=467 */
+ int tmp[2];
+ int result = _pipe (tmp, 4096, _O_BINARY);
+ if (!result)
+ {
+ fd[0] = tmp[0];
+ fd[1] = tmp[1];
+ }
+ return result;
+}
+
+#else
+
+# error "This platform lacks a pipe function, and Gnulib doesn't provide a replacement. This is a bug in Gnulib."
+
+#endif
diff --git a/lib/posixtm.c b/lib/posixtm.c
index 5514ba4..b9148d2 100644
--- a/lib/posixtm.c
+++ b/lib/posixtm.c
@@ -1,12 +1,11 @@
/* Parse dates for touch and date.
- Copyright (C) 1989, 1990, 1991, 1998, 2000, 2001, 2002, 2003, 2004,
- 2005, 2006, 2007 Free Software Foundation Inc.
+ Copyright (C) 1989-1991, 1998, 2000-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Yacc-based version written by Jim Kingdon and David MacKenzie.
Rewritten by Jim Meyering. */
@@ -39,11 +37,9 @@
- It's typically faster.
POSIX says that only '0' through '9' are digits. Prefer ISDIGIT to
isdigit unless it's important to use the locale's definition
- of `digit' even when the host does not conform to POSIX. */
+ of "digit" even when the host does not conform to POSIX. */
#define ISDIGIT(c) ((unsigned int) (c) - '0' <= 9)
-time_t mktime ();
-
/*
POSIX requires:
@@ -61,7 +57,7 @@ time_t mktime ();
*/
-static int
+static bool
year (struct tm *tm, const int *digit_pair, size_t n, unsigned int syntax_bits)
{
switch (n)
@@ -69,33 +65,33 @@ year (struct tm *tm, const int *digit_pair, size_t n, unsigned int syntax_bits)
case 1:
tm->tm_year = *digit_pair;
/* Deduce the century based on the year.
- POSIX requires that 00-68 be interpreted as 2000-2068,
- and that 69-99 be interpreted as 1969-1999. */
+ POSIX requires that 00-68 be interpreted as 2000-2068,
+ and that 69-99 be interpreted as 1969-1999. */
if (digit_pair[0] <= 68)
- {
- if (syntax_bits & PDS_PRE_2000)
- return 1;
- tm->tm_year += 100;
- }
+ {
+ if (syntax_bits & PDS_PRE_2000)
+ return false;
+ tm->tm_year += 100;
+ }
break;
case 2:
if (! (syntax_bits & PDS_CENTURY))
- return 1;
+ return false;
tm->tm_year = digit_pair[0] * 100 + digit_pair[1] - 1900;
break;
case 0:
{
- time_t now;
- struct tm *tmp;
-
- /* Use current year. */
- time (&now);
- tmp = localtime (&now);
- if (! tmp)
- return 1;
- tm->tm_year = tmp->tm_year;
+ time_t now;
+ struct tm *tmp;
+
+ /* Use current year. */
+ time (&now);
+ tmp = localtime (&now);
+ if (! tmp)
+ return false;
+ tm->tm_year = tmp->tm_year;
}
break;
@@ -103,10 +99,10 @@ year (struct tm *tm, const int *digit_pair, size_t n, unsigned int syntax_bits)
abort ();
}
- return 0;
+ return true;
}
-static int
+static bool
posix_time_parse (struct tm *tm, const char *s, unsigned int syntax_bits)
{
const char *dot = NULL;
@@ -115,25 +111,25 @@ posix_time_parse (struct tm *tm, const char *s, unsigned int syntax_bits)
size_t i;
size_t s_len = strlen (s);
- size_t len = (((syntax_bits & PDS_SECONDS) && (dot = strchr (s, '.')))
- ? (size_t) (dot - s)
- : s_len);
-
- if (len != 8 && len != 10 && len != 12)
- return 1;
+ size_t len = s_len;
- if (dot)
+ if (syntax_bits & PDS_SECONDS)
{
- if (!(syntax_bits & PDS_SECONDS))
- return 1;
-
- if (s_len - len != 3)
- return 1;
+ dot = strchr (s, '.');
+ if (dot)
+ {
+ len = dot - s;
+ if (s_len - len != 3)
+ return false;
+ }
}
+ if (! (8 <= len && len <= 12 && len % 2 == 0))
+ return false;
+
for (i = 0; i < len; i++)
if (!ISDIGIT (s[i]))
- return 1;
+ return false;
len /= 2;
for (i = 0; i < len; i++)
@@ -142,13 +138,13 @@ posix_time_parse (struct tm *tm, const char *s, unsigned int syntax_bits)
p = pair;
if (syntax_bits & PDS_LEADING_YEAR)
{
- if (year (tm, p, len - 4, syntax_bits))
- return 1;
+ if (! year (tm, p, len - 4, syntax_bits))
+ return false;
p += len - 4;
len = 4;
}
- /* Handle 8 digits worth of `MMDDhhmm'. */
+ /* Handle 8 digits worth of 'MMDDhhmm'. */
tm->tm_mon = *p++ - 1;
tm->tm_mday = *p++;
tm->tm_hour = *p++;
@@ -158,28 +154,19 @@ posix_time_parse (struct tm *tm, const char *s, unsigned int syntax_bits)
/* Handle any trailing year. */
if (syntax_bits & PDS_TRAILING_YEAR)
{
- if (year (tm, p, len, syntax_bits))
- return 1;
+ if (! year (tm, p, len, syntax_bits))
+ return false;
}
/* Handle seconds. */
if (!dot)
- {
- tm->tm_sec = 0;
- }
+ tm->tm_sec = 0;
+ else if (ISDIGIT (dot[1]) && ISDIGIT (dot[2]))
+ tm->tm_sec = 10 * (dot[1] - '0') + dot[2] - '0';
else
- {
- int seconds;
-
- ++dot;
- if (!ISDIGIT (dot[0]) || !ISDIGIT (dot[1]))
- return 1;
- seconds = 10 * (dot[0] - '0') + dot[1] - '0';
-
- tm->tm_sec = seconds;
- }
+ return false;
- return 0;
+ return true;
}
/* Parse a POSIX-style date, returning true if successful. */
@@ -187,20 +174,12 @@ posix_time_parse (struct tm *tm, const char *s, unsigned int syntax_bits)
bool
posixtime (time_t *p, const char *s, unsigned int syntax_bits)
{
- struct tm tm0
-#ifdef lint
- /* Placate gcc-4's -Wuninitialized.
- posix_time_parse fails to set all of tm0 only when it returns
- nonzero (due to year() returning nonzero), and in that case,
- this code doesn't use the tm0 at all. */
- = { 0, }
-#endif
- ;
+ struct tm tm0;
struct tm tm1;
struct tm const *tm;
time_t t;
- if (posix_time_parse (&tm0, s, syntax_bits))
+ if (! posix_time_parse (&tm0, s, syntax_bits))
return false;
tm1 = tm0;
@@ -212,117 +191,38 @@ posixtime (time_t *p, const char *s, unsigned int syntax_bits)
else
{
/* mktime returns -1 for errors, but -1 is also a valid time_t
- value. Check whether an error really occurred. */
+ value. Check whether an error really occurred. */
tm = localtime (&t);
if (! tm)
- return false;
+ return false;
}
- /* Reject dates like "September 31" and times like "25:61". */
+ /* Reject dates like "September 31" and times like "25:61".
+ However, allow a seconds count of 60 even in time zones that do
+ not support leap seconds, treating it as the following second;
+ POSIX requires this. */
if ((tm0.tm_year ^ tm->tm_year)
| (tm0.tm_mon ^ tm->tm_mon)
| (tm0.tm_mday ^ tm->tm_mday)
| (tm0.tm_hour ^ tm->tm_hour)
| (tm0.tm_min ^ tm->tm_min)
| (tm0.tm_sec ^ tm->tm_sec))
- return false;
-
- *p = t;
- return true;
-}
-
-#ifdef TEST_POSIXTIME
-/*
- Test mainly with syntax_bits == 13
- (aka: (PDS_LEADING_YEAR | PDS_CENTURY | PDS_SECONDS))
-
- This test data assumes Universal Time, e.g., TZ="UTC0".
-
- This test data also assumes that time_t is signed and is at least
- 39 bits wide, so that it can represent all years from 0000 through
- 9999. A host with 32-bit signed time_t can represent only time
- stamps in the range 1901-12-13 20:45:52 through 2038-01-18
- 03:14:07 UTC, assuming POSIX time_t with no leap seconds, so test
- cases outside this range will not work on such a host.
-
- Also, the first two lines of test data assume that the current
- year is 2002.
-
-BEGIN-DATA
-12131415.16 13 1039788916 Fri Dec 13 14:15:16 2002
-12131415.16 13 1039788916 Fri Dec 13 14:15:16 2002
-000001010000.00 13 -62167132800 Sun Jan 1 00:00:00 0000
-190112132045.52 13 -2147483648 Fri Dec 13 20:45:52 1901
-190112132045.53 13 -2147483647 Fri Dec 13 20:45:53 1901
-190112132046.52 13 -2147483588 Fri Dec 13 20:46:52 1901
-190112132145.52 13 -2147480048 Fri Dec 13 21:45:52 1901
-190112142045.52 13 -2147397248 Sat Dec 14 20:45:52 1901
-190201132045.52 13 -2144805248 Mon Jan 13 20:45:52 1902
-196912312359.59 13 -1 Wed Dec 31 23:59:59 1969
-197001010000.00 13 0 Thu Jan 1 00:00:00 1970
-197001010000.01 13 1 Thu Jan 1 00:00:01 1970
-197001010001.00 13 60 Thu Jan 1 00:01:00 1970
-197001010100.00 13 3600 Thu Jan 1 01:00:00 1970
-197001020000.00 13 86400 Fri Jan 2 00:00:00 1970
-197002010000.00 13 2678400 Sun Feb 1 00:00:00 1970
-197101010000.00 13 31536000 Fri Jan 1 00:00:00 1971
-197001000000.00 13 * *
-197000010000.00 13 * *
-197001010000.60 13 * *
-197001010060.00 13 * *
-197001012400.00 13 * *
-197001320000.00 13 * *
-197013010000.00 13 * *
-203801190314.06 13 2147483646 Tue Jan 19 03:14:06 2038
-203801190314.07 13 2147483647 Tue Jan 19 03:14:07 2038
-203801190314.08 13 2147483648 Tue Jan 19 03:14:08 2038
-999912312359.59 13 253402300799 Fri Dec 31 23:59:59 9999
-1112131415 13 1323785700 Tue Dec 13 14:15:00 2011
-1112131415.16 13 1323785716 Tue Dec 13 14:15:16 2011
-201112131415.16 13 1323785716 Tue Dec 13 14:15:16 2011
-191112131415.16 13 -1831974284 Wed Dec 13 14:15:16 1911
-203712131415.16 13 2144326516 Sun Dec 13 14:15:16 2037
-3712131415.16 13 2144326516 Sun Dec 13 14:15:16 2037
-6812131415.16 13 3122633716 Thu Dec 13 14:15:16 2068
-6912131415.16 13 -1590284 Sat Dec 13 14:15:16 1969
-7012131415.16 13 29945716 Sun Dec 13 14:15:16 1970
-1213141599 2 945094500 Mon Dec 13 14:15:00 1999
-1213141500 2 976716900 Wed Dec 13 14:15:00 2000
-END-DATA
-
-*/
-
-# define MAX_BUFF_LEN 1024
-
-int
-main (void)
-{
- char buff[MAX_BUFF_LEN + 1];
-
- buff[MAX_BUFF_LEN] = 0;
- while (fgets (buff, MAX_BUFF_LEN, stdin) && buff[0])
{
- char time_str[MAX_BUFF_LEN];
- unsigned int syntax_bits;
- time_t t;
- if (sscanf (buff, "%s %u", time_str, &syntax_bits) != 2)
- printf ("*\n");
- else
- {
- printf ("%-15s %2u ", time_str, syntax_bits);
- if (posixtime (&t, time_str, syntax_bits))
- printf ("%12ld %s", (long int) t, ctime (&t));
- else
- printf ("%12s %s", "*", "*\n");
- }
+ /* Any mismatch without 60 in the tm_sec field is invalid. */
+ if (tm0.tm_sec != 60)
+ return false;
+
+ {
+ /* Allow times like 01:35:60 or 23:59:60. */
+ time_t dummy;
+ char buf[16];
+ char *b = stpcpy (buf, s);
+ strcpy (b - 2, "59");
+ if (!posixtime (&dummy, buf, syntax_bits))
+ return false;
+ }
}
- exit (0);
+ *p = t;
+ return true;
}
-#endif
-
-/*
-Local Variables:
-compile-command: "gcc -DTEST_POSIXTIME -g -O -Wall -W posixtm.c"
-End:
-*/
diff --git a/lib/posixtm.h b/lib/posixtm.h
index e91749d..4dcb522 100644
--- a/lib/posixtm.h
+++ b/lib/posixtm.h
@@ -1,11 +1,11 @@
/* Parse dates for touch and date.
- Copyright (C) 1998, 2003, 2005, 2007 Free Software Foundation Inc.
+ Copyright (C) 1998, 2003, 2005, 2007-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Yacc-based version written by Jim Kingdon and David MacKenzie.
Rewritten by Jim Meyering. */
diff --git a/lib/posixver.c b/lib/posixver.c
index e7b4699..61f07e4 100644
--- a/lib/posixver.c
+++ b/lib/posixver.c
@@ -1,21 +1,19 @@
/* Which POSIX version to conform to, for utilities.
- Copyright (C) 2002, 2003, 2004, 2005, 2006 Free Software
- Foundation, Inc.
+ Copyright (C) 2002-2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
@@ -49,7 +47,7 @@ posix2_version (void)
char *e;
long int i = strtol (s, &e, 10);
if (! *e)
- v = i;
+ v = i;
}
return v < INT_MIN ? INT_MIN : v < INT_MAX ? v : INT_MAX;
diff --git a/lib/printf-args.c b/lib/printf-args.c
index 2259d53..cfaed99 100644
--- a/lib/printf-args.c
+++ b/lib/printf-args.c
@@ -1,9 +1,10 @@
/* Decomposed printf argument list.
- Copyright (C) 1999, 2002-2003, 2005-2007 Free Software Foundation, Inc.
+ Copyright (C) 1999, 2002-2003, 2005-2007, 2009-2016 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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -12,19 +13,27 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ with this program; if not, see <http://www.gnu.org/licenses/>. */
-#include <config.h>
+/* This file can be parametrized with the following macros:
+ ENABLE_UNISTDIO Set to 1 to enable the unistdio extensions.
+ PRINTF_FETCHARGS Name of the function to be defined.
+ STATIC Set to 'static' to declare the function static. */
+
+#ifndef PRINTF_FETCHARGS
+# include <config.h>
+#endif
/* Specification. */
-#include "printf-args.h"
+#ifndef PRINTF_FETCHARGS
+# include "printf-args.h"
+#endif
#ifdef STATIC
STATIC
#endif
int
-printf_fetchargs (va_list args, arguments *a)
+PRINTF_FETCHARGS (va_list args, arguments *a)
{
size_t i;
argument *ap;
@@ -33,109 +42,146 @@ printf_fetchargs (va_list args, arguments *a)
switch (ap->type)
{
case TYPE_SCHAR:
- ap->a.a_schar = va_arg (args, /*signed char*/ int);
- break;
+ ap->a.a_schar = va_arg (args, /*signed char*/ int);
+ break;
case TYPE_UCHAR:
- ap->a.a_uchar = va_arg (args, /*unsigned char*/ int);
- break;
+ ap->a.a_uchar = va_arg (args, /*unsigned char*/ int);
+ break;
case TYPE_SHORT:
- ap->a.a_short = va_arg (args, /*short*/ int);
- break;
+ ap->a.a_short = va_arg (args, /*short*/ int);
+ break;
case TYPE_USHORT:
- ap->a.a_ushort = va_arg (args, /*unsigned short*/ int);
- break;
+ ap->a.a_ushort = va_arg (args, /*unsigned short*/ int);
+ break;
case TYPE_INT:
- ap->a.a_int = va_arg (args, int);
- break;
+ ap->a.a_int = va_arg (args, int);
+ break;
case TYPE_UINT:
- ap->a.a_uint = va_arg (args, unsigned int);
- break;
+ ap->a.a_uint = va_arg (args, unsigned int);
+ break;
case TYPE_LONGINT:
- ap->a.a_longint = va_arg (args, long int);
- break;
+ ap->a.a_longint = va_arg (args, long int);
+ break;
case TYPE_ULONGINT:
- ap->a.a_ulongint = va_arg (args, unsigned long int);
- break;
+ ap->a.a_ulongint = va_arg (args, unsigned long int);
+ break;
#if HAVE_LONG_LONG_INT
case TYPE_LONGLONGINT:
- ap->a.a_longlongint = va_arg (args, long long int);
- break;
+ ap->a.a_longlongint = va_arg (args, long long int);
+ break;
case TYPE_ULONGLONGINT:
- ap->a.a_ulonglongint = va_arg (args, unsigned long long int);
- break;
+ ap->a.a_ulonglongint = va_arg (args, unsigned long long int);
+ break;
#endif
case TYPE_DOUBLE:
- ap->a.a_double = va_arg (args, double);
- break;
-#if HAVE_LONG_DOUBLE
+ ap->a.a_double = va_arg (args, double);
+ break;
case TYPE_LONGDOUBLE:
- ap->a.a_longdouble = va_arg (args, long double);
- break;
-#endif
+ ap->a.a_longdouble = va_arg (args, long double);
+ break;
case TYPE_CHAR:
- ap->a.a_char = va_arg (args, int);
- break;
+ ap->a.a_char = va_arg (args, int);
+ break;
#if HAVE_WINT_T
case TYPE_WIDE_CHAR:
- /* Although ISO C 99 7.24.1.(2) says that wint_t is "unchanged by
- default argument promotions", this is not the case in mingw32,
- where wint_t is 'unsigned short'. */
- ap->a.a_wide_char =
- (sizeof (wint_t) < sizeof (int)
- ? va_arg (args, int)
- : va_arg (args, wint_t));
- break;
+ /* Although ISO C 99 7.24.1.(2) says that wint_t is "unchanged by
+ default argument promotions", this is not the case in mingw32,
+ where wint_t is 'unsigned short'. */
+ ap->a.a_wide_char =
+ (sizeof (wint_t) < sizeof (int)
+ ? (wint_t) va_arg (args, int)
+ : va_arg (args, wint_t));
+ break;
#endif
case TYPE_STRING:
- ap->a.a_string = va_arg (args, const char *);
- /* A null pointer is an invalid argument for "%s", but in practice
- it occurs quite frequently in printf statements that produce
- debug output. Use a fallback in this case. */
- if (ap->a.a_string == NULL)
- ap->a.a_string = "(NULL)";
- break;
+ ap->a.a_string = va_arg (args, const char *);
+ /* A null pointer is an invalid argument for "%s", but in practice
+ it occurs quite frequently in printf statements that produce
+ debug output. Use a fallback in this case. */
+ if (ap->a.a_string == NULL)
+ ap->a.a_string = "(NULL)";
+ break;
#if HAVE_WCHAR_T
case TYPE_WIDE_STRING:
- ap->a.a_wide_string = va_arg (args, const wchar_t *);
- /* A null pointer is an invalid argument for "%ls", but in practice
- it occurs quite frequently in printf statements that produce
- debug output. Use a fallback in this case. */
- if (ap->a.a_wide_string == NULL)
- {
- static const wchar_t wide_null_string[] =
- {
- (wchar_t)'(',
- (wchar_t)'N', (wchar_t)'U', (wchar_t)'L', (wchar_t)'L',
- (wchar_t)')',
- (wchar_t)0
- };
- ap->a.a_wide_string = wide_null_string;
- }
- break;
+ ap->a.a_wide_string = va_arg (args, const wchar_t *);
+ /* A null pointer is an invalid argument for "%ls", but in practice
+ it occurs quite frequently in printf statements that produce
+ debug output. Use a fallback in this case. */
+ if (ap->a.a_wide_string == NULL)
+ {
+ static const wchar_t wide_null_string[] =
+ {
+ (wchar_t)'(',
+ (wchar_t)'N', (wchar_t)'U', (wchar_t)'L', (wchar_t)'L',
+ (wchar_t)')',
+ (wchar_t)0
+ };
+ ap->a.a_wide_string = wide_null_string;
+ }
+ break;
#endif
case TYPE_POINTER:
- ap->a.a_pointer = va_arg (args, void *);
- break;
+ ap->a.a_pointer = va_arg (args, void *);
+ break;
case TYPE_COUNT_SCHAR_POINTER:
- ap->a.a_count_schar_pointer = va_arg (args, signed char *);
- break;
+ ap->a.a_count_schar_pointer = va_arg (args, signed char *);
+ break;
case TYPE_COUNT_SHORT_POINTER:
- ap->a.a_count_short_pointer = va_arg (args, short *);
- break;
+ ap->a.a_count_short_pointer = va_arg (args, short *);
+ break;
case TYPE_COUNT_INT_POINTER:
- ap->a.a_count_int_pointer = va_arg (args, int *);
- break;
+ ap->a.a_count_int_pointer = va_arg (args, int *);
+ break;
case TYPE_COUNT_LONGINT_POINTER:
- ap->a.a_count_longint_pointer = va_arg (args, long int *);
- break;
+ ap->a.a_count_longint_pointer = va_arg (args, long int *);
+ break;
#if HAVE_LONG_LONG_INT
case TYPE_COUNT_LONGLONGINT_POINTER:
- ap->a.a_count_longlongint_pointer = va_arg (args, long long int *);
- break;
+ ap->a.a_count_longlongint_pointer = va_arg (args, long long int *);
+ break;
+#endif
+#if ENABLE_UNISTDIO
+ /* The unistdio extensions. */
+ case TYPE_U8_STRING:
+ ap->a.a_u8_string = va_arg (args, const uint8_t *);
+ /* A null pointer is an invalid argument for "%U", but in practice
+ it occurs quite frequently in printf statements that produce
+ debug output. Use a fallback in this case. */
+ if (ap->a.a_u8_string == NULL)
+ {
+ static const uint8_t u8_null_string[] =
+ { '(', 'N', 'U', 'L', 'L', ')', 0 };
+ ap->a.a_u8_string = u8_null_string;
+ }
+ break;
+ case TYPE_U16_STRING:
+ ap->a.a_u16_string = va_arg (args, const uint16_t *);
+ /* A null pointer is an invalid argument for "%lU", but in practice
+ it occurs quite frequently in printf statements that produce
+ debug output. Use a fallback in this case. */
+ if (ap->a.a_u16_string == NULL)
+ {
+ static const uint16_t u16_null_string[] =
+ { '(', 'N', 'U', 'L', 'L', ')', 0 };
+ ap->a.a_u16_string = u16_null_string;
+ }
+ break;
+ case TYPE_U32_STRING:
+ ap->a.a_u32_string = va_arg (args, const uint32_t *);
+ /* A null pointer is an invalid argument for "%llU", but in practice
+ it occurs quite frequently in printf statements that produce
+ debug output. Use a fallback in this case. */
+ if (ap->a.a_u32_string == NULL)
+ {
+ static const uint32_t u32_null_string[] =
+ { '(', 'N', 'U', 'L', 'L', ')', 0 };
+ ap->a.a_u32_string = u32_null_string;
+ }
+ break;
#endif
default:
- /* Unknown type. */
- return -1;
+ /* Unknown type. */
+ return -1;
}
return 0;
}
diff --git a/lib/printf-args.h b/lib/printf-args.h
index 74a18d9..256c413 100644
--- a/lib/printf-args.h
+++ b/lib/printf-args.h
@@ -1,9 +1,10 @@
/* Decomposed printf argument list.
- Copyright (C) 1999, 2002-2003, 2006-2007 Free Software Foundation, Inc.
+ Copyright (C) 1999, 2002-2003, 2006-2007, 2011-2016 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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -12,12 +13,21 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ with this program; if not, see <http://www.gnu.org/licenses/>. */
#ifndef _PRINTF_ARGS_H
#define _PRINTF_ARGS_H
+/* This file can be parametrized with the following macros:
+ ENABLE_UNISTDIO Set to 1 to enable the unistdio extensions.
+ PRINTF_FETCHARGS Name of the function to be declared.
+ STATIC Set to 'static' to declare the function static. */
+
+/* Default parameters. */
+#ifndef PRINTF_FETCHARGS
+# define PRINTF_FETCHARGS printf_fetchargs
+#endif
+
/* Get size_t. */
#include <stddef.h>
@@ -52,9 +62,7 @@ typedef enum
TYPE_ULONGLONGINT,
#endif
TYPE_DOUBLE,
-#if HAVE_LONG_DOUBLE
TYPE_LONGDOUBLE,
-#endif
TYPE_CHAR,
#if HAVE_WINT_T
TYPE_WIDE_CHAR,
@@ -71,6 +79,12 @@ typedef enum
#if HAVE_LONG_LONG_INT
, TYPE_COUNT_LONGLONGINT_POINTER
#endif
+#if ENABLE_UNISTDIO
+ /* The unistdio extensions. */
+, TYPE_U8_STRING
+, TYPE_U16_STRING
+, TYPE_U32_STRING
+#endif
} arg_type;
/* Polymorphic argument */
@@ -79,48 +93,56 @@ typedef struct
arg_type type;
union
{
- signed char a_schar;
- unsigned char a_uchar;
- short a_short;
- unsigned short a_ushort;
- int a_int;
- unsigned int a_uint;
- long int a_longint;
- unsigned long int a_ulongint;
+ signed char a_schar;
+ unsigned char a_uchar;
+ short a_short;
+ unsigned short a_ushort;
+ int a_int;
+ unsigned int a_uint;
+ long int a_longint;
+ unsigned long int a_ulongint;
#if HAVE_LONG_LONG_INT
- long long int a_longlongint;
- unsigned long long int a_ulonglongint;
-#endif
- float a_float;
- double a_double;
-#if HAVE_LONG_DOUBLE
- long double a_longdouble;
+ long long int a_longlongint;
+ unsigned long long int a_ulonglongint;
#endif
- int a_char;
+ float a_float;
+ double a_double;
+ long double a_longdouble;
+ int a_char;
#if HAVE_WINT_T
- wint_t a_wide_char;
+ wint_t a_wide_char;
#endif
- const char* a_string;
+ const char* a_string;
#if HAVE_WCHAR_T
- const wchar_t* a_wide_string;
+ const wchar_t* a_wide_string;
#endif
- void* a_pointer;
- signed char * a_count_schar_pointer;
- short * a_count_short_pointer;
- int * a_count_int_pointer;
- long int * a_count_longint_pointer;
+ void* a_pointer;
+ signed char * a_count_schar_pointer;
+ short * a_count_short_pointer;
+ int * a_count_int_pointer;
+ long int * a_count_longint_pointer;
#if HAVE_LONG_LONG_INT
- long long int * a_count_longlongint_pointer;
+ long long int * a_count_longlongint_pointer;
+#endif
+#if ENABLE_UNISTDIO
+ /* The unistdio extensions. */
+ const uint8_t * a_u8_string;
+ const uint16_t * a_u16_string;
+ const uint32_t * a_u32_string;
#endif
}
a;
}
argument;
+/* Number of directly allocated arguments (no malloc() needed). */
+#define N_DIRECT_ALLOC_ARGUMENTS 7
+
typedef struct
{
size_t count;
argument *arg;
+ argument direct_alloc_arg[N_DIRECT_ALLOC_ARGUMENTS];
}
arguments;
@@ -131,6 +153,6 @@ STATIC
#else
extern
#endif
-int printf_fetchargs (va_list args, arguments *a);
+int PRINTF_FETCHARGS (va_list args, arguments *a);
#endif /* _PRINTF_ARGS_H */
diff --git a/lib/printf-frexp.c b/lib/printf-frexp.c
new file mode 100644
index 0000000..1841b86
--- /dev/null
+++ b/lib/printf-frexp.c
@@ -0,0 +1,190 @@
+/* Split a double into fraction and mantissa, for hexadecimal printf.
+ Copyright (C) 2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+#if ! defined USE_LONG_DOUBLE
+# include <config.h>
+#endif
+
+/* Specification. */
+#ifdef USE_LONG_DOUBLE
+# include "printf-frexpl.h"
+#else
+# include "printf-frexp.h"
+#endif
+
+#include <float.h>
+#include <math.h>
+#ifdef USE_LONG_DOUBLE
+# include "fpucw.h"
+#endif
+
+/* This file assumes FLT_RADIX = 2. If FLT_RADIX is a power of 2 greater
+ than 2, or not even a power of 2, some rounding errors can occur, so that
+ then the returned mantissa is only guaranteed to be <= 2.0, not < 2.0. */
+
+#ifdef USE_LONG_DOUBLE
+# define FUNC printf_frexpl
+# define DOUBLE long double
+# define MIN_EXP LDBL_MIN_EXP
+# if HAVE_FREXPL_IN_LIBC && HAVE_LDEXPL_IN_LIBC
+# define USE_FREXP_LDEXP
+# define FREXP frexpl
+# define LDEXP ldexpl
+# endif
+# define DECL_ROUNDING DECL_LONG_DOUBLE_ROUNDING
+# define BEGIN_ROUNDING() BEGIN_LONG_DOUBLE_ROUNDING ()
+# define END_ROUNDING() END_LONG_DOUBLE_ROUNDING ()
+# define L_(literal) literal##L
+#else
+# define FUNC printf_frexp
+# define DOUBLE double
+# define MIN_EXP DBL_MIN_EXP
+# if HAVE_FREXP_IN_LIBC && HAVE_LDEXP_IN_LIBC
+# define USE_FREXP_LDEXP
+# define FREXP frexp
+# define LDEXP ldexp
+# endif
+# define DECL_ROUNDING
+# define BEGIN_ROUNDING()
+# define END_ROUNDING()
+# define L_(literal) literal
+#endif
+
+DOUBLE
+FUNC (DOUBLE x, int *expptr)
+{
+ int exponent;
+ DECL_ROUNDING
+
+ BEGIN_ROUNDING ();
+
+#ifdef USE_FREXP_LDEXP
+ /* frexp and ldexp are usually faster than the loop below. */
+ x = FREXP (x, &exponent);
+
+ x = x + x;
+ exponent -= 1;
+
+ if (exponent < MIN_EXP - 1)
+ {
+ x = LDEXP (x, exponent - (MIN_EXP - 1));
+ exponent = MIN_EXP - 1;
+ }
+#else
+ {
+ /* Since the exponent is an 'int', it fits in 64 bits. Therefore the
+ loops are executed no more than 64 times. */
+ DOUBLE pow2[64]; /* pow2[i] = 2^2^i */
+ DOUBLE powh[64]; /* powh[i] = 2^-2^i */
+ int i;
+
+ exponent = 0;
+ if (x >= L_(1.0))
+ {
+ /* A nonnegative exponent. */
+ {
+ DOUBLE pow2_i; /* = pow2[i] */
+ DOUBLE powh_i; /* = powh[i] */
+
+ /* Invariants: pow2_i = 2^2^i, powh_i = 2^-2^i,
+ x * 2^exponent = argument, x >= 1.0. */
+ for (i = 0, pow2_i = L_(2.0), powh_i = L_(0.5);
+ ;
+ i++, pow2_i = pow2_i * pow2_i, powh_i = powh_i * powh_i)
+ {
+ if (x >= pow2_i)
+ {
+ exponent += (1 << i);
+ x *= powh_i;
+ }
+ else
+ break;
+
+ pow2[i] = pow2_i;
+ powh[i] = powh_i;
+ }
+ }
+ /* Here 1.0 <= x < 2^2^i. */
+ }
+ else
+ {
+ /* A negative exponent. */
+ {
+ DOUBLE pow2_i; /* = pow2[i] */
+ DOUBLE powh_i; /* = powh[i] */
+
+ /* Invariants: pow2_i = 2^2^i, powh_i = 2^-2^i,
+ x * 2^exponent = argument, x < 1.0, exponent >= MIN_EXP - 1. */
+ for (i = 0, pow2_i = L_(2.0), powh_i = L_(0.5);
+ ;
+ i++, pow2_i = pow2_i * pow2_i, powh_i = powh_i * powh_i)
+ {
+ if (exponent - (1 << i) < MIN_EXP - 1)
+ break;
+
+ exponent -= (1 << i);
+ x *= pow2_i;
+ if (x >= L_(1.0))
+ break;
+
+ pow2[i] = pow2_i;
+ powh[i] = powh_i;
+ }
+ }
+ /* Here either x < 1.0 and exponent - 2^i < MIN_EXP - 1 <= exponent,
+ or 1.0 <= x < 2^2^i and exponent >= MIN_EXP - 1. */
+
+ if (x < L_(1.0))
+ /* Invariants: x * 2^exponent = argument, x < 1.0 and
+ exponent - 2^i < MIN_EXP - 1 <= exponent. */
+ while (i > 0)
+ {
+ i--;
+ if (exponent - (1 << i) >= MIN_EXP - 1)
+ {
+ exponent -= (1 << i);
+ x *= pow2[i];
+ if (x >= L_(1.0))
+ break;
+ }
+ }
+
+ /* Here either x < 1.0 and exponent = MIN_EXP - 1,
+ or 1.0 <= x < 2^2^i and exponent >= MIN_EXP - 1. */
+ }
+
+ /* Invariants: x * 2^exponent = argument, and
+ either x < 1.0 and exponent = MIN_EXP - 1,
+ or 1.0 <= x < 2^2^i and exponent >= MIN_EXP - 1. */
+ while (i > 0)
+ {
+ i--;
+ if (x >= pow2[i])
+ {
+ exponent += (1 << i);
+ x *= powh[i];
+ }
+ }
+ /* Here either x < 1.0 and exponent = MIN_EXP - 1,
+ or 1.0 <= x < 2.0 and exponent >= MIN_EXP - 1. */
+ }
+#endif
+
+ END_ROUNDING ();
+
+ *expptr = exponent;
+ return x;
+}
diff --git a/lib/printf-frexp.h b/lib/printf-frexp.h
new file mode 100644
index 0000000..ec75c60
--- /dev/null
+++ b/lib/printf-frexp.h
@@ -0,0 +1,23 @@
+/* Split a double into fraction and mantissa, for hexadecimal printf.
+ Copyright (C) 2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Write a finite, positive number x as
+ x = mantissa * 2^exp
+ where exp >= DBL_MIN_EXP - 1,
+ mantissa < 2.0,
+ if x is not a denormalized number then mantissa >= 1.0.
+ Store exp in *EXPPTR and return mantissa. */
+extern double printf_frexp (double x, int *expptr);
diff --git a/lib/printf-frexpl.c b/lib/printf-frexpl.c
new file mode 100644
index 0000000..3d0ce9b
--- /dev/null
+++ b/lib/printf-frexpl.c
@@ -0,0 +1,37 @@
+/* Split a 'long double' into fraction and mantissa, for hexadecimal printf.
+ Copyright (C) 2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+#if HAVE_SAME_LONG_DOUBLE_AS_DOUBLE
+
+/* Specification. */
+# include "printf-frexpl.h"
+
+# include "printf-frexp.h"
+
+long double
+printf_frexpl (long double x, int *expptr)
+{
+ return printf_frexp (x, expptr);
+}
+
+#else
+
+# define USE_LONG_DOUBLE
+# include "printf-frexp.c"
+
+#endif
diff --git a/lib/printf-frexpl.h b/lib/printf-frexpl.h
new file mode 100644
index 0000000..344f37a
--- /dev/null
+++ b/lib/printf-frexpl.h
@@ -0,0 +1,23 @@
+/* Split a 'long double' into fraction and mantissa, for hexadecimal printf.
+ Copyright (C) 2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Write a finite, positive number x as
+ x = mantissa * 2^exp
+ where exp >= LDBL_MIN_EXP - 1,
+ mantissa < 2.0,
+ if x is not a denormalized number then mantissa >= 1.0.
+ Store exp in *EXPPTR and return mantissa. */
+extern long double printf_frexpl (long double x, int *expptr);
diff --git a/lib/printf-parse.c b/lib/printf-parse.c
index 9493403..fad5d3d 100644
--- a/lib/printf-parse.c
+++ b/lib/printf-parse.c
@@ -1,12 +1,9 @@
/* Formatted output to strings.
- This file is intended to provide exactly the same functionality
- as the version in gnulib, but without the need for the xsize module.
-
- Copyright (C) 1999-2000, 2002-2003, 2006-2007 Free Software Foundation, Inc.
+ Copyright (C) 1999-2000, 2002-2003, 2006-2016 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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -15,37 +12,68 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-#include <config.h>
+ with this program; if not, see <http://www.gnu.org/licenses/>. */
+
+/* This file can be parametrized with the following macros:
+ CHAR_T The element type of the format string.
+ CHAR_T_ONLY_ASCII Set to 1 to enable verification that all characters
+ in the format string are ASCII.
+ DIRECTIVE Structure denoting a format directive.
+ Depends on CHAR_T.
+ DIRECTIVES Structure denoting the set of format directives of a
+ format string. Depends on CHAR_T.
+ PRINTF_PARSE Function that parses a format string.
+ Depends on CHAR_T.
+ STATIC Set to 'static' to declare the function static.
+ ENABLE_UNISTDIO Set to 1 to enable the unistdio extensions. */
+
+#ifndef PRINTF_PARSE
+# include <config.h>
+#endif
/* Specification. */
-#if WIDE_CHAR_VERSION
-# include "wprintf-parse.h"
-#else
+#ifndef PRINTF_PARSE
# include "printf-parse.h"
#endif
+/* Default parameters. */
+#ifndef PRINTF_PARSE
+# define PRINTF_PARSE printf_parse
+# define CHAR_T char
+# define DIRECTIVE char_directive
+# define DIRECTIVES char_directives
+#endif
+
/* Get size_t, NULL. */
#include <stddef.h>
-/* Get intmax_t, SIZE_MAX. */
-#include <stdint.h>
+/* Get intmax_t. */
+#if defined IN_LIBINTL || defined IN_LIBASPRINTF
+# if HAVE_STDINT_H_WITH_UINTMAX
+# include <stdint.h>
+# endif
+# if HAVE_INTTYPES_H_WITH_UINTMAX
+# include <inttypes.h>
+# endif
+#else
+# include <stdint.h>
+#endif
/* malloc(), realloc(), free(). */
#include <stdlib.h>
-#if WIDE_CHAR_VERSION
-# define PRINTF_PARSE wprintf_parse
-# define CHAR_T wchar_t
-# define DIRECTIVE wchar_t_directive
-# define DIRECTIVES wchar_t_directives
-#else
-# define PRINTF_PARSE printf_parse
-# define CHAR_T char
-# define DIRECTIVE char_directive
-# define DIRECTIVES char_directives
+/* memcpy(). */
+#include <string.h>
+
+/* errno. */
+#include <errno.h>
+
+/* Checked size_t computations. */
+#include "xsize.h"
+
+#if CHAR_T_ONLY_ASCII
+/* c_isascii(). */
+# include "c-ctype.h"
#endif
#ifdef STATIC
@@ -54,469 +82,531 @@ STATIC
int
PRINTF_PARSE (const CHAR_T *format, DIRECTIVES *d, arguments *a)
{
- const CHAR_T *cp = format; /* pointer into format */
- size_t arg_posn = 0; /* number of regular arguments consumed */
- size_t d_allocated; /* allocated elements of d->dir */
- size_t a_allocated; /* allocated elements of a->arg */
+ const CHAR_T *cp = format; /* pointer into format */
+ size_t arg_posn = 0; /* number of regular arguments consumed */
+ size_t d_allocated; /* allocated elements of d->dir */
+ size_t a_allocated; /* allocated elements of a->arg */
size_t max_width_length = 0;
size_t max_precision_length = 0;
d->count = 0;
- d_allocated = 1;
- d->dir = malloc (d_allocated * sizeof (DIRECTIVE));
- if (d->dir == NULL)
- /* Out of memory. */
- return -1;
+ d_allocated = N_DIRECT_ALLOC_DIRECTIVES;
+ d->dir = d->direct_alloc_dir;
a->count = 0;
- a_allocated = 0;
- a->arg = NULL;
+ a_allocated = N_DIRECT_ALLOC_ARGUMENTS;
+ a->arg = a->direct_alloc_arg;
#define REGISTER_ARG(_index_,_type_) \
- { \
- size_t n = (_index_); \
- if (n >= a_allocated) \
- { \
- size_t memory_size; \
- argument *memory; \
- \
- a_allocated *= 2; \
- if (a_allocated <= n) \
- a_allocated = n + 1; \
- if (SIZE_MAX / sizeof (argument) < a_allocated) \
- /* Overflow, would lead to out of memory. */ \
- goto error; \
- memory_size = a_allocated * sizeof (argument); \
- memory = (a->arg \
- ? realloc (a->arg, memory_size) \
- : malloc (memory_size)); \
- if (memory == NULL) \
- /* Out of memory. */ \
- goto error; \
- a->arg = memory; \
- } \
- while (a->count <= n) \
- a->arg[a->count++].type = TYPE_NONE; \
- if (a->arg[n].type == TYPE_NONE) \
- a->arg[n].type = (_type_); \
- else if (a->arg[n].type != (_type_)) \
- /* Ambiguous type for positional argument. */ \
- goto error; \
+ { \
+ size_t n = (_index_); \
+ if (n >= a_allocated) \
+ { \
+ size_t memory_size; \
+ argument *memory; \
+ \
+ a_allocated = xtimes (a_allocated, 2); \
+ if (a_allocated <= n) \
+ a_allocated = xsum (n, 1); \
+ memory_size = xtimes (a_allocated, sizeof (argument)); \
+ if (size_overflow_p (memory_size)) \
+ /* Overflow, would lead to out of memory. */ \
+ goto out_of_memory; \
+ memory = (argument *) (a->arg != a->direct_alloc_arg \
+ ? realloc (a->arg, memory_size) \
+ : malloc (memory_size)); \
+ if (memory == NULL) \
+ /* Out of memory. */ \
+ goto out_of_memory; \
+ if (a->arg == a->direct_alloc_arg) \
+ memcpy (memory, a->arg, a->count * sizeof (argument)); \
+ a->arg = memory; \
+ } \
+ while (a->count <= n) \
+ a->arg[a->count++].type = TYPE_NONE; \
+ if (a->arg[n].type == TYPE_NONE) \
+ a->arg[n].type = (_type_); \
+ else if (a->arg[n].type != (_type_)) \
+ /* Ambiguous type for positional argument. */ \
+ goto error; \
}
while (*cp != '\0')
{
CHAR_T c = *cp++;
if (c == '%')
- {
- size_t arg_index = ARG_NONE;
- DIRECTIVE *dp = &d->dir[d->count];/* pointer to next directive */
-
- /* Initialize the next directive. */
- dp->dir_start = cp - 1;
- dp->flags = 0;
- dp->width_start = NULL;
- dp->width_end = NULL;
- dp->width_arg_index = ARG_NONE;
- dp->precision_start = NULL;
- dp->precision_end = NULL;
- dp->precision_arg_index = ARG_NONE;
- dp->arg_index = ARG_NONE;
-
- /* Test for positional argument. */
- if (*cp >= '0' && *cp <= '9')
- {
- const CHAR_T *np;
-
- for (np = cp; *np >= '0' && *np <= '9'; np++)
- ;
- if (*np == '$')
- {
- size_t n = 0;
-
- for (np = cp; *np >= '0' && *np <= '9'; np++)
- if (n < SIZE_MAX / 10)
- n = 10 * n + (*np - '0');
- else
- /* n too large for memory. */
- goto error;
- if (n == 0)
- /* Positional argument 0. */
- goto error;
- arg_index = n - 1;
- cp = np + 1;
- }
- }
-
- /* Read the flags. */
- for (;;)
- {
- if (*cp == '\'')
- {
- dp->flags |= FLAG_GROUP;
- cp++;
- }
- else if (*cp == '-')
- {
- dp->flags |= FLAG_LEFT;
- cp++;
- }
- else if (*cp == '+')
- {
- dp->flags |= FLAG_SHOWSIGN;
- cp++;
- }
- else if (*cp == ' ')
- {
- dp->flags |= FLAG_SPACE;
- cp++;
- }
- else if (*cp == '#')
- {
- dp->flags |= FLAG_ALT;
- cp++;
- }
- else if (*cp == '0')
- {
- dp->flags |= FLAG_ZERO;
- cp++;
- }
- else
- break;
- }
-
- /* Parse the field width. */
- if (*cp == '*')
- {
- dp->width_start = cp;
- cp++;
- dp->width_end = cp;
- if (max_width_length < 1)
- max_width_length = 1;
-
- /* Test for positional argument. */
- if (*cp >= '0' && *cp <= '9')
- {
- const CHAR_T *np;
-
- for (np = cp; *np >= '0' && *np <= '9'; np++)
- ;
- if (*np == '$')
- {
- size_t n = 0;
-
- for (np = cp; *np >= '0' && *np <= '9'; np++)
- if (n < SIZE_MAX / 10)
- n = 10 * n + (*np - '0');
- else
- /* n too large for memory. */
- goto error;
- if (n == 0)
- /* Positional argument 0. */
- goto error;
- dp->width_arg_index = n - 1;
- cp = np + 1;
- }
- }
- if (dp->width_arg_index == ARG_NONE)
- {
- dp->width_arg_index = arg_posn++;
- if (dp->width_arg_index == ARG_NONE)
- /* arg_posn wrapped around. */
- goto error;
- }
- REGISTER_ARG (dp->width_arg_index, TYPE_INT);
- }
- else if (*cp >= '0' && *cp <= '9')
- {
- size_t width_length;
-
- dp->width_start = cp;
- for (; *cp >= '0' && *cp <= '9'; cp++)
- ;
- dp->width_end = cp;
- width_length = dp->width_end - dp->width_start;
- if (max_width_length < width_length)
- max_width_length = width_length;
- }
-
- /* Parse the precision. */
- if (*cp == '.')
- {
- cp++;
- if (*cp == '*')
- {
- dp->precision_start = cp - 1;
- cp++;
- dp->precision_end = cp;
- if (max_precision_length < 2)
- max_precision_length = 2;
-
- /* Test for positional argument. */
- if (*cp >= '0' && *cp <= '9')
- {
- const CHAR_T *np;
-
- for (np = cp; *np >= '0' && *np <= '9'; np++)
- ;
- if (*np == '$')
- {
- size_t n = 0;
-
- for (np = cp; *np >= '0' && *np <= '9'; np++)
- if (n < SIZE_MAX / 10)
- n = 10 * n + (*np - '0');
- else
- /* n too large for memory. */
- goto error;
- if (n == 0)
- /* Positional argument 0. */
- goto error;
- dp->precision_arg_index = n - 1;
- cp = np + 1;
- }
- }
- if (dp->precision_arg_index == ARG_NONE)
- {
- dp->precision_arg_index = arg_posn++;
- if (dp->precision_arg_index == ARG_NONE)
- /* arg_posn wrapped around. */
- goto error;
- }
- REGISTER_ARG (dp->precision_arg_index, TYPE_INT);
- }
- else
- {
- size_t precision_length;
-
- dp->precision_start = cp - 1;
- for (; *cp >= '0' && *cp <= '9'; cp++)
- ;
- dp->precision_end = cp;
- precision_length = dp->precision_end - dp->precision_start;
- if (max_precision_length < precision_length)
- max_precision_length = precision_length;
- }
- }
-
- {
- arg_type type;
-
- /* Parse argument type/size specifiers. */
- {
- int flags = 0;
-
- for (;;)
- {
- if (*cp == 'h')
- {
- flags |= (1 << (flags & 1));
- cp++;
- }
- else if (*cp == 'L')
- {
- flags |= 4;
- cp++;
- }
- else if (*cp == 'l')
- {
- flags += 8;
- cp++;
- }
-#if HAVE_INTMAX_T
- else if (*cp == 'j')
- {
- if (sizeof (intmax_t) > sizeof (long))
- {
- /* intmax_t = long long */
- flags += 16;
- }
- else if (sizeof (intmax_t) > sizeof (int))
- {
- /* intmax_t = long */
- flags += 8;
- }
- cp++;
- }
+ {
+ size_t arg_index = ARG_NONE;
+ DIRECTIVE *dp = &d->dir[d->count]; /* pointer to next directive */
+
+ /* Initialize the next directive. */
+ dp->dir_start = cp - 1;
+ dp->flags = 0;
+ dp->width_start = NULL;
+ dp->width_end = NULL;
+ dp->width_arg_index = ARG_NONE;
+ dp->precision_start = NULL;
+ dp->precision_end = NULL;
+ dp->precision_arg_index = ARG_NONE;
+ dp->arg_index = ARG_NONE;
+
+ /* Test for positional argument. */
+ if (*cp >= '0' && *cp <= '9')
+ {
+ const CHAR_T *np;
+
+ for (np = cp; *np >= '0' && *np <= '9'; np++)
+ ;
+ if (*np == '$')
+ {
+ size_t n = 0;
+
+ for (np = cp; *np >= '0' && *np <= '9'; np++)
+ n = xsum (xtimes (n, 10), *np - '0');
+ if (n == 0)
+ /* Positional argument 0. */
+ goto error;
+ if (size_overflow_p (n))
+ /* n too large, would lead to out of memory later. */
+ goto error;
+ arg_index = n - 1;
+ cp = np + 1;
+ }
+ }
+
+ /* Read the flags. */
+ for (;;)
+ {
+ if (*cp == '\'')
+ {
+ dp->flags |= FLAG_GROUP;
+ cp++;
+ }
+ else if (*cp == '-')
+ {
+ dp->flags |= FLAG_LEFT;
+ cp++;
+ }
+ else if (*cp == '+')
+ {
+ dp->flags |= FLAG_SHOWSIGN;
+ cp++;
+ }
+ else if (*cp == ' ')
+ {
+ dp->flags |= FLAG_SPACE;
+ cp++;
+ }
+ else if (*cp == '#')
+ {
+ dp->flags |= FLAG_ALT;
+ cp++;
+ }
+ else if (*cp == '0')
+ {
+ dp->flags |= FLAG_ZERO;
+ cp++;
+ }
+#if __GLIBC__ >= 2 && !defined __UCLIBC__
+ else if (*cp == 'I')
+ {
+ dp->flags |= FLAG_LOCALIZED;
+ cp++;
+ }
#endif
- else if (*cp == 'z' || *cp == 'Z')
- {
- /* 'z' is standardized in ISO C 99, but glibc uses 'Z'
- because the warning facility in gcc-2.95.2 understands
- only 'Z' (see gcc-2.95.2/gcc/c-common.c:1784). */
- if (sizeof (size_t) > sizeof (long))
- {
- /* size_t = long long */
- flags += 16;
- }
- else if (sizeof (size_t) > sizeof (int))
- {
- /* size_t = long */
- flags += 8;
- }
- cp++;
- }
- else if (*cp == 't')
- {
- if (sizeof (ptrdiff_t) > sizeof (long))
- {
- /* ptrdiff_t = long long */
- flags += 16;
- }
- else if (sizeof (ptrdiff_t) > sizeof (int))
- {
- /* ptrdiff_t = long */
- flags += 8;
- }
- cp++;
- }
- else
- break;
- }
-
- /* Read the conversion character. */
- c = *cp++;
- switch (c)
- {
- case 'd': case 'i':
-#if HAVE_LONG_LONG_INT
- /* If 'long long' exists and is larger than 'long': */
- if (flags >= 16 || (flags & 4))
- type = TYPE_LONGLONGINT;
- else
+ else
+ break;
+ }
+
+ /* Parse the field width. */
+ if (*cp == '*')
+ {
+ dp->width_start = cp;
+ cp++;
+ dp->width_end = cp;
+ if (max_width_length < 1)
+ max_width_length = 1;
+
+ /* Test for positional argument. */
+ if (*cp >= '0' && *cp <= '9')
+ {
+ const CHAR_T *np;
+
+ for (np = cp; *np >= '0' && *np <= '9'; np++)
+ ;
+ if (*np == '$')
+ {
+ size_t n = 0;
+
+ for (np = cp; *np >= '0' && *np <= '9'; np++)
+ n = xsum (xtimes (n, 10), *np - '0');
+ if (n == 0)
+ /* Positional argument 0. */
+ goto error;
+ if (size_overflow_p (n))
+ /* n too large, would lead to out of memory later. */
+ goto error;
+ dp->width_arg_index = n - 1;
+ cp = np + 1;
+ }
+ }
+ if (dp->width_arg_index == ARG_NONE)
+ {
+ dp->width_arg_index = arg_posn++;
+ if (dp->width_arg_index == ARG_NONE)
+ /* arg_posn wrapped around. */
+ goto error;
+ }
+ REGISTER_ARG (dp->width_arg_index, TYPE_INT);
+ }
+ else if (*cp >= '0' && *cp <= '9')
+ {
+ size_t width_length;
+
+ dp->width_start = cp;
+ for (; *cp >= '0' && *cp <= '9'; cp++)
+ ;
+ dp->width_end = cp;
+ width_length = dp->width_end - dp->width_start;
+ if (max_width_length < width_length)
+ max_width_length = width_length;
+ }
+
+ /* Parse the precision. */
+ if (*cp == '.')
+ {
+ cp++;
+ if (*cp == '*')
+ {
+ dp->precision_start = cp - 1;
+ cp++;
+ dp->precision_end = cp;
+ if (max_precision_length < 2)
+ max_precision_length = 2;
+
+ /* Test for positional argument. */
+ if (*cp >= '0' && *cp <= '9')
+ {
+ const CHAR_T *np;
+
+ for (np = cp; *np >= '0' && *np <= '9'; np++)
+ ;
+ if (*np == '$')
+ {
+ size_t n = 0;
+
+ for (np = cp; *np >= '0' && *np <= '9'; np++)
+ n = xsum (xtimes (n, 10), *np - '0');
+ if (n == 0)
+ /* Positional argument 0. */
+ goto error;
+ if (size_overflow_p (n))
+ /* n too large, would lead to out of memory
+ later. */
+ goto error;
+ dp->precision_arg_index = n - 1;
+ cp = np + 1;
+ }
+ }
+ if (dp->precision_arg_index == ARG_NONE)
+ {
+ dp->precision_arg_index = arg_posn++;
+ if (dp->precision_arg_index == ARG_NONE)
+ /* arg_posn wrapped around. */
+ goto error;
+ }
+ REGISTER_ARG (dp->precision_arg_index, TYPE_INT);
+ }
+ else
+ {
+ size_t precision_length;
+
+ dp->precision_start = cp - 1;
+ for (; *cp >= '0' && *cp <= '9'; cp++)
+ ;
+ dp->precision_end = cp;
+ precision_length = dp->precision_end - dp->precision_start;
+ if (max_precision_length < precision_length)
+ max_precision_length = precision_length;
+ }
+ }
+
+ {
+ arg_type type;
+
+ /* Parse argument type/size specifiers. */
+ {
+ int flags = 0;
+
+ for (;;)
+ {
+ if (*cp == 'h')
+ {
+ flags |= (1 << (flags & 1));
+ cp++;
+ }
+ else if (*cp == 'L')
+ {
+ flags |= 4;
+ cp++;
+ }
+ else if (*cp == 'l')
+ {
+ flags += 8;
+ cp++;
+ }
+ else if (*cp == 'j')
+ {
+ if (sizeof (intmax_t) > sizeof (long))
+ {
+ /* intmax_t = long long */
+ flags += 16;
+ }
+ else if (sizeof (intmax_t) > sizeof (int))
+ {
+ /* intmax_t = long */
+ flags += 8;
+ }
+ cp++;
+ }
+ else if (*cp == 'z' || *cp == 'Z')
+ {
+ /* 'z' is standardized in ISO C 99, but glibc uses 'Z'
+ because the warning facility in gcc-2.95.2 understands
+ only 'Z' (see gcc-2.95.2/gcc/c-common.c:1784). */
+ if (sizeof (size_t) > sizeof (long))
+ {
+ /* size_t = long long */
+ flags += 16;
+ }
+ else if (sizeof (size_t) > sizeof (int))
+ {
+ /* size_t = long */
+ flags += 8;
+ }
+ cp++;
+ }
+ else if (*cp == 't')
+ {
+ if (sizeof (ptrdiff_t) > sizeof (long))
+ {
+ /* ptrdiff_t = long long */
+ flags += 16;
+ }
+ else if (sizeof (ptrdiff_t) > sizeof (int))
+ {
+ /* ptrdiff_t = long */
+ flags += 8;
+ }
+ cp++;
+ }
+#if defined __APPLE__ && defined __MACH__
+ /* On Mac OS X 10.3, PRIdMAX is defined as "qd".
+ We cannot change it to "lld" because PRIdMAX must also
+ be understood by the system's printf routines. */
+ else if (*cp == 'q')
+ {
+ if (64 / 8 > sizeof (long))
+ {
+ /* int64_t = long long */
+ flags += 16;
+ }
+ else
+ {
+ /* int64_t = long */
+ flags += 8;
+ }
+ cp++;
+ }
+#endif
+#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+ /* On native Windows, PRIdMAX is defined as "I64d".
+ We cannot change it to "lld" because PRIdMAX must also
+ be understood by the system's printf routines. */
+ else if (*cp == 'I' && cp[1] == '6' && cp[2] == '4')
+ {
+ if (64 / 8 > sizeof (long))
+ {
+ /* __int64 = long long */
+ flags += 16;
+ }
+ else
+ {
+ /* __int64 = long */
+ flags += 8;
+ }
+ cp += 3;
+ }
#endif
- /* If 'long long' exists and is the same as 'long', we parse
- "lld" into TYPE_LONGINT. */
- if (flags >= 8)
- type = TYPE_LONGINT;
- else if (flags & 2)
- type = TYPE_SCHAR;
- else if (flags & 1)
- type = TYPE_SHORT;
- else
- type = TYPE_INT;
- break;
- case 'o': case 'u': case 'x': case 'X':
+ else
+ break;
+ }
+
+ /* Read the conversion character. */
+ c = *cp++;
+ switch (c)
+ {
+ case 'd': case 'i':
#if HAVE_LONG_LONG_INT
- /* If 'long long' exists and is larger than 'long': */
- if (flags >= 16 || (flags & 4))
- type = TYPE_ULONGLONGINT;
- else
+ /* If 'long long' exists and is larger than 'long': */
+ if (flags >= 16 || (flags & 4))
+ type = TYPE_LONGLONGINT;
+ else
#endif
- /* If 'unsigned long long' exists and is the same as
- 'unsigned long', we parse "llu" into TYPE_ULONGINT. */
- if (flags >= 8)
- type = TYPE_ULONGINT;
- else if (flags & 2)
- type = TYPE_UCHAR;
- else if (flags & 1)
- type = TYPE_USHORT;
- else
- type = TYPE_UINT;
- break;
- case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
- case 'a': case 'A':
-#if HAVE_LONG_DOUBLE
- if (flags >= 16 || (flags & 4))
- type = TYPE_LONGDOUBLE;
- else
+ /* If 'long long' exists and is the same as 'long', we parse
+ "lld" into TYPE_LONGINT. */
+ if (flags >= 8)
+ type = TYPE_LONGINT;
+ else if (flags & 2)
+ type = TYPE_SCHAR;
+ else if (flags & 1)
+ type = TYPE_SHORT;
+ else
+ type = TYPE_INT;
+ break;
+ case 'o': case 'u': case 'x': case 'X':
+#if HAVE_LONG_LONG_INT
+ /* If 'long long' exists and is larger than 'long': */
+ if (flags >= 16 || (flags & 4))
+ type = TYPE_ULONGLONGINT;
+ else
#endif
- type = TYPE_DOUBLE;
- break;
- case 'c':
- if (flags >= 8)
+ /* If 'unsigned long long' exists and is the same as
+ 'unsigned long', we parse "llu" into TYPE_ULONGINT. */
+ if (flags >= 8)
+ type = TYPE_ULONGINT;
+ else if (flags & 2)
+ type = TYPE_UCHAR;
+ else if (flags & 1)
+ type = TYPE_USHORT;
+ else
+ type = TYPE_UINT;
+ break;
+ case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
+ case 'a': case 'A':
+ if (flags >= 16 || (flags & 4))
+ type = TYPE_LONGDOUBLE;
+ else
+ type = TYPE_DOUBLE;
+ break;
+ case 'c':
+ if (flags >= 8)
#if HAVE_WINT_T
- type = TYPE_WIDE_CHAR;
+ type = TYPE_WIDE_CHAR;
#else
- goto error;
+ goto error;
#endif
- else
- type = TYPE_CHAR;
- break;
+ else
+ type = TYPE_CHAR;
+ break;
#if HAVE_WINT_T
- case 'C':
- type = TYPE_WIDE_CHAR;
- c = 'c';
- break;
+ case 'C':
+ type = TYPE_WIDE_CHAR;
+ c = 'c';
+ break;
#endif
- case 's':
- if (flags >= 8)
+ case 's':
+ if (flags >= 8)
#if HAVE_WCHAR_T
- type = TYPE_WIDE_STRING;
+ type = TYPE_WIDE_STRING;
#else
- goto error;
+ goto error;
#endif
- else
- type = TYPE_STRING;
- break;
+ else
+ type = TYPE_STRING;
+ break;
#if HAVE_WCHAR_T
- case 'S':
- type = TYPE_WIDE_STRING;
- c = 's';
- break;
+ case 'S':
+ type = TYPE_WIDE_STRING;
+ c = 's';
+ break;
#endif
- case 'p':
- type = TYPE_POINTER;
- break;
- case 'n':
+ case 'p':
+ type = TYPE_POINTER;
+ break;
+ case 'n':
#if HAVE_LONG_LONG_INT
- /* If 'long long' exists and is larger than 'long': */
- if (flags >= 16 || (flags & 4))
- type = TYPE_COUNT_LONGLONGINT_POINTER;
- else
+ /* If 'long long' exists and is larger than 'long': */
+ if (flags >= 16 || (flags & 4))
+ type = TYPE_COUNT_LONGLONGINT_POINTER;
+ else
+#endif
+ /* If 'long long' exists and is the same as 'long', we parse
+ "lln" into TYPE_COUNT_LONGINT_POINTER. */
+ if (flags >= 8)
+ type = TYPE_COUNT_LONGINT_POINTER;
+ else if (flags & 2)
+ type = TYPE_COUNT_SCHAR_POINTER;
+ else if (flags & 1)
+ type = TYPE_COUNT_SHORT_POINTER;
+ else
+ type = TYPE_COUNT_INT_POINTER;
+ break;
+#if ENABLE_UNISTDIO
+ /* The unistdio extensions. */
+ case 'U':
+ if (flags >= 16)
+ type = TYPE_U32_STRING;
+ else if (flags >= 8)
+ type = TYPE_U16_STRING;
+ else
+ type = TYPE_U8_STRING;
+ break;
+#endif
+ case '%':
+ type = TYPE_NONE;
+ break;
+ default:
+ /* Unknown conversion character. */
+ goto error;
+ }
+ }
+
+ if (type != TYPE_NONE)
+ {
+ dp->arg_index = arg_index;
+ if (dp->arg_index == ARG_NONE)
+ {
+ dp->arg_index = arg_posn++;
+ if (dp->arg_index == ARG_NONE)
+ /* arg_posn wrapped around. */
+ goto error;
+ }
+ REGISTER_ARG (dp->arg_index, type);
+ }
+ dp->conversion = c;
+ dp->dir_end = cp;
+ }
+
+ d->count++;
+ if (d->count >= d_allocated)
+ {
+ size_t memory_size;
+ DIRECTIVE *memory;
+
+ d_allocated = xtimes (d_allocated, 2);
+ memory_size = xtimes (d_allocated, sizeof (DIRECTIVE));
+ if (size_overflow_p (memory_size))
+ /* Overflow, would lead to out of memory. */
+ goto out_of_memory;
+ memory = (DIRECTIVE *) (d->dir != d->direct_alloc_dir
+ ? realloc (d->dir, memory_size)
+ : malloc (memory_size));
+ if (memory == NULL)
+ /* Out of memory. */
+ goto out_of_memory;
+ if (d->dir == d->direct_alloc_dir)
+ memcpy (memory, d->dir, d->count * sizeof (DIRECTIVE));
+ d->dir = memory;
+ }
+ }
+#if CHAR_T_ONLY_ASCII
+ else if (!c_isascii (c))
+ {
+ /* Non-ASCII character. Not supported. */
+ goto error;
+ }
#endif
- /* If 'long long' exists and is the same as 'long', we parse
- "lln" into TYPE_COUNT_LONGINT_POINTER. */
- if (flags >= 8)
- type = TYPE_COUNT_LONGINT_POINTER;
- else if (flags & 2)
- type = TYPE_COUNT_SCHAR_POINTER;
- else if (flags & 1)
- type = TYPE_COUNT_SHORT_POINTER;
- else
- type = TYPE_COUNT_INT_POINTER;
- break;
- case '%':
- type = TYPE_NONE;
- break;
- default:
- /* Unknown conversion character. */
- goto error;
- }
- }
-
- if (type != TYPE_NONE)
- {
- dp->arg_index = arg_index;
- if (dp->arg_index == ARG_NONE)
- {
- dp->arg_index = arg_posn++;
- if (dp->arg_index == ARG_NONE)
- /* arg_posn wrapped around. */
- goto error;
- }
- REGISTER_ARG (dp->arg_index, type);
- }
- dp->conversion = c;
- dp->dir_end = cp;
- }
-
- d->count++;
- if (d->count >= d_allocated)
- {
- DIRECTIVE *memory;
-
- if (SIZE_MAX / (2 * sizeof (DIRECTIVE)) < d_allocated)
- /* Overflow, would lead to out of memory. */
- goto error;
- d_allocated *= 2;
- memory = realloc (d->dir, d_allocated * sizeof (DIRECTIVE));
- if (memory == NULL)
- /* Out of memory. */
- goto error;
- d->dir = memory;
- }
- }
}
d->dir[d->count].dir_start = cp;
@@ -525,14 +615,24 @@ PRINTF_PARSE (const CHAR_T *format, DIRECTIVES *d, arguments *a)
return 0;
error:
- if (a->arg)
+ if (a->arg != a->direct_alloc_arg)
free (a->arg);
- if (d->dir)
+ if (d->dir != d->direct_alloc_dir)
free (d->dir);
+ errno = EINVAL;
+ return -1;
+
+out_of_memory:
+ if (a->arg != a->direct_alloc_arg)
+ free (a->arg);
+ if (d->dir != d->direct_alloc_dir)
+ free (d->dir);
+ errno = ENOMEM;
return -1;
}
+#undef PRINTF_PARSE
#undef DIRECTIVES
#undef DIRECTIVE
+#undef CHAR_T_ONLY_ASCII
#undef CHAR_T
-#undef PRINTF_PARSE
diff --git a/lib/printf-parse.h b/lib/printf-parse.h
index 82a0d37..a46d946 100644
--- a/lib/printf-parse.h
+++ b/lib/printf-parse.h
@@ -1,9 +1,10 @@
/* Parse printf format string.
- Copyright (C) 1999, 2002-2003 Free Software Foundation, Inc.
+ Copyright (C) 1999, 2002-2003, 2005, 2007, 2010-2016 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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -12,25 +13,41 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ with this program; if not, see <http://www.gnu.org/licenses/>. */
#ifndef _PRINTF_PARSE_H
#define _PRINTF_PARSE_H
+/* This file can be parametrized with the following macros:
+ ENABLE_UNISTDIO Set to 1 to enable the unistdio extensions.
+ STATIC Set to 'static' to declare the function static. */
+
+#if HAVE_FEATURES_H
+# include <features.h> /* for __GLIBC__, __UCLIBC__ */
+#endif
+
#include "printf-args.h"
/* Flags */
-#define FLAG_GROUP 1 /* ' flag */
-#define FLAG_LEFT 2 /* - flag */
-#define FLAG_SHOWSIGN 4 /* + flag */
-#define FLAG_SPACE 8 /* space flag */
-#define FLAG_ALT 16 /* # flag */
-#define FLAG_ZERO 32
+#define FLAG_GROUP 1 /* ' flag */
+#define FLAG_LEFT 2 /* - flag */
+#define FLAG_SHOWSIGN 4 /* + flag */
+#define FLAG_SPACE 8 /* space flag */
+#define FLAG_ALT 16 /* # flag */
+#define FLAG_ZERO 32
+#if __GLIBC__ >= 2 && !defined __UCLIBC__
+# define FLAG_LOCALIZED 64 /* I flag, uses localized digits */
+#endif
/* arg_index value indicating that no argument is consumed. */
-#define ARG_NONE (~(size_t)0)
+#define ARG_NONE (~(size_t)0)
+
+/* xxx_directive: A parsed directive.
+ xxx_directives: A parsed format string. */
+
+/* Number of directly allocated directives (no malloc() needed). */
+#define N_DIRECT_ALLOC_DIRECTIVES 7
/* A parsed directive. */
typedef struct
@@ -44,7 +61,7 @@ typedef struct
const char* precision_start;
const char* precision_end;
size_t precision_arg_index;
- char conversion; /* d i o u x X f e E g G c s p n U % but not C S */
+ char conversion; /* d i o u x X f F e E g G a A c s p n U % but not C S */
size_t arg_index;
}
char_directive;
@@ -56,19 +73,121 @@ typedef struct
char_directive *dir;
size_t max_width_length;
size_t max_precision_length;
+ char_directive direct_alloc_dir[N_DIRECT_ALLOC_DIRECTIVES];
}
char_directives;
+#if ENABLE_UNISTDIO
+
+/* A parsed directive. */
+typedef struct
+{
+ const uint8_t* dir_start;
+ const uint8_t* dir_end;
+ int flags;
+ const uint8_t* width_start;
+ const uint8_t* width_end;
+ size_t width_arg_index;
+ const uint8_t* precision_start;
+ const uint8_t* precision_end;
+ size_t precision_arg_index;
+ uint8_t conversion; /* d i o u x X f F e E g G a A c s p n U % but not C S */
+ size_t arg_index;
+}
+u8_directive;
+
+/* A parsed format string. */
+typedef struct
+{
+ size_t count;
+ u8_directive *dir;
+ size_t max_width_length;
+ size_t max_precision_length;
+ u8_directive direct_alloc_dir[N_DIRECT_ALLOC_DIRECTIVES];
+}
+u8_directives;
+
+/* A parsed directive. */
+typedef struct
+{
+ const uint16_t* dir_start;
+ const uint16_t* dir_end;
+ int flags;
+ const uint16_t* width_start;
+ const uint16_t* width_end;
+ size_t width_arg_index;
+ const uint16_t* precision_start;
+ const uint16_t* precision_end;
+ size_t precision_arg_index;
+ uint16_t conversion; /* d i o u x X f F e E g G a A c s p n U % but not C S */
+ size_t arg_index;
+}
+u16_directive;
+
+/* A parsed format string. */
+typedef struct
+{
+ size_t count;
+ u16_directive *dir;
+ size_t max_width_length;
+ size_t max_precision_length;
+ u16_directive direct_alloc_dir[N_DIRECT_ALLOC_DIRECTIVES];
+}
+u16_directives;
+
+/* A parsed directive. */
+typedef struct
+{
+ const uint32_t* dir_start;
+ const uint32_t* dir_end;
+ int flags;
+ const uint32_t* width_start;
+ const uint32_t* width_end;
+ size_t width_arg_index;
+ const uint32_t* precision_start;
+ const uint32_t* precision_end;
+ size_t precision_arg_index;
+ uint32_t conversion; /* d i o u x X f F e E g G a A c s p n U % but not C S */
+ size_t arg_index;
+}
+u32_directive;
+
+/* A parsed format string. */
+typedef struct
+{
+ size_t count;
+ u32_directive *dir;
+ size_t max_width_length;
+ size_t max_precision_length;
+ u32_directive direct_alloc_dir[N_DIRECT_ALLOC_DIRECTIVES];
+}
+u32_directives;
+
+#endif
+
/* Parses the format string. Fills in the number N of directives, and fills
in directives[0], ..., directives[N-1], and sets directives[N].dir_start
to the end of the format string. Also fills in the arg_type fields of the
arguments and the needed count of arguments. */
-#ifdef STATIC
-STATIC
+#if ENABLE_UNISTDIO
+extern int
+ ulc_printf_parse (const char *format, char_directives *d, arguments *a);
+extern int
+ u8_printf_parse (const uint8_t *format, u8_directives *d, arguments *a);
+extern int
+ u16_printf_parse (const uint16_t *format, u16_directives *d,
+ arguments *a);
+extern int
+ u32_printf_parse (const uint32_t *format, u32_directives *d,
+ arguments *a);
#else
+# ifdef STATIC
+STATIC
+# else
extern
-#endif
+# endif
int printf_parse (const char *format, char_directives *d, arguments *a);
+#endif
#endif /* _PRINTF_PARSE_H */
diff --git a/lib/priv-set.c b/lib/priv-set.c
new file mode 100644
index 0000000..4a92a06
--- /dev/null
+++ b/lib/priv-set.c
@@ -0,0 +1,145 @@
+/* Query, remove, or restore a Solaris privilege.
+
+ Copyright (C) 2009-2016 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 <http://www.gnu.org/licenses/>.
+
+ Written by David Bartley. */
+
+#include <config.h>
+
+#define PRIV_SET_INLINE _GL_EXTERN_INLINE
+
+#include "priv-set.h"
+
+#if HAVE_GETPPRIV && HAVE_PRIV_H
+
+# include <errno.h>
+# include <stdbool.h>
+# include <priv.h>
+
+/* Holds a (cached) copy of the effective set. */
+static priv_set_t *eff_set;
+
+/* Holds a set of privileges that we have removed. */
+static priv_set_t *rem_set;
+
+static bool initialized;
+
+static int
+priv_set_initialize (void)
+{
+ if (! initialized)
+ {
+ eff_set = priv_allocset ();
+ if (!eff_set)
+ {
+ return -1;
+ }
+ rem_set = priv_allocset ();
+ if (!rem_set)
+ {
+ priv_freeset (eff_set);
+ return -1;
+ }
+ if (getppriv (PRIV_EFFECTIVE, eff_set) != 0)
+ {
+ priv_freeset (eff_set);
+ priv_freeset (rem_set);
+ return -1;
+ }
+ priv_emptyset (rem_set);
+ initialized = true;
+ }
+
+ return 0;
+}
+
+
+/* Check if priv is in the effective set.
+ Returns 1 if priv is a member and 0 if not.
+ Returns -1 on error with errno set appropriately. */
+int
+priv_set_ismember (const char *priv)
+{
+ if (! initialized && priv_set_initialize () != 0)
+ return -1;
+
+ return priv_ismember (eff_set, priv);
+}
+
+
+/* Try to remove priv from the effective set.
+ Returns 0 if priv was removed.
+ Returns -1 on error with errno set appropriately. */
+int
+priv_set_remove (const char *priv)
+{
+ if (! initialized && priv_set_initialize () != 0)
+ return -1;
+
+ if (priv_ismember (eff_set, priv))
+ {
+ /* priv_addset/priv_delset can only fail if priv is invalid, which is
+ checked above by the priv_ismember call. */
+ priv_delset (eff_set, priv);
+ if (setppriv (PRIV_SET, PRIV_EFFECTIVE, eff_set) != 0)
+ {
+ priv_addset (eff_set, priv);
+ return -1;
+ }
+ priv_addset (rem_set, priv);
+ }
+ else
+ {
+ errno = EINVAL;
+ return -1;
+ }
+
+ return 0;
+}
+
+
+/* Try to restore priv to the effective set.
+ Returns 0 if priv was re-added to the effective set (after being previously
+ removed by a call to priv_set_remove).
+ Returns -1 on error with errno set appropriately. */
+int
+priv_set_restore (const char *priv)
+{
+ if (! initialized && priv_set_initialize () != 0)
+ return -1;
+
+ if (priv_ismember (rem_set, priv))
+ {
+ /* priv_addset/priv_delset can only fail if priv is invalid, which is
+ checked above by the priv_ismember call. */
+ priv_addset (eff_set, priv);
+ if (setppriv (PRIV_SET, PRIV_EFFECTIVE, eff_set) != 0)
+ {
+ priv_delset (eff_set, priv);
+ return -1;
+ }
+ priv_delset (rem_set, priv);
+ }
+ else
+ {
+ errno = EINVAL;
+ return -1;
+ }
+
+ return 0;
+}
+
+#endif
diff --git a/lib/priv-set.h b/lib/priv-set.h
new file mode 100644
index 0000000..b656f73
--- /dev/null
+++ b/lib/priv-set.h
@@ -0,0 +1,64 @@
+/* Query, remove, or restore a Solaris privilege.
+
+ Copyright (C) 2009-2016 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 <http://www.gnu.org/licenses/>.
+
+ Written by David Bartley. */
+
+#ifndef _GL_INLINE_HEADER_BEGIN
+ #error "Please include config.h first."
+#endif
+_GL_INLINE_HEADER_BEGIN
+#ifndef PRIV_SET_INLINE
+# define PRIV_SET_INLINE _GL_INLINE
+#endif
+
+#if HAVE_GETPPRIV && HAVE_PRIV_H
+
+# include <priv.h>
+
+int priv_set_ismember (const char *priv);
+int priv_set_remove (const char *priv);
+int priv_set_restore (const char *priv);
+
+PRIV_SET_INLINE int
+priv_set_remove_linkdir (void)
+{
+ return priv_set_remove (PRIV_SYS_LINKDIR);
+}
+
+PRIV_SET_INLINE int
+priv_set_restore_linkdir (void)
+{
+ return priv_set_restore (PRIV_SYS_LINKDIR);
+}
+
+#else
+
+PRIV_SET_INLINE int
+priv_set_remove_linkdir (void)
+{
+ return -1;
+}
+
+PRIV_SET_INLINE int
+priv_set_restore_linkdir (void)
+{
+ return -1;
+}
+
+#endif
+
+_GL_INLINE_HEADER_END
diff --git a/lib/progname.c b/lib/progname.c
new file mode 100644
index 0000000..debb760
--- /dev/null
+++ b/lib/progname.c
@@ -0,0 +1,92 @@
+/* Program name management.
+ Copyright (C) 2001-2003, 2005-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2001.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+
+#include <config.h>
+
+/* Specification. */
+#undef ENABLE_RELOCATABLE /* avoid defining set_program_name as a macro */
+#include "progname.h"
+
+#include <errno.h> /* get program_invocation_name declaration */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+
+/* String containing name the program is called with.
+ To be initialized by main(). */
+const char *program_name = NULL;
+
+/* Set program_name, based on argv[0].
+ argv0 must be a string allocated with indefinite extent, and must not be
+ modified after this call. */
+void
+set_program_name (const char *argv0)
+{
+ /* libtool creates a temporary executable whose name is sometimes prefixed
+ with "lt-" (depends on the platform). It also makes argv[0] absolute.
+ But the name of the temporary executable is a detail that should not be
+ visible to the end user and to the test suite.
+ Remove this "<dirname>/.libs/" or "<dirname>/.libs/lt-" prefix here. */
+ const char *slash;
+ const char *base;
+
+ /* Sanity check. POSIX requires the invoking process to pass a non-NULL
+ argv[0]. */
+ if (argv0 == NULL)
+ {
+ /* It's a bug in the invoking program. Help diagnosing it. */
+ fputs ("A NULL argv[0] was passed through an exec system call.\n",
+ stderr);
+ abort ();
+ }
+
+ slash = strrchr (argv0, '/');
+ base = (slash != NULL ? slash + 1 : argv0);
+ if (base - argv0 >= 7 && strncmp (base - 7, "/.libs/", 7) == 0)
+ {
+ argv0 = base;
+ if (strncmp (base, "lt-", 3) == 0)
+ {
+ argv0 = base + 3;
+ /* On glibc systems, remove the "lt-" prefix from the variable
+ program_invocation_short_name. */
+#if HAVE_DECL_PROGRAM_INVOCATION_SHORT_NAME
+ program_invocation_short_name = (char *) argv0;
+#endif
+ }
+ }
+
+ /* But don't strip off a leading <dirname>/ in general, because when the user
+ runs
+ /some/hidden/place/bin/cp foo foo
+ he should get the error message
+ /some/hidden/place/bin/cp: `foo' and `foo' are the same file
+ not
+ cp: `foo' and `foo' are the same file
+ */
+
+ program_name = argv0;
+
+ /* On glibc systems, the error() function comes from libc and uses the
+ variable program_invocation_name, not program_name. So set this variable
+ as well. */
+#if HAVE_DECL_PROGRAM_INVOCATION_NAME
+ program_invocation_name = (char *) argv0;
+#endif
+}
diff --git a/lib/progname.h b/lib/progname.h
new file mode 100644
index 0000000..0a57407
--- /dev/null
+++ b/lib/progname.h
@@ -0,0 +1,62 @@
+/* Program name management.
+ Copyright (C) 2001-2004, 2006, 2009-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2001.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _PROGNAME_H
+#define _PROGNAME_H
+
+/* Programs using this file should do the following in main():
+ set_program_name (argv[0]);
+ */
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/* String containing name the program is called with. */
+extern const char *program_name;
+
+/* Set program_name, based on argv[0].
+ argv0 must be a string allocated with indefinite extent, and must not be
+ modified after this call. */
+extern void set_program_name (const char *argv0);
+
+#if ENABLE_RELOCATABLE
+
+/* Set program_name, based on argv[0], and original installation prefix and
+ directory, for relocatability. */
+extern void set_program_name_and_installdir (const char *argv0,
+ const char *orig_installprefix,
+ const char *orig_installdir);
+#undef set_program_name
+#define set_program_name(ARG0) \
+ set_program_name_and_installdir (ARG0, INSTALLPREFIX, INSTALLDIR)
+
+/* Return the full pathname of the current executable, based on the earlier
+ call to set_program_name_and_installdir. Return NULL if unknown. */
+extern char *get_full_program_name (void);
+
+#endif
+
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif /* _PROGNAME_H */
diff --git a/lib/propername.c b/lib/propername.c
new file mode 100644
index 0000000..90ad284
--- /dev/null
+++ b/lib/propername.c
@@ -0,0 +1,318 @@
+/* Localization of proper names.
+ Copyright (C) 2006-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2006.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+/* Without this pragma, gcc 4.7.0 20111124 mistakenly suggests that
+ the proper_name function might be candidate for attribute 'const' */
+#if (__GNUC__ == 4 && 6 <= __GNUC_MINOR__) || 4 < __GNUC__
+# pragma GCC diagnostic ignored "-Wsuggest-attribute=const"
+#endif
+
+#include <config.h>
+
+/* Specification. */
+#include "propername.h"
+
+#include <ctype.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#if HAVE_ICONV
+# include <iconv.h>
+#endif
+
+#include "trim.h"
+#include "mbchar.h"
+#include "mbuiter.h"
+#include "localcharset.h"
+#include "c-strcase.h"
+#include "xstriconv.h"
+#include "xalloc.h"
+#include "gettext.h"
+
+
+/* Tests whether STRING contains trim (SUB), starting and ending at word
+ boundaries.
+ Here, instead of implementing Unicode Standard Annex #29 for determining
+ word boundaries, we assume that trim (SUB) starts and ends with words and
+ only test whether the part before it ends with a non-word and the part
+ after it starts with a non-word. */
+static bool
+mbsstr_trimmed_wordbounded (const char *string, const char *sub)
+{
+ char *tsub = trim (sub);
+ bool found = false;
+
+ for (; *string != '\0';)
+ {
+ const char *tsub_in_string = mbsstr (string, tsub);
+ if (tsub_in_string == NULL)
+ break;
+ else
+ {
+ if (MB_CUR_MAX > 1)
+ {
+ mbui_iterator_t string_iter;
+ bool word_boundary_before;
+ bool word_boundary_after;
+
+ mbui_init (string_iter, string);
+ word_boundary_before = true;
+ if (mbui_cur_ptr (string_iter) < tsub_in_string)
+ {
+ mbchar_t last_char_before_tsub;
+ do
+ {
+ if (!mbui_avail (string_iter))
+ abort ();
+ last_char_before_tsub = mbui_cur (string_iter);
+ mbui_advance (string_iter);
+ }
+ while (mbui_cur_ptr (string_iter) < tsub_in_string);
+ if (mb_isalnum (last_char_before_tsub))
+ word_boundary_before = false;
+ }
+
+ mbui_init (string_iter, tsub_in_string);
+ {
+ mbui_iterator_t tsub_iter;
+
+ for (mbui_init (tsub_iter, tsub);
+ mbui_avail (tsub_iter);
+ mbui_advance (tsub_iter))
+ {
+ if (!mbui_avail (string_iter))
+ abort ();
+ mbui_advance (string_iter);
+ }
+ }
+ word_boundary_after = true;
+ if (mbui_avail (string_iter))
+ {
+ mbchar_t first_char_after_tsub = mbui_cur (string_iter);
+ if (mb_isalnum (first_char_after_tsub))
+ word_boundary_after = false;
+ }
+
+ if (word_boundary_before && word_boundary_after)
+ {
+ found = true;
+ break;
+ }
+
+ mbui_init (string_iter, tsub_in_string);
+ if (!mbui_avail (string_iter))
+ break;
+ string = tsub_in_string + mb_len (mbui_cur (string_iter));
+ }
+ else
+ {
+ bool word_boundary_before;
+ const char *p;
+ bool word_boundary_after;
+
+ word_boundary_before = true;
+ if (string < tsub_in_string)
+ if (isalnum ((unsigned char) tsub_in_string[-1]))
+ word_boundary_before = false;
+
+ p = tsub_in_string + strlen (tsub);
+ word_boundary_after = true;
+ if (*p != '\0')
+ if (isalnum ((unsigned char) *p))
+ word_boundary_after = false;
+
+ if (word_boundary_before && word_boundary_after)
+ {
+ found = true;
+ break;
+ }
+
+ if (*tsub_in_string == '\0')
+ break;
+ string = tsub_in_string + 1;
+ }
+ }
+ }
+ free (tsub);
+ return found;
+}
+
+/* Return the localization of NAME. NAME is written in ASCII. */
+
+const char *
+proper_name (const char *name)
+{
+ /* See whether there is a translation. */
+ const char *translation = gettext (name);
+
+ if (translation != name)
+ {
+ /* See whether the translation contains the original name. */
+ if (mbsstr_trimmed_wordbounded (translation, name))
+ return translation;
+ else
+ {
+ /* Return "TRANSLATION (NAME)". */
+ char *result =
+ XNMALLOC (strlen (translation) + 2 + strlen (name) + 1 + 1, char);
+
+ sprintf (result, "%s (%s)", translation, name);
+ return result;
+ }
+ }
+ else
+ return name;
+}
+
+/* Return the localization of a name whose original writing is not ASCII.
+ NAME_UTF8 is the real name, written in UTF-8 with octal or hexadecimal
+ escape sequences. NAME_ASCII is a fallback written only with ASCII
+ characters. */
+
+const char *
+proper_name_utf8 (const char *name_ascii, const char *name_utf8)
+{
+ /* See whether there is a translation. */
+ const char *translation = gettext (name_ascii);
+
+ /* Try to convert NAME_UTF8 to the locale encoding. */
+ const char *locale_code = locale_charset ();
+ char *alloc_name_converted = NULL;
+ char *alloc_name_converted_translit = NULL;
+ const char *name_converted = NULL;
+ const char *name_converted_translit = NULL;
+ const char *name;
+
+ if (c_strcasecmp (locale_code, "UTF-8") != 0)
+ {
+#if HAVE_ICONV
+ name_converted = alloc_name_converted =
+ xstr_iconv (name_utf8, "UTF-8", locale_code);
+
+# if (((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2) || __GLIBC__ > 2) \
+ && !defined __UCLIBC__) \
+ || _LIBICONV_VERSION >= 0x0105
+ {
+ char *converted_translit;
+
+ size_t len = strlen (locale_code);
+ char *locale_code_translit = XNMALLOC (len + 10 + 1, char);
+ memcpy (locale_code_translit, locale_code, len);
+ memcpy (locale_code_translit + len, "//TRANSLIT", 10 + 1);
+
+ converted_translit =
+ xstr_iconv (name_utf8, "UTF-8", locale_code_translit);
+
+ free (locale_code_translit);
+
+ if (converted_translit != NULL)
+ {
+# if !_LIBICONV_VERSION
+ /* Don't use the transliteration if it added question marks.
+ glibc's transliteration falls back to question marks; libiconv's
+ transliteration does not.
+ mbschr is equivalent to strchr in this case. */
+ if (strchr (converted_translit, '?') != NULL)
+ free (converted_translit);
+ else
+# endif
+ name_converted_translit = alloc_name_converted_translit =
+ converted_translit;
+ }
+ }
+# endif
+#endif
+ }
+ else
+ {
+ name_converted = name_utf8;
+ name_converted_translit = name_utf8;
+ }
+
+ /* The name in locale encoding. */
+ name = (name_converted != NULL ? name_converted :
+ name_converted_translit != NULL ? name_converted_translit :
+ name_ascii);
+
+ /* See whether we have a translation. Some translators have not understood
+ that they should use the UTF-8 form of the name, if possible. So if the
+ translator provided a no-op translation, we ignore it. */
+ if (strcmp (translation, name_ascii) != 0)
+ {
+ /* See whether the translation contains the original name. */
+ if (mbsstr_trimmed_wordbounded (translation, name_ascii)
+ || (name_converted != NULL
+ && mbsstr_trimmed_wordbounded (translation, name_converted))
+ || (name_converted_translit != NULL
+ && mbsstr_trimmed_wordbounded (translation, name_converted_translit)))
+ {
+ if (alloc_name_converted != NULL)
+ free (alloc_name_converted);
+ if (alloc_name_converted_translit != NULL)
+ free (alloc_name_converted_translit);
+ return translation;
+ }
+ else
+ {
+ /* Return "TRANSLATION (NAME)". */
+ char *result =
+ XNMALLOC (strlen (translation) + 2 + strlen (name) + 1 + 1, char);
+
+ sprintf (result, "%s (%s)", translation, name);
+
+ if (alloc_name_converted != NULL)
+ free (alloc_name_converted);
+ if (alloc_name_converted_translit != NULL)
+ free (alloc_name_converted_translit);
+ return result;
+ }
+ }
+ else
+ {
+ if (alloc_name_converted != NULL && alloc_name_converted != name)
+ free (alloc_name_converted);
+ if (alloc_name_converted_translit != NULL
+ && alloc_name_converted_translit != name)
+ free (alloc_name_converted_translit);
+ return name;
+ }
+}
+
+#ifdef TEST1
+# include <locale.h>
+int
+main (int argc, char *argv[])
+{
+ setlocale (LC_ALL, "");
+ if (mbsstr_trimmed_wordbounded (argv[1], argv[2]))
+ printf("found\n");
+ return 0;
+}
+#endif
+
+#ifdef TEST2
+# include <locale.h>
+# include <stdio.h>
+int
+main (int argc, char *argv[])
+{
+ setlocale (LC_ALL, "");
+ printf ("%s\n", proper_name_utf8 ("Franc,ois Pinard", "Fran\303\247ois Pinard"));
+ return 0;
+}
+#endif
diff --git a/lib/propername.h b/lib/propername.h
new file mode 100644
index 0000000..83fac08
--- /dev/null
+++ b/lib/propername.h
@@ -0,0 +1,106 @@
+/* Localization of proper names. -*- coding: utf-8 -*-
+ Copyright (C) 2006, 2008-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2006.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+/* INTRODUCTION
+
+ What do
+
+ Torbjörn Granlund (coreutils)
+ François Pinard (coreutils)
+ Danilo Å egan (gettext)
+
+ have in common?
+
+ A non-ASCII name. This causes trouble in the --version output. The simple
+ "solution" unfortunately mutilates the name.
+
+ $ du --version | grep Granlund
+ Écrit par Torbjorn Granlund, David MacKenzie, Paul Eggert et Jim Meyering.
+
+ $ ptx --version | grep Pinard
+ Écrit par F. Pinard.
+
+ What is desirable, is to print the full name if the output character set
+ allows it, and the ASCIIfied name only as a fallback.
+
+ $ recode-sr-latin --version
+ ...
+ Written by Danilo Å egan and Bruno Haible.
+
+ $ LC_ALL=C recode-sr-latin --version
+ ...
+ Written by Danilo Segan and Bruno Haible.
+
+ The 'propername' module does exactly this. Plus, for languages that use
+ a different writing system than the Latin alphabet, it allows a translator
+ to write the name using that different writing system. In that case the
+ output will look like this:
+ <translated name> (<original name in English>)
+
+ To use the 'propername' module requires three simple steps:
+
+ 1) Add it to the list of gnulib modules to import,
+
+ 2) Change the arguments of version_etc(),
+
+ from "Paul Eggert"
+ to proper_name ("Paul Eggert")
+
+ from "Torbjorn Granlund"
+ to proper_name_utf8 ("Torbjorn Granlund", "Torbj\303\266rn Granlund")
+
+ from "F. Pinard"
+ to proper_name_utf8 ("Franc,ois Pinard", "Fran\303\247ois Pinard")
+
+ (Optionally, here you can also add / * TRANSLATORS: ... * / comments
+ explaining how the name is written or pronounced.)
+
+ 3) If you are using GNU gettext version 0.16.1 or older, in po/Makevars,
+ in the definition of the XGETTEXT_OPTIONS variable, add:
+
+ --keyword='proper_name:1,"This is a proper name. See the gettext manual, section Names."'
+ --keyword='proper_name_utf8:1,"This is a proper name. See the gettext manual, section Names."'
+
+ This specifies automatic comments for the translator. (Requires
+ xgettext >= 0.15. The double-quotes inside the quoted string are on
+ purpose: they are part of the --keyword argument syntax.)
+ */
+
+#ifndef _PROPERNAME_H
+#define _PROPERNAME_H
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Return the localization of NAME. NAME is written in ASCII. */
+extern const char * proper_name (const char *name) /* NOT attribute const */;
+
+/* Return the localization of a name whose original writing is not ASCII.
+ NAME_UTF8 is the real name, written in UTF-8 with octal or hexadecimal
+ escape sequences. NAME_ASCII is a fallback written only with ASCII
+ characters. */
+extern const char * proper_name_utf8 (const char *name_ascii,
+ const char *name_utf8);
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif /* _PROPERNAME_H */
diff --git a/lib/pthread.c b/lib/pthread.c
new file mode 100644
index 0000000..188eb0a
--- /dev/null
+++ b/lib/pthread.c
@@ -0,0 +1,4 @@
+#include <config.h>
+#define _GL_PTHREAD_INLINE _GL_EXTERN_INLINE
+#include "pthread.h"
+typedef int dummy;
diff --git a/lib/pthread.in.h b/lib/pthread.in.h
new file mode 100644
index 0000000..02f8b55
--- /dev/null
+++ b/lib/pthread.in.h
@@ -0,0 +1,295 @@
+/* Implement a trivial subset of POSIX 1003.1-2008 pthread.h.
+
+ Copyright (C) 2009-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Paul Eggert and Glen Lenker. */
+
+#ifndef _@GUARD_PREFIX@_PTHREAD_H_
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+/* The include_next requires a split double-inclusion guard. */
+#if @HAVE_PTHREAD_H@
+# @INCLUDE_NEXT@ @NEXT_PTHREAD_H@
+#endif
+
+#ifndef _@GUARD_PREFIX@_PTHREAD_H_
+#define _@GUARD_PREFIX@_PTHREAD_H_
+
+#define __need_system_stdlib_h
+#include <stdlib.h>
+#undef __need_system_stdlib_h
+
+
+/* The pthreads-win32 <pthread.h> defines a couple of broken macros. */
+#undef asctime_r
+#undef ctime_r
+#undef gmtime_r
+#undef localtime_r
+#undef rand_r
+#undef strtok_r
+
+#include <errno.h>
+#include <sched.h>
+#include <sys/types.h>
+#include <time.h>
+
+#ifndef _GL_INLINE_HEADER_BEGIN
+ #error "Please include config.h first."
+#endif
+_GL_INLINE_HEADER_BEGIN
+#ifndef _GL_PTHREAD_INLINE
+# define _GL_PTHREAD_INLINE _GL_INLINE
+#endif
+
+#if ! @HAVE_PTHREAD_T@
+# if !GNULIB_defined_pthread_types
+ typedef int pthread_t;
+ typedef int pthread_attr_t;
+ typedef int pthread_barrier_t;
+ typedef int pthread_barrierattr_t;
+ typedef int pthread_cond_t;
+ typedef int pthread_condattr_t;
+ typedef int pthread_key_t;
+ typedef int pthread_mutex_t;
+ typedef int pthread_mutexattr_t;
+ typedef int pthread_once_t;
+ typedef int pthread_rwlock_t;
+ typedef int pthread_rwlockattr_t;
+# define GNULIB_defined_pthread_types 1
+# endif
+#endif
+
+#ifndef PTHREAD_COND_INITIALIZER
+#define PTHREAD_COND_INITIALIZER { 0 }
+#define PTHREAD_MUTEX_INITIALIZER { 0 }
+#define PTHREAD_ONCE_INIT { 0 }
+#define PTHREAD_RWLOCK_INITIALIZER { 0 }
+
+#define PTHREAD_BARRIER_SERIAL_THREAD (-1)
+
+#define PTHREAD_CANCEL_DEFERRED 0
+#define PTHREAD_CANCEL_ASYNCHRONOUS 1
+
+#define PTHREAD_CANCEL_ENABLE 0
+#define PTHREAD_CANCEL_DISABLE 1
+
+#define PTHREAD_CANCELED ((void *) -1)
+
+#define PTHREAD_CREATE_JOINABLE 0
+#define PTHREAD_CREATE_DETACHED 1
+
+#define PTHREAD_INHERIT_SCHED 0
+#define PTHREAD_EXPLICIT_SCHED 1
+
+#define PTHREAD_MUTEX_DEFAULT PTHREAD_MUTEX_NORMAL
+#define PTHREAD_MUTEX_NORMAL 0
+#define PTHREAD_MUTEX_ERRORCHECK 1
+#define PTHREAD_MUTEX_RECURSIVE 2
+
+#define PTHREAD_MUTEX_STALLED 0
+#define PTHREAD_MUTEX_ROBUST 1
+
+#define PTHREAD_PRIO_NONE 0
+#define PTHREAD_PRIO_INHERIT 1
+#define PTHREAD_PRIO_PROTECT 2
+
+#define PTHREAD_PROCESS_PRIVATE 0
+#define PTHREAD_PROCESS_SHARED 1
+
+#define PTHREAD_SCOPE_SYSTEM 0
+#define PTHREAD_SCOPE_PROCESS 1
+#endif
+
+#if ! @HAVE_PTHREAD_T@
+
+# if !GNULIB_defined_pthread_functions
+
+/* Provide substitutes for the thread functions that should work
+ adequately on a single-threaded implementation, where
+ pthread_create always fails. The goal is to let programs compile
+ on non-pthread hosts with minimal runtime overhead.
+
+ Omit interfaces that have not been analyzed and for which we do not
+ know what to do, so that they elicit a compile-time error for
+ now. */
+
+_GL_PTHREAD_INLINE int
+pthread_cond_destroy (pthread_cond_t *cond)
+{
+ /* COND is never seriously used. */
+ return 0;
+}
+
+_GL_PTHREAD_INLINE int
+pthread_cond_init (pthread_cond_t *restrict cond,
+ pthread_condattr_t const *restrict attr)
+{
+ /* COND is never seriously used. */
+ return 0;
+}
+
+_GL_PTHREAD_INLINE int
+pthread_cond_signal (pthread_cond_t *cond)
+{
+ /* No threads can currently be blocked on COND. */
+ return 0;
+}
+
+_GL_PTHREAD_INLINE int
+pthread_cond_wait (pthread_cond_t *restrict cond,
+ pthread_mutex_t *restrict mutex)
+{
+ /* Properly-written applications never come here. */
+ abort ();
+ return 0;
+}
+
+_GL_PTHREAD_INLINE int
+pthread_create (pthread_t *restrict thread,
+ pthread_attr_t const *restrict attr,
+ void * (*start_routine) (void*), void *restrict arg)
+{
+ /* Do not create a thread. */
+ return EAGAIN;
+}
+
+_GL_PTHREAD_INLINE void
+pthread_exit (void *value)
+{
+ /* There is just one thread, so the process exits. */
+ exit (0);
+}
+
+_GL_PTHREAD_INLINE int
+pthread_join (pthread_t thread, void **pvalue)
+{
+ /* Properly-written applications never come here. */
+ abort ();
+ return 0;
+}
+
+_GL_PTHREAD_INLINE int
+pthread_mutexattr_destroy (pthread_mutexattr_t *attr)
+{
+ return 0;
+}
+
+_GL_PTHREAD_INLINE int
+pthread_mutexattr_init (pthread_mutexattr_t *attr)
+{
+ return 0;
+}
+
+_GL_PTHREAD_INLINE int
+pthread_mutexattr_settype (pthread_mutexattr_t *attr, int attr_type)
+{
+ return 0;
+}
+
+_GL_PTHREAD_INLINE int
+pthread_mutex_destroy (pthread_mutex_t *mutex)
+{
+ /* MUTEX is never seriously used. */
+ return 0;
+}
+
+_GL_PTHREAD_INLINE int
+pthread_mutex_init (pthread_mutex_t *restrict mutex,
+ pthread_mutexattr_t const *restrict attr)
+{
+ /* MUTEX is never seriously used. */
+ return 0;
+}
+
+_GL_PTHREAD_INLINE int
+pthread_mutex_lock (pthread_mutex_t *mutex)
+{
+ /* There is only one thread, so it always gets the lock. This
+ implementation does not support PTHREAD_MUTEX_ERRORCHECK. */
+ return 0;
+}
+
+_GL_PTHREAD_INLINE int
+pthread_mutex_trylock (pthread_mutex_t *mutex)
+{
+ return pthread_mutex_lock (mutex);
+}
+
+_GL_PTHREAD_INLINE int
+pthread_mutex_unlock (pthread_mutex_t *mutex)
+{
+ /* There is only one thread, so it always unlocks successfully.
+ This implementation does not support robust mutexes or
+ PTHREAD_MUTEX_ERRORCHECK. */
+ return 0;
+}
+
+# define GNULIB_defined_pthread_functions 1
+# endif
+
+#endif
+
+#if ! @HAVE_PTHREAD_SPINLOCK_T@
+
+# if !GNULIB_defined_pthread_spinlock_t
+
+/* Approximate spinlocks with mutexes. */
+
+typedef pthread_mutex_t pthread_spinlock_t;
+
+_GL_PTHREAD_INLINE int
+pthread_spin_init (pthread_spinlock_t *lock, int pshared)
+{
+ return pthread_mutex_init (lock, NULL);
+}
+
+_GL_PTHREAD_INLINE int
+pthread_spin_destroy (pthread_spinlock_t *lock)
+{
+ return pthread_mutex_destroy (lock);
+}
+
+_GL_PTHREAD_INLINE int
+pthread_spin_lock (pthread_spinlock_t *lock)
+{
+ return pthread_mutex_lock (lock);
+}
+
+_GL_PTHREAD_INLINE int
+pthread_spin_trylock (pthread_spinlock_t *lock)
+{
+ return pthread_mutex_trylock (lock);
+}
+
+_GL_PTHREAD_INLINE int
+pthread_spin_unlock (pthread_spinlock_t *lock)
+{
+ return pthread_mutex_unlock (lock);
+}
+
+# define GNULIB_defined_pthread_spinlock_t 1
+# endif
+
+#endif
+
+_GL_INLINE_HEADER_END
+
+#endif /* _@GUARD_PREFIX@_PTHREAD_H_ */
+#endif /* _@GUARD_PREFIX@_PTHREAD_H_ */
diff --git a/lib/putenv.c b/lib/putenv.c
index 0602e44..e67712d 100644
--- a/lib/putenv.c
+++ b/lib/putenv.c
@@ -1,12 +1,12 @@
-/* Copyright (C) 1991, 1994, 1997, 1998, 2000, 2003, 2004, 2005, 2006, 2007
- Free Software Foundation, Inc.
+/* Copyright (C) 1991, 1994, 1997-1998, 2000, 2003-2016 Free Software
+ Foundation, Inc.
NOTE: The canonical source of this file is maintained with the GNU C
Library. Bugs can be reported to bug-glibc@prep.ai.mit.edu.
- This program is free software; you can redistribute it and/or modify it
+ 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 2, or (at your option) any
+ Free Software Foundation; either version 3 of the License, or any
later version.
This program is distributed in the hope that it will be useful,
@@ -15,16 +15,12 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
-/* undef putenv here, because some (e.g., Solaris 10) declare putenv in
- with a non-const argument. That would conflict with the declaration of
- rpl_putenv below (due to the #define putenv rpl_putenv from config.h). */
-#undef putenv
-int rpl_putenv (char const *);
+/* Specification. */
+#include <stdlib.h>
#include <stddef.h>
@@ -35,22 +31,28 @@ int rpl_putenv (char const *);
# define __set_errno(ev) ((errno) = (ev))
#endif
-#include <stdlib.h>
#include <string.h>
#include <unistd.h>
-#if HAVE_GNU_LD
-# define environ __environ
-#else
+#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+# define WIN32_LEAN_AND_MEAN
+# include <windows.h>
+#endif
+
+#if _LIBC
+# if HAVE_GNU_LD
+# define environ __environ
+# else
extern char **environ;
+# endif
#endif
#if _LIBC
-/* This lock protects against simultaneous modifications of `environ'. */
+/* This lock protects against simultaneous modifications of 'environ'. */
# include <bits/libc-lock.h>
__libc_lock_define_initialized (static, envlock)
-# define LOCK __libc_lock_lock (envlock)
-# define UNLOCK __libc_lock_unlock (envlock)
+# define LOCK __libc_lock_lock (envlock)
+# define UNLOCK __libc_lock_unlock (envlock)
#else
# define LOCK
# define UNLOCK
@@ -60,7 +62,9 @@ static int
_unsetenv (const char *name)
{
size_t len;
+#if !HAVE_DECL__PUTENV
char **ep;
+#endif
if (name == NULL || *name == '\0' || strchr (name, '=') != NULL)
{
@@ -70,19 +74,34 @@ _unsetenv (const char *name)
len = strlen (name);
+#if HAVE_DECL__PUTENV
+ {
+ int putenv_result, putenv_errno;
+ char *name_ = malloc (len + 2);
+ memcpy (name_, name, len);
+ name_[len] = '=';
+ name_[len + 1] = 0;
+ putenv_result = _putenv (name_);
+ putenv_errno = errno;
+ free (name_);
+ __set_errno (putenv_errno);
+ return putenv_result;
+ }
+#else
+
LOCK;
ep = environ;
while (*ep != NULL)
if (!strncmp (*ep, name, len) && (*ep)[len] == '=')
{
- /* Found it. Remove this pointer by moving later ones back. */
- char **dp = ep;
+ /* Found it. Remove this pointer by moving later ones back. */
+ char **dp = ep;
- do
- dp[0] = dp[1];
- while (*dp++);
- /* Continue the loop in case NAME appears again. */
+ do
+ dp[0] = dp[1];
+ while (*dp++);
+ /* Continue the loop in case NAME appears again. */
}
else
++ep;
@@ -90,17 +109,17 @@ _unsetenv (const char *name)
UNLOCK;
return 0;
+#endif
}
/* Put STRING, which is of the form "NAME=VALUE", in the environment.
- If STRING contains no `=', then remove STRING from the environment. */
+ If STRING contains no '=', then remove STRING from the environment. */
int
-rpl_putenv (const char *string)
+putenv (char *string)
{
- const char *const name_end = strchr (string, '=');
- register size_t size;
- register char **ep;
+ const char *name_end = strchr (string, '=');
+ char **ep;
if (name_end == NULL)
{
@@ -108,31 +127,68 @@ rpl_putenv (const char *string)
return _unsetenv (string);
}
- size = 0;
- for (ep = environ; *ep != NULL; ++ep)
- if (!strncmp (*ep, string, name_end - string) &&
- (*ep)[name_end - string] == '=')
+#if HAVE_DECL__PUTENV
+ /* Rely on _putenv to allocate the new environment. If other
+ parts of the application use _putenv, the !HAVE_DECL__PUTENV code
+ would fight over who owns the environ vector, causing a crash. */
+ if (name_end[1])
+ return _putenv (string);
+ else
+ {
+ /* _putenv ("NAME=") unsets NAME, so invoke _putenv ("NAME= ")
+ to allocate the environ vector and then replace the new
+ entry with "NAME=". */
+ int putenv_result, putenv_errno;
+ char *name_x = malloc (name_end - string + sizeof "= ");
+ if (!name_x)
+ return -1;
+ memcpy (name_x, string, name_end - string + 1);
+ name_x[name_end - string + 1] = ' ';
+ name_x[name_end - string + 2] = 0;
+ putenv_result = _putenv (name_x);
+ putenv_errno = errno;
+ for (ep = environ; *ep; ep++)
+ if (strcmp (*ep, name_x) == 0)
+ {
+ *ep = string;
+ break;
+ }
+# if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+ if (putenv_result == 0)
+ {
+ /* _putenv propagated "NAME= " into the subprocess environment;
+ fix that by calling SetEnvironmentVariable directly. */
+ name_x[name_end - string] = 0;
+ putenv_result = SetEnvironmentVariable (name_x, "") ? 0 : -1;
+ putenv_errno = ENOMEM; /* ENOMEM is the only way to fail. */
+ }
+# endif
+ free (name_x);
+ __set_errno (putenv_errno);
+ return putenv_result;
+ }
+#else
+ for (ep = environ; *ep; ep++)
+ if (strncmp (*ep, string, name_end - string) == 0
+ && (*ep)[name_end - string] == '=')
break;
- else
- ++size;
- if (*ep == NULL)
+ if (*ep)
+ *ep = string;
+ else
{
static char **last_environ = NULL;
- char **new_environ = (char **) malloc ((size + 2) * sizeof (char *));
- if (new_environ == NULL)
- return -1;
- (void) memcpy ((void *) new_environ, (void *) environ,
- size * sizeof (char *));
- new_environ[size] = (char *) string;
- new_environ[size + 1] = NULL;
- if (last_environ != NULL)
- free (last_environ);
+ size_t size = ep - environ;
+ char **new_environ = malloc ((size + 2) * sizeof *new_environ);
+ if (! new_environ)
+ return -1;
+ new_environ[0] = string;
+ memcpy (new_environ + 1, environ, (size + 1) * sizeof *new_environ);
+ free (last_environ);
last_environ = new_environ;
environ = new_environ;
}
- else
- *ep = (char *) string;
return 0;
+#endif
}
diff --git a/lib/qcopy-acl.c b/lib/qcopy-acl.c
new file mode 100644
index 0000000..c7bdfbb
--- /dev/null
+++ b/lib/qcopy-acl.c
@@ -0,0 +1,51 @@
+/* Copy access control list from one file to another. -*- coding: utf-8 -*-
+
+ Copyright (C) 2002-2003, 2005-2016 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 <http://www.gnu.org/licenses/>.
+
+ Written by Paul Eggert, Andreas Grünbacher, and Bruno Haible. */
+
+#include <config.h>
+
+#include "acl.h"
+
+#include "acl-internal.h"
+
+
+/* Copy access control lists from one file to another. If SOURCE_DESC is
+ a valid file descriptor, use file descriptor operations, else use
+ filename based operations on SRC_NAME. Likewise for DEST_DESC and
+ DST_NAME.
+ If access control lists are not available, fchmod the target file to
+ MODE. Also sets the non-permission bits of the destination file
+ (S_ISUID, S_ISGID, S_ISVTX) to those from MODE if any are set.
+ Return 0 if successful.
+ Return -2 and set errno for an error relating to the source file.
+ Return -1 and set errno for an error relating to the destination file. */
+
+int
+qcopy_acl (const char *src_name, int source_desc, const char *dst_name,
+ int dest_desc, mode_t mode)
+{
+ struct permission_context ctx;
+ int ret;
+
+ ret = get_permissions (src_name, source_desc, mode, &ctx);
+ if (ret != 0)
+ return -2;
+ ret = set_permissions (&ctx, dst_name, dest_desc);
+ free_permission_context (&ctx);
+ return ret;
+}
diff --git a/lib/qset-acl.c b/lib/qset-acl.c
new file mode 100644
index 0000000..77227dc
--- /dev/null
+++ b/lib/qset-acl.c
@@ -0,0 +1,49 @@
+/* qset-acl.c - set access control list equivalent to a mode
+
+ Copyright (C) 2002-2003, 2005-2016 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 <http://www.gnu.org/licenses/>.
+
+ Written by Paul Eggert and Andreas Gruenbacher, and Bruno Haible. */
+
+#include <config.h>
+
+#define ACL_INTERNAL_INLINE _GL_EXTERN_INLINE
+
+#include <string.h>
+#include "acl.h"
+
+#include "acl-internal.h"
+
+
+/* Set the access control lists of a file. If DESC is a valid file
+ descriptor, use file descriptor operations where available, else use
+ filename based operations on NAME. If access control lists are not
+ available, fchmod the target file to MODE. Also sets the
+ non-permission bits of the destination file (S_ISUID, S_ISGID, S_ISVTX)
+ to those from MODE if any are set.
+ Return 0 if successful. Return -1 and set errno upon failure. */
+
+int
+qset_acl (char const *name, int desc, mode_t mode)
+{
+ struct permission_context ctx;
+ int ret;
+
+ memset (&ctx, 0, sizeof ctx);
+ ctx.mode = mode;
+ ret = set_permissions (&ctx, name, desc);
+ free_permission_context (&ctx);
+ return ret;
+}
diff --git a/lib/quote.c b/lib/quote.c
deleted file mode 100644
index 119be72..0000000
--- a/lib/quote.c
+++ /dev/null
@@ -1,41 +0,0 @@
-/* quote.c - quote arguments for output
-
- Copyright (C) 1998, 1999, 2000, 2001, 2003, 2005, 2006 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-/* Written by Paul Eggert <eggert@twinsun.com> */
-
-#include <config.h>
-
-#include "quotearg.h"
-#include "quote.h"
-
-/* Return an unambiguous printable representation of NAME,
- allocated in slot N, suitable for diagnostics. */
-char const *
-quote_n (int n, char const *name)
-{
- return quotearg_n_style (n, locale_quoting_style, name);
-}
-
-/* Return an unambiguous printable representation of NAME,
- suitable for diagnostics. */
-char const *
-quote (char const *name)
-{
- return quote_n (0, name);
-}
diff --git a/lib/quote.h b/lib/quote.h
index 5400ead..b53d0ea 100644
--- a/lib/quote.h
+++ b/lib/quote.h
@@ -1,12 +1,11 @@
/* quote.h - prototypes for quote.c
- Copyright (C) 1998, 1999, 2000, 2001, 2003 Free Software
- Foundation, Inc.
+ Copyright (C) 1998-2001, 2003, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,9 +13,34 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
+#ifndef QUOTE_H_
+# define QUOTE_H_ 1
-char const *quote_n (int n, char const *name);
-char const *quote (char const *name);
+# include <stddef.h>
+
+/* The quoting options used by quote_n and quote. Its type is incomplete,
+ so it's useful only in expressions like '&quote_quoting_options'. */
+extern struct quoting_options quote_quoting_options;
+
+/* Return an unambiguous printable representation of ARG (of size
+ ARGSIZE), allocated in slot N, suitable for diagnostics. If
+ ARGSIZE is SIZE_MAX, use the string length of the argument for
+ ARGSIZE. */
+char const *quote_n_mem (int n, char const *arg, size_t argsize);
+
+/* Return an unambiguous printable representation of ARG (of size
+ ARGSIZE), suitable for diagnostics. If ARGSIZE is SIZE_MAX, use
+ the string length of the argument for ARGSIZE. */
+char const *quote_mem (char const *arg, size_t argsize);
+
+/* Return an unambiguous printable representation of ARG, allocated in
+ slot N, suitable for diagnostics. */
+char const *quote_n (int n, char const *arg);
+
+/* Return an unambiguous printable representation of ARG, suitable for
+ diagnostics. */
+char const *quote (char const *arg);
+
+#endif /* !QUOTE_H_ */
diff --git a/lib/quotearg.c b/lib/quotearg.c
index f7f326a..73a5084 100644
--- a/lib/quotearg.c
+++ b/lib/quotearg.c
@@ -1,12 +1,11 @@
/* quotearg.c - quote arguments for output
- Copyright (C) 1998, 1999, 2000, 2001, 2002, 2004, 2005, 2006, 2007 Free
- Software Foundation, Inc.
+ Copyright (C) 1998-2002, 2004-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,16 +13,25 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert <eggert@twinsun.com> */
+/* Without this pragma, gcc 4.7.0 20111124 mistakenly suggests that
+ the quoting_options_from_style function might be candidate for
+ attribute 'pure' */
+#if (__GNUC__ == 4 && 6 <= __GNUC_MINOR__) || 4 < __GNUC__
+# pragma GCC diagnostic ignored "-Wsuggest-attribute=pure"
+#endif
+
#include <config.h>
#include "quotearg.h"
+#include "quote.h"
#include "xalloc.h"
+#include "c-strcaseeq.h"
+#include "localcharset.h"
#include <ctype.h>
#include <errno.h>
@@ -38,23 +46,6 @@
#define _(msgid) gettext (msgid)
#define N_(msgid) msgid
-#if !HAVE_MBRTOWC
-/* Disable multibyte processing entirely. Since MB_CUR_MAX is 1, the
- other macros are defined only for documentation and to satisfy C
- syntax. */
-# undef MB_CUR_MAX
-# define MB_CUR_MAX 1
-# undef mbstate_t
-# define mbstate_t int
-# define mbrtowc(pwc, s, n, ps) ((*(pwc) = *(s)) != 0)
-# define iswprint(wc) isprint ((unsigned char) (wc))
-# undef HAVE_MBSINIT
-#endif
-
-#if !defined mbsinit && !HAVE_MBSINIT
-# define mbsinit(ps) 1
-#endif
-
#ifndef SIZE_MAX
# define SIZE_MAX ((size_t) -1)
#endif
@@ -66,9 +57,18 @@ struct quoting_options
/* Basic quoting style. */
enum quoting_style style;
+ /* Additional flags. Bitwise combination of enum quoting_flags. */
+ int flags;
+
/* Quote the characters indicated by this bit vector even if the
quoting style would not normally require them to be quoted. */
unsigned int quote_these_too[(UCHAR_MAX / INT_BITS) + 1];
+
+ /* The left quote for custom_quoting_style. */
+ char const *left_quote;
+
+ /* The right quote for custom_quoting_style. */
+ char const *right_quote;
};
/* Names of quoting styles. */
@@ -77,7 +77,10 @@ char const *const quoting_style_args[] =
"literal",
"shell",
"shell-always",
+ "shell-escape",
+ "shell-escape-always",
"c",
+ "c-maybe",
"escape",
"locale",
"clocale",
@@ -90,7 +93,10 @@ enum quoting_style const quoting_style_vals[] =
literal_quoting_style,
shell_quoting_style,
shell_always_quoting_style,
+ shell_escape_quoting_style,
+ shell_escape_always_quoting_style,
c_quoting_style,
+ c_maybe_quoting_style,
escape_quoting_style,
locale_quoting_style,
clocale_quoting_style
@@ -107,14 +113,14 @@ clone_quoting_options (struct quoting_options *o)
{
int e = errno;
struct quoting_options *p = xmemdup (o ? o : &default_quoting_options,
- sizeof *o);
+ sizeof *o);
errno = e;
return p;
}
/* Get the value of O's quoting style. If O is null, use the default. */
enum quoting_style
-get_quoting_style (struct quoting_options *o)
+get_quoting_style (struct quoting_options const *o)
{
return (o ? o : &default_quoting_options)->style;
}
@@ -144,20 +150,88 @@ set_char_quoting (struct quoting_options *o, char c, int i)
return r;
}
+/* In O (or in the default if O is null),
+ set the value of the quoting options flag to I, which can be a
+ bitwise combination of enum quoting_flags, or 0 for default
+ behavior. Return the old value. */
+int
+set_quoting_flags (struct quoting_options *o, int i)
+{
+ int r;
+ if (!o)
+ o = &default_quoting_options;
+ r = o->flags;
+ o->flags = i;
+ return r;
+}
+
+void
+set_custom_quoting (struct quoting_options *o,
+ char const *left_quote, char const *right_quote)
+{
+ if (!o)
+ o = &default_quoting_options;
+ o->style = custom_quoting_style;
+ if (!left_quote || !right_quote)
+ abort ();
+ o->left_quote = left_quote;
+ o->right_quote = right_quote;
+}
+
+/* Return quoting options for STYLE, with no extra quoting. */
+static struct quoting_options /* NOT PURE!! */
+quoting_options_from_style (enum quoting_style style)
+{
+ struct quoting_options o = { literal_quoting_style, 0, { 0 }, NULL, NULL };
+ if (style == custom_quoting_style)
+ abort ();
+ o.style = style;
+ return o;
+}
+
/* MSGID approximates a quotation mark. Return its translation if it
- has one; otherwise, return either it or "\"", depending on S. */
+ has one; otherwise, return either it or "\"", depending on S.
+
+ S is either clocale_quoting_style or locale_quoting_style. */
static char const *
gettext_quote (char const *msgid, enum quoting_style s)
{
char const *translation = _(msgid);
- if (translation == msgid && s == clocale_quoting_style)
- translation = "\"";
- return translation;
+ char const *locale_code;
+
+ if (translation != msgid)
+ return translation;
+
+ /* For UTF-8 and GB-18030, use single quotes U+2018 and U+2019.
+ Here is a list of other locales that include U+2018 and U+2019:
+
+ ISO-8859-7 0xA1 KOI8-T 0x91
+ CP869 0x8B CP874 0x91
+ CP932 0x81 0x65 CP936 0xA1 0xAE
+ CP949 0xA1 0xAE CP950 0xA1 0xA5
+ CP1250 0x91 CP1251 0x91
+ CP1252 0x91 CP1253 0x91
+ CP1254 0x91 CP1255 0x91
+ CP1256 0x91 CP1257 0x91
+ EUC-JP 0xA1 0xC6 EUC-KR 0xA1 0xAE
+ EUC-TW 0xA1 0xE4 BIG5 0xA1 0xA5
+ BIG5-HKSCS 0xA1 0xA5 EUC-CN 0xA1 0xAE
+ GBK 0xA1 0xAE Georgian-PS 0x91
+ PT154 0x91
+
+ None of these is still in wide use; using iconv is overkill. */
+ locale_code = locale_charset ();
+ if (STRCASEEQ (locale_code, "UTF-8", 'U','T','F','-','8',0,0,0,0))
+ return msgid[0] == '`' ? "\xe2\x80\x98": "\xe2\x80\x99";
+ if (STRCASEEQ (locale_code, "GB18030", 'G','B','1','8','0','3','0',0,0))
+ return msgid[0] == '`' ? "\xa1\ae": "\xa1\xaf";
+
+ return (s == clocale_quoting_style ? "\"" : "'");
}
/* Place into buffer BUFFER (of size BUFFERSIZE) a quoted version of
- argument ARG (of size ARGSIZE), using QUOTING_STYLE and the
- non-quoting-style part of O to control quoting.
+ argument ARG (of size ARGSIZE), using QUOTING_STYLE, FLAGS, and
+ QUOTE_THESE_TOO to control quoting.
Terminate the output with a null character, and return the written
size of the output, not counting the terminating null.
If BUFFERSIZE is too small to store the output string, return the
@@ -165,14 +239,16 @@ gettext_quote (char const *msgid, enum quoting_style s)
If ARGSIZE is SIZE_MAX, use the string length of the argument for ARGSIZE.
This function acts like quotearg_buffer (BUFFER, BUFFERSIZE, ARG,
- ARGSIZE, O), except it uses QUOTING_STYLE instead of the quoting
- style specified by O, and O may not be null. */
+ ARGSIZE, O), except it breaks O into its component pieces and is
+ not careful about errno. */
static size_t
quotearg_buffer_restyled (char *buffer, size_t buffersize,
- char const *arg, size_t argsize,
- enum quoting_style quoting_style,
- struct quoting_options const *o)
+ char const *arg, size_t argsize,
+ enum quoting_style quoting_style, int flags,
+ unsigned int const *quote_these_too,
+ char const *left_quote,
+ char const *right_quote)
{
size_t i;
size_t len = 0;
@@ -180,20 +256,57 @@ quotearg_buffer_restyled (char *buffer, size_t buffersize,
size_t quote_string_len = 0;
bool backslash_escapes = false;
bool unibyte_locale = MB_CUR_MAX == 1;
+ bool elide_outer_quotes = (flags & QA_ELIDE_OUTER_QUOTES) != 0;
+ bool pending_shell_escape_end = false;
#define STORE(c) \
do \
{ \
- if (len < buffersize) \
- buffer[len] = (c); \
- len++; \
+ if (len < buffersize) \
+ buffer[len] = (c); \
+ len++; \
+ } \
+ while (0)
+
+#define START_ESC() \
+ do \
+ { \
+ if (elide_outer_quotes) \
+ goto force_outer_quoting_style; \
+ escaping = true; \
+ if (quoting_style == shell_always_quoting_style \
+ && ! pending_shell_escape_end) \
+ { \
+ STORE ('\''); \
+ STORE ('$'); \
+ STORE ('\''); \
+ pending_shell_escape_end = true; \
+ } \
+ STORE ('\\'); \
+ } \
+ while (0)
+
+#define END_ESC() \
+ do \
+ { \
+ if (pending_shell_escape_end && ! escaping) \
+ { \
+ STORE ('\''); \
+ STORE ('\''); \
+ pending_shell_escape_end = false; \
+ } \
} \
while (0)
switch (quoting_style)
{
+ case c_maybe_quoting_style:
+ quoting_style = c_quoting_style;
+ elide_outer_quotes = true;
+ /* Fall through. */
case c_quoting_style:
- STORE ('"');
+ if (!elide_outer_quotes)
+ STORE ('"');
backslash_escapes = true;
quote_string = "\"";
quote_string_len = 1;
@@ -201,301 +314,388 @@ quotearg_buffer_restyled (char *buffer, size_t buffersize,
case escape_quoting_style:
backslash_escapes = true;
+ elide_outer_quotes = false;
break;
case locale_quoting_style:
case clocale_quoting_style:
+ case custom_quoting_style:
{
- /* TRANSLATORS:
- Get translations for open and closing quotation marks.
-
- The message catalog should translate "`" to a left
- quotation mark suitable for the locale, and similarly for
- "'". If the catalog has no translation,
- locale_quoting_style quotes `like this', and
- clocale_quoting_style quotes "like this".
-
- For example, an American English Unicode locale should
- translate "`" to U+201C (LEFT DOUBLE QUOTATION MARK), and
- should translate "'" to U+201D (RIGHT DOUBLE QUOTATION
- MARK). A British English Unicode locale should instead
- translate these to U+2018 (LEFT SINGLE QUOTATION MARK) and
- U+2019 (RIGHT SINGLE QUOTATION MARK), respectively.
-
- If you don't know what to put here, please see
- <http://en.wikipedia.org/wiki/Quotation_mark#Glyphs>
- and use glyphs suitable for your language. */
-
- char const *left = gettext_quote (N_("`"), quoting_style);
- char const *right = gettext_quote (N_("'"), quoting_style);
- for (quote_string = left; *quote_string; quote_string++)
- STORE (*quote_string);
- backslash_escapes = true;
- quote_string = right;
- quote_string_len = strlen (quote_string);
+ if (quoting_style != custom_quoting_style)
+ {
+ /* TRANSLATORS:
+ Get translations for open and closing quotation marks.
+ The message catalog should translate "`" to a left
+ quotation mark suitable for the locale, and similarly for
+ "'". For example, a French Unicode local should translate
+ these to U+00AB (LEFT-POINTING DOUBLE ANGLE
+ QUOTATION MARK), and U+00BB (RIGHT-POINTING DOUBLE ANGLE
+ QUOTATION MARK), respectively.
+
+ If the catalog has no translation, we will try to
+ use Unicode U+2018 (LEFT SINGLE QUOTATION MARK) and
+ Unicode U+2019 (RIGHT SINGLE QUOTATION MARK). If the
+ current locale is not Unicode, locale_quoting_style
+ will quote 'like this', and clocale_quoting_style will
+ quote "like this". You should always include translations
+ for "`" and "'" even if U+2018 and U+2019 are appropriate
+ for your locale.
+
+ If you don't know what to put here, please see
+ <http://en.wikipedia.org/wiki/Quotation_marks_in_other_languages>
+ and use glyphs suitable for your language. */
+ left_quote = gettext_quote (N_("`"), quoting_style);
+ right_quote = gettext_quote (N_("'"), quoting_style);
+ }
+ if (!elide_outer_quotes)
+ for (quote_string = left_quote; *quote_string; quote_string++)
+ STORE (*quote_string);
+ backslash_escapes = true;
+ quote_string = right_quote;
+ quote_string_len = strlen (quote_string);
}
break;
+ case shell_escape_quoting_style:
+ backslash_escapes = true;
+ /* Fall through. */
+ case shell_quoting_style:
+ elide_outer_quotes = true;
+ /* Fall through. */
+ case shell_escape_always_quoting_style:
+ if (!elide_outer_quotes)
+ backslash_escapes = true;
+ /* Fall through. */
case shell_always_quoting_style:
- STORE ('\'');
+ quoting_style = shell_always_quoting_style;
+ if (!elide_outer_quotes)
+ STORE ('\'');
quote_string = "'";
quote_string_len = 1;
break;
- default:
+ case literal_quoting_style:
+ elide_outer_quotes = false;
break;
+
+ default:
+ abort ();
}
for (i = 0; ! (argsize == SIZE_MAX ? arg[i] == '\0' : i == argsize); i++)
{
unsigned char c;
unsigned char esc;
+ bool is_right_quote = false;
+ bool escaping = false;
if (backslash_escapes
- && quote_string_len
- && i + quote_string_len <= argsize
- && memcmp (arg + i, quote_string, quote_string_len) == 0)
- STORE ('\\');
+ && quoting_style != shell_always_quoting_style
+ && quote_string_len
+ && (i + quote_string_len
+ <= (argsize == SIZE_MAX && 1 < quote_string_len
+ /* Use strlen only if we must: when argsize is SIZE_MAX,
+ and when the quote string is more than 1 byte long.
+ If we do call strlen, save the result. */
+ ? (argsize = strlen (arg)) : argsize))
+ && memcmp (arg + i, quote_string, quote_string_len) == 0)
+ {
+ if (elide_outer_quotes)
+ goto force_outer_quoting_style;
+ is_right_quote = true;
+ }
c = arg[i];
switch (c)
- {
- case '\0':
- if (backslash_escapes)
- {
- STORE ('\\');
- STORE ('0');
- STORE ('0');
- c = '0';
- }
- break;
-
- case '?':
- switch (quoting_style)
- {
- case shell_quoting_style:
- goto use_shell_always_quoting_style;
-
- case c_quoting_style:
- if (i + 2 < argsize && arg[i + 1] == '?')
- switch (arg[i + 2])
- {
- case '!': case '\'':
- case '(': case ')': case '-': case '/':
- case '<': case '=': case '>':
- /* Escape the second '?' in what would otherwise be
- a trigraph. */
- c = arg[i + 2];
- i += 2;
- STORE ('?');
- STORE ('\\');
- STORE ('?');
- break;
-
- default:
- break;
- }
- break;
-
- default:
- break;
- }
- break;
-
- case '\a': esc = 'a'; goto c_escape;
- case '\b': esc = 'b'; goto c_escape;
- case '\f': esc = 'f'; goto c_escape;
- case '\n': esc = 'n'; goto c_and_shell_escape;
- case '\r': esc = 'r'; goto c_and_shell_escape;
- case '\t': esc = 't'; goto c_and_shell_escape;
- case '\v': esc = 'v'; goto c_escape;
- case '\\': esc = c; goto c_and_shell_escape;
-
- c_and_shell_escape:
- if (quoting_style == shell_quoting_style)
- goto use_shell_always_quoting_style;
- c_escape:
- if (backslash_escapes)
- {
- c = esc;
- goto store_escape;
- }
- break;
-
- case '{': case '}': /* sometimes special if isolated */
- if (! (argsize == SIZE_MAX ? arg[1] == '\0' : argsize == 1))
- break;
- /* Fall through. */
- case '#': case '~':
- if (i != 0)
- break;
- /* Fall through. */
- case ' ':
- case '!': /* special in bash */
- case '"': case '$': case '&':
- case '(': case ')': case '*': case ';':
- case '<':
- case '=': /* sometimes special in 0th or (with "set -k") later args */
- case '>': case '[':
- case '^': /* special in old /bin/sh, e.g. SunOS 4.1.4 */
- case '`': case '|':
- /* A shell special character. In theory, '$' and '`' could
- be the first bytes of multibyte characters, which means
- we should check them with mbrtowc, but in practice this
- doesn't happen so it's not worth worrying about. */
- if (quoting_style == shell_quoting_style)
- goto use_shell_always_quoting_style;
- break;
-
- case '\'':
- switch (quoting_style)
- {
- case shell_quoting_style:
- goto use_shell_always_quoting_style;
-
- case shell_always_quoting_style:
- STORE ('\'');
- STORE ('\\');
- STORE ('\'');
- break;
-
- default:
- break;
- }
- break;
-
- case '%': case '+': case ',': case '-': case '.': case '/':
- case '0': case '1': case '2': case '3': case '4': case '5':
- case '6': case '7': case '8': case '9': case ':':
- case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
- case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
- case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
- case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
- case 'Y': case 'Z': case ']': case '_': case 'a': case 'b':
- case 'c': case 'd': case 'e': case 'f': case 'g': case 'h':
- case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
- case 'o': case 'p': case 'q': case 'r': case 's': case 't':
- case 'u': case 'v': case 'w': case 'x': case 'y': case 'z':
- /* These characters don't cause problems, no matter what the
- quoting style is. They cannot start multibyte sequences. */
- break;
-
- default:
- /* If we have a multibyte sequence, copy it until we reach
- its end, find an error, or come back to the initial shift
- state. For C-like styles, if the sequence has
- unprintable characters, escape the whole sequence, since
- we can't easily escape single characters within it. */
- {
- /* Length of multibyte sequence found so far. */
- size_t m;
-
- bool printable;
-
- if (unibyte_locale)
- {
- m = 1;
- printable = isprint (c) != 0;
- }
- else
- {
- mbstate_t mbstate;
- memset (&mbstate, 0, sizeof mbstate);
-
- m = 0;
- printable = true;
- if (argsize == SIZE_MAX)
- argsize = strlen (arg);
-
- do
- {
- wchar_t w;
- size_t bytes = mbrtowc (&w, &arg[i + m],
- argsize - (i + m), &mbstate);
- if (bytes == 0)
- break;
- else if (bytes == (size_t) -1)
- {
- printable = false;
- break;
- }
- else if (bytes == (size_t) -2)
- {
- printable = false;
- while (i + m < argsize && arg[i + m])
- m++;
- break;
- }
- else
- {
- /* Work around a bug with older shells that "see" a '\'
- that is really the 2nd byte of a multibyte character.
- In practice the problem is limited to ASCII
- chars >= '@' that are shell special chars. */
- if ('[' == 0x5b && quoting_style == shell_quoting_style)
- {
- size_t j;
- for (j = 1; j < bytes; j++)
- switch (arg[i + m + j])
- {
- case '[': case '\\': case '^':
- case '`': case '|':
- goto use_shell_always_quoting_style;
-
- default:
- break;
- }
- }
-
- if (! iswprint (w))
- printable = false;
- m += bytes;
- }
- }
- while (! mbsinit (&mbstate));
- }
-
- if (1 < m || (backslash_escapes && ! printable))
- {
- /* Output a multibyte sequence, or an escaped
- unprintable unibyte character. */
- size_t ilim = i + m;
-
- for (;;)
- {
- if (backslash_escapes && ! printable)
- {
- STORE ('\\');
- STORE ('0' + (c >> 6));
- STORE ('0' + ((c >> 3) & 7));
- c = '0' + (c & 7);
- }
- if (ilim <= i + 1)
- break;
- STORE (c);
- c = arg[++i];
- }
-
- goto store_c;
- }
- }
- }
-
- if (! (backslash_escapes
- && o->quote_these_too[c / INT_BITS] & (1 << (c % INT_BITS))))
- goto store_c;
+ {
+ case '\0':
+ if (backslash_escapes)
+ {
+ START_ESC ();
+ /* If quote_string were to begin with digits, we'd need to
+ test for the end of the arg as well. However, it's
+ hard to imagine any locale that would use digits in
+ quotes, and set_custom_quoting is documented not to
+ accept them. Use only a single \0 with shell-escape
+ as currently digits are not printed within $'...' */
+ if (quoting_style != shell_always_quoting_style
+ && i + 1 < argsize && '0' <= arg[i + 1] && arg[i + 1] <= '9')
+ {
+ STORE ('0');
+ STORE ('0');
+ }
+ c = '0';
+ /* We don't have to worry that this last '0' will be
+ backslash-escaped because, again, quote_string should
+ not start with it and because quote_these_too is
+ documented as not accepting it. */
+ }
+ else if (flags & QA_ELIDE_NULL_BYTES)
+ continue;
+ break;
+
+ case '?':
+ switch (quoting_style)
+ {
+ case shell_always_quoting_style:
+ if (elide_outer_quotes)
+ goto force_outer_quoting_style;
+ break;
+
+ case c_quoting_style:
+ if ((flags & QA_SPLIT_TRIGRAPHS)
+ && i + 2 < argsize && arg[i + 1] == '?')
+ switch (arg[i + 2])
+ {
+ case '!': case '\'':
+ case '(': case ')': case '-': case '/':
+ case '<': case '=': case '>':
+ /* Escape the second '?' in what would otherwise be
+ a trigraph. */
+ if (elide_outer_quotes)
+ goto force_outer_quoting_style;
+ c = arg[i + 2];
+ i += 2;
+ STORE ('?');
+ STORE ('"');
+ STORE ('"');
+ STORE ('?');
+ break;
+
+ default:
+ break;
+ }
+ break;
+
+ default:
+ break;
+ }
+ break;
+
+ case '\a': esc = 'a'; goto c_escape;
+ case '\b': esc = 'b'; goto c_escape;
+ case '\f': esc = 'f'; goto c_escape;
+ case '\n': esc = 'n'; goto c_and_shell_escape;
+ case '\r': esc = 'r'; goto c_and_shell_escape;
+ case '\t': esc = 't'; goto c_and_shell_escape;
+ case '\v': esc = 'v'; goto c_escape;
+ case '\\': esc = c;
+ /* Never need to escape '\' in shell case. */
+ if (quoting_style == shell_always_quoting_style)
+ {
+ if (elide_outer_quotes)
+ goto force_outer_quoting_style;
+ goto store_c;
+ }
+
+ /* No need to escape the escape if we are trying to elide
+ outer quotes and nothing else is problematic. */
+ if (backslash_escapes && elide_outer_quotes && quote_string_len)
+ goto store_c;
+
+ c_and_shell_escape:
+ if (quoting_style == shell_always_quoting_style
+ && elide_outer_quotes)
+ goto force_outer_quoting_style;
+ /* Fall through. */
+ c_escape:
+ if (backslash_escapes)
+ {
+ c = esc;
+ goto store_escape;
+ }
+ break;
+
+ case '{': case '}': /* sometimes special if isolated */
+ if (! (argsize == SIZE_MAX ? arg[1] == '\0' : argsize == 1))
+ break;
+ /* Fall through. */
+ case '#': case '~':
+ if (i != 0)
+ break;
+ /* Fall through. */
+ case ' ':
+ case '!': /* special in bash */
+ case '"': case '$': case '&':
+ case '(': case ')': case '*': case ';':
+ case '<':
+ case '=': /* sometimes special in 0th or (with "set -k") later args */
+ case '>': case '[':
+ case '^': /* special in old /bin/sh, e.g. SunOS 4.1.4 */
+ case '`': case '|':
+ /* A shell special character. In theory, '$' and '`' could
+ be the first bytes of multibyte characters, which means
+ we should check them with mbrtowc, but in practice this
+ doesn't happen so it's not worth worrying about. */
+ if (quoting_style == shell_always_quoting_style
+ && elide_outer_quotes)
+ goto force_outer_quoting_style;
+ break;
+
+ case '\'':
+ if (quoting_style == shell_always_quoting_style)
+ {
+ if (elide_outer_quotes)
+ goto force_outer_quoting_style;
+ STORE ('\'');
+ STORE ('\\');
+ STORE ('\'');
+ pending_shell_escape_end = false;
+ }
+ break;
+
+ case '%': case '+': case ',': case '-': case '.': case '/':
+ case '0': case '1': case '2': case '3': case '4': case '5':
+ case '6': case '7': case '8': case '9': case ':':
+ case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
+ case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
+ case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
+ case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
+ case 'Y': case 'Z': case ']': case '_': case 'a': case 'b':
+ case 'c': case 'd': case 'e': case 'f': case 'g': case 'h':
+ case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
+ case 'o': case 'p': case 'q': case 'r': case 's': case 't':
+ case 'u': case 'v': case 'w': case 'x': case 'y': case 'z':
+ /* These characters don't cause problems, no matter what the
+ quoting style is. They cannot start multibyte sequences.
+ A digit or a special letter would cause trouble if it
+ appeared at the beginning of quote_string because we'd then
+ escape by prepending a backslash. However, it's hard to
+ imagine any locale that would use digits or letters as
+ quotes, and set_custom_quoting is documented not to accept
+ them. Also, a digit or a special letter would cause
+ trouble if it appeared in quote_these_too, but that's also
+ documented as not accepting them. */
+ break;
+
+ default:
+ /* If we have a multibyte sequence, copy it until we reach
+ its end, find an error, or come back to the initial shift
+ state. For C-like styles, if the sequence has
+ unprintable characters, escape the whole sequence, since
+ we can't easily escape single characters within it. */
+ {
+ /* Length of multibyte sequence found so far. */
+ size_t m;
+
+ bool printable;
+
+ if (unibyte_locale)
+ {
+ m = 1;
+ printable = isprint (c) != 0;
+ }
+ else
+ {
+ mbstate_t mbstate;
+ memset (&mbstate, 0, sizeof mbstate);
+
+ m = 0;
+ printable = true;
+ if (argsize == SIZE_MAX)
+ argsize = strlen (arg);
+
+ do
+ {
+ wchar_t w;
+ size_t bytes = mbrtowc (&w, &arg[i + m],
+ argsize - (i + m), &mbstate);
+ if (bytes == 0)
+ break;
+ else if (bytes == (size_t) -1)
+ {
+ printable = false;
+ break;
+ }
+ else if (bytes == (size_t) -2)
+ {
+ printable = false;
+ while (i + m < argsize && arg[i + m])
+ m++;
+ break;
+ }
+ else
+ {
+ /* Work around a bug with older shells that "see" a '\'
+ that is really the 2nd byte of a multibyte character.
+ In practice the problem is limited to ASCII
+ chars >= '@' that are shell special chars. */
+ if ('[' == 0x5b && elide_outer_quotes
+ && quoting_style == shell_always_quoting_style)
+ {
+ size_t j;
+ for (j = 1; j < bytes; j++)
+ switch (arg[i + m + j])
+ {
+ case '[': case '\\': case '^':
+ case '`': case '|':
+ goto force_outer_quoting_style;
+
+ default:
+ break;
+ }
+ }
+
+ if (! iswprint (w))
+ printable = false;
+ m += bytes;
+ }
+ }
+ while (! mbsinit (&mbstate));
+ }
+
+ if (1 < m || (backslash_escapes && ! printable))
+ {
+ /* Output a multibyte sequence, or an escaped
+ unprintable unibyte character. */
+ size_t ilim = i + m;
+
+ for (;;)
+ {
+ if (backslash_escapes && ! printable)
+ {
+ START_ESC ();
+ STORE ('0' + (c >> 6));
+ STORE ('0' + ((c >> 3) & 7));
+ c = '0' + (c & 7);
+ }
+ else if (is_right_quote)
+ {
+ STORE ('\\');
+ is_right_quote = false;
+ }
+ if (ilim <= i + 1)
+ break;
+ END_ESC ();
+ STORE (c);
+ c = arg[++i];
+ }
+
+ goto store_c;
+ }
+ }
+ }
+
+ if (! (((backslash_escapes && quoting_style != shell_always_quoting_style)
+ || elide_outer_quotes)
+ && quote_these_too
+ && quote_these_too[c / INT_BITS] >> (c % INT_BITS) & 1)
+ && !is_right_quote)
+ goto store_c;
store_escape:
- STORE ('\\');
+ START_ESC ();
store_c:
+ END_ESC ();
STORE (c);
}
- if (i == 0 && quoting_style == shell_quoting_style)
- goto use_shell_always_quoting_style;
+ if (len == 0 && quoting_style == shell_always_quoting_style
+ && elide_outer_quotes)
+ goto force_outer_quoting_style;
- if (quote_string)
+ if (quote_string && !elide_outer_quotes)
for (; *quote_string; quote_string++)
STORE (*quote_string);
@@ -503,9 +703,15 @@ quotearg_buffer_restyled (char *buffer, size_t buffersize,
buffer[len] = '\0';
return len;
- use_shell_always_quoting_style:
+ force_outer_quoting_style:
+ /* Don't reuse quote_these_too, since the addition of outer quotes
+ sufficiently quotes the specified characters. */
+ if (quoting_style == shell_always_quoting_style && backslash_escapes)
+ quoting_style = shell_escape_always_quoting_style;
return quotearg_buffer_restyled (buffer, buffersize, arg, argsize,
- shell_always_quoting_style, o);
+ quoting_style,
+ flags & ~QA_ELIDE_OUTER_QUOTES, NULL,
+ left_quote, right_quote);
}
/* Place into buffer BUFFER (of size BUFFERSIZE) a quoted version of
@@ -519,28 +725,51 @@ quotearg_buffer_restyled (char *buffer, size_t buffersize,
ARGSIZE. */
size_t
quotearg_buffer (char *buffer, size_t buffersize,
- char const *arg, size_t argsize,
- struct quoting_options const *o)
+ char const *arg, size_t argsize,
+ struct quoting_options const *o)
{
struct quoting_options const *p = o ? o : &default_quoting_options;
int e = errno;
size_t r = quotearg_buffer_restyled (buffer, buffersize, arg, argsize,
- p->style, p);
+ p->style, p->flags, p->quote_these_too,
+ p->left_quote, p->right_quote);
errno = e;
return r;
}
-/* Like quotearg_buffer (..., ARG, ARGSIZE, O), except return newly
- allocated storage containing the quoted string. */
+/* Equivalent to quotearg_alloc (ARG, ARGSIZE, NULL, O). */
char *
quotearg_alloc (char const *arg, size_t argsize,
- struct quoting_options const *o)
+ struct quoting_options const *o)
+{
+ return quotearg_alloc_mem (arg, argsize, NULL, o);
+}
+
+/* Like quotearg_buffer (..., ARG, ARGSIZE, O), except return newly
+ allocated storage containing the quoted string, and store the
+ resulting size into *SIZE, if non-NULL. The result can contain
+ embedded null bytes only if ARGSIZE is not SIZE_MAX, SIZE is not
+ NULL, and set_quoting_flags has not set the null byte elision
+ flag. */
+char *
+quotearg_alloc_mem (char const *arg, size_t argsize, size_t *size,
+ struct quoting_options const *o)
{
+ struct quoting_options const *p = o ? o : &default_quoting_options;
int e = errno;
- size_t bufsize = quotearg_buffer (0, 0, arg, argsize, o) + 1;
+ /* Elide embedded null bytes if we can't return a size. */
+ int flags = p->flags | (size ? 0 : QA_ELIDE_NULL_BYTES);
+ size_t bufsize = quotearg_buffer_restyled (0, 0, arg, argsize, p->style,
+ flags, p->quote_these_too,
+ p->left_quote,
+ p->right_quote) + 1;
char *buf = xcharalloc (bufsize);
- quotearg_buffer (buf, bufsize, arg, argsize, o);
+ quotearg_buffer_restyled (buf, bufsize, arg, argsize, p->style, flags,
+ p->quote_these_too,
+ p->left_quote, p->right_quote);
errno = e;
+ if (size)
+ *size = bufsize - 1;
return buf;
}
@@ -589,7 +818,7 @@ quotearg_free (void)
to allow for future extensions (using negative values). */
static char *
quotearg_n_options (int n, char const *arg, size_t argsize,
- struct quoting_options const *options)
+ struct quoting_options const *options)
{
int e = errno;
@@ -601,20 +830,20 @@ quotearg_n_options (int n, char const *arg, size_t argsize,
if (nslots <= n0)
{
- /* FIXME: technically, the type of n1 should be `unsigned int',
- but that evokes an unsuppressible warning from gcc-4.0.1 and
- older. If gcc ever provides an option to suppress that warning,
- revert to the original type, so that the test in xalloc_oversized
- is once again performed only at compile time. */
+ /* FIXME: technically, the type of n1 should be 'unsigned int',
+ but that evokes an unsuppressible warning from gcc-4.0.1 and
+ older. If gcc ever provides an option to suppress that warning,
+ revert to the original type, so that the test in xalloc_oversized
+ is once again performed only at compile time. */
size_t n1 = n0 + 1;
bool preallocated = (sv == &slotvec0);
if (xalloc_oversized (n1, sizeof *sv))
- xalloc_die ();
+ xalloc_die ();
slotvec = sv = xrealloc (preallocated ? NULL : sv, n1 * sizeof *sv);
if (preallocated)
- *sv = slotvec0;
+ *sv = slotvec0;
memset (sv + nslots, 0, (n1 - nslots) * sizeof *sv);
nslots = n1;
}
@@ -622,15 +851,24 @@ quotearg_n_options (int n, char const *arg, size_t argsize,
{
size_t size = sv[n].size;
char *val = sv[n].val;
- size_t qsize = quotearg_buffer (val, size, arg, argsize, options);
+ /* Elide embedded null bytes since we don't return a size. */
+ int flags = options->flags | QA_ELIDE_NULL_BYTES;
+ size_t qsize = quotearg_buffer_restyled (val, size, arg, argsize,
+ options->style, flags,
+ options->quote_these_too,
+ options->left_quote,
+ options->right_quote);
if (size <= qsize)
{
- sv[n].size = size = qsize + 1;
- if (val != slot0)
- free (val);
- sv[n].val = val = xcharalloc (size);
- quotearg_buffer (val, size, arg, argsize, options);
+ sv[n].size = size = qsize + 1;
+ if (val != slot0)
+ free (val);
+ sv[n].val = val = xcharalloc (size);
+ quotearg_buffer_restyled (val, size, arg, argsize, options->style,
+ flags, options->quote_these_too,
+ options->left_quote,
+ options->right_quote);
}
errno = e;
@@ -645,19 +883,21 @@ quotearg_n (int n, char const *arg)
}
char *
+quotearg_n_mem (int n, char const *arg, size_t argsize)
+{
+ return quotearg_n_options (n, arg, argsize, &default_quoting_options);
+}
+
+char *
quotearg (char const *arg)
{
return quotearg_n (0, arg);
}
-/* Return quoting options for STYLE, with no extra quoting. */
-static struct quoting_options
-quoting_options_from_style (enum quoting_style style)
+char *
+quotearg_mem (char const *arg, size_t argsize)
{
- struct quoting_options o;
- o.style = style;
- memset (o.quote_these_too, 0, sizeof o.quote_these_too);
- return o;
+ return quotearg_n_mem (0, arg, argsize);
}
char *
@@ -669,7 +909,7 @@ quotearg_n_style (int n, enum quoting_style s, char const *arg)
char *
quotearg_n_style_mem (int n, enum quoting_style s,
- char const *arg, size_t argsize)
+ char const *arg, size_t argsize)
{
struct quoting_options const o = quoting_options_from_style (s);
return quotearg_n_options (n, arg, argsize, &o);
@@ -682,12 +922,24 @@ quotearg_style (enum quoting_style s, char const *arg)
}
char *
-quotearg_char (char const *arg, char ch)
+quotearg_style_mem (enum quoting_style s, char const *arg, size_t argsize)
+{
+ return quotearg_n_style_mem (0, s, arg, argsize);
+}
+
+char *
+quotearg_char_mem (char const *arg, size_t argsize, char ch)
{
struct quoting_options options;
options = default_quoting_options;
set_char_quoting (&options, ch, 1);
- return quotearg_n_options (0, arg, SIZE_MAX, &options);
+ return quotearg_n_options (0, arg, argsize, &options);
+}
+
+char *
+quotearg_char (char const *arg, char ch)
+{
+ return quotearg_char_mem (arg, SIZE_MAX, ch);
}
char *
@@ -695,3 +947,85 @@ quotearg_colon (char const *arg)
{
return quotearg_char (arg, ':');
}
+
+char *
+quotearg_colon_mem (char const *arg, size_t argsize)
+{
+ return quotearg_char_mem (arg, argsize, ':');
+}
+
+char *
+quotearg_n_style_colon (int n, enum quoting_style s, char const *arg)
+{
+ struct quoting_options options;
+ options = quoting_options_from_style (s);
+ set_char_quoting (&options, ':', 1);
+ return quotearg_n_options (n, arg, SIZE_MAX, &options);
+}
+
+char *
+quotearg_n_custom (int n, char const *left_quote,
+ char const *right_quote, char const *arg)
+{
+ return quotearg_n_custom_mem (n, left_quote, right_quote, arg,
+ SIZE_MAX);
+}
+
+char *
+quotearg_n_custom_mem (int n, char const *left_quote,
+ char const *right_quote,
+ char const *arg, size_t argsize)
+{
+ struct quoting_options o = default_quoting_options;
+ set_custom_quoting (&o, left_quote, right_quote);
+ return quotearg_n_options (n, arg, argsize, &o);
+}
+
+char *
+quotearg_custom (char const *left_quote, char const *right_quote,
+ char const *arg)
+{
+ return quotearg_n_custom (0, left_quote, right_quote, arg);
+}
+
+char *
+quotearg_custom_mem (char const *left_quote, char const *right_quote,
+ char const *arg, size_t argsize)
+{
+ return quotearg_n_custom_mem (0, left_quote, right_quote, arg,
+ argsize);
+}
+
+
+/* The quoting option used by the functions of quote.h. */
+struct quoting_options quote_quoting_options =
+ {
+ locale_quoting_style,
+ 0,
+ { 0 },
+ NULL, NULL
+ };
+
+char const *
+quote_n_mem (int n, char const *arg, size_t argsize)
+{
+ return quotearg_n_options (n, arg, argsize, &quote_quoting_options);
+}
+
+char const *
+quote_mem (char const *arg, size_t argsize)
+{
+ return quote_n_mem (0, arg, argsize);
+}
+
+char const *
+quote_n (int n, char const *arg)
+{
+ return quote_n_mem (n, arg, SIZE_MAX);
+}
+
+char const *
+quote (char const *arg)
+{
+ return quote_n (0, arg);
+}
diff --git a/lib/quotearg.h b/lib/quotearg.h
index 4887df3..bc29052 100644
--- a/lib/quotearg.h
+++ b/lib/quotearg.h
@@ -1,12 +1,12 @@
/* quotearg.h - quote arguments for output
- Copyright (C) 1998, 1999, 2000, 2001, 2002, 2004, 2006 Free
- Software Foundation, Inc.
+ Copyright (C) 1998-2002, 2004, 2006, 2008-2016 Free Software Foundation,
+ Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert <eggert@twinsun.com> */
@@ -24,34 +23,239 @@
# include <stddef.h>
-/* Basic quoting styles. */
+/* Basic quoting styles. For each style, an example is given on the
+ input strings "simple", "\0 \t\n'\"\033?""?/\\", and "a:b", using
+ quotearg_buffer, quotearg_mem, and quotearg_colon_mem with that
+ style and the default flags and quoted characters. Note that the
+ examples are shown here as valid C strings rather than what
+ displays on a terminal (with "??/" as a trigraph for "\\"). */
enum quoting_style
{
- /* Output names as-is (ls --quoting-style=literal). */
+ /* Output names as-is (ls --quoting-style=literal). Can result in
+ embedded null bytes if QA_ELIDE_NULL_BYTES is not in
+ effect.
+
+ quotearg_buffer:
+ "simple", "\0 \t\n'\"\033??/\\", "a:b"
+ quotearg:
+ "simple", " \t\n'\"\033??/\\", "a:b"
+ quotearg_colon:
+ "simple", " \t\n'\"\033??/\\", "a:b"
+ */
literal_quoting_style,
/* Quote names for the shell if they contain shell metacharacters
- or would cause ambiguous output (ls --quoting-style=shell). */
+ or would cause ambiguous output (ls --quoting-style=shell).
+ Can result in embedded null bytes if QA_ELIDE_NULL_BYTES is not
+ in effect.
+
+ quotearg_buffer:
+ "simple", "'\0 \t\n'\\''\"\033??/\\'", "a:b"
+ quotearg:
+ "simple", "' \t\n'\\''\"\033??/\\'", "a:b"
+ quotearg_colon:
+ "simple", "' \t\n'\\''\"\033??/\\'", "'a:b'"
+ */
shell_quoting_style,
/* Quote names for the shell, even if they would normally not
- require quoting (ls --quoting-style=shell-always). */
+ require quoting (ls --quoting-style=shell-always). Can result
+ in embedded null bytes if QA_ELIDE_NULL_BYTES is not in effect.
+ Behaves like shell_quoting_style if QA_ELIDE_OUTER_QUOTES is in
+ effect.
+
+ quotearg_buffer:
+ "'simple'", "'\0 \t\n'\\''\"\033??/\\'", "'a:b'"
+ quotearg:
+ "'simple'", "' \t\n'\\''\"\033??/\\'", "'a:b'"
+ quotearg_colon:
+ "'simple'", "' \t\n'\\''\"\033??/\\'", "'a:b'"
+ */
shell_always_quoting_style,
- /* Quote names as for a C language string (ls --quoting-style=c). */
+ /* Quote names for the shell if they contain shell metacharacters
+ or other problematic characters (ls --quoting-style=shell-escape).
+ Non printable characters are quoted using the $'...' syntax,
+ which originated in ksh93 and is widely supported by most shells,
+ and proposed for inclusion in POSIX.
+
+ quotearg_buffer:
+ "simple", "''$'\\0'' '$'\\t\\n'\\''\"'$'\\033''??/\\'", "a:b"
+ quotearg:
+ "simple", "''$'\\0'' '$'\\t\\n'\\''\"'$'\\033''??/\\'", "a:b"
+ quotearg_colon:
+ "simple", "''$'\\0'' '$'\\t\\n'\\''\"'$'\\033''??/\\'", "'a:b'"
+ */
+ shell_escape_quoting_style,
+
+ /* Quote names for the shell even if they would normally not
+ require quoting (ls --quoting-style=shell-escape).
+ Non printable characters are quoted using the $'...' syntax,
+ which originated in ksh93 and is widely supported by most shells,
+ and proposed for inclusion in POSIX. Behaves like
+ shell_escape_quoting_style if QA_ELIDE_OUTER_QUOTES is in effect.
+
+ quotearg_buffer:
+ "simple", "''$'\\0'' '$'\\t\\n'\\''\"'$'\\033''??/\'", "a:b"
+ quotearg:
+ "simple", "''$'\\0'' '$'\\t\\n'\\''\"'$'\\033''??/\'", "a:b"
+ quotearg_colon:
+ "simple", "''$'\\0'' '$'\\t\\n'\\''\"'$'\\033''??/\'", "'a:b'"
+ */
+ shell_escape_always_quoting_style,
+
+ /* Quote names as for a C language string (ls --quoting-style=c).
+ Behaves like c_maybe_quoting_style if QA_ELIDE_OUTER_QUOTES is
+ in effect. Split into consecutive strings if
+ QA_SPLIT_TRIGRAPHS.
+
+ quotearg_buffer:
+ "\"simple\"", "\"\\0 \\t\\n'\\\"\\033??/\\\\\"", "\"a:b\""
+ quotearg:
+ "\"simple\"", "\"\\0 \\t\\n'\\\"\\033??/\\\\\"", "\"a:b\""
+ quotearg_colon:
+ "\"simple\"", "\"\\0 \\t\\n'\\\"\\033??/\\\\\"", "\"a\\:b\""
+ */
c_quoting_style,
/* Like c_quoting_style except omit the surrounding double-quote
- characters (ls --quoting-style=escape). */
+ characters if no quoted characters are encountered.
+
+ quotearg_buffer:
+ "simple", "\"\\0 \\t\\n'\\\"\\033??/\\\\\"", "a:b"
+ quotearg:
+ "simple", "\"\\0 \\t\\n'\\\"\\033??/\\\\\"", "a:b"
+ quotearg_colon:
+ "simple", "\"\\0 \\t\\n'\\\"\\033??/\\\\\"", "\"a:b\""
+ */
+ c_maybe_quoting_style,
+
+ /* Like c_quoting_style except always omit the surrounding
+ double-quote characters and ignore QA_SPLIT_TRIGRAPHS
+ (ls --quoting-style=escape).
+
+ quotearg_buffer:
+ "simple", "\\0 \\t\\n'\"\\033??/\\\\", "a:b"
+ quotearg:
+ "simple", "\\0 \\t\\n'\"\\033??/\\\\", "a:b"
+ quotearg_colon:
+ "simple", "\\0 \\t\\n'\"\\033??/\\\\", "a\\:b"
+ */
escape_quoting_style,
- /* Like clocale_quoting_style, but quote `like this' instead of
- "like this" in the default C locale (ls --quoting-style=locale). */
+ /* Like clocale_quoting_style, but use single quotes in the
+ default C locale or if the program does not use gettext
+ (ls --quoting-style=locale). For UTF-8 locales, quote
+ characters will use Unicode.
+
+ LC_MESSAGES=C
+ quotearg_buffer:
+ "`simple'", "`\\0 \\t\\n\\'\"\\033??/\\\\'", "`a:b'"
+ quotearg:
+ "`simple'", "`\\0 \\t\\n\\'\"\\033??/\\\\'", "`a:b'"
+ quotearg_colon:
+ "`simple'", "`\\0 \\t\\n\\'\"\\033??/\\\\'", "`a\\:b'"
+
+ LC_MESSAGES=pt_PT.utf8
+ quotearg_buffer:
+ "\302\253simple\302\273",
+ "\302\253\\0 \\t\\n'\"\\033??/\\\\\302\253", "\302\253a:b\302\273"
+ quotearg:
+ "\302\253simple\302\273",
+ "\302\253\\0 \\t\\n'\"\\033??/\\\\\302\253", "\302\253a:b\302\273"
+ quotearg_colon:
+ "\302\253simple\302\273",
+ "\302\253\\0 \\t\\n'\"\\033??/\\\\\302\253", "\302\253a\\:b\302\273"
+ */
locale_quoting_style,
/* Like c_quoting_style except use quotation marks appropriate for
- the locale (ls --quoting-style=clocale). */
- clocale_quoting_style
+ the locale and ignore QA_SPLIT_TRIGRAPHS
+ (ls --quoting-style=clocale).
+
+ LC_MESSAGES=C
+ quotearg_buffer:
+ "\"simple\"", "\"\\0 \\t\\n'\\\"\\033??/\\\\\"", "\"a:b\""
+ quotearg:
+ "\"simple\"", "\"\\0 \\t\\n'\\\"\\033??/\\\\\"", "\"a:b\""
+ quotearg_colon:
+ "\"simple\"", "\"\\0 \\t\\n'\\\"\\033??/\\\\\"", "\"a\\:b\""
+
+ LC_MESSAGES=pt_PT.utf8
+ quotearg_buffer:
+ "\302\253simple\302\273",
+ "\302\253\\0 \\t\\n'\"\\033??/\\\\\302\253", "\302\253a:b\302\273"
+ quotearg:
+ "\302\253simple\302\273",
+ "\302\253\\0 \\t\\n'\"\\033??/\\\\\302\253", "\302\253a:b\302\273"
+ quotearg_colon:
+ "\302\253simple\302\273",
+ "\302\253\\0 \\t\\n'\"\\033??/\\\\\302\253", "\302\253a\\:b\302\273"
+ */
+ clocale_quoting_style,
+
+ /* Like clocale_quoting_style except use the custom quotation marks
+ set by set_custom_quoting. If custom quotation marks are not
+ set, the behavior is undefined.
+
+ left_quote = right_quote = "'"
+ quotearg_buffer:
+ "'simple'", "'\\0 \\t\\n\\'\"\\033??/\\\\'", "'a:b'"
+ quotearg:
+ "'simple'", "'\\0 \\t\\n\\'\"\\033??/\\\\'", "'a:b'"
+ quotearg_colon:
+ "'simple'", "'\\0 \\t\\n\\'\"\\033??/\\\\'", "'a\\:b'"
+
+ left_quote = "(" and right_quote = ")"
+ quotearg_buffer:
+ "(simple)", "(\\0 \\t\\n'\"\\033??/\\\\)", "(a:b)"
+ quotearg:
+ "(simple)", "(\\0 \\t\\n'\"\\033??/\\\\)", "(a:b)"
+ quotearg_colon:
+ "(simple)", "(\\0 \\t\\n'\"\\033??/\\\\)", "(a\\:b)"
+
+ left_quote = ":" and right_quote = " "
+ quotearg_buffer:
+ ":simple ", ":\\0\\ \\t\\n'\"\\033??/\\\\ ", ":a:b "
+ quotearg:
+ ":simple ", ":\\0\\ \\t\\n'\"\\033??/\\\\ ", ":a:b "
+ quotearg_colon:
+ ":simple ", ":\\0\\ \\t\\n'\"\\033??/\\\\ ", ":a\\:b "
+
+ left_quote = "\"'" and right_quote = "'\""
+ Notice that this is treated as a single level of quotes or two
+ levels where the outer quote need not be escaped within the inner
+ quotes. For two levels where the outer quote must be escaped
+ within the inner quotes, you must use separate quotearg
+ invocations.
+ quotearg_buffer:
+ "\"'simple'\"", "\"'\\0 \\t\\n\\'\"\\033??/\\\\'\"", "\"'a:b'\""
+ quotearg:
+ "\"'simple'\"", "\"'\\0 \\t\\n\\'\"\\033??/\\\\'\"", "\"'a:b'\""
+ quotearg_colon:
+ "\"'simple'\"", "\"'\\0 \\t\\n\\'\"\\033??/\\\\'\"", "\"'a\\:b'\""
+ */
+ custom_quoting_style
+ };
+
+/* Flags for use in set_quoting_flags. */
+enum quoting_flags
+ {
+ /* Always elide null bytes from styles that do not quote them,
+ even when the length of the result is available to the
+ caller. */
+ QA_ELIDE_NULL_BYTES = 0x01,
+
+ /* Omit the surrounding quote characters if no escaped characters
+ are encountered. Note that if no other character needs
+ escaping, then neither does the escape character. */
+ QA_ELIDE_OUTER_QUOTES = 0x02,
+
+ /* In the c_quoting_style and c_maybe_quoting_style, split ANSI
+ trigraph sequences into concatenated strings (for example,
+ "?""?/" rather than "??/", which could be confused with
+ "\\"). */
+ QA_SPLIT_TRIGRAPHS = 0x04
};
/* For now, --quoting-style=literal is the default, but this may change. */
@@ -74,7 +278,7 @@ struct quoting_options;
struct quoting_options *clone_quoting_options (struct quoting_options *o);
/* Get the value of O's quoting style. If O is null, use the default. */
-enum quoting_style get_quoting_style (struct quoting_options *o);
+enum quoting_style get_quoting_style (struct quoting_options const *o);
/* In O (or in the default if O is null),
set the value of the quoting style to S. */
@@ -84,9 +288,30 @@ void set_quoting_style (struct quoting_options *o, enum quoting_style s);
set the value of the quoting options for character C to I.
Return the old value. Currently, the only values defined for I are
0 (the default) and 1 (which means to quote the character even if
- it would not otherwise be quoted). */
+ it would not otherwise be quoted). C must never be a digit or a
+ letter that has special meaning after a backslash (for example, "\t"
+ for tab). */
int set_char_quoting (struct quoting_options *o, char c, int i);
+/* In O (or in the default if O is null),
+ set the value of the quoting options flag to I, which can be a
+ bitwise combination of enum quoting_flags, or 0 for default
+ behavior. Return the old value. */
+int set_quoting_flags (struct quoting_options *o, int i);
+
+/* In O (or in the default if O is null),
+ set the value of the quoting style to custom_quoting_style,
+ set the left quote to LEFT_QUOTE, and set the right quote to
+ RIGHT_QUOTE. Each of LEFT_QUOTE and RIGHT_QUOTE must be
+ null-terminated and can be the empty string. Because backslashes are
+ used for escaping, it does not make sense for RIGHT_QUOTE to contain
+ a backslash. RIGHT_QUOTE must not begin with a digit or a letter
+ that has special meaning after a backslash (for example, "\t" for
+ tab). */
+void set_custom_quoting (struct quoting_options *o,
+ char const *left_quote,
+ char const *right_quote);
+
/* Place into buffer BUFFER (of size BUFFERSIZE) a quoted version of
argument ARG (of size ARGSIZE), using O to control quoting.
If O is null, use the default.
@@ -94,26 +319,49 @@ int set_char_quoting (struct quoting_options *o, char c, int i);
size of the output, not counting the terminating null.
If BUFFERSIZE is too small to store the output string, return the
value that would have been returned had BUFFERSIZE been large enough.
- If ARGSIZE is -1, use the string length of the argument for ARGSIZE. */
+ If ARGSIZE is -1, use the string length of the argument for ARGSIZE.
+ On output, BUFFER might contain embedded null bytes if ARGSIZE was
+ not -1, the style of O does not use backslash escapes, and the
+ flags of O do not request elision of null bytes.*/
size_t quotearg_buffer (char *buffer, size_t buffersize,
- char const *arg, size_t argsize,
- struct quoting_options const *o);
+ char const *arg, size_t argsize,
+ struct quoting_options const *o);
/* Like quotearg_buffer, except return the result in a newly allocated
- buffer. It is the caller's responsibility to free the result. */
+ buffer. It is the caller's responsibility to free the result. The
+ result will not contain embedded null bytes. */
char *quotearg_alloc (char const *arg, size_t argsize,
- struct quoting_options const *o);
+ struct quoting_options const *o);
+
+/* Like quotearg_alloc, except that the length of the result,
+ excluding the terminating null byte, is stored into SIZE if it is
+ non-NULL. The result might contain embedded null bytes if ARGSIZE
+ was not -1, SIZE was not NULL, the style of O does not use
+ backslash escapes, and the flags of O do not request elision of
+ null bytes.*/
+char *quotearg_alloc_mem (char const *arg, size_t argsize,
+ size_t *size, struct quoting_options const *o);
/* Use storage slot N to return a quoted version of the string ARG.
Use the default quoting options.
The returned value points to static storage that can be
reused by the next call to this function with the same value of N.
- N must be nonnegative. */
+ N must be nonnegative. The output of all functions in the
+ quotearg_n family are guaranteed to not contain embedded null
+ bytes.*/
char *quotearg_n (int n, char const *arg);
/* Equivalent to quotearg_n (0, ARG). */
char *quotearg (char const *arg);
+/* Use storage slot N to return a quoted version of the argument ARG
+ of size ARGSIZE. This is like quotearg_n (N, ARG), except it can
+ quote null bytes. */
+char *quotearg_n_mem (int n, char const *arg, size_t argsize);
+
+/* Equivalent to quotearg_n_mem (0, ARG, ARGSIZE). */
+char *quotearg_mem (char const *arg, size_t argsize);
+
/* Use style S and storage slot N to return a quoted version of the string ARG.
This is like quotearg_n (N, ARG), except that it uses S with no other
options to specify the quoting method. */
@@ -123,17 +371,54 @@ char *quotearg_n_style (int n, enum quoting_style s, char const *arg);
argument ARG of size ARGSIZE. This is like quotearg_n_style
(N, S, ARG), except it can quote null bytes. */
char *quotearg_n_style_mem (int n, enum quoting_style s,
- char const *arg, size_t argsize);
+ char const *arg, size_t argsize);
/* Equivalent to quotearg_n_style (0, S, ARG). */
char *quotearg_style (enum quoting_style s, char const *arg);
-/* Like quotearg (ARG), except also quote any instances of CH. */
+/* Equivalent to quotearg_n_style_mem (0, S, ARG, ARGSIZE). */
+char *quotearg_style_mem (enum quoting_style s,
+ char const *arg, size_t argsize);
+
+/* Like quotearg (ARG), except also quote any instances of CH.
+ See set_char_quoting for a description of acceptable CH values. */
char *quotearg_char (char const *arg, char ch);
+/* Like quotearg_char (ARG, CH), except it can quote null bytes. */
+char *quotearg_char_mem (char const *arg, size_t argsize, char ch);
+
/* Equivalent to quotearg_char (ARG, ':'). */
char *quotearg_colon (char const *arg);
+/* Like quotearg_colon (ARG), except it can quote null bytes. */
+char *quotearg_colon_mem (char const *arg, size_t argsize);
+
+/* Like quotearg_n_style, except with ':' quoting enabled. */
+char *quotearg_n_style_colon (int n, enum quoting_style s, char const *arg);
+
+/* Like quotearg_n_style (N, S, ARG) but with S as custom_quoting_style
+ with left quote as LEFT_QUOTE and right quote as RIGHT_QUOTE. See
+ set_custom_quoting for a description of acceptable LEFT_QUOTE and
+ RIGHT_QUOTE values. */
+char *quotearg_n_custom (int n, char const *left_quote,
+ char const *right_quote, char const *arg);
+
+/* Like quotearg_n_custom (N, LEFT_QUOTE, RIGHT_QUOTE, ARG) except it
+ can quote null bytes. */
+char *quotearg_n_custom_mem (int n, char const *left_quote,
+ char const *right_quote,
+ char const *arg, size_t argsize);
+
+/* Equivalent to quotearg_n_custom (0, LEFT_QUOTE, RIGHT_QUOTE, ARG). */
+char *quotearg_custom (char const *left_quote, char const *right_quote,
+ char const *arg);
+
+/* Equivalent to quotearg_n_custom_mem (0, LEFT_QUOTE, RIGHT_QUOTE, ARG,
+ ARGSIZE). */
+char *quotearg_custom_mem (char const *left_quote,
+ char const *right_quote,
+ char const *arg, size_t argsize);
+
/* Free any dynamically allocated memory. */
void quotearg_free (void);
diff --git a/lib/raise.c b/lib/raise.c
index 98a97da..bf24c3e 100644
--- a/lib/raise.c
+++ b/lib/raise.c
@@ -1,11 +1,11 @@
/* Provide a non-threads replacement for the POSIX raise function.
- Copyright (C) 2002, 2003, 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2002-2003, 2005-2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,19 +13,67 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
-/* written by Jim Meyering */
+/* written by Jim Meyering and Bruno Haible */
#include <config.h>
-#include <sys/types.h>
+/* Specification. */
#include <signal.h>
-#include <unistd.h>
+
+#if HAVE_RAISE
+/* Native Windows platform. */
+
+# include <errno.h>
+
+# include "msvc-inval.h"
+
+# undef raise
+
+# if HAVE_MSVC_INVALID_PARAMETER_HANDLER
+static int
+raise_nothrow (int sig)
+{
+ int result;
+
+ TRY_MSVC_INVAL
+ {
+ result = raise (sig);
+ }
+ CATCH_MSVC_INVAL
+ {
+ result = -1;
+ errno = EINVAL;
+ }
+ DONE_MSVC_INVAL;
+
+ return result;
+}
+# else
+# define raise_nothrow raise
+# endif
+
+#else
+/* An old Unix platform. */
+
+# include <unistd.h>
+
+# define rpl_raise raise
+
+#endif
int
-raise (int sig)
+rpl_raise (int sig)
{
+#if GNULIB_defined_signal_blocking && GNULIB_defined_SIGPIPE
+ if (sig == SIGPIPE)
+ return _gl_raise_SIGPIPE ();
+#endif
+
+#if HAVE_RAISE
+ return raise_nothrow (sig);
+#else
return kill (getpid (), sig);
+#endif
}
diff --git a/lib/rand-isaac.c b/lib/rand-isaac.c
index cfdc643..5ad9cae 100644
--- a/lib/rand-isaac.c
+++ b/lib/rand-isaac.c
@@ -1,12 +1,12 @@
-/* Bob Jenkins's cryptographic random number generator, ISAAC.
+/* Bob Jenkins's cryptographic random number generators, ISAAC and ISAAC64.
- Copyright (C) 1999-2006 Free Software Foundation, Inc.
+ Copyright (C) 1999-2016 Free Software Foundation, Inc.
Copyright (C) 1997, 1998, 1999 Colin Plumb.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,10 +14,9 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
- Written by Colin Plumb. */
+ Written by Colin Plumb and Paul Eggert. */
/*
* --------------------------------------------------------------------
@@ -35,60 +34,112 @@
#include "rand-isaac.h"
+#include <limits.h>
#include <string.h>
-#include <unistd.h>
-#include "gethrxtime.h"
+/* If the platform supports unaligned access,
+ then don't have -fsanitize=undefined warn about it. */
+#undef ATTRIBUTE_NO_WARN_SANITIZE_UNDEFINED
+#if !_STRING_ARCH_unaligned \
+ || __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 9)
+# define ATTRIBUTE_NO_WARN_SANITIZE_UNDEFINED /* empty */
+#else
+# define ATTRIBUTE_NO_WARN_SANITIZE_UNDEFINED \
+ __attribute__ ((__no_sanitize_undefined__))
+#endif
+/* The minimum of two sizes A and B. */
+static inline size_t
+min (size_t a, size_t b)
+{
+ return (a < b ? a : b);
+}
-/* This index operation is more efficient on many processors */
-#define ind(mm, x) \
- (* (uint32_t *) ((char *) (mm) \
- + ((x) & (ISAAC_WORDS - 1) * sizeof (uint32_t))))
+/* A if 32-bit ISAAC, B if 64-bit. This is a macro, not an inline
+ function, to prevent undefined behavior if the unused argument
+ shifts by more than a word width. */
+#define IF32(a, b) (ISAAC_BITS == 32 ? (a) : (b))
-/*
- * The central step. This uses two temporaries, x and y. mm is the
- * whole state array, while m is a pointer to the current word. off is
- * the offset from m to the word ISAAC_WORDS/2 words away in the mm array,
- * i.e. +/- ISAAC_WORDS/2.
- */
-#define isaac_step(mix, a, b, mm, m, off, r) \
-( \
- a = ((a) ^ (mix)) + (m)[off], \
- x = *(m), \
- *(m) = y = ind (mm, x) + (a) + (b), \
- *(r) = b = ind (mm, (y) >> ISAAC_LOG) + x \
-)
+/* Discard bits outside the desired range. On typical machines, any
+ decent compiler should optimize this function call away to nothing.
+ But machines with pad bits in integers may need to do more work. */
+static inline isaac_word
+just (isaac_word a)
+{
+ isaac_word desired_bits = ((isaac_word) 1 << 1 << (ISAAC_BITS - 1)) - 1;
+ return a & desired_bits;
+}
-/* Use and update *S to generate random data to fill R. */
-void
-isaac_refill (struct isaac_state *s, uint32_t r[ISAAC_WORDS])
+/* The index operation. */
+static inline isaac_word
+ind (isaac_word const *m, isaac_word x)
{
- uint32_t a, b; /* Caches of a and b */
- uint32_t x, y; /* Temps needed by isaac_step macro */
- uint32_t *m = s->mm; /* Pointer into state array */
+ if (sizeof *m * CHAR_BIT == ISAAC_BITS)
+ {
+ /* The typical case, where words are exactly the right size.
+ Optimize this to a mask, an addition, and an indirect
+ load. */
+ void const *void_m = m;
+ char const *base_p = void_m;
+ void const *word_p = base_p + (x & ((ISAAC_WORDS - 1) * sizeof *m));
+ isaac_word const *p = word_p;
+ return *p;
+ }
+ else
+ {
+ /* Atypical machines need more work. */
+ return m[(x / (ISAAC_BITS / CHAR_BIT)) & (ISAAC_WORDS - 1)];
+ }
+}
- a = s->a;
- b = s->b + (++s->c);
+/* Use and update *S to generate random data to fill RESULT. */
+void ATTRIBUTE_NO_WARN_SANITIZE_UNDEFINED
+isaac_refill (struct isaac_state *s, isaac_word result[ISAAC_WORDS])
+{
+ /* Caches of S->a and S->b. */
+ isaac_word a = s->a;
+ isaac_word b = s->b + (++s->c);
+
+ /* Pointers into state array and into result. */
+ isaac_word *m = s->m;
+ isaac_word *r = result;
+
+ enum { HALF = ISAAC_WORDS / 2 };
+
+ /* The central step. S->m is the whole state array, while M is a
+ pointer to the current word. OFF is the offset from M to the
+ word ISAAC_WORDS/2 words away in the SM array, i.e., +/-
+ ISAAC_WORDS/2. A and B are state variables, and R the result.
+ This updates A, B, M[I], and R[I]. */
+ #define ISAAC_STEP(i, off, mix) \
+ { \
+ isaac_word x, y; \
+ a = (IF32 (a, 0) ^ (mix)) + m[off + (i)]; \
+ x = m[i]; \
+ m[i] = y = ind (s->m, x) + a + b; \
+ r[i] = b = just (ind (s->m, y >> ISAAC_WORDS_LOG) + x); \
+ }
do
{
- isaac_step (a << 13, a, b, s->mm, m, ISAAC_WORDS / 2, r);
- isaac_step (a >> 6, a, b, s->mm, m + 1, ISAAC_WORDS / 2, r + 1);
- isaac_step (a << 2, a, b, s->mm, m + 2, ISAAC_WORDS / 2, r + 2);
- isaac_step (a >> 16, a, b, s->mm, m + 3, ISAAC_WORDS / 2, r + 3);
+ ISAAC_STEP (0, HALF, IF32 ( a << 13, ~ (a ^ (a << 21))));
+ ISAAC_STEP (1, HALF, IF32 (just (a) >> 6, a ^ (just (a) >> 5)));
+ ISAAC_STEP (2, HALF, IF32 ( a << 2, a ^ ( a << 12)));
+ ISAAC_STEP (3, HALF, IF32 (just (a) >> 16, a ^ (just (a) >> 33)));
r += 4;
}
- while ((m += 4) < s->mm + ISAAC_WORDS / 2);
+ while ((m += 4) < s->m + HALF);
+
do
{
- isaac_step (a << 13, a, b, s->mm, m, -ISAAC_WORDS / 2, r);
- isaac_step (a >> 6, a, b, s->mm, m + 1, -ISAAC_WORDS / 2, r + 1);
- isaac_step (a << 2, a, b, s->mm, m + 2, -ISAAC_WORDS / 2, r + 2);
- isaac_step (a >> 16, a, b, s->mm, m + 3, -ISAAC_WORDS / 2, r + 3);
+ ISAAC_STEP (0, -HALF, IF32 ( a << 13, ~ (a ^ (a << 21))));
+ ISAAC_STEP (1, -HALF, IF32 (just (a) >> 6, a ^ (just (a) >> 5)));
+ ISAAC_STEP (2, -HALF, IF32 ( a << 2, a ^ ( a << 12)));
+ ISAAC_STEP (3, -HALF, IF32 (just (a) >> 16, a ^ (just (a) >> 33)));
r += 4;
}
- while ((m += 4) < s->mm + ISAAC_WORDS);
+ while ((m += 4) < s->m + ISAAC_WORDS);
+
s->a = a;
s->b = b;
}
@@ -97,205 +148,133 @@ isaac_refill (struct isaac_state *s, uint32_t r[ISAAC_WORDS])
* The basic seed-scrambling step for initialization, based on Bob
* Jenkins' 256-bit hash.
*/
-#define mix(a,b,c,d,e,f,g,h) \
- ( a ^= b << 11, d += a, \
- b += c, b ^= c >> 2, e += b, \
- c += d, c ^= d << 8, f += c, \
- d += e, d ^= e >> 16, g += d, \
- e += f, e ^= f << 10, h += e, \
- f += g, f ^= g >> 4, a += f, \
- g += h, g ^= h << 8, b += g, \
- h += a, h ^= a >> 9, c += h, \
- a += b )
-
-/* The basic ISAAC initialization pass. */
-static void
-isaac_mix (struct isaac_state *s, uint32_t const seed[/* ISAAC_WORDS */])
-{
- int i;
- uint32_t a = s->iv[0];
- uint32_t b = s->iv[1];
- uint32_t c = s->iv[2];
- uint32_t d = s->iv[3];
- uint32_t e = s->iv[4];
- uint32_t f = s->iv[5];
- uint32_t g = s->iv[6];
- uint32_t h = s->iv[7];
-
- for (i = 0; i < ISAAC_WORDS; i += 8)
- {
- a += seed[i];
- b += seed[i + 1];
- c += seed[i + 2];
- d += seed[i + 3];
- e += seed[i + 4];
- f += seed[i + 5];
- g += seed[i + 6];
- h += seed[i + 7];
-
- mix (a, b, c, d, e, f, g, h);
-
- s->mm[i] = a;
- s->mm[i + 1] = b;
- s->mm[i + 2] = c;
- s->mm[i + 3] = d;
- s->mm[i + 4] = e;
- s->mm[i + 5] = f;
- s->mm[i + 6] = g;
- s->mm[i + 7] = h;
+#if ISAAC_BITS == 32
+ #define mix(a, b, c, d, e, f, g, h) \
+ { \
+ a ^= b << 11; d += a; \
+ b += c; b ^= just (c) >> 2; e += b; \
+ c += d; c ^= d << 8; f += c; \
+ d += e; d ^= just (e) >> 16; g += d; \
+ e += f; e ^= f << 10; h += e; \
+ f += g; f ^= just (g) >> 4; a += f; \
+ g += h; g ^= h << 8; b += g; \
+ h += a; h ^= just (a) >> 9; c += h; \
+ a += b; \
+ }
+#else
+ #define mix(a, b, c, d, e, f, g, h) \
+ { \
+ a -= e; f ^= just (h) >> 9; h += a; \
+ b -= f; g ^= a << 9; a += b; \
+ c -= g; h ^= just (b) >> 23; b += c; \
+ d -= h; a ^= c << 15; c += d; \
+ e -= a; b ^= just (d) >> 14; d += e; \
+ f -= b; c ^= e << 20; e += f; \
+ g -= c; d ^= just (f) >> 17; f += g; \
+ h -= d; e ^= g << 14; g += h; \
}
+#endif
- s->iv[0] = a;
- s->iv[1] = b;
- s->iv[2] = c;
- s->iv[3] = d;
- s->iv[4] = e;
- s->iv[5] = f;
- s->iv[6] = g;
- s->iv[7] = h;
-}
+
+/* The basic ISAAC initialization pass. */
+#define ISAAC_MIX(s, a, b, c, d, e, f, g, h, seed) \
+ { \
+ int i; \
+ \
+ for (i = 0; i < ISAAC_WORDS; i += 8) \
+ { \
+ a += seed[i]; \
+ b += seed[i + 1]; \
+ c += seed[i + 2]; \
+ d += seed[i + 3]; \
+ e += seed[i + 4]; \
+ f += seed[i + 5]; \
+ g += seed[i + 6]; \
+ h += seed[i + 7]; \
+ mix (a, b, c, d, e, f, g, h); \
+ s->m[i] = a; \
+ s->m[i + 1] = b; \
+ s->m[i + 2] = c; \
+ s->m[i + 3] = d; \
+ s->m[i + 4] = e; \
+ s->m[i + 5] = f; \
+ s->m[i + 6] = g; \
+ s->m[i + 7] = h; \
+ } \
+ }
#if 0 /* Provided for reference only; not used in this code */
/*
* Initialize the ISAAC RNG with the given seed material.
* Its size MUST be a multiple of ISAAC_BYTES, and may be
- * stored in the s->mm array.
+ * stored in the s->m array.
*
* This is a generalization of the original ISAAC initialization code
* to support larger seed sizes. For seed sizes of 0 and ISAAC_BYTES,
* it is identical.
*/
static void
-isaac_init (struct isaac_state *s, uint32_t const *seed, size_t seedsize)
+isaac_init (struct isaac_state *s, isaac_word const *seed, size_t seedsize)
{
- static uint32_t const iv[8] =
- {
- 0x1367df5a, 0x95d90059, 0xc3163e4b, 0x0f421ad8,
- 0xd92a4a78, 0xa51a3c49, 0xc4efea1b, 0x30609119};
- int i;
+ isaac_word a, b, c, d, e, f, g, h;
-# if 0
- /* The initialization of iv is a precomputed form of: */
- for (i = 0; i < 7; i++)
- iv[i] = 0x9e3779b9; /* the golden ratio */
- for (i = 0; i < 4; ++i) /* scramble it */
- mix (iv[0], iv[1], iv[2], iv[3], iv[4], iv[5], iv[6], iv[7]);
-# endif
+ a = b = c = d = e = f = g = h = /* the golden ratio */
+ IF32 (UINT32_C (0x9e3779b9), UINT64_C (0x9e3779b97f4a7c13));
+ for (int i = 0; i < 4; i++) /* scramble it */
+ mix (a, b, c, d, e, f, g, h);
s->a = s->b = s->c = 0;
- for (i = 0; i < 8; i++)
- s->iv[i] = iv[i];
-
if (seedsize)
{
/* First pass (as in reference ISAAC code) */
- isaac_mix (s, seed);
+ ISAAC_MIX (s, a, b, c, d, e, f, g, h, seed);
/* Second and subsequent passes (extension to ISAAC) */
while (seedsize -= ISAAC_BYTES)
- {
- seed += ISAAC_WORDS;
- for (i = 0; i < ISAAC_WORDS; i++)
- s->mm[i] += seed[i];
- isaac_mix (s, s->mm);
- }
+ {
+ seed += ISAAC_WORDS;
+ for (i = 0; i < ISAAC_WORDS; i++)
+ s->m[i] += seed[i];
+ ISAAC_MIX (s, a, b, c, d, e, f, g, h, s->m);
+ }
}
else
{
/* The no seed case (as in reference ISAAC code) */
for (i = 0; i < ISAAC_WORDS; i++)
- s->mm[i] = 0;
+ s->m[i] = 0;
}
/* Final pass */
- isaac_mix (s, s->mm);
+ ISAAC_MIX (s, a, b, c, d, e, f, g, h, s->m);
}
#endif
-/* Initialize *S to a somewhat-random value. */
-static void
-isaac_seed_start (struct isaac_state *s)
+/* Initialize *S to a somewhat-random value, derived from a seed
+ stored in S->m. */
+void
+isaac_seed (struct isaac_state *s)
{
- static uint32_t const iv[8] =
- {
- 0x1367df5a, 0x95d90059, 0xc3163e4b, 0x0f421ad8,
- 0xd92a4a78, 0xa51a3c49, 0xc4efea1b, 0x30609119
- };
+ isaac_word a = IF32 (UINT32_C (0x1367df5a), UINT64_C (0x647c4677a2884b7c));
+ isaac_word b = IF32 (UINT32_C (0x95d90059), UINT64_C (0xb9f8b322c73ac862));
+ isaac_word c = IF32 (UINT32_C (0xc3163e4b), UINT64_C (0x8c0ea5053d4712a0));
+ isaac_word d = IF32 (UINT32_C (0x0f421ad8), UINT64_C (0xb29b2e824a595524));
+ isaac_word e = IF32 (UINT32_C (0xd92a4a78), UINT64_C (0x82f053db8355e0ce));
+ isaac_word f = IF32 (UINT32_C (0xa51a3c49), UINT64_C (0x48fe4a0fa5a09315));
+ isaac_word g = IF32 (UINT32_C (0xc4efea1b), UINT64_C (0xae985bf2cbfc89ed));
+ isaac_word h = IF32 (UINT32_C (0x30609119), UINT64_C (0x98f5704f6c44c0ab));
#if 0
- /* The initialization of iv is a precomputed form of: */
- int i;
- for (i = 0; i < 7; i++)
- iv[i] = 0x9e3779b9; /* the golden ratio */
- for (i = 0; i < 4; ++i) /* scramble it */
- mix (iv[0], iv[1], iv[2], iv[3], iv[4], iv[5], iv[6], iv[7]);
+ /* The initialization of a through h is a precomputed form of: */
+ a = b = c = d = e = f = g = h = /* the golden ratio */
+ IF32 (UINT32_C (0x9e3779b9), UINT64_C (0x9e3779b97f4a7c13));
+ for (int i = 0; i < 4; i++) /* scramble it */
+ mix (a, b, c, d, e, f, g, h);
#endif
- memset (s->mm, 0, sizeof s->mm);
- memcpy (s->iv, iv, sizeof s->iv);
+ /* Mix S->m so that every part of the seed affects every part of the
+ state. */
+ ISAAC_MIX (s, a, b, c, d, e, f, g, h, s->m);
+ ISAAC_MIX (s, a, b, c, d, e, f, g, h, s->m);
- /* s->c gets used for a data pointer during the seeding phase */
s->a = s->b = s->c = 0;
}
-
-/* Add a buffer of seed material. */
-static void
-isaac_seed_data (struct isaac_state *s, void const *buffer, size_t size)
-{
- unsigned char const *buf = buffer;
- unsigned char *p;
- size_t avail;
- size_t i;
-
- avail = sizeof s->mm - s->c; /* s->c is used as a write pointer */
-
- /* Do any full buffers that are necessary */
- while (size > avail)
- {
- p = (unsigned char *) s->mm + s->c;
- for (i = 0; i < avail; i++)
- p[i] ^= buf[i];
- buf += avail;
- size -= avail;
- isaac_mix (s, s->mm);
- s->c = 0;
- avail = sizeof s->mm;
- }
-
- /* And the final partial block */
- p = (unsigned char *) s->mm + s->c;
- for (i = 0; i < size; i++)
- p[i] ^= buf[i];
- s->c = size;
-}
-
-
-/* End of seeding phase; get everything ready to produce output. */
-static void
-isaac_seed_finish (struct isaac_state *s)
-{
- isaac_mix (s, s->mm);
- isaac_mix (s, s->mm);
- /* Now reinitialize c to start things off right */
- s->c = 0;
-}
-#define ISAAC_SEED(s,x) isaac_seed_data (s, &(x), sizeof (x))
-
-/* Initialize *S to a somewhat-random value; this starts seeding,
- seeds with somewhat-random data, and finishes seeding. */
-void
-isaac_seed (struct isaac_state *s)
-{
- isaac_seed_start (s);
-
- { pid_t t = getpid (); ISAAC_SEED (s, t); }
- { pid_t t = getppid (); ISAAC_SEED (s, t); }
- { uid_t t = getuid (); ISAAC_SEED (s, t); }
- { gid_t t = getgid (); ISAAC_SEED (s, t); }
-
- {
- xtime_t t = gethrxtime ();
- ISAAC_SEED (s, t);
- }
-
- isaac_seed_finish (s);
-}
diff --git a/lib/rand-isaac.h b/lib/rand-isaac.h
index f8daee0..3092bf4 100644
--- a/lib/rand-isaac.h
+++ b/lib/rand-isaac.h
@@ -1,12 +1,12 @@
-/* Bob Jenkins's cryptographic random number generator, ISAAC.
+/* Bob Jenkins's cryptographic random number generators, ISAAC and ISAAC64.
- Copyright (C) 1999-2005 Free Software Foundation, Inc.
+ Copyright (C) 1999-2016 Free Software Foundation, Inc.
Copyright (C) 1997, 1998, 1999 Colin Plumb.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,31 +14,52 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
- Written by Colin Plumb. */
+ Written by Colin Plumb and Paul Eggert. */
-#ifndef RAND_ISAAC_H
-# define RAND_ISAAC_H
+#ifndef _GL_RAND_ISAAC_H
+#define _GL_RAND_ISAAC_H
-# include <stdint.h>
+#include <stddef.h>
+#include <stdint.h>
-/* Size of the state tables to use. ISAAC_LOG should be at least 3,
+/* Log base 2 of the number of useful bits in an ISAAC word. It must
+ be either 5 or 6. By default, this uses a value that should be
+ faster for this architecture. */
+#ifndef ISAAC_BITS_LOG
+ #if SIZE_MAX >> 31 >> 31 < 3 /* SIZE_MAX < 2**64 - 1 */
+ #define ISAAC_BITS_LOG 5
+ #else
+ #define ISAAC_BITS_LOG 6
+ #endif
+#endif
+
+/* The number of bits in an ISAAC word. */
+#define ISAAC_BITS (1 << ISAAC_BITS_LOG)
+
+#if ISAAC_BITS == 32
+ typedef uint_least32_t isaac_word;
+#else
+ typedef uint_least64_t isaac_word;
+#endif
+
+/* Size of the state tables to use. ISAAC_WORDS_LOG should be at least 3,
and smaller values give less security. */
-# define ISAAC_LOG 8
-# define ISAAC_WORDS (1 << ISAAC_LOG)
-# define ISAAC_BYTES (ISAAC_WORDS * sizeof (uint32_t))
+#define ISAAC_WORDS_LOG 8
+#define ISAAC_WORDS (1 << ISAAC_WORDS_LOG)
+#define ISAAC_BYTES (ISAAC_WORDS * sizeof (isaac_word))
-/* RNG state variables. The members of this structure are private. */
+/* State variables for the random number generator. The M member
+ should be seeded with nonce data before calling isaac_seed. The
+ other members are private. */
struct isaac_state
{
- uint32_t mm[ISAAC_WORDS]; /* Main state array */
- uint32_t iv[8]; /* Seeding initial vector */
- uint32_t a, b, c; /* Extra index variables */
+ isaac_word m[ISAAC_WORDS]; /* Main state array */
+ isaac_word a, b, c; /* Extra variables */
};
void isaac_seed (struct isaac_state *);
-void isaac_refill (struct isaac_state *, uint32_t[ISAAC_WORDS]);
+void isaac_refill (struct isaac_state *, isaac_word[ISAAC_WORDS]);
#endif
diff --git a/lib/randint.c b/lib/randint.c
index 5ee738a..95c3c6d 100644
--- a/lib/randint.c
+++ b/lib/randint.c
@@ -1,11 +1,11 @@
/* Generate random integers.
- Copyright (C) 2006 Free Software Foundation, Inc.
+ Copyright (C) 2006-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
@@ -51,10 +50,6 @@ main (int argc, char **argv)
#include "xalloc.h"
-#ifndef MAX
-# define MAX(a,b) ((a) < (b) ? (b) : (a))
-#endif
-
/* A source of random data for generating random integers. */
struct randint_source
{
@@ -130,78 +125,78 @@ randint_genmax (struct randint_source *s, randint genmax)
randint randmax = s->randmax;
randint choices = genmax + 1;
- for (;;)
+ while (1)
{
if (randmax < genmax)
- {
- /* Calculate how many input bytes will be needed, and read
- the bytes. */
-
- size_t i = 0;
- randint rmax = randmax;
- unsigned char buf[sizeof randnum];
-
- do
- {
- rmax = shift_left (rmax) + UCHAR_MAX;
- i++;
- }
- while (rmax < genmax);
-
- randread (source, buf, i);
-
- /* Increase RANDMAX by appending random bytes to RANDNUM and
- UCHAR_MAX to RANDMAX until RANDMAX is no less than
- GENMAX. This may lose up to CHAR_BIT bits of information
- if shift_right (RANDINT_MAX) < GENMAX, but it is not
- worth the programming hassle of saving these bits since
- GENMAX is rarely that large in practice. */
-
- i = 0;
-
- do
- {
- randnum = shift_left (randnum) + buf[i];
- randmax = shift_left (randmax) + UCHAR_MAX;
- i++;
- }
- while (randmax < genmax);
- }
+ {
+ /* Calculate how many input bytes will be needed, and read
+ the bytes. */
+
+ size_t i = 0;
+ randint rmax = randmax;
+ unsigned char buf[sizeof randnum];
+
+ do
+ {
+ rmax = shift_left (rmax) + UCHAR_MAX;
+ i++;
+ }
+ while (rmax < genmax);
+
+ randread (source, buf, i);
+
+ /* Increase RANDMAX by appending random bytes to RANDNUM and
+ UCHAR_MAX to RANDMAX until RANDMAX is no less than
+ GENMAX. This may lose up to CHAR_BIT bits of information
+ if shift_right (RANDINT_MAX) < GENMAX, but it is not
+ worth the programming hassle of saving these bits since
+ GENMAX is rarely that large in practice. */
+
+ i = 0;
+
+ do
+ {
+ randnum = shift_left (randnum) + buf[i];
+ randmax = shift_left (randmax) + UCHAR_MAX;
+ i++;
+ }
+ while (randmax < genmax);
+ }
if (randmax == genmax)
- {
- s->randnum = s->randmax = 0;
- return randnum;
- }
+ {
+ s->randnum = s->randmax = 0;
+ return randnum;
+ }
else
- {
- /* GENMAX < RANDMAX, so attempt to generate a random number
- by taking RANDNUM modulo GENMAX+1. This will choose
- fairly so long as RANDNUM falls within an integral
- multiple of GENMAX+1; otherwise, LAST_USABLE_CHOICE < RANDNUM,
- so discard this attempt and try again.
-
- Since GENMAX cannot be RANDINT_MAX, CHOICES cannot be
- zero and there is no need to worry about dividing by
- zero. */
-
- randint excess_choices = randmax - genmax;
- randint unusable_choices = excess_choices % choices;
- randint last_usable_choice = randmax - unusable_choices;
- randint reduced_randnum = randnum % choices;
-
- if (randnum <= last_usable_choice)
- {
- s->randnum = randnum / choices;
- s->randmax = excess_choices / choices;
- return reduced_randnum;
- }
-
- /* Retry, but retain the randomness from the fact that RANDNUM fell
- into the range LAST_USABLE_CHOICE+1 .. RANDMAX. */
- randnum = reduced_randnum;
- randmax = unusable_choices - 1;
- }
+ {
+ /* GENMAX < RANDMAX, so attempt to generate a random number
+ by taking RANDNUM modulo GENMAX+1. This will choose
+ fairly so long as RANDNUM falls within an integral
+ multiple of GENMAX+1; otherwise, LAST_USABLE_CHOICE < RANDNUM,
+ so discard this attempt and try again.
+
+ Since GENMAX cannot be RANDINT_MAX, CHOICES cannot be
+ zero and there is no need to worry about dividing by
+ zero. */
+
+ randint excess_choices = randmax - genmax;
+ randint unusable_choices = excess_choices % choices;
+ randint last_usable_choice = randmax - unusable_choices;
+ randint reduced_randnum = randnum % choices;
+
+ if (randnum <= last_usable_choice)
+ {
+ s->randnum = randnum / choices;
+ s->randmax = excess_choices / choices;
+ return reduced_randnum;
+ }
+
+ /* Retry, but retain the randomness from the fact that RANDNUM fell
+ into the range LAST_USABLE_CHOICE+1 .. RANDMAX. */
+ randnum = reduced_randnum;
+ randmax = unusable_choices - 1;
+ }
}
}
diff --git a/lib/randint.h b/lib/randint.h
index 4245a6d..682b483 100644
--- a/lib/randint.h
+++ b/lib/randint.h
@@ -1,11 +1,11 @@
/* Generate random integers.
- Copyright (C) 2006 Free Software Foundation, Inc.
+ Copyright (C) 2006-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
@@ -35,7 +34,8 @@ struct randint_source;
struct randint_source *randint_new (struct randread_source *);
struct randint_source *randint_all_new (char const *, size_t);
-struct randread_source *randint_get_source (struct randint_source const *);
+struct randread_source *randint_get_source (struct randint_source const *)
+ _GL_ATTRIBUTE_PURE;
randint randint_genmax (struct randint_source *, randint genmax);
/* Consume random data from *S to generate a random number in the range
diff --git a/lib/randperm.c b/lib/randperm.c
index c4438dd..9b5919e 100644
--- a/lib/randperm.c
+++ b/lib/randperm.c
@@ -1,11 +1,11 @@
/* Generate random permutations.
- Copyright (C) 2006, 2007 Free Software Foundation, Inc.
+ Copyright (C) 2006-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,23 +13,24 @@
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, write to the Free Software Foundation,
- Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
#include <config.h>
+#include "hash.h"
#include "randperm.h"
#include <limits.h>
+#include <stdlib.h>
#include "xalloc.h"
/* Return the ceiling of the log base 2 of N. If N is zero, return
an unspecified value. */
-static size_t
+static size_t _GL_ATTRIBUTE_CONST
ceil_lg (size_t n)
{
size_t b = 0;
@@ -58,6 +59,94 @@ randperm_bound (size_t h, size_t n)
return bound;
}
+/* Swap elements I and J in array V. */
+
+static void
+swap (size_t *v, size_t i, size_t j)
+{
+ size_t t = v[i];
+ v[i] = v[j];
+ v[j] = t;
+}
+
+/* Structures and functions for a sparse_map abstract data type that's
+ used to effectively swap elements I and J in array V like swap(),
+ but in a more memory efficient manner (when the number of permutations
+ performed is significantly less than the size of the input). */
+
+struct sparse_ent_
+{
+ size_t index;
+ size_t val;
+};
+
+static size_t
+sparse_hash_ (void const *x, size_t table_size)
+{
+ struct sparse_ent_ const *ent = x;
+ return ent->index % table_size;
+}
+
+static bool
+sparse_cmp_ (void const *x, void const *y)
+{
+ struct sparse_ent_ const *ent1 = x;
+ struct sparse_ent_ const *ent2 = y;
+ return ent1->index == ent2->index;
+}
+
+typedef Hash_table sparse_map;
+
+/* Initialize the structure for the sparse map,
+ when a best guess as to the number of entries
+ specified with SIZE_HINT. */
+
+static sparse_map *
+sparse_new (size_t size_hint)
+{
+ return hash_initialize (size_hint, NULL, sparse_hash_, sparse_cmp_, free);
+}
+
+/* Swap the values for I and J. If a value is not already present
+ then assume it's equal to the index. Update the value for
+ index I in array V. */
+
+static void
+sparse_swap (sparse_map *sv, size_t* v, size_t i, size_t j)
+{
+ struct sparse_ent_ *v1 = hash_delete (sv, &(struct sparse_ent_) {i,0});
+ struct sparse_ent_ *v2 = hash_delete (sv, &(struct sparse_ent_) {j,0});
+
+ /* FIXME: reduce the frequency of these mallocs. */
+ if (!v1)
+ {
+ v1 = xmalloc (sizeof *v1);
+ v1->index = v1->val = i;
+ }
+ if (!v2)
+ {
+ v2 = xmalloc (sizeof *v2);
+ v2->index = v2->val = j;
+ }
+
+ size_t t = v1->val;
+ v1->val = v2->val;
+ v2->val = t;
+ if (!hash_insert (sv, v1))
+ xalloc_die ();
+ if (!hash_insert (sv, v2))
+ xalloc_die ();
+
+ v[i] = v1->val;
+}
+
+static void
+sparse_free (sparse_map *sv)
+{
+ hash_free (sv);
+}
+
+
/* From R, allocate and return a malloc'd array of the first H elements
of a random permutation of N elements. H must not exceed N.
Return NULL if H is zero. */
@@ -80,21 +169,66 @@ randperm_new (struct randint_source *r, size_t h, size_t n)
default:
{
- size_t i;
-
- v = xnmalloc (n, sizeof *v);
- for (i = 0; i < n; i++)
- v[i] = i;
-
- for (i = 0; i < h; i++)
- {
- size_t j = i + randint_choose (r, n - i);
- size_t t = v[i];
- v[i] = v[j];
- v[j] = t;
- }
-
- v = xnrealloc (v, h, sizeof *v);
+ /* The algorithm is essentially the same in both
+ the sparse and non sparse case. In the sparse case we use
+ a hash to implement sparse storage for the set of n numbers
+ we're shuffling. When to use the sparse method was
+ determined with the help of this script:
+
+ #!/bin/sh
+ for n in $(seq 2 32); do
+ for h in $(seq 2 32); do
+ test $h -gt $n && continue
+ for s in o n; do
+ test $s = o && shuf=shuf || shuf=./shuf
+ num=$(env time -f "$s:${h},${n} = %e,%M" \
+ $shuf -i0-$((2**$n-2)) -n$((2**$h-2)) | wc -l)
+ test $num = $((2**$h-2)) || echo "$s:${h},${n} = failed" >&2
+ done
+ done
+ done
+
+ This showed that if sparseness = n/h, then:
+
+ sparseness = 128 => .125 mem used, and about same speed
+ sparseness = 64 => .25 mem used, but 1.5 times slower
+ sparseness = 32 => .5 mem used, but 2 times slower
+
+ Also the memory usage was only significant when n > 128Ki
+ */
+ bool sparse = (n >= (128 * 1024)) && (n / h >= 32);
+
+ size_t i;
+ sparse_map *sv;
+
+ if (sparse)
+ {
+ sv = sparse_new (h * 2);
+ if (sv == NULL)
+ xalloc_die ();
+ v = xnmalloc (h, sizeof *v);
+ }
+ else
+ {
+ sv = NULL; /* To placate GCC's -Wuninitialized. */
+ v = xnmalloc (n, sizeof *v);
+ for (i = 0; i < n; i++)
+ v[i] = i;
+ }
+
+ for (i = 0; i < h; i++)
+ {
+ size_t j = i + randint_choose (r, n - i);
+ if (sparse)
+ sparse_swap (sv, v, i, j);
+ else
+ swap (v, i, j);
+ }
+
+ if (sparse)
+ sparse_free (sv);
+ else
+ v = xnrealloc (v, h, sizeof *v);
}
break;
}
diff --git a/lib/randperm.h b/lib/randperm.h
index 79bbf9f..0a0837a 100644
--- a/lib/randperm.h
+++ b/lib/randperm.h
@@ -1,4 +1,4 @@
#include "randint.h"
#include <stddef.h>
-size_t randperm_bound (size_t, size_t);
+size_t randperm_bound (size_t, size_t) _GL_ATTRIBUTE_CONST;
size_t *randperm_new (struct randint_source *, size_t, size_t);
diff --git a/lib/randread.c b/lib/randread.c
index 5462d44..ff85d56 100644
--- a/lib/randread.c
+++ b/lib/randread.c
@@ -1,11 +1,11 @@
/* Generate buffers of random data.
- Copyright (C) 2006 Free Software Foundation, Inc.
+ Copyright (C) 2006-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,11 +13,13 @@
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, write to the Free Software Foundation,
- Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
+/* FIXME: Improve performance by adding support for the RDRAND machine
+ instruction if available (e.g., Ivy Bridge processors). */
+
#include <config.h>
#include "randread.h"
@@ -25,12 +27,16 @@
#include <errno.h>
#include <error.h>
#include <exitfail.h>
-#include <quotearg.h>
+#include <fcntl.h>
+#include <quote.h>
+#include <stdalign.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#include <sys/time.h>
+#include <unistd.h>
#include "gettext.h"
#define _(msgid) gettext (msgid)
@@ -40,29 +46,28 @@
#include "unlocked-io.h"
#include "xalloc.h"
-#ifndef MIN
-# define MIN(a, b) ((a) < (b) ? (a) : (b))
-#endif
-
#ifndef __attribute__
-# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 8) || __STRICT_ANSI__
-# define __attribute__(x)
+# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 8)
+# define __attribute__(x) /* empty */
# endif
#endif
-#ifndef ATTRIBUTE_UNUSED
-# define ATTRIBUTE_UNUSED __attribute__ ((__unused__))
+#ifndef ATTRIBUTE_NORETURN
+# define ATTRIBUTE_NORETURN __attribute__ ((__noreturn__))
+#endif
+
+#ifndef MIN
+# define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif
#if _STRING_ARCH_unaligned
# define ALIGNED_POINTER(ptr, type) true
#else
-# define alignof(type) offsetof (struct { char c; type x; }, x)
# define ALIGNED_POINTER(ptr, type) ((size_t) (ptr) % alignof (type) == 0)
#endif
-#ifndef DEFAULT_RANDOM_FILE
-# define DEFAULT_RANDOM_FILE "/dev/urandom"
+#ifndef NAME_OF_NONCE_DEVICE
+# define NAME_OF_NONCE_DEVICE "/dev/urandom"
#endif
/* The maximum buffer size used for reads of random data. Using the
@@ -73,10 +78,8 @@
/* A source of random data for generating random buffers. */
struct randread_source
{
- /* Stream to read random bytes from. If null, the behavior is
- undefined; the current implementation uses ISAAC in this case,
- but this is for old-fashioned implementations that lack
- /dev/urandom and callers should not rely on this. */
+ /* Stream to read random bytes from. If null, the current
+ implementation uses an internal PRNG (ISAAC). */
FILE *source;
/* Function to call, and its argument, if there is an input error or
@@ -107,8 +110,8 @@ struct randread_source
/* Up to a buffer's worth of pseudorandom data. */
union
{
- uint32_t w[ISAAC_WORDS];
- unsigned char b[ISAAC_BYTES];
+ isaac_word w[ISAAC_WORDS];
+ unsigned char b[ISAAC_BYTES];
} data;
} isaac;
} buf;
@@ -117,13 +120,13 @@ struct randread_source
/* The default error handler. */
-static void
+static void ATTRIBUTE_NORETURN
randread_error (void const *file_name)
{
if (file_name)
error (exit_failure, errno,
- _(errno == 0 ? "%s: end of file" : "%s: read error"),
- quotearg_colon (file_name));
+ errno == 0 ? _("%s: end of file") : _("%s: read error"),
+ quote (file_name));
abort ();
}
@@ -140,6 +143,52 @@ simple_new (FILE *source, void const *handler_arg)
return s;
}
+/* Put a nonce value into BUFFER, with size BUFSIZE, but do not get
+ more than BYTES_BOUND bytes' worth of random information from any
+ nonce device. */
+
+static void
+get_nonce (void *buffer, size_t bufsize, size_t bytes_bound)
+{
+ char *buf = buffer;
+ ssize_t seeded = 0;
+
+ /* Get some data from FD if available. */
+ int fd = open (NAME_OF_NONCE_DEVICE, O_RDONLY | O_BINARY);
+ if (0 <= fd)
+ {
+ seeded = read (fd, buf, MIN (bufsize, bytes_bound));
+ if (seeded < 0)
+ seeded = 0;
+ close (fd);
+ }
+
+ /* If there's no nonce device, use a poor approximation
+ by getting the time of day, etc. */
+#define ISAAC_SEED(type, initialize_v) \
+ if (seeded < bufsize) \
+ { \
+ type v; \
+ size_t nbytes = MIN (sizeof v, bufsize - seeded); \
+ initialize_v; \
+ memcpy (buf + seeded, &v, nbytes); \
+ seeded += nbytes; \
+ }
+ ISAAC_SEED (struct timeval, gettimeofday (&v, NULL));
+ ISAAC_SEED (pid_t, v = getpid ());
+ ISAAC_SEED (pid_t, v = getppid ());
+ ISAAC_SEED (uid_t, v = getuid ());
+ ISAAC_SEED (uid_t, v = getgid ());
+
+#ifdef lint
+ /* Normally we like having the extra randomness from uninitialized
+ parts of BUFFER. However, omit this randomness if we want to
+ avoid false-positives from memory-checking debugging tools. */
+ memset (buf + seeded, 0, bufsize - seeded);
+#endif
+}
+
+
/* Create and initialize a random data source from NAME, or use a
reasonable default source if NAME is null. BYTES_BOUND is an upper
bound on the number of bytes that will be needed. If zero, it is a
@@ -158,26 +207,24 @@ randread_new (char const *name, size_t bytes_bound)
return simple_new (NULL, NULL);
else
{
- char const *file_name = (name ? name : DEFAULT_RANDOM_FILE);
- FILE *source = fopen_safer (file_name, "rb");
+ FILE *source = NULL;
struct randread_source *s;
- if (! source)
- {
- if (name)
- return NULL;
- file_name = NULL;
- }
+ if (name)
+ if (! (source = fopen_safer (name, "rb")))
+ return NULL;
- s = simple_new (source, file_name);
+ s = simple_new (source, name);
if (source)
- setvbuf (source, s->buf.c, _IOFBF, MIN (sizeof s->buf.c, bytes_bound));
+ setvbuf (source, s->buf.c, _IOFBF, MIN (sizeof s->buf.c, bytes_bound));
else
- {
- s->buf.isaac.buffered = 0;
- isaac_seed (&s->buf.isaac.state);
- }
+ {
+ s->buf.isaac.buffered = 0;
+ get_nonce (s->buf.isaac.state.m, sizeof s->buf.isaac.state.m,
+ bytes_bound);
+ isaac_seed (&s->buf.isaac.state);
+ }
return s;
}
@@ -210,14 +257,14 @@ randread_set_handler_arg (struct randread_source *s, void const *handler_arg)
static void
readsource (struct randread_source *s, unsigned char *p, size_t size)
{
- for (;;)
+ while (true)
{
size_t inbytes = fread (p, sizeof *p, size, s->source);
int fread_errno = errno;
p += inbytes;
size -= inbytes;
if (size == 0)
- break;
+ break;
errno = (ferror (s->source) ? fread_errno : 0);
s->handler (s->handler_arg);
}
@@ -228,41 +275,43 @@ readsource (struct randread_source *s, unsigned char *p, size_t size)
the buffered ISAAC generator in ISAAC. */
static void
-readisaac (struct isaac *isaac, unsigned char *p, size_t size)
+readisaac (struct isaac *isaac, void *p, size_t size)
{
size_t inbytes = isaac->buffered;
- for (;;)
+ while (true)
{
+ char *char_p = p;
+
if (size <= inbytes)
- {
- memcpy (p, isaac->data.b + ISAAC_BYTES - inbytes, size);
- isaac->buffered = inbytes - size;
- return;
- }
+ {
+ memcpy (p, isaac->data.b + ISAAC_BYTES - inbytes, size);
+ isaac->buffered = inbytes - size;
+ return;
+ }
memcpy (p, isaac->data.b + ISAAC_BYTES - inbytes, inbytes);
- p += inbytes;
+ p = char_p + inbytes;
size -= inbytes;
/* If P is aligned, write to *P directly to avoid the overhead
- of copying from the buffer. */
- if (ALIGNED_POINTER (p, uint32_t))
- {
- uint32_t *wp = (uint32_t *) p;
- while (ISAAC_BYTES <= size)
- {
- isaac_refill (&isaac->state, wp);
- wp += ISAAC_WORDS;
- size -= ISAAC_BYTES;
- if (size == 0)
- {
- isaac->buffered = 0;
- return;
- }
- }
- p = (unsigned char *) wp;
- }
+ of copying from the buffer. */
+ if (ALIGNED_POINTER (p, isaac_word))
+ {
+ isaac_word *wp = p;
+ while (ISAAC_BYTES <= size)
+ {
+ isaac_refill (&isaac->state, wp);
+ wp += ISAAC_WORDS;
+ size -= ISAAC_BYTES;
+ if (size == 0)
+ {
+ isaac->buffered = 0;
+ return;
+ }
+ }
+ p = wp;
+ }
isaac_refill (&isaac->state, isaac->data.w);
inbytes = ISAAC_BYTES;
diff --git a/lib/randread.h b/lib/randread.h
index 8e34334..a91a358 100644
--- a/lib/randread.h
+++ b/lib/randread.h
@@ -1,11 +1,11 @@
/* Generate buffers of random data.
- Copyright (C) 2006 Free Software Foundation, Inc.
+ Copyright (C) 2006-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
diff --git a/lib/read-file.c b/lib/read-file.c
new file mode 100644
index 0000000..f7b1199
--- /dev/null
+++ b/lib/read-file.c
@@ -0,0 +1,188 @@
+/* read-file.c -- read file contents into a string
+ Copyright (C) 2006, 2009-2016 Free Software Foundation, Inc.
+ Written by Simon Josefsson and Bruno Haible.
+
+ 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, 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+#include "read-file.h"
+
+/* Get fstat. */
+#include <sys/stat.h>
+
+/* Get ftello. */
+#include <stdio.h>
+
+/* Get SIZE_MAX. */
+#include <stdint.h>
+
+/* Get malloc, realloc, free. */
+#include <stdlib.h>
+
+/* Get errno. */
+#include <errno.h>
+
+/* Read a STREAM and return a newly allocated string with the content,
+ and set *LENGTH to the length of the string. The string is
+ zero-terminated, but the terminating zero byte is not counted in
+ *LENGTH. On errors, *LENGTH is undefined, errno preserves the
+ values set by system functions (if any), and NULL is returned. */
+char *
+fread_file (FILE *stream, size_t *length)
+{
+ char *buf = NULL;
+ size_t alloc = BUFSIZ;
+
+ /* For a regular file, allocate a buffer that has exactly the right
+ size. This avoids the need to do dynamic reallocations later. */
+ {
+ struct stat st;
+
+ if (fstat (fileno (stream), &st) >= 0 && S_ISREG (st.st_mode))
+ {
+ off_t pos = ftello (stream);
+
+ if (pos >= 0 && pos < st.st_size)
+ {
+ off_t alloc_off = st.st_size - pos;
+
+ /* '1' below, accounts for the trailing NUL. */
+ if (SIZE_MAX - 1 < alloc_off)
+ {
+ errno = ENOMEM;
+ return NULL;
+ }
+
+ alloc = alloc_off + 1;
+ }
+ }
+ }
+
+ if (!(buf = malloc (alloc)))
+ return NULL; /* errno is ENOMEM. */
+
+ {
+ size_t size = 0; /* number of bytes read so far */
+ int save_errno;
+
+ for (;;)
+ {
+ /* This reads 1 more than the size of a regular file
+ so that we get eof immediately. */
+ size_t requested = alloc - size;
+ size_t count = fread (buf + size, 1, requested, stream);
+ size += count;
+
+ if (count != requested)
+ {
+ save_errno = errno;
+ if (ferror (stream))
+ break;
+
+ /* Shrink the allocated memory if possible. */
+ if (size < alloc - 1)
+ {
+ char *smaller_buf = realloc (buf, size + 1);
+ if (smaller_buf != NULL)
+ buf = smaller_buf;
+ }
+
+ buf[size] = '\0';
+ *length = size;
+ return buf;
+ }
+
+ {
+ char *new_buf;
+
+ if (alloc == SIZE_MAX)
+ {
+ save_errno = ENOMEM;
+ break;
+ }
+
+ if (alloc < SIZE_MAX - alloc / 2)
+ alloc = alloc + alloc / 2;
+ else
+ alloc = SIZE_MAX;
+
+ if (!(new_buf = realloc (buf, alloc)))
+ {
+ save_errno = errno;
+ break;
+ }
+
+ buf = new_buf;
+ }
+ }
+
+ free (buf);
+ errno = save_errno;
+ return NULL;
+ }
+}
+
+static char *
+internal_read_file (const char *filename, size_t *length, const char *mode)
+{
+ FILE *stream = fopen (filename, mode);
+ char *out;
+ int save_errno;
+
+ if (!stream)
+ return NULL;
+
+ out = fread_file (stream, length);
+
+ save_errno = errno;
+
+ if (fclose (stream) != 0)
+ {
+ if (out)
+ {
+ save_errno = errno;
+ free (out);
+ }
+ errno = save_errno;
+ return NULL;
+ }
+
+ return out;
+}
+
+/* Open and read the contents of FILENAME, and return a newly
+ allocated string with the content, and set *LENGTH to the length of
+ the string. The string is zero-terminated, but the terminating
+ zero byte is not counted in *LENGTH. On errors, *LENGTH is
+ undefined, errno preserves the values set by system functions (if
+ any), and NULL is returned. */
+char *
+read_file (const char *filename, size_t *length)
+{
+ return internal_read_file (filename, length, "r");
+}
+
+/* Open (on non-POSIX systems, in binary mode) and read the contents
+ of FILENAME, and return a newly allocated string with the content,
+ and set LENGTH to the length of the string. The string is
+ zero-terminated, but the terminating zero byte is not counted in
+ the LENGTH variable. On errors, *LENGTH is undefined, errno
+ preserves the values set by system functions (if any), and NULL is
+ returned. */
+char *
+read_binary_file (const char *filename, size_t *length)
+{
+ return internal_read_file (filename, length, "rb");
+}
diff --git a/lib/read-file.h b/lib/read-file.h
new file mode 100644
index 0000000..6248065
--- /dev/null
+++ b/lib/read-file.h
@@ -0,0 +1,33 @@
+/* read-file.h -- read file contents into a string
+ Copyright (C) 2006, 2009-2016 Free Software Foundation, Inc.
+ Written by Simon Josefsson.
+
+ 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, 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef READ_FILE_H
+#define READ_FILE_H
+
+/* Get size_t. */
+#include <stddef.h>
+
+/* Get FILE. */
+#include <stdio.h>
+
+extern char *fread_file (FILE * stream, size_t * length);
+
+extern char *read_file (const char *filename, size_t * length);
+
+extern char *read_binary_file (const char *filename, size_t * length);
+
+#endif /* READ_FILE_H */
diff --git a/lib/read.c b/lib/read.c
new file mode 100644
index 0000000..23b2411
--- /dev/null
+++ b/lib/read.c
@@ -0,0 +1,85 @@
+/* POSIX compatible read() function.
+ Copyright (C) 2008-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2011.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <unistd.h>
+
+#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+
+# include <errno.h>
+# include <io.h>
+
+# define WIN32_LEAN_AND_MEAN /* avoid including junk */
+# include <windows.h>
+
+# include "msvc-inval.h"
+# include "msvc-nothrow.h"
+
+# undef read
+
+# if HAVE_MSVC_INVALID_PARAMETER_HANDLER
+static ssize_t
+read_nothrow (int fd, void *buf, size_t count)
+{
+ ssize_t result;
+
+ TRY_MSVC_INVAL
+ {
+ result = read (fd, buf, count);
+ }
+ CATCH_MSVC_INVAL
+ {
+ result = -1;
+ errno = EBADF;
+ }
+ DONE_MSVC_INVAL;
+
+ return result;
+}
+# else
+# define read_nothrow read
+# endif
+
+ssize_t
+rpl_read (int fd, void *buf, size_t count)
+{
+ ssize_t ret = read_nothrow (fd, buf, count);
+
+# if GNULIB_NONBLOCKING
+ if (ret < 0
+ && GetLastError () == ERROR_NO_DATA)
+ {
+ HANDLE h = (HANDLE) _get_osfhandle (fd);
+ if (GetFileType (h) == FILE_TYPE_PIPE)
+ {
+ /* h is a pipe or socket. */
+ DWORD state;
+ if (GetNamedPipeHandleState (h, &state, NULL, NULL, NULL, NULL, 0)
+ && (state & PIPE_NOWAIT) != 0)
+ /* h is a pipe in non-blocking mode.
+ Change errno from EINVAL to EAGAIN. */
+ errno = EAGAIN;
+ }
+ }
+# endif
+
+ return ret;
+}
+
+#endif
diff --git a/lib/readdir.c b/lib/readdir.c
new file mode 100644
index 0000000..76b7e9d
--- /dev/null
+++ b/lib/readdir.c
@@ -0,0 +1,98 @@
+/* Read the next entry of a directory.
+ Copyright (C) 2011-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <dirent.h>
+
+#include <errno.h>
+#include <stddef.h>
+
+#include "dirent-private.h"
+
+struct dirent *
+readdir (DIR *dirp)
+{
+ char type;
+ struct dirent *result;
+
+ /* There is no need to add code to produce entries for "." and "..".
+ According to the POSIX:2008 section "4.12 Pathname Resolution"
+ <http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html>
+ "." and ".." are syntactic entities.
+ POSIX also says:
+ "If entries for dot or dot-dot exist, one entry shall be returned
+ for dot and one entry shall be returned for dot-dot; otherwise,
+ they shall not be returned." */
+
+ switch (dirp->status)
+ {
+ case -2:
+ /* End of directory already reached. */
+ return NULL;
+ case -1:
+ break;
+ case 0:
+ if (!FindNextFile (dirp->current, &dirp->entry))
+ {
+ switch (GetLastError ())
+ {
+ case ERROR_NO_MORE_FILES:
+ dirp->status = -2;
+ return NULL;
+ default:
+ errno = EIO;
+ return NULL;
+ }
+ }
+ break;
+ default:
+ errno = dirp->status;
+ return NULL;
+ }
+
+ dirp->status = 0;
+
+ if (dirp->entry.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
+ type = DT_DIR;
+ else if (dirp->entry.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
+ type = DT_LNK;
+ else if ((dirp->entry.dwFileAttributes
+ & ~(FILE_ATTRIBUTE_READONLY
+ | FILE_ATTRIBUTE_HIDDEN
+ | FILE_ATTRIBUTE_SYSTEM
+ | FILE_ATTRIBUTE_ARCHIVE
+ | FILE_ATTRIBUTE_NORMAL
+ | FILE_ATTRIBUTE_TEMPORARY
+ | FILE_ATTRIBUTE_SPARSE_FILE
+ | FILE_ATTRIBUTE_COMPRESSED
+ | FILE_ATTRIBUTE_NOT_CONTENT_INDEXED
+ | FILE_ATTRIBUTE_ENCRYPTED)) == 0)
+ /* Devices like COM1, LPT1, NUL would also have the attributes 0x20 but
+ they cannot occur here. */
+ type = DT_REG;
+ else
+ type = DT_UNKNOWN;
+
+ /* Reuse the memory of dirp->entry for the result. */
+ result =
+ (struct dirent *)
+ ((char *) dirp->entry.cFileName - offsetof (struct dirent, d_name[0]));
+ result->d_type = type;
+
+ return result;
+}
diff --git a/lib/readlink.c b/lib/readlink.c
index 3cbdc1c..e6c3925 100644
--- a/lib/readlink.c
+++ b/lib/readlink.c
@@ -1,10 +1,10 @@
/* Stub for readlink().
- Copyright (C) 2003-2007 Free Software Foundation, Inc.
+ Copyright (C) 2003-2007, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -12,8 +12,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
@@ -21,30 +20,55 @@
#include <unistd.h>
#include <errno.h>
-#include <sys/types.h>
+#include <string.h>
#include <sys/stat.h>
-#include <stddef.h>
#if !HAVE_READLINK
/* readlink() substitute for systems that don't have a readlink() function,
such as DJGPP 2.03 and mingw32. */
-/* The official POSIX return type of readlink() is ssize_t, but since here
- we have no declaration in a public header file, we use 'int' as return
- type. */
-
-int
-readlink (const char *path, char *buf, size_t bufsize)
+ssize_t
+readlink (const char *name, char *buf _GL_UNUSED,
+ size_t bufsize _GL_UNUSED)
{
struct stat statbuf;
/* In general we should use lstat() here, not stat(). But on platforms
- without symbolic links lstat() - if it exists - would be equivalent to
+ without symbolic links, lstat() - if it exists - would be equivalent to
stat(), therefore we can use stat(). This saves us a configure check. */
- if (stat (path, &statbuf) >= 0)
+ if (stat (name, &statbuf) >= 0)
errno = EINVAL;
return -1;
}
-#endif
+#else /* HAVE_READLINK */
+
+# undef readlink
+
+/* readlink() wrapper that uses correct types, for systems like cygwin
+ 1.5.x where readlink returns int, and which rejects trailing slash,
+ for Solaris 9. */
+
+ssize_t
+rpl_readlink (const char *name, char *buf, size_t bufsize)
+{
+# if READLINK_TRAILING_SLASH_BUG
+ size_t len = strlen (name);
+ if (len && name[len - 1] == '/')
+ {
+ /* Even if name without the slash is a symlink to a directory,
+ both lstat() and stat() must resolve the trailing slash to
+ the directory rather than the symlink. We can therefore
+ safely use stat() to distinguish between EINVAL and
+ ENOTDIR/ENOENT, avoiding extra overhead of rpl_lstat(). */
+ struct stat st;
+ if (stat (name, &st) == 0)
+ errno = EINVAL;
+ return -1;
+ }
+# endif /* READLINK_TRAILING_SLASH_BUG */
+ return readlink (name, buf, bufsize);
+}
+
+#endif /* HAVE_READLINK */
diff --git a/lib/readlinkat.c b/lib/readlinkat.c
new file mode 100644
index 0000000..7006db8
--- /dev/null
+++ b/lib/readlinkat.c
@@ -0,0 +1,79 @@
+/* Read a symlink relative to an open directory.
+ Copyright (C) 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* written by Eric Blake */
+
+#include <config.h>
+
+#include <errno.h>
+#include <unistd.h>
+#include <string.h>
+#include <sys/stat.h>
+
+#if HAVE_READLINKAT
+
+# undef readlinkat
+
+ssize_t
+rpl_readlinkat (int fd, char const *file, char *buf, size_t len)
+{
+# if READLINK_TRAILING_SLASH_BUG
+ size_t file_len = strlen (file);
+ if (file_len && file[file_len - 1] == '/')
+ {
+ /* Even if FILE without the slash is a symlink to a directory,
+ both lstat() and stat() must resolve the trailing slash to
+ the directory rather than the symlink. We can therefore
+ safely use stat() to distinguish between EINVAL and
+ ENOTDIR/ENOENT, avoiding extra overhead of rpl_lstat(). */
+ struct stat st;
+ if (stat (file, &st) == 0)
+ errno = EINVAL;
+ return -1;
+ }
+# endif /* READLINK_TRAILING_SLASH_BUG */
+ return readlinkat (fd, file, buf, len);
+}
+
+#else
+
+/* Gnulib provides a readlink stub for mingw; use it for distinction
+ between EINVAL and ENOENT, rather than always failing with ENOSYS. */
+
+/* POSIX 2008 says that unlike readlink, readlinkat returns 0 for
+ success instead of the buffer length. But this would render
+ readlinkat worthless since readlink does not guarantee a
+ NUL-terminated buffer. Assume this was a bug in POSIX. */
+
+/* Read the contents of symlink FILE into buffer BUF of size LEN, in the
+ directory open on descriptor FD. If possible, do it without changing
+ the working directory. Otherwise, resort to using save_cwd/fchdir,
+ then readlink/restore_cwd. If either the save_cwd or the restore_cwd
+ fails, then give a diagnostic and exit nonzero. */
+
+# define AT_FUNC_NAME readlinkat
+# define AT_FUNC_F1 readlink
+# define AT_FUNC_POST_FILE_PARAM_DECLS , char *buf, size_t len
+# define AT_FUNC_POST_FILE_ARGS , buf, len
+# define AT_FUNC_RESULT ssize_t
+# include "at-func.c"
+# undef AT_FUNC_NAME
+# undef AT_FUNC_F1
+# undef AT_FUNC_POST_FILE_PARAM_DECLS
+# undef AT_FUNC_POST_FILE_ARGS
+# undef AT_FUNC_RESULT
+
+#endif
diff --git a/lib/readtokens.c b/lib/readtokens.c
index 28aafa9..5933120 100644
--- a/lib/readtokens.c
+++ b/lib/readtokens.c
@@ -1,11 +1,12 @@
/* readtokens.c -- Functions for reading tokens from an input stream.
- Copyright (C) 1990-1991, 1999-2004, 2006 Free Software Foundation, Inc.
+ Copyright (C) 1990-1991, 1999-2004, 2006, 2009-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,12 +14,11 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
Written by Jim Meyering. */
-/* This almost supercedes xreadline stuff -- using delim="\n"
+/* This almost supersedes xreadline stuff -- using delim="\n"
gives the same functionality, except that these functions
would never return empty lines. */
@@ -26,6 +26,7 @@
#include "readtokens.h"
+#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -37,9 +38,6 @@
# include "unlocked-io.h"
#endif
-#define STREQ(a,b) ((a) == (b) || ((a) && (b) && *(a) == *(b) \
- && strcmp(a, b) == 0))
-
/* Initialize a tokenbuffer. */
void
@@ -49,6 +47,22 @@ init_tokenbuffer (token_buffer *tokenbuffer)
tokenbuffer->buffer = NULL;
}
+typedef size_t word;
+enum { bits_per_word = sizeof (word) * CHAR_BIT };
+
+static bool
+get_nth_bit (size_t n, word const *bitset)
+{
+ return bitset[n / bits_per_word] >> n % bits_per_word & 1;
+}
+
+static void
+set_nth_bit (size_t n, word *bitset)
+{
+ size_t one = 1;
+ bitset[n / bits_per_word] |= one << n % bits_per_word;
+}
+
/* Read a token from STREAM into TOKENBUFFER.
A token is delimited by any of the N_DELIM bytes in DELIM.
Upon return, the token is in tokenbuffer->buffer and
@@ -60,53 +74,28 @@ init_tokenbuffer (token_buffer *tokenbuffer)
by testing ferror (STREAM).
This function works properly on lines containing NUL bytes
- and on files do not end with a delimiter. */
+ and on files that do not end with a delimiter. */
size_t
readtoken (FILE *stream,
- const char *delim,
- size_t n_delim,
- token_buffer *tokenbuffer)
+ const char *delim,
+ size_t n_delim,
+ token_buffer *tokenbuffer)
{
char *p;
int c;
size_t i, n;
- static const char *saved_delim = NULL;
- static char isdelim[256];
- bool same_delimiters;
-
- if (delim == NULL && saved_delim == NULL)
- abort ();
-
- same_delimiters = false;
- if (delim != saved_delim && saved_delim != NULL)
- {
- same_delimiters = true;
- for (i = 0; i < n_delim; i++)
- {
- if (delim[i] != saved_delim[i])
- {
- same_delimiters = false;
- break;
- }
- }
- }
+ word isdelim[(UCHAR_MAX + bits_per_word) / bits_per_word];
- if (!same_delimiters)
+ memset (isdelim, 0, sizeof isdelim);
+ for (i = 0; i < n_delim; i++)
{
- size_t j;
- saved_delim = delim;
- memset (isdelim, 0, sizeof isdelim);
- for (j = 0; j < n_delim; j++)
- {
- unsigned char ch = delim[j];
- isdelim[ch] = 1;
- }
+ unsigned char ch = delim[i];
+ set_nth_bit (ch, isdelim);
}
- /* FIXME: don't fool with this caching. Use strchr instead. */
/* skip over any leading delimiters */
- for (c = getc (stream); c >= 0 && isdelim[c]; c = getc (stream))
+ for (c = getc (stream); c >= 0 && get_nth_bit (c, isdelim); c = getc (stream))
{
/* empty */
}
@@ -117,21 +106,21 @@ readtoken (FILE *stream,
for (;;)
{
if (c < 0 && i == 0)
- return -1;
+ return -1;
if (i == n)
- p = x2nrealloc (p, &n, sizeof *p);
+ p = x2nrealloc (p, &n, sizeof *p);
if (c < 0)
- {
- p[i] = 0;
- break;
- }
- if (isdelim[c])
- {
- p[i] = 0;
- break;
- }
+ {
+ p[i] = 0;
+ break;
+ }
+ if (get_nth_bit (c, isdelim))
+ {
+ p[i] = 0;
+ break;
+ }
p[i++] = c;
c = getc (stream);
}
@@ -146,15 +135,15 @@ readtoken (FILE *stream,
All storage is obtained through calls to xmalloc-like functions.
%%% Question: is it worth it to do a single
- %%% realloc() of `tokens' just before returning? */
+ %%% realloc() of 'tokens' just before returning? */
size_t
readtokens (FILE *stream,
- size_t projected_n_tokens,
- const char *delim,
- size_t n_delim,
- char ***tokens_out,
- size_t **token_lengths)
+ size_t projected_n_tokens,
+ const char *delim,
+ size_t n_delim,
+ char ***tokens_out,
+ size_t **token_lengths)
{
token_buffer tb, *token = &tb;
char **tokens;
@@ -165,7 +154,7 @@ readtokens (FILE *stream,
if (projected_n_tokens == 0)
projected_n_tokens = 64;
else
- projected_n_tokens++; /* add one for trailing NULL pointer */
+ projected_n_tokens++; /* add one for trailing NULL pointer */
sz = projected_n_tokens;
tokens = xnmalloc (sz, sizeof *tokens);
@@ -178,18 +167,18 @@ readtokens (FILE *stream,
char *tmp;
size_t token_length = readtoken (stream, delim, n_delim, token);
if (n_tokens >= sz)
- {
- tokens = x2nrealloc (tokens, &sz, sizeof *tokens);
- lengths = xnrealloc (lengths, sz, sizeof *lengths);
- }
+ {
+ tokens = x2nrealloc (tokens, &sz, sizeof *tokens);
+ lengths = xnrealloc (lengths, sz, sizeof *lengths);
+ }
if (token_length == (size_t) -1)
- {
- /* don't increment n_tokens for NULL entry */
- tokens[n_tokens] = NULL;
- lengths[n_tokens] = 0;
- break;
- }
+ {
+ /* don't increment n_tokens for NULL entry */
+ tokens[n_tokens] = NULL;
+ lengths[n_tokens] = 0;
+ break;
+ }
tmp = xnmalloc (token_length + 1, sizeof *tmp);
lengths[n_tokens] = token_length;
tokens[n_tokens] = memcpy (tmp, token->buffer, token_length + 1);
@@ -200,5 +189,7 @@ readtokens (FILE *stream,
*tokens_out = tokens;
if (token_lengths != NULL)
*token_lengths = lengths;
+ else
+ free (lengths);
return n_tokens;
}
diff --git a/lib/readtokens.h b/lib/readtokens.h
index 45a0c48..37cbb37 100644
--- a/lib/readtokens.h
+++ b/lib/readtokens.h
@@ -1,11 +1,12 @@
/* readtokens.h -- Functions for reading tokens from an input stream.
- Copyright (C) 1990, 1991, 1999, 2001-2004 Free Software Foundation, Inc.
+ Copyright (C) 1990-1991, 1999, 2001-2004, 2009-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
Written by Jim Meyering. */
@@ -34,10 +34,10 @@ void init_tokenbuffer (token_buffer *tokenbuffer);
size_t
readtoken (FILE *stream, const char *delim, size_t n_delim,
- token_buffer *tokenbuffer);
+ token_buffer *tokenbuffer);
size_t
readtokens (FILE *stream, size_t projected_n_tokens,
- const char *delim, size_t n_delim,
- char ***tokens_out, size_t **token_lengths);
+ const char *delim, size_t n_delim,
+ char ***tokens_out, size_t **token_lengths);
#endif /* not READTOKENS_H */
diff --git a/lib/readtokens0.c b/lib/readtokens0.c
index b60fd5a..89a15e4 100644
--- a/lib/readtokens0.c
+++ b/lib/readtokens0.c
@@ -1,11 +1,11 @@
/* readtokens0.c -- Read NUL-separated tokens from an input stream.
- Copyright (C) 2004, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2004, 2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
Written by Jim Meyering. */
@@ -71,23 +70,23 @@ readtokens0 (FILE *in, struct Tokens *t)
{
int c = fgetc (in);
if (c == EOF)
- {
- size_t len = obstack_object_size (&t->o_data);
- /* If the current object has nonzero length, then there
- was no NUL byte at EOF -- or maybe there was an error,
- in which case, we need to append a NUL byte to our buffer. */
- if (len)
- {
- obstack_1grow (&t->o_data, '\0');
- save_token (t);
- }
-
- break;
- }
+ {
+ size_t len = obstack_object_size (&t->o_data);
+ /* If the current object has nonzero length, then there
+ was no NUL byte at EOF -- or maybe there was an error,
+ in which case, we need to append a NUL byte to our buffer. */
+ if (len)
+ {
+ obstack_1grow (&t->o_data, '\0');
+ save_token (t);
+ }
+
+ break;
+ }
obstack_1grow (&t->o_data, c);
if (c == '\0')
- save_token (t);
+ save_token (t);
}
/* Add a NULL pointer at the end, in case the caller (like du)
diff --git a/lib/readtokens0.h b/lib/readtokens0.h
index 94c9a49..74e4e39 100644
--- a/lib/readtokens0.h
+++ b/lib/readtokens0.h
@@ -1,11 +1,11 @@
/* readtokens0.h -- read NUL-separated tokens from an input stream.
- Copyright (C) 2004 Free Software Foundation, Inc.
+ Copyright (C) 2004, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
Written by Jim Meyering. */
diff --git a/lib/readutmp.c b/lib/readutmp.c
index 73c7b53..d9b1efa 100644
--- a/lib/readutmp.c
+++ b/lib/readutmp.c
@@ -1,12 +1,11 @@
/* GNU's read utmp module.
- Copyright (C) 1992-2001, 2003, 2004, 2005, 2006 Free Software
- Foundation, Inc.
+ Copyright (C) 1992-2001, 2003-2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by jla; revised by djm */
@@ -32,6 +30,7 @@
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
+#include <stdint.h>
#include "xalloc.h"
@@ -39,10 +38,6 @@
# include "unlocked-io.h"
#endif
-#ifndef SIZE_MAX
-# define SIZE_MAX ((size_t) -1)
-#endif
-
/* Copy UT->ut_name into storage obtained from malloc. Then remove any
trailing spaces from the copy, NUL terminate it, and return the copy. */
@@ -66,7 +61,7 @@ extract_trimmed_name (const STRUCT_UTMP *ut)
/* Is the utmp entry U desired by the user who asked for OPTIONS? */
-static inline bool
+static bool
desirable_utmp_entry (STRUCT_UTMP const *u, int options)
{
bool user_proc = IS_USER_PROCESS (u);
@@ -74,8 +69,8 @@ desirable_utmp_entry (STRUCT_UTMP const *u, int options)
return false;
if ((options & READ_UTMP_CHECK_PIDS)
&& user_proc
- && (UT_PID (u) <= 0
- || (kill (UT_PID (u), 0) < 0 && errno == ESRCH)))
+ && 0 < UT_PID (u)
+ && (kill (UT_PID (u), 0) < 0 && errno == ESRCH))
return false;
return true;
}
@@ -91,7 +86,7 @@ desirable_utmp_entry (STRUCT_UTMP const *u, int options)
int
read_utmp (char const *file, size_t *n_entries, STRUCT_UTMP **utmp_buf,
- int options)
+ int options)
{
size_t n_read = 0;
size_t n_alloc = 0;
@@ -102,17 +97,17 @@ read_utmp (char const *file, size_t *n_entries, STRUCT_UTMP **utmp_buf,
Solaris' utmpname returns 1 upon success -- which is contrary
to what the GNU libc version does. In addition, older GNU libc
versions are actually void. */
- UTMP_NAME_FUNCTION (file);
+ UTMP_NAME_FUNCTION ((char *) file);
SET_UTMP_ENT ();
while ((u = GET_UTMP_ENT ()) != NULL)
if (desirable_utmp_entry (u, options))
{
- if (n_read == n_alloc)
- utmp = x2nrealloc (utmp, &n_alloc, sizeof *utmp);
+ if (n_read == n_alloc)
+ utmp = x2nrealloc (utmp, &n_alloc, sizeof *utmp);
- utmp[n_read++] = *u;
+ utmp[n_read++] = *u;
}
END_UTMP_ENT ();
@@ -127,7 +122,7 @@ read_utmp (char const *file, size_t *n_entries, STRUCT_UTMP **utmp_buf,
int
read_utmp (char const *file, size_t *n_entries, STRUCT_UTMP **utmp_buf,
- int options)
+ int options)
{
size_t n_read = 0;
size_t n_alloc = 0;
@@ -141,9 +136,9 @@ read_utmp (char const *file, size_t *n_entries, STRUCT_UTMP **utmp_buf,
for (;;)
{
if (n_read == n_alloc)
- utmp = x2nrealloc (utmp, &n_alloc, sizeof *utmp);
+ utmp = x2nrealloc (utmp, &n_alloc, sizeof *utmp);
if (fread (&utmp[n_read], sizeof utmp[n_read], 1, f) == 0)
- break;
+ break;
n_read += desirable_utmp_entry (&utmp[n_read], options);
}
diff --git a/lib/readutmp.h b/lib/readutmp.h
index 84cf117..8b09e2e 100644
--- a/lib/readutmp.h
+++ b/lib/readutmp.h
@@ -1,11 +1,11 @@
/* Declarations for GNU's read utmp module.
- Copyright (C) 1992-2007 Free Software Foundation, Inc.
+ Copyright (C) 1992-2007, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by jla; revised by djm */
@@ -48,6 +47,8 @@
# define END_UTMP_ENT endutxent
# ifdef HAVE_UTMPXNAME
# define UTMP_NAME_FUNCTION utmpxname
+# elif defined UTXDB_ACTIVE
+# define UTMP_NAME_FUNCTION(x) setutxdb (UTXDB_ACTIVE, x)
# endif
# if HAVE_STRUCT_UTMPX_UT_EXIT_E_TERMINATION
@@ -74,7 +75,7 @@
# include <utmp.h>
# if !HAVE_DECL_GETUTENT
- struct utmp *getutent();
+ struct utmp *getutent (void);
# endif
# define UTMP_STRUCT_NAME utmp
# define UT_TIME_MEMBER(UT_PTR) ((UT_PTR)->ut_time)
@@ -198,9 +199,9 @@ enum { UT_USER_SIZE = sizeof UT_USER ((STRUCT_UTMP *) 0) };
# define UT_TYPE_USER_PROCESS(U) 0
# endif
-# define IS_USER_PROCESS(U) \
- (UT_USER (U)[0] \
- && (UT_TYPE_USER_PROCESS (U) \
+# define IS_USER_PROCESS(U) \
+ (UT_USER (U)[0] \
+ && (UT_TYPE_USER_PROCESS (U) \
|| (UT_TYPE_NOT_DEFINED && UT_TIME_MEMBER (U) != 0)))
/* Options for read_utmp. */
@@ -212,6 +213,6 @@ enum
char *extract_trimmed_name (const STRUCT_UTMP *ut);
int read_utmp (char const *file, size_t *n_entries, STRUCT_UTMP **utmp_buf,
- int options);
+ int options);
#endif /* __READUTMP_H__ */
diff --git a/lib/realloc.c b/lib/realloc.c
index c1fe9e5..83cb44e 100644
--- a/lib/realloc.c
+++ b/lib/realloc.c
@@ -1,11 +1,12 @@
/* realloc() function that is glibc compatible.
- Copyright (C) 1997, 2003, 2004, 2006 Free Software Foundation, Inc.
+ Copyright (C) 1997, 2003-2004, 2006-2007, 2009-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,16 +14,31 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
-/* written by Jim Meyering */
+/* written by Jim Meyering and Bruno Haible */
+#define _GL_USE_STDLIB_ALLOC 1
#include <config.h>
-#undef realloc
+
+/* Only the AC_FUNC_REALLOC macro defines 'realloc' already in config.h. */
+#ifdef realloc
+# define NEED_REALLOC_GNU 1
+/* Whereas the gnulib module 'realloc-gnu' defines HAVE_REALLOC_GNU. */
+#elif GNULIB_REALLOC_GNU && !HAVE_REALLOC_GNU
+# define NEED_REALLOC_GNU 1
+#endif
+
+/* Infer the properties of the system's malloc function.
+ The gnulib module 'malloc-gnu' defines HAVE_MALLOC_GNU. */
+#if GNULIB_MALLOC_GNU && HAVE_MALLOC_GNU
+# define SYSTEM_MALLOC_GLIBC_COMPATIBLE 1
+#endif
#include <stdlib.h>
+#include <errno.h>
+
/* Change the size of an allocated block of memory P to N bytes,
with error checking. If N is zero, change it to 1. If P is NULL,
use malloc. */
@@ -30,6 +46,9 @@
void *
rpl_realloc (void *p, size_t n)
{
+ void *result;
+
+#if NEED_REALLOC_GNU
if (n == 0)
{
n = 1;
@@ -38,8 +57,23 @@ rpl_realloc (void *p, size_t n)
free (p);
p = NULL;
}
+#endif
if (p == NULL)
- return malloc (n);
- return realloc (p, n);
+ {
+#if GNULIB_REALLOC_GNU && !NEED_REALLOC_GNU && !SYSTEM_MALLOC_GLIBC_COMPATIBLE
+ if (n == 0)
+ n = 1;
+#endif
+ result = malloc (n);
+ }
+ else
+ result = realloc (p, n);
+
+#if !HAVE_REALLOC_POSIX
+ if (result == NULL)
+ errno = ENOMEM;
+#endif
+
+ return result;
}
diff --git a/lib/ref-add.sin b/lib/ref-add.sin
index bc5cc79..42d3ab0 100644
--- a/lib/ref-add.sin
+++ b/lib/ref-add.sin
@@ -1,10 +1,10 @@
# Add this package to a list of references stored in a text file.
#
-# Copyright (C) 2000 Free Software Foundation, Inc.
+# Copyright (C) 2000, 2009-2016 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 2, or (at your option)
+# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -13,8 +13,7 @@
# 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, write to the Free Software Foundation,
-# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+# with this program; if not, see <http://www.gnu.org/licenses/>.
#
# Written by Bruno Haible <haible@clisp.cons.org>.
#
diff --git a/lib/ref-del.sin b/lib/ref-del.sin
index e9301bf..c77b33b 100644
--- a/lib/ref-del.sin
+++ b/lib/ref-del.sin
@@ -1,10 +1,10 @@
# Remove this package from a list of references stored in a text file.
#
-# Copyright (C) 2000 Free Software Foundation, Inc.
+# Copyright (C) 2000, 2009-2016 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 2, or (at your option)
+# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
@@ -13,8 +13,7 @@
# 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, write to the Free Software Foundation,
-# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+# with this program; if not, see <http://www.gnu.org/licenses/>.
#
# Written by Bruno Haible <haible@clisp.cons.org>.
#
diff --git a/lib/regcomp.c b/lib/regcomp.c
index fe4d243..6b0ddea 100644
--- a/lib/regcomp.c
+++ b/lib/regcomp.c
@@ -1,21 +1,25 @@
/* Extended regular expression matching and search library.
- Copyright (C) 2002,2003,2004,2005,2006,2007 Free Software Foundation, Inc.
+ Copyright (C) 2002-2016 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Isamu Hasegawa <isamu@yamato.ibm.com>.
- 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 2, or (at your option)
- any later version.
+ The GNU C Library 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,
+ The GNU C Library 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.
+ 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ You should have received a copy of the GNU General Public
+ License along with the GNU C Library; if not, see
+ <http://www.gnu.org/licenses/>. */
+
+#ifdef _LIBC
+# include <locale/weight.h>
+#endif
static reg_errcode_t re_compile_internal (regex_t *preg, const char * pattern,
size_t length, reg_syntax_t syntax);
@@ -94,20 +98,20 @@ static reg_errcode_t build_charclass (RE_TRANSLATE_TYPE trans,
bitset_t sbcset,
re_charset_t *mbcset,
Idx *char_class_alloc,
- const unsigned char *class_name,
+ const char *class_name,
reg_syntax_t syntax);
#else /* not RE_ENABLE_I18N */
static reg_errcode_t build_equiv_class (bitset_t sbcset,
const unsigned char *name);
static reg_errcode_t build_charclass (RE_TRANSLATE_TYPE trans,
bitset_t sbcset,
- const unsigned char *class_name,
+ const char *class_name,
reg_syntax_t syntax);
#endif /* not RE_ENABLE_I18N */
static bin_tree_t *build_charclass_op (re_dfa_t *dfa,
RE_TRANSLATE_TYPE trans,
- const unsigned char *class_name,
- const unsigned char *extra,
+ const char *class_name,
+ const char *extra,
bool non_match, reg_errcode_t *err);
static bin_tree_t *create_tree (re_dfa_t *dfa,
bin_tree_t *left, bin_tree_t *right,
@@ -206,7 +210,7 @@ static const size_t __re_error_msgid_idx[] =
compiles PATTERN (of length LENGTH) and puts the result in BUFP.
Returns 0 if the pattern was valid, otherwise an error string.
- Assumes the `allocated' (and perhaps `buffer') and `translate' fields
+ Assumes the 'allocated' (and perhaps 'buffer') and 'translate' fields
are set in BUFP on entry. */
#ifdef _LIBC
@@ -241,7 +245,7 @@ re_compile_pattern (const char *pattern, size_t length,
weak_alias (__re_compile_pattern, re_compile_pattern)
#endif
-/* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
+/* Set by 're_set_syntax' to the current regexp syntax to recognize. Can
also be assigned to arbitrarily: each pattern buffer stores its own
syntax, so it can be changed between regex compilations. */
/* This has no initializer because initialized variables in Emacs
@@ -273,7 +277,7 @@ int
re_compile_fastmap (bufp)
struct re_pattern_buffer *bufp;
{
- re_dfa_t *dfa = (re_dfa_t *) bufp->buffer;
+ re_dfa_t *dfa = bufp->buffer;
char *fastmap = bufp->fastmap;
memset (fastmap, '\0', sizeof (char) * SBC_MAX);
@@ -292,7 +296,7 @@ weak_alias (__re_compile_fastmap, re_compile_fastmap)
#endif
static inline void
-__attribute ((always_inline))
+__attribute__ ((always_inline))
re_set_fastmap (char *fastmap, bool icase, int ch)
{
fastmap[ch] = 1;
@@ -307,7 +311,7 @@ static void
re_compile_fastmap_iter (regex_t *bufp, const re_dfastate_t *init_state,
char *fastmap)
{
- re_dfa_t *dfa = (re_dfa_t *) bufp->buffer;
+ re_dfa_t *dfa = bufp->buffer;
Idx node_cnt;
bool icase = (dfa->mb_cur_max == 1 && (bufp->syntax & RE_ICASE));
for (node_cnt = 0; node_cnt < init_state->nodes.nelem; ++node_cnt)
@@ -333,9 +337,9 @@ re_compile_fastmap_iter (regex_t *bufp, const re_dfastate_t *init_state,
&& dfa->nodes[node].mb_partial)
*p++ = dfa->nodes[node].opr.c;
memset (&state, '\0', sizeof (state));
- if (mbrtowc (&wc, (const char *) buf, p - buf,
- &state) == p - buf
- && (__wcrtomb ((char *) buf, towlower (wc), &state)
+ if (__mbrtowc (&wc, (const char *) buf, p - buf,
+ &state) == p - buf
+ && (__wcrtomb ((char *) buf, __towlower (wc), &state)
!= (size_t) -1))
re_set_fastmap (fastmap, false, buf[0]);
}
@@ -356,45 +360,65 @@ re_compile_fastmap_iter (regex_t *bufp, const re_dfastate_t *init_state,
#ifdef RE_ENABLE_I18N
else if (type == COMPLEX_BRACKET)
{
- Idx i;
re_charset_t *cset = dfa->nodes[node].opr.mbcset;
- if (cset->non_match || cset->ncoll_syms || cset->nequiv_classes
- || cset->nranges || cset->nchar_classes)
- {
+ Idx i;
+
# ifdef _LIBC
- if (_NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES) != 0)
+ /* See if we have to try all bytes which start multiple collation
+ elements.
+ e.g. In da_DK, we want to catch 'a' since "aa" is a valid
+ collation element, and don't catch 'b' since 'b' is
+ the only collation element which starts from 'b' (and
+ it is caught by SIMPLE_BRACKET). */
+ if (_NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES) != 0
+ && (cset->ncoll_syms || cset->nranges))
{
- /* In this case we want to catch the bytes which are
- the first byte of any collation elements.
- e.g. In da_DK, we want to catch 'a' since "aa"
- is a valid collation element, and don't catch
- 'b' since 'b' is the only collation element
- which starts from 'b'. */
const int32_t *table = (const int32_t *)
_NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB);
for (i = 0; i < SBC_MAX; ++i)
if (table[i] < 0)
re_set_fastmap (fastmap, icase, i);
}
-# else
- if (dfa->mb_cur_max > 1)
- for (i = 0; i < SBC_MAX; ++i)
- if (__btowc (i) == WEOF)
- re_set_fastmap (fastmap, icase, i);
-# endif /* not _LIBC */
+# endif /* _LIBC */
+
+ /* See if we have to start the match at all multibyte characters,
+ i.e. where we would not find an invalid sequence. This only
+ applies to multibyte character sets; for single byte character
+ sets, the SIMPLE_BRACKET again suffices. */
+ if (dfa->mb_cur_max > 1
+ && (cset->nchar_classes || cset->non_match || cset->nranges
+# ifdef _LIBC
+ || cset->nequiv_classes
+# endif /* _LIBC */
+ ))
+ {
+ unsigned char c = 0;
+ do
+ {
+ mbstate_t mbs;
+ memset (&mbs, 0, sizeof (mbs));
+ if (__mbrtowc (NULL, (char *) &c, 1, &mbs) == (size_t) -2)
+ re_set_fastmap (fastmap, false, (int) c);
+ }
+ while (++c != 0);
}
- for (i = 0; i < cset->nmbchars; ++i)
+
+ else
{
- char buf[256];
- mbstate_t state;
- memset (&state, '\0', sizeof (state));
- if (__wcrtomb (buf, cset->mbchars[i], &state) != (size_t) -1)
- re_set_fastmap (fastmap, icase, *(unsigned char *) buf);
- if ((bufp->syntax & RE_ICASE) && dfa->mb_cur_max > 1)
+ /* ... Else catch all bytes which can start the mbchars. */
+ for (i = 0; i < cset->nmbchars; ++i)
{
- if (__wcrtomb (buf, towlower (cset->mbchars[i]), &state)
- != (size_t) -1)
- re_set_fastmap (fastmap, false, *(unsigned char *) buf);
+ char buf[256];
+ mbstate_t state;
+ memset (&state, '\0', sizeof (state));
+ if (__wcrtomb (buf, cset->mbchars[i], &state) != (size_t) -1)
+ re_set_fastmap (fastmap, icase, *(unsigned char *) buf);
+ if ((bufp->syntax & RE_ICASE) && dfa->mb_cur_max > 1)
+ {
+ if (__wcrtomb (buf, __towlower (cset->mbchars[i]), &state)
+ != (size_t) -1)
+ re_set_fastmap (fastmap, false, *(unsigned char *) buf);
+ }
}
}
}
@@ -419,15 +443,15 @@ re_compile_fastmap_iter (regex_t *bufp, const re_dfastate_t *init_state,
PREG is a regex_t *. We do not expect any fields to be initialized,
since POSIX says we shouldn't. Thus, we set
- `buffer' to the compiled pattern;
- `used' to the length of the compiled pattern;
- `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
+ 'buffer' to the compiled pattern;
+ 'used' to the length of the compiled pattern;
+ 'syntax' to RE_SYNTAX_POSIX_EXTENDED if the
REG_EXTENDED bit in CFLAGS is set; otherwise, to
RE_SYNTAX_POSIX_BASIC;
- `newline_anchor' to REG_NEWLINE being set in CFLAGS;
- `fastmap' to an allocated space for the fastmap;
- `fastmap_accurate' to zero;
- `re_nsub' to the number of subexpressions in PATTERN.
+ 'newline_anchor' to REG_NEWLINE being set in CFLAGS;
+ 'fastmap' to an allocated space for the fastmap;
+ 'fastmap_accurate' to zero;
+ 're_nsub' to the number of subexpressions in PATTERN.
PATTERN is the address of the pattern string.
@@ -520,7 +544,7 @@ regerror (errcode, preg, errbuf, errbuf_size)
size_t errbuf_size;
#else /* size_t might promote */
size_t
-regerror (int errcode, const regex_t *_Restrict_ preg,
+regerror (int errcode, const regex_t *_Restrict_ preg _UNUSED_PARAMETER_,
char *_Restrict_ errbuf, size_t errbuf_size)
#endif
{
@@ -566,19 +590,23 @@ weak_alias (__regerror, regerror)
static const bitset_t utf8_sb_map =
{
/* Set the first 128 bits. */
-# if 4 * BITSET_WORD_BITS < ASCII_CHARS
-# error "bitset_word_t is narrower than 32 bits"
-# elif 3 * BITSET_WORD_BITS < ASCII_CHARS
+# if defined __GNUC__ && !defined __STRICT_ANSI__
+ [0 ... 0x80 / BITSET_WORD_BITS - 1] = BITSET_WORD_MAX
+# else
+# if 4 * BITSET_WORD_BITS < ASCII_CHARS
+# error "bitset_word_t is narrower than 32 bits"
+# elif 3 * BITSET_WORD_BITS < ASCII_CHARS
BITSET_WORD_MAX, BITSET_WORD_MAX, BITSET_WORD_MAX,
-# elif 2 * BITSET_WORD_BITS < ASCII_CHARS
+# elif 2 * BITSET_WORD_BITS < ASCII_CHARS
BITSET_WORD_MAX, BITSET_WORD_MAX,
-# elif 1 * BITSET_WORD_BITS < ASCII_CHARS
+# elif 1 * BITSET_WORD_BITS < ASCII_CHARS
BITSET_WORD_MAX,
-# endif
+# endif
(BITSET_WORD_MAX
>> (SBC_MAX % BITSET_WORD_BITS == 0
? 0
: BITSET_WORD_BITS - SBC_MAX % BITSET_WORD_BITS))
+# endif
};
#endif
@@ -615,7 +643,7 @@ free_dfa_content (re_dfa_t *dfa)
re_dfastate_t *state = entry->array[j];
free_state (state);
}
- re_free (entry->array);
+ re_free (entry->array);
}
re_free (dfa->state_table);
#ifdef RE_ENABLE_I18N
@@ -637,9 +665,12 @@ void
regfree (preg)
regex_t *preg;
{
- re_dfa_t *dfa = (re_dfa_t *) preg->buffer;
+ re_dfa_t *dfa = preg->buffer;
if (BE (dfa != NULL, 1))
- free_dfa_content (dfa);
+ {
+ lock_fini (dfa->lock);
+ free_dfa_content (dfa);
+ }
preg->buffer = NULL;
preg->allocated = 0;
@@ -698,7 +729,7 @@ re_comp (s)
+ __re_error_msgid_idx[(int) REG_ESPACE]);
}
- /* Since `re_exec' always passes NULL for the `regs' argument, we
+ /* Since 're_exec' always passes NULL for the 'regs' argument, we
don't need to initialize the pattern buffer fields which affect it. */
/* Match anchors at newlines. */
@@ -709,7 +740,7 @@ re_comp (s)
if (!ret)
return NULL;
- /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
+ /* Yes, we're discarding 'const' here if !HAVE_LIBINTL. */
return (char *) gettext (__re_error_msgid + __re_error_msgid_idx[(int) ret]);
}
@@ -744,7 +775,7 @@ re_compile_internal (regex_t *preg, const char * pattern, size_t length,
preg->regs_allocated = REGS_UNALLOCATED;
/* Initialize the dfa. */
- dfa = (re_dfa_t *) preg->buffer;
+ dfa = preg->buffer;
if (BE (preg->allocated < sizeof (re_dfa_t), 0))
{
/* If zero allocated, but buffer is non-null, try to realloc
@@ -755,11 +786,13 @@ re_compile_internal (regex_t *preg, const char * pattern, size_t length,
if (dfa == NULL)
return REG_ESPACE;
preg->allocated = sizeof (re_dfa_t);
- preg->buffer = (unsigned char *) dfa;
+ preg->buffer = dfa;
}
preg->used = sizeof (re_dfa_t);
err = init_dfa (dfa, length);
+ if (BE (err == REG_NOERROR && lock_init (dfa->lock) != 0, 0))
+ err = REG_ESPACE;
if (BE (err != REG_NOERROR, 0))
{
free_dfa_content (dfa);
@@ -773,15 +806,14 @@ re_compile_internal (regex_t *preg, const char * pattern, size_t length,
strncpy (dfa->re_str, pattern, length + 1);
#endif
- __libc_lock_init (dfa->lock);
-
err = re_string_construct (&regexp, pattern, length, preg->translate,
- syntax & RE_ICASE, dfa);
+ (syntax & RE_ICASE) != 0, dfa);
if (BE (err != REG_NOERROR, 0))
{
re_compile_internal_free_return:
free_workarea_compile (preg);
re_string_destruct (&regexp);
+ lock_fini (dfa->lock);
free_dfa_content (dfa);
preg->buffer = NULL;
preg->allocated = 0;
@@ -814,6 +846,7 @@ re_compile_internal (regex_t *preg, const char * pattern, size_t length,
if (BE (err != REG_NOERROR, 0))
{
+ lock_fini (dfa->lock);
free_dfa_content (dfa);
preg->buffer = NULL;
preg->allocated = 0;
@@ -829,6 +862,9 @@ static reg_errcode_t
init_dfa (re_dfa_t *dfa, size_t pat_len)
{
__re_size_t table_size;
+#ifndef _LIBC
+ const char *codeset_name;
+#endif
#ifdef RE_ENABLE_I18N
size_t max_i18n_object_size = MAX (sizeof (wchar_t), sizeof (wctype_t));
#else
@@ -850,7 +886,7 @@ init_dfa (re_dfa_t *dfa, size_t pat_len)
calculation below, and for similar doubling calculations
elsewhere. And it's <= rather than <, because some of the
doubling calculations add 1 afterwards. */
- if (BE (SIZE_MAX / max_object_size / 2 <= pat_len, 0))
+ if (BE (MIN (IDX_MAX, SIZE_MAX / max_object_size) / 2 <= pat_len, 0))
return REG_ESPACE;
dfa->nodes_alloc = pat_len + 1;
@@ -872,7 +908,11 @@ init_dfa (re_dfa_t *dfa, size_t pat_len)
dfa->map_notascii = (_NL_CURRENT_WORD (LC_CTYPE, _NL_CTYPE_MAP_TO_NONASCII)
!= 0);
#else
- if (strcmp (locale_charset (), "UTF-8") == 0)
+ codeset_name = nl_langinfo (CODESET);
+ if ((codeset_name[0] == 'U' || codeset_name[0] == 'u')
+ && (codeset_name[1] == 'T' || codeset_name[1] == 't')
+ && (codeset_name[2] == 'F' || codeset_name[2] == 'f')
+ && strcmp (codeset_name + 3 + (codeset_name[3] == '-'), "8") == 0)
dfa->is_utf8 = 1;
/* We check exhaustively in the loop below if this charset is a
@@ -922,9 +962,43 @@ static void
internal_function
init_word_char (re_dfa_t *dfa)
{
- int i, j, ch;
+ int i = 0;
+ int j;
+ int ch = 0;
dfa->word_ops_used = 1;
- for (i = 0, ch = 0; i < BITSET_WORDS; ++i)
+ if (BE (dfa->map_notascii == 0, 1))
+ {
+ bitset_word_t bits0 = 0x00000000;
+ bitset_word_t bits1 = 0x03ff0000;
+ bitset_word_t bits2 = 0x87fffffe;
+ bitset_word_t bits3 = 0x07fffffe;
+ if (BITSET_WORD_BITS == 64)
+ {
+ dfa->word_char[0] = bits1 << 31 << 1 | bits0;
+ dfa->word_char[1] = bits3 << 31 << 1 | bits2;
+ i = 2;
+ }
+ else if (BITSET_WORD_BITS == 32)
+ {
+ dfa->word_char[0] = bits0;
+ dfa->word_char[1] = bits1;
+ dfa->word_char[2] = bits2;
+ dfa->word_char[3] = bits3;
+ i = 4;
+ }
+ else
+ goto general_case;
+ ch = 128;
+
+ if (BE (dfa->is_utf8, 1))
+ {
+ memset (&dfa->word_char[i], '\0', (SBC_MAX - ch) / 8);
+ return;
+ }
+ }
+
+ general_case:
+ for (; i < BITSET_WORDS; ++i)
for (j = 0; j < BITSET_WORD_BITS; ++j, ++ch)
if (isalnum (ch) || ch == '_')
dfa->word_char[i] |= (bitset_word_t) 1 << j;
@@ -935,7 +1009,7 @@ init_word_char (re_dfa_t *dfa)
static void
free_workarea_compile (regex_t *preg)
{
- re_dfa_t *dfa = (re_dfa_t *) preg->buffer;
+ re_dfa_t *dfa = preg->buffer;
bin_tree_storage_t *storage, *next;
for (storage = dfa->str_tree_storage; storage; storage = next)
{
@@ -995,7 +1069,10 @@ create_initial_state (re_dfa_t *dfa)
Idx dest_idx = dfa->edests[node_idx].elems[0];
if (!re_node_set_contains (&init_nodes, dest_idx))
{
- re_node_set_merge (&init_nodes, dfa->eclosures + dest_idx);
+ reg_errcode_t merge_err
+ = re_node_set_merge (&init_nodes, dfa->eclosures + dest_idx);
+ if (merge_err != REG_NOERROR)
+ return merge_err;
i = 0;
}
}
@@ -1049,7 +1126,7 @@ optimize_utf8 (re_dfa_t *dfa)
mb_chars = true;
break;
case ANCHOR:
- switch (dfa->nodes[node].opr.idx)
+ switch (dfa->nodes[node].opr.ctx_type)
{
case LINE_FIRST:
case LINE_LAST:
@@ -1057,13 +1134,15 @@ optimize_utf8 (re_dfa_t *dfa)
case BUF_LAST:
break;
default:
- /* Word anchors etc. cannot be handled. */
+ /* Word anchors etc. cannot be handled. It's okay to test
+ opr.ctx_type since constraints (for all DFA nodes) are
+ created by ORing one or more opr.ctx_type values. */
return;
}
break;
case OP_PERIOD:
- has_period = true;
- break;
+ has_period = true;
+ break;
case OP_BACK_REF:
case OP_ALT:
case END_OF_RE:
@@ -1114,7 +1193,7 @@ optimize_utf8 (re_dfa_t *dfa)
static reg_errcode_t
analyze (regex_t *preg)
{
- re_dfa_t *dfa = (re_dfa_t *) preg->buffer;
+ re_dfa_t *dfa = preg->buffer;
reg_errcode_t ret;
/* Allocate arrays. */
@@ -1164,7 +1243,7 @@ analyze (regex_t *preg)
{
dfa->inveclosures = re_malloc (re_node_set, dfa->nodes_len);
if (BE (dfa->inveclosures == NULL, 0))
- return REG_ESPACE;
+ return REG_ESPACE;
ret = calc_inveclosure (dfa);
}
@@ -1186,16 +1265,16 @@ postorder (bin_tree_t *root, reg_errcode_t (fn (void *, bin_tree_t *)),
if that's the only child). */
while (node->left || node->right)
if (node->left)
- node = node->left;
- else
- node = node->right;
+ node = node->left;
+ else
+ node = node->right;
do
{
reg_errcode_t err = fn (extra, node);
if (BE (err != REG_NOERROR, 0))
return err;
- if (node->parent == NULL)
+ if (node->parent == NULL)
return REG_NOERROR;
prev = node;
node = node->parent;
@@ -1229,7 +1308,7 @@ preorder (bin_tree_t *root, reg_errcode_t (fn (void *, bin_tree_t *)),
prev = node;
node = node->parent;
if (!node)
- return REG_NOERROR;
+ return REG_NOERROR;
}
node = node->right;
}
@@ -1252,13 +1331,13 @@ optimize_subexps (void *extra, bin_tree_t *node)
}
else if (node->token.type == SUBEXP
- && node->left && node->left->token.type == SUBEXP)
+ && node->left && node->left->token.type == SUBEXP)
{
Idx other_idx = node->left->token.opr.idx;
node->left = node->left->left;
if (node->left)
- node->left->parent = node;
+ node->left->parent = node;
dfa->subexp_map[other_idx] = dfa->subexp_map[node->token.opr.idx];
if (other_idx < BITSET_WORD_BITS)
@@ -1295,7 +1374,7 @@ lower_subexps (void *extra, bin_tree_t *node)
static bin_tree_t *
lower_subexp (reg_errcode_t *err, regex_t *preg, bin_tree_t *node)
{
- re_dfa_t *dfa = (re_dfa_t *) preg->buffer;
+ re_dfa_t *dfa = preg->buffer;
bin_tree_t *body = node->left;
bin_tree_t *op, *cls, *tree1, *tree;
@@ -1343,14 +1422,16 @@ calc_first (void *extra, bin_tree_t *node)
node->first = node;
node->node_idx = re_dfa_add_node (dfa, node->token);
if (BE (node->node_idx == REG_MISSING, 0))
- return REG_ESPACE;
+ return REG_ESPACE;
+ if (node->token.type == ANCHOR)
+ dfa->nodes[node->node_idx].constraint = node->token.opr.ctx_type;
}
return REG_NOERROR;
}
/* Pass 2: compute NEXT on the tree. Preorder visit. */
static reg_errcode_t
-calc_next (void *extra, bin_tree_t *node)
+calc_next (void *extra _UNUSED_PARAMETER_, bin_tree_t *node)
{
switch (node->token.type)
{
@@ -1365,7 +1446,7 @@ calc_next (void *extra, bin_tree_t *node)
if (node->left)
node->left->next = node->next;
if (node->right)
- node->right->next = node->next;
+ node->right->next = node->next;
break;
}
return REG_NOERROR;
@@ -1416,7 +1497,7 @@ link_nfa_nodes (void *extra, bin_tree_t *node)
case OP_BACK_REF:
dfa->nexts[idx] = node->next->node_idx;
if (node->token.type == OP_BACK_REF)
- re_node_set_init_1 (dfa->edests + idx, dfa->nexts[idx]);
+ err = re_node_set_init_1 (dfa->edests + idx, dfa->nexts[idx]);
break;
default:
@@ -1473,21 +1554,17 @@ duplicate_node_closure (re_dfa_t *dfa, Idx top_org_node, Idx top_clone_node,
destination. */
org_dest = dfa->edests[org_node].elems[0];
re_node_set_empty (dfa->edests + clone_node);
- if (dfa->nodes[org_node].type == ANCHOR)
+ /* If the node is root_node itself, it means the epsilon closure
+ has a loop. Then tie it to the destination of the root_node. */
+ if (org_node == root_node && clone_node != org_node)
{
- /* In case of the node has another constraint, append it. */
- if (org_node == root_node && clone_node != org_node)
- {
- /* ...but if the node is root_node itself, it means the
- epsilon closure have a loop, then tie it to the
- destination of the root_node. */
- ok = re_node_set_insert (dfa->edests + clone_node, org_dest);
- if (BE (! ok, 0))
- return REG_ESPACE;
- break;
- }
- constraint |= dfa->nodes[org_node].opr.ctx_type;
+ ok = re_node_set_insert (dfa->edests + clone_node, org_dest);
+ if (BE (! ok, 0))
+ return REG_ESPACE;
+ break;
}
+ /* In case the node has another constraint, append it. */
+ constraint |= dfa->nodes[org_node].constraint;
clone_dest = duplicate_node (dfa, org_dest, constraint);
if (BE (clone_dest == REG_MISSING, 0))
return REG_ESPACE;
@@ -1505,7 +1582,7 @@ duplicate_node_closure (re_dfa_t *dfa, Idx top_org_node, Idx top_clone_node,
clone_dest = search_duplicated_node (dfa, org_dest, constraint);
if (clone_dest == REG_MISSING)
{
- /* There are no such a duplicated node, create a new one. */
+ /* There is no such duplicated node, create a new one. */
reg_errcode_t err;
clone_dest = duplicate_node (dfa, org_dest, constraint);
if (BE (clone_dest == REG_MISSING, 0))
@@ -1520,7 +1597,7 @@ duplicate_node_closure (re_dfa_t *dfa, Idx top_org_node, Idx top_clone_node,
}
else
{
- /* There are a duplicated node which satisfy the constraint,
+ /* There is a duplicated node which satisfies the constraint,
use it to avoid infinite loop. */
ok = re_node_set_insert (dfa->edests + clone_node, clone_dest);
if (BE (! ok, 0))
@@ -1569,8 +1646,7 @@ duplicate_node (re_dfa_t *dfa, Idx org_idx, unsigned int constraint)
if (BE (dup_idx != REG_MISSING, 1))
{
dfa->nodes[dup_idx].constraint = constraint;
- if (dfa->nodes[org_idx].type == ANCHOR)
- dfa->nodes[dup_idx].constraint |= dfa->nodes[org_idx].opr.ctx_type;
+ dfa->nodes[dup_idx].constraint |= dfa->nodes[org_idx].constraint;
dfa->nodes[dup_idx].duplicated = 1;
/* Store the index of the original node. */
@@ -1632,7 +1708,7 @@ calc_eclosure (re_dfa_t *dfa)
/* If we have already calculated, skip it. */
if (dfa->eclosures[node_idx].nelem != 0)
continue;
- /* Calculate epsilon closure of `node_idx'. */
+ /* Calculate epsilon closure of 'node_idx'. */
err = calc_eclosure_iter (&eclosure_elem, dfa, node_idx, true);
if (BE (err != REG_NOERROR, 0))
return err;
@@ -1652,12 +1728,10 @@ static reg_errcode_t
calc_eclosure_iter (re_node_set *new_set, re_dfa_t *dfa, Idx node, bool root)
{
reg_errcode_t err;
- unsigned int constraint;
Idx i;
- bool incomplete;
- bool ok;
re_node_set eclosure;
- incomplete = false;
+ bool ok;
+ bool incomplete = false;
err = re_node_set_alloc (&eclosure, dfa->edests[node].nelem + 1);
if (BE (err != REG_NOERROR, 0))
return err;
@@ -1666,15 +1740,14 @@ calc_eclosure_iter (re_node_set *new_set, re_dfa_t *dfa, Idx node, bool root)
We reference this value to avoid infinite loop. */
dfa->eclosures[node].nelem = REG_MISSING;
- constraint = ((dfa->nodes[node].type == ANCHOR)
- ? dfa->nodes[node].opr.ctx_type : 0);
- /* If the current node has constraints, duplicate all nodes.
- Since they must inherit the constraints. */
- if (constraint
+ /* If the current node has constraints, duplicate all nodes
+ since they must inherit the constraints. */
+ if (dfa->nodes[node].constraint
&& dfa->edests[node].nelem
&& !dfa->nodes[dfa->edests[node].elems[0]].duplicated)
{
- err = duplicate_node_closure (dfa, node, node, node, constraint);
+ err = duplicate_node_closure (dfa, node, node, node,
+ dfa->nodes[node].constraint);
if (BE (err != REG_NOERROR, 0))
return err;
}
@@ -1685,14 +1758,14 @@ calc_eclosure_iter (re_node_set *new_set, re_dfa_t *dfa, Idx node, bool root)
{
re_node_set eclosure_elem;
Idx edest = dfa->edests[node].elems[i];
- /* If calculating the epsilon closure of `edest' is in progress,
+ /* If calculating the epsilon closure of 'edest' is in progress,
return intermediate result. */
if (dfa->eclosures[edest].nelem == REG_MISSING)
{
incomplete = true;
continue;
}
- /* If we haven't calculated the epsilon closure of `edest' yet,
+ /* If we haven't calculated the epsilon closure of 'edest' yet,
calculate now. Otherwise use calculated epsilon closure. */
if (dfa->eclosures[edest].nelem == 0)
{
@@ -1702,9 +1775,11 @@ calc_eclosure_iter (re_node_set *new_set, re_dfa_t *dfa, Idx node, bool root)
}
else
eclosure_elem = dfa->eclosures[edest];
- /* Merge the epsilon closure of `edest'. */
- re_node_set_merge (&eclosure, &eclosure_elem);
- /* If the epsilon closure of `edest' is incomplete,
+ /* Merge the epsilon closure of 'edest'. */
+ err = re_node_set_merge (&eclosure, &eclosure_elem);
+ if (BE (err != REG_NOERROR, 0))
+ return err;
+ /* If the epsilon closure of 'edest' is incomplete,
the epsilon closure of this node is also incomplete. */
if (dfa->eclosures[edest].nelem == 0)
{
@@ -1713,7 +1788,7 @@ calc_eclosure_iter (re_node_set *new_set, re_dfa_t *dfa, Idx node, bool root)
}
}
- /* Epsilon closures include itself. */
+ /* An epsilon closure includes itself. */
ok = re_node_set_insert (&eclosure, node);
if (BE (! ok, 0))
return REG_ESPACE;
@@ -2066,7 +2141,7 @@ peek_token_bracket (re_token_t *token, re_string_t *input, reg_syntax_t syntax)
/* Entry point of the parser.
Parse the regular expression REGEXP and return the structure tree.
- If an error is occured, ERR is set by error code, and return NULL.
+ If an error occurs, ERR is set by error code, and return NULL.
This function build the following tree, from regular expression <reg_exp>:
CAT
/ \
@@ -2080,7 +2155,7 @@ static bin_tree_t *
parse (re_string_t *regexp, regex_t *preg, reg_syntax_t syntax,
reg_errcode_t *err)
{
- re_dfa_t *dfa = (re_dfa_t *) preg->buffer;
+ re_dfa_t *dfa = preg->buffer;
bin_tree_t *tree, *eor, *root;
re_token_t current_token;
dfa->syntax = syntax;
@@ -2108,14 +2183,15 @@ parse (re_string_t *regexp, regex_t *preg, reg_syntax_t syntax,
/ \
<branch1> <branch2>
- ALT means alternative, which represents the operator `|'. */
+ ALT means alternative, which represents the operator '|'. */
static bin_tree_t *
parse_reg_exp (re_string_t *regexp, regex_t *preg, re_token_t *token,
reg_syntax_t syntax, Idx nest, reg_errcode_t *err)
{
- re_dfa_t *dfa = (re_dfa_t *) preg->buffer;
+ re_dfa_t *dfa = preg->buffer;
bin_tree_t *tree, *branch = NULL;
+ bitset_word_t initial_bkref_map = dfa->completed_bkref_map;
tree = parse_branch (regexp, preg, token, syntax, nest, err);
if (BE (*err != REG_NOERROR && tree == NULL, 0))
return NULL;
@@ -2126,9 +2202,16 @@ parse_reg_exp (re_string_t *regexp, regex_t *preg, re_token_t *token,
if (token->type != OP_ALT && token->type != END_OF_RE
&& (nest == 0 || token->type != OP_CLOSE_SUBEXP))
{
+ bitset_word_t accumulated_bkref_map = dfa->completed_bkref_map;
+ dfa->completed_bkref_map = initial_bkref_map;
branch = parse_branch (regexp, preg, token, syntax, nest, err);
if (BE (*err != REG_NOERROR && branch == NULL, 0))
- return NULL;
+ {
+ if (tree != NULL)
+ postorder (tree, free_tree, NULL);
+ return NULL;
+ }
+ dfa->completed_bkref_map |= accumulated_bkref_map;
}
else
branch = NULL;
@@ -2156,7 +2239,7 @@ parse_branch (re_string_t *regexp, regex_t *preg, re_token_t *token,
reg_syntax_t syntax, Idx nest, reg_errcode_t *err)
{
bin_tree_t *tree, *expr;
- re_dfa_t *dfa = (re_dfa_t *) preg->buffer;
+ re_dfa_t *dfa = preg->buffer;
tree = parse_expression (regexp, preg, token, syntax, nest, err);
if (BE (*err != REG_NOERROR && tree == NULL, 0))
return NULL;
@@ -2167,16 +2250,21 @@ parse_branch (re_string_t *regexp, regex_t *preg, re_token_t *token,
expr = parse_expression (regexp, preg, token, syntax, nest, err);
if (BE (*err != REG_NOERROR && expr == NULL, 0))
{
+ if (tree != NULL)
+ postorder (tree, free_tree, NULL);
return NULL;
}
if (tree != NULL && expr != NULL)
{
- tree = create_tree (dfa, tree, expr, CONCAT);
- if (tree == NULL)
+ bin_tree_t *newtree = create_tree (dfa, tree, expr, CONCAT);
+ if (newtree == NULL)
{
+ postorder (expr, free_tree, NULL);
+ postorder (tree, free_tree, NULL);
*err = REG_ESPACE;
return NULL;
}
+ tree = newtree;
}
else if (tree == NULL)
tree = expr;
@@ -2195,7 +2283,7 @@ static bin_tree_t *
parse_expression (re_string_t *regexp, regex_t *preg, re_token_t *token,
reg_syntax_t syntax, Idx nest, reg_errcode_t *err)
{
- re_dfa_t *dfa = (re_dfa_t *) preg->buffer;
+ re_dfa_t *dfa = preg->buffer;
bin_tree_t *tree;
switch (token->type)
{
@@ -2300,7 +2388,7 @@ parse_expression (re_string_t *regexp, regex_t *preg, re_token_t *token,
&& dfa->word_ops_used == 0)
init_word_char (dfa);
if (token->opr.ctx_type == WORD_DELIM
- || token->opr.ctx_type == NOT_WORD_DELIM)
+ || token->opr.ctx_type == NOT_WORD_DELIM)
{
bin_tree_t *tree_first, *tree_last;
if (token->opr.ctx_type == WORD_DELIM)
@@ -2308,13 +2396,13 @@ parse_expression (re_string_t *regexp, regex_t *preg, re_token_t *token,
token->opr.ctx_type = WORD_FIRST;
tree_first = create_token_tree (dfa, NULL, NULL, token);
token->opr.ctx_type = WORD_LAST;
- }
- else
- {
+ }
+ else
+ {
token->opr.ctx_type = INSIDE_WORD;
tree_first = create_token_tree (dfa, NULL, NULL, token);
token->opr.ctx_type = INSIDE_NOTWORD;
- }
+ }
tree_last = create_token_tree (dfa, NULL, NULL, token);
tree = create_tree (dfa, tree_first, tree_last, OP_ALT);
if (BE (tree_first == NULL || tree_last == NULL || tree == NULL, 0))
@@ -2351,8 +2439,8 @@ parse_expression (re_string_t *regexp, regex_t *preg, re_token_t *token,
case OP_WORD:
case OP_NOTWORD:
tree = build_charclass_op (dfa, regexp->trans,
- (const unsigned char *) "alnum",
- (const unsigned char *) "_",
+ "alnum",
+ "_",
token->type == OP_NOTWORD, err);
if (BE (*err != REG_NOERROR && tree == NULL, 0))
return NULL;
@@ -2360,8 +2448,8 @@ parse_expression (re_string_t *regexp, regex_t *preg, re_token_t *token,
case OP_SPACE:
case OP_NOTSPACE:
tree = build_charclass_op (dfa, regexp->trans,
- (const unsigned char *) "space",
- (const unsigned char *) "",
+ "space",
+ "",
token->type == OP_NOTSPACE, err);
if (BE (*err != REG_NOERROR && tree == NULL, 0))
return NULL;
@@ -2384,14 +2472,22 @@ parse_expression (re_string_t *regexp, regex_t *preg, re_token_t *token,
while (token->type == OP_DUP_ASTERISK || token->type == OP_DUP_PLUS
|| token->type == OP_DUP_QUESTION || token->type == OP_OPEN_DUP_NUM)
{
- tree = parse_dup_op (tree, regexp, dfa, token, syntax, err);
- if (BE (*err != REG_NOERROR && tree == NULL, 0))
- return NULL;
+ bin_tree_t *dup_tree = parse_dup_op (tree, regexp, dfa, token,
+ syntax, err);
+ if (BE (*err != REG_NOERROR && dup_tree == NULL, 0))
+ {
+ if (tree != NULL)
+ postorder (tree, free_tree, NULL);
+ return NULL;
+ }
+ tree = dup_tree;
/* In BRE consecutive duplications are not allowed. */
if ((syntax & RE_CONTEXT_INVALID_DUP)
&& (token->type == OP_DUP_ASTERISK
|| token->type == OP_OPEN_DUP_NUM))
{
+ if (tree != NULL)
+ postorder (tree, free_tree, NULL);
*err = REG_BADRPT;
return NULL;
}
@@ -2411,7 +2507,7 @@ static bin_tree_t *
parse_sub_exp (re_string_t *regexp, regex_t *preg, re_token_t *token,
reg_syntax_t syntax, Idx nest, reg_errcode_t *err)
{
- re_dfa_t *dfa = (re_dfa_t *) preg->buffer;
+ re_dfa_t *dfa = preg->buffer;
bin_tree_t *tree;
size_t cur_nsub;
cur_nsub = preg->re_nsub++;
@@ -2425,7 +2521,11 @@ parse_sub_exp (re_string_t *regexp, regex_t *preg, re_token_t *token,
{
tree = parse_reg_exp (regexp, preg, token, syntax, nest, err);
if (BE (*err == REG_NOERROR && token->type != OP_CLOSE_SUBEXP, 0))
- *err = REG_EPAREN;
+ {
+ if (tree != NULL)
+ postorder (tree, free_tree, NULL);
+ *err = REG_EPAREN;
+ }
if (BE (*err != REG_NOERROR, 0))
return NULL;
}
@@ -2496,12 +2596,19 @@ parse_dup_op (bin_tree_t *elem, re_string_t *regexp, re_dfa_t *dfa,
return elem;
}
- if (BE (end != REG_MISSING && start > end, 0))
+ if (BE ((end != REG_MISSING && start > end)
+ || token->type != OP_CLOSE_DUP_NUM, 0))
{
/* First number greater than second. */
*err = REG_BADBR;
return NULL;
}
+
+ if (BE (RE_DUP_MAX < (end == REG_MISSING ? start : end), 0))
+ {
+ *err = REG_ESIZE;
+ return NULL;
+ }
}
else
{
@@ -2536,23 +2643,32 @@ parse_dup_op (bin_tree_t *elem, re_string_t *regexp, re_dfa_t *dfa,
/* Duplicate ELEM before it is marked optional. */
elem = duplicate_tree (elem, dfa);
+ if (BE (elem == NULL, 0))
+ goto parse_dup_op_espace;
old_tree = tree;
}
else
old_tree = NULL;
if (elem->token.type == SUBEXP)
- postorder (elem, mark_opt_subexp, (void *) (long) elem->token.opr.idx);
+ {
+ uintptr_t subidx = elem->token.opr.idx;
+ postorder (elem, mark_opt_subexp, (void *) subidx);
+ }
tree = create_tree (dfa, elem, NULL,
(end == REG_MISSING ? OP_DUP_ASTERISK : OP_ALT));
if (BE (tree == NULL, 0))
goto parse_dup_op_espace;
+/* From gnulib's "intprops.h":
+ True if the arithmetic type T is signed. */
+#define TYPE_SIGNED(t) (! ((t) 0 < (t) -1))
+
/* This loop is actually executed only when end != REG_MISSING,
to rewrite <re>{0,n} as (<re>(<re>...<re>?)?)?... We have
already created the start+1-th copy. */
- if ((Idx) -1 < 0 || end != REG_MISSING)
+ if (TYPE_SIGNED (Idx) || end != REG_MISSING)
for (i = start + 2; i <= end; ++i)
{
elem = duplicate_tree (elem, dfa);
@@ -2584,17 +2700,23 @@ parse_dup_op (bin_tree_t *elem, re_string_t *regexp, re_dfa_t *dfa,
Build the range expression which starts from START_ELEM, and ends
at END_ELEM. The result are written to MBCSET and SBCSET.
RANGE_ALLOC is the allocated size of mbcset->range_starts, and
- mbcset->range_ends, is a pointer argument sinse we may
+ mbcset->range_ends, is a pointer argument since we may
update it. */
static reg_errcode_t
internal_function
# ifdef RE_ENABLE_I18N
-build_range_exp (bitset_t sbcset, re_charset_t *mbcset, Idx *range_alloc,
- bracket_elem_t *start_elem, bracket_elem_t *end_elem)
+build_range_exp (const reg_syntax_t syntax,
+ bitset_t sbcset,
+ re_charset_t *mbcset,
+ Idx *range_alloc,
+ const bracket_elem_t *start_elem,
+ const bracket_elem_t *end_elem)
# else /* not RE_ENABLE_I18N */
-build_range_exp (bitset_t sbcset, bracket_elem_t *start_elem,
- bracket_elem_t *end_elem)
+build_range_exp (const reg_syntax_t syntax,
+ bitset_t sbcset,
+ const bracket_elem_t *start_elem,
+ const bracket_elem_t *end_elem)
# endif /* not RE_ENABLE_I18N */
{
unsigned int start_ch, end_ch;
@@ -2617,7 +2739,6 @@ build_range_exp (bitset_t sbcset, bracket_elem_t *start_elem,
wchar_t wc;
wint_t start_wc;
wint_t end_wc;
- wchar_t cmp_buf[6] = {L'\0', L'\0', L'\0', L'\0', L'\0', L'\0'};
start_ch = ((start_elem->type == SB_CHAR) ? start_elem->opr.ch
: ((start_elem->type == COLL_SYM) ? start_elem->opr.name[0]
@@ -2631,9 +2752,7 @@ build_range_exp (bitset_t sbcset, bracket_elem_t *start_elem,
? __btowc (end_ch) : end_elem->opr.wch);
if (start_wc == WEOF || end_wc == WEOF)
return REG_ECOLLATE;
- cmp_buf[0] = start_wc;
- cmp_buf[4] = end_wc;
- if (wcscoll (cmp_buf, cmp_buf + 4) > 0)
+ else if (BE ((syntax & RE_NO_EMPTY_RANGES) && start_wc > end_wc, 0))
return REG_ERANGE;
/* Got valid collation sequence values, add them as a new entry.
@@ -2643,9 +2762,9 @@ build_range_exp (bitset_t sbcset, bracket_elem_t *start_elem,
no MBCSET if dfa->mb_cur_max == 1. */
if (mbcset)
{
- /* Check the space of the arrays. */
- if (BE (*range_alloc == mbcset->nranges, 0))
- {
+ /* Check the space of the arrays. */
+ if (BE (*range_alloc == mbcset->nranges, 0))
+ {
/* There is not enough space, need realloc. */
wchar_t *new_array_start, *new_array_end;
Idx new_nranges;
@@ -2655,9 +2774,9 @@ build_range_exp (bitset_t sbcset, bracket_elem_t *start_elem,
/* Use realloc since mbcset->range_starts and mbcset->range_ends
are NULL if *range_alloc == 0. */
new_array_start = re_realloc (mbcset->range_starts, wchar_t,
- new_nranges);
+ new_nranges);
new_array_end = re_realloc (mbcset->range_ends, wchar_t,
- new_nranges);
+ new_nranges);
if (BE (new_array_start == NULL || new_array_end == NULL, 0))
return REG_ESPACE;
@@ -2665,18 +2784,16 @@ build_range_exp (bitset_t sbcset, bracket_elem_t *start_elem,
mbcset->range_starts = new_array_start;
mbcset->range_ends = new_array_end;
*range_alloc = new_nranges;
- }
+ }
- mbcset->range_starts[mbcset->nranges] = start_wc;
- mbcset->range_ends[mbcset->nranges++] = end_wc;
+ mbcset->range_starts[mbcset->nranges] = start_wc;
+ mbcset->range_ends[mbcset->nranges++] = end_wc;
}
/* Build the table for single byte characters. */
for (wc = 0; wc < SBC_MAX; ++wc)
{
- cmp_buf[2] = wc;
- if (wcscoll (cmp_buf, cmp_buf + 2) <= 0
- && wcscoll (cmp_buf + 2, cmp_buf + 4) <= 0)
+ if (start_wc <= wc && wc <= end_wc)
bitset_set (sbcset, wc);
}
}
@@ -2710,11 +2827,14 @@ build_range_exp (bitset_t sbcset, bracket_elem_t *start_elem,
static reg_errcode_t
internal_function
-build_collating_symbol (bitset_t sbcset,
# ifdef RE_ENABLE_I18N
- re_charset_t *mbcset, Idx *coll_sym_alloc,
-# endif
- const unsigned char *name)
+build_collating_symbol (bitset_t sbcset,
+ re_charset_t *mbcset _UNUSED_PARAMETER_,
+ Idx *coll_sym_alloc _UNUSED_PARAMETER_,
+ const unsigned char *name)
+# else /* not RE_ENABLE_I18N */
+build_collating_symbol (bitset_t sbcset, const unsigned char *name)
+# endif /* not RE_ENABLE_I18N */
{
size_t name_len = strlen ((const char *) name);
if (BE (name_len != 1, 0))
@@ -2742,52 +2862,40 @@ parse_bracket_exp (re_string_t *regexp, re_dfa_t *dfa, re_token_t *token,
const int32_t *symb_table;
const unsigned char *extra;
- /* Local function for parse_bracket_exp used in _LIBC environement.
- Seek the collating symbol entry correspondings to NAME.
- Return the index of the symbol in the SYMB_TABLE. */
+ /* Local function for parse_bracket_exp used in _LIBC environment.
+ Seek the collating symbol entry corresponding to NAME.
+ Return the index of the symbol in the SYMB_TABLE,
+ or -1 if not found. */
auto inline int32_t
- __attribute ((always_inline))
- seek_collating_symbol_entry (name, name_len)
- const unsigned char *name;
- size_t name_len;
+ __attribute__ ((always_inline))
+ seek_collating_symbol_entry (const unsigned char *name, size_t name_len)
{
- int32_t hash = elem_hash ((const char *) name, name_len);
- int32_t elem = hash % table_size;
- if (symb_table[2 * elem] != 0)
- {
- int32_t second = hash % (table_size - 2) + 1;
+ int32_t elem;
- do
- {
- /* First compare the hashing value. */
- if (symb_table[2 * elem] == hash
- /* Compare the length of the name. */
- && name_len == extra[symb_table[2 * elem + 1]]
- /* Compare the name. */
- && memcmp (name, &extra[symb_table[2 * elem + 1] + 1],
- name_len) == 0)
- {
- /* Yep, this is the entry. */
- break;
- }
-
- /* Next entry. */
- elem += second;
- }
- while (symb_table[2 * elem] != 0);
- }
- return elem;
+ for (elem = 0; elem < table_size; elem++)
+ if (symb_table[2 * elem] != 0)
+ {
+ int32_t idx = symb_table[2 * elem + 1];
+ /* Skip the name of collating element name. */
+ idx += 1 + extra[idx];
+ if (/* Compare the length of the name. */
+ name_len == extra[idx]
+ /* Compare the name. */
+ && memcmp (name, &extra[idx + 1], name_len) == 0)
+ /* Yep, this is the entry. */
+ return elem;
+ }
+ return -1;
}
- /* Local function for parse_bracket_exp used in _LIBC environement.
+ /* Local function for parse_bracket_exp used in _LIBC environment.
Look up the collation sequence value of BR_ELEM.
Return the value if succeeded, UINT_MAX otherwise. */
auto inline unsigned int
- __attribute ((always_inline))
- lookup_collation_sequence_value (br_elem)
- bracket_elem_t *br_elem;
+ __attribute__ ((always_inline))
+ lookup_collation_sequence_value (bracket_elem_t *br_elem)
{
if (br_elem->type == SB_CHAR)
{
@@ -2804,7 +2912,8 @@ parse_bracket_exp (re_string_t *regexp, re_dfa_t *dfa, re_token_t *token,
}
else if (br_elem->type == MB_CHAR)
{
- return __collseq_table_lookup (collseqwc, br_elem->opr.wch);
+ if (nrules != 0)
+ return __collseq_table_lookup (collseqwc, br_elem->opr.wch);
}
else if (br_elem->type == COLL_SYM)
{
@@ -2814,7 +2923,7 @@ parse_bracket_exp (re_string_t *regexp, re_dfa_t *dfa, re_token_t *token,
int32_t elem, idx;
elem = seek_collating_symbol_entry (br_elem->opr.name,
sym_name_len);
- if (symb_table[2 * elem] != 0)
+ if (elem != -1)
{
/* We found the entry. */
idx = symb_table[2 * elem + 1];
@@ -2832,7 +2941,7 @@ parse_bracket_exp (re_string_t *regexp, re_dfa_t *dfa, re_token_t *token,
/* Return the collation sequence value. */
return *(unsigned int *) (extra + idx);
}
- else if (symb_table[2 * elem] == 0 && sym_name_len == 1)
+ else if (sym_name_len == 1)
{
/* No valid character. Match it as a single byte
character. */
@@ -2845,20 +2954,17 @@ parse_bracket_exp (re_string_t *regexp, re_dfa_t *dfa, re_token_t *token,
return UINT_MAX;
}
- /* Local function for parse_bracket_exp used in _LIBC environement.
+ /* Local function for parse_bracket_exp used in _LIBC environment.
Build the range expression which starts from START_ELEM, and ends
at END_ELEM. The result are written to MBCSET and SBCSET.
RANGE_ALLOC is the allocated size of mbcset->range_starts, and
- mbcset->range_ends, is a pointer argument sinse we may
+ mbcset->range_ends, is a pointer argument since we may
update it. */
auto inline reg_errcode_t
- __attribute ((always_inline))
- build_range_exp (sbcset, mbcset, range_alloc, start_elem, end_elem)
- re_charset_t *mbcset;
- Idx *range_alloc;
- bitset_t sbcset;
- bracket_elem_t *start_elem, *end_elem;
+ __attribute__ ((always_inline))
+ build_range_exp (bitset_t sbcset, re_charset_t *mbcset, int *range_alloc,
+ bracket_elem_t *start_elem, bracket_elem_t *end_elem)
{
unsigned int ch;
uint32_t start_collseq;
@@ -2871,6 +2977,7 @@ parse_bracket_exp (re_string_t *regexp, re_dfa_t *dfa, re_token_t *token,
0))
return REG_ERANGE;
+ /* FIXME: Implement rational ranges here, too. */
start_collseq = lookup_collation_sequence_value (start_elem);
end_collseq = lookup_collation_sequence_value (end_elem);
/* Check start/end collation sequence values. */
@@ -2885,8 +2992,8 @@ parse_bracket_exp (re_string_t *regexp, re_dfa_t *dfa, re_token_t *token,
build below suffices. */
if (nrules > 0 || dfa->mb_cur_max > 1)
{
- /* Check the space of the arrays. */
- if (BE (*range_alloc == mbcset->nranges, 0))
+ /* Check the space of the arrays. */
+ if (BE (*range_alloc == mbcset->nranges, 0))
{
/* There is not enough space, need realloc. */
uint32_t *new_array_start;
@@ -2898,18 +3005,18 @@ parse_bracket_exp (re_string_t *regexp, re_dfa_t *dfa, re_token_t *token,
new_array_start = re_realloc (mbcset->range_starts, uint32_t,
new_nranges);
new_array_end = re_realloc (mbcset->range_ends, uint32_t,
- new_nranges);
+ new_nranges);
if (BE (new_array_start == NULL || new_array_end == NULL, 0))
- return REG_ESPACE;
+ return REG_ESPACE;
mbcset->range_starts = new_array_start;
mbcset->range_ends = new_array_end;
*range_alloc = new_nranges;
}
- mbcset->range_starts[mbcset->nranges] = start_collseq;
- mbcset->range_ends[mbcset->nranges++] = end_collseq;
+ mbcset->range_starts[mbcset->nranges] = start_collseq;
+ mbcset->range_ends[mbcset->nranges++] = end_collseq;
}
/* Build the table for single byte characters. */
@@ -2929,33 +3036,30 @@ parse_bracket_exp (re_string_t *regexp, re_dfa_t *dfa, re_token_t *token,
return REG_NOERROR;
}
- /* Local function for parse_bracket_exp used in _LIBC environement.
+ /* Local function for parse_bracket_exp used in _LIBC environment.
Build the collating element which is represented by NAME.
The result are written to MBCSET and SBCSET.
COLL_SYM_ALLOC is the allocated size of mbcset->coll_sym, is a
- pointer argument sinse we may update it. */
+ pointer argument since we may update it. */
auto inline reg_errcode_t
- __attribute ((always_inline))
- build_collating_symbol (sbcset, mbcset, coll_sym_alloc, name)
- re_charset_t *mbcset;
- Idx *coll_sym_alloc;
- bitset_t sbcset;
- const unsigned char *name;
+ __attribute__ ((always_inline))
+ build_collating_symbol (bitset_t sbcset, re_charset_t *mbcset,
+ Idx *coll_sym_alloc, const unsigned char *name)
{
int32_t elem, idx;
size_t name_len = strlen ((const char *) name);
if (nrules != 0)
{
elem = seek_collating_symbol_entry (name, name_len);
- if (symb_table[2 * elem] != 0)
+ if (elem != -1)
{
/* We found the entry. */
idx = symb_table[2 * elem + 1];
/* Skip the name of collating element name. */
idx += 1 + extra[idx];
}
- else if (symb_table[2 * elem] == 0 && name_len == 1)
+ else if (name_len == 1)
{
/* No valid character, treat it as a normal
character. */
@@ -3035,6 +3139,10 @@ parse_bracket_exp (re_string_t *regexp, re_dfa_t *dfa, re_token_t *token,
if (BE (sbcset == NULL, 0))
#endif /* RE_ENABLE_I18N */
{
+ re_free (sbcset);
+#ifdef RE_ENABLE_I18N
+ re_free (mbcset);
+#endif
*err = REG_ESPACE;
return NULL;
}
@@ -3077,6 +3185,7 @@ parse_bracket_exp (re_string_t *regexp, re_dfa_t *dfa, re_token_t *token,
re_token_t token2;
start_elem.opr.name = start_name_buf;
+ start_elem.type = COLL_SYM;
ret = parse_bracket_element (&start_elem, regexp, token, token_len, dfa,
syntax, first_round);
if (BE (ret != REG_NOERROR, 0))
@@ -3120,6 +3229,7 @@ parse_bracket_exp (re_string_t *regexp, re_dfa_t *dfa, re_token_t *token,
if (is_range_exp == true)
{
end_elem.opr.name = end_name_buf;
+ end_elem.type = COLL_SYM;
ret = parse_bracket_element (&end_elem, regexp, &token2, token_len2,
dfa, syntax, true);
if (BE (ret != REG_NOERROR, 0))
@@ -3135,11 +3245,11 @@ parse_bracket_exp (re_string_t *regexp, re_dfa_t *dfa, re_token_t *token,
&start_elem, &end_elem);
#else
# ifdef RE_ENABLE_I18N
- *err = build_range_exp (sbcset,
+ *err = build_range_exp (syntax, sbcset,
dfa->mb_cur_max > 1 ? mbcset : NULL,
&range_alloc, &start_elem, &end_elem);
# else
- *err = build_range_exp (sbcset, &start_elem, &end_elem);
+ *err = build_range_exp (syntax, sbcset, &start_elem, &end_elem);
# endif
#endif /* RE_ENABLE_I18N */
if (BE (*err != REG_NOERROR, 0))
@@ -3194,7 +3304,8 @@ parse_bracket_exp (re_string_t *regexp, re_dfa_t *dfa, re_token_t *token,
#ifdef RE_ENABLE_I18N
mbcset, &char_class_alloc,
#endif /* RE_ENABLE_I18N */
- start_elem.opr.name, syntax);
+ (const char *) start_elem.opr.name,
+ syntax);
if (BE (*err != REG_NOERROR, 0))
goto parse_bracket_exp_free_return;
break;
@@ -3243,17 +3354,17 @@ parse_bracket_exp (re_string_t *regexp, re_dfa_t *dfa, re_token_t *token,
of having both SIMPLE_BRACKET and COMPLEX_BRACKET. */
if (sbc_idx < BITSET_WORDS)
{
- /* Build a tree for simple bracket. */
- br_token.type = SIMPLE_BRACKET;
- br_token.opr.sbcset = sbcset;
- work_tree = create_token_tree (dfa, NULL, NULL, &br_token);
- if (BE (work_tree == NULL, 0))
- goto parse_bracket_exp_espace;
+ /* Build a tree for simple bracket. */
+ br_token.type = SIMPLE_BRACKET;
+ br_token.opr.sbcset = sbcset;
+ work_tree = create_token_tree (dfa, NULL, NULL, &br_token);
+ if (BE (work_tree == NULL, 0))
+ goto parse_bracket_exp_espace;
- /* Then join them by ALT node. */
- work_tree = create_tree (dfa, work_tree, mbc_tree, OP_ALT);
- if (BE (work_tree == NULL, 0))
- goto parse_bracket_exp_espace;
+ /* Then join them by ALT node. */
+ work_tree = create_tree (dfa, work_tree, mbc_tree, OP_ALT);
+ if (BE (work_tree == NULL, 0))
+ goto parse_bracket_exp_espace;
}
else
{
@@ -3272,7 +3383,7 @@ parse_bracket_exp (re_string_t *regexp, re_dfa_t *dfa, re_token_t *token,
br_token.opr.sbcset = sbcset;
work_tree = create_token_tree (dfa, NULL, NULL, &br_token);
if (BE (work_tree == NULL, 0))
- goto parse_bracket_exp_espace;
+ goto parse_bracket_exp_espace;
}
return work_tree;
@@ -3290,7 +3401,8 @@ parse_bracket_exp (re_string_t *regexp, re_dfa_t *dfa, re_token_t *token,
static reg_errcode_t
parse_bracket_element (bracket_elem_t *elem, re_string_t *regexp,
- re_token_t *token, int token_len, re_dfa_t *dfa,
+ re_token_t *token, int token_len,
+ re_dfa_t *dfa _UNUSED_PARAMETER_,
reg_syntax_t syntax, bool accept_hyphen)
{
#ifdef RE_ENABLE_I18N
@@ -3373,12 +3485,14 @@ parse_bracket_symbol (bracket_elem_t *elem, re_string_t *regexp,
Build the equivalence class which is represented by NAME.
The result are written to MBCSET and SBCSET.
EQUIV_CLASS_ALLOC is the allocated size of mbcset->equiv_classes,
- is a pointer argument sinse we may update it. */
+ is a pointer argument since we may update it. */
static reg_errcode_t
#ifdef RE_ENABLE_I18N
-build_equiv_class (bitset_t sbcset, re_charset_t *mbcset,
- Idx *equiv_class_alloc, const unsigned char *name)
+build_equiv_class (bitset_t sbcset,
+ re_charset_t *mbcset _UNUSED_PARAMETER_,
+ Idx *equiv_class_alloc _UNUSED_PARAMETER_,
+ const unsigned char *name)
#else /* not RE_ENABLE_I18N */
build_equiv_class (bitset_t sbcset, const unsigned char *name)
#endif /* not RE_ENABLE_I18N */
@@ -3393,8 +3507,6 @@ build_equiv_class (bitset_t sbcset, const unsigned char *name)
int32_t idx1, idx2;
unsigned int ch;
size_t len;
- /* This #include defines a local function! */
-# include <locale/weight.h>
/* Calculate the index for equivalence class. */
cp = name;
table = (const int32_t *) _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB);
@@ -3404,30 +3516,33 @@ build_equiv_class (bitset_t sbcset, const unsigned char *name)
_NL_COLLATE_EXTRAMB);
indirect = (const int32_t *) _NL_CURRENT (LC_COLLATE,
_NL_COLLATE_INDIRECTMB);
- idx1 = findidx (&cp);
- if (BE (idx1 == 0 || cp < name + strlen ((const char *) name), 0))
+ idx1 = findidx (table, indirect, extra, &cp, -1);
+ if (BE (idx1 == 0 || *cp != '\0', 0))
/* This isn't a valid character. */
return REG_ECOLLATE;
- /* Build single byte matcing table for this equivalence class. */
- char_buf[1] = (unsigned char) '\0';
- len = weights[idx1];
+ /* Build single byte matching table for this equivalence class. */
+ len = weights[idx1 & 0xffffff];
for (ch = 0; ch < SBC_MAX; ++ch)
{
char_buf[0] = ch;
cp = char_buf;
- idx2 = findidx (&cp);
+ idx2 = findidx (table, indirect, extra, &cp, 1);
/*
idx2 = table[ch];
*/
if (idx2 == 0)
/* This isn't a valid character. */
continue;
- if (len == weights[idx2])
+ /* Compare only if the length matches and the collation rule
+ index is the same. */
+ if (len == weights[idx2 & 0xffffff] && (idx1 >> 24) == (idx2 >> 24))
{
int cnt = 0;
+
while (cnt <= len &&
- weights[idx1 + 1 + cnt] == weights[idx2 + 1 + cnt])
+ weights[(idx1 & 0xffffff) + 1 + cnt]
+ == weights[(idx2 & 0xffffff) + 1 + cnt])
++cnt;
if (cnt > len)
@@ -3465,20 +3580,20 @@ build_equiv_class (bitset_t sbcset, const unsigned char *name)
Build the character class which is represented by NAME.
The result are written to MBCSET and SBCSET.
CHAR_CLASS_ALLOC is the allocated size of mbcset->char_classes,
- is a pointer argument sinse we may update it. */
+ is a pointer argument since we may update it. */
static reg_errcode_t
#ifdef RE_ENABLE_I18N
build_charclass (RE_TRANSLATE_TYPE trans, bitset_t sbcset,
re_charset_t *mbcset, Idx *char_class_alloc,
- const unsigned char *class_name, reg_syntax_t syntax)
+ const char *class_name, reg_syntax_t syntax)
#else /* not RE_ENABLE_I18N */
build_charclass (RE_TRANSLATE_TYPE trans, bitset_t sbcset,
- const unsigned char *class_name, reg_syntax_t syntax)
+ const char *class_name, reg_syntax_t syntax)
#endif /* not RE_ENABLE_I18N */
{
int i;
- const char *name = (const char *) class_name;
+ const char *name = class_name;
/* In case of REG_ICASE "upper" and "lower" match the both of
upper and lower cases. */
@@ -3552,8 +3667,8 @@ build_charclass (RE_TRANSLATE_TYPE trans, bitset_t sbcset,
static bin_tree_t *
build_charclass_op (re_dfa_t *dfa, RE_TRANSLATE_TYPE trans,
- const unsigned char *class_name,
- const unsigned char *extra, bool non_match,
+ const char *class_name,
+ const char *extra, bool non_match,
reg_errcode_t *err)
{
re_bitset_ptr_t sbcset;
@@ -3659,8 +3774,9 @@ build_charclass_op (re_dfa_t *dfa, RE_TRANSLATE_TYPE trans,
}
/* This is intended for the expressions like "a{1,3}".
- Fetch a number from `input', and return the number.
+ Fetch a number from 'input', and return the number.
Return REG_MISSING if the number field is empty like "{,1}".
+ Return RE_DUP_MAX + 1 if the number field is too large.
Return REG_ERROR if an error occurred. */
static Idx
@@ -3679,8 +3795,9 @@ fetch_number (re_string_t *input, re_token_t *token, reg_syntax_t syntax)
num = ((token->type != CHARACTER || c < '0' || '9' < c
|| num == REG_ERROR)
? REG_ERROR
- : ((num == REG_MISSING) ? c - '0' : num * 10 + c - '0'));
- num = (num > RE_DUP_MAX) ? REG_ERROR : num;
+ : num == REG_MISSING
+ ? c - '0'
+ : MIN (RE_DUP_MAX + 1, num * 10 + c - '0'));
}
return num;
}
@@ -3754,7 +3871,7 @@ create_token_tree (re_dfa_t *dfa, bin_tree_t *left, bin_tree_t *right,
static reg_errcode_t
mark_opt_subexp (void *extra, bin_tree_t *node)
{
- Idx idx = (Idx) (long) extra;
+ Idx idx = (uintptr_t) extra;
if (node->token.type == SUBEXP && node->token.opr.idx == idx)
node->token.opt_subexp = 1;
@@ -3779,7 +3896,7 @@ free_token (re_token_t *node)
and its children. */
static reg_errcode_t
-free_tree (void *extra, bin_tree_t *node)
+free_tree (void *extra _UNUSED_PARAMETER_, bin_tree_t *node)
{
free_token (&node->token);
return REG_NOERROR;
@@ -3823,7 +3940,7 @@ duplicate_tree (const bin_tree_t *root, re_dfa_t *dfa)
node = node->parent;
dup_node = dup_node->parent;
if (!node)
- return dup_root;
+ return dup_root;
}
node = node->right;
p_new = &dup_node->right;
diff --git a/lib/regex.c b/lib/regex.c
index d4eb726..432b465 100644
--- a/lib/regex.c
+++ b/lib/regex.c
@@ -1,25 +1,35 @@
/* Extended regular expression matching and search library.
- Copyright (C) 2002, 2003, 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2002-2016 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Isamu Hasegawa <isamu@yamato.ibm.com>.
- 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 2, or (at your option)
- any later version.
+ The GNU C Library 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,
+ The GNU C Library 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.
+ 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ You should have received a copy of the GNU General Public
+ License along with the GNU C Library; if not, see
+ <http://www.gnu.org/licenses/>. */
-#include <config.h>
+#ifndef _LIBC
+# include <config.h>
-/* Make sure noone compiles this code with a C++ compiler. */
+# if (__GNUC__ == 4 && 6 <= __GNUC_MINOR__) || 4 < __GNUC__
+# pragma GCC diagnostic ignored "-Wsuggest-attribute=pure"
+# endif
+# if (__GNUC__ == 4 && 3 <= __GNUC_MINOR__) || 4 < __GNUC__
+# pragma GCC diagnostic ignored "-Wold-style-definition"
+# pragma GCC diagnostic ignored "-Wtype-limits"
+# endif
+#endif
+
+/* Make sure no one compiles this code with a C++ compiler. */
#if defined __cplusplus && defined _LIBC
# error "This is C code, use a C compiler"
#endif
diff --git a/lib/regex.h b/lib/regex.h
index 7a79ca3..54db920 100644
--- a/lib/regex.h
+++ b/lib/regex.h
@@ -1,22 +1,22 @@
/* Definitions for data structures and routines for the regular
expression library.
- Copyright (C) 1985,1989-93,1995-98,2000,2001,2002,2003,2005,2006
- Free Software Foundation, Inc.
+ Copyright (C) 1985, 1989-1993, 1995-1998, 2000-2003, 2005-2016 Free Software
+ Foundation, Inc.
This file is part of the GNU C Library.
- 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 2, or (at your option)
- any later version.
+ The GNU C Library 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,
+ The GNU C Library 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.
+ 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ You should have received a copy of the GNU General Public
+ License along with the GNU C Library; if not, see
+ <http://www.gnu.org/licenses/>. */
#ifndef _REGEX_H
#define _REGEX_H 1
@@ -28,13 +28,10 @@
extern "C" {
#endif
-/* Define __USE_GNU_REGEX to declare GNU extensions that violate the
+/* Define __USE_GNU to declare GNU extensions that violate the
POSIX name space rules. */
-#undef __USE_GNU_REGEX
-#if (defined _GNU_SOURCE \
- || (!defined _POSIX_C_SOURCE && !defined _POSIX_SOURCE \
- && !defined _XOPEN_SOURCE))
-# define __USE_GNU_REGEX 1
+#ifdef _GNU_SOURCE
+# define __USE_GNU 1
#endif
#ifdef _REGEX_LARGE_OFFSETS
@@ -45,16 +42,6 @@ extern "C" {
supported within glibc itself, and glibc users should not define
_REGEX_LARGE_OFFSETS. */
-/* The type of the offset of a byte within a string.
- For historical reasons POSIX 1003.1-2004 requires that regoff_t be
- at least as wide as off_t. However, many common POSIX platforms set
- regoff_t to the more-sensible ssize_t and the Open Group has
- signalled its intention to change the requirement to be that
- regoff_t be at least as wide as ptrdiff_t and ssize_t; see XBD ERN
- 60 (2005-08-25). We don't know of any hosts where ssize_t or
- ptrdiff_t is wider than ssize_t, so ssize_t is safe. */
-typedef ssize_t regoff_t;
-
/* The type of nonnegative object indexes. Traditionally, GNU regex
uses 'int' for these. Code that uses __re_idx_t should work
regardless of whether the type is signed. */
@@ -69,10 +56,8 @@ typedef size_t __re_long_size_t;
#else
-/* Use types that are binary-compatible with the traditional GNU regex
- implementation, which mishandles strings longer than INT_MAX. */
-
-typedef int regoff_t;
+/* The traditional GNU regex implementation mishandles strings longer
+ than INT_MAX. */
typedef int __re_idx_t;
typedef unsigned int __re_size_t;
typedef unsigned long int __re_long_size_t;
@@ -93,8 +78,7 @@ typedef unsigned long int active_reg_t;
add or remove a bit, only one other definition need change. */
typedef unsigned long int reg_syntax_t;
-#ifdef __USE_GNU_REGEX
-
+#ifdef __USE_GNU
/* If this bit is not set, then \ inside a bracket expression is literal.
If set, then such a \ quotes the following character. */
# define RE_BACKSLASH_ESCAPE_IN_LISTS ((unsigned long int) 1)
@@ -113,10 +97,10 @@ typedef unsigned long int reg_syntax_t;
/* If this bit is set, then ^ and $ are always anchors (outside bracket
expressions, of course).
If this bit is not set, then it depends:
- ^ is an anchor if it is at the beginning of a regular
- expression or after an open-group or an alternation operator;
- $ is an anchor if it is at the end of a regular expression, or
- before a close-group or an alternation operator.
+ ^ is an anchor if it is at the beginning of a regular
+ expression or after an open-group or an alternation operator;
+ $ is an anchor if it is at the end of a regular expression, or
+ before a close-group or an alternation operator.
This bit could be (re)combined with RE_CONTEXT_INDEP_OPS, because
POSIX draft 11.2 says that * etc. in leading positions is undefined.
@@ -161,9 +145,9 @@ typedef unsigned long int reg_syntax_t;
If not set, newline is literal. */
# define RE_NEWLINE_ALT (RE_LIMITED_OPS << 1)
-/* If this bit is set, then `{...}' defines an interval, and \{ and \}
+/* If this bit is set, then '{...}' defines an interval, and \{ and \}
are literals.
- If not set, then `\{...\}' defines an interval. */
+ If not set, then '\{...\}' defines an interval. */
# define RE_NO_BK_BRACES (RE_NEWLINE_ALT << 1)
/* If this bit is set, (...) defines a group, and \( and \) are literals.
@@ -218,15 +202,14 @@ typedef unsigned long int reg_syntax_t;
whether ^ should be special. */
# define RE_CARET_ANCHORS_HERE (RE_ICASE << 1)
-/* If this bit is set, then \{ cannot be first in an bre or
- immediately after an alternation or begin-group operator. */
+/* If this bit is set, then \{ cannot be first in a regex or
+ immediately after an alternation, open-group or \} operator. */
# define RE_CONTEXT_INVALID_DUP (RE_CARET_ANCHORS_HERE << 1)
/* If this bit is set, then no_sub will be set to 1 during
re_compile_pattern. */
# define RE_NO_SUB (RE_CONTEXT_INVALID_DUP << 1)
-
-#endif /* defined __USE_GNU_REGEX */
+#endif
/* This global variable defines the particular regexp syntax to use (for
some interfaces). When a regexp is compiled, the syntax used is
@@ -234,7 +217,7 @@ typedef unsigned long int reg_syntax_t;
already-compiled regexps. */
extern reg_syntax_t re_syntax_options;
-#ifdef __USE_GNU_REGEX
+#ifdef __USE_GNU
/* Define combinations of the above bits for the standard possibilities.
(The [[[ comments delimit what gets put into the Texinfo file, so
don't delete them!) */
@@ -246,31 +229,31 @@ extern reg_syntax_t re_syntax_options;
| RE_NO_BK_PARENS | RE_NO_BK_REFS \
| RE_NO_BK_VBAR | RE_NO_EMPTY_RANGES \
| RE_DOT_NEWLINE | RE_CONTEXT_INDEP_ANCHORS \
+ | RE_CHAR_CLASSES \
| RE_UNMATCHED_RIGHT_PAREN_ORD | RE_NO_GNU_OPS)
# define RE_SYNTAX_GNU_AWK \
- ((RE_SYNTAX_POSIX_EXTENDED | RE_BACKSLASH_ESCAPE_IN_LISTS | RE_DEBUG) \
- & ~(RE_DOT_NOT_NULL | RE_INTERVALS | RE_CONTEXT_INDEP_OPS \
- | RE_CONTEXT_INVALID_OPS ))
+ ((RE_SYNTAX_POSIX_EXTENDED | RE_BACKSLASH_ESCAPE_IN_LISTS \
+ | RE_INVALID_INTERVAL_ORD) \
+ & ~(RE_DOT_NOT_NULL | RE_CONTEXT_INDEP_OPS \
+ | RE_CONTEXT_INVALID_OPS ))
# define RE_SYNTAX_POSIX_AWK \
(RE_SYNTAX_POSIX_EXTENDED | RE_BACKSLASH_ESCAPE_IN_LISTS \
- | RE_INTERVALS | RE_NO_GNU_OPS)
+ | RE_INTERVALS | RE_NO_GNU_OPS \
+ | RE_INVALID_INTERVAL_ORD)
# define RE_SYNTAX_GREP \
- (RE_BK_PLUS_QM | RE_CHAR_CLASSES \
- | RE_HAT_LISTS_NOT_NEWLINE | RE_INTERVALS \
- | RE_NEWLINE_ALT)
+ ((RE_SYNTAX_POSIX_BASIC | RE_NEWLINE_ALT) \
+ & ~(RE_CONTEXT_INVALID_DUP | RE_DOT_NOT_NULL))
# define RE_SYNTAX_EGREP \
- (RE_CHAR_CLASSES | RE_CONTEXT_INDEP_ANCHORS \
- | RE_CONTEXT_INDEP_OPS | RE_HAT_LISTS_NOT_NEWLINE \
- | RE_NEWLINE_ALT | RE_NO_BK_PARENS \
- | RE_NO_BK_VBAR)
+ ((RE_SYNTAX_POSIX_EXTENDED | RE_INVALID_INTERVAL_ORD | RE_NEWLINE_ALT) \
+ & ~(RE_CONTEXT_INVALID_OPS | RE_DOT_NOT_NULL))
+/* POSIX grep -E behavior is no longer incompatible with GNU. */
# define RE_SYNTAX_POSIX_EGREP \
- (RE_SYNTAX_EGREP | RE_INTERVALS | RE_NO_BK_BRACES \
- | RE_INVALID_INTERVAL_ORD)
+ RE_SYNTAX_EGREP
/* P1003.2/D11.2, section 4.20.7.1, lines 5078ff. */
# define RE_SYNTAX_ED RE_SYNTAX_POSIX_BASIC
@@ -306,13 +289,12 @@ extern reg_syntax_t re_syntax_options;
| RE_NO_BK_VBAR | RE_UNMATCHED_RIGHT_PAREN_ORD)
/* [[[end syntaxes]]] */
-#endif /* defined __USE_GNU_REGEX */
-
-#ifdef __USE_GNU_REGEX
-
/* Maximum number of duplicates an interval can allow. POSIX-conforming
systems might define this in <limits.h>, but we want our
value, so remove any previous define. */
+# ifdef _REGEX_INCLUDE_LIMITS_H
+# include <limits.h>
+# endif
# ifdef RE_DUP_MAX
# undef RE_DUP_MAX
# endif
@@ -320,16 +302,15 @@ extern reg_syntax_t re_syntax_options;
/* RE_DUP_MAX is 2**15 - 1 because an earlier implementation stored
the counter as a 2-byte signed integer. This is no longer true, so
RE_DUP_MAX could be increased to (INT_MAX / 10 - 1), or to
- ((SIZE_MAX - 2) / 10 - 1) if _REGEX_LARGE_OFFSETS is defined.
+ ((SIZE_MAX - 9) / 10) if _REGEX_LARGE_OFFSETS is defined.
However, there would be a huge performance problem if someone
actually used a pattern like a\{214748363\}, so RE_DUP_MAX retains
its historical value. */
# define RE_DUP_MAX (0x7fff)
-
-#endif /* defined __USE_GNU_REGEX */
+#endif
-/* POSIX `cflags' bits (i.e., information for `regcomp'). */
+/* POSIX 'cflags' bits (i.e., information for 'regcomp'). */
/* If this bit is set, then use extended regular expression syntax.
If not set, then use basic regular expression syntax. */
@@ -349,7 +330,7 @@ extern reg_syntax_t re_syntax_options;
#define REG_NOSUB (1 << 3)
-/* POSIX `eflags' bits (i.e., information for regexec). */
+/* POSIX 'eflags' bits (i.e., information for regexec). */
/* If this bit is set, then the beginning-of-line operator doesn't match
the beginning of the string (presumably because it's not the
@@ -367,7 +348,7 @@ extern reg_syntax_t re_syntax_options;
/* If any error codes are removed, changed, or added, update the
- `__re_error_msgid' table in regcomp.c. */
+ '__re_error_msgid' table in regcomp.c. */
typedef enum
{
@@ -392,11 +373,11 @@ typedef enum
/* Error codes we've added. */
_REG_EEND, /* Premature end. */
- _REG_ESIZE, /* Compiled pattern bigger than 2^16 bytes. */
+ _REG_ESIZE, /* Too large (e.g., repeat count too large). */
_REG_ERPAREN /* Unmatched ) or \); not returned from regcomp. */
} reg_errcode_t;
-#ifdef _XOPEN_SOURCE
+#if defined _XOPEN_SOURCE || defined __USE_XOPEN2K
# define REG_ENOSYS _REG_ENOSYS
#endif
#define REG_NOERROR _REG_NOERROR
@@ -417,126 +398,127 @@ typedef enum
#define REG_ESIZE _REG_ESIZE
#define REG_ERPAREN _REG_ERPAREN
-/* struct re_pattern_buffer normally uses member names like `buffer'
- that POSIX does not allow. In POSIX mode these members have names
- with leading `re_' (e.g., `re_buffer'). */
-#ifdef __USE_GNU_REGEX
-# define _REG_RE_NAME(id) id
-# define _REG_RM_NAME(id) id
-#else
-# define _REG_RE_NAME(id) re_##id
-# define _REG_RM_NAME(id) rm_##id
+/* This data structure represents a compiled pattern. Before calling
+ the pattern compiler, the fields 'buffer', 'allocated', 'fastmap',
+ and 'translate' can be set. After the pattern has been compiled,
+ the fields 're_nsub', 'not_bol' and 'not_eol' are available. All
+ other fields are private to the regex routines. */
+
+#ifndef RE_TRANSLATE_TYPE
+# define __RE_TRANSLATE_TYPE unsigned char *
+# ifdef __USE_GNU
+# define RE_TRANSLATE_TYPE __RE_TRANSLATE_TYPE
+# endif
#endif
-/* The user can specify the type of the re_translate member by
- defining the macro RE_TRANSLATE_TYPE, which defaults to unsigned
- char *. This pollutes the POSIX name space, so in POSIX mode just
- use unsigned char *. */
-#ifdef __USE_GNU_REGEX
-# ifndef RE_TRANSLATE_TYPE
-# define RE_TRANSLATE_TYPE unsigned char *
-# endif
-# define REG_TRANSLATE_TYPE RE_TRANSLATE_TYPE
+#ifdef __USE_GNU
+# define __REPB_PREFIX(name) name
#else
-# define REG_TRANSLATE_TYPE unsigned char *
+# define __REPB_PREFIX(name) __##name
#endif
-/* This data structure represents a compiled pattern. Before calling
- the pattern compiler, the fields `buffer', `allocated', `fastmap',
- `translate', and `no_sub' can be set. After the pattern has been
- compiled, the `re_nsub' field is available. All other fields are
- private to the regex routines. */
-
struct re_pattern_buffer
{
- /* Space that holds the compiled pattern. It is declared as
- `unsigned char *' because its elements are sometimes used as
- array indexes. */
- unsigned char *_REG_RE_NAME (buffer);
+ /* Space that holds the compiled pattern. The type
+ 'struct re_dfa_t' is private and is not declared here. */
+ struct re_dfa_t *__REPB_PREFIX(buffer);
- /* Number of bytes to which `buffer' points. */
- __re_long_size_t _REG_RE_NAME (allocated);
+ /* Number of bytes to which 'buffer' points. */
+ __re_long_size_t __REPB_PREFIX(allocated);
- /* Number of bytes actually used in `buffer'. */
- __re_long_size_t _REG_RE_NAME (used);
+ /* Number of bytes actually used in 'buffer'. */
+ __re_long_size_t __REPB_PREFIX(used);
/* Syntax setting with which the pattern was compiled. */
- reg_syntax_t _REG_RE_NAME (syntax);
+ reg_syntax_t __REPB_PREFIX(syntax);
/* Pointer to a fastmap, if any, otherwise zero. re_search uses the
fastmap, if there is one, to skip over impossible starting points
for matches. */
- char *_REG_RE_NAME (fastmap);
+ char *__REPB_PREFIX(fastmap);
/* Either a translate table to apply to all characters before
comparing them, or zero for no translation. The translation is
applied to a pattern when it is compiled and to a string when it
is matched. */
- REG_TRANSLATE_TYPE _REG_RE_NAME (translate);
+ __RE_TRANSLATE_TYPE __REPB_PREFIX(translate);
/* Number of subexpressions found by the compiler. */
size_t re_nsub;
/* Zero if this pattern cannot match the empty string, one else.
- Well, in truth it's used only in `re_search_2', to see whether or
+ Well, in truth it's used only in 're_search_2', to see whether or
not we should use the fastmap, so we don't set this absolutely
- perfectly; see `re_compile_fastmap' (the `duplicate' case). */
- unsigned int _REG_RE_NAME (can_be_null) : 1;
+ perfectly; see 're_compile_fastmap' (the "duplicate" case). */
+ unsigned __REPB_PREFIX(can_be_null) : 1;
- /* If REGS_UNALLOCATED, allocate space in the `regs' structure
- for `max (RE_NREGS, re_nsub + 1)' groups.
+ /* If REGS_UNALLOCATED, allocate space in the 'regs' structure
+ for 'max (RE_NREGS, re_nsub + 1)' groups.
If REGS_REALLOCATE, reallocate space if necessary.
If REGS_FIXED, use what's there. */
-#ifdef __USE_GNU_REGEX
+#ifdef __USE_GNU
# define REGS_UNALLOCATED 0
# define REGS_REALLOCATE 1
# define REGS_FIXED 2
#endif
- unsigned int _REG_RE_NAME (regs_allocated) : 2;
+ unsigned __REPB_PREFIX(regs_allocated) : 2;
- /* Set to zero when `regex_compile' compiles a pattern; set to one
- by `re_compile_fastmap' if it updates the fastmap. */
- unsigned int _REG_RE_NAME (fastmap_accurate) : 1;
+ /* Set to zero when 're_compile_pattern' compiles a pattern; set to
+ one by 're_compile_fastmap' if it updates the fastmap. */
+ unsigned __REPB_PREFIX(fastmap_accurate) : 1;
- /* If set, `re_match_2' does not return information about
+ /* If set, 're_match_2' does not return information about
subexpressions. */
- unsigned int _REG_RE_NAME (no_sub) : 1;
+ unsigned __REPB_PREFIX(no_sub) : 1;
/* If set, a beginning-of-line anchor doesn't match at the beginning
of the string. */
- unsigned int _REG_RE_NAME (not_bol) : 1;
+ unsigned __REPB_PREFIX(not_bol) : 1;
/* Similarly for an end-of-line anchor. */
- unsigned int _REG_RE_NAME (not_eol) : 1;
+ unsigned __REPB_PREFIX(not_eol) : 1;
/* If true, an anchor at a newline matches. */
- unsigned int _REG_RE_NAME (newline_anchor) : 1;
-
-/* [[[end pattern_buffer]]] */
+ unsigned __REPB_PREFIX(newline_anchor) : 1;
};
typedef struct re_pattern_buffer regex_t;
+/* Type for byte offsets within the string. POSIX mandates this. */
+#ifdef _REGEX_LARGE_OFFSETS
+/* POSIX 1003.1-2008 requires that regoff_t be at least as wide as
+ ptrdiff_t and ssize_t. We don't know of any hosts where ptrdiff_t
+ is wider than ssize_t, so ssize_t is safe. */
+typedef ssize_t regoff_t;
+#else
+/* The traditional GNU regex implementation mishandles strings longer
+ than INT_MAX. */
+typedef int regoff_t;
+#endif
+
+
+#ifdef __USE_GNU
/* This is the structure we store register match data in. See
regex.texinfo for a full description of what registers match. */
struct re_registers
{
- __re_size_t _REG_RM_NAME (num_regs);
- regoff_t *_REG_RM_NAME (start);
- regoff_t *_REG_RM_NAME (end);
+ __re_size_t num_regs;
+ regoff_t *start;
+ regoff_t *end;
};
-/* If `regs_allocated' is REGS_UNALLOCATED in the pattern buffer,
- `re_match_2' returns information about at least this many registers
- the first time a `regs' structure is passed. */
-#if !defined RE_NREGS && defined __USE_GNU_REGEX
-# define RE_NREGS 30
+/* If 'regs_allocated' is REGS_UNALLOCATED in the pattern buffer,
+ 're_match_2' returns information about at least this many registers
+ the first time a 'regs' structure is passed. */
+# ifndef RE_NREGS
+# define RE_NREGS 30
+# endif
#endif
/* POSIX specification for registers. Aside from the different names than
- `re_registers', POSIX uses an array of structures, instead of a
+ 're_registers', POSIX uses an array of structures, instead of a
structure of arrays. */
typedef struct
{
@@ -546,13 +528,19 @@ typedef struct
/* Declarations for routines. */
+#ifdef __USE_GNU
/* Sets the current default syntax to SYNTAX, and return the old syntax.
- You can also simply assign to the `re_syntax_options' variable. */
+ You can also simply assign to the 're_syntax_options' variable. */
extern reg_syntax_t re_set_syntax (reg_syntax_t __syntax);
/* Compile the regular expression PATTERN, with length LENGTH
- and syntax given by the global `re_syntax_options', into the buffer
- BUFFER. Return NULL if successful, and an error string if not. */
+ and syntax given by the global 're_syntax_options', into the buffer
+ BUFFER. Return NULL if successful, and an error string if not.
+
+ To free the allocated storage, you must call 'regfree' on BUFFER.
+ Note that the translate table must either have been initialised by
+ 'regcomp', with a malloc'ed value, or set to NULL before calling
+ 'regfree'. */
extern const char *re_compile_pattern (const char *__pattern, size_t __length,
struct re_pattern_buffer *__buffer);
@@ -574,7 +562,7 @@ extern regoff_t re_search (struct re_pattern_buffer *__buffer,
struct re_registers *__regs);
-/* Like `re_search', but search in the concatenation of STRING1 and
+/* Like 're_search', but search in the concatenation of STRING1 and
STRING2. Also, stop searching at index START + STOP. */
extern regoff_t re_search_2 (struct re_pattern_buffer *__buffer,
const char *__string1, __re_idx_t __length1,
@@ -584,14 +572,14 @@ extern regoff_t re_search_2 (struct re_pattern_buffer *__buffer,
__re_idx_t __stop);
-/* Like `re_search', but return how many characters in STRING the regexp
+/* Like 're_search', but return how many characters in STRING the regexp
in BUFFER matched, starting at position START. */
extern regoff_t re_match (struct re_pattern_buffer *__buffer,
const char *__string, __re_idx_t __length,
__re_idx_t __start, struct re_registers *__regs);
-/* Relates to `re_match' as `re_search_2' relates to `re_search'. */
+/* Relates to 're_match' as 're_search_2' relates to 're_search'. */
extern regoff_t re_match_2 (struct re_pattern_buffer *__buffer,
const char *__string1, __re_idx_t __length1,
const char *__string2, __re_idx_t __length2,
@@ -602,21 +590,22 @@ extern regoff_t re_match_2 (struct re_pattern_buffer *__buffer,
/* Set REGS to hold NUM_REGS registers, storing them in STARTS and
ENDS. Subsequent matches using BUFFER and REGS will use this memory
for recording register information. STARTS and ENDS must be
- allocated with malloc, and must each be at least `NUM_REGS * sizeof
+ allocated with malloc, and must each be at least 'NUM_REGS * sizeof
(regoff_t)' bytes long.
If NUM_REGS == 0, then subsequent matches should allocate their own
register data.
Unless this function is called, the first search or match using
- PATTERN_BUFFER will allocate its own register data, without
+ BUFFER will allocate its own register data, without
freeing the old data. */
extern void re_set_registers (struct re_pattern_buffer *__buffer,
struct re_registers *__regs,
__re_size_t __num_regs,
regoff_t *__starts, regoff_t *__ends);
+#endif /* Use GNU */
-#if defined _REGEX_RE_COMP || defined _LIBC
+#if defined _REGEX_RE_COMP || (defined _LIBC && defined __USE_MISC)
# ifndef _CRAY
/* 4.2 bsd compatibility. */
extern char *re_comp (const char *);
@@ -644,7 +633,7 @@ extern int re_exec (const char *);
#ifndef _Restrict_arr_
# if ((199901L <= __STDC_VERSION__ \
|| ((3 < __GNUC__ || (3 == __GNUC__ && 1 <= __GNUC_MINOR__)) \
- && !__STRICT_ANSI__)) \
+ && !defined __STRICT_ANSI__)) \
&& !defined __GNUG__)
# define _Restrict_arr_ _Restrict_
# else
diff --git a/lib/regex_internal.c b/lib/regex_internal.c
index 2129888..2ad17d8 100644
--- a/lib/regex_internal.c
+++ b/lib/regex_internal.c
@@ -1,23 +1,24 @@
/* Extended regular expression matching and search library.
- Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007 Free Software
- Foundation, Inc.
+ Copyright (C) 2002-2016 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Isamu Hasegawa <isamu@yamato.ibm.com>.
- 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 2, or (at your option)
- any later version.
+ The GNU C Library 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,
+ The GNU C Library 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.
+ 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ You should have received a copy of the GNU General Public
+ License along with the GNU C Library; if not, see
+ <http://www.gnu.org/licenses/>. */
+#include "verify.h"
+#include "intprops.h"
static void re_string_construct_common (const char *str, Idx len,
re_string_t *pstr,
RE_TRANSLATE_TYPE trans, bool icase,
@@ -36,7 +37,7 @@ static re_dfastate_t *create_cd_newstate (const re_dfa_t *dfa,
re_string_reconstruct before using the object. */
static reg_errcode_t
-internal_function
+internal_function __attribute_warn_unused_result__
re_string_allocate (re_string_t *pstr, const char *str, Idx len, Idx init_len,
RE_TRANSLATE_TYPE trans, bool icase, const re_dfa_t *dfa)
{
@@ -64,7 +65,7 @@ re_string_allocate (re_string_t *pstr, const char *str, Idx len, Idx init_len,
/* This function allocate the buffers, and initialize them. */
static reg_errcode_t
-internal_function
+internal_function __attribute_warn_unused_result__
re_string_construct (re_string_t *pstr, const char *str, Idx len,
RE_TRANSLATE_TYPE trans, bool icase, const re_dfa_t *dfa)
{
@@ -127,7 +128,7 @@ re_string_construct (re_string_t *pstr, const char *str, Idx len,
/* Helper functions for re_string_allocate, and re_string_construct. */
static reg_errcode_t
-internal_function
+internal_function __attribute_warn_unused_result__
re_string_realloc_buffers (re_string_t *pstr, Idx new_buf_len)
{
#ifdef RE_ENABLE_I18N
@@ -135,9 +136,9 @@ re_string_realloc_buffers (re_string_t *pstr, Idx new_buf_len)
{
wint_t *new_wcs;
- /* Avoid overflow. */
- size_t max_object_size = MAX (sizeof (wint_t), sizeof (Idx));
- if (BE (SIZE_MAX / max_object_size < new_buf_len, 0))
+ /* Avoid overflow in realloc. */
+ const size_t max_object_size = MAX (sizeof (wint_t), sizeof (Idx));
+ if (BE (MIN (IDX_MAX, SIZE_MAX / max_object_size) < new_buf_len, 0))
return REG_ESPACE;
new_wcs = re_realloc (pstr->wcs, wint_t, new_buf_len);
@@ -236,14 +237,9 @@ build_wcs_buffer (re_string_t *pstr)
}
else
p = (const char *) pstr->raw_mbs + pstr->raw_mbs_idx + byte_idx;
- mbclen = mbrtowc (&wc, p, remain_len, &pstr->cur_state);
- if (BE (mbclen == (size_t) -2, 0))
- {
- /* The buffer doesn't have enough space, finish to build. */
- pstr->cur_state = prev_st;
- break;
- }
- else if (BE (mbclen == (size_t) -1 || mbclen == 0, 0))
+ mbclen = __mbrtowc (&wc, p, remain_len, &pstr->cur_state);
+ if (BE (mbclen == (size_t) -1 || mbclen == 0
+ || (mbclen == (size_t) -2 && pstr->bufs_len >= pstr->len), 0))
{
/* We treat these cases as a singlebyte character. */
mbclen = 1;
@@ -252,6 +248,12 @@ build_wcs_buffer (re_string_t *pstr)
wc = pstr->trans[wc];
pstr->cur_state = prev_st;
}
+ else if (BE (mbclen == (size_t) -2, 0))
+ {
+ /* The buffer doesn't have enough space, finish to build. */
+ pstr->cur_state = prev_st;
+ break;
+ }
/* Write wide character and padding. */
pstr->wcs[byte_idx++] = wc;
@@ -267,7 +269,7 @@ build_wcs_buffer (re_string_t *pstr)
but for REG_ICASE. */
static reg_errcode_t
-internal_function
+internal_function __attribute_warn_unused_result__
build_wcs_upper_buffer (re_string_t *pstr)
{
mbstate_t prev_st;
@@ -306,18 +308,17 @@ build_wcs_upper_buffer (re_string_t *pstr)
remain_len = end_idx - byte_idx;
prev_st = pstr->cur_state;
- mbclen = mbrtowc (&wc,
- ((const char *) pstr->raw_mbs + pstr->raw_mbs_idx
- + byte_idx), remain_len, &pstr->cur_state);
+ mbclen = __mbrtowc (&wc,
+ ((const char *) pstr->raw_mbs + pstr->raw_mbs_idx
+ + byte_idx), remain_len, &pstr->cur_state);
if (BE (mbclen < (size_t) -2, 1))
{
- wchar_t wcu = wc;
- if (iswlower (wc))
+ wchar_t wcu = __towupper (wc);
+ if (wcu != wc)
{
size_t mbcdlen;
- wcu = towupper (wc);
- mbcdlen = wcrtomb (buf, wcu, &prev_st);
+ mbcdlen = __wcrtomb (buf, wcu, &prev_st);
if (BE (mbclen == mbcdlen, 1))
memcpy (pstr->mbs + byte_idx, buf, mbclen);
else
@@ -334,9 +335,11 @@ build_wcs_upper_buffer (re_string_t *pstr)
for (remain_len = byte_idx + mbclen - 1; byte_idx < remain_len ;)
pstr->wcs[byte_idx++] = WEOF;
}
- else if (mbclen == (size_t) -1 || mbclen == 0)
+ else if (mbclen == (size_t) -1 || mbclen == 0
+ || (mbclen == (size_t) -2 && pstr->bufs_len >= pstr->len))
{
- /* It is an invalid character or '\0'. Just use the byte. */
+ /* It is an invalid character, an incomplete character
+ at the end of the string, or '\0'. Just use the byte. */
int ch = pstr->raw_mbs[pstr->raw_mbs_idx + byte_idx];
pstr->mbs[byte_idx] = ch;
/* And also cast it to wide char. */
@@ -376,15 +379,14 @@ build_wcs_upper_buffer (re_string_t *pstr)
}
else
p = (const char *) pstr->raw_mbs + pstr->raw_mbs_idx + src_idx;
- mbclen = mbrtowc (&wc, p, remain_len, &pstr->cur_state);
+ mbclen = __mbrtowc (&wc, p, remain_len, &pstr->cur_state);
if (BE (mbclen < (size_t) -2, 1))
{
- wchar_t wcu = wc;
- if (iswlower (wc))
+ wchar_t wcu = __towupper (wc);
+ if (wcu != wc)
{
size_t mbcdlen;
- wcu = towupper (wc);
mbcdlen = wcrtomb ((char *) buf, wcu, &prev_st);
if (BE (mbclen == mbcdlen, 1))
memcpy (pstr->mbs + byte_idx, buf, mbclen);
@@ -430,8 +432,8 @@ build_wcs_upper_buffer (re_string_t *pstr)
src_idx += mbclen;
continue;
}
- else
- memcpy (pstr->mbs + byte_idx, p, mbclen);
+ else
+ memcpy (pstr->mbs + byte_idx, p, mbclen);
}
else
memcpy (pstr->mbs + byte_idx, p, mbclen);
@@ -449,7 +451,8 @@ build_wcs_upper_buffer (re_string_t *pstr)
for (remain_len = byte_idx + mbclen - 1; byte_idx < remain_len ;)
pstr->wcs[byte_idx++] = WEOF;
}
- else if (mbclen == (size_t) -1 || mbclen == 0)
+ else if (mbclen == (size_t) -1 || mbclen == 0
+ || (mbclen == (size_t) -2 && pstr->bufs_len >= pstr->len))
{
/* It is an invalid character or '\0'. Just use the byte. */
int ch = pstr->raw_mbs[pstr->raw_mbs_idx + src_idx];
@@ -496,11 +499,10 @@ re_string_skip_chars (re_string_t *pstr, Idx new_raw_idx, wint_t *last_wc)
rawbuf_idx < new_raw_idx;)
{
wchar_t wc2;
- Idx remain_len;
- remain_len = pstr->len - rawbuf_idx;
+ Idx remain_len = pstr->raw_len - rawbuf_idx;
prev_st = pstr->cur_state;
- mbclen = mbrtowc (&wc2, (const char *) pstr->raw_mbs + rawbuf_idx,
- remain_len, &pstr->cur_state);
+ mbclen = __mbrtowc (&wc2, (const char *) pstr->raw_mbs + rawbuf_idx,
+ remain_len, &pstr->cur_state);
if (BE (mbclen == (size_t) -2 || mbclen == (size_t) -1 || mbclen == 0, 0))
{
/* We treat these cases as a single byte character. */
@@ -536,10 +538,7 @@ build_upper_buffer (re_string_t *pstr)
int ch = pstr->raw_mbs[pstr->raw_mbs_idx + char_idx];
if (BE (pstr->trans != NULL, 0))
ch = pstr->trans[ch];
- if (islower (ch))
- pstr->mbs[char_idx] = toupper (ch);
- else
- pstr->mbs[char_idx] = ch;
+ pstr->mbs[char_idx] = toupper (ch);
}
pstr->valid_len = char_idx;
pstr->valid_raw_len = char_idx;
@@ -569,7 +568,7 @@ re_string_translate_buffer (re_string_t *pstr)
convert to upper case in case of REG_ICASE, apply translation. */
static reg_errcode_t
-internal_function
+internal_function __attribute_warn_unused_result__
re_string_reconstruct (re_string_t *pstr, Idx idx, int eflags)
{
Idx offset;
@@ -680,17 +679,17 @@ re_string_reconstruct (re_string_t *pstr, Idx idx, int eflags)
pstr->valid_len - offset);
pstr->valid_len -= offset;
pstr->valid_raw_len -= offset;
-#if DEBUG
+#if defined DEBUG && DEBUG
assert (pstr->valid_len > 0);
#endif
}
}
else
{
+#ifdef RE_ENABLE_I18N
/* No, skip all characters until IDX. */
Idx prev_valid_len = pstr->valid_len;
-#ifdef RE_ENABLE_I18N
if (BE (pstr->offsets_needed, 0))
{
pstr->len = pstr->raw_len - idx + offset;
@@ -736,17 +735,19 @@ re_string_reconstruct (re_string_t *pstr, Idx idx, int eflags)
unsigned char buf[6];
size_t mbclen;
+ const unsigned char *pp = p;
if (BE (pstr->trans != NULL, 0))
{
int i = mlen < 6 ? mlen : 6;
while (--i >= 0)
buf[i] = pstr->trans[p[i]];
+ pp = buf;
}
/* XXX Don't use mbrtowc, we know which conversion
to use (UTF-8 -> UCS4). */
memset (&cur_state, 0, sizeof (cur_state));
- mbclen = mbrtowc (&wc2, (const char *) p, mlen,
- &cur_state);
+ mbclen = __mbrtowc (&wc2, (const char *) pp, mlen,
+ &cur_state);
if (raw + offset - p <= mbclen
&& mbclen < (size_t) -2)
{
@@ -830,7 +831,7 @@ re_string_reconstruct (re_string_t *pstr, Idx idx, int eflags)
}
static unsigned char
-internal_function __attribute ((pure))
+internal_function __attribute__ ((pure))
re_string_peek_byte_case (const re_string_t *pstr, Idx idx)
{
int ch;
@@ -867,7 +868,7 @@ re_string_peek_byte_case (const re_string_t *pstr, Idx idx)
}
static unsigned char
-internal_function __attribute ((pure))
+internal_function
re_string_fetch_byte_case (re_string_t *pstr)
{
if (BE (!pstr->mbs_allocated, 1))
@@ -937,7 +938,7 @@ re_string_context_at (const re_string_t *input, Idx idx, int eflags)
Idx wc_idx = idx;
while(input->wcs[wc_idx] == WEOF)
{
-#ifdef DEBUG
+#if defined DEBUG && DEBUG
/* It must not happen. */
assert (REG_VALID_INDEX (wc_idx));
#endif
@@ -964,19 +965,19 @@ re_string_context_at (const re_string_t *input, Idx idx, int eflags)
/* Functions for set operation. */
static reg_errcode_t
-internal_function
+internal_function __attribute_warn_unused_result__
re_node_set_alloc (re_node_set *set, Idx size)
{
set->alloc = size;
set->nelem = 0;
set->elems = re_malloc (Idx, size);
- if (BE (set->elems == NULL, 0))
+ if (BE (set->elems == NULL, 0) && (MALLOC_0_IS_NONNULL || size != 0))
return REG_ESPACE;
return REG_NOERROR;
}
static reg_errcode_t
-internal_function
+internal_function __attribute_warn_unused_result__
re_node_set_init_1 (re_node_set *set, Idx elem)
{
set->alloc = 1;
@@ -992,7 +993,7 @@ re_node_set_init_1 (re_node_set *set, Idx elem)
}
static reg_errcode_t
-internal_function
+internal_function __attribute_warn_unused_result__
re_node_set_init_2 (re_node_set *set, Idx elem1, Idx elem2)
{
set->alloc = 2;
@@ -1022,7 +1023,7 @@ re_node_set_init_2 (re_node_set *set, Idx elem1, Idx elem2)
}
static reg_errcode_t
-internal_function
+internal_function __attribute_warn_unused_result__
re_node_set_init_copy (re_node_set *dest, const re_node_set *src)
{
dest->nelem = src->nelem;
@@ -1047,7 +1048,7 @@ re_node_set_init_copy (re_node_set *dest, const re_node_set *src)
Note: We assume dest->elems is NULL, when dest->alloc is 0. */
static reg_errcode_t
-internal_function
+internal_function __attribute_warn_unused_result__
re_node_set_add_intersect (re_node_set *dest, const re_node_set *src1,
const re_node_set *src2)
{
@@ -1062,7 +1063,7 @@ re_node_set_add_intersect (re_node_set *dest, const re_node_set *src1,
Idx new_alloc = src1->nelem + src2->nelem + dest->alloc;
Idx *new_elems = re_realloc (dest->elems, Idx, new_alloc);
if (BE (new_elems == NULL, 0))
- return REG_ESPACE;
+ return REG_ESPACE;
dest->elems = new_elems;
dest->alloc = new_alloc;
}
@@ -1112,20 +1113,20 @@ re_node_set_add_intersect (re_node_set *dest, const re_node_set *src1,
if (delta > 0 && REG_VALID_INDEX (id))
for (;;)
{
- if (dest->elems[is] > dest->elems[id])
- {
- /* Copy from the top. */
- dest->elems[id + delta--] = dest->elems[is--];
- if (delta == 0)
- break;
- }
- else
- {
- /* Slide from the bottom. */
- dest->elems[id + delta] = dest->elems[id];
- if (! REG_VALID_INDEX (--id))
- break;
- }
+ if (dest->elems[is] > dest->elems[id])
+ {
+ /* Copy from the top. */
+ dest->elems[id + delta--] = dest->elems[is--];
+ if (delta == 0)
+ break;
+ }
+ else
+ {
+ /* Slide from the bottom. */
+ dest->elems[id + delta] = dest->elems[id];
+ if (! REG_VALID_INDEX (--id))
+ break;
+ }
}
/* Copy remaining SRC elements. */
@@ -1138,7 +1139,7 @@ re_node_set_add_intersect (re_node_set *dest, const re_node_set *src1,
DEST. Return value indicate the error code or REG_NOERROR if succeeded. */
static reg_errcode_t
-internal_function
+internal_function __attribute_warn_unused_result__
re_node_set_init_union (re_node_set *dest, const re_node_set *src1,
const re_node_set *src2)
{
@@ -1191,7 +1192,7 @@ re_node_set_init_union (re_node_set *dest, const re_node_set *src1,
DEST. Return value indicate the error code or REG_NOERROR if succeeded. */
static reg_errcode_t
-internal_function
+internal_function __attribute_warn_unused_result__
re_node_set_merge (re_node_set *dest, const re_node_set *src)
{
Idx is, id, sbase, delta;
@@ -1221,11 +1222,11 @@ re_node_set_merge (re_node_set *dest, const re_node_set *src)
REG_VALID_INDEX (is) && REG_VALID_INDEX (id); )
{
if (dest->elems[id] == src->elems[is])
- is--, id--;
+ is--, id--;
else if (dest->elems[id] < src->elems[is])
- dest->elems[--sbase] = src->elems[is--];
+ dest->elems[--sbase] = src->elems[is--];
else /* if (dest->elems[id] > src->elems[is]) */
- --id;
+ --id;
}
if (REG_VALID_INDEX (is))
@@ -1247,21 +1248,21 @@ re_node_set_merge (re_node_set *dest, const re_node_set *src)
for (;;)
{
if (dest->elems[is] > dest->elems[id])
- {
+ {
/* Copy from the top. */
- dest->elems[id + delta--] = dest->elems[is--];
+ dest->elems[id + delta--] = dest->elems[is--];
if (delta == 0)
break;
}
else
- {
- /* Slide from the bottom. */
- dest->elems[id + delta] = dest->elems[id];
+ {
+ /* Slide from the bottom. */
+ dest->elems[id + delta] = dest->elems[id];
if (! REG_VALID_INDEX (--id))
{
/* Copy remaining SRC elements. */
memcpy (dest->elems, dest->elems + sbase,
- delta * sizeof (Idx));
+ delta * sizeof (Idx));
break;
}
}
@@ -1275,7 +1276,7 @@ re_node_set_merge (re_node_set *dest, const re_node_set *src)
Return true if successful. */
static bool
-internal_function
+internal_function __attribute_warn_unused_result__
re_node_set_insert (re_node_set *set, Idx elem)
{
Idx idx;
@@ -1308,12 +1309,12 @@ re_node_set_insert (re_node_set *set, Idx elem)
{
idx = 0;
for (idx = set->nelem; idx > 0; idx--)
- set->elems[idx] = set->elems[idx - 1];
+ set->elems[idx] = set->elems[idx - 1];
}
else
{
for (idx = set->nelem; set->elems[idx - 1] > elem; idx--)
- set->elems[idx] = set->elems[idx - 1];
+ set->elems[idx] = set->elems[idx - 1];
}
/* Insert the new element. */
@@ -1327,7 +1328,7 @@ re_node_set_insert (re_node_set *set, Idx elem)
Return true if successful. */
static bool
-internal_function
+internal_function __attribute_warn_unused_result__
re_node_set_insert_last (re_node_set *set, Idx elem)
{
/* Realloc if we need. */
@@ -1350,7 +1351,7 @@ re_node_set_insert_last (re_node_set *set, Idx elem)
Return true if SET1 and SET2 are equivalent. */
static bool
-internal_function __attribute ((pure))
+internal_function __attribute__ ((pure))
re_node_set_compare (const re_node_set *set1, const re_node_set *set2)
{
Idx i;
@@ -1365,7 +1366,7 @@ re_node_set_compare (const re_node_set *set1, const re_node_set *set2)
/* Return (idx + 1) if SET contains the element ELEM, return 0 otherwise. */
static Idx
-internal_function __attribute ((pure))
+internal_function __attribute__ ((pure))
re_node_set_contains (const re_node_set *set, Idx elem)
{
__re_size_t idx, right, mid;
@@ -1390,7 +1391,10 @@ static void
internal_function
re_node_set_remove_at (re_node_set *set, Idx idx)
{
- if (idx < 0 || idx >= set->nelem)
+ verify (! TYPE_SIGNED (Idx));
+ /* if (idx < 0)
+ return; */
+ if (idx >= set->nelem)
return;
--set->nelem;
for (; idx < set->nelem; idx++)
@@ -1411,13 +1415,12 @@ re_dfa_add_node (re_dfa_t *dfa, re_token_t token)
Idx *new_nexts, *new_indices;
re_node_set *new_edests, *new_eclosures;
re_token_t *new_nodes;
- size_t max_object_size =
- MAX (sizeof (re_token_t),
- MAX (sizeof (re_node_set),
- sizeof (Idx)));
- /* Avoid overflows. */
- if (BE (SIZE_MAX / 2 / max_object_size < dfa->nodes_alloc, 0))
+ /* Avoid overflows in realloc. */
+ const size_t max_object_size = MAX (sizeof (re_token_t),
+ MAX (sizeof (re_node_set),
+ sizeof (Idx)));
+ if (BE (MIN (IDX_MAX, SIZE_MAX / max_object_size) < new_nodes_alloc, 0))
return REG_MISSING;
new_nodes = re_realloc (dfa->nodes, re_token_t, new_nodes_alloc);
@@ -1440,11 +1443,9 @@ re_dfa_add_node (re_dfa_t *dfa, re_token_t token)
dfa->nodes[dfa->nodes_len] = token;
dfa->nodes[dfa->nodes_len].constraint = 0;
#ifdef RE_ENABLE_I18N
- {
- int type = token.type;
dfa->nodes[dfa->nodes_len].accept_mb =
- (type == OP_PERIOD && dfa->mb_cur_max > 1) || type == COMPLEX_BRACKET;
- }
+ ((token.type == OP_PERIOD && dfa->mb_cur_max > 1)
+ || token.type == COMPLEX_BRACKET);
#endif
dfa->nexts[dfa->nodes_len] = REG_MISSING;
re_node_set_init_empty (dfa->edests + dfa->nodes_len);
@@ -1452,7 +1453,7 @@ re_dfa_add_node (re_dfa_t *dfa, re_token_t token)
return dfa->nodes_len++;
}
-static inline re_hashval_t
+static re_hashval_t
internal_function
calc_state_hash (const re_node_set *nodes, unsigned int context)
{
@@ -1473,7 +1474,7 @@ calc_state_hash (const re_node_set *nodes, unsigned int context)
optimization. */
static re_dfastate_t *
-internal_function
+internal_function __attribute_warn_unused_result__
re_acquire_state (reg_errcode_t *err, const re_dfa_t *dfa,
const re_node_set *nodes)
{
@@ -1521,7 +1522,7 @@ re_acquire_state (reg_errcode_t *err, const re_dfa_t *dfa,
optimization. */
static re_dfastate_t *
-internal_function
+internal_function __attribute_warn_unused_result__
re_acquire_state_context (reg_errcode_t *err, const re_dfa_t *dfa,
const re_node_set *nodes, unsigned int context)
{
@@ -1549,7 +1550,7 @@ re_acquire_state_context (reg_errcode_t *err, const re_dfa_t *dfa,
&& re_node_set_compare (state->entrance_nodes, nodes))
return state;
}
- /* There are no appropriate state in `dfa', create the new one. */
+ /* There are no appropriate state in 'dfa', create the new one. */
new_state = create_cd_newstate (dfa, nodes, context, hash);
if (BE (new_state == NULL, 0))
*err = REG_ESPACE;
@@ -1562,6 +1563,7 @@ re_acquire_state_context (reg_errcode_t *err, const re_dfa_t *dfa,
indicates the error code if failed. */
static reg_errcode_t
+__attribute_warn_unused_result__
register_state (const re_dfa_t *dfa, re_dfastate_t *newstate,
re_hashval_t hash)
{
@@ -1577,7 +1579,7 @@ register_state (const re_dfa_t *dfa, re_dfastate_t *newstate,
{
Idx elem = newstate->nodes.elems[i];
if (!IS_EPSILON_NODE (dfa->nodes[elem].type))
- if (BE (! re_node_set_insert_last (&newstate->non_eps_nodes, elem), 0))
+ if (! re_node_set_insert_last (&newstate->non_eps_nodes, elem))
return REG_ESPACE;
}
@@ -1612,11 +1614,11 @@ free_state (re_dfastate_t *state)
re_free (state);
}
-/* Create the new state which is independ of contexts.
+/* Create the new state which is independent of contexts.
Return the new state if succeeded, otherwise return NULL. */
static re_dfastate_t *
-internal_function
+internal_function __attribute_warn_unused_result__
create_ci_newstate (const re_dfa_t *dfa, const re_node_set *nodes,
re_hashval_t hash)
{
@@ -1666,7 +1668,7 @@ create_ci_newstate (const re_dfa_t *dfa, const re_node_set *nodes,
Return the new state if succeeded, otherwise return NULL. */
static re_dfastate_t *
-internal_function
+internal_function __attribute_warn_unused_result__
create_cd_newstate (const re_dfa_t *dfa, const re_node_set *nodes,
unsigned int context, re_hashval_t hash)
{
@@ -1689,11 +1691,9 @@ create_cd_newstate (const re_dfa_t *dfa, const re_node_set *nodes,
for (i = 0 ; i < nodes->nelem ; i++)
{
- unsigned int constraint = 0;
re_token_t *node = dfa->nodes + nodes->elems[i];
re_token_type_t type = node->type;
- if (node->constraint)
- constraint = node->constraint;
+ unsigned int constraint = node->constraint;
if (type == CHARACTER && !constraint)
continue;
@@ -1706,8 +1706,6 @@ create_cd_newstate (const re_dfa_t *dfa, const re_node_set *nodes,
newstate->halt = 1;
else if (type == OP_BACK_REF)
newstate->has_backref = 1;
- else if (type == ANCHOR)
- constraint = node->opr.ctx_type;
if (constraint)
{
@@ -1719,7 +1717,9 @@ create_cd_newstate (const re_dfa_t *dfa, const re_node_set *nodes,
free_state (newstate);
return NULL;
}
- re_node_set_init_copy (newstate->entrance_nodes, nodes);
+ if (re_node_set_init_copy (newstate->entrance_nodes, nodes)
+ != REG_NOERROR)
+ return NULL;
nctx_nodes = 0;
newstate->has_constraint = 1;
}
diff --git a/lib/regex_internal.h b/lib/regex_internal.h
index 9bbc6ac..181b02a 100644
--- a/lib/regex_internal.h
+++ b/lib/regex_internal.h
@@ -1,54 +1,85 @@
/* Extended regular expression matching and search library.
- Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
+ Copyright (C) 2002-2016 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Isamu Hasegawa <isamu@yamato.ibm.com>.
- 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 2, or (at your option)
- any later version.
+ The GNU C Library 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,
+ The GNU C Library 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.
+ 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ You should have received a copy of the GNU General Public
+ License along with the GNU C Library; if not, see
+ <http://www.gnu.org/licenses/>. */
#ifndef _REGEX_INTERNAL_H
#define _REGEX_INTERNAL_H 1
#include <assert.h>
#include <ctype.h>
-#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
-#ifdef _LIBC
-# include <langinfo.h>
-#else
-# include "localcharset.h"
-#endif
-#if defined HAVE_LOCALE_H || defined _LIBC
-# include <locale.h>
-#endif
-
+#include <langinfo.h>
+#include <locale.h>
#include <wchar.h>
#include <wctype.h>
+#include <stdbool.h>
#include <stdint.h>
-#if defined _LIBC
-# include <bits/libc-lock.h>
+
+#ifdef _LIBC
+# include <libc-lock.h>
+# define lock_define(name) __libc_lock_define (, name)
+# define lock_init(lock) (__libc_lock_init (lock), 0)
+# define lock_fini(lock) 0
+# define lock_lock(lock) __libc_lock_lock (lock)
+# define lock_unlock(lock) __libc_lock_unlock (lock)
+#elif defined GNULIB_LOCK && !defined USE_UNLOCKED_IO
+# include "glthread/lock.h"
+ /* Use gl_lock_define if empty macro arguments are known to work.
+ Otherwise, fall back on less-portable substitutes. */
+# if ((defined __GNUC__ && !defined __STRICT_ANSI__) \
+ || (defined __STDC_VERSION__ && 199901L <= __STDC_VERSION__))
+# define lock_define(name) gl_lock_define (, name)
+# elif USE_POSIX_THREADS
+# define lock_define(name) pthread_mutex_t name;
+# elif USE_PTH_THREADS
+# define lock_define(name) pth_mutex_t name;
+# elif USE_SOLARIS_THREADS
+# define lock_define(name) mutex_t name;
+# elif USE_WINDOWS_THREADS
+# define lock_define(name) gl_lock_t name;
+# else
+# define lock_define(name)
+# endif
+# define lock_init(lock) glthread_lock_init (&(lock))
+# define lock_fini(lock) glthread_lock_destroy (&(lock))
+# define lock_lock(lock) glthread_lock_lock (&(lock))
+# define lock_unlock(lock) glthread_lock_unlock (&(lock))
+#elif defined GNULIB_PTHREAD && !defined USE_UNLOCKED_IO
+# include <pthread.h>
+# define lock_define(name) pthread_mutex_t name;
+# define lock_init(lock) pthread_mutex_init (&(lock), 0)
+# define lock_fini(lock) pthread_mutex_destroy (&(lock))
+# define lock_lock(lock) pthread_mutex_lock (&(lock))
+# define lock_unlock(lock) pthread_mutex_unlock (&(lock))
#else
-# define __libc_lock_init(NAME) do { } while (0)
-# define __libc_lock_lock(NAME) do { } while (0)
-# define __libc_lock_unlock(NAME) do { } while (0)
+# define lock_define(name)
+# define lock_init(lock) 0
+# define lock_fini(lock) ((void) 0)
+ /* The 'dfa' avoids an "unused variable 'dfa'" warning from GCC. */
+# define lock_lock(lock) ((void) dfa)
+# define lock_unlock(lock) ((void) 0)
#endif
/* In case that the system doesn't have isblank(). */
-#if !defined _LIBC && !HAVE_DECL_ISBLANK && !defined isblank
+#if !defined _LIBC && ! (defined isblank || (HAVE_ISBLANK && HAVE_DECL_ISBLANK))
# define isblank(ch) ((ch) == ' ' || (ch) == '\t')
#endif
@@ -56,7 +87,6 @@
# ifndef _RE_DEFINE_LOCALE_FUNCTIONS
# define _RE_DEFINE_LOCALE_FUNCTIONS 1
# include <locale/localeinfo.h>
-# include <locale/elem-hash.h>
# include <locale/coll-lookup.h>
# endif
#endif
@@ -67,7 +97,7 @@
# ifdef _LIBC
# undef gettext
# define gettext(msgid) \
- INTUSE(__dcgettext) (_libc_intl_domainname, msgid, LC_MESSAGES)
+ __dcgettext (_libc_intl_domainname, msgid, LC_MESSAGES)
# endif
#else
# define gettext(msgid) (msgid)
@@ -79,12 +109,7 @@
# define gettext_noop(String) String
#endif
-/* For loser systems without the definition. */
-#ifndef SIZE_MAX
-# define SIZE_MAX ((size_t) -1)
-#endif
-
-#if (defined MB_CUR_MAX && HAVE_LOCALE_H && HAVE_WCTYPE_H && HAVE_ISWCTYPE && HAVE_WCRTOMB && HAVE_MBRTOWC && HAVE_WCSCOLL) || _LIBC
+#if (defined MB_CUR_MAX && HAVE_WCTYPE_H && HAVE_ISWCTYPE) || _LIBC
# define RE_ENABLE_I18N
#endif
@@ -92,9 +117,6 @@
# define BE(expr, val) __builtin_expect (expr, val)
#else
# define BE(expr, val) (expr)
-# ifdef _LIBC
-# define inline
-# endif
#endif
/* Number of ASCII characters. */
@@ -111,21 +133,30 @@
/* Rename to standard API for using out of glibc. */
#ifndef _LIBC
+# undef __wctype
+# undef __iswctype
# define __wctype wctype
+# define __iswalnum iswalnum
# define __iswctype iswctype
+# define __towlower towlower
+# define __towupper towupper
# define __btowc btowc
+# define __mbrtowc mbrtowc
# define __wcrtomb wcrtomb
# define __regfree regfree
# define attribute_hidden
#endif /* not _LIBC */
-#if __GNUC__ >= 4 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)
-# define __attribute(arg) __attribute__ (arg)
-#else
-# define __attribute(arg)
+#if __GNUC__ < 3 + (__GNUC_MINOR__ < 1)
+# define __attribute__(arg)
#endif
typedef __re_idx_t Idx;
+#ifdef _REGEX_LARGE_OFFSETS
+# define IDX_MAX (SIZE_MAX - 2)
+#else
+# define IDX_MAX INT_MAX
+#endif
/* Special return value for failure to match. */
#define REG_MISSING ((Idx) -1)
@@ -161,9 +192,9 @@ typedef unsigned long int bitset_word_t;
instead, deduce it directly from BITSET_WORD_MAX. Avoid
greater-than-32-bit integers and unconditional shifts by more than
31 bits, as they're not portable. */
-#if BITSET_WORD_MAX == 0xffffffff
+#if BITSET_WORD_MAX == 0xffffffffUL
# define BITSET_WORD_BITS 32
-#elif BITSET_WORD_MAX >> 31 >> 5 == 1
+#elif BITSET_WORD_MAX >> 31 >> 4 == 1
# define BITSET_WORD_BITS 36
#elif BITSET_WORD_MAX >> 31 >> 16 == 1
# define BITSET_WORD_BITS 48
@@ -182,10 +213,6 @@ typedef unsigned long int bitset_word_t;
# if BITSET_WORD_BITS <= SBC_MAX
# error "Invalid SBC_MAX"
# endif
-#elif BITSET_WORD_MAX == (0xffffffff + 2) * 0xffffffff
-/* Work around a bug in 64-bit PGC (before version 6.1-2), where the
- preprocessor mishandles large unsigned values as if they were signed. */
-# define BITSET_WORD_BITS 64
#else
# error "Add case for new bitset_word_t size"
#endif
@@ -340,7 +367,7 @@ typedef struct
Idx idx; /* for BACK_REF */
re_context_type ctx_type; /* for ANCHOR */
} opr;
-#if __GNUC__ >= 2 && !__STRICT_ANSI__
+#if __GNUC__ >= 2 && !defined __STRICT_ANSI__
re_token_type_t type : 8;
#else
re_token_type_t type;
@@ -421,11 +448,8 @@ struct re_dfa_t;
typedef struct re_dfa_t re_dfa_t;
#ifndef _LIBC
-# ifdef __i386__
-# define internal_function __attribute ((regparm (3), stdcall))
-# else
-# define internal_function
-# endif
+# define internal_function
+# define IS_IN(libc) false
#endif
static reg_errcode_t re_string_realloc_buffers (re_string_t *pstr,
@@ -434,13 +458,14 @@ static reg_errcode_t re_string_realloc_buffers (re_string_t *pstr,
#ifdef RE_ENABLE_I18N
static void build_wcs_buffer (re_string_t *pstr) internal_function;
static reg_errcode_t build_wcs_upper_buffer (re_string_t *pstr)
- internal_function;
+ internal_function;
#endif /* RE_ENABLE_I18N */
static void build_upper_buffer (re_string_t *pstr) internal_function;
static void re_string_translate_buffer (re_string_t *pstr) internal_function;
static unsigned int re_string_context_at (const re_string_t *input, Idx idx,
int eflags)
- internal_function __attribute ((pure));
+ internal_function __attribute__ ((pure));
+
#define re_string_peek_byte(pstr, offset) \
((pstr)->mbs[(pstr)->cur_idx + offset])
#define re_string_fetch_byte(pstr) \
@@ -458,7 +483,9 @@ static unsigned int re_string_context_at (const re_string_t *input, Idx idx,
#define re_string_skip_bytes(pstr,idx) ((pstr)->cur_idx += (idx))
#define re_string_set_index(pstr,idx) ((pstr)->cur_idx = (idx))
-#include <alloca.h>
+#if defined _LIBC || HAVE_ALLOCA
+# include <alloca.h>
+#endif
#ifndef _LIBC
# if HAVE_ALLOCA
@@ -470,12 +497,23 @@ static unsigned int re_string_context_at (const re_string_t *input, Idx idx,
# else
/* alloca is implemented with malloc, so just use malloc. */
# define __libc_use_alloca(n) 0
+# undef alloca
+# define alloca(n) malloc (n)
# endif
#endif
+#ifdef _LIBC
+# define MALLOC_0_IS_NONNULL 1
+#elif !defined MALLOC_0_IS_NONNULL
+# define MALLOC_0_IS_NONNULL 0
+#endif
+
#ifndef MAX
# define MAX(a,b) ((a) < (b) ? (b) : (a))
#endif
+#ifndef MIN
+# define MIN(a,b) ((a) < (b) ? (a) : (b))
+#endif
#define re_malloc(t,n) ((t *) malloc ((n) * sizeof (t)))
#define re_realloc(p,t,n) ((t *) realloc (p, (n) * sizeof (t)))
@@ -491,8 +529,8 @@ struct bin_tree_t
re_token_t token;
- /* `node_idx' is the index in dfa->nodes, if `type' == 0.
- Otherwise `type' indicate the type of this node. */
+ /* 'node_idx' is the index in dfa->nodes, if 'type' == 0.
+ Otherwise 'type' indicate the type of this node. */
Idx node_idx;
};
typedef struct bin_tree_t bin_tree_t;
@@ -520,7 +558,7 @@ typedef struct bin_tree_storage_t bin_tree_storage_t;
#define IS_WORD_CHAR(ch) (isalnum (ch) || (ch) == '_')
#define IS_NEWLINE(ch) ((ch) == NEWLINE_CHAR)
-#define IS_WIDE_WORD_CHAR(ch) (iswalnum (ch) || (ch) == L'_')
+#define IS_WIDE_WORD_CHAR(ch) (__iswalnum (ch) || (ch) == L'_')
#define IS_WIDE_NEWLINE(ch) ((ch) == WIDE_NEWLINE_CHAR)
#define NOT_SATISFY_PREV_CONSTRAINT(constraint,context) \
@@ -545,9 +583,9 @@ struct re_dfastate_t
struct re_dfastate_t **trtable, **word_trtable;
unsigned int context : 4;
unsigned int halt : 1;
- /* If this state can accept `multi byte'.
+ /* If this state can accept "multi byte".
Note that we refer to multibyte characters, and multi character
- collating elements as `multi byte'. */
+ collating elements as "multi byte". */
unsigned int accept_mb : 1;
/* If this state has backreference node(s). */
unsigned int has_backref : 1;
@@ -676,7 +714,7 @@ struct re_dfa_t
re_bitset_ptr_t sb_char;
int str_tree_storage_idx;
- /* number of subexpressions `re_nsub' is in regex_t. */
+ /* number of subexpressions 're_nsub' is in regex_t. */
re_hashval_t state_hash_mask;
Idx init_node;
Idx nbackref; /* The number of backreference in this dfa. */
@@ -700,9 +738,7 @@ struct re_dfa_t
#ifdef DEBUG
char* re_str;
#endif
-#ifdef _LIBC
- __libc_lock_define (, lock)
-#endif
+ lock_define (lock)
};
#define re_node_set_init_empty(set) memset (set, '\0', sizeof (re_node_set))
@@ -733,33 +769,33 @@ typedef struct
} bracket_elem_t;
-/* Inline functions for bitset_t operation. */
+/* Functions for bitset_t operation. */
-static inline void
+static void
bitset_set (bitset_t set, Idx i)
{
set[i / BITSET_WORD_BITS] |= (bitset_word_t) 1 << i % BITSET_WORD_BITS;
}
-static inline void
+static void
bitset_clear (bitset_t set, Idx i)
{
set[i / BITSET_WORD_BITS] &= ~ ((bitset_word_t) 1 << i % BITSET_WORD_BITS);
}
-static inline bool
+static bool
bitset_contain (const bitset_t set, Idx i)
{
return (set[i / BITSET_WORD_BITS] >> i % BITSET_WORD_BITS) & 1;
}
-static inline void
+static void
bitset_empty (bitset_t set)
{
memset (set, '\0', sizeof (bitset_t));
}
-static inline void
+static void
bitset_set_all (bitset_t set)
{
memset (set, -1, sizeof (bitset_word_t) * (SBC_MAX / BITSET_WORD_BITS));
@@ -768,13 +804,13 @@ bitset_set_all (bitset_t set)
((bitset_word_t) 1 << SBC_MAX % BITSET_WORD_BITS) - 1;
}
-static inline void
+static void
bitset_copy (bitset_t dest, const bitset_t src)
{
memcpy (dest, src, sizeof (bitset_t));
}
-static inline void
+static void __attribute__ ((unused))
bitset_not (bitset_t set)
{
int bitset_i;
@@ -786,7 +822,7 @@ bitset_not (bitset_t set)
& ~set[BITSET_WORDS - 1]);
}
-static inline void
+static void __attribute__ ((unused))
bitset_merge (bitset_t dest, const bitset_t src)
{
int bitset_i;
@@ -794,7 +830,7 @@ bitset_merge (bitset_t dest, const bitset_t src)
dest[bitset_i] |= src[bitset_i];
}
-static inline void
+static void __attribute__ ((unused))
bitset_mask (bitset_t dest, const bitset_t src)
{
int bitset_i;
@@ -803,9 +839,9 @@ bitset_mask (bitset_t dest, const bitset_t src)
}
#ifdef RE_ENABLE_I18N
-/* Inline functions for re_string. */
-static inline int
-internal_function __attribute ((pure))
+/* Functions for re_string. */
+static int
+internal_function __attribute__ ((pure, unused))
re_string_char_size_at (const re_string_t *pstr, Idx idx)
{
int byte_idx;
@@ -817,8 +853,8 @@ re_string_char_size_at (const re_string_t *pstr, Idx idx)
return byte_idx;
}
-static inline wint_t
-internal_function __attribute ((pure))
+static wint_t
+internal_function __attribute__ ((pure, unused))
re_string_wchar_at (const re_string_t *pstr, Idx idx)
{
if (pstr->mb_cur_max == 1)
@@ -826,15 +862,18 @@ re_string_wchar_at (const re_string_t *pstr, Idx idx)
return (wint_t) pstr->wcs[idx];
}
+# ifdef _LIBC
+# include <locale/weight.h>
+# endif
+
static int
-internal_function __attribute ((pure))
-re_string_elem_size_at (const re_string_t *pstr, Idx idx)
+internal_function __attribute__ ((pure, unused))
+re_string_elem_size_at (const re_string_t *pstr _UNUSED_PARAMETER_,
+ Idx idx _UNUSED_PARAMETER_)
{
# ifdef _LIBC
const unsigned char *p, *extra;
const int32_t *table, *indirect;
- int32_t tmp;
-# include <locale/weight.h>
uint_fast32_t nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
if (nrules != 0)
@@ -845,7 +884,7 @@ re_string_elem_size_at (const re_string_t *pstr, Idx idx)
indirect = (const int32_t *) _NL_CURRENT (LC_COLLATE,
_NL_COLLATE_INDIRECTMB);
p = pstr->mbs + idx;
- tmp = findidx (&p);
+ findidx (table, indirect, extra, &p, pstr->len - idx);
return p - pstr->mbs - idx;
}
else
@@ -854,4 +893,21 @@ re_string_elem_size_at (const re_string_t *pstr, Idx idx)
}
#endif /* RE_ENABLE_I18N */
+#ifndef __GNUC_PREREQ
+# if defined __GNUC__ && defined __GNUC_MINOR__
+# define __GNUC_PREREQ(maj, min) \
+ ((__GNUC__ << 16) + __GNUC_MINOR__ >= ((maj) << 16) + (min))
+# else
+# define __GNUC_PREREQ(maj, min) 0
+# endif
+#endif
+
+#if __GNUC_PREREQ (3,4)
+# undef __attribute_warn_unused_result__
+# define __attribute_warn_unused_result__ \
+ __attribute__ ((__warn_unused_result__))
+#else
+# define __attribute_warn_unused_result__ /* empty */
+#endif
+
#endif /* _REGEX_INTERNAL_H */
diff --git a/lib/regexec.c b/lib/regexec.c
index cba5ea2..9045ec4 100644
--- a/lib/regexec.c
+++ b/lib/regexec.c
@@ -1,22 +1,24 @@
/* Extended regular expression matching and search library.
- Copyright (C) 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2002-2016 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Isamu Hasegawa <isamu@yamato.ibm.com>.
- 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 2, or (at your option)
- any later version.
+ The GNU C Library 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,
+ The GNU C Library 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.
+ 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ You should have received a copy of the GNU General Public
+ License along with the GNU C Library; if not, see
+ <http://www.gnu.org/licenses/>. */
+#include "verify.h"
+#include "intprops.h"
static reg_errcode_t match_ctx_init (re_match_context_t *cache, int eflags,
Idx n) internal_function;
static void match_ctx_clean (re_match_context_t *mctx) internal_function;
@@ -51,9 +53,8 @@ static regoff_t re_search_stub (struct re_pattern_buffer *bufp,
regoff_t range, Idx stop,
struct re_registers *regs,
bool ret_len) internal_function;
-static unsigned int re_copy_regs (struct re_registers *regs, regmatch_t *pmatch,
- Idx nregs, int regs_allocated)
- internal_function;
+static unsigned re_copy_regs (struct re_registers *regs, regmatch_t *pmatch,
+ Idx nregs, int regs_allocated) internal_function;
static reg_errcode_t prune_impossible_nodes (re_match_context_t *mctx)
internal_function;
static Idx check_matching (re_match_context_t *mctx, bool fl_longest_match,
@@ -200,7 +201,7 @@ static Idx group_nodes_into_DFAstates (const re_dfa_t *dfa,
static bool check_node_accept (const re_match_context_t *mctx,
const re_token_t *node, Idx idx)
internal_function;
-static reg_errcode_t extend_buffers (re_match_context_t *mctx)
+static reg_errcode_t extend_buffers (re_match_context_t *mctx, int min_len)
internal_function;
/* Entry point for POSIX code. */
@@ -209,11 +210,11 @@ static reg_errcode_t extend_buffers (re_match_context_t *mctx)
string STRING.
If NMATCH is zero or REG_NOSUB was set in the cflags argument to
- `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
+ 'regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
least NMATCH elements, and we set them to the offsets of the
corresponding matched substrings.
- EFLAGS specifies `execution flags' which affect matching: if
+ EFLAGS specifies "execution flags" which affect matching: if
REG_NOTBOL is set, then ^ does not match at the beginning of the
string; if REG_NOTEOL is set, then $ does not match at the end.
@@ -229,9 +230,7 @@ regexec (preg, string, nmatch, pmatch, eflags)
{
reg_errcode_t err;
Idx start, length;
-#ifdef _LIBC
- re_dfa_t *dfa = (re_dfa_t *) preg->buffer;
-#endif
+ re_dfa_t *dfa = preg->buffer;
if (eflags & ~(REG_NOTBOL | REG_NOTEOL | REG_STARTEND))
return REG_BADPAT;
@@ -247,14 +246,14 @@ regexec (preg, string, nmatch, pmatch, eflags)
length = strlen (string);
}
- __libc_lock_lock (dfa->lock);
+ lock_lock (dfa->lock);
if (preg->no_sub)
err = re_search_internal (preg, string, length, start, length,
length, 0, NULL, eflags);
else
err = re_search_internal (preg, string, length, start, length,
length, nmatch, pmatch, eflags);
- __libc_lock_unlock (dfa->lock);
+ lock_unlock (dfa->lock);
return err != REG_NOERROR;
}
@@ -365,7 +364,6 @@ weak_alias (__re_search_2, re_search_2)
#endif
static regoff_t
-internal_function
re_search_2_stub (struct re_pattern_buffer *bufp,
const char *string1, Idx length1,
const char *string2, Idx length2,
@@ -377,8 +375,11 @@ re_search_2_stub (struct re_pattern_buffer *bufp,
Idx len = length1 + length2;
char *s = NULL;
- if (BE (length1 < 0 || length2 < 0 || stop < 0 || len < length1, 0))
- return -2;
+ verify (! TYPE_SIGNED (Idx));
+ if (BE (len < length1, 0))
+ return -2;
+ /* if (BE (length1 < 0 || length2 < 0 || stop < 0, 0))
+ return -2; */
/* Concatenate the strings. */
if (length2 > 0)
@@ -413,7 +414,6 @@ re_search_2_stub (struct re_pattern_buffer *bufp,
otherwise the position of the match is returned. */
static regoff_t
-internal_function
re_search_stub (struct re_pattern_buffer *bufp,
const char *string, Idx length,
Idx start, regoff_t range, Idx stop, struct re_registers *regs,
@@ -424,20 +424,21 @@ re_search_stub (struct re_pattern_buffer *bufp,
Idx nregs;
regoff_t rval;
int eflags = 0;
-#ifdef _LIBC
- re_dfa_t *dfa = (re_dfa_t *) bufp->buffer;
-#endif
+ re_dfa_t *dfa = bufp->buffer;
Idx last_start = start + range;
/* Check for out-of-range. */
- if (BE (start < 0 || start > length, 0))
- return -1;
+ verify (! TYPE_SIGNED (Idx));
+ /* if (BE (start < 0, 0))
+ return -1; */
+ if (BE (start > length, 0))
+ return -1;
if (BE (length < last_start || (0 <= range && last_start < start), 0))
last_start = length;
- else if (BE (last_start < 0 || (range < 0 && start <= last_start), 0))
+ else if (BE (/* last_start < 0 || */ (range < 0 && start <= last_start), 0))
last_start = 0;
- __libc_lock_lock (dfa->lock);
+ lock_lock (dfa->lock);
eflags |= (bufp->not_bol) ? REG_NOTBOL : 0;
eflags |= (bufp->not_eol) ? REG_NOTEOL : 0;
@@ -477,9 +478,9 @@ re_search_stub (struct re_pattern_buffer *bufp,
rval = 0;
- /* I hope we needn't fill ther regs with -1's when no match was found. */
+ /* I hope we needn't fill their regs with -1's when no match was found. */
if (result != REG_NOERROR)
- rval = -1;
+ rval = result == REG_NOMATCH ? -1 : -2;
else if (regs != NULL)
{
/* If caller wants register contents data back, copy them. */
@@ -501,19 +502,18 @@ re_search_stub (struct re_pattern_buffer *bufp,
}
re_free (pmatch);
out:
- __libc_lock_unlock (dfa->lock);
+ lock_unlock (dfa->lock);
return rval;
}
-static unsigned int
-internal_function
+static unsigned
re_copy_regs (struct re_registers *regs, regmatch_t *pmatch, Idx nregs,
int regs_allocated)
{
int rval = REGS_REALLOCATE;
Idx i;
Idx need_regs = nregs + 1;
- /* We need one extra element beyond `num_regs' for the `-1' marker GNU code
+ /* We need one extra element beyond 'num_regs' for the '-1' marker GNU code
uses. */
/* Have the register data arrays been allocated? */
@@ -636,7 +636,7 @@ re_exec (s)
(0 <= LAST_START && LAST_START <= LENGTH) */
static reg_errcode_t
-internal_function
+__attribute_warn_unused_result__
re_search_internal (const regex_t *preg,
const char *string, Idx length,
Idx start, Idx last_start, Idx stop,
@@ -644,7 +644,7 @@ re_search_internal (const regex_t *preg,
int eflags)
{
reg_errcode_t err;
- const re_dfa_t *dfa = (const re_dfa_t *) preg->buffer;
+ const re_dfa_t *dfa = preg->buffer;
Idx left_lim, right_lim;
int incr;
bool fl_longest_match;
@@ -700,7 +700,8 @@ re_search_internal (const regex_t *preg,
fl_longest_match = (nmatch != 0 || dfa->nbackref);
err = re_string_allocate (&mctx.input, string, length, dfa->nodes_len + 1,
- preg->translate, preg->syntax & RE_ICASE, dfa);
+ preg->translate, (preg->syntax & RE_ICASE) != 0,
+ dfa);
if (BE (err != REG_NOERROR, 0))
goto free_return;
mctx.input.stop = stop;
@@ -718,7 +719,8 @@ re_search_internal (const regex_t *preg,
if (nmatch > 1 || dfa->has_mb_node)
{
/* Avoid overflow. */
- if (BE (SIZE_MAX / sizeof (re_dfastate_t *) <= mctx.input.bufs_len, 0))
+ if (BE ((MIN (IDX_MAX, SIZE_MAX / sizeof (re_dfastate_t *))
+ <= mctx.input.bufs_len), 0))
{
err = REG_ESPACE;
goto free_return;
@@ -738,7 +740,7 @@ re_search_internal (const regex_t *preg,
mctx.input.tip_context = (eflags & REG_NOTBOL) ? CONTEXT_BEGBUF
: CONTEXT_NEWLINE | CONTEXT_BEGBUF;
- /* Check incrementally whether of not the input string match. */
+ /* Check incrementally whether the input string matches. */
incr = (last_start < start) ? -1 : 1;
left_lim = (last_start < start) ? last_start : start;
right_lim = (last_start < start) ? start : last_start;
@@ -831,10 +833,10 @@ re_search_internal (const regex_t *preg,
break;
match_first += incr;
if (match_first < left_lim || match_first > right_lim)
- {
- err = REG_NOMATCH;
- goto free_return;
- }
+ {
+ err = REG_NOMATCH;
+ goto free_return;
+ }
}
break;
}
@@ -920,7 +922,7 @@ re_search_internal (const regex_t *preg,
goto free_return;
}
- /* At last, add the offset to the each registers, since we slided
+ /* At last, add the offset to each register, since we slid
the buffers so that we could assume that the matching starts
from 0. */
for (reg_idx = 0; reg_idx < nmatch; ++reg_idx)
@@ -951,14 +953,14 @@ re_search_internal (const regex_t *preg,
}
if (dfa->subexp_map)
- for (reg_idx = 0; reg_idx + 1 < nmatch; reg_idx++)
- if (dfa->subexp_map[reg_idx] != reg_idx)
- {
- pmatch[reg_idx + 1].rm_so
- = pmatch[dfa->subexp_map[reg_idx] + 1].rm_so;
- pmatch[reg_idx + 1].rm_eo
- = pmatch[dfa->subexp_map[reg_idx] + 1].rm_eo;
- }
+ for (reg_idx = 0; reg_idx + 1 < nmatch; reg_idx++)
+ if (dfa->subexp_map[reg_idx] != reg_idx)
+ {
+ pmatch[reg_idx + 1].rm_so
+ = pmatch[dfa->subexp_map[reg_idx] + 1].rm_so;
+ pmatch[reg_idx + 1].rm_eo
+ = pmatch[dfa->subexp_map[reg_idx] + 1].rm_eo;
+ }
}
free_return:
@@ -970,7 +972,7 @@ re_search_internal (const regex_t *preg,
}
static reg_errcode_t
-internal_function
+__attribute_warn_unused_result__
prune_impossible_nodes (re_match_context_t *mctx)
{
const re_dfa_t *const dfa = mctx->dfa;
@@ -986,7 +988,7 @@ prune_impossible_nodes (re_match_context_t *mctx)
halt_node = mctx->last_node;
/* Avoid overflow. */
- if (BE (SIZE_MAX / sizeof (re_dfastate_t *) <= match_last, 0))
+ if (BE (MIN (IDX_MAX, SIZE_MAX / sizeof (re_dfastate_t *)) <= match_last, 0))
return REG_ESPACE;
sifted_states = re_malloc (re_dfastate_t *, match_last + 1);
@@ -1043,6 +1045,11 @@ prune_impossible_nodes (re_match_context_t *mctx)
re_node_set_free (&sctx.limits);
if (BE (ret != REG_NOERROR, 0))
goto free_return;
+ if (sifted_states[0] == NULL)
+ {
+ ret = REG_NOMATCH;
+ goto free_return;
+ }
}
re_free (mctx->state_log);
mctx->state_log = sifted_states;
@@ -1061,7 +1068,7 @@ prune_impossible_nodes (re_match_context_t *mctx)
since initial states may have constraints like "\<", "^", etc.. */
static inline re_dfastate_t *
-__attribute ((always_inline)) internal_function
+__attribute__ ((always_inline)) internal_function
acquire_init_state_context (reg_errcode_t *err, const re_match_context_t *mctx,
Idx idx)
{
@@ -1099,11 +1106,11 @@ acquire_init_state_context (reg_errcode_t *err, const re_match_context_t *mctx,
FL_LONGEST_MATCH means we want the POSIX longest matching.
If P_MATCH_FIRST is not NULL, and the match fails, it is set to the
next place where we may want to try matching.
- Note that the matcher assume that the maching starts from the current
+ Note that the matcher assumes that the matching starts from the current
index of the buffer. */
static Idx
-internal_function
+internal_function __attribute_warn_unused_result__
check_matching (re_match_context_t *mctx, bool fl_longest_match,
Idx *p_match_first)
{
@@ -1142,7 +1149,7 @@ check_matching (re_match_context_t *mctx, bool fl_longest_match,
{
err = transit_state_bkref (mctx, &cur_state->nodes);
if (BE (err != REG_NOERROR, 0))
- return err;
+ return err;
}
}
}
@@ -1168,17 +1175,18 @@ check_matching (re_match_context_t *mctx, bool fl_longest_match,
re_dfastate_t *old_state = cur_state;
Idx next_char_idx = re_string_cur_idx (&mctx->input) + 1;
- if (BE (next_char_idx >= mctx->input.bufs_len, 0)
- || (BE (next_char_idx >= mctx->input.valid_len, 0)
- && mctx->input.valid_len < mctx->input.len))
- {
- err = extend_buffers (mctx);
- if (BE (err != REG_NOERROR, 0))
+ if ((BE (next_char_idx >= mctx->input.bufs_len, 0)
+ && mctx->input.bufs_len < mctx->input.len)
+ || (BE (next_char_idx >= mctx->input.valid_len, 0)
+ && mctx->input.valid_len < mctx->input.len))
+ {
+ err = extend_buffers (mctx, next_char_idx + 1);
+ if (BE (err != REG_NOERROR, 0))
{
assert (err == REG_ESPACE);
return REG_ERROR;
}
- }
+ }
cur_state = transit_state (&err, mctx, cur_state);
if (mctx->state_log != NULL)
@@ -1302,17 +1310,17 @@ proceed_next_node (const re_match_context_t *mctx, Idx nregs, regmatch_t *regs,
if (dest_node == REG_MISSING)
dest_node = candidate;
- else
+ else
{
/* In order to avoid infinite loop like "(a*)*", return the second
- epsilon-transition if the first was already considered. */
+ epsilon-transition if the first was already considered. */
if (re_node_set_contains (eps_via_nodes, dest_node))
- return candidate;
+ return candidate;
/* Otherwise, push the second epsilon-transition on the fail stack. */
else if (fs != NULL
&& push_fail_stack (fs, *pidx, candidate, nregs, regs,
- eps_via_nodes))
+ eps_via_nodes))
return REG_ERROR;
/* We know we are going to exit. */
@@ -1378,7 +1386,7 @@ proceed_next_node (const re_match_context_t *mctx, Idx nregs, regmatch_t *regs,
}
static reg_errcode_t
-internal_function
+internal_function __attribute_warn_unused_result__
push_fail_stack (struct re_fail_stack_t *fs, Idx str_idx, Idx dest_node,
Idx nregs, regmatch_t *regs, re_node_set *eps_via_nodes)
{
@@ -1425,11 +1433,11 @@ pop_fail_stack (struct re_fail_stack_t *fs, Idx *pidx, Idx nregs,
pmatch[i].rm_so == pmatch[i].rm_eo == -1 for 0 < i < nmatch. */
static reg_errcode_t
-internal_function
+internal_function __attribute_warn_unused_result__
set_regs (const regex_t *preg, const re_match_context_t *mctx, size_t nmatch,
regmatch_t *pmatch, bool fl_backtrack)
{
- const re_dfa_t *dfa = (const re_dfa_t *) preg->buffer;
+ const re_dfa_t *dfa = preg->buffer;
Idx idx, cur_node;
re_node_set eps_via_nodes;
struct re_fail_stack_t *fs;
@@ -1601,21 +1609,21 @@ update_regs (const re_dfa_t *dfa, regmatch_t *pmatch,
and sift the nodes in each states according to the following rules.
Updated state_log will be wrote to STATE_LOG.
- Rules: We throw away the Node `a' in the STATE_LOG[STR_IDX] if...
+ Rules: We throw away the Node 'a' in the STATE_LOG[STR_IDX] if...
1. When STR_IDX == MATCH_LAST(the last index in the state_log):
- If `a' isn't the LAST_NODE and `a' can't epsilon transit to
- the LAST_NODE, we throw away the node `a'.
- 2. When 0 <= STR_IDX < MATCH_LAST and `a' accepts
- string `s' and transit to `b':
+ If 'a' isn't the LAST_NODE and 'a' can't epsilon transit to
+ the LAST_NODE, we throw away the node 'a'.
+ 2. When 0 <= STR_IDX < MATCH_LAST and 'a' accepts
+ string 's' and transit to 'b':
i. If 'b' isn't in the STATE_LOG[STR_IDX+strlen('s')], we throw
- away the node `a'.
+ away the node 'a'.
ii. If 'b' is in the STATE_LOG[STR_IDX+strlen('s')] but 'b' is
- thrown away, we throw away the node `a'.
+ thrown away, we throw away the node 'a'.
3. When 0 <= STR_IDX < MATCH_LAST and 'a' epsilon transit to 'b':
i. If 'b' isn't in the STATE_LOG[STR_IDX], we throw away the
- node `a'.
+ node 'a'.
ii. If 'b' is in the STATE_LOG[STR_IDX] but 'b' is thrown away,
- we throw away the node `a'. */
+ we throw away the node 'a'. */
#define STATE_NODE_CONTAINS(state,node) \
((state) != NULL && re_node_set_contains (&(state)->nodes, node))
@@ -1660,7 +1668,7 @@ sift_states_backward (const re_match_context_t *mctx, re_sift_context_t *sctx)
if (mctx->state_log[str_idx])
{
err = build_sifted_states (mctx, sctx, str_idx, &cur_dest);
- if (BE (err != REG_NOERROR, 0))
+ if (BE (err != REG_NOERROR, 0))
goto free_return;
}
@@ -1679,7 +1687,7 @@ sift_states_backward (const re_match_context_t *mctx, re_sift_context_t *sctx)
}
static reg_errcode_t
-internal_function
+internal_function __attribute_warn_unused_result__
build_sifted_states (const re_match_context_t *mctx, re_sift_context_t *sctx,
Idx str_idx, re_node_set *cur_dest)
{
@@ -1688,11 +1696,11 @@ build_sifted_states (const re_match_context_t *mctx, re_sift_context_t *sctx,
Idx i;
/* Then build the next sifted state.
- We build the next sifted state on `cur_dest', and update
- `sifted_states[str_idx]' with `cur_dest'.
+ We build the next sifted state on 'cur_dest', and update
+ 'sifted_states[str_idx]' with 'cur_dest'.
Note:
- `cur_dest' is the sifted state from `state_log[str_idx + 1]'.
- `cur_src' points the node_set of the old `state_log[str_idx]'
+ 'cur_dest' is the sifted state from 'state_log[str_idx + 1]'.
+ 'cur_src' points the node_set of the old 'state_log[str_idx]'
(with the epsilon nodes pre-filtered out). */
for (i = 0; i < cur_src->nelem; i++)
{
@@ -1705,7 +1713,7 @@ build_sifted_states (const re_match_context_t *mctx, re_sift_context_t *sctx,
assert (!IS_EPSILON_NODE (type));
#endif
#ifdef RE_ENABLE_I18N
- /* If the node may accept `multi byte'. */
+ /* If the node may accept "multi byte". */
if (dfa->nodes[prev_node].accept_mb)
naccepted = sift_states_iter_mb (mctx, sctx, prev_node,
str_idx, sctx->last_str_idx);
@@ -1746,12 +1754,13 @@ clean_state_log_if_needed (re_match_context_t *mctx, Idx next_state_log_idx)
{
Idx top = mctx->state_log_top;
- if (next_state_log_idx >= mctx->input.bufs_len
+ if ((next_state_log_idx >= mctx->input.bufs_len
+ && mctx->input.bufs_len < mctx->input.len)
|| (next_state_log_idx >= mctx->input.valid_len
&& mctx->input.valid_len < mctx->input.len))
{
reg_errcode_t err;
- err = extend_buffers (mctx);
+ err = extend_buffers (mctx, next_state_log_idx + 1);
if (BE (err != REG_NOERROR, 0))
return err;
}
@@ -1841,7 +1850,7 @@ update_cur_sifted_state (const re_match_context_t *mctx,
}
static reg_errcode_t
-internal_function
+internal_function __attribute_warn_unused_result__
add_epsilon_src_nodes (const re_dfa_t *dfa, re_node_set *dest_nodes,
const re_node_set *candidates)
{
@@ -1856,10 +1865,14 @@ add_epsilon_src_nodes (const re_dfa_t *dfa, re_node_set *dest_nodes,
{
err = re_node_set_alloc (&state->inveclosure, dest_nodes->nelem);
if (BE (err != REG_NOERROR, 0))
- return REG_ESPACE;
+ return REG_ESPACE;
for (i = 0; i < dest_nodes->nelem; i++)
- re_node_set_merge (&state->inveclosure,
- dfa->inveclosures + dest_nodes->elems[i]);
+ {
+ err = re_node_set_merge (&state->inveclosure,
+ dfa->inveclosures + dest_nodes->elems[i]);
+ if (BE (err != REG_NOERROR, 0))
+ return REG_ESPACE;
+ }
}
return re_node_set_add_intersect (dest_nodes, candidates,
&state->inveclosure);
@@ -1971,7 +1984,7 @@ check_dst_limits_calc_pos_1 (const re_match_context_t *mctx, int boundaries,
{
struct re_backref_cache_entry *ent = mctx->bkref_ents + bkref_idx;
do
- {
+ {
Idx dst;
int cpos;
@@ -1993,9 +2006,9 @@ check_dst_limits_calc_pos_1 (const re_match_context_t *mctx, int boundaries,
if (dst == from_node)
{
if (boundaries & 1)
- return -1;
+ return -1;
else /* if (boundaries & 2) */
- return 0;
+ return 0;
}
cpos =
@@ -2009,7 +2022,7 @@ check_dst_limits_calc_pos_1 (const re_match_context_t *mctx, int boundaries,
if (subexp_idx < BITSET_WORD_BITS)
ent->eps_reachable_subexps_map
&= ~((bitset_word_t) 1 << subexp_idx);
- }
+ }
while (ent++->more);
}
break;
@@ -2151,7 +2164,7 @@ check_subexp_limits (const re_dfa_t *dfa, re_node_set *dest_nodes,
}
static reg_errcode_t
-internal_function
+internal_function __attribute_warn_unused_result__
sift_states_bkref (const re_match_context_t *mctx, re_sift_context_t *sctx,
Idx str_idx, const re_node_set *candidates)
{
@@ -2234,7 +2247,7 @@ sift_states_bkref (const re_match_context_t *mctx, re_sift_context_t *sctx,
re_node_set_remove (&local_sctx.limits, enabled_idx);
/* mctx->bkref_ents may have changed, reload the pointer. */
- entry = mctx->bkref_ents + enabled_idx;
+ entry = mctx->bkref_ents + enabled_idx;
}
while (enabled_idx++, entry++->more);
}
@@ -2257,17 +2270,17 @@ sift_states_iter_mb (const re_match_context_t *mctx, re_sift_context_t *sctx,
{
const re_dfa_t *const dfa = mctx->dfa;
int naccepted;
- /* Check the node can accept `multi byte'. */
+ /* Check the node can accept "multi byte". */
naccepted = check_node_accept_bytes (dfa, node_idx, &mctx->input, str_idx);
if (naccepted > 0 && str_idx + naccepted <= max_str_idx &&
!STATE_NODE_CONTAINS (sctx->sifted_states[str_idx + naccepted],
dfa->nexts[node_idx]))
- /* The node can't accept the `multi byte', or the
+ /* The node can't accept the "multi byte", or the
destination was already thrown away, then the node
- could't accept the current input `multi byte'. */
+ could't accept the current input "multi byte". */
naccepted = 0;
/* Otherwise, it is sure that the node could accept
- `naccepted' bytes input. */
+ 'naccepted' bytes input. */
return naccepted;
}
#endif /* RE_ENABLE_I18N */
@@ -2281,7 +2294,7 @@ sift_states_iter_mb (const re_match_context_t *mctx, re_sift_context_t *sctx,
update the destination of STATE_LOG. */
static re_dfastate_t *
-internal_function
+internal_function __attribute_warn_unused_result__
transit_state (reg_errcode_t *err, re_match_context_t *mctx,
re_dfastate_t *state)
{
@@ -2315,7 +2328,7 @@ transit_state (reg_errcode_t *err, re_match_context_t *mctx,
trtable = state->word_trtable;
if (BE (trtable != NULL, 1))
- {
+ {
unsigned int context;
context
= re_string_context_at (&mctx->input,
@@ -2338,7 +2351,7 @@ transit_state (reg_errcode_t *err, re_match_context_t *mctx,
}
/* Update the state_log if we need */
-re_dfastate_t *
+static re_dfastate_t *
internal_function
merge_state_with_log (reg_errcode_t *err, re_match_context_t *mctx,
re_dfastate_t *next_state)
@@ -2361,21 +2374,21 @@ merge_state_with_log (reg_errcode_t *err, re_match_context_t *mctx,
unsigned int context;
re_node_set next_nodes, *log_nodes, *table_nodes = NULL;
/* If (state_log[cur_idx] != 0), it implies that cur_idx is
- the destination of a multibyte char/collating element/
- back reference. Then the next state is the union set of
- these destinations and the results of the transition table. */
+ the destination of a multibyte char/collating element/
+ back reference. Then the next state is the union set of
+ these destinations and the results of the transition table. */
pstate = mctx->state_log[cur_idx];
log_nodes = pstate->entrance_nodes;
if (next_state != NULL)
- {
- table_nodes = next_state->entrance_nodes;
- *err = re_node_set_init_union (&next_nodes, table_nodes,
+ {
+ table_nodes = next_state->entrance_nodes;
+ *err = re_node_set_init_union (&next_nodes, table_nodes,
log_nodes);
- if (BE (*err != REG_NOERROR, 0))
+ if (BE (*err != REG_NOERROR, 0))
return NULL;
- }
+ }
else
- next_nodes = *log_nodes;
+ next_nodes = *log_nodes;
/* Note: We already add the nodes of the initial state,
then we don't need to add them here. */
@@ -2383,12 +2396,12 @@ merge_state_with_log (reg_errcode_t *err, re_match_context_t *mctx,
re_string_cur_idx (&mctx->input) - 1,
mctx->eflags);
next_state = mctx->state_log[cur_idx]
- = re_acquire_state_context (err, dfa, &next_nodes, context);
+ = re_acquire_state_context (err, dfa, &next_nodes, context);
/* We don't need to check errors here, since the return value of
- this function is next_state and ERR is already set. */
+ this function is next_state and ERR is already set. */
if (table_nodes != NULL)
- re_node_set_free (&next_nodes);
+ re_node_set_free (&next_nodes);
}
if (BE (dfa->nbackref, 0) && next_state != NULL)
@@ -2429,9 +2442,9 @@ find_recover_state (reg_errcode_t *err, re_match_context_t *mctx)
do
{
- if (++cur_str_idx > max)
- return NULL;
- re_string_skip_bytes (&mctx->input, 1);
+ if (++cur_str_idx > max)
+ return NULL;
+ re_string_skip_bytes (&mctx->input, 1);
}
while (mctx->state_log[cur_str_idx] == NULL);
@@ -2446,7 +2459,7 @@ find_recover_state (reg_errcode_t *err, re_match_context_t *mctx)
/* From the node set CUR_NODES, pick up the nodes whose types are
OP_OPEN_SUBEXP and which have corresponding back references in the regular
expression. And register them to use them later for evaluating the
- correspoding back references. */
+ corresponding back references. */
static reg_errcode_t
internal_function
@@ -2539,7 +2552,7 @@ transit_state_mb (re_match_context_t *mctx, re_dfastate_t *pstate)
re_dfastate_t *dest_state;
if (!dfa->nodes[cur_node_idx].accept_mb)
- continue;
+ continue;
if (dfa->nodes[cur_node_idx].constraint)
{
@@ -2557,7 +2570,7 @@ transit_state_mb (re_match_context_t *mctx, re_dfastate_t *pstate)
if (naccepted == 0)
continue;
- /* The node can accepts `naccepted' bytes. */
+ /* The node can accepts 'naccepted' bytes. */
dest_idx = re_string_cur_idx (&mctx->input) + naccepted;
mctx->max_mb_elem_len = ((mctx->max_mb_elem_len < naccepted) ? naccepted
: mctx->max_mb_elem_len);
@@ -2609,7 +2622,7 @@ transit_state_bkref (re_match_context_t *mctx, const re_node_set *nodes)
const re_token_t *node = dfa->nodes + node_idx;
re_node_set *new_dest_nodes;
- /* Check whether `node' is a backreference or not. */
+ /* Check whether 'node' is a backreference or not. */
if (node->type != OP_BACK_REF)
continue;
@@ -2621,14 +2634,14 @@ transit_state_bkref (re_match_context_t *mctx, const re_node_set *nodes)
continue;
}
- /* `node' is a backreference.
+ /* 'node' is a backreference.
Check the substring which the substring matched. */
bkc_idx = mctx->nbkref_ents;
err = get_subexp (mctx, node_idx, cur_str_idx);
if (BE (err != REG_NOERROR, 0))
goto free_return;
- /* And add the epsilon closures (which is `new_dest_nodes') of
+ /* And add the epsilon closures (which is 'new_dest_nodes') of
the backreference to appropriate state_log. */
#ifdef DEBUG
assert (dfa->nexts[node_idx] != REG_MISSING);
@@ -2652,7 +2665,7 @@ transit_state_bkref (re_match_context_t *mctx, const re_node_set *nodes)
dest_state = mctx->state_log[dest_str_idx];
prev_nelem = ((mctx->state_log[cur_str_idx] == NULL) ? 0
: mctx->state_log[cur_str_idx]->nodes.nelem);
- /* Add `new_dest_node' to state_log. */
+ /* Add 'new_dest_node' to state_log. */
if (dest_state == NULL)
{
mctx->state_log[dest_str_idx]
@@ -2707,7 +2720,7 @@ transit_state_bkref (re_match_context_t *mctx, const re_node_set *nodes)
delay these checking for prune_impossible_nodes(). */
static reg_errcode_t
-internal_function
+internal_function __attribute_warn_unused_result__
get_subexp (re_match_context_t *mctx, Idx bkref_node, Idx bkref_str_idx)
{
const re_dfa_t *const dfa = mctx->dfa;
@@ -2720,7 +2733,7 @@ get_subexp (re_match_context_t *mctx, Idx bkref_node, Idx bkref_str_idx)
const struct re_backref_cache_entry *entry
= mctx->bkref_ents + cache_idx;
do
- if (entry->node == bkref_node)
+ if (entry->node == bkref_node)
return REG_NOERROR; /* We already checked it. */
while (entry++->more);
}
@@ -2804,7 +2817,7 @@ get_subexp (re_match_context_t *mctx, Idx bkref_node, Idx bkref_str_idx)
if (bkref_str_off >= mctx->input.len)
break;
- err = extend_buffers (mctx);
+ err = extend_buffers (mctx, bkref_str_off + 1);
if (BE (err != REG_NOERROR, 0))
return err;
@@ -2908,7 +2921,7 @@ find_subexp_node (const re_dfa_t *dfa, const re_node_set *nodes,
Return REG_NOERROR if it can arrive, or REG_NOMATCH otherwise. */
static reg_errcode_t
-internal_function
+internal_function __attribute_warn_unused_result__
check_arrival (re_match_context_t *mctx, state_array_t *path, Idx top_node,
Idx top_str, Idx last_node, Idx last_str, int type)
{
@@ -2926,9 +2939,12 @@ check_arrival (re_match_context_t *mctx, state_array_t *path, Idx top_node,
{
re_dfastate_t **new_array;
Idx old_alloc = path->alloc;
- Idx new_alloc = old_alloc + last_str + mctx->max_mb_elem_len + 1;
- if (BE (new_alloc < old_alloc, 0)
- || BE (SIZE_MAX / sizeof (re_dfastate_t *) < new_alloc, 0))
+ Idx incr_alloc = last_str + mctx->max_mb_elem_len + 1;
+ Idx new_alloc;
+ if (BE (IDX_MAX - old_alloc < incr_alloc, 0))
+ return REG_ESPACE;
+ new_alloc = old_alloc + incr_alloc;
+ if (BE (SIZE_MAX / sizeof (re_dfastate_t *) < new_alloc, 0))
return REG_ESPACE;
new_array = re_realloc (path->array, re_dfastate_t *, new_alloc);
if (BE (new_array == NULL, 0))
@@ -3070,14 +3086,16 @@ check_arrival (re_match_context_t *mctx, state_array_t *path, Idx top_node,
Can't we unify them? */
static reg_errcode_t
-internal_function
+internal_function __attribute_warn_unused_result__
check_arrival_add_next_nodes (re_match_context_t *mctx, Idx str_idx,
re_node_set *cur_nodes, re_node_set *next_nodes)
{
const re_dfa_t *const dfa = mctx->dfa;
bool ok;
Idx cur_idx;
+#ifdef RE_ENABLE_I18N
reg_errcode_t err = REG_NOERROR;
+#endif
re_node_set union_set;
re_node_set_init_empty (&union_set);
for (cur_idx = 0; cur_idx < cur_nodes->nelem; ++cur_idx)
@@ -3089,7 +3107,7 @@ check_arrival_add_next_nodes (re_match_context_t *mctx, Idx str_idx,
assert (!IS_EPSILON_NODE (type));
#endif
#ifdef RE_ENABLE_I18N
- /* If the node may accept `multi byte'. */
+ /* If the node may accept "multi byte". */
if (dfa->nodes[cur_node].accept_mb)
{
naccepted = check_node_accept_bytes (dfa, cur_node, &mctx->input,
@@ -3202,7 +3220,7 @@ check_arrival_expand_ecl (const re_dfa_t *dfa, re_node_set *cur_nodes,
problematic append it to DST_NODES. */
static reg_errcode_t
-internal_function
+internal_function __attribute_warn_unused_result__
check_arrival_expand_ecl_sub (const re_dfa_t *dfa, re_node_set *dst_nodes,
Idx target, Idx ex_subexp, int type)
{
@@ -3247,7 +3265,7 @@ check_arrival_expand_ecl_sub (const re_dfa_t *dfa, re_node_set *dst_nodes,
in MCTX->BKREF_ENTS. */
static reg_errcode_t
-internal_function
+internal_function __attribute_warn_unused_result__
expand_bkref_cache (re_match_context_t *mctx, re_node_set *cur_nodes,
Idx cur_str, Idx subexp_num, int type)
{
@@ -3346,7 +3364,7 @@ build_trtable (const re_dfa_t *dfa, re_dfastate_t *state)
bitset_word_t elem, mask;
bool dests_node_malloced = false;
bool dest_states_malloced = false;
- Idx ndests; /* Number of the destination states from `state'. */
+ Idx ndests; /* Number of the destination states from 'state'. */
re_dfastate_t **trtable;
re_dfastate_t **dest_states = NULL, **dest_states_word, **dest_states_nl;
re_node_set follows, *dests_node;
@@ -3360,8 +3378,8 @@ build_trtable (const re_dfa_t *dfa, re_dfastate_t *state)
} *dests_alloc;
/* We build DFA states which corresponds to the destination nodes
- from `state'. `dests_node[i]' represents the nodes which i-th
- destination state contains, and `dests_ch[i]' represents the
+ from 'state'. 'dests_node[i]' represents the nodes which i-th
+ destination state contains, and 'dests_ch[i]' represents the
characters which i-th destination state accepts. */
if (__libc_use_alloca (sizeof (struct dests_alloc)))
dests_alloc = (struct dests_alloc *) alloca (sizeof (struct dests_alloc));
@@ -3375,20 +3393,23 @@ build_trtable (const re_dfa_t *dfa, re_dfastate_t *state)
dests_node = dests_alloc->dests_node;
dests_ch = dests_alloc->dests_ch;
- /* Initialize transiton table. */
+ /* Initialize transition table. */
state->word_trtable = state->trtable = NULL;
- /* At first, group all nodes belonging to `state' into several
+ /* At first, group all nodes belonging to 'state' into several
destinations. */
ndests = group_nodes_into_DFAstates (dfa, state, dests_node, dests_ch);
if (BE (! REG_VALID_NONZERO_INDEX (ndests), 0))
{
if (dests_node_malloced)
free (dests_alloc);
+ /* Return false in case of an error, true otherwise. */
if (ndests == 0)
{
state->trtable = (re_dfastate_t **)
calloc (sizeof (re_dfastate_t *), SBC_MAX);
+ if (BE (state->trtable == NULL, 0))
+ return false;
return true;
}
return false;
@@ -3466,7 +3487,7 @@ out_free:
CONTEXT_NEWLINE);
if (BE (dest_states_nl[i] == NULL && err != REG_NOERROR, 0))
goto out_free;
- }
+ }
else
{
dest_states_word[i] = dest_states[i];
@@ -3578,13 +3599,13 @@ group_nodes_into_DFAstates (const re_dfa_t *dfa, const re_dfastate_t *state,
reg_errcode_t err;
bool ok;
Idx i, j, k;
- Idx ndests; /* Number of the destinations from `state'. */
+ Idx ndests; /* Number of the destinations from 'state'. */
bitset_t accepts; /* Characters a node can accept. */
const re_node_set *cur_nodes = &state->nodes;
bitset_empty (accepts);
ndests = 0;
- /* For all the nodes belonging to `state', */
+ /* For all the nodes belonging to 'state', */
for (i = 0; i < cur_nodes->nelem; ++i)
{
re_token_t *node = &dfa->nodes[cur_nodes->elems[i]];
@@ -3613,7 +3634,7 @@ group_nodes_into_DFAstates (const re_dfa_t *dfa, const re_dfastate_t *state,
}
#ifdef RE_ENABLE_I18N
else if (type == OP_UTF8_PERIOD)
- {
+ {
if (ASCII_CHARS % BITSET_WORD_BITS == 0)
memset (accepts, -1, ASCII_CHARS / CHAR_BIT);
else
@@ -3622,12 +3643,12 @@ group_nodes_into_DFAstates (const re_dfa_t *dfa, const re_dfastate_t *state,
bitset_clear (accepts, '\n');
if (dfa->syntax & RE_DOT_NOT_NULL)
bitset_clear (accepts, '\0');
- }
+ }
#endif
else
continue;
- /* Check the `accepts' and sift the characters which are not
+ /* Check the 'accepts' and sift the characters which are not
match it the context. */
if (constraint)
{
@@ -3686,7 +3707,7 @@ group_nodes_into_DFAstates (const re_dfa_t *dfa, const re_dfastate_t *state,
}
}
- /* Then divide `accepts' into DFA states, or create a new
+ /* Then divide 'accepts' into DFA states, or create a new
state. Above, we make sure that accepts is not empty. */
for (j = 0; j < ndests; ++j)
{
@@ -3699,7 +3720,7 @@ group_nodes_into_DFAstates (const re_dfa_t *dfa, const re_dfastate_t *state,
if (type == CHARACTER && !bitset_contain (dests_ch[j], node->opr.c))
continue;
- /* Enumerate the intersection set of this state and `accepts'. */
+ /* Enumerate the intersection set of this state and 'accepts'. */
has_intersec = 0;
for (k = 0; k < BITSET_WORDS; ++k)
has_intersec |= intersec[k] = accepts[k] & dests_ch[j][k];
@@ -3707,7 +3728,7 @@ group_nodes_into_DFAstates (const re_dfa_t *dfa, const re_dfastate_t *state,
if (!has_intersec)
continue;
- /* Then check if this state is a subset of `accepts'. */
+ /* Then check if this state is a subset of 'accepts'. */
not_subset = not_consumed = 0;
for (k = 0; k < BITSET_WORDS; ++k)
{
@@ -3715,8 +3736,8 @@ group_nodes_into_DFAstates (const re_dfa_t *dfa, const re_dfastate_t *state,
not_consumed |= accepts[k] = accepts[k] & ~dests_ch[j][k];
}
- /* If this state isn't a subset of `accepts', create a
- new group state, which has the `remains'. */
+ /* If this state isn't a subset of 'accepts', create a
+ new group state, which has the 'remains'. */
if (not_subset)
{
bitset_copy (dests_ch[ndests], remains);
@@ -3755,7 +3776,7 @@ group_nodes_into_DFAstates (const re_dfa_t *dfa, const re_dfastate_t *state,
}
#ifdef RE_ENABLE_I18N
-/* Check how many bytes the node `dfa->nodes[node_idx]' accepts.
+/* Check how many bytes the node 'dfa->nodes[node_idx]' accepts.
Return the number of the bytes the node accepts.
STR_IDX is the current index of the input string.
@@ -3763,6 +3784,10 @@ group_nodes_into_DFAstates (const re_dfa_t *dfa, const re_dfastate_t *state,
one collating element like '.', '[a-z]', opposite to the other nodes
can only accept one byte. */
+# ifdef _LIBC
+# include <locale/weight.h>
+# endif
+
static int
internal_function
check_node_accept_bytes (const re_dfa_t *dfa, Idx node_idx,
@@ -3827,7 +3852,7 @@ check_node_accept_bytes (const re_dfa_t *dfa, Idx node_idx,
if (node->type == OP_PERIOD)
{
if (char_len <= 1)
- return 0;
+ return 0;
/* FIXME: I don't think this if is needed, as both '\n'
and '\0' are char_len == 1. */
/* '.' accepts any one character except the following two cases. */
@@ -3882,9 +3907,6 @@ check_node_accept_bytes (const re_dfa_t *dfa, Idx node_idx,
const int32_t *table, *indirect;
const unsigned char *weights, *extra;
const char *collseqwc;
- int32_t idx;
- /* This #include defines a local function! */
-# include <locale/weight.h>
/* match with collating_symbol? */
if (cset->ncoll_syms)
@@ -3920,6 +3942,7 @@ check_node_accept_bytes (const re_dfa_t *dfa, Idx node_idx,
in_collseq = find_collation_sequence_value (pin, elem_len);
}
/* match with range expression? */
+ /* FIXME: Implement rational ranges here, too. */
for (i = 0; i < cset->nranges; ++i)
if (cset->range_starts[i] <= in_collseq
&& in_collseq <= cset->range_ends[i])
@@ -3940,15 +3963,20 @@ check_node_accept_bytes (const re_dfa_t *dfa, Idx node_idx,
_NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAMB);
indirect = (const int32_t *)
_NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTMB);
- idx = findidx (&cp);
+ int32_t idx = findidx (table, indirect, extra, &cp, elem_len);
if (idx > 0)
for (i = 0; i < cset->nequiv_classes; ++i)
{
int32_t equiv_class_idx = cset->equiv_classes[i];
- size_t weight_len = weights[idx];
- if (weight_len == weights[equiv_class_idx])
+ size_t weight_len = weights[idx & 0xffffff];
+ if (weight_len == weights[equiv_class_idx & 0xffffff]
+ && (idx >> 24) == (equiv_class_idx >> 24))
{
Idx cnt = 0;
+
+ idx &= 0xffffff;
+ equiv_class_idx &= 0xffffff;
+
while (cnt <= weight_len
&& (weights[equiv_class_idx + 1 + cnt]
== weights[idx + 1 + cnt]))
@@ -3966,18 +3994,9 @@ check_node_accept_bytes (const re_dfa_t *dfa, Idx node_idx,
# endif /* _LIBC */
{
/* match with range expression? */
-#if __GNUC__ >= 2 && ! (__STDC_VERSION__ < 199901L && __STRICT_ANSI__)
- wchar_t cmp_buf[] = {L'\0', L'\0', wc, L'\0', L'\0', L'\0'};
-#else
- wchar_t cmp_buf[] = {L'\0', L'\0', L'\0', L'\0', L'\0', L'\0'};
- cmp_buf[2] = wc;
-#endif
for (i = 0; i < cset->nranges; ++i)
{
- cmp_buf[0] = cset->range_starts[i];
- cmp_buf[4] = cset->range_ends[i];
- if (wcscoll (cmp_buf, cmp_buf + 2) <= 0
- && wcscoll (cmp_buf + 2, cmp_buf + 4) <= 0)
+ if (cset->range_starts[i] <= wc && wc <= cset->range_ends[i])
{
match_len = char_len;
goto check_node_accept_bytes_match;
@@ -4047,7 +4066,7 @@ find_collation_sequence_value (const unsigned char *mbs, size_t mbs_len)
/* Skip the collation sequence value. */
idx += sizeof (uint32_t);
/* Skip the wide char sequence of the collating element. */
- idx = idx + sizeof (uint32_t) * (extra[idx] + 1);
+ idx = idx + sizeof (uint32_t) * (*(int32_t *) (extra + idx) + 1);
/* If we found the entry, return the sequence value. */
if (found)
return *(uint32_t *) (extra + idx);
@@ -4114,18 +4133,21 @@ check_node_accept (const re_match_context_t *mctx, const re_token_t *node,
/* Extend the buffers, if the buffers have run out. */
static reg_errcode_t
-internal_function
-extend_buffers (re_match_context_t *mctx)
+internal_function __attribute_warn_unused_result__
+extend_buffers (re_match_context_t *mctx, int min_len)
{
reg_errcode_t ret;
re_string_t *pstr = &mctx->input;
/* Avoid overflow. */
- if (BE (SIZE_MAX / 2 / sizeof (re_dfastate_t *) <= pstr->bufs_len, 0))
+ if (BE (MIN (IDX_MAX, SIZE_MAX / sizeof (re_dfastate_t *)) / 2
+ <= pstr->bufs_len, 0))
return REG_ESPACE;
- /* Double the lengthes of the buffers. */
- ret = re_string_realloc_buffers (pstr, pstr->bufs_len * 2);
+ /* Double the lengths of the buffers, but allocate at least MIN_LEN. */
+ ret = re_string_realloc_buffers (pstr,
+ MAX (min_len,
+ MIN (pstr->len, pstr->bufs_len * 2)));
if (BE (ret != REG_NOERROR, 0))
return ret;
@@ -4177,7 +4199,7 @@ extend_buffers (re_match_context_t *mctx)
/* Initialize MCTX. */
static reg_errcode_t
-internal_function
+internal_function __attribute_warn_unused_result__
match_ctx_init (re_match_context_t *mctx, int eflags, Idx n)
{
mctx->eflags = eflags;
@@ -4188,7 +4210,7 @@ match_ctx_init (re_match_context_t *mctx, int eflags, Idx n)
size_t max_object_size =
MAX (sizeof (struct re_backref_cache_entry),
sizeof (re_sub_match_top_t *));
- if (BE (SIZE_MAX / max_object_size < n, 0))
+ if (BE (MIN (IDX_MAX, SIZE_MAX / max_object_size) < n, 0))
return REG_ESPACE;
mctx->bkref_ents = re_malloc (struct re_backref_cache_entry, n);
@@ -4257,7 +4279,7 @@ match_ctx_free (re_match_context_t *mctx)
*/
static reg_errcode_t
-internal_function
+internal_function __attribute_warn_unused_result__
match_ctx_add_entry (re_match_context_t *mctx, Idx node, Idx str_idx, Idx from,
Idx to)
{
@@ -4329,7 +4351,7 @@ search_cur_bkref_entry (const re_match_context_t *mctx, Idx str_idx)
at STR_IDX. */
static reg_errcode_t
-internal_function
+internal_function __attribute_warn_unused_result__
match_ctx_add_subtop (re_match_context_t *mctx, Idx node, Idx str_idx)
{
#ifdef DEBUG
diff --git a/lib/remove.c b/lib/remove.c
new file mode 100644
index 0000000..25b8dd3
--- /dev/null
+++ b/lib/remove.c
@@ -0,0 +1,43 @@
+/* Remove a file or directory.
+ Copyright (C) 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* written by Eric Blake */
+
+#include <config.h>
+
+#include <stdio.h>
+
+#include <errno.h>
+#include <unistd.h>
+
+#undef remove
+
+/* Remove NAME from the file system. This works around C89 platforms
+ that don't handle directories like POSIX requires; it also works
+ around Solaris 9 bugs with trailing slash. */
+int
+rpl_remove (char const *name)
+{
+ /* It is faster to just try rmdir, and fall back on unlink, than it
+ is to use lstat to see what we are about to remove. Technically,
+ it is more likely that we want unlink, not rmdir, but we cannot
+ guarantee the safety of unlink on directories. Trailing slash
+ bugs are handled by our rmdir and unlink wrappers. */
+ int result = rmdir (name);
+ if (result && errno == ENOTDIR)
+ result = unlink (name);
+ return result;
+}
diff --git a/lib/rename-dest-slash.c b/lib/rename-dest-slash.c
deleted file mode 100644
index e07ff9c..0000000
--- a/lib/rename-dest-slash.c
+++ /dev/null
@@ -1,88 +0,0 @@
-/* A rename wrapper to make tools like mv -- that would normally rely
- on the underlying rename syscall -- work more consistently.
- On at least NetBSD 1.6, `rename ("dir", "B/")' fails when B doesn't
- exist, whereas it succeeds on Linux-2.6.x and Solaris 10. This wrapper
- provides an interface for systems like the former so that the tools
- (namely mv) relying on the rename syscall have more consistent
- semantics.
-
- Copyright (C) 2006 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-/* written by Jim Meyering */
-
-#include <config.h>
-#undef rename
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <errno.h>
-
-#include <stdbool.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include "dirname.h"
-#include "xalloc.h"
-
-static bool
-has_trailing_slash (char const *file)
-{
- /* Don't count "/", "//", etc., as having a trailing slash. */
- bool has_non_slash = false;
- bool ends_in_slash = false;
-
- for (file += FILE_SYSTEM_PREFIX_LEN (file); *file; file++)
- {
- ends_in_slash = ISSLASH (*file);
- has_non_slash |= ~ ends_in_slash;
- }
-
- return has_non_slash & ends_in_slash;
-}
-
-/* This is a rename wrapper for systems where the rename syscall
- works differently than desired when SRC is a directory and DST does
- not exist but is specified with a trailing slash. On NetBSD 6.1,
- rename fails in that case. On Linux and Solaris systems, it succeeds.
- This wrapper makes it succeed on NetBSD by running the originally
- requested rename, and if it fails due to the above scenario, calling
- it again with DST's trailing slashes removed. */
-int
-rpl_rename_dest_slash (char const *src, char const *dst)
-{
- int ret_val = rename (src, dst);
-
- if (ret_val != 0 && errno == ENOENT && has_trailing_slash (dst))
- {
- int rename_errno = ENOENT;
-
- /* Fail now, unless SRC is a directory. */
- struct stat sb;
- if (lstat (src, &sb) == 0 && S_ISDIR (sb.st_mode))
- {
- char *dst_temp = xstrdup (dst);
- strip_trailing_slashes (dst_temp);
- ret_val = rename (src, dst_temp);
- rename_errno = errno;
- free (dst_temp);
- }
-
- errno = rename_errno;
- }
-
- return ret_val;
-}
diff --git a/lib/rename.c b/lib/rename.c
index 32d2b01..e1d169a 100644
--- a/lib/rename.c
+++ b/lib/rename.c
@@ -1,13 +1,11 @@
-/* Work around the bug in some systems whereby rename fails when the source
- file has a trailing slash. The rename functions of SunOS 4.1.1_U1 and
- mips-dec-ultrix4.4 have this bug.
+/* Work around rename bugs in some systems.
- Copyright (C) 2001, 2002, 2003, 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2001-2003, 2005-2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -15,43 +13,463 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
-/* written by Volker Borchert */
+/* Written by Volker Borchert, Eric Blake. */
#include <config.h>
-#undef rename
#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include "dirname.h"
-#include "xalloc.h"
+#undef rename
+
+#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+/* The mingw rename has problems with trailing slashes; it also
+ requires use of native Windows calls to allow atomic renames over
+ existing files. */
+
+# include <errno.h>
+# include <stdbool.h>
+# include <stdlib.h>
+# include <sys/stat.h>
+# include <unistd.h>
+
+# define WIN32_LEAN_AND_MEAN
+# include <windows.h>
-/* Rename the file SRC to DST, removing any trailing
- slashes from SRC. Needed for SunOS 4.1.1_U1. */
+# include "dirname.h"
+/* Rename the file SRC to DST. This replacement is necessary on
+ Windows, on which the system rename function will not replace
+ an existing DST. */
int
rpl_rename (char const *src, char const *dst)
{
- char *src_temp;
- int ret_val;
- size_t s_len = strlen (src);
+ int error;
+ size_t src_len = strlen (src);
+ size_t dst_len = strlen (dst);
+ char *src_base = last_component (src);
+ char *dst_base = last_component (dst);
+ bool src_slash;
+ bool dst_slash;
+ bool dst_exists;
+ struct stat src_st;
+ struct stat dst_st;
- if (s_len && src[s_len - 1] == '/')
+ /* Filter out dot as last component. */
+ if (!src_len || !dst_len)
{
- src_temp = xstrdup (src);
- strip_trailing_slashes (src_temp);
+ errno = ENOENT;
+ return -1;
+ }
+ if (*src_base == '.')
+ {
+ size_t len = base_len (src_base);
+ if (len == 1 || (len == 2 && src_base[1] == '.'))
+ {
+ errno = EINVAL;
+ return -1;
+ }
+ }
+ if (*dst_base == '.')
+ {
+ size_t len = base_len (dst_base);
+ if (len == 1 || (len == 2 && dst_base[1] == '.'))
+ {
+ errno = EINVAL;
+ return -1;
+ }
+ }
+
+ /* Presence of a trailing slash requires directory semantics. If
+ the source does not exist, or if the destination cannot be turned
+ into a directory, give up now. Otherwise, strip trailing slashes
+ before calling rename. There are no symlinks on mingw, so stat
+ works instead of lstat. */
+ src_slash = ISSLASH (src[src_len - 1]);
+ dst_slash = ISSLASH (dst[dst_len - 1]);
+ if (stat (src, &src_st))
+ return -1;
+ if (stat (dst, &dst_st))
+ {
+ if (errno != ENOENT || (!S_ISDIR (src_st.st_mode) && dst_slash))
+ return -1;
+ dst_exists = false;
}
else
- src_temp = (char *) src;
+ {
+ if (S_ISDIR (dst_st.st_mode) != S_ISDIR (src_st.st_mode))
+ {
+ errno = S_ISDIR (dst_st.st_mode) ? EISDIR : ENOTDIR;
+ return -1;
+ }
+ dst_exists = true;
+ }
+
+ /* There are no symlinks, so if a file existed with a trailing
+ slash, it must be a directory, and we don't have to worry about
+ stripping strip trailing slash. However, mingw refuses to
+ replace an existing empty directory, so we have to help it out.
+ And canonicalize_file_name is not yet ported to mingw; however,
+ for directories, getcwd works as a viable alternative. Ensure
+ that we can get back to where we started before using it; later
+ attempts to return are fatal. Note that we can end up losing a
+ directory if rename then fails, but it was empty, so not much
+ damage was done. */
+ if (dst_exists && S_ISDIR (dst_st.st_mode))
+ {
+ char *cwd = getcwd (NULL, 0);
+ char *src_temp;
+ char *dst_temp;
+ if (!cwd || chdir (cwd))
+ return -1;
+ if (IS_ABSOLUTE_FILE_NAME (src))
+ {
+ dst_temp = chdir (dst) ? NULL : getcwd (NULL, 0);
+ src_temp = chdir (src) ? NULL : getcwd (NULL, 0);
+ }
+ else
+ {
+ src_temp = chdir (src) ? NULL : getcwd (NULL, 0);
+ if (!IS_ABSOLUTE_FILE_NAME (dst) && chdir (cwd))
+ abort ();
+ dst_temp = chdir (dst) ? NULL : getcwd (NULL, 0);
+ }
+ if (chdir (cwd))
+ abort ();
+ free (cwd);
+ if (!src_temp || !dst_temp)
+ {
+ free (src_temp);
+ free (dst_temp);
+ errno = ENOMEM;
+ return -1;
+ }
+ src_len = strlen (src_temp);
+ if (strncmp (src_temp, dst_temp, src_len) == 0
+ && (ISSLASH (dst_temp[src_len]) || dst_temp[src_len] == '\0'))
+ {
+ error = dst_temp[src_len];
+ free (src_temp);
+ free (dst_temp);
+ if (error)
+ {
+ errno = EINVAL;
+ return -1;
+ }
+ return 0;
+ }
+ if (rmdir (dst))
+ {
+ error = errno;
+ free (src_temp);
+ free (dst_temp);
+ errno = error;
+ return -1;
+ }
+ free (src_temp);
+ free (dst_temp);
+ }
- ret_val = rename (src_temp, dst);
+ /* MoveFileEx works if SRC is a directory without any flags, but
+ fails with MOVEFILE_REPLACE_EXISTING, so try without flags first.
+ Thankfully, MoveFileEx handles hard links correctly, even though
+ rename() does not. */
+ if (MoveFileEx (src, dst, 0))
+ return 0;
+
+ /* Retry with MOVEFILE_REPLACE_EXISTING if the move failed
+ due to the destination already existing. */
+ error = GetLastError ();
+ if (error == ERROR_FILE_EXISTS || error == ERROR_ALREADY_EXISTS)
+ {
+ if (MoveFileEx (src, dst, MOVEFILE_REPLACE_EXISTING))
+ return 0;
+
+ error = GetLastError ();
+ }
+
+ switch (error)
+ {
+ case ERROR_FILE_NOT_FOUND:
+ case ERROR_PATH_NOT_FOUND:
+ case ERROR_BAD_PATHNAME:
+ case ERROR_DIRECTORY:
+ errno = ENOENT;
+ break;
+
+ case ERROR_ACCESS_DENIED:
+ case ERROR_SHARING_VIOLATION:
+ errno = EACCES;
+ break;
+
+ case ERROR_OUTOFMEMORY:
+ errno = ENOMEM;
+ break;
+
+ case ERROR_CURRENT_DIRECTORY:
+ errno = EBUSY;
+ break;
+
+ case ERROR_NOT_SAME_DEVICE:
+ errno = EXDEV;
+ break;
+
+ case ERROR_WRITE_PROTECT:
+ errno = EROFS;
+ break;
+
+ case ERROR_WRITE_FAULT:
+ case ERROR_READ_FAULT:
+ case ERROR_GEN_FAILURE:
+ errno = EIO;
+ break;
+
+ case ERROR_HANDLE_DISK_FULL:
+ case ERROR_DISK_FULL:
+ case ERROR_DISK_TOO_FRAGMENTED:
+ errno = ENOSPC;
+ break;
+
+ case ERROR_FILE_EXISTS:
+ case ERROR_ALREADY_EXISTS:
+ errno = EEXIST;
+ break;
+
+ case ERROR_BUFFER_OVERFLOW:
+ case ERROR_FILENAME_EXCED_RANGE:
+ errno = ENAMETOOLONG;
+ break;
+
+ case ERROR_INVALID_NAME:
+ case ERROR_DELETE_PENDING:
+ errno = EPERM; /* ? */
+ break;
+
+# ifndef ERROR_FILE_TOO_LARGE
+/* This value is documented but not defined in all versions of windows.h. */
+# define ERROR_FILE_TOO_LARGE 223
+# endif
+ case ERROR_FILE_TOO_LARGE:
+ errno = EFBIG;
+ break;
+
+ default:
+ errno = EINVAL;
+ break;
+ }
+
+ return -1;
+}
+
+#else /* ! W32 platform */
+
+# include <errno.h>
+# include <stdio.h>
+# include <stdlib.h>
+# include <string.h>
+# include <sys/stat.h>
+# include <unistd.h>
+
+# include "dirname.h"
+# include "same-inode.h"
+
+/* Rename the file SRC to DST, fixing any trailing slash bugs. */
+
+int
+rpl_rename (char const *src, char const *dst)
+{
+ size_t src_len = strlen (src);
+ size_t dst_len = strlen (dst);
+ char *src_temp = (char *) src;
+ char *dst_temp = (char *) dst;
+ bool src_slash;
+ bool dst_slash;
+ bool dst_exists _GL_UNUSED;
+ int ret_val = -1;
+ int rename_errno = ENOTDIR;
+ struct stat src_st;
+ struct stat dst_st;
+
+ if (!src_len || !dst_len)
+ return rename (src, dst); /* Let strace see the ENOENT failure. */
+
+# if RENAME_DEST_EXISTS_BUG
+ {
+ char *src_base = last_component (src);
+ char *dst_base = last_component (dst);
+ if (*src_base == '.')
+ {
+ size_t len = base_len (src_base);
+ if (len == 1 || (len == 2 && src_base[1] == '.'))
+ {
+ errno = EINVAL;
+ return -1;
+ }
+ }
+ if (*dst_base == '.')
+ {
+ size_t len = base_len (dst_base);
+ if (len == 1 || (len == 2 && dst_base[1] == '.'))
+ {
+ errno = EINVAL;
+ return -1;
+ }
+ }
+ }
+# endif /* RENAME_DEST_EXISTS_BUG */
+
+ src_slash = src[src_len - 1] == '/';
+ dst_slash = dst[dst_len - 1] == '/';
+
+# if !RENAME_HARD_LINK_BUG && !RENAME_DEST_EXISTS_BUG
+ /* If there are no trailing slashes, then trust the native
+ implementation unless we also suspect issues with hard link
+ detection or file/directory conflicts. */
+ if (!src_slash && !dst_slash)
+ return rename (src, dst);
+# endif /* !RENAME_HARD_LINK_BUG && !RENAME_DEST_EXISTS_BUG */
+
+ /* Presence of a trailing slash requires directory semantics. If
+ the source does not exist, or if the destination cannot be turned
+ into a directory, give up now. Otherwise, strip trailing slashes
+ before calling rename. */
+ if (lstat (src, &src_st))
+ return -1;
+ if (lstat (dst, &dst_st))
+ {
+ if (errno != ENOENT || (!S_ISDIR (src_st.st_mode) && dst_slash))
+ return -1;
+ dst_exists = false;
+ }
+ else
+ {
+ if (S_ISDIR (dst_st.st_mode) != S_ISDIR (src_st.st_mode))
+ {
+ errno = S_ISDIR (dst_st.st_mode) ? EISDIR : ENOTDIR;
+ return -1;
+ }
+# if RENAME_HARD_LINK_BUG
+ if (SAME_INODE (src_st, dst_st))
+ return 0;
+# endif /* RENAME_HARD_LINK_BUG */
+ dst_exists = true;
+ }
+
+# if (RENAME_TRAILING_SLASH_SOURCE_BUG || RENAME_DEST_EXISTS_BUG \
+ || RENAME_HARD_LINK_BUG)
+ /* If the only bug was that a trailing slash was allowed on a
+ non-existing file destination, as in Solaris 10, then we've
+ already covered that situation. But if there is any problem with
+ a trailing slash on an existing source or destination, as in
+ Solaris 9, or if a directory can overwrite a symlink, as on
+ Cygwin 1.5, or if directories cannot be created with trailing
+ slash, as on NetBSD 1.6, then we must strip the offending slash
+ and check that we have not encountered a symlink instead of a
+ directory.
+
+ Stripping a trailing slash interferes with POSIX semantics, where
+ rename behavior on a symlink with a trailing slash operates on
+ the corresponding target directory. We prefer the GNU semantics
+ of rejecting any use of a symlink with trailing slash, but do not
+ enforce them, since Solaris 10 is able to obey POSIX semantics
+ and there might be clients expecting it, as counter-intuitive as
+ those semantics are.
+
+ Technically, we could also follow the POSIX behavior by chasing a
+ readlink trail, but that is harder to implement. */
+ if (src_slash)
+ {
+ src_temp = strdup (src);
+ if (!src_temp)
+ {
+ /* Rather than rely on strdup-posix, we set errno ourselves. */
+ rename_errno = ENOMEM;
+ goto out;
+ }
+ strip_trailing_slashes (src_temp);
+ if (lstat (src_temp, &src_st))
+ {
+ rename_errno = errno;
+ goto out;
+ }
+ if (S_ISLNK (src_st.st_mode))
+ goto out;
+ }
+ if (dst_slash)
+ {
+ dst_temp = strdup (dst);
+ if (!dst_temp)
+ {
+ rename_errno = ENOMEM;
+ goto out;
+ }
+ strip_trailing_slashes (dst_temp);
+ if (lstat (dst_temp, &dst_st))
+ {
+ if (errno != ENOENT)
+ {
+ rename_errno = errno;
+ goto out;
+ }
+ }
+ else if (S_ISLNK (dst_st.st_mode))
+ goto out;
+ }
+# endif /* RENAME_TRAILING_SLASH_SOURCE_BUG || RENAME_DEST_EXISTS_BUG
+ || RENAME_HARD_LINK_BUG */
+
+# if RENAME_DEST_EXISTS_BUG
+ /* Cygwin 1.5 sometimes behaves oddly when moving a non-empty
+ directory on top of an empty one (the old directory name can
+ reappear if the new directory tree is removed). Work around this
+ by removing the target first, but don't remove the target if it
+ is a subdirectory of the source. Note that we can end up losing
+ a directory if rename then fails, but it was empty, so not much
+ damage was done. */
+ if (dst_exists && S_ISDIR (dst_st.st_mode))
+ {
+ if (src_st.st_dev != dst_st.st_dev)
+ {
+ rename_errno = EXDEV;
+ goto out;
+ }
+ if (src_temp != src)
+ free (src_temp);
+ src_temp = canonicalize_file_name (src);
+ if (dst_temp != dst)
+ free (dst_temp);
+ dst_temp = canonicalize_file_name (dst);
+ if (!src_temp || !dst_temp)
+ {
+ rename_errno = ENOMEM;
+ goto out;
+ }
+ src_len = strlen (src_temp);
+ if (strncmp (src_temp, dst_temp, src_len) == 0
+ && dst_temp[src_len] == '/')
+ {
+ rename_errno = EINVAL;
+ goto out;
+ }
+ if (rmdir (dst))
+ {
+ rename_errno = errno;
+ goto out;
+ }
+ }
+# endif /* RENAME_DEST_EXISTS_BUG */
+
+ ret_val = rename (src_temp, dst_temp);
+ rename_errno = errno;
+
+ out: _GL_UNUSED_LABEL;
if (src_temp != src)
free (src_temp);
-
+ if (dst_temp != dst)
+ free (dst_temp);
+ errno = rename_errno;
return ret_val;
}
+#endif /* ! W32 platform */
diff --git a/lib/rewinddir.c b/lib/rewinddir.c
new file mode 100644
index 0000000..2a70e7f
--- /dev/null
+++ b/lib/rewinddir.c
@@ -0,0 +1,49 @@
+/* Restart reading the entries of a directory from the beginning.
+ Copyright (C) 2011-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <dirent.h>
+
+#include <errno.h>
+
+#include "dirent-private.h"
+
+void
+rewinddir (DIR *dirp)
+{
+ /* Like in closedir(). */
+ if (dirp->current != INVALID_HANDLE_VALUE)
+ FindClose (dirp->current);
+
+ /* Like in opendir(). */
+ dirp->status = -1;
+ dirp->current = FindFirstFile (dirp->dir_name_mask, &dirp->entry);
+ if (dirp->current == INVALID_HANDLE_VALUE)
+ {
+ switch (GetLastError ())
+ {
+ case ERROR_FILE_NOT_FOUND:
+ dirp->status = -2;
+ break;
+ default:
+ /* Save the error code for the next readdir() call. */
+ dirp->status = ENOENT;
+ break;
+ }
+ }
+}
diff --git a/lib/rmdir.c b/lib/rmdir.c
index 1221f4f..4949df2 100644
--- a/lib/rmdir.c
+++ b/lib/rmdir.c
@@ -1,12 +1,12 @@
-/* BSD compatible remove directory function for System V
+/* Work around rmdir bugs.
- Copyright (C) 1988, 1990, 1999, 2003, 2004, 2005, 2006 Free
- Software Foundation, Inc.
+ Copyright (C) 1988, 1990, 1999, 2003-2006, 2009-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,61 +14,40 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
-#include <sys/types.h>
-#include <sys/stat.h>
+#include <unistd.h>
+
#include <errno.h>
+#include <string.h>
+
+#include "dosname.h"
-/* rmdir adapted from GNU tar. */
+#undef rmdir
/* Remove directory DIR.
Return 0 if successful, -1 if not. */
int
-rmdir (char const *dir)
+rpl_rmdir (char const *dir)
{
- pid_t cpid;
- int status;
- struct stat statbuf;
-
- if (stat (dir, &statbuf) != 0)
- return -1; /* errno already set */
-
- if (!S_ISDIR (statbuf.st_mode))
+ /* Work around cygwin 1.5.x bug where rmdir("dir/./") succeeds. */
+ size_t len = strlen (dir);
+ int result;
+ while (len && ISSLASH (dir[len - 1]))
+ len--;
+ if (len && dir[len - 1] == '.' && (1 == len || ISSLASH (dir[len - 2])))
{
- errno = ENOTDIR;
+ errno = EINVAL;
return -1;
}
-
- cpid = fork ();
- switch (cpid)
- {
- case -1: /* cannot fork */
- return -1; /* errno already set */
-
- case 0: /* child process */
- execl ("/bin/rmdir", "rmdir", dir, (char *) 0);
- _exit (1);
-
- default: /* parent process */
-
- /* Wait for kid to finish. */
-
- while (wait (&status) != cpid)
- /* Do nothing. */ ;
-
- if (status)
- {
-
- /* /bin/rmdir failed. */
-
- errno = EIO;
- return -1;
- }
- return 0;
- }
+ result = rmdir (dir);
+ /* Work around mingw bug, where rmdir("file/") fails with EINVAL
+ instead of ENOTDIR. We've already filtered out trailing ., the
+ only reason allowed by POSIX for EINVAL. */
+ if (result == -1 && errno == EINVAL)
+ errno = ENOTDIR;
+ return result;
}
diff --git a/lib/root-dev-ino.c b/lib/root-dev-ino.c
index 4c35d2f..28990d8 100644
--- a/lib/root-dev-ino.c
+++ b/lib/root-dev-ino.c
@@ -1,12 +1,10 @@
-/* -*- buffer-read-only: t -*- vi: set ro: */
-/* DO NOT EDIT! GENERATED AUTOMATICALLY! */
-/* root-dev-ino.c -- get the device and inode numbers for `/'.
- Copyright (C) 2003, 2005, 2006 Free Software Foundation, Inc.
+/* root-dev-ino.c -- get the device and inode numbers for '/'.
+ Copyright (C) 2003-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +12,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Jim Meyering. */
@@ -25,7 +22,7 @@
#include <stdlib.h>
-/* Call lstat to get the device and inode numbers for `/'.
+/* Call lstat to get the device and inode numbers for '/'.
Upon failure, return NULL. Otherwise, set the members of
*ROOT_D_I accordingly and return ROOT_D_I. */
struct dev_ino *
diff --git a/lib/root-dev-ino.h b/lib/root-dev-ino.h
index 3f9a407..1058a0c 100644
--- a/lib/root-dev-ino.h
+++ b/lib/root-dev-ino.h
@@ -1,13 +1,11 @@
-/* -*- buffer-read-only: t -*- vi: set ro: */
-/* DO NOT EDIT! GENERATED AUTOMATICALLY! */
/* Root device and inode number checking.
- Copyright (C) 2003, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2003-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -15,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifndef ROOT_DEV_INO_H
# define ROOT_DEV_INO_H 1
@@ -37,12 +34,12 @@ get_root_dev_ino (struct dev_ino *root_d_i);
do \
{ \
if (STREQ (Dirname, "/")) \
- error (0, 0, _("it is dangerous to operate recursively on %s"), \
- quote (Dirname)); \
+ error (0, 0, _("it is dangerous to operate recursively on %s"), \
+ quoteaf (Dirname)); \
else \
- error (0, 0, \
- _("it is dangerous to operate recursively on %s (same as %s)"), \
- quote_n (0, Dirname), quote_n (1, "/")); \
+ error (0, 0, \
+ _("it is dangerous to operate recursively on %s (same as %s)"), \
+ quoteaf_n (0, Dirname), quoteaf_n (1, "/")); \
error (0, 0, _("use --no-preserve-root to override this failsafe")); \
} \
while (0)
diff --git a/lib/root-uid.h b/lib/root-uid.h
new file mode 100644
index 0000000..23c630b
--- /dev/null
+++ b/lib/root-uid.h
@@ -0,0 +1,30 @@
+/* The user ID that always has appropriate privileges in the POSIX sense.
+
+ Copyright 2012-2016 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 <http://www.gnu.org/licenses/>.
+
+ Written by Paul Eggert. */
+
+#ifndef ROOT_UID_H_
+#define ROOT_UID_H_
+
+/* The user ID that always has appropriate privileges in the POSIX sense. */
+#ifdef __TANDEM
+# define ROOT_UID 65535
+#else
+# define ROOT_UID 0
+#endif
+
+#endif
diff --git a/lib/rpmatch.c b/lib/rpmatch.c
index e5f79f8..3c9ce54 100644
--- a/lib/rpmatch.c
+++ b/lib/rpmatch.c
@@ -1,13 +1,13 @@
/* Determine whether string value is affirmation or negative response
according to current locale's data.
- Copyright (C) 1996, 1998, 2000, 2002, 2003, 2006 Free Software
+ Copyright (C) 1996, 1998, 2000, 2002-2003, 2006-2016 Free Software
Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -15,42 +15,110 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
-#include <stddef.h>
+/* Specification. */
#include <stdlib.h>
+#include <stdbool.h>
+#include <stddef.h>
+
#if ENABLE_NLS
# include <sys/types.h>
# include <limits.h>
+# include <string.h>
+# if HAVE_LANGINFO_YESEXPR
+# include <langinfo.h>
+# endif
# include <regex.h>
# include "gettext.h"
# define _(msgid) gettext (msgid)
+# define N_(msgid) gettext_noop (msgid)
+
+# if HAVE_LANGINFO_YESEXPR
+/* Return the localized regular expression pattern corresponding to
+ ENGLISH_PATTERN. NL_INDEX can be used with nl_langinfo.
+ The resulting string may only be used until the next nl_langinfo call. */
+static const char *
+localized_pattern (const char *english_pattern, nl_item nl_index,
+ bool posixly_correct)
+{
+ const char *translated_pattern;
+
+ /* We prefer to get the patterns from a PO file. It would be possible to
+ always use nl_langinfo (YESEXPR) instead of _("^[yY]"), and
+ nl_langinfo (NOEXPR) instead of _("^[nN]"), if we could assume that the
+ system's locale support is good. But this is not the case e.g. on Cygwin.
+ The localizations of gnulib.pot are of better quality in general.
+ Also, if we use locale info from non-free systems that don't have a
+ 'localedef' command, we deprive the users of the freedom to localize
+ this pattern for their preferred language.
+ But some programs, such as 'cp', 'mv', 'rm', 'find', 'xargs', are
+ specified by POSIX to use nl_langinfo (YESEXPR). We implement this
+ behaviour if POSIXLY_CORRECT is set, for the sake of these programs. */
+
+ /* If the user wants strict POSIX compliance, use nl_langinfo. */
+ if (posixly_correct)
+ {
+ translated_pattern = nl_langinfo (nl_index);
+ /* Check against a broken system return value. */
+ if (translated_pattern != NULL && translated_pattern[0] != '\0')
+ return translated_pattern;
+ }
+
+ /* Look in the gnulib message catalog. */
+ translated_pattern = _(english_pattern);
+ if (translated_pattern == english_pattern)
+ {
+ /* The gnulib message catalog provides no translation.
+ Try the system's message catalog. */
+ translated_pattern = nl_langinfo (nl_index);
+ /* Check against a broken system return value. */
+ if (translated_pattern != NULL && translated_pattern[0] != '\0')
+ return translated_pattern;
+ /* Fall back to English. */
+ translated_pattern = english_pattern;
+ }
+ return translated_pattern;
+}
+# else
+# define localized_pattern(english_pattern,nl_index,posixly_correct) \
+ _(english_pattern)
+# endif
static int
-try (const char *response, const char *pattern, const int match,
- const int nomatch, const char **lastp, regex_t *re)
+try (const char *response, const char *pattern, char **lastp, regex_t *re)
{
- if (pattern != *lastp)
+ if (*lastp == NULL || strcmp (pattern, *lastp) != 0)
{
+ char *safe_pattern;
+
/* The pattern has changed. */
- if (*lastp)
- {
- /* Free the old compiled pattern. */
- regfree (re);
- *lastp = NULL;
- }
+ if (*lastp != NULL)
+ {
+ /* Free the old compiled pattern. */
+ regfree (re);
+ free (*lastp);
+ *lastp = NULL;
+ }
+ /* Put the PATTERN into safe memory before calling regcomp.
+ (regcomp may call nl_langinfo, overwriting PATTERN's storage. */
+ safe_pattern = strdup (pattern);
+ if (safe_pattern == NULL)
+ return -1;
/* Compile the pattern and cache it for future runs. */
- if (regcomp (re, pattern, REG_EXTENDED) != 0)
- return -1;
- *lastp = pattern;
+ if (regcomp (re, safe_pattern, REG_EXTENDED) != 0)
+ {
+ free (safe_pattern);
+ return -1;
+ }
+ *lastp = safe_pattern;
}
/* See if the regular expression matches RESPONSE. */
- return regexec (re, response, 0, NULL, 0) == 0 ? match : nomatch;
+ return regexec (re, response, 0, NULL, 0) == 0;
}
#endif
@@ -63,17 +131,46 @@ rpmatch (const char *response)
first if necessary. */
/* We cache the response patterns and compiled regexps here. */
- static const char *yesexpr, *noexpr;
- static regex_t yesre, nore;
+ static char *last_yesexpr, *last_noexpr;
+ static regex_t cached_yesre, cached_nore;
+
+# if HAVE_LANGINFO_YESEXPR
+ bool posixly_correct = (getenv ("POSIXLY_CORRECT") != NULL);
+# endif
+
+ const char *yesexpr, *noexpr;
int result;
- return ((result = try (response, _("^[yY]"), 1, 0,
- &yesexpr, &yesre))
- ? result
- : try (response, _("^[nN]"), 0, -1, &noexpr, &nore));
+ /* TRANSLATORS: A regular expression testing for an affirmative answer
+ (english: "yes"). Testing the first character may be sufficient.
+ Take care to consider upper and lower case.
+ To enquire the regular expression that your system uses for this
+ purpose, you can use the command
+ locale -k LC_MESSAGES | grep '^yesexpr=' */
+ yesexpr = localized_pattern (N_("^[yY]"), YESEXPR, posixly_correct);
+ result = try (response, yesexpr, &last_yesexpr, &cached_yesre);
+ if (result < 0)
+ return -1;
+ if (result)
+ return 1;
+
+ /* TRANSLATORS: A regular expression testing for a negative answer
+ (english: "no"). Testing the first character may be sufficient.
+ Take care to consider upper and lower case.
+ To enquire the regular expression that your system uses for this
+ purpose, you can use the command
+ locale -k LC_MESSAGES | grep '^noexpr=' */
+ noexpr = localized_pattern (N_("^[nN]"), NOEXPR, posixly_correct);
+ result = try (response, noexpr, &last_noexpr, &cached_nore);
+ if (result < 0)
+ return -1;
+ if (result)
+ return 0;
+
+ return -1;
#else
/* Test against "^[yY]" and "^[nN]", hardcoded to avoid requiring regex */
return (*response == 'y' || *response == 'Y' ? 1
- : *response == 'n' || *response == 'N' ? 0 : -1);
+ : *response == 'n' || *response == 'N' ? 0 : -1);
#endif
}
diff --git a/lib/safe-read.c b/lib/safe-read.c
index b7bf1d5..3dde5b5 100644
--- a/lib/safe-read.c
+++ b/lib/safe-read.c
@@ -1,12 +1,12 @@
/* An interface to read and write that retries after interrupts.
- Copyright (C) 1993, 1994, 1998, 2002, 2003, 2004, 2005, 2006 Free
- Software Foundation, Inc.
+ Copyright (C) 1993-1994, 1998, 2002-2006, 2009-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
@@ -67,12 +66,12 @@ safe_rw (int fd, void const *buf, size_t count)
ssize_t result = rw (fd, buf, count);
if (0 <= result)
- return result;
+ return result;
else if (IS_EINTR (errno))
- continue;
+ continue;
else if (errno == EINVAL && BUGGY_READ_MAXIMUM < count)
- count = BUGGY_READ_MAXIMUM;
+ count = BUGGY_READ_MAXIMUM;
else
- return result;
+ return result;
}
}
diff --git a/lib/safe-read.h b/lib/safe-read.h
index 3451955..b99586a 100644
--- a/lib/safe-read.h
+++ b/lib/safe-read.h
@@ -1,10 +1,10 @@
/* An interface to read() that retries after interrupts.
- Copyright (C) 2002, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2002, 2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -12,8 +12,20 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
+
+/* Some system calls may be interrupted and fail with errno = EINTR in the
+ following situations:
+ - The process is stopped and restarted (signal SIGSTOP and SIGCONT, user
+ types Ctrl-Z) on some platforms: Mac OS X.
+ - The process receives a signal for which a signal handler was installed
+ with sigaction() with an sa_flags field that does not contain
+ SA_RESTART.
+ - The process receives a signal for which a signal handler was installed
+ with signal() and for which no call to siginterrupt(sig,0) was done,
+ on some platforms: AIX, HP-UX, IRIX, OSF/1, Solaris.
+
+ This module provides a wrapper around read() that handles EINTR. */
#include <stddef.h>
diff --git a/lib/safe-write.c b/lib/safe-write.c
index 4c375a6..acd7aee 100644
--- a/lib/safe-write.c
+++ b/lib/safe-write.c
@@ -1,10 +1,10 @@
/* An interface to write that retries after interrupts.
- Copyright (C) 2002 Free Software Foundation, Inc.
+ Copyright (C) 2002, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -12,8 +12,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#define SAFE_WRITE
#include "safe-read.c"
diff --git a/lib/safe-write.h b/lib/safe-write.h
index c194636..65fa425 100644
--- a/lib/safe-write.h
+++ b/lib/safe-write.h
@@ -1,10 +1,10 @@
/* An interface to write() that retries after interrupts.
- Copyright (C) 2002 Free Software Foundation, Inc.
+ Copyright (C) 2002, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -12,8 +12,20 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
+
+/* Some system calls may be interrupted and fail with errno = EINTR in the
+ following situations:
+ - The process is stopped and restarted (signal SIGSTOP and SIGCONT, user
+ types Ctrl-Z) on some platforms: Mac OS X.
+ - The process receives a signal for which a signal handler was installed
+ with sigaction() with an sa_flags field that does not contain
+ SA_RESTART.
+ - The process receives a signal for which a signal handler was installed
+ with signal() and for which no call to siginterrupt(sig,0) was done,
+ on some platforms: AIX, HP-UX, IRIX, OSF/1, Solaris.
+
+ This module provides a wrapper around write() that handles EINTR. */
#include <stddef.h>
diff --git a/lib/same-inode.h b/lib/same-inode.h
index deca87b..bf45635 100644
--- a/lib/same-inode.h
+++ b/lib/same-inode.h
@@ -1,11 +1,11 @@
/* Determine whether two stat buffers refer to the same file.
- Copyright (C) 2006 Free Software Foundation, Inc.
+ Copyright (C) 2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,14 +13,21 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifndef SAME_INODE_H
# define SAME_INODE_H 1
-# define SAME_INODE(Stat_buf_1, Stat_buf_2) \
- ((Stat_buf_1).st_ino == (Stat_buf_2).st_ino \
- && (Stat_buf_1).st_dev == (Stat_buf_2).st_dev)
+# ifdef __VMS
+# define SAME_INODE(a, b) \
+ ((a).st_ino[0] == (b).st_ino[0] \
+ && (a).st_ino[1] == (b).st_ino[1] \
+ && (a).st_ino[2] == (b).st_ino[2] \
+ && (a).st_dev == (b).st_dev)
+# else
+# define SAME_INODE(a, b) \
+ ((a).st_ino == (b).st_ino \
+ && (a).st_dev == (b).st_dev)
+# endif
#endif
diff --git a/lib/same.c b/lib/same.c
index 11590c6..a25ee86 100644
--- a/lib/same.c
+++ b/lib/same.c
@@ -1,12 +1,11 @@
/* Determine whether two file names refer to the same file.
- Copyright (C) 1997, 1998, 1999, 2000, 2002, 2003, 2004, 2005, 2006 Free
- Software Foundation, Inc.
+ Copyright (C) 1997-2000, 2002-2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* written by Jim Meyering */
@@ -41,7 +39,6 @@
#include "dirname.h"
#include "error.h"
#include "same-inode.h"
-#include "xalloc.h"
#ifndef MIN
# define MIN(a, b) ((a) < (b) ? (a) : (b))
@@ -86,36 +83,36 @@ same_name (const char *source, const char *dest)
dest_dirname = dir_name (dest);
if (stat (source_dirname, &source_dir_stats))
- {
- /* Shouldn't happen. */
- error (1, errno, "%s", source_dirname);
- }
+ {
+ /* Shouldn't happen. */
+ error (1, errno, "%s", source_dirname);
+ }
if (stat (dest_dirname, &dest_dir_stats))
- {
- /* Shouldn't happen. */
- error (1, errno, "%s", dest_dirname);
- }
+ {
+ /* Shouldn't happen. */
+ error (1, errno, "%s", dest_dirname);
+ }
same = SAME_INODE (source_dir_stats, dest_dir_stats);
#if ! _POSIX_NO_TRUNC && HAVE_PATHCONF && defined _PC_NAME_MAX
if (same && ! identical_basenames)
- {
- long name_max = (errno = 0, pathconf (dest_dirname, _PC_NAME_MAX));
- if (name_max < 0)
- {
- if (errno)
- {
- /* Shouldn't happen. */
- error (1, errno, "%s", dest_dirname);
- }
- same = false;
- }
- else
- same = (name_max <= min_baselen
- && memcmp (source_basename, dest_basename, name_max) == 0);
- }
+ {
+ long name_max = (errno = 0, pathconf (dest_dirname, _PC_NAME_MAX));
+ if (name_max < 0)
+ {
+ if (errno)
+ {
+ /* Shouldn't happen. */
+ error (1, errno, "%s", dest_dirname);
+ }
+ same = false;
+ }
+ else
+ same = (name_max <= min_baselen
+ && memcmp (source_basename, dest_basename, name_max) == 0);
+ }
#endif
free (source_dirname);
diff --git a/lib/same.h b/lib/same.h
index 9fc0579..71ba52e 100644
--- a/lib/same.h
+++ b/lib/same.h
@@ -1,12 +1,11 @@
/* Determine whether two file names refer to the same file.
- Copyright (C) 1997, 1998, 1999, 2000, 2003, 2004 Free Software
- Foundation, Inc.
+ Copyright (C) 1997-2000, 2003-2004, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifndef SAME_H_
# define SAME_H_ 1
diff --git a/lib/save-cwd.c b/lib/save-cwd.c
index f07973a..27cb750 100644
--- a/lib/save-cwd.c
+++ b/lib/save-cwd.c
@@ -1,12 +1,12 @@
/* save-cwd.c -- Save and restore current working directory.
- Copyright (C) 1995, 1997, 1998, 2003, 2004, 2005, 2006 Free
- Software Foundation, Inc.
+ Copyright (C) 1995, 1997-1998, 2003-2006, 2009-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Jim Meyering. */
@@ -24,40 +23,35 @@
#include "save-cwd.h"
#include <errno.h>
+#include <fcntl.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
-#include <unistd.h>
#include "chdir-long.h"
-#include "fcntl--.h"
-#include "xgetcwd.h"
-
-/* On systems without the fchdir function (WOE), pretend that open
- always returns -1 so that save_cwd resorts to using xgetcwd.
- Since chdir_long requires fchdir, use chdir instead. */
-#if !HAVE_FCHDIR
-# undef open
-# define open(File, Flags) (-1)
-# undef fchdir
-# define fchdir(Fd) (abort (), -1)
-# undef chdir_long
-# define chdir_long(Dir) chdir (Dir)
+#include "unistd--.h"
+#include "cloexec.h"
+
+#if GNULIB_FCNTL_SAFER
+# include "fcntl--.h"
+#else
+# define GNULIB_FCNTL_SAFER 0
#endif
/* Record the location of the current working directory in CWD so that
the program may change to other directories and later use restore_cwd
to return to the recorded location. This function may allocate
- space using malloc (via xgetcwd) or leave a file descriptor open;
+ space using malloc (via getcwd) or leave a file descriptor open;
use free_cwd to perform the necessary free or close. Upon failure,
no memory is allocated, any locally opened file descriptors are
closed; return non-zero -- in that case, free_cwd need not be
called, but doing so is ok. Otherwise, return zero.
- The `raison d'etre' for this interface is that the working directory
+ The _raison d'etre_ for this interface is that the working directory
is sometimes inaccessible, and getcwd is not robust or as efficient.
So, we prefer to use the open/fchdir approach, but fall back on
- getcwd if necessary.
+ getcwd if necessary. This module works for most cases with just
+ the getcwd-lgpl module, but to be truly robust, use the getcwd module.
Some systems lack fchdir altogether: e.g., OS/2, pre-2001 Cygwin,
SCO Xenix. Also, SunOS 4 and Irix 5.3 provide the function, yet it
@@ -70,13 +64,16 @@ save_cwd (struct saved_cwd *cwd)
{
cwd->name = NULL;
- cwd->desc = open (".", O_RDONLY);
+ cwd->desc = open (".", O_SEARCH);
+ if (!GNULIB_FCNTL_SAFER)
+ cwd->desc = fd_safer (cwd->desc);
if (cwd->desc < 0)
{
- cwd->name = xgetcwd ();
+ cwd->name = getcwd (NULL, 0);
return cwd->name ? 0 : -1;
}
+ set_cloexec_flag (cwd->desc, true);
return 0;
}
@@ -98,6 +95,5 @@ free_cwd (struct saved_cwd *cwd)
{
if (cwd->desc >= 0)
close (cwd->desc);
- if (cwd->name)
- free (cwd->name);
+ free (cwd->name);
}
diff --git a/lib/save-cwd.h b/lib/save-cwd.h
index d646b55..dbb598d 100644
--- a/lib/save-cwd.h
+++ b/lib/save-cwd.h
@@ -1,11 +1,12 @@
/* Save and restore current working directory.
- Copyright (C) 1995, 1997, 1998, 2003 Free Software Foundation, Inc.
+ Copyright (C) 1995, 1997-1998, 2003, 2009-2016 Free Software Foundation,
+ Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Jim Meyering. */
diff --git a/lib/savedir.c b/lib/savedir.c
index d930fb4..3604f62 100644
--- a/lib/savedir.c
+++ b/lib/savedir.c
@@ -1,12 +1,12 @@
/* savedir.c -- save the list of files in a directory in a string
- Copyright (C) 1990, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005,
- 2006 Free Software Foundation, Inc.
+ Copyright (C) 1990, 1997-2001, 2003-2006, 2009-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by David MacKenzie <djm@gnu.ai.mit.edu>. */
@@ -27,46 +26,82 @@
#include <errno.h>
-#include <dirent.h>
+#include "dirent--.h"
#ifndef _D_EXACT_NAMLEN
-# define _D_EXACT_NAMLEN(dp) strlen ((dp)->d_name)
+# define _D_EXACT_NAMLEN(dp) strlen ((dp)->d_name)
#endif
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
-#include "openat.h"
#include "xalloc.h"
-#ifndef NAME_SIZE_DEFAULT
-# define NAME_SIZE_DEFAULT 512
+typedef struct
+{
+ char *name;
+#if D_INO_IN_DIRENT
+ ino_t ino;
#endif
+} direntry_t;
+
+/* Compare the names of two directory entries */
-/* The results of opendir() in this file are not used with dirfd and fchdir,
- therefore save some unnecessary work in fchdir.c. */
-#undef opendir
-#undef closedir
+static int
+direntry_cmp_name (void const *a, void const *b)
+{
+ direntry_t const *dea = a;
+ direntry_t const *deb = b;
+
+ return strcmp (dea->name, deb->name);
+}
+
+#if D_INO_IN_DIRENT
+/* Compare the inode numbers of two directory entries */
+
+static int
+direntry_cmp_inode (void const *a, void const *b)
+{
+ direntry_t const *dea = a;
+ direntry_t const *deb = b;
+
+ return dea->ino < deb->ino ? -1 : dea->ino > deb->ino;
+}
+#endif
+
+typedef int (*comparison_function) (void const *, void const *);
+
+static comparison_function const comparison_function_table[] =
+ {
+ 0,
+ direntry_cmp_name
+#if D_INO_IN_DIRENT
+ , direntry_cmp_inode
+#endif
+ };
/* Return a freshly allocated string containing the file names
in directory DIRP, separated by '\0' characters;
the end is marked by two '\0' characters in a row.
- Return NULL (setting errno) if DIRP cannot be read or closed.
+ Returned values are sorted according to OPTION.
+ Return NULL (setting errno) if DIRP cannot be read.
If DIRP is NULL, return NULL without affecting errno. */
-static char *
-savedirstream (DIR *dirp)
+char *
+streamsavedir (DIR *dirp, enum savedir_option option)
{
- char *name_space;
- size_t allocated = NAME_SIZE_DEFAULT;
+ char *name_space = NULL;
+ size_t allocated = 0;
+ direntry_t *entries = NULL;
+ size_t entries_allocated = 0;
+ size_t entries_used = 0;
size_t used = 0;
- int save_errno;
+ int readdir_errno;
+ comparison_function cmp = comparison_function_table[option];
if (dirp == NULL)
return NULL;
- name_space = xmalloc (allocated);
-
for (;;)
{
struct dirent const *dp;
@@ -75,42 +110,73 @@ savedirstream (DIR *dirp)
errno = 0;
dp = readdir (dirp);
if (! dp)
- break;
+ break;
/* Skip "", ".", and "..". "" is returned by at least one buggy
implementation: Solaris 2.4 readdir on NFS file systems. */
entry = dp->d_name;
if (entry[entry[0] != '.' ? 0 : entry[1] != '.' ? 1 : 2] != '\0')
- {
- size_t entry_size = _D_EXACT_NAMLEN (dp) + 1;
- if (used + entry_size < used)
- xalloc_die ();
- if (allocated <= used + entry_size)
- {
- do
- {
- if (2 * allocated < allocated)
- xalloc_die ();
- allocated *= 2;
- }
- while (allocated <= used + entry_size);
-
- name_space = xrealloc (name_space, allocated);
- }
- memcpy (name_space + used, entry, entry_size);
- used += entry_size;
- }
+ {
+ size_t entry_size = _D_EXACT_NAMLEN (dp) + 1;
+ if (cmp)
+ {
+ if (entries_allocated == entries_used)
+ {
+ size_t n = entries_allocated;
+ entries = x2nrealloc (entries, &n, sizeof *entries);
+ entries_allocated = n;
+ }
+ entries[entries_used].name = xstrdup (entry);
+#if D_INO_IN_DIRENT
+ entries[entries_used].ino = dp->d_ino;
+#endif
+ entries_used++;
+ }
+ else
+ {
+ if (allocated - used <= entry_size)
+ {
+ size_t n = used + entry_size;
+ if (n < used)
+ xalloc_die ();
+ name_space = x2nrealloc (name_space, &n, 1);
+ allocated = n;
+ }
+ memcpy (name_space + used, entry, entry_size);
+ }
+ used += entry_size;
+ }
}
- name_space[used] = '\0';
- save_errno = errno;
- if (closedir (dirp) != 0)
- save_errno = errno;
- if (save_errno != 0)
+
+ readdir_errno = errno;
+ if (readdir_errno != 0)
{
+ free (entries);
free (name_space);
- errno = save_errno;
+ errno = readdir_errno;
return NULL;
}
+
+ if (cmp)
+ {
+ size_t i;
+
+ if (entries_used)
+ qsort (entries, entries_used, sizeof *entries, cmp);
+ name_space = xmalloc (used + 1);
+ used = 0;
+ for (i = 0; i < entries_used; i++)
+ {
+ char *dest = name_space + used;
+ used += stpcpy (dest, entries[i].name) - dest + 1;
+ free (entries[i].name);
+ }
+ free (entries);
+ }
+ else if (used == allocated)
+ name_space = xrealloc (name_space, used + 1);
+
+ name_space[used] = '\0';
return name_space;
}
@@ -120,18 +186,21 @@ savedirstream (DIR *dirp)
Return NULL (setting errno) if DIR cannot be opened, read, or closed. */
char *
-savedir (char const *dir)
+savedir (char const *dir, enum savedir_option option)
{
- return savedirstream (opendir (dir));
-}
-
-/* Return a freshly allocated string containing the file names
- in directory FD, separated by '\0' characters;
- the end is marked by two '\0' characters in a row.
- Return NULL (setting errno) if FD cannot be read or closed. */
-
-char *
-fdsavedir (int fd)
-{
- return savedirstream (fdopendir (fd));
+ DIR *dirp = opendir (dir);
+ if (! dirp)
+ return NULL;
+ else
+ {
+ char *name_space = streamsavedir (dirp, option);
+ if (closedir (dirp) != 0)
+ {
+ int closedir_errno = errno;
+ free (name_space);
+ errno = closedir_errno;
+ return NULL;
+ }
+ return name_space;
+ }
}
diff --git a/lib/savedir.h b/lib/savedir.h
index 5b7bef9..a277024 100644
--- a/lib/savedir.h
+++ b/lib/savedir.h
@@ -1,11 +1,12 @@
/* Save the list of files in a directory in a string.
- Copyright (C) 1997, 1999, 2001, 2003, 2005 Free Software Foundation, Inc.
+ Copyright (C) 1997, 1999, 2001, 2003, 2005, 2009-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,15 +14,28 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by David MacKenzie <djm@gnu.ai.mit.edu>. */
-#if !defined SAVEDIR_H_
-# define SAVEDIR_H_
+#ifndef _GL_SAVEDIR_H
+#define _GL_SAVEDIR_H
-char *savedir (char const *dir);
-char *fdsavedir (int fd);
+#include <dirent.h>
+
+enum savedir_option
+ {
+ SAVEDIR_SORT_NONE,
+ SAVEDIR_SORT_NAME,
+#if D_INO_IN_DIRENT
+ SAVEDIR_SORT_INODE,
+ SAVEDIR_SORT_FASTREAD = SAVEDIR_SORT_INODE
+#else
+ SAVEDIR_SORT_FASTREAD = SAVEDIR_SORT_NONE
+#endif
+ };
+
+char *streamsavedir (DIR *, enum savedir_option);
+char *savedir (char const *, enum savedir_option);
#endif
diff --git a/lib/savewd.c b/lib/savewd.c
index 9af3085..1367c88 100644
--- a/lib/savewd.c
+++ b/lib/savewd.c
@@ -1,11 +1,11 @@
/* Save and restore the working directory, possibly using a child process.
- Copyright (C) 2006, 2007 Free Software Foundation, Inc.
+ Copyright (C) 2006-2007, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,16 +13,16 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
#include <config.h>
+#define SAVEWD_INLINE _GL_EXTERN_INLINE
+
#include "savewd.h"
-#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
@@ -32,10 +32,10 @@
#include <sys/wait.h>
#include <unistd.h>
-#include "dirname.h"
+#include "assure.h"
+#include "dosname.h"
#include "fcntl-safer.h"
-
/* Save the working directory into *WD, if it hasn't been saved
already. Return true if a child has been forked to do the real
work. */
@@ -47,38 +47,38 @@ savewd_save (struct savewd *wd)
case INITIAL_STATE:
/* Save the working directory, or prepare to fall back if possible. */
{
- int fd = open_safer (".", O_RDONLY);
- if (0 <= fd)
- {
- wd->state = FD_STATE;
- wd->val.fd = fd;
- break;
- }
- if (errno != EACCES && errno != ESTALE)
- {
- wd->state = ERROR_STATE;
- wd->val.errnum = errno;
- break;
- }
+ int fd = open_safer (".", O_SEARCH);
+ if (0 <= fd)
+ {
+ wd->state = FD_STATE;
+ wd->val.fd = fd;
+ break;
+ }
+ if (errno != EACCES && errno != ESTALE)
+ {
+ wd->state = ERROR_STATE;
+ wd->val.errnum = errno;
+ break;
+ }
}
wd->state = FORKING_STATE;
wd->val.child = -1;
/* Fall through. */
case FORKING_STATE:
if (wd->val.child < 0)
- {
- /* "Save" the initial working directory by forking a new
- subprocess that will attempt all the work from the chdir
- until until the next savewd_restore. */
- wd->val.child = fork ();
- if (wd->val.child != 0)
- {
- if (0 < wd->val.child)
- return true;
- wd->state = ERROR_STATE;
- wd->val.errnum = errno;
- }
- }
+ {
+ /* "Save" the initial working directory by forking a new
+ subprocess that will attempt all the work from the chdir
+ until until the next savewd_restore. */
+ wd->val.child = fork ();
+ if (wd->val.child != 0)
+ {
+ if (0 < wd->val.child)
+ return true;
+ wd->state = ERROR_STATE;
+ wd->val.errnum = errno;
+ }
+ }
break;
case FD_STATE:
@@ -88,7 +88,7 @@ savewd_save (struct savewd *wd)
break;
default:
- assert (false);
+ assure (false);
}
return false;
@@ -96,7 +96,7 @@ savewd_save (struct savewd *wd)
int
savewd_chdir (struct savewd *wd, char const *dir, int options,
- int open_result[2])
+ int open_result[2])
{
int fd = -1;
int result = 0;
@@ -107,50 +107,50 @@ savewd_chdir (struct savewd *wd, char const *dir, int options,
|| (options & (HAVE_WORKING_O_NOFOLLOW ? SAVEWD_CHDIR_NOFOLLOW : 0)))
{
fd = open (dir,
- (O_RDONLY | O_DIRECTORY | O_NOCTTY | O_NONBLOCK
- | (options & SAVEWD_CHDIR_NOFOLLOW ? O_NOFOLLOW : 0)));
+ (O_SEARCH | O_DIRECTORY | O_NOCTTY | O_NONBLOCK
+ | (options & SAVEWD_CHDIR_NOFOLLOW ? O_NOFOLLOW : 0)));
if (open_result)
- {
- open_result[0] = fd;
- open_result[1] = errno;
- }
+ {
+ open_result[0] = fd;
+ open_result[1] = errno;
+ }
- if (fd < 0 && (errno != EACCES || (options & SAVEWD_CHDIR_READABLE)))
- result = -1;
+ if (fd < 0 && errno != EACCES)
+ result = -1;
}
if (result == 0 && ! (0 <= fd && options & SAVEWD_CHDIR_SKIP_READABLE))
{
if (savewd_save (wd))
- {
- open_result = NULL;
- result = -2;
- }
+ {
+ open_result = NULL;
+ result = -2;
+ }
else
- {
- result = (fd < 0 ? chdir (dir) : fchdir (fd));
-
- if (result == 0)
- switch (wd->state)
- {
- case FD_STATE:
- wd->state = FD_POST_CHDIR_STATE;
- break;
-
- case ERROR_STATE:
- case FD_POST_CHDIR_STATE:
- case FINAL_STATE:
- break;
-
- case FORKING_STATE:
- assert (wd->val.child == 0);
- break;
-
- default:
- assert (false);
- }
- }
+ {
+ result = (fd < 0 ? chdir (dir) : fchdir (fd));
+
+ if (result == 0)
+ switch (wd->state)
+ {
+ case FD_STATE:
+ wd->state = FD_POST_CHDIR_STATE;
+ break;
+
+ case ERROR_STATE:
+ case FD_POST_CHDIR_STATE:
+ case FINAL_STATE:
+ break;
+
+ case FORKING_STATE:
+ assure (wd->val.child == 0);
+ break;
+
+ default:
+ assure (false);
+ }
+ }
}
if (0 <= fd && ! open_result)
@@ -171,23 +171,23 @@ savewd_restore (struct savewd *wd, int status)
case INITIAL_STATE:
case FD_STATE:
/* The working directory is the desired directory, so there's no
- work to do. */
+ work to do. */
break;
case FD_POST_CHDIR_STATE:
/* Restore the working directory using fchdir. */
if (fchdir (wd->val.fd) == 0)
- {
- wd->state = FD_STATE;
- break;
- }
+ {
+ wd->state = FD_STATE;
+ break;
+ }
else
- {
- int chdir_errno = errno;
- close (wd->val.fd);
- wd->state = ERROR_STATE;
- wd->val.errnum = chdir_errno;
- }
+ {
+ int chdir_errno = errno;
+ close (wd->val.fd);
+ wd->state = ERROR_STATE;
+ wd->val.errnum = chdir_errno;
+ }
/* Fall through. */
case ERROR_STATE:
/* Report an error if asked to restore the working directory. */
@@ -196,26 +196,26 @@ savewd_restore (struct savewd *wd, int status)
case FORKING_STATE:
/* "Restore" the working directory by waiting for the subprocess
- to finish. */
+ to finish. */
{
- pid_t child = wd->val.child;
- if (child == 0)
- _exit (status);
- if (0 < child)
- {
- int child_status;
- while (waitpid (child, &child_status, 0) < 0)
- assert (errno == EINTR);
- wd->val.child = -1;
- if (! WIFEXITED (child_status))
- raise (WTERMSIG (child_status));
- return WEXITSTATUS (child_status);
- }
+ pid_t child = wd->val.child;
+ if (child == 0)
+ _exit (status);
+ if (0 < child)
+ {
+ int child_status;
+ while (waitpid (child, &child_status, 0) < 0)
+ assure (errno == EINTR);
+ wd->val.child = -1;
+ if (! WIFEXITED (child_status))
+ raise (WTERMSIG (child_status));
+ return WEXITSTATUS (child_status);
+ }
}
break;
default:
- assert (false);
+ assure (false);
}
return 0;
@@ -236,11 +236,11 @@ savewd_finish (struct savewd *wd)
break;
case FORKING_STATE:
- assert (wd->val.child < 0);
+ assure (wd->val.child < 0);
break;
default:
- assert (false);
+ assure (false);
}
wd->state = FINAL_STATE;
@@ -256,7 +256,7 @@ savewd_finish (struct savewd *wd)
This is why savewd_chdir is broken out into another function;
savewd_chdir's callers _can_ inspect the file system to decide
whether to call savewd_chdir. */
-static inline bool
+static bool
savewd_delegating (struct savewd const *wd)
{
return wd->state == FORKING_STATE && 0 < wd->val.child;
@@ -264,8 +264,8 @@ savewd_delegating (struct savewd const *wd)
int
savewd_process_files (int n_files, char **file,
- int (*act) (char *, struct savewd *, void *),
- void *options)
+ int (*act) (char *, struct savewd *, void *),
+ void *options)
{
int i = 0;
int last_relative;
@@ -280,18 +280,18 @@ savewd_process_files (int n_files, char **file,
for (; i < last_relative; i++)
{
if (! savewd_delegating (&wd))
- {
- int s = act (file[i], &wd, options);
- if (exit_status < s)
- exit_status = s;
- }
+ {
+ int s = act (file[i], &wd, options);
+ if (exit_status < s)
+ exit_status = s;
+ }
if (! IS_ABSOLUTE_FILE_NAME (file[i + 1]))
- {
- int r = savewd_restore (&wd, exit_status);
- if (exit_status < r)
- exit_status = r;
- }
+ {
+ int r = savewd_restore (&wd, exit_status);
+ if (exit_status < r)
+ exit_status = r;
+ }
}
savewd_finish (&wd);
@@ -300,7 +300,7 @@ savewd_process_files (int n_files, char **file,
{
int s = act (file[i], &wd, options);
if (exit_status < s)
- exit_status = s;
+ exit_status = s;
}
return exit_status;
diff --git a/lib/savewd.h b/lib/savewd.h
index 880b8f1..7b454b6 100644
--- a/lib/savewd.h
+++ b/lib/savewd.h
@@ -1,11 +1,11 @@
/* Save and restore the working directory, possibly using a subprocess.
- Copyright (C) 2006 Free Software Foundation, Inc.
+ Copyright (C) 2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
@@ -24,6 +23,14 @@
#include <stdbool.h>
#include <sys/types.h>
+#ifndef _GL_INLINE_HEADER_BEGIN
+ #error "Please include config.h first."
+#endif
+_GL_INLINE_HEADER_BEGIN
+#ifndef SAVEWD_INLINE
+# define SAVEWD_INLINE _GL_INLINE
+#endif
+
/* A saved working directory. The member names and constants defined
by this structure are private to the savewd module. */
struct savewd
@@ -32,29 +39,29 @@ struct savewd
enum
{
/* This object has been created but does not yet represent
- the working directory. */
+ the working directory. */
INITIAL_STATE,
/* val.fd is the original working directory's file descriptor.
- It is still the working directory. */
+ It is still the working directory. */
FD_STATE,
/* Like FD_STATE, but the working directory has changed, so
- restoring it will require a fchdir. */
+ restoring it will require a fchdir. */
FD_POST_CHDIR_STATE,
/* Fork and let the subprocess do the work. val.child is 0 in a
- child, negative in a childless parent, and the child process
- ID in a parent with a child. */
+ child, negative in a childless parent, and the child process
+ ID in a parent with a child. */
FORKING_STATE,
/* A serious problem argues against further efforts. val.errnum
- contains the error number (e.g., EIO). */
+ contains the error number (e.g., EIO). */
ERROR_STATE,
/* savewd_finish has been called, so the application no longer
- cares whether the working directory is saved, and there is no
- more work to do. */
+ cares whether the working directory is saved, and there is no
+ more work to do. */
FINAL_STATE
} state;
@@ -68,27 +75,22 @@ struct savewd
};
/* Initialize a saved working directory object. */
-static inline void
+SAVEWD_INLINE void
savewd_init (struct savewd *wd)
{
wd->state = INITIAL_STATE;
}
-/* Options for savewd_chdir. */
+/* Options for savewd_chdir. Can be ORed together. */
enum
{
/* Do not follow symbolic links, if supported. */
SAVEWD_CHDIR_NOFOLLOW = 1,
- /* The directory should be readable, so fail if it happens to be
- discovered that the directory is not readable. (Unreadable
- directories are not necessarily diagnosed, though.) */
- SAVEWD_CHDIR_READABLE = 2,
-
/* Do not chdir if the directory is readable; simply succeed
without invoking chdir if the directory was opened. */
- SAVEWD_CHDIR_SKIP_READABLE = 4
+ SAVEWD_CHDIR_SKIP_READABLE = 2
};
/* Change the directory, and if successful, record into *WD the fact
@@ -107,7 +109,7 @@ enum
Return -2 if a subprocess was spun off to do the real work, -1
(setting errno) if unsuccessful, 0 if successful. */
int savewd_chdir (struct savewd *wd, char const *dir, int options,
- int open_result[2]);
+ int open_result[2]);
/* Restore the working directory from *WD. STATUS indicates the exit
status corresponding to the work done since the last save; this is
@@ -118,7 +120,7 @@ int savewd_chdir (struct savewd *wd, char const *dir, int options,
int savewd_restore (struct savewd *wd, int status);
/* Return WD's error number, or 0 if WD is not in an error state. */
-static inline int
+SAVEWD_INLINE int _GL_ATTRIBUTE_PURE
savewd_errno (struct savewd const *wd)
{
return (wd->state == ERROR_STATE ? wd->val.errnum : 0);
@@ -143,7 +145,9 @@ void savewd_finish (struct savewd *wd);
Return the maximum exit status that any call to ACT returned, or
EXIT_SUCCESS (i.e., 0) if no calls were made. */
int savewd_process_files (int n_files, char **file,
- int (*act) (char *, struct savewd *, void *),
- void *options);
+ int (*act) (char *, struct savewd *, void *),
+ void *options);
+
+_GL_INLINE_HEADER_END
#endif
diff --git a/lib/sched.in.h b/lib/sched.in.h
new file mode 100644
index 0000000..1c0fe59
--- /dev/null
+++ b/lib/sched.in.h
@@ -0,0 +1,64 @@
+/* Replacement <sched.h> for platforms that lack it.
+ Copyright (C) 2008-2016 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _@GUARD_PREFIX@_SCHED_H
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+/* The include_next requires a split double-inclusion guard. */
+#if @HAVE_SCHED_H@
+# @INCLUDE_NEXT@ @NEXT_SCHED_H@
+#endif
+
+#ifndef _@GUARD_PREFIX@_SCHED_H
+#define _@GUARD_PREFIX@_SCHED_H
+
+/* Get pid_t.
+ This is needed on glibc 2.11 (see
+ glibc bug <http://sourceware.org/bugzilla/show_bug.cgi?id=13198>)
+ and Mac OS X 10.5. */
+#include <sys/types.h>
+
+#ifdef __KLIBC__
+
+/* On OS/2 kLIBC, struct sched_param is in spawn.h */
+# include <spawn.h>
+
+#endif
+
+#if !@HAVE_STRUCT_SCHED_PARAM@
+
+# if !GNULIB_defined_struct_sched_param
+struct sched_param
+{
+ int sched_priority;
+};
+# define GNULIB_defined_struct_sched_param 1
+# endif
+
+#endif
+
+#if !(defined SCHED_FIFO && defined SCHED_RR && defined SCHED_OTHER)
+# define SCHED_FIFO 1
+# define SCHED_RR 2
+# define SCHED_OTHER 0
+#endif
+
+#endif /* _@GUARD_PREFIX@_SCHED_H */
+#endif /* _@GUARD_PREFIX@_SCHED_H */
diff --git a/lib/se-context.c b/lib/se-context.c
new file mode 100644
index 0000000..2e5aa13
--- /dev/null
+++ b/lib/se-context.c
@@ -0,0 +1,3 @@
+#include <config.h>
+#define SE_CONTEXT_INLINE _GL_EXTERN_INLINE
+#include <selinux/context.h>
diff --git a/lib/se-context.in.h b/lib/se-context.in.h
new file mode 100644
index 0000000..c3890a2
--- /dev/null
+++ b/lib/se-context.in.h
@@ -0,0 +1,46 @@
+#ifndef SELINUX_CONTEXT_H
+# define SELINUX_CONTEXT_H
+
+# include <errno.h>
+
+#ifndef _GL_INLINE_HEADER_BEGIN
+ #error "Please include config.h first."
+#endif
+_GL_INLINE_HEADER_BEGIN
+#ifndef SE_CONTEXT_INLINE
+# define SE_CONTEXT_INLINE _GL_INLINE
+#endif
+
+/* The definition of _GL_UNUSED_PARAMETER is copied here. */
+
+typedef int context_t;
+SE_CONTEXT_INLINE context_t context_new (char const *s _GL_UNUSED_PARAMETER)
+ { errno = ENOTSUP; return 0; }
+SE_CONTEXT_INLINE char *context_str (context_t con _GL_UNUSED_PARAMETER)
+ { errno = ENOTSUP; return (void *) 0; }
+SE_CONTEXT_INLINE void context_free (context_t c _GL_UNUSED_PARAMETER) {}
+
+SE_CONTEXT_INLINE int context_user_set (context_t sc _GL_UNUSED_PARAMETER,
+ char const *s _GL_UNUSED_PARAMETER)
+ { errno = ENOTSUP; return -1; }
+SE_CONTEXT_INLINE int context_role_set (context_t sc _GL_UNUSED_PARAMETER,
+ char const *s _GL_UNUSED_PARAMETER)
+ { errno = ENOTSUP; return -1; }
+SE_CONTEXT_INLINE int context_range_set (context_t sc _GL_UNUSED_PARAMETER,
+ char const *s _GL_UNUSED_PARAMETER)
+ { errno = ENOTSUP; return -1; }
+SE_CONTEXT_INLINE int context_type_set (context_t sc _GL_UNUSED_PARAMETER,
+ char const *s _GL_UNUSED_PARAMETER)
+ { errno = ENOTSUP; return -1; }
+SE_CONTEXT_INLINE char *context_type_get (context_t sc _GL_UNUSED_PARAMETER)
+ { errno = ENOTSUP; return (void *) 0; }
+SE_CONTEXT_INLINE char *context_range_get (context_t sc _GL_UNUSED_PARAMETER)
+ { errno = ENOTSUP; return (void *) 0; }
+SE_CONTEXT_INLINE char *context_role_get (context_t sc _GL_UNUSED_PARAMETER)
+ { errno = ENOTSUP; return (void *) 0; }
+SE_CONTEXT_INLINE char *context_user_get (context_t sc _GL_UNUSED_PARAMETER)
+ { errno = ENOTSUP; return (void *) 0; }
+
+_GL_INLINE_HEADER_END
+
+#endif
diff --git a/lib/se-selinux.c b/lib/se-selinux.c
new file mode 100644
index 0000000..ee4e57f
--- /dev/null
+++ b/lib/se-selinux.c
@@ -0,0 +1,3 @@
+#include <config.h>
+#define SE_SELINUX_INLINE _GL_EXTERN_INLINE
+#include <selinux/selinux.h>
diff --git a/lib/se-selinux.in.h b/lib/se-selinux.in.h
new file mode 100644
index 0000000..dd56e27
--- /dev/null
+++ b/lib/se-selinux.in.h
@@ -0,0 +1,123 @@
+/* Replacement <selinux/selinux.h> for platforms that lack it.
+ Copyright (C) 2008-2016 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _@GUARD_PREFIX@_SELINUX_SELINUX_H
+# define _@GUARD_PREFIX@_SELINUX_SELINUX_H
+
+# if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+# endif
+@PRAGMA_COLUMNS@
+
+# if HAVE_SELINUX_SELINUX_H
+
+#@INCLUDE_NEXT@ @NEXT_SELINUX_SELINUX_H@
+
+# else
+
+# include <sys/types.h>
+# include <errno.h>
+
+#ifndef _GL_INLINE_HEADER_BEGIN
+ #error "Please include config.h first."
+#endif
+_GL_INLINE_HEADER_BEGIN
+# ifndef SE_SELINUX_INLINE
+# define SE_SELINUX_INLINE _GL_INLINE
+# endif
+
+/* The definition of _GL_UNUSED_PARAMETER is copied here. */
+
+# if !GNULIB_defined_security_types
+
+typedef unsigned short security_class_t;
+typedef char *security_context_t;
+# define is_selinux_enabled() 0
+
+SE_SELINUX_INLINE int
+getcon (security_context_t *con _GL_UNUSED_PARAMETER)
+ { errno = ENOTSUP; return -1; }
+SE_SELINUX_INLINE void
+freecon (security_context_t con _GL_UNUSED_PARAMETER) {}
+
+SE_SELINUX_INLINE int
+getfscreatecon (security_context_t *con _GL_UNUSED_PARAMETER)
+ { errno = ENOTSUP; return -1; }
+SE_SELINUX_INLINE int
+setfscreatecon (security_context_t con _GL_UNUSED_PARAMETER)
+ { errno = ENOTSUP; return -1; }
+SE_SELINUX_INLINE int
+matchpathcon (char const *file _GL_UNUSED_PARAMETER,
+ mode_t m _GL_UNUSED_PARAMETER,
+ security_context_t *con _GL_UNUSED_PARAMETER)
+ { errno = ENOTSUP; return -1; }
+SE_SELINUX_INLINE int
+getfilecon (char const *file _GL_UNUSED_PARAMETER,
+ security_context_t *con _GL_UNUSED_PARAMETER)
+ { errno = ENOTSUP; return -1; }
+SE_SELINUX_INLINE int
+lgetfilecon (char const *file _GL_UNUSED_PARAMETER,
+ security_context_t *con _GL_UNUSED_PARAMETER)
+ { errno = ENOTSUP; return -1; }
+SE_SELINUX_INLINE int
+fgetfilecon (int fd, security_context_t *con _GL_UNUSED_PARAMETER)
+ { errno = ENOTSUP; return -1; }
+SE_SELINUX_INLINE int
+setfilecon (char const *file _GL_UNUSED_PARAMETER,
+ security_context_t con _GL_UNUSED_PARAMETER)
+ { errno = ENOTSUP; return -1; }
+SE_SELINUX_INLINE int
+lsetfilecon (char const *file _GL_UNUSED_PARAMETER,
+ security_context_t con _GL_UNUSED_PARAMETER)
+ { errno = ENOTSUP; return -1; }
+SE_SELINUX_INLINE int
+fsetfilecon (int fd _GL_UNUSED_PARAMETER,
+ security_context_t con _GL_UNUSED_PARAMETER)
+ { errno = ENOTSUP; return -1; }
+
+SE_SELINUX_INLINE int
+security_check_context (security_context_t con _GL_UNUSED_PARAMETER)
+ { errno = ENOTSUP; return -1; }
+SE_SELINUX_INLINE int
+security_check_context_raw (security_context_t con _GL_UNUSED_PARAMETER)
+ { errno = ENOTSUP; return -1; }
+SE_SELINUX_INLINE int
+setexeccon (security_context_t con _GL_UNUSED_PARAMETER)
+ { errno = ENOTSUP; return -1; }
+SE_SELINUX_INLINE int
+security_compute_create (security_context_t scon _GL_UNUSED_PARAMETER,
+ security_context_t tcon _GL_UNUSED_PARAMETER,
+ security_class_t tclass _GL_UNUSED_PARAMETER,
+ security_context_t *newcon _GL_UNUSED_PARAMETER)
+ { errno = ENOTSUP; return -1; }
+SE_SELINUX_INLINE security_class_t
+string_to_security_class (char const *name)
+ { errno = ENOTSUP; return 0; }
+SE_SELINUX_INLINE int
+matchpathcon_init_prefix (char const *path _GL_UNUSED_PARAMETER,
+ char const *prefix _GL_UNUSED_PARAMETER)
+ { errno = ENOTSUP; return -1; }
+
+# define GNULIB_defined_security_types 1
+# endif
+
+#ifndef _GL_INLINE_HEADER_BEGIN
+ #error "Please include config.h first."
+#endif
+_GL_INLINE_HEADER_BEGIN
+
+# endif
+#endif /* _@GUARD_PREFIX@_SELINUX_SELINUX_H */
diff --git a/lib/secure_getenv.c b/lib/secure_getenv.c
new file mode 100644
index 0000000..f359ab2
--- /dev/null
+++ b/lib/secure_getenv.c
@@ -0,0 +1,41 @@
+/* Look up an environment variable more securely.
+
+ Copyright 2013-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+#include <stdlib.h>
+
+#if !HAVE___SECURE_GETENV
+# if HAVE_ISSETUGID
+# include <unistd.h>
+# else
+# undef issetugid
+# define issetugid() 1
+# endif
+#endif
+
+char *
+secure_getenv (char const *name)
+{
+#if HAVE___SECURE_GETENV
+ return __secure_getenv (name);
+#else
+ if (issetugid ())
+ return 0;
+ return getenv (name);
+#endif
+}
diff --git a/lib/select.c b/lib/select.c
new file mode 100644
index 0000000..73abcf3
--- /dev/null
+++ b/lib/select.c
@@ -0,0 +1,575 @@
+/* Emulation for select(2)
+ Contributed by Paolo Bonzini.
+
+ Copyright 2008-2016 Free Software Foundation, Inc.
+
+ This file is part of gnulib.
+
+ 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, 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+#include <alloca.h>
+#include <assert.h>
+
+#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+/* Native Windows. */
+
+#include <sys/types.h>
+#include <errno.h>
+#include <limits.h>
+
+#include <winsock2.h>
+#include <windows.h>
+#include <io.h>
+#include <stdio.h>
+#include <conio.h>
+#include <time.h>
+
+/* Get the overridden 'struct timeval'. */
+#include <sys/time.h>
+
+#include "msvc-nothrow.h"
+
+#undef select
+
+struct bitset {
+ unsigned char in[FD_SETSIZE / CHAR_BIT];
+ unsigned char out[FD_SETSIZE / CHAR_BIT];
+};
+
+/* Declare data structures for ntdll functions. */
+typedef struct _FILE_PIPE_LOCAL_INFORMATION {
+ ULONG NamedPipeType;
+ ULONG NamedPipeConfiguration;
+ ULONG MaximumInstances;
+ ULONG CurrentInstances;
+ ULONG InboundQuota;
+ ULONG ReadDataAvailable;
+ ULONG OutboundQuota;
+ ULONG WriteQuotaAvailable;
+ ULONG NamedPipeState;
+ ULONG NamedPipeEnd;
+} FILE_PIPE_LOCAL_INFORMATION, *PFILE_PIPE_LOCAL_INFORMATION;
+
+typedef struct _IO_STATUS_BLOCK
+{
+ union {
+ DWORD Status;
+ PVOID Pointer;
+ } u;
+ ULONG_PTR Information;
+} IO_STATUS_BLOCK, *PIO_STATUS_BLOCK;
+
+typedef enum _FILE_INFORMATION_CLASS {
+ FilePipeLocalInformation = 24
+} FILE_INFORMATION_CLASS, *PFILE_INFORMATION_CLASS;
+
+typedef DWORD (WINAPI *PNtQueryInformationFile)
+ (HANDLE, IO_STATUS_BLOCK *, VOID *, ULONG, FILE_INFORMATION_CLASS);
+
+#ifndef PIPE_BUF
+#define PIPE_BUF 512
+#endif
+
+static BOOL IsConsoleHandle (HANDLE h)
+{
+ DWORD mode;
+ return GetConsoleMode (h, &mode) != 0;
+}
+
+static BOOL
+IsSocketHandle (HANDLE h)
+{
+ WSANETWORKEVENTS ev;
+
+ if (IsConsoleHandle (h))
+ return FALSE;
+
+ /* Under Wine, it seems that getsockopt returns 0 for pipes too.
+ WSAEnumNetworkEvents instead distinguishes the two correctly. */
+ ev.lNetworkEvents = 0xDEADBEEF;
+ WSAEnumNetworkEvents ((SOCKET) h, NULL, &ev);
+ return ev.lNetworkEvents != 0xDEADBEEF;
+}
+
+/* Compute output fd_sets for libc descriptor FD (whose Windows handle is
+ H). */
+
+static int
+windows_poll_handle (HANDLE h, int fd,
+ struct bitset *rbits,
+ struct bitset *wbits,
+ struct bitset *xbits)
+{
+ BOOL read, write, except;
+ int i, ret;
+ INPUT_RECORD *irbuffer;
+ DWORD avail, nbuffer;
+ BOOL bRet;
+ IO_STATUS_BLOCK iosb;
+ FILE_PIPE_LOCAL_INFORMATION fpli;
+ static PNtQueryInformationFile NtQueryInformationFile;
+ static BOOL once_only;
+
+ read = write = except = FALSE;
+ switch (GetFileType (h))
+ {
+ case FILE_TYPE_DISK:
+ read = TRUE;
+ write = TRUE;
+ break;
+
+ case FILE_TYPE_PIPE:
+ if (!once_only)
+ {
+ NtQueryInformationFile = (PNtQueryInformationFile)
+ GetProcAddress (GetModuleHandle ("ntdll.dll"),
+ "NtQueryInformationFile");
+ once_only = TRUE;
+ }
+
+ if (PeekNamedPipe (h, NULL, 0, NULL, &avail, NULL) != 0)
+ {
+ if (avail)
+ read = TRUE;
+ }
+ else if (GetLastError () == ERROR_BROKEN_PIPE)
+ ;
+
+ else
+ {
+ /* It was the write-end of the pipe. Check if it is writable.
+ If NtQueryInformationFile fails, optimistically assume the pipe is
+ writable. This could happen on Windows 9x, where
+ NtQueryInformationFile is not available, or if we inherit a pipe
+ that doesn't permit FILE_READ_ATTRIBUTES access on the write end
+ (I think this should not happen since Windows XP SP2; WINE seems
+ fine too). Otherwise, ensure that enough space is available for
+ atomic writes. */
+ memset (&iosb, 0, sizeof (iosb));
+ memset (&fpli, 0, sizeof (fpli));
+
+ if (!NtQueryInformationFile
+ || NtQueryInformationFile (h, &iosb, &fpli, sizeof (fpli),
+ FilePipeLocalInformation)
+ || fpli.WriteQuotaAvailable >= PIPE_BUF
+ || (fpli.OutboundQuota < PIPE_BUF &&
+ fpli.WriteQuotaAvailable == fpli.OutboundQuota))
+ write = TRUE;
+ }
+ break;
+
+ case FILE_TYPE_CHAR:
+ write = TRUE;
+ if (!(rbits->in[fd / CHAR_BIT] & (1 << (fd & (CHAR_BIT - 1)))))
+ break;
+
+ ret = WaitForSingleObject (h, 0);
+ if (ret == WAIT_OBJECT_0)
+ {
+ if (!IsConsoleHandle (h))
+ {
+ read = TRUE;
+ break;
+ }
+
+ nbuffer = avail = 0;
+ bRet = GetNumberOfConsoleInputEvents (h, &nbuffer);
+
+ /* Screen buffers handles are filtered earlier. */
+ assert (bRet);
+ if (nbuffer == 0)
+ {
+ except = TRUE;
+ break;
+ }
+
+ irbuffer = (INPUT_RECORD *) alloca (nbuffer * sizeof (INPUT_RECORD));
+ bRet = PeekConsoleInput (h, irbuffer, nbuffer, &avail);
+ if (!bRet || avail == 0)
+ {
+ except = TRUE;
+ break;
+ }
+
+ for (i = 0; i < avail; i++)
+ if (irbuffer[i].EventType == KEY_EVENT)
+ read = TRUE;
+ }
+ break;
+
+ default:
+ ret = WaitForSingleObject (h, 0);
+ write = TRUE;
+ if (ret == WAIT_OBJECT_0)
+ read = TRUE;
+
+ break;
+ }
+
+ ret = 0;
+ if (read && (rbits->in[fd / CHAR_BIT] & (1 << (fd & (CHAR_BIT - 1)))))
+ {
+ rbits->out[fd / CHAR_BIT] |= (1 << (fd & (CHAR_BIT - 1)));
+ ret++;
+ }
+
+ if (write && (wbits->in[fd / CHAR_BIT] & (1 << (fd & (CHAR_BIT - 1)))))
+ {
+ wbits->out[fd / CHAR_BIT] |= (1 << (fd & (CHAR_BIT - 1)));
+ ret++;
+ }
+
+ if (except && (xbits->in[fd / CHAR_BIT] & (1 << (fd & (CHAR_BIT - 1)))))
+ {
+ xbits->out[fd / CHAR_BIT] |= (1 << (fd & (CHAR_BIT - 1)));
+ ret++;
+ }
+
+ return ret;
+}
+
+int
+rpl_select (int nfds, fd_set *rfds, fd_set *wfds, fd_set *xfds,
+ struct timeval *timeout)
+#undef timeval
+{
+ static struct timeval tv0;
+ static HANDLE hEvent;
+ HANDLE h, handle_array[FD_SETSIZE + 2];
+ fd_set handle_rfds, handle_wfds, handle_xfds;
+ struct bitset rbits, wbits, xbits;
+ unsigned char anyfds_in[FD_SETSIZE / CHAR_BIT];
+ DWORD ret, wait_timeout, nhandles, nsock, nbuffer;
+ MSG msg;
+ int i, fd, rc;
+ clock_t tend;
+
+ if (nfds > FD_SETSIZE)
+ nfds = FD_SETSIZE;
+
+ if (!timeout)
+ wait_timeout = INFINITE;
+ else
+ {
+ wait_timeout = timeout->tv_sec * 1000 + timeout->tv_usec / 1000;
+
+ /* select is also used as a portable usleep. */
+ if (!rfds && !wfds && !xfds)
+ {
+ Sleep (wait_timeout);
+ return 0;
+ }
+ }
+
+ if (!hEvent)
+ hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
+
+ handle_array[0] = hEvent;
+ nhandles = 1;
+ nsock = 0;
+
+ /* Copy descriptors to bitsets. At the same time, eliminate
+ bits in the "wrong" direction for console input buffers
+ and screen buffers, because screen buffers are waitable
+ and they will block until a character is available. */
+ memset (&rbits, 0, sizeof (rbits));
+ memset (&wbits, 0, sizeof (wbits));
+ memset (&xbits, 0, sizeof (xbits));
+ memset (anyfds_in, 0, sizeof (anyfds_in));
+ if (rfds)
+ for (i = 0; i < rfds->fd_count; i++)
+ {
+ fd = rfds->fd_array[i];
+ h = (HANDLE) _get_osfhandle (fd);
+ if (IsConsoleHandle (h)
+ && !GetNumberOfConsoleInputEvents (h, &nbuffer))
+ continue;
+
+ rbits.in[fd / CHAR_BIT] |= 1 << (fd & (CHAR_BIT - 1));
+ anyfds_in[fd / CHAR_BIT] |= 1 << (fd & (CHAR_BIT - 1));
+ }
+ else
+ rfds = (fd_set *) alloca (sizeof (fd_set));
+
+ if (wfds)
+ for (i = 0; i < wfds->fd_count; i++)
+ {
+ fd = wfds->fd_array[i];
+ h = (HANDLE) _get_osfhandle (fd);
+ if (IsConsoleHandle (h)
+ && GetNumberOfConsoleInputEvents (h, &nbuffer))
+ continue;
+
+ wbits.in[fd / CHAR_BIT] |= 1 << (fd & (CHAR_BIT - 1));
+ anyfds_in[fd / CHAR_BIT] |= 1 << (fd & (CHAR_BIT - 1));
+ }
+ else
+ wfds = (fd_set *) alloca (sizeof (fd_set));
+
+ if (xfds)
+ for (i = 0; i < xfds->fd_count; i++)
+ {
+ fd = xfds->fd_array[i];
+ xbits.in[fd / CHAR_BIT] |= 1 << (fd & (CHAR_BIT - 1));
+ anyfds_in[fd / CHAR_BIT] |= 1 << (fd & (CHAR_BIT - 1));
+ }
+ else
+ xfds = (fd_set *) alloca (sizeof (fd_set));
+
+ /* Zero all the fd_sets, including the application's. */
+ FD_ZERO (rfds);
+ FD_ZERO (wfds);
+ FD_ZERO (xfds);
+ FD_ZERO (&handle_rfds);
+ FD_ZERO (&handle_wfds);
+ FD_ZERO (&handle_xfds);
+
+ /* Classify handles. Create fd sets for sockets, poll the others. */
+ for (i = 0; i < nfds; i++)
+ {
+ if ((anyfds_in[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1)))) == 0)
+ continue;
+
+ h = (HANDLE) _get_osfhandle (i);
+ if (!h)
+ {
+ errno = EBADF;
+ return -1;
+ }
+
+ if (IsSocketHandle (h))
+ {
+ int requested = FD_CLOSE;
+
+ /* See above; socket handles are mapped onto select, but we
+ need to map descriptors to handles. */
+ if (rbits.in[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1))))
+ {
+ requested |= FD_READ | FD_ACCEPT;
+ FD_SET ((SOCKET) h, rfds);
+ FD_SET ((SOCKET) h, &handle_rfds);
+ }
+ if (wbits.in[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1))))
+ {
+ requested |= FD_WRITE | FD_CONNECT;
+ FD_SET ((SOCKET) h, wfds);
+ FD_SET ((SOCKET) h, &handle_wfds);
+ }
+ if (xbits.in[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1))))
+ {
+ requested |= FD_OOB;
+ FD_SET ((SOCKET) h, xfds);
+ FD_SET ((SOCKET) h, &handle_xfds);
+ }
+
+ WSAEventSelect ((SOCKET) h, hEvent, requested);
+ nsock++;
+ }
+ else
+ {
+ handle_array[nhandles++] = h;
+
+ /* Poll now. If we get an event, do not wait below. */
+ if (wait_timeout != 0
+ && windows_poll_handle (h, i, &rbits, &wbits, &xbits))
+ wait_timeout = 0;
+ }
+ }
+
+ /* Place a sentinel at the end of the array. */
+ handle_array[nhandles] = NULL;
+
+ /* When will the waiting period expire? */
+ if (wait_timeout != INFINITE)
+ tend = clock () + wait_timeout;
+
+restart:
+ if (wait_timeout == 0 || nsock == 0)
+ rc = 0;
+ else
+ {
+ /* See if we need to wait in the loop below. If any select is ready,
+ do MsgWaitForMultipleObjects anyway to dispatch messages, but
+ no need to call select again. */
+ rc = select (0, &handle_rfds, &handle_wfds, &handle_xfds, &tv0);
+ if (rc == 0)
+ {
+ /* Restore the fd_sets for the other select we do below. */
+ memcpy (&handle_rfds, rfds, sizeof (fd_set));
+ memcpy (&handle_wfds, wfds, sizeof (fd_set));
+ memcpy (&handle_xfds, xfds, sizeof (fd_set));
+ }
+ else
+ wait_timeout = 0;
+ }
+
+ /* How much is left to wait? */
+ if (wait_timeout != INFINITE)
+ {
+ clock_t tnow = clock ();
+ if (tend >= tnow)
+ wait_timeout = tend - tnow;
+ else
+ wait_timeout = 0;
+ }
+
+ for (;;)
+ {
+ ret = MsgWaitForMultipleObjects (nhandles, handle_array, FALSE,
+ wait_timeout, QS_ALLINPUT);
+
+ if (ret == WAIT_OBJECT_0 + nhandles)
+ {
+ /* new input of some other kind */
+ BOOL bRet;
+ while ((bRet = PeekMessage (&msg, NULL, 0, 0, PM_REMOVE)) != 0)
+ {
+ TranslateMessage (&msg);
+ DispatchMessage (&msg);
+ }
+ }
+ else
+ break;
+ }
+
+ /* If we haven't done it yet, check the status of the sockets. */
+ if (rc == 0 && nsock > 0)
+ rc = select (0, &handle_rfds, &handle_wfds, &handle_xfds, &tv0);
+
+ if (nhandles > 1)
+ {
+ /* Count results that are not counted in the return value of select. */
+ nhandles = 1;
+ for (i = 0; i < nfds; i++)
+ {
+ if ((anyfds_in[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1)))) == 0)
+ continue;
+
+ h = (HANDLE) _get_osfhandle (i);
+ if (h == handle_array[nhandles])
+ {
+ /* Not a socket. */
+ nhandles++;
+ windows_poll_handle (h, i, &rbits, &wbits, &xbits);
+ if (rbits.out[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1)))
+ || wbits.out[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1)))
+ || xbits.out[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1))))
+ rc++;
+ }
+ }
+
+ if (rc == 0
+ && (wait_timeout == INFINITE
+ /* If NHANDLES > 1, but no bits are set, it means we've
+ been told incorrectly that some handle was signaled.
+ This happens with anonymous pipes, which always cause
+ MsgWaitForMultipleObjects to exit immediately, but no
+ data is found ready to be read by windows_poll_handle.
+ To avoid a total failure (whereby we return zero and
+ don't wait at all), let's poll in a more busy loop. */
+ || (wait_timeout != 0 && nhandles > 1)))
+ {
+ /* Sleep 1 millisecond to avoid busy wait and retry with the
+ original fd_sets. */
+ memcpy (&handle_rfds, rfds, sizeof (fd_set));
+ memcpy (&handle_wfds, wfds, sizeof (fd_set));
+ memcpy (&handle_xfds, xfds, sizeof (fd_set));
+ SleepEx (1, TRUE);
+ goto restart;
+ }
+ if (timeout && wait_timeout == 0 && rc == 0)
+ timeout->tv_sec = timeout->tv_usec = 0;
+ }
+
+ /* Now fill in the results. */
+ FD_ZERO (rfds);
+ FD_ZERO (wfds);
+ FD_ZERO (xfds);
+ nhandles = 1;
+ for (i = 0; i < nfds; i++)
+ {
+ if ((anyfds_in[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1)))) == 0)
+ continue;
+
+ h = (HANDLE) _get_osfhandle (i);
+ if (h != handle_array[nhandles])
+ {
+ /* Perform handle->descriptor mapping. */
+ WSAEventSelect ((SOCKET) h, NULL, 0);
+ if (FD_ISSET (h, &handle_rfds))
+ FD_SET (i, rfds);
+ if (FD_ISSET (h, &handle_wfds))
+ FD_SET (i, wfds);
+ if (FD_ISSET (h, &handle_xfds))
+ FD_SET (i, xfds);
+ }
+ else
+ {
+ /* Not a socket. */
+ nhandles++;
+ if (rbits.out[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1))))
+ FD_SET (i, rfds);
+ if (wbits.out[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1))))
+ FD_SET (i, wfds);
+ if (xbits.out[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1))))
+ FD_SET (i, xfds);
+ }
+ }
+
+ return rc;
+}
+
+#else /* ! Native Windows. */
+
+#include <sys/select.h>
+#include <stddef.h> /* NULL */
+#include <errno.h>
+#include <unistd.h>
+
+#undef select
+
+int
+rpl_select (int nfds, fd_set *rfds, fd_set *wfds, fd_set *xfds,
+ struct timeval *timeout)
+{
+ int i;
+
+ /* FreeBSD 8.2 has a bug: it does not always detect invalid fds. */
+ if (nfds < 0 || nfds > FD_SETSIZE)
+ {
+ errno = EINVAL;
+ return -1;
+ }
+ for (i = 0; i < nfds; i++)
+ {
+ if (((rfds && FD_ISSET (i, rfds))
+ || (wfds && FD_ISSET (i, wfds))
+ || (xfds && FD_ISSET (i, xfds)))
+ && dup2 (i, i) != i)
+ return -1;
+ }
+
+ /* Interix 3.5 has a bug: it does not support nfds == 0. */
+ if (nfds == 0)
+ {
+ nfds = 1;
+ rfds = NULL;
+ wfds = NULL;
+ xfds = NULL;
+ }
+ return select (nfds, rfds, wfds, xfds, timeout);
+}
+
+#endif
diff --git a/lib/selinux-at.c b/lib/selinux-at.c
new file mode 100644
index 0000000..a798d8e
--- /dev/null
+++ b/lib/selinux-at.c
@@ -0,0 +1,71 @@
+/* openat-style fd-relative functions for SE Linux
+ Copyright (C) 2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* written by Jim Meyering */
+
+#include <config.h>
+
+#include "selinux-at.h"
+#include "openat.h"
+
+#include <stdlib.h>
+#include <unistd.h>
+#include <errno.h>
+#include <fcntl.h>
+
+#include "save-cwd.h"
+
+#include "openat-priv.h"
+
+#define AT_FUNC_NAME getfileconat
+#define AT_FUNC_F1 getfilecon
+#define AT_FUNC_POST_FILE_PARAM_DECLS , security_context_t *con
+#define AT_FUNC_POST_FILE_ARGS , con
+#include "at-func.c"
+#undef AT_FUNC_NAME
+#undef AT_FUNC_F1
+#undef AT_FUNC_POST_FILE_PARAM_DECLS
+#undef AT_FUNC_POST_FILE_ARGS
+
+#define AT_FUNC_NAME lgetfileconat
+#define AT_FUNC_F1 lgetfilecon
+#define AT_FUNC_POST_FILE_PARAM_DECLS , security_context_t *con
+#define AT_FUNC_POST_FILE_ARGS , con
+#include "at-func.c"
+#undef AT_FUNC_NAME
+#undef AT_FUNC_F1
+#undef AT_FUNC_POST_FILE_PARAM_DECLS
+#undef AT_FUNC_POST_FILE_ARGS
+
+#define AT_FUNC_NAME setfileconat
+#define AT_FUNC_F1 setfilecon
+#define AT_FUNC_POST_FILE_PARAM_DECLS , security_context_t con
+#define AT_FUNC_POST_FILE_ARGS , con
+#include "at-func.c"
+#undef AT_FUNC_NAME
+#undef AT_FUNC_F1
+#undef AT_FUNC_POST_FILE_PARAM_DECLS
+#undef AT_FUNC_POST_FILE_ARGS
+
+#define AT_FUNC_NAME lsetfileconat
+#define AT_FUNC_F1 lsetfilecon
+#define AT_FUNC_POST_FILE_PARAM_DECLS , security_context_t con
+#define AT_FUNC_POST_FILE_ARGS , con
+#include "at-func.c"
+#undef AT_FUNC_NAME
+#undef AT_FUNC_F1
+#undef AT_FUNC_POST_FILE_PARAM_DECLS
+#undef AT_FUNC_POST_FILE_ARGS
diff --git a/lib/selinux-at.h b/lib/selinux-at.h
new file mode 100644
index 0000000..20baaae
--- /dev/null
+++ b/lib/selinux-at.h
@@ -0,0 +1,52 @@
+/* Prototypes for openat-style fd-relative SELinux functions
+ Copyright (C) 2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <selinux/selinux.h>
+#include <selinux/context.h>
+
+/* These are the dir-fd-relative variants of the functions without the
+ "at" suffix. For example, getfileconat (AT_FDCWD, file, &c) is usually
+ equivalent to getfilecon (file, &c). The emulation is accomplished
+ by first attempting getfilecon ("/proc/self/fd/DIR_FD/FILE", &c).
+ Failing that, simulate it via save_cwd/fchdir/getfilecon/restore_cwd.
+ If either the save_cwd or the restore_cwd fails (relatively unlikely),
+ then give a diagnostic and exit nonzero. */
+
+/* dir-fd-relative getfilecon. Set *CON to the SELinux security context
+ of the file specified by DIR_FD and FILE and return the length of *CON.
+ DIR_FD and FILE are interpreted as for fstatat[*]. A non-NULL *CON
+ must be freed with freecon. Upon error, set *CON to NULL, set errno
+ and return -1.
+ [*] with flags=0 here, with flags=AT_SYMLINK_NOFOLLOW for lgetfileconat */
+int getfileconat (int dir_fd, char const *file, security_context_t *con);
+
+/* dir-fd-relative lgetfilecon. This function is just like getfileconat,
+ except when DIR_FD and FILE specify a symlink: lgetfileconat operates on
+ the symlink, while getfileconat operates on the referent of the symlink. */
+int lgetfileconat (int dir_fd, char const *file, security_context_t *con);
+
+/* dir-fd-relative setfilecon. Set the SELinux security context of
+ the file specified by DIR_FD and FILE to CON. DIR_FD and FILE are
+ interpreted as for fstatat[*]. Upon success, return 0.
+ Otherwise, return -1 and set errno. */
+int setfileconat (int dir_fd, char const *file, security_context_t con);
+
+/* dir-fd-relative lsetfilecon. This function is just like setfileconat,
+ except that rather than dereferencing a symlink, this function affects it. */
+/* dir-fd-relative lsetfilecon. This function is just like setfileconat,
+ except when DIR_FD and FILE specify a symlink: lsetfileconat operates on
+ the symlink, while setfileconat operates on the referent of the symlink. */
+int lsetfileconat (int dir_fd, char const *file, security_context_t con);
diff --git a/lib/set-acl.c b/lib/set-acl.c
new file mode 100644
index 0000000..fbb5c16
--- /dev/null
+++ b/lib/set-acl.c
@@ -0,0 +1,48 @@
+/* set-acl.c - set access control list equivalent to a mode
+
+ Copyright (C) 2002-2003, 2005-2016 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 <http://www.gnu.org/licenses/>.
+
+ Written by Paul Eggert and Andreas Gruenbacher, and Bruno Haible. */
+
+#include <config.h>
+
+#include "acl.h"
+
+#include <errno.h>
+
+#include "quote.h"
+#include "error.h"
+#include "gettext.h"
+#define _(msgid) gettext (msgid)
+
+
+/* Set the access control lists of a file. If DESC is a valid file
+ descriptor, use file descriptor operations where available, else use
+ filename based operations on NAME. If access control lists are not
+ available, fchmod the target file to MODE. Also sets the
+ non-permission bits of the destination file (S_ISUID, S_ISGID, S_ISVTX)
+ to those from MODE if any are set.
+ Return 0 if successful. On failure, output a diagnostic, set errno and
+ return -1. */
+
+int
+set_acl (char const *name, int desc, mode_t mode)
+{
+ int ret = qset_acl (name, desc, mode);
+ if (ret != 0)
+ error (0, errno, _("setting permissions for %s"), quote (name));
+ return ret;
+}
diff --git a/lib/set-permissions.c b/lib/set-permissions.c
new file mode 100644
index 0000000..0730754
--- /dev/null
+++ b/lib/set-permissions.c
@@ -0,0 +1,846 @@
+/* Set permissions of a file. -*- coding: utf-8 -*-
+
+ Copyright (C) 2002-2003, 2005-2016 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 <http://www.gnu.org/licenses/>.
+
+ Written by Paul Eggert, Andreas Grünbacher, and Bruno Haible. */
+
+#include <config.h>
+
+#include "acl.h"
+
+#include "acl-internal.h"
+
+#if USE_ACL
+# if ! defined HAVE_ACL_FROM_MODE && defined HAVE_ACL_FROM_TEXT /* FreeBSD, IRIX, Tru64 */
+# if HAVE_ACL_GET_FILE && !HAVE_ACL_TYPE_EXTENDED
+
+static acl_t
+acl_from_mode (mode_t mode)
+{
+# if HAVE_ACL_FREE_TEXT /* Tru64 */
+ char acl_text[] = "u::---,g::---,o::---,";
+# else /* FreeBSD, IRIX */
+ char acl_text[] = "u::---,g::---,o::---";
+# endif
+
+ if (mode & S_IRUSR) acl_text[ 3] = 'r';
+ if (mode & S_IWUSR) acl_text[ 4] = 'w';
+ if (mode & S_IXUSR) acl_text[ 5] = 'x';
+ if (mode & S_IRGRP) acl_text[10] = 'r';
+ if (mode & S_IWGRP) acl_text[11] = 'w';
+ if (mode & S_IXGRP) acl_text[12] = 'x';
+ if (mode & S_IROTH) acl_text[17] = 'r';
+ if (mode & S_IWOTH) acl_text[18] = 'w';
+ if (mode & S_IXOTH) acl_text[19] = 'x';
+
+ return acl_from_text (acl_text);
+}
+# endif
+# endif
+
+# if HAVE_FACL && defined GETACL /* Solaris, Cygwin, not HP-UX */
+static int
+set_acls_from_mode (const char *name, int desc, mode_t mode, bool *must_chmod)
+{
+# ifdef ACE_GETACL
+ /* Solaris also has a different variant of ACLs, used in ZFS and NFSv4
+ file systems (whereas the other ones are used in UFS file systems). */
+
+ /* The flags in the ace_t structure changed in a binary incompatible way
+ when ACL_NO_TRIVIAL etc. were introduced in <sys/acl.h> version 1.15.
+ How to distinguish the two conventions at runtime?
+ We fetch the existing ACL. In the old convention, usually three ACEs have
+ a_flags = ACE_OWNER / ACE_GROUP / ACE_OTHER, in the range 0x0100..0x0400.
+ In the new convention, these values are not used. */
+ int convention;
+
+ {
+ /* Initially, try to read the entries into a stack-allocated buffer.
+ Use malloc if it does not fit. */
+ enum
+ {
+ alloc_init = 4000 / sizeof (ace_t), /* >= 3 */
+ alloc_max = MIN (INT_MAX, SIZE_MAX / sizeof (ace_t))
+ };
+ ace_t buf[alloc_init];
+ size_t alloc = alloc_init;
+ ace_t *entries = buf;
+ ace_t *malloced = NULL;
+ int count;
+
+ for (;;)
+ {
+ count = (desc != -1
+ ? facl (desc, ACE_GETACL, alloc, entries)
+ : acl (name, ACE_GETACL, alloc, entries));
+ if (count < 0 && errno == ENOSPC)
+ {
+ /* Increase the size of the buffer. */
+ free (malloced);
+ if (alloc > alloc_max / 2)
+ {
+ errno = ENOMEM;
+ return -1;
+ }
+ alloc = 2 * alloc; /* <= alloc_max */
+ entries = malloced = (ace_t *) malloc (alloc * sizeof (ace_t));
+ if (entries == NULL)
+ {
+ errno = ENOMEM;
+ return -1;
+ }
+ continue;
+ }
+ break;
+ }
+
+ if (count <= 0)
+ convention = -1;
+ else
+ {
+ int i;
+
+ convention = 0;
+ for (i = 0; i < count; i++)
+ if (entries[i].a_flags & (OLD_ACE_OWNER | OLD_ACE_GROUP | OLD_ACE_OTHER))
+ {
+ convention = 1;
+ break;
+ }
+ }
+ free (malloced);
+ }
+
+ if (convention >= 0)
+ {
+ ace_t entries[6];
+ int count;
+ int ret;
+
+ if (convention)
+ {
+ /* Running on Solaris 10. */
+ entries[0].a_type = OLD_ALLOW;
+ entries[0].a_flags = OLD_ACE_OWNER;
+ entries[0].a_who = 0; /* irrelevant */
+ entries[0].a_access_mask = (mode >> 6) & 7;
+ entries[1].a_type = OLD_ALLOW;
+ entries[1].a_flags = OLD_ACE_GROUP;
+ entries[1].a_who = 0; /* irrelevant */
+ entries[1].a_access_mask = (mode >> 3) & 7;
+ entries[2].a_type = OLD_ALLOW;
+ entries[2].a_flags = OLD_ACE_OTHER;
+ entries[2].a_who = 0;
+ entries[2].a_access_mask = mode & 7;
+ count = 3;
+ }
+ else
+ {
+ /* Running on Solaris 10 (newer version) or Solaris 11.
+ The details here were found through "/bin/ls -lvd somefiles". */
+ entries[0].a_type = NEW_ACE_ACCESS_DENIED_ACE_TYPE;
+ entries[0].a_flags = NEW_ACE_OWNER;
+ entries[0].a_who = 0; /* irrelevant */
+ entries[0].a_access_mask = 0;
+ entries[1].a_type = NEW_ACE_ACCESS_ALLOWED_ACE_TYPE;
+ entries[1].a_flags = NEW_ACE_OWNER;
+ entries[1].a_who = 0; /* irrelevant */
+ entries[1].a_access_mask = NEW_ACE_WRITE_NAMED_ATTRS
+ | NEW_ACE_WRITE_ATTRIBUTES
+ | NEW_ACE_WRITE_ACL
+ | NEW_ACE_WRITE_OWNER;
+ if (mode & 0400)
+ entries[1].a_access_mask |= NEW_ACE_READ_DATA;
+ else
+ entries[0].a_access_mask |= NEW_ACE_READ_DATA;
+ if (mode & 0200)
+ entries[1].a_access_mask |= NEW_ACE_WRITE_DATA | NEW_ACE_APPEND_DATA;
+ else
+ entries[0].a_access_mask |= NEW_ACE_WRITE_DATA | NEW_ACE_APPEND_DATA;
+ if (mode & 0100)
+ entries[1].a_access_mask |= NEW_ACE_EXECUTE;
+ else
+ entries[0].a_access_mask |= NEW_ACE_EXECUTE;
+ entries[2].a_type = NEW_ACE_ACCESS_DENIED_ACE_TYPE;
+ entries[2].a_flags = NEW_ACE_GROUP | NEW_ACE_IDENTIFIER_GROUP;
+ entries[2].a_who = 0; /* irrelevant */
+ entries[2].a_access_mask = 0;
+ entries[3].a_type = NEW_ACE_ACCESS_ALLOWED_ACE_TYPE;
+ entries[3].a_flags = NEW_ACE_GROUP | NEW_ACE_IDENTIFIER_GROUP;
+ entries[3].a_who = 0; /* irrelevant */
+ entries[3].a_access_mask = 0;
+ if (mode & 0040)
+ entries[3].a_access_mask |= NEW_ACE_READ_DATA;
+ else
+ entries[2].a_access_mask |= NEW_ACE_READ_DATA;
+ if (mode & 0020)
+ entries[3].a_access_mask |= NEW_ACE_WRITE_DATA | NEW_ACE_APPEND_DATA;
+ else
+ entries[2].a_access_mask |= NEW_ACE_WRITE_DATA | NEW_ACE_APPEND_DATA;
+ if (mode & 0010)
+ entries[3].a_access_mask |= NEW_ACE_EXECUTE;
+ else
+ entries[2].a_access_mask |= NEW_ACE_EXECUTE;
+ entries[4].a_type = NEW_ACE_ACCESS_DENIED_ACE_TYPE;
+ entries[4].a_flags = NEW_ACE_EVERYONE;
+ entries[4].a_who = 0;
+ entries[4].a_access_mask = NEW_ACE_WRITE_NAMED_ATTRS
+ | NEW_ACE_WRITE_ATTRIBUTES
+ | NEW_ACE_WRITE_ACL
+ | NEW_ACE_WRITE_OWNER;
+ entries[5].a_type = NEW_ACE_ACCESS_ALLOWED_ACE_TYPE;
+ entries[5].a_flags = NEW_ACE_EVERYONE;
+ entries[5].a_who = 0;
+ entries[5].a_access_mask = NEW_ACE_READ_NAMED_ATTRS
+ | NEW_ACE_READ_ATTRIBUTES
+ | NEW_ACE_READ_ACL
+ | NEW_ACE_SYNCHRONIZE;
+ if (mode & 0004)
+ entries[5].a_access_mask |= NEW_ACE_READ_DATA;
+ else
+ entries[4].a_access_mask |= NEW_ACE_READ_DATA;
+ if (mode & 0002)
+ entries[5].a_access_mask |= NEW_ACE_WRITE_DATA | NEW_ACE_APPEND_DATA;
+ else
+ entries[4].a_access_mask |= NEW_ACE_WRITE_DATA | NEW_ACE_APPEND_DATA;
+ if (mode & 0001)
+ entries[5].a_access_mask |= NEW_ACE_EXECUTE;
+ else
+ entries[4].a_access_mask |= NEW_ACE_EXECUTE;
+ count = 6;
+ }
+ if (desc != -1)
+ ret = facl (desc, ACE_SETACL, count, entries);
+ else
+ ret = acl (name, ACE_SETACL, count, entries);
+ if (ret < 0 && errno != EINVAL && errno != ENOTSUP)
+ {
+ if (errno == ENOSYS)
+ {
+ *must_chmod = true;
+ return 0;
+ }
+ return -1;
+ }
+ if (ret == 0)
+ return 0;
+ }
+# endif
+
+ {
+ aclent_t entries[3];
+ int ret;
+
+ entries[0].a_type = USER_OBJ;
+ entries[0].a_id = 0; /* irrelevant */
+ entries[0].a_perm = (mode >> 6) & 7;
+ entries[1].a_type = GROUP_OBJ;
+ entries[1].a_id = 0; /* irrelevant */
+ entries[1].a_perm = (mode >> 3) & 7;
+ entries[2].a_type = OTHER_OBJ;
+ entries[2].a_id = 0;
+ entries[2].a_perm = mode & 7;
+
+ if (desc != -1)
+ ret = facl (desc, SETACL,
+ sizeof (entries) / sizeof (aclent_t), entries);
+ else
+ ret = acl (name, SETACL,
+ sizeof (entries) / sizeof (aclent_t), entries);
+ if (ret < 0)
+ {
+ if (errno == ENOSYS || errno == EOPNOTSUPP)
+ {
+ *must_chmod = true;
+ return 0;
+ }
+ return -1;
+ }
+ }
+}
+
+# elif HAVE_GETACL /* HP-UX */
+static int
+context_acl_from_mode (struct permission_context *ctx, const char *name, int desc)
+{
+ struct stat statbuf;
+ int ret;
+
+ if (desc != -1)
+ ret = fstat (desc, &statbuf);
+ else
+ ret = stat (name, &statbuf);
+ if (ret < 0)
+ return -1;
+
+ ctx->entries[0].uid = statbuf.st_uid;
+ ctx->entries[0].gid = ACL_NSGROUP;
+ ctx->entries[0].mode = (ctx->mode >> 6) & 7;
+ ctx->entries[1].uid = ACL_NSUSER;
+ ctx->entries[1].gid = statbuf.st_gid;
+ ctx->entries[1].mode = (ctx->mode >> 3) & 7;
+ ctx->entries[2].uid = ACL_NSUSER;
+ ctx->entries[2].gid = ACL_NSGROUP;
+ ctx->entries[2].mode = ctx->mode & 7;
+ ctx->count = 3;
+ return 0;
+}
+
+# if HAVE_ACLV_H /* HP-UX >= 11.11 */
+static int
+context_aclv_from_mode (struct permission_context *ctx)
+{
+ int ret;
+
+ ctx->aclv_entries[0].a_type = USER_OBJ;
+ ctx->aclv_entries[0].a_id = 0; /* irrelevant */
+ ctx->aclv_entries[0].a_perm = (ctx->mode >> 6) & 7;
+ ctx->aclv_entries[1].a_type = GROUP_OBJ;
+ ctx->aclv_entries[1].a_id = 0; /* irrelevant */
+ ctx->aclv_entries[1].a_perm = (ctx->mode >> 3) & 7;
+ ctx->aclv_entries[2].a_type = CLASS_OBJ;
+ ctx->aclv_entries[2].a_id = 0;
+ ctx->aclv_entries[2].a_perm = (ctx->mode >> 3) & 7;
+ ctx->aclv_entries[3].a_type = OTHER_OBJ;
+ ctx->aclv_entries[3].a_id = 0;
+ ctx->aclv_entries[3].a_perm = ctx->mode & 7;
+ ctx->aclv_count = 4;
+
+ ret = aclsort (ctx->aclv_count, 1, ctx->aclv_entries);
+ if (ret > 0)
+ abort ();
+ return ret;
+}
+# endif
+
+# elif HAVE_ACLX_GET && defined ACL_AIX_WIP /* AIX */
+static int
+set_acls_from_mode (const char *name, int desc, mode_t mode, bool *must_chmod)
+{
+ acl_type_list_t types;
+ size_t types_size = sizeof (types);
+ acl_type_t type;
+
+ if (aclx_gettypes (name, &types, &types_size) < 0
+ || types.num_entries == 0)
+ {
+ *must_chmod = true;
+ return 0;
+ }
+
+ /* XXX Do we need to clear all types of ACLs for the given file, or is it
+ sufficient to clear the first one? */
+ type = types.entries[0];
+ if (type.u64 == ACL_AIXC)
+ {
+ union { struct acl a; char room[128]; } u;
+ int ret;
+
+ u.a.acl_len = (char *) &u.a.acl_ext[0] - (char *) &u.a; /* no entries */
+ u.a.acl_mode = mode & ~(S_IXACL | 0777);
+ u.a.u_access = (mode >> 6) & 7;
+ u.a.g_access = (mode >> 3) & 7;
+ u.a.o_access = mode & 7;
+
+ if (desc != -1)
+ ret = aclx_fput (desc, SET_ACL | SET_MODE_S_BITS,
+ type, &u.a, u.a.acl_len, mode);
+ else
+ ret = aclx_put (name, SET_ACL | SET_MODE_S_BITS,
+ type, &u.a, u.a.acl_len, mode);
+ if (!(ret < 0 && errno == ENOSYS))
+ return ret;
+ }
+ else if (type.u64 == ACL_NFS4)
+ {
+ union { nfs4_acl_int_t a; char room[128]; } u;
+ nfs4_ace_int_t *ace;
+ int ret;
+
+ u.a.aclVersion = NFS4_ACL_INT_STRUCT_VERSION;
+ u.a.aclEntryN = 0;
+ ace = &u.a.aclEntry[0];
+ {
+ ace->flags = ACE4_ID_SPECIAL;
+ ace->aceWho.special_whoid = ACE4_WHO_OWNER;
+ ace->aceType = ACE4_ACCESS_ALLOWED_ACE_TYPE;
+ ace->aceFlags = 0;
+ ace->aceMask =
+ (mode & 0400 ? ACE4_READ_DATA | ACE4_LIST_DIRECTORY : 0)
+ | (mode & 0200
+ ? ACE4_WRITE_DATA | ACE4_ADD_FILE | ACE4_APPEND_DATA
+ | ACE4_ADD_SUBDIRECTORY
+ : 0)
+ | (mode & 0100 ? ACE4_EXECUTE : 0);
+ ace->aceWhoString[0] = '\0';
+ ace->entryLen = (char *) &ace->aceWhoString[4] - (char *) ace;
+ ace = (nfs4_ace_int_t *) (char *) &ace->aceWhoString[4];
+ u.a.aclEntryN++;
+ }
+ {
+ ace->flags = ACE4_ID_SPECIAL;
+ ace->aceWho.special_whoid = ACE4_WHO_GROUP;
+ ace->aceType = ACE4_ACCESS_ALLOWED_ACE_TYPE;
+ ace->aceFlags = 0;
+ ace->aceMask =
+ (mode & 0040 ? ACE4_READ_DATA | ACE4_LIST_DIRECTORY : 0)
+ | (mode & 0020
+ ? ACE4_WRITE_DATA | ACE4_ADD_FILE | ACE4_APPEND_DATA
+ | ACE4_ADD_SUBDIRECTORY
+ : 0)
+ | (mode & 0010 ? ACE4_EXECUTE : 0);
+ ace->aceWhoString[0] = '\0';
+ ace->entryLen = (char *) &ace->aceWhoString[4] - (char *) ace;
+ ace = (nfs4_ace_int_t *) (char *) &ace->aceWhoString[4];
+ u.a.aclEntryN++;
+ }
+ {
+ ace->flags = ACE4_ID_SPECIAL;
+ ace->aceWho.special_whoid = ACE4_WHO_EVERYONE;
+ ace->aceType = ACE4_ACCESS_ALLOWED_ACE_TYPE;
+ ace->aceFlags = 0;
+ ace->aceMask =
+ (mode & 0004 ? ACE4_READ_DATA | ACE4_LIST_DIRECTORY : 0)
+ | (mode & 0002
+ ? ACE4_WRITE_DATA | ACE4_ADD_FILE | ACE4_APPEND_DATA
+ | ACE4_ADD_SUBDIRECTORY
+ : 0)
+ | (mode & 0001 ? ACE4_EXECUTE : 0);
+ ace->aceWhoString[0] = '\0';
+ ace->entryLen = (char *) &ace->aceWhoString[4] - (char *) ace;
+ ace = (nfs4_ace_int_t *) (char *) &ace->aceWhoString[4];
+ u.a.aclEntryN++;
+ }
+ u.a.aclLength = (char *) ace - (char *) &u.a;
+
+ if (desc != -1)
+ ret = aclx_fput (desc, SET_ACL | SET_MODE_S_BITS,
+ type, &u.a, u.a.aclLength, mode);
+ else
+ ret = aclx_put (name, SET_ACL | SET_MODE_S_BITS,
+ type, &u.a, u.a.aclLength, mode);
+ if (!(ret < 0 && errno == ENOSYS))
+ return ret;
+ }
+
+ *must_chmod = true;
+ return 0;
+}
+
+# elif HAVE_STATACL /* older AIX */
+static int
+context_acl_from_mode (struct permission_context *ctx)
+{
+ ctx->u.a.acl_len = (char *) &ctx->u.a.acl_ext[0] - (char *) &ctx->u.a; /* no entries */
+ ctx->u.a.acl_mode = ctx->mode & ~(S_IXACL | 0777);
+ ctx->u.a.u_access = (ctx->mode >> 6) & 7;
+ ctx->u.a.g_access = (ctx->mode >> 3) & 7;
+ ctx->u.a.o_access = ctx->mode & 7;
+ ctx->have_u = true;
+ return 0;
+}
+
+# elif HAVE_ACLSORT /* NonStop Kernel */
+static int
+context_acl_from_mode (struct permission_context *ctx)
+{
+ int ret;
+
+ ctx->entries[0].a_type = USER_OBJ;
+ ctx->entries[0].a_id = 0; /* irrelevant */
+ ctx->entries[0].a_perm = (ctx->mode >> 6) & 7;
+ ctx->entries[1].a_type = GROUP_OBJ;
+ ctx->entries[1].a_id = 0; /* irrelevant */
+ ctx->entries[1].a_perm = (ctx->mode >> 3) & 7;
+ ctx->entries[2].a_type = CLASS_OBJ;
+ ctx->entries[2].a_id = 0;
+ ctx->entries[2].a_perm = (ctx->mode >> 3) & 7;
+ ctx->entries[3].a_type = OTHER_OBJ;
+ ctx->entries[3].a_id = 0;
+ ctx->entries[3].a_perm = ctx->mode & 7;
+ ctx->count = 4;
+
+ ret = aclsort (ctx->count, 1, entries);
+ if (ret > 0)
+ abort ();
+ return ret;
+}
+# endif
+
+static int
+set_acls (struct permission_context *ctx, const char *name, int desc,
+ int from_mode, bool *must_chmod, bool *acls_set)
+{
+ int ret = 0;
+
+# if HAVE_ACL_GET_FILE
+ /* POSIX 1003.1e (draft 17 -- abandoned) specific version. */
+ /* Linux, FreeBSD, Mac OS X, IRIX, Tru64 */
+# if !HAVE_ACL_TYPE_EXTENDED
+ /* Linux, FreeBSD, IRIX, Tru64 */
+
+# ifndef HAVE_ACL_FROM_TEXT
+# error Must have acl_from_text (see POSIX 1003.1e draft 17).
+# endif
+# ifndef HAVE_ACL_DELETE_DEF_FILE
+# error Must have acl_delete_def_file (see POSIX 1003.1e draft 17).
+# endif
+
+ if (! ctx->acls_not_supported)
+ {
+ if (ret == 0 && from_mode)
+ {
+ if (ctx->acl)
+ acl_free (ctx->acl);
+ ctx->acl = acl_from_mode (ctx->mode);
+ if (ctx->acl == NULL)
+ ret = -1;
+ }
+
+ if (ret == 0 && ctx->acl)
+ {
+ if (HAVE_ACL_SET_FD && desc != -1)
+ ret = acl_set_fd (desc, ctx->acl);
+ else
+ ret = acl_set_file (name, ACL_TYPE_ACCESS, ctx->acl);
+ if (ret != 0)
+ {
+ if (! acl_errno_valid (errno))
+ {
+ ctx->acls_not_supported = true;
+ if (from_mode || acl_access_nontrivial (ctx->acl) == 0)
+ ret = 0;
+ }
+ }
+ else
+ {
+ *acls_set = true;
+ if (S_ISDIR(ctx->mode))
+ {
+ if (! from_mode && ctx->default_acl &&
+ acl_default_nontrivial (ctx->default_acl))
+ ret = acl_set_file (name, ACL_TYPE_DEFAULT,
+ ctx->default_acl);
+ else
+ ret = acl_delete_def_file (name);
+ }
+ }
+ }
+ }
+
+# if HAVE_ACL_TYPE_NFS4 /* FreeBSD */
+
+ /* File systems either support POSIX ACLs (for example, ufs) or NFS4 ACLs
+ (for example, zfs). */
+
+ /* TODO: Implement setting ACLs once get_permissions() reads them. */
+
+# endif
+
+# else /* HAVE_ACL_TYPE_EXTENDED */
+ /* Mac OS X */
+
+ /* On Mac OS X, acl_get_file (name, ACL_TYPE_ACCESS)
+ and acl_get_file (name, ACL_TYPE_DEFAULT)
+ always return NULL / EINVAL. You have to use
+ acl_get_file (name, ACL_TYPE_EXTENDED)
+ or acl_get_fd (open (name, ...))
+ to retrieve an ACL.
+ On the other hand,
+ acl_set_file (name, ACL_TYPE_ACCESS, acl)
+ and acl_set_file (name, ACL_TYPE_DEFAULT, acl)
+ have the same effect as
+ acl_set_file (name, ACL_TYPE_EXTENDED, acl):
+ Each of these calls sets the file's ACL. */
+
+ if (ctx->acl == NULL)
+ {
+ acl_t acl;
+
+ /* Remove ACLs if the file has ACLs. */
+ if (HAVE_ACL_GET_FD && desc != -1)
+ acl = acl_get_fd (desc);
+ else
+ acl = acl_get_file (name, ACL_TYPE_EXTENDED);
+ if (acl)
+ {
+ acl_free (acl);
+
+ acl = acl_init (0);
+ if (acl)
+ {
+ if (HAVE_ACL_SET_FD && desc != -1)
+ ret = acl_set_fd (desc, acl);
+ else
+ ret = acl_set_file (name, ACL_TYPE_EXTENDED, acl);
+ acl_free (acl);
+ }
+ else
+ ret = -1;
+ }
+ }
+ else
+ {
+ if (HAVE_ACL_SET_FD && desc != -1)
+ ret = acl_set_fd (desc, ctx->acl);
+ else
+ ret = acl_set_file (name, ACL_TYPE_EXTENDED, ctx->acl);
+ if (ret != 0)
+ {
+ if (! acl_errno_valid (errno)
+ && ! acl_extended_nontrivial (ctx->acl))
+ ret = 0;
+ }
+ }
+ *acls_set = true;
+
+# endif
+
+# elif defined GETACL /* Solaris, Cygwin, not HP-UX */
+
+ /* Solaris 2.5 through Solaris 10, Cygwin, and contemporaneous versions
+ of Unixware. The acl() call returns the access and default ACL both
+ at once. */
+
+ /* If both ace_entries and entries are available, try SETACL before
+ ACE_SETACL, because SETACL cannot fail with ENOTSUP whereas ACE_SETACL
+ can. */
+
+ if (from_mode)
+ return set_acls_from_mode (name, desc, ctx->mode, must_chmod);
+
+ if (ret == 0 && ctx->count)
+ {
+ if (desc != -1)
+ ret = facl (desc, SETACL, ctx->count, ctx->entries);
+ else
+ ret = acl (name, SETACL, ctx->count, ctx->entries);
+ if (ret < 0)
+ {
+ if ((errno == ENOSYS || errno == EOPNOTSUPP || errno == EINVAL)
+ && acl_nontrivial (ctx->count, ctx->entries) == 0)
+ ret = 0;
+ }
+ else
+ *acls_set = true;
+ }
+
+# ifdef ACE_GETACL
+ if (ret == 0 && ctx->ace_count)
+ {
+ if (desc != -1)
+ ret = facl (desc, ACE_SETACL, ctx->ace_count, ctx->ace_entries);
+ else
+ ret = acl (name, ACE_SETACL, ctx->ace_count, ctx->ace_entries);
+ if (ret < 0)
+ {
+ if ((errno == ENOSYS || errno == EINVAL || errno == ENOTSUP)
+ && acl_ace_nontrivial (ctx->ace_count, ctx->ace_entries) == 0)
+ ret = 0;
+ }
+ else
+ *acls_set = true;
+ }
+# endif
+
+# elif HAVE_GETACL /* HP-UX */
+
+ if (from_mode)
+ ret = context_acl_from_mode (ctx, name, desc);
+
+ if (ret == 0 && ctx->count > 0)
+ {
+ if (desc != -1)
+ ret = fsetacl (desc, ctx->count, ctx->entries);
+ else
+ ret = setacl (name, ctx->count, ctx->entries);
+ if (ret < 0)
+ {
+ if ((errno == ENOSYS || errno == EOPNOTSUPP || errno == ENOTSUP)
+ && (from_mode || !acl_nontrivial (ctx->count, ctx->entries)))
+ ret = 0;
+ }
+ else
+ *acls_set = true;
+ }
+
+# if HAVE_ACLV_H
+ if (from_mode)
+ ret = context_aclv_from_mode (ctx);
+
+ if (ret == 0 && ctx->aclv_count > 0)
+ {
+ ret = acl ((char *) name, ACL_SET, ctx->aclv_count, ctx->aclv_entries);
+ if (ret < 0)
+ {
+ if ((errno == ENOSYS || errno == EOPNOTSUPP || errno == EINVAL)
+ && (from_mode || !aclv_nontrivial (ctx->aclv_count, ctx->aclv_entries)))
+ ret = 0;
+ }
+ else
+ *acls_set = true;
+ }
+# endif
+
+# elif HAVE_ACLX_GET && ACL_AIX_WIP /* AIX */
+
+ /* TODO: Implement setting ACLs once get_permissions() reads them. */
+
+ if (from_mode)
+ ret = set_acls_from_mode (name, desc, mode, must_chmod);
+
+# elif HAVE_STATACL /* older AIX */
+
+ if (from_mode)
+ ret = context_acl_from_mode (ctx);
+
+ if (ret == 0 && ctx->have_u)
+ {
+ if (desc != -1)
+ ret = fchacl (desc, &ctx->u.a, ctx->u.a.acl_len);
+ else
+ ret = chacl ((char *) name, &ctx->u.a, ctx->u.a.acl_len);
+ if (ret < 0)
+ {
+ if (errno == ENOSYS && from_mode)
+ ret = 0;
+ }
+ else
+ *acls_set = true;
+ }
+
+# elif HAVE_ACLSORT /* NonStop Kernel */
+
+ if (from_mode)
+ ret = context_acl_from_mode (ctx);
+
+ if (ret == 0 && ctx->count)
+ {
+ ret = acl ((char *) name, ACL_SET, ctx->count, ctx->entries);
+ if (ret != 0)
+ {
+ if (!acl_nontrivial (ctx->count, ctx->entries))
+ ret = 0;
+ }
+ else
+ *acls_set = true;
+ }
+
+# else /* No ACLs */
+
+ /* Nothing to do. */
+
+# endif
+
+ return ret;
+}
+#endif
+
+/* If DESC is a valid file descriptor use fchmod to change the
+ file's mode to MODE on systems that have fchmod. On systems
+ that don't have fchmod and if DESC is invalid, use chmod on
+ NAME instead.
+ Return 0 if successful. Return -1 and set errno upon failure. */
+
+int
+chmod_or_fchmod (const char *name, int desc, mode_t mode)
+{
+ if (HAVE_FCHMOD && desc != -1)
+ return fchmod (desc, mode);
+ else
+ return chmod (name, mode);
+}
+
+/* Set the permissions in CTX on a file. If DESC is a valid file descriptor,
+ use file descriptor operations, else use filename based operations on NAME.
+ If access control lists are not available, fchmod the target file to the
+ mode in CTX. Also sets the non-permission bits of the destination file
+ (S_ISUID, S_ISGID, S_ISVTX) to those from the mode in CTX if any are set.
+ Return 0 if successful. Return -1 and set errno upon failure. */
+
+int
+set_permissions (struct permission_context *ctx, const char *name, int desc)
+{
+ bool acls_set _GL_UNUSED = false;
+ bool early_chmod;
+ bool must_chmod = false;
+ int ret = 0;
+
+#if USE_ACL
+# if HAVE_STATACL
+ /* older AIX */
+ /* There is no need to call chmod_or_fchmod, since the mode
+ bits S_ISUID, S_ISGID, S_ISVTX are also stored in the ACL. */
+
+ early_chmod = false;
+# else
+ /* All other platforms */
+ /* On Cygwin, it is necessary to call chmod before acl, because
+ chmod can change the contents of the ACL (in ways that don't
+ change the allowed accesses, but still visible). */
+
+ early_chmod = (! MODE_INSIDE_ACL || (ctx->mode & (S_ISUID | S_ISGID | S_ISVTX)));
+# endif
+#else
+ /* No ACLs */
+
+ early_chmod = true;
+#endif
+
+ if (early_chmod)
+ {
+ ret = chmod_or_fchmod (name, desc, ctx->mode);
+ if (ret != 0)
+ return -1;
+ }
+
+#if USE_ACL
+ ret = set_acls (ctx, name, desc, false, &must_chmod, &acls_set);
+ if (! acls_set)
+ {
+ int saved_errno = ret ? errno : 0;
+
+ /* If we can't set an acl which we expect to be able to set, try setting
+ the permissions to ctx->mode. Due to possible inherited permissions,
+ we cannot simply chmod. */
+
+ ret = set_acls (ctx, name, desc, true, &must_chmod, &acls_set);
+ if (! acls_set)
+ must_chmod = true;
+
+ if (saved_errno)
+ {
+ errno = saved_errno;
+ ret = -1;
+ }
+ }
+#endif
+
+ if (must_chmod && ! early_chmod)
+ {
+ int saved_errno = ret ? errno : 0;
+
+ ret = chmod_or_fchmod (name, desc, ctx->mode);
+
+ if (saved_errno)
+ {
+ errno = saved_errno;
+ ret = -1;
+ }
+ }
+
+ return ret;
+}
diff --git a/lib/setenv.c b/lib/setenv.c
index c54c28d..85c32cb 100644
--- a/lib/setenv.c
+++ b/lib/setenv.c
@@ -1,55 +1,59 @@
-/* Copyright (C) 1992,1995-1999,2000-2003,2005-2007 Free Software Foundation, Inc.
+/* Copyright (C) 1992, 1995-2003, 2005-2016 Free Software Foundation, Inc.
This file is part of the GNU C Library.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#if !_LIBC
+/* Don't use __attribute__ __nonnull__ in this compilation unit. Otherwise gcc
+ optimizes away the name == NULL test below. */
+# define _GL_ARG_NONNULL(params)
+
+# define _GL_USE_STDLIB_ALLOC 1
# include <config.h>
#endif
+
#include <alloca.h>
+/* Specification. */
+#include <stdlib.h>
+
#include <errno.h>
#ifndef __set_errno
# define __set_errno(ev) ((errno) = (ev))
#endif
-#include <stdlib.h>
#include <string.h>
#if _LIBC || HAVE_UNISTD_H
# include <unistd.h>
#endif
-#if _LIBC || !HAVE_SETENV
-
#if !_LIBC
-# include "allocsa.h"
+# include "malloca.h"
#endif
+#if _LIBC || !HAVE_SETENV
+
#if !_LIBC
-# define __environ environ
-# ifndef HAVE_ENVIRON_DECL
-extern char **environ;
-# endif
+# define __environ environ
#endif
#if _LIBC
-/* This lock protects against simultaneous modifications of `environ'. */
+/* This lock protects against simultaneous modifications of 'environ'. */
# include <bits/libc-lock.h>
__libc_lock_define_initialized (static, envlock)
-# define LOCK __libc_lock_lock (envlock)
-# define UNLOCK __libc_lock_unlock (envlock)
+# define LOCK __libc_lock_lock (envlock)
+# define UNLOCK __libc_lock_unlock (envlock)
#else
# define LOCK
# define UNLOCK
@@ -68,8 +72,8 @@ __libc_lock_define_initialized (static, envlock)
values are from a small set. Outside glibc this will eat up all
memory after a while. */
#if defined _LIBC || (defined HAVE_SEARCH_H && defined HAVE_TSEARCH \
- && defined __GNUC__)
-# define USE_TSEARCH 1
+ && defined __GNUC__)
+# define USE_TSEARCH 1
# include <search.h>
typedef int (*compar_fn_t) (const void *, const void *);
@@ -78,9 +82,9 @@ typedef int (*compar_fn_t) (const void *, const void *);
static void *known_values;
# define KNOWN_VALUE(Str) \
- ({ \
- void *value = tfind (Str, &known_values, (compar_fn_t) strcmp); \
- value != NULL ? *(char **) value : NULL; \
+ ({ \
+ void *value = tfind (Str, &known_values, (compar_fn_t) strcmp); \
+ value != NULL ? *(char **) value : NULL; \
})
# define STORE_VALUE(Str) \
tsearch (Str, &known_values, (compar_fn_t) strcmp)
@@ -99,18 +103,18 @@ static void *known_values;
static char **last_environ;
-/* This function is used by `setenv' and `putenv'. The difference between
+/* This function is used by 'setenv' and 'putenv'. The difference between
the two functions is that for the former must create a new string which
- is then placed in the environment, while the argument of `putenv'
+ is then placed in the environment, while the argument of 'putenv'
must be used directly. This is all complicated by the fact that we try
- to reuse values once generated for a `setenv' call since we can never
+ to reuse values once generated for a 'setenv' call since we can never
free the strings. */
int
__add_to_environ (const char *name, const char *value, const char *combined,
- int replace)
+ int replace)
{
- register char **ep;
- register size_t size;
+ char **ep;
+ size_t size;
const size_t namelen = strlen (name);
const size_t vallen = value != NULL ? strlen (value) + 1 : 0;
@@ -124,10 +128,10 @@ __add_to_environ (const char *name, const char *value, const char *combined,
if (ep != NULL)
{
for (; *ep != NULL; ++ep)
- if (!strncmp (*ep, name, namelen) && (*ep)[namelen] == '=')
- break;
- else
- ++size;
+ if (!strncmp (*ep, name, namelen) && (*ep)[namelen] == '=')
+ break;
+ else
+ ++size;
}
if (ep == NULL || *ep == NULL)
@@ -139,76 +143,79 @@ __add_to_environ (const char *name, const char *value, const char *combined,
/* We allocated this space; we can extend it. */
new_environ =
- (char **) (last_environ == NULL
- ? malloc ((size + 2) * sizeof (char *))
- : realloc (last_environ, (size + 2) * sizeof (char *)));
+ (char **) (last_environ == NULL
+ ? malloc ((size + 2) * sizeof (char *))
+ : realloc (last_environ, (size + 2) * sizeof (char *)));
if (new_environ == NULL)
- {
- UNLOCK;
- return -1;
- }
+ {
+ /* It's easier to set errno to ENOMEM than to rely on the
+ 'malloc-posix' and 'realloc-posix' gnulib modules. */
+ __set_errno (ENOMEM);
+ UNLOCK;
+ return -1;
+ }
/* If the whole entry is given add it. */
if (combined != NULL)
- /* We must not add the string to the search tree since it belongs
- to the user. */
- new_environ[size] = (char *) combined;
+ /* We must not add the string to the search tree since it belongs
+ to the user. */
+ new_environ[size] = (char *) combined;
else
- {
- /* See whether the value is already known. */
+ {
+ /* See whether the value is already known. */
#ifdef USE_TSEARCH
# ifdef _LIBC
- new_value = (char *) alloca (namelen + 1 + vallen);
- __mempcpy (__mempcpy (__mempcpy (new_value, name, namelen), "=", 1),
- value, vallen);
+ new_value = (char *) alloca (namelen + 1 + vallen);
+ __mempcpy (__mempcpy (__mempcpy (new_value, name, namelen), "=", 1),
+ value, vallen);
# else
- new_value = (char *) allocsa (namelen + 1 + vallen);
- if (new_value == NULL)
- {
- __set_errno (ENOMEM);
- UNLOCK;
- return -1;
- }
- memcpy (new_value, name, namelen);
- new_value[namelen] = '=';
- memcpy (&new_value[namelen + 1], value, vallen);
+ new_value = (char *) malloca (namelen + 1 + vallen);
+ if (new_value == NULL)
+ {
+ __set_errno (ENOMEM);
+ UNLOCK;
+ return -1;
+ }
+ memcpy (new_value, name, namelen);
+ new_value[namelen] = '=';
+ memcpy (&new_value[namelen + 1], value, vallen);
# endif
- new_environ[size] = KNOWN_VALUE (new_value);
- if (new_environ[size] == NULL)
+ new_environ[size] = KNOWN_VALUE (new_value);
+ if (new_environ[size] == NULL)
#endif
- {
- new_environ[size] = (char *) malloc (namelen + 1 + vallen);
- if (new_environ[size] == NULL)
- {
+ {
+ new_environ[size] = (char *) malloc (namelen + 1 + vallen);
+ if (new_environ[size] == NULL)
+ {
#if defined USE_TSEARCH && !defined _LIBC
- freesa (new_value);
+ freea (new_value);
#endif
- __set_errno (ENOMEM);
- UNLOCK;
- return -1;
- }
+ __set_errno (ENOMEM);
+ UNLOCK;
+ return -1;
+ }
#ifdef USE_TSEARCH
- memcpy (new_environ[size], new_value, namelen + 1 + vallen);
+ memcpy (new_environ[size], new_value, namelen + 1 + vallen);
#else
- memcpy (new_environ[size], name, namelen);
- new_environ[size][namelen] = '=';
- memcpy (&new_environ[size][namelen + 1], value, vallen);
+ memcpy (new_environ[size], name, namelen);
+ new_environ[size][namelen] = '=';
+ memcpy (&new_environ[size][namelen + 1], value, vallen);
#endif
- /* And save the value now. We cannot do this when we remove
- the string since then we cannot decide whether it is a
- user string or not. */
- STORE_VALUE (new_environ[size]);
- }
+ /* And save the value now. We cannot do this when we remove
+ the string since then we cannot decide whether it is a
+ user string or not. */
+ STORE_VALUE (new_environ[size]);
+ }
#if defined USE_TSEARCH && !defined _LIBC
- freesa (new_value);
+ freea (new_value);
#endif
- }
+ }
if (__environ != last_environ)
- memcpy ((char *) new_environ, (char *) __environ,
- size * sizeof (char *));
+ memcpy ((char *) new_environ, (char *) __environ,
+ size * sizeof (char *));
new_environ[size + 1] = NULL;
@@ -220,57 +227,57 @@ __add_to_environ (const char *name, const char *value, const char *combined,
/* Use the user string if given. */
if (combined != NULL)
- np = (char *) combined;
+ np = (char *) combined;
else
- {
+ {
#ifdef USE_TSEARCH
- char *new_value;
+ char *new_value;
# ifdef _LIBC
- new_value = alloca (namelen + 1 + vallen);
- __mempcpy (__mempcpy (__mempcpy (new_value, name, namelen), "=", 1),
- value, vallen);
+ new_value = alloca (namelen + 1 + vallen);
+ __mempcpy (__mempcpy (__mempcpy (new_value, name, namelen), "=", 1),
+ value, vallen);
# else
- new_value = allocsa (namelen + 1 + vallen);
- if (new_value == NULL)
- {
- __set_errno (ENOMEM);
- UNLOCK;
- return -1;
- }
- memcpy (new_value, name, namelen);
- new_value[namelen] = '=';
- memcpy (&new_value[namelen + 1], value, vallen);
+ new_value = malloca (namelen + 1 + vallen);
+ if (new_value == NULL)
+ {
+ __set_errno (ENOMEM);
+ UNLOCK;
+ return -1;
+ }
+ memcpy (new_value, name, namelen);
+ new_value[namelen] = '=';
+ memcpy (&new_value[namelen + 1], value, vallen);
# endif
- np = KNOWN_VALUE (new_value);
- if (np == NULL)
+ np = KNOWN_VALUE (new_value);
+ if (np == NULL)
#endif
- {
- np = malloc (namelen + 1 + vallen);
- if (np == NULL)
- {
+ {
+ np = (char *) malloc (namelen + 1 + vallen);
+ if (np == NULL)
+ {
#if defined USE_TSEARCH && !defined _LIBC
- freesa (new_value);
+ freea (new_value);
#endif
- __set_errno (ENOMEM);
- UNLOCK;
- return -1;
- }
+ __set_errno (ENOMEM);
+ UNLOCK;
+ return -1;
+ }
#ifdef USE_TSEARCH
- memcpy (np, new_value, namelen + 1 + vallen);
+ memcpy (np, new_value, namelen + 1 + vallen);
#else
- memcpy (np, name, namelen);
- np[namelen] = '=';
- memcpy (&np[namelen + 1], value, vallen);
+ memcpy (np, name, namelen);
+ np[namelen] = '=';
+ memcpy (&np[namelen + 1], value, vallen);
#endif
- /* And remember the value. */
- STORE_VALUE (np);
- }
+ /* And remember the value. */
+ STORE_VALUE (np);
+ }
#if defined USE_TSEARCH && !defined _LIBC
- freesa (new_value);
+ freea (new_value);
#endif
- }
+ }
*ep = np;
}
@@ -283,10 +290,16 @@ __add_to_environ (const char *name, const char *value, const char *combined,
int
setenv (const char *name, const char *value, int replace)
{
+ if (name == NULL || *name == '\0' || strchr (name, '=') != NULL)
+ {
+ __set_errno (EINVAL);
+ return -1;
+ }
+
return __add_to_environ (name, value, NULL, replace);
}
-/* The `clearenv' was planned to be added to POSIX.1 but probably
+/* The 'clearenv' was planned to be added to POSIX.1 but probably
never made it. Nevertheless the POSIX.9 standard (POSIX bindings
for Fortran 77) requires this function. */
int
@@ -330,3 +343,48 @@ weak_alias (__clearenv, clearenv)
#endif
#endif /* _LIBC || !HAVE_SETENV */
+
+/* The rest of this file is called into use when replacing an existing
+ but buggy setenv. Known bugs include failure to diagnose invalid
+ name, and consuming a leading '=' from value. */
+#if HAVE_SETENV
+
+# undef setenv
+# if !HAVE_DECL_SETENV
+extern int setenv (const char *, const char *, int);
+# endif
+# define STREQ(a, b) (strcmp (a, b) == 0)
+
+int
+rpl_setenv (const char *name, const char *value, int replace)
+{
+ int result;
+ if (!name || !*name || strchr (name, '='))
+ {
+ errno = EINVAL;
+ return -1;
+ }
+ /* Call the real setenv even if replace is 0, in case implementation
+ has underlying data to update, such as when environ changes. */
+ result = setenv (name, value, replace);
+ if (result == 0 && replace && *value == '=')
+ {
+ char *tmp = getenv (name);
+ if (!STREQ (tmp, value))
+ {
+ int saved_errno;
+ size_t len = strlen (value);
+ tmp = malloca (len + 2);
+ /* Since leading '=' is eaten, double it up. */
+ *tmp = '=';
+ memcpy (tmp + 1, value, len + 1);
+ result = setenv (name, tmp, replace);
+ saved_errno = errno;
+ freea (tmp);
+ errno = saved_errno;
+ }
+ }
+ return result;
+}
+
+#endif /* HAVE_SETENV */
diff --git a/lib/setenv.h b/lib/setenv.h
deleted file mode 100644
index 92e7bba..0000000
--- a/lib/setenv.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/* Setting environment variables.
- Copyright (C) 2001-2004, 2007 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-#if HAVE_SETENV || HAVE_UNSETENV
-
-/* Get setenv(), unsetenv() declarations. */
-# include <stdlib.h>
-
-#endif
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#if !HAVE_SETENV
-
-/* Set NAME to VALUE in the environment.
- If REPLACE is nonzero, overwrite an existing value. */
-extern int setenv (const char *name, const char *value, int replace);
-
-#endif
-
-#if HAVE_UNSETENV
-
-# if VOID_UNSETENV
-/* On some systems, unsetenv() returns void.
- This is the case for FreeBSD 4.8, NetBSD 1.6, OpenBSD 3.4. */
-# define unsetenv(name) ((unsetenv)(name), 0)
-# endif
-
-#else
-
-/* Remove the variable NAME from the environment. */
-extern int unsetenv (const char *name);
-
-#endif
-
-#ifdef __cplusplus
-}
-#endif
diff --git a/lib/settime.c b/lib/settime.c
index 25e7e68..d47fe3b 100644
--- a/lib/settime.c
+++ b/lib/settime.c
@@ -1,12 +1,11 @@
/* settime -- set the system clock
- Copyright (C) 2002, 2004, 2005, 2006, 2007 Free Software
- Foundation, Inc.
+ Copyright (C) 2002, 2004-2007, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
@@ -28,16 +26,6 @@
#include <errno.h>
-/* Some systems don't have ENOSYS. */
-#ifndef ENOSYS
-# ifdef ENOTSUP
-# define ENOSYS ENOTSUP
-# else
-/* Some systems don't have ENOTSUP either. */
-# define ENOSYS EINVAL
-# endif
-#endif
-
/* Set the system time. */
int
@@ -61,7 +49,7 @@ settime (struct timespec const *ts)
}
#elif HAVE_STIME
/* This fails to compile on OSF1 V5.1, due to stime requiring
- a `long int*' and tv_sec is `int'. But that system does provide
+ a 'long int*' and tv_sec is 'int'. But that system does provide
settimeofday. */
return stime (&ts->tv_sec);
#else
diff --git a/lib/sha1.c b/lib/sha1.c
index 035f898..45f1cbe 100644
--- a/lib/sha1.c
+++ b/lib/sha1.c
@@ -1,12 +1,11 @@
/* sha1.c - Functions to compute SHA1 message digest of files or
memory blocks according to the NIST specification FIPS-180-1.
- Copyright (C) 2000, 2001, 2003, 2004, 2005, 2006 Free Software
- Foundation, Inc.
+ Copyright (C) 2000-2001, 2003-2006, 2008-2016 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 2, or (at your option) any
+ Free Software Foundation; either version 3, or (at your option) any
later version.
This program is distributed in the hope that it will be useful,
@@ -15,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program; if not, see <http://www.gnu.org/licenses/>. */
/* Written by Scott G. Miller
Credits:
@@ -25,9 +23,14 @@
#include <config.h>
+#if HAVE_OPENSSL_SHA1
+# define GL_OPENSSL_INLINE _GL_EXTERN_INLINE
+#endif
#include "sha1.h"
-#include <stddef.h>
+#include <stdalign.h>
+#include <stdint.h>
+#include <stdlib.h>
#include <string.h>
#if USE_UNLOCKED_IO
@@ -41,11 +44,12 @@
(((n) << 24) | (((n) & 0xff00) << 8) | (((n) >> 8) & 0xff00) | ((n) >> 24))
#endif
-#define BLOCKSIZE 4096
+#define BLOCKSIZE 32768
#if BLOCKSIZE % 64 != 0
# error "invalid BLOCKSIZE"
#endif
+#if ! HAVE_OPENSSL_SHA1
/* This array contains the bytes used to pad the buffer to the next
64-byte boundary. (RFC 1321, 3.1: Step 1) */
static const unsigned char fillbuf[64] = { 0x80, 0 /* , 0, 0, ... */ };
@@ -67,28 +71,32 @@ sha1_init_ctx (struct sha1_ctx *ctx)
ctx->buflen = 0;
}
-/* Put result from CTX in first 20 bytes following RESBUF. The result
- must be in little endian byte order.
+/* Copy the 4 byte value from v into the memory location pointed to by *cp,
+ If your architecture allows unaligned access this is equivalent to
+ * (uint32_t *) cp = v */
+static void
+set_uint32 (char *cp, uint32_t v)
+{
+ memcpy (cp, &v, sizeof v);
+}
- IMPORTANT: On some systems it is required that RESBUF is correctly
- aligned for a 32-bit value. */
+/* Put result from CTX in first 20 bytes following RESBUF. The result
+ must be in little endian byte order. */
void *
sha1_read_ctx (const struct sha1_ctx *ctx, void *resbuf)
{
- ((uint32_t *) resbuf)[0] = SWAP (ctx->A);
- ((uint32_t *) resbuf)[1] = SWAP (ctx->B);
- ((uint32_t *) resbuf)[2] = SWAP (ctx->C);
- ((uint32_t *) resbuf)[3] = SWAP (ctx->D);
- ((uint32_t *) resbuf)[4] = SWAP (ctx->E);
+ char *r = resbuf;
+ set_uint32 (r + 0 * sizeof ctx->A, SWAP (ctx->A));
+ set_uint32 (r + 1 * sizeof ctx->B, SWAP (ctx->B));
+ set_uint32 (r + 2 * sizeof ctx->C, SWAP (ctx->C));
+ set_uint32 (r + 3 * sizeof ctx->D, SWAP (ctx->D));
+ set_uint32 (r + 4 * sizeof ctx->E, SWAP (ctx->E));
return resbuf;
}
/* Process the remaining bytes in the internal buffer and the usual
- prolog according to the standard and write the result to RESBUF.
-
- IMPORTANT: On some systems it is required that RESBUF is correctly
- aligned for a 32-bit value. */
+ prolog according to the standard and write the result to RESBUF. */
void *
sha1_finish_ctx (struct sha1_ctx *ctx, void *resbuf)
{
@@ -112,6 +120,7 @@ sha1_finish_ctx (struct sha1_ctx *ctx, void *resbuf)
return sha1_read_ctx (ctx, resbuf);
}
+#endif
/* Compute SHA1 message digest for bytes read from STREAM. The
resulting message digest number will be written into the 16 bytes
@@ -120,9 +129,12 @@ int
sha1_stream (FILE *stream, void *resblock)
{
struct sha1_ctx ctx;
- char buffer[BLOCKSIZE + 72];
size_t sum;
+ char *buffer = malloc (BLOCKSIZE + 72);
+ if (!buffer)
+ return 1;
+
/* Initialize the computation context. */
sha1_init_ctx (&ctx);
@@ -130,40 +142,43 @@ sha1_stream (FILE *stream, void *resblock)
while (1)
{
/* We read the file in blocks of BLOCKSIZE bytes. One call of the
- computation function processes the whole buffer so that with the
- next round of the loop another block can be read. */
+ computation function processes the whole buffer so that with the
+ next round of the loop another block can be read. */
size_t n;
sum = 0;
/* Read block. Take care for partial reads. */
while (1)
- {
- n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
-
- sum += n;
-
- if (sum == BLOCKSIZE)
- break;
-
- if (n == 0)
- {
- /* Check for the error flag IFF N == 0, so that we don't
- exit the loop after a partial read due to e.g., EAGAIN
- or EWOULDBLOCK. */
- if (ferror (stream))
- return 1;
- goto process_partial_block;
- }
-
- /* We've read at least one byte, so ignore errors. But always
- check for EOF, since feof may be true even though N > 0.
- Otherwise, we could end up calling fread after EOF. */
- if (feof (stream))
- goto process_partial_block;
- }
+ {
+ n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
+
+ sum += n;
+
+ if (sum == BLOCKSIZE)
+ break;
+
+ if (n == 0)
+ {
+ /* Check for the error flag IFF N == 0, so that we don't
+ exit the loop after a partial read due to e.g., EAGAIN
+ or EWOULDBLOCK. */
+ if (ferror (stream))
+ {
+ free (buffer);
+ return 1;
+ }
+ goto process_partial_block;
+ }
+
+ /* We've read at least one byte, so ignore errors. But always
+ check for EOF, since feof may be true even though N > 0.
+ Otherwise, we could end up calling fread after EOF. */
+ if (feof (stream))
+ goto process_partial_block;
+ }
/* Process buffer with BLOCKSIZE bytes. Note that
- BLOCKSIZE % 64 == 0
+ BLOCKSIZE % 64 == 0
*/
sha1_process_block (buffer, BLOCKSIZE, &ctx);
}
@@ -176,9 +191,11 @@ sha1_stream (FILE *stream, void *resblock)
/* Construct result in desired memory. */
sha1_finish_ctx (&ctx, resblock);
+ free (buffer);
return 0;
}
+#if ! HAVE_OPENSSL_SHA1
/* Compute SHA1 message digest for LEN bytes beginning at BUFFER. The
result is always in little endian byte order, so that a byte-wise
output yields to the wanted ASCII representation of the message
@@ -212,15 +229,15 @@ sha1_process_bytes (const void *buffer, size_t len, struct sha1_ctx *ctx)
ctx->buflen += add;
if (ctx->buflen > 64)
- {
- sha1_process_block (ctx->buffer, ctx->buflen & ~63, ctx);
+ {
+ sha1_process_block (ctx->buffer, ctx->buflen & ~63, ctx);
- ctx->buflen &= 63;
- /* The regions in the following copy operation cannot overlap. */
- memcpy (ctx->buffer,
- &((char *) ctx->buffer)[(left_over + add) & ~63],
- ctx->buflen);
- }
+ ctx->buflen &= 63;
+ /* The regions in the following copy operation cannot overlap. */
+ memcpy (ctx->buffer,
+ &((char *) ctx->buffer)[(left_over + add) & ~63],
+ ctx->buflen);
+ }
buffer = (const char *) buffer + add;
len -= add;
@@ -230,22 +247,21 @@ sha1_process_bytes (const void *buffer, size_t len, struct sha1_ctx *ctx)
if (len >= 64)
{
#if !_STRING_ARCH_unaligned
-# define alignof(type) offsetof (struct { char c; type x; }, x)
-# define UNALIGNED_P(p) (((size_t) p) % alignof (uint32_t) != 0)
+# define UNALIGNED_P(p) ((uintptr_t) (p) % alignof (uint32_t) != 0)
if (UNALIGNED_P (buffer))
- while (len > 64)
- {
- sha1_process_block (memcpy (ctx->buffer, buffer, 64), 64, ctx);
- buffer = (const char *) buffer + 64;
- len -= 64;
- }
+ while (len > 64)
+ {
+ sha1_process_block (memcpy (ctx->buffer, buffer, 64), 64, ctx);
+ buffer = (const char *) buffer + 64;
+ len -= 64;
+ }
else
#endif
- {
- sha1_process_block (buffer, len & ~63, ctx);
- buffer = (const char *) buffer + (len & ~63);
- len &= 63;
- }
+ {
+ sha1_process_block (buffer, len & ~63, ctx);
+ buffer = (const char *) buffer + (len & ~63);
+ len &= 63;
+ }
}
/* Move remaining bytes in internal buffer. */
@@ -256,11 +272,11 @@ sha1_process_bytes (const void *buffer, size_t len, struct sha1_ctx *ctx)
memcpy (&((char *) ctx->buffer)[left_over], buffer, len);
left_over += len;
if (left_over >= 64)
- {
- sha1_process_block (ctx->buffer, 64, ctx);
- left_over -= 64;
- memcpy (ctx->buffer, &ctx->buffer[16], left_over);
- }
+ {
+ sha1_process_block (ctx->buffer, 64, ctx);
+ left_over -= 64;
+ memcpy (ctx->buffer, &ctx->buffer[16], left_over);
+ }
ctx->buflen = left_over;
}
}
@@ -295,36 +311,36 @@ sha1_process_block (const void *buffer, size_t len, struct sha1_ctx *ctx)
uint32_t c = ctx->C;
uint32_t d = ctx->D;
uint32_t e = ctx->E;
+ uint32_t lolen = len;
/* First increment the byte count. RFC 1321 specifies the possible
length of the file up to 2^64 bits. Here we only compute the
number of bytes. Do a double word increment. */
- ctx->total[0] += len;
- if (ctx->total[0] < len)
- ++ctx->total[1];
+ ctx->total[0] += lolen;
+ ctx->total[1] += (len >> 31 >> 1) + (ctx->total[0] < lolen);
#define rol(x, n) (((x) << (n)) | ((uint32_t) (x) >> (32 - (n))))
#define M(I) ( tm = x[I&0x0f] ^ x[(I-14)&0x0f] \
- ^ x[(I-8)&0x0f] ^ x[(I-3)&0x0f] \
- , (x[I&0x0f] = rol(tm, 1)) )
+ ^ x[(I-8)&0x0f] ^ x[(I-3)&0x0f] \
+ , (x[I&0x0f] = rol(tm, 1)) )
#define R(A,B,C,D,E,F,K,M) do { E += rol( A, 5 ) \
- + F( B, C, D ) \
- + K \
- + M; \
- B = rol( B, 30 ); \
- } while(0)
+ + F( B, C, D ) \
+ + K \
+ + M; \
+ B = rol( B, 30 ); \
+ } while(0)
while (words < endp)
{
uint32_t tm;
int t;
for (t = 0; t < 16; t++)
- {
- x[t] = SWAP (*words);
- words++;
- }
+ {
+ x[t] = SWAP (*words);
+ words++;
+ }
R( a, b, c, d, e, F1, K1, x[ 0] );
R( e, a, b, c, d, F1, K1, x[ 1] );
@@ -414,3 +430,4 @@ sha1_process_block (const void *buffer, size_t len, struct sha1_ctx *ctx)
e = ctx->E += e;
}
}
+#endif
diff --git a/lib/sha1.h b/lib/sha1.h
index 9545f0b..2f2f230 100644
--- a/lib/sha1.h
+++ b/lib/sha1.h
@@ -1,10 +1,11 @@
/* Declarations of functions and data types used for SHA1 sum
library functions.
- Copyright (C) 2000, 2001, 2003, 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2000-2001, 2003, 2005-2006, 2008-2016 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 2, or (at your option) any
+ Free Software Foundation; either version 3, or (at your option) any
later version.
This program is distributed in the hope that it will be useful,
@@ -13,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program; if not, see <http://www.gnu.org/licenses/>. */
#ifndef SHA1_H
# define SHA1_H 1
@@ -22,6 +22,20 @@
# include <stdio.h>
# include <stdint.h>
+# if HAVE_OPENSSL_SHA1
+# include <openssl/sha.h>
+# endif
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+#define SHA1_DIGEST_SIZE 20
+
+# if HAVE_OPENSSL_SHA1
+# define GL_OPENSSL_NAME 1
+# include "gl_openssl.h"
+# else
/* Structure to save state of computation between the single steps. */
struct sha1_ctx
{
@@ -36,7 +50,6 @@ struct sha1_ctx
uint32_t buffer[32];
};
-
/* Initialize structure containing state of computation. */
extern void sha1_init_ctx (struct sha1_ctx *ctx);
@@ -45,43 +58,43 @@ extern void sha1_init_ctx (struct sha1_ctx *ctx);
starting at BUFFER.
It is necessary that LEN is a multiple of 64!!! */
extern void sha1_process_block (const void *buffer, size_t len,
- struct sha1_ctx *ctx);
+ struct sha1_ctx *ctx);
/* Starting with the result of former calls of this function (or the
initialization function update the context for the next LEN bytes
starting at BUFFER.
It is NOT required that LEN is a multiple of 64. */
extern void sha1_process_bytes (const void *buffer, size_t len,
- struct sha1_ctx *ctx);
+ struct sha1_ctx *ctx);
/* Process the remaining bytes in the buffer and put result from CTX
in first 20 bytes following RESBUF. The result is always in little
endian byte order, so that a byte-wise output yields to the wanted
- ASCII representation of the message digest.
-
- IMPORTANT: On some systems it is required that RESBUF be correctly
- aligned for a 32 bits value. */
+ ASCII representation of the message digest. */
extern void *sha1_finish_ctx (struct sha1_ctx *ctx, void *resbuf);
/* Put result from CTX in first 20 bytes following RESBUF. The result is
always in little endian byte order, so that a byte-wise output yields
- to the wanted ASCII representation of the message digest.
-
- IMPORTANT: On some systems it is required that RESBUF is correctly
- aligned for a 32 bits value. */
+ to the wanted ASCII representation of the message digest. */
extern void *sha1_read_ctx (const struct sha1_ctx *ctx, void *resbuf);
-/* Compute SHA1 message digest for bytes read from STREAM. The
- resulting message digest number will be written into the 20 bytes
- beginning at RESBLOCK. */
-extern int sha1_stream (FILE *stream, void *resblock);
-
/* Compute SHA1 message digest for LEN bytes beginning at BUFFER. The
result is always in little endian byte order, so that a byte-wise
output yields to the wanted ASCII representation of the message
digest. */
extern void *sha1_buffer (const char *buffer, size_t len, void *resblock);
+# endif
+/* Compute SHA1 message digest for bytes read from STREAM. The
+ resulting message digest number will be written into the 20 bytes
+ beginning at RESBLOCK. */
+extern int sha1_stream (FILE *stream, void *resblock);
+
+
+# ifdef __cplusplus
+}
+# endif
+
#endif
diff --git a/lib/sha256.c b/lib/sha256.c
index d23c509..0be8fd2 100644
--- a/lib/sha256.c
+++ b/lib/sha256.c
@@ -1,12 +1,12 @@
/* sha256.c - Functions to compute SHA256 and SHA224 message digest of files or
memory blocks according to the NIST specification FIPS-180-2.
- Copyright (C) 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2005-2006, 2008-2016 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 2, or (at your option) any
- later version.
+ 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
@@ -14,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by David Madore, considerably copypasting from
Scott G. Miller's sha1.c
@@ -23,9 +22,14 @@
#include <config.h>
+#if HAVE_OPENSSL_SHA256
+# define GL_OPENSSL_INLINE _GL_EXTERN_INLINE
+#endif
#include "sha256.h"
-#include <stddef.h>
+#include <stdalign.h>
+#include <stdint.h>
+#include <stdlib.h>
#include <string.h>
#if USE_UNLOCKED_IO
@@ -39,11 +43,12 @@
(((n) << 24) | (((n) & 0xff00) << 8) | (((n) >> 8) & 0xff00) | ((n) >> 24))
#endif
-#define BLOCKSIZE 4096
+#define BLOCKSIZE 32768
#if BLOCKSIZE % 64 != 0
# error "invalid BLOCKSIZE"
#endif
+#if ! HAVE_OPENSSL_SHA256
/* This array contains the bytes used to pad the buffer to the next
64-byte boundary. */
static const unsigned char fillbuf[64] = { 0x80, 0 /* , 0, 0, ... */ };
@@ -51,7 +56,7 @@ static const unsigned char fillbuf[64] = { 0x80, 0 /* , 0, 0, ... */ };
/*
Takes a pointer to a 256 bit block of data (eight 32 bit ints) and
- intializes it to the start constants of the SHA256 algorithm. This
+ initializes it to the start constants of the SHA256 algorithm. This
must be called before using hash in the call to sha256_hash
*/
void
@@ -86,18 +91,25 @@ sha224_init_ctx (struct sha256_ctx *ctx)
ctx->buflen = 0;
}
-/* Put result from CTX in first 32 bytes following RESBUF. The result
- must be in little endian byte order.
+/* Copy the value from v into the memory location pointed to by *cp,
+ If your architecture allows unaligned access this is equivalent to
+ * (uint32_t *) cp = v */
+static void
+set_uint32 (char *cp, uint32_t v)
+{
+ memcpy (cp, &v, sizeof v);
+}
- IMPORTANT: On some systems it is required that RESBUF is correctly
- aligned for a 32-bit value. */
+/* Put result from CTX in first 32 bytes following RESBUF. The result
+ must be in little endian byte order. */
void *
sha256_read_ctx (const struct sha256_ctx *ctx, void *resbuf)
{
int i;
+ char *r = resbuf;
for (i = 0; i < 8; i++)
- ((uint32_t *) resbuf)[i] = SWAP (ctx->state[i]);
+ set_uint32 (r + i * sizeof ctx->state[0], SWAP (ctx->state[i]));
return resbuf;
}
@@ -106,23 +118,21 @@ void *
sha224_read_ctx (const struct sha256_ctx *ctx, void *resbuf)
{
int i;
+ char *r = resbuf;
for (i = 0; i < 7; i++)
- ((uint32_t *) resbuf)[i] = SWAP (ctx->state[i]);
+ set_uint32 (r + i * sizeof ctx->state[0], SWAP (ctx->state[i]));
return resbuf;
}
/* Process the remaining bytes in the internal buffer and the usual
- prolog according to the standard and write the result to RESBUF.
-
- IMPORTANT: On some systems it is required that RESBUF is correctly
- aligned for a 32-bit value. */
+ prolog according to the standard and write the result to RESBUF. */
static void
sha256_conclude_ctx (struct sha256_ctx *ctx)
{
/* Take yet unprocessed bytes into account. */
- uint32_t bytes = ctx->buflen;
+ size_t bytes = ctx->buflen;
size_t size = (bytes < 56) ? 64 / 4 : 64 * 2 / 4;
/* Now count remaining bytes. */
@@ -130,9 +140,13 @@ sha256_conclude_ctx (struct sha256_ctx *ctx)
if (ctx->total[0] < bytes)
++ctx->total[1];
- /* Put the 64-bit file length in *bits* at the end of the buffer. */
- ctx->buffer[size - 2] = SWAP ((ctx->total[1] << 3) | (ctx->total[0] >> 29));
- ctx->buffer[size - 1] = SWAP (ctx->total[0] << 3);
+ /* Put the 64-bit file length in *bits* at the end of the buffer.
+ Use set_uint32 rather than a simple assignment, to avoid risk of
+ unaligned access. */
+ set_uint32 ((char *) &ctx->buffer[size - 2],
+ SWAP ((ctx->total[1] << 3) | (ctx->total[0] >> 29)));
+ set_uint32 ((char *) &ctx->buffer[size - 1],
+ SWAP (ctx->total[0] << 3));
memcpy (&((char *) ctx->buffer)[bytes], fillbuf, (size - 2) * 4 - bytes);
@@ -153,6 +167,7 @@ sha224_finish_ctx (struct sha256_ctx *ctx, void *resbuf)
sha256_conclude_ctx (ctx);
return sha224_read_ctx (ctx, resbuf);
}
+#endif
/* Compute SHA256 message digest for bytes read from STREAM. The
resulting message digest number will be written into the 32 bytes
@@ -161,9 +176,12 @@ int
sha256_stream (FILE *stream, void *resblock)
{
struct sha256_ctx ctx;
- char buffer[BLOCKSIZE + 72];
size_t sum;
+ char *buffer = malloc (BLOCKSIZE + 72);
+ if (!buffer)
+ return 1;
+
/* Initialize the computation context. */
sha256_init_ctx (&ctx);
@@ -171,40 +189,43 @@ sha256_stream (FILE *stream, void *resblock)
while (1)
{
/* We read the file in blocks of BLOCKSIZE bytes. One call of the
- computation function processes the whole buffer so that with the
- next round of the loop another block can be read. */
+ computation function processes the whole buffer so that with the
+ next round of the loop another block can be read. */
size_t n;
sum = 0;
/* Read block. Take care for partial reads. */
while (1)
- {
- n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
-
- sum += n;
-
- if (sum == BLOCKSIZE)
- break;
-
- if (n == 0)
- {
- /* Check for the error flag IFF N == 0, so that we don't
- exit the loop after a partial read due to e.g., EAGAIN
- or EWOULDBLOCK. */
- if (ferror (stream))
- return 1;
- goto process_partial_block;
- }
-
- /* We've read at least one byte, so ignore errors. But always
- check for EOF, since feof may be true even though N > 0.
- Otherwise, we could end up calling fread after EOF. */
- if (feof (stream))
- goto process_partial_block;
- }
+ {
+ n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
+
+ sum += n;
+
+ if (sum == BLOCKSIZE)
+ break;
+
+ if (n == 0)
+ {
+ /* Check for the error flag IFF N == 0, so that we don't
+ exit the loop after a partial read due to e.g., EAGAIN
+ or EWOULDBLOCK. */
+ if (ferror (stream))
+ {
+ free (buffer);
+ return 1;
+ }
+ goto process_partial_block;
+ }
+
+ /* We've read at least one byte, so ignore errors. But always
+ check for EOF, since feof may be true even though N > 0.
+ Otherwise, we could end up calling fread after EOF. */
+ if (feof (stream))
+ goto process_partial_block;
+ }
/* Process buffer with BLOCKSIZE bytes. Note that
- BLOCKSIZE % 64 == 0
+ BLOCKSIZE % 64 == 0
*/
sha256_process_block (buffer, BLOCKSIZE, &ctx);
}
@@ -217,6 +238,7 @@ sha256_stream (FILE *stream, void *resblock)
/* Construct result in desired memory. */
sha256_finish_ctx (&ctx, resblock);
+ free (buffer);
return 0;
}
@@ -225,9 +247,12 @@ int
sha224_stream (FILE *stream, void *resblock)
{
struct sha256_ctx ctx;
- char buffer[BLOCKSIZE + 72];
size_t sum;
+ char *buffer = malloc (BLOCKSIZE + 72);
+ if (!buffer)
+ return 1;
+
/* Initialize the computation context. */
sha224_init_ctx (&ctx);
@@ -235,40 +260,43 @@ sha224_stream (FILE *stream, void *resblock)
while (1)
{
/* We read the file in blocks of BLOCKSIZE bytes. One call of the
- computation function processes the whole buffer so that with the
- next round of the loop another block can be read. */
+ computation function processes the whole buffer so that with the
+ next round of the loop another block can be read. */
size_t n;
sum = 0;
/* Read block. Take care for partial reads. */
while (1)
- {
- n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
-
- sum += n;
-
- if (sum == BLOCKSIZE)
- break;
-
- if (n == 0)
- {
- /* Check for the error flag IFF N == 0, so that we don't
- exit the loop after a partial read due to e.g., EAGAIN
- or EWOULDBLOCK. */
- if (ferror (stream))
- return 1;
- goto process_partial_block;
- }
-
- /* We've read at least one byte, so ignore errors. But always
- check for EOF, since feof may be true even though N > 0.
- Otherwise, we could end up calling fread after EOF. */
- if (feof (stream))
- goto process_partial_block;
- }
+ {
+ n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
+
+ sum += n;
+
+ if (sum == BLOCKSIZE)
+ break;
+
+ if (n == 0)
+ {
+ /* Check for the error flag IFF N == 0, so that we don't
+ exit the loop after a partial read due to e.g., EAGAIN
+ or EWOULDBLOCK. */
+ if (ferror (stream))
+ {
+ free (buffer);
+ return 1;
+ }
+ goto process_partial_block;
+ }
+
+ /* We've read at least one byte, so ignore errors. But always
+ check for EOF, since feof may be true even though N > 0.
+ Otherwise, we could end up calling fread after EOF. */
+ if (feof (stream))
+ goto process_partial_block;
+ }
/* Process buffer with BLOCKSIZE bytes. Note that
- BLOCKSIZE % 64 == 0
+ BLOCKSIZE % 64 == 0
*/
sha256_process_block (buffer, BLOCKSIZE, &ctx);
}
@@ -281,9 +309,11 @@ sha224_stream (FILE *stream, void *resblock)
/* Construct result in desired memory. */
sha224_finish_ctx (&ctx, resblock);
+ free (buffer);
return 0;
}
+#if ! HAVE_OPENSSL_SHA256
/* Compute SHA512 message digest for LEN bytes beginning at BUFFER. The
result is always in little endian byte order, so that a byte-wise
output yields to the wanted ASCII representation of the message
@@ -332,15 +362,15 @@ sha256_process_bytes (const void *buffer, size_t len, struct sha256_ctx *ctx)
ctx->buflen += add;
if (ctx->buflen > 64)
- {
- sha256_process_block (ctx->buffer, ctx->buflen & ~63, ctx);
+ {
+ sha256_process_block (ctx->buffer, ctx->buflen & ~63, ctx);
- ctx->buflen &= 63;
- /* The regions in the following copy operation cannot overlap. */
- memcpy (ctx->buffer,
- &((char *) ctx->buffer)[(left_over + add) & ~63],
- ctx->buflen);
- }
+ ctx->buflen &= 63;
+ /* The regions in the following copy operation cannot overlap. */
+ memcpy (ctx->buffer,
+ &((char *) ctx->buffer)[(left_over + add) & ~63],
+ ctx->buflen);
+ }
buffer = (const char *) buffer + add;
len -= add;
@@ -350,22 +380,21 @@ sha256_process_bytes (const void *buffer, size_t len, struct sha256_ctx *ctx)
if (len >= 64)
{
#if !_STRING_ARCH_unaligned
-# define alignof(type) offsetof (struct { char c; type x; }, x)
-# define UNALIGNED_P(p) (((size_t) p) % alignof (uint32_t) != 0)
+# define UNALIGNED_P(p) ((uintptr_t) (p) % alignof (uint32_t) != 0)
if (UNALIGNED_P (buffer))
- while (len > 64)
- {
- sha256_process_block (memcpy (ctx->buffer, buffer, 64), 64, ctx);
- buffer = (const char *) buffer + 64;
- len -= 64;
- }
+ while (len > 64)
+ {
+ sha256_process_block (memcpy (ctx->buffer, buffer, 64), 64, ctx);
+ buffer = (const char *) buffer + 64;
+ len -= 64;
+ }
else
#endif
- {
- sha256_process_block (buffer, len & ~63, ctx);
- buffer = (const char *) buffer + (len & ~63);
- len &= 63;
- }
+ {
+ sha256_process_block (buffer, len & ~63, ctx);
+ buffer = (const char *) buffer + (len & ~63);
+ len &= 63;
+ }
}
/* Move remaining bytes in internal buffer. */
@@ -376,11 +405,11 @@ sha256_process_bytes (const void *buffer, size_t len, struct sha256_ctx *ctx)
memcpy (&((char *) ctx->buffer)[left_over], buffer, len);
left_over += len;
if (left_over >= 64)
- {
- sha256_process_block (ctx->buffer, 64, ctx);
- left_over -= 64;
- memcpy (ctx->buffer, &ctx->buffer[16], left_over);
- }
+ {
+ sha256_process_block (ctx->buffer, 64, ctx);
+ left_over -= 64;
+ memcpy (ctx->buffer, &ctx->buffer[16], left_over);
+ }
ctx->buflen = left_over;
}
}
@@ -431,13 +460,13 @@ sha256_process_block (const void *buffer, size_t len, struct sha256_ctx *ctx)
uint32_t f = ctx->state[5];
uint32_t g = ctx->state[6];
uint32_t h = ctx->state[7];
+ uint32_t lolen = len;
/* First increment the byte count. FIPS PUB 180-2 specifies the possible
length of the file up to 2^64 bits. Here we only compute the
number of bytes. Do a double word increment. */
- ctx->total[0] += len;
- if (ctx->total[0] < len)
- ++ctx->total[1];
+ ctx->total[0] += lolen;
+ ctx->total[1] += (len >> 31 >> 1) + (ctx->total[0] < lolen);
#define rol(x, n) (((x) << (n)) | ((x) >> (32 - (n))))
#define S0(x) (rol(x,25)^rol(x,14)^(x>>3))
@@ -446,16 +475,16 @@ sha256_process_block (const void *buffer, size_t len, struct sha256_ctx *ctx)
#define SS1(x) (rol(x,26)^rol(x,21)^rol(x,7))
#define M(I) ( tm = S1(x[(I-2)&0x0f]) + x[(I-7)&0x0f] \
- + S0(x[(I-15)&0x0f]) + x[I&0x0f] \
- , x[I&0x0f] = tm )
+ + S0(x[(I-15)&0x0f]) + x[I&0x0f] \
+ , x[I&0x0f] = tm )
#define R(A,B,C,D,E,F,G,H,K,M) do { t0 = SS0(A) + F2(A,B,C); \
t1 = H + SS1(E) \
+ F1(E,F,G) \
- + K \
- + M; \
- D += t1; H = t0 + t1; \
- } while(0)
+ + K \
+ + M; \
+ D += t1; H = t0 + t1; \
+ } while(0)
while (words < endp)
{
@@ -464,10 +493,10 @@ sha256_process_block (const void *buffer, size_t len, struct sha256_ctx *ctx)
int t;
/* FIXME: see sha1.c for a better implementation. */
for (t = 0; t < 16; t++)
- {
- x[t] = SWAP (*words);
- words++;
- }
+ {
+ x[t] = SWAP (*words);
+ words++;
+ }
R( a, b, c, d, e, f, g, h, K( 0), x[ 0] );
R( h, a, b, c, d, e, f, g, K( 1), x[ 1] );
@@ -544,3 +573,4 @@ sha256_process_block (const void *buffer, size_t len, struct sha256_ctx *ctx)
h = ctx->state[7] += h;
}
}
+#endif
diff --git a/lib/sha256.h b/lib/sha256.h
index ccbe6cf..fc6d67f 100644
--- a/lib/sha256.h
+++ b/lib/sha256.h
@@ -1,11 +1,11 @@
/* Declarations of functions and data types used for SHA256 and SHA224 sum
library functions.
- Copyright (C) 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2005-2006, 2008-2016 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 2, or (at your option) any
- later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifndef SHA256_H
# define SHA256_H 1
@@ -22,17 +21,33 @@
# include <stdio.h>
# include <stdint.h>
+# if HAVE_OPENSSL_SHA256
+# include <openssl/sha.h>
+# endif
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+enum { SHA224_DIGEST_SIZE = 224 / 8 };
+enum { SHA256_DIGEST_SIZE = 256 / 8 };
+
+# if HAVE_OPENSSL_SHA256
+# define GL_OPENSSL_NAME 224
+# include "gl_openssl.h"
+# define GL_OPENSSL_NAME 256
+# include "gl_openssl.h"
+# else
/* Structure to save state of computation between the single steps. */
struct sha256_ctx
{
uint32_t state[8];
uint32_t total[2];
- uint32_t buflen;
+ size_t buflen;
uint32_t buffer[32];
};
-
/* Initialize structure containing state of computation. */
extern void sha256_init_ctx (struct sha256_ctx *ctx);
extern void sha224_init_ctx (struct sha256_ctx *ctx);
@@ -42,42 +57,30 @@ extern void sha224_init_ctx (struct sha256_ctx *ctx);
starting at BUFFER.
It is necessary that LEN is a multiple of 64!!! */
extern void sha256_process_block (const void *buffer, size_t len,
- struct sha256_ctx *ctx);
+ struct sha256_ctx *ctx);
/* Starting with the result of former calls of this function (or the
initialization function update the context for the next LEN bytes
starting at BUFFER.
It is NOT required that LEN is a multiple of 64. */
extern void sha256_process_bytes (const void *buffer, size_t len,
- struct sha256_ctx *ctx);
+ struct sha256_ctx *ctx);
/* Process the remaining bytes in the buffer and put result from CTX
in first 32 (28) bytes following RESBUF. The result is always in little
endian byte order, so that a byte-wise output yields to the wanted
- ASCII representation of the message digest.
-
- IMPORTANT: On some systems it is required that RESBUF be correctly
- aligned for a 32 bits value. */
+ ASCII representation of the message digest. */
extern void *sha256_finish_ctx (struct sha256_ctx *ctx, void *resbuf);
extern void *sha224_finish_ctx (struct sha256_ctx *ctx, void *resbuf);
/* Put result from CTX in first 32 (28) bytes following RESBUF. The result is
always in little endian byte order, so that a byte-wise output yields
- to the wanted ASCII representation of the message digest.
-
- IMPORTANT: On some systems it is required that RESBUF is correctly
- aligned for a 32 bits value. */
+ to the wanted ASCII representation of the message digest. */
extern void *sha256_read_ctx (const struct sha256_ctx *ctx, void *resbuf);
extern void *sha224_read_ctx (const struct sha256_ctx *ctx, void *resbuf);
-/* Compute SHA256 (SHA224) message digest for bytes read from STREAM. The
- resulting message digest number will be written into the 32 (28) bytes
- beginning at RESBLOCK. */
-extern int sha256_stream (FILE *stream, void *resblock);
-extern int sha224_stream (FILE *stream, void *resblock);
-
/* Compute SHA256 (SHA224) message digest for LEN bytes beginning at BUFFER. The
result is always in little endian byte order, so that a byte-wise
output yields to the wanted ASCII representation of the message
@@ -85,4 +88,16 @@ extern int sha224_stream (FILE *stream, void *resblock);
extern void *sha256_buffer (const char *buffer, size_t len, void *resblock);
extern void *sha224_buffer (const char *buffer, size_t len, void *resblock);
+# endif
+/* Compute SHA256 (SHA224) message digest for bytes read from STREAM. The
+ resulting message digest number will be written into the 32 (28) bytes
+ beginning at RESBLOCK. */
+extern int sha256_stream (FILE *stream, void *resblock);
+extern int sha224_stream (FILE *stream, void *resblock);
+
+
+# ifdef __cplusplus
+}
+# endif
+
#endif
diff --git a/lib/sha512.c b/lib/sha512.c
index e24c6f5..5494dcb 100644
--- a/lib/sha512.c
+++ b/lib/sha512.c
@@ -1,12 +1,12 @@
/* sha512.c - Functions to compute SHA512 and SHA384 message digest of files or
memory blocks according to the NIST specification FIPS-180-2.
- Copyright (C) 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2005-2006, 2008-2016 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 2, or (at your option) any
- later version.
+ 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
@@ -14,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by David Madore, considerably copypasting from
Scott G. Miller's sha1.c
@@ -23,9 +22,14 @@
#include <config.h>
+#if HAVE_OPENSSL_SHA512
+# define GL_OPENSSL_INLINE _GL_EXTERN_INLINE
+#endif
#include "sha512.h"
-#include <stddef.h>
+#include <stdalign.h>
+#include <stdint.h>
+#include <stdlib.h>
#include <string.h>
#if USE_UNLOCKED_IO
@@ -36,21 +40,22 @@
# define SWAP(n) (n)
#else
# define SWAP(n) \
- u64or (u64or (u64or (u64shl (n, 56), \
- u64shl (u64and (n, u64lo (0x0000ff00)), 40)), \
- u64or (u64shl (u64and (n, u64lo (0x00ff0000)), 24), \
- u64shl (u64and (n, u64lo (0xff000000)), 8))), \
- u64or (u64or (u64and (u64shr (n, 8), u64lo (0xff000000)), \
- u64and (u64shr (n, 24), u64lo (0x00ff0000))), \
- u64or (u64and (u64shr (n, 40), u64lo (0x0000ff00)), \
- u64shr (n, 56))))
+ u64or (u64or (u64or (u64shl (n, 56), \
+ u64shl (u64and (n, u64lo (0x0000ff00)), 40)), \
+ u64or (u64shl (u64and (n, u64lo (0x00ff0000)), 24), \
+ u64shl (u64and (n, u64lo (0xff000000)), 8))), \
+ u64or (u64or (u64and (u64shr (n, 8), u64lo (0xff000000)), \
+ u64and (u64shr (n, 24), u64lo (0x00ff0000))), \
+ u64or (u64and (u64shr (n, 40), u64lo (0x0000ff00)), \
+ u64shr (n, 56))))
#endif
-#define BLOCKSIZE 4096
+#define BLOCKSIZE 32768
#if BLOCKSIZE % 128 != 0
# error "invalid BLOCKSIZE"
#endif
+#if ! HAVE_OPENSSL_SHA512
/* This array contains the bytes used to pad the buffer to the next
128-byte boundary. */
static const unsigned char fillbuf[128] = { 0x80, 0 /* , 0, 0, ... */ };
@@ -58,7 +63,7 @@ static const unsigned char fillbuf[128] = { 0x80, 0 /* , 0, 0, ... */ };
/*
Takes a pointer to a 512 bit block of data (eight 64 bit ints) and
- intializes it to the start constants of the SHA512 algorithm. This
+ initializes it to the start constants of the SHA512 algorithm. This
must be called before using hash in the call to sha512_hash
*/
void
@@ -93,18 +98,25 @@ sha384_init_ctx (struct sha512_ctx *ctx)
ctx->buflen = 0;
}
-/* Put result from CTX in first 64 bytes following RESBUF. The result
- must be in little endian byte order.
+/* Copy the value from V into the memory location pointed to by *CP,
+ If your architecture allows unaligned access, this is equivalent to
+ * (__typeof__ (v) *) cp = v */
+static void
+set_uint64 (char *cp, u64 v)
+{
+ memcpy (cp, &v, sizeof v);
+}
- IMPORTANT: On some systems it is required that RESBUF is correctly
- aligned for a 64-bit value. */
+/* Put result from CTX in first 64 bytes following RESBUF.
+ The result must be in little endian byte order. */
void *
sha512_read_ctx (const struct sha512_ctx *ctx, void *resbuf)
{
int i;
+ char *r = resbuf;
for (i = 0; i < 8; i++)
- ((u64 *) resbuf)[i] = SWAP (ctx->state[i]);
+ set_uint64 (r + i * sizeof ctx->state[0], SWAP (ctx->state[i]));
return resbuf;
}
@@ -113,18 +125,16 @@ void *
sha384_read_ctx (const struct sha512_ctx *ctx, void *resbuf)
{
int i;
+ char *r = resbuf;
for (i = 0; i < 6; i++)
- ((u64 *) resbuf)[i] = SWAP (ctx->state[i]);
+ set_uint64 (r + i * sizeof ctx->state[0], SWAP (ctx->state[i]));
return resbuf;
}
/* Process the remaining bytes in the internal buffer and the usual
- prolog according to the standard and write the result to RESBUF.
-
- IMPORTANT: On some systems it is required that RESBUF is correctly
- aligned for a 64-bit value. */
+ prolog according to the standard and write the result to RESBUF. */
static void
sha512_conclude_ctx (struct sha512_ctx *ctx)
{
@@ -137,10 +147,14 @@ sha512_conclude_ctx (struct sha512_ctx *ctx)
if (u64lt (ctx->total[0], u64lo (bytes)))
ctx->total[1] = u64plus (ctx->total[1], u64lo (1));
- /* Put the 64-bit file length in *bits* at the end of the buffer. */
- ctx->buffer[size - 2] = SWAP (u64or (u64shl (ctx->total[1], 3),
- u64shr (ctx->total[0], 61)));
- ctx->buffer[size - 1] = SWAP (u64shl (ctx->total[0], 3));
+ /* Put the 128-bit file length in *bits* at the end of the buffer.
+ Use set_uint64 rather than a simple assignment, to avoid risk of
+ unaligned access. */
+ set_uint64 ((char *) &ctx->buffer[size - 2],
+ SWAP (u64or (u64shl (ctx->total[1], 3),
+ u64shr (ctx->total[0], 61))));
+ set_uint64 ((char *) &ctx->buffer[size - 1],
+ SWAP (u64shl (ctx->total[0], 3)));
memcpy (&((char *) ctx->buffer)[bytes], fillbuf, (size - 2) * 8 - bytes);
@@ -161,6 +175,7 @@ sha384_finish_ctx (struct sha512_ctx *ctx, void *resbuf)
sha512_conclude_ctx (ctx);
return sha384_read_ctx (ctx, resbuf);
}
+#endif
/* Compute SHA512 message digest for bytes read from STREAM. The
resulting message digest number will be written into the 64 bytes
@@ -169,9 +184,12 @@ int
sha512_stream (FILE *stream, void *resblock)
{
struct sha512_ctx ctx;
- char buffer[BLOCKSIZE + 72];
size_t sum;
+ char *buffer = malloc (BLOCKSIZE + 72);
+ if (!buffer)
+ return 1;
+
/* Initialize the computation context. */
sha512_init_ctx (&ctx);
@@ -179,40 +197,43 @@ sha512_stream (FILE *stream, void *resblock)
while (1)
{
/* We read the file in blocks of BLOCKSIZE bytes. One call of the
- computation function processes the whole buffer so that with the
- next round of the loop another block can be read. */
+ computation function processes the whole buffer so that with the
+ next round of the loop another block can be read. */
size_t n;
sum = 0;
/* Read block. Take care for partial reads. */
while (1)
- {
- n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
-
- sum += n;
-
- if (sum == BLOCKSIZE)
- break;
-
- if (n == 0)
- {
- /* Check for the error flag IFF N == 0, so that we don't
- exit the loop after a partial read due to e.g., EAGAIN
- or EWOULDBLOCK. */
- if (ferror (stream))
- return 1;
- goto process_partial_block;
- }
-
- /* We've read at least one byte, so ignore errors. But always
- check for EOF, since feof may be true even though N > 0.
- Otherwise, we could end up calling fread after EOF. */
- if (feof (stream))
- goto process_partial_block;
- }
+ {
+ n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
+
+ sum += n;
+
+ if (sum == BLOCKSIZE)
+ break;
+
+ if (n == 0)
+ {
+ /* Check for the error flag IFF N == 0, so that we don't
+ exit the loop after a partial read due to e.g., EAGAIN
+ or EWOULDBLOCK. */
+ if (ferror (stream))
+ {
+ free (buffer);
+ return 1;
+ }
+ goto process_partial_block;
+ }
+
+ /* We've read at least one byte, so ignore errors. But always
+ check for EOF, since feof may be true even though N > 0.
+ Otherwise, we could end up calling fread after EOF. */
+ if (feof (stream))
+ goto process_partial_block;
+ }
/* Process buffer with BLOCKSIZE bytes. Note that
- BLOCKSIZE % 128 == 0
+ BLOCKSIZE % 128 == 0
*/
sha512_process_block (buffer, BLOCKSIZE, &ctx);
}
@@ -225,6 +246,7 @@ sha512_stream (FILE *stream, void *resblock)
/* Construct result in desired memory. */
sha512_finish_ctx (&ctx, resblock);
+ free (buffer);
return 0;
}
@@ -233,9 +255,12 @@ int
sha384_stream (FILE *stream, void *resblock)
{
struct sha512_ctx ctx;
- char buffer[BLOCKSIZE + 72];
size_t sum;
+ char *buffer = malloc (BLOCKSIZE + 72);
+ if (!buffer)
+ return 1;
+
/* Initialize the computation context. */
sha384_init_ctx (&ctx);
@@ -243,40 +268,43 @@ sha384_stream (FILE *stream, void *resblock)
while (1)
{
/* We read the file in blocks of BLOCKSIZE bytes. One call of the
- computation function processes the whole buffer so that with the
- next round of the loop another block can be read. */
+ computation function processes the whole buffer so that with the
+ next round of the loop another block can be read. */
size_t n;
sum = 0;
/* Read block. Take care for partial reads. */
while (1)
- {
- n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
-
- sum += n;
-
- if (sum == BLOCKSIZE)
- break;
-
- if (n == 0)
- {
- /* Check for the error flag IFF N == 0, so that we don't
- exit the loop after a partial read due to e.g., EAGAIN
- or EWOULDBLOCK. */
- if (ferror (stream))
- return 1;
- goto process_partial_block;
- }
-
- /* We've read at least one byte, so ignore errors. But always
- check for EOF, since feof may be true even though N > 0.
- Otherwise, we could end up calling fread after EOF. */
- if (feof (stream))
- goto process_partial_block;
- }
+ {
+ n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
+
+ sum += n;
+
+ if (sum == BLOCKSIZE)
+ break;
+
+ if (n == 0)
+ {
+ /* Check for the error flag IFF N == 0, so that we don't
+ exit the loop after a partial read due to e.g., EAGAIN
+ or EWOULDBLOCK. */
+ if (ferror (stream))
+ {
+ free (buffer);
+ return 1;
+ }
+ goto process_partial_block;
+ }
+
+ /* We've read at least one byte, so ignore errors. But always
+ check for EOF, since feof may be true even though N > 0.
+ Otherwise, we could end up calling fread after EOF. */
+ if (feof (stream))
+ goto process_partial_block;
+ }
/* Process buffer with BLOCKSIZE bytes. Note that
- BLOCKSIZE % 128 == 0
+ BLOCKSIZE % 128 == 0
*/
sha512_process_block (buffer, BLOCKSIZE, &ctx);
}
@@ -289,9 +317,11 @@ sha384_stream (FILE *stream, void *resblock)
/* Construct result in desired memory. */
sha384_finish_ctx (&ctx, resblock);
+ free (buffer);
return 0;
}
+#if ! HAVE_OPENSSL_SHA512
/* Compute SHA512 message digest for LEN bytes beginning at BUFFER. The
result is always in little endian byte order, so that a byte-wise
output yields to the wanted ASCII representation of the message
@@ -340,15 +370,15 @@ sha512_process_bytes (const void *buffer, size_t len, struct sha512_ctx *ctx)
ctx->buflen += add;
if (ctx->buflen > 128)
- {
- sha512_process_block (ctx->buffer, ctx->buflen & ~63, ctx);
+ {
+ sha512_process_block (ctx->buffer, ctx->buflen & ~127, ctx);
- ctx->buflen &= 127;
- /* The regions in the following copy operation cannot overlap. */
- memcpy (ctx->buffer,
- &((char *) ctx->buffer)[(left_over + add) & ~127],
- ctx->buflen);
- }
+ ctx->buflen &= 127;
+ /* The regions in the following copy operation cannot overlap. */
+ memcpy (ctx->buffer,
+ &((char *) ctx->buffer)[(left_over + add) & ~127],
+ ctx->buflen);
+ }
buffer = (const char *) buffer + add;
len -= add;
@@ -358,22 +388,21 @@ sha512_process_bytes (const void *buffer, size_t len, struct sha512_ctx *ctx)
if (len >= 128)
{
#if !_STRING_ARCH_unaligned
-# define alignof(type) offsetof (struct { char c; type x; }, x)
-# define UNALIGNED_P(p) (((size_t) p) % alignof (u64) != 0)
+# define UNALIGNED_P(p) ((uintptr_t) (p) % alignof (u64) != 0)
if (UNALIGNED_P (buffer))
- while (len > 128)
- {
- sha512_process_block (memcpy (ctx->buffer, buffer, 128), 128, ctx);
- buffer = (const char *) buffer + 128;
- len -= 128;
- }
+ while (len > 128)
+ {
+ sha512_process_block (memcpy (ctx->buffer, buffer, 128), 128, ctx);
+ buffer = (const char *) buffer + 128;
+ len -= 128;
+ }
else
#endif
- {
- sha512_process_block (buffer, len & ~127, ctx);
- buffer = (const char *) buffer + (len & ~127);
- len &= 127;
- }
+ {
+ sha512_process_block (buffer, len & ~127, ctx);
+ buffer = (const char *) buffer + (len & ~127);
+ len &= 127;
+ }
}
/* Move remaining bytes in internal buffer. */
@@ -384,11 +413,11 @@ sha512_process_bytes (const void *buffer, size_t len, struct sha512_ctx *ctx)
memcpy (&((char *) ctx->buffer)[left_over], buffer, len);
left_over += len;
if (left_over >= 128)
- {
- sha512_process_block (ctx->buffer, 128, ctx);
- left_over -= 128;
- memcpy (ctx->buffer, &ctx->buffer[16], left_over);
- }
+ {
+ sha512_process_block (ctx->buffer, 128, ctx);
+ left_over -= 128;
+ memcpy (ctx->buffer, &ctx->buffer[16], left_over);
+ }
ctx->buflen = left_over;
}
}
@@ -462,35 +491,37 @@ sha512_process_block (const void *buffer, size_t len, struct sha512_ctx *ctx)
u64 f = ctx->state[5];
u64 g = ctx->state[6];
u64 h = ctx->state[7];
+ u64 lolen = u64size (len);
/* First increment the byte count. FIPS PUB 180-2 specifies the possible
length of the file up to 2^128 bits. Here we only compute the
number of bytes. Do a double word increment. */
- ctx->total[0] = u64plus (ctx->total[0], u64lo (len));
- if (u64lt (ctx->total[0], u64lo (len)))
- ctx->total[1] = u64plus (ctx->total[1], u64lo (1));
+ ctx->total[0] = u64plus (ctx->total[0], lolen);
+ ctx->total[1] = u64plus (ctx->total[1],
+ u64plus (u64size (len >> 31 >> 31 >> 2),
+ u64lo (u64lt (ctx->total[0], lolen))));
#define S0(x) u64xor (u64rol(x, 63), u64xor (u64rol (x, 56), u64shr (x, 7)))
#define S1(x) u64xor (u64rol (x, 45), u64xor (u64rol (x, 3), u64shr (x, 6)))
#define SS0(x) u64xor (u64rol (x, 36), u64xor (u64rol (x, 30), u64rol (x, 25)))
#define SS1(x) u64xor (u64rol(x, 50), u64xor (u64rol (x, 46), u64rol (x, 23)))
-#define M(I) (x[(I) & 15] \
- = u64plus (x[(I) & 15], \
- u64plus (S1 (x[((I) - 2) & 15]), \
- u64plus (x[((I) - 7) & 15], \
- S0 (x[((I) - 15) & 15])))))
-
-#define R(A, B, C, D, E, F, G, H, K, M) \
- do \
- { \
- u64 t0 = u64plus (SS0 (A), F2 (A, B, C)); \
- u64 t1 = \
- u64plus (H, u64plus (SS1 (E), \
- u64plus (F1 (E, F, G), u64plus (K, M)))); \
- D = u64plus (D, t1); \
- H = u64plus (t0, t1); \
- } \
+#define M(I) (x[(I) & 15] \
+ = u64plus (x[(I) & 15], \
+ u64plus (S1 (x[((I) - 2) & 15]), \
+ u64plus (x[((I) - 7) & 15], \
+ S0 (x[((I) - 15) & 15])))))
+
+#define R(A, B, C, D, E, F, G, H, K, M) \
+ do \
+ { \
+ u64 t0 = u64plus (SS0 (A), F2 (A, B, C)); \
+ u64 t1 = \
+ u64plus (H, u64plus (SS1 (E), \
+ u64plus (F1 (E, F, G), u64plus (K, M)))); \
+ D = u64plus (D, t1); \
+ H = u64plus (t0, t1); \
+ } \
while (0)
while (words < endp)
@@ -498,10 +529,10 @@ sha512_process_block (const void *buffer, size_t len, struct sha512_ctx *ctx)
int t;
/* FIXME: see sha1.c for a better implementation. */
for (t = 0; t < 16; t++)
- {
- x[t] = SWAP (*words);
- words++;
- }
+ {
+ x[t] = SWAP (*words);
+ words++;
+ }
R( a, b, c, d, e, f, g, h, K( 0), x[ 0] );
R( h, a, b, c, d, e, f, g, K( 1), x[ 1] );
@@ -594,3 +625,4 @@ sha512_process_block (const void *buffer, size_t len, struct sha512_ctx *ctx)
h = ctx->state[7] = u64plus (ctx->state[7], h);
}
}
+#endif
diff --git a/lib/sha512.h b/lib/sha512.h
index 995511e..b8a8251 100644
--- a/lib/sha512.h
+++ b/lib/sha512.h
@@ -1,11 +1,11 @@
/* Declarations of functions and data types used for SHA512 and SHA384 sum
library functions.
- Copyright (C) 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2005-2006, 2008-2016 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 2, or (at your option) any
- later version.
+ 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
@@ -13,16 +13,31 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifndef SHA512_H
# define SHA512_H 1
# include <stdio.h>
-
# include "u64.h"
+# if HAVE_OPENSSL_SHA512
+# include <openssl/sha.h>
+# endif
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+enum { SHA384_DIGEST_SIZE = 384 / 8 };
+enum { SHA512_DIGEST_SIZE = 512 / 8 };
+
+# if HAVE_OPENSSL_SHA512
+# define GL_OPENSSL_NAME 384
+# include "gl_openssl.h"
+# define GL_OPENSSL_NAME 512
+# include "gl_openssl.h"
+# else
/* Structure to save state of computation between the single steps. */
struct sha512_ctx
{
@@ -33,7 +48,6 @@ struct sha512_ctx
u64 buffer[32];
};
-
/* Initialize structure containing state of computation. */
extern void sha512_init_ctx (struct sha512_ctx *ctx);
extern void sha384_init_ctx (struct sha512_ctx *ctx);
@@ -43,22 +57,19 @@ extern void sha384_init_ctx (struct sha512_ctx *ctx);
starting at BUFFER.
It is necessary that LEN is a multiple of 128!!! */
extern void sha512_process_block (const void *buffer, size_t len,
- struct sha512_ctx *ctx);
+ struct sha512_ctx *ctx);
/* Starting with the result of former calls of this function (or the
initialization function update the context for the next LEN bytes
starting at BUFFER.
It is NOT required that LEN is a multiple of 128. */
extern void sha512_process_bytes (const void *buffer, size_t len,
- struct sha512_ctx *ctx);
+ struct sha512_ctx *ctx);
/* Process the remaining bytes in the buffer and put result from CTX
in first 64 (48) bytes following RESBUF. The result is always in little
endian byte order, so that a byte-wise output yields to the wanted
- ASCII representation of the message digest.
-
- IMPORTANT: On some systems it is required that RESBUF be correctly
- aligned for a 64 bits value. */
+ ASCII representation of the message digest. */
extern void *sha512_finish_ctx (struct sha512_ctx *ctx, void *resbuf);
extern void *sha384_finish_ctx (struct sha512_ctx *ctx, void *resbuf);
@@ -73,12 +84,6 @@ extern void *sha512_read_ctx (const struct sha512_ctx *ctx, void *resbuf);
extern void *sha384_read_ctx (const struct sha512_ctx *ctx, void *resbuf);
-/* Compute SHA512 (SHA384) message digest for bytes read from STREAM. The
- resulting message digest number will be written into the 64 (48) bytes
- beginning at RESBLOCK. */
-extern int sha512_stream (FILE *stream, void *resblock);
-extern int sha384_stream (FILE *stream, void *resblock);
-
/* Compute SHA512 (SHA384) message digest for LEN bytes beginning at BUFFER. The
result is always in little endian byte order, so that a byte-wise
output yields to the wanted ASCII representation of the message
@@ -86,4 +91,16 @@ extern int sha384_stream (FILE *stream, void *resblock);
extern void *sha512_buffer (const char *buffer, size_t len, void *resblock);
extern void *sha384_buffer (const char *buffer, size_t len, void *resblock);
+# endif
+/* Compute SHA512 (SHA384) message digest for bytes read from STREAM. The
+ resulting message digest number will be written into the 64 (48) bytes
+ beginning at RESBLOCK. */
+extern int sha512_stream (FILE *stream, void *resblock);
+extern int sha384_stream (FILE *stream, void *resblock);
+
+
+# ifdef __cplusplus
+}
+# endif
+
#endif
diff --git a/lib/sig-handler.c b/lib/sig-handler.c
new file mode 100644
index 0000000..52c3621
--- /dev/null
+++ b/lib/sig-handler.c
@@ -0,0 +1,3 @@
+#include <config.h>
+#define SIG_HANDLER_INLINE _GL_EXTERN_INLINE
+#include "sig-handler.h"
diff --git a/lib/sig-handler.h b/lib/sig-handler.h
new file mode 100644
index 0000000..ad8c1dd
--- /dev/null
+++ b/lib/sig-handler.h
@@ -0,0 +1,54 @@
+/* Convenience declarations when working with <signal.h>.
+
+ Copyright (C) 2008-2016 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _GL_SIG_HANDLER_H
+#define _GL_SIG_HANDLER_H
+
+#include <signal.h>
+
+#ifndef _GL_INLINE_HEADER_BEGIN
+ #error "Please include config.h first."
+#endif
+_GL_INLINE_HEADER_BEGIN
+#ifndef SIG_HANDLER_INLINE
+# define SIG_HANDLER_INLINE _GL_INLINE
+#endif
+
+/* Convenience type when working with signal handlers. */
+typedef void (*sa_handler_t) (int);
+
+/* Return the handler of a signal, as a sa_handler_t value regardless
+ of its true type. The resulting function can be compared to
+ special values like SIG_IGN but it is not portable to call it. */
+SIG_HANDLER_INLINE sa_handler_t _GL_ATTRIBUTE_PURE
+get_handler (struct sigaction const *a)
+{
+#ifdef SA_SIGINFO
+ /* POSIX says that special values like SIG_IGN can only occur when
+ action.sa_flags does not contain SA_SIGINFO. But in Linux 2.4,
+ for example, sa_sigaction and sa_handler are aliases and a signal
+ is ignored if sa_sigaction (after casting) equals SIG_IGN. So
+ use (and cast) sa_sigaction in that case. */
+ if (a->sa_flags & SA_SIGINFO)
+ return (sa_handler_t) a->sa_sigaction;
+#endif
+ return a->sa_handler;
+}
+
+_GL_INLINE_HEADER_END
+
+#endif /* _GL_SIG_HANDLER_H */
diff --git a/lib/sig2str.c b/lib/sig2str.c
index cf2819d..ca8ac78 100644
--- a/lib/sig2str.c
+++ b/lib/sig2str.c
@@ -1,11 +1,11 @@
/* sig2str.c -- convert between signal names and numbers
- Copyright (C) 2002, 2004, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2002, 2004, 2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
@@ -42,7 +41,7 @@
static struct numname { int num; char const name[8]; } numname_table[] =
{
/* Signals required by POSIX 1003.1-2001 base, listed in
- traditional numeric order. */
+ traditional numeric order where possible. */
#ifdef SIGHUP
NUMNAME (HUP),
#endif
@@ -67,12 +66,14 @@ static struct numname { int num; char const name[8]; } numname_table[] =
#ifdef SIGKILL
NUMNAME (KILL),
#endif
-#ifdef SIGBUS
- NUMNAME (BUS),
-#endif
#ifdef SIGSEGV
NUMNAME (SEGV),
#endif
+ /* On Haiku, SIGSEGV == SIGBUS, but we prefer SIGSEGV to match
+ strsignal.c output, so SIGBUS must be listed second. */
+#ifdef SIGBUS
+ NUMNAME (BUS),
+#endif
#ifdef SIGPIPE
NUMNAME (PIPE),
#endif
@@ -132,7 +133,7 @@ static struct numname { int num; char const name[8]; } numname_table[] =
/* Unix Version 7. */
#ifdef SIGIOT
- NUMNAME (IOT), /* Older name for ABRT. */
+ NUMNAME (IOT), /* Older name for ABRT. */
#endif
#ifdef SIGEMT
NUMNAME (EMT),
@@ -216,16 +217,16 @@ static struct numname { int num; char const name[8]; } numname_table[] =
/* Older AIX versions. */
#ifdef SIGALRM1
- NUMNAME (ALRM1), /* unknown; taken from Bash 2.05 */
+ NUMNAME (ALRM1), /* unknown; taken from Bash 2.05 */
#endif
#ifdef SIGKAP
- NUMNAME (KAP), /* Older name for SIGGRANT. */
+ NUMNAME (KAP), /* Older name for SIGGRANT. */
#endif
#ifdef SIGVIRT
- NUMNAME (VIRT), /* unknown; taken from Bash 2.05 */
+ NUMNAME (VIRT), /* unknown; taken from Bash 2.05 */
#endif
#ifdef SIGWINDOW
- NUMNAME (WINDOW), /* Older name for SIGWINCH. */
+ NUMNAME (WINDOW), /* Older name for SIGWINCH. */
#endif
/* BeOS */
@@ -250,7 +251,7 @@ static struct numname { int num; char const name[8]; } numname_table[] =
- It's typically faster.
POSIX says that only '0' through '9' are digits. Prefer ISDIGIT to
isdigit unless it's important to use the locale's definition
- of `digit' even when the host does not conform to POSIX. */
+ of "digit" even when the host does not conform to POSIX. */
#define ISDIGIT(c) ((unsigned int) (c) - '0' <= 9)
/* Convert the signal name SIGNAME to a signal number. Return the
@@ -264,32 +265,32 @@ str2signum (char const *signame)
char *endp;
long int n = strtol (signame, &endp, 10);
if (! *endp && n <= SIGNUM_BOUND)
- return n;
+ return n;
}
else
{
unsigned int i;
for (i = 0; i < NUMNAME_ENTRIES; i++)
- if (strcmp (numname_table[i].name, signame) == 0)
- return numname_table[i].num;
+ if (strcmp (numname_table[i].name, signame) == 0)
+ return numname_table[i].num;
{
- char *endp;
- int rtmin = SIGRTMIN;
- int rtmax = SIGRTMAX;
-
- if (0 < rtmin && strncmp (signame, "RTMIN", 5) == 0)
- {
- long int n = strtol (signame + 5, &endp, 10);
- if (! *endp && 0 <= n && n <= rtmax - rtmin)
- return rtmin + n;
- }
- else if (0 < rtmax && strncmp (signame, "RTMAX", 5) == 0)
- {
- long int n = strtol (signame + 5, &endp, 10);
- if (! *endp && rtmin - rtmax <= n && n <= 0)
- return rtmax + n;
- }
+ char *endp;
+ int rtmin = SIGRTMIN;
+ int rtmax = SIGRTMAX;
+
+ if (0 < rtmin && strncmp (signame, "RTMIN", 5) == 0)
+ {
+ long int n = strtol (signame + 5, &endp, 10);
+ if (! *endp && 0 <= n && n <= rtmax - rtmin)
+ return rtmin + n;
+ }
+ else if (0 < rtmax && strncmp (signame, "RTMAX", 5) == 0)
+ {
+ long int n = strtol (signame + 5, &endp, 10);
+ if (! *endp && rtmin - rtmax <= n && n <= 0)
+ return rtmax + n;
+ }
}
}
@@ -317,28 +318,32 @@ sig2str (int signum, char *signame)
for (i = 0; i < NUMNAME_ENTRIES; i++)
if (numname_table[i].num == signum)
{
- strcpy (signame, numname_table[i].name);
- return 0;
+ strcpy (signame, numname_table[i].name);
+ return 0;
}
{
int rtmin = SIGRTMIN;
int rtmax = SIGRTMAX;
+ int base, delta;
if (! (rtmin <= signum && signum <= rtmax))
return -1;
if (signum <= rtmin + (rtmax - rtmin) / 2)
{
- int delta = signum - rtmin;
- sprintf (signame, delta ? "RTMIN+%d" : "RTMIN", delta);
+ strcpy (signame, "RTMIN");
+ base = rtmin;
}
else
{
- int delta = rtmax - signum;
- sprintf (signame, delta ? "RTMAX-%d" : "RTMAX", delta);
+ strcpy (signame, "RTMAX");
+ base = rtmax;
}
+ delta = signum - base;
+ if (delta != 0)
+ sprintf (signame + 5, "%+d", delta);
return 0;
}
}
diff --git a/lib/sig2str.h b/lib/sig2str.h
index f0fe9c3..2730774 100644
--- a/lib/sig2str.h
+++ b/lib/sig2str.h
@@ -1,11 +1,11 @@
/* sig2str.h -- convert between signal names and numbers
- Copyright (C) 2002, 2005 Free Software Foundation, Inc.
+ Copyright (C) 2002, 2005, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
@@ -28,15 +27,25 @@
/* Size of a buffer needed to hold a signal name like "HUP". */
# define SIG2STR_MAX (sizeof "SIGRTMAX" + INT_STRLEN_BOUND (int) - 1)
+#ifdef __cplusplus
+extern "C" {
+#endif
+
int sig2str (int, char *);
int str2sig (char const *, int *);
+#ifdef __cplusplus
+}
+#endif
+
#endif
/* An upper bound on signal numbers allowed by the system. */
#if defined _sys_nsig
# define SIGNUM_BOUND (_sys_nsig - 1)
+#elif defined _SIG_MAXSIG
+# define SIGNUM_BOUND (_SIG_MAXSIG - 2) /* FreeBSD >= 7. */
#elif defined NSIG
# define SIGNUM_BOUND (NSIG - 1)
#else
diff --git a/lib/sigaction.c b/lib/sigaction.c
new file mode 100644
index 0000000..529b612
--- /dev/null
+++ b/lib/sigaction.c
@@ -0,0 +1,204 @@
+/* POSIX compatible signal blocking.
+ Copyright (C) 2008-2016 Free Software Foundation, Inc.
+ Written by Eric Blake <ebb9@byu.net>, 2008.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <signal.h>
+
+#include <errno.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+/* This implementation of sigaction is tailored to native Windows behavior:
+ signal() has SysV semantics (ie. the handler is uninstalled before
+ it is invoked). This is an inherent data race if an asynchronous
+ signal is sent twice in a row before we can reinstall our handler,
+ but there's nothing we can do about it. Meanwhile, sigprocmask()
+ is not present, and while we can use the gnulib replacement to
+ provide critical sections, it too suffers from potential data races
+ in the face of an ill-timed asynchronous signal. And we compound
+ the situation by reading static storage in a signal handler, which
+ POSIX warns is not generically async-signal-safe. Oh well.
+
+ Additionally:
+ - We don't implement SA_NOCLDSTOP or SA_NOCLDWAIT, because SIGCHLD
+ is not defined.
+ - We don't implement SA_ONSTACK, because sigaltstack() is not present.
+ - We ignore SA_RESTART, because blocking native Windows API calls are
+ not interrupted anyway when an asynchronous signal occurs, and the
+ MSVCRT runtime never sets errno to EINTR.
+ - We don't implement SA_SIGINFO because it is impossible to do so
+ portably.
+
+ POSIX states that an application should not mix signal() and
+ sigaction(). We support the use of signal() within the gnulib
+ sigprocmask() substitute, but all other application code linked
+ with this module should stick with only sigaction(). */
+
+/* Check some of our assumptions. */
+#if defined SIGCHLD || defined HAVE_SIGALTSTACK || defined HAVE_SIGINTERRUPT
+# error "Revisit the assumptions made in the sigaction module"
+#endif
+
+/* Out-of-range substitutes make a good fallback for uncatchable
+ signals. */
+#ifndef SIGKILL
+# define SIGKILL (-1)
+#endif
+#ifndef SIGSTOP
+# define SIGSTOP (-1)
+#endif
+
+/* On native Windows, as of 2008, the signal SIGABRT_COMPAT is an alias
+ for the signal SIGABRT. Only one signal handler is stored for both
+ SIGABRT and SIGABRT_COMPAT. SIGABRT_COMPAT is not a signal of its own. */
+#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+# undef SIGABRT_COMPAT
+# define SIGABRT_COMPAT 6
+#endif
+
+/* A signal handler. */
+typedef void (*handler_t) (int signal);
+
+/* Set of current actions. If sa_handler for an entry is NULL, then
+ that signal is not currently handled by the sigaction handler. */
+static struct sigaction volatile action_array[NSIG] /* = 0 */;
+
+/* Signal handler that is installed for signals. */
+static void
+sigaction_handler (int sig)
+{
+ handler_t handler;
+ sigset_t mask;
+ sigset_t oldmask;
+ int saved_errno = errno;
+ if (sig < 0 || NSIG <= sig || !action_array[sig].sa_handler)
+ {
+ /* Unexpected situation; be careful to avoid recursive abort. */
+ if (sig == SIGABRT)
+ signal (SIGABRT, SIG_DFL);
+ abort ();
+ }
+
+ /* Reinstall the signal handler when required; otherwise update the
+ bookkeeping so that the user's handler may call sigaction and get
+ accurate results. We know the signal isn't currently blocked, or
+ we wouldn't be in its handler, therefore we know that we are not
+ interrupting a sigaction() call. There is a race where any
+ asynchronous instance of the same signal occurring before we
+ reinstall the handler will trigger the default handler; oh
+ well. */
+ handler = action_array[sig].sa_handler;
+ if ((action_array[sig].sa_flags & SA_RESETHAND) == 0)
+ signal (sig, sigaction_handler);
+ else
+ action_array[sig].sa_handler = NULL;
+
+ /* Block appropriate signals. */
+ mask = action_array[sig].sa_mask;
+ if ((action_array[sig].sa_flags & SA_NODEFER) == 0)
+ sigaddset (&mask, sig);
+ sigprocmask (SIG_BLOCK, &mask, &oldmask);
+
+ /* Invoke the user's handler, then restore prior mask. */
+ errno = saved_errno;
+ handler (sig);
+ saved_errno = errno;
+ sigprocmask (SIG_SETMASK, &oldmask, NULL);
+ errno = saved_errno;
+}
+
+/* Change and/or query the action that will be taken on delivery of
+ signal SIG. If not NULL, ACT describes the new behavior. If not
+ NULL, OACT is set to the prior behavior. Return 0 on success, or
+ set errno and return -1 on failure. */
+int
+sigaction (int sig, const struct sigaction *restrict act,
+ struct sigaction *restrict oact)
+{
+ sigset_t mask;
+ sigset_t oldmask;
+ int saved_errno;
+
+ if (sig < 0 || NSIG <= sig || sig == SIGKILL || sig == SIGSTOP
+ || (act && act->sa_handler == SIG_ERR))
+ {
+ errno = EINVAL;
+ return -1;
+ }
+
+#ifdef SIGABRT_COMPAT
+ if (sig == SIGABRT_COMPAT)
+ sig = SIGABRT;
+#endif
+
+ /* POSIX requires sigaction() to be async-signal-safe. In other
+ words, if an asynchronous signal can occur while we are anywhere
+ inside this function, the user's handler could then call
+ sigaction() recursively and expect consistent results. We meet
+ this rule by using sigprocmask to block all signals before
+ modifying any data structure that could be read from a signal
+ handler; this works since we know that the gnulib sigprocmask
+ replacement does not try to use sigaction() from its handler. */
+ if (!act && !oact)
+ return 0;
+ sigfillset (&mask);
+ sigprocmask (SIG_BLOCK, &mask, &oldmask);
+ if (oact)
+ {
+ if (action_array[sig].sa_handler)
+ *oact = action_array[sig];
+ else
+ {
+ /* Safe to change the handler at will here, since all
+ signals are currently blocked. */
+ oact->sa_handler = signal (sig, SIG_DFL);
+ if (oact->sa_handler == SIG_ERR)
+ goto failure;
+ signal (sig, oact->sa_handler);
+ oact->sa_flags = SA_RESETHAND | SA_NODEFER;
+ sigemptyset (&oact->sa_mask);
+ }
+ }
+
+ if (act)
+ {
+ /* Safe to install the handler before updating action_array,
+ since all signals are currently blocked. */
+ if (act->sa_handler == SIG_DFL || act->sa_handler == SIG_IGN)
+ {
+ if (signal (sig, act->sa_handler) == SIG_ERR)
+ goto failure;
+ action_array[sig].sa_handler = NULL;
+ }
+ else
+ {
+ if (signal (sig, sigaction_handler) == SIG_ERR)
+ goto failure;
+ action_array[sig] = *act;
+ }
+ }
+ sigprocmask (SIG_SETMASK, &oldmask, NULL);
+ return 0;
+
+ failure:
+ saved_errno = errno;
+ sigprocmask (SIG_SETMASK, &oldmask, NULL);
+ errno = saved_errno;
+ return -1;
+}
diff --git a/lib/siglist.h b/lib/siglist.h
new file mode 100644
index 0000000..7e1da0b
--- /dev/null
+++ b/lib/siglist.h
@@ -0,0 +1,132 @@
+/* Canonical list of all signal names.
+ Copyright (C) 1996-1999, 2008-2016 Free Software Foundation, Inc.
+ This file is part of the GNU C Library.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+/* This file should be usable for any platform, since it just associates
+ the SIG* macros with text names and descriptions. The actual values
+ come from <bits/signum.h> (via <signal.h>). For any signal macros do not
+ exist on every platform, we can use #ifdef tests here and still use
+ this single common file for all platforms. */
+
+/* This file is included multiple times. */
+
+/* Duplicate values (such as SIGBUS==SIGSEGV on Haiku) favor the last
+ list entry. */
+
+/* Standard signals */
+#ifdef SIGHUP
+ init_sig (SIGHUP, "HUP", N_("Hangup"))
+#endif
+#ifdef SIGINT
+ init_sig (SIGINT, "INT", N_("Interrupt"))
+#endif
+#ifdef SIGQUIT
+ init_sig (SIGQUIT, "QUIT", N_("Quit"))
+#endif
+#ifdef SIGILL
+ init_sig (SIGILL, "ILL", N_("Illegal instruction"))
+#endif
+#ifdef SIGTRAP
+ init_sig (SIGTRAP, "TRAP", N_("Trace/breakpoint trap"))
+#endif
+#ifdef SIGABRT
+ init_sig (SIGABRT, "ABRT", N_("Aborted"))
+#endif
+#ifdef SIGFPE
+ init_sig (SIGFPE, "FPE", N_("Floating point exception"))
+#endif
+#ifdef SIGKILL
+ init_sig (SIGKILL, "KILL", N_("Killed"))
+#endif
+#ifdef SIGBUS
+ init_sig (SIGBUS, "BUS", N_("Bus error"))
+#endif
+#ifdef SIGSEGV
+ init_sig (SIGSEGV, "SEGV", N_("Segmentation fault"))
+#endif
+#ifdef SIGPIPE
+ init_sig (SIGPIPE, "PIPE", N_("Broken pipe"))
+#endif
+#ifdef SIGALRM
+ init_sig (SIGALRM, "ALRM", N_("Alarm clock"))
+#endif
+#ifdef SIGTERM
+ init_sig (SIGTERM, "TERM", N_("Terminated"))
+#endif
+#ifdef SIGURG
+ init_sig (SIGURG, "URG", N_("Urgent I/O condition"))
+#endif
+#ifdef SIGSTOP
+ init_sig (SIGSTOP, "STOP", N_("Stopped (signal)"))
+#endif
+#ifdef SIGTSTP
+ init_sig (SIGTSTP, "TSTP", N_("Stopped"))
+#endif
+#ifdef SIGCONT
+ init_sig (SIGCONT, "CONT", N_("Continued"))
+#endif
+#ifdef SIGCHLD
+ init_sig (SIGCHLD, "CHLD", N_("Child exited"))
+#endif
+#ifdef SIGTTIN
+ init_sig (SIGTTIN, "TTIN", N_("Stopped (tty input)"))
+#endif
+#ifdef SIGTTOU
+ init_sig (SIGTTOU, "TTOU", N_("Stopped (tty output)"))
+#endif
+#ifdef SIGIO
+ init_sig (SIGIO, "IO", N_("I/O possible"))
+#endif
+#ifdef SIGXCPU
+ init_sig (SIGXCPU, "XCPU", N_("CPU time limit exceeded"))
+#endif
+#ifdef SIGXFSZ
+ init_sig (SIGXFSZ, "XFSZ", N_("File size limit exceeded"))
+#endif
+#ifdef SIGVTALRM
+ init_sig (SIGVTALRM, "VTALRM", N_("Virtual timer expired"))
+#endif
+#ifdef SIGPROF
+ init_sig (SIGPROF, "PROF", N_("Profiling timer expired"))
+#endif
+#ifdef SIGWINCH
+ init_sig (SIGWINCH, "WINCH", N_("Window changed"))
+#endif
+#ifdef SIGUSR1
+ init_sig (SIGUSR1, "USR1", N_("User defined signal 1"))
+#endif
+#ifdef SIGUSR2
+ init_sig (SIGUSR2, "USR2", N_("User defined signal 2"))
+#endif
+
+/* Variations */
+#ifdef SIGEMT
+ init_sig (SIGEMT, "EMT", N_("EMT trap"))
+#endif
+#ifdef SIGSYS
+ init_sig (SIGSYS, "SYS", N_("Bad system call"))
+#endif
+#ifdef SIGSTKFLT
+ init_sig (SIGSTKFLT, "STKFLT", N_("Stack fault"))
+#endif
+#ifdef SIGINFO
+ init_sig (SIGINFO, "INFO", N_("Information request"))
+#elif defined(SIGPWR) && (!defined(SIGLOST) || (SIGPWR != SIGLOST))
+ init_sig (SIGPWR, "PWR", N_("Power failure"))
+#endif
+#ifdef SIGLOST
+ init_sig (SIGLOST, "LOST", N_("Resource lost"))
+#endif
diff --git a/lib/signal.in.h b/lib/signal.in.h
new file mode 100644
index 0000000..ab0a049
--- /dev/null
+++ b/lib/signal.in.h
@@ -0,0 +1,463 @@
+/* A GNU-like <signal.h>.
+
+ Copyright (C) 2006-2016 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 <http://www.gnu.org/licenses/>. */
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+#if defined __need_sig_atomic_t || defined __need_sigset_t || defined _GL_ALREADY_INCLUDING_SIGNAL_H || (defined _SIGNAL_H && !defined __SIZEOF_PTHREAD_MUTEX_T)
+/* Special invocation convention:
+ - Inside glibc header files.
+ - On glibc systems we have a sequence of nested includes
+ <signal.h> -> <ucontext.h> -> <signal.h>.
+ In this situation, the functions are not yet declared, therefore we cannot
+ provide the C++ aliases.
+ - On glibc systems with GCC 4.3 we have a sequence of nested includes
+ <csignal> -> </usr/include/signal.h> -> <sys/ucontext.h> -> <signal.h>.
+ In this situation, some of the functions are not yet declared, therefore
+ we cannot provide the C++ aliases. */
+
+# @INCLUDE_NEXT@ @NEXT_SIGNAL_H@
+
+#else
+/* Normal invocation convention. */
+
+#ifndef _@GUARD_PREFIX@_SIGNAL_H
+
+#define _GL_ALREADY_INCLUDING_SIGNAL_H
+
+/* Define pid_t, uid_t.
+ Also, mingw defines sigset_t not in <signal.h>, but in <sys/types.h>.
+ On Solaris 10, <signal.h> includes <sys/types.h>, which eventually includes
+ us; so include <sys/types.h> now, before the second inclusion guard. */
+#include <sys/types.h>
+
+/* The include_next requires a split double-inclusion guard. */
+#@INCLUDE_NEXT@ @NEXT_SIGNAL_H@
+
+#undef _GL_ALREADY_INCLUDING_SIGNAL_H
+
+#ifndef _@GUARD_PREFIX@_SIGNAL_H
+#define _@GUARD_PREFIX@_SIGNAL_H
+
+/* Mac OS X 10.3, FreeBSD 6.4, OpenBSD 3.8, OSF/1 4.0, Solaris 2.6, Android
+ declare pthread_sigmask in <pthread.h>, not in <signal.h>.
+ But avoid namespace pollution on glibc systems.*/
+#if (@GNULIB_PTHREAD_SIGMASK@ || defined GNULIB_POSIXCHECK) \
+ && ((defined __APPLE__ && defined __MACH__) \
+ || defined __FreeBSD__ || defined __OpenBSD__ || defined __osf__ \
+ || defined __sun || defined __ANDROID__) \
+ && ! defined __GLIBC__
+# include <pthread.h>
+#endif
+
+/* The definitions of _GL_FUNCDECL_RPL etc. are copied here. */
+
+/* The definition of _GL_ARG_NONNULL is copied here. */
+
+/* The definition of _GL_WARN_ON_USE is copied here. */
+
+/* On AIX, sig_atomic_t already includes volatile. C99 requires that
+ 'volatile sig_atomic_t' ignore the extra modifier, but C89 did not.
+ Hence, redefine this to a non-volatile type as needed. */
+#if ! @HAVE_TYPE_VOLATILE_SIG_ATOMIC_T@
+# if !GNULIB_defined_sig_atomic_t
+typedef int rpl_sig_atomic_t;
+# undef sig_atomic_t
+# define sig_atomic_t rpl_sig_atomic_t
+# define GNULIB_defined_sig_atomic_t 1
+# endif
+#endif
+
+/* A set or mask of signals. */
+#if !@HAVE_SIGSET_T@
+# if !GNULIB_defined_sigset_t
+typedef unsigned int sigset_t;
+# define GNULIB_defined_sigset_t 1
+# endif
+#endif
+
+/* Define sighandler_t, the type of signal handlers. A GNU extension. */
+#if !@HAVE_SIGHANDLER_T@
+# ifdef __cplusplus
+extern "C" {
+# endif
+# if !GNULIB_defined_sighandler_t
+typedef void (*sighandler_t) (int);
+# define GNULIB_defined_sighandler_t 1
+# endif
+# ifdef __cplusplus
+}
+# endif
+#endif
+
+
+#if @GNULIB_SIGNAL_H_SIGPIPE@
+# ifndef SIGPIPE
+/* Define SIGPIPE to a value that does not overlap with other signals. */
+# define SIGPIPE 13
+# define GNULIB_defined_SIGPIPE 1
+/* To actually use SIGPIPE, you also need the gnulib modules 'sigprocmask',
+ 'write', 'stdio'. */
+# endif
+#endif
+
+
+/* Maximum signal number + 1. */
+#ifndef NSIG
+# if defined __TANDEM
+# define NSIG 32
+# endif
+#endif
+
+
+#if @GNULIB_PTHREAD_SIGMASK@
+# if @REPLACE_PTHREAD_SIGMASK@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef pthread_sigmask
+# define pthread_sigmask rpl_pthread_sigmask
+# endif
+_GL_FUNCDECL_RPL (pthread_sigmask, int,
+ (int how, const sigset_t *new_mask, sigset_t *old_mask));
+_GL_CXXALIAS_RPL (pthread_sigmask, int,
+ (int how, const sigset_t *new_mask, sigset_t *old_mask));
+# else
+# if !@HAVE_PTHREAD_SIGMASK@
+_GL_FUNCDECL_SYS (pthread_sigmask, int,
+ (int how, const sigset_t *new_mask, sigset_t *old_mask));
+# endif
+_GL_CXXALIAS_SYS (pthread_sigmask, int,
+ (int how, const sigset_t *new_mask, sigset_t *old_mask));
+# endif
+_GL_CXXALIASWARN (pthread_sigmask);
+#elif defined GNULIB_POSIXCHECK
+# undef pthread_sigmask
+# if HAVE_RAW_DECL_PTHREAD_SIGMASK
+_GL_WARN_ON_USE (pthread_sigmask, "pthread_sigmask is not portable - "
+ "use gnulib module pthread_sigmask for portability");
+# endif
+#endif
+
+
+#if @GNULIB_RAISE@
+# if @REPLACE_RAISE@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef raise
+# define raise rpl_raise
+# endif
+_GL_FUNCDECL_RPL (raise, int, (int sig));
+_GL_CXXALIAS_RPL (raise, int, (int sig));
+# else
+# if !@HAVE_RAISE@
+_GL_FUNCDECL_SYS (raise, int, (int sig));
+# endif
+_GL_CXXALIAS_SYS (raise, int, (int sig));
+# endif
+_GL_CXXALIASWARN (raise);
+#elif defined GNULIB_POSIXCHECK
+# undef raise
+/* Assume raise is always declared. */
+_GL_WARN_ON_USE (raise, "raise can crash on native Windows - "
+ "use gnulib module raise for portability");
+#endif
+
+
+#if @GNULIB_SIGPROCMASK@
+# if !@HAVE_POSIX_SIGNALBLOCKING@
+
+# ifndef GNULIB_defined_signal_blocking
+# define GNULIB_defined_signal_blocking 1
+# endif
+
+/* Maximum signal number + 1. */
+# ifndef NSIG
+# define NSIG 32
+# endif
+
+/* This code supports only 32 signals. */
+# if !GNULIB_defined_verify_NSIG_constraint
+typedef int verify_NSIG_constraint[NSIG <= 32 ? 1 : -1];
+# define GNULIB_defined_verify_NSIG_constraint 1
+# endif
+
+# endif
+
+/* When also using extern inline, suppress the use of static inline in
+ standard headers of problematic Apple configurations, as Libc at
+ least through Libc-825.26 (2013-04-09) mishandles it; see, e.g.,
+ <http://lists.gnu.org/archive/html/bug-gnulib/2012-12/msg00023.html>.
+ Perhaps Apple will fix this some day. */
+#if (defined _GL_EXTERN_INLINE_IN_USE && defined __APPLE__ \
+ && (defined __i386__ || defined __x86_64__))
+# undef sigaddset
+# undef sigdelset
+# undef sigemptyset
+# undef sigfillset
+# undef sigismember
+#endif
+
+/* Test whether a given signal is contained in a signal set. */
+# if @HAVE_POSIX_SIGNALBLOCKING@
+/* This function is defined as a macro on Mac OS X. */
+# if defined __cplusplus && defined GNULIB_NAMESPACE
+# undef sigismember
+# endif
+# else
+_GL_FUNCDECL_SYS (sigismember, int, (const sigset_t *set, int sig)
+ _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (sigismember, int, (const sigset_t *set, int sig));
+_GL_CXXALIASWARN (sigismember);
+
+/* Initialize a signal set to the empty set. */
+# if @HAVE_POSIX_SIGNALBLOCKING@
+/* This function is defined as a macro on Mac OS X. */
+# if defined __cplusplus && defined GNULIB_NAMESPACE
+# undef sigemptyset
+# endif
+# else
+_GL_FUNCDECL_SYS (sigemptyset, int, (sigset_t *set) _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (sigemptyset, int, (sigset_t *set));
+_GL_CXXALIASWARN (sigemptyset);
+
+/* Add a signal to a signal set. */
+# if @HAVE_POSIX_SIGNALBLOCKING@
+/* This function is defined as a macro on Mac OS X. */
+# if defined __cplusplus && defined GNULIB_NAMESPACE
+# undef sigaddset
+# endif
+# else
+_GL_FUNCDECL_SYS (sigaddset, int, (sigset_t *set, int sig)
+ _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (sigaddset, int, (sigset_t *set, int sig));
+_GL_CXXALIASWARN (sigaddset);
+
+/* Remove a signal from a signal set. */
+# if @HAVE_POSIX_SIGNALBLOCKING@
+/* This function is defined as a macro on Mac OS X. */
+# if defined __cplusplus && defined GNULIB_NAMESPACE
+# undef sigdelset
+# endif
+# else
+_GL_FUNCDECL_SYS (sigdelset, int, (sigset_t *set, int sig)
+ _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (sigdelset, int, (sigset_t *set, int sig));
+_GL_CXXALIASWARN (sigdelset);
+
+/* Fill a signal set with all possible signals. */
+# if @HAVE_POSIX_SIGNALBLOCKING@
+/* This function is defined as a macro on Mac OS X. */
+# if defined __cplusplus && defined GNULIB_NAMESPACE
+# undef sigfillset
+# endif
+# else
+_GL_FUNCDECL_SYS (sigfillset, int, (sigset_t *set) _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (sigfillset, int, (sigset_t *set));
+_GL_CXXALIASWARN (sigfillset);
+
+/* Return the set of those blocked signals that are pending. */
+# if !@HAVE_POSIX_SIGNALBLOCKING@
+_GL_FUNCDECL_SYS (sigpending, int, (sigset_t *set) _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (sigpending, int, (sigset_t *set));
+_GL_CXXALIASWARN (sigpending);
+
+/* If OLD_SET is not NULL, put the current set of blocked signals in *OLD_SET.
+ Then, if SET is not NULL, affect the current set of blocked signals by
+ combining it with *SET as indicated in OPERATION.
+ In this implementation, you are not allowed to change a signal handler
+ while the signal is blocked. */
+# if !@HAVE_POSIX_SIGNALBLOCKING@
+# define SIG_BLOCK 0 /* blocked_set = blocked_set | *set; */
+# define SIG_SETMASK 1 /* blocked_set = *set; */
+# define SIG_UNBLOCK 2 /* blocked_set = blocked_set & ~*set; */
+_GL_FUNCDECL_SYS (sigprocmask, int,
+ (int operation, const sigset_t *set, sigset_t *old_set));
+# endif
+_GL_CXXALIAS_SYS (sigprocmask, int,
+ (int operation, const sigset_t *set, sigset_t *old_set));
+_GL_CXXALIASWARN (sigprocmask);
+
+/* Install the handler FUNC for signal SIG, and return the previous
+ handler. */
+# ifdef __cplusplus
+extern "C" {
+# endif
+# if !GNULIB_defined_function_taking_int_returning_void_t
+typedef void (*_gl_function_taking_int_returning_void_t) (int);
+# define GNULIB_defined_function_taking_int_returning_void_t 1
+# endif
+# ifdef __cplusplus
+}
+# endif
+# if !@HAVE_POSIX_SIGNALBLOCKING@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define signal rpl_signal
+# endif
+_GL_FUNCDECL_RPL (signal, _gl_function_taking_int_returning_void_t,
+ (int sig, _gl_function_taking_int_returning_void_t func));
+_GL_CXXALIAS_RPL (signal, _gl_function_taking_int_returning_void_t,
+ (int sig, _gl_function_taking_int_returning_void_t func));
+# else
+_GL_CXXALIAS_SYS (signal, _gl_function_taking_int_returning_void_t,
+ (int sig, _gl_function_taking_int_returning_void_t func));
+# endif
+_GL_CXXALIASWARN (signal);
+
+# if !@HAVE_POSIX_SIGNALBLOCKING@ && GNULIB_defined_SIGPIPE
+/* Raise signal SIGPIPE. */
+_GL_EXTERN_C int _gl_raise_SIGPIPE (void);
+# endif
+
+#elif defined GNULIB_POSIXCHECK
+# undef sigaddset
+# if HAVE_RAW_DECL_SIGADDSET
+_GL_WARN_ON_USE (sigaddset, "sigaddset is unportable - "
+ "use the gnulib module sigprocmask for portability");
+# endif
+# undef sigdelset
+# if HAVE_RAW_DECL_SIGDELSET
+_GL_WARN_ON_USE (sigdelset, "sigdelset is unportable - "
+ "use the gnulib module sigprocmask for portability");
+# endif
+# undef sigemptyset
+# if HAVE_RAW_DECL_SIGEMPTYSET
+_GL_WARN_ON_USE (sigemptyset, "sigemptyset is unportable - "
+ "use the gnulib module sigprocmask for portability");
+# endif
+# undef sigfillset
+# if HAVE_RAW_DECL_SIGFILLSET
+_GL_WARN_ON_USE (sigfillset, "sigfillset is unportable - "
+ "use the gnulib module sigprocmask for portability");
+# endif
+# undef sigismember
+# if HAVE_RAW_DECL_SIGISMEMBER
+_GL_WARN_ON_USE (sigismember, "sigismember is unportable - "
+ "use the gnulib module sigprocmask for portability");
+# endif
+# undef sigpending
+# if HAVE_RAW_DECL_SIGPENDING
+_GL_WARN_ON_USE (sigpending, "sigpending is unportable - "
+ "use the gnulib module sigprocmask for portability");
+# endif
+# undef sigprocmask
+# if HAVE_RAW_DECL_SIGPROCMASK
+_GL_WARN_ON_USE (sigprocmask, "sigprocmask is unportable - "
+ "use the gnulib module sigprocmask for portability");
+# endif
+#endif /* @GNULIB_SIGPROCMASK@ */
+
+
+#if @GNULIB_SIGACTION@
+# if !@HAVE_SIGACTION@
+
+# if !@HAVE_SIGINFO_T@
+
+# if !GNULIB_defined_siginfo_types
+
+/* Present to allow compilation, but unsupported by gnulib. */
+union sigval
+{
+ int sival_int;
+ void *sival_ptr;
+};
+
+/* Present to allow compilation, but unsupported by gnulib. */
+struct siginfo_t
+{
+ int si_signo;
+ int si_code;
+ int si_errno;
+ pid_t si_pid;
+ uid_t si_uid;
+ void *si_addr;
+ int si_status;
+ long si_band;
+ union sigval si_value;
+};
+typedef struct siginfo_t siginfo_t;
+
+# define GNULIB_defined_siginfo_types 1
+# endif
+
+# endif /* !@HAVE_SIGINFO_T@ */
+
+/* We assume that platforms which lack the sigaction() function also lack
+ the 'struct sigaction' type, and vice versa. */
+
+# if !GNULIB_defined_struct_sigaction
+
+struct sigaction
+{
+ union
+ {
+ void (*_sa_handler) (int);
+ /* Present to allow compilation, but unsupported by gnulib. POSIX
+ says that implementations may, but not must, make sa_sigaction
+ overlap with sa_handler, but we know of no implementation where
+ they do not overlap. */
+ void (*_sa_sigaction) (int, siginfo_t *, void *);
+ } _sa_func;
+ sigset_t sa_mask;
+ /* Not all POSIX flags are supported. */
+ int sa_flags;
+};
+# define sa_handler _sa_func._sa_handler
+# define sa_sigaction _sa_func._sa_sigaction
+/* Unsupported flags are not present. */
+# define SA_RESETHAND 1
+# define SA_NODEFER 2
+# define SA_RESTART 4
+
+# define GNULIB_defined_struct_sigaction 1
+# endif
+
+_GL_FUNCDECL_SYS (sigaction, int, (int, const struct sigaction *restrict,
+ struct sigaction *restrict));
+
+# elif !@HAVE_STRUCT_SIGACTION_SA_SIGACTION@
+
+# define sa_sigaction sa_handler
+
+# endif /* !@HAVE_SIGACTION@, !@HAVE_STRUCT_SIGACTION_SA_SIGACTION@ */
+
+_GL_CXXALIAS_SYS (sigaction, int, (int, const struct sigaction *restrict,
+ struct sigaction *restrict));
+_GL_CXXALIASWARN (sigaction);
+
+#elif defined GNULIB_POSIXCHECK
+# undef sigaction
+# if HAVE_RAW_DECL_SIGACTION
+_GL_WARN_ON_USE (sigaction, "sigaction is unportable - "
+ "use the gnulib module sigaction for portability");
+# endif
+#endif
+
+/* Some systems don't have SA_NODEFER. */
+#ifndef SA_NODEFER
+# define SA_NODEFER 0
+#endif
+
+
+#endif /* _@GUARD_PREFIX@_SIGNAL_H */
+#endif /* _@GUARD_PREFIX@_SIGNAL_H */
+#endif
diff --git a/lib/signbitd.c b/lib/signbitd.c
new file mode 100644
index 0000000..2de7ee6
--- /dev/null
+++ b/lib/signbitd.c
@@ -0,0 +1,64 @@
+/* signbit() macro: Determine the sign bit of a floating-point number.
+ Copyright (C) 2007-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <math.h>
+
+#include <string.h>
+#include "isnand-nolibm.h"
+#include "float+.h"
+
+#ifdef gl_signbitd_OPTIMIZED_MACRO
+# undef gl_signbitd
+#endif
+
+int
+gl_signbitd (double arg)
+{
+#if defined DBL_SIGNBIT_WORD && defined DBL_SIGNBIT_BIT
+ /* The use of a union to extract the bits of the representation of a
+ 'long double' is safe in practice, despite of the "aliasing rules" of
+ C99, because the GCC docs say
+ "Even with '-fstrict-aliasing', type-punning is allowed, provided the
+ memory is accessed through the union type."
+ and similarly for other compilers. */
+# define NWORDS \
+ ((sizeof (double) + sizeof (unsigned int) - 1) / sizeof (unsigned int))
+ union { double value; unsigned int word[NWORDS]; } m;
+ m.value = arg;
+ return (m.word[DBL_SIGNBIT_WORD] >> DBL_SIGNBIT_BIT) & 1;
+#elif HAVE_COPYSIGN_IN_LIBC
+ return copysign (1.0, arg) < 0;
+#else
+ /* This does not do the right thing for NaN, but this is irrelevant for
+ most use cases. */
+ if (isnand (arg))
+ return 0;
+ if (arg < 0.0)
+ return 1;
+ else if (arg == 0.0)
+ {
+ /* Distinguish 0.0 and -0.0. */
+ static double plus_zero = 0.0;
+ double arg_mem = arg;
+ return (memcmp (&plus_zero, &arg_mem, SIZEOF_DBL) != 0);
+ }
+ else
+ return 0;
+#endif
+}
diff --git a/lib/signbitf.c b/lib/signbitf.c
new file mode 100644
index 0000000..e185971
--- /dev/null
+++ b/lib/signbitf.c
@@ -0,0 +1,64 @@
+/* signbit() macro: Determine the sign bit of a floating-point number.
+ Copyright (C) 2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <math.h>
+
+#include <string.h>
+#include "isnanf-nolibm.h"
+#include "float+.h"
+
+#ifdef gl_signbitf_OPTIMIZED_MACRO
+# undef gl_signbitf
+#endif
+
+int
+gl_signbitf (float arg)
+{
+#if defined FLT_SIGNBIT_WORD && defined FLT_SIGNBIT_BIT
+ /* The use of a union to extract the bits of the representation of a
+ 'long double' is safe in practice, despite of the "aliasing rules" of
+ C99, because the GCC docs say
+ "Even with '-fstrict-aliasing', type-punning is allowed, provided the
+ memory is accessed through the union type."
+ and similarly for other compilers. */
+# define NWORDS \
+ ((sizeof (float) + sizeof (unsigned int) - 1) / sizeof (unsigned int))
+ union { float value; unsigned int word[NWORDS]; } m;
+ m.value = arg;
+ return (m.word[FLT_SIGNBIT_WORD] >> FLT_SIGNBIT_BIT) & 1;
+#elif HAVE_COPYSIGNF_IN_LIBC
+ return copysignf (1.0f, arg) < 0;
+#else
+ /* This does not do the right thing for NaN, but this is irrelevant for
+ most use cases. */
+ if (isnanf (arg))
+ return 0;
+ if (arg < 0.0f)
+ return 1;
+ else if (arg == 0.0f)
+ {
+ /* Distinguish 0.0f and -0.0f. */
+ static float plus_zero = 0.0f;
+ float arg_mem = arg;
+ return (memcmp (&plus_zero, &arg_mem, SIZEOF_FLT) != 0);
+ }
+ else
+ return 0;
+#endif
+}
diff --git a/lib/signbitl.c b/lib/signbitl.c
new file mode 100644
index 0000000..7dc0908
--- /dev/null
+++ b/lib/signbitl.c
@@ -0,0 +1,64 @@
+/* signbit() macro: Determine the sign bit of a floating-point number.
+ Copyright (C) 2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <math.h>
+
+#include <string.h>
+#include "isnanl-nolibm.h"
+#include "float+.h"
+
+#ifdef gl_signbitl_OPTIMIZED_MACRO
+# undef gl_signbitl
+#endif
+
+int
+gl_signbitl (long double arg)
+{
+#if defined LDBL_SIGNBIT_WORD && defined LDBL_SIGNBIT_BIT
+ /* The use of a union to extract the bits of the representation of a
+ 'long double' is safe in practice, despite of the "aliasing rules" of
+ C99, because the GCC docs say
+ "Even with '-fstrict-aliasing', type-punning is allowed, provided the
+ memory is accessed through the union type."
+ and similarly for other compilers. */
+# define NWORDS \
+ ((sizeof (long double) + sizeof (unsigned int) - 1) / sizeof (unsigned int))
+ union { long double value; unsigned int word[NWORDS]; } m;
+ m.value = arg;
+ return (m.word[LDBL_SIGNBIT_WORD] >> LDBL_SIGNBIT_BIT) & 1;
+#elif HAVE_COPYSIGNL_IN_LIBC
+ return copysignl (1.0L, arg) < 0;
+#else
+ /* This does not do the right thing for NaN, but this is irrelevant for
+ most use cases. */
+ if (isnanl (arg))
+ return 0;
+ if (arg < 0.0L)
+ return 1;
+ else if (arg == 0.0L)
+ {
+ /* Distinguish 0.0L and -0.0L. */
+ static long double plus_zero = 0.0L;
+ long double arg_mem = arg;
+ return (memcmp (&plus_zero, &arg_mem, SIZEOF_LDBL) != 0);
+ }
+ else
+ return 0;
+#endif
+}
diff --git a/lib/sigprocmask.c b/lib/sigprocmask.c
new file mode 100644
index 0000000..fcbf032
--- /dev/null
+++ b/lib/sigprocmask.c
@@ -0,0 +1,349 @@
+/* POSIX compatible signal blocking.
+ Copyright (C) 2006-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2006.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <signal.h>
+
+#include <errno.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+#if HAVE_MSVC_INVALID_PARAMETER_HANDLER
+# include "msvc-inval.h"
+#endif
+
+/* We assume that a platform without POSIX signal blocking functions
+ also does not have the POSIX sigaction() function, only the
+ signal() function. We also assume signal() has SysV semantics,
+ where any handler is uninstalled prior to being invoked. This is
+ true for native Windows platforms. */
+
+/* We use raw signal(), but also provide a wrapper rpl_signal() so
+ that applications can query or change a blocked signal. */
+#undef signal
+
+/* Provide invalid signal numbers as fallbacks if the uncatchable
+ signals are not defined. */
+#ifndef SIGKILL
+# define SIGKILL (-1)
+#endif
+#ifndef SIGSTOP
+# define SIGSTOP (-1)
+#endif
+
+/* On native Windows, as of 2008, the signal SIGABRT_COMPAT is an alias
+ for the signal SIGABRT. Only one signal handler is stored for both
+ SIGABRT and SIGABRT_COMPAT. SIGABRT_COMPAT is not a signal of its own. */
+#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+# undef SIGABRT_COMPAT
+# define SIGABRT_COMPAT 6
+#endif
+#ifdef SIGABRT_COMPAT
+# define SIGABRT_COMPAT_MASK (1U << SIGABRT_COMPAT)
+#else
+# define SIGABRT_COMPAT_MASK 0
+#endif
+
+typedef void (*handler_t) (int);
+
+#if HAVE_MSVC_INVALID_PARAMETER_HANDLER
+static handler_t
+signal_nothrow (int sig, handler_t handler)
+{
+ handler_t result;
+
+ TRY_MSVC_INVAL
+ {
+ result = signal (sig, handler);
+ }
+ CATCH_MSVC_INVAL
+ {
+ result = SIG_ERR;
+ errno = EINVAL;
+ }
+ DONE_MSVC_INVAL;
+
+ return result;
+}
+# define signal signal_nothrow
+#endif
+
+/* Handling of gnulib defined signals. */
+
+#if GNULIB_defined_SIGPIPE
+static handler_t SIGPIPE_handler = SIG_DFL;
+#endif
+
+#if GNULIB_defined_SIGPIPE
+static handler_t
+ext_signal (int sig, handler_t handler)
+{
+ switch (sig)
+ {
+ case SIGPIPE:
+ {
+ handler_t old_handler = SIGPIPE_handler;
+ SIGPIPE_handler = handler;
+ return old_handler;
+ }
+ default: /* System defined signal */
+ return signal (sig, handler);
+ }
+}
+# undef signal
+# define signal ext_signal
+#endif
+
+int
+sigismember (const sigset_t *set, int sig)
+{
+ if (sig >= 0 && sig < NSIG)
+ {
+ #ifdef SIGABRT_COMPAT
+ if (sig == SIGABRT_COMPAT)
+ sig = SIGABRT;
+ #endif
+
+ return (*set >> sig) & 1;
+ }
+ else
+ return 0;
+}
+
+int
+sigemptyset (sigset_t *set)
+{
+ *set = 0;
+ return 0;
+}
+
+int
+sigaddset (sigset_t *set, int sig)
+{
+ if (sig >= 0 && sig < NSIG)
+ {
+ #ifdef SIGABRT_COMPAT
+ if (sig == SIGABRT_COMPAT)
+ sig = SIGABRT;
+ #endif
+
+ *set |= 1U << sig;
+ return 0;
+ }
+ else
+ {
+ errno = EINVAL;
+ return -1;
+ }
+}
+
+int
+sigdelset (sigset_t *set, int sig)
+{
+ if (sig >= 0 && sig < NSIG)
+ {
+ #ifdef SIGABRT_COMPAT
+ if (sig == SIGABRT_COMPAT)
+ sig = SIGABRT;
+ #endif
+
+ *set &= ~(1U << sig);
+ return 0;
+ }
+ else
+ {
+ errno = EINVAL;
+ return -1;
+ }
+}
+
+
+int
+sigfillset (sigset_t *set)
+{
+ *set = ((2U << (NSIG - 1)) - 1) & ~ SIGABRT_COMPAT_MASK;
+ return 0;
+}
+
+/* Set of currently blocked signals. */
+static volatile sigset_t blocked_set /* = 0 */;
+
+/* Set of currently blocked and pending signals. */
+static volatile sig_atomic_t pending_array[NSIG] /* = { 0 } */;
+
+/* Signal handler that is installed for blocked signals. */
+static void
+blocked_handler (int sig)
+{
+ /* Reinstall the handler, in case the signal occurs multiple times
+ while blocked. There is an inherent race where an asynchronous
+ signal in between when the kernel uninstalled the handler and
+ when we reinstall it will trigger the default handler; oh
+ well. */
+ signal (sig, blocked_handler);
+ if (sig >= 0 && sig < NSIG)
+ pending_array[sig] = 1;
+}
+
+int
+sigpending (sigset_t *set)
+{
+ sigset_t pending = 0;
+ int sig;
+
+ for (sig = 0; sig < NSIG; sig++)
+ if (pending_array[sig])
+ pending |= 1U << sig;
+ *set = pending;
+ return 0;
+}
+
+/* The previous signal handlers.
+ Only the array elements corresponding to blocked signals are relevant. */
+static volatile handler_t old_handlers[NSIG];
+
+int
+sigprocmask (int operation, const sigset_t *set, sigset_t *old_set)
+{
+ if (old_set != NULL)
+ *old_set = blocked_set;
+
+ if (set != NULL)
+ {
+ sigset_t new_blocked_set;
+ sigset_t to_unblock;
+ sigset_t to_block;
+
+ switch (operation)
+ {
+ case SIG_BLOCK:
+ new_blocked_set = blocked_set | *set;
+ break;
+ case SIG_SETMASK:
+ new_blocked_set = *set;
+ break;
+ case SIG_UNBLOCK:
+ new_blocked_set = blocked_set & ~*set;
+ break;
+ default:
+ errno = EINVAL;
+ return -1;
+ }
+ to_unblock = blocked_set & ~new_blocked_set;
+ to_block = new_blocked_set & ~blocked_set;
+
+ if (to_block != 0)
+ {
+ int sig;
+
+ for (sig = 0; sig < NSIG; sig++)
+ if ((to_block >> sig) & 1)
+ {
+ pending_array[sig] = 0;
+ if ((old_handlers[sig] = signal (sig, blocked_handler)) != SIG_ERR)
+ blocked_set |= 1U << sig;
+ }
+ }
+
+ if (to_unblock != 0)
+ {
+ sig_atomic_t received[NSIG];
+ int sig;
+
+ for (sig = 0; sig < NSIG; sig++)
+ if ((to_unblock >> sig) & 1)
+ {
+ if (signal (sig, old_handlers[sig]) != blocked_handler)
+ /* The application changed a signal handler while the signal
+ was blocked, bypassing our rpl_signal replacement.
+ We don't support this. */
+ abort ();
+ received[sig] = pending_array[sig];
+ blocked_set &= ~(1U << sig);
+ pending_array[sig] = 0;
+ }
+ else
+ received[sig] = 0;
+
+ for (sig = 0; sig < NSIG; sig++)
+ if (received[sig])
+ raise (sig);
+ }
+ }
+ return 0;
+}
+
+/* Install the handler FUNC for signal SIG, and return the previous
+ handler. */
+handler_t
+rpl_signal (int sig, handler_t handler)
+{
+ /* We must provide a wrapper, so that a user can query what handler
+ they installed even if that signal is currently blocked. */
+ if (sig >= 0 && sig < NSIG && sig != SIGKILL && sig != SIGSTOP
+ && handler != SIG_ERR)
+ {
+ #ifdef SIGABRT_COMPAT
+ if (sig == SIGABRT_COMPAT)
+ sig = SIGABRT;
+ #endif
+
+ if (blocked_set & (1U << sig))
+ {
+ /* POSIX states that sigprocmask and signal are both
+ async-signal-safe. This is not true of our
+ implementation - there is a slight data race where an
+ asynchronous interrupt on signal A can occur after we
+ install blocked_handler but before we have updated
+ old_handlers for signal B, such that handler A can see
+ stale information if it calls signal(B). Oh well -
+ signal handlers really shouldn't try to manipulate the
+ installed handlers of unrelated signals. */
+ handler_t result = old_handlers[sig];
+ old_handlers[sig] = handler;
+ return result;
+ }
+ else
+ return signal (sig, handler);
+ }
+ else
+ {
+ errno = EINVAL;
+ return SIG_ERR;
+ }
+}
+
+#if GNULIB_defined_SIGPIPE
+/* Raise the signal SIGPIPE. */
+int
+_gl_raise_SIGPIPE (void)
+{
+ if (blocked_set & (1U << SIGPIPE))
+ pending_array[SIGPIPE] = 1;
+ else
+ {
+ handler_t handler = SIGPIPE_handler;
+ if (handler == SIG_DFL)
+ exit (128 + SIGPIPE);
+ else if (handler != SIG_IGN)
+ (*handler) (SIGPIPE);
+ }
+ return 0;
+}
+#endif
diff --git a/lib/size_max.h b/lib/size_max.h
new file mode 100644
index 0000000..2f2792c
--- /dev/null
+++ b/lib/size_max.h
@@ -0,0 +1,30 @@
+/* size_max.h -- declare SIZE_MAX through system headers
+ Copyright (C) 2005-2006, 2009-2016 Free Software Foundation, Inc.
+ Written by Simon Josefsson.
+
+ 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, 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef GNULIB_SIZE_MAX_H
+#define GNULIB_SIZE_MAX_H
+
+/* Get SIZE_MAX declaration on systems like Solaris 7/8/9. */
+# include <limits.h>
+/* Get SIZE_MAX declaration on systems like glibc 2. */
+# if HAVE_STDINT_H
+# include <stdint.h>
+# endif
+/* On systems where these include files don't define it, SIZE_MAX is defined
+ in config.h. */
+
+#endif /* GNULIB_SIZE_MAX_H */
diff --git a/lib/smack.h b/lib/smack.h
new file mode 100644
index 0000000..966191c
--- /dev/null
+++ b/lib/smack.h
@@ -0,0 +1,46 @@
+/* Include and determine availability of smack routines
+ Copyright (C) 2013-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Here we replace or wrap the most common smack functions used by coreutils.
+ Others will need to be protected by HAVE_SMACK. */
+
+#include <config.h>
+
+#ifdef HAVE_SMACK
+# include <sys/smack.h>
+#else
+static inline ssize_t
+smack_new_label_from_self (char **label)
+{
+ return -1;
+}
+
+static inline int
+smack_set_label_for_self (const char *label)
+{
+ return -1;
+}
+#endif
+
+static inline bool
+is_smack_enabled (void)
+{
+#ifdef HAVE_SMACK
+ return smack_smackfs_path () != NULL;
+#else
+ return false;
+#endif
+}
diff --git a/lib/snprintf.c b/lib/snprintf.c
index 7314c83..7cd89af 100644
--- a/lib/snprintf.c
+++ b/lib/snprintf.c
@@ -1,10 +1,10 @@
/* Formatted output to strings.
- Copyright (C) 2004, 2006-2007 Free Software Foundation, Inc.
+ Copyright (C) 2004, 2006-2016 Free Software Foundation, Inc.
Written by Simon Josefsson and Paul Eggert.
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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ with this program; if not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
@@ -29,11 +28,6 @@
#include "vasnprintf.h"
-/* Some systems, like OSF/1 4.0 and Woe32, don't have EOVERFLOW. */
-#ifndef EOVERFLOW
-# define EOVERFLOW E2BIG
-#endif
-
/* Print formatted output to string STR. Similar to sprintf, but
additional length SIZE limit how much is written into STR. Returns
string length of formatted string (which may be larger than SIZE).
@@ -58,11 +52,11 @@ snprintf (char *str, size_t size, const char *format, ...)
if (output != str)
{
if (size)
- {
- size_t pruned_len = (len < size ? len : size - 1);
- memcpy (str, output, pruned_len);
- str[pruned_len] = '\0';
- }
+ {
+ size_t pruned_len = (len < size ? len : size - 1);
+ memcpy (str, output, pruned_len);
+ str[pruned_len] = '\0';
+ }
free (output);
}
diff --git a/lib/socket_.h b/lib/socket_.h
deleted file mode 100644
index 623c98c..0000000
--- a/lib/socket_.h
+++ /dev/null
@@ -1,85 +0,0 @@
-/* Provide a sys/socket header file for systems lacking it (read: MinGW).
- Copyright (C) 2005, 2006, 2007 Free Software Foundation, Inc.
- Written by Simon Josefsson.
-
- 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-#ifndef _GL_SYS_SOCKET_H
-#define _GL_SYS_SOCKET_H
-
-/* This file is supposed to be used on platforms that lack <sys/socket.h>
- and on platforms where <sys/socket.h> cannot be included standalone.
- It is intended to provide definitions and prototypes needed by an
- application. */
-
-#if @HAVE_SYS_SOCKET_H@
-
-/* On many platforms, <sys/socket.h> assumes prior inclusion of
- <sys/types.h>. */
-
-# include <sys/types.h>
-# include @ABSOLUTE_SYS_SOCKET_H@
-
-#else
-
-/* A platform that lacks <sys/socket.h>.
-
- Currently only MinGW is supported. See the gnulib manual regarding
- Windows sockets. MinGW has the header files winsock2.h and
- ws2tcpip.h that declare the sys/socket.h definitions we need. Note
- that you can influence which definitions you get by setting the
- WINVER symbol before including these two files. For example,
- getaddrinfo is only available if _WIN32_WINNT >= 0x0501 (that
- symbol is set indiriectly through WINVER). You can set this by
- adding AC_DEFINE(WINVER, 0x0501) to configure.ac. Note that your
- code may not run on older Windows releases then. My Windows 2000
- box was not able to run the code, for example. The situation is
- slightly confusing because:
- http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winsock/winsock/getaddrinfo_2.asp
- suggests that getaddrinfo should be available on all Windows
- releases. */
-
-
-# if @HAVE_WINSOCK2_H@
-# include <winsock2.h>
-# endif
-# if @HAVE_WS2TCPIP_H@
-# include <ws2tcpip.h>
-# endif
-
-/* For shutdown(). */
-# if !defined SHUT_RD && defined SD_RECEIVE
-# define SHUT_RD SD_RECEIVE
-# endif
-# if !defined SHUT_WR && defined SD_SEND
-# define SHUT_WR SD_SEND
-# endif
-# if !defined SHUT_RDWR && defined SD_BOTH
-# define SHUT_RDWR SD_BOTH
-# endif
-
-# if defined _WIN32 || defined __WIN32__
-# define ENOTSOCK WSAENOTSOCK
-# define EADDRINUSE WSAEADDRINUSE
-# define ENETRESET WSAENETRESET
-# define ECONNABORTED WSAECONNABORTED
-# define ECONNRESET WSAECONNRESET
-# define ENOTCONN WSAENOTCONN
-# define ESHUTDOWN WSAESHUTDOWN
-# endif
-
-#endif /* HAVE_SYS_SOCKET_H */
-
-#endif /* _GL_SYS_SOCKET_H */
diff --git a/lib/sockets.c b/lib/sockets.c
new file mode 100644
index 0000000..abfab02
--- /dev/null
+++ b/lib/sockets.c
@@ -0,0 +1,157 @@
+/* sockets.c --- wrappers for Windows socket functions
+
+ Copyright (C) 2008-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Simon Josefsson */
+
+#include <config.h>
+
+/* Specification. */
+#include "sockets.h"
+
+#if WINDOWS_SOCKETS
+
+/* This includes winsock2.h on MinGW. */
+# include <sys/socket.h>
+
+# include "fd-hook.h"
+# include "msvc-nothrow.h"
+
+/* Get set_winsock_errno, FD_TO_SOCKET etc. */
+# include "w32sock.h"
+
+static int
+close_fd_maybe_socket (const struct fd_hook *remaining_list,
+ gl_close_fn primary,
+ int fd)
+{
+ /* Note about multithread-safety: There is a race condition where, between
+ our calls to closesocket() and the primary close(), some other thread
+ could make system calls that allocate precisely the same HANDLE value
+ as sock; then the primary close() would call CloseHandle() on it. */
+ SOCKET sock;
+ WSANETWORKEVENTS ev;
+
+ /* Test whether fd refers to a socket. */
+ sock = FD_TO_SOCKET (fd);
+ ev.lNetworkEvents = 0xDEADBEEF;
+ WSAEnumNetworkEvents (sock, NULL, &ev);
+ if (ev.lNetworkEvents != 0xDEADBEEF)
+ {
+ /* fd refers to a socket. */
+ /* FIXME: other applications, like squid, use an undocumented
+ _free_osfhnd free function. But this is not enough: The 'osfile'
+ flags for fd also needs to be cleared, but it is hard to access it.
+ Instead, here we just close twice the file descriptor. */
+ if (closesocket (sock))
+ {
+ set_winsock_errno ();
+ return -1;
+ }
+ else
+ {
+ /* This call frees the file descriptor and does a
+ CloseHandle ((HANDLE) _get_osfhandle (fd)), which fails. */
+ _close (fd);
+ return 0;
+ }
+ }
+ else
+ /* Some other type of file descriptor. */
+ return execute_close_hooks (remaining_list, primary, fd);
+}
+
+static int
+ioctl_fd_maybe_socket (const struct fd_hook *remaining_list,
+ gl_ioctl_fn primary,
+ int fd, int request, void *arg)
+{
+ SOCKET sock;
+ WSANETWORKEVENTS ev;
+
+ /* Test whether fd refers to a socket. */
+ sock = FD_TO_SOCKET (fd);
+ ev.lNetworkEvents = 0xDEADBEEF;
+ WSAEnumNetworkEvents (sock, NULL, &ev);
+ if (ev.lNetworkEvents != 0xDEADBEEF)
+ {
+ /* fd refers to a socket. */
+ if (ioctlsocket (sock, request, arg) < 0)
+ {
+ set_winsock_errno ();
+ return -1;
+ }
+ else
+ return 0;
+ }
+ else
+ /* Some other type of file descriptor. */
+ return execute_ioctl_hooks (remaining_list, primary, fd, request, arg);
+}
+
+static struct fd_hook fd_sockets_hook;
+
+static int initialized_sockets_version /* = 0 */;
+
+#endif /* WINDOWS_SOCKETS */
+
+int
+gl_sockets_startup (int version _GL_UNUSED)
+{
+#if WINDOWS_SOCKETS
+ if (version > initialized_sockets_version)
+ {
+ WSADATA data;
+ int err;
+
+ err = WSAStartup (version, &data);
+ if (err != 0)
+ return 1;
+
+ if (data.wVersion != version)
+ {
+ WSACleanup ();
+ return 2;
+ }
+
+ if (initialized_sockets_version == 0)
+ register_fd_hook (close_fd_maybe_socket, ioctl_fd_maybe_socket,
+ &fd_sockets_hook);
+
+ initialized_sockets_version = version;
+ }
+#endif
+
+ return 0;
+}
+
+int
+gl_sockets_cleanup (void)
+{
+#if WINDOWS_SOCKETS
+ int err;
+
+ initialized_sockets_version = 0;
+
+ unregister_fd_hook (&fd_sockets_hook);
+
+ err = WSACleanup ();
+ if (err != 0)
+ return 1;
+#endif
+
+ return 0;
+}
diff --git a/lib/sockets.h b/lib/sockets.h
new file mode 100644
index 0000000..01a68d0
--- /dev/null
+++ b/lib/sockets.h
@@ -0,0 +1,62 @@
+/* sockets.h - wrappers for Windows socket functions
+
+ Copyright (C) 2008-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Simon Josefsson */
+
+#ifndef SOCKETS_H
+# define SOCKETS_H 1
+
+#define SOCKETS_1_0 0x0001
+#define SOCKETS_1_1 0x0101
+#define SOCKETS_2_0 0x0002
+#define SOCKETS_2_1 0x0102
+#define SOCKETS_2_2 0x0202
+
+int gl_sockets_startup (int version)
+#if !WINDOWS_SOCKETS
+ _GL_ATTRIBUTE_CONST
+#endif
+ ;
+
+int gl_sockets_cleanup (void)
+#if !WINDOWS_SOCKETS
+ _GL_ATTRIBUTE_CONST
+#endif
+ ;
+
+/* This function is useful it you create a socket using gnulib's
+ Winsock wrappers but needs to pass on the socket handle to some
+ other library that only accepts sockets. */
+#if WINDOWS_SOCKETS
+
+#include <sys/socket.h>
+
+#include "msvc-nothrow.h"
+
+static inline SOCKET
+gl_fd_to_handle (int fd)
+{
+ return _get_osfhandle (fd);
+}
+
+#else
+
+#define gl_fd_to_handle(x) (x)
+
+#endif /* WINDOWS_SOCKETS */
+
+#endif /* SOCKETS_H */
diff --git a/lib/stat-size.h b/lib/stat-size.h
new file mode 100644
index 0000000..151f1c9
--- /dev/null
+++ b/lib/stat-size.h
@@ -0,0 +1,107 @@
+/* macros useful in interpreting size-related values in struct stat.
+ Copyright (C) 1989, 1991-2016 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 <http://www.gnu.org/licenses/>. */
+/*
+ Macros defined by this file (s is an rvalue of type struct stat):
+
+ DEV_BSIZE: The device blocksize. But use ST_NBLOCKSIZE instead.
+ ST_BLKSIZE(s): Preferred (in the sense of best performance) I/O blocksize
+ for the file, in bytes.
+ ST_NBLOCKS(s): Number of blocks in the file, including indirect blocks.
+ ST_NBLOCKSIZE: Size of blocks used when calculating ST_NBLOCKS.
+ */
+#ifndef STAT_SIZE_H
+#define STAT_SIZE_H
+
+/* sys/param.h may define DEV_BSIZE */
+#if HAVE_SYS_PARAM_H
+# include <sys/param.h>
+#endif
+
+
+/* Get or fake the disk device blocksize.
+ Usually defined by sys/param.h (if at all). */
+#if !defined DEV_BSIZE && defined BSIZE
+# define DEV_BSIZE BSIZE
+#endif
+#if !defined DEV_BSIZE && defined BBSIZE /* SGI sys/param.h */
+# define DEV_BSIZE BBSIZE
+#endif
+#ifndef DEV_BSIZE
+# define DEV_BSIZE 4096
+#endif
+
+
+
+/* Extract or fake data from a 'struct stat'.
+ ST_BLKSIZE: Preferred I/O blocksize for the file, in bytes.
+ ST_NBLOCKS: Number of blocks in the file, including indirect blocks.
+ ST_NBLOCKSIZE: Size of blocks used when calculating ST_NBLOCKS. */
+#ifndef HAVE_STRUCT_STAT_ST_BLOCKS
+# define ST_BLKSIZE(statbuf) DEV_BSIZE
+ /* coreutils' fileblocks.c also uses BSIZE. */
+# if defined _POSIX_SOURCE || !defined BSIZE
+# define ST_NBLOCKS(statbuf) \
+ ((statbuf).st_size / ST_NBLOCKSIZE + ((statbuf).st_size % ST_NBLOCKSIZE != 0))
+# else
+ /* This definition calls st_blocks, which is in the fileblocks module. */
+# define ST_NBLOCKS(statbuf) \
+ (S_ISREG ((statbuf).st_mode) || S_ISDIR ((statbuf).st_mode) ? \
+ st_blocks ((statbuf).st_size) : 0)
+# endif
+#else
+/* Some systems, like Sequents, return st_blksize of 0 on pipes.
+ Also, when running 'rsh hpux11-system cat any-file', cat would
+ determine that the output stream had an st_blksize of 2147421096.
+ Conversely st_blksize can be 2 GiB (or maybe even larger) with XFS
+ on 64-bit hosts. Somewhat arbitrarily, limit the "optimal" block
+ size to SIZE_MAX / 8 + 1. (Dividing SIZE_MAX by only 4 wouldn't
+ suffice, since "cat" sometimes multiplies the result by 4.) If
+ anyone knows of a system for which this limit is too small, please
+ report it as a bug in this code. */
+# define ST_BLKSIZE(statbuf) ((0 < (statbuf).st_blksize \
+ && (statbuf).st_blksize <= ((size_t)-1) / 8 + 1) \
+ ? (statbuf).st_blksize : DEV_BSIZE)
+# if defined hpux || defined __hpux__ || defined __hpux
+ /* HP-UX counts st_blocks in 1024-byte units.
+ This loses when mixing HP-UX and BSD file systems with NFS. */
+# define ST_NBLOCKSIZE 1024
+# else /* !hpux */
+# if defined _AIX && defined _I386
+ /* AIX PS/2 counts st_blocks in 4K units. */
+# define ST_NBLOCKSIZE (4 * 1024)
+# else
+# if defined _CRAY
+# define ST_NBLOCKS(statbuf) \
+ (S_ISREG ((statbuf).st_mode) || S_ISDIR ((statbuf).st_mode) \
+ ? (statbuf).st_blocks * ST_BLKSIZE (statbuf) / ST_NBLOCKSIZE : 0)
+# endif
+# endif
+# endif
+#endif
+
+#ifndef ST_NBLOCKS
+# define ST_NBLOCKS(statbuf) ((statbuf).st_blocks)
+#endif
+
+#ifndef ST_NBLOCKSIZE
+# ifdef S_BLKSIZE
+# define ST_NBLOCKSIZE S_BLKSIZE
+# else
+# define ST_NBLOCKSIZE 512
+# endif
+#endif
+
+#endif /* STAT_SIZE_H */
diff --git a/lib/stat-time.c b/lib/stat-time.c
new file mode 100644
index 0000000..81b83dd
--- /dev/null
+++ b/lib/stat-time.c
@@ -0,0 +1,3 @@
+#include <config.h>
+#define _GL_STAT_TIME_INLINE _GL_EXTERN_INLINE
+#include "stat-time.h"
diff --git a/lib/stat-time.h b/lib/stat-time.h
index 5fd18c1..f5c4cd2 100644
--- a/lib/stat-time.h
+++ b/lib/stat-time.h
@@ -1,11 +1,11 @@
/* stat-related time functions.
- Copyright (C) 2005, 2007 Free Software Foundation, Inc.
+ Copyright (C) 2005, 2007, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,21 +13,30 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
#ifndef STAT_TIME_H
#define STAT_TIME_H 1
+#include <sys/stat.h>
#include <time.h>
+#ifndef _GL_INLINE_HEADER_BEGIN
+ #error "Please include config.h first."
+#endif
+_GL_INLINE_HEADER_BEGIN
+#ifndef _GL_STAT_TIME_INLINE
+# define _GL_STAT_TIME_INLINE _GL_INLINE
+#endif
+
/* STAT_TIMESPEC (ST, ST_XTIM) is the ST_XTIM member for *ST of type
struct timespec, if available. If not, then STAT_TIMESPEC_NS (ST,
ST_XTIM) is the nanosecond component of the ST_XTIM member for *ST,
- if available. ST_XTIM can be st_atim, st_ctim, or st_mtim for
- access, status change, or data modification time, respectively.
+ if available. ST_XTIM can be st_atim, st_ctim, st_mtim, or st_birthtim
+ for access, status change, data modification, or birth (creation)
+ time respectively.
These macros are private to stat-time.h. */
#if defined HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC
@@ -45,52 +54,61 @@
#endif
/* Return the nanosecond component of *ST's access time. */
-static inline long int
+_GL_STAT_TIME_INLINE long int _GL_ATTRIBUTE_PURE
get_stat_atime_ns (struct stat const *st)
{
# if defined STAT_TIMESPEC
return STAT_TIMESPEC (st, st_atim).tv_nsec;
# elif defined STAT_TIMESPEC_NS
return STAT_TIMESPEC_NS (st, st_atim);
-# elif defined HAVE_STRUCT_STAT_ST_SPARE1
- return st->st_spare1 * 1000;
# else
return 0;
# endif
}
/* Return the nanosecond component of *ST's status change time. */
-static inline long int
+_GL_STAT_TIME_INLINE long int _GL_ATTRIBUTE_PURE
get_stat_ctime_ns (struct stat const *st)
{
# if defined STAT_TIMESPEC
return STAT_TIMESPEC (st, st_ctim).tv_nsec;
# elif defined STAT_TIMESPEC_NS
return STAT_TIMESPEC_NS (st, st_ctim);
-# elif defined HAVE_STRUCT_STAT_ST_SPARE1
- return st->st_spare3 * 1000;
# else
return 0;
# endif
}
/* Return the nanosecond component of *ST's data modification time. */
-static inline long int
+_GL_STAT_TIME_INLINE long int _GL_ATTRIBUTE_PURE
get_stat_mtime_ns (struct stat const *st)
{
# if defined STAT_TIMESPEC
return STAT_TIMESPEC (st, st_mtim).tv_nsec;
# elif defined STAT_TIMESPEC_NS
return STAT_TIMESPEC_NS (st, st_mtim);
-# elif defined HAVE_STRUCT_STAT_ST_SPARE1
- return st->st_spare2 * 1000;
# else
return 0;
# endif
}
+/* Return the nanosecond component of *ST's birth time. */
+_GL_STAT_TIME_INLINE long int _GL_ATTRIBUTE_PURE
+get_stat_birthtime_ns (struct stat const *st)
+{
+# if defined HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC_TV_NSEC
+ return STAT_TIMESPEC (st, st_birthtim).tv_nsec;
+# elif defined HAVE_STRUCT_STAT_ST_BIRTHTIMENSEC
+ return STAT_TIMESPEC_NS (st, st_birthtim);
+# else
+ /* Avoid a "parameter unused" warning. */
+ (void) st;
+ return 0;
+# endif
+}
+
/* Return *ST's access time. */
-static inline struct timespec
+_GL_STAT_TIME_INLINE struct timespec _GL_ATTRIBUTE_PURE
get_stat_atime (struct stat const *st)
{
#ifdef STAT_TIMESPEC
@@ -104,7 +122,7 @@ get_stat_atime (struct stat const *st)
}
/* Return *ST's status change time. */
-static inline struct timespec
+_GL_STAT_TIME_INLINE struct timespec _GL_ATTRIBUTE_PURE
get_stat_ctime (struct stat const *st)
{
#ifdef STAT_TIMESPEC
@@ -118,7 +136,7 @@ get_stat_ctime (struct stat const *st)
}
/* Return *ST's data modification time. */
-static inline struct timespec
+_GL_STAT_TIME_INLINE struct timespec _GL_ATTRIBUTE_PURE
get_stat_mtime (struct stat const *st)
{
#ifdef STAT_TIMESPEC
@@ -131,4 +149,51 @@ get_stat_mtime (struct stat const *st)
#endif
}
+/* Return *ST's birth time, if available; otherwise return a value
+ with tv_sec and tv_nsec both equal to -1. */
+_GL_STAT_TIME_INLINE struct timespec _GL_ATTRIBUTE_PURE
+get_stat_birthtime (struct stat const *st)
+{
+ struct timespec t;
+
+#if (defined HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC_TV_NSEC \
+ || defined HAVE_STRUCT_STAT_ST_BIRTHTIM_TV_NSEC)
+ t = STAT_TIMESPEC (st, st_birthtim);
+#elif defined HAVE_STRUCT_STAT_ST_BIRTHTIMENSEC
+ t.tv_sec = st->st_birthtime;
+ t.tv_nsec = st->st_birthtimensec;
+#elif (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+ /* Native Windows platforms (but not Cygwin) put the "file creation
+ time" in st_ctime (!). See
+ <http://msdn2.microsoft.com/de-de/library/14h5k7ff(VS.80).aspx>. */
+ t.tv_sec = st->st_ctime;
+ t.tv_nsec = 0;
+#else
+ /* Birth time is not supported. */
+ t.tv_sec = -1;
+ t.tv_nsec = -1;
+ /* Avoid a "parameter unused" warning. */
+ (void) st;
+#endif
+
+#if (defined HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC_TV_NSEC \
+ || defined HAVE_STRUCT_STAT_ST_BIRTHTIM_TV_NSEC \
+ || defined HAVE_STRUCT_STAT_ST_BIRTHTIMENSEC)
+ /* FreeBSD and NetBSD sometimes signal the absence of knowledge by
+ using zero. Attempt to work around this problem. Alas, this can
+ report failure even for valid time stamps. Also, NetBSD
+ sometimes returns junk in the birth time fields; work around this
+ bug if it is detected. */
+ if (! (t.tv_sec && 0 <= t.tv_nsec && t.tv_nsec < 1000000000))
+ {
+ t.tv_sec = -1;
+ t.tv_nsec = -1;
+ }
+#endif
+
+ return t;
+}
+
+_GL_INLINE_HEADER_END
+
#endif
diff --git a/lib/stat.c b/lib/stat.c
new file mode 100644
index 0000000..62e9e0b
--- /dev/null
+++ b/lib/stat.c
@@ -0,0 +1,138 @@
+/* Work around platform bugs in stat.
+ Copyright (C) 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* written by Eric Blake */
+
+/* If the user's config.h happens to include <sys/stat.h>, let it include only
+ the system's <sys/stat.h> here, so that orig_stat doesn't recurse to
+ rpl_stat. */
+#define __need_system_sys_stat_h
+#include <config.h>
+
+/* Get the original definition of stat. It might be defined as a macro. */
+#include <sys/types.h>
+#include <sys/stat.h>
+#undef __need_system_sys_stat_h
+
+#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+# if _GL_WINDOWS_64_BIT_ST_SIZE
+# undef stat /* avoid warning on mingw64 with _FILE_OFFSET_BITS=64 */
+# define stat _stati64
+# define REPLACE_FUNC_STAT_DIR 1
+# undef REPLACE_FUNC_STAT_FILE
+# elif REPLACE_FUNC_STAT_FILE
+/* mingw64 has a broken stat() function, based on _stat(), in libmingwex.a.
+ Bypass it. */
+# define stat _stat
+# define REPLACE_FUNC_STAT_DIR 1
+# undef REPLACE_FUNC_STAT_FILE
+# endif
+#endif
+
+static int
+orig_stat (const char *filename, struct stat *buf)
+{
+ return stat (filename, buf);
+}
+
+/* Specification. */
+/* Write "sys/stat.h" here, not <sys/stat.h>, otherwise OSF/1 5.1 DTK cc
+ eliminates this include because of the preliminary #include <sys/stat.h>
+ above. */
+#include "sys/stat.h"
+
+#include <errno.h>
+#include <limits.h>
+#include <stdbool.h>
+#include <string.h>
+#include "dosname.h"
+#include "verify.h"
+
+#if REPLACE_FUNC_STAT_DIR
+# include "pathmax.h"
+ /* The only known systems where REPLACE_FUNC_STAT_DIR is needed also
+ have a constant PATH_MAX. */
+# ifndef PATH_MAX
+# error "Please port this replacement to your platform"
+# endif
+#endif
+
+/* Store information about NAME into ST. Work around bugs with
+ trailing slashes. Mingw has other bugs (such as st_ino always
+ being 0 on success) which this wrapper does not work around. But
+ at least this implementation provides the ability to emulate fchdir
+ correctly. */
+
+int
+rpl_stat (char const *name, struct stat *st)
+{
+ int result = orig_stat (name, st);
+#if REPLACE_FUNC_STAT_FILE
+ /* Solaris 9 mistakenly succeeds when given a non-directory with a
+ trailing slash. */
+ if (result == 0 && !S_ISDIR (st->st_mode))
+ {
+ size_t len = strlen (name);
+ if (ISSLASH (name[len - 1]))
+ {
+ errno = ENOTDIR;
+ return -1;
+ }
+ }
+#endif /* REPLACE_FUNC_STAT_FILE */
+#if REPLACE_FUNC_STAT_DIR
+
+ if (result == -1 && errno == ENOENT)
+ {
+ /* Due to mingw's oddities, there are some directories (like
+ c:\) where stat() only succeeds with a trailing slash, and
+ other directories (like c:\windows) where stat() only
+ succeeds without a trailing slash. But we want the two to be
+ synonymous, since chdir() manages either style. Likewise, Mingw also
+ reports ENOENT for names longer than PATH_MAX, when we want
+ ENAMETOOLONG, and for stat("file/"), when we want ENOTDIR.
+ Fortunately, mingw PATH_MAX is small enough for stack
+ allocation. */
+ char fixed_name[PATH_MAX + 1] = {0};
+ size_t len = strlen (name);
+ bool check_dir = false;
+ verify (PATH_MAX <= 4096);
+ if (PATH_MAX <= len)
+ errno = ENAMETOOLONG;
+ else if (len)
+ {
+ strcpy (fixed_name, name);
+ if (ISSLASH (fixed_name[len - 1]))
+ {
+ check_dir = true;
+ while (len && ISSLASH (fixed_name[len - 1]))
+ fixed_name[--len] = '\0';
+ if (!len)
+ fixed_name[0] = '/';
+ }
+ else
+ fixed_name[len++] = '/';
+ result = orig_stat (fixed_name, st);
+ if (result == 0 && check_dir && !S_ISDIR (st->st_mode))
+ {
+ result = -1;
+ errno = ENOTDIR;
+ }
+ }
+ }
+#endif /* REPLACE_FUNC_STAT_DIR */
+ return result;
+}
diff --git a/lib/stat_.h b/lib/stat_.h
deleted file mode 100644
index cbf5ac0..0000000
--- a/lib/stat_.h
+++ /dev/null
@@ -1,275 +0,0 @@
-/* Provide a more complete sys/stat header file.
- Copyright (C) 2006 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-/* Written by Eric Blake, Paul Eggert, and Jim Meyering. */
-
-#ifndef _gl_SYS_STAT_H
-#define _gl_SYS_STAT_H
-
-/* This file is supposed to be used on platforms where <sys/stat.h> is
- incomplete. It is intended to provide definitions and prototypes
- needed by an application. Start with what the system provides. */
-#include @ABSOLUTE_SYS_STAT_H@
-
-#ifndef S_IFMT
-# define S_IFMT 0170000
-#endif
-
-#if STAT_MACROS_BROKEN
-# undef S_ISBLK
-# undef S_ISCHR
-# undef S_ISDIR
-# undef S_ISFIFO
-# undef S_ISLNK
-# undef S_ISNAM
-# undef S_ISMPB
-# undef S_ISMPC
-# undef S_ISNWK
-# undef S_ISREG
-# undef S_ISSOCK
-#endif
-
-#ifndef S_ISBLK
-# ifdef S_IFBLK
-# define S_ISBLK(m) (((m) & S_IFMT) == S_IFBLK)
-# else
-# define S_ISBLK(m) 0
-# endif
-#endif
-
-#ifndef S_ISCHR
-# ifdef S_IFCHR
-# define S_ISCHR(m) (((m) & S_IFMT) == S_IFCHR)
-# else
-# define S_ISCHR(m) 0
-# endif
-#endif
-
-#ifndef S_ISDIR
-# ifdef S_IFDIR
-# define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
-# else
-# define S_ISDIR(m) 0
-# endif
-#endif
-
-#ifndef S_ISDOOR /* Solaris 2.5 and up */
-# define S_ISDOOR(m) 0
-#endif
-
-#ifndef S_ISFIFO
-# ifdef S_IFIFO
-# define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO)
-# else
-# define S_ISFIFO(m) 0
-# endif
-#endif
-
-#ifndef S_ISLNK
-# ifdef S_IFLNK
-# define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
-# else
-# define S_ISLNK(m) 0
-# endif
-#endif
-
-#ifndef S_ISMPB /* V7 */
-# ifdef S_IFMPB
-# define S_ISMPB(m) (((m) & S_IFMT) == S_IFMPB)
-# define S_ISMPC(m) (((m) & S_IFMT) == S_IFMPC)
-# else
-# define S_ISMPB(m) 0
-# define S_ISMPC(m) 0
-# endif
-#endif
-
-#ifndef S_ISNAM /* Xenix */
-# ifdef S_IFNAM
-# define S_ISNAM(m) (((m) & S_IFMT) == S_IFNAM)
-# else
-# define S_ISNAM(m) 0
-# endif
-#endif
-
-#ifndef S_ISNWK /* HP/UX */
-# ifdef S_IFNWK
-# define S_ISNWK(m) (((m) & S_IFMT) == S_IFNWK)
-# else
-# define S_ISNWK(m) 0
-# endif
-#endif
-
-#ifndef S_ISPORT /* Solaris 10 and up */
-# define S_ISPORT(m) 0
-#endif
-
-#ifndef S_ISREG
-# ifdef S_IFREG
-# define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
-# else
-# define S_ISREG(m) 0
-# endif
-#endif
-
-#ifndef S_ISSOCK
-# ifdef S_IFSOCK
-# define S_ISSOCK(m) (((m) & S_IFMT) == S_IFSOCK)
-# else
-# define S_ISSOCK(m) 0
-# endif
-#endif
-
-
-#ifndef S_TYPEISMQ
-# define S_TYPEISMQ(p) 0
-#endif
-
-#ifndef S_TYPEISTMO
-# define S_TYPEISTMO(p) 0
-#endif
-
-
-#ifndef S_TYPEISSEM
-# ifdef S_INSEM
-# define S_TYPEISSEM(p) (S_ISNAM ((p)->st_mode) && (p)->st_rdev == S_INSEM)
-# else
-# define S_TYPEISSEM(p) 0
-# endif
-#endif
-
-#ifndef S_TYPEISSHM
-# ifdef S_INSHD
-# define S_TYPEISSHM(p) (S_ISNAM ((p)->st_mode) && (p)->st_rdev == S_INSHD)
-# else
-# define S_TYPEISSHM(p) 0
-# endif
-#endif
-
-/* high performance ("contiguous data") */
-#ifndef S_ISCTG
-# define S_ISCTG(p) 0
-#endif
-
-/* Cray DMF (data migration facility): off line, with data */
-#ifndef S_ISOFD
-# define S_ISOFD(p) 0
-#endif
-
-/* Cray DMF (data migration facility): off line, with no data */
-#ifndef S_ISOFL
-# define S_ISOFL(p) 0
-#endif
-
-/* 4.4BSD whiteout */
-#ifndef S_ISWHT
-# define S_ISWHT(m) 0
-#endif
-
-/* If any of the following are undefined,
- define them to their de facto standard values. */
-#if !S_ISUID
-# define S_ISUID 04000
-#endif
-#if !S_ISGID
-# define S_ISGID 02000
-#endif
-
-/* S_ISVTX is a common extension to POSIX. */
-#ifndef S_ISVTX
-# define S_ISVTX 01000
-#endif
-
-#if !S_IRUSR && S_IREAD
-# define S_IRUSR S_IREAD
-#endif
-#if !S_IRUSR
-# define S_IRUSR 00400
-#endif
-#if !S_IRGRP
-# define S_IRGRP (S_IRUSR >> 3)
-#endif
-#if !S_IROTH
-# define S_IROTH (S_IRUSR >> 6)
-#endif
-
-#if !S_IWUSR && S_IWRITE
-# define S_IWUSR S_IWRITE
-#endif
-#if !S_IWUSR
-# define S_IWUSR 00200
-#endif
-#if !S_IWGRP
-# define S_IWGRP (S_IWUSR >> 3)
-#endif
-#if !S_IWOTH
-# define S_IWOTH (S_IWUSR >> 6)
-#endif
-
-#if !S_IXUSR && S_IEXEC
-# define S_IXUSR S_IEXEC
-#endif
-#if !S_IXUSR
-# define S_IXUSR 00100
-#endif
-#if !S_IXGRP
-# define S_IXGRP (S_IXUSR >> 3)
-#endif
-#if !S_IXOTH
-# define S_IXOTH (S_IXUSR >> 6)
-#endif
-
-#if !S_IRWXU
-# define S_IRWXU (S_IRUSR | S_IWUSR | S_IXUSR)
-#endif
-#if !S_IRWXG
-# define S_IRWXG (S_IRGRP | S_IWGRP | S_IXGRP)
-#endif
-#if !S_IRWXO
-# define S_IRWXO (S_IROTH | S_IWOTH | S_IXOTH)
-#endif
-
-/* S_IXUGO is a common extension to POSIX. */
-#if !S_IXUGO
-# define S_IXUGO (S_IXUSR | S_IXGRP | S_IXOTH)
-#endif
-
-#ifndef S_IRWXUGO
-# define S_IRWXUGO (S_IRWXU | S_IRWXG | S_IRWXO)
-#endif
-
-/* mingw does not support symlinks, therefore it does not have lstat. But
- without links, stat does just fine. */
-#if ! HAVE_LSTAT
-# define lstat stat
-#endif
-
-/* mingw's _mkdir() function has 1 argument, but we pass 2 arguments.
- Additionally, it declares _mkdir (and depending on compile flags, an
- alias mkdir), only in the nonstandard io.h. */
-#if ! HAVE_DECL_MKDIR && HAVE_IO_H
-# include <io.h>
-
-static inline int
-rpl_mkdir (char const *name, mode_t mode)
-{
- return _mkdir (name);
-}
-
-# define mkdir rpl_mkdir
-#endif
-
-#endif /* _gl_SYS_STAT_H */
diff --git a/lib/statat.c b/lib/statat.c
new file mode 100644
index 0000000..8cdb17e
--- /dev/null
+++ b/lib/statat.c
@@ -0,0 +1,3 @@
+#include <config.h>
+#define STATAT_INLINE _GL_EXTERN_INLINE
+#include "openat.h"
diff --git a/lib/stdalign.in.h b/lib/stdalign.in.h
new file mode 100644
index 0000000..9abb9aa
--- /dev/null
+++ b/lib/stdalign.in.h
@@ -0,0 +1,121 @@
+/* A substitute for ISO C11 <stdalign.h>.
+
+ Copyright 2011-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Paul Eggert and Bruno Haible. */
+
+#ifndef _GL_STDALIGN_H
+#define _GL_STDALIGN_H
+
+/* ISO C11 <stdalign.h> for platforms that lack it.
+
+ References:
+ ISO C11 (latest free draft
+ <http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf>)
+ sections 6.5.3.4, 6.7.5, 7.15.
+ C++11 (latest free draft
+ <http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3242.pdf>)
+ section 18.10. */
+
+/* alignof (TYPE), also known as _Alignof (TYPE), yields the alignment
+ requirement of a structure member (i.e., slot or field) that is of
+ type TYPE, as an integer constant expression.
+
+ This differs from GCC's __alignof__ operator, which can yield a
+ better-performing alignment for an object of that type. For
+ example, on x86 with GCC, __alignof__ (double) and __alignof__
+ (long long) are 8, whereas alignof (double) and alignof (long long)
+ are 4 unless the option '-malign-double' is used.
+
+ The result cannot be used as a value for an 'enum' constant, if you
+ want to be portable to HP-UX 10.20 cc and AIX 3.2.5 xlc.
+
+ Include <stddef.h> for offsetof. */
+#include <stddef.h>
+
+/* FreeBSD 9.1 <sys/cdefs.h>, included by <stddef.h> and lots of other
+ standard headers, defines conflicting implementations of _Alignas
+ and _Alignof that are no better than ours; override them. */
+#undef _Alignas
+#undef _Alignof
+
+/* GCC releases before GCC 4.9 had a bug in _Alignof. See GCC bug 52023
+ <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52023>. */
+#if (!defined __STDC_VERSION__ || __STDC_VERSION__ < 201112 \
+ || (defined __GNUC__ && __GNUC__ < 4 + (__GNUC_MINOR__ < 9)))
+# ifdef __cplusplus
+# if 201103 <= __cplusplus
+# define _Alignof(type) alignof (type)
+# else
+ template <class __t> struct __alignof_helper { char __a; __t __b; };
+# define _Alignof(type) offsetof (__alignof_helper<type>, __b)
+# endif
+# else
+# define _Alignof(type) offsetof (struct { char __a; type __b; }, __b)
+# endif
+#endif
+#if ! (defined __cplusplus && 201103 <= __cplusplus)
+# define alignof _Alignof
+#endif
+#define __alignof_is_defined 1
+
+/* alignas (A), also known as _Alignas (A), aligns a variable or type
+ to the alignment A, where A is an integer constant expression. For
+ example:
+
+ int alignas (8) foo;
+ struct s { int a; int alignas (8) bar; };
+
+ aligns the address of FOO and the offset of BAR to be multiples of 8.
+
+ A should be a power of two that is at least the type's alignment
+ and at most the implementation's alignment limit. This limit is
+ 2**28 on typical GNUish hosts, and 2**13 on MSVC. To be portable
+ to MSVC through at least version 10.0, A should be an integer
+ constant, as MSVC does not support expressions such as 1 << 3.
+ To be portable to Sun C 5.11, do not align auto variables to
+ anything stricter than their default alignment.
+
+ The following C11 requirements are not supported here:
+
+ - If A is zero, alignas has no effect.
+ - alignas can be used multiple times; the strictest one wins.
+ - alignas (TYPE) is equivalent to alignas (alignof (TYPE)).
+
+ */
+
+#if !defined __STDC_VERSION__ || __STDC_VERSION__ < 201112
+# if defined __cplusplus && 201103 <= __cplusplus
+# define _Alignas(a) alignas (a)
+# elif ((defined __APPLE__ && defined __MACH__ \
+ ? 4 < __GNUC__ + (1 <= __GNUC_MINOR__) \
+ : __GNUC__) \
+ || __HP_cc || __HP_aCC || __IBMC__ || __IBMCPP__ \
+ || __ICC || 0x590 <= __SUNPRO_C)
+# define _Alignas(a) __attribute__ ((__aligned__ (a)))
+# elif 1300 <= _MSC_VER
+# define _Alignas(a) __declspec (align (a))
+# endif
+#endif
+#if ((defined _Alignas && ! (defined __cplusplus && 201103 <= __cplusplus)) \
+ || (defined __STDC_VERSION && 201112 <= __STDC_VERSION__))
+# define alignas _Alignas
+#endif
+#if defined alignas || (defined __cplusplus && 201103 <= __cplusplus)
+# define __alignas_is_defined 1
+#endif
+
+#endif /* _GL_STDALIGN_H */
diff --git a/lib/stdarg.in.h b/lib/stdarg.in.h
new file mode 100644
index 0000000..63371e2
--- /dev/null
+++ b/lib/stdarg.in.h
@@ -0,0 +1,35 @@
+/* Substitute for and wrapper around <stdarg.h>.
+ Copyright (C) 2008-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _@GUARD_PREFIX@_STDARG_H
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+/* The include_next requires a split double-inclusion guard. */
+#@INCLUDE_NEXT@ @NEXT_STDARG_H@
+
+#ifndef _@GUARD_PREFIX@_STDARG_H
+#define _@GUARD_PREFIX@_STDARG_H
+
+#ifndef va_copy
+# define va_copy(a,b) ((a) = (b))
+#endif
+
+#endif /* _@GUARD_PREFIX@_STDARG_H */
+#endif /* _@GUARD_PREFIX@_STDARG_H */
diff --git a/lib/stdbool_.h b/lib/stdbool.in.h
index 8525f0f..7ecf203 100644
--- a/lib/stdbool_.h
+++ b/lib/stdbool.in.h
@@ -1,9 +1,9 @@
-/* Copyright (C) 2001, 2002, 2003, 2006, 2007 Free Software Foundation, Inc.
+/* Copyright (C) 2001-2003, 2006-2016 Free Software Foundation, Inc.
Written by Bruno Haible <haible@clisp.cons.org>, 2001.
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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -12,11 +12,10 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program; if not, see <http://www.gnu.org/licenses/>. */
-#ifndef _STDBOOL_H
-#define _STDBOOL_H
+#ifndef _GL_STDBOOL_H
+#define _GL_STDBOOL_H
/* ISO C 99 <stdbool.h> for platforms that lack it. */
@@ -50,6 +49,9 @@
with this substitute. With this substitute, only the values 0 and 1
give the expected result when converted to _Bool' or 'bool'.
+ - C99 allows the use of (_Bool)0.0 in constant expressions, but
+ this substitute cannot always provide this property.
+
Also, it is suggested that programs use 'bool' rather than '_Bool';
this isn't required, but 'bool' is more common. */
@@ -58,30 +60,25 @@
/* BeOS <sys/socket.h> already #defines false 0, true 1. We use the same
definitions below, but temporarily we have to #undef them. */
-#ifdef __BEOS__
+#if defined __BEOS__ && !defined __HAIKU__
# include <OS.h> /* defines bool but not _Bool */
# undef false
# undef true
#endif
-/* For the sake of symbolic names in gdb, we define true and false as
- enum constants, not only as macros.
- It is tempting to write
- typedef enum { false = 0, true = 1 } _Bool;
- so that gdb prints values of type 'bool' symbolically. But if we do
- this, values of type '_Bool' may promote to 'int' or 'unsigned int'
- (see ISO C 99 6.7.2.2.(4)); however, '_Bool' must promote to 'int'
- (see ISO C 99 6.3.1.1.(2)). So we add a negative value to the
- enum; this ensures that '_Bool' promotes to 'int'. */
-#if defined __cplusplus || defined __BEOS__
+#ifdef __cplusplus
+# define _Bool bool
+# define bool bool
+#else
+# if defined __BEOS__ && !defined __HAIKU__
/* A compiler known to have 'bool'. */
/* If the compiler already has both 'bool' and '_Bool', we can assume they
are the same types. */
-# if !@HAVE__BOOL@
+# if !@HAVE__BOOL@
typedef bool _Bool;
-# endif
-#else
-# if !defined __GNUC__
+# endif
+# else
+# if !defined __GNUC__
/* If @HAVE__BOOL@:
Some HP-UX cc and AIX IBM C compiler versions have compiler bugs when
the built-in _Bool type is used. See
@@ -97,22 +94,39 @@ typedef bool _Bool;
"warning: _Bool is a keyword in ISO C99".
Use of an enum type, with IRIX cc, leads to a stupid
"warning(1185): enumerated type mixed with another type".
- The only benefit of the enum type, debuggability, is not important
- with these compilers. So use 'signed char' and no typedef. */
-# define _Bool signed char
-enum { false = 0, true = 1 };
-# else
+ Even the existence of an enum type, without a typedef,
+ "Invalid enumerator. (badenum)" with HP-UX cc on Tru64.
+ The only benefit of the enum, debuggability, is not important
+ with these compilers. So use 'signed char' and no enum. */
+# define _Bool signed char
+# else
/* With this compiler, trust the _Bool type if the compiler has it. */
-# if !@HAVE__BOOL@
+# if !@HAVE__BOOL@
+ /* For the sake of symbolic names in gdb, define true and false as
+ enum constants, not only as macros.
+ It is tempting to write
+ typedef enum { false = 0, true = 1 } _Bool;
+ so that gdb prints values of type 'bool' symbolically. But then
+ values of type '_Bool' might promote to 'int' or 'unsigned int'
+ (see ISO C 99 6.7.2.2.(4)); however, '_Bool' must promote to 'int'
+ (see ISO C 99 6.3.1.1.(2)). So add a negative value to the
+ enum; this ensures that '_Bool' promotes to 'int'. */
typedef enum { _Bool_must_promote_to_int = -1, false = 0, true = 1 } _Bool;
+# endif
# endif
# endif
+# define bool _Bool
#endif
-#define bool _Bool
/* The other macros must be usable in preprocessor directives. */
-#define false 0
-#define true 1
+#ifdef __cplusplus
+# define false false
+# define true true
+#else
+# define false 0
+# define true 1
+#endif
+
#define __bool_true_false_are_defined 1
-#endif /* _STDBOOL_H */
+#endif /* _GL_STDBOOL_H */
diff --git a/lib/stddef.in.h b/lib/stddef.in.h
new file mode 100644
index 0000000..c6d2317
--- /dev/null
+++ b/lib/stddef.in.h
@@ -0,0 +1,108 @@
+/* A substitute for POSIX 2008 <stddef.h>, for platforms that have issues.
+
+ Copyright (C) 2009-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Eric Blake. */
+
+/*
+ * POSIX 2008 <stddef.h> for platforms that have issues.
+ * <http://www.opengroup.org/susv3xbd/stddef.h.html>
+ */
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+#if defined __need_wchar_t || defined __need_size_t \
+ || defined __need_ptrdiff_t || defined __need_NULL \
+ || defined __need_wint_t
+/* Special invocation convention inside gcc header files. In
+ particular, gcc provides a version of <stddef.h> that blindly
+ redefines NULL even when __need_wint_t was defined, even though
+ wint_t is not normally provided by <stddef.h>. Hence, we must
+ remember if special invocation has ever been used to obtain wint_t,
+ in which case we need to clean up NULL yet again. */
+
+# if !(defined _@GUARD_PREFIX@_STDDEF_H && defined _GL_STDDEF_WINT_T)
+# ifdef __need_wint_t
+# define _GL_STDDEF_WINT_T
+# endif
+# @INCLUDE_NEXT@ @NEXT_STDDEF_H@
+# endif
+
+#else
+/* Normal invocation convention. */
+
+# ifndef _@GUARD_PREFIX@_STDDEF_H
+
+/* The include_next requires a split double-inclusion guard. */
+
+# @INCLUDE_NEXT@ @NEXT_STDDEF_H@
+
+/* On NetBSD 5.0, the definition of NULL lacks proper parentheses. */
+# if (@REPLACE_NULL@ \
+ && (!defined _@GUARD_PREFIX@_STDDEF_H || defined _GL_STDDEF_WINT_T))
+# undef NULL
+# ifdef __cplusplus
+ /* ISO C++ says that the macro NULL must expand to an integer constant
+ expression, hence '((void *) 0)' is not allowed in C++. */
+# if __GNUG__ >= 3
+ /* GNU C++ has a __null macro that behaves like an integer ('int' or
+ 'long') but has the same size as a pointer. Use that, to avoid
+ warnings. */
+# define NULL __null
+# else
+# define NULL 0L
+# endif
+# else
+# define NULL ((void *) 0)
+# endif
+# endif
+
+# ifndef _@GUARD_PREFIX@_STDDEF_H
+# define _@GUARD_PREFIX@_STDDEF_H
+
+/* Some platforms lack wchar_t. */
+#if !@HAVE_WCHAR_T@
+# define wchar_t int
+#endif
+
+/* Some platforms lack max_align_t. */
+#if !@HAVE_MAX_ALIGN_T@
+/* On the x86, the maximum storage alignment of double, long, etc. is 4,
+ but GCC's C11 ABI for x86 says that max_align_t has an alignment of 8,
+ and the C11 standard allows this. Work around this problem by
+ using __alignof__ (which returns 8 for double) rather than _Alignof
+ (which returns 4), and align each union member accordingly. */
+# ifdef __GNUC__
+# define _GL_STDDEF_ALIGNAS(type) \
+ __attribute__ ((__aligned__ (__alignof__ (type))))
+# else
+# define _GL_STDDEF_ALIGNAS(type) /* */
+# endif
+typedef union
+{
+ char *__p _GL_STDDEF_ALIGNAS (char *);
+ double __d _GL_STDDEF_ALIGNAS (double);
+ long double __ld _GL_STDDEF_ALIGNAS (long double);
+ long int __i _GL_STDDEF_ALIGNAS (long int);
+} max_align_t;
+#endif
+
+# endif /* _@GUARD_PREFIX@_STDDEF_H */
+# endif /* _@GUARD_PREFIX@_STDDEF_H */
+#endif /* __need_XXX */
diff --git a/lib/stdint_.h b/lib/stdint.in.h
index 4fa5251..0bb9ad4 100644
--- a/lib/stdint_.h
+++ b/lib/stdint.in.h
@@ -1,10 +1,10 @@
-/* Copyright (C) 2001-2002, 2004-2007 Free Software Foundation, Inc.
+/* Copyright (C) 2001-2002, 2004-2016 Free Software Foundation, Inc.
Written by Paul Eggert, Bruno Haible, Sam Steingold, Peter Burwood.
This file is part of gnulib.
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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -13,17 +13,35 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-#ifndef _GL_STDINT_H
-#define _GL_STDINT_H
+ along with this program; if not, see <http://www.gnu.org/licenses/>. */
/*
* ISO C 99 <stdint.h> for platforms that lack it.
* <http://www.opengroup.org/susv3xbd/stdint.h.html>
*/
+#ifndef _@GUARD_PREFIX@_STDINT_H
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+/* When including a system file that in turn includes <inttypes.h>,
+ use the system <inttypes.h>, not our substitute. This avoids
+ problems with (for example) VMS, whose <sys/bitypes.h> includes
+ <inttypes.h>. */
+#define _GL_JUST_INCLUDE_SYSTEM_INTTYPES_H
+
+/* On Android (Bionic libc), <sys/types.h> includes this file before
+ having defined 'time_t'. Therefore in this case avoid including
+ other system header files; just include the system's <stdint.h>.
+ Ideally we should test __BIONIC__ here, but it is only defined after
+ <sys/cdefs.h> has been included; hence test __ANDROID__ instead. */
+#if defined __ANDROID__ && defined _GL_INCLUDING_SYS_TYPES_H
+# @INCLUDE_NEXT@ @NEXT_STDINT_H@
+#else
+
/* Get those types that are already defined in other system include
files, so that we can "#define int8_t signed char" below without
worrying about a later system include file containing a "typedef
@@ -39,33 +57,47 @@
diagnostics. */
# define __STDINT_H__
# endif
+
+ /* Some pre-C++11 <stdint.h> implementations need this. */
+# ifdef __cplusplus
+# ifndef __STDC_CONSTANT_MACROS
+# define __STDC_CONSTANT_MACROS 1
+# endif
+# ifndef __STDC_LIMIT_MACROS
+# define __STDC_LIMIT_MACROS 1
+# endif
+# endif
+
/* Other systems may have an incomplete or buggy <stdint.h>.
Include it before <inttypes.h>, since any "#include <stdint.h>"
in <inttypes.h> would reinclude us, skipping our contents because
- _GL_STDINT_H is defined. */
-# include @ABSOLUTE_STDINT_H@
+ _@GUARD_PREFIX@_STDINT_H is defined.
+ The include_next requires a split double-inclusion guard. */
+# @INCLUDE_NEXT@ @NEXT_STDINT_H@
#endif
+#if ! defined _@GUARD_PREFIX@_STDINT_H && ! defined _GL_JUST_INCLUDE_SYSTEM_STDINT_H
+#define _@GUARD_PREFIX@_STDINT_H
+
/* <sys/types.h> defines some of the stdint.h types as well, on glibc,
IRIX 6.5, and OpenBSD 3.8 (via <machine/types.h>).
AIX 5.2 <sys/types.h> isn't needed and causes troubles.
- MacOS X 10.4.6 <sys/types.h> includes <stdint.h> (which is us), but
+ Mac OS X 10.4.6 <sys/types.h> includes <stdint.h> (which is us), but
relies on the system <stdint.h> definitions, so include
- <sys/types.h> after @ABSOLUTE_STDINT_H@. */
+ <sys/types.h> after @NEXT_STDINT_H@. */
#if @HAVE_SYS_TYPES_H@ && ! defined _AIX
# include <sys/types.h>
#endif
-/* Get LONG_MIN, LONG_MAX, ULONG_MAX. */
+/* Get SCHAR_MIN, SCHAR_MAX, UCHAR_MAX, INT_MIN, INT_MAX,
+ LONG_MIN, LONG_MAX, ULONG_MAX. */
#include <limits.h>
#if @HAVE_INTTYPES_H@
/* In OpenBSD 3.8, <inttypes.h> includes <machine/types.h>, which defines
int{8,16,32,64}_t, uint{8,16,32,64}_t and __BIT_TYPES_DEFINED__.
<inttypes.h> also defines intptr_t and uintptr_t. */
-# define _GL_JUST_INCLUDE_ABSOLUTE_INTTYPES_H
# include <inttypes.h>
-# undef _GL_JUST_INCLUDE_ABSOLUTE_INTTYPES_H
#elif @HAVE_SYS_INTTYPES_H@
/* Solaris 7 <sys/inttypes.h> has the types except the *_fast*_t types, and
the macros except for *_FAST*_*, INTPTR_MIN, PTRDIFF_MIN, PTRDIFF_MAX. */
@@ -79,16 +111,9 @@
# include <sys/bitypes.h>
#endif
-#if ! defined __cplusplus || defined __STDC_CONSTANT_MACROS
+#undef _GL_JUST_INCLUDE_SYSTEM_INTTYPES_H
-/* Get WCHAR_MIN, WCHAR_MAX. */
-# if ! (defined WCHAR_MIN && defined WCHAR_MAX)
-# include <wchar.h>
-# endif
-
-#endif
-
-/* Minimum and maximum values for a integer type under the usual assumption.
+/* Minimum and maximum values for an integer type under the usual assumption.
Return an unspecified value if BITS == 0, adding a check to pacify
picky compilers. */
@@ -98,7 +123,12 @@
#define _STDINT_MAX(signed, bits, zero) \
((signed) \
? ~ _STDINT_MIN (signed, bits, zero) \
- : ((((zero) + 1) << ((bits) ? (bits) - 1 : 0)) - 1) * 2 + 1)
+ : /* The expression for the unsigned case. The subtraction of (signed) \
+ is a nop in the unsigned case and avoids "signed integer overflow" \
+ warnings in the signed case. */ \
+ ((((zero) + 1) << ((bits) ? (bits) - 1 - (signed) : 0)) - 1) * 2 + 1)
+
+#if !GNULIB_defined_stdint_types
/* 7.18.1.1. Exact-width integer types */
@@ -107,47 +137,73 @@
#undef int8_t
#undef uint8_t
-#define int8_t signed char
-#define uint8_t unsigned char
+typedef signed char gl_int8_t;
+typedef unsigned char gl_uint8_t;
+#define int8_t gl_int8_t
+#define uint8_t gl_uint8_t
#undef int16_t
#undef uint16_t
-#define int16_t short int
-#define uint16_t unsigned short int
+typedef short int gl_int16_t;
+typedef unsigned short int gl_uint16_t;
+#define int16_t gl_int16_t
+#define uint16_t gl_uint16_t
#undef int32_t
#undef uint32_t
-#define int32_t int
-#define uint32_t unsigned int
+typedef int gl_int32_t;
+typedef unsigned int gl_uint32_t;
+#define int32_t gl_int32_t
+#define uint32_t gl_uint32_t
+
+/* If the system defines INT64_MAX, assume int64_t works. That way,
+ if the underlying platform defines int64_t to be a 64-bit long long
+ int, the code below won't mistakenly define it to be a 64-bit long
+ int, which would mess up C++ name mangling. We must use #ifdef
+ rather than #if, to avoid an error with HP-UX 10.20 cc. */
+#ifdef INT64_MAX
+# define GL_INT64_T
+#else
/* Do not undefine int64_t if gnulib is not being used with 64-bit
types, since otherwise it breaks platforms like Tandem/NSK. */
-#if LONG_MAX >> 31 >> 31 == 1
-# undef int64_t
-# define int64_t long int
-# define GL_INT64_T
-#elif defined _MSC_VER
-# undef int64_t
-# define int64_t __int64
-# define GL_INT64_T
-#elif @HAVE_LONG_LONG_INT@
-# undef int64_t
-# define int64_t long long int
-# define GL_INT64_T
+# if LONG_MAX >> 31 >> 31 == 1
+# undef int64_t
+typedef long int gl_int64_t;
+# define int64_t gl_int64_t
+# define GL_INT64_T
+# elif defined _MSC_VER
+# undef int64_t
+typedef __int64 gl_int64_t;
+# define int64_t gl_int64_t
+# define GL_INT64_T
+# elif @HAVE_LONG_LONG_INT@
+# undef int64_t
+typedef long long int gl_int64_t;
+# define int64_t gl_int64_t
+# define GL_INT64_T
+# endif
#endif
-#if ULONG_MAX >> 31 >> 31 >> 1 == 1
-# undef uint64_t
-# define uint64_t unsigned long int
-# define GL_UINT64_T
-#elif defined _MSC_VER
-# undef uint64_t
-# define uint64_t unsigned __int64
-# define GL_UINT64_T
-#elif @HAVE_UNSIGNED_LONG_LONG_INT@
-# undef uint64_t
-# define uint64_t unsigned long long int
+#ifdef UINT64_MAX
# define GL_UINT64_T
+#else
+# if ULONG_MAX >> 31 >> 31 >> 1 == 1
+# undef uint64_t
+typedef unsigned long int gl_uint64_t;
+# define uint64_t gl_uint64_t
+# define GL_UINT64_T
+# elif defined _MSC_VER
+# undef uint64_t
+typedef unsigned __int64 gl_uint64_t;
+# define uint64_t gl_uint64_t
+# define GL_UINT64_T
+# elif @HAVE_UNSIGNED_LONG_LONG_INT@
+# undef uint64_t
+typedef unsigned long long int gl_uint64_t;
+# define uint64_t gl_uint64_t
+# define GL_UINT64_T
+# endif
#endif
/* Avoid collision with Solaris 2.5.1 <pthread.h> etc. */
@@ -190,8 +246,9 @@
/* Here we assume a standard architecture where the hardware integer
types have 8, 16, 32, optionally 64 bits. Therefore the fastN_t types
- are taken from the same list of types. Assume that 'long int'
- is fast enough for all narrower integers. */
+ are taken from the same list of types. The following code normally
+ uses types consistent with glibc, as that lessens the chance of
+ incompatibility with older GNU hosts. */
#undef int_fast8_t
#undef uint_fast8_t
@@ -201,12 +258,27 @@
#undef uint_fast32_t
#undef int_fast64_t
#undef uint_fast64_t
-#define int_fast8_t long int
-#define uint_fast8_t unsigned int_fast8_t
-#define int_fast16_t long int
-#define uint_fast16_t unsigned int_fast16_t
-#define int_fast32_t long int
-#define uint_fast32_t unsigned int_fast32_t
+typedef signed char gl_int_fast8_t;
+typedef unsigned char gl_uint_fast8_t;
+
+#ifdef __sun
+/* Define types compatible with SunOS 5.10, so that code compiled under
+ earlier SunOS versions works with code compiled under SunOS 5.10. */
+typedef int gl_int_fast32_t;
+typedef unsigned int gl_uint_fast32_t;
+#else
+typedef long int gl_int_fast32_t;
+typedef unsigned long int gl_uint_fast32_t;
+#endif
+typedef gl_int_fast32_t gl_int_fast16_t;
+typedef gl_uint_fast32_t gl_uint_fast16_t;
+
+#define int_fast8_t gl_int_fast8_t
+#define uint_fast8_t gl_uint_fast8_t
+#define int_fast16_t gl_int_fast16_t
+#define uint_fast16_t gl_uint_fast16_t
+#define int_fast32_t gl_int_fast32_t
+#define uint_fast32_t gl_uint_fast32_t
#ifdef GL_INT64_T
# define int_fast64_t int64_t
#endif
@@ -216,37 +288,65 @@
/* 7.18.1.4. Integer types capable of holding object pointers */
+/* kLIBC's stdint.h defines _INTPTR_T_DECLARED and needs its own
+ definitions of intptr_t and uintptr_t (which use int and unsigned)
+ to avoid clashes with declarations of system functions like sbrk. */
+#ifndef _INTPTR_T_DECLARED
#undef intptr_t
#undef uintptr_t
-#define intptr_t long int
-#define uintptr_t unsigned long int
+typedef long int gl_intptr_t;
+typedef unsigned long int gl_uintptr_t;
+#define intptr_t gl_intptr_t
+#define uintptr_t gl_uintptr_t
+#endif
/* 7.18.1.5. Greatest-width integer types */
/* Note: These types are compiler dependent. It may be unwise to use them in
public header files. */
-#undef intmax_t
-#if @HAVE_LONG_LONG_INT@ && LONG_MAX >> 30 == 1
-# define intmax_t long long int
-#elif defined GL_INT64_T
-# define intmax_t int64_t
-#else
-# define intmax_t long int
+/* If the system defines INTMAX_MAX, assume that intmax_t works, and
+ similarly for UINTMAX_MAX and uintmax_t. This avoids problems with
+ assuming one type where another is used by the system. */
+
+#ifndef INTMAX_MAX
+# undef INTMAX_C
+# undef intmax_t
+# if @HAVE_LONG_LONG_INT@ && LONG_MAX >> 30 == 1
+typedef long long int gl_intmax_t;
+# define intmax_t gl_intmax_t
+# elif defined GL_INT64_T
+# define intmax_t int64_t
+# else
+typedef long int gl_intmax_t;
+# define intmax_t gl_intmax_t
+# endif
#endif
-#undef uintmax_t
-#if @HAVE_UNSIGNED_LONG_LONG_INT@ && ULONG_MAX >> 31 == 1
-# define uintmax_t unsigned long long int
-#elif defined GL_UINT64_T
-# define uintmax_t uint64_t
-#else
-# define uintmax_t unsigned long int
+#ifndef UINTMAX_MAX
+# undef UINTMAX_C
+# undef uintmax_t
+# if @HAVE_UNSIGNED_LONG_LONG_INT@ && ULONG_MAX >> 31 == 1
+typedef unsigned long long int gl_uintmax_t;
+# define uintmax_t gl_uintmax_t
+# elif defined GL_UINT64_T
+# define uintmax_t uint64_t
+# else
+typedef unsigned long int gl_uintmax_t;
+# define uintmax_t gl_uintmax_t
+# endif
#endif
-/* 7.18.2. Limits of specified-width integer types */
+/* Verify that intmax_t and uintmax_t have the same size. Too much code
+ breaks if this is not the case. If this check fails, the reason is likely
+ to be found in the autoconf macros. */
+typedef int _verify_intmax_size[sizeof (intmax_t) == sizeof (uintmax_t)
+ ? 1 : -1];
-#if ! defined __cplusplus || defined __STDC_LIMIT_MACROS
+#define GNULIB_defined_stdint_types 1
+#endif /* !GNULIB_defined_stdint_types */
+
+/* 7.18.2. Limits of specified-width integer types */
/* 7.18.2.1. Limits of exact-width integer types */
@@ -274,17 +374,14 @@
#define INT32_MAX 2147483647
#define UINT32_MAX 4294967295U
-#undef INT64_MIN
-#undef INT64_MAX
-#ifdef GL_INT64_T
+#if defined GL_INT64_T && ! defined INT64_MAX
/* Prefer (- INTMAX_C (1) << 63) over (~ INT64_MAX) because SunPRO C 5.0
evaluates the latter incorrectly in preprocessor expressions. */
# define INT64_MIN (- INTMAX_C (1) << 63)
# define INT64_MAX INTMAX_C (9223372036854775807)
#endif
-#undef UINT64_MAX
-#ifdef GL_UINT64_T
+#if defined GL_UINT64_T && ! defined UINT64_MAX
# define UINT64_MAX UINTMAX_C (18446744073709551615)
#endif
@@ -336,23 +433,29 @@
#undef INT_FAST8_MIN
#undef INT_FAST8_MAX
#undef UINT_FAST8_MAX
-#define INT_FAST8_MIN LONG_MIN
-#define INT_FAST8_MAX LONG_MAX
-#define UINT_FAST8_MAX ULONG_MAX
+#define INT_FAST8_MIN SCHAR_MIN
+#define INT_FAST8_MAX SCHAR_MAX
+#define UINT_FAST8_MAX UCHAR_MAX
#undef INT_FAST16_MIN
#undef INT_FAST16_MAX
#undef UINT_FAST16_MAX
-#define INT_FAST16_MIN LONG_MIN
-#define INT_FAST16_MAX LONG_MAX
-#define UINT_FAST16_MAX ULONG_MAX
+#define INT_FAST16_MIN INT_FAST32_MIN
+#define INT_FAST16_MAX INT_FAST32_MAX
+#define UINT_FAST16_MAX UINT_FAST32_MAX
#undef INT_FAST32_MIN
#undef INT_FAST32_MAX
#undef UINT_FAST32_MAX
-#define INT_FAST32_MIN LONG_MIN
-#define INT_FAST32_MAX LONG_MAX
-#define UINT_FAST32_MAX ULONG_MAX
+#ifdef __sun
+# define INT_FAST32_MIN INT_MIN
+# define INT_FAST32_MAX INT_MAX
+# define UINT_FAST32_MAX UINT_MAX
+#else
+# define INT_FAST32_MIN LONG_MIN
+# define INT_FAST32_MAX LONG_MAX
+# define UINT_FAST32_MAX ULONG_MAX
+#endif
#undef INT_FAST64_MIN
#undef INT_FAST64_MAX
@@ -377,21 +480,23 @@
/* 7.18.2.5. Limits of greatest-width integer types */
-#undef INTMAX_MIN
-#undef INTMAX_MAX
-#ifdef INT64_MAX
-# define INTMAX_MIN INT64_MIN
-# define INTMAX_MAX INT64_MAX
-#else
-# define INTMAX_MIN INT32_MIN
-# define INTMAX_MAX INT32_MAX
+#ifndef INTMAX_MAX
+# undef INTMAX_MIN
+# ifdef INT64_MAX
+# define INTMAX_MIN INT64_MIN
+# define INTMAX_MAX INT64_MAX
+# else
+# define INTMAX_MIN INT32_MIN
+# define INTMAX_MAX INT32_MAX
+# endif
#endif
-#undef UINTMAX_MAX
-#ifdef UINT64_MAX
-# define UINTMAX_MAX UINT64_MAX
-#else
-# define UINTMAX_MAX UINT32_MAX
+#ifndef UINTMAX_MAX
+# ifdef UINT64_MAX
+# define UINTMAX_MAX UINT64_MAX
+# else
+# define UINTMAX_MAX UINT32_MAX
+# endif
#endif
/* 7.18.3. Limits of other integer types */
@@ -399,27 +504,60 @@
/* ptrdiff_t limits */
#undef PTRDIFF_MIN
#undef PTRDIFF_MAX
-#define PTRDIFF_MIN \
- _STDINT_MIN (1, @BITSIZEOF_PTRDIFF_T@, 0@PTRDIFF_T_SUFFIX@)
-#define PTRDIFF_MAX \
- _STDINT_MAX (1, @BITSIZEOF_PTRDIFF_T@, 0@PTRDIFF_T_SUFFIX@)
+#if @APPLE_UNIVERSAL_BUILD@
+# ifdef _LP64
+# define PTRDIFF_MIN _STDINT_MIN (1, 64, 0l)
+# define PTRDIFF_MAX _STDINT_MAX (1, 64, 0l)
+# else
+# define PTRDIFF_MIN _STDINT_MIN (1, 32, 0)
+# define PTRDIFF_MAX _STDINT_MAX (1, 32, 0)
+# endif
+#else
+# define PTRDIFF_MIN \
+ _STDINT_MIN (1, @BITSIZEOF_PTRDIFF_T@, 0@PTRDIFF_T_SUFFIX@)
+# define PTRDIFF_MAX \
+ _STDINT_MAX (1, @BITSIZEOF_PTRDIFF_T@, 0@PTRDIFF_T_SUFFIX@)
+#endif
/* sig_atomic_t limits */
#undef SIG_ATOMIC_MIN
#undef SIG_ATOMIC_MAX
#define SIG_ATOMIC_MIN \
_STDINT_MIN (@HAVE_SIGNED_SIG_ATOMIC_T@, @BITSIZEOF_SIG_ATOMIC_T@, \
- 0@SIG_ATOMIC_T_SUFFIX@)
+ 0@SIG_ATOMIC_T_SUFFIX@)
#define SIG_ATOMIC_MAX \
_STDINT_MAX (@HAVE_SIGNED_SIG_ATOMIC_T@, @BITSIZEOF_SIG_ATOMIC_T@, \
- 0@SIG_ATOMIC_T_SUFFIX@)
+ 0@SIG_ATOMIC_T_SUFFIX@)
/* size_t limit */
#undef SIZE_MAX
-#define SIZE_MAX _STDINT_MAX (0, @BITSIZEOF_SIZE_T@, 0@SIZE_T_SUFFIX@)
+#if @APPLE_UNIVERSAL_BUILD@
+# ifdef _LP64
+# define SIZE_MAX _STDINT_MAX (0, 64, 0ul)
+# else
+# define SIZE_MAX _STDINT_MAX (0, 32, 0ul)
+# endif
+#else
+# define SIZE_MAX _STDINT_MAX (0, @BITSIZEOF_SIZE_T@, 0@SIZE_T_SUFFIX@)
+#endif
/* wchar_t limits */
+/* Get WCHAR_MIN, WCHAR_MAX.
+ This include is not on the top, above, because on OSF/1 4.0 we have a
+ sequence of nested includes
+ <wchar.h> -> <stdio.h> -> <getopt.h> -> <stdlib.h>, and the latter includes
+ <stdint.h> and assumes its types are already defined. */
+#if @HAVE_WCHAR_H@ && ! (defined WCHAR_MIN && defined WCHAR_MAX)
+ /* BSD/OS 4.0.1 has a bug: <stddef.h>, <stdio.h> and <time.h> must be
+ included before <wchar.h>. */
+# include <stddef.h>
+# include <stdio.h>
+# include <time.h>
+# define _GL_JUST_INCLUDE_SYSTEM_WCHAR_H
+# include <wchar.h>
+# undef _GL_JUST_INCLUDE_SYSTEM_WCHAR_H
+#endif
#undef WCHAR_MIN
#undef WCHAR_MAX
#define WCHAR_MIN \
@@ -435,12 +573,8 @@
#define WINT_MAX \
_STDINT_MAX (@HAVE_SIGNED_WINT_T@, @BITSIZEOF_WINT_T@, 0@WINT_T_SUFFIX@)
-#endif /* !defined __cplusplus || defined __STDC_LIMIT_MACROS */
-
/* 7.18.4. Macros for integer constants */
-#if ! defined __cplusplus || defined __STDC_CONSTANT_MACROS
-
/* 7.18.4.1. Macros for minimum-width integer constants */
/* According to ISO C 99 Technical Corrigendum 1 */
@@ -481,24 +615,26 @@
/* 7.18.4.2. Macros for greatest-width integer constants */
-#undef INTMAX_C
-#if @HAVE_LONG_LONG_INT@ && LONG_MAX >> 30 == 1
-# define INTMAX_C(x) x##LL
-#elif defined GL_INT64_T
-# define INTMAX_C(x) INT64_C(x)
-#else
-# define INTMAX_C(x) x##L
+#ifndef INTMAX_C
+# if @HAVE_LONG_LONG_INT@ && LONG_MAX >> 30 == 1
+# define INTMAX_C(x) x##LL
+# elif defined GL_INT64_T
+# define INTMAX_C(x) INT64_C(x)
+# else
+# define INTMAX_C(x) x##L
+# endif
#endif
-#undef UINTMAX_C
-#if @HAVE_UNSIGNED_LONG_LONG_INT@ && ULONG_MAX >> 31 == 1
-# define UINTMAX_C(x) x##ULL
-#elif defined GL_UINT64_T
-# define UINTMAX_C(x) UINT64_C(x)
-#else
-# define UINTMAX_C(x) x##UL
+#ifndef UINTMAX_C
+# if @HAVE_UNSIGNED_LONG_LONG_INT@ && ULONG_MAX >> 31 == 1
+# define UINTMAX_C(x) x##ULL
+# elif defined GL_UINT64_T
+# define UINTMAX_C(x) UINT64_C(x)
+# else
+# define UINTMAX_C(x) x##UL
+# endif
#endif
-#endif /* !defined __cplusplus || defined __STDC_CONSTANT_MACROS */
-
-#endif /* _GL_STDINT_H */
+#endif /* _@GUARD_PREFIX@_STDINT_H */
+#endif /* !(defined __ANDROID__ && ...) */
+#endif /* !defined _@GUARD_PREFIX@_STDINT_H && !defined _GL_JUST_INCLUDE_SYSTEM_STDINT_H */
diff --git a/lib/stdio--.h b/lib/stdio--.h
index 2385e62..8e23817 100644
--- a/lib/stdio--.h
+++ b/lib/stdio--.h
@@ -1,11 +1,11 @@
/* Like stdio.h, but redefine some names to avoid glitches.
- Copyright (C) 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2005-2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,16 +13,29 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
#include <stdio.h>
#include "stdio-safer.h"
-#undef fopen
-#define fopen fopen_safer
-
-#undef tmpfile
-#define tmpfile tmpfile_safer
+#if GNULIB_FOPEN_SAFER
+# undef fopen
+# define fopen fopen_safer
+#endif
+
+#if GNULIB_FREOPEN_SAFER
+# undef freopen
+# define freopen freopen_safer
+#endif
+
+#if GNULIB_TMPFILE_SAFER
+# undef tmpfile
+# define tmpfile tmpfile_safer
+#endif
+
+#if GNULIB_POPEN_SAFER
+# undef popen
+# define popen popen_safer
+#endif
diff --git a/lib/stdio-impl.h b/lib/stdio-impl.h
new file mode 100644
index 0000000..987897a
--- /dev/null
+++ b/lib/stdio-impl.h
@@ -0,0 +1,113 @@
+/* Implementation details of FILE streams.
+ Copyright (C) 2007-2008, 2010-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Many stdio implementations have the same logic and therefore can share
+ the same implementation of stdio extension API, except that some fields
+ have different naming conventions, or their access requires some casts. */
+
+
+/* BSD stdio derived implementations. */
+
+#if defined __NetBSD__ /* NetBSD */
+/* Get __NetBSD_Version__. */
+# include <sys/param.h>
+#endif
+
+#include <errno.h> /* For detecting Plan9. */
+
+#if defined __sferror || defined __DragonFly__ || defined __ANDROID__
+ /* FreeBSD, NetBSD, OpenBSD, DragonFly, Mac OS X, Cygwin, Android */
+
+# if defined __DragonFly__ /* DragonFly */
+ /* See <http://www.dragonflybsd.org/cvsweb/src/lib/libc/stdio/priv_stdio.h?rev=HEAD&content-type=text/x-cvsweb-markup>. */
+# define fp_ ((struct { struct __FILE_public pub; \
+ struct { unsigned char *_base; int _size; } _bf; \
+ void *cookie; \
+ void *_close; \
+ void *_read; \
+ void *_seek; \
+ void *_write; \
+ struct { unsigned char *_base; int _size; } _ub; \
+ int _ur; \
+ unsigned char _ubuf[3]; \
+ unsigned char _nbuf[1]; \
+ struct { unsigned char *_base; int _size; } _lb; \
+ int _blksize; \
+ fpos_t _offset; \
+ /* More fields, not relevant here. */ \
+ } *) fp)
+ /* See <http://www.dragonflybsd.org/cvsweb/src/include/stdio.h?rev=HEAD&content-type=text/x-cvsweb-markup>. */
+# define _p pub._p
+# define _flags pub._flags
+# define _r pub._r
+# define _w pub._w
+# else
+# define fp_ fp
+# endif
+
+# if (defined __NetBSD__ && __NetBSD_Version__ >= 105270000) || defined __OpenBSD__ || defined __ANDROID__ /* NetBSD >= 1.5ZA, OpenBSD, Android */
+ /* See <http://cvsweb.netbsd.org/bsdweb.cgi/src/lib/libc/stdio/fileext.h?rev=HEAD&content-type=text/x-cvsweb-markup>
+ and <http://www.openbsd.org/cgi-bin/cvsweb/src/lib/libc/stdio/fileext.h?rev=HEAD&content-type=text/x-cvsweb-markup> */
+ struct __sfileext
+ {
+ struct __sbuf _ub; /* ungetc buffer */
+ /* More fields, not relevant here. */
+ };
+# define fp_ub ((struct __sfileext *) fp->_ext._base)->_ub
+# else /* FreeBSD, NetBSD <= 1.5Z, DragonFly, Mac OS X, Cygwin, Android */
+# define fp_ub fp_->_ub
+# endif
+
+# define HASUB(fp) (fp_ub._base != NULL)
+
+#endif
+
+
+/* SystemV derived implementations. */
+
+#ifdef __TANDEM /* NonStop Kernel */
+# ifndef _IOERR
+/* These values were determined by the program 'stdioext-flags' at
+ <http://lists.gnu.org/archive/html/bug-gnulib/2010-12/msg00165.html>. */
+# define _IOERR 0x40
+# define _IOREAD 0x80
+# define _IOWRT 0x4
+# define _IORW 0x100
+# endif
+#endif
+
+#if defined _IOERR
+
+# if defined __sun && defined _LP64 /* Solaris/{SPARC,AMD64} 64-bit */
+# define fp_ ((struct { unsigned char *_ptr; \
+ unsigned char *_base; \
+ unsigned char *_end; \
+ long _cnt; \
+ int _file; \
+ unsigned int _flag; \
+ } *) fp)
+# else
+# define fp_ fp
+# endif
+
+# if defined _SCO_DS /* OpenServer */
+# define _cnt __cnt
+# define _ptr __ptr
+# define _base __base
+# define _flag __flag
+# endif
+
+#endif
diff --git a/lib/stdio-safer.h b/lib/stdio-safer.h
index 8329a1a..4231609 100644
--- a/lib/stdio-safer.h
+++ b/lib/stdio-safer.h
@@ -1,11 +1,11 @@
/* Invoke stdio functions, but avoid some glitches.
- Copyright (C) 2001, 2003, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2001, 2003, 2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,12 +13,24 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
#include <stdio.h>
+#if GNULIB_FOPEN_SAFER
FILE *fopen_safer (char const *, char const *);
+#endif
+
+#if GNULIB_FREOPEN_SAFER
+FILE *freopen_safer (char const *, char const *, FILE *);
+#endif
+
+#if GNULIB_POPEN_SAFER
+FILE *popen_safer (char const *, char const *);
+#endif
+
+#if GNULIB_TMPFILE_SAFER
FILE *tmpfile_safer (void);
+#endif
diff --git a/lib/stdio.in.h b/lib/stdio.in.h
new file mode 100644
index 0000000..9b31365
--- /dev/null
+++ b/lib/stdio.in.h
@@ -0,0 +1,1357 @@
+/* A GNU-like <stdio.h>.
+
+ Copyright (C) 2004, 2007-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+#if defined __need_FILE || defined __need___FILE || defined _GL_ALREADY_INCLUDING_STDIO_H
+/* Special invocation convention:
+ - Inside glibc header files.
+ - On OSF/1 5.1 we have a sequence of nested includes
+ <stdio.h> -> <getopt.h> -> <ctype.h> -> <sys/localedef.h> ->
+ <sys/lc_core.h> -> <nl_types.h> -> <mesg.h> -> <stdio.h>.
+ In this situation, the functions are not yet declared, therefore we cannot
+ provide the C++ aliases. */
+
+#@INCLUDE_NEXT@ @NEXT_STDIO_H@
+
+#else
+/* Normal invocation convention. */
+
+#ifndef _@GUARD_PREFIX@_STDIO_H
+
+#define _GL_ALREADY_INCLUDING_STDIO_H
+
+/* The include_next requires a split double-inclusion guard. */
+#@INCLUDE_NEXT@ @NEXT_STDIO_H@
+
+#undef _GL_ALREADY_INCLUDING_STDIO_H
+
+#ifndef _@GUARD_PREFIX@_STDIO_H
+#define _@GUARD_PREFIX@_STDIO_H
+
+/* Get va_list. Needed on many systems, including glibc 2.8. */
+#include <stdarg.h>
+
+#include <stddef.h>
+
+/* Get off_t and ssize_t. Needed on many systems, including glibc 2.8
+ and eglibc 2.11.2.
+ May also define off_t to a 64-bit type on native Windows. */
+#include <sys/types.h>
+
+/* The __attribute__ feature is available in gcc versions 2.5 and later.
+ The __-protected variants of the attributes 'format' and 'printf' are
+ accepted by gcc versions 2.6.4 (effectively 2.7) and later.
+ We enable _GL_ATTRIBUTE_FORMAT only if these are supported too, because
+ gnulib and libintl do '#define printf __printf__' when they override
+ the 'printf' function. */
+#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 7)
+# define _GL_ATTRIBUTE_FORMAT(spec) __attribute__ ((__format__ spec))
+#else
+# define _GL_ATTRIBUTE_FORMAT(spec) /* empty */
+#endif
+
+/* _GL_ATTRIBUTE_FORMAT_PRINTF
+ indicates to GCC that the function takes a format string and arguments,
+ where the format string directives are the ones standardized by ISO C99
+ and POSIX. */
+#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)
+# define _GL_ATTRIBUTE_FORMAT_PRINTF(formatstring_parameter, first_argument) \
+ _GL_ATTRIBUTE_FORMAT ((__gnu_printf__, formatstring_parameter, first_argument))
+#else
+# define _GL_ATTRIBUTE_FORMAT_PRINTF(formatstring_parameter, first_argument) \
+ _GL_ATTRIBUTE_FORMAT ((__printf__, formatstring_parameter, first_argument))
+#endif
+
+/* _GL_ATTRIBUTE_FORMAT_PRINTF_SYSTEM is like _GL_ATTRIBUTE_FORMAT_PRINTF,
+ except that it indicates to GCC that the supported format string directives
+ are the ones of the system printf(), rather than the ones standardized by
+ ISO C99 and POSIX. */
+#if GNULIB_PRINTF_ATTRIBUTE_FLAVOR_GNU
+# define _GL_ATTRIBUTE_FORMAT_PRINTF_SYSTEM(formatstring_parameter, first_argument) \
+ _GL_ATTRIBUTE_FORMAT_PRINTF (formatstring_parameter, first_argument)
+#else
+# define _GL_ATTRIBUTE_FORMAT_PRINTF_SYSTEM(formatstring_parameter, first_argument) \
+ _GL_ATTRIBUTE_FORMAT ((__printf__, formatstring_parameter, first_argument))
+#endif
+
+/* _GL_ATTRIBUTE_FORMAT_SCANF
+ indicates to GCC that the function takes a format string and arguments,
+ where the format string directives are the ones standardized by ISO C99
+ and POSIX. */
+#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)
+# define _GL_ATTRIBUTE_FORMAT_SCANF(formatstring_parameter, first_argument) \
+ _GL_ATTRIBUTE_FORMAT ((__gnu_scanf__, formatstring_parameter, first_argument))
+#else
+# define _GL_ATTRIBUTE_FORMAT_SCANF(formatstring_parameter, first_argument) \
+ _GL_ATTRIBUTE_FORMAT ((__scanf__, formatstring_parameter, first_argument))
+#endif
+
+/* _GL_ATTRIBUTE_FORMAT_SCANF_SYSTEM is like _GL_ATTRIBUTE_FORMAT_SCANF,
+ except that it indicates to GCC that the supported format string directives
+ are the ones of the system scanf(), rather than the ones standardized by
+ ISO C99 and POSIX. */
+#define _GL_ATTRIBUTE_FORMAT_SCANF_SYSTEM(formatstring_parameter, first_argument) \
+ _GL_ATTRIBUTE_FORMAT ((__scanf__, formatstring_parameter, first_argument))
+
+/* Solaris 10 declares renameat in <unistd.h>, not in <stdio.h>. */
+/* But in any case avoid namespace pollution on glibc systems. */
+#if (@GNULIB_RENAMEAT@ || defined GNULIB_POSIXCHECK) && defined __sun \
+ && ! defined __GLIBC__
+# include <unistd.h>
+#endif
+
+
+/* The definitions of _GL_FUNCDECL_RPL etc. are copied here. */
+
+/* The definition of _GL_ARG_NONNULL is copied here. */
+
+/* The definition of _GL_WARN_ON_USE is copied here. */
+
+/* Macros for stringification. */
+#define _GL_STDIO_STRINGIZE(token) #token
+#define _GL_STDIO_MACROEXPAND_AND_STRINGIZE(token) _GL_STDIO_STRINGIZE(token)
+
+/* When also using extern inline, suppress the use of static inline in
+ standard headers of problematic Apple configurations, as Libc at
+ least through Libc-825.26 (2013-04-09) mishandles it; see, e.g.,
+ <http://lists.gnu.org/archive/html/bug-gnulib/2012-12/msg00023.html>.
+ Perhaps Apple will fix this some day. */
+#if (defined _GL_EXTERN_INLINE_IN_USE && defined __APPLE__ \
+ && defined __GNUC__ && defined __STDC__)
+# undef putc_unlocked
+#endif
+
+#if @GNULIB_DPRINTF@
+# if @REPLACE_DPRINTF@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define dprintf rpl_dprintf
+# endif
+_GL_FUNCDECL_RPL (dprintf, int, (int fd, const char *format, ...)
+ _GL_ATTRIBUTE_FORMAT_PRINTF (2, 3)
+ _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_RPL (dprintf, int, (int fd, const char *format, ...));
+# else
+# if !@HAVE_DPRINTF@
+_GL_FUNCDECL_SYS (dprintf, int, (int fd, const char *format, ...)
+ _GL_ATTRIBUTE_FORMAT_PRINTF (2, 3)
+ _GL_ARG_NONNULL ((2)));
+# endif
+_GL_CXXALIAS_SYS (dprintf, int, (int fd, const char *format, ...));
+# endif
+_GL_CXXALIASWARN (dprintf);
+#elif defined GNULIB_POSIXCHECK
+# undef dprintf
+# if HAVE_RAW_DECL_DPRINTF
+_GL_WARN_ON_USE (dprintf, "dprintf is unportable - "
+ "use gnulib module dprintf for portability");
+# endif
+#endif
+
+#if @GNULIB_FCLOSE@
+/* Close STREAM and its underlying file descriptor. */
+# if @REPLACE_FCLOSE@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define fclose rpl_fclose
+# endif
+_GL_FUNCDECL_RPL (fclose, int, (FILE *stream) _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (fclose, int, (FILE *stream));
+# else
+_GL_CXXALIAS_SYS (fclose, int, (FILE *stream));
+# endif
+_GL_CXXALIASWARN (fclose);
+#elif defined GNULIB_POSIXCHECK
+# undef fclose
+/* Assume fclose is always declared. */
+_GL_WARN_ON_USE (fclose, "fclose is not always POSIX compliant - "
+ "use gnulib module fclose for portable POSIX compliance");
+#endif
+
+#if @GNULIB_FDOPEN@
+# if @REPLACE_FDOPEN@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef fdopen
+# define fdopen rpl_fdopen
+# endif
+_GL_FUNCDECL_RPL (fdopen, FILE *, (int fd, const char *mode)
+ _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_RPL (fdopen, FILE *, (int fd, const char *mode));
+# else
+_GL_CXXALIAS_SYS (fdopen, FILE *, (int fd, const char *mode));
+# endif
+_GL_CXXALIASWARN (fdopen);
+#elif defined GNULIB_POSIXCHECK
+# undef fdopen
+/* Assume fdopen is always declared. */
+_GL_WARN_ON_USE (fdopen, "fdopen on native Windows platforms is not POSIX compliant - "
+ "use gnulib module fdopen for portability");
+#endif
+
+#if @GNULIB_FFLUSH@
+/* Flush all pending data on STREAM according to POSIX rules. Both
+ output and seekable input streams are supported.
+ Note! LOSS OF DATA can occur if fflush is applied on an input stream
+ that is _not_seekable_ or on an update stream that is _not_seekable_
+ and in which the most recent operation was input. Seekability can
+ be tested with lseek(fileno(fp),0,SEEK_CUR). */
+# if @REPLACE_FFLUSH@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define fflush rpl_fflush
+# endif
+_GL_FUNCDECL_RPL (fflush, int, (FILE *gl_stream));
+_GL_CXXALIAS_RPL (fflush, int, (FILE *gl_stream));
+# else
+_GL_CXXALIAS_SYS (fflush, int, (FILE *gl_stream));
+# endif
+_GL_CXXALIASWARN (fflush);
+#elif defined GNULIB_POSIXCHECK
+# undef fflush
+/* Assume fflush is always declared. */
+_GL_WARN_ON_USE (fflush, "fflush is not always POSIX compliant - "
+ "use gnulib module fflush for portable POSIX compliance");
+#endif
+
+#if @GNULIB_FGETC@
+# if @REPLACE_STDIO_READ_FUNCS@ && @GNULIB_STDIO_H_NONBLOCKING@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef fgetc
+# define fgetc rpl_fgetc
+# endif
+_GL_FUNCDECL_RPL (fgetc, int, (FILE *stream) _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (fgetc, int, (FILE *stream));
+# else
+_GL_CXXALIAS_SYS (fgetc, int, (FILE *stream));
+# endif
+_GL_CXXALIASWARN (fgetc);
+#endif
+
+#if @GNULIB_FGETS@
+# if @REPLACE_STDIO_READ_FUNCS@ && @GNULIB_STDIO_H_NONBLOCKING@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef fgets
+# define fgets rpl_fgets
+# endif
+_GL_FUNCDECL_RPL (fgets, char *, (char *s, int n, FILE *stream)
+ _GL_ARG_NONNULL ((1, 3)));
+_GL_CXXALIAS_RPL (fgets, char *, (char *s, int n, FILE *stream));
+# else
+_GL_CXXALIAS_SYS (fgets, char *, (char *s, int n, FILE *stream));
+# endif
+_GL_CXXALIASWARN (fgets);
+#endif
+
+#if @GNULIB_FOPEN@
+# if @REPLACE_FOPEN@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef fopen
+# define fopen rpl_fopen
+# endif
+_GL_FUNCDECL_RPL (fopen, FILE *, (const char *filename, const char *mode)
+ _GL_ARG_NONNULL ((1, 2)));
+_GL_CXXALIAS_RPL (fopen, FILE *, (const char *filename, const char *mode));
+# else
+_GL_CXXALIAS_SYS (fopen, FILE *, (const char *filename, const char *mode));
+# endif
+_GL_CXXALIASWARN (fopen);
+#elif defined GNULIB_POSIXCHECK
+# undef fopen
+/* Assume fopen is always declared. */
+_GL_WARN_ON_USE (fopen, "fopen on native Windows platforms is not POSIX compliant - "
+ "use gnulib module fopen for portability");
+#endif
+
+#if @GNULIB_FPRINTF_POSIX@ || @GNULIB_FPRINTF@
+# if (@GNULIB_FPRINTF_POSIX@ && @REPLACE_FPRINTF@) \
+ || (@GNULIB_FPRINTF@ && @REPLACE_STDIO_WRITE_FUNCS@ && (@GNULIB_STDIO_H_NONBLOCKING@ || @GNULIB_STDIO_H_SIGPIPE@))
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define fprintf rpl_fprintf
+# endif
+# define GNULIB_overrides_fprintf 1
+# if @GNULIB_FPRINTF_POSIX@ || @GNULIB_VFPRINTF_POSIX@
+_GL_FUNCDECL_RPL (fprintf, int, (FILE *fp, const char *format, ...)
+ _GL_ATTRIBUTE_FORMAT_PRINTF (2, 3)
+ _GL_ARG_NONNULL ((1, 2)));
+# else
+_GL_FUNCDECL_RPL (fprintf, int, (FILE *fp, const char *format, ...)
+ _GL_ATTRIBUTE_FORMAT_PRINTF_SYSTEM (2, 3)
+ _GL_ARG_NONNULL ((1, 2)));
+# endif
+_GL_CXXALIAS_RPL (fprintf, int, (FILE *fp, const char *format, ...));
+# else
+_GL_CXXALIAS_SYS (fprintf, int, (FILE *fp, const char *format, ...));
+# endif
+_GL_CXXALIASWARN (fprintf);
+#endif
+#if !@GNULIB_FPRINTF_POSIX@ && defined GNULIB_POSIXCHECK
+# if !GNULIB_overrides_fprintf
+# undef fprintf
+# endif
+/* Assume fprintf is always declared. */
+_GL_WARN_ON_USE (fprintf, "fprintf is not always POSIX compliant - "
+ "use gnulib module fprintf-posix for portable "
+ "POSIX compliance");
+#endif
+
+#if @GNULIB_FPURGE@
+/* Discard all pending buffered I/O data on STREAM.
+ STREAM must not be wide-character oriented.
+ When discarding pending output, the file position is set back to where it
+ was before the write calls. When discarding pending input, the file
+ position is advanced to match the end of the previously read input.
+ Return 0 if successful. Upon error, return -1 and set errno. */
+# if @REPLACE_FPURGE@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define fpurge rpl_fpurge
+# endif
+_GL_FUNCDECL_RPL (fpurge, int, (FILE *gl_stream) _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (fpurge, int, (FILE *gl_stream));
+# else
+# if !@HAVE_DECL_FPURGE@
+_GL_FUNCDECL_SYS (fpurge, int, (FILE *gl_stream) _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (fpurge, int, (FILE *gl_stream));
+# endif
+_GL_CXXALIASWARN (fpurge);
+#elif defined GNULIB_POSIXCHECK
+# undef fpurge
+# if HAVE_RAW_DECL_FPURGE
+_GL_WARN_ON_USE (fpurge, "fpurge is not always present - "
+ "use gnulib module fpurge for portability");
+# endif
+#endif
+
+#if @GNULIB_FPUTC@
+# if @REPLACE_STDIO_WRITE_FUNCS@ && (@GNULIB_STDIO_H_NONBLOCKING@ || @GNULIB_STDIO_H_SIGPIPE@)
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef fputc
+# define fputc rpl_fputc
+# endif
+_GL_FUNCDECL_RPL (fputc, int, (int c, FILE *stream) _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_RPL (fputc, int, (int c, FILE *stream));
+# else
+_GL_CXXALIAS_SYS (fputc, int, (int c, FILE *stream));
+# endif
+_GL_CXXALIASWARN (fputc);
+#endif
+
+#if @GNULIB_FPUTS@
+# if @REPLACE_STDIO_WRITE_FUNCS@ && (@GNULIB_STDIO_H_NONBLOCKING@ || @GNULIB_STDIO_H_SIGPIPE@)
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef fputs
+# define fputs rpl_fputs
+# endif
+_GL_FUNCDECL_RPL (fputs, int, (const char *string, FILE *stream)
+ _GL_ARG_NONNULL ((1, 2)));
+_GL_CXXALIAS_RPL (fputs, int, (const char *string, FILE *stream));
+# else
+_GL_CXXALIAS_SYS (fputs, int, (const char *string, FILE *stream));
+# endif
+_GL_CXXALIASWARN (fputs);
+#endif
+
+#if @GNULIB_FREAD@
+# if @REPLACE_STDIO_READ_FUNCS@ && @GNULIB_STDIO_H_NONBLOCKING@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef fread
+# define fread rpl_fread
+# endif
+_GL_FUNCDECL_RPL (fread, size_t, (void *ptr, size_t s, size_t n, FILE *stream)
+ _GL_ARG_NONNULL ((4)));
+_GL_CXXALIAS_RPL (fread, size_t, (void *ptr, size_t s, size_t n, FILE *stream));
+# else
+_GL_CXXALIAS_SYS (fread, size_t, (void *ptr, size_t s, size_t n, FILE *stream));
+# endif
+_GL_CXXALIASWARN (fread);
+#endif
+
+#if @GNULIB_FREOPEN@
+# if @REPLACE_FREOPEN@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef freopen
+# define freopen rpl_freopen
+# endif
+_GL_FUNCDECL_RPL (freopen, FILE *,
+ (const char *filename, const char *mode, FILE *stream)
+ _GL_ARG_NONNULL ((2, 3)));
+_GL_CXXALIAS_RPL (freopen, FILE *,
+ (const char *filename, const char *mode, FILE *stream));
+# else
+_GL_CXXALIAS_SYS (freopen, FILE *,
+ (const char *filename, const char *mode, FILE *stream));
+# endif
+_GL_CXXALIASWARN (freopen);
+#elif defined GNULIB_POSIXCHECK
+# undef freopen
+/* Assume freopen is always declared. */
+_GL_WARN_ON_USE (freopen,
+ "freopen on native Windows platforms is not POSIX compliant - "
+ "use gnulib module freopen for portability");
+#endif
+
+#if @GNULIB_FSCANF@
+# if @REPLACE_STDIO_READ_FUNCS@ && @GNULIB_STDIO_H_NONBLOCKING@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef fscanf
+# define fscanf rpl_fscanf
+# endif
+_GL_FUNCDECL_RPL (fscanf, int, (FILE *stream, const char *format, ...)
+ _GL_ATTRIBUTE_FORMAT_SCANF_SYSTEM (2, 3)
+ _GL_ARG_NONNULL ((1, 2)));
+_GL_CXXALIAS_RPL (fscanf, int, (FILE *stream, const char *format, ...));
+# else
+_GL_CXXALIAS_SYS (fscanf, int, (FILE *stream, const char *format, ...));
+# endif
+_GL_CXXALIASWARN (fscanf);
+#endif
+
+
+/* Set up the following warnings, based on which modules are in use.
+ GNU Coding Standards discourage the use of fseek, since it imposes
+ an arbitrary limitation on some 32-bit hosts. Remember that the
+ fseek module depends on the fseeko module, so we only have three
+ cases to consider:
+
+ 1. The developer is not using either module. Issue a warning under
+ GNULIB_POSIXCHECK for both functions, to remind them that both
+ functions have bugs on some systems. _GL_NO_LARGE_FILES has no
+ impact on this warning.
+
+ 2. The developer is using both modules. They may be unaware of the
+ arbitrary limitations of fseek, so issue a warning under
+ GNULIB_POSIXCHECK. On the other hand, they may be using both
+ modules intentionally, so the developer can define
+ _GL_NO_LARGE_FILES in the compilation units where the use of fseek
+ is safe, to silence the warning.
+
+ 3. The developer is using the fseeko module, but not fseek. Gnulib
+ guarantees that fseek will still work around platform bugs in that
+ case, but we presume that the developer is aware of the pitfalls of
+ fseek and was trying to avoid it, so issue a warning even when
+ GNULIB_POSIXCHECK is undefined. Again, _GL_NO_LARGE_FILES can be
+ defined to silence the warning in particular compilation units.
+ In C++ compilations with GNULIB_NAMESPACE, in order to avoid that
+ fseek gets defined as a macro, it is recommended that the developer
+ uses the fseek module, even if he is not calling the fseek function.
+
+ Most gnulib clients that perform stream operations should fall into
+ category 3. */
+
+#if @GNULIB_FSEEK@
+# if defined GNULIB_POSIXCHECK && !defined _GL_NO_LARGE_FILES
+# define _GL_FSEEK_WARN /* Category 2, above. */
+# undef fseek
+# endif
+# if @REPLACE_FSEEK@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef fseek
+# define fseek rpl_fseek
+# endif
+_GL_FUNCDECL_RPL (fseek, int, (FILE *fp, long offset, int whence)
+ _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (fseek, int, (FILE *fp, long offset, int whence));
+# else
+_GL_CXXALIAS_SYS (fseek, int, (FILE *fp, long offset, int whence));
+# endif
+_GL_CXXALIASWARN (fseek);
+#endif
+
+#if @GNULIB_FSEEKO@
+# if !@GNULIB_FSEEK@ && !defined _GL_NO_LARGE_FILES
+# define _GL_FSEEK_WARN /* Category 3, above. */
+# undef fseek
+# endif
+# if @REPLACE_FSEEKO@
+/* Provide an fseeko function that is aware of a preceding fflush(), and which
+ detects pipes. */
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef fseeko
+# define fseeko rpl_fseeko
+# endif
+_GL_FUNCDECL_RPL (fseeko, int, (FILE *fp, off_t offset, int whence)
+ _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (fseeko, int, (FILE *fp, off_t offset, int whence));
+# else
+# if ! @HAVE_DECL_FSEEKO@
+_GL_FUNCDECL_SYS (fseeko, int, (FILE *fp, off_t offset, int whence)
+ _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (fseeko, int, (FILE *fp, off_t offset, int whence));
+# endif
+_GL_CXXALIASWARN (fseeko);
+#elif defined GNULIB_POSIXCHECK
+# define _GL_FSEEK_WARN /* Category 1, above. */
+# undef fseek
+# undef fseeko
+# if HAVE_RAW_DECL_FSEEKO
+_GL_WARN_ON_USE (fseeko, "fseeko is unportable - "
+ "use gnulib module fseeko for portability");
+# endif
+#endif
+
+#ifdef _GL_FSEEK_WARN
+# undef _GL_FSEEK_WARN
+/* Here, either fseek is undefined (but C89 guarantees that it is
+ declared), or it is defined as rpl_fseek (declared above). */
+_GL_WARN_ON_USE (fseek, "fseek cannot handle files larger than 4 GB "
+ "on 32-bit platforms - "
+ "use fseeko function for handling of large files");
+#endif
+
+
+/* ftell, ftello. See the comments on fseek/fseeko. */
+
+#if @GNULIB_FTELL@
+# if defined GNULIB_POSIXCHECK && !defined _GL_NO_LARGE_FILES
+# define _GL_FTELL_WARN /* Category 2, above. */
+# undef ftell
+# endif
+# if @REPLACE_FTELL@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef ftell
+# define ftell rpl_ftell
+# endif
+_GL_FUNCDECL_RPL (ftell, long, (FILE *fp) _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (ftell, long, (FILE *fp));
+# else
+_GL_CXXALIAS_SYS (ftell, long, (FILE *fp));
+# endif
+_GL_CXXALIASWARN (ftell);
+#endif
+
+#if @GNULIB_FTELLO@
+# if !@GNULIB_FTELL@ && !defined _GL_NO_LARGE_FILES
+# define _GL_FTELL_WARN /* Category 3, above. */
+# undef ftell
+# endif
+# if @REPLACE_FTELLO@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef ftello
+# define ftello rpl_ftello
+# endif
+_GL_FUNCDECL_RPL (ftello, off_t, (FILE *fp) _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (ftello, off_t, (FILE *fp));
+# else
+# if ! @HAVE_DECL_FTELLO@
+_GL_FUNCDECL_SYS (ftello, off_t, (FILE *fp) _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (ftello, off_t, (FILE *fp));
+# endif
+_GL_CXXALIASWARN (ftello);
+#elif defined GNULIB_POSIXCHECK
+# define _GL_FTELL_WARN /* Category 1, above. */
+# undef ftell
+# undef ftello
+# if HAVE_RAW_DECL_FTELLO
+_GL_WARN_ON_USE (ftello, "ftello is unportable - "
+ "use gnulib module ftello for portability");
+# endif
+#endif
+
+#ifdef _GL_FTELL_WARN
+# undef _GL_FTELL_WARN
+/* Here, either ftell is undefined (but C89 guarantees that it is
+ declared), or it is defined as rpl_ftell (declared above). */
+_GL_WARN_ON_USE (ftell, "ftell cannot handle files larger than 4 GB "
+ "on 32-bit platforms - "
+ "use ftello function for handling of large files");
+#endif
+
+
+#if @GNULIB_FWRITE@
+# if @REPLACE_STDIO_WRITE_FUNCS@ && (@GNULIB_STDIO_H_NONBLOCKING@ || @GNULIB_STDIO_H_SIGPIPE@)
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef fwrite
+# define fwrite rpl_fwrite
+# endif
+_GL_FUNCDECL_RPL (fwrite, size_t,
+ (const void *ptr, size_t s, size_t n, FILE *stream)
+ _GL_ARG_NONNULL ((1, 4)));
+_GL_CXXALIAS_RPL (fwrite, size_t,
+ (const void *ptr, size_t s, size_t n, FILE *stream));
+# else
+_GL_CXXALIAS_SYS (fwrite, size_t,
+ (const void *ptr, size_t s, size_t n, FILE *stream));
+
+/* Work around bug 11959 when fortifying glibc 2.4 through 2.15
+ <http://sources.redhat.com/bugzilla/show_bug.cgi?id=11959>,
+ which sometimes causes an unwanted diagnostic for fwrite calls.
+ This affects only function declaration attributes under certain
+ versions of gcc and clang, and is not needed for C++. */
+# if (0 < __USE_FORTIFY_LEVEL \
+ && __GLIBC__ == 2 && 4 <= __GLIBC_MINOR__ && __GLIBC_MINOR__ <= 15 \
+ && 3 < __GNUC__ + (4 <= __GNUC_MINOR__) \
+ && !defined __cplusplus)
+# undef fwrite
+# undef fwrite_unlocked
+extern size_t __REDIRECT (rpl_fwrite,
+ (const void *__restrict, size_t, size_t,
+ FILE *__restrict),
+ fwrite);
+extern size_t __REDIRECT (rpl_fwrite_unlocked,
+ (const void *__restrict, size_t, size_t,
+ FILE *__restrict),
+ fwrite_unlocked);
+# define fwrite rpl_fwrite
+# define fwrite_unlocked rpl_fwrite_unlocked
+# endif
+# endif
+_GL_CXXALIASWARN (fwrite);
+#endif
+
+#if @GNULIB_GETC@
+# if @REPLACE_STDIO_READ_FUNCS@ && @GNULIB_STDIO_H_NONBLOCKING@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef getc
+# define getc rpl_fgetc
+# endif
+_GL_FUNCDECL_RPL (fgetc, int, (FILE *stream) _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL_1 (getc, rpl_fgetc, int, (FILE *stream));
+# else
+_GL_CXXALIAS_SYS (getc, int, (FILE *stream));
+# endif
+_GL_CXXALIASWARN (getc);
+#endif
+
+#if @GNULIB_GETCHAR@
+# if @REPLACE_STDIO_READ_FUNCS@ && @GNULIB_STDIO_H_NONBLOCKING@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef getchar
+# define getchar rpl_getchar
+# endif
+_GL_FUNCDECL_RPL (getchar, int, (void));
+_GL_CXXALIAS_RPL (getchar, int, (void));
+# else
+_GL_CXXALIAS_SYS (getchar, int, (void));
+# endif
+_GL_CXXALIASWARN (getchar);
+#endif
+
+#if @GNULIB_GETDELIM@
+/* Read input, up to (and including) the next occurrence of DELIMITER, from
+ STREAM, store it in *LINEPTR (and NUL-terminate it).
+ *LINEPTR is a pointer returned from malloc (or NULL), pointing to *LINESIZE
+ bytes of space. It is realloc'd as necessary.
+ Return the number of bytes read and stored at *LINEPTR (not including the
+ NUL terminator), or -1 on error or EOF. */
+# if @REPLACE_GETDELIM@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef getdelim
+# define getdelim rpl_getdelim
+# endif
+_GL_FUNCDECL_RPL (getdelim, ssize_t,
+ (char **lineptr, size_t *linesize, int delimiter,
+ FILE *stream)
+ _GL_ARG_NONNULL ((1, 2, 4)));
+_GL_CXXALIAS_RPL (getdelim, ssize_t,
+ (char **lineptr, size_t *linesize, int delimiter,
+ FILE *stream));
+# else
+# if !@HAVE_DECL_GETDELIM@
+_GL_FUNCDECL_SYS (getdelim, ssize_t,
+ (char **lineptr, size_t *linesize, int delimiter,
+ FILE *stream)
+ _GL_ARG_NONNULL ((1, 2, 4)));
+# endif
+_GL_CXXALIAS_SYS (getdelim, ssize_t,
+ (char **lineptr, size_t *linesize, int delimiter,
+ FILE *stream));
+# endif
+_GL_CXXALIASWARN (getdelim);
+#elif defined GNULIB_POSIXCHECK
+# undef getdelim
+# if HAVE_RAW_DECL_GETDELIM
+_GL_WARN_ON_USE (getdelim, "getdelim is unportable - "
+ "use gnulib module getdelim for portability");
+# endif
+#endif
+
+#if @GNULIB_GETLINE@
+/* Read a line, up to (and including) the next newline, from STREAM, store it
+ in *LINEPTR (and NUL-terminate it).
+ *LINEPTR is a pointer returned from malloc (or NULL), pointing to *LINESIZE
+ bytes of space. It is realloc'd as necessary.
+ Return the number of bytes read and stored at *LINEPTR (not including the
+ NUL terminator), or -1 on error or EOF. */
+# if @REPLACE_GETLINE@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef getline
+# define getline rpl_getline
+# endif
+_GL_FUNCDECL_RPL (getline, ssize_t,
+ (char **lineptr, size_t *linesize, FILE *stream)
+ _GL_ARG_NONNULL ((1, 2, 3)));
+_GL_CXXALIAS_RPL (getline, ssize_t,
+ (char **lineptr, size_t *linesize, FILE *stream));
+# else
+# if !@HAVE_DECL_GETLINE@
+_GL_FUNCDECL_SYS (getline, ssize_t,
+ (char **lineptr, size_t *linesize, FILE *stream)
+ _GL_ARG_NONNULL ((1, 2, 3)));
+# endif
+_GL_CXXALIAS_SYS (getline, ssize_t,
+ (char **lineptr, size_t *linesize, FILE *stream));
+# endif
+# if @HAVE_DECL_GETLINE@
+_GL_CXXALIASWARN (getline);
+# endif
+#elif defined GNULIB_POSIXCHECK
+# undef getline
+# if HAVE_RAW_DECL_GETLINE
+_GL_WARN_ON_USE (getline, "getline is unportable - "
+ "use gnulib module getline for portability");
+# endif
+#endif
+
+/* It is very rare that the developer ever has full control of stdin,
+ so any use of gets warrants an unconditional warning; besides, C11
+ removed it. */
+#undef gets
+#if HAVE_RAW_DECL_GETS && !defined __cplusplus
+_GL_WARN_ON_USE (gets, "gets is a security hole - use fgets instead");
+#endif
+
+#if @GNULIB_OBSTACK_PRINTF@ || @GNULIB_OBSTACK_PRINTF_POSIX@
+struct obstack;
+/* Grow an obstack with formatted output. Return the number of
+ bytes added to OBS. No trailing nul byte is added, and the
+ object should be closed with obstack_finish before use. Upon
+ memory allocation error, call obstack_alloc_failed_handler. Upon
+ other error, return -1. */
+# if @REPLACE_OBSTACK_PRINTF@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define obstack_printf rpl_obstack_printf
+# endif
+_GL_FUNCDECL_RPL (obstack_printf, int,
+ (struct obstack *obs, const char *format, ...)
+ _GL_ATTRIBUTE_FORMAT_PRINTF (2, 3)
+ _GL_ARG_NONNULL ((1, 2)));
+_GL_CXXALIAS_RPL (obstack_printf, int,
+ (struct obstack *obs, const char *format, ...));
+# else
+# if !@HAVE_DECL_OBSTACK_PRINTF@
+_GL_FUNCDECL_SYS (obstack_printf, int,
+ (struct obstack *obs, const char *format, ...)
+ _GL_ATTRIBUTE_FORMAT_PRINTF (2, 3)
+ _GL_ARG_NONNULL ((1, 2)));
+# endif
+_GL_CXXALIAS_SYS (obstack_printf, int,
+ (struct obstack *obs, const char *format, ...));
+# endif
+_GL_CXXALIASWARN (obstack_printf);
+# if @REPLACE_OBSTACK_PRINTF@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define obstack_vprintf rpl_obstack_vprintf
+# endif
+_GL_FUNCDECL_RPL (obstack_vprintf, int,
+ (struct obstack *obs, const char *format, va_list args)
+ _GL_ATTRIBUTE_FORMAT_PRINTF (2, 0)
+ _GL_ARG_NONNULL ((1, 2)));
+_GL_CXXALIAS_RPL (obstack_vprintf, int,
+ (struct obstack *obs, const char *format, va_list args));
+# else
+# if !@HAVE_DECL_OBSTACK_PRINTF@
+_GL_FUNCDECL_SYS (obstack_vprintf, int,
+ (struct obstack *obs, const char *format, va_list args)
+ _GL_ATTRIBUTE_FORMAT_PRINTF (2, 0)
+ _GL_ARG_NONNULL ((1, 2)));
+# endif
+_GL_CXXALIAS_SYS (obstack_vprintf, int,
+ (struct obstack *obs, const char *format, va_list args));
+# endif
+_GL_CXXALIASWARN (obstack_vprintf);
+#endif
+
+#if @GNULIB_PCLOSE@
+# if !@HAVE_PCLOSE@
+_GL_FUNCDECL_SYS (pclose, int, (FILE *stream) _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (pclose, int, (FILE *stream));
+_GL_CXXALIASWARN (pclose);
+#elif defined GNULIB_POSIXCHECK
+# undef pclose
+# if HAVE_RAW_DECL_PCLOSE
+_GL_WARN_ON_USE (pclose, "pclose is unportable - "
+ "use gnulib module pclose for more portability");
+# endif
+#endif
+
+#if @GNULIB_PERROR@
+/* Print a message to standard error, describing the value of ERRNO,
+ (if STRING is not NULL and not empty) prefixed with STRING and ": ",
+ and terminated with a newline. */
+# if @REPLACE_PERROR@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define perror rpl_perror
+# endif
+_GL_FUNCDECL_RPL (perror, void, (const char *string));
+_GL_CXXALIAS_RPL (perror, void, (const char *string));
+# else
+_GL_CXXALIAS_SYS (perror, void, (const char *string));
+# endif
+_GL_CXXALIASWARN (perror);
+#elif defined GNULIB_POSIXCHECK
+# undef perror
+/* Assume perror is always declared. */
+_GL_WARN_ON_USE (perror, "perror is not always POSIX compliant - "
+ "use gnulib module perror for portability");
+#endif
+
+#if @GNULIB_POPEN@
+# if @REPLACE_POPEN@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef popen
+# define popen rpl_popen
+# endif
+_GL_FUNCDECL_RPL (popen, FILE *, (const char *cmd, const char *mode)
+ _GL_ARG_NONNULL ((1, 2)));
+_GL_CXXALIAS_RPL (popen, FILE *, (const char *cmd, const char *mode));
+# else
+# if !@HAVE_POPEN@
+_GL_FUNCDECL_SYS (popen, FILE *, (const char *cmd, const char *mode)
+ _GL_ARG_NONNULL ((1, 2)));
+# endif
+_GL_CXXALIAS_SYS (popen, FILE *, (const char *cmd, const char *mode));
+# endif
+_GL_CXXALIASWARN (popen);
+#elif defined GNULIB_POSIXCHECK
+# undef popen
+# if HAVE_RAW_DECL_POPEN
+_GL_WARN_ON_USE (popen, "popen is buggy on some platforms - "
+ "use gnulib module popen or pipe for more portability");
+# endif
+#endif
+
+#if @GNULIB_PRINTF_POSIX@ || @GNULIB_PRINTF@
+# if (@GNULIB_PRINTF_POSIX@ && @REPLACE_PRINTF@) \
+ || (@GNULIB_PRINTF@ && @REPLACE_STDIO_WRITE_FUNCS@ && (@GNULIB_STDIO_H_NONBLOCKING@ || @GNULIB_STDIO_H_SIGPIPE@))
+# if defined __GNUC__
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+/* Don't break __attribute__((format(printf,M,N))). */
+# define printf __printf__
+# endif
+# if @GNULIB_PRINTF_POSIX@ || @GNULIB_VFPRINTF_POSIX@
+_GL_FUNCDECL_RPL_1 (__printf__, int,
+ (const char *format, ...)
+ __asm__ (@ASM_SYMBOL_PREFIX@
+ _GL_STDIO_MACROEXPAND_AND_STRINGIZE(rpl_printf))
+ _GL_ATTRIBUTE_FORMAT_PRINTF (1, 2)
+ _GL_ARG_NONNULL ((1)));
+# else
+_GL_FUNCDECL_RPL_1 (__printf__, int,
+ (const char *format, ...)
+ __asm__ (@ASM_SYMBOL_PREFIX@
+ _GL_STDIO_MACROEXPAND_AND_STRINGIZE(rpl_printf))
+ _GL_ATTRIBUTE_FORMAT_PRINTF_SYSTEM (1, 2)
+ _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_RPL_1 (printf, __printf__, int, (const char *format, ...));
+# else
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define printf rpl_printf
+# endif
+_GL_FUNCDECL_RPL (printf, int,
+ (const char *format, ...)
+ _GL_ATTRIBUTE_FORMAT_PRINTF (1, 2)
+ _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (printf, int, (const char *format, ...));
+# endif
+# define GNULIB_overrides_printf 1
+# else
+_GL_CXXALIAS_SYS (printf, int, (const char *format, ...));
+# endif
+_GL_CXXALIASWARN (printf);
+#endif
+#if !@GNULIB_PRINTF_POSIX@ && defined GNULIB_POSIXCHECK
+# if !GNULIB_overrides_printf
+# undef printf
+# endif
+/* Assume printf is always declared. */
+_GL_WARN_ON_USE (printf, "printf is not always POSIX compliant - "
+ "use gnulib module printf-posix for portable "
+ "POSIX compliance");
+#endif
+
+#if @GNULIB_PUTC@
+# if @REPLACE_STDIO_WRITE_FUNCS@ && (@GNULIB_STDIO_H_NONBLOCKING@ || @GNULIB_STDIO_H_SIGPIPE@)
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef putc
+# define putc rpl_fputc
+# endif
+_GL_FUNCDECL_RPL (fputc, int, (int c, FILE *stream) _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_RPL_1 (putc, rpl_fputc, int, (int c, FILE *stream));
+# else
+_GL_CXXALIAS_SYS (putc, int, (int c, FILE *stream));
+# endif
+_GL_CXXALIASWARN (putc);
+#endif
+
+#if @GNULIB_PUTCHAR@
+# if @REPLACE_STDIO_WRITE_FUNCS@ && (@GNULIB_STDIO_H_NONBLOCKING@ || @GNULIB_STDIO_H_SIGPIPE@)
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef putchar
+# define putchar rpl_putchar
+# endif
+_GL_FUNCDECL_RPL (putchar, int, (int c));
+_GL_CXXALIAS_RPL (putchar, int, (int c));
+# else
+_GL_CXXALIAS_SYS (putchar, int, (int c));
+# endif
+_GL_CXXALIASWARN (putchar);
+#endif
+
+#if @GNULIB_PUTS@
+# if @REPLACE_STDIO_WRITE_FUNCS@ && (@GNULIB_STDIO_H_NONBLOCKING@ || @GNULIB_STDIO_H_SIGPIPE@)
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef puts
+# define puts rpl_puts
+# endif
+_GL_FUNCDECL_RPL (puts, int, (const char *string) _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (puts, int, (const char *string));
+# else
+_GL_CXXALIAS_SYS (puts, int, (const char *string));
+# endif
+_GL_CXXALIASWARN (puts);
+#endif
+
+#if @GNULIB_REMOVE@
+# if @REPLACE_REMOVE@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef remove
+# define remove rpl_remove
+# endif
+_GL_FUNCDECL_RPL (remove, int, (const char *name) _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (remove, int, (const char *name));
+# else
+_GL_CXXALIAS_SYS (remove, int, (const char *name));
+# endif
+_GL_CXXALIASWARN (remove);
+#elif defined GNULIB_POSIXCHECK
+# undef remove
+/* Assume remove is always declared. */
+_GL_WARN_ON_USE (remove, "remove cannot handle directories on some platforms - "
+ "use gnulib module remove for more portability");
+#endif
+
+#if @GNULIB_RENAME@
+# if @REPLACE_RENAME@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef rename
+# define rename rpl_rename
+# endif
+_GL_FUNCDECL_RPL (rename, int,
+ (const char *old_filename, const char *new_filename)
+ _GL_ARG_NONNULL ((1, 2)));
+_GL_CXXALIAS_RPL (rename, int,
+ (const char *old_filename, const char *new_filename));
+# else
+_GL_CXXALIAS_SYS (rename, int,
+ (const char *old_filename, const char *new_filename));
+# endif
+_GL_CXXALIASWARN (rename);
+#elif defined GNULIB_POSIXCHECK
+# undef rename
+/* Assume rename is always declared. */
+_GL_WARN_ON_USE (rename, "rename is buggy on some platforms - "
+ "use gnulib module rename for more portability");
+#endif
+
+#if @GNULIB_RENAMEAT@
+# if @REPLACE_RENAMEAT@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef renameat
+# define renameat rpl_renameat
+# endif
+_GL_FUNCDECL_RPL (renameat, int,
+ (int fd1, char const *file1, int fd2, char const *file2)
+ _GL_ARG_NONNULL ((2, 4)));
+_GL_CXXALIAS_RPL (renameat, int,
+ (int fd1, char const *file1, int fd2, char const *file2));
+# else
+# if !@HAVE_RENAMEAT@
+_GL_FUNCDECL_SYS (renameat, int,
+ (int fd1, char const *file1, int fd2, char const *file2)
+ _GL_ARG_NONNULL ((2, 4)));
+# endif
+_GL_CXXALIAS_SYS (renameat, int,
+ (int fd1, char const *file1, int fd2, char const *file2));
+# endif
+_GL_CXXALIASWARN (renameat);
+#elif defined GNULIB_POSIXCHECK
+# undef renameat
+# if HAVE_RAW_DECL_RENAMEAT
+_GL_WARN_ON_USE (renameat, "renameat is not portable - "
+ "use gnulib module renameat for portability");
+# endif
+#endif
+
+#if @GNULIB_SCANF@
+# if @REPLACE_STDIO_READ_FUNCS@ && @GNULIB_STDIO_H_NONBLOCKING@
+# if defined __GNUC__
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef scanf
+/* Don't break __attribute__((format(scanf,M,N))). */
+# define scanf __scanf__
+# endif
+_GL_FUNCDECL_RPL_1 (__scanf__, int,
+ (const char *format, ...)
+ __asm__ (@ASM_SYMBOL_PREFIX@
+ _GL_STDIO_MACROEXPAND_AND_STRINGIZE(rpl_scanf))
+ _GL_ATTRIBUTE_FORMAT_SCANF_SYSTEM (1, 2)
+ _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL_1 (scanf, __scanf__, int, (const char *format, ...));
+# else
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef scanf
+# define scanf rpl_scanf
+# endif
+_GL_FUNCDECL_RPL (scanf, int, (const char *format, ...)
+ _GL_ATTRIBUTE_FORMAT_SCANF_SYSTEM (1, 2)
+ _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (scanf, int, (const char *format, ...));
+# endif
+# else
+_GL_CXXALIAS_SYS (scanf, int, (const char *format, ...));
+# endif
+_GL_CXXALIASWARN (scanf);
+#endif
+
+#if @GNULIB_SNPRINTF@
+# if @REPLACE_SNPRINTF@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define snprintf rpl_snprintf
+# endif
+_GL_FUNCDECL_RPL (snprintf, int,
+ (char *str, size_t size, const char *format, ...)
+ _GL_ATTRIBUTE_FORMAT_PRINTF (3, 4)
+ _GL_ARG_NONNULL ((3)));
+_GL_CXXALIAS_RPL (snprintf, int,
+ (char *str, size_t size, const char *format, ...));
+# else
+# if !@HAVE_DECL_SNPRINTF@
+_GL_FUNCDECL_SYS (snprintf, int,
+ (char *str, size_t size, const char *format, ...)
+ _GL_ATTRIBUTE_FORMAT_PRINTF (3, 4)
+ _GL_ARG_NONNULL ((3)));
+# endif
+_GL_CXXALIAS_SYS (snprintf, int,
+ (char *str, size_t size, const char *format, ...));
+# endif
+_GL_CXXALIASWARN (snprintf);
+#elif defined GNULIB_POSIXCHECK
+# undef snprintf
+# if HAVE_RAW_DECL_SNPRINTF
+_GL_WARN_ON_USE (snprintf, "snprintf is unportable - "
+ "use gnulib module snprintf for portability");
+# endif
+#endif
+
+/* Some people would argue that all sprintf uses should be warned about
+ (for example, OpenBSD issues a link warning for it),
+ since it can cause security holes due to buffer overruns.
+ However, we believe that sprintf can be used safely, and is more
+ efficient than snprintf in those safe cases; and as proof of our
+ belief, we use sprintf in several gnulib modules. So this header
+ intentionally avoids adding a warning to sprintf except when
+ GNULIB_POSIXCHECK is defined. */
+
+#if @GNULIB_SPRINTF_POSIX@
+# if @REPLACE_SPRINTF@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define sprintf rpl_sprintf
+# endif
+_GL_FUNCDECL_RPL (sprintf, int, (char *str, const char *format, ...)
+ _GL_ATTRIBUTE_FORMAT_PRINTF (2, 3)
+ _GL_ARG_NONNULL ((1, 2)));
+_GL_CXXALIAS_RPL (sprintf, int, (char *str, const char *format, ...));
+# else
+_GL_CXXALIAS_SYS (sprintf, int, (char *str, const char *format, ...));
+# endif
+_GL_CXXALIASWARN (sprintf);
+#elif defined GNULIB_POSIXCHECK
+# undef sprintf
+/* Assume sprintf is always declared. */
+_GL_WARN_ON_USE (sprintf, "sprintf is not always POSIX compliant - "
+ "use gnulib module sprintf-posix for portable "
+ "POSIX compliance");
+#endif
+
+#if @GNULIB_TMPFILE@
+# if @REPLACE_TMPFILE@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define tmpfile rpl_tmpfile
+# endif
+_GL_FUNCDECL_RPL (tmpfile, FILE *, (void));
+_GL_CXXALIAS_RPL (tmpfile, FILE *, (void));
+# else
+_GL_CXXALIAS_SYS (tmpfile, FILE *, (void));
+# endif
+_GL_CXXALIASWARN (tmpfile);
+#elif defined GNULIB_POSIXCHECK
+# undef tmpfile
+# if HAVE_RAW_DECL_TMPFILE
+_GL_WARN_ON_USE (tmpfile, "tmpfile is not usable on mingw - "
+ "use gnulib module tmpfile for portability");
+# endif
+#endif
+
+#if @GNULIB_VASPRINTF@
+/* Write formatted output to a string dynamically allocated with malloc().
+ If the memory allocation succeeds, store the address of the string in
+ *RESULT and return the number of resulting bytes, excluding the trailing
+ NUL. Upon memory allocation error, or some other error, return -1. */
+# if @REPLACE_VASPRINTF@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define asprintf rpl_asprintf
+# endif
+_GL_FUNCDECL_RPL (asprintf, int,
+ (char **result, const char *format, ...)
+ _GL_ATTRIBUTE_FORMAT_PRINTF (2, 3)
+ _GL_ARG_NONNULL ((1, 2)));
+_GL_CXXALIAS_RPL (asprintf, int,
+ (char **result, const char *format, ...));
+# else
+# if !@HAVE_VASPRINTF@
+_GL_FUNCDECL_SYS (asprintf, int,
+ (char **result, const char *format, ...)
+ _GL_ATTRIBUTE_FORMAT_PRINTF (2, 3)
+ _GL_ARG_NONNULL ((1, 2)));
+# endif
+_GL_CXXALIAS_SYS (asprintf, int,
+ (char **result, const char *format, ...));
+# endif
+_GL_CXXALIASWARN (asprintf);
+# if @REPLACE_VASPRINTF@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define vasprintf rpl_vasprintf
+# endif
+_GL_FUNCDECL_RPL (vasprintf, int,
+ (char **result, const char *format, va_list args)
+ _GL_ATTRIBUTE_FORMAT_PRINTF (2, 0)
+ _GL_ARG_NONNULL ((1, 2)));
+_GL_CXXALIAS_RPL (vasprintf, int,
+ (char **result, const char *format, va_list args));
+# else
+# if !@HAVE_VASPRINTF@
+_GL_FUNCDECL_SYS (vasprintf, int,
+ (char **result, const char *format, va_list args)
+ _GL_ATTRIBUTE_FORMAT_PRINTF (2, 0)
+ _GL_ARG_NONNULL ((1, 2)));
+# endif
+_GL_CXXALIAS_SYS (vasprintf, int,
+ (char **result, const char *format, va_list args));
+# endif
+_GL_CXXALIASWARN (vasprintf);
+#endif
+
+#if @GNULIB_VDPRINTF@
+# if @REPLACE_VDPRINTF@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define vdprintf rpl_vdprintf
+# endif
+_GL_FUNCDECL_RPL (vdprintf, int, (int fd, const char *format, va_list args)
+ _GL_ATTRIBUTE_FORMAT_PRINTF (2, 0)
+ _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_RPL (vdprintf, int, (int fd, const char *format, va_list args));
+# else
+# if !@HAVE_VDPRINTF@
+_GL_FUNCDECL_SYS (vdprintf, int, (int fd, const char *format, va_list args)
+ _GL_ATTRIBUTE_FORMAT_PRINTF (2, 0)
+ _GL_ARG_NONNULL ((2)));
+# endif
+/* Need to cast, because on Solaris, the third parameter will likely be
+ __va_list args. */
+_GL_CXXALIAS_SYS_CAST (vdprintf, int,
+ (int fd, const char *format, va_list args));
+# endif
+_GL_CXXALIASWARN (vdprintf);
+#elif defined GNULIB_POSIXCHECK
+# undef vdprintf
+# if HAVE_RAW_DECL_VDPRINTF
+_GL_WARN_ON_USE (vdprintf, "vdprintf is unportable - "
+ "use gnulib module vdprintf for portability");
+# endif
+#endif
+
+#if @GNULIB_VFPRINTF_POSIX@ || @GNULIB_VFPRINTF@
+# if (@GNULIB_VFPRINTF_POSIX@ && @REPLACE_VFPRINTF@) \
+ || (@GNULIB_VFPRINTF@ && @REPLACE_STDIO_WRITE_FUNCS@ && (@GNULIB_STDIO_H_NONBLOCKING@ || @GNULIB_STDIO_H_SIGPIPE@))
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define vfprintf rpl_vfprintf
+# endif
+# define GNULIB_overrides_vfprintf 1
+# if @GNULIB_VFPRINTF_POSIX@
+_GL_FUNCDECL_RPL (vfprintf, int, (FILE *fp, const char *format, va_list args)
+ _GL_ATTRIBUTE_FORMAT_PRINTF (2, 0)
+ _GL_ARG_NONNULL ((1, 2)));
+# else
+_GL_FUNCDECL_RPL (vfprintf, int, (FILE *fp, const char *format, va_list args)
+ _GL_ATTRIBUTE_FORMAT_PRINTF_SYSTEM (2, 0)
+ _GL_ARG_NONNULL ((1, 2)));
+# endif
+_GL_CXXALIAS_RPL (vfprintf, int, (FILE *fp, const char *format, va_list args));
+# else
+/* Need to cast, because on Solaris, the third parameter is
+ __va_list args
+ and GCC's fixincludes did not change this to __gnuc_va_list. */
+_GL_CXXALIAS_SYS_CAST (vfprintf, int,
+ (FILE *fp, const char *format, va_list args));
+# endif
+_GL_CXXALIASWARN (vfprintf);
+#endif
+#if !@GNULIB_VFPRINTF_POSIX@ && defined GNULIB_POSIXCHECK
+# if !GNULIB_overrides_vfprintf
+# undef vfprintf
+# endif
+/* Assume vfprintf is always declared. */
+_GL_WARN_ON_USE (vfprintf, "vfprintf is not always POSIX compliant - "
+ "use gnulib module vfprintf-posix for portable "
+ "POSIX compliance");
+#endif
+
+#if @GNULIB_VFSCANF@
+# if @REPLACE_STDIO_READ_FUNCS@ && @GNULIB_STDIO_H_NONBLOCKING@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef vfscanf
+# define vfscanf rpl_vfscanf
+# endif
+_GL_FUNCDECL_RPL (vfscanf, int,
+ (FILE *stream, const char *format, va_list args)
+ _GL_ATTRIBUTE_FORMAT_SCANF_SYSTEM (2, 0)
+ _GL_ARG_NONNULL ((1, 2)));
+_GL_CXXALIAS_RPL (vfscanf, int,
+ (FILE *stream, const char *format, va_list args));
+# else
+_GL_CXXALIAS_SYS (vfscanf, int,
+ (FILE *stream, const char *format, va_list args));
+# endif
+_GL_CXXALIASWARN (vfscanf);
+#endif
+
+#if @GNULIB_VPRINTF_POSIX@ || @GNULIB_VPRINTF@
+# if (@GNULIB_VPRINTF_POSIX@ && @REPLACE_VPRINTF@) \
+ || (@GNULIB_VPRINTF@ && @REPLACE_STDIO_WRITE_FUNCS@ && (@GNULIB_STDIO_H_NONBLOCKING@ || @GNULIB_STDIO_H_SIGPIPE@))
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define vprintf rpl_vprintf
+# endif
+# define GNULIB_overrides_vprintf 1
+# if @GNULIB_VPRINTF_POSIX@ || @GNULIB_VFPRINTF_POSIX@
+_GL_FUNCDECL_RPL (vprintf, int, (const char *format, va_list args)
+ _GL_ATTRIBUTE_FORMAT_PRINTF (1, 0)
+ _GL_ARG_NONNULL ((1)));
+# else
+_GL_FUNCDECL_RPL (vprintf, int, (const char *format, va_list args)
+ _GL_ATTRIBUTE_FORMAT_PRINTF_SYSTEM (1, 0)
+ _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_RPL (vprintf, int, (const char *format, va_list args));
+# else
+/* Need to cast, because on Solaris, the second parameter is
+ __va_list args
+ and GCC's fixincludes did not change this to __gnuc_va_list. */
+_GL_CXXALIAS_SYS_CAST (vprintf, int, (const char *format, va_list args));
+# endif
+_GL_CXXALIASWARN (vprintf);
+#endif
+#if !@GNULIB_VPRINTF_POSIX@ && defined GNULIB_POSIXCHECK
+# if !GNULIB_overrides_vprintf
+# undef vprintf
+# endif
+/* Assume vprintf is always declared. */
+_GL_WARN_ON_USE (vprintf, "vprintf is not always POSIX compliant - "
+ "use gnulib module vprintf-posix for portable "
+ "POSIX compliance");
+#endif
+
+#if @GNULIB_VSCANF@
+# if @REPLACE_STDIO_READ_FUNCS@ && @GNULIB_STDIO_H_NONBLOCKING@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef vscanf
+# define vscanf rpl_vscanf
+# endif
+_GL_FUNCDECL_RPL (vscanf, int, (const char *format, va_list args)
+ _GL_ATTRIBUTE_FORMAT_SCANF_SYSTEM (1, 0)
+ _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (vscanf, int, (const char *format, va_list args));
+# else
+_GL_CXXALIAS_SYS (vscanf, int, (const char *format, va_list args));
+# endif
+_GL_CXXALIASWARN (vscanf);
+#endif
+
+#if @GNULIB_VSNPRINTF@
+# if @REPLACE_VSNPRINTF@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define vsnprintf rpl_vsnprintf
+# endif
+_GL_FUNCDECL_RPL (vsnprintf, int,
+ (char *str, size_t size, const char *format, va_list args)
+ _GL_ATTRIBUTE_FORMAT_PRINTF (3, 0)
+ _GL_ARG_NONNULL ((3)));
+_GL_CXXALIAS_RPL (vsnprintf, int,
+ (char *str, size_t size, const char *format, va_list args));
+# else
+# if !@HAVE_DECL_VSNPRINTF@
+_GL_FUNCDECL_SYS (vsnprintf, int,
+ (char *str, size_t size, const char *format, va_list args)
+ _GL_ATTRIBUTE_FORMAT_PRINTF (3, 0)
+ _GL_ARG_NONNULL ((3)));
+# endif
+_GL_CXXALIAS_SYS (vsnprintf, int,
+ (char *str, size_t size, const char *format, va_list args));
+# endif
+_GL_CXXALIASWARN (vsnprintf);
+#elif defined GNULIB_POSIXCHECK
+# undef vsnprintf
+# if HAVE_RAW_DECL_VSNPRINTF
+_GL_WARN_ON_USE (vsnprintf, "vsnprintf is unportable - "
+ "use gnulib module vsnprintf for portability");
+# endif
+#endif
+
+#if @GNULIB_VSPRINTF_POSIX@
+# if @REPLACE_VSPRINTF@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define vsprintf rpl_vsprintf
+# endif
+_GL_FUNCDECL_RPL (vsprintf, int,
+ (char *str, const char *format, va_list args)
+ _GL_ATTRIBUTE_FORMAT_PRINTF (2, 0)
+ _GL_ARG_NONNULL ((1, 2)));
+_GL_CXXALIAS_RPL (vsprintf, int,
+ (char *str, const char *format, va_list args));
+# else
+/* Need to cast, because on Solaris, the third parameter is
+ __va_list args
+ and GCC's fixincludes did not change this to __gnuc_va_list. */
+_GL_CXXALIAS_SYS_CAST (vsprintf, int,
+ (char *str, const char *format, va_list args));
+# endif
+_GL_CXXALIASWARN (vsprintf);
+#elif defined GNULIB_POSIXCHECK
+# undef vsprintf
+/* Assume vsprintf is always declared. */
+_GL_WARN_ON_USE (vsprintf, "vsprintf is not always POSIX compliant - "
+ "use gnulib module vsprintf-posix for portable "
+ "POSIX compliance");
+#endif
+
+#endif /* _@GUARD_PREFIX@_STDIO_H */
+#endif /* _@GUARD_PREFIX@_STDIO_H */
+#endif
diff --git a/lib/stdio_.h b/lib/stdio_.h
deleted file mode 100644
index 441c0d5..0000000
--- a/lib/stdio_.h
+++ /dev/null
@@ -1,192 +0,0 @@
-/* A GNU-like <stdio.h>.
-
- Copyright (C) 2004, 2007 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-#if defined __need_FILE || defined __need___FILE
-/* Special invocation convention inside glibc header files. */
-
-#include @ABSOLUTE_STDIO_H@
-
-#else
-/* Normal invocation convention. */
-#ifndef _GL_STDIO_H
-#define _GL_STDIO_H
-
-#include @ABSOLUTE_STDIO_H@
-
-#include <stdarg.h>
-#include <stddef.h>
-
-#ifndef __attribute__
-/* This feature is available in gcc versions 2.5 and later. */
-# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 5) || __STRICT_ANSI__
-# define __attribute__(Spec) /* empty */
-# endif
-/* The __-protected variants of `format' and `printf' attributes
- are accepted by gcc versions 2.6.4 (effectively 2.7) and later. */
-# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 7)
-# define __format__ format
-# define __printf__ printf
-# endif
-#endif
-
-
-/* The definition of GL_LINK_WARNING is copied here. */
-
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-#if @GNULIB_FPRINTF_POSIX@
-# if @REPLACE_FPRINTF@
-# define fprintf rpl_fprintf
-extern int fprintf (FILE *fp, const char *format, ...)
- __attribute__ ((__format__ (__printf__, 2, 3)));
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef fprintf
-# define fprintf \
- (GL_LINK_WARNING ("fprintf is not always POSIX compliant - " \
- "use gnulib module fprintf-posix for portable " \
- "POSIX compliance"), \
- fprintf)
-#endif
-
-#if @GNULIB_VFPRINTF_POSIX@
-# if @REPLACE_VFPRINTF@
-# define vfprintf rpl_vfprintf
-extern int vfprintf (FILE *fp, const char *format, va_list args)
- __attribute__ ((__format__ (__printf__, 2, 0)));
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef vfprintf
-# define vfprintf(s,f,a) \
- (GL_LINK_WARNING ("vfprintf is not always POSIX compliant - " \
- "use gnulib module vfprintf-posix for portable " \
- "POSIX compliance"), \
- vfprintf (s, f, a))
-#endif
-
-#if @GNULIB_PRINTF_POSIX@
-# if @REPLACE_PRINTF@
-/* Don't break __attribute__((format(printf,M,N))). */
-# define printf __printf__
-extern int printf (const char *format, ...)
- __attribute__ ((__format__ (__printf__, 1, 2)));
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef printf
-# define printf \
- (GL_LINK_WARNING ("printf is not always POSIX compliant - " \
- "use gnulib module printf-posix for portable " \
- "POSIX compliance"), \
- printf)
-/* Don't break __attribute__((format(printf,M,N))). */
-# define format(kind,m,n) format (__##kind##__, m, n)
-# define __format__(kind,m,n) __format__ (__##kind##__, m, n)
-# define ____printf____ __printf__
-# define ____scanf____ __scanf__
-# define ____strftime____ __strftime__
-# define ____strfmon____ __strfmon__
-#endif
-
-#if @GNULIB_VPRINTF_POSIX@
-# if @REPLACE_VPRINTF@
-# define vprintf rpl_vprintf
-extern int vprintf (const char *format, va_list args)
- __attribute__ ((__format__ (__printf__, 1, 0)));
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef vprintf
-# define vprintf(f,a) \
- (GL_LINK_WARNING ("vprintf is not always POSIX compliant - " \
- "use gnulib module vprintf-posix for portable " \
- "POSIX compliance"), \
- vprintf (f, a))
-#endif
-
-#if @GNULIB_SNPRINTF@
-# if @REPLACE_SNPRINTF@
-# define snprintf rpl_snprintf
-# endif
-# if @REPLACE_SNPRINTF@ || !@HAVE_DECL_SNPRINTF@
-extern int snprintf (char *str, size_t size, const char *format, ...)
- __attribute__ ((__format__ (__printf__, 3, 4)));
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef snprintf
-# define snprintf \
- (GL_LINK_WARNING ("snprintf is unportable - " \
- "use gnulib module snprintf for portability"), \
- snprintf)
-#endif
-
-#if @GNULIB_VSNPRINTF@
-# if @REPLACE_VSNPRINTF@
-# define vsnprintf rpl_vsnprintf
-# endif
-# if @REPLACE_VSNPRINTF@ || !@HAVE_DECL_VSNPRINTF@
-extern int vsnprintf (char *str, size_t size, const char *format, va_list args)
- __attribute__ ((__format__ (__printf__, 3, 0)));
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef vsnprintf
-# define vsnprintf(b,s,f,a) \
- (GL_LINK_WARNING ("vsnprintf is unportable - " \
- "use gnulib module vsnprintf for portability"), \
- vsnprintf (b, s, f, a))
-#endif
-
-#if @GNULIB_SPRINTF_POSIX@
-# if @REPLACE_SPRINTF@
-# define sprintf rpl_sprintf
-extern int sprintf (char *str, const char *format, ...)
- __attribute__ ((__format__ (__printf__, 2, 3)));
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef sprintf
-# define sprintf \
- (GL_LINK_WARNING ("sprintf is not always POSIX compliant - " \
- "use gnulib module sprintf-posix for portable " \
- "POSIX compliance"), \
- sprintf)
-#endif
-
-#if @GNULIB_VSPRINTF_POSIX@
-# if @REPLACE_VSPRINTF@
-# define vsprintf rpl_vsprintf
-extern int vsprintf (char *str, const char *format, va_list args)
- __attribute__ ((__format__ (__printf__, 2, 0)));
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef vsprintf
-# define vsprintf(b,f,a) \
- (GL_LINK_WARNING ("vsprintf is not always POSIX compliant - " \
- "use gnulib module vsprintf-posix for portable " \
- "POSIX compliance"), \
- vsprintf (b, f, a))
-#endif
-
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _GL_STDIO_H */
-#endif
diff --git a/lib/stdlib--.h b/lib/stdlib--.h
index 61d6ebe..af83455 100644
--- a/lib/stdlib--.h
+++ b/lib/stdlib--.h
@@ -1,11 +1,11 @@
/* Like stdlib.h, but redefine some names to avoid glitches.
- Copyright (C) 2005, 2006, 2007 Free Software Foundation, Inc.
+ Copyright (C) 2005-2007, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
@@ -23,3 +22,15 @@
#undef mkstemp
#define mkstemp mkstemp_safer
+
+#if GNULIB_MKOSTEMP
+# define mkostemp mkostemp_safer
+#endif
+
+#if GNULIB_MKOSTEMPS
+# define mkostemps mkostemps_safer
+#endif
+
+#if GNULIB_MKSTEMPS
+# define mkstemps mkstemps_safer
+#endif
diff --git a/lib/stdlib-safer.h b/lib/stdlib-safer.h
index 8b1a7e1..91294f4 100644
--- a/lib/stdlib-safer.h
+++ b/lib/stdlib-safer.h
@@ -1,11 +1,11 @@
/* Invoke stdlib.h functions, but avoid some glitches.
- Copyright (C) 2005 Free Software Foundation, Inc.
+ Copyright (C) 2005, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,9 +13,20 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
int mkstemp_safer (char *);
+
+#if GNULIB_MKOSTEMP
+int mkostemp_safer (char *, int);
+#endif
+
+#if GNULIB_MKOSTEMPS
+int mkostemps_safer (char *, int, int);
+#endif
+
+#if GNULIB_MKSTEMPS
+int mkstemps_safer (char *, int);
+#endif
diff --git a/lib/stdlib.in.h b/lib/stdlib.in.h
new file mode 100644
index 0000000..70dc88d
--- /dev/null
+++ b/lib/stdlib.in.h
@@ -0,0 +1,977 @@
+/* A GNU-like <stdlib.h>.
+
+ Copyright (C) 1995, 2001-2004, 2006-2016 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 <http://www.gnu.org/licenses/>. */
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+#if defined __need_system_stdlib_h || defined __need_malloc_and_calloc
+/* Special invocation conventions inside some gnulib header files,
+ and inside some glibc header files, respectively. */
+
+#@INCLUDE_NEXT@ @NEXT_STDLIB_H@
+
+#else
+/* Normal invocation convention. */
+
+#ifndef _@GUARD_PREFIX@_STDLIB_H
+
+/* The include_next requires a split double-inclusion guard. */
+#@INCLUDE_NEXT@ @NEXT_STDLIB_H@
+
+#ifndef _@GUARD_PREFIX@_STDLIB_H
+#define _@GUARD_PREFIX@_STDLIB_H
+
+/* NetBSD 5.0 mis-defines NULL. */
+#include <stddef.h>
+
+/* MirBSD 10 defines WEXITSTATUS in <sys/wait.h>, not in <stdlib.h>. */
+#if @GNULIB_SYSTEM_POSIX@ && !defined WEXITSTATUS
+# include <sys/wait.h>
+#endif
+
+/* Solaris declares getloadavg() in <sys/loadavg.h>. */
+#if (@GNULIB_GETLOADAVG@ || defined GNULIB_POSIXCHECK) && @HAVE_SYS_LOADAVG_H@
+# include <sys/loadavg.h>
+#endif
+
+/* Native Windows platforms declare mktemp() in <io.h>. */
+#if 0 && ((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__)
+# include <io.h>
+#endif
+
+#if @GNULIB_RANDOM_R@
+
+/* OSF/1 5.1 declares 'struct random_data' in <random.h>, which is included
+ from <stdlib.h> if _REENTRANT is defined. Include it whenever we need
+ 'struct random_data'. */
+# if @HAVE_RANDOM_H@
+# include <random.h>
+# endif
+
+# if !@HAVE_STRUCT_RANDOM_DATA@ || @REPLACE_RANDOM_R@ || !@HAVE_RANDOM_R@
+# include <stdint.h>
+# endif
+
+# if !@HAVE_STRUCT_RANDOM_DATA@
+/* Define 'struct random_data'.
+ But allow multiple gnulib generated <stdlib.h> replacements to coexist. */
+# if !GNULIB_defined_struct_random_data
+struct random_data
+{
+ int32_t *fptr; /* Front pointer. */
+ int32_t *rptr; /* Rear pointer. */
+ int32_t *state; /* Array of state values. */
+ int rand_type; /* Type of random number generator. */
+ int rand_deg; /* Degree of random number generator. */
+ int rand_sep; /* Distance between front and rear. */
+ int32_t *end_ptr; /* Pointer behind state table. */
+};
+# define GNULIB_defined_struct_random_data 1
+# endif
+# endif
+#endif
+
+#if (@GNULIB_MKSTEMP@ || @GNULIB_MKSTEMPS@ || @GNULIB_GETSUBOPT@ || defined GNULIB_POSIXCHECK) && ! defined __GLIBC__ && !((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__)
+/* On Mac OS X 10.3, only <unistd.h> declares mkstemp. */
+/* On Mac OS X 10.5, only <unistd.h> declares mkstemps. */
+/* On Cygwin 1.7.1, only <unistd.h> declares getsubopt. */
+/* But avoid namespace pollution on glibc systems and native Windows. */
+# include <unistd.h>
+#endif
+
+/* The __attribute__ feature is available in gcc versions 2.5 and later.
+ The attribute __pure__ was added in gcc 2.96. */
+#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96)
+# define _GL_ATTRIBUTE_PURE __attribute__ ((__pure__))
+#else
+# define _GL_ATTRIBUTE_PURE /* empty */
+#endif
+
+/* The definition of _Noreturn is copied here. */
+
+/* The definitions of _GL_FUNCDECL_RPL etc. are copied here. */
+
+/* The definition of _GL_ARG_NONNULL is copied here. */
+
+/* The definition of _GL_WARN_ON_USE is copied here. */
+
+
+/* Some systems do not define EXIT_*, despite otherwise supporting C89. */
+#ifndef EXIT_SUCCESS
+# define EXIT_SUCCESS 0
+#endif
+/* Tandem/NSK and other platforms that define EXIT_FAILURE as -1 interfere
+ with proper operation of xargs. */
+#ifndef EXIT_FAILURE
+# define EXIT_FAILURE 1
+#elif EXIT_FAILURE != 1
+# undef EXIT_FAILURE
+# define EXIT_FAILURE 1
+#endif
+
+
+#if @GNULIB__EXIT@
+/* Terminate the current process with the given return code, without running
+ the 'atexit' handlers. */
+# if !@HAVE__EXIT@
+_GL_FUNCDECL_SYS (_Exit, _Noreturn void, (int status));
+# endif
+_GL_CXXALIAS_SYS (_Exit, void, (int status));
+_GL_CXXALIASWARN (_Exit);
+#elif defined GNULIB_POSIXCHECK
+# undef _Exit
+# if HAVE_RAW_DECL__EXIT
+_GL_WARN_ON_USE (_Exit, "_Exit is unportable - "
+ "use gnulib module _Exit for portability");
+# endif
+#endif
+
+
+#if @GNULIB_ATOLL@
+/* Parse a signed decimal integer.
+ Returns the value of the integer. Errors are not detected. */
+# if !@HAVE_ATOLL@
+_GL_FUNCDECL_SYS (atoll, long long, (const char *string)
+ _GL_ATTRIBUTE_PURE
+ _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (atoll, long long, (const char *string));
+_GL_CXXALIASWARN (atoll);
+#elif defined GNULIB_POSIXCHECK
+# undef atoll
+# if HAVE_RAW_DECL_ATOLL
+_GL_WARN_ON_USE (atoll, "atoll is unportable - "
+ "use gnulib module atoll for portability");
+# endif
+#endif
+
+#if @GNULIB_CALLOC_POSIX@
+# if @REPLACE_CALLOC@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef calloc
+# define calloc rpl_calloc
+# endif
+_GL_FUNCDECL_RPL (calloc, void *, (size_t nmemb, size_t size));
+_GL_CXXALIAS_RPL (calloc, void *, (size_t nmemb, size_t size));
+# else
+_GL_CXXALIAS_SYS (calloc, void *, (size_t nmemb, size_t size));
+# endif
+_GL_CXXALIASWARN (calloc);
+#elif defined GNULIB_POSIXCHECK
+# undef calloc
+/* Assume calloc is always declared. */
+_GL_WARN_ON_USE (calloc, "calloc is not POSIX compliant everywhere - "
+ "use gnulib module calloc-posix for portability");
+#endif
+
+#if @GNULIB_CANONICALIZE_FILE_NAME@
+# if @REPLACE_CANONICALIZE_FILE_NAME@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define canonicalize_file_name rpl_canonicalize_file_name
+# endif
+_GL_FUNCDECL_RPL (canonicalize_file_name, char *, (const char *name)
+ _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (canonicalize_file_name, char *, (const char *name));
+# else
+# if !@HAVE_CANONICALIZE_FILE_NAME@
+_GL_FUNCDECL_SYS (canonicalize_file_name, char *, (const char *name)
+ _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (canonicalize_file_name, char *, (const char *name));
+# endif
+_GL_CXXALIASWARN (canonicalize_file_name);
+#elif defined GNULIB_POSIXCHECK
+# undef canonicalize_file_name
+# if HAVE_RAW_DECL_CANONICALIZE_FILE_NAME
+_GL_WARN_ON_USE (canonicalize_file_name,
+ "canonicalize_file_name is unportable - "
+ "use gnulib module canonicalize-lgpl for portability");
+# endif
+#endif
+
+#if @GNULIB_GETLOADAVG@
+/* Store max(NELEM,3) load average numbers in LOADAVG[].
+ The three numbers are the load average of the last 1 minute, the last 5
+ minutes, and the last 15 minutes, respectively.
+ LOADAVG is an array of NELEM numbers. */
+# if !@HAVE_DECL_GETLOADAVG@
+_GL_FUNCDECL_SYS (getloadavg, int, (double loadavg[], int nelem)
+ _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (getloadavg, int, (double loadavg[], int nelem));
+_GL_CXXALIASWARN (getloadavg);
+#elif defined GNULIB_POSIXCHECK
+# undef getloadavg
+# if HAVE_RAW_DECL_GETLOADAVG
+_GL_WARN_ON_USE (getloadavg, "getloadavg is not portable - "
+ "use gnulib module getloadavg for portability");
+# endif
+#endif
+
+#if @GNULIB_GETSUBOPT@
+/* Assuming *OPTIONP is a comma separated list of elements of the form
+ "token" or "token=value", getsubopt parses the first of these elements.
+ If the first element refers to a "token" that is member of the given
+ NULL-terminated array of tokens:
+ - It replaces the comma with a NUL byte, updates *OPTIONP to point past
+ the first option and the comma, sets *VALUEP to the value of the
+ element (or NULL if it doesn't contain an "=" sign),
+ - It returns the index of the "token" in the given array of tokens.
+ Otherwise it returns -1, and *OPTIONP and *VALUEP are undefined.
+ For more details see the POSIX:2001 specification.
+ http://www.opengroup.org/susv3xsh/getsubopt.html */
+# if !@HAVE_GETSUBOPT@
+_GL_FUNCDECL_SYS (getsubopt, int,
+ (char **optionp, char *const *tokens, char **valuep)
+ _GL_ARG_NONNULL ((1, 2, 3)));
+# endif
+_GL_CXXALIAS_SYS (getsubopt, int,
+ (char **optionp, char *const *tokens, char **valuep));
+_GL_CXXALIASWARN (getsubopt);
+#elif defined GNULIB_POSIXCHECK
+# undef getsubopt
+# if HAVE_RAW_DECL_GETSUBOPT
+_GL_WARN_ON_USE (getsubopt, "getsubopt is unportable - "
+ "use gnulib module getsubopt for portability");
+# endif
+#endif
+
+#if @GNULIB_GRANTPT@
+/* Change the ownership and access permission of the slave side of the
+ pseudo-terminal whose master side is specified by FD. */
+# if !@HAVE_GRANTPT@
+_GL_FUNCDECL_SYS (grantpt, int, (int fd));
+# endif
+_GL_CXXALIAS_SYS (grantpt, int, (int fd));
+_GL_CXXALIASWARN (grantpt);
+#elif defined GNULIB_POSIXCHECK
+# undef grantpt
+# if HAVE_RAW_DECL_GRANTPT
+_GL_WARN_ON_USE (grantpt, "grantpt is not portable - "
+ "use gnulib module grantpt for portability");
+# endif
+#endif
+
+/* If _GL_USE_STDLIB_ALLOC is nonzero, the including module does not
+ rely on GNU or POSIX semantics for malloc and realloc (for example,
+ by never specifying a zero size), so it does not need malloc or
+ realloc to be redefined. */
+#if @GNULIB_MALLOC_POSIX@
+# if @REPLACE_MALLOC@
+# if !((defined __cplusplus && defined GNULIB_NAMESPACE) \
+ || _GL_USE_STDLIB_ALLOC)
+# undef malloc
+# define malloc rpl_malloc
+# endif
+_GL_FUNCDECL_RPL (malloc, void *, (size_t size));
+_GL_CXXALIAS_RPL (malloc, void *, (size_t size));
+# else
+_GL_CXXALIAS_SYS (malloc, void *, (size_t size));
+# endif
+_GL_CXXALIASWARN (malloc);
+#elif defined GNULIB_POSIXCHECK && !_GL_USE_STDLIB_ALLOC
+# undef malloc
+/* Assume malloc is always declared. */
+_GL_WARN_ON_USE (malloc, "malloc is not POSIX compliant everywhere - "
+ "use gnulib module malloc-posix for portability");
+#endif
+
+/* Convert a multibyte character to a wide character. */
+#if @GNULIB_MBTOWC@
+# if @REPLACE_MBTOWC@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef mbtowc
+# define mbtowc rpl_mbtowc
+# endif
+_GL_FUNCDECL_RPL (mbtowc, int, (wchar_t *pwc, const char *s, size_t n));
+_GL_CXXALIAS_RPL (mbtowc, int, (wchar_t *pwc, const char *s, size_t n));
+# else
+_GL_CXXALIAS_SYS (mbtowc, int, (wchar_t *pwc, const char *s, size_t n));
+# endif
+_GL_CXXALIASWARN (mbtowc);
+#endif
+
+#if @GNULIB_MKDTEMP@
+/* Create a unique temporary directory from TEMPLATE.
+ The last six characters of TEMPLATE must be "XXXXXX";
+ they are replaced with a string that makes the directory name unique.
+ Returns TEMPLATE, or a null pointer if it cannot get a unique name.
+ The directory is created mode 700. */
+# if !@HAVE_MKDTEMP@
+_GL_FUNCDECL_SYS (mkdtemp, char *, (char * /*template*/) _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (mkdtemp, char *, (char * /*template*/));
+_GL_CXXALIASWARN (mkdtemp);
+#elif defined GNULIB_POSIXCHECK
+# undef mkdtemp
+# if HAVE_RAW_DECL_MKDTEMP
+_GL_WARN_ON_USE (mkdtemp, "mkdtemp is unportable - "
+ "use gnulib module mkdtemp for portability");
+# endif
+#endif
+
+#if @GNULIB_MKOSTEMP@
+/* Create a unique temporary file from TEMPLATE.
+ The last six characters of TEMPLATE must be "XXXXXX";
+ they are replaced with a string that makes the file name unique.
+ The flags are a bitmask, possibly including O_CLOEXEC (defined in <fcntl.h>)
+ and O_TEXT, O_BINARY (defined in "binary-io.h").
+ The file is then created, with the specified flags, ensuring it didn't exist
+ before.
+ The file is created read-write (mask at least 0600 & ~umask), but it may be
+ world-readable and world-writable (mask 0666 & ~umask), depending on the
+ implementation.
+ Returns the open file descriptor if successful, otherwise -1 and errno
+ set. */
+# if !@HAVE_MKOSTEMP@
+_GL_FUNCDECL_SYS (mkostemp, int, (char * /*template*/, int /*flags*/)
+ _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (mkostemp, int, (char * /*template*/, int /*flags*/));
+_GL_CXXALIASWARN (mkostemp);
+#elif defined GNULIB_POSIXCHECK
+# undef mkostemp
+# if HAVE_RAW_DECL_MKOSTEMP
+_GL_WARN_ON_USE (mkostemp, "mkostemp is unportable - "
+ "use gnulib module mkostemp for portability");
+# endif
+#endif
+
+#if @GNULIB_MKOSTEMPS@
+/* Create a unique temporary file from TEMPLATE.
+ The last six characters of TEMPLATE before a suffix of length
+ SUFFIXLEN must be "XXXXXX";
+ they are replaced with a string that makes the file name unique.
+ The flags are a bitmask, possibly including O_CLOEXEC (defined in <fcntl.h>)
+ and O_TEXT, O_BINARY (defined in "binary-io.h").
+ The file is then created, with the specified flags, ensuring it didn't exist
+ before.
+ The file is created read-write (mask at least 0600 & ~umask), but it may be
+ world-readable and world-writable (mask 0666 & ~umask), depending on the
+ implementation.
+ Returns the open file descriptor if successful, otherwise -1 and errno
+ set. */
+# if !@HAVE_MKOSTEMPS@
+_GL_FUNCDECL_SYS (mkostemps, int,
+ (char * /*template*/, int /*suffixlen*/, int /*flags*/)
+ _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (mkostemps, int,
+ (char * /*template*/, int /*suffixlen*/, int /*flags*/));
+_GL_CXXALIASWARN (mkostemps);
+#elif defined GNULIB_POSIXCHECK
+# undef mkostemps
+# if HAVE_RAW_DECL_MKOSTEMPS
+_GL_WARN_ON_USE (mkostemps, "mkostemps is unportable - "
+ "use gnulib module mkostemps for portability");
+# endif
+#endif
+
+#if @GNULIB_MKSTEMP@
+/* Create a unique temporary file from TEMPLATE.
+ The last six characters of TEMPLATE must be "XXXXXX";
+ they are replaced with a string that makes the file name unique.
+ The file is then created, ensuring it didn't exist before.
+ The file is created read-write (mask at least 0600 & ~umask), but it may be
+ world-readable and world-writable (mask 0666 & ~umask), depending on the
+ implementation.
+ Returns the open file descriptor if successful, otherwise -1 and errno
+ set. */
+# if @REPLACE_MKSTEMP@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define mkstemp rpl_mkstemp
+# endif
+_GL_FUNCDECL_RPL (mkstemp, int, (char * /*template*/) _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (mkstemp, int, (char * /*template*/));
+# else
+# if ! @HAVE_MKSTEMP@
+_GL_FUNCDECL_SYS (mkstemp, int, (char * /*template*/) _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (mkstemp, int, (char * /*template*/));
+# endif
+_GL_CXXALIASWARN (mkstemp);
+#elif defined GNULIB_POSIXCHECK
+# undef mkstemp
+# if HAVE_RAW_DECL_MKSTEMP
+_GL_WARN_ON_USE (mkstemp, "mkstemp is unportable - "
+ "use gnulib module mkstemp for portability");
+# endif
+#endif
+
+#if @GNULIB_MKSTEMPS@
+/* Create a unique temporary file from TEMPLATE.
+ The last six characters of TEMPLATE prior to a suffix of length
+ SUFFIXLEN must be "XXXXXX";
+ they are replaced with a string that makes the file name unique.
+ The file is then created, ensuring it didn't exist before.
+ The file is created read-write (mask at least 0600 & ~umask), but it may be
+ world-readable and world-writable (mask 0666 & ~umask), depending on the
+ implementation.
+ Returns the open file descriptor if successful, otherwise -1 and errno
+ set. */
+# if !@HAVE_MKSTEMPS@
+_GL_FUNCDECL_SYS (mkstemps, int, (char * /*template*/, int /*suffixlen*/)
+ _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (mkstemps, int, (char * /*template*/, int /*suffixlen*/));
+_GL_CXXALIASWARN (mkstemps);
+#elif defined GNULIB_POSIXCHECK
+# undef mkstemps
+# if HAVE_RAW_DECL_MKSTEMPS
+_GL_WARN_ON_USE (mkstemps, "mkstemps is unportable - "
+ "use gnulib module mkstemps for portability");
+# endif
+#endif
+
+#if @GNULIB_POSIX_OPENPT@
+/* Return an FD open to the master side of a pseudo-terminal. Flags should
+ include O_RDWR, and may also include O_NOCTTY. */
+# if !@HAVE_POSIX_OPENPT@
+_GL_FUNCDECL_SYS (posix_openpt, int, (int flags));
+# endif
+_GL_CXXALIAS_SYS (posix_openpt, int, (int flags));
+_GL_CXXALIASWARN (posix_openpt);
+#elif defined GNULIB_POSIXCHECK
+# undef posix_openpt
+# if HAVE_RAW_DECL_POSIX_OPENPT
+_GL_WARN_ON_USE (posix_openpt, "posix_openpt is not portable - "
+ "use gnulib module posix_openpt for portability");
+# endif
+#endif
+
+#if @GNULIB_PTSNAME@
+/* Return the pathname of the pseudo-terminal slave associated with
+ the master FD is open on, or NULL on errors. */
+# if @REPLACE_PTSNAME@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef ptsname
+# define ptsname rpl_ptsname
+# endif
+_GL_FUNCDECL_RPL (ptsname, char *, (int fd));
+_GL_CXXALIAS_RPL (ptsname, char *, (int fd));
+# else
+# if !@HAVE_PTSNAME@
+_GL_FUNCDECL_SYS (ptsname, char *, (int fd));
+# endif
+_GL_CXXALIAS_SYS (ptsname, char *, (int fd));
+# endif
+_GL_CXXALIASWARN (ptsname);
+#elif defined GNULIB_POSIXCHECK
+# undef ptsname
+# if HAVE_RAW_DECL_PTSNAME
+_GL_WARN_ON_USE (ptsname, "ptsname is not portable - "
+ "use gnulib module ptsname for portability");
+# endif
+#endif
+
+#if @GNULIB_PTSNAME_R@
+/* Set the pathname of the pseudo-terminal slave associated with
+ the master FD is open on and return 0, or set errno and return
+ non-zero on errors. */
+# if @REPLACE_PTSNAME_R@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef ptsname_r
+# define ptsname_r rpl_ptsname_r
+# endif
+_GL_FUNCDECL_RPL (ptsname_r, int, (int fd, char *buf, size_t len));
+_GL_CXXALIAS_RPL (ptsname_r, int, (int fd, char *buf, size_t len));
+# else
+# if !@HAVE_PTSNAME_R@
+_GL_FUNCDECL_SYS (ptsname_r, int, (int fd, char *buf, size_t len));
+# endif
+_GL_CXXALIAS_SYS (ptsname_r, int, (int fd, char *buf, size_t len));
+# endif
+_GL_CXXALIASWARN (ptsname_r);
+#elif defined GNULIB_POSIXCHECK
+# undef ptsname_r
+# if HAVE_RAW_DECL_PTSNAME_R
+_GL_WARN_ON_USE (ptsname_r, "ptsname_r is not portable - "
+ "use gnulib module ptsname_r for portability");
+# endif
+#endif
+
+#if @GNULIB_PUTENV@
+# if @REPLACE_PUTENV@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef putenv
+# define putenv rpl_putenv
+# endif
+_GL_FUNCDECL_RPL (putenv, int, (char *string) _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (putenv, int, (char *string));
+# else
+_GL_CXXALIAS_SYS (putenv, int, (char *string));
+# endif
+_GL_CXXALIASWARN (putenv);
+#endif
+
+#if @GNULIB_QSORT_R@
+# if @REPLACE_QSORT_R@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef qsort_r
+# define qsort_r rpl_qsort_r
+# endif
+_GL_FUNCDECL_RPL (qsort_r, void, (void *base, size_t nmemb, size_t size,
+ int (*compare) (void const *, void const *,
+ void *),
+ void *arg) _GL_ARG_NONNULL ((1, 4)));
+_GL_CXXALIAS_RPL (qsort_r, void, (void *base, size_t nmemb, size_t size,
+ int (*compare) (void const *, void const *,
+ void *),
+ void *arg));
+# else
+_GL_CXXALIAS_SYS (qsort_r, void, (void *base, size_t nmemb, size_t size,
+ int (*compare) (void const *, void const *,
+ void *),
+ void *arg));
+# endif
+_GL_CXXALIASWARN (qsort_r);
+#endif
+
+
+#if @GNULIB_RANDOM_R@
+# if !@HAVE_RANDOM_R@
+# ifndef RAND_MAX
+# define RAND_MAX 2147483647
+# endif
+# endif
+#endif
+
+
+#if @GNULIB_RANDOM@
+# if !@HAVE_RANDOM@
+_GL_FUNCDECL_SYS (random, long, (void));
+# endif
+_GL_CXXALIAS_SYS (random, long, (void));
+_GL_CXXALIASWARN (random);
+#elif defined GNULIB_POSIXCHECK
+# undef random
+# if HAVE_RAW_DECL_RANDOM
+_GL_WARN_ON_USE (random, "random is unportable - "
+ "use gnulib module random for portability");
+# endif
+#endif
+
+#if @GNULIB_RANDOM@
+# if !@HAVE_RANDOM@
+_GL_FUNCDECL_SYS (srandom, void, (unsigned int seed));
+# endif
+_GL_CXXALIAS_SYS (srandom, void, (unsigned int seed));
+_GL_CXXALIASWARN (srandom);
+#elif defined GNULIB_POSIXCHECK
+# undef srandom
+# if HAVE_RAW_DECL_SRANDOM
+_GL_WARN_ON_USE (srandom, "srandom is unportable - "
+ "use gnulib module random for portability");
+# endif
+#endif
+
+#if @GNULIB_RANDOM@
+# if !@HAVE_RANDOM@
+_GL_FUNCDECL_SYS (initstate, char *,
+ (unsigned int seed, char *buf, size_t buf_size)
+ _GL_ARG_NONNULL ((2)));
+# endif
+_GL_CXXALIAS_SYS (initstate, char *,
+ (unsigned int seed, char *buf, size_t buf_size));
+_GL_CXXALIASWARN (initstate);
+#elif defined GNULIB_POSIXCHECK
+# undef initstate
+# if HAVE_RAW_DECL_INITSTATE_R
+_GL_WARN_ON_USE (initstate, "initstate is unportable - "
+ "use gnulib module random for portability");
+# endif
+#endif
+
+#if @GNULIB_RANDOM@
+# if !@HAVE_RANDOM@
+_GL_FUNCDECL_SYS (setstate, char *, (char *arg_state) _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (setstate, char *, (char *arg_state));
+_GL_CXXALIASWARN (setstate);
+#elif defined GNULIB_POSIXCHECK
+# undef setstate
+# if HAVE_RAW_DECL_SETSTATE_R
+_GL_WARN_ON_USE (setstate, "setstate is unportable - "
+ "use gnulib module random for portability");
+# endif
+#endif
+
+
+#if @GNULIB_RANDOM_R@
+# if @REPLACE_RANDOM_R@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef random_r
+# define random_r rpl_random_r
+# endif
+_GL_FUNCDECL_RPL (random_r, int, (struct random_data *buf, int32_t *result)
+ _GL_ARG_NONNULL ((1, 2)));
+_GL_CXXALIAS_RPL (random_r, int, (struct random_data *buf, int32_t *result));
+# else
+# if !@HAVE_RANDOM_R@
+_GL_FUNCDECL_SYS (random_r, int, (struct random_data *buf, int32_t *result)
+ _GL_ARG_NONNULL ((1, 2)));
+# endif
+_GL_CXXALIAS_SYS (random_r, int, (struct random_data *buf, int32_t *result));
+# endif
+_GL_CXXALIASWARN (random_r);
+#elif defined GNULIB_POSIXCHECK
+# undef random_r
+# if HAVE_RAW_DECL_RANDOM_R
+_GL_WARN_ON_USE (random_r, "random_r is unportable - "
+ "use gnulib module random_r for portability");
+# endif
+#endif
+
+#if @GNULIB_RANDOM_R@
+# if @REPLACE_RANDOM_R@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef srandom_r
+# define srandom_r rpl_srandom_r
+# endif
+_GL_FUNCDECL_RPL (srandom_r, int,
+ (unsigned int seed, struct random_data *rand_state)
+ _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_RPL (srandom_r, int,
+ (unsigned int seed, struct random_data *rand_state));
+# else
+# if !@HAVE_RANDOM_R@
+_GL_FUNCDECL_SYS (srandom_r, int,
+ (unsigned int seed, struct random_data *rand_state)
+ _GL_ARG_NONNULL ((2)));
+# endif
+_GL_CXXALIAS_SYS (srandom_r, int,
+ (unsigned int seed, struct random_data *rand_state));
+# endif
+_GL_CXXALIASWARN (srandom_r);
+#elif defined GNULIB_POSIXCHECK
+# undef srandom_r
+# if HAVE_RAW_DECL_SRANDOM_R
+_GL_WARN_ON_USE (srandom_r, "srandom_r is unportable - "
+ "use gnulib module random_r for portability");
+# endif
+#endif
+
+#if @GNULIB_RANDOM_R@
+# if @REPLACE_RANDOM_R@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef initstate_r
+# define initstate_r rpl_initstate_r
+# endif
+_GL_FUNCDECL_RPL (initstate_r, int,
+ (unsigned int seed, char *buf, size_t buf_size,
+ struct random_data *rand_state)
+ _GL_ARG_NONNULL ((2, 4)));
+_GL_CXXALIAS_RPL (initstate_r, int,
+ (unsigned int seed, char *buf, size_t buf_size,
+ struct random_data *rand_state));
+# else
+# if !@HAVE_RANDOM_R@
+_GL_FUNCDECL_SYS (initstate_r, int,
+ (unsigned int seed, char *buf, size_t buf_size,
+ struct random_data *rand_state)
+ _GL_ARG_NONNULL ((2, 4)));
+# endif
+_GL_CXXALIAS_SYS (initstate_r, int,
+ (unsigned int seed, char *buf, size_t buf_size,
+ struct random_data *rand_state));
+# endif
+_GL_CXXALIASWARN (initstate_r);
+#elif defined GNULIB_POSIXCHECK
+# undef initstate_r
+# if HAVE_RAW_DECL_INITSTATE_R
+_GL_WARN_ON_USE (initstate_r, "initstate_r is unportable - "
+ "use gnulib module random_r for portability");
+# endif
+#endif
+
+#if @GNULIB_RANDOM_R@
+# if @REPLACE_RANDOM_R@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef setstate_r
+# define setstate_r rpl_setstate_r
+# endif
+_GL_FUNCDECL_RPL (setstate_r, int,
+ (char *arg_state, struct random_data *rand_state)
+ _GL_ARG_NONNULL ((1, 2)));
+_GL_CXXALIAS_RPL (setstate_r, int,
+ (char *arg_state, struct random_data *rand_state));
+# else
+# if !@HAVE_RANDOM_R@
+_GL_FUNCDECL_SYS (setstate_r, int,
+ (char *arg_state, struct random_data *rand_state)
+ _GL_ARG_NONNULL ((1, 2)));
+# endif
+_GL_CXXALIAS_SYS (setstate_r, int,
+ (char *arg_state, struct random_data *rand_state));
+# endif
+_GL_CXXALIASWARN (setstate_r);
+#elif defined GNULIB_POSIXCHECK
+# undef setstate_r
+# if HAVE_RAW_DECL_SETSTATE_R
+_GL_WARN_ON_USE (setstate_r, "setstate_r is unportable - "
+ "use gnulib module random_r for portability");
+# endif
+#endif
+
+
+#if @GNULIB_REALLOC_POSIX@
+# if @REPLACE_REALLOC@
+# if !((defined __cplusplus && defined GNULIB_NAMESPACE) \
+ || _GL_USE_STDLIB_ALLOC)
+# undef realloc
+# define realloc rpl_realloc
+# endif
+_GL_FUNCDECL_RPL (realloc, void *, (void *ptr, size_t size));
+_GL_CXXALIAS_RPL (realloc, void *, (void *ptr, size_t size));
+# else
+_GL_CXXALIAS_SYS (realloc, void *, (void *ptr, size_t size));
+# endif
+_GL_CXXALIASWARN (realloc);
+#elif defined GNULIB_POSIXCHECK && !_GL_USE_STDLIB_ALLOC
+# undef realloc
+/* Assume realloc is always declared. */
+_GL_WARN_ON_USE (realloc, "realloc is not POSIX compliant everywhere - "
+ "use gnulib module realloc-posix for portability");
+#endif
+
+#if @GNULIB_REALPATH@
+# if @REPLACE_REALPATH@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define realpath rpl_realpath
+# endif
+_GL_FUNCDECL_RPL (realpath, char *, (const char *name, char *resolved)
+ _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (realpath, char *, (const char *name, char *resolved));
+# else
+# if !@HAVE_REALPATH@
+_GL_FUNCDECL_SYS (realpath, char *, (const char *name, char *resolved)
+ _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (realpath, char *, (const char *name, char *resolved));
+# endif
+_GL_CXXALIASWARN (realpath);
+#elif defined GNULIB_POSIXCHECK
+# undef realpath
+# if HAVE_RAW_DECL_REALPATH
+_GL_WARN_ON_USE (realpath, "realpath is unportable - use gnulib module "
+ "canonicalize or canonicalize-lgpl for portability");
+# endif
+#endif
+
+#if @GNULIB_RPMATCH@
+/* Test a user response to a question.
+ Return 1 if it is affirmative, 0 if it is negative, or -1 if not clear. */
+# if !@HAVE_RPMATCH@
+_GL_FUNCDECL_SYS (rpmatch, int, (const char *response) _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (rpmatch, int, (const char *response));
+_GL_CXXALIASWARN (rpmatch);
+#elif defined GNULIB_POSIXCHECK
+# undef rpmatch
+# if HAVE_RAW_DECL_RPMATCH
+_GL_WARN_ON_USE (rpmatch, "rpmatch is unportable - "
+ "use gnulib module rpmatch for portability");
+# endif
+#endif
+
+#if @GNULIB_SECURE_GETENV@
+/* Look up NAME in the environment, returning 0 in insecure situations. */
+# if !@HAVE_SECURE_GETENV@
+_GL_FUNCDECL_SYS (secure_getenv, char *,
+ (char const *name) _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (secure_getenv, char *, (char const *name));
+_GL_CXXALIASWARN (secure_getenv);
+#elif defined GNULIB_POSIXCHECK
+# undef secure_getenv
+# if HAVE_RAW_DECL_SECURE_GETENV
+_GL_WARN_ON_USE (secure_getenv, "secure_getenv is unportable - "
+ "use gnulib module secure_getenv for portability");
+# endif
+#endif
+
+#if @GNULIB_SETENV@
+/* Set NAME to VALUE in the environment.
+ If REPLACE is nonzero, overwrite an existing value. */
+# if @REPLACE_SETENV@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef setenv
+# define setenv rpl_setenv
+# endif
+_GL_FUNCDECL_RPL (setenv, int,
+ (const char *name, const char *value, int replace)
+ _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (setenv, int,
+ (const char *name, const char *value, int replace));
+# else
+# if !@HAVE_DECL_SETENV@
+_GL_FUNCDECL_SYS (setenv, int,
+ (const char *name, const char *value, int replace)
+ _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (setenv, int,
+ (const char *name, const char *value, int replace));
+# endif
+# if !(@REPLACE_SETENV@ && !@HAVE_DECL_SETENV@)
+_GL_CXXALIASWARN (setenv);
+# endif
+#elif defined GNULIB_POSIXCHECK
+# undef setenv
+# if HAVE_RAW_DECL_SETENV
+_GL_WARN_ON_USE (setenv, "setenv is unportable - "
+ "use gnulib module setenv for portability");
+# endif
+#endif
+
+#if @GNULIB_STRTOD@
+ /* Parse a double from STRING, updating ENDP if appropriate. */
+# if @REPLACE_STRTOD@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define strtod rpl_strtod
+# endif
+_GL_FUNCDECL_RPL (strtod, double, (const char *str, char **endp)
+ _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (strtod, double, (const char *str, char **endp));
+# else
+# if !@HAVE_STRTOD@
+_GL_FUNCDECL_SYS (strtod, double, (const char *str, char **endp)
+ _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (strtod, double, (const char *str, char **endp));
+# endif
+_GL_CXXALIASWARN (strtod);
+#elif defined GNULIB_POSIXCHECK
+# undef strtod
+# if HAVE_RAW_DECL_STRTOD
+_GL_WARN_ON_USE (strtod, "strtod is unportable - "
+ "use gnulib module strtod for portability");
+# endif
+#endif
+
+#if @GNULIB_STRTOLL@
+/* Parse a signed integer whose textual representation starts at STRING.
+ The integer is expected to be in base BASE (2 <= BASE <= 36); if BASE == 0,
+ it may be decimal or octal (with prefix "0") or hexadecimal (with prefix
+ "0x").
+ If ENDPTR is not NULL, the address of the first byte after the integer is
+ stored in *ENDPTR.
+ Upon overflow, the return value is LLONG_MAX or LLONG_MIN, and errno is set
+ to ERANGE. */
+# if !@HAVE_STRTOLL@
+_GL_FUNCDECL_SYS (strtoll, long long,
+ (const char *string, char **endptr, int base)
+ _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (strtoll, long long,
+ (const char *string, char **endptr, int base));
+_GL_CXXALIASWARN (strtoll);
+#elif defined GNULIB_POSIXCHECK
+# undef strtoll
+# if HAVE_RAW_DECL_STRTOLL
+_GL_WARN_ON_USE (strtoll, "strtoll is unportable - "
+ "use gnulib module strtoll for portability");
+# endif
+#endif
+
+#if @GNULIB_STRTOULL@
+/* Parse an unsigned integer whose textual representation starts at STRING.
+ The integer is expected to be in base BASE (2 <= BASE <= 36); if BASE == 0,
+ it may be decimal or octal (with prefix "0") or hexadecimal (with prefix
+ "0x").
+ If ENDPTR is not NULL, the address of the first byte after the integer is
+ stored in *ENDPTR.
+ Upon overflow, the return value is ULLONG_MAX, and errno is set to
+ ERANGE. */
+# if !@HAVE_STRTOULL@
+_GL_FUNCDECL_SYS (strtoull, unsigned long long,
+ (const char *string, char **endptr, int base)
+ _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (strtoull, unsigned long long,
+ (const char *string, char **endptr, int base));
+_GL_CXXALIASWARN (strtoull);
+#elif defined GNULIB_POSIXCHECK
+# undef strtoull
+# if HAVE_RAW_DECL_STRTOULL
+_GL_WARN_ON_USE (strtoull, "strtoull is unportable - "
+ "use gnulib module strtoull for portability");
+# endif
+#endif
+
+#if @GNULIB_UNLOCKPT@
+/* Unlock the slave side of the pseudo-terminal whose master side is specified
+ by FD, so that it can be opened. */
+# if !@HAVE_UNLOCKPT@
+_GL_FUNCDECL_SYS (unlockpt, int, (int fd));
+# endif
+_GL_CXXALIAS_SYS (unlockpt, int, (int fd));
+_GL_CXXALIASWARN (unlockpt);
+#elif defined GNULIB_POSIXCHECK
+# undef unlockpt
+# if HAVE_RAW_DECL_UNLOCKPT
+_GL_WARN_ON_USE (unlockpt, "unlockpt is not portable - "
+ "use gnulib module unlockpt for portability");
+# endif
+#endif
+
+#if @GNULIB_UNSETENV@
+/* Remove the variable NAME from the environment. */
+# if @REPLACE_UNSETENV@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef unsetenv
+# define unsetenv rpl_unsetenv
+# endif
+_GL_FUNCDECL_RPL (unsetenv, int, (const char *name) _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (unsetenv, int, (const char *name));
+# else
+# if !@HAVE_DECL_UNSETENV@
+_GL_FUNCDECL_SYS (unsetenv, int, (const char *name) _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (unsetenv, int, (const char *name));
+# endif
+# if !(@REPLACE_UNSETENV@ && !@HAVE_DECL_UNSETENV@)
+_GL_CXXALIASWARN (unsetenv);
+# endif
+#elif defined GNULIB_POSIXCHECK
+# undef unsetenv
+# if HAVE_RAW_DECL_UNSETENV
+_GL_WARN_ON_USE (unsetenv, "unsetenv is unportable - "
+ "use gnulib module unsetenv for portability");
+# endif
+#endif
+
+/* Convert a wide character to a multibyte character. */
+#if @GNULIB_WCTOMB@
+# if @REPLACE_WCTOMB@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef wctomb
+# define wctomb rpl_wctomb
+# endif
+_GL_FUNCDECL_RPL (wctomb, int, (char *s, wchar_t wc));
+_GL_CXXALIAS_RPL (wctomb, int, (char *s, wchar_t wc));
+# else
+_GL_CXXALIAS_SYS (wctomb, int, (char *s, wchar_t wc));
+# endif
+_GL_CXXALIASWARN (wctomb);
+#endif
+
+
+#endif /* _@GUARD_PREFIX@_STDLIB_H */
+#endif /* _@GUARD_PREFIX@_STDLIB_H */
+#endif
diff --git a/lib/stdlib_.h b/lib/stdlib_.h
deleted file mode 100644
index a920408..0000000
--- a/lib/stdlib_.h
+++ /dev/null
@@ -1,141 +0,0 @@
-/* A GNU-like <stdlib.h>.
-
- Copyright (C) 1995, 2001-2002, 2006-2007 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-#if defined __need_malloc_and_calloc
-/* Special invocation convention inside glibc header files. */
-
-/* This #pragma avoids a warning with "gcc -Wall" on some glibc systems
- on which <stdlib.h> has an inappropriate declaration, see
- <http://sourceware.org/bugzilla/show_bug.cgi?id=1079>. */
-#ifdef __GNUC__
-# pragma GCC system_header
-#endif
-
-#include @ABSOLUTE_STDLIB_H@
-
-#else
-/* Normal invocation convention. */
-#ifndef _GL_STDLIB_H
-#define _GL_STDLIB_H
-
-/* This #pragma avoids a warning with "gcc -Wall" on some glibc systems
- on which <stdlib.h> has an inappropriate declaration, see
- <http://sourceware.org/bugzilla/show_bug.cgi?id=1079>. */
-#ifdef __GNUC__
-# pragma GCC system_header
-#endif
-
-#include @ABSOLUTE_STDLIB_H@
-
-
-/* The definition of GL_LINK_WARNING is copied here. */
-
-
-/* Some systems do not define EXIT_*, despite otherwise supporting C89. */
-#ifndef EXIT_SUCCESS
-# define EXIT_SUCCESS 0
-#endif
-/* Tandem/NSK and other platforms that define EXIT_FAILURE as -1 interfere
- with proper operation of xargs. */
-#ifndef EXIT_FAILURE
-# define EXIT_FAILURE 1
-#elif EXIT_FAILURE != 1
-# undef EXIT_FAILURE
-# define EXIT_FAILURE 1
-#endif
-
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-#if @GNULIB_GETSUBOPT@
-/* Assuming *OPTIONP is a comma separated list of elements of the form
- "token" or "token=value", getsubopt parses the first of these elements.
- If the first element refers to a "token" that is member of the given
- NULL-terminated array of tokens:
- - It replaces the comma with a NUL byte, updates *OPTIONP to point past
- the first option and the comma, sets *VALUEP to the value of the
- element (or NULL if it doesn't contain an "=" sign),
- - It returns the index of the "token" in the given array of tokens.
- Otherwise it returns -1, and *OPTIONP and *VALUEP are undefined.
- For more details see the POSIX:2001 specification.
- http://www.opengroup.org/susv3xsh/getsubopt.html */
-# if !@HAVE_GETSUBOPT@
-extern int getsubopt (char **optionp, char *const *tokens, char **valuep);
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef getsubopt
-# define getsubopt(o,t,v) \
- (GL_LINK_WARNING ("getsubopt is unportable - " \
- "use gnulib module getsubopt for portability"), \
- getsubopt (o, t, v))
-#endif
-
-
-#if @GNULIB_MKDTEMP@
-# if !@HAVE_MKDTEMP@
-/* Create a unique temporary directory from TEMPLATE.
- The last six characters of TEMPLATE must be "XXXXXX";
- they are replaced with a string that makes the directory name unique.
- Returns TEMPLATE, or a null pointer if it cannot get a unique name.
- The directory is created mode 700. */
-extern char * mkdtemp (char *template);
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef mkdtemp
-# define mkdtemp(t) \
- (GL_LINK_WARNING ("mkdtemp is unportable - " \
- "use gnulib module mkdtemp for portability"), \
- mkdtemp (t))
-#endif
-
-
-#if @GNULIB_MKSTEMP@
-# if @REPLACE_MKSTEMP@
-/* Create a unique temporary file from TEMPLATE.
- The last six characters of TEMPLATE must be "XXXXXX";
- they are replaced with a string that makes the file name unique.
- The file is then created, ensuring it didn't exist before.
- The file is created read-write (mask at least 0600 & ~umask), but it may be
- world-readable and world-writable (mask 0666 & ~umask), depending on the
- implementation.
- Returns the open file descriptor if successful, otherwise -1 and errno
- set. */
-# define mkstemp rpl_mkstemp
-extern int mkstemp (char *template);
-# else
-/* On MacOS X 10.3, only <unistd.h> declares mkstemp. */
-# include <unistd.h>
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef mkstemp
-# define mkstemp(t) \
- (GL_LINK_WARNING ("mkstemp is unportable - " \
- "use gnulib module mkstemp for portability"), \
- mkstemp (t))
-#endif
-
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _GL_STDLIB_H */
-#endif
diff --git a/lib/stpcpy.c b/lib/stpcpy.c
index 4089d39..ec3996e 100644
--- a/lib/stpcpy.c
+++ b/lib/stpcpy.c
@@ -1,12 +1,13 @@
/* stpcpy.c -- copy a string and return pointer to end of new string
- Copyright (C) 1992, 1995, 1997-1998, 2006 Free Software Foundation, Inc.
+ Copyright (C) 1992, 1995, 1997-1998, 2006, 2009-2016 Free Software
+ Foundation, Inc.
NOTE: The canonical source of this file is maintained with the GNU C Library.
Bugs can be reported to bug-glibc@prep.ai.mit.edu.
- This program is free software; you can redistribute it and/or modify it
+ 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 2, or (at your option) any
+ Free Software Foundation; either version 3 of the License, or any
later version.
This program is distributed in the hope that it will be useful,
@@ -15,8 +16,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
diff --git a/lib/stpncpy.c b/lib/stpncpy.c
new file mode 100644
index 0000000..89d6321
--- /dev/null
+++ b/lib/stpncpy.c
@@ -0,0 +1,92 @@
+/* Copyright (C) 1993, 1995-1997, 2002-2003, 2005-2007, 2009-2016 Free Software
+ * Foundation, Inc.
+
+ NOTE: The canonical source of this file is maintained with the GNU C Library.
+ Bugs can be reported to bug-glibc@gnu.org.
+
+ 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 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 <http://www.gnu.org/licenses/>. */
+
+/* This is almost copied from strncpy.c, written by Torbjorn Granlund. */
+
+#include <config.h>
+
+/* Specification. */
+#include <string.h>
+
+#ifndef weak_alias
+# define __stpncpy stpncpy
+#endif
+
+/* Copy no more than N bytes of SRC to DST, returning a pointer past the
+ last non-NUL byte written into DST. */
+char *
+(__stpncpy) (char *dest, const char *src, size_t n)
+{
+ char c;
+ char *s = dest;
+
+ if (n >= 4)
+ {
+ size_t n4 = n >> 2;
+
+ for (;;)
+ {
+ c = *src++;
+ *dest++ = c;
+ if (c == '\0')
+ break;
+ c = *src++;
+ *dest++ = c;
+ if (c == '\0')
+ break;
+ c = *src++;
+ *dest++ = c;
+ if (c == '\0')
+ break;
+ c = *src++;
+ *dest++ = c;
+ if (c == '\0')
+ break;
+ if (--n4 == 0)
+ goto last_chars;
+ }
+ n -= dest - s;
+ goto zero_fill;
+ }
+
+ last_chars:
+ n &= 3;
+ if (n == 0)
+ return dest;
+
+ for (;;)
+ {
+ c = *src++;
+ --n;
+ *dest++ = c;
+ if (c == '\0')
+ break;
+ if (n == 0)
+ return dest;
+ }
+
+ zero_fill:
+ while (n-- > 0)
+ dest[n] = '\0';
+
+ return dest - 1;
+}
+#ifdef weak_alias
+weak_alias (__stpncpy, stpncpy)
+#endif
diff --git a/lib/str-kmp.h b/lib/str-kmp.h
new file mode 100644
index 0000000..fcb2813
--- /dev/null
+++ b/lib/str-kmp.h
@@ -0,0 +1,153 @@
+/* Substring search in a NUL terminated string of UNIT elements,
+ using the Knuth-Morris-Pratt algorithm.
+ Copyright (C) 2005-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2005.
+
+ 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, 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 <http://www.gnu.org/licenses/>. */
+
+/* Before including this file, you need to define:
+ UNIT The element type of the needle and haystack.
+ CANON_ELEMENT(c) A macro that canonicalizes an element right after
+ it has been fetched from needle or haystack.
+ The argument is of type UNIT; the result must be
+ of type UNIT as well. */
+
+/* Knuth-Morris-Pratt algorithm.
+ See http://en.wikipedia.org/wiki/Knuth-Morris-Pratt_algorithm
+ HAYSTACK is the NUL terminated string in which to search for.
+ NEEDLE is the string to search for in HAYSTACK, consisting of NEEDLE_LEN
+ units.
+ Return a boolean indicating success:
+ Return true and set *RESULTP if the search was completed.
+ Return false if it was aborted because not enough memory was available. */
+static bool
+knuth_morris_pratt (const UNIT *haystack,
+ const UNIT *needle, size_t needle_len,
+ const UNIT **resultp)
+{
+ size_t m = needle_len;
+
+ /* Allocate the table. */
+ size_t *table = (size_t *) nmalloca (m, sizeof (size_t));
+ if (table == NULL)
+ return false;
+ /* Fill the table.
+ For 0 < i < m:
+ 0 < table[i] <= i is defined such that
+ forall 0 < x < table[i]: needle[x..i-1] != needle[0..i-1-x],
+ and table[i] is as large as possible with this property.
+ This implies:
+ 1) For 0 < i < m:
+ If table[i] < i,
+ needle[table[i]..i-1] = needle[0..i-1-table[i]].
+ 2) For 0 < i < m:
+ rhaystack[0..i-1] == needle[0..i-1]
+ and exists h, i <= h < m: rhaystack[h] != needle[h]
+ implies
+ forall 0 <= x < table[i]: rhaystack[x..x+m-1] != needle[0..m-1].
+ table[0] remains uninitialized. */
+ {
+ size_t i, j;
+
+ /* i = 1: Nothing to verify for x = 0. */
+ table[1] = 1;
+ j = 0;
+
+ for (i = 2; i < m; i++)
+ {
+ /* Here: j = i-1 - table[i-1].
+ The inequality needle[x..i-1] != needle[0..i-1-x] is known to hold
+ for x < table[i-1], by induction.
+ Furthermore, if j>0: needle[i-1-j..i-2] = needle[0..j-1]. */
+ UNIT b = CANON_ELEMENT (needle[i - 1]);
+
+ for (;;)
+ {
+ /* Invariants: The inequality needle[x..i-1] != needle[0..i-1-x]
+ is known to hold for x < i-1-j.
+ Furthermore, if j>0: needle[i-1-j..i-2] = needle[0..j-1]. */
+ if (b == CANON_ELEMENT (needle[j]))
+ {
+ /* Set table[i] := i-1-j. */
+ table[i] = i - ++j;
+ break;
+ }
+ /* The inequality needle[x..i-1] != needle[0..i-1-x] also holds
+ for x = i-1-j, because
+ needle[i-1] != needle[j] = needle[i-1-x]. */
+ if (j == 0)
+ {
+ /* The inequality holds for all possible x. */
+ table[i] = i;
+ break;
+ }
+ /* The inequality needle[x..i-1] != needle[0..i-1-x] also holds
+ for i-1-j < x < i-1-j+table[j], because for these x:
+ needle[x..i-2]
+ = needle[x-(i-1-j)..j-1]
+ != needle[0..j-1-(x-(i-1-j))] (by definition of table[j])
+ = needle[0..i-2-x],
+ hence needle[x..i-1] != needle[0..i-1-x].
+ Furthermore
+ needle[i-1-j+table[j]..i-2]
+ = needle[table[j]..j-1]
+ = needle[0..j-1-table[j]] (by definition of table[j]). */
+ j = j - table[j];
+ }
+ /* Here: j = i - table[i]. */
+ }
+ }
+
+ /* Search, using the table to accelerate the processing. */
+ {
+ size_t j;
+ const UNIT *rhaystack;
+ const UNIT *phaystack;
+
+ *resultp = NULL;
+ j = 0;
+ rhaystack = haystack;
+ phaystack = haystack;
+ /* Invariant: phaystack = rhaystack + j. */
+ while (*phaystack != 0)
+ if (CANON_ELEMENT (needle[j]) == CANON_ELEMENT (*phaystack))
+ {
+ j++;
+ phaystack++;
+ if (j == m)
+ {
+ /* The entire needle has been found. */
+ *resultp = rhaystack;
+ break;
+ }
+ }
+ else if (j > 0)
+ {
+ /* Found a match of needle[0..j-1], mismatch at needle[j]. */
+ rhaystack += table[j];
+ j -= table[j];
+ }
+ else
+ {
+ /* Found a mismatch at needle[0] already. */
+ rhaystack++;
+ phaystack++;
+ }
+ }
+
+ freea (table);
+ return true;
+}
+
+#undef CANON_ELEMENT
diff --git a/lib/str-two-way.h b/lib/str-two-way.h
new file mode 100644
index 0000000..0fe3161
--- /dev/null
+++ b/lib/str-two-way.h
@@ -0,0 +1,452 @@
+/* Byte-wise substring search, using the Two-Way algorithm.
+ Copyright (C) 2008-2016 Free Software Foundation, Inc.
+ This file is part of the GNU C Library.
+ Written by Eric Blake <ebb9@byu.net>, 2008.
+
+ 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, 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 <http://www.gnu.org/licenses/>. */
+
+/* Before including this file, you need to include <config.h> and
+ <string.h>, and define:
+ RESULT_TYPE A macro that expands to the return type.
+ AVAILABLE(h, h_l, j, n_l)
+ A macro that returns nonzero if there are
+ at least N_L bytes left starting at H[J].
+ H is 'unsigned char *', H_L, J, and N_L
+ are 'size_t'; H_L is an lvalue. For
+ NUL-terminated searches, H_L can be
+ modified each iteration to avoid having
+ to compute the end of H up front.
+
+ For case-insensitivity, you may optionally define:
+ CMP_FUNC(p1, p2, l) A macro that returns 0 iff the first L
+ characters of P1 and P2 are equal.
+ CANON_ELEMENT(c) A macro that canonicalizes an element right after
+ it has been fetched from one of the two strings.
+ The argument is an 'unsigned char'; the result
+ must be an 'unsigned char' as well.
+
+ This file undefines the macros documented above, and defines
+ LONG_NEEDLE_THRESHOLD.
+*/
+
+#include <limits.h>
+#include <stdint.h>
+
+/* We use the Two-Way string matching algorithm (also known as
+ Chrochemore-Perrin), which guarantees linear complexity with
+ constant space. Additionally, for long needles, we also use a bad
+ character shift table similar to the Boyer-Moore algorithm to
+ achieve improved (potentially sub-linear) performance.
+
+ See http://www-igm.univ-mlv.fr/~lecroq/string/node26.html#SECTION00260,
+ http://en.wikipedia.org/wiki/Boyer-Moore_string_search_algorithm,
+ http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.34.6641&rep=rep1&type=pdf
+*/
+
+/* Point at which computing a bad-byte shift table is likely to be
+ worthwhile. Small needles should not compute a table, since it
+ adds (1 << CHAR_BIT) + NEEDLE_LEN computations of preparation for a
+ speedup no greater than a factor of NEEDLE_LEN. The larger the
+ needle, the better the potential performance gain. On the other
+ hand, on non-POSIX systems with CHAR_BIT larger than eight, the
+ memory required for the table is prohibitive. */
+#if CHAR_BIT < 10
+# define LONG_NEEDLE_THRESHOLD 32U
+#else
+# define LONG_NEEDLE_THRESHOLD SIZE_MAX
+#endif
+
+#ifndef MAX
+# define MAX(a, b) ((a < b) ? (b) : (a))
+#endif
+
+#ifndef CANON_ELEMENT
+# define CANON_ELEMENT(c) c
+#endif
+#ifndef CMP_FUNC
+# define CMP_FUNC memcmp
+#endif
+
+/* Perform a critical factorization of NEEDLE, of length NEEDLE_LEN.
+ Return the index of the first byte in the right half, and set
+ *PERIOD to the global period of the right half.
+
+ The global period of a string is the smallest index (possibly its
+ length) at which all remaining bytes in the string are repetitions
+ of the prefix (the last repetition may be a subset of the prefix).
+
+ When NEEDLE is factored into two halves, a local period is the
+ length of the smallest word that shares a suffix with the left half
+ and shares a prefix with the right half. All factorizations of a
+ non-empty NEEDLE have a local period of at least 1 and no greater
+ than NEEDLE_LEN.
+
+ A critical factorization has the property that the local period
+ equals the global period. All strings have at least one critical
+ factorization with the left half smaller than the global period.
+ And while some strings have more than one critical factorization,
+ it is provable that with an ordered alphabet, at least one of the
+ critical factorizations corresponds to a maximal suffix.
+
+ Given an ordered alphabet, a critical factorization can be computed
+ in linear time, with 2 * NEEDLE_LEN comparisons, by computing the
+ shorter of two ordered maximal suffixes. The ordered maximal
+ suffixes are determined by lexicographic comparison while tracking
+ periodicity. */
+static size_t
+critical_factorization (const unsigned char *needle, size_t needle_len,
+ size_t *period)
+{
+ /* Index of last byte of left half, or SIZE_MAX. */
+ size_t max_suffix, max_suffix_rev;
+ size_t j; /* Index into NEEDLE for current candidate suffix. */
+ size_t k; /* Offset into current period. */
+ size_t p; /* Intermediate period. */
+ unsigned char a, b; /* Current comparison bytes. */
+
+ /* Special case NEEDLE_LEN of 1 or 2 (all callers already filtered
+ out 0-length needles. */
+ if (needle_len < 3)
+ {
+ *period = 1;
+ return needle_len - 1;
+ }
+
+ /* Invariants:
+ 0 <= j < NEEDLE_LEN - 1
+ -1 <= max_suffix{,_rev} < j (treating SIZE_MAX as if it were signed)
+ min(max_suffix, max_suffix_rev) < global period of NEEDLE
+ 1 <= p <= global period of NEEDLE
+ p == global period of the substring NEEDLE[max_suffix{,_rev}+1...j]
+ 1 <= k <= p
+ */
+
+ /* Perform lexicographic search. */
+ max_suffix = SIZE_MAX;
+ j = 0;
+ k = p = 1;
+ while (j + k < needle_len)
+ {
+ a = CANON_ELEMENT (needle[j + k]);
+ b = CANON_ELEMENT (needle[max_suffix + k]);
+ if (a < b)
+ {
+ /* Suffix is smaller, period is entire prefix so far. */
+ j += k;
+ k = 1;
+ p = j - max_suffix;
+ }
+ else if (a == b)
+ {
+ /* Advance through repetition of the current period. */
+ if (k != p)
+ ++k;
+ else
+ {
+ j += p;
+ k = 1;
+ }
+ }
+ else /* b < a */
+ {
+ /* Suffix is larger, start over from current location. */
+ max_suffix = j++;
+ k = p = 1;
+ }
+ }
+ *period = p;
+
+ /* Perform reverse lexicographic search. */
+ max_suffix_rev = SIZE_MAX;
+ j = 0;
+ k = p = 1;
+ while (j + k < needle_len)
+ {
+ a = CANON_ELEMENT (needle[j + k]);
+ b = CANON_ELEMENT (needle[max_suffix_rev + k]);
+ if (b < a)
+ {
+ /* Suffix is smaller, period is entire prefix so far. */
+ j += k;
+ k = 1;
+ p = j - max_suffix_rev;
+ }
+ else if (a == b)
+ {
+ /* Advance through repetition of the current period. */
+ if (k != p)
+ ++k;
+ else
+ {
+ j += p;
+ k = 1;
+ }
+ }
+ else /* a < b */
+ {
+ /* Suffix is larger, start over from current location. */
+ max_suffix_rev = j++;
+ k = p = 1;
+ }
+ }
+
+ /* Choose the shorter suffix. Return the index of the first byte of
+ the right half, rather than the last byte of the left half.
+
+ For some examples, 'banana' has two critical factorizations, both
+ exposed by the two lexicographic extreme suffixes of 'anana' and
+ 'nana', where both suffixes have a period of 2. On the other
+ hand, with 'aab' and 'bba', both strings have a single critical
+ factorization of the last byte, with the suffix having a period
+ of 1. While the maximal lexicographic suffix of 'aab' is 'b',
+ the maximal lexicographic suffix of 'bba' is 'ba', which is not a
+ critical factorization. Conversely, the maximal reverse
+ lexicographic suffix of 'a' works for 'bba', but not 'ab' for
+ 'aab'. The shorter suffix of the two will always be a critical
+ factorization. */
+ if (max_suffix_rev + 1 < max_suffix + 1)
+ return max_suffix + 1;
+ *period = p;
+ return max_suffix_rev + 1;
+}
+
+/* Return the first location of non-empty NEEDLE within HAYSTACK, or
+ NULL. HAYSTACK_LEN is the minimum known length of HAYSTACK. This
+ method is optimized for NEEDLE_LEN < LONG_NEEDLE_THRESHOLD.
+ Performance is guaranteed to be linear, with an initialization cost
+ of 2 * NEEDLE_LEN comparisons.
+
+ If AVAILABLE does not modify HAYSTACK_LEN (as in memmem), then at
+ most 2 * HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching.
+ If AVAILABLE modifies HAYSTACK_LEN (as in strstr), then at most 3 *
+ HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching. */
+static RETURN_TYPE
+two_way_short_needle (const unsigned char *haystack, size_t haystack_len,
+ const unsigned char *needle, size_t needle_len)
+{
+ size_t i; /* Index into current byte of NEEDLE. */
+ size_t j; /* Index into current window of HAYSTACK. */
+ size_t period; /* The period of the right half of needle. */
+ size_t suffix; /* The index of the right half of needle. */
+
+ /* Factor the needle into two halves, such that the left half is
+ smaller than the global period, and the right half is
+ periodic (with a period as large as NEEDLE_LEN - suffix). */
+ suffix = critical_factorization (needle, needle_len, &period);
+
+ /* Perform the search. Each iteration compares the right half
+ first. */
+ if (CMP_FUNC (needle, needle + period, suffix) == 0)
+ {
+ /* Entire needle is periodic; a mismatch in the left half can
+ only advance by the period, so use memory to avoid rescanning
+ known occurrences of the period in the right half. */
+ size_t memory = 0;
+ j = 0;
+ while (AVAILABLE (haystack, haystack_len, j, needle_len))
+ {
+ /* Scan for matches in right half. */
+ i = MAX (suffix, memory);
+ while (i < needle_len && (CANON_ELEMENT (needle[i])
+ == CANON_ELEMENT (haystack[i + j])))
+ ++i;
+ if (needle_len <= i)
+ {
+ /* Scan for matches in left half. */
+ i = suffix - 1;
+ while (memory < i + 1 && (CANON_ELEMENT (needle[i])
+ == CANON_ELEMENT (haystack[i + j])))
+ --i;
+ if (i + 1 < memory + 1)
+ return (RETURN_TYPE) (haystack + j);
+ /* No match, so remember how many repetitions of period
+ on the right half were scanned. */
+ j += period;
+ memory = needle_len - period;
+ }
+ else
+ {
+ j += i - suffix + 1;
+ memory = 0;
+ }
+ }
+ }
+ else
+ {
+ /* The two halves of needle are distinct; no extra memory is
+ required, and any mismatch results in a maximal shift. */
+ period = MAX (suffix, needle_len - suffix) + 1;
+ j = 0;
+ while (AVAILABLE (haystack, haystack_len, j, needle_len))
+ {
+ /* Scan for matches in right half. */
+ i = suffix;
+ while (i < needle_len && (CANON_ELEMENT (needle[i])
+ == CANON_ELEMENT (haystack[i + j])))
+ ++i;
+ if (needle_len <= i)
+ {
+ /* Scan for matches in left half. */
+ i = suffix - 1;
+ while (i != SIZE_MAX && (CANON_ELEMENT (needle[i])
+ == CANON_ELEMENT (haystack[i + j])))
+ --i;
+ if (i == SIZE_MAX)
+ return (RETURN_TYPE) (haystack + j);
+ j += period;
+ }
+ else
+ j += i - suffix + 1;
+ }
+ }
+ return NULL;
+}
+
+/* Return the first location of non-empty NEEDLE within HAYSTACK, or
+ NULL. HAYSTACK_LEN is the minimum known length of HAYSTACK. This
+ method is optimized for LONG_NEEDLE_THRESHOLD <= NEEDLE_LEN.
+ Performance is guaranteed to be linear, with an initialization cost
+ of 3 * NEEDLE_LEN + (1 << CHAR_BIT) operations.
+
+ If AVAILABLE does not modify HAYSTACK_LEN (as in memmem), then at
+ most 2 * HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching,
+ and sublinear performance O(HAYSTACK_LEN / NEEDLE_LEN) is possible.
+ If AVAILABLE modifies HAYSTACK_LEN (as in strstr), then at most 3 *
+ HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching, and
+ sublinear performance is not possible. */
+static RETURN_TYPE
+two_way_long_needle (const unsigned char *haystack, size_t haystack_len,
+ const unsigned char *needle, size_t needle_len)
+{
+ size_t i; /* Index into current byte of NEEDLE. */
+ size_t j; /* Index into current window of HAYSTACK. */
+ size_t period; /* The period of the right half of needle. */
+ size_t suffix; /* The index of the right half of needle. */
+ size_t shift_table[1U << CHAR_BIT]; /* See below. */
+
+ /* Factor the needle into two halves, such that the left half is
+ smaller than the global period, and the right half is
+ periodic (with a period as large as NEEDLE_LEN - suffix). */
+ suffix = critical_factorization (needle, needle_len, &period);
+
+ /* Populate shift_table. For each possible byte value c,
+ shift_table[c] is the distance from the last occurrence of c to
+ the end of NEEDLE, or NEEDLE_LEN if c is absent from the NEEDLE.
+ shift_table[NEEDLE[NEEDLE_LEN - 1]] contains the only 0. */
+ for (i = 0; i < 1U << CHAR_BIT; i++)
+ shift_table[i] = needle_len;
+ for (i = 0; i < needle_len; i++)
+ shift_table[CANON_ELEMENT (needle[i])] = needle_len - i - 1;
+
+ /* Perform the search. Each iteration compares the right half
+ first. */
+ if (CMP_FUNC (needle, needle + period, suffix) == 0)
+ {
+ /* Entire needle is periodic; a mismatch in the left half can
+ only advance by the period, so use memory to avoid rescanning
+ known occurrences of the period in the right half. */
+ size_t memory = 0;
+ size_t shift;
+ j = 0;
+ while (AVAILABLE (haystack, haystack_len, j, needle_len))
+ {
+ /* Check the last byte first; if it does not match, then
+ shift to the next possible match location. */
+ shift = shift_table[CANON_ELEMENT (haystack[j + needle_len - 1])];
+ if (0 < shift)
+ {
+ if (memory && shift < period)
+ {
+ /* Since needle is periodic, but the last period has
+ a byte out of place, there can be no match until
+ after the mismatch. */
+ shift = needle_len - period;
+ }
+ memory = 0;
+ j += shift;
+ continue;
+ }
+ /* Scan for matches in right half. The last byte has
+ already been matched, by virtue of the shift table. */
+ i = MAX (suffix, memory);
+ while (i < needle_len - 1 && (CANON_ELEMENT (needle[i])
+ == CANON_ELEMENT (haystack[i + j])))
+ ++i;
+ if (needle_len - 1 <= i)
+ {
+ /* Scan for matches in left half. */
+ i = suffix - 1;
+ while (memory < i + 1 && (CANON_ELEMENT (needle[i])
+ == CANON_ELEMENT (haystack[i + j])))
+ --i;
+ if (i + 1 < memory + 1)
+ return (RETURN_TYPE) (haystack + j);
+ /* No match, so remember how many repetitions of period
+ on the right half were scanned. */
+ j += period;
+ memory = needle_len - period;
+ }
+ else
+ {
+ j += i - suffix + 1;
+ memory = 0;
+ }
+ }
+ }
+ else
+ {
+ /* The two halves of needle are distinct; no extra memory is
+ required, and any mismatch results in a maximal shift. */
+ size_t shift;
+ period = MAX (suffix, needle_len - suffix) + 1;
+ j = 0;
+ while (AVAILABLE (haystack, haystack_len, j, needle_len))
+ {
+ /* Check the last byte first; if it does not match, then
+ shift to the next possible match location. */
+ shift = shift_table[CANON_ELEMENT (haystack[j + needle_len - 1])];
+ if (0 < shift)
+ {
+ j += shift;
+ continue;
+ }
+ /* Scan for matches in right half. The last byte has
+ already been matched, by virtue of the shift table. */
+ i = suffix;
+ while (i < needle_len - 1 && (CANON_ELEMENT (needle[i])
+ == CANON_ELEMENT (haystack[i + j])))
+ ++i;
+ if (needle_len - 1 <= i)
+ {
+ /* Scan for matches in left half. */
+ i = suffix - 1;
+ while (i != SIZE_MAX && (CANON_ELEMENT (needle[i])
+ == CANON_ELEMENT (haystack[i + j])))
+ --i;
+ if (i == SIZE_MAX)
+ return (RETURN_TYPE) (haystack + j);
+ j += period;
+ }
+ else
+ j += i - suffix + 1;
+ }
+ }
+ return NULL;
+}
+
+#undef AVAILABLE
+#undef CANON_ELEMENT
+#undef CMP_FUNC
+#undef MAX
+#undef RETURN_TYPE
diff --git a/lib/strcspn.c b/lib/strcspn.c
deleted file mode 100644
index 5a8d6f9..0000000
--- a/lib/strcspn.c
+++ /dev/null
@@ -1,41 +0,0 @@
-/* Copyright (C) 1991, 1994, 1996-1997, 2002-2003, 2005-2006 Free Software Foundation, Inc.
-
- NOTE: The canonical source of this file is maintained with the GNU C Library.
- Bugs can be reported to bug-glibc@gnu.org.
-
- 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-#include <config.h>
-
-#include <stddef.h>
-#include <string.h>
-
-#undef strcspn
-
-/* Return the length of the maximum initial segment of S
- which contains no characters from REJECT. */
-size_t
-strcspn (const char *s, const char *reject)
-{
- size_t count = 0;
-
- while (*s != '\0')
- if (strchr (reject, *s++) == NULL)
- ++count;
- else
- return count;
-
- return count;
-}
diff --git a/lib/strdup.c b/lib/strdup.c
index c614108..81eb226 100644
--- a/lib/strdup.c
+++ b/lib/strdup.c
@@ -1,11 +1,11 @@
-/* Copyright (C) 1991, 1996, 1997, 1998, 2002, 2003, 2004, 2006, 2007 Free
- Software Foundation, Inc.
+/* Copyright (C) 1991, 1996-1998, 2002-2004, 2006-2007, 2009-2016 Free Software
+ Foundation, Inc.
This file is part of the GNU C Library.
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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -14,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ with this program; if not, see <http://www.gnu.org/licenses/>. */
#ifndef _LIBC
# include <config.h>
diff --git a/lib/streq.h b/lib/streq.h
new file mode 100644
index 0000000..234f075
--- /dev/null
+++ b/lib/streq.h
@@ -0,0 +1,176 @@
+/* Optimized string comparison.
+ Copyright (C) 2001-2002, 2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Bruno Haible <bruno@clisp.org>. */
+
+#ifndef _GL_STREQ_H
+#define _GL_STREQ_H
+
+#include <string.h>
+
+/* STREQ_OPT allows to optimize string comparison with a small literal string.
+ STREQ_OPT (s, "EUC-KR", 'E', 'U', 'C', '-', 'K', 'R', 0, 0, 0)
+ is semantically equivalent to
+ strcmp (s, "EUC-KR") == 0
+ just faster. */
+
+/* Help GCC to generate good code for string comparisons with
+ immediate strings. */
+#if defined (__GNUC__) && defined (__OPTIMIZE__)
+
+static inline int
+streq9 (const char *s1, const char *s2)
+{
+ return strcmp (s1 + 9, s2 + 9) == 0;
+}
+
+static inline int
+streq8 (const char *s1, const char *s2, char s28)
+{
+ if (s1[8] == s28)
+ {
+ if (s28 == 0)
+ return 1;
+ else
+ return streq9 (s1, s2);
+ }
+ else
+ return 0;
+}
+
+static inline int
+streq7 (const char *s1, const char *s2, char s27, char s28)
+{
+ if (s1[7] == s27)
+ {
+ if (s27 == 0)
+ return 1;
+ else
+ return streq8 (s1, s2, s28);
+ }
+ else
+ return 0;
+}
+
+static inline int
+streq6 (const char *s1, const char *s2, char s26, char s27, char s28)
+{
+ if (s1[6] == s26)
+ {
+ if (s26 == 0)
+ return 1;
+ else
+ return streq7 (s1, s2, s27, s28);
+ }
+ else
+ return 0;
+}
+
+static inline int
+streq5 (const char *s1, const char *s2, char s25, char s26, char s27, char s28)
+{
+ if (s1[5] == s25)
+ {
+ if (s25 == 0)
+ return 1;
+ else
+ return streq6 (s1, s2, s26, s27, s28);
+ }
+ else
+ return 0;
+}
+
+static inline int
+streq4 (const char *s1, const char *s2, char s24, char s25, char s26, char s27, char s28)
+{
+ if (s1[4] == s24)
+ {
+ if (s24 == 0)
+ return 1;
+ else
+ return streq5 (s1, s2, s25, s26, s27, s28);
+ }
+ else
+ return 0;
+}
+
+static inline int
+streq3 (const char *s1, const char *s2, char s23, char s24, char s25, char s26, char s27, char s28)
+{
+ if (s1[3] == s23)
+ {
+ if (s23 == 0)
+ return 1;
+ else
+ return streq4 (s1, s2, s24, s25, s26, s27, s28);
+ }
+ else
+ return 0;
+}
+
+static inline int
+streq2 (const char *s1, const char *s2, char s22, char s23, char s24, char s25, char s26, char s27, char s28)
+{
+ if (s1[2] == s22)
+ {
+ if (s22 == 0)
+ return 1;
+ else
+ return streq3 (s1, s2, s23, s24, s25, s26, s27, s28);
+ }
+ else
+ return 0;
+}
+
+static inline int
+streq1 (const char *s1, const char *s2, char s21, char s22, char s23, char s24, char s25, char s26, char s27, char s28)
+{
+ if (s1[1] == s21)
+ {
+ if (s21 == 0)
+ return 1;
+ else
+ return streq2 (s1, s2, s22, s23, s24, s25, s26, s27, s28);
+ }
+ else
+ return 0;
+}
+
+static inline int
+streq0 (const char *s1, const char *s2, char s20, char s21, char s22, char s23, char s24, char s25, char s26, char s27, char s28)
+{
+ if (s1[0] == s20)
+ {
+ if (s20 == 0)
+ return 1;
+ else
+ return streq1 (s1, s2, s21, s22, s23, s24, s25, s26, s27, s28);
+ }
+ else
+ return 0;
+}
+
+#define STREQ_OPT(s1,s2,s20,s21,s22,s23,s24,s25,s26,s27,s28) \
+ streq0 (s1, s2, s20, s21, s22, s23, s24, s25, s26, s27, s28)
+
+#else
+
+#define STREQ_OPT(s1,s2,s20,s21,s22,s23,s24,s25,s26,s27,s28) \
+ (strcmp (s1, s2) == 0)
+
+#endif
+
+#endif /* _GL_STREQ_H */
diff --git a/lib/strerror-override.c b/lib/strerror-override.c
new file mode 100644
index 0000000..9bc9b18
--- /dev/null
+++ b/lib/strerror-override.c
@@ -0,0 +1,302 @@
+/* strerror-override.c --- POSIX compatible system error routine
+
+ Copyright (C) 2010-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Bruno Haible <bruno@clisp.org>, 2010. */
+
+#include <config.h>
+
+#include "strerror-override.h"
+
+#include <errno.h>
+
+#if GNULIB_defined_EWINSOCK /* native Windows platforms */
+# if HAVE_WINSOCK2_H
+# include <winsock2.h>
+# endif
+#endif
+
+/* If ERRNUM maps to an errno value defined by gnulib, return a string
+ describing the error. Otherwise return NULL. */
+const char *
+strerror_override (int errnum)
+{
+ /* These error messages are taken from glibc/sysdeps/gnu/errlist.c. */
+ switch (errnum)
+ {
+#if REPLACE_STRERROR_0
+ case 0:
+ return "Success";
+#endif
+
+#if GNULIB_defined_ESOCK /* native Windows platforms with older <errno.h> */
+ case EINPROGRESS:
+ return "Operation now in progress";
+ case EALREADY:
+ return "Operation already in progress";
+ case ENOTSOCK:
+ return "Socket operation on non-socket";
+ case EDESTADDRREQ:
+ return "Destination address required";
+ case EMSGSIZE:
+ return "Message too long";
+ case EPROTOTYPE:
+ return "Protocol wrong type for socket";
+ case ENOPROTOOPT:
+ return "Protocol not available";
+ case EPROTONOSUPPORT:
+ return "Protocol not supported";
+ case EOPNOTSUPP:
+ return "Operation not supported";
+ case EAFNOSUPPORT:
+ return "Address family not supported by protocol";
+ case EADDRINUSE:
+ return "Address already in use";
+ case EADDRNOTAVAIL:
+ return "Cannot assign requested address";
+ case ENETDOWN:
+ return "Network is down";
+ case ENETUNREACH:
+ return "Network is unreachable";
+ case ECONNRESET:
+ return "Connection reset by peer";
+ case ENOBUFS:
+ return "No buffer space available";
+ case EISCONN:
+ return "Transport endpoint is already connected";
+ case ENOTCONN:
+ return "Transport endpoint is not connected";
+ case ETIMEDOUT:
+ return "Connection timed out";
+ case ECONNREFUSED:
+ return "Connection refused";
+ case ELOOP:
+ return "Too many levels of symbolic links";
+ case EHOSTUNREACH:
+ return "No route to host";
+ case EWOULDBLOCK:
+ return "Operation would block";
+#endif
+#if GNULIB_defined_ESTREAMS /* native Windows platforms with older <errno.h> */
+ case ETXTBSY:
+ return "Text file busy";
+ case ENODATA:
+ return "No data available";
+ case ENOSR:
+ return "Out of streams resources";
+ case ENOSTR:
+ return "Device not a stream";
+ case ETIME:
+ return "Timer expired";
+ case EOTHER:
+ return "Other error";
+#endif
+#if GNULIB_defined_EWINSOCK /* native Windows platforms */
+ case ESOCKTNOSUPPORT:
+ return "Socket type not supported";
+ case EPFNOSUPPORT:
+ return "Protocol family not supported";
+ case ESHUTDOWN:
+ return "Cannot send after transport endpoint shutdown";
+ case ETOOMANYREFS:
+ return "Too many references: cannot splice";
+ case EHOSTDOWN:
+ return "Host is down";
+ case EPROCLIM:
+ return "Too many processes";
+ case EUSERS:
+ return "Too many users";
+ case EDQUOT:
+ return "Disk quota exceeded";
+ case ESTALE:
+ return "Stale NFS file handle";
+ case EREMOTE:
+ return "Object is remote";
+# if HAVE_WINSOCK2_H
+ /* WSA_INVALID_HANDLE maps to EBADF */
+ /* WSA_NOT_ENOUGH_MEMORY maps to ENOMEM */
+ /* WSA_INVALID_PARAMETER maps to EINVAL */
+ case WSA_OPERATION_ABORTED:
+ return "Overlapped operation aborted";
+ case WSA_IO_INCOMPLETE:
+ return "Overlapped I/O event object not in signaled state";
+ case WSA_IO_PENDING:
+ return "Overlapped operations will complete later";
+ /* WSAEINTR maps to EINTR */
+ /* WSAEBADF maps to EBADF */
+ /* WSAEACCES maps to EACCES */
+ /* WSAEFAULT maps to EFAULT */
+ /* WSAEINVAL maps to EINVAL */
+ /* WSAEMFILE maps to EMFILE */
+ /* WSAEWOULDBLOCK maps to EWOULDBLOCK */
+ /* WSAEINPROGRESS maps to EINPROGRESS */
+ /* WSAEALREADY maps to EALREADY */
+ /* WSAENOTSOCK maps to ENOTSOCK */
+ /* WSAEDESTADDRREQ maps to EDESTADDRREQ */
+ /* WSAEMSGSIZE maps to EMSGSIZE */
+ /* WSAEPROTOTYPE maps to EPROTOTYPE */
+ /* WSAENOPROTOOPT maps to ENOPROTOOPT */
+ /* WSAEPROTONOSUPPORT maps to EPROTONOSUPPORT */
+ /* WSAESOCKTNOSUPPORT is ESOCKTNOSUPPORT */
+ /* WSAEOPNOTSUPP maps to EOPNOTSUPP */
+ /* WSAEPFNOSUPPORT is EPFNOSUPPORT */
+ /* WSAEAFNOSUPPORT maps to EAFNOSUPPORT */
+ /* WSAEADDRINUSE maps to EADDRINUSE */
+ /* WSAEADDRNOTAVAIL maps to EADDRNOTAVAIL */
+ /* WSAENETDOWN maps to ENETDOWN */
+ /* WSAENETUNREACH maps to ENETUNREACH */
+ /* WSAENETRESET maps to ENETRESET */
+ /* WSAECONNABORTED maps to ECONNABORTED */
+ /* WSAECONNRESET maps to ECONNRESET */
+ /* WSAENOBUFS maps to ENOBUFS */
+ /* WSAEISCONN maps to EISCONN */
+ /* WSAENOTCONN maps to ENOTCONN */
+ /* WSAESHUTDOWN is ESHUTDOWN */
+ /* WSAETOOMANYREFS is ETOOMANYREFS */
+ /* WSAETIMEDOUT maps to ETIMEDOUT */
+ /* WSAECONNREFUSED maps to ECONNREFUSED */
+ /* WSAELOOP maps to ELOOP */
+ /* WSAENAMETOOLONG maps to ENAMETOOLONG */
+ /* WSAEHOSTDOWN is EHOSTDOWN */
+ /* WSAEHOSTUNREACH maps to EHOSTUNREACH */
+ /* WSAENOTEMPTY maps to ENOTEMPTY */
+ /* WSAEPROCLIM is EPROCLIM */
+ /* WSAEUSERS is EUSERS */
+ /* WSAEDQUOT is EDQUOT */
+ /* WSAESTALE is ESTALE */
+ /* WSAEREMOTE is EREMOTE */
+ case WSASYSNOTREADY:
+ return "Network subsystem is unavailable";
+ case WSAVERNOTSUPPORTED:
+ return "Winsock.dll version out of range";
+ case WSANOTINITIALISED:
+ return "Successful WSAStartup not yet performed";
+ case WSAEDISCON:
+ return "Graceful shutdown in progress";
+ case WSAENOMORE: case WSA_E_NO_MORE:
+ return "No more results";
+ case WSAECANCELLED: case WSA_E_CANCELLED:
+ return "Call was canceled";
+ case WSAEINVALIDPROCTABLE:
+ return "Procedure call table is invalid";
+ case WSAEINVALIDPROVIDER:
+ return "Service provider is invalid";
+ case WSAEPROVIDERFAILEDINIT:
+ return "Service provider failed to initialize";
+ case WSASYSCALLFAILURE:
+ return "System call failure";
+ case WSASERVICE_NOT_FOUND:
+ return "Service not found";
+ case WSATYPE_NOT_FOUND:
+ return "Class type not found";
+ case WSAEREFUSED:
+ return "Database query was refused";
+ case WSAHOST_NOT_FOUND:
+ return "Host not found";
+ case WSATRY_AGAIN:
+ return "Nonauthoritative host not found";
+ case WSANO_RECOVERY:
+ return "Nonrecoverable error";
+ case WSANO_DATA:
+ return "Valid name, no data record of requested type";
+ /* WSA_QOS_* omitted */
+# endif
+#endif
+
+#if GNULIB_defined_ENOMSG
+ case ENOMSG:
+ return "No message of desired type";
+#endif
+
+#if GNULIB_defined_EIDRM
+ case EIDRM:
+ return "Identifier removed";
+#endif
+
+#if GNULIB_defined_ENOLINK
+ case ENOLINK:
+ return "Link has been severed";
+#endif
+
+#if GNULIB_defined_EPROTO
+ case EPROTO:
+ return "Protocol error";
+#endif
+
+#if GNULIB_defined_EMULTIHOP
+ case EMULTIHOP:
+ return "Multihop attempted";
+#endif
+
+#if GNULIB_defined_EBADMSG
+ case EBADMSG:
+ return "Bad message";
+#endif
+
+#if GNULIB_defined_EOVERFLOW
+ case EOVERFLOW:
+ return "Value too large for defined data type";
+#endif
+
+#if GNULIB_defined_ENOTSUP
+ case ENOTSUP:
+ return "Not supported";
+#endif
+
+#if GNULIB_defined_ENETRESET
+ case ENETRESET:
+ return "Network dropped connection on reset";
+#endif
+
+#if GNULIB_defined_ECONNABORTED
+ case ECONNABORTED:
+ return "Software caused connection abort";
+#endif
+
+#if GNULIB_defined_ESTALE
+ case ESTALE:
+ return "Stale NFS file handle";
+#endif
+
+#if GNULIB_defined_EDQUOT
+ case EDQUOT:
+ return "Disk quota exceeded";
+#endif
+
+#if GNULIB_defined_ECANCELED
+ case ECANCELED:
+ return "Operation canceled";
+#endif
+
+#if GNULIB_defined_EOWNERDEAD
+ case EOWNERDEAD:
+ return "Owner died";
+#endif
+
+#if GNULIB_defined_ENOTRECOVERABLE
+ case ENOTRECOVERABLE:
+ return "State not recoverable";
+#endif
+
+#if GNULIB_defined_EILSEQ
+ case EILSEQ:
+ return "Invalid or incomplete multibyte or wide character";
+#endif
+
+ default:
+ return NULL;
+ }
+}
diff --git a/lib/strerror-override.h b/lib/strerror-override.h
new file mode 100644
index 0000000..5264fd5
--- /dev/null
+++ b/lib/strerror-override.h
@@ -0,0 +1,56 @@
+/* strerror-override.h --- POSIX compatible system error routine
+
+ Copyright (C) 2010-2016 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _GL_STRERROR_OVERRIDE_H
+# define _GL_STRERROR_OVERRIDE_H
+
+# include <errno.h>
+# include <stddef.h>
+
+/* Reasonable buffer size that should never trigger ERANGE; if this
+ proves too small, we intentionally abort(), to remind us to fix
+ this value. */
+# define STACKBUF_LEN 256
+
+/* If ERRNUM maps to an errno value defined by gnulib, return a string
+ describing the error. Otherwise return NULL. */
+# if REPLACE_STRERROR_0 \
+ || GNULIB_defined_ESOCK \
+ || GNULIB_defined_ESTREAMS \
+ || GNULIB_defined_EWINSOCK \
+ || GNULIB_defined_ENOMSG \
+ || GNULIB_defined_EIDRM \
+ || GNULIB_defined_ENOLINK \
+ || GNULIB_defined_EPROTO \
+ || GNULIB_defined_EMULTIHOP \
+ || GNULIB_defined_EBADMSG \
+ || GNULIB_defined_EOVERFLOW \
+ || GNULIB_defined_ENOTSUP \
+ || GNULIB_defined_ENETRESET \
+ || GNULIB_defined_ECONNABORTED \
+ || GNULIB_defined_ESTALE \
+ || GNULIB_defined_EDQUOT \
+ || GNULIB_defined_ECANCELED \
+ || GNULIB_defined_EOWNERDEAD \
+ || GNULIB_defined_ENOTRECOVERABLE \
+ || GNULIB_defined_EILSEQ
+extern const char *strerror_override (int errnum) _GL_ATTRIBUTE_CONST;
+# else
+# define strerror_override(ignored) NULL
+# endif
+
+#endif /* _GL_STRERROR_OVERRIDE_H */
diff --git a/lib/strerror.c b/lib/strerror.c
new file mode 100644
index 0000000..45c7633
--- /dev/null
+++ b/lib/strerror.c
@@ -0,0 +1,70 @@
+/* strerror.c --- POSIX compatible system error routine
+
+ Copyright (C) 2007-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <string.h>
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "intprops.h"
+#include "strerror-override.h"
+#include "verify.h"
+
+/* Use the system functions, not the gnulib overrides in this file. */
+#undef sprintf
+
+char *
+strerror (int n)
+#undef strerror
+{
+ static char buf[STACKBUF_LEN];
+ size_t len;
+
+ /* Cast away const, due to the historical signature of strerror;
+ callers should not be modifying the string. */
+ const char *msg = strerror_override (n);
+ if (msg)
+ return (char *) msg;
+
+ msg = strerror (n);
+
+ /* Our strerror_r implementation might use the system's strerror
+ buffer, so all other clients of strerror have to see the error
+ copied into a buffer that we manage. This is not thread-safe,
+ even if the system strerror is, but portable programs shouldn't
+ be using strerror if they care about thread-safety. */
+ if (!msg || !*msg)
+ {
+ static char const fmt[] = "Unknown error %d";
+ verify (sizeof buf >= sizeof (fmt) + INT_STRLEN_BOUND (n));
+ sprintf (buf, fmt, n);
+ errno = EINVAL;
+ return buf;
+ }
+
+ /* Fix STACKBUF_LEN if this ever aborts. */
+ len = strlen (msg);
+ if (sizeof buf <= len)
+ abort ();
+
+ return memcpy (buf, msg, len + 1);
+}
diff --git a/lib/strftime.c b/lib/strftime.c
index 1c202c9..10d3eb4 100644
--- a/lib/strftime.c
+++ b/lib/strftime.c
@@ -1,64 +1,64 @@
-/* Copyright (C) 1991-1999, 2000, 2001, 2003, 2004, 2005, 2006, 2007 Free Software
- Foundation, Inc.
+/* Copyright (C) 1991-2001, 2003-2007, 2009-2016 Free Software Foundation, Inc.
NOTE: The canonical source of this file is maintained with the GNU C Library.
Bugs can be reported to bug-glibc@prep.ai.mit.edu.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifdef _LIBC
-# define HAVE_MBLEN 1
-# define HAVE_MBRLEN 1
# define HAVE_STRUCT_ERA_ENTRY 1
# define HAVE_TM_GMTOFF 1
# define HAVE_TM_ZONE 1
# define HAVE_TZNAME 1
# define HAVE_TZSET 1
-# define MULTIBYTE_IS_FORMAT_SAFE 1
# include "../locale/localeinfo.h"
#else
# include <config.h>
# if FPRINTFTIME
# include "fprintftime.h"
+# else
+# include "strftime.h"
# endif
+# include "time-internal.h"
#endif
#include <ctype.h>
#include <time.h>
-#if HAVE_TZNAME && ! defined tzname
+#if HAVE_TZNAME && !HAVE_DECL_TZNAME
extern char *tzname[];
#endif
-/* Do multibyte processing if multibytes are supported, unless
+/* Do multibyte processing if multibyte encodings are supported, unless
multibyte sequences are safe in formats. Multibyte sequences are
safe if they cannot contain byte sequences that look like format
- conversion specifications. The GNU C Library uses UTF8 multibyte
- encoding, which is safe for formats, but strftime.c can be used
- with other C libraries that use unsafe encodings. */
-#define DO_MULTIBYTE (HAVE_MBLEN && ! MULTIBYTE_IS_FORMAT_SAFE)
+ conversion specifications. The multibyte encodings used by the
+ C library on the various platforms (UTF-8, GB2312, GBK, CP936,
+ GB18030, EUC-TW, BIG5, BIG5-HKSCS, CP950, EUC-JP, EUC-KR, CP949,
+ SHIFT_JIS, CP932, JOHAB) are safe for formats, because the byte '%'
+ cannot occur in a multibyte character except in the first byte.
+
+ The DEC-HANYU encoding used on OSF/1 is not safe for formats, but
+ this encoding has never been seen in real-life use, so we ignore
+ it. */
+#if !(defined __osf__ && 0)
+# define MULTIBYTE_IS_FORMAT_SAFE 1
+#endif
+#define DO_MULTIBYTE (! MULTIBYTE_IS_FORMAT_SAFE)
#if DO_MULTIBYTE
-# if HAVE_MBRLEN
-# include <wchar.h>
-# else
- /* Simulate mbrlen with mblen as best we can. */
-# define mbstate_t int
-# define mbrlen(s, n, ps) mblen (s, n)
-# define mbsinit(ps) (*(ps) == 0)
-# endif
+# include <wchar.h>
static const mbstate_t mbstate_zero;
#endif
@@ -87,13 +87,6 @@ extern char *tzname[];
# define MEMCPY(d, s, n) memcpy (d, s, n)
# define STRLEN(s) strlen (s)
-# ifdef _LIBC
-# define MEMPCPY(d, s, n) __mempcpy (d, s, n)
-# else
-# ifndef HAVE_MEMPCPY
-# define MEMPCPY(d, s, n) ((void *) ((char *) memcpy (d, s, n) + (n)))
-# endif
-# endif
#endif
/* Shift A right by B bits portably, by dividing A by 2**B and
@@ -106,9 +99,9 @@ extern char *tzname[];
implementations (e.g., UNICOS 9.0 on a Cray Y-MP EL) don't shift
right in the usual way when A < 0, so SHR falls back on division if
ordinary A >> B doesn't seem to be the usual signed shift. */
-#define SHR(a, b) \
- (-1 >> 1 == -1 \
- ? (a) >> (b) \
+#define SHR(a, b) \
+ (-1 >> 1 == -1 \
+ ? (a) >> (b) \
: (a) / (1 << (b)) - ((a) % (1 << (b)) < 0))
/* Bound on length of the string representing an integer type or expression T.
@@ -123,28 +116,17 @@ extern char *tzname[];
#ifndef __isleap
/* Nonzero if YEAR is a leap year (every 4 years,
except every 100th isn't, and every 400th is). */
-# define __isleap(year) \
+# define __isleap(year) \
((year) % 4 == 0 && ((year) % 100 != 0 || (year) % 400 == 0))
#endif
#ifdef _LIBC
+# define mktime_z(tz, tm) mktime (tm)
# define tzname __tzname
# define tzset __tzset
#endif
-#if !HAVE_TM_GMTOFF
-/* Portable standalone applications should supply a "time.h" that
- declares a POSIX-compliant localtime_r, for the benefit of older
- implementations that lack localtime_r or have a nonstandard one.
- See the gnulib time_r module for one way to implement this. */
-# undef __gmtime_r
-# undef __localtime_r
-# define __gmtime_r gmtime_r
-# define __localtime_r localtime_r
-#endif
-
-
#ifndef FPRINTFTIME
# define FPRINTFTIME 0
#endif
@@ -176,27 +158,28 @@ extern char *tzname[];
# define advance(P, N) ((P) += (N))
#endif
-#define add(n, f) \
- do \
- { \
- int _n = (n); \
- int _delta = width - _n; \
- int _incr = _n + (_delta > 0 ? _delta : 0); \
- if ((size_t) _incr >= maxsize - i) \
- return 0; \
- if (p) \
- { \
- if (digits == 0 && _delta > 0) \
- { \
- if (pad == L_('0')) \
- memset_zero (p, _delta); \
- else \
- memset_space (p, _delta); \
- } \
- f; \
- advance (p, _n); \
- } \
- i += _incr; \
+#define add(n, f) \
+ do \
+ { \
+ size_t _n = (n); \
+ size_t _w = (width < 0 ? 0 : width); \
+ size_t _incr = _n < _w ? _w : _n; \
+ if (_incr >= maxsize - i) \
+ return 0; \
+ if (p) \
+ { \
+ if (digits == 0 && _n < _w) \
+ { \
+ size_t _delta = width - _n; \
+ if (pad == L_('0')) \
+ memset_zero (p, _delta); \
+ else \
+ memset_space (p, _delta); \
+ } \
+ f; \
+ advance (p, _n); \
+ } \
+ i += _incr; \
} while (0)
#if FPRINTFTIME
@@ -207,22 +190,34 @@ extern char *tzname[];
#if FPRINTFTIME
# define cpy(n, s) \
- add ((n), \
- if (to_lowcase) \
- fwrite_lowcase (p, (s), _n); \
- else if (to_uppcase) \
- fwrite_uppcase (p, (s), _n); \
- else \
- fwrite ((s), _n, 1, p))
+ add ((n), \
+ do \
+ { \
+ if (to_lowcase) \
+ fwrite_lowcase (p, (s), _n); \
+ else if (to_uppcase) \
+ fwrite_uppcase (p, (s), _n); \
+ else \
+ { \
+ /* Ignore the value of fwrite. The caller can determine whether \
+ an error occurred by inspecting ferror (P). All known fwrite \
+ implementations set the stream's error indicator when they \
+ fail due to ENOMEM etc., even though C11 and POSIX.1-2008 do \
+ not require this. */ \
+ fwrite (s, _n, 1, p); \
+ } \
+ } \
+ while (0) \
+ )
#else
-# define cpy(n, s) \
- add ((n), \
- if (to_lowcase) \
- memcpy_lowcase (p, (s), _n LOCALE_ARG); \
- else if (to_uppcase) \
- memcpy_uppcase (p, (s), _n LOCALE_ARG); \
- else \
- MEMCPY ((void *) p, (void const *) (s), _n))
+# define cpy(n, s) \
+ add ((n), \
+ if (to_lowcase) \
+ memcpy_lowcase (p, (s), _n LOCALE_ARG); \
+ else if (to_uppcase) \
+ memcpy_uppcase (p, (s), _n LOCALE_ARG); \
+ else \
+ MEMCPY ((void *) p, (void const *) (s), _n))
#endif
#ifdef COMPILE_WIDE
@@ -231,13 +226,13 @@ extern char *tzname[];
# define __mbsrtowcs_l(d, s, l, st, loc) __mbsrtowcs (d, s, l, st)
# endif
# define widen(os, ws, l) \
- { \
- mbstate_t __st; \
- const char *__s = os; \
- memset (&__st, '\0', sizeof (__st)); \
- l = __mbsrtowcs_l (NULL, &__s, 0, &__st, loc); \
- ws = (wchar_t *) alloca ((l + 1) * sizeof (wchar_t)); \
- (void) __mbsrtowcs_l (ws, &__s, l, &__st, loc); \
+ { \
+ mbstate_t __st; \
+ const char *__s = os; \
+ memset (&__st, '\0', sizeof (__st)); \
+ l = __mbsrtowcs_l (NULL, &__s, 0, &__st, loc); \
+ ws = (wchar_t *) alloca ((l + 1) * sizeof (wchar_t)); \
+ (void) __mbsrtowcs_l (ws, &__s, l, &__st, loc); \
}
#endif
@@ -247,8 +242,8 @@ extern char *tzname[];
function gets as an additional argument the locale which has to be
used. To access the values we have to redefine the _NL_CURRENT
macro. */
-# define strftime __strftime_l
-# define wcsftime __wcsftime_l
+# define strftime __strftime_l
+# define wcsftime __wcsftime_l
# undef _NL_CURRENT
# define _NL_CURRENT(category, item) \
(current->values[_NL_ITEM_INDEX (item)].string)
@@ -282,7 +277,7 @@ extern char *tzname[];
# define TOLOWER(Ch, L) tolower (Ch)
# endif
#endif
-/* We don't use `isdigit' here since the locale dependent
+/* We don't use 'isdigit' here since the locale dependent
interpretation is not what we want here. We only need to accept
the arabic digits in the ASCII range. One day there is perhaps a
more reliable way to accept other sets of digits. */
@@ -311,7 +306,7 @@ fwrite_uppcase (FILE *fp, const CHAR_T *src, size_t len)
#else
static CHAR_T *
memcpy_lowcase (CHAR_T *dest, const CHAR_T *src,
- size_t len LOCALE_PARAM_PROTO)
+ size_t len LOCALE_PARAM_PROTO)
{
while (len-- > 0)
dest[len] = TOLOWER ((UCHAR_T) src[len], loc);
@@ -320,7 +315,7 @@ memcpy_lowcase (CHAR_T *dest, const CHAR_T *src,
static CHAR_T *
memcpy_uppcase (CHAR_T *dest, const CHAR_T *src,
- size_t len LOCALE_PARAM_PROTO)
+ size_t len LOCALE_PARAM_PROTO)
{
while (len-- > 0)
dest[len] = TOUPPER ((UCHAR_T) src[len], loc);
@@ -348,10 +343,10 @@ tm_diff (const struct tm *a, const struct tm *b)
int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
int years = a->tm_year - b->tm_year;
int days = (365 * years + intervening_leap_days
- + (a->tm_yday - b->tm_yday));
+ + (a->tm_yday - b->tm_yday));
return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
- + (a->tm_min - b->tm_min))
- + (a->tm_sec - b->tm_sec));
+ + (a->tm_min - b->tm_min))
+ + (a->tm_sec - b->tm_sec));
}
#endif /* ! HAVE_TM_GMTOFF */
@@ -373,19 +368,14 @@ iso_week_days (int yday, int wday)
/* Add enough to the first operand of % to make it nonnegative. */
int big_enough_multiple_of_7 = (-YDAY_MINIMUM / 7 + 2) * 7;
return (yday
- - (yday - wday + ISO_WEEK1_WDAY + big_enough_multiple_of_7) % 7
- + ISO_WEEK1_WDAY - ISO_WEEK_START_WDAY);
+ - (yday - wday + ISO_WEEK1_WDAY + big_enough_multiple_of_7) % 7
+ + ISO_WEEK1_WDAY - ISO_WEEK_START_WDAY);
}
/* When compiling this file, GNU applications can #define my_strftime
to a symbol (typically nstrftime) to get an extended strftime with
- extra arguments UT and NS. Emacs is a special case for now, but
- this Emacs-specific code can be removed once Emacs's config.h
- defines my_strftime. */
-#if defined emacs && !defined my_strftime
-# define my_strftime nstrftime
-#endif
+ extra arguments TZ and NS. */
#if FPRINTFTIME
# undef my_strftime
@@ -393,8 +383,9 @@ iso_week_days (int yday, int wday)
#endif
#ifdef my_strftime
-# define extra_args , ut, ns
-# define extra_args_spec , int ut, int ns
+# undef HAVE_TZSET
+# define extra_args , tz, ns
+# define extra_args_spec , timezone_t tz, int ns
#else
# if defined COMPILE_WIDE
# define my_strftime wcsftime
@@ -406,7 +397,7 @@ iso_week_days (int yday, int wday)
# define extra_args
# define extra_args_spec
/* We don't have this information in general. */
-# define ut 0
+# define tz 1
# define ns 0
#endif
@@ -415,9 +406,9 @@ iso_week_days (int yday, int wday)
to indicate that the result should be converted to upper case. */
static size_t
strftime_case_ (bool upcase, STREAM_OR_CHAR_T *s,
- STRFTIME_ARG (size_t maxsize)
- const CHAR_T *format,
- const struct tm *tp extra_args_spec LOCALE_PARAM_PROTO)
+ STRFTIME_ARG (size_t maxsize)
+ const CHAR_T *format,
+ const struct tm *tp extra_args_spec LOCALE_PARAM_PROTO)
{
#if defined _LIBC && defined USE_IN_EXTENDED_LOCALE_MODEL
struct locale_data *const current = loc->__locales[LC_TIME];
@@ -430,7 +421,7 @@ strftime_case_ (bool upcase, STREAM_OR_CHAR_T *s,
#ifdef _NL_CURRENT
/* We cannot make the following values variables since we must delay
the evaluation of these values until really needed since some
- expressions might not be valid in every situation. The `struct tm'
+ expressions might not be valid in every situation. The 'struct tm'
might be generated by a strptime() call that initialized
only a few elements. Dereference the pointers only if the format
requires this. Then it is ok to fail if the pointers are invalid. */
@@ -443,13 +434,16 @@ strftime_case_ (bool upcase, STREAM_OR_CHAR_T *s,
# define f_month \
((const CHAR_T *) _NL_CURRENT (LC_TIME, NLW(MON_1) + tp->tm_mon))
# define ampm \
- ((const CHAR_T *) _NL_CURRENT (LC_TIME, tp->tm_hour > 11 \
- ? NLW(PM_STR) : NLW(AM_STR)))
+ ((const CHAR_T *) _NL_CURRENT (LC_TIME, tp->tm_hour > 11 \
+ ? NLW(PM_STR) : NLW(AM_STR)))
# define aw_len STRLEN (a_wkday)
# define am_len STRLEN (a_month)
# define ap_len STRLEN (ampm)
#endif
+#if HAVE_TZNAME
+ char **tzname_vec = tzname;
+#endif
const char *zone;
size_t i = 0;
STREAM_OR_CHAR_T *p = s;
@@ -478,20 +472,29 @@ strftime_case_ (bool upcase, STREAM_OR_CHAR_T *s,
zone = (const char *) tp->tm_zone;
#endif
#if HAVE_TZNAME
- if (ut)
+ if (!tz)
{
if (! (zone && *zone))
- zone = "GMT";
+ zone = "GMT";
}
else
{
+# if !HAVE_TM_ZONE
+ /* Infer the zone name from *TZ instead of from TZNAME. */
+ tzname_vec = tz->tzname_copy;
+# endif
/* POSIX.1 requires that local time zone information be used as
- though strftime called tzset. */
+ though strftime called tzset. */
# if HAVE_TZSET
tzset ();
# endif
}
+ /* The tzset() call might have changed the value. */
+ if (!(zone && *zone) && tp->tm_isdst >= 0)
+ zone = tzname_vec[tp->tm_isdst != 0];
#endif
+ if (! zone)
+ zone = "";
if (hour12 > 12)
hour12 -= 12;
@@ -501,22 +504,22 @@ strftime_case_ (bool upcase, STREAM_OR_CHAR_T *s,
for (f = format; *f != '\0'; ++f)
{
- int pad = 0; /* Padding for number ('-', '_', or 0). */
- int modifier; /* Field modifier ('E', 'O', or 0). */
- int digits = 0; /* Max digits for numeric format. */
- int number_value; /* Numeric value to be printed. */
+ int pad = 0; /* Padding for number ('-', '_', or 0). */
+ int modifier; /* Field modifier ('E', 'O', or 0). */
+ int digits = 0; /* Max digits for numeric format. */
+ int number_value; /* Numeric value to be printed. */
unsigned int u_number_value; /* (unsigned int) number_value. */
- bool negative_number; /* The number is negative. */
+ bool negative_number; /* The number is negative. */
bool always_output_a_sign; /* +/- should always be output. */
- int tz_colon_mask; /* Bitmask of where ':' should appear. */
+ int tz_colon_mask; /* Bitmask of where ':' should appear. */
const CHAR_T *subfmt;
CHAR_T sign_char;
CHAR_T *bufp;
CHAR_T buf[1
- + 2 /* for the two colons in a %::z or %:::z time zone */
- + (sizeof (int) < sizeof (time_t)
- ? INT_STRLEN_BOUND (time_t)
- : INT_STRLEN_BOUND (int))];
+ + 2 /* for the two colons in a %::z or %:::z time zone */
+ + (sizeof (int) < sizeof (time_t)
+ ? INT_STRLEN_BOUND (time_t)
+ : INT_STRLEN_BOUND (int))];
int width = -1;
bool to_lowcase = false;
bool to_uppcase = upcase;
@@ -526,900 +529,912 @@ strftime_case_ (bool upcase, STREAM_OR_CHAR_T *s,
#if DO_MULTIBYTE && !defined COMPILE_WIDE
switch (*f)
- {
- case L_('%'):
- break;
-
- case L_('\b'): case L_('\t'): case L_('\n'):
- case L_('\v'): case L_('\f'): case L_('\r'):
- case L_(' '): case L_('!'): case L_('"'): case L_('#'): case L_('&'):
- case L_('\''): case L_('('): case L_(')'): case L_('*'): case L_('+'):
- case L_(','): case L_('-'): case L_('.'): case L_('/'): case L_('0'):
- case L_('1'): case L_('2'): case L_('3'): case L_('4'): case L_('5'):
- case L_('6'): case L_('7'): case L_('8'): case L_('9'): case L_(':'):
- case L_(';'): case L_('<'): case L_('='): case L_('>'): case L_('?'):
- case L_('A'): case L_('B'): case L_('C'): case L_('D'): case L_('E'):
- case L_('F'): case L_('G'): case L_('H'): case L_('I'): case L_('J'):
- case L_('K'): case L_('L'): case L_('M'): case L_('N'): case L_('O'):
- case L_('P'): case L_('Q'): case L_('R'): case L_('S'): case L_('T'):
- case L_('U'): case L_('V'): case L_('W'): case L_('X'): case L_('Y'):
- case L_('Z'): case L_('['): case L_('\\'): case L_(']'): case L_('^'):
- case L_('_'): case L_('a'): case L_('b'): case L_('c'): case L_('d'):
- case L_('e'): case L_('f'): case L_('g'): case L_('h'): case L_('i'):
- case L_('j'): case L_('k'): case L_('l'): case L_('m'): case L_('n'):
- case L_('o'): case L_('p'): case L_('q'): case L_('r'): case L_('s'):
- case L_('t'): case L_('u'): case L_('v'): case L_('w'): case L_('x'):
- case L_('y'): case L_('z'): case L_('{'): case L_('|'): case L_('}'):
- case L_('~'):
- /* The C Standard requires these 98 characters (plus '%') to
- be in the basic execution character set. None of these
- characters can start a multibyte sequence, so they need
- not be analyzed further. */
- add1 (*f);
- continue;
-
- default:
- /* Copy this multibyte sequence until we reach its end, find
- an error, or come back to the initial shift state. */
- {
- mbstate_t mbstate = mbstate_zero;
- size_t len = 0;
- size_t fsize;
-
- if (! format_end)
- format_end = f + strlen (f) + 1;
- fsize = format_end - f;
-
- do
- {
- size_t bytes = mbrlen (f + len, fsize - len, &mbstate);
-
- if (bytes == 0)
- break;
-
- if (bytes == (size_t) -2)
- {
- len += strlen (f + len);
- break;
- }
-
- if (bytes == (size_t) -1)
- {
- len++;
- break;
- }
-
- len += bytes;
- }
- while (! mbsinit (&mbstate));
-
- cpy (len, f);
- f += len - 1;
- continue;
- }
- }
+ {
+ case L_('%'):
+ break;
+
+ case L_('\b'): case L_('\t'): case L_('\n'):
+ case L_('\v'): case L_('\f'): case L_('\r'):
+ case L_(' '): case L_('!'): case L_('"'): case L_('#'): case L_('&'):
+ case L_('\''): case L_('('): case L_(')'): case L_('*'): case L_('+'):
+ case L_(','): case L_('-'): case L_('.'): case L_('/'): case L_('0'):
+ case L_('1'): case L_('2'): case L_('3'): case L_('4'): case L_('5'):
+ case L_('6'): case L_('7'): case L_('8'): case L_('9'): case L_(':'):
+ case L_(';'): case L_('<'): case L_('='): case L_('>'): case L_('?'):
+ case L_('A'): case L_('B'): case L_('C'): case L_('D'): case L_('E'):
+ case L_('F'): case L_('G'): case L_('H'): case L_('I'): case L_('J'):
+ case L_('K'): case L_('L'): case L_('M'): case L_('N'): case L_('O'):
+ case L_('P'): case L_('Q'): case L_('R'): case L_('S'): case L_('T'):
+ case L_('U'): case L_('V'): case L_('W'): case L_('X'): case L_('Y'):
+ case L_('Z'): case L_('['): case L_('\\'): case L_(']'): case L_('^'):
+ case L_('_'): case L_('a'): case L_('b'): case L_('c'): case L_('d'):
+ case L_('e'): case L_('f'): case L_('g'): case L_('h'): case L_('i'):
+ case L_('j'): case L_('k'): case L_('l'): case L_('m'): case L_('n'):
+ case L_('o'): case L_('p'): case L_('q'): case L_('r'): case L_('s'):
+ case L_('t'): case L_('u'): case L_('v'): case L_('w'): case L_('x'):
+ case L_('y'): case L_('z'): case L_('{'): case L_('|'): case L_('}'):
+ case L_('~'):
+ /* The C Standard requires these 98 characters (plus '%') to
+ be in the basic execution character set. None of these
+ characters can start a multibyte sequence, so they need
+ not be analyzed further. */
+ add1 (*f);
+ continue;
+
+ default:
+ /* Copy this multibyte sequence until we reach its end, find
+ an error, or come back to the initial shift state. */
+ {
+ mbstate_t mbstate = mbstate_zero;
+ size_t len = 0;
+ size_t fsize;
+
+ if (! format_end)
+ format_end = f + strlen (f) + 1;
+ fsize = format_end - f;
+
+ do
+ {
+ size_t bytes = mbrlen (f + len, fsize - len, &mbstate);
+
+ if (bytes == 0)
+ break;
+
+ if (bytes == (size_t) -2)
+ {
+ len += strlen (f + len);
+ break;
+ }
+
+ if (bytes == (size_t) -1)
+ {
+ len++;
+ break;
+ }
+
+ len += bytes;
+ }
+ while (! mbsinit (&mbstate));
+
+ cpy (len, f);
+ f += len - 1;
+ continue;
+ }
+ }
#else /* ! DO_MULTIBYTE */
/* Either multibyte encodings are not supported, they are
- safe for formats, so any non-'%' byte can be copied through,
- or this is the wide character version. */
+ safe for formats, so any non-'%' byte can be copied through,
+ or this is the wide character version. */
if (*f != L_('%'))
- {
- add1 (*f);
- continue;
- }
+ {
+ add1 (*f);
+ continue;
+ }
#endif /* ! DO_MULTIBYTE */
/* Check for flags that can modify a format. */
while (1)
- {
- switch (*++f)
- {
- /* This influences the number formats. */
- case L_('_'):
- case L_('-'):
- case L_('0'):
- pad = *f;
- continue;
-
- /* This changes textual output. */
- case L_('^'):
- to_uppcase = true;
- continue;
- case L_('#'):
- change_case = true;
- continue;
-
- default:
- break;
- }
- break;
- }
+ {
+ switch (*++f)
+ {
+ /* This influences the number formats. */
+ case L_('_'):
+ case L_('-'):
+ case L_('0'):
+ pad = *f;
+ continue;
+
+ /* This changes textual output. */
+ case L_('^'):
+ to_uppcase = true;
+ continue;
+ case L_('#'):
+ change_case = true;
+ continue;
+
+ default:
+ break;
+ }
+ break;
+ }
/* As a GNU extension we allow to specify the field width. */
if (ISDIGIT (*f))
- {
- width = 0;
- do
- {
- if (width > INT_MAX / 10
- || (width == INT_MAX / 10 && *f - L_('0') > INT_MAX % 10))
- /* Avoid overflow. */
- width = INT_MAX;
- else
- {
- width *= 10;
- width += *f - L_('0');
- }
- ++f;
- }
- while (ISDIGIT (*f));
- }
+ {
+ width = 0;
+ do
+ {
+ if (width > INT_MAX / 10
+ || (width == INT_MAX / 10 && *f - L_('0') > INT_MAX % 10))
+ /* Avoid overflow. */
+ width = INT_MAX;
+ else
+ {
+ width *= 10;
+ width += *f - L_('0');
+ }
+ ++f;
+ }
+ while (ISDIGIT (*f));
+ }
/* Check for modifiers. */
switch (*f)
- {
- case L_('E'):
- case L_('O'):
- modifier = *f++;
- break;
+ {
+ case L_('E'):
+ case L_('O'):
+ modifier = *f++;
+ break;
- default:
- modifier = 0;
- break;
- }
+ default:
+ modifier = 0;
+ break;
+ }
/* Now do the specified format. */
format_char = *f;
switch (format_char)
- {
+ {
#define DO_NUMBER(d, v) \
- digits = d; \
- number_value = v; goto do_number
+ do \
+ { \
+ digits = d; \
+ number_value = v; \
+ goto do_number; \
+ } \
+ while (0)
#define DO_SIGNED_NUMBER(d, negative, v) \
- digits = d; \
- negative_number = negative; \
- u_number_value = v; goto do_signed_number
-
- /* The mask is not what you might think.
- When the ordinal i'th bit is set, insert a colon
- before the i'th digit of the time zone representation. */
+ do \
+ { \
+ digits = d; \
+ negative_number = negative; \
+ u_number_value = v; \
+ goto do_signed_number; \
+ } \
+ while (0)
+
+ /* The mask is not what you might think.
+ When the ordinal i'th bit is set, insert a colon
+ before the i'th digit of the time zone representation. */
#define DO_TZ_OFFSET(d, negative, mask, v) \
- digits = d; \
- negative_number = negative; \
- tz_colon_mask = mask; \
- u_number_value = v; goto do_tz_offset
+ do \
+ { \
+ digits = d; \
+ negative_number = negative; \
+ tz_colon_mask = mask; \
+ u_number_value = v; \
+ goto do_tz_offset; \
+ } \
+ while (0)
#define DO_NUMBER_SPACEPAD(d, v) \
- digits = d; \
- number_value = v; goto do_number_spacepad
-
- case L_('%'):
- if (modifier != 0)
- goto bad_format;
- add1 (*f);
- break;
-
- case L_('a'):
- if (modifier != 0)
- goto bad_format;
- if (change_case)
- {
- to_uppcase = true;
- to_lowcase = false;
- }
+ do \
+ { \
+ digits = d; \
+ number_value = v; \
+ goto do_number_spacepad; \
+ } \
+ while (0)
+
+ case L_('%'):
+ if (modifier != 0)
+ goto bad_format;
+ add1 (*f);
+ break;
+
+ case L_('a'):
+ if (modifier != 0)
+ goto bad_format;
+ if (change_case)
+ {
+ to_uppcase = true;
+ to_lowcase = false;
+ }
#ifdef _NL_CURRENT
- cpy (aw_len, a_wkday);
- break;
+ cpy (aw_len, a_wkday);
+ break;
#else
- goto underlying_strftime;
+ goto underlying_strftime;
#endif
- case 'A':
- if (modifier != 0)
- goto bad_format;
- if (change_case)
- {
- to_uppcase = true;
- to_lowcase = false;
- }
+ case 'A':
+ if (modifier != 0)
+ goto bad_format;
+ if (change_case)
+ {
+ to_uppcase = true;
+ to_lowcase = false;
+ }
#ifdef _NL_CURRENT
- cpy (STRLEN (f_wkday), f_wkday);
- break;
+ cpy (STRLEN (f_wkday), f_wkday);
+ break;
#else
- goto underlying_strftime;
+ goto underlying_strftime;
#endif
- case L_('b'):
- case L_('h'):
- if (change_case)
- {
- to_uppcase = true;
- to_lowcase = false;
- }
- if (modifier != 0)
- goto bad_format;
+ case L_('b'):
+ case L_('h'):
+ if (change_case)
+ {
+ to_uppcase = true;
+ to_lowcase = false;
+ }
+ if (modifier != 0)
+ goto bad_format;
#ifdef _NL_CURRENT
- cpy (am_len, a_month);
- break;
+ cpy (am_len, a_month);
+ break;
#else
- goto underlying_strftime;
+ goto underlying_strftime;
#endif
- case L_('B'):
- if (modifier != 0)
- goto bad_format;
- if (change_case)
- {
- to_uppcase = true;
- to_lowcase = false;
- }
+ case L_('B'):
+ if (modifier != 0)
+ goto bad_format;
+ if (change_case)
+ {
+ to_uppcase = true;
+ to_lowcase = false;
+ }
#ifdef _NL_CURRENT
- cpy (STRLEN (f_month), f_month);
- break;
+ cpy (STRLEN (f_month), f_month);
+ break;
#else
- goto underlying_strftime;
+ goto underlying_strftime;
#endif
- case L_('c'):
- if (modifier == L_('O'))
- goto bad_format;
+ case L_('c'):
+ if (modifier == L_('O'))
+ goto bad_format;
#ifdef _NL_CURRENT
- if (! (modifier == 'E'
- && (*(subfmt =
- (const CHAR_T *) _NL_CURRENT (LC_TIME,
- NLW(ERA_D_T_FMT)))
- != '\0')))
- subfmt = (const CHAR_T *) _NL_CURRENT (LC_TIME, NLW(D_T_FMT));
+ if (! (modifier == 'E'
+ && (*(subfmt =
+ (const CHAR_T *) _NL_CURRENT (LC_TIME,
+ NLW(ERA_D_T_FMT)))
+ != '\0')))
+ subfmt = (const CHAR_T *) _NL_CURRENT (LC_TIME, NLW(D_T_FMT));
#else
- goto underlying_strftime;
+ goto underlying_strftime;
#endif
- subformat:
- {
- size_t len = strftime_case_ (to_uppcase,
- NULL, STRFTIME_ARG ((size_t) -1)
- subfmt,
- tp extra_args LOCALE_ARG);
- add (len, strftime_case_ (to_uppcase, p,
- STRFTIME_ARG (maxsize - i)
- subfmt,
- tp extra_args LOCALE_ARG));
- }
- break;
+ subformat:
+ {
+ size_t len = strftime_case_ (to_uppcase,
+ NULL, STRFTIME_ARG ((size_t) -1)
+ subfmt,
+ tp extra_args LOCALE_ARG);
+ add (len, strftime_case_ (to_uppcase, p,
+ STRFTIME_ARG (maxsize - i)
+ subfmt,
+ tp extra_args LOCALE_ARG));
+ }
+ break;
#if !(defined _NL_CURRENT && HAVE_STRUCT_ERA_ENTRY)
- underlying_strftime:
- {
- /* The relevant information is available only via the
- underlying strftime implementation, so use that. */
- char ufmt[5];
- char *u = ufmt;
- char ubuf[1024]; /* enough for any single format in practice */
- size_t len;
- /* Make sure we're calling the actual underlying strftime.
- In some cases, config.h contains something like
- "#define strftime rpl_strftime". */
+ underlying_strftime:
+ {
+ /* The relevant information is available only via the
+ underlying strftime implementation, so use that. */
+ char ufmt[5];
+ char *u = ufmt;
+ char ubuf[1024]; /* enough for any single format in practice */
+ size_t len;
+ /* Make sure we're calling the actual underlying strftime.
+ In some cases, config.h contains something like
+ "#define strftime rpl_strftime". */
# ifdef strftime
# undef strftime
- size_t strftime ();
+ size_t strftime ();
# endif
- /* The space helps distinguish strftime failure from empty
- output. */
- *u++ = ' ';
- *u++ = '%';
- if (modifier != 0)
- *u++ = modifier;
- *u++ = format_char;
- *u = '\0';
- len = strftime (ubuf, sizeof ubuf, ufmt, tp);
- if (len != 0)
- cpy (len - 1, ubuf + 1);
- }
- break;
+ /* The space helps distinguish strftime failure from empty
+ output. */
+ *u++ = ' ';
+ *u++ = '%';
+ if (modifier != 0)
+ *u++ = modifier;
+ *u++ = format_char;
+ *u = '\0';
+ len = strftime (ubuf, sizeof ubuf, ufmt, tp);
+ if (len != 0)
+ cpy (len - 1, ubuf + 1);
+ }
+ break;
#endif
- case L_('C'):
- if (modifier == L_('O'))
- goto bad_format;
- if (modifier == L_('E'))
- {
+ case L_('C'):
+ if (modifier == L_('O'))
+ goto bad_format;
+ if (modifier == L_('E'))
+ {
#if HAVE_STRUCT_ERA_ENTRY
- struct era_entry *era = _nl_get_era_entry (tp HELPER_LOCALE_ARG);
- if (era)
- {
+ struct era_entry *era = _nl_get_era_entry (tp HELPER_LOCALE_ARG);
+ if (era)
+ {
# ifdef COMPILE_WIDE
- size_t len = __wcslen (era->era_wname);
- cpy (len, era->era_wname);
+ size_t len = __wcslen (era->era_wname);
+ cpy (len, era->era_wname);
# else
- size_t len = strlen (era->era_name);
- cpy (len, era->era_name);
+ size_t len = strlen (era->era_name);
+ cpy (len, era->era_name);
# endif
- break;
- }
+ break;
+ }
#else
- goto underlying_strftime;
+ goto underlying_strftime;
#endif
- }
+ }
- {
- int century = tp->tm_year / 100 + TM_YEAR_BASE / 100;
- century -= tp->tm_year % 100 < 0 && 0 < century;
- DO_SIGNED_NUMBER (2, tp->tm_year < - TM_YEAR_BASE, century);
- }
+ {
+ int century = tp->tm_year / 100 + TM_YEAR_BASE / 100;
+ century -= tp->tm_year % 100 < 0 && 0 < century;
+ DO_SIGNED_NUMBER (2, tp->tm_year < - TM_YEAR_BASE, century);
+ }
- case L_('x'):
- if (modifier == L_('O'))
- goto bad_format;
+ case L_('x'):
+ if (modifier == L_('O'))
+ goto bad_format;
#ifdef _NL_CURRENT
- if (! (modifier == L_('E')
- && (*(subfmt =
- (const CHAR_T *)_NL_CURRENT (LC_TIME, NLW(ERA_D_FMT)))
- != L_('\0'))))
- subfmt = (const CHAR_T *) _NL_CURRENT (LC_TIME, NLW(D_FMT));
- goto subformat;
+ if (! (modifier == L_('E')
+ && (*(subfmt =
+ (const CHAR_T *)_NL_CURRENT (LC_TIME, NLW(ERA_D_FMT)))
+ != L_('\0'))))
+ subfmt = (const CHAR_T *) _NL_CURRENT (LC_TIME, NLW(D_FMT));
+ goto subformat;
#else
- goto underlying_strftime;
+ goto underlying_strftime;
#endif
- case L_('D'):
- if (modifier != 0)
- goto bad_format;
- subfmt = L_("%m/%d/%y");
- goto subformat;
-
- case L_('d'):
- if (modifier == L_('E'))
- goto bad_format;
-
- DO_NUMBER (2, tp->tm_mday);
-
- case L_('e'):
- if (modifier == L_('E'))
- goto bad_format;
-
- DO_NUMBER_SPACEPAD (2, tp->tm_mday);
-
- /* All numeric formats set DIGITS and NUMBER_VALUE (or U_NUMBER_VALUE)
- and then jump to one of these labels. */
-
- do_tz_offset:
- always_output_a_sign = true;
- goto do_number_body;
-
- do_number_spacepad:
- /* Force `_' flag unless overridden by `0' or `-' flag. */
- if (pad != L_('0') && pad != L_('-'))
- pad = L_('_');
-
- do_number:
- /* Format NUMBER_VALUE according to the MODIFIER flag. */
- negative_number = number_value < 0;
- u_number_value = number_value;
-
- do_signed_number:
- always_output_a_sign = false;
- tz_colon_mask = 0;
-
- do_number_body:
- /* Format U_NUMBER_VALUE according to the MODIFIER flag.
- NEGATIVE_NUMBER is nonzero if the original number was
- negative; in this case it was converted directly to
- unsigned int (i.e., modulo (UINT_MAX + 1)) without
- negating it. */
- if (modifier == L_('O') && !negative_number)
- {
+ case L_('D'):
+ if (modifier != 0)
+ goto bad_format;
+ subfmt = L_("%m/%d/%y");
+ goto subformat;
+
+ case L_('d'):
+ if (modifier == L_('E'))
+ goto bad_format;
+
+ DO_NUMBER (2, tp->tm_mday);
+
+ case L_('e'):
+ if (modifier == L_('E'))
+ goto bad_format;
+
+ DO_NUMBER_SPACEPAD (2, tp->tm_mday);
+
+ /* All numeric formats set DIGITS and NUMBER_VALUE (or U_NUMBER_VALUE)
+ and then jump to one of these labels. */
+
+ do_tz_offset:
+ always_output_a_sign = true;
+ goto do_number_body;
+
+ do_number_spacepad:
+ /* Force '_' flag unless overridden by '0' or '-' flag. */
+ if (pad != L_('0') && pad != L_('-'))
+ pad = L_('_');
+
+ do_number:
+ /* Format NUMBER_VALUE according to the MODIFIER flag. */
+ negative_number = number_value < 0;
+ u_number_value = number_value;
+
+ do_signed_number:
+ always_output_a_sign = false;
+ tz_colon_mask = 0;
+
+ do_number_body:
+ /* Format U_NUMBER_VALUE according to the MODIFIER flag.
+ NEGATIVE_NUMBER is nonzero if the original number was
+ negative; in this case it was converted directly to
+ unsigned int (i.e., modulo (UINT_MAX + 1)) without
+ negating it. */
+ if (modifier == L_('O') && !negative_number)
+ {
#ifdef _NL_CURRENT
- /* Get the locale specific alternate representation of
- the number. If none exist NULL is returned. */
- const CHAR_T *cp = nl_get_alt_digit (u_number_value
- HELPER_LOCALE_ARG);
-
- if (cp != NULL)
- {
- size_t digitlen = STRLEN (cp);
- if (digitlen != 0)
- {
- cpy (digitlen, cp);
- break;
- }
- }
+ /* Get the locale specific alternate representation of
+ the number. If none exist NULL is returned. */
+ const CHAR_T *cp = nl_get_alt_digit (u_number_value
+ HELPER_LOCALE_ARG);
+
+ if (cp != NULL)
+ {
+ size_t digitlen = STRLEN (cp);
+ if (digitlen != 0)
+ {
+ cpy (digitlen, cp);
+ break;
+ }
+ }
#else
- goto underlying_strftime;
+ goto underlying_strftime;
#endif
- }
-
- bufp = buf + sizeof (buf) / sizeof (buf[0]);
-
- if (negative_number)
- u_number_value = - u_number_value;
-
- do
- {
- if (tz_colon_mask & 1)
- *--bufp = ':';
- tz_colon_mask >>= 1;
- *--bufp = u_number_value % 10 + L_('0');
- u_number_value /= 10;
- }
- while (u_number_value != 0 || tz_colon_mask != 0);
-
- do_number_sign_and_padding:
- if (digits < width)
- digits = width;
-
- sign_char = (negative_number ? L_('-')
- : always_output_a_sign ? L_('+')
- : 0);
-
- if (pad == L_('-'))
- {
- if (sign_char)
- add1 (sign_char);
- }
- else
- {
- int padding = digits - (buf + (sizeof (buf) / sizeof (buf[0]))
- - bufp) - !!sign_char;
-
- if (padding > 0)
- {
- if (pad == L_('_'))
- {
- if ((size_t) padding >= maxsize - i)
- return 0;
-
- if (p)
- memset_space (p, padding);
- i += padding;
- width = width > padding ? width - padding : 0;
- if (sign_char)
- add1 (sign_char);
- }
- else
- {
- if ((size_t) digits >= maxsize - i)
- return 0;
-
- if (sign_char)
- add1 (sign_char);
-
- if (p)
- memset_zero (p, padding);
- i += padding;
- width = 0;
- }
- }
- else
- {
- if (sign_char)
- add1 (sign_char);
- }
- }
-
- cpy (buf + sizeof (buf) / sizeof (buf[0]) - bufp, bufp);
- break;
-
- case L_('F'):
- if (modifier != 0)
- goto bad_format;
- subfmt = L_("%Y-%m-%d");
- goto subformat;
-
- case L_('H'):
- if (modifier == L_('E'))
- goto bad_format;
-
- DO_NUMBER (2, tp->tm_hour);
-
- case L_('I'):
- if (modifier == L_('E'))
- goto bad_format;
-
- DO_NUMBER (2, hour12);
-
- case L_('k'): /* GNU extension. */
- if (modifier == L_('E'))
- goto bad_format;
-
- DO_NUMBER_SPACEPAD (2, tp->tm_hour);
-
- case L_('l'): /* GNU extension. */
- if (modifier == L_('E'))
- goto bad_format;
-
- DO_NUMBER_SPACEPAD (2, hour12);
-
- case L_('j'):
- if (modifier == L_('E'))
- goto bad_format;
-
- DO_SIGNED_NUMBER (3, tp->tm_yday < -1, tp->tm_yday + 1U);
-
- case L_('M'):
- if (modifier == L_('E'))
- goto bad_format;
-
- DO_NUMBER (2, tp->tm_min);
-
- case L_('m'):
- if (modifier == L_('E'))
- goto bad_format;
-
- DO_SIGNED_NUMBER (2, tp->tm_mon < -1, tp->tm_mon + 1U);
+ }
+
+ bufp = buf + sizeof (buf) / sizeof (buf[0]);
+
+ if (negative_number)
+ u_number_value = - u_number_value;
+
+ do
+ {
+ if (tz_colon_mask & 1)
+ *--bufp = ':';
+ tz_colon_mask >>= 1;
+ *--bufp = u_number_value % 10 + L_('0');
+ u_number_value /= 10;
+ }
+ while (u_number_value != 0 || tz_colon_mask != 0);
+
+ do_number_sign_and_padding:
+ if (digits < width)
+ digits = width;
+
+ sign_char = (negative_number ? L_('-')
+ : always_output_a_sign ? L_('+')
+ : 0);
+
+ if (pad == L_('-'))
+ {
+ if (sign_char)
+ add1 (sign_char);
+ }
+ else
+ {
+ int padding = digits - (buf + (sizeof (buf) / sizeof (buf[0]))
+ - bufp) - !!sign_char;
+
+ if (padding > 0)
+ {
+ if (pad == L_('_'))
+ {
+ if ((size_t) padding >= maxsize - i)
+ return 0;
+
+ if (p)
+ memset_space (p, padding);
+ i += padding;
+ width = width > padding ? width - padding : 0;
+ if (sign_char)
+ add1 (sign_char);
+ }
+ else
+ {
+ if ((size_t) digits >= maxsize - i)
+ return 0;
+
+ if (sign_char)
+ add1 (sign_char);
+
+ if (p)
+ memset_zero (p, padding);
+ i += padding;
+ width = 0;
+ }
+ }
+ else
+ {
+ if (sign_char)
+ add1 (sign_char);
+ }
+ }
+
+ cpy (buf + sizeof (buf) / sizeof (buf[0]) - bufp, bufp);
+ break;
+
+ case L_('F'):
+ if (modifier != 0)
+ goto bad_format;
+ subfmt = L_("%Y-%m-%d");
+ goto subformat;
+
+ case L_('H'):
+ if (modifier == L_('E'))
+ goto bad_format;
+
+ DO_NUMBER (2, tp->tm_hour);
+
+ case L_('I'):
+ if (modifier == L_('E'))
+ goto bad_format;
+
+ DO_NUMBER (2, hour12);
+
+ case L_('k'): /* GNU extension. */
+ if (modifier == L_('E'))
+ goto bad_format;
+
+ DO_NUMBER_SPACEPAD (2, tp->tm_hour);
+
+ case L_('l'): /* GNU extension. */
+ if (modifier == L_('E'))
+ goto bad_format;
+
+ DO_NUMBER_SPACEPAD (2, hour12);
+
+ case L_('j'):
+ if (modifier == L_('E'))
+ goto bad_format;
+
+ DO_SIGNED_NUMBER (3, tp->tm_yday < -1, tp->tm_yday + 1U);
+
+ case L_('M'):
+ if (modifier == L_('E'))
+ goto bad_format;
+
+ DO_NUMBER (2, tp->tm_min);
+
+ case L_('m'):
+ if (modifier == L_('E'))
+ goto bad_format;
+
+ DO_SIGNED_NUMBER (2, tp->tm_mon < -1, tp->tm_mon + 1U);
#ifndef _LIBC
- case L_('N'): /* GNU extension. */
- if (modifier == L_('E'))
- goto bad_format;
-
- number_value = ns;
- if (width == -1)
- width = 9;
- else
- {
- /* Take an explicit width less than 9 as a precision. */
- int j;
- for (j = width; j < 9; j++)
- number_value /= 10;
- }
-
- DO_NUMBER (width, number_value);
+ case L_('N'): /* GNU extension. */
+ if (modifier == L_('E'))
+ goto bad_format;
+
+ number_value = ns;
+ if (width == -1)
+ width = 9;
+ else
+ {
+ /* Take an explicit width less than 9 as a precision. */
+ int j;
+ for (j = width; j < 9; j++)
+ number_value /= 10;
+ }
+
+ DO_NUMBER (width, number_value);
#endif
- case L_('n'):
- add1 (L_('\n'));
- break;
+ case L_('n'):
+ add1 (L_('\n'));
+ break;
- case L_('P'):
- to_lowcase = true;
+ case L_('P'):
+ to_lowcase = true;
#ifndef _NL_CURRENT
- format_char = L_('p');
+ format_char = L_('p');
#endif
- /* FALLTHROUGH */
-
- case L_('p'):
- if (change_case)
- {
- to_uppcase = false;
- to_lowcase = true;
- }
+ /* FALLTHROUGH */
+
+ case L_('p'):
+ if (change_case)
+ {
+ to_uppcase = false;
+ to_lowcase = true;
+ }
#ifdef _NL_CURRENT
- cpy (ap_len, ampm);
- break;
+ cpy (ap_len, ampm);
+ break;
#else
- goto underlying_strftime;
+ goto underlying_strftime;
#endif
- case L_('R'):
- subfmt = L_("%H:%M");
- goto subformat;
+ case L_('R'):
+ subfmt = L_("%H:%M");
+ goto subformat;
- case L_('r'):
+ case L_('r'):
#ifdef _NL_CURRENT
- if (*(subfmt = (const CHAR_T *) _NL_CURRENT (LC_TIME,
- NLW(T_FMT_AMPM)))
- == L_('\0'))
- subfmt = L_("%I:%M:%S %p");
- goto subformat;
+ if (*(subfmt = (const CHAR_T *) _NL_CURRENT (LC_TIME,
+ NLW(T_FMT_AMPM)))
+ == L_('\0'))
+ subfmt = L_("%I:%M:%S %p");
+ goto subformat;
#else
- goto underlying_strftime;
+ goto underlying_strftime;
#endif
- case L_('S'):
- if (modifier == L_('E'))
- goto bad_format;
+ case L_('S'):
+ if (modifier == L_('E'))
+ goto bad_format;
- DO_NUMBER (2, tp->tm_sec);
+ DO_NUMBER (2, tp->tm_sec);
- case L_('s'): /* GNU extension. */
- {
- struct tm ltm;
- time_t t;
+ case L_('s'): /* GNU extension. */
+ {
+ struct tm ltm;
+ time_t t;
- ltm = *tp;
- t = mktime (&ltm);
+ ltm = *tp;
+ t = mktime_z (tz, &ltm);
- /* Generate string value for T using time_t arithmetic;
- this works even if sizeof (long) < sizeof (time_t). */
+ /* Generate string value for T using time_t arithmetic;
+ this works even if sizeof (long) < sizeof (time_t). */
- bufp = buf + sizeof (buf) / sizeof (buf[0]);
- negative_number = t < 0;
+ bufp = buf + sizeof (buf) / sizeof (buf[0]);
+ negative_number = t < 0;
- do
- {
- int d = t % 10;
- t /= 10;
- *--bufp = (negative_number ? -d : d) + L_('0');
- }
- while (t != 0);
+ do
+ {
+ int d = t % 10;
+ t /= 10;
+ *--bufp = (negative_number ? -d : d) + L_('0');
+ }
+ while (t != 0);
- digits = 1;
- always_output_a_sign = false;
- goto do_number_sign_and_padding;
- }
+ digits = 1;
+ always_output_a_sign = false;
+ goto do_number_sign_and_padding;
+ }
- case L_('X'):
- if (modifier == L_('O'))
- goto bad_format;
+ case L_('X'):
+ if (modifier == L_('O'))
+ goto bad_format;
#ifdef _NL_CURRENT
- if (! (modifier == L_('E')
- && (*(subfmt =
- (const CHAR_T *) _NL_CURRENT (LC_TIME, NLW(ERA_T_FMT)))
- != L_('\0'))))
- subfmt = (const CHAR_T *) _NL_CURRENT (LC_TIME, NLW(T_FMT));
- goto subformat;
+ if (! (modifier == L_('E')
+ && (*(subfmt =
+ (const CHAR_T *) _NL_CURRENT (LC_TIME, NLW(ERA_T_FMT)))
+ != L_('\0'))))
+ subfmt = (const CHAR_T *) _NL_CURRENT (LC_TIME, NLW(T_FMT));
+ goto subformat;
#else
- goto underlying_strftime;
+ goto underlying_strftime;
#endif
- case L_('T'):
- subfmt = L_("%H:%M:%S");
- goto subformat;
-
- case L_('t'):
- add1 (L_('\t'));
- break;
-
- case L_('u'):
- DO_NUMBER (1, (tp->tm_wday - 1 + 7) % 7 + 1);
-
- case L_('U'):
- if (modifier == L_('E'))
- goto bad_format;
-
- DO_NUMBER (2, (tp->tm_yday - tp->tm_wday + 7) / 7);
-
- case L_('V'):
- case L_('g'):
- case L_('G'):
- if (modifier == L_('E'))
- goto bad_format;
- {
- /* YEAR is a leap year if and only if (tp->tm_year + TM_YEAR_BASE)
- is a leap year, except that YEAR and YEAR - 1 both work
- correctly even when (tp->tm_year + TM_YEAR_BASE) would
- overflow. */
- int year = (tp->tm_year
- + (tp->tm_year < 0
- ? TM_YEAR_BASE % 400
- : TM_YEAR_BASE % 400 - 400));
- int year_adjust = 0;
- int days = iso_week_days (tp->tm_yday, tp->tm_wday);
-
- if (days < 0)
- {
- /* This ISO week belongs to the previous year. */
- year_adjust = -1;
- days = iso_week_days (tp->tm_yday + (365 + __isleap (year - 1)),
- tp->tm_wday);
- }
- else
- {
- int d = iso_week_days (tp->tm_yday - (365 + __isleap (year)),
- tp->tm_wday);
- if (0 <= d)
- {
- /* This ISO week belongs to the next year. */
- year_adjust = 1;
- days = d;
- }
- }
-
- switch (*f)
- {
- case L_('g'):
- {
- int yy = (tp->tm_year % 100 + year_adjust) % 100;
- DO_NUMBER (2, (0 <= yy
- ? yy
- : tp->tm_year < -TM_YEAR_BASE - year_adjust
- ? -yy
- : yy + 100));
- }
-
- case L_('G'):
- DO_SIGNED_NUMBER (4, tp->tm_year < -TM_YEAR_BASE - year_adjust,
- (tp->tm_year + (unsigned int) TM_YEAR_BASE
- + year_adjust));
-
- default:
- DO_NUMBER (2, days / 7 + 1);
- }
- }
-
- case L_('W'):
- if (modifier == L_('E'))
- goto bad_format;
-
- DO_NUMBER (2, (tp->tm_yday - (tp->tm_wday - 1 + 7) % 7 + 7) / 7);
-
- case L_('w'):
- if (modifier == L_('E'))
- goto bad_format;
-
- DO_NUMBER (1, tp->tm_wday);
-
- case L_('Y'):
- if (modifier == 'E')
- {
+ case L_('T'):
+ subfmt = L_("%H:%M:%S");
+ goto subformat;
+
+ case L_('t'):
+ add1 (L_('\t'));
+ break;
+
+ case L_('u'):
+ DO_NUMBER (1, (tp->tm_wday - 1 + 7) % 7 + 1);
+
+ case L_('U'):
+ if (modifier == L_('E'))
+ goto bad_format;
+
+ DO_NUMBER (2, (tp->tm_yday - tp->tm_wday + 7) / 7);
+
+ case L_('V'):
+ case L_('g'):
+ case L_('G'):
+ if (modifier == L_('E'))
+ goto bad_format;
+ {
+ /* YEAR is a leap year if and only if (tp->tm_year + TM_YEAR_BASE)
+ is a leap year, except that YEAR and YEAR - 1 both work
+ correctly even when (tp->tm_year + TM_YEAR_BASE) would
+ overflow. */
+ int year = (tp->tm_year
+ + (tp->tm_year < 0
+ ? TM_YEAR_BASE % 400
+ : TM_YEAR_BASE % 400 - 400));
+ int year_adjust = 0;
+ int days = iso_week_days (tp->tm_yday, tp->tm_wday);
+
+ if (days < 0)
+ {
+ /* This ISO week belongs to the previous year. */
+ year_adjust = -1;
+ days = iso_week_days (tp->tm_yday + (365 + __isleap (year - 1)),
+ tp->tm_wday);
+ }
+ else
+ {
+ int d = iso_week_days (tp->tm_yday - (365 + __isleap (year)),
+ tp->tm_wday);
+ if (0 <= d)
+ {
+ /* This ISO week belongs to the next year. */
+ year_adjust = 1;
+ days = d;
+ }
+ }
+
+ switch (*f)
+ {
+ case L_('g'):
+ {
+ int yy = (tp->tm_year % 100 + year_adjust) % 100;
+ DO_NUMBER (2, (0 <= yy
+ ? yy
+ : tp->tm_year < -TM_YEAR_BASE - year_adjust
+ ? -yy
+ : yy + 100));
+ }
+
+ case L_('G'):
+ DO_SIGNED_NUMBER (4, tp->tm_year < -TM_YEAR_BASE - year_adjust,
+ (tp->tm_year + (unsigned int) TM_YEAR_BASE
+ + year_adjust));
+
+ default:
+ DO_NUMBER (2, days / 7 + 1);
+ }
+ }
+
+ case L_('W'):
+ if (modifier == L_('E'))
+ goto bad_format;
+
+ DO_NUMBER (2, (tp->tm_yday - (tp->tm_wday - 1 + 7) % 7 + 7) / 7);
+
+ case L_('w'):
+ if (modifier == L_('E'))
+ goto bad_format;
+
+ DO_NUMBER (1, tp->tm_wday);
+
+ case L_('Y'):
+ if (modifier == 'E')
+ {
#if HAVE_STRUCT_ERA_ENTRY
- struct era_entry *era = _nl_get_era_entry (tp HELPER_LOCALE_ARG);
- if (era)
- {
+ struct era_entry *era = _nl_get_era_entry (tp HELPER_LOCALE_ARG);
+ if (era)
+ {
# ifdef COMPILE_WIDE
- subfmt = era->era_wformat;
+ subfmt = era->era_wformat;
# else
- subfmt = era->era_format;
+ subfmt = era->era_format;
# endif
- goto subformat;
- }
+ goto subformat;
+ }
#else
- goto underlying_strftime;
+ goto underlying_strftime;
#endif
- }
- if (modifier == L_('O'))
- goto bad_format;
- else
- DO_SIGNED_NUMBER (4, tp->tm_year < -TM_YEAR_BASE,
- tp->tm_year + (unsigned int) TM_YEAR_BASE);
-
- case L_('y'):
- if (modifier == L_('E'))
- {
+ }
+ if (modifier == L_('O'))
+ goto bad_format;
+
+ DO_SIGNED_NUMBER (4, tp->tm_year < -TM_YEAR_BASE,
+ tp->tm_year + (unsigned int) TM_YEAR_BASE);
+
+ case L_('y'):
+ if (modifier == L_('E'))
+ {
#if HAVE_STRUCT_ERA_ENTRY
- struct era_entry *era = _nl_get_era_entry (tp HELPER_LOCALE_ARG);
- if (era)
- {
- int delta = tp->tm_year - era->start_date[0];
- DO_NUMBER (1, (era->offset
- + delta * era->absolute_direction));
- }
+ struct era_entry *era = _nl_get_era_entry (tp HELPER_LOCALE_ARG);
+ if (era)
+ {
+ int delta = tp->tm_year - era->start_date[0];
+ DO_NUMBER (1, (era->offset
+ + delta * era->absolute_direction));
+ }
#else
- goto underlying_strftime;
-#endif
- }
-
- {
- int yy = tp->tm_year % 100;
- if (yy < 0)
- yy = tp->tm_year < - TM_YEAR_BASE ? -yy : yy + 100;
- DO_NUMBER (2, yy);
- }
-
- case L_('Z'):
- if (change_case)
- {
- to_uppcase = false;
- to_lowcase = true;
- }
-
-#if HAVE_TZNAME
- /* The tzset() call might have changed the value. */
- if (!(zone && *zone) && tp->tm_isdst >= 0)
- zone = tzname[tp->tm_isdst != 0];
+ goto underlying_strftime;
#endif
- if (! zone)
- zone = "";
+ }
+
+ {
+ int yy = tp->tm_year % 100;
+ if (yy < 0)
+ yy = tp->tm_year < - TM_YEAR_BASE ? -yy : yy + 100;
+ DO_NUMBER (2, yy);
+ }
+
+ case L_('Z'):
+ if (change_case)
+ {
+ to_uppcase = false;
+ to_lowcase = true;
+ }
#ifdef COMPILE_WIDE
- {
- /* The zone string is always given in multibyte form. We have
- to transform it first. */
- wchar_t *wczone;
- size_t len;
- widen (zone, wczone, len);
- cpy (len, wczone);
- }
+ {
+ /* The zone string is always given in multibyte form. We have
+ to transform it first. */
+ wchar_t *wczone;
+ size_t len;
+ widen (zone, wczone, len);
+ cpy (len, wczone);
+ }
#else
- cpy (strlen (zone), zone);
+ cpy (strlen (zone), zone);
#endif
- break;
-
- case L_(':'):
- /* :, ::, and ::: are valid only just before 'z'.
- :::: etc. are rejected later. */
- for (colons = 1; f[colons] == L_(':'); colons++)
- continue;
- if (f[colons] != L_('z'))
- goto bad_format;
- f += colons;
- goto do_z_conversion;
-
- case L_('z'):
- colons = 0;
-
- do_z_conversion:
- if (tp->tm_isdst < 0)
- break;
-
- {
- int diff;
- int hour_diff;
- int min_diff;
- int sec_diff;
+ break;
+
+ case L_(':'):
+ /* :, ::, and ::: are valid only just before 'z'.
+ :::: etc. are rejected later. */
+ for (colons = 1; f[colons] == L_(':'); colons++)
+ continue;
+ if (f[colons] != L_('z'))
+ goto bad_format;
+ f += colons;
+ goto do_z_conversion;
+
+ case L_('z'):
+ colons = 0;
+
+ do_z_conversion:
+ if (tp->tm_isdst < 0)
+ break;
+
+ {
+ int diff;
+ int hour_diff;
+ int min_diff;
+ int sec_diff;
#if HAVE_TM_GMTOFF
- diff = tp->tm_gmtoff;
+ diff = tp->tm_gmtoff;
#else
- if (ut)
- diff = 0;
- else
- {
- struct tm gtm;
- struct tm ltm;
- time_t lt;
-
- ltm = *tp;
- lt = mktime (&ltm);
-
- if (lt == (time_t) -1)
- {
- /* mktime returns -1 for errors, but -1 is also a
- valid time_t value. Check whether an error really
- occurred. */
- struct tm tm;
-
- if (! __localtime_r (&lt, &tm)
- || ((ltm.tm_sec ^ tm.tm_sec)
- | (ltm.tm_min ^ tm.tm_min)
- | (ltm.tm_hour ^ tm.tm_hour)
- | (ltm.tm_mday ^ tm.tm_mday)
- | (ltm.tm_mon ^ tm.tm_mon)
- | (ltm.tm_year ^ tm.tm_year)))
- break;
- }
-
- if (! __gmtime_r (&lt, &gtm))
- break;
-
- diff = tm_diff (&ltm, &gtm);
- }
+ if (!tz)
+ diff = 0;
+ else
+ {
+ struct tm gtm;
+ struct tm ltm;
+ time_t lt;
+
+ ltm = *tp;
+ lt = mktime_z (tz, &ltm);
+
+ if (lt == (time_t) -1)
+ {
+ /* mktime returns -1 for errors, but -1 is also a
+ valid time_t value. Check whether an error really
+ occurred. */
+ struct tm tm;
+
+ if (! localtime_rz (tz, &lt, &tm)
+ || ((ltm.tm_sec ^ tm.tm_sec)
+ | (ltm.tm_min ^ tm.tm_min)
+ | (ltm.tm_hour ^ tm.tm_hour)
+ | (ltm.tm_mday ^ tm.tm_mday)
+ | (ltm.tm_mon ^ tm.tm_mon)
+ | (ltm.tm_year ^ tm.tm_year)))
+ break;
+ }
+
+ if (! localtime_rz (0, &lt, &gtm))
+ break;
+
+ diff = tm_diff (&ltm, &gtm);
+ }
#endif
- hour_diff = diff / 60 / 60;
- min_diff = diff / 60 % 60;
- sec_diff = diff % 60;
-
- switch (colons)
- {
- case 0: /* +hhmm */
- DO_TZ_OFFSET (5, diff < 0, 0, hour_diff * 100 + min_diff);
-
- case 1: tz_hh_mm: /* +hh:mm */
- DO_TZ_OFFSET (6, diff < 0, 04, hour_diff * 100 + min_diff);
-
- case 2: tz_hh_mm_ss: /* +hh:mm:ss */
- DO_TZ_OFFSET (9, diff < 0, 024,
- hour_diff * 10000 + min_diff * 100 + sec_diff);
-
- case 3: /* +hh if possible, else +hh:mm, else +hh:mm:ss */
- if (sec_diff != 0)
- goto tz_hh_mm_ss;
- if (min_diff != 0)
- goto tz_hh_mm;
- DO_TZ_OFFSET (3, diff < 0, 0, hour_diff);
-
- default:
- goto bad_format;
- }
- }
-
- case L_('\0'): /* GNU extension: % at end of format. */
- --f;
- /* Fall through. */
- default:
- /* Unknown format; output the format, including the '%',
- since this is most likely the right thing to do if a
- multibyte string has been misparsed. */
- bad_format:
- {
- int flen;
- for (flen = 1; f[1 - flen] != L_('%'); flen++)
- continue;
- cpy (flen, &f[1 - flen]);
- }
- break;
- }
+ hour_diff = diff / 60 / 60;
+ min_diff = diff / 60 % 60;
+ sec_diff = diff % 60;
+
+ switch (colons)
+ {
+ case 0: /* +hhmm */
+ DO_TZ_OFFSET (5, diff < 0, 0, hour_diff * 100 + min_diff);
+
+ case 1: tz_hh_mm: /* +hh:mm */
+ DO_TZ_OFFSET (6, diff < 0, 04, hour_diff * 100 + min_diff);
+
+ case 2: tz_hh_mm_ss: /* +hh:mm:ss */
+ DO_TZ_OFFSET (9, diff < 0, 024,
+ hour_diff * 10000 + min_diff * 100 + sec_diff);
+
+ case 3: /* +hh if possible, else +hh:mm, else +hh:mm:ss */
+ if (sec_diff != 0)
+ goto tz_hh_mm_ss;
+ if (min_diff != 0)
+ goto tz_hh_mm;
+ DO_TZ_OFFSET (3, diff < 0, 0, hour_diff);
+
+ default:
+ goto bad_format;
+ }
+ }
+
+ case L_('\0'): /* GNU extension: % at end of format. */
+ --f;
+ /* Fall through. */
+ default:
+ /* Unknown format; output the format, including the '%',
+ since this is most likely the right thing to do if a
+ multibyte string has been misparsed. */
+ bad_format:
+ {
+ int flen;
+ for (flen = 1; f[1 - flen] != L_('%'); flen++)
+ continue;
+ cpy (flen, &f[1 - flen]);
+ }
+ break;
+ }
}
#if ! FPRINTFTIME
@@ -1438,25 +1453,13 @@ strftime_case_ (bool upcase, STREAM_OR_CHAR_T *s,
written, use NULL for S and (size_t) -1 for MAXSIZE. */
size_t
my_strftime (STREAM_OR_CHAR_T *s, STRFTIME_ARG (size_t maxsize)
- const CHAR_T *format,
- const struct tm *tp extra_args_spec LOCALE_PARAM_PROTO)
+ const CHAR_T *format,
+ const struct tm *tp extra_args_spec LOCALE_PARAM_PROTO)
{
return strftime_case_ (false, s, STRFTIME_ARG (maxsize)
- format, tp extra_args LOCALE_ARG);
+ format, tp extra_args LOCALE_ARG);
}
#if defined _LIBC && ! FPRINTFTIME
libc_hidden_def (my_strftime)
#endif
-
-
-#if defined emacs && ! FPRINTFTIME
-/* For Emacs we have a separate interface which corresponds to the normal
- strftime function plus the ut argument, but without the ns argument. */
-size_t
-emacs_strftimeu (char *s, size_t maxsize, const char *format,
- const struct tm *tp, int ut)
-{
- return my_strftime (s, maxsize, format, tp, ut, 0);
-}
-#endif
diff --git a/lib/strftime.h b/lib/strftime.h
index 16b996e..17445e1 100644
--- a/lib/strftime.h
+++ b/lib/strftime.h
@@ -1,11 +1,11 @@
/* declarations for strftime.c
- Copyright (C) 2002, 2004 Free Software Foundation, Inc.
+ Copyright (C) 2002, 2004, 2008-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,9 +13,21 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <time.h>
-size_t nstrftime (char *, size_t, char const *, struct tm const *, int, int);
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Just like strftime, but with two more arguments:
+ POSIX requires that strftime use the local timezone information.
+ Use the timezone __TZ instead. Use __NS as the number of
+ nanoseconds in the %N directive. */
+size_t nstrftime (char *, size_t, char const *, struct tm const *,
+ timezone_t __tz, int __ns);
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/lib/striconv.c b/lib/striconv.c
new file mode 100644
index 0000000..0d9ccdc
--- /dev/null
+++ b/lib/striconv.c
@@ -0,0 +1,463 @@
+/* Charset conversion.
+ Copyright (C) 2001-2007, 2010-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible and Simon Josefsson.
+
+ 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, 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include "striconv.h"
+
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+
+#if HAVE_ICONV
+# include <iconv.h>
+/* Get MB_LEN_MAX, CHAR_BIT. */
+# include <limits.h>
+#endif
+
+#include "c-strcase.h"
+
+#ifndef SIZE_MAX
+# define SIZE_MAX ((size_t) -1)
+#endif
+
+
+#if HAVE_ICONV
+
+int
+mem_cd_iconv (const char *src, size_t srclen, iconv_t cd,
+ char **resultp, size_t *lengthp)
+{
+# define tmpbufsize 4096
+ size_t length;
+ char *result;
+
+ /* Avoid glibc-2.1 bug and Solaris 2.7-2.9 bug. */
+# if defined _LIBICONV_VERSION \
+ || !(((__GLIBC__ == 2 && __GLIBC_MINOR__ <= 1) && !defined __UCLIBC__) \
+ || defined __sun)
+ /* Set to the initial state. */
+ iconv (cd, NULL, NULL, NULL, NULL);
+# endif
+
+ /* Determine the length we need. */
+ {
+ size_t count = 0;
+ /* The alignment is needed when converting e.g. to glibc's WCHAR_T or
+ libiconv's UCS-4-INTERNAL encoding. */
+ union { unsigned int align; char buf[tmpbufsize]; } tmp;
+# define tmpbuf tmp.buf
+ const char *inptr = src;
+ size_t insize = srclen;
+
+ while (insize > 0)
+ {
+ char *outptr = tmpbuf;
+ size_t outsize = tmpbufsize;
+ size_t res = iconv (cd,
+ (ICONV_CONST char **) &inptr, &insize,
+ &outptr, &outsize);
+
+ if (res == (size_t)(-1))
+ {
+ if (errno == E2BIG)
+ ;
+ else if (errno == EINVAL)
+ break;
+ else
+ return -1;
+ }
+# if !defined _LIBICONV_VERSION && !(defined __GLIBC__ && !defined __UCLIBC__)
+ /* Irix iconv() inserts a NUL byte if it cannot convert.
+ NetBSD iconv() inserts a question mark if it cannot convert.
+ Only GNU libiconv and GNU libc are known to prefer to fail rather
+ than doing a lossy conversion. */
+ else if (res > 0)
+ {
+ errno = EILSEQ;
+ return -1;
+ }
+# endif
+ count += outptr - tmpbuf;
+ }
+ /* Avoid glibc-2.1 bug and Solaris 2.7 bug. */
+# if defined _LIBICONV_VERSION \
+ || !(((__GLIBC__ == 2 && __GLIBC_MINOR__ <= 1) && !defined __UCLIBC__) \
+ || defined __sun)
+ {
+ char *outptr = tmpbuf;
+ size_t outsize = tmpbufsize;
+ size_t res = iconv (cd, NULL, NULL, &outptr, &outsize);
+
+ if (res == (size_t)(-1))
+ return -1;
+ count += outptr - tmpbuf;
+ }
+# endif
+ length = count;
+# undef tmpbuf
+ }
+
+ if (length == 0)
+ {
+ *lengthp = 0;
+ return 0;
+ }
+ if (*resultp != NULL && *lengthp >= length)
+ result = *resultp;
+ else
+ {
+ result = (char *) malloc (length);
+ if (result == NULL)
+ {
+ errno = ENOMEM;
+ return -1;
+ }
+ }
+
+ /* Avoid glibc-2.1 bug and Solaris 2.7-2.9 bug. */
+# if defined _LIBICONV_VERSION \
+ || !(((__GLIBC__ == 2 && __GLIBC_MINOR__ <= 1) && !defined __UCLIBC__) \
+ || defined __sun)
+ /* Return to the initial state. */
+ iconv (cd, NULL, NULL, NULL, NULL);
+# endif
+
+ /* Do the conversion for real. */
+ {
+ const char *inptr = src;
+ size_t insize = srclen;
+ char *outptr = result;
+ size_t outsize = length;
+
+ while (insize > 0)
+ {
+ size_t res = iconv (cd,
+ (ICONV_CONST char **) &inptr, &insize,
+ &outptr, &outsize);
+
+ if (res == (size_t)(-1))
+ {
+ if (errno == EINVAL)
+ break;
+ else
+ goto fail;
+ }
+# if !defined _LIBICONV_VERSION && !(defined __GLIBC__ && !defined __UCLIBC__)
+ /* Irix iconv() inserts a NUL byte if it cannot convert.
+ NetBSD iconv() inserts a question mark if it cannot convert.
+ Only GNU libiconv and GNU libc are known to prefer to fail rather
+ than doing a lossy conversion. */
+ else if (res > 0)
+ {
+ errno = EILSEQ;
+ goto fail;
+ }
+# endif
+ }
+ /* Avoid glibc-2.1 bug and Solaris 2.7 bug. */
+# if defined _LIBICONV_VERSION \
+ || !(((__GLIBC__ == 2 && __GLIBC_MINOR__ <= 1) && !defined __UCLIBC__) \
+ || defined __sun)
+ {
+ size_t res = iconv (cd, NULL, NULL, &outptr, &outsize);
+
+ if (res == (size_t)(-1))
+ goto fail;
+ }
+# endif
+ if (outsize != 0)
+ abort ();
+ }
+
+ *resultp = result;
+ *lengthp = length;
+
+ return 0;
+
+ fail:
+ {
+ if (result != *resultp)
+ {
+ int saved_errno = errno;
+ free (result);
+ errno = saved_errno;
+ }
+ return -1;
+ }
+# undef tmpbufsize
+}
+
+char *
+str_cd_iconv (const char *src, iconv_t cd)
+{
+ /* For most encodings, a trailing NUL byte in the input will be converted
+ to a trailing NUL byte in the output. But not for UTF-7. So that this
+ function is usable for UTF-7, we have to exclude the NUL byte from the
+ conversion and add it by hand afterwards. */
+# if !defined _LIBICONV_VERSION && !(defined __GLIBC__ && !defined __UCLIBC__)
+ /* Irix iconv() inserts a NUL byte if it cannot convert.
+ NetBSD iconv() inserts a question mark if it cannot convert.
+ Only GNU libiconv and GNU libc are known to prefer to fail rather
+ than doing a lossy conversion. For other iconv() implementations,
+ we have to look at the number of irreversible conversions returned;
+ but this information is lost when iconv() returns for an E2BIG reason.
+ Therefore we cannot use the second, faster algorithm. */
+
+ char *result = NULL;
+ size_t length = 0;
+ int retval = mem_cd_iconv (src, strlen (src), cd, &result, &length);
+ char *final_result;
+
+ if (retval < 0)
+ {
+ if (result != NULL)
+ abort ();
+ return NULL;
+ }
+
+ /* Add the terminating NUL byte. */
+ final_result =
+ (result != NULL ? realloc (result, length + 1) : malloc (length + 1));
+ if (final_result == NULL)
+ {
+ free (result);
+ errno = ENOMEM;
+ return NULL;
+ }
+ final_result[length] = '\0';
+
+ return final_result;
+
+# else
+ /* This algorithm is likely faster than the one above. But it may produce
+ iconv() returns for an E2BIG reason, when the output size guess is too
+ small. Therefore it can only be used when we don't need the number of
+ irreversible conversions performed. */
+ char *result;
+ size_t result_size;
+ size_t length;
+ const char *inptr = src;
+ size_t inbytes_remaining = strlen (src);
+
+ /* Make a guess for the worst-case output size, in order to avoid a
+ realloc. It's OK if the guess is wrong as long as it is not zero and
+ doesn't lead to an integer overflow. */
+ result_size = inbytes_remaining;
+ {
+ size_t approx_sqrt_SIZE_MAX = SIZE_MAX >> (sizeof (size_t) * CHAR_BIT / 2);
+ if (result_size <= approx_sqrt_SIZE_MAX / MB_LEN_MAX)
+ result_size *= MB_LEN_MAX;
+ }
+ result_size += 1; /* for the terminating NUL */
+
+ result = (char *) malloc (result_size);
+ if (result == NULL)
+ {
+ errno = ENOMEM;
+ return NULL;
+ }
+
+ /* Avoid glibc-2.1 bug and Solaris 2.7-2.9 bug. */
+# if defined _LIBICONV_VERSION \
+ || !(((__GLIBC__ == 2 && __GLIBC_MINOR__ <= 1) && !defined __UCLIBC__) \
+ || defined __sun)
+ /* Set to the initial state. */
+ iconv (cd, NULL, NULL, NULL, NULL);
+# endif
+
+ /* Do the conversion. */
+ {
+ char *outptr = result;
+ size_t outbytes_remaining = result_size - 1;
+
+ for (;;)
+ {
+ /* Here inptr + inbytes_remaining = src + strlen (src),
+ outptr + outbytes_remaining = result + result_size - 1. */
+ size_t res = iconv (cd,
+ (ICONV_CONST char **) &inptr, &inbytes_remaining,
+ &outptr, &outbytes_remaining);
+
+ if (res == (size_t)(-1))
+ {
+ if (errno == EINVAL)
+ break;
+ else if (errno == E2BIG)
+ {
+ size_t used = outptr - result;
+ size_t newsize = result_size * 2;
+ char *newresult;
+
+ if (!(newsize > result_size))
+ {
+ errno = ENOMEM;
+ goto failed;
+ }
+ newresult = (char *) realloc (result, newsize);
+ if (newresult == NULL)
+ {
+ errno = ENOMEM;
+ goto failed;
+ }
+ result = newresult;
+ result_size = newsize;
+ outptr = result + used;
+ outbytes_remaining = result_size - 1 - used;
+ }
+ else
+ goto failed;
+ }
+ else
+ break;
+ }
+ /* Avoid glibc-2.1 bug and Solaris 2.7 bug. */
+# if defined _LIBICONV_VERSION \
+ || !(((__GLIBC__ == 2 && __GLIBC_MINOR__ <= 1) && !defined __UCLIBC__) \
+ || defined __sun)
+ for (;;)
+ {
+ /* Here outptr + outbytes_remaining = result + result_size - 1. */
+ size_t res = iconv (cd, NULL, NULL, &outptr, &outbytes_remaining);
+
+ if (res == (size_t)(-1))
+ {
+ if (errno == E2BIG)
+ {
+ size_t used = outptr - result;
+ size_t newsize = result_size * 2;
+ char *newresult;
+
+ if (!(newsize > result_size))
+ {
+ errno = ENOMEM;
+ goto failed;
+ }
+ newresult = (char *) realloc (result, newsize);
+ if (newresult == NULL)
+ {
+ errno = ENOMEM;
+ goto failed;
+ }
+ result = newresult;
+ result_size = newsize;
+ outptr = result + used;
+ outbytes_remaining = result_size - 1 - used;
+ }
+ else
+ goto failed;
+ }
+ else
+ break;
+ }
+# endif
+
+ /* Add the terminating NUL byte. */
+ *outptr++ = '\0';
+
+ length = outptr - result;
+ }
+
+ /* Give away unused memory. */
+ if (length < result_size)
+ {
+ char *smaller_result = (char *) realloc (result, length);
+
+ if (smaller_result != NULL)
+ result = smaller_result;
+ }
+
+ return result;
+
+ failed:
+ {
+ int saved_errno = errno;
+ free (result);
+ errno = saved_errno;
+ return NULL;
+ }
+
+# endif
+}
+
+#endif
+
+char *
+str_iconv (const char *src, const char *from_codeset, const char *to_codeset)
+{
+ if (*src == '\0' || c_strcasecmp (from_codeset, to_codeset) == 0)
+ {
+ char *result = strdup (src);
+
+ if (result == NULL)
+ errno = ENOMEM;
+ return result;
+ }
+ else
+ {
+#if HAVE_ICONV
+ iconv_t cd;
+ char *result;
+
+ /* Avoid glibc-2.1 bug with EUC-KR. */
+# if ((__GLIBC__ == 2 && __GLIBC_MINOR__ <= 1) && !defined __UCLIBC__) \
+ && !defined _LIBICONV_VERSION
+ if (c_strcasecmp (from_codeset, "EUC-KR") == 0
+ || c_strcasecmp (to_codeset, "EUC-KR") == 0)
+ {
+ errno = EINVAL;
+ return NULL;
+ }
+# endif
+ cd = iconv_open (to_codeset, from_codeset);
+ if (cd == (iconv_t) -1)
+ return NULL;
+
+ result = str_cd_iconv (src, cd);
+
+ if (result == NULL)
+ {
+ /* Close cd, but preserve the errno from str_cd_iconv. */
+ int saved_errno = errno;
+ iconv_close (cd);
+ errno = saved_errno;
+ }
+ else
+ {
+ if (iconv_close (cd) < 0)
+ {
+ /* Return NULL, but free the allocated memory, and while doing
+ that, preserve the errno from iconv_close. */
+ int saved_errno = errno;
+ free (result);
+ errno = saved_errno;
+ return NULL;
+ }
+ }
+ return result;
+#else
+ /* This is a different error code than if iconv_open existed but didn't
+ support from_codeset and to_codeset, so that the caller can emit
+ an error message such as
+ "iconv() is not supported. Installing GNU libiconv and
+ then reinstalling this package would fix this." */
+ errno = ENOSYS;
+ return NULL;
+#endif
+ }
+}
diff --git a/lib/striconv.h b/lib/striconv.h
new file mode 100644
index 0000000..e5217d7
--- /dev/null
+++ b/lib/striconv.h
@@ -0,0 +1,75 @@
+/* Charset conversion.
+ Copyright (C) 2001-2004, 2006-2007, 2009-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible and Simon Josefsson.
+
+ 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, 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _STRICONV_H
+#define _STRICONV_H
+
+#include <stddef.h>
+#if HAVE_ICONV
+#include <iconv.h>
+#endif
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+#if HAVE_ICONV
+
+/* Convert an entire string from one encoding to another, using iconv.
+ The original string is at [SRC,...,SRC+SRCLEN-1].
+ The conversion descriptor is passed as CD.
+ *RESULTP and *LENGTH should initially be a scratch buffer and its size,
+ or *RESULTP can initially be NULL.
+ May erase the contents of the memory at *RESULTP.
+ Return value: 0 if successful, otherwise -1 and errno set.
+ If successful: The resulting string is stored in *RESULTP and its length
+ in *LENGTHP. *RESULTP is set to a freshly allocated memory block, or is
+ unchanged if no dynamic memory allocation was necessary. */
+extern int mem_cd_iconv (const char *src, size_t srclen, iconv_t cd,
+ char **resultp, size_t *lengthp);
+
+/* Convert an entire string from one encoding to another, using iconv.
+ The original string is the NUL-terminated string starting at SRC.
+ The conversion descriptor is passed as CD. Both the "from" and the "to"
+ encoding must use a single NUL byte at the end of the string (i.e. not
+ UCS-2, UCS-4, UTF-16, UTF-32).
+ Allocate a malloced memory block for the result.
+ Return value: the freshly allocated resulting NUL-terminated string if
+ successful, otherwise NULL and errno set. */
+extern char * str_cd_iconv (const char *src, iconv_t cd);
+
+#endif
+
+/* Convert an entire string from one encoding to another, using iconv.
+ The original string is the NUL-terminated string starting at SRC.
+ Both the "from" and the "to" encoding must use a single NUL byte at the
+ end of the string (i.e. not UCS-2, UCS-4, UTF-16, UTF-32).
+ Allocate a malloced memory block for the result.
+ Return value: the freshly allocated resulting NUL-terminated string if
+ successful, otherwise NULL and errno set. */
+extern char * str_iconv (const char *src,
+ const char *from_codeset, const char *to_codeset);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif /* _STRICONV_H */
diff --git a/lib/string.in.h b/lib/string.in.h
new file mode 100644
index 0000000..7fb00c1
--- /dev/null
+++ b/lib/string.in.h
@@ -0,0 +1,1046 @@
+/* A GNU-like <string.h>.
+
+ Copyright (C) 1995-1996, 2001-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+#if defined _GL_ALREADY_INCLUDING_STRING_H
+/* Special invocation convention:
+ - On OS X/NetBSD we have a sequence of nested includes
+ <string.h> -> <strings.h> -> "string.h"
+ In this situation system _chk variants due to -D_FORTIFY_SOURCE
+ might be used after any replacements defined here. */
+
+#@INCLUDE_NEXT@ @NEXT_STRING_H@
+
+#else
+/* Normal invocation convention. */
+
+#ifndef _@GUARD_PREFIX@_STRING_H
+
+#define _GL_ALREADY_INCLUDING_STRING_H
+
+/* The include_next requires a split double-inclusion guard. */
+#@INCLUDE_NEXT@ @NEXT_STRING_H@
+
+#undef _GL_ALREADY_INCLUDING_STRING_H
+
+#ifndef _@GUARD_PREFIX@_STRING_H
+#define _@GUARD_PREFIX@_STRING_H
+
+/* NetBSD 5.0 mis-defines NULL. */
+#include <stddef.h>
+
+/* MirBSD defines mbslen as a macro. */
+#if @GNULIB_MBSLEN@ && defined __MirBSD__
+# include <wchar.h>
+#endif
+
+/* The __attribute__ feature is available in gcc versions 2.5 and later.
+ The attribute __pure__ was added in gcc 2.96. */
+#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96)
+# define _GL_ATTRIBUTE_PURE __attribute__ ((__pure__))
+#else
+# define _GL_ATTRIBUTE_PURE /* empty */
+#endif
+
+/* NetBSD 5.0 declares strsignal in <unistd.h>, not in <string.h>. */
+/* But in any case avoid namespace pollution on glibc systems. */
+#if (@GNULIB_STRSIGNAL@ || defined GNULIB_POSIXCHECK) && defined __NetBSD__ \
+ && ! defined __GLIBC__
+# include <unistd.h>
+#endif
+
+/* The definitions of _GL_FUNCDECL_RPL etc. are copied here. */
+
+/* The definition of _GL_ARG_NONNULL is copied here. */
+
+/* The definition of _GL_WARN_ON_USE is copied here. */
+
+
+/* Find the index of the least-significant set bit. */
+#if @GNULIB_FFSL@
+# if !@HAVE_FFSL@
+_GL_FUNCDECL_SYS (ffsl, int, (long int i));
+# endif
+_GL_CXXALIAS_SYS (ffsl, int, (long int i));
+_GL_CXXALIASWARN (ffsl);
+#elif defined GNULIB_POSIXCHECK
+# undef ffsl
+# if HAVE_RAW_DECL_FFSL
+_GL_WARN_ON_USE (ffsl, "ffsl is not portable - use the ffsl module");
+# endif
+#endif
+
+
+/* Find the index of the least-significant set bit. */
+#if @GNULIB_FFSLL@
+# if !@HAVE_FFSLL@
+_GL_FUNCDECL_SYS (ffsll, int, (long long int i));
+# endif
+_GL_CXXALIAS_SYS (ffsll, int, (long long int i));
+_GL_CXXALIASWARN (ffsll);
+#elif defined GNULIB_POSIXCHECK
+# undef ffsll
+# if HAVE_RAW_DECL_FFSLL
+_GL_WARN_ON_USE (ffsll, "ffsll is not portable - use the ffsll module");
+# endif
+#endif
+
+
+/* Return the first instance of C within N bytes of S, or NULL. */
+#if @GNULIB_MEMCHR@
+# if @REPLACE_MEMCHR@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define memchr rpl_memchr
+# endif
+_GL_FUNCDECL_RPL (memchr, void *, (void const *__s, int __c, size_t __n)
+ _GL_ATTRIBUTE_PURE
+ _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (memchr, void *, (void const *__s, int __c, size_t __n));
+# else
+# if ! @HAVE_MEMCHR@
+_GL_FUNCDECL_SYS (memchr, void *, (void const *__s, int __c, size_t __n)
+ _GL_ATTRIBUTE_PURE
+ _GL_ARG_NONNULL ((1)));
+# endif
+ /* On some systems, this function is defined as an overloaded function:
+ extern "C" { const void * std::memchr (const void *, int, size_t); }
+ extern "C++" { void * std::memchr (void *, int, size_t); } */
+_GL_CXXALIAS_SYS_CAST2 (memchr,
+ void *, (void const *__s, int __c, size_t __n),
+ void const *, (void const *__s, int __c, size_t __n));
+# endif
+# if ((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 10) && !defined __UCLIBC__) \
+ && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4))
+_GL_CXXALIASWARN1 (memchr, void *, (void *__s, int __c, size_t __n));
+_GL_CXXALIASWARN1 (memchr, void const *,
+ (void const *__s, int __c, size_t __n));
+# else
+_GL_CXXALIASWARN (memchr);
+# endif
+#elif defined GNULIB_POSIXCHECK
+# undef memchr
+/* Assume memchr is always declared. */
+_GL_WARN_ON_USE (memchr, "memchr has platform-specific bugs - "
+ "use gnulib module memchr for portability" );
+#endif
+
+/* Return the first occurrence of NEEDLE in HAYSTACK. */
+#if @GNULIB_MEMMEM@
+# if @REPLACE_MEMMEM@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define memmem rpl_memmem
+# endif
+_GL_FUNCDECL_RPL (memmem, void *,
+ (void const *__haystack, size_t __haystack_len,
+ void const *__needle, size_t __needle_len)
+ _GL_ATTRIBUTE_PURE
+ _GL_ARG_NONNULL ((1, 3)));
+_GL_CXXALIAS_RPL (memmem, void *,
+ (void const *__haystack, size_t __haystack_len,
+ void const *__needle, size_t __needle_len));
+# else
+# if ! @HAVE_DECL_MEMMEM@
+_GL_FUNCDECL_SYS (memmem, void *,
+ (void const *__haystack, size_t __haystack_len,
+ void const *__needle, size_t __needle_len)
+ _GL_ATTRIBUTE_PURE
+ _GL_ARG_NONNULL ((1, 3)));
+# endif
+_GL_CXXALIAS_SYS (memmem, void *,
+ (void const *__haystack, size_t __haystack_len,
+ void const *__needle, size_t __needle_len));
+# endif
+_GL_CXXALIASWARN (memmem);
+#elif defined GNULIB_POSIXCHECK
+# undef memmem
+# if HAVE_RAW_DECL_MEMMEM
+_GL_WARN_ON_USE (memmem, "memmem is unportable and often quadratic - "
+ "use gnulib module memmem-simple for portability, "
+ "and module memmem for speed" );
+# endif
+#endif
+
+/* Copy N bytes of SRC to DEST, return pointer to bytes after the
+ last written byte. */
+#if @GNULIB_MEMPCPY@
+# if ! @HAVE_MEMPCPY@
+_GL_FUNCDECL_SYS (mempcpy, void *,
+ (void *restrict __dest, void const *restrict __src,
+ size_t __n)
+ _GL_ARG_NONNULL ((1, 2)));
+# endif
+_GL_CXXALIAS_SYS (mempcpy, void *,
+ (void *restrict __dest, void const *restrict __src,
+ size_t __n));
+_GL_CXXALIASWARN (mempcpy);
+#elif defined GNULIB_POSIXCHECK
+# undef mempcpy
+# if HAVE_RAW_DECL_MEMPCPY
+_GL_WARN_ON_USE (mempcpy, "mempcpy is unportable - "
+ "use gnulib module mempcpy for portability");
+# endif
+#endif
+
+/* Search backwards through a block for a byte (specified as an int). */
+#if @GNULIB_MEMRCHR@
+# if ! @HAVE_DECL_MEMRCHR@
+_GL_FUNCDECL_SYS (memrchr, void *, (void const *, int, size_t)
+ _GL_ATTRIBUTE_PURE
+ _GL_ARG_NONNULL ((1)));
+# endif
+ /* On some systems, this function is defined as an overloaded function:
+ extern "C++" { const void * std::memrchr (const void *, int, size_t); }
+ extern "C++" { void * std::memrchr (void *, int, size_t); } */
+_GL_CXXALIAS_SYS_CAST2 (memrchr,
+ void *, (void const *, int, size_t),
+ void const *, (void const *, int, size_t));
+# if ((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 10) && !defined __UCLIBC__) \
+ && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4))
+_GL_CXXALIASWARN1 (memrchr, void *, (void *, int, size_t));
+_GL_CXXALIASWARN1 (memrchr, void const *, (void const *, int, size_t));
+# else
+_GL_CXXALIASWARN (memrchr);
+# endif
+#elif defined GNULIB_POSIXCHECK
+# undef memrchr
+# if HAVE_RAW_DECL_MEMRCHR
+_GL_WARN_ON_USE (memrchr, "memrchr is unportable - "
+ "use gnulib module memrchr for portability");
+# endif
+#endif
+
+/* Find the first occurrence of C in S. More efficient than
+ memchr(S,C,N), at the expense of undefined behavior if C does not
+ occur within N bytes. */
+#if @GNULIB_RAWMEMCHR@
+# if ! @HAVE_RAWMEMCHR@
+_GL_FUNCDECL_SYS (rawmemchr, void *, (void const *__s, int __c_in)
+ _GL_ATTRIBUTE_PURE
+ _GL_ARG_NONNULL ((1)));
+# endif
+ /* On some systems, this function is defined as an overloaded function:
+ extern "C++" { const void * std::rawmemchr (const void *, int); }
+ extern "C++" { void * std::rawmemchr (void *, int); } */
+_GL_CXXALIAS_SYS_CAST2 (rawmemchr,
+ void *, (void const *__s, int __c_in),
+ void const *, (void const *__s, int __c_in));
+# if ((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 10) && !defined __UCLIBC__) \
+ && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4))
+_GL_CXXALIASWARN1 (rawmemchr, void *, (void *__s, int __c_in));
+_GL_CXXALIASWARN1 (rawmemchr, void const *, (void const *__s, int __c_in));
+# else
+_GL_CXXALIASWARN (rawmemchr);
+# endif
+#elif defined GNULIB_POSIXCHECK
+# undef rawmemchr
+# if HAVE_RAW_DECL_RAWMEMCHR
+_GL_WARN_ON_USE (rawmemchr, "rawmemchr is unportable - "
+ "use gnulib module rawmemchr for portability");
+# endif
+#endif
+
+/* Copy SRC to DST, returning the address of the terminating '\0' in DST. */
+#if @GNULIB_STPCPY@
+# if ! @HAVE_STPCPY@
+_GL_FUNCDECL_SYS (stpcpy, char *,
+ (char *restrict __dst, char const *restrict __src)
+ _GL_ARG_NONNULL ((1, 2)));
+# endif
+_GL_CXXALIAS_SYS (stpcpy, char *,
+ (char *restrict __dst, char const *restrict __src));
+_GL_CXXALIASWARN (stpcpy);
+#elif defined GNULIB_POSIXCHECK
+# undef stpcpy
+# if HAVE_RAW_DECL_STPCPY
+_GL_WARN_ON_USE (stpcpy, "stpcpy is unportable - "
+ "use gnulib module stpcpy for portability");
+# endif
+#endif
+
+/* Copy no more than N bytes of SRC to DST, returning a pointer past the
+ last non-NUL byte written into DST. */
+#if @GNULIB_STPNCPY@
+# if @REPLACE_STPNCPY@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef stpncpy
+# define stpncpy rpl_stpncpy
+# endif
+_GL_FUNCDECL_RPL (stpncpy, char *,
+ (char *restrict __dst, char const *restrict __src,
+ size_t __n)
+ _GL_ARG_NONNULL ((1, 2)));
+_GL_CXXALIAS_RPL (stpncpy, char *,
+ (char *restrict __dst, char const *restrict __src,
+ size_t __n));
+# else
+# if ! @HAVE_STPNCPY@
+_GL_FUNCDECL_SYS (stpncpy, char *,
+ (char *restrict __dst, char const *restrict __src,
+ size_t __n)
+ _GL_ARG_NONNULL ((1, 2)));
+# endif
+_GL_CXXALIAS_SYS (stpncpy, char *,
+ (char *restrict __dst, char const *restrict __src,
+ size_t __n));
+# endif
+_GL_CXXALIASWARN (stpncpy);
+#elif defined GNULIB_POSIXCHECK
+# undef stpncpy
+# if HAVE_RAW_DECL_STPNCPY
+_GL_WARN_ON_USE (stpncpy, "stpncpy is unportable - "
+ "use gnulib module stpncpy for portability");
+# endif
+#endif
+
+#if defined GNULIB_POSIXCHECK
+/* strchr() does not work with multibyte strings if the locale encoding is
+ GB18030 and the character to be searched is a digit. */
+# undef strchr
+/* Assume strchr is always declared. */
+_GL_WARN_ON_USE (strchr, "strchr cannot work correctly on character strings "
+ "in some multibyte locales - "
+ "use mbschr if you care about internationalization");
+#endif
+
+/* Find the first occurrence of C in S or the final NUL byte. */
+#if @GNULIB_STRCHRNUL@
+# if @REPLACE_STRCHRNUL@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define strchrnul rpl_strchrnul
+# endif
+_GL_FUNCDECL_RPL (strchrnul, char *, (const char *__s, int __c_in)
+ _GL_ATTRIBUTE_PURE
+ _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (strchrnul, char *,
+ (const char *str, int ch));
+# else
+# if ! @HAVE_STRCHRNUL@
+_GL_FUNCDECL_SYS (strchrnul, char *, (char const *__s, int __c_in)
+ _GL_ATTRIBUTE_PURE
+ _GL_ARG_NONNULL ((1)));
+# endif
+ /* On some systems, this function is defined as an overloaded function:
+ extern "C++" { const char * std::strchrnul (const char *, int); }
+ extern "C++" { char * std::strchrnul (char *, int); } */
+_GL_CXXALIAS_SYS_CAST2 (strchrnul,
+ char *, (char const *__s, int __c_in),
+ char const *, (char const *__s, int __c_in));
+# endif
+# if ((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 10) && !defined __UCLIBC__) \
+ && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4))
+_GL_CXXALIASWARN1 (strchrnul, char *, (char *__s, int __c_in));
+_GL_CXXALIASWARN1 (strchrnul, char const *, (char const *__s, int __c_in));
+# else
+_GL_CXXALIASWARN (strchrnul);
+# endif
+#elif defined GNULIB_POSIXCHECK
+# undef strchrnul
+# if HAVE_RAW_DECL_STRCHRNUL
+_GL_WARN_ON_USE (strchrnul, "strchrnul is unportable - "
+ "use gnulib module strchrnul for portability");
+# endif
+#endif
+
+/* Duplicate S, returning an identical malloc'd string. */
+#if @GNULIB_STRDUP@
+# if @REPLACE_STRDUP@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef strdup
+# define strdup rpl_strdup
+# endif
+_GL_FUNCDECL_RPL (strdup, char *, (char const *__s) _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (strdup, char *, (char const *__s));
+# else
+# if defined __cplusplus && defined GNULIB_NAMESPACE && defined strdup
+ /* strdup exists as a function and as a macro. Get rid of the macro. */
+# undef strdup
+# endif
+# if !(@HAVE_DECL_STRDUP@ || defined strdup)
+_GL_FUNCDECL_SYS (strdup, char *, (char const *__s) _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (strdup, char *, (char const *__s));
+# endif
+_GL_CXXALIASWARN (strdup);
+#elif defined GNULIB_POSIXCHECK
+# undef strdup
+# if HAVE_RAW_DECL_STRDUP
+_GL_WARN_ON_USE (strdup, "strdup is unportable - "
+ "use gnulib module strdup for portability");
+# endif
+#endif
+
+/* Append no more than N characters from SRC onto DEST. */
+#if @GNULIB_STRNCAT@
+# if @REPLACE_STRNCAT@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef strncat
+# define strncat rpl_strncat
+# endif
+_GL_FUNCDECL_RPL (strncat, char *, (char *dest, const char *src, size_t n)
+ _GL_ARG_NONNULL ((1, 2)));
+_GL_CXXALIAS_RPL (strncat, char *, (char *dest, const char *src, size_t n));
+# else
+_GL_CXXALIAS_SYS (strncat, char *, (char *dest, const char *src, size_t n));
+# endif
+_GL_CXXALIASWARN (strncat);
+#elif defined GNULIB_POSIXCHECK
+# undef strncat
+# if HAVE_RAW_DECL_STRNCAT
+_GL_WARN_ON_USE (strncat, "strncat is unportable - "
+ "use gnulib module strncat for portability");
+# endif
+#endif
+
+/* Return a newly allocated copy of at most N bytes of STRING. */
+#if @GNULIB_STRNDUP@
+# if @REPLACE_STRNDUP@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef strndup
+# define strndup rpl_strndup
+# endif
+_GL_FUNCDECL_RPL (strndup, char *, (char const *__string, size_t __n)
+ _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (strndup, char *, (char const *__string, size_t __n));
+# else
+# if ! @HAVE_DECL_STRNDUP@
+_GL_FUNCDECL_SYS (strndup, char *, (char const *__string, size_t __n)
+ _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (strndup, char *, (char const *__string, size_t __n));
+# endif
+_GL_CXXALIASWARN (strndup);
+#elif defined GNULIB_POSIXCHECK
+# undef strndup
+# if HAVE_RAW_DECL_STRNDUP
+_GL_WARN_ON_USE (strndup, "strndup is unportable - "
+ "use gnulib module strndup for portability");
+# endif
+#endif
+
+/* Find the length (number of bytes) of STRING, but scan at most
+ MAXLEN bytes. If no '\0' terminator is found in that many bytes,
+ return MAXLEN. */
+#if @GNULIB_STRNLEN@
+# if @REPLACE_STRNLEN@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef strnlen
+# define strnlen rpl_strnlen
+# endif
+_GL_FUNCDECL_RPL (strnlen, size_t, (char const *__string, size_t __maxlen)
+ _GL_ATTRIBUTE_PURE
+ _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (strnlen, size_t, (char const *__string, size_t __maxlen));
+# else
+# if ! @HAVE_DECL_STRNLEN@
+_GL_FUNCDECL_SYS (strnlen, size_t, (char const *__string, size_t __maxlen)
+ _GL_ATTRIBUTE_PURE
+ _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (strnlen, size_t, (char const *__string, size_t __maxlen));
+# endif
+_GL_CXXALIASWARN (strnlen);
+#elif defined GNULIB_POSIXCHECK
+# undef strnlen
+# if HAVE_RAW_DECL_STRNLEN
+_GL_WARN_ON_USE (strnlen, "strnlen is unportable - "
+ "use gnulib module strnlen for portability");
+# endif
+#endif
+
+#if defined GNULIB_POSIXCHECK
+/* strcspn() assumes the second argument is a list of single-byte characters.
+ Even in this simple case, it does not work with multibyte strings if the
+ locale encoding is GB18030 and one of the characters to be searched is a
+ digit. */
+# undef strcspn
+/* Assume strcspn is always declared. */
+_GL_WARN_ON_USE (strcspn, "strcspn cannot work correctly on character strings "
+ "in multibyte locales - "
+ "use mbscspn if you care about internationalization");
+#endif
+
+/* Find the first occurrence in S of any character in ACCEPT. */
+#if @GNULIB_STRPBRK@
+# if ! @HAVE_STRPBRK@
+_GL_FUNCDECL_SYS (strpbrk, char *, (char const *__s, char const *__accept)
+ _GL_ATTRIBUTE_PURE
+ _GL_ARG_NONNULL ((1, 2)));
+# endif
+ /* On some systems, this function is defined as an overloaded function:
+ extern "C" { const char * strpbrk (const char *, const char *); }
+ extern "C++" { char * strpbrk (char *, const char *); } */
+_GL_CXXALIAS_SYS_CAST2 (strpbrk,
+ char *, (char const *__s, char const *__accept),
+ const char *, (char const *__s, char const *__accept));
+# if ((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 10) && !defined __UCLIBC__) \
+ && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4))
+_GL_CXXALIASWARN1 (strpbrk, char *, (char *__s, char const *__accept));
+_GL_CXXALIASWARN1 (strpbrk, char const *,
+ (char const *__s, char const *__accept));
+# else
+_GL_CXXALIASWARN (strpbrk);
+# endif
+# if defined GNULIB_POSIXCHECK
+/* strpbrk() assumes the second argument is a list of single-byte characters.
+ Even in this simple case, it does not work with multibyte strings if the
+ locale encoding is GB18030 and one of the characters to be searched is a
+ digit. */
+# undef strpbrk
+_GL_WARN_ON_USE (strpbrk, "strpbrk cannot work correctly on character strings "
+ "in multibyte locales - "
+ "use mbspbrk if you care about internationalization");
+# endif
+#elif defined GNULIB_POSIXCHECK
+# undef strpbrk
+# if HAVE_RAW_DECL_STRPBRK
+_GL_WARN_ON_USE (strpbrk, "strpbrk is unportable - "
+ "use gnulib module strpbrk for portability");
+# endif
+#endif
+
+#if defined GNULIB_POSIXCHECK
+/* strspn() assumes the second argument is a list of single-byte characters.
+ Even in this simple case, it cannot work with multibyte strings. */
+# undef strspn
+/* Assume strspn is always declared. */
+_GL_WARN_ON_USE (strspn, "strspn cannot work correctly on character strings "
+ "in multibyte locales - "
+ "use mbsspn if you care about internationalization");
+#endif
+
+#if defined GNULIB_POSIXCHECK
+/* strrchr() does not work with multibyte strings if the locale encoding is
+ GB18030 and the character to be searched is a digit. */
+# undef strrchr
+/* Assume strrchr is always declared. */
+_GL_WARN_ON_USE (strrchr, "strrchr cannot work correctly on character strings "
+ "in some multibyte locales - "
+ "use mbsrchr if you care about internationalization");
+#endif
+
+/* Search the next delimiter (char listed in DELIM) starting at *STRINGP.
+ If one is found, overwrite it with a NUL, and advance *STRINGP
+ to point to the next char after it. Otherwise, set *STRINGP to NULL.
+ If *STRINGP was already NULL, nothing happens.
+ Return the old value of *STRINGP.
+
+ This is a variant of strtok() that is multithread-safe and supports
+ empty fields.
+
+ Caveat: It modifies the original string.
+ Caveat: These functions cannot be used on constant strings.
+ Caveat: The identity of the delimiting character is lost.
+ Caveat: It doesn't work with multibyte strings unless all of the delimiter
+ characters are ASCII characters < 0x30.
+
+ See also strtok_r(). */
+#if @GNULIB_STRSEP@
+# if ! @HAVE_STRSEP@
+_GL_FUNCDECL_SYS (strsep, char *,
+ (char **restrict __stringp, char const *restrict __delim)
+ _GL_ARG_NONNULL ((1, 2)));
+# endif
+_GL_CXXALIAS_SYS (strsep, char *,
+ (char **restrict __stringp, char const *restrict __delim));
+_GL_CXXALIASWARN (strsep);
+# if defined GNULIB_POSIXCHECK
+# undef strsep
+_GL_WARN_ON_USE (strsep, "strsep cannot work correctly on character strings "
+ "in multibyte locales - "
+ "use mbssep if you care about internationalization");
+# endif
+#elif defined GNULIB_POSIXCHECK
+# undef strsep
+# if HAVE_RAW_DECL_STRSEP
+_GL_WARN_ON_USE (strsep, "strsep is unportable - "
+ "use gnulib module strsep for portability");
+# endif
+#endif
+
+#if @GNULIB_STRSTR@
+# if @REPLACE_STRSTR@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define strstr rpl_strstr
+# endif
+_GL_FUNCDECL_RPL (strstr, char *, (const char *haystack, const char *needle)
+ _GL_ATTRIBUTE_PURE
+ _GL_ARG_NONNULL ((1, 2)));
+_GL_CXXALIAS_RPL (strstr, char *, (const char *haystack, const char *needle));
+# else
+ /* On some systems, this function is defined as an overloaded function:
+ extern "C++" { const char * strstr (const char *, const char *); }
+ extern "C++" { char * strstr (char *, const char *); } */
+_GL_CXXALIAS_SYS_CAST2 (strstr,
+ char *, (const char *haystack, const char *needle),
+ const char *, (const char *haystack, const char *needle));
+# endif
+# if ((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 10) && !defined __UCLIBC__) \
+ && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4))
+_GL_CXXALIASWARN1 (strstr, char *, (char *haystack, const char *needle));
+_GL_CXXALIASWARN1 (strstr, const char *,
+ (const char *haystack, const char *needle));
+# else
+_GL_CXXALIASWARN (strstr);
+# endif
+#elif defined GNULIB_POSIXCHECK
+/* strstr() does not work with multibyte strings if the locale encoding is
+ different from UTF-8:
+ POSIX says that it operates on "strings", and "string" in POSIX is defined
+ as a sequence of bytes, not of characters. */
+# undef strstr
+/* Assume strstr is always declared. */
+_GL_WARN_ON_USE (strstr, "strstr is quadratic on many systems, and cannot "
+ "work correctly on character strings in most "
+ "multibyte locales - "
+ "use mbsstr if you care about internationalization, "
+ "or use strstr if you care about speed");
+#endif
+
+/* Find the first occurrence of NEEDLE in HAYSTACK, using case-insensitive
+ comparison. */
+#if @GNULIB_STRCASESTR@
+# if @REPLACE_STRCASESTR@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define strcasestr rpl_strcasestr
+# endif
+_GL_FUNCDECL_RPL (strcasestr, char *,
+ (const char *haystack, const char *needle)
+ _GL_ATTRIBUTE_PURE
+ _GL_ARG_NONNULL ((1, 2)));
+_GL_CXXALIAS_RPL (strcasestr, char *,
+ (const char *haystack, const char *needle));
+# else
+# if ! @HAVE_STRCASESTR@
+_GL_FUNCDECL_SYS (strcasestr, char *,
+ (const char *haystack, const char *needle)
+ _GL_ATTRIBUTE_PURE
+ _GL_ARG_NONNULL ((1, 2)));
+# endif
+ /* On some systems, this function is defined as an overloaded function:
+ extern "C++" { const char * strcasestr (const char *, const char *); }
+ extern "C++" { char * strcasestr (char *, const char *); } */
+_GL_CXXALIAS_SYS_CAST2 (strcasestr,
+ char *, (const char *haystack, const char *needle),
+ const char *, (const char *haystack, const char *needle));
+# endif
+# if ((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 10) && !defined __UCLIBC__) \
+ && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4))
+_GL_CXXALIASWARN1 (strcasestr, char *, (char *haystack, const char *needle));
+_GL_CXXALIASWARN1 (strcasestr, const char *,
+ (const char *haystack, const char *needle));
+# else
+_GL_CXXALIASWARN (strcasestr);
+# endif
+#elif defined GNULIB_POSIXCHECK
+/* strcasestr() does not work with multibyte strings:
+ It is a glibc extension, and glibc implements it only for unibyte
+ locales. */
+# undef strcasestr
+# if HAVE_RAW_DECL_STRCASESTR
+_GL_WARN_ON_USE (strcasestr, "strcasestr does work correctly on character "
+ "strings in multibyte locales - "
+ "use mbscasestr if you care about "
+ "internationalization, or use c-strcasestr if you want "
+ "a locale independent function");
+# endif
+#endif
+
+/* Parse S into tokens separated by characters in DELIM.
+ If S is NULL, the saved pointer in SAVE_PTR is used as
+ the next starting point. For example:
+ char s[] = "-abc-=-def";
+ char *sp;
+ x = strtok_r(s, "-", &sp); // x = "abc", sp = "=-def"
+ x = strtok_r(NULL, "-=", &sp); // x = "def", sp = NULL
+ x = strtok_r(NULL, "=", &sp); // x = NULL
+ // s = "abc\0-def\0"
+
+ This is a variant of strtok() that is multithread-safe.
+
+ For the POSIX documentation for this function, see:
+ http://www.opengroup.org/susv3xsh/strtok.html
+
+ Caveat: It modifies the original string.
+ Caveat: These functions cannot be used on constant strings.
+ Caveat: The identity of the delimiting character is lost.
+ Caveat: It doesn't work with multibyte strings unless all of the delimiter
+ characters are ASCII characters < 0x30.
+
+ See also strsep(). */
+#if @GNULIB_STRTOK_R@
+# if @REPLACE_STRTOK_R@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef strtok_r
+# define strtok_r rpl_strtok_r
+# endif
+_GL_FUNCDECL_RPL (strtok_r, char *,
+ (char *restrict s, char const *restrict delim,
+ char **restrict save_ptr)
+ _GL_ARG_NONNULL ((2, 3)));
+_GL_CXXALIAS_RPL (strtok_r, char *,
+ (char *restrict s, char const *restrict delim,
+ char **restrict save_ptr));
+# else
+# if @UNDEFINE_STRTOK_R@ || defined GNULIB_POSIXCHECK
+# undef strtok_r
+# endif
+# if ! @HAVE_DECL_STRTOK_R@
+_GL_FUNCDECL_SYS (strtok_r, char *,
+ (char *restrict s, char const *restrict delim,
+ char **restrict save_ptr)
+ _GL_ARG_NONNULL ((2, 3)));
+# endif
+_GL_CXXALIAS_SYS (strtok_r, char *,
+ (char *restrict s, char const *restrict delim,
+ char **restrict save_ptr));
+# endif
+_GL_CXXALIASWARN (strtok_r);
+# if defined GNULIB_POSIXCHECK
+_GL_WARN_ON_USE (strtok_r, "strtok_r cannot work correctly on character "
+ "strings in multibyte locales - "
+ "use mbstok_r if you care about internationalization");
+# endif
+#elif defined GNULIB_POSIXCHECK
+# undef strtok_r
+# if HAVE_RAW_DECL_STRTOK_R
+_GL_WARN_ON_USE (strtok_r, "strtok_r is unportable - "
+ "use gnulib module strtok_r for portability");
+# endif
+#endif
+
+
+/* The following functions are not specified by POSIX. They are gnulib
+ extensions. */
+
+#if @GNULIB_MBSLEN@
+/* Return the number of multibyte characters in the character string STRING.
+ This considers multibyte characters, unlike strlen, which counts bytes. */
+# ifdef __MirBSD__ /* MirBSD defines mbslen as a macro. Override it. */
+# undef mbslen
+# endif
+# if @HAVE_MBSLEN@ /* AIX, OSF/1, MirBSD define mbslen already in libc. */
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define mbslen rpl_mbslen
+# endif
+_GL_FUNCDECL_RPL (mbslen, size_t, (const char *string)
+ _GL_ATTRIBUTE_PURE
+ _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (mbslen, size_t, (const char *string));
+# else
+_GL_FUNCDECL_SYS (mbslen, size_t, (const char *string)
+ _GL_ATTRIBUTE_PURE
+ _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_SYS (mbslen, size_t, (const char *string));
+# endif
+_GL_CXXALIASWARN (mbslen);
+#endif
+
+#if @GNULIB_MBSNLEN@
+/* Return the number of multibyte characters in the character string starting
+ at STRING and ending at STRING + LEN. */
+_GL_EXTERN_C size_t mbsnlen (const char *string, size_t len)
+ _GL_ATTRIBUTE_PURE
+ _GL_ARG_NONNULL ((1));
+#endif
+
+#if @GNULIB_MBSCHR@
+/* Locate the first single-byte character C in the character string STRING,
+ and return a pointer to it. Return NULL if C is not found in STRING.
+ Unlike strchr(), this function works correctly in multibyte locales with
+ encodings such as GB18030. */
+# if defined __hpux
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define mbschr rpl_mbschr /* avoid collision with HP-UX function */
+# endif
+_GL_FUNCDECL_RPL (mbschr, char *, (const char *string, int c)
+ _GL_ATTRIBUTE_PURE
+ _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (mbschr, char *, (const char *string, int c));
+# else
+_GL_FUNCDECL_SYS (mbschr, char *, (const char *string, int c)
+ _GL_ATTRIBUTE_PURE
+ _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_SYS (mbschr, char *, (const char *string, int c));
+# endif
+_GL_CXXALIASWARN (mbschr);
+#endif
+
+#if @GNULIB_MBSRCHR@
+/* Locate the last single-byte character C in the character string STRING,
+ and return a pointer to it. Return NULL if C is not found in STRING.
+ Unlike strrchr(), this function works correctly in multibyte locales with
+ encodings such as GB18030. */
+# if defined __hpux || defined __INTERIX
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define mbsrchr rpl_mbsrchr /* avoid collision with system function */
+# endif
+_GL_FUNCDECL_RPL (mbsrchr, char *, (const char *string, int c)
+ _GL_ATTRIBUTE_PURE
+ _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (mbsrchr, char *, (const char *string, int c));
+# else
+_GL_FUNCDECL_SYS (mbsrchr, char *, (const char *string, int c)
+ _GL_ATTRIBUTE_PURE
+ _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_SYS (mbsrchr, char *, (const char *string, int c));
+# endif
+_GL_CXXALIASWARN (mbsrchr);
+#endif
+
+#if @GNULIB_MBSSTR@
+/* Find the first occurrence of the character string NEEDLE in the character
+ string HAYSTACK. Return NULL if NEEDLE is not found in HAYSTACK.
+ Unlike strstr(), this function works correctly in multibyte locales with
+ encodings different from UTF-8. */
+_GL_EXTERN_C char * mbsstr (const char *haystack, const char *needle)
+ _GL_ATTRIBUTE_PURE
+ _GL_ARG_NONNULL ((1, 2));
+#endif
+
+#if @GNULIB_MBSCASECMP@
+/* Compare the character strings S1 and S2, ignoring case, returning less than,
+ equal to or greater than zero if S1 is lexicographically less than, equal to
+ or greater than S2.
+ Note: This function may, in multibyte locales, return 0 for strings of
+ different lengths!
+ Unlike strcasecmp(), this function works correctly in multibyte locales. */
+_GL_EXTERN_C int mbscasecmp (const char *s1, const char *s2)
+ _GL_ATTRIBUTE_PURE
+ _GL_ARG_NONNULL ((1, 2));
+#endif
+
+#if @GNULIB_MBSNCASECMP@
+/* Compare the initial segment of the character string S1 consisting of at most
+ N characters with the initial segment of the character string S2 consisting
+ of at most N characters, ignoring case, returning less than, equal to or
+ greater than zero if the initial segment of S1 is lexicographically less
+ than, equal to or greater than the initial segment of S2.
+ Note: This function may, in multibyte locales, return 0 for initial segments
+ of different lengths!
+ Unlike strncasecmp(), this function works correctly in multibyte locales.
+ But beware that N is not a byte count but a character count! */
+_GL_EXTERN_C int mbsncasecmp (const char *s1, const char *s2, size_t n)
+ _GL_ATTRIBUTE_PURE
+ _GL_ARG_NONNULL ((1, 2));
+#endif
+
+#if @GNULIB_MBSPCASECMP@
+/* Compare the initial segment of the character string STRING consisting of
+ at most mbslen (PREFIX) characters with the character string PREFIX,
+ ignoring case. If the two match, return a pointer to the first byte
+ after this prefix in STRING. Otherwise, return NULL.
+ Note: This function may, in multibyte locales, return non-NULL if STRING
+ is of smaller length than PREFIX!
+ Unlike strncasecmp(), this function works correctly in multibyte
+ locales. */
+_GL_EXTERN_C char * mbspcasecmp (const char *string, const char *prefix)
+ _GL_ATTRIBUTE_PURE
+ _GL_ARG_NONNULL ((1, 2));
+#endif
+
+#if @GNULIB_MBSCASESTR@
+/* Find the first occurrence of the character string NEEDLE in the character
+ string HAYSTACK, using case-insensitive comparison.
+ Note: This function may, in multibyte locales, return success even if
+ strlen (haystack) < strlen (needle) !
+ Unlike strcasestr(), this function works correctly in multibyte locales. */
+_GL_EXTERN_C char * mbscasestr (const char *haystack, const char *needle)
+ _GL_ATTRIBUTE_PURE
+ _GL_ARG_NONNULL ((1, 2));
+#endif
+
+#if @GNULIB_MBSCSPN@
+/* Find the first occurrence in the character string STRING of any character
+ in the character string ACCEPT. Return the number of bytes from the
+ beginning of the string to this occurrence, or to the end of the string
+ if none exists.
+ Unlike strcspn(), this function works correctly in multibyte locales. */
+_GL_EXTERN_C size_t mbscspn (const char *string, const char *accept)
+ _GL_ATTRIBUTE_PURE
+ _GL_ARG_NONNULL ((1, 2));
+#endif
+
+#if @GNULIB_MBSPBRK@
+/* Find the first occurrence in the character string STRING of any character
+ in the character string ACCEPT. Return the pointer to it, or NULL if none
+ exists.
+ Unlike strpbrk(), this function works correctly in multibyte locales. */
+# if defined __hpux
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define mbspbrk rpl_mbspbrk /* avoid collision with HP-UX function */
+# endif
+_GL_FUNCDECL_RPL (mbspbrk, char *, (const char *string, const char *accept)
+ _GL_ATTRIBUTE_PURE
+ _GL_ARG_NONNULL ((1, 2)));
+_GL_CXXALIAS_RPL (mbspbrk, char *, (const char *string, const char *accept));
+# else
+_GL_FUNCDECL_SYS (mbspbrk, char *, (const char *string, const char *accept)
+ _GL_ATTRIBUTE_PURE
+ _GL_ARG_NONNULL ((1, 2)));
+_GL_CXXALIAS_SYS (mbspbrk, char *, (const char *string, const char *accept));
+# endif
+_GL_CXXALIASWARN (mbspbrk);
+#endif
+
+#if @GNULIB_MBSSPN@
+/* Find the first occurrence in the character string STRING of any character
+ not in the character string REJECT. Return the number of bytes from the
+ beginning of the string to this occurrence, or to the end of the string
+ if none exists.
+ Unlike strspn(), this function works correctly in multibyte locales. */
+_GL_EXTERN_C size_t mbsspn (const char *string, const char *reject)
+ _GL_ATTRIBUTE_PURE
+ _GL_ARG_NONNULL ((1, 2));
+#endif
+
+#if @GNULIB_MBSSEP@
+/* Search the next delimiter (multibyte character listed in the character
+ string DELIM) starting at the character string *STRINGP.
+ If one is found, overwrite it with a NUL, and advance *STRINGP to point
+ to the next multibyte character after it. Otherwise, set *STRINGP to NULL.
+ If *STRINGP was already NULL, nothing happens.
+ Return the old value of *STRINGP.
+
+ This is a variant of mbstok_r() that supports empty fields.
+
+ Caveat: It modifies the original string.
+ Caveat: These functions cannot be used on constant strings.
+ Caveat: The identity of the delimiting character is lost.
+
+ See also mbstok_r(). */
+_GL_EXTERN_C char * mbssep (char **stringp, const char *delim)
+ _GL_ARG_NONNULL ((1, 2));
+#endif
+
+#if @GNULIB_MBSTOK_R@
+/* Parse the character string STRING into tokens separated by characters in
+ the character string DELIM.
+ If STRING is NULL, the saved pointer in SAVE_PTR is used as
+ the next starting point. For example:
+ char s[] = "-abc-=-def";
+ char *sp;
+ x = mbstok_r(s, "-", &sp); // x = "abc", sp = "=-def"
+ x = mbstok_r(NULL, "-=", &sp); // x = "def", sp = NULL
+ x = mbstok_r(NULL, "=", &sp); // x = NULL
+ // s = "abc\0-def\0"
+
+ Caveat: It modifies the original string.
+ Caveat: These functions cannot be used on constant strings.
+ Caveat: The identity of the delimiting character is lost.
+
+ See also mbssep(). */
+_GL_EXTERN_C char * mbstok_r (char *string, const char *delim, char **save_ptr)
+ _GL_ARG_NONNULL ((2, 3));
+#endif
+
+/* Map any int, typically from errno, into an error message. */
+#if @GNULIB_STRERROR@
+# if @REPLACE_STRERROR@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef strerror
+# define strerror rpl_strerror
+# endif
+_GL_FUNCDECL_RPL (strerror, char *, (int));
+_GL_CXXALIAS_RPL (strerror, char *, (int));
+# else
+_GL_CXXALIAS_SYS (strerror, char *, (int));
+# endif
+_GL_CXXALIASWARN (strerror);
+#elif defined GNULIB_POSIXCHECK
+# undef strerror
+/* Assume strerror is always declared. */
+_GL_WARN_ON_USE (strerror, "strerror is unportable - "
+ "use gnulib module strerror to guarantee non-NULL result");
+#endif
+
+/* Map any int, typically from errno, into an error message. Multithread-safe.
+ Uses the POSIX declaration, not the glibc declaration. */
+#if @GNULIB_STRERROR_R@
+# if @REPLACE_STRERROR_R@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef strerror_r
+# define strerror_r rpl_strerror_r
+# endif
+_GL_FUNCDECL_RPL (strerror_r, int, (int errnum, char *buf, size_t buflen)
+ _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_RPL (strerror_r, int, (int errnum, char *buf, size_t buflen));
+# else
+# if !@HAVE_DECL_STRERROR_R@
+_GL_FUNCDECL_SYS (strerror_r, int, (int errnum, char *buf, size_t buflen)
+ _GL_ARG_NONNULL ((2)));
+# endif
+_GL_CXXALIAS_SYS (strerror_r, int, (int errnum, char *buf, size_t buflen));
+# endif
+# if @HAVE_DECL_STRERROR_R@
+_GL_CXXALIASWARN (strerror_r);
+# endif
+#elif defined GNULIB_POSIXCHECK
+# undef strerror_r
+# if HAVE_RAW_DECL_STRERROR_R
+_GL_WARN_ON_USE (strerror_r, "strerror_r is unportable - "
+ "use gnulib module strerror_r-posix for portability");
+# endif
+#endif
+
+#if @GNULIB_STRSIGNAL@
+# if @REPLACE_STRSIGNAL@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define strsignal rpl_strsignal
+# endif
+_GL_FUNCDECL_RPL (strsignal, char *, (int __sig));
+_GL_CXXALIAS_RPL (strsignal, char *, (int __sig));
+# else
+# if ! @HAVE_DECL_STRSIGNAL@
+_GL_FUNCDECL_SYS (strsignal, char *, (int __sig));
+# endif
+/* Need to cast, because on Cygwin 1.5.x systems, the return type is
+ 'const char *'. */
+_GL_CXXALIAS_SYS_CAST (strsignal, char *, (int __sig));
+# endif
+_GL_CXXALIASWARN (strsignal);
+#elif defined GNULIB_POSIXCHECK
+# undef strsignal
+# if HAVE_RAW_DECL_STRSIGNAL
+_GL_WARN_ON_USE (strsignal, "strsignal is unportable - "
+ "use gnulib module strsignal for portability");
+# endif
+#endif
+
+#if @GNULIB_STRVERSCMP@
+# if !@HAVE_STRVERSCMP@
+_GL_FUNCDECL_SYS (strverscmp, int, (const char *, const char *)
+ _GL_ATTRIBUTE_PURE
+ _GL_ARG_NONNULL ((1, 2)));
+# endif
+_GL_CXXALIAS_SYS (strverscmp, int, (const char *, const char *));
+_GL_CXXALIASWARN (strverscmp);
+#elif defined GNULIB_POSIXCHECK
+# undef strverscmp
+# if HAVE_RAW_DECL_STRVERSCMP
+_GL_WARN_ON_USE (strverscmp, "strverscmp is unportable - "
+ "use gnulib module strverscmp for portability");
+# endif
+#endif
+
+
+#endif /* _@GUARD_PREFIX@_STRING_H */
+#endif /* _@GUARD_PREFIX@_STRING_H */
+#endif
diff --git a/lib/string_.h b/lib/string_.h
deleted file mode 100644
index b50523c..0000000
--- a/lib/string_.h
+++ /dev/null
@@ -1,544 +0,0 @@
-/* A GNU-like <string.h>.
-
- Copyright (C) 1995-1996, 2001-2007 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-#ifndef _GL_STRING_H
-#define _GL_STRING_H
-
-/* This #pragma avoids a warning with "gcc -Wmissing-prototypes" on some
- mingw systems. */
-#ifdef __GNUC__
-# pragma GCC system_header
-#endif
-
-#include @ABSOLUTE_STRING_H@
-
-
-/* The definition of GL_LINK_WARNING is copied here. */
-
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Return the first occurrence of NEEDLE in HAYSTACK. */
-#if @GNULIB_MEMMEM@
-# if ! @HAVE_DECL_MEMMEM@
-extern void *memmem (void const *__haystack, size_t __haystack_len,
- void const *__needle, size_t __needle_len);
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef memmem
-# define memmem(a,al,b,bl) \
- (GL_LINK_WARNING ("memmem is unportable - " \
- "use gnulib module memmem for portability"), \
- memmem (a, al, b, bl))
-#endif
-
-/* Copy N bytes of SRC to DEST, return pointer to bytes after the
- last written byte. */
-#if @GNULIB_MEMPCPY@
-# if ! @HAVE_MEMPCPY@
-extern void *mempcpy (void *restrict __dest, void const *restrict __src,
- size_t __n);
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef mempcpy
-# define mempcpy(a,b,n) \
- (GL_LINK_WARNING ("mempcpy is unportable - " \
- "use gnulib module mempcpy for portability"), \
- mempcpy (a, b, n))
-#endif
-
-/* Search backwards through a block for a byte (specified as an int). */
-#if @GNULIB_MEMRCHR@
-# if ! @HAVE_DECL_MEMRCHR@
-extern void *memrchr (void const *, int, size_t);
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef memrchr
-# define memrchr(a,b,c) \
- (GL_LINK_WARNING ("memrchr is unportable - " \
- "use gnulib module memrchr for portability"), \
- memrchr (a, b, c))
-#endif
-
-/* Copy SRC to DST, returning the address of the terminating '\0' in DST. */
-#if @GNULIB_STPCPY@
-# if ! @HAVE_STPCPY@
-extern char *stpcpy (char *restrict __dst, char const *restrict __src);
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef stpcpy
-# define stpcpy(a,b) \
- (GL_LINK_WARNING ("stpcpy is unportable - " \
- "use gnulib module stpcpy for portability"), \
- stpcpy (a, b))
-#endif
-
-/* Copy no more than N bytes of SRC to DST, returning a pointer past the
- last non-NUL byte written into DST. */
-#if @GNULIB_STPNCPY@
-# if ! @HAVE_STPNCPY@
-# define stpncpy gnu_stpncpy
-extern char *stpncpy (char *restrict __dst, char const *restrict __src,
- size_t __n);
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef stpncpy
-# define stpncpy(a,b,n) \
- (GL_LINK_WARNING ("stpncpy is unportable - " \
- "use gnulib module stpncpy for portability"), \
- stpncpy (a, b, n))
-#endif
-
-/* Compare strings S1 and S2, ignoring case, returning less than, equal to or
- greater than zero if S1 is lexicographically less than, equal to or greater
- than S2.
- Note: This function does not work in multibyte locales. */
-#if ! @HAVE_STRCASECMP@
-extern int strcasecmp (char const *s1, char const *s2);
-#endif
-#if defined GNULIB_POSIXCHECK
-/* strcasecmp() does not work with multibyte strings:
- POSIX says that it operates on "strings", and "string" in POSIX is defined
- as a sequence of bytes, not of characters. */
-# undef strcasecmp
-# define strcasecmp(a,b) \
- (GL_LINK_WARNING ("strcasecmp cannot work correctly on character strings " \
- "in multibyte locales - " \
- "use mbscasecmp if you care about " \
- "internationalization, or use c_strcasecmp (from " \
- "gnulib module c-strcase) if you want a locale " \
- "independent function"), \
- strcasecmp (a, b))
-#endif
-
-/* Compare no more than N bytes of strings S1 and S2, ignoring case,
- returning less than, equal to or greater than zero if S1 is
- lexicographically less than, equal to or greater than S2.
- Note: This function cannot work correctly in multibyte locales. */
-#if ! @HAVE_DECL_STRNCASECMP@
-extern int strncasecmp (char const *s1, char const *s2, size_t n);
-#endif
-#if defined GNULIB_POSIXCHECK
-/* strncasecmp() does not work with multibyte strings:
- POSIX says that it operates on "strings", and "string" in POSIX is defined
- as a sequence of bytes, not of characters. */
-# undef strncasecmp
-# define strncasecmp(a,b,n) \
- (GL_LINK_WARNING ("strncasecmp cannot work correctly on character " \
- "strings in multibyte locales - " \
- "use mbsncasecmp or mbspcasecmp if you care about " \
- "internationalization, or use c_strncasecmp (from " \
- "gnulib module c-strcase) if you want a locale " \
- "independent function"), \
- strncasecmp (a, b, n))
-#endif
-
-#if defined GNULIB_POSIXCHECK
-/* strchr() does not work with multibyte strings if the locale encoding is
- GB18030 and the character to be searched is a digit. */
-# undef strchr
-# define strchr(s,c) \
- (GL_LINK_WARNING ("strchr cannot work correctly on character strings " \
- "in some multibyte locales - " \
- "use mbschr if you care about internationalization"), \
- strchr (s, c))
-#endif
-
-/* Find the first occurrence of C in S or the final NUL byte. */
-#if @GNULIB_STRCHRNUL@
-# if ! @HAVE_STRCHRNUL@
-extern char *strchrnul (char const *__s, int __c_in);
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef strchrnul
-# define strchrnul(a,b) \
- (GL_LINK_WARNING ("strchrnul is unportable - " \
- "use gnulib module strchrnul for portability"), \
- strchrnul (a, b))
-#endif
-
-/* Duplicate S, returning an identical malloc'd string. */
-#if @GNULIB_STRDUP@
-# if ! @HAVE_DECL_STRDUP@ && ! defined strdup
-extern char *strdup (char const *__s);
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef strdup
-# define strdup(a) \
- (GL_LINK_WARNING ("strdup is unportable - " \
- "use gnulib module strdup for portability"), \
- strdup (a))
-#endif
-
-/* Return a newly allocated copy of at most N bytes of STRING. */
-#if @GNULIB_STRNDUP@
-# if ! @HAVE_STRNDUP@
-# undef strndup
-# define strndup rpl_strndup
-# endif
-# if ! @HAVE_STRNDUP@ || ! @HAVE_DECL_STRNDUP@
-extern char *strndup (char const *__string, size_t __n);
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef strndup
-# define strndup(a,n) \
- (GL_LINK_WARNING ("strndup is unportable - " \
- "use gnulib module strndup for portability"), \
- strndup (a, n))
-#endif
-
-/* Find the length (number of bytes) of STRING, but scan at most
- MAXLEN bytes. If no '\0' terminator is found in that many bytes,
- return MAXLEN. */
-#if @GNULIB_STRNLEN@
-# if ! @HAVE_DECL_STRNLEN@
-extern size_t strnlen (char const *__string, size_t __maxlen);
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef strnlen
-# define strnlen(a,n) \
- (GL_LINK_WARNING ("strnlen is unportable - " \
- "use gnulib module strnlen for portability"), \
- strnlen (a, n))
-#endif
-
-#if defined GNULIB_POSIXCHECK
-/* strcspn() assumes the second argument is a list of single-byte characters.
- Even in this simple case, it does not work with multibyte strings if the
- locale encoding is GB18030 and one of the characters to be searched is a
- digit. */
-# undef strcspn
-# define strcspn(s,a) \
- (GL_LINK_WARNING ("strcspn cannot work correctly on character strings " \
- "in multibyte locales - " \
- "use mbscspn if you care about internationalization"), \
- strcspn (s, a))
-#endif
-
-/* Find the first occurrence in S of any character in ACCEPT. */
-#if @GNULIB_STRPBRK@
-# if ! @HAVE_STRPBRK@
-extern char *strpbrk (char const *__s, char const *__accept);
-# endif
-# if defined GNULIB_POSIXCHECK
-/* strpbrk() assumes the second argument is a list of single-byte characters.
- Even in this simple case, it does not work with multibyte strings if the
- locale encoding is GB18030 and one of the characters to be searched is a
- digit. */
-# undef strpbrk
-# define strpbrk(s,a) \
- (GL_LINK_WARNING ("strpbrk cannot work correctly on character strings " \
- "in multibyte locales - " \
- "use mbspbrk if you care about internationalization"), \
- strpbrk (s, a))
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef strpbrk
-# define strpbrk(s,a) \
- (GL_LINK_WARNING ("strpbrk is unportable - " \
- "use gnulib module strpbrk for portability"), \
- strpbrk (s, a))
-#endif
-
-#if defined GNULIB_POSIXCHECK
-/* strspn() assumes the second argument is a list of single-byte characters.
- Even in this simple case, it cannot work with multibyte strings. */
-# undef strspn
-# define strspn(s,a) \
- (GL_LINK_WARNING ("strspn cannot work correctly on character strings " \
- "in multibyte locales - " \
- "use mbsspn if you care about internationalization"), \
- strspn (s, a))
-#endif
-
-#if defined GNULIB_POSIXCHECK
-/* strrchr() does not work with multibyte strings if the locale encoding is
- GB18030 and the character to be searched is a digit. */
-# undef strrchr
-# define strrchr(s,c) \
- (GL_LINK_WARNING ("strrchr cannot work correctly on character strings " \
- "in some multibyte locales - " \
- "use mbsrchr if you care about internationalization"), \
- strrchr (s, c))
-#endif
-
-/* Search the next delimiter (char listed in DELIM) starting at *STRINGP.
- If one is found, overwrite it with a NUL, and advance *STRINGP
- to point to the next char after it. Otherwise, set *STRINGP to NULL.
- If *STRINGP was already NULL, nothing happens.
- Return the old value of *STRINGP.
-
- This is a variant of strtok() that is multithread-safe and supports
- empty fields.
-
- Caveat: It modifies the original string.
- Caveat: These functions cannot be used on constant strings.
- Caveat: The identity of the delimiting character is lost.
- Caveat: It doesn't work with multibyte strings unless all of the delimiter
- characters are ASCII characters < 0x30.
-
- See also strtok_r(). */
-#if @GNULIB_STRSEP@
-# if ! @HAVE_STRSEP@
-extern char *strsep (char **restrict __stringp, char const *restrict __delim);
-# endif
-# if defined GNULIB_POSIXCHECK
-# undef strsep
-# define strsep(s,d) \
- (GL_LINK_WARNING ("strsep cannot work correctly on character strings " \
- "in multibyte locales - " \
- "use mbssep if you care about internationalization"), \
- strsep (s, d))
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef strsep
-# define strsep(s,d) \
- (GL_LINK_WARNING ("strsep is unportable - " \
- "use gnulib module strsep for portability"), \
- strsep (s, d))
-#endif
-
-#if defined GNULIB_POSIXCHECK
-/* strstr() does not work with multibyte strings if the locale encoding is
- different from UTF-8:
- POSIX says that it operates on "strings", and "string" in POSIX is defined
- as a sequence of bytes, not of characters. */
-# undef strstr
-# define strstr(a,b) \
- (GL_LINK_WARNING ("strstr cannot work correctly on character strings " \
- "in most multibyte locales - " \
- "use mbsstr if you care about internationalization"), \
- strstr (a, b))
-#endif
-
-/* Find the first occurrence of NEEDLE in HAYSTACK, using case-insensitive
- comparison. */
-#if ! @HAVE_STRCASESTR@
-extern char *strcasestr (const char *haystack, const char *needle);
-#endif
-#if defined GNULIB_POSIXCHECK
-/* strcasestr() does not work with multibyte strings:
- It is a glibc extension, and glibc implements it only for unibyte
- locales. */
-# undef strcasestr
-# define strcasestr(a,b) \
- (GL_LINK_WARNING ("strcasestr does work correctly on character strings " \
- "in multibyte locales - " \
- "use mbscasestr if you care about " \
- "internationalization, or use c-strcasestr if you want " \
- "a locale independent function"), \
- strcasestr (a, b))
-#endif
-
-/* Parse S into tokens separated by characters in DELIM.
- If S is NULL, the saved pointer in SAVE_PTR is used as
- the next starting point. For example:
- char s[] = "-abc-=-def";
- char *sp;
- x = strtok_r(s, "-", &sp); // x = "abc", sp = "=-def"
- x = strtok_r(NULL, "-=", &sp); // x = "def", sp = NULL
- x = strtok_r(NULL, "=", &sp); // x = NULL
- // s = "abc\0-def\0"
-
- This is a variant of strtok() that is multithread-safe.
-
- For the POSIX documentation for this function, see:
- http://www.opengroup.org/susv3xsh/strtok.html
-
- Caveat: It modifies the original string.
- Caveat: These functions cannot be used on constant strings.
- Caveat: The identity of the delimiting character is lost.
- Caveat: It doesn't work with multibyte strings unless all of the delimiter
- characters are ASCII characters < 0x30.
-
- See also strsep(). */
-#if @GNULIB_STRTOK_R@
-# if ! @HAVE_DECL_STRTOK_R@
-extern char *strtok_r (char *restrict s, char const *restrict delim,
- char **restrict save_ptr);
-# endif
-# if defined GNULIB_POSIXCHECK
-# undef strtok_r
-# define strtok_r(s,d,p) \
- (GL_LINK_WARNING ("strtok_r cannot work correctly on character strings " \
- "in multibyte locales - " \
- "use mbstok_r if you care about internationalization"), \
- strtok_r (s, d, p))
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef strtok_r
-# define strtok_r(s,d,p) \
- (GL_LINK_WARNING ("strtok_r is unportable - " \
- "use gnulib module strtok_r for portability"), \
- strtok_r (s, d, p))
-#endif
-
-
-/* The following functions are not specified by POSIX. They are gnulib
- extensions. */
-
-#if @GNULIB_MBSLEN@
-/* Return the number of multibyte characters in the character string STRING.
- This considers multibyte characters, unlike strlen, which counts bytes. */
-extern size_t mbslen (const char *string);
-#endif
-
-#if @GNULIB_MBSCHR@
-/* Locate the first single-byte character C in the character string STRING,
- and return a pointer to it. Return NULL if C is not found in STRING.
- Unlike strchr(), this function works correctly in multibyte locales with
- encodings such as GB18030. */
-# define mbschr rpl_mbschr /* avoid collision with HP-UX function */
-extern char * mbschr (const char *string, int c);
-#endif
-
-#if @GNULIB_MBSRCHR@
-/* Locate the last single-byte character C in the character string STRING,
- and return a pointer to it. Return NULL if C is not found in STRING.
- Unlike strrchr(), this function works correctly in multibyte locales with
- encodings such as GB18030. */
-# define mbsrchr rpl_mbsrchr /* avoid collision with HP-UX function */
-extern char * mbsrchr (const char *string, int c);
-#endif
-
-#if @GNULIB_MBSSTR@
-/* Find the first occurrence of the character string NEEDLE in the character
- string HAYSTACK. Return NULL if NEEDLE is not found in HAYSTACK.
- Unlike strstr(), this function works correctly in multibyte locales with
- encodings different from UTF-8. */
-extern char * mbsstr (const char *haystack, const char *needle);
-#endif
-
-#if @GNULIB_MBSCASECMP@
-/* Compare the character strings S1 and S2, ignoring case, returning less than,
- equal to or greater than zero if S1 is lexicographically less than, equal to
- or greater than S2.
- Note: This function may, in multibyte locales, return 0 for strings of
- different lengths!
- Unlike strcasecmp(), this function works correctly in multibyte locales. */
-extern int mbscasecmp (const char *s1, const char *s2);
-#endif
-
-#if @GNULIB_MBSNCASECMP@
-/* Compare the initial segment of the character string S1 consisting of at most
- N characters with the initial segment of the character string S2 consisting
- of at most N characters, ignoring case, returning less than, equal to or
- greater than zero if the initial segment of S1 is lexicographically less
- than, equal to or greater than the initial segment of S2.
- Note: This function may, in multibyte locales, return 0 for initial segments
- of different lengths!
- Unlike strncasecmp(), this function works correctly in multibyte locales.
- But beware that N is not a byte count but a character count! */
-extern int mbsncasecmp (const char *s1, const char *s2, size_t n);
-#endif
-
-#if @GNULIB_MBSPCASECMP@
-/* Compare the initial segment of the character string STRING consisting of
- at most mbslen (PREFIX) characters with the character string PREFIX,
- ignoring case, returning less than, equal to or greater than zero if this
- initial segment is lexicographically less than, equal to or greater than
- PREFIX.
- Note: This function may, in multibyte locales, return 0 if STRING is of
- smaller length than PREFIX!
- Unlike strncasecmp(), this function works correctly in multibyte
- locales. */
-extern char * mbspcasecmp (const char *string, const char *prefix);
-#endif
-
-#if @GNULIB_MBSCASESTR@
-/* Find the first occurrence of the character string NEEDLE in the character
- string HAYSTACK, using case-insensitive comparison.
- Note: This function may, in multibyte locales, return success even if
- strlen (haystack) < strlen (needle) !
- Unlike strcasestr(), this function works correctly in multibyte locales. */
-extern char * mbscasestr (const char *haystack, const char *needle);
-#endif
-
-#if @GNULIB_MBSCSPN@
-/* Find the first occurrence in the character string STRING of any character
- in the character string ACCEPT. Return the number of bytes from the
- beginning of the string to this occurrence, or to the end of the string
- if none exists.
- Unlike strcspn(), this function works correctly in multibyte locales. */
-extern size_t mbscspn (const char *string, const char *accept);
-#endif
-
-#if @GNULIB_MBSPBRK@
-/* Find the first occurrence in the character string STRING of any character
- in the character string ACCEPT. Return the pointer to it, or NULL if none
- exists.
- Unlike strpbrk(), this function works correctly in multibyte locales. */
-# define mbspbrk rpl_mbspbrk /* avoid collision with HP-UX function */
-extern char * mbspbrk (const char *string, const char *accept);
-#endif
-
-#if @GNULIB_MBSSPN@
-/* Find the first occurrence in the character string STRING of any character
- not in the character string REJECT. Return the number of bytes from the
- beginning of the string to this occurrence, or to the end of the string
- if none exists.
- Unlike strspn(), this function works correctly in multibyte locales. */
-extern size_t mbsspn (const char *string, const char *reject);
-#endif
-
-#if @GNULIB_MBSSEP@
-/* Search the next delimiter (multibyte character listed in the character
- string DELIM) starting at the character string *STRINGP.
- If one is found, overwrite it with a NUL, and advance *STRINGP to point
- to the next multibyte character after it. Otherwise, set *STRINGP to NULL.
- If *STRINGP was already NULL, nothing happens.
- Return the old value of *STRINGP.
-
- This is a variant of mbstok_r() that supports empty fields.
-
- Caveat: It modifies the original string.
- Caveat: These functions cannot be used on constant strings.
- Caveat: The identity of the delimiting character is lost.
-
- See also mbstok_r(). */
-extern char * mbssep (char **stringp, const char *delim);
-#endif
-
-#if @GNULIB_MBSTOK_R@
-/* Parse the character string STRING into tokens separated by characters in
- the character string DELIM.
- If STRING is NULL, the saved pointer in SAVE_PTR is used as
- the next starting point. For example:
- char s[] = "-abc-=-def";
- char *sp;
- x = mbstok_r(s, "-", &sp); // x = "abc", sp = "=-def"
- x = mbstok_r(NULL, "-=", &sp); // x = "def", sp = NULL
- x = mbstok_r(NULL, "=", &sp); // x = NULL
- // s = "abc\0-def\0"
-
- Caveat: It modifies the original string.
- Caveat: These functions cannot be used on constant strings.
- Caveat: The identity of the delimiting character is lost.
-
- See also mbssep(). */
-extern char * mbstok_r (char *string, const char *delim, char **save_ptr);
-#endif
-
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
diff --git a/lib/strintcmp.c b/lib/strintcmp.c
index f8f1801..7aae359 100644
--- a/lib/strintcmp.c
+++ b/lib/strintcmp.c
@@ -1,11 +1,11 @@
/* Compare integer strings.
- Copyright (C) 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2005-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
diff --git a/lib/stripslash.c b/lib/stripslash.c
index 342d497..0453e36 100644
--- a/lib/stripslash.c
+++ b/lib/stripslash.c
@@ -1,11 +1,12 @@
/* stripslash.c -- remove redundant trailing slashes from a file name
- Copyright (C) 1990, 2001, 2003-2006 Free Software Foundation, Inc.
+ Copyright (C) 1990, 2001, 2003-2006, 2009-2016 Free Software Foundation,
+ Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
@@ -35,7 +35,7 @@ strip_trailing_slashes (char *file)
bool had_slash;
/* last_component returns "" for file system roots, but we need to turn
- `///' into `/'. */
+ "///" into "/". */
if (! *base)
base = file;
base_lim = base + base_len (base);
diff --git a/lib/strncat.c b/lib/strncat.c
new file mode 100644
index 0000000..f114405
--- /dev/null
+++ b/lib/strncat.c
@@ -0,0 +1,33 @@
+/* Concatenate strings.
+ Copyright (C) 1999, 2002, 2006, 2010-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2002.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <string.h>
+
+char *
+strncat (char *dest, const char *src, size_t n)
+{
+ char *destptr = dest + strlen (dest);
+
+ for (; n > 0 && (*destptr = *src) != '\0'; src++, destptr++, n--)
+ ;
+ if (n == 0)
+ *destptr = '\0';
+ return dest;
+}
diff --git a/lib/strndup.c b/lib/strndup.c
index 3a1b0ea..6250fcd 100644
--- a/lib/strndup.c
+++ b/lib/strndup.c
@@ -1,11 +1,11 @@
/* A replacement function, for systems that lack strndup.
- Copyright (C) 1996, 1997, 1998, 2001, 2002, 2003, 2005, 2006, 2007
- Free Software Foundation, Inc.
+ Copyright (C) 1996-1998, 2001-2003, 2005-2007, 2009-2016 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 2, or (at your option) any
+ Free Software Foundation; either version 3, or (at your option) any
later version.
This program is distributed in the hope that it will be useful,
@@ -14,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program; if not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
diff --git a/lib/strnlen.c b/lib/strnlen.c
index d346d32..1bd7936 100644
--- a/lib/strnlen.c
+++ b/lib/strnlen.c
@@ -1,10 +1,10 @@
/* Find the length of STRING, but scan at most MAXLEN characters.
- Copyright (C) 2005, 2006, 2007 Free Software Foundation, Inc.
+ Copyright (C) 2005-2007, 2009-2016 Free Software Foundation, Inc.
Written by Simon Josefsson.
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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program; if not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
diff --git a/lib/strnlen1.c b/lib/strnlen1.c
index 422ed9e..f5e0ffc 100644
--- a/lib/strnlen1.c
+++ b/lib/strnlen1.c
@@ -1,10 +1,10 @@
/* Find the length of STRING + 1, but scan at most MAXLEN bytes.
- Copyright (C) 2005-2006 Free Software Foundation, Inc.
+ Copyright (C) 2005-2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -12,8 +12,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
diff --git a/lib/strnlen1.h b/lib/strnlen1.h
index 7ce7d0c..d3cd7c1 100644
--- a/lib/strnlen1.h
+++ b/lib/strnlen1.h
@@ -1,10 +1,10 @@
/* Find the length of STRING + 1, but scan at most MAXLEN bytes.
- Copyright (C) 2005 Free Software Foundation, Inc.
+ Copyright (C) 2005, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -12,8 +12,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifndef _STRNLEN1_H
#define _STRNLEN1_H
@@ -29,7 +28,8 @@ extern "C" {
/* Find the length of STRING + 1, but scan at most MAXLEN bytes.
If no '\0' terminator is found in that many characters, return MAXLEN. */
/* This is the same as strnlen (string, maxlen - 1) + 1. */
-extern size_t strnlen1 (const char *string, size_t maxlen);
+extern size_t strnlen1 (const char *string, size_t maxlen)
+ _GL_ATTRIBUTE_PURE;
#ifdef __cplusplus
diff --git a/lib/strnumcmp-in.h b/lib/strnumcmp-in.h
index 9b968cb..2187af4 100644
--- a/lib/strnumcmp-in.h
+++ b/lib/strnumcmp-in.h
@@ -1,12 +1,11 @@
/* Compare numeric strings. This is an internal include file.
- Copyright (C) 1988, 1991, 1992, 1993, 1995, 1996, 1998, 1999, 2000,
- 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 1988-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Mike Haertel. */
@@ -35,7 +33,7 @@
- It's typically faster.
POSIX says that only '0' through '9' are digits. Prefer ISDIGIT to
isdigit unless it's important to use the locale's definition
- of `digit' even when the host does not conform to POSIX. */
+ of 'digit' even when the host does not conform to POSIX. */
# define ISDIGIT(c) ((unsigned int) (c) - '0' <= 9)
@@ -72,34 +70,34 @@
if digit return -1, else 0
return 0 */
-static inline int
+static inline int _GL_ATTRIBUTE_PURE
fraccompare (char const *a, char const *b, char decimal_point)
{
if (*a == decimal_point && *b == decimal_point)
{
while (*++a == *++b)
- if (! ISDIGIT (*a))
- return 0;
+ if (! ISDIGIT (*a))
+ return 0;
if (ISDIGIT (*a) && ISDIGIT (*b))
- return *a - *b;
+ return *a - *b;
if (ISDIGIT (*a))
- goto a_trailing_nonzero;
+ goto a_trailing_nonzero;
if (ISDIGIT (*b))
- goto b_trailing_nonzero;
+ goto b_trailing_nonzero;
return 0;
}
else if (*a++ == decimal_point)
{
a_trailing_nonzero:
while (*a == NUMERIC_ZERO)
- a++;
+ a++;
return ISDIGIT (*a);
}
else if (*b++ == decimal_point)
{
b_trailing_nonzero:
while (*b == NUMERIC_ZERO)
- b++;
+ b++;
return - ISDIGIT (*b);
}
return 0;
@@ -112,9 +110,9 @@ fraccompare (char const *a, char const *b, char decimal_point)
causes comparisons to act as if there is no decimal point
character, and likewise for THOUSANDS_SEP. */
-static inline int
+static inline int _GL_ATTRIBUTE_PURE
numcompare (char const *a, char const *b,
- int decimal_point, int thousands_sep)
+ int decimal_point, int thousands_sep)
{
unsigned char tmpa = *a;
unsigned char tmpb = *b;
@@ -125,119 +123,119 @@ numcompare (char const *a, char const *b,
if (tmpa == NEGATION_SIGN)
{
do
- tmpa = *++a;
+ tmpa = *++a;
while (tmpa == NUMERIC_ZERO || tmpa == thousands_sep);
if (tmpb != NEGATION_SIGN)
- {
- if (tmpa == decimal_point)
- do
- tmpa = *++a;
- while (tmpa == NUMERIC_ZERO);
- if (ISDIGIT (tmpa))
- return -1;
- while (tmpb == NUMERIC_ZERO || tmpb == thousands_sep)
- tmpb = *++b;
- if (tmpb == decimal_point)
- do
- tmpb = *++b;
- while (tmpb == NUMERIC_ZERO);
- return - ISDIGIT (tmpb);
- }
+ {
+ if (tmpa == decimal_point)
+ do
+ tmpa = *++a;
+ while (tmpa == NUMERIC_ZERO);
+ if (ISDIGIT (tmpa))
+ return -1;
+ while (tmpb == NUMERIC_ZERO || tmpb == thousands_sep)
+ tmpb = *++b;
+ if (tmpb == decimal_point)
+ do
+ tmpb = *++b;
+ while (tmpb == NUMERIC_ZERO);
+ return - ISDIGIT (tmpb);
+ }
do
- tmpb = *++b;
+ tmpb = *++b;
while (tmpb == NUMERIC_ZERO || tmpb == thousands_sep);
while (tmpa == tmpb && ISDIGIT (tmpa))
- {
- do
- tmpa = *++a;
- while (tmpa == thousands_sep);
- do
- tmpb = *++b;
- while (tmpb == thousands_sep);
- }
+ {
+ do
+ tmpa = *++a;
+ while (tmpa == thousands_sep);
+ do
+ tmpb = *++b;
+ while (tmpb == thousands_sep);
+ }
if ((tmpa == decimal_point && !ISDIGIT (tmpb))
- || (tmpb == decimal_point && !ISDIGIT (tmpa)))
- return fraccompare (b, a, decimal_point);
+ || (tmpb == decimal_point && !ISDIGIT (tmpa)))
+ return fraccompare (b, a, decimal_point);
tmp = tmpb - tmpa;
for (log_a = 0; ISDIGIT (tmpa); ++log_a)
- do
- tmpa = *++a;
- while (tmpa == thousands_sep);
+ do
+ tmpa = *++a;
+ while (tmpa == thousands_sep);
for (log_b = 0; ISDIGIT (tmpb); ++log_b)
- do
- tmpb = *++b;
- while (tmpb == thousands_sep);
+ do
+ tmpb = *++b;
+ while (tmpb == thousands_sep);
if (log_a != log_b)
- return log_a < log_b ? 1 : -1;
+ return log_a < log_b ? 1 : -1;
if (!log_a)
- return 0;
+ return 0;
return tmp;
}
else if (tmpb == NEGATION_SIGN)
{
do
- tmpb = *++b;
+ tmpb = *++b;
while (tmpb == NUMERIC_ZERO || tmpb == thousands_sep);
if (tmpb == decimal_point)
- do
- tmpb = *++b;
- while (tmpb == NUMERIC_ZERO);
+ do
+ tmpb = *++b;
+ while (tmpb == NUMERIC_ZERO);
if (ISDIGIT (tmpb))
- return 1;
+ return 1;
while (tmpa == NUMERIC_ZERO || tmpa == thousands_sep)
- tmpa = *++a;
+ tmpa = *++a;
if (tmpa == decimal_point)
- do
- tmpa = *++a;
- while (tmpa == NUMERIC_ZERO);
+ do
+ tmpa = *++a;
+ while (tmpa == NUMERIC_ZERO);
return ISDIGIT (tmpa);
}
else
{
while (tmpa == NUMERIC_ZERO || tmpa == thousands_sep)
- tmpa = *++a;
+ tmpa = *++a;
while (tmpb == NUMERIC_ZERO || tmpb == thousands_sep)
- tmpb = *++b;
+ tmpb = *++b;
while (tmpa == tmpb && ISDIGIT (tmpa))
- {
- do
- tmpa = *++a;
- while (tmpa == thousands_sep);
- do
- tmpb = *++b;
- while (tmpb == thousands_sep);
- }
+ {
+ do
+ tmpa = *++a;
+ while (tmpa == thousands_sep);
+ do
+ tmpb = *++b;
+ while (tmpb == thousands_sep);
+ }
if ((tmpa == decimal_point && !ISDIGIT (tmpb))
- || (tmpb == decimal_point && !ISDIGIT (tmpa)))
- return fraccompare (a, b, decimal_point);
+ || (tmpb == decimal_point && !ISDIGIT (tmpa)))
+ return fraccompare (a, b, decimal_point);
tmp = tmpa - tmpb;
for (log_a = 0; ISDIGIT (tmpa); ++log_a)
- do
- tmpa = *++a;
- while (tmpa == thousands_sep);
+ do
+ tmpa = *++a;
+ while (tmpa == thousands_sep);
for (log_b = 0; ISDIGIT (tmpb); ++log_b)
- do
- tmpb = *++b;
- while (tmpb == thousands_sep);
+ do
+ tmpb = *++b;
+ while (tmpb == thousands_sep);
if (log_a != log_b)
- return log_a < log_b ? -1 : 1;
+ return log_a < log_b ? -1 : 1;
if (!log_a)
- return 0;
+ return 0;
return tmp;
}
diff --git a/lib/strnumcmp.c b/lib/strnumcmp.c
index 3afbfb1..6aa7bf4 100644
--- a/lib/strnumcmp.c
+++ b/lib/strnumcmp.c
@@ -1,11 +1,11 @@
/* Compare numeric strings.
- Copyright (C) 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2005-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
@@ -24,9 +23,9 @@
/* Externally-visible name for numcompare. */
-int
+int _GL_ATTRIBUTE_PURE
strnumcmp (char const *a, char const *b,
- int decimal_point, int thousands_sep)
+ int decimal_point, int thousands_sep)
{
return numcompare (a, b, decimal_point, thousands_sep);
}
diff --git a/lib/strnumcmp.h b/lib/strnumcmp.h
index 91ad351..4deef82 100644
--- a/lib/strnumcmp.h
+++ b/lib/strnumcmp.h
@@ -1,2 +1,2 @@
-int strintcmp (char const *, char const *);
+int strintcmp (char const *, char const *) _GL_ATTRIBUTE_PURE;
int strnumcmp (char const *, char const *, int, int);
diff --git a/lib/strpbrk.c b/lib/strpbrk.c
index 7843a6d..0562544 100644
--- a/lib/strpbrk.c
+++ b/lib/strpbrk.c
@@ -1,4 +1,4 @@
-/* Copyright (C) 1991, 1994, 2000, 2002-2003, 2006 Free Software
+/* Copyright (C) 1991, 1994, 2000, 2002-2003, 2006, 2009-2016 Free Software
Foundation, Inc.
NOTE: The canonical source of this file is maintained with the GNU C Library.
@@ -6,7 +6,7 @@
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 2, or (at your option) any
+ Free Software Foundation; either version 3, or (at your option) any
later version.
This program is distributed in the hope that it will be useful,
@@ -15,8 +15,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program; if not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
@@ -33,8 +32,8 @@ strpbrk (const char *s, const char *accept)
{
const char *a = accept;
while (*a != '\0')
- if (*a++ == *s)
- return (char *) s;
+ if (*a++ == *s)
+ return (char *) s;
++s;
}
diff --git a/lib/strsignal.c b/lib/strsignal.c
new file mode 100644
index 0000000..6b0d49d
--- /dev/null
+++ b/lib/strsignal.c
@@ -0,0 +1,200 @@
+/* Copyright (C) 1991, 1994-2002, 2005, 2008-2016 Free Software Foundation,
+ Inc.
+ This file is part of the GNU C Library.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _LIBC
+# include <config.h>
+#endif
+
+/* Specification. */
+#include <string.h>
+
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#ifdef _LIBC
+# include <libintl.h>
+#else /* !_LIBC */
+# include "gettext.h"
+# define _(msgid) gettext (msgid)
+# define N_(msgid) gettext_noop (msgid)
+#endif /* _LIBC */
+
+#ifdef _LIBC
+# include <bits/libc-lock.h>
+#else /* !_LIBC */
+# include "glthread/lock.h"
+# include "glthread/tls.h"
+# define __libc_once_define(CLASS, NAME) gl_once_define (CLASS, NAME)
+# define __libc_once(NAME, INIT) gl_once ((NAME), (INIT))
+# define __libc_key_t gl_tls_key_t
+# define __libc_getspecific(NAME) gl_tls_get ((NAME))
+# define __libc_setspecific(NAME, POINTER) gl_tls_set ((NAME), (POINTER))
+# define __snprintf snprintf
+#endif /* _LIBC */
+
+#ifdef _LIBC
+
+/* Defined in siglist.c. */
+extern const char *const _sys_siglist[];
+extern const char *const _sys_siglist_internal[] attribute_hidden;
+
+#else /* !_LIBC */
+
+/* NetBSD declares sys_siglist in unistd.h. */
+# if HAVE_UNISTD_H
+# include <unistd.h>
+# endif
+
+# define INTUSE(x) (x)
+
+# if HAVE_DECL_SYS_SIGLIST
+# undef _sys_siglist
+# define _sys_siglist sys_siglist
+# else /* !HAVE_DECL_SYS_SIGLIST */
+# ifndef NSIG
+# define NSIG 32
+# endif /* NSIG */
+# if !HAVE_DECL__SYS_SIGLIST
+static const char *_sys_siglist[NSIG];
+# endif
+# endif /* !HAVE_DECL_SYS_SIGLIST */
+
+#endif /* _LIBC */
+
+static __libc_key_t key;
+
+/* If nonzero the key allocation failed and we should better use a
+ static buffer than fail. */
+#define BUFFERSIZ 100
+static char local_buf[BUFFERSIZ];
+static char *static_buf;
+
+/* Destructor for the thread-specific data. */
+static void init (void);
+static void free_key_mem (void *mem);
+static char *getbuffer (void);
+
+
+/* Return a string describing the meaning of the signal number SIGNUM. */
+char *
+strsignal (int signum)
+{
+ const char *desc;
+ __libc_once_define (static, once);
+
+ /* If we have not yet initialized the buffer do it now. */
+ __libc_once (once, init);
+
+ if (
+#ifdef SIGRTMIN
+ (signum >= SIGRTMIN && signum <= SIGRTMAX) ||
+#endif
+ signum < 0 || signum >= NSIG
+ || (desc = INTUSE(_sys_siglist)[signum]) == NULL)
+ {
+ char *buffer = getbuffer ();
+ int len;
+#ifdef SIGRTMIN
+ if (signum >= SIGRTMIN && signum <= SIGRTMAX)
+ len = __snprintf (buffer, BUFFERSIZ - 1, _("Real-time signal %d"),
+ signum - (int) SIGRTMIN);
+ else
+#endif
+ len = __snprintf (buffer, BUFFERSIZ - 1, _("Unknown signal %d"),
+ signum);
+ if (len >= BUFFERSIZ)
+ buffer = NULL;
+ else
+ buffer[len] = '\0';
+
+ return buffer;
+ }
+
+ return (char *) _(desc);
+}
+
+
+/* Initialize buffer. */
+static void
+init (void)
+{
+#ifdef _LIBC
+ if (__libc_key_create (&key, free_key_mem))
+ /* Creating the key failed. This means something really went
+ wrong. In any case use a static buffer which is better than
+ nothing. */
+ static_buf = local_buf;
+#else /* !_LIBC */
+ gl_tls_key_init (key, free_key_mem);
+
+# if !HAVE_DECL_SYS_SIGLIST
+ memset (_sys_siglist, 0, NSIG * sizeof *_sys_siglist);
+
+ /* No need to use a do {} while (0) here since init_sig(...) must expand
+ to a complete statement. (We cannot use the ISO C99 designated array
+ initializer syntax since it is not supported by ANSI C compilers and
+ since some signal numbers might exceed NSIG.) */
+# define init_sig(sig, abbrev, desc) \
+ if (sig >= 0 && sig < NSIG) \
+ _sys_siglist[sig] = desc;
+
+# include "siglist.h"
+
+# undef init_sig
+
+# endif /* !HAVE_DECL_SYS_SIGLIST */
+#endif /* !_LIBC */
+}
+
+
+/* Free the thread specific data, this is done if a thread terminates. */
+static void
+free_key_mem (void *mem)
+{
+ free (mem);
+ __libc_setspecific (key, NULL);
+}
+
+
+/* Return the buffer to be used. */
+static char *
+getbuffer (void)
+{
+ char *result;
+
+ if (static_buf != NULL)
+ result = static_buf;
+ else
+ {
+ /* We don't use the static buffer and so we have a key. Use it
+ to get the thread-specific buffer. */
+ result = __libc_getspecific (key);
+ if (result == NULL)
+ {
+ /* No buffer allocated so far. */
+ result = malloc (BUFFERSIZ);
+ if (result == NULL)
+ /* No more memory available. We use the static buffer. */
+ result = local_buf;
+ else
+ __libc_setspecific (key, result);
+ }
+ }
+
+ return result;
+}
diff --git a/lib/strstr.c b/lib/strstr.c
new file mode 100644
index 0000000..60cd3e3
--- /dev/null
+++ b/lib/strstr.c
@@ -0,0 +1,82 @@
+/* Copyright (C) 1991-1994, 1996-1998, 2000, 2004, 2007-2016 Free Software
+ Foundation, Inc.
+ This file is part of the GNU C Library.
+
+ 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, 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 <http://www.gnu.org/licenses/>. */
+
+/* This particular implementation was written by Eric Blake, 2008. */
+
+#ifndef _LIBC
+# include <config.h>
+#endif
+
+/* Specification of strstr. */
+#include <string.h>
+
+#include <stdbool.h>
+
+#ifndef _LIBC
+# define __builtin_expect(expr, val) (expr)
+#endif
+
+#define RETURN_TYPE char *
+#define AVAILABLE(h, h_l, j, n_l) \
+ (!memchr ((h) + (h_l), '\0', (j) + (n_l) - (h_l)) \
+ && ((h_l) = (j) + (n_l)))
+#include "str-two-way.h"
+
+/* Return the first occurrence of NEEDLE in HAYSTACK. Return HAYSTACK
+ if NEEDLE is empty, otherwise NULL if NEEDLE is not found in
+ HAYSTACK. */
+char *
+strstr (const char *haystack_start, const char *needle_start)
+{
+ const char *haystack = haystack_start;
+ const char *needle = needle_start;
+ size_t needle_len; /* Length of NEEDLE. */
+ size_t haystack_len; /* Known minimum length of HAYSTACK. */
+ bool ok = true; /* True if NEEDLE is prefix of HAYSTACK. */
+
+ /* Determine length of NEEDLE, and in the process, make sure
+ HAYSTACK is at least as long (no point processing all of a long
+ NEEDLE if HAYSTACK is too short). */
+ while (*haystack && *needle)
+ ok &= *haystack++ == *needle++;
+ if (*needle)
+ return NULL;
+ if (ok)
+ return (char *) haystack_start;
+
+ /* Reduce the size of haystack using strchr, since it has a smaller
+ linear coefficient than the Two-Way algorithm. */
+ needle_len = needle - needle_start;
+ haystack = strchr (haystack_start + 1, *needle_start);
+ if (!haystack || __builtin_expect (needle_len == 1, 0))
+ return (char *) haystack;
+ needle -= needle_len;
+ haystack_len = (haystack > haystack_start + needle_len ? 1
+ : needle_len + haystack_start - haystack);
+
+ /* Perform the search. Abstract memory is considered to be an array
+ of 'unsigned char' values, not an array of 'char' values. See
+ ISO C 99 section 6.2.6.1. */
+ if (needle_len < LONG_NEEDLE_THRESHOLD)
+ return two_way_short_needle ((const unsigned char *) haystack,
+ haystack_len,
+ (const unsigned char *) needle, needle_len);
+ return two_way_long_needle ((const unsigned char *) haystack, haystack_len,
+ (const unsigned char *) needle, needle_len);
+}
+
+#undef LONG_NEEDLE_THRESHOLD
diff --git a/lib/strtod.c b/lib/strtod.c
index fdfc09f..2db7c73 100644
--- a/lib/strtod.c
+++ b/lib/strtod.c
@@ -1,9 +1,10 @@
-/* Copyright (C) 1991, 1992, 1997, 1999, 2003, 2006 Free Software Foundation, Inc.
+/* Copyright (C) 1991-1992, 1997, 1999, 2003, 2006, 2008-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -11,164 +12,340 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
-#include <errno.h>
+#include <stdlib.h>
#include <ctype.h>
-
-#include <math.h>
-
+#include <errno.h>
#include <float.h>
-#include <stdlib.h>
+#include <limits.h>
+#include <math.h>
+#include <stdbool.h>
#include <string.h>
+#include "c-ctype.h"
+
+#ifndef HAVE_LDEXP_IN_LIBC
+#define HAVE_LDEXP_IN_LIBC 0
+#endif
+
+/* Return true if C is a space in the current locale, avoiding
+ problems with signed char and isspace. */
+static bool
+locale_isspace (char c)
+{
+ unsigned char uc = c;
+ return isspace (uc) != 0;
+}
+
+#if !HAVE_LDEXP_IN_LIBC
+ #define ldexp dummy_ldexp
+ /* A dummy definition that will never be invoked. */
+ static double ldexp (double x _GL_UNUSED, int exponent _GL_UNUSED)
+ {
+ abort ();
+ return 0.0;
+ }
+#endif
+
+/* Return X * BASE**EXPONENT. Return an extreme value and set errno
+ to ERANGE if underflow or overflow occurs. */
+static double
+scale_radix_exp (double x, int radix, long int exponent)
+{
+ /* If RADIX == 10, this code is neither precise nor fast; it is
+ merely a straightforward and relatively portable approximation.
+ If N == 2, this code is precise on a radix-2 implementation,
+ albeit perhaps not fast if ldexp is not in libc. */
+
+ long int e = exponent;
+
+ if (HAVE_LDEXP_IN_LIBC && radix == 2)
+ return ldexp (x, e < INT_MIN ? INT_MIN : INT_MAX < e ? INT_MAX : e);
+ else
+ {
+ double r = x;
+
+ if (r != 0)
+ {
+ if (e < 0)
+ {
+ while (e++ != 0)
+ {
+ r /= radix;
+ if (r == 0 && x != 0)
+ {
+ errno = ERANGE;
+ break;
+ }
+ }
+ }
+ else
+ {
+ while (e-- != 0)
+ {
+ if (r < -DBL_MAX / radix)
+ {
+ errno = ERANGE;
+ return -HUGE_VAL;
+ }
+ else if (DBL_MAX / radix < r)
+ {
+ errno = ERANGE;
+ return HUGE_VAL;
+ }
+ else
+ r *= radix;
+ }
+ }
+ }
+
+ return r;
+ }
+}
+
+/* Parse a number at NPTR; this is a bit like strtol (NPTR, ENDPTR)
+ except there are no leading spaces or signs or "0x", and ENDPTR is
+ nonnull. The number uses a base BASE (either 10 or 16) fraction, a
+ radix RADIX (either 10 or 2) exponent, and exponent character
+ EXPCHAR. To convert from a number of digits to a radix exponent,
+ multiply by RADIX_MULTIPLIER (either 1 or 4). */
+static double
+parse_number (const char *nptr,
+ int base, int radix, int radix_multiplier, char expchar,
+ char **endptr)
+{
+ const char *s = nptr;
+ bool got_dot = false;
+ long int exponent = 0;
+ double num = 0;
+
+ for (;; ++s)
+ {
+ int digit;
+ if (c_isdigit (*s))
+ digit = *s - '0';
+ else if (base == 16 && c_isxdigit (*s))
+ digit = c_tolower (*s) - ('a' - 10);
+ else if (! got_dot && *s == '.')
+ {
+ /* Record that we have found the decimal point. */
+ got_dot = true;
+ continue;
+ }
+ else
+ /* Any other character terminates the number. */
+ break;
+
+ /* Make sure that multiplication by base will not overflow. */
+ if (num <= DBL_MAX / base)
+ num = num * base + digit;
+ else
+ {
+ /* The value of the digit doesn't matter, since we have already
+ gotten as many digits as can be represented in a 'double'.
+ This doesn't necessarily mean the result will overflow.
+ The exponent may reduce it to within range.
+
+ We just need to record that there was another
+ digit so that we can multiply by 10 later. */
+ exponent += radix_multiplier;
+ }
+
+ /* Keep track of the number of digits after the decimal point.
+ If we just divided by base here, we might lose precision. */
+ if (got_dot)
+ exponent -= radix_multiplier;
+ }
+
+ if (c_tolower (*s) == expchar && ! locale_isspace (s[1]))
+ {
+ /* Add any given exponent to the implicit one. */
+ int save = errno;
+ char *end;
+ long int value = strtol (s + 1, &end, 10);
+ errno = save;
+
+ if (s + 1 != end)
+ {
+ /* Skip past the exponent, and add in the implicit exponent,
+ resulting in an extreme value on overflow. */
+ s = end;
+ exponent =
+ (exponent < 0
+ ? (value < LONG_MIN - exponent ? LONG_MIN : exponent + value)
+ : (LONG_MAX - exponent < value ? LONG_MAX : exponent + value));
+ }
+ }
+
+ *endptr = (char *) s;
+ return scale_radix_exp (num, radix, exponent);
+}
+
+static double underlying_strtod (const char *, char **);
+
+/* HP cc on HP-UX 10.20 has a bug with the constant expression -0.0.
+ ICC 10.0 has a bug when optimizing the expression -zero.
+ The expression -DBL_MIN * DBL_MIN does not work when cross-compiling
+ to PowerPC on Mac OS X 10.5. */
+#if defined __hpux || defined __sgi || defined __ICC
+static double
+compute_minus_zero (void)
+{
+ return -DBL_MIN * DBL_MIN;
+}
+# define minus_zero compute_minus_zero ()
+#else
+double minus_zero = -0.0;
+#endif
+
/* Convert NPTR to a double. If ENDPTR is not NULL, a pointer to the
character after the last one used in the number is put in *ENDPTR. */
double
strtod (const char *nptr, char **endptr)
{
- register const char *s;
- short int sign;
+ bool negative = false;
/* The number so far. */
double num;
- int got_dot; /* Found a decimal point. */
- int got_digit; /* Seen any digits. */
-
- /* The exponent of the number. */
- long int exponent;
-
- if (nptr == NULL)
- {
- errno = EINVAL;
- goto noconv;
- }
-
- s = nptr;
+ const char *s = nptr;
+ const char *end;
+ char *endbuf;
+ int saved_errno;
/* Eat whitespace. */
- while (isspace ((unsigned char) *s))
+ while (locale_isspace (*s))
++s;
/* Get the sign. */
- sign = *s == '-' ? -1 : 1;
+ negative = *s == '-';
if (*s == '-' || *s == '+')
++s;
- num = 0.0;
- got_dot = 0;
- got_digit = 0;
- exponent = 0;
- for (;; ++s)
+ saved_errno = errno;
+ num = underlying_strtod (s, &endbuf);
+ end = endbuf;
+
+ if (c_isdigit (s[*s == '.']))
{
- if ('0' <= *s && *s <= '9')
- {
- got_digit = 1;
-
- /* Make sure that multiplication by 10 will not overflow. */
- if (num > DBL_MAX * 0.1)
- /* The value of the digit doesn't matter, since we have already
- gotten as many digits as can be represented in a `double'.
- This doesn't necessarily mean the result will overflow.
- The exponent may reduce it to within range.
-
- We just need to record that there was another
- digit so that we can multiply by 10 later. */
- ++exponent;
- else
- num = (num * 10.0) + (*s - '0');
-
- /* Keep track of the number of digits after the decimal point.
- If we just divided by 10 here, we would lose precision. */
- if (got_dot)
- --exponent;
- }
- else if (!got_dot && *s == '.')
- /* Record that we have found the decimal point. */
- got_dot = 1;
+ /* If a hex float was converted incorrectly, do it ourselves.
+ If the string starts with "0x" but does not contain digits,
+ consume the "0" ourselves. If a hex float is followed by a
+ 'p' but no exponent, then adjust the end pointer. */
+ if (*s == '0' && c_tolower (s[1]) == 'x')
+ {
+ if (! c_isxdigit (s[2 + (s[2] == '.')]))
+ end = s + 1;
+ else if (end <= s + 2)
+ {
+ num = parse_number (s + 2, 16, 2, 4, 'p', &endbuf);
+ end = endbuf;
+ }
+ else
+ {
+ const char *p = s + 2;
+ while (p < end && c_tolower (*p) != 'p')
+ p++;
+ if (p < end && ! c_isdigit (p[1 + (p[1] == '-' || p[1] == '+')]))
+ end = p;
+ }
+ }
else
- /* Any other character terminates the number. */
- break;
- }
-
- if (!got_digit)
- goto noconv;
+ {
+ /* If "1e 1" was misparsed as 10.0 instead of 1.0, re-do the
+ underlying strtod on a copy of the original string
+ truncated to avoid the bug. */
+ const char *e = s + 1;
+ while (e < end && c_tolower (*e) != 'e')
+ e++;
+ if (e < end && ! c_isdigit (e[1 + (e[1] == '-' || e[1] == '+')]))
+ {
+ char *dup = strdup (s);
+ errno = saved_errno;
+ if (!dup)
+ {
+ /* Not really our day, is it. Rounding errors are
+ better than outright failure. */
+ num = parse_number (s, 10, 10, 1, 'e', &endbuf);
+ }
+ else
+ {
+ dup[e - s] = '\0';
+ num = underlying_strtod (dup, &endbuf);
+ saved_errno = errno;
+ free (dup);
+ errno = saved_errno;
+ }
+ end = e;
+ }
+ }
- if (tolower ((unsigned char) *s) == 'e')
- {
- /* Get the exponent specified after the `e' or `E'. */
- int save = errno;
- char *end;
- long int exp;
-
- errno = 0;
- ++s;
- exp = strtol (s, &end, 10);
- if (errno == ERANGE)
- {
- /* The exponent overflowed a `long int'. It is probably a safe
- assumption that an exponent that cannot be represented by
- a `long int' exceeds the limits of a `double'. */
- if (endptr != NULL)
- *endptr = end;
- if (exp < 0)
- goto underflow;
- else
- goto overflow;
- }
- else if (end == s)
- /* There was no exponent. Reset END to point to
- the 'e' or 'E', so *ENDPTR will be set there. */
- end = (char *) s - 1;
- errno = save;
s = end;
- exponent += exp;
}
- if (endptr != NULL)
- *endptr = (char *) s;
-
- if (num == 0.0)
- return 0.0;
-
- /* Multiply NUM by 10 to the EXPONENT power,
- checking for overflow and underflow. */
-
- if (exponent < 0)
+ /* Check for infinities and NaNs. */
+ else if (c_tolower (*s) == 'i'
+ && c_tolower (s[1]) == 'n'
+ && c_tolower (s[2]) == 'f')
{
- if (num < DBL_MIN * pow (10.0, (double) -exponent))
- goto underflow;
+ s += 3;
+ if (c_tolower (*s) == 'i'
+ && c_tolower (s[1]) == 'n'
+ && c_tolower (s[2]) == 'i'
+ && c_tolower (s[3]) == 't'
+ && c_tolower (s[4]) == 'y')
+ s += 5;
+ num = HUGE_VAL;
+ errno = saved_errno;
}
- else if (exponent > 0)
+ else if (c_tolower (*s) == 'n'
+ && c_tolower (s[1]) == 'a'
+ && c_tolower (s[2]) == 'n')
{
- if (num > DBL_MAX * pow (10.0, (double) -exponent))
- goto overflow;
+ s += 3;
+ if (*s == '(')
+ {
+ const char *p = s + 1;
+ while (c_isalnum (*p))
+ p++;
+ if (*p == ')')
+ s = p + 1;
+ }
+
+ /* If the underlying implementation misparsed the NaN, assume
+ its result is incorrect, and return a NaN. Normally it's
+ better to use the underlying implementation's result, since a
+ nice implementation populates the bits of the NaN according
+ to interpreting n-char-sequence as a hexadecimal number. */
+ if (s != end)
+ num = NAN;
+ errno = saved_errno;
+ }
+ else
+ {
+ /* No conversion could be performed. */
+ errno = EINVAL;
+ s = nptr;
}
- num *= pow (10.0, (double) exponent);
-
- return num * sign;
-
-overflow:
- /* Return an overflow error. */
- errno = ERANGE;
- return HUGE_VAL * sign;
-
-underflow:
- /* Return an underflow error. */
if (endptr != NULL)
- *endptr = (char *) nptr;
- errno = ERANGE;
- return 0.0;
+ *endptr = (char *) s;
+ /* Special case -0.0, since at least ICC miscompiles negation. We
+ can't use copysign(), as that drags in -lm on some platforms. */
+ if (!num && negative)
+ return minus_zero;
+ return negative ? -num : num;
+}
-noconv:
- /* There was no number. */
- if (endptr != NULL)
- *endptr = (char *) nptr;
- return 0.0;
+/* The underlying strtod implementation. This must be defined
+ after strtod because it #undefs strtod. */
+static double
+underlying_strtod (const char *nptr, char **endptr)
+{
+#undef strtod
+ return strtod (nptr, endptr);
}
diff --git a/lib/strtoimax.c b/lib/strtoimax.c
index 82dc4f0..223412b 100644
--- a/lib/strtoimax.c
+++ b/lib/strtoimax.c
@@ -1,12 +1,12 @@
/* Convert string representation of a number into an intmax_t value.
- Copyright (C) 1999, 2001, 2002, 2003, 2004, 2006 Free Software
- Foundation, Inc.
+ Copyright (C) 1999, 2001-2004, 2006, 2009-2016 Free Software Foundation,
+ Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
@@ -29,48 +28,55 @@
#include "verify.h"
#ifdef UNSIGNED
-# ifndef HAVE_DECL_STRTOULL
+# if HAVE_UNSIGNED_LONG_LONG_INT
+# ifndef HAVE_DECL_STRTOULL
"this configure-time declaration test was not run"
-# endif
-# if !HAVE_DECL_STRTOULL && HAVE_UNSIGNED_LONG_LONG_INT
+# endif
+# if !HAVE_DECL_STRTOULL
unsigned long long int strtoull (char const *, char **, int);
+# endif
# endif
#else
-# ifndef HAVE_DECL_STRTOLL
+# if HAVE_LONG_LONG_INT
+# ifndef HAVE_DECL_STRTOLL
"this configure-time declaration test was not run"
-# endif
-# if !HAVE_DECL_STRTOLL && HAVE_LONG_LONG_INT
+# endif
+# if !HAVE_DECL_STRTOLL
long long int strtoll (char const *, char **, int);
+# endif
# endif
#endif
#ifdef UNSIGNED
# define Have_long_long HAVE_UNSIGNED_LONG_LONG_INT
# define Int uintmax_t
+# define Strtoimax strtoumax
+# define Strtol strtoul
+# define Strtoll strtoull
# define Unsigned unsigned
-# define strtoimax strtoumax
-# define strtol strtoul
-# define strtoll strtoull
#else
# define Have_long_long HAVE_LONG_LONG_INT
# define Int intmax_t
+# define Strtoimax strtoimax
+# define Strtol strtol
+# define Strtoll strtoll
# define Unsigned
#endif
Int
-strtoimax (char const *ptr, char **endptr, int base)
+Strtoimax (char const *ptr, char **endptr, int base)
{
#if Have_long_long
verify (sizeof (Int) == sizeof (Unsigned long int)
- || sizeof (Int) == sizeof (Unsigned long long int));
+ || sizeof (Int) == sizeof (Unsigned long long int));
if (sizeof (Int) != sizeof (Unsigned long int))
- return strtoll (ptr, endptr, base);
+ return Strtoll (ptr, endptr, base);
#else
verify (sizeof (Int) == sizeof (Unsigned long int));
#endif
- return strtol (ptr, endptr, base);
+ return Strtol (ptr, endptr, base);
}
diff --git a/lib/strtol.c b/lib/strtol.c
index e14d3cf..b0215fc 100644
--- a/lib/strtol.c
+++ b/lib/strtol.c
@@ -1,15 +1,14 @@
/* Convert string representation of a number into an integer value.
- Copyright (C) 1991, 1992, 1994, 1995, 1996, 1997, 1998, 1999, 2003, 2005,
- 2006, 2007
- Free Software Foundation, Inc.
+ Copyright (C) 1991-1992, 1994-1999, 2003, 2005-2007, 2009-2016 Free Software
+ Foundation, Inc.
NOTE: The canonical source of this file is maintained with the GNU C
Library. Bugs can be reported to bug-glibc@gnu.org.
- This program is free software; you can redistribute it and/or modify it
+ 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 2, or (at your option) any
+ Free Software Foundation; either version 3 of the License, or any
later version.
This program is distributed in the hope that it will be useful,
@@ -18,8 +17,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifdef _LIBC
# define USE_NUMBER_GROUPING
@@ -42,7 +40,7 @@
# include "../locale/localeinfo.h"
#endif
-/* Nonzero if we are defining `strtoul' or `strtoull', operating on
+/* Nonzero if we are defining 'strtoul' or 'strtoull', operating on
unsigned integers. */
#ifndef UNSIGNED
# define UNSIGNED 0
@@ -112,13 +110,13 @@
# endif
#endif
-/* If QUAD is defined, we are defining `strtoll' or `strtoull',
- operating on `long long int's. */
+/* If QUAD is defined, we are defining 'strtoll' or 'strtoull',
+ operating on 'long long int's. */
#ifdef QUAD
# define LONG long long
-# define STRTOL_LONG_MIN LONG_LONG_MIN
-# define STRTOL_LONG_MAX LONG_LONG_MAX
-# define STRTOL_ULONG_MAX ULONG_LONG_MAX
+# define STRTOL_LONG_MIN LLONG_MIN
+# define STRTOL_LONG_MAX LLONG_MAX
+# define STRTOL_ULONG_MAX ULLONG_MAX
/* The extra casts in the following macros work around compiler bugs,
e.g., in Cray C 5.0.3.0. */
@@ -140,28 +138,28 @@
your host. */
# define TYPE_MINIMUM(t) \
((t) (! TYPE_SIGNED (t) \
- ? (t) 0 \
- : TYPE_SIGNED_MAGNITUDE (t) \
- ? ~ (t) 0 \
- : ~ (t) 0 << (sizeof (t) * CHAR_BIT - 1)))
+ ? (t) 0 \
+ : TYPE_SIGNED_MAGNITUDE (t) \
+ ? ~ (t) 0 \
+ : ~ TYPE_MAXIMUM (t)))
# define TYPE_MAXIMUM(t) \
((t) (! TYPE_SIGNED (t) \
- ? (t) -1 \
- : ~ (~ (t) 0 << (sizeof (t) * CHAR_BIT - 1))))
+ ? (t) -1 \
+ : ((((t) 1 << (sizeof (t) * CHAR_BIT - 2)) - 1) * 2 + 1)))
-# ifndef ULONG_LONG_MAX
-# define ULONG_LONG_MAX TYPE_MAXIMUM (unsigned long long)
+# ifndef ULLONG_MAX
+# define ULLONG_MAX TYPE_MAXIMUM (unsigned long long)
# endif
-# ifndef LONG_LONG_MAX
-# define LONG_LONG_MAX TYPE_MAXIMUM (long long int)
+# ifndef LLONG_MAX
+# define LLONG_MAX TYPE_MAXIMUM (long long int)
# endif
-# ifndef LONG_LONG_MIN
-# define LONG_LONG_MIN TYPE_MINIMUM (long long int)
+# ifndef LLONG_MIN
+# define LLONG_MIN TYPE_MINIMUM (long long int)
# endif
# if __GNUC__ == 2 && __GNUC_MINOR__ < 7
/* Work around gcc bug with using this constant. */
- static const unsigned long long int maxquad = ULONG_LONG_MAX;
+ static const unsigned long long int maxquad = ULLONG_MAX;
# undef STRTOL_ULONG_MAX
# define STRTOL_ULONG_MAX maxquad
# endif
@@ -188,9 +186,8 @@
# define LOCALE_PARAM_PROTO
#endif
-#include <wchar.h>
-
#ifdef USE_WIDE_CHAR
+# include <wchar.h>
# include <wctype.h>
# define L_(Ch) L##Ch
# define UCHAR_TYPE wint_t
@@ -230,7 +227,7 @@
-/* Convert NPTR to an `unsigned long int' or `long int' in base BASE.
+/* Convert NPTR to an 'unsigned long int' or 'long int' in base BASE.
If BASE is 0 the base is determined by the presence of a leading
zero, indicating octal or a leading "0x" or "0X", indicating hexadecimal.
If BASE is < 2 or > 36, it is reset to 10.
@@ -239,7 +236,7 @@
INT
INTERNAL (strtol) (const STRING_TYPE *nptr, STRING_TYPE **endptr,
- int base, int group LOCALE_PARAM_PROTO)
+ int base, int group LOCALE_PARAM_PROTO)
{
int negative;
register unsigned LONG int cutoff;
@@ -264,18 +261,18 @@ INTERNAL (strtol) (const STRING_TYPE *nptr, STRING_TYPE **endptr,
{
grouping = _NL_CURRENT (LC_NUMERIC, GROUPING);
if (*grouping <= 0 || *grouping == CHAR_MAX)
- grouping = NULL;
+ grouping = NULL;
else
- {
- /* Figure out the thousands separator character. */
+ {
+ /* Figure out the thousands separator character. */
# if defined _LIBC || defined _HAVE_BTOWC
- thousands = __btowc (*_NL_CURRENT (LC_NUMERIC, THOUSANDS_SEP));
- if (thousands == WEOF)
- thousands = L'\0';
+ thousands = __btowc (*_NL_CURRENT (LC_NUMERIC, THOUSANDS_SEP));
+ if (thousands == WEOF)
+ thousands = L'\0';
# endif
- if (thousands == L'\0')
- grouping = NULL;
- }
+ if (thousands == L'\0')
+ grouping = NULL;
+ }
}
else
grouping = NULL;
@@ -313,12 +310,12 @@ INTERNAL (strtol) (const STRING_TYPE *nptr, STRING_TYPE **endptr,
if (*s == L_('0'))
{
if ((base == 0 || base == 16) && TOUPPER (s[1]) == L_('X'))
- {
- s += 2;
- base = 16;
- }
+ {
+ s += 2;
+ base = 16;
+ }
else if (base == 0)
- base = 8;
+ base = 8;
}
else if (base == 0)
base = 10;
@@ -332,14 +329,14 @@ INTERNAL (strtol) (const STRING_TYPE *nptr, STRING_TYPE **endptr,
/* Find the end of the digit string and check its grouping. */
end = s;
for (c = *end; c != L_('\0'); c = *++end)
- if ((wchar_t) c != thousands
- && ((wchar_t) c < L_('0') || (wchar_t) c > L_('9'))
- && (!ISALPHA (c) || (int) (TOUPPER (c) - L_('A') + 10) >= base))
- break;
+ if ((wchar_t) c != thousands
+ && ((wchar_t) c < L_('0') || (wchar_t) c > L_('9'))
+ && (!ISALPHA (c) || (int) (TOUPPER (c) - L_('A') + 10) >= base))
+ break;
if (*s == thousands)
- end = s;
+ end = s;
else
- end = correctly_grouped_prefix (s, end, thousands, grouping);
+ end = correctly_grouped_prefix (s, end, thousands, grouping);
}
else
#endif
@@ -353,23 +350,23 @@ INTERNAL (strtol) (const STRING_TYPE *nptr, STRING_TYPE **endptr,
for (c = *s; c != L_('\0'); c = *++s)
{
if (s == end)
- break;
+ break;
if (c >= L_('0') && c <= L_('9'))
- c -= L_('0');
+ c -= L_('0');
else if (ISALPHA (c))
- c = TOUPPER (c) - L_('A') + 10;
+ c = TOUPPER (c) - L_('A') + 10;
else
- break;
+ break;
if ((int) c >= base)
- break;
+ break;
/* Check for overflow. */
if (i > cutoff || (i == cutoff && c > cutlim))
- overflow = 1;
+ overflow = 1;
else
- {
- i *= (unsigned LONG int) base;
- i += c;
- }
+ {
+ i *= (unsigned LONG int) base;
+ i += c;
+ }
}
/* Check if anything actually happened. */
@@ -383,11 +380,11 @@ INTERNAL (strtol) (const STRING_TYPE *nptr, STRING_TYPE **endptr,
#if !UNSIGNED
/* Check for a value that is within the range of
- `unsigned LONG int', but outside the range of `LONG int'. */
+ 'unsigned LONG int', but outside the range of 'LONG int'. */
if (overflow == 0
&& i > (negative
- ? -((unsigned LONG int) (STRTOL_LONG_MIN + 1)) + 1
- : (unsigned LONG int) STRTOL_LONG_MAX))
+ ? -((unsigned LONG int) (STRTOL_LONG_MIN + 1)) + 1
+ : (unsigned LONG int) STRTOL_LONG_MAX))
overflow = 1;
#endif
@@ -408,15 +405,15 @@ noconv:
/* We must handle a special case here: the base is 0 or 16 and the
first two characters are '0' and 'x', but the rest are no
hexadecimal digits. This is no error case. We return 0 and
- ENDPTR points to the `x`. */
+ ENDPTR points to the 'x'. */
if (endptr != NULL)
{
if (save - nptr >= 2 && TOUPPER (save[-1]) == L_('X')
- && save[-2] == L_('0'))
- *endptr = (STRING_TYPE *) &save[-1];
+ && save[-2] == L_('0'))
+ *endptr = (STRING_TYPE *) &save[-1];
else
- /* There was no number to convert. */
- *endptr = (STRING_TYPE *) nptr;
+ /* There was no number to convert. */
+ *endptr = (STRING_TYPE *) nptr;
}
return 0L;
@@ -430,7 +427,7 @@ INT
weak_function
#endif
strtol (const STRING_TYPE *nptr, STRING_TYPE **endptr,
- int base LOCALE_PARAM_PROTO)
+ int base LOCALE_PARAM_PROTO)
{
return INTERNAL (strtol) (nptr, endptr, base, 0 LOCALE_PARAM);
}
diff --git a/lib/strtoll.c b/lib/strtoll.c
index f61f5ad..d0f7b62 100644
--- a/lib/strtoll.c
+++ b/lib/strtoll.c
@@ -1,22 +1,22 @@
-/* Function to parse a `long long int' from text.
- Copyright (C) 1995, 1996, 1997, 1999, 2001 Free Software Foundation, Inc.
+/* Function to parse a 'long long int' from text.
+ Copyright (C) 1995-1997, 1999, 2001, 2009-2016 Free Software Foundation,
+ Inc.
This file is part of the GNU C Library.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
-#define QUAD 1
+#define QUAD 1
#include <strtol.c>
diff --git a/lib/strtoul.c b/lib/strtoul.c
index 79ceed2..6a5d4dd 100644
--- a/lib/strtoul.c
+++ b/lib/strtoul.c
@@ -1,20 +1,19 @@
-/* Copyright (C) 1991, 1997 Free Software Foundation, Inc.
+/* Copyright (C) 1991, 1997, 2009-2016 Free Software Foundation, Inc.
This file is part of the GNU C Library.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
-#define UNSIGNED 1
+#define UNSIGNED 1
#include "strtol.c"
diff --git a/lib/strtoull.c b/lib/strtoull.c
index 6186bfb..16da823 100644
--- a/lib/strtoull.c
+++ b/lib/strtoull.c
@@ -1,11 +1,11 @@
-/* Function to parse an `unsigned long long int' from text.
- Copyright (C) 1995, 1996, 1997, 1999 Free Software Foundation, Inc.
+/* Function to parse an 'unsigned long long int' from text.
+ Copyright (C) 1995-1997, 1999, 2009-2016 Free Software Foundation, Inc.
NOTE: The canonical source of this file is maintained with the GNU C
Library. Bugs can be reported to bug-glibc@gnu.org.
- This program is free software; you can redistribute it and/or modify it
+ 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 2, or (at your option) any
+ Free Software Foundation; either version 3 of the License, or any
later version.
This program is distributed in the hope that it will be useful,
@@ -14,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#define QUAD 1
diff --git a/lib/strverscmp.c b/lib/strverscmp.c
deleted file mode 100644
index f077651..0000000
--- a/lib/strverscmp.c
+++ /dev/null
@@ -1,131 +0,0 @@
-/* Compare strings while treating digits characters numerically.
- Copyright (C) 1997, 2000, 2002, 2004, 2006 Free Software Foundation, Inc.
- This file is part of the GNU C Library.
- Contributed by Jean-François Bignolles <bignolle@ecoledoc.ibp.fr>, 1997.
-
- 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-#if !_LIBC
-# include <config.h>
-#endif
-
-#include <string.h>
-#include <ctype.h>
-
-/* states: S_N: normal, S_I: comparing integral part, S_F: comparing
- fractional parts, S_Z: idem but with leading Zeroes only */
-#define S_N 0x0
-#define S_I 0x4
-#define S_F 0x8
-#define S_Z 0xC
-
-/* result_type: CMP: return diff; LEN: compare using len_diff/diff */
-#define CMP 2
-#define LEN 3
-
-
-/* ISDIGIT differs from isdigit, as follows:
- - Its arg may be any int or unsigned int; it need not be an unsigned char
- or EOF.
- - It's typically faster.
- POSIX says that only '0' through '9' are digits. Prefer ISDIGIT to
- isdigit unless it's important to use the locale's definition
- of `digit' even when the host does not conform to POSIX. */
-#define ISDIGIT(c) ((unsigned int) (c) - '0' <= 9)
-
-#undef __strverscmp
-#undef strverscmp
-
-#ifndef weak_alias
-# define __strverscmp strverscmp
-#endif
-
-/* Compare S1 and S2 as strings holding indices/version numbers,
- returning less than, equal to or greater than zero if S1 is less than,
- equal to or greater than S2 (for more info, see the texinfo doc).
-*/
-
-int
-__strverscmp (const char *s1, const char *s2)
-{
- const unsigned char *p1 = (const unsigned char *) s1;
- const unsigned char *p2 = (const unsigned char *) s2;
- unsigned char c1, c2;
- int state;
- int diff;
-
- /* Symbol(s) 0 [1-9] others (padding)
- Transition (10) 0 (01) d (00) x (11) - */
- static const unsigned int next_state[] =
- {
- /* state x d 0 - */
- /* S_N */ S_N, S_I, S_Z, S_N,
- /* S_I */ S_N, S_I, S_I, S_I,
- /* S_F */ S_N, S_F, S_F, S_F,
- /* S_Z */ S_N, S_F, S_Z, S_Z
- };
-
- static const int result_type[] =
- {
- /* state x/x x/d x/0 x/- d/x d/d d/0 d/-
- 0/x 0/d 0/0 0/- -/x -/d -/0 -/- */
-
- /* S_N */ CMP, CMP, CMP, CMP, CMP, LEN, CMP, CMP,
- CMP, CMP, CMP, CMP, CMP, CMP, CMP, CMP,
- /* S_I */ CMP, -1, -1, CMP, 1, LEN, LEN, CMP,
- 1, LEN, LEN, CMP, CMP, CMP, CMP, CMP,
- /* S_F */ CMP, CMP, CMP, CMP, CMP, LEN, CMP, CMP,
- CMP, CMP, CMP, CMP, CMP, CMP, CMP, CMP,
- /* S_Z */ CMP, 1, 1, CMP, -1, CMP, CMP, CMP,
- -1, CMP, CMP, CMP
- };
-
- if (p1 == p2)
- return 0;
-
- c1 = *p1++;
- c2 = *p2++;
- /* Hint: '0' is a digit too. */
- state = S_N | ((c1 == '0') + (ISDIGIT (c1) != 0));
-
- while ((diff = c1 - c2) == 0 && c1 != '\0')
- {
- state = next_state[state];
- c1 = *p1++;
- c2 = *p2++;
- state |= (c1 == '0') + (ISDIGIT (c1) != 0);
- }
-
- state = result_type[state << 2 | ((c2 == '0') + (ISDIGIT (c2) != 0))];
-
- switch (state)
- {
- case CMP:
- return diff;
-
- case LEN:
- while (ISDIGIT (*p1++))
- if (!ISDIGIT (*p2++))
- return 1;
-
- return ISDIGIT (*p2) ? -1 : diff;
-
- default:
- return state;
- }
-}
-#ifdef weak_alias
-weak_alias (__strverscmp, strverscmp)
-#endif
diff --git a/lib/strverscmp.h b/lib/strverscmp.h
deleted file mode 100644
index 7edeac5..0000000
--- a/lib/strverscmp.h
+++ /dev/null
@@ -1,24 +0,0 @@
-/* Compare strings while treating digits characters numerically.
-
- Copyright (C) 1997, 2003 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-#ifndef STRVERSCMP_H_
-# define STRVERSCMP_H_
-
-int strverscmp (const char *, const char *);
-
-#endif /* not STRVERSCMP_H_ */
diff --git a/lib/symlink.c b/lib/symlink.c
new file mode 100644
index 0000000..d8684b6
--- /dev/null
+++ b/lib/symlink.c
@@ -0,0 +1,57 @@
+/* Stub for symlink().
+ Copyright (C) 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <unistd.h>
+
+#include <errno.h>
+#include <string.h>
+#include <sys/stat.h>
+
+
+#if HAVE_SYMLINK
+
+# undef symlink
+
+/* Create a symlink, but reject trailing slash. */
+int
+rpl_symlink (char const *contents, char const *name)
+{
+ size_t len = strlen (name);
+ if (len && name[len - 1] == '/')
+ {
+ struct stat st;
+ if (lstat (name, &st) == 0)
+ errno = EEXIST;
+ return -1;
+ }
+ return symlink (contents, name);
+}
+
+#else /* !HAVE_SYMLINK */
+
+/* The system does not support symlinks. */
+int
+symlink (char const *contents _GL_UNUSED,
+ char const *name _GL_UNUSED)
+{
+ errno = ENOSYS;
+ return -1;
+}
+
+#endif /* !HAVE_SYMLINK */
diff --git a/lib/sys_ioctl.in.h b/lib/sys_ioctl.in.h
new file mode 100644
index 0000000..a07dc97
--- /dev/null
+++ b/lib/sys_ioctl.in.h
@@ -0,0 +1,78 @@
+/* Substitute for and wrapper around <sys/ioctl.h>.
+ Copyright (C) 2008-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _@GUARD_PREFIX@_SYS_IOCTL_H
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+/* The include_next requires a split double-inclusion guard. */
+#if @HAVE_SYS_IOCTL_H@
+# @INCLUDE_NEXT@ @NEXT_SYS_IOCTL_H@
+#endif
+
+#ifndef _@GUARD_PREFIX@_SYS_IOCTL_H
+#define _@GUARD_PREFIX@_SYS_IOCTL_H
+
+/* AIX 5.1 and Solaris 10 declare ioctl() in <unistd.h> and in <stropts.h>,
+ but not in <sys/ioctl.h>.
+ But avoid namespace pollution on glibc systems. */
+#ifndef __GLIBC__
+# include <unistd.h>
+#endif
+
+/* The definitions of _GL_FUNCDECL_RPL etc. are copied here. */
+
+/* The definition of _GL_WARN_ON_USE is copied here. */
+
+
+/* Declare overridden functions. */
+
+#if @GNULIB_IOCTL@
+# if @REPLACE_IOCTL@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef ioctl
+# define ioctl rpl_ioctl
+# endif
+_GL_FUNCDECL_RPL (ioctl, int,
+ (int fd, int request, ... /* {void *,char *} arg */));
+_GL_CXXALIAS_RPL (ioctl, int,
+ (int fd, int request, ... /* {void *,char *} arg */));
+# else
+# if @SYS_IOCTL_H_HAVE_WINSOCK2_H@ || 1
+_GL_FUNCDECL_SYS (ioctl, int,
+ (int fd, int request, ... /* {void *,char *} arg */));
+# endif
+_GL_CXXALIAS_SYS (ioctl, int,
+ (int fd, int request, ... /* {void *,char *} arg */));
+# endif
+_GL_CXXALIASWARN (ioctl);
+#elif @SYS_IOCTL_H_HAVE_WINSOCK2_H_AND_USE_SOCKETS@
+# undef ioctl
+# define ioctl ioctl_used_without_requesting_gnulib_module_ioctl
+#elif defined GNULIB_POSIXCHECK
+# undef ioctl
+# if HAVE_RAW_DECL_IOCTL
+_GL_WARN_ON_USE (ioctl, "ioctl does not portably work on sockets - "
+ "use gnulib module ioctl for portability");
+# endif
+#endif
+
+
+#endif /* _@GUARD_PREFIX@_SYS_IOCTL_H */
+#endif /* _@GUARD_PREFIX@_SYS_IOCTL_H */
diff --git a/lib/sys_resource.in.h b/lib/sys_resource.in.h
new file mode 100644
index 0000000..7a4c2f4
--- /dev/null
+++ b/lib/sys_resource.in.h
@@ -0,0 +1,111 @@
+/* Substitute for <sys/resource.h>.
+ Copyright (C) 2012-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+# if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+# endif
+@PRAGMA_COLUMNS@
+
+#ifndef _@GUARD_PREFIX@_SYS_RESOURCE_H
+
+#if @HAVE_SYS_RESOURCE_H@
+
+/* On FreeBSD 5.0, <sys/resource.h> assumes prior inclusion of <sys/types.h>
+ and <sys/time.h>. */
+# include <sys/types.h>
+# include <sys/time.h>
+
+/* The include_next requires a split double-inclusion guard. */
+# @INCLUDE_NEXT@ @NEXT_SYS_RESOURCE_H@
+
+#endif
+
+#ifndef _@GUARD_PREFIX@_SYS_RESOURCE_H
+#define _@GUARD_PREFIX@_SYS_RESOURCE_H
+
+#if !@HAVE_SYS_RESOURCE_H@
+/* A platform that lacks <sys/resource.h>. */
+
+/* Get 'struct timeval'. */
+# include <sys/time.h>
+
+/* Define the RUSAGE_* constants. */
+# define RUSAGE_SELF 0
+# define RUSAGE_CHILDREN -1
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# if !GNULIB_defined_struct_rusage
+/* All known platforms that lack <sys/resource.h> also lack any declaration
+ of struct rusage in any other header. */
+struct rusage
+{
+ struct timeval ru_utime; /* CPU time used in user mode */
+ struct timeval ru_stime; /* CPU time used in system mode (kernel) */
+ long ru_maxrss;
+ long ru_ixrss;
+ long ru_idrss;
+ long ru_isrss;
+ long ru_minflt;
+ long ru_majflt;
+ long ru_nswap;
+ long ru_inblock;
+ long ru_oublock;
+ long ru_msgsnd;
+ long ru_msgrcv;
+ long ru_nsignals;
+ long ru_nvcsw;
+ long ru_nivcsw;
+};
+# define GNULIB_defined_struct_rusage 1
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+
+#endif
+
+/* The definitions of _GL_FUNCDECL_RPL etc. are copied here. */
+
+/* The definition of _GL_ARG_NONNULL is copied here. */
+
+/* The definition of _GL_WARN_ON_USE is copied here. */
+
+
+/* Declare overridden functions. */
+
+
+#if @GNULIB_GETRUSAGE@
+# if !@HAVE_GETRUSAGE@
+_GL_FUNCDECL_SYS (getrusage, int, (int who, struct rusage *usage_p)
+ _GL_ARG_NONNULL ((2)));
+# endif
+_GL_CXXALIAS_SYS (getrusage, int, (int who, struct rusage *usage_p));
+_GL_CXXALIASWARN (getrusage);
+#elif defined GNULIB_POSIXCHECK
+# undef getrusage
+# if HAVE_RAW_DECL_GETRUSAGE
+_GL_WARN_ON_USE (getrusage, "getrusage is unportable - "
+ "use gnulib module getrusage for portability");
+# endif
+#endif
+
+
+#endif /* _@GUARD_PREFIX@_SYS_RESOURCE_H */
+#endif /* _@GUARD_PREFIX@_SYS_RESOURCE_H */
diff --git a/lib/sys_select.in.h b/lib/sys_select.in.h
new file mode 100644
index 0000000..f7b260d
--- /dev/null
+++ b/lib/sys_select.in.h
@@ -0,0 +1,314 @@
+/* Substitute for <sys/select.h>.
+ Copyright (C) 2007-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+# if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+# endif
+@PRAGMA_COLUMNS@
+
+/* On OSF/1 and Solaris 2.6, <sys/types.h> and <sys/time.h>
+ both include <sys/select.h>.
+ On Cygwin, <sys/time.h> includes <sys/select.h>.
+ Simply delegate to the system's header in this case. */
+#if (@HAVE_SYS_SELECT_H@ \
+ && !defined _GL_SYS_SELECT_H_REDIRECT_FROM_SYS_TYPES_H \
+ && ((defined __osf__ && defined _SYS_TYPES_H_ \
+ && defined _OSF_SOURCE) \
+ || (defined __sun && defined _SYS_TYPES_H \
+ && (! (defined _XOPEN_SOURCE || defined _POSIX_C_SOURCE) \
+ || defined __EXTENSIONS__))))
+
+# define _GL_SYS_SELECT_H_REDIRECT_FROM_SYS_TYPES_H
+# @INCLUDE_NEXT@ @NEXT_SYS_SELECT_H@
+
+#elif (@HAVE_SYS_SELECT_H@ \
+ && (defined _CYGWIN_SYS_TIME_H \
+ || (!defined _GL_SYS_SELECT_H_REDIRECT_FROM_SYS_TIME_H \
+ && ((defined __osf__ && defined _SYS_TIME_H_ \
+ && defined _OSF_SOURCE) \
+ || (defined __sun && defined _SYS_TIME_H \
+ && (! (defined _XOPEN_SOURCE \
+ || defined _POSIX_C_SOURCE) \
+ || defined __EXTENSIONS__))))))
+
+# define _GL_SYS_SELECT_H_REDIRECT_FROM_SYS_TIME_H
+# @INCLUDE_NEXT@ @NEXT_SYS_SELECT_H@
+
+/* On IRIX 6.5, <sys/timespec.h> includes <sys/types.h>, which includes
+ <sys/bsd_types.h>, which includes <sys/select.h>. At this point we cannot
+ include <signal.h>, because that includes <internal/signal_core.h>, which
+ gives a syntax error because <sys/timespec.h> has not been completely
+ processed. Simply delegate to the system's header in this case. */
+#elif @HAVE_SYS_SELECT_H@ && defined __sgi && (defined _SYS_BSD_TYPES_H && !defined _GL_SYS_SELECT_H_REDIRECT_FROM_SYS_BSD_TYPES_H)
+
+# define _GL_SYS_SELECT_H_REDIRECT_FROM_SYS_BSD_TYPES_H
+# @INCLUDE_NEXT@ @NEXT_SYS_SELECT_H@
+
+/* On OpenBSD 5.0, <pthread.h> includes <sys/types.h>, which includes
+ <sys/select.h>. At this point we cannot include <signal.h>, because that
+ includes gnulib's pthread.h override, which gives a syntax error because
+ /usr/include/pthread.h has not been completely processed. Simply delegate
+ to the system's header in this case. */
+#elif @HAVE_SYS_SELECT_H@ && defined __OpenBSD__ && (defined _PTHREAD_H_ && !defined PTHREAD_MUTEX_INITIALIZER)
+
+# @INCLUDE_NEXT@ @NEXT_SYS_SELECT_H@
+
+#else
+
+#ifndef _@GUARD_PREFIX@_SYS_SELECT_H
+
+/* On many platforms, <sys/select.h> assumes prior inclusion of
+ <sys/types.h>. Also, mingw defines sigset_t there, instead of
+ in <signal.h> where it belongs. */
+#include <sys/types.h>
+
+#if @HAVE_SYS_SELECT_H@
+
+/* On OSF/1 4.0, <sys/select.h> provides only a forward declaration
+ of 'struct timeval', and no definition of this type.
+ Also, Mac OS X, AIX, HP-UX, IRIX, Solaris, Interix declare select()
+ in <sys/time.h>.
+ But avoid namespace pollution on glibc systems. */
+# ifndef __GLIBC__
+# include <sys/time.h>
+# endif
+
+/* On AIX 7 and Solaris 10, <sys/select.h> provides an FD_ZERO implementation
+ that relies on memset(), but without including <string.h>.
+ But in any case avoid namespace pollution on glibc systems. */
+# if (defined __OpenBSD__ || defined _AIX || defined __sun || defined __osf__ || defined __BEOS__) \
+ && ! defined __GLIBC__
+# include <string.h>
+# endif
+
+/* The include_next requires a split double-inclusion guard. */
+# @INCLUDE_NEXT@ @NEXT_SYS_SELECT_H@
+
+#endif
+
+/* Get definition of 'sigset_t'.
+ But avoid namespace pollution on glibc systems.
+ Do this after the include_next (for the sake of OpenBSD 5.0) but before
+ the split double-inclusion guard (for the sake of Solaris). */
+#if !(defined __GLIBC__ && !defined __UCLIBC__)
+# include <signal.h>
+#endif
+
+#ifndef _@GUARD_PREFIX@_SYS_SELECT_H
+#define _@GUARD_PREFIX@_SYS_SELECT_H
+
+#if !@HAVE_SYS_SELECT_H@
+/* A platform that lacks <sys/select.h>. */
+/* Get the 'struct timeval' and 'fd_set' types and the FD_* macros
+ on most platforms. */
+# include <sys/time.h>
+/* On HP-UX 11, <sys/time.h> provides an FD_ZERO implementation
+ that relies on memset(), but without including <string.h>. */
+# if defined __hpux
+# include <string.h>
+# endif
+/* On native Windows platforms:
+ Get the 'fd_set' type.
+ Get the close() declaration before we override it. */
+# if @HAVE_WINSOCK2_H@
+# if !defined _GL_INCLUDING_WINSOCK2_H
+# define _GL_INCLUDING_WINSOCK2_H
+# include <winsock2.h>
+# undef _GL_INCLUDING_WINSOCK2_H
+# endif
+# include <io.h>
+# endif
+#endif
+
+/* The definitions of _GL_FUNCDECL_RPL etc. are copied here. */
+
+/* The definition of _GL_WARN_ON_USE is copied here. */
+
+
+/* Fix some definitions from <winsock2.h>. */
+
+#if @HAVE_WINSOCK2_H@
+
+# if !GNULIB_defined_rpl_fd_isset
+
+/* Re-define FD_ISSET to avoid a WSA call while we are not using
+ network sockets. */
+static int
+rpl_fd_isset (SOCKET fd, fd_set * set)
+{
+ u_int i;
+ if (set == NULL)
+ return 0;
+
+ for (i = 0; i < set->fd_count; i++)
+ if (set->fd_array[i] == fd)
+ return 1;
+
+ return 0;
+}
+
+# define GNULIB_defined_rpl_fd_isset 1
+# endif
+
+# undef FD_ISSET
+# define FD_ISSET(fd, set) rpl_fd_isset(fd, set)
+
+#endif
+
+/* Hide some function declarations from <winsock2.h>. */
+
+#if @HAVE_WINSOCK2_H@
+# if !defined _@GUARD_PREFIX@_UNISTD_H
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef close
+# define close close_used_without_including_unistd_h
+# else
+ _GL_WARN_ON_USE (close,
+ "close() used without including <unistd.h>");
+# endif
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef gethostname
+# define gethostname gethostname_used_without_including_unistd_h
+# else
+ _GL_WARN_ON_USE (gethostname,
+ "gethostname() used without including <unistd.h>");
+# endif
+# endif
+# if !defined _@GUARD_PREFIX@_SYS_SOCKET_H
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef socket
+# define socket socket_used_without_including_sys_socket_h
+# undef connect
+# define connect connect_used_without_including_sys_socket_h
+# undef accept
+# define accept accept_used_without_including_sys_socket_h
+# undef bind
+# define bind bind_used_without_including_sys_socket_h
+# undef getpeername
+# define getpeername getpeername_used_without_including_sys_socket_h
+# undef getsockname
+# define getsockname getsockname_used_without_including_sys_socket_h
+# undef getsockopt
+# define getsockopt getsockopt_used_without_including_sys_socket_h
+# undef listen
+# define listen listen_used_without_including_sys_socket_h
+# undef recv
+# define recv recv_used_without_including_sys_socket_h
+# undef send
+# define send send_used_without_including_sys_socket_h
+# undef recvfrom
+# define recvfrom recvfrom_used_without_including_sys_socket_h
+# undef sendto
+# define sendto sendto_used_without_including_sys_socket_h
+# undef setsockopt
+# define setsockopt setsockopt_used_without_including_sys_socket_h
+# undef shutdown
+# define shutdown shutdown_used_without_including_sys_socket_h
+# else
+ _GL_WARN_ON_USE (socket,
+ "socket() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (connect,
+ "connect() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (accept,
+ "accept() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (bind,
+ "bind() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (getpeername,
+ "getpeername() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (getsockname,
+ "getsockname() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (getsockopt,
+ "getsockopt() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (listen,
+ "listen() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (recv,
+ "recv() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (send,
+ "send() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (recvfrom,
+ "recvfrom() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (sendto,
+ "sendto() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (setsockopt,
+ "setsockopt() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (shutdown,
+ "shutdown() used without including <sys/socket.h>");
+# endif
+# endif
+#endif
+
+
+#if @GNULIB_PSELECT@
+# if @REPLACE_PSELECT@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef pselect
+# define pselect rpl_pselect
+# endif
+_GL_FUNCDECL_RPL (pselect, int,
+ (int, fd_set *restrict, fd_set *restrict, fd_set *restrict,
+ struct timespec const *restrict, const sigset_t *restrict));
+_GL_CXXALIAS_RPL (pselect, int,
+ (int, fd_set *restrict, fd_set *restrict, fd_set *restrict,
+ struct timespec const *restrict, const sigset_t *restrict));
+# else
+# if !@HAVE_PSELECT@
+_GL_FUNCDECL_SYS (pselect, int,
+ (int, fd_set *restrict, fd_set *restrict, fd_set *restrict,
+ struct timespec const *restrict, const sigset_t *restrict));
+# endif
+_GL_CXXALIAS_SYS (pselect, int,
+ (int, fd_set *restrict, fd_set *restrict, fd_set *restrict,
+ struct timespec const *restrict, const sigset_t *restrict));
+# endif
+_GL_CXXALIASWARN (pselect);
+#elif defined GNULIB_POSIXCHECK
+# undef pselect
+# if HAVE_RAW_DECL_PSELECT
+_GL_WARN_ON_USE (pselect, "pselect is not portable - "
+ "use gnulib module pselect for portability");
+# endif
+#endif
+
+#if @GNULIB_SELECT@
+# if @REPLACE_SELECT@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef select
+# define select rpl_select
+# endif
+_GL_FUNCDECL_RPL (select, int,
+ (int, fd_set *, fd_set *, fd_set *, struct timeval *));
+_GL_CXXALIAS_RPL (select, int,
+ (int, fd_set *, fd_set *, fd_set *, struct timeval *));
+# else
+_GL_CXXALIAS_SYS (select, int,
+ (int, fd_set *, fd_set *, fd_set *, struct timeval *));
+# endif
+_GL_CXXALIASWARN (select);
+#elif @HAVE_WINSOCK2_H@
+# undef select
+# define select select_used_without_requesting_gnulib_module_select
+#elif defined GNULIB_POSIXCHECK
+# undef select
+# if HAVE_RAW_DECL_SELECT
+_GL_WARN_ON_USE (select, "select is not always POSIX compliant - "
+ "use gnulib module select for portability");
+# endif
+#endif
+
+
+#endif /* _@GUARD_PREFIX@_SYS_SELECT_H */
+#endif /* _@GUARD_PREFIX@_SYS_SELECT_H */
+#endif /* OSF/1 */
diff --git a/lib/sys_socket.c b/lib/sys_socket.c
new file mode 100644
index 0000000..3b261da
--- /dev/null
+++ b/lib/sys_socket.c
@@ -0,0 +1,4 @@
+#include <config.h>
+#define _GL_SYS_SOCKET_INLINE _GL_EXTERN_INLINE
+#include "sys/socket.h"
+typedef int dummy;
diff --git a/lib/sys_socket.in.h b/lib/sys_socket.in.h
new file mode 100644
index 0000000..a627dd4
--- /dev/null
+++ b/lib/sys_socket.in.h
@@ -0,0 +1,692 @@
+/* Provide a sys/socket header file for systems lacking it (read: MinGW)
+ and for systems where it is incomplete.
+ Copyright (C) 2005-2016 Free Software Foundation, Inc.
+ Written by Simon Josefsson.
+
+ 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, 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 <http://www.gnu.org/licenses/>. */
+
+/* This file is supposed to be used on platforms that lack <sys/socket.h>,
+ on platforms where <sys/socket.h> cannot be included standalone, and on
+ platforms where <sys/socket.h> does not provide all necessary definitions.
+ It is intended to provide definitions and prototypes needed by an
+ application. */
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+#if defined _GL_ALREADY_INCLUDING_SYS_SOCKET_H
+/* Special invocation convention:
+ - On Cygwin 1.5.x we have a sequence of nested includes
+ <sys/socket.h> -> <cygwin/socket.h> -> <asm/socket.h> -> <cygwin/if.h>,
+ and the latter includes <sys/socket.h>. In this situation, the functions
+ are not yet declared, therefore we cannot provide the C++ aliases. */
+
+#@INCLUDE_NEXT@ @NEXT_SYS_SOCKET_H@
+
+#else
+/* Normal invocation convention. */
+
+#ifndef _@GUARD_PREFIX@_SYS_SOCKET_H
+
+#if @HAVE_SYS_SOCKET_H@
+
+# define _GL_ALREADY_INCLUDING_SYS_SOCKET_H
+
+/* On many platforms, <sys/socket.h> assumes prior inclusion of
+ <sys/types.h>. */
+# include <sys/types.h>
+
+/* On FreeBSD 6.4, <sys/socket.h> defines some macros that assume that NULL
+ is defined. */
+# include <stddef.h>
+
+/* The include_next requires a split double-inclusion guard. */
+# @INCLUDE_NEXT@ @NEXT_SYS_SOCKET_H@
+
+# undef _GL_ALREADY_INCLUDING_SYS_SOCKET_H
+
+#endif
+
+#ifndef _@GUARD_PREFIX@_SYS_SOCKET_H
+#define _@GUARD_PREFIX@_SYS_SOCKET_H
+
+#ifndef _GL_INLINE_HEADER_BEGIN
+ #error "Please include config.h first."
+#endif
+_GL_INLINE_HEADER_BEGIN
+#ifndef _GL_SYS_SOCKET_INLINE
+# define _GL_SYS_SOCKET_INLINE _GL_INLINE
+#endif
+
+/* The definitions of _GL_FUNCDECL_RPL etc. are copied here. */
+
+/* The definition of _GL_ARG_NONNULL is copied here. */
+
+/* The definition of _GL_WARN_ON_USE is copied here. */
+
+#if !@HAVE_SA_FAMILY_T@
+# if !GNULIB_defined_sa_family_t
+typedef unsigned short sa_family_t;
+# define GNULIB_defined_sa_family_t 1
+# endif
+#endif
+
+#if @HAVE_STRUCT_SOCKADDR_STORAGE@
+/* Make the 'struct sockaddr_storage' field 'ss_family' visible on AIX 7.1. */
+# if !@HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY@
+# ifndef ss_family
+# define ss_family __ss_family
+# endif
+# endif
+#else
+# include <stdalign.h>
+/* Code taken from glibc sysdeps/unix/sysv/linux/bits/socket.h on
+ 2009-05-08, licensed under LGPLv2.1+, plus portability fixes. */
+# define __ss_aligntype unsigned long int
+# define _SS_SIZE 256
+# define _SS_PADSIZE \
+ (_SS_SIZE - ((sizeof (sa_family_t) >= alignof (__ss_aligntype) \
+ ? sizeof (sa_family_t) \
+ : alignof (__ss_aligntype)) \
+ + sizeof (__ss_aligntype)))
+
+# if !GNULIB_defined_struct_sockaddr_storage
+struct sockaddr_storage
+{
+ sa_family_t ss_family; /* Address family, etc. */
+ __ss_aligntype __ss_align; /* Force desired alignment. */
+ char __ss_padding[_SS_PADSIZE];
+};
+# define GNULIB_defined_struct_sockaddr_storage 1
+# endif
+
+#endif
+
+/* Get struct iovec. */
+/* But avoid namespace pollution on glibc systems. */
+#if ! defined __GLIBC__
+# include <sys/uio.h>
+#endif
+
+#if @HAVE_SYS_SOCKET_H@
+
+/* A platform that has <sys/socket.h>. */
+
+/* For shutdown(). */
+# if !defined SHUT_RD
+# define SHUT_RD 0
+# endif
+# if !defined SHUT_WR
+# define SHUT_WR 1
+# endif
+# if !defined SHUT_RDWR
+# define SHUT_RDWR 2
+# endif
+
+#else
+
+# ifdef __CYGWIN__
+# error "Cygwin does have a sys/socket.h, doesn't it?!?"
+# endif
+
+/* A platform that lacks <sys/socket.h>.
+
+ Currently only MinGW is supported. See the gnulib manual regarding
+ Windows sockets. MinGW has the header files winsock2.h and
+ ws2tcpip.h that declare the sys/socket.h definitions we need. Note
+ that you can influence which definitions you get by setting the
+ WINVER symbol before including these two files. For example,
+ getaddrinfo is only available if _WIN32_WINNT >= 0x0501 (that
+ symbol is set indirectly through WINVER). You can set this by
+ adding AC_DEFINE(WINVER, 0x0501) to configure.ac. Note that your
+ code may not run on older Windows releases then. My Windows 2000
+ box was not able to run the code, for example. The situation is
+ slightly confusing because
+ <http://msdn.microsoft.com/en-us/library/ms738520>
+ suggests that getaddrinfo should be available on all Windows
+ releases. */
+
+# if @HAVE_WINSOCK2_H@
+# include <winsock2.h>
+# endif
+# if @HAVE_WS2TCPIP_H@
+# include <ws2tcpip.h>
+# endif
+
+/* For shutdown(). */
+# if !defined SHUT_RD && defined SD_RECEIVE
+# define SHUT_RD SD_RECEIVE
+# endif
+# if !defined SHUT_WR && defined SD_SEND
+# define SHUT_WR SD_SEND
+# endif
+# if !defined SHUT_RDWR && defined SD_BOTH
+# define SHUT_RDWR SD_BOTH
+# endif
+
+# if @HAVE_WINSOCK2_H@
+/* Include headers needed by the emulation code. */
+# include <sys/types.h>
+# include <io.h>
+
+# if !GNULIB_defined_socklen_t
+typedef int socklen_t;
+# define GNULIB_defined_socklen_t 1
+# endif
+
+# endif
+
+/* Rudimentary 'struct msghdr'; this works as long as you don't try to
+ access msg_control or msg_controllen. */
+struct msghdr {
+ void *msg_name;
+ socklen_t msg_namelen;
+ struct iovec *msg_iov;
+ int msg_iovlen;
+ int msg_flags;
+};
+
+#endif
+
+/* Fix some definitions from <winsock2.h>. */
+
+#if @HAVE_WINSOCK2_H@
+
+# if !GNULIB_defined_rpl_fd_isset
+
+/* Re-define FD_ISSET to avoid a WSA call while we are not using
+ network sockets. */
+_GL_SYS_SOCKET_INLINE int
+rpl_fd_isset (SOCKET fd, fd_set * set)
+{
+ u_int i;
+ if (set == NULL)
+ return 0;
+
+ for (i = 0; i < set->fd_count; i++)
+ if (set->fd_array[i] == fd)
+ return 1;
+
+ return 0;
+}
+
+# define GNULIB_defined_rpl_fd_isset 1
+# endif
+
+# undef FD_ISSET
+# define FD_ISSET(fd, set) rpl_fd_isset(fd, set)
+
+#endif
+
+/* Hide some function declarations from <winsock2.h>. */
+
+#if @HAVE_WINSOCK2_H@
+# if !defined _@GUARD_PREFIX@_UNISTD_H
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef close
+# define close close_used_without_including_unistd_h
+# else
+ _GL_WARN_ON_USE (close,
+ "close() used without including <unistd.h>");
+# endif
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef gethostname
+# define gethostname gethostname_used_without_including_unistd_h
+# else
+ _GL_WARN_ON_USE (gethostname,
+ "gethostname() used without including <unistd.h>");
+# endif
+# endif
+# if !defined _@GUARD_PREFIX@_SYS_SELECT_H
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef select
+# define select select_used_without_including_sys_select_h
+# else
+ _GL_WARN_ON_USE (select,
+ "select() used without including <sys/select.h>");
+# endif
+# endif
+#endif
+
+/* Wrap everything else to use libc file descriptors for sockets. */
+
+#if @GNULIB_SOCKET@
+# if @HAVE_WINSOCK2_H@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef socket
+# define socket rpl_socket
+# endif
+_GL_FUNCDECL_RPL (socket, int, (int domain, int type, int protocol));
+_GL_CXXALIAS_RPL (socket, int, (int domain, int type, int protocol));
+# else
+_GL_CXXALIAS_SYS (socket, int, (int domain, int type, int protocol));
+# endif
+_GL_CXXALIASWARN (socket);
+#elif @HAVE_WINSOCK2_H@
+# undef socket
+# define socket socket_used_without_requesting_gnulib_module_socket
+#elif defined GNULIB_POSIXCHECK
+# undef socket
+# if HAVE_RAW_DECL_SOCKET
+_GL_WARN_ON_USE (socket, "socket is not always POSIX compliant - "
+ "use gnulib module socket for portability");
+# endif
+#endif
+
+#if @GNULIB_CONNECT@
+# if @HAVE_WINSOCK2_H@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef connect
+# define connect rpl_connect
+# endif
+_GL_FUNCDECL_RPL (connect, int,
+ (int fd, const struct sockaddr *addr, socklen_t addrlen)
+ _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_RPL (connect, int,
+ (int fd, const struct sockaddr *addr, socklen_t addrlen));
+# else
+/* Need to cast, because on NonStop Kernel, the third parameter is
+ size_t addrlen. */
+_GL_CXXALIAS_SYS_CAST (connect, int,
+ (int fd,
+ const struct sockaddr *addr, socklen_t addrlen));
+# endif
+_GL_CXXALIASWARN (connect);
+#elif @HAVE_WINSOCK2_H@
+# undef connect
+# define connect socket_used_without_requesting_gnulib_module_connect
+#elif defined GNULIB_POSIXCHECK
+# undef connect
+# if HAVE_RAW_DECL_CONNECT
+_GL_WARN_ON_USE (connect, "connect is not always POSIX compliant - "
+ "use gnulib module connect for portability");
+# endif
+#endif
+
+#if @GNULIB_ACCEPT@
+# if @HAVE_WINSOCK2_H@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef accept
+# define accept rpl_accept
+# endif
+_GL_FUNCDECL_RPL (accept, int,
+ (int fd, struct sockaddr *addr, socklen_t *addrlen));
+_GL_CXXALIAS_RPL (accept, int,
+ (int fd, struct sockaddr *addr, socklen_t *addrlen));
+# else
+/* Need to cast, because on Solaris 10 systems, the third parameter is
+ void *addrlen. */
+_GL_CXXALIAS_SYS_CAST (accept, int,
+ (int fd, struct sockaddr *addr, socklen_t *addrlen));
+# endif
+_GL_CXXALIASWARN (accept);
+#elif @HAVE_WINSOCK2_H@
+# undef accept
+# define accept accept_used_without_requesting_gnulib_module_accept
+#elif defined GNULIB_POSIXCHECK
+# undef accept
+# if HAVE_RAW_DECL_ACCEPT
+_GL_WARN_ON_USE (accept, "accept is not always POSIX compliant - "
+ "use gnulib module accept for portability");
+# endif
+#endif
+
+#if @GNULIB_BIND@
+# if @HAVE_WINSOCK2_H@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef bind
+# define bind rpl_bind
+# endif
+_GL_FUNCDECL_RPL (bind, int,
+ (int fd, const struct sockaddr *addr, socklen_t addrlen)
+ _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_RPL (bind, int,
+ (int fd, const struct sockaddr *addr, socklen_t addrlen));
+# else
+/* Need to cast, because on NonStop Kernel, the third parameter is
+ size_t addrlen. */
+_GL_CXXALIAS_SYS_CAST (bind, int,
+ (int fd,
+ const struct sockaddr *addr, socklen_t addrlen));
+# endif
+_GL_CXXALIASWARN (bind);
+#elif @HAVE_WINSOCK2_H@
+# undef bind
+# define bind bind_used_without_requesting_gnulib_module_bind
+#elif defined GNULIB_POSIXCHECK
+# undef bind
+# if HAVE_RAW_DECL_BIND
+_GL_WARN_ON_USE (bind, "bind is not always POSIX compliant - "
+ "use gnulib module bind for portability");
+# endif
+#endif
+
+#if @GNULIB_GETPEERNAME@
+# if @HAVE_WINSOCK2_H@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef getpeername
+# define getpeername rpl_getpeername
+# endif
+_GL_FUNCDECL_RPL (getpeername, int,
+ (int fd, struct sockaddr *addr, socklen_t *addrlen)
+ _GL_ARG_NONNULL ((2, 3)));
+_GL_CXXALIAS_RPL (getpeername, int,
+ (int fd, struct sockaddr *addr, socklen_t *addrlen));
+# else
+/* Need to cast, because on Solaris 10 systems, the third parameter is
+ void *addrlen. */
+_GL_CXXALIAS_SYS_CAST (getpeername, int,
+ (int fd, struct sockaddr *addr, socklen_t *addrlen));
+# endif
+_GL_CXXALIASWARN (getpeername);
+#elif @HAVE_WINSOCK2_H@
+# undef getpeername
+# define getpeername getpeername_used_without_requesting_gnulib_module_getpeername
+#elif defined GNULIB_POSIXCHECK
+# undef getpeername
+# if HAVE_RAW_DECL_GETPEERNAME
+_GL_WARN_ON_USE (getpeername, "getpeername is not always POSIX compliant - "
+ "use gnulib module getpeername for portability");
+# endif
+#endif
+
+#if @GNULIB_GETSOCKNAME@
+# if @HAVE_WINSOCK2_H@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef getsockname
+# define getsockname rpl_getsockname
+# endif
+_GL_FUNCDECL_RPL (getsockname, int,
+ (int fd, struct sockaddr *addr, socklen_t *addrlen)
+ _GL_ARG_NONNULL ((2, 3)));
+_GL_CXXALIAS_RPL (getsockname, int,
+ (int fd, struct sockaddr *addr, socklen_t *addrlen));
+# else
+/* Need to cast, because on Solaris 10 systems, the third parameter is
+ void *addrlen. */
+_GL_CXXALIAS_SYS_CAST (getsockname, int,
+ (int fd, struct sockaddr *addr, socklen_t *addrlen));
+# endif
+_GL_CXXALIASWARN (getsockname);
+#elif @HAVE_WINSOCK2_H@
+# undef getsockname
+# define getsockname getsockname_used_without_requesting_gnulib_module_getsockname
+#elif defined GNULIB_POSIXCHECK
+# undef getsockname
+# if HAVE_RAW_DECL_GETSOCKNAME
+_GL_WARN_ON_USE (getsockname, "getsockname is not always POSIX compliant - "
+ "use gnulib module getsockname for portability");
+# endif
+#endif
+
+#if @GNULIB_GETSOCKOPT@
+# if @HAVE_WINSOCK2_H@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef getsockopt
+# define getsockopt rpl_getsockopt
+# endif
+_GL_FUNCDECL_RPL (getsockopt, int, (int fd, int level, int optname,
+ void *optval, socklen_t *optlen)
+ _GL_ARG_NONNULL ((4, 5)));
+_GL_CXXALIAS_RPL (getsockopt, int, (int fd, int level, int optname,
+ void *optval, socklen_t *optlen));
+# else
+/* Need to cast, because on Solaris 10 systems, the fifth parameter is
+ void *optlen. */
+_GL_CXXALIAS_SYS_CAST (getsockopt, int, (int fd, int level, int optname,
+ void *optval, socklen_t *optlen));
+# endif
+_GL_CXXALIASWARN (getsockopt);
+#elif @HAVE_WINSOCK2_H@
+# undef getsockopt
+# define getsockopt getsockopt_used_without_requesting_gnulib_module_getsockopt
+#elif defined GNULIB_POSIXCHECK
+# undef getsockopt
+# if HAVE_RAW_DECL_GETSOCKOPT
+_GL_WARN_ON_USE (getsockopt, "getsockopt is not always POSIX compliant - "
+ "use gnulib module getsockopt for portability");
+# endif
+#endif
+
+#if @GNULIB_LISTEN@
+# if @HAVE_WINSOCK2_H@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef listen
+# define listen rpl_listen
+# endif
+_GL_FUNCDECL_RPL (listen, int, (int fd, int backlog));
+_GL_CXXALIAS_RPL (listen, int, (int fd, int backlog));
+# else
+_GL_CXXALIAS_SYS (listen, int, (int fd, int backlog));
+# endif
+_GL_CXXALIASWARN (listen);
+#elif @HAVE_WINSOCK2_H@
+# undef listen
+# define listen listen_used_without_requesting_gnulib_module_listen
+#elif defined GNULIB_POSIXCHECK
+# undef listen
+# if HAVE_RAW_DECL_LISTEN
+_GL_WARN_ON_USE (listen, "listen is not always POSIX compliant - "
+ "use gnulib module listen for portability");
+# endif
+#endif
+
+#if @GNULIB_RECV@
+# if @HAVE_WINSOCK2_H@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef recv
+# define recv rpl_recv
+# endif
+_GL_FUNCDECL_RPL (recv, ssize_t, (int fd, void *buf, size_t len, int flags)
+ _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_RPL (recv, ssize_t, (int fd, void *buf, size_t len, int flags));
+# else
+_GL_CXXALIAS_SYS (recv, ssize_t, (int fd, void *buf, size_t len, int flags));
+# endif
+_GL_CXXALIASWARN (recv);
+#elif @HAVE_WINSOCK2_H@
+# undef recv
+# define recv recv_used_without_requesting_gnulib_module_recv
+#elif defined GNULIB_POSIXCHECK
+# undef recv
+# if HAVE_RAW_DECL_RECV
+_GL_WARN_ON_USE (recv, "recv is not always POSIX compliant - "
+ "use gnulib module recv for portability");
+# endif
+#endif
+
+#if @GNULIB_SEND@
+# if @HAVE_WINSOCK2_H@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef send
+# define send rpl_send
+# endif
+_GL_FUNCDECL_RPL (send, ssize_t,
+ (int fd, const void *buf, size_t len, int flags)
+ _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_RPL (send, ssize_t,
+ (int fd, const void *buf, size_t len, int flags));
+# else
+_GL_CXXALIAS_SYS (send, ssize_t,
+ (int fd, const void *buf, size_t len, int flags));
+# endif
+_GL_CXXALIASWARN (send);
+#elif @HAVE_WINSOCK2_H@
+# undef send
+# define send send_used_without_requesting_gnulib_module_send
+#elif defined GNULIB_POSIXCHECK
+# undef send
+# if HAVE_RAW_DECL_SEND
+_GL_WARN_ON_USE (send, "send is not always POSIX compliant - "
+ "use gnulib module send for portability");
+# endif
+#endif
+
+#if @GNULIB_RECVFROM@
+# if @HAVE_WINSOCK2_H@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef recvfrom
+# define recvfrom rpl_recvfrom
+# endif
+_GL_FUNCDECL_RPL (recvfrom, ssize_t,
+ (int fd, void *buf, size_t len, int flags,
+ struct sockaddr *from, socklen_t *fromlen)
+ _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_RPL (recvfrom, ssize_t,
+ (int fd, void *buf, size_t len, int flags,
+ struct sockaddr *from, socklen_t *fromlen));
+# else
+/* Need to cast, because on Solaris 10 systems, the sixth parameter is
+ void *fromlen. */
+_GL_CXXALIAS_SYS_CAST (recvfrom, ssize_t,
+ (int fd, void *buf, size_t len, int flags,
+ struct sockaddr *from, socklen_t *fromlen));
+# endif
+_GL_CXXALIASWARN (recvfrom);
+#elif @HAVE_WINSOCK2_H@
+# undef recvfrom
+# define recvfrom recvfrom_used_without_requesting_gnulib_module_recvfrom
+#elif defined GNULIB_POSIXCHECK
+# undef recvfrom
+# if HAVE_RAW_DECL_RECVFROM
+_GL_WARN_ON_USE (recvfrom, "recvfrom is not always POSIX compliant - "
+ "use gnulib module recvfrom for portability");
+# endif
+#endif
+
+#if @GNULIB_SENDTO@
+# if @HAVE_WINSOCK2_H@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef sendto
+# define sendto rpl_sendto
+# endif
+_GL_FUNCDECL_RPL (sendto, ssize_t,
+ (int fd, const void *buf, size_t len, int flags,
+ const struct sockaddr *to, socklen_t tolen)
+ _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_RPL (sendto, ssize_t,
+ (int fd, const void *buf, size_t len, int flags,
+ const struct sockaddr *to, socklen_t tolen));
+# else
+/* Need to cast, because on NonStop Kernel, the sixth parameter is
+ size_t tolen. */
+_GL_CXXALIAS_SYS_CAST (sendto, ssize_t,
+ (int fd, const void *buf, size_t len, int flags,
+ const struct sockaddr *to, socklen_t tolen));
+# endif
+_GL_CXXALIASWARN (sendto);
+#elif @HAVE_WINSOCK2_H@
+# undef sendto
+# define sendto sendto_used_without_requesting_gnulib_module_sendto
+#elif defined GNULIB_POSIXCHECK
+# undef sendto
+# if HAVE_RAW_DECL_SENDTO
+_GL_WARN_ON_USE (sendto, "sendto is not always POSIX compliant - "
+ "use gnulib module sendto for portability");
+# endif
+#endif
+
+#if @GNULIB_SETSOCKOPT@
+# if @HAVE_WINSOCK2_H@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef setsockopt
+# define setsockopt rpl_setsockopt
+# endif
+_GL_FUNCDECL_RPL (setsockopt, int, (int fd, int level, int optname,
+ const void * optval, socklen_t optlen)
+ _GL_ARG_NONNULL ((4)));
+_GL_CXXALIAS_RPL (setsockopt, int, (int fd, int level, int optname,
+ const void * optval, socklen_t optlen));
+# else
+/* Need to cast, because on NonStop Kernel, the fifth parameter is
+ size_t optlen. */
+_GL_CXXALIAS_SYS_CAST (setsockopt, int,
+ (int fd, int level, int optname,
+ const void * optval, socklen_t optlen));
+# endif
+_GL_CXXALIASWARN (setsockopt);
+#elif @HAVE_WINSOCK2_H@
+# undef setsockopt
+# define setsockopt setsockopt_used_without_requesting_gnulib_module_setsockopt
+#elif defined GNULIB_POSIXCHECK
+# undef setsockopt
+# if HAVE_RAW_DECL_SETSOCKOPT
+_GL_WARN_ON_USE (setsockopt, "setsockopt is not always POSIX compliant - "
+ "use gnulib module setsockopt for portability");
+# endif
+#endif
+
+#if @GNULIB_SHUTDOWN@
+# if @HAVE_WINSOCK2_H@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef shutdown
+# define shutdown rpl_shutdown
+# endif
+_GL_FUNCDECL_RPL (shutdown, int, (int fd, int how));
+_GL_CXXALIAS_RPL (shutdown, int, (int fd, int how));
+# else
+_GL_CXXALIAS_SYS (shutdown, int, (int fd, int how));
+# endif
+_GL_CXXALIASWARN (shutdown);
+#elif @HAVE_WINSOCK2_H@
+# undef shutdown
+# define shutdown shutdown_used_without_requesting_gnulib_module_shutdown
+#elif defined GNULIB_POSIXCHECK
+# undef shutdown
+# if HAVE_RAW_DECL_SHUTDOWN
+_GL_WARN_ON_USE (shutdown, "shutdown is not always POSIX compliant - "
+ "use gnulib module shutdown for portability");
+# endif
+#endif
+
+#if @GNULIB_ACCEPT4@
+/* Accept a connection on a socket, with specific opening flags.
+ The flags are a bitmask, possibly including O_CLOEXEC (defined in <fcntl.h>)
+ and O_TEXT, O_BINARY (defined in "binary-io.h").
+ See also the Linux man page at
+ <http://www.kernel.org/doc/man-pages/online/pages/man2/accept4.2.html>. */
+# if @HAVE_ACCEPT4@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define accept4 rpl_accept4
+# endif
+_GL_FUNCDECL_RPL (accept4, int,
+ (int sockfd, struct sockaddr *addr, socklen_t *addrlen,
+ int flags));
+_GL_CXXALIAS_RPL (accept4, int,
+ (int sockfd, struct sockaddr *addr, socklen_t *addrlen,
+ int flags));
+# else
+_GL_FUNCDECL_SYS (accept4, int,
+ (int sockfd, struct sockaddr *addr, socklen_t *addrlen,
+ int flags));
+_GL_CXXALIAS_SYS (accept4, int,
+ (int sockfd, struct sockaddr *addr, socklen_t *addrlen,
+ int flags));
+# endif
+_GL_CXXALIASWARN (accept4);
+#elif defined GNULIB_POSIXCHECK
+# undef accept4
+# if HAVE_RAW_DECL_ACCEPT4
+_GL_WARN_ON_USE (accept4, "accept4 is unportable - "
+ "use gnulib module accept4 for portability");
+# endif
+#endif
+
+_GL_INLINE_HEADER_END
+
+#endif /* _@GUARD_PREFIX@_SYS_SOCKET_H */
+#endif /* _@GUARD_PREFIX@_SYS_SOCKET_H */
+#endif
diff --git a/lib/sys_stat.in.h b/lib/sys_stat.in.h
new file mode 100644
index 0000000..72d9537
--- /dev/null
+++ b/lib/sys_stat.in.h
@@ -0,0 +1,732 @@
+/* Provide a more complete sys/stat header file.
+ Copyright (C) 2005-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Eric Blake, Paul Eggert, and Jim Meyering. */
+
+/* This file is supposed to be used on platforms where <sys/stat.h> is
+ incomplete. It is intended to provide definitions and prototypes
+ needed by an application. Start with what the system provides. */
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+#if defined __need_system_sys_stat_h
+/* Special invocation convention. */
+
+#@INCLUDE_NEXT@ @NEXT_SYS_STAT_H@
+
+#else
+/* Normal invocation convention. */
+
+#ifndef _@GUARD_PREFIX@_SYS_STAT_H
+
+/* Get nlink_t.
+ May also define off_t to a 64-bit type on native Windows. */
+#include <sys/types.h>
+
+/* Get struct timespec. */
+#include <time.h>
+
+/* The include_next requires a split double-inclusion guard. */
+#@INCLUDE_NEXT@ @NEXT_SYS_STAT_H@
+
+#ifndef _@GUARD_PREFIX@_SYS_STAT_H
+#define _@GUARD_PREFIX@_SYS_STAT_H
+
+/* The definitions of _GL_FUNCDECL_RPL etc. are copied here. */
+
+/* The definition of _GL_ARG_NONNULL is copied here. */
+
+/* The definition of _GL_WARN_ON_USE is copied here. */
+
+/* Before doing "#define mkdir rpl_mkdir" below, we need to include all
+ headers that may declare mkdir(). Native Windows platforms declare mkdir
+ in <io.h> and/or <direct.h>, not in <unistd.h>. */
+#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+# include <io.h> /* mingw32, mingw64 */
+# include <direct.h> /* mingw64, MSVC 9 */
+#endif
+
+/* Native Windows platforms declare umask() in <io.h>. */
+#if 0 && ((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__)
+# include <io.h>
+#endif
+
+/* Large File Support on native Windows. */
+#if @WINDOWS_64_BIT_ST_SIZE@
+# define stat _stati64
+#endif
+
+#ifndef S_IFIFO
+# ifdef _S_IFIFO
+# define S_IFIFO _S_IFIFO
+# endif
+#endif
+
+#ifndef S_IFMT
+# define S_IFMT 0170000
+#endif
+
+#if STAT_MACROS_BROKEN
+# undef S_ISBLK
+# undef S_ISCHR
+# undef S_ISDIR
+# undef S_ISFIFO
+# undef S_ISLNK
+# undef S_ISNAM
+# undef S_ISMPB
+# undef S_ISMPC
+# undef S_ISNWK
+# undef S_ISREG
+# undef S_ISSOCK
+#endif
+
+#ifndef S_ISBLK
+# ifdef S_IFBLK
+# define S_ISBLK(m) (((m) & S_IFMT) == S_IFBLK)
+# else
+# define S_ISBLK(m) 0
+# endif
+#endif
+
+#ifndef S_ISCHR
+# ifdef S_IFCHR
+# define S_ISCHR(m) (((m) & S_IFMT) == S_IFCHR)
+# else
+# define S_ISCHR(m) 0
+# endif
+#endif
+
+#ifndef S_ISDIR
+# ifdef S_IFDIR
+# define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
+# else
+# define S_ISDIR(m) 0
+# endif
+#endif
+
+#ifndef S_ISDOOR /* Solaris 2.5 and up */
+# define S_ISDOOR(m) 0
+#endif
+
+#ifndef S_ISFIFO
+# ifdef S_IFIFO
+# define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO)
+# else
+# define S_ISFIFO(m) 0
+# endif
+#endif
+
+#ifndef S_ISLNK
+# ifdef S_IFLNK
+# define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
+# else
+# define S_ISLNK(m) 0
+# endif
+#endif
+
+#ifndef S_ISMPB /* V7 */
+# ifdef S_IFMPB
+# define S_ISMPB(m) (((m) & S_IFMT) == S_IFMPB)
+# define S_ISMPC(m) (((m) & S_IFMT) == S_IFMPC)
+# else
+# define S_ISMPB(m) 0
+# define S_ISMPC(m) 0
+# endif
+#endif
+
+#ifndef S_ISMPX /* AIX */
+# define S_ISMPX(m) 0
+#endif
+
+#ifndef S_ISNAM /* Xenix */
+# ifdef S_IFNAM
+# define S_ISNAM(m) (((m) & S_IFMT) == S_IFNAM)
+# else
+# define S_ISNAM(m) 0
+# endif
+#endif
+
+#ifndef S_ISNWK /* HP/UX */
+# ifdef S_IFNWK
+# define S_ISNWK(m) (((m) & S_IFMT) == S_IFNWK)
+# else
+# define S_ISNWK(m) 0
+# endif
+#endif
+
+#ifndef S_ISPORT /* Solaris 10 and up */
+# define S_ISPORT(m) 0
+#endif
+
+#ifndef S_ISREG
+# ifdef S_IFREG
+# define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
+# else
+# define S_ISREG(m) 0
+# endif
+#endif
+
+#ifndef S_ISSOCK
+# ifdef S_IFSOCK
+# define S_ISSOCK(m) (((m) & S_IFMT) == S_IFSOCK)
+# else
+# define S_ISSOCK(m) 0
+# endif
+#endif
+
+
+#ifndef S_TYPEISMQ
+# define S_TYPEISMQ(p) 0
+#endif
+
+#ifndef S_TYPEISTMO
+# define S_TYPEISTMO(p) 0
+#endif
+
+
+#ifndef S_TYPEISSEM
+# ifdef S_INSEM
+# define S_TYPEISSEM(p) (S_ISNAM ((p)->st_mode) && (p)->st_rdev == S_INSEM)
+# else
+# define S_TYPEISSEM(p) 0
+# endif
+#endif
+
+#ifndef S_TYPEISSHM
+# ifdef S_INSHD
+# define S_TYPEISSHM(p) (S_ISNAM ((p)->st_mode) && (p)->st_rdev == S_INSHD)
+# else
+# define S_TYPEISSHM(p) 0
+# endif
+#endif
+
+/* high performance ("contiguous data") */
+#ifndef S_ISCTG
+# define S_ISCTG(p) 0
+#endif
+
+/* Cray DMF (data migration facility): off line, with data */
+#ifndef S_ISOFD
+# define S_ISOFD(p) 0
+#endif
+
+/* Cray DMF (data migration facility): off line, with no data */
+#ifndef S_ISOFL
+# define S_ISOFL(p) 0
+#endif
+
+/* 4.4BSD whiteout */
+#ifndef S_ISWHT
+# define S_ISWHT(m) 0
+#endif
+
+/* If any of the following are undefined,
+ define them to their de facto standard values. */
+#if !S_ISUID
+# define S_ISUID 04000
+#endif
+#if !S_ISGID
+# define S_ISGID 02000
+#endif
+
+/* S_ISVTX is a common extension to POSIX. */
+#ifndef S_ISVTX
+# define S_ISVTX 01000
+#endif
+
+#if !S_IRUSR && S_IREAD
+# define S_IRUSR S_IREAD
+#endif
+#if !S_IRUSR
+# define S_IRUSR 00400
+#endif
+#if !S_IRGRP
+# define S_IRGRP (S_IRUSR >> 3)
+#endif
+#if !S_IROTH
+# define S_IROTH (S_IRUSR >> 6)
+#endif
+
+#if !S_IWUSR && S_IWRITE
+# define S_IWUSR S_IWRITE
+#endif
+#if !S_IWUSR
+# define S_IWUSR 00200
+#endif
+#if !S_IWGRP
+# define S_IWGRP (S_IWUSR >> 3)
+#endif
+#if !S_IWOTH
+# define S_IWOTH (S_IWUSR >> 6)
+#endif
+
+#if !S_IXUSR && S_IEXEC
+# define S_IXUSR S_IEXEC
+#endif
+#if !S_IXUSR
+# define S_IXUSR 00100
+#endif
+#if !S_IXGRP
+# define S_IXGRP (S_IXUSR >> 3)
+#endif
+#if !S_IXOTH
+# define S_IXOTH (S_IXUSR >> 6)
+#endif
+
+#if !S_IRWXU
+# define S_IRWXU (S_IRUSR | S_IWUSR | S_IXUSR)
+#endif
+#if !S_IRWXG
+# define S_IRWXG (S_IRGRP | S_IWGRP | S_IXGRP)
+#endif
+#if !S_IRWXO
+# define S_IRWXO (S_IROTH | S_IWOTH | S_IXOTH)
+#endif
+
+/* S_IXUGO is a common extension to POSIX. */
+#if !S_IXUGO
+# define S_IXUGO (S_IXUSR | S_IXGRP | S_IXOTH)
+#endif
+
+#ifndef S_IRWXUGO
+# define S_IRWXUGO (S_IRWXU | S_IRWXG | S_IRWXO)
+#endif
+
+/* Macros for futimens and utimensat. */
+#ifndef UTIME_NOW
+# define UTIME_NOW (-1)
+# define UTIME_OMIT (-2)
+#endif
+
+
+#if @GNULIB_FCHMODAT@
+# if !@HAVE_FCHMODAT@
+_GL_FUNCDECL_SYS (fchmodat, int,
+ (int fd, char const *file, mode_t mode, int flag)
+ _GL_ARG_NONNULL ((2)));
+# endif
+_GL_CXXALIAS_SYS (fchmodat, int,
+ (int fd, char const *file, mode_t mode, int flag));
+_GL_CXXALIASWARN (fchmodat);
+#elif defined GNULIB_POSIXCHECK
+# undef fchmodat
+# if HAVE_RAW_DECL_FCHMODAT
+_GL_WARN_ON_USE (fchmodat, "fchmodat is not portable - "
+ "use gnulib module openat for portability");
+# endif
+#endif
+
+
+#if @GNULIB_FSTAT@
+# if @REPLACE_FSTAT@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef fstat
+# define fstat rpl_fstat
+# endif
+_GL_FUNCDECL_RPL (fstat, int, (int fd, struct stat *buf) _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_RPL (fstat, int, (int fd, struct stat *buf));
+# else
+_GL_CXXALIAS_SYS (fstat, int, (int fd, struct stat *buf));
+# endif
+_GL_CXXALIASWARN (fstat);
+#elif @WINDOWS_64_BIT_ST_SIZE@
+/* Above, we define stat to _stati64. */
+# define fstat _fstati64
+#elif defined GNULIB_POSIXCHECK
+# undef fstat
+# if HAVE_RAW_DECL_FSTAT
+_GL_WARN_ON_USE (fstat, "fstat has portability problems - "
+ "use gnulib module fstat for portability");
+# endif
+#endif
+
+
+#if @GNULIB_FSTATAT@
+# if @REPLACE_FSTATAT@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef fstatat
+# define fstatat rpl_fstatat
+# endif
+_GL_FUNCDECL_RPL (fstatat, int,
+ (int fd, char const *name, struct stat *st, int flags)
+ _GL_ARG_NONNULL ((2, 3)));
+_GL_CXXALIAS_RPL (fstatat, int,
+ (int fd, char const *name, struct stat *st, int flags));
+# else
+# if !@HAVE_FSTATAT@
+_GL_FUNCDECL_SYS (fstatat, int,
+ (int fd, char const *name, struct stat *st, int flags)
+ _GL_ARG_NONNULL ((2, 3)));
+# endif
+_GL_CXXALIAS_SYS (fstatat, int,
+ (int fd, char const *name, struct stat *st, int flags));
+# endif
+_GL_CXXALIASWARN (fstatat);
+#elif defined GNULIB_POSIXCHECK
+# undef fstatat
+# if HAVE_RAW_DECL_FSTATAT
+_GL_WARN_ON_USE (fstatat, "fstatat is not portable - "
+ "use gnulib module openat for portability");
+# endif
+#endif
+
+
+#if @GNULIB_FUTIMENS@
+/* Use the rpl_ prefix also on Solaris <= 9, because on Solaris 9 our futimens
+ implementation relies on futimesat, which on Solaris 10 makes an invocation
+ to futimens that is meant to invoke the libc's futimens(), not gnulib's
+ futimens(). */
+# if @REPLACE_FUTIMENS@ || (!@HAVE_FUTIMENS@ && defined __sun)
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef futimens
+# define futimens rpl_futimens
+# endif
+_GL_FUNCDECL_RPL (futimens, int, (int fd, struct timespec const times[2]));
+_GL_CXXALIAS_RPL (futimens, int, (int fd, struct timespec const times[2]));
+# else
+# if !@HAVE_FUTIMENS@
+_GL_FUNCDECL_SYS (futimens, int, (int fd, struct timespec const times[2]));
+# endif
+_GL_CXXALIAS_SYS (futimens, int, (int fd, struct timespec const times[2]));
+# endif
+# if @HAVE_FUTIMENS@
+_GL_CXXALIASWARN (futimens);
+# endif
+#elif defined GNULIB_POSIXCHECK
+# undef futimens
+# if HAVE_RAW_DECL_FUTIMENS
+_GL_WARN_ON_USE (futimens, "futimens is not portable - "
+ "use gnulib module futimens for portability");
+# endif
+#endif
+
+
+#if @GNULIB_LCHMOD@
+/* Change the mode of FILENAME to MODE, without dereferencing it if FILENAME
+ denotes a symbolic link. */
+# if !@HAVE_LCHMOD@
+/* The lchmod replacement follows symbolic links. Callers should take
+ this into account; lchmod should be applied only to arguments that
+ are known to not be symbolic links. On hosts that lack lchmod,
+ this can lead to race conditions between the check and the
+ invocation of lchmod, but we know of no workarounds that are
+ reliable in general. You might try requesting support for lchmod
+ from your operating system supplier. */
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define lchmod chmod
+# endif
+/* Need to cast, because on mingw, the second parameter of chmod is
+ int mode. */
+_GL_CXXALIAS_RPL_CAST_1 (lchmod, chmod, int,
+ (const char *filename, mode_t mode));
+# else
+# if 0 /* assume already declared */
+_GL_FUNCDECL_SYS (lchmod, int, (const char *filename, mode_t mode)
+ _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (lchmod, int, (const char *filename, mode_t mode));
+# endif
+# if @HAVE_LCHMOD@
+_GL_CXXALIASWARN (lchmod);
+# endif
+#elif defined GNULIB_POSIXCHECK
+# undef lchmod
+# if HAVE_RAW_DECL_LCHMOD
+_GL_WARN_ON_USE (lchmod, "lchmod is unportable - "
+ "use gnulib module lchmod for portability");
+# endif
+#endif
+
+
+#if @GNULIB_LSTAT@
+# if ! @HAVE_LSTAT@
+/* mingw does not support symlinks, therefore it does not have lstat. But
+ without links, stat does just fine. */
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define lstat stat
+# endif
+_GL_CXXALIAS_RPL_1 (lstat, stat, int, (const char *name, struct stat *buf));
+# elif @REPLACE_LSTAT@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef lstat
+# define lstat rpl_lstat
+# endif
+_GL_FUNCDECL_RPL (lstat, int, (const char *name, struct stat *buf)
+ _GL_ARG_NONNULL ((1, 2)));
+_GL_CXXALIAS_RPL (lstat, int, (const char *name, struct stat *buf));
+# else
+_GL_CXXALIAS_SYS (lstat, int, (const char *name, struct stat *buf));
+# endif
+# if @HAVE_LSTAT@
+_GL_CXXALIASWARN (lstat);
+# endif
+#elif defined GNULIB_POSIXCHECK
+# undef lstat
+# if HAVE_RAW_DECL_LSTAT
+_GL_WARN_ON_USE (lstat, "lstat is unportable - "
+ "use gnulib module lstat for portability");
+# endif
+#endif
+
+
+#if @REPLACE_MKDIR@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef mkdir
+# define mkdir rpl_mkdir
+# endif
+_GL_FUNCDECL_RPL (mkdir, int, (char const *name, mode_t mode)
+ _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (mkdir, int, (char const *name, mode_t mode));
+#else
+/* mingw's _mkdir() function has 1 argument, but we pass 2 arguments.
+ Additionally, it declares _mkdir (and depending on compile flags, an
+ alias mkdir), only in the nonstandard includes <direct.h> and <io.h>,
+ which are included above. */
+# if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+
+# if !GNULIB_defined_rpl_mkdir
+static int
+rpl_mkdir (char const *name, mode_t mode)
+{
+ return _mkdir (name);
+}
+# define GNULIB_defined_rpl_mkdir 1
+# endif
+
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define mkdir rpl_mkdir
+# endif
+_GL_CXXALIAS_RPL (mkdir, int, (char const *name, mode_t mode));
+# else
+_GL_CXXALIAS_SYS (mkdir, int, (char const *name, mode_t mode));
+# endif
+#endif
+_GL_CXXALIASWARN (mkdir);
+
+
+#if @GNULIB_MKDIRAT@
+# if !@HAVE_MKDIRAT@
+_GL_FUNCDECL_SYS (mkdirat, int, (int fd, char const *file, mode_t mode)
+ _GL_ARG_NONNULL ((2)));
+# endif
+_GL_CXXALIAS_SYS (mkdirat, int, (int fd, char const *file, mode_t mode));
+_GL_CXXALIASWARN (mkdirat);
+#elif defined GNULIB_POSIXCHECK
+# undef mkdirat
+# if HAVE_RAW_DECL_MKDIRAT
+_GL_WARN_ON_USE (mkdirat, "mkdirat is not portable - "
+ "use gnulib module openat for portability");
+# endif
+#endif
+
+
+#if @GNULIB_MKFIFO@
+# if @REPLACE_MKFIFO@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef mkfifo
+# define mkfifo rpl_mkfifo
+# endif
+_GL_FUNCDECL_RPL (mkfifo, int, (char const *file, mode_t mode)
+ _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (mkfifo, int, (char const *file, mode_t mode));
+# else
+# if !@HAVE_MKFIFO@
+_GL_FUNCDECL_SYS (mkfifo, int, (char const *file, mode_t mode)
+ _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (mkfifo, int, (char const *file, mode_t mode));
+# endif
+_GL_CXXALIASWARN (mkfifo);
+#elif defined GNULIB_POSIXCHECK
+# undef mkfifo
+# if HAVE_RAW_DECL_MKFIFO
+_GL_WARN_ON_USE (mkfifo, "mkfifo is not portable - "
+ "use gnulib module mkfifo for portability");
+# endif
+#endif
+
+
+#if @GNULIB_MKFIFOAT@
+# if !@HAVE_MKFIFOAT@
+_GL_FUNCDECL_SYS (mkfifoat, int, (int fd, char const *file, mode_t mode)
+ _GL_ARG_NONNULL ((2)));
+# endif
+_GL_CXXALIAS_SYS (mkfifoat, int, (int fd, char const *file, mode_t mode));
+_GL_CXXALIASWARN (mkfifoat);
+#elif defined GNULIB_POSIXCHECK
+# undef mkfifoat
+# if HAVE_RAW_DECL_MKFIFOAT
+_GL_WARN_ON_USE (mkfifoat, "mkfifoat is not portable - "
+ "use gnulib module mkfifoat for portability");
+# endif
+#endif
+
+
+#if @GNULIB_MKNOD@
+# if @REPLACE_MKNOD@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef mknod
+# define mknod rpl_mknod
+# endif
+_GL_FUNCDECL_RPL (mknod, int, (char const *file, mode_t mode, dev_t dev)
+ _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (mknod, int, (char const *file, mode_t mode, dev_t dev));
+# else
+# if !@HAVE_MKNOD@
+_GL_FUNCDECL_SYS (mknod, int, (char const *file, mode_t mode, dev_t dev)
+ _GL_ARG_NONNULL ((1)));
+# endif
+/* Need to cast, because on OSF/1 5.1, the third parameter is '...'. */
+_GL_CXXALIAS_SYS_CAST (mknod, int, (char const *file, mode_t mode, dev_t dev));
+# endif
+_GL_CXXALIASWARN (mknod);
+#elif defined GNULIB_POSIXCHECK
+# undef mknod
+# if HAVE_RAW_DECL_MKNOD
+_GL_WARN_ON_USE (mknod, "mknod is not portable - "
+ "use gnulib module mknod for portability");
+# endif
+#endif
+
+
+#if @GNULIB_MKNODAT@
+# if !@HAVE_MKNODAT@
+_GL_FUNCDECL_SYS (mknodat, int,
+ (int fd, char const *file, mode_t mode, dev_t dev)
+ _GL_ARG_NONNULL ((2)));
+# endif
+_GL_CXXALIAS_SYS (mknodat, int,
+ (int fd, char const *file, mode_t mode, dev_t dev));
+_GL_CXXALIASWARN (mknodat);
+#elif defined GNULIB_POSIXCHECK
+# undef mknodat
+# if HAVE_RAW_DECL_MKNODAT
+_GL_WARN_ON_USE (mknodat, "mknodat is not portable - "
+ "use gnulib module mkfifoat for portability");
+# endif
+#endif
+
+
+#if @GNULIB_STAT@
+# if @REPLACE_STAT@
+/* We can't use the object-like #define stat rpl_stat, because of
+ struct stat. This means that rpl_stat will not be used if the user
+ does (stat)(a,b). Oh well. */
+# if defined _AIX && defined stat && defined _LARGE_FILES
+ /* With _LARGE_FILES defined, AIX (only) defines stat to stat64,
+ so we have to replace stat64() instead of stat(). */
+# undef stat64
+# define stat64(name, st) rpl_stat (name, st)
+# elif @WINDOWS_64_BIT_ST_SIZE@
+ /* Above, we define stat to _stati64. */
+# if defined __MINGW32__ && defined _stati64
+# ifndef _USE_32BIT_TIME_T
+ /* The system headers define _stati64 to _stat64. */
+# undef _stat64
+# define _stat64(name, st) rpl_stat (name, st)
+# endif
+# elif defined _MSC_VER && defined _stati64
+# ifdef _USE_32BIT_TIME_T
+ /* The system headers define _stati64 to _stat32i64. */
+# undef _stat32i64
+# define _stat32i64(name, st) rpl_stat (name, st)
+# else
+ /* The system headers define _stati64 to _stat64. */
+# undef _stat64
+# define _stat64(name, st) rpl_stat (name, st)
+# endif
+# else
+# undef _stati64
+# define _stati64(name, st) rpl_stat (name, st)
+# endif
+# elif defined __MINGW32__ && defined stat
+# ifdef _USE_32BIT_TIME_T
+ /* The system headers define stat to _stat32i64. */
+# undef _stat32i64
+# define _stat32i64(name, st) rpl_stat (name, st)
+# else
+ /* The system headers define stat to _stat64. */
+# undef _stat64
+# define _stat64(name, st) rpl_stat (name, st)
+# endif
+# elif defined _MSC_VER && defined stat
+# ifdef _USE_32BIT_TIME_T
+ /* The system headers define stat to _stat32. */
+# undef _stat32
+# define _stat32(name, st) rpl_stat (name, st)
+# else
+ /* The system headers define stat to _stat64i32. */
+# undef _stat64i32
+# define _stat64i32(name, st) rpl_stat (name, st)
+# endif
+# else /* !(_AIX ||__MINGW32__ || _MSC_VER) */
+# undef stat
+# define stat(name, st) rpl_stat (name, st)
+# endif /* !_LARGE_FILES */
+_GL_EXTERN_C int stat (const char *name, struct stat *buf)
+ _GL_ARG_NONNULL ((1, 2));
+# endif
+#elif defined GNULIB_POSIXCHECK
+# undef stat
+# if HAVE_RAW_DECL_STAT
+_GL_WARN_ON_USE (stat, "stat is unportable - "
+ "use gnulib module stat for portability");
+# endif
+#endif
+
+
+#if @GNULIB_UTIMENSAT@
+/* Use the rpl_ prefix also on Solaris <= 9, because on Solaris 9 our utimensat
+ implementation relies on futimesat, which on Solaris 10 makes an invocation
+ to utimensat that is meant to invoke the libc's utimensat(), not gnulib's
+ utimensat(). */
+# if @REPLACE_UTIMENSAT@ || (!@HAVE_UTIMENSAT@ && defined __sun)
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef utimensat
+# define utimensat rpl_utimensat
+# endif
+_GL_FUNCDECL_RPL (utimensat, int, (int fd, char const *name,
+ struct timespec const times[2], int flag)
+ _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_RPL (utimensat, int, (int fd, char const *name,
+ struct timespec const times[2], int flag));
+# else
+# if !@HAVE_UTIMENSAT@
+_GL_FUNCDECL_SYS (utimensat, int, (int fd, char const *name,
+ struct timespec const times[2], int flag)
+ _GL_ARG_NONNULL ((2)));
+# endif
+_GL_CXXALIAS_SYS (utimensat, int, (int fd, char const *name,
+ struct timespec const times[2], int flag));
+# endif
+# if @HAVE_UTIMENSAT@
+_GL_CXXALIASWARN (utimensat);
+# endif
+#elif defined GNULIB_POSIXCHECK
+# undef utimensat
+# if HAVE_RAW_DECL_UTIMENSAT
+_GL_WARN_ON_USE (utimensat, "utimensat is not portable - "
+ "use gnulib module utimensat for portability");
+# endif
+#endif
+
+
+#endif /* _@GUARD_PREFIX@_SYS_STAT_H */
+#endif /* _@GUARD_PREFIX@_SYS_STAT_H */
+#endif
diff --git a/lib/sys_time.in.h b/lib/sys_time.in.h
new file mode 100644
index 0000000..1623a1d
--- /dev/null
+++ b/lib/sys_time.in.h
@@ -0,0 +1,213 @@
+/* Provide a more complete sys/time.h.
+
+ Copyright (C) 2007-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Paul Eggert. */
+
+#ifndef _@GUARD_PREFIX@_SYS_TIME_H
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+/* On Cygwin and on many BSDish systems, <sys/time.h> includes itself
+ recursively via <sys/select.h>.
+ Simply delegate to the system's header in this case; it is a no-op.
+ Without this extra ifdef, the C++ gettimeofday declaration below
+ would be a forward declaration in gnulib's nested <sys/time.h>. */
+#if defined _CYGWIN_SYS_TIME_H || defined _SYS_TIME_H || defined _SYS_TIME_H_
+# @INCLUDE_NEXT@ @NEXT_SYS_TIME_H@
+#else
+
+/* The include_next requires a split double-inclusion guard. */
+#if @HAVE_SYS_TIME_H@
+# @INCLUDE_NEXT@ @NEXT_SYS_TIME_H@
+#endif
+
+#ifndef _@GUARD_PREFIX@_SYS_TIME_H
+#define _@GUARD_PREFIX@_SYS_TIME_H
+
+#if ! @HAVE_SYS_TIME_H@
+# include <time.h>
+#endif
+
+/* On native Windows with MSVC, get the 'struct timeval' type.
+ Also, on native Windows with a 64-bit time_t, where we are overriding the
+ 'struct timeval' type, get all declarations of system functions whose
+ signature contains 'struct timeval'. */
+#if (defined _MSC_VER || @REPLACE_STRUCT_TIMEVAL@) && @HAVE_WINSOCK2_H@ && !defined _GL_INCLUDING_WINSOCK2_H
+# define _GL_INCLUDING_WINSOCK2_H
+# include <winsock2.h>
+# undef _GL_INCLUDING_WINSOCK2_H
+#endif
+
+/* The definitions of _GL_FUNCDECL_RPL etc. are copied here. */
+
+/* The definition of _GL_ARG_NONNULL is copied here. */
+
+/* The definition of _GL_WARN_ON_USE is copied here. */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if !@HAVE_STRUCT_TIMEVAL@ || @REPLACE_STRUCT_TIMEVAL@
+
+# if @REPLACE_STRUCT_TIMEVAL@
+# define timeval rpl_timeval
+# endif
+
+# if !GNULIB_defined_struct_timeval
+struct timeval
+{
+ time_t tv_sec;
+ long int tv_usec;
+};
+# define GNULIB_defined_struct_timeval 1
+# endif
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#if @GNULIB_GETTIMEOFDAY@
+# if @REPLACE_GETTIMEOFDAY@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef gettimeofday
+# define gettimeofday rpl_gettimeofday
+# endif
+_GL_FUNCDECL_RPL (gettimeofday, int,
+ (struct timeval *restrict, void *restrict)
+ _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (gettimeofday, int,
+ (struct timeval *restrict, void *restrict));
+# else
+# if !@HAVE_GETTIMEOFDAY@
+_GL_FUNCDECL_SYS (gettimeofday, int,
+ (struct timeval *restrict, void *restrict)
+ _GL_ARG_NONNULL ((1)));
+# endif
+/* Need to cast, because on glibc systems, by default, the second argument is
+ struct timezone *. */
+_GL_CXXALIAS_SYS_CAST (gettimeofday, int,
+ (struct timeval *restrict, void *restrict));
+# endif
+_GL_CXXALIASWARN (gettimeofday);
+#elif defined GNULIB_POSIXCHECK
+# undef gettimeofday
+# if HAVE_RAW_DECL_GETTIMEOFDAY
+_GL_WARN_ON_USE (gettimeofday, "gettimeofday is unportable - "
+ "use gnulib module gettimeofday for portability");
+# endif
+#endif
+
+/* Hide some function declarations from <winsock2.h>. */
+
+#if defined _MSC_VER && @HAVE_WINSOCK2_H@
+# if !defined _@GUARD_PREFIX@_UNISTD_H
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef close
+# define close close_used_without_including_unistd_h
+# else
+ _GL_WARN_ON_USE (close,
+ "close() used without including <unistd.h>");
+# endif
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef gethostname
+# define gethostname gethostname_used_without_including_unistd_h
+# else
+ _GL_WARN_ON_USE (gethostname,
+ "gethostname() used without including <unistd.h>");
+# endif
+# endif
+# if !defined _@GUARD_PREFIX@_SYS_SOCKET_H
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef socket
+# define socket socket_used_without_including_sys_socket_h
+# undef connect
+# define connect connect_used_without_including_sys_socket_h
+# undef accept
+# define accept accept_used_without_including_sys_socket_h
+# undef bind
+# define bind bind_used_without_including_sys_socket_h
+# undef getpeername
+# define getpeername getpeername_used_without_including_sys_socket_h
+# undef getsockname
+# define getsockname getsockname_used_without_including_sys_socket_h
+# undef getsockopt
+# define getsockopt getsockopt_used_without_including_sys_socket_h
+# undef listen
+# define listen listen_used_without_including_sys_socket_h
+# undef recv
+# define recv recv_used_without_including_sys_socket_h
+# undef send
+# define send send_used_without_including_sys_socket_h
+# undef recvfrom
+# define recvfrom recvfrom_used_without_including_sys_socket_h
+# undef sendto
+# define sendto sendto_used_without_including_sys_socket_h
+# undef setsockopt
+# define setsockopt setsockopt_used_without_including_sys_socket_h
+# undef shutdown
+# define shutdown shutdown_used_without_including_sys_socket_h
+# else
+ _GL_WARN_ON_USE (socket,
+ "socket() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (connect,
+ "connect() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (accept,
+ "accept() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (bind,
+ "bind() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (getpeername,
+ "getpeername() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (getsockname,
+ "getsockname() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (getsockopt,
+ "getsockopt() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (listen,
+ "listen() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (recv,
+ "recv() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (send,
+ "send() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (recvfrom,
+ "recvfrom() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (sendto,
+ "sendto() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (setsockopt,
+ "setsockopt() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (shutdown,
+ "shutdown() used without including <sys/socket.h>");
+# endif
+# endif
+# if !defined _@GUARD_PREFIX@_SYS_SELECT_H
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef select
+# define select select_used_without_including_sys_select_h
+# else
+ _GL_WARN_ON_USE (select,
+ "select() used without including <sys/select.h>");
+# endif
+# endif
+#endif
+
+#endif /* _@GUARD_PREFIX@_SYS_TIME_H */
+#endif /* _CYGWIN_SYS_TIME_H */
+#endif /* _@GUARD_PREFIX@_SYS_TIME_H */
diff --git a/lib/sys_time_.h b/lib/sys_time_.h
deleted file mode 100644
index 46cdb70..0000000
--- a/lib/sys_time_.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/* Provide a more complete sys/time.h.
-
- Copyright (C) 2007 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-/* Written by Paul Eggert. */
-
-#ifndef _gl_SYS_TIME_H
-#define _gl_SYS_TIME_H
-
-#if @HAVE_SYS_TIME_H@
-# include @ABSOLUTE_SYS_TIME_H@
-#else
-# include <time.h>
-#endif
-
-#if ! @HAVE_STRUCT_TIMEVAL@
-struct timeval
-{
- time_t tv_sec;
- long int tv_usec;
-};
-#endif
-
-#if @REPLACE_GETTIMEOFDAY@
-# undef gettimeofday
-# define gettimeofday rpl_gettimeofday
-int gettimeofday (struct timeval *restrict, void *restrict);
-#endif
-
-#endif /* _gl_SYS_TIME_H */
diff --git a/lib/sys_types.in.h b/lib/sys_types.in.h
new file mode 100644
index 0000000..8ab0545
--- /dev/null
+++ b/lib/sys_types.in.h
@@ -0,0 +1,53 @@
+/* Provide a more complete sys/types.h.
+
+ Copyright (C) 2011-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+#ifndef _@GUARD_PREFIX@_SYS_TYPES_H
+
+/* The include_next requires a split double-inclusion guard. */
+# define _GL_INCLUDING_SYS_TYPES_H
+#@INCLUDE_NEXT@ @NEXT_SYS_TYPES_H@
+# undef _GL_INCLUDING_SYS_TYPES_H
+
+#ifndef _@GUARD_PREFIX@_SYS_TYPES_H
+#define _@GUARD_PREFIX@_SYS_TYPES_H
+
+/* Override off_t if Large File Support is requested on native Windows. */
+#if @WINDOWS_64_BIT_OFF_T@
+/* Same as int64_t in <stdint.h>. */
+# if defined _MSC_VER
+# define off_t __int64
+# else
+# define off_t long long int
+# endif
+/* Indicator, for gnulib internal purposes. */
+# define _GL_WINDOWS_64_BIT_OFF_T 1
+#endif
+
+/* MSVC 9 defines size_t in <stddef.h>, not in <sys/types.h>. */
+/* But avoid namespace pollution on glibc systems. */
+#if ((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__) \
+ && ! defined __GLIBC__
+# include <stddef.h>
+#endif
+
+#endif /* _@GUARD_PREFIX@_SYS_TYPES_H */
+#endif /* _@GUARD_PREFIX@_SYS_TYPES_H */
diff --git a/lib/sys_uio.in.h b/lib/sys_uio.in.h
new file mode 100644
index 0000000..e70663f
--- /dev/null
+++ b/lib/sys_uio.in.h
@@ -0,0 +1,63 @@
+/* Substitute for <sys/uio.h>.
+ Copyright (C) 2011-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+# if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+# endif
+@PRAGMA_COLUMNS@
+
+#ifndef _@GUARD_PREFIX@_SYS_UIO_H
+
+#if @HAVE_SYS_UIO_H@
+
+/* On OpenBSD 4.4, <sys/uio.h> assumes prior inclusion of <sys/types.h>. */
+# include <sys/types.h>
+
+/* The include_next requires a split double-inclusion guard. */
+# @INCLUDE_NEXT@ @NEXT_SYS_UIO_H@
+
+#endif
+
+#ifndef _@GUARD_PREFIX@_SYS_UIO_H
+#define _@GUARD_PREFIX@_SYS_UIO_H
+
+#if !@HAVE_SYS_UIO_H@
+/* A platform that lacks <sys/uio.h>. */
+/* Get 'size_t' and 'ssize_t'. */
+# include <sys/types.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# if !GNULIB_defined_struct_iovec
+/* All known platforms that lack <sys/uio.h> also lack any declaration
+ of struct iovec in any other header. */
+struct iovec {
+ void *iov_base;
+ size_t iov_len;
+};
+# define GNULIB_defined_struct_iovec 1
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+
+#endif
+
+#endif /* _@GUARD_PREFIX@_SYS_UIO_H */
+#endif /* _@GUARD_PREFIX@_SYS_UIO_H */
diff --git a/lib/sys_utsname.in.h b/lib/sys_utsname.in.h
new file mode 100644
index 0000000..01dc32e
--- /dev/null
+++ b/lib/sys_utsname.in.h
@@ -0,0 +1,108 @@
+/* Substitute for <sys/utsname.h>.
+ Copyright (C) 2009-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _@GUARD_PREFIX@_SYS_UTSNAME_H
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+#if @HAVE_SYS_UTSNAME_H@
+
+/* Minix 3.1.8 has a bug: <stddef.h> must be included before <sys/utsname.h>.
+ But avoid namespace pollution on glibc systems. */
+# if defined __minix && !defined __GLIBC__
+# include <stddef.h>
+# endif
+
+# @INCLUDE_NEXT@ @NEXT_SYS_UTSNAME_H@
+
+#endif
+
+#define _@GUARD_PREFIX@_SYS_UTSNAME_H
+
+/* The definition of _GL_ARG_NONNULL is copied here. */
+
+/* The definition of _GL_WARN_ON_USE is copied here. */
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if !@HAVE_STRUCT_UTSNAME@
+/* Length of the entries in 'struct utsname' is 256. */
+# define _UTSNAME_LENGTH 256
+
+# ifndef _UTSNAME_NODENAME_LENGTH
+# define _UTSNAME_NODENAME_LENGTH _UTSNAME_LENGTH
+# endif
+# ifndef _UTSNAME_SYSNAME_LENGTH
+# define _UTSNAME_SYSNAME_LENGTH _UTSNAME_LENGTH
+# endif
+# ifndef _UTSNAME_RELEASE_LENGTH
+# define _UTSNAME_RELEASE_LENGTH _UTSNAME_LENGTH
+# endif
+# ifndef _UTSNAME_VERSION_LENGTH
+# define _UTSNAME_VERSION_LENGTH _UTSNAME_LENGTH
+# endif
+# ifndef _UTSNAME_MACHINE_LENGTH
+# define _UTSNAME_MACHINE_LENGTH _UTSNAME_LENGTH
+# endif
+
+# if !GNULIB_defined_struct_utsname
+/* Structure describing the system and machine. */
+struct utsname
+ {
+ /* Name of this node on the network. */
+ char nodename[_UTSNAME_NODENAME_LENGTH];
+
+ /* Name of the implementation of the operating system. */
+ char sysname[_UTSNAME_SYSNAME_LENGTH];
+ /* Current release level of this implementation. */
+ char release[_UTSNAME_RELEASE_LENGTH];
+ /* Current version level of this release. */
+ char version[_UTSNAME_VERSION_LENGTH];
+
+ /* Name of the hardware type the system is running on. */
+ char machine[_UTSNAME_MACHINE_LENGTH];
+ };
+# define GNULIB_defined_struct_utsname 1
+# endif
+
+#endif /* !@HAVE_STRUCT_UTSNAME@ */
+
+
+#if @GNULIB_UNAME@
+# if !@HAVE_UNAME@
+extern int uname (struct utsname *buf) _GL_ARG_NONNULL ((1));
+# endif
+#elif defined GNULIB_POSIXCHECK
+# undef uname
+# if HAVE_RAW_DECL_UNAME
+_GL_WARN_ON_USE (uname, "uname is unportable - "
+ "use gnulib module uname for portability");
+# endif
+#endif
+
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif /* _@GUARD_PREFIX@_SYS_UTSNAME_H */
diff --git a/lib/sys_wait.in.h b/lib/sys_wait.in.h
new file mode 100644
index 0000000..3982b2b
--- /dev/null
+++ b/lib/sys_wait.in.h
@@ -0,0 +1,129 @@
+/* A POSIX-like <sys/wait.h>.
+ Copyright (C) 2001-2003, 2005-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+
+#ifndef _@GUARD_PREFIX@_SYS_WAIT_H
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+/* The include_next requires a split double-inclusion guard. */
+#if !((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__)
+# @INCLUDE_NEXT@ @NEXT_SYS_WAIT_H@
+#endif
+
+#ifndef _@GUARD_PREFIX@_SYS_WAIT_H
+#define _@GUARD_PREFIX@_SYS_WAIT_H
+
+/* Get pid_t. */
+#include <sys/types.h>
+
+
+/* The definitions of _GL_FUNCDECL_RPL etc. are copied here. */
+
+/* The definition of _GL_WARN_ON_USE is copied here. */
+
+
+#if !((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__)
+/* Unix API. */
+
+/* The following macros apply to an argument x, that is a status of a process,
+ as returned by waitpid().
+ On nearly all systems, including Linux/x86, WEXITSTATUS are bits 15..8 and
+ WTERMSIG are bits 7..0, while BeOS uses the opposite. Therefore programs
+ have to use the abstract macros. */
+
+/* For valid x, exactly one of WIFSIGNALED(x), WIFEXITED(x), WIFSTOPPED(x)
+ is true. */
+# ifndef WIFSIGNALED
+# define WIFSIGNALED(x) (WTERMSIG (x) != 0 && WTERMSIG(x) != 0x7f)
+# endif
+# ifndef WIFEXITED
+# define WIFEXITED(x) (WTERMSIG (x) == 0)
+# endif
+# ifndef WIFSTOPPED
+# define WIFSTOPPED(x) (WTERMSIG (x) == 0x7f)
+# endif
+
+/* The termination signal. Only to be accessed if WIFSIGNALED(x) is true. */
+# ifndef WTERMSIG
+# define WTERMSIG(x) ((x) & 0x7f)
+# endif
+
+/* The exit status. Only to be accessed if WIFEXITED(x) is true. */
+# ifndef WEXITSTATUS
+# define WEXITSTATUS(x) (((x) >> 8) & 0xff)
+# endif
+
+/* The stopping signal. Only to be accessed if WIFSTOPPED(x) is true. */
+# ifndef WSTOPSIG
+# define WSTOPSIG(x) (((x) >> 8) & 0x7f)
+# endif
+
+/* True if the process dumped core. Not standardized by POSIX. */
+# ifndef WCOREDUMP
+# define WCOREDUMP(x) ((x) & 0x80)
+# endif
+
+#else
+/* Native Windows API. */
+
+# include <signal.h> /* for SIGTERM */
+
+/* The following macros apply to an argument x, that is a status of a process,
+ as returned by waitpid() or, equivalently, _cwait() or GetExitCodeProcess().
+ This value is simply an 'int', not composed of bit fields. */
+
+/* When an unhandled fatal signal terminates a process, the exit code is 3. */
+# define WIFSIGNALED(x) ((x) == 3)
+# define WIFEXITED(x) ((x) != 3)
+# define WIFSTOPPED(x) 0
+
+/* The signal that terminated a process is not known posthum. */
+# define WTERMSIG(x) SIGTERM
+
+# define WEXITSTATUS(x) (x)
+
+/* There are no stopping signals. */
+# define WSTOPSIG(x) 0
+
+/* There are no core dumps. */
+# define WCOREDUMP(x) 0
+
+#endif
+
+
+/* Declarations of functions. */
+
+#if @GNULIB_WAITPID@
+# if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+_GL_FUNCDECL_SYS (waitpid, pid_t, (pid_t pid, int *statusp, int options));
+# endif
+_GL_CXXALIAS_SYS (waitpid, pid_t, (pid_t pid, int *statusp, int options));
+_GL_CXXALIASWARN (waitpid);
+#elif defined GNULIB_POSIXCHECK
+# undef waitpid
+# if HAVE_RAW_DECL_WAITPID
+_GL_WARN_ON_USE (waitpid, "waitpid is unportable - "
+ "use gnulib module sys_wait for portability");
+# endif
+#endif
+
+
+#endif /* _@GUARD_PREFIX@_SYS_WAIT_H */
+#endif /* _@GUARD_PREFIX@_SYS_WAIT_H */
diff --git a/lib/t-fpending.c b/lib/t-fpending.c
deleted file mode 100644
index 74ecae1..0000000
--- a/lib/t-fpending.c
+++ /dev/null
@@ -1,42 +0,0 @@
-/* Ensure that __fpending works.
-
- Copyright (C) 2004 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-
- Written by Jim Meyering. */
-
-#include <config.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include "__fpending.h"
-
-int
-main ()
-{
- if (__fpending (stdout) != 0)
- abort ();
-
- fputs ("foo", stdout);
- if (__fpending (stdout) != 3)
- abort ();
-
- fflush (stdout);
- if (__fpending (stdout) != 0)
- abort ();
-
- exit (0);
-}
diff --git a/lib/tempname.c b/lib/tempname.c
index e213600..31ecc50 100644
--- a/lib/tempname.c
+++ b/lib/tempname.c
@@ -1,28 +1,26 @@
/* tempname.c - generate the name of a temporary file.
- Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
- 2000, 2001, 2002, 2003, 2005, 2006, 2007 Free Software Foundation,
- Inc.
+ Copyright (C) 1991-2003, 2005-2007, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Extracted from glibc sysdeps/posix/tempname.c. See also tmpdir.c. */
#if !_LIBC
# include <config.h>
# include "tempname.h"
+# include "randint.h"
#endif
#include <sys/types.h>
@@ -41,12 +39,16 @@
# define TMP_MAX 238328
#endif
#ifndef __GT_FILE
-# define __GT_FILE 0
-# define __GT_BIGFILE 1
-# define __GT_DIR 2
-# define __GT_NOCREATE 3
+# define __GT_FILE 0
+# define __GT_DIR 1
+# define __GT_NOCREATE 2
+#endif
+#if !_LIBC && (GT_FILE != __GT_FILE || GT_DIR != __GT_DIR \
+ || GT_NOCREATE != __GT_NOCREATE)
+# error report this to bug-gnulib@gnu.org
#endif
+#include <stdbool.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
@@ -60,39 +62,33 @@
#if _LIBC
# define struct_stat64 struct stat64
-# define small_open __open
-# define large_open __open64
#else
# define struct_stat64 struct stat
-# define small_open open
-# define large_open open
+# define __try_tempname try_tempname
# define __gen_tempname gen_tempname
# define __getpid getpid
# define __gettimeofday gettimeofday
# define __mkdir mkdir
+# define __open open
# define __lxstat64(version, file, buf) lstat (file, buf)
-# define __xstat64(version, file, buf) stat (file, buf)
-#endif
-
-#if ! (HAVE___SECURE_GETENV || _LIBC)
-# define __secure_getenv getenv
+# define __secure_getenv secure_getenv
#endif
#ifdef _LIBC
# include <hp-timing.h>
# if HP_TIMING_AVAIL
# define RANDOM_BITS(Var) \
- if (__builtin_expect (value == UINT64_C (0), 0)) \
- { \
- /* If this is the first time this function is used initialize \
- the variable we accumulate the value in to some somewhat \
- random value. If we'd not do this programs at startup time \
- might have a reduced set of possible names, at least on slow \
- machines. */ \
- struct timeval tv; \
- __gettimeofday (&tv, NULL); \
- value = ((uint64_t) tv.tv_usec << 16) ^ tv.tv_sec; \
- } \
+ if (__builtin_expect (value == UINT64_C (0), 0)) \
+ { \
+ /* If this is the first time this function is used initialize \
+ the variable we accumulate the value in to some somewhat \
+ random value. If we'd not do this programs at startup time \
+ might have a reduced set of possible names, at least on slow \
+ machines. */ \
+ struct timeval tv; \
+ __gettimeofday (&tv, NULL); \
+ value = ((uint64_t) tv.tv_usec << 16) ^ tv.tv_sec; \
+ } \
HP_TIMING_NOW (Var)
# endif
#endif
@@ -123,7 +119,7 @@ direxists (const char *dir)
enough space in TMPL. */
int
__path_search (char *tmpl, size_t tmpl_len, const char *dir, const char *pfx,
- int try_tmpdir)
+ int try_tmpdir)
{
const char *d;
size_t dlen, plen;
@@ -137,35 +133,35 @@ __path_search (char *tmpl, size_t tmpl_len, const char *dir, const char *pfx,
{
plen = strlen (pfx);
if (plen > 5)
- plen = 5;
+ plen = 5;
}
if (try_tmpdir)
{
d = __secure_getenv ("TMPDIR");
if (d != NULL && direxists (d))
- dir = d;
+ dir = d;
else if (dir != NULL && direxists (dir))
- /* nothing */ ;
+ /* nothing */ ;
else
- dir = NULL;
+ dir = NULL;
}
if (dir == NULL)
{
if (direxists (P_tmpdir))
- dir = P_tmpdir;
+ dir = P_tmpdir;
else if (strcmp (P_tmpdir, "/tmp") != 0 && direxists ("/tmp"))
- dir = "/tmp";
+ dir = "/tmp";
else
- {
- __set_errno (ENOENT);
- return -1;
- }
+ {
+ __set_errno (ENOENT);
+ return -1;
+ }
}
dlen = strlen (dir);
while (dlen > 1 && dir[dlen - 1] == '/')
- dlen--; /* remove trailing slashes */
+ dlen--; /* remove trailing slashes */
/* check we have room for "${dir}/${pfx}XXXXXX\0" */
if (tmpl_len < dlen + 1 + plen + 6 + 1)
@@ -179,42 +175,34 @@ __path_search (char *tmpl, size_t tmpl_len, const char *dir, const char *pfx,
}
#endif /* _LIBC */
+static inline bool _GL_ATTRIBUTE_PURE
+check_x_suffix (char const *s, size_t len)
+{
+ return len <= strspn (s, "X");
+}
+
/* These are the characters used in temporary file names. */
static const char letters[] =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
-/* Generate a temporary file name based on TMPL. TMPL must match the
- rules for mk[s]temp (i.e. end in "XXXXXX"). The name constructed
- does not exist at the time of the call to __gen_tempname. TMPL is
- overwritten with the result.
-
- KIND may be one of:
- __GT_NOCREATE: simply verify that the name does not exist
- at the time of the call.
- __GT_FILE: create the file using open(O_CREAT|O_EXCL)
- and return a read-write fd. The file is mode 0600.
- __GT_BIGFILE: same as __GT_FILE but use open64().
- __GT_DIR: create a directory, which will be mode 0700.
-
- We use a clever algorithm to get hard-to-predict names. */
int
-__gen_tempname (char *tmpl, int kind)
+try_tempname_len (char *tmpl, int suffixlen, void *args,
+ int (*tryfunc) (char *, void *), size_t x_suffix_len)
{
- int len;
+ size_t len;
char *XXXXXX;
- static uint64_t value;
- uint64_t random_time_bits;
unsigned int count;
int fd = -1;
int save_errno = errno;
- struct_stat64 st;
+ struct randint_source *rand_src;
/* A lower bound on the number of temporary files to attempt to
generate. The maximum total number of temporary file names that
can exist for a given template is 62**6. It should never be
- necessary to try all these combinations. Instead if a reasonable
+ necessary to try all of these combinations. Instead if a reasonable
number of names is tried (we define reasonable as 62**3) fail to
- give the system administrator the chance to remove the problems. */
+ give the system administrator the chance to remove the problems.
+ This value requires that X_SUFFIX_LEN be at least 3. */
#define ATTEMPTS_MIN (62 * 62 * 62)
/* The number of times to attempt to generate a temporary file. To
@@ -226,90 +214,132 @@ __gen_tempname (char *tmpl, int kind)
#endif
len = strlen (tmpl);
- if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
+ if (len < x_suffix_len + suffixlen
+ || ! check_x_suffix (&tmpl[len - x_suffix_len - suffixlen],
+ x_suffix_len))
{
__set_errno (EINVAL);
return -1;
}
/* This is where the Xs start. */
- XXXXXX = &tmpl[len - 6];
+ XXXXXX = &tmpl[len - x_suffix_len - suffixlen];
/* Get some more or less random data. */
-#ifdef RANDOM_BITS
- RANDOM_BITS (random_time_bits);
-#else
- {
- struct timeval tv;
- __gettimeofday (&tv, NULL);
- random_time_bits = ((uint64_t) tv.tv_usec << 16) ^ tv.tv_sec;
- }
-#endif
- value += random_time_bits ^ __getpid ();
+ rand_src = randint_all_new (NULL, x_suffix_len);
+ if (! rand_src)
+ return -1;
- for (count = 0; count < attempts; value += 7777, ++count)
+ for (count = 0; count < attempts; ++count)
{
- uint64_t v = value;
-
- /* Fill in the random bits. */
- XXXXXX[0] = letters[v % 62];
- v /= 62;
- XXXXXX[1] = letters[v % 62];
- v /= 62;
- XXXXXX[2] = letters[v % 62];
- v /= 62;
- XXXXXX[3] = letters[v % 62];
- v /= 62;
- XXXXXX[4] = letters[v % 62];
- v /= 62;
- XXXXXX[5] = letters[v % 62];
-
- switch (kind)
- {
- case __GT_FILE:
- fd = small_open (tmpl, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
- break;
-
- case __GT_BIGFILE:
- fd = large_open (tmpl, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
- break;
-
- case __GT_DIR:
- fd = __mkdir (tmpl, S_IRUSR | S_IWUSR | S_IXUSR);
- break;
-
- case __GT_NOCREATE:
- /* This case is backward from the other three. __gen_tempname
- succeeds if __xstat fails because the name does not exist.
- Note the continue to bypass the common logic at the bottom
- of the loop. */
- if (__lxstat64 (_STAT_VER, tmpl, &st) < 0)
- {
- if (errno == ENOENT)
- {
- __set_errno (save_errno);
- return 0;
- }
- else
- /* Give up now. */
- return -1;
- }
- continue;
-
- default:
- assert (! "invalid KIND in __gen_tempname");
- }
+ size_t i;
+
+ for (i = 0; i < x_suffix_len; i++)
+ XXXXXX[i] = letters[randint_genmax (rand_src, sizeof letters - 2)];
+ fd = tryfunc (tmpl, args);
if (fd >= 0)
- {
- __set_errno (save_errno);
- return fd;
- }
+ {
+ __set_errno (save_errno);
+ goto done;
+ }
else if (errno != EEXIST)
- return -1;
+ {
+ fd = -1;
+ goto done;
+ }
}
+ randint_all_free (rand_src);
+
/* We got out of the loop because we ran out of combinations to try. */
__set_errno (EEXIST);
return -1;
+
+ done:
+ {
+ int saved_errno = errno;
+ randint_all_free (rand_src);
+ __set_errno (saved_errno);
+ }
+ return fd;
+}
+
+static int
+try_file (char *tmpl, void *flags)
+{
+ int *openflags = flags;
+ return __open (tmpl,
+ (*openflags & ~O_ACCMODE)
+ | O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
+}
+
+static int
+try_dir (char *tmpl, void *flags _GL_UNUSED)
+{
+ return __mkdir (tmpl, S_IRUSR | S_IWUSR | S_IXUSR);
+}
+
+static int
+try_nocreate (char *tmpl, void *flags _GL_UNUSED)
+{
+ struct_stat64 st;
+
+ if (__lxstat64 (_STAT_VER, tmpl, &st) == 0)
+ __set_errno (EEXIST);
+ return errno == ENOENT ? 0 : -1;
+}
+
+/* Generate a temporary file name based on TMPL. TMPL must match the
+ rules for mk[s]temp (i.e., end in at least X_SUFFIX_LEN "X"s,
+ possibly with a suffix).
+ The name constructed does not exist at the time of the call to
+ this function. TMPL is overwritten with the result.
+
+ KIND may be one of:
+ __GT_NOCREATE: simply verify that the name does not exist
+ at the time of the call.
+ __GT_FILE: create the file using open(O_CREAT|O_EXCL)
+ and return a read-write fd. The file is mode 0600.
+ __GT_DIR: create a directory, which will be mode 0700.
+
+ We use a clever algorithm to get hard-to-predict names. */
+int
+gen_tempname_len (char *tmpl, int suffixlen, int flags, int kind,
+ size_t x_suffix_len)
+{
+ int (*tryfunc) (char *, void *);
+
+ switch (kind)
+ {
+ case __GT_FILE:
+ tryfunc = try_file;
+ break;
+
+ case __GT_DIR:
+ tryfunc = try_dir;
+ break;
+
+ case __GT_NOCREATE:
+ tryfunc = try_nocreate;
+ break;
+
+ default:
+ assert (! "invalid KIND in __gen_tempname");
+ abort ();
+ }
+ return try_tempname_len (tmpl, suffixlen, &flags, tryfunc, x_suffix_len);
+}
+
+int
+__gen_tempname (char *tmpl, int suffixlen, int flags, int kind)
+{
+ return gen_tempname_len (tmpl, suffixlen, flags, kind, 6);
+}
+
+int
+__try_tempname (char *tmpl, int suffixlen, void *args,
+ int (*tryfunc) (char *, void *))
+{
+ return try_tempname_len (tmpl, suffixlen, args, tryfunc, 6);
}
diff --git a/lib/tempname.h b/lib/tempname.h
index c51fa69..246d930 100644
--- a/lib/tempname.h
+++ b/lib/tempname.h
@@ -1,11 +1,11 @@
/* Create a temporary file or directory.
- Copyright (C) 2006 Free Software Foundation, Inc.
+ Copyright (C) 2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,28 +13,58 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* header written by Eric Blake */
-/* In gnulib, always prefer large files. GT_FILE maps to
- __GT_BIGFILE, not __GT_FILE, for a reason. */
-#define GT_FILE 1
-#define GT_DIR 2
-#define GT_NOCREATE 3
+#ifndef GL_TEMPNAME_H
+# define GL_TEMPNAME_H
+
+# include <stdio.h>
+
+# ifdef __GT_FILE
+# define GT_FILE __GT_FILE
+# define GT_DIR __GT_DIR
+# define GT_NOCREATE __GT_NOCREATE
+# else
+# define GT_FILE 0
+# define GT_DIR 1
+# define GT_NOCREATE 2
+# endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
/* Generate a temporary file name based on TMPL. TMPL must match the
- rules for mk[s]temp (i.e. end in "XXXXXX"). The name constructed
- does not exist at the time of the call to gen_tempname. TMPL is
- overwritten with the result.
+ rules for mk[s]temp (i.e. end in "XXXXXX", possibly with a suffix).
+ The name constructed does not exist at the time of the call to
+ gen_tempname. TMPL is overwritten with the result.
KIND may be one of:
- GT_NOCREATE: simply verify that the name does not exist
- at the time of the call.
- GT_FILE: create a large file using open(O_CREAT|O_EXCL)
- and return a read-write fd. The file is mode 0600.
- GT_DIR: create a directory, which will be mode 0700.
+ GT_NOCREATE: simply verify that the name does not exist
+ at the time of the call.
+ GT_FILE: create a large file using open(O_CREAT|O_EXCL)
+ and return a read-write fd. The file is mode 0600.
+ GT_DIR: create a directory, which will be mode 0700.
We use a clever algorithm to get hard-to-predict names. */
-extern int gen_tempname (char *tmpl, int kind);
+extern int gen_tempname (char *tmpl, int suffixlen, int flags, int kind);
+extern int gen_tempname_len (char *tmpl, int suffixlen, int flags, int kind,
+ size_t x_suffix_len);
+
+/* Similar to gen_tempname, but TRYFUNC is called for each temporary
+ name to try. If TRYFUNC returns a non-negative number, TRY_GEN_TEMPNAME
+ returns with this value. Otherwise, if errno is set to EEXIST, another
+ name is tried, or else TRY_GEN_TEMPNAME returns -1. */
+extern int try_tempname (char *tmpl, int suffixlen, void *args,
+ int (*tryfunc) (char *, void *));
+extern int try_tempname_len (char *tmpl, int suffixlen, void *args,
+ int (*tryfunc) (char *, void *),
+ size_t x_suffix_len);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* GL_TEMPNAME_H */
diff --git a/lib/termios.in.h b/lib/termios.in.h
new file mode 100644
index 0000000..7c83d74
--- /dev/null
+++ b/lib/termios.in.h
@@ -0,0 +1,73 @@
+/* Substitute for and wrapper around <termios.h>.
+ Copyright (C) 2010-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _@GUARD_PREFIX@_TERMIOS_H
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+/* On HP-UX 11.00, some of the function declarations in <sys/termio.h>,
+ included by <termios.h>, are not protected by extern "C". Enforce
+ "C" linkage for these functions nevertheless. */
+#if defined __hpux && defined __cplusplus
+# include <sys/types.h>
+# include <sys/ioctl.h>
+extern "C" {
+# include <sys/termio.h>
+}
+#endif
+
+/* The include_next requires a split double-inclusion guard. */
+#if @HAVE_TERMIOS_H@
+# @INCLUDE_NEXT@ @NEXT_TERMIOS_H@
+#endif
+
+#ifndef _@GUARD_PREFIX@_TERMIOS_H
+#define _@GUARD_PREFIX@_TERMIOS_H
+
+/* Get pid_t. */
+#include <sys/types.h>
+
+/* The definitions of _GL_FUNCDECL_RPL etc. are copied here. */
+
+/* The definition of _GL_WARN_ON_USE is copied here. */
+
+
+/* Declare overridden functions. */
+
+#if @GNULIB_TCGETSID@
+/* Return the session ID of the controlling terminal of the current process.
+ The argument is a descriptor if this controlling terminal.
+ Return -1, with errno set, upon failure. errno = ENOSYS means that the
+ function is unsupported. */
+# if !@HAVE_DECL_TCGETSID@
+_GL_FUNCDECL_SYS (tcgetsid, pid_t, (int fd));
+# endif
+_GL_CXXALIAS_SYS (tcgetsid, pid_t, (int fd));
+_GL_CXXALIASWARN (tcgetsid);
+#elif defined GNULIB_POSIXCHECK
+# undef tcgetsid
+# if HAVE_RAW_DECL_TCGETSID
+_GL_WARN_ON_USE (tcgetsid, "tcgetsid is not portable - "
+ "use gnulib module tcgetsid for portability");
+# endif
+#endif
+
+
+#endif /* _@GUARD_PREFIX@_TERMIOS_H */
+#endif /* _@GUARD_PREFIX@_TERMIOS_H */
diff --git a/lib/time-internal.h b/lib/time-internal.h
new file mode 100644
index 0000000..0635f28
--- /dev/null
+++ b/lib/time-internal.h
@@ -0,0 +1,49 @@
+/* Time internal interface
+
+ Copyright 2015-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Paul Eggert. */
+
+/* A time zone rule. */
+struct tm_zone
+{
+ /* More abbreviations, should they be needed. Their TZ_IS_SET
+ members are zero. */
+ struct tm_zone *next;
+
+#if HAVE_TZNAME && !HAVE_TM_ZONE
+ /* Copies of recent strings taken from tzname[0] and tzname[1].
+ The copies are in ABBRS, so that they survive tzset. Null if unknown. */
+ char *tzname_copy[2];
+#endif
+
+ /* If nonzero, the rule represents the TZ environment variable set
+ to the first "abbreviation" (this may be the empty string).
+ Otherwise, it represents an unset TZ. */
+ char tz_is_set;
+
+ /* A sequence of null-terminated strings packed next to each other.
+ The strings are followed by an extra null byte. If TZ_IS_SET,
+ there must be at least one string and the first string (which is
+ actually a TZ environment value value) may be empty. Otherwise
+ all strings must be nonempty.
+
+ Abbreviations are stored here because otherwise the values of
+ tm_zone and/or tzname would be dead after changing TZ and calling
+ tzset. Abbreviations never move once allocated, and are live
+ until tzfree is called. */
+ char abbrs[FLEXIBLE_ARRAY_MEMBER];
+};
diff --git a/lib/time.in.h b/lib/time.in.h
new file mode 100644
index 0000000..865c114
--- /dev/null
+++ b/lib/time.in.h
@@ -0,0 +1,297 @@
+/* A more-standard <time.h>.
+
+ Copyright (C) 2007-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+/* Don't get in the way of glibc when it includes time.h merely to
+ declare a few standard symbols, rather than to declare all the
+ symbols. (However, skip this for MinGW as it treats __need_time_t
+ incompatibly.) Also, Solaris 8 <time.h> eventually includes itself
+ recursively; if that is happening, just include the system <time.h>
+ without adding our own declarations. */
+#if (((defined __need_time_t || defined __need_clock_t \
+ || defined __need_timespec) \
+ && !defined __MINGW32__) \
+ || defined _@GUARD_PREFIX@_TIME_H)
+
+# @INCLUDE_NEXT@ @NEXT_TIME_H@
+
+#else
+
+# define _@GUARD_PREFIX@_TIME_H
+
+# @INCLUDE_NEXT@ @NEXT_TIME_H@
+
+/* NetBSD 5.0 mis-defines NULL. */
+# include <stddef.h>
+
+/* The definitions of _GL_FUNCDECL_RPL etc. are copied here. */
+
+/* The definition of _GL_ARG_NONNULL is copied here. */
+
+/* The definition of _GL_WARN_ON_USE is copied here. */
+
+/* Some systems don't define struct timespec (e.g., AIX 4.1, Ultrix 4.3).
+ Or they define it with the wrong member names or define it in <sys/time.h>
+ (e.g., FreeBSD circa 1997). Stock Mingw prior to 3.0 does not define it,
+ but the pthreads-win32 library defines it in <pthread.h>. */
+# if ! @TIME_H_DEFINES_STRUCT_TIMESPEC@
+# if @SYS_TIME_H_DEFINES_STRUCT_TIMESPEC@
+# include <sys/time.h>
+# elif @PTHREAD_H_DEFINES_STRUCT_TIMESPEC@
+# include <pthread.h>
+# elif @UNISTD_H_DEFINES_STRUCT_TIMESPEC@
+# include <unistd.h>
+# else
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# if !GNULIB_defined_struct_timespec
+# undef timespec
+# define timespec rpl_timespec
+struct timespec
+{
+ time_t tv_sec;
+ long int tv_nsec;
+};
+# define GNULIB_defined_struct_timespec 1
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+
+# endif
+# endif
+
+# if !GNULIB_defined_struct_time_t_must_be_integral
+/* Per http://austingroupbugs.net/view.php?id=327, POSIX requires
+ time_t to be an integer type, even though C99 permits floating
+ point. We don't know of any implementation that uses floating
+ point, and it is much easier to write code that doesn't have to
+ worry about that corner case, so we force the issue. */
+struct __time_t_must_be_integral {
+ unsigned int __floating_time_t_unsupported : (time_t) 1;
+};
+# define GNULIB_defined_struct_time_t_must_be_integral 1
+# endif
+
+/* Sleep for at least RQTP seconds unless interrupted, If interrupted,
+ return -1 and store the remaining time into RMTP. See
+ <http://www.opengroup.org/susv3xsh/nanosleep.html>. */
+# if @GNULIB_NANOSLEEP@
+# if @REPLACE_NANOSLEEP@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define nanosleep rpl_nanosleep
+# endif
+_GL_FUNCDECL_RPL (nanosleep, int,
+ (struct timespec const *__rqtp, struct timespec *__rmtp)
+ _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (nanosleep, int,
+ (struct timespec const *__rqtp, struct timespec *__rmtp));
+# else
+# if ! @HAVE_NANOSLEEP@
+_GL_FUNCDECL_SYS (nanosleep, int,
+ (struct timespec const *__rqtp, struct timespec *__rmtp)
+ _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (nanosleep, int,
+ (struct timespec const *__rqtp, struct timespec *__rmtp));
+# endif
+_GL_CXXALIASWARN (nanosleep);
+# endif
+
+/* Return the 'time_t' representation of TP and normalize TP. */
+# if @GNULIB_MKTIME@
+# if @REPLACE_MKTIME@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define mktime rpl_mktime
+# endif
+_GL_FUNCDECL_RPL (mktime, time_t, (struct tm *__tp) _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (mktime, time_t, (struct tm *__tp));
+# else
+_GL_CXXALIAS_SYS (mktime, time_t, (struct tm *__tp));
+# endif
+_GL_CXXALIASWARN (mktime);
+# endif
+
+/* Convert TIMER to RESULT, assuming local time and UTC respectively. See
+ <http://www.opengroup.org/susv3xsh/localtime_r.html> and
+ <http://www.opengroup.org/susv3xsh/gmtime_r.html>. */
+# if @GNULIB_TIME_R@
+# if @REPLACE_LOCALTIME_R@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef localtime_r
+# define localtime_r rpl_localtime_r
+# endif
+_GL_FUNCDECL_RPL (localtime_r, struct tm *, (time_t const *restrict __timer,
+ struct tm *restrict __result)
+ _GL_ARG_NONNULL ((1, 2)));
+_GL_CXXALIAS_RPL (localtime_r, struct tm *, (time_t const *restrict __timer,
+ struct tm *restrict __result));
+# else
+# if ! @HAVE_DECL_LOCALTIME_R@
+_GL_FUNCDECL_SYS (localtime_r, struct tm *, (time_t const *restrict __timer,
+ struct tm *restrict __result)
+ _GL_ARG_NONNULL ((1, 2)));
+# endif
+_GL_CXXALIAS_SYS (localtime_r, struct tm *, (time_t const *restrict __timer,
+ struct tm *restrict __result));
+# endif
+# if @HAVE_DECL_LOCALTIME_R@
+_GL_CXXALIASWARN (localtime_r);
+# endif
+# if @REPLACE_LOCALTIME_R@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef gmtime_r
+# define gmtime_r rpl_gmtime_r
+# endif
+_GL_FUNCDECL_RPL (gmtime_r, struct tm *, (time_t const *restrict __timer,
+ struct tm *restrict __result)
+ _GL_ARG_NONNULL ((1, 2)));
+_GL_CXXALIAS_RPL (gmtime_r, struct tm *, (time_t const *restrict __timer,
+ struct tm *restrict __result));
+# else
+# if ! @HAVE_DECL_LOCALTIME_R@
+_GL_FUNCDECL_SYS (gmtime_r, struct tm *, (time_t const *restrict __timer,
+ struct tm *restrict __result)
+ _GL_ARG_NONNULL ((1, 2)));
+# endif
+_GL_CXXALIAS_SYS (gmtime_r, struct tm *, (time_t const *restrict __timer,
+ struct tm *restrict __result));
+# endif
+# if @HAVE_DECL_LOCALTIME_R@
+_GL_CXXALIASWARN (gmtime_r);
+# endif
+# endif
+
+/* Convert TIMER to RESULT, assuming local time and UTC respectively. See
+ <http://www.opengroup.org/susv3xsh/localtime.html> and
+ <http://www.opengroup.org/susv3xsh/gmtime.html>. */
+# if @GNULIB_GETTIMEOFDAY@
+# if @REPLACE_LOCALTIME@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef localtime
+# define localtime rpl_localtime
+# endif
+_GL_FUNCDECL_RPL (localtime, struct tm *, (time_t const *__timer)
+ _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (localtime, struct tm *, (time_t const *__timer));
+# else
+_GL_CXXALIAS_SYS (localtime, struct tm *, (time_t const *__timer));
+# endif
+_GL_CXXALIASWARN (localtime);
+# endif
+
+# if @GNULIB_GETTIMEOFDAY@
+# if @REPLACE_GMTIME@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef gmtime
+# define gmtime rpl_gmtime
+# endif
+_GL_FUNCDECL_RPL (gmtime, struct tm *, (time_t const *__timer)
+ _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (gmtime, struct tm *, (time_t const *__timer));
+# else
+_GL_CXXALIAS_SYS (gmtime, struct tm *, (time_t const *__timer));
+# endif
+_GL_CXXALIASWARN (gmtime);
+# endif
+
+/* Parse BUF as a time stamp, assuming FORMAT specifies its layout, and store
+ the resulting broken-down time into TM. See
+ <http://www.opengroup.org/susv3xsh/strptime.html>. */
+# if @GNULIB_STRPTIME@
+# if ! @HAVE_STRPTIME@
+_GL_FUNCDECL_SYS (strptime, char *, (char const *restrict __buf,
+ char const *restrict __format,
+ struct tm *restrict __tm)
+ _GL_ARG_NONNULL ((1, 2, 3)));
+# endif
+_GL_CXXALIAS_SYS (strptime, char *, (char const *restrict __buf,
+ char const *restrict __format,
+ struct tm *restrict __tm));
+_GL_CXXALIASWARN (strptime);
+# endif
+
+# if defined _GNU_SOURCE && @GNULIB_TIME_RZ@ && ! @HAVE_TIMEZONE_T@
+typedef struct tm_zone *timezone_t;
+_GL_FUNCDECL_SYS (tzalloc, timezone_t, (char const *__name));
+_GL_CXXALIAS_SYS (tzalloc, timezone_t, (char const *__name));
+_GL_FUNCDECL_SYS (tzfree, void, (timezone_t __tz));
+_GL_CXXALIAS_SYS (tzfree, void, (timezone_t __tz));
+_GL_FUNCDECL_SYS (localtime_rz, struct tm *,
+ (timezone_t __tz, time_t const *restrict __timer,
+ struct tm *restrict __result) _GL_ARG_NONNULL ((2, 3)));
+_GL_CXXALIAS_SYS (localtime_rz, struct tm *,
+ (timezone_t __tz, time_t const *restrict __timer,
+ struct tm *restrict __result));
+_GL_FUNCDECL_SYS (mktime_z, time_t,
+ (timezone_t __tz, struct tm *restrict __result)
+ _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_SYS (mktime_z, time_t,
+ (timezone_t __tz, struct tm *restrict __result));
+# endif
+
+/* Convert TM to a time_t value, assuming UTC. */
+# if @GNULIB_TIMEGM@
+# if @REPLACE_TIMEGM@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef timegm
+# define timegm rpl_timegm
+# endif
+_GL_FUNCDECL_RPL (timegm, time_t, (struct tm *__tm) _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (timegm, time_t, (struct tm *__tm));
+# else
+# if ! @HAVE_TIMEGM@
+_GL_FUNCDECL_SYS (timegm, time_t, (struct tm *__tm) _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (timegm, time_t, (struct tm *__tm));
+# endif
+_GL_CXXALIASWARN (timegm);
+# endif
+
+/* Encourage applications to avoid unsafe functions that can overrun
+ buffers when given outlandish struct tm values. Portable
+ applications should use strftime (or even sprintf) instead. */
+# if defined GNULIB_POSIXCHECK
+# undef asctime
+_GL_WARN_ON_USE (asctime, "asctime can overrun buffers in some cases - "
+ "better use strftime (or even sprintf) instead");
+# endif
+# if defined GNULIB_POSIXCHECK
+# undef asctime_r
+_GL_WARN_ON_USE (asctime, "asctime_r can overrun buffers in some cases - "
+ "better use strftime (or even sprintf) instead");
+# endif
+# if defined GNULIB_POSIXCHECK
+# undef ctime
+_GL_WARN_ON_USE (asctime, "ctime can overrun buffers in some cases - "
+ "better use strftime (or even sprintf) instead");
+# endif
+# if defined GNULIB_POSIXCHECK
+# undef ctime_r
+_GL_WARN_ON_USE (asctime, "ctime_r can overrun buffers in some cases - "
+ "better use strftime (or even sprintf) instead");
+# endif
+
+#endif
diff --git a/lib/time_.h b/lib/time_.h
deleted file mode 100644
index 5467d3d..0000000
--- a/lib/time_.h
+++ /dev/null
@@ -1,107 +0,0 @@
-/* A more-standard <time.h>.
-
- Copyright (C) 2007 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-/* Don't get in the way of glibc when it includes time.h merely to
- declare a few standard symbols, rather than to declare all the
- symbols. */
-#if defined __need_time_t || defined __need_clock_t || defined __need_timespec
-# include @ABSOLUTE_TIME_H@
-
-#elif ! defined _GL_TIME_H
-# define _GL_TIME_H
-# include @ABSOLUTE_TIME_H@
-
-# ifdef __cplusplus
-extern "C" {
-# endif
-
-/* Some systems don't define struct timespec (e.g., AIX 4.1, Ultrix 4.3).
- Or they define it with the wrong member names or define it in <sys/time.h>
- (e.g., FreeBSD circa 1997). */
-# if ! @TIME_H_DEFINES_STRUCT_TIMESPEC@
-# if @SYS_TIME_H_DEFINES_STRUCT_TIMESPEC@
-# include <sys/time.h>
-# else
-# undef timespec
-# define timespec rpl_timespec
-struct timespec
-{
- time_t tv_sec;
- long int tv_nsec;
-};
-# endif
-# endif
-
-/* Sleep for at least RQTP seconds unless interrupted, If interrupted,
- return -1 and store the remaining time into RMTP. See
- <http://www.opengroup.org/susv3xsh/nanosleep.html>. */
-# if @REPLACE_NANOSLEEP@
-# define nanosleep rpl_nanosleep
-int nanosleep (struct timespec const *__rqtp, struct timespec *__rmtp);
-# endif
-
-/* Convert TIMER to RESULT, assuming local time and UTC respectively. See
- <http://www.opengroup.org/susv3xsh/localtime_r.html> and
- <http://www.opengroup.org/susv3xsh/gmtime_r.html>. */
-# if @REPLACE_LOCALTIME_R@
-# undef localtime_r
-# define localtime_r rpl_localtime_r
-# undef gmtime_r
-# define gmtime_r rpl_gmtime_r
-struct tm *localtime_r (time_t const *restrict __timer,
- struct tm *restrict __result);
-struct tm *gmtime_r (time_t const *restrict __timer,
- struct tm *restrict __result);
-# endif
-
-/* Parse BUF as a time stamp, assuming FORMAT specifies its layout, and store
- the resulting broken-down time into TM. See
- <http://www.opengroup.org/susv3xsh/strptime.html>. */
-# if @REPLACE_STRPTIME@
-# undef strptime
-# define strptime rpl_strptime
-char *strptime (char const *restrict __buf, char const *restrict __format,
- struct tm *restrict __tm);
-# endif
-
-/* Convert TM to a time_t value, assuming UTC. */
-# if @REPLACE_TIMEGM@
-# undef timegm
-# define timegm rpl_timegm
-time_t timegm (struct tm *__tm);
-#endif
-
-/* Encourage applications to avoid unsafe functions that can overrun
- buffers when given outlandish struct tm values. Portable
- applications should use strftime (or even sprintf) instead. */
-# if GNULIB_PORTCHECK
-# undef asctime
-# define asctime eschew_asctime
-# undef asctime_r
-# define asctime_r eschew_asctime_r
-# undef ctime
-# define ctime eschew_ctime
-# undef ctime_r
-# define ctime_r eschew_ctime_r
-# endif
-
-# ifdef __cplusplus
-}
-# endif
-
-#endif
diff --git a/lib/time_r.c b/lib/time_r.c
index 2b72692..dc1e161 100644
--- a/lib/time_r.c
+++ b/lib/time_r.c
@@ -1,10 +1,10 @@
/* Reentrant time functions like localtime_r.
- Copyright (C) 2003, 2006, 2007 Free Software Foundation, Inc.
+ Copyright (C) 2003, 2006-2007, 2010-2016 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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ with this program; if not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
@@ -22,8 +21,6 @@
#include <time.h>
-#include <string.h>
-
static struct tm *
copy_tm_result (struct tm *dest, struct tm const *src)
{
diff --git a/lib/time_rz.c b/lib/time_rz.c
new file mode 100644
index 0000000..bc80127
--- /dev/null
+++ b/lib/time_rz.c
@@ -0,0 +1,323 @@
+/* Time zone functions such as tzalloc and localtime_rz
+
+ Copyright 2015-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Paul Eggert. */
+
+/* Although this module is not thread-safe, any races should be fairly
+ rare and reasonably benign. For complete thread-safety, use a C
+ library with a working timezone_t type, so that this module is not
+ needed. */
+
+#include <config.h>
+
+#include <time.h>
+
+#include <errno.h>
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "time-internal.h"
+
+#if !HAVE_TZSET
+static void tzset (void) { }
+#endif
+
+/* The approximate size to use for small allocation requests. This is
+ the largest "small" request for the GNU C library malloc. */
+enum { DEFAULT_MXFAST = 64 * sizeof (size_t) / 4 };
+
+/* Minimum size of the ABBRS member of struct abbr. ABBRS is larger
+ only in the unlikely case where an abbreviation longer than this is
+ used. */
+enum { ABBR_SIZE_MIN = DEFAULT_MXFAST - offsetof (struct tm_zone, abbrs) };
+
+static char const TZ[] = "TZ";
+
+/* Magic cookie timezone_t value, for local time. It differs from
+ NULL and from all other timezone_t values. Only the address
+ matters; the pointer is never dereferenced. */
+static timezone_t const local_tz = (timezone_t) 1;
+
+#if HAVE_TM_ZONE || HAVE_TZNAME
+
+/* Return true if the values A and B differ according to the rules for
+ tm_isdst: A and B differ if one is zero and the other positive. */
+static bool
+isdst_differ (int a, int b)
+{
+ return !a != !b && 0 <= a && 0 <= b;
+}
+
+/* Return true if A and B are equal. */
+static int
+equal_tm (const struct tm *a, const struct tm *b)
+{
+ return ! ((a->tm_sec ^ b->tm_sec)
+ | (a->tm_min ^ b->tm_min)
+ | (a->tm_hour ^ b->tm_hour)
+ | (a->tm_mday ^ b->tm_mday)
+ | (a->tm_mon ^ b->tm_mon)
+ | (a->tm_year ^ b->tm_year)
+ | isdst_differ (a->tm_isdst, b->tm_isdst));
+}
+
+#endif
+
+/* Copy to ABBRS the abbreviation at ABBR with size ABBR_SIZE (this
+ includes its trailing null byte). Append an extra null byte to
+ mark the end of ABBRS. */
+static void
+extend_abbrs (char *abbrs, char const *abbr, size_t abbr_size)
+{
+ memcpy (abbrs, abbr, abbr_size);
+ abbrs[abbr_size] = '\0';
+}
+
+/* Return a newly allocated time zone for NAME, or NULL on failure.
+ A null NAME stands for wall clock time (which is like unset TZ). */
+timezone_t
+tzalloc (char const *name)
+{
+ size_t name_size = name ? strlen (name) + 1 : 0;
+ size_t abbr_size = name_size < ABBR_SIZE_MIN ? ABBR_SIZE_MIN : name_size + 1;
+ timezone_t tz = malloc (offsetof (struct tm_zone, abbrs) + abbr_size);
+ if (tz)
+ {
+ tz->next = NULL;
+#if HAVE_TZNAME && !HAVE_TM_ZONE
+ tz->tzname_copy[0] = tz->tzname_copy[1] = NULL;
+#endif
+ tz->tz_is_set = !!name;
+ tz->abbrs[0] = '\0';
+ if (name)
+ extend_abbrs (tz->abbrs, name, name_size);
+ }
+ return tz;
+}
+
+/* Save into TZ any nontrivial time zone abbreviation used by TM, and
+ update *TM (if HAVE_TM_ZONE) or *TZ (if !HAVE_TM_ZONE &&
+ HAVE_TZNAME) if they use the abbreviation. Return true if
+ successful, false (setting errno) otherwise. */
+static bool
+save_abbr (timezone_t tz, struct tm *tm)
+{
+#if HAVE_TM_ZONE || HAVE_TZNAME
+ char const *zone = NULL;
+ char *zone_copy = (char *) "";
+
+# if HAVE_TZNAME
+ int tzname_index = -1;
+# endif
+
+# if HAVE_TM_ZONE
+ zone = tm->tm_zone;
+# endif
+
+# if HAVE_TZNAME
+ if (! (zone && *zone) && 0 <= tm->tm_isdst)
+ {
+ tzname_index = tm->tm_isdst != 0;
+ zone = tzname[tzname_index];
+ }
+# endif
+
+ /* No need to replace null zones, or zones within the struct tm. */
+ if (!zone || ((char *) tm <= zone && zone < (char *) (tm + 1)))
+ return true;
+
+ if (*zone)
+ {
+ zone_copy = tz->abbrs;
+
+ while (strcmp (zone_copy, zone) != 0)
+ {
+ if (! (*zone_copy || (zone_copy == tz->abbrs && tz->tz_is_set)))
+ {
+ size_t zone_size = strlen (zone) + 1;
+ if (zone_size < tz->abbrs + ABBR_SIZE_MIN - zone_copy)
+ extend_abbrs (zone_copy, zone, zone_size);
+ else
+ {
+ tz = tz->next = tzalloc (zone);
+ if (!tz)
+ return false;
+ tz->tz_is_set = 0;
+ zone_copy = tz->abbrs;
+ }
+ break;
+ }
+
+ zone_copy += strlen (zone_copy) + 1;
+ if (!*zone_copy && tz->next)
+ {
+ tz = tz->next;
+ zone_copy = tz->abbrs;
+ }
+ }
+ }
+
+ /* Replace the zone name so that its lifetime matches that of TZ. */
+# if HAVE_TM_ZONE
+ tm->tm_zone = zone_copy;
+# else
+ if (0 <= tzname_index)
+ tz->tzname_copy[tzname_index] = zone_copy;
+# endif
+#endif
+
+ return true;
+}
+
+/* Free a time zone. */
+void
+tzfree (timezone_t tz)
+{
+ if (tz != local_tz)
+ while (tz)
+ {
+ timezone_t next = tz->next;
+ free (tz);
+ tz = next;
+ }
+}
+
+/* Get and set the TZ environment variable. These functions can be
+ overridden by programs like Emacs that manage their own environment. */
+
+#ifndef getenv_TZ
+static char *
+getenv_TZ (void)
+{
+ return getenv (TZ);
+}
+#endif
+
+#ifndef setenv_TZ
+static int
+setenv_TZ (char const *tz)
+{
+ return tz ? setenv (TZ, tz, 1) : unsetenv (TZ);
+}
+#endif
+
+/* Change the environment to match the specified timezone_t value.
+ Return true if successful, false (setting errno) otherwise. */
+static bool
+change_env (timezone_t tz)
+{
+ if (setenv_TZ (tz->tz_is_set ? tz->abbrs : NULL) != 0)
+ return false;
+ tzset ();
+ return true;
+}
+
+/* Temporarily set the time zone to TZ, which must not be null.
+ Return LOCAL_TZ if the time zone setting is already correct.
+ Otherwise return a newly allocated time zone representing the old
+ setting, or NULL (setting errno) on failure. */
+static timezone_t
+set_tz (timezone_t tz)
+{
+ char *env_tz = getenv_TZ ();
+ if (env_tz
+ ? tz->tz_is_set && strcmp (tz->abbrs, env_tz) == 0
+ : !tz->tz_is_set)
+ return local_tz;
+ else
+ {
+ timezone_t old_tz = tzalloc (env_tz);
+ if (!old_tz)
+ return old_tz;
+ if (! change_env (tz))
+ {
+ int saved_errno = errno;
+ tzfree (old_tz);
+ errno = saved_errno;
+ return NULL;
+ }
+ return old_tz;
+ }
+}
+
+/* Restore an old setting returned by set_tz. It must not be null.
+ Return true (preserving errno) if successful, false (setting errno)
+ otherwise. */
+static bool
+revert_tz (timezone_t tz)
+{
+ if (tz == local_tz)
+ return true;
+ else
+ {
+ int saved_errno = errno;
+ bool ok = change_env (tz);
+ if (!ok)
+ saved_errno = errno;
+ tzfree (tz);
+ errno = saved_errno;
+ return ok;
+ }
+}
+
+/* Use time zone TZ to compute localtime_r (T, TM). */
+struct tm *
+localtime_rz (timezone_t tz, time_t const *t, struct tm *tm)
+{
+ if (!tz)
+ return gmtime_r (t, tm);
+ else
+ {
+ timezone_t old_tz = set_tz (tz);
+ if (old_tz)
+ {
+ bool abbr_saved = localtime_r (t, tm) && save_abbr (tz, tm);
+ if (revert_tz (old_tz) && abbr_saved)
+ return tm;
+ }
+ return NULL;
+ }
+}
+
+/* Use time zone TZ to compute mktime (TM). */
+time_t
+mktime_z (timezone_t tz, struct tm *tm)
+{
+ if (!tz)
+ return timegm (tm);
+ else
+ {
+ timezone_t old_tz = set_tz (tz);
+ if (old_tz)
+ {
+ time_t t = mktime (tm);
+#if HAVE_TM_ZONE || HAVE_TZNAME
+ time_t badtime = -1;
+ struct tm tm_1;
+ if ((t != badtime
+ || (localtime_r (&t, &tm_1) && equal_tm (tm, &tm_1)))
+ && !save_abbr (tz, tm))
+ t = badtime;
+#endif
+ if (revert_tz (old_tz))
+ return t;
+ }
+ return -1;
+ }
+}
diff --git a/lib/timegm.c b/lib/timegm.c
new file mode 100644
index 0000000..86bdac3
--- /dev/null
+++ b/lib/timegm.c
@@ -0,0 +1,38 @@
+/* Convert UTC calendar time to simple time. Like mktime but assumes UTC.
+
+ Copyright (C) 1994, 1997, 2003-2004, 2006-2007, 2009-2016 Free Software
+ Foundation, Inc. This file is part of the GNU C Library.
+
+ 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, 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _LIBC
+# include <config.h>
+#endif
+
+#include <time.h>
+
+#ifndef _LIBC
+# undef __gmtime_r
+# define __gmtime_r gmtime_r
+# define __mktime_internal mktime_internal
+# include "mktime-internal.h"
+#endif
+
+time_t
+timegm (struct tm *tmp)
+{
+ static time_t gmtime_offset;
+ tmp->tm_isdst = 0;
+ return __mktime_internal (tmp, __gmtime_r, &gmtime_offset);
+}
diff --git a/lib/timespec.c b/lib/timespec.c
new file mode 100644
index 0000000..2b6098e
--- /dev/null
+++ b/lib/timespec.c
@@ -0,0 +1,3 @@
+#include <config.h>
+#define _GL_TIMESPEC_INLINE _GL_EXTERN_INLINE
+#include "timespec.h"
diff --git a/lib/timespec.h b/lib/timespec.h
index cce2d66..601394b 100644
--- a/lib/timespec.h
+++ b/lib/timespec.h
@@ -1,11 +1,12 @@
/* timespec -- System time interface
- Copyright (C) 2000, 2002, 2004, 2005, 2007 Free Software Foundation, Inc.
+ Copyright (C) 2000, 2002, 2004-2005, 2007, 2009-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,25 +14,99 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#if ! defined TIMESPEC_H
# define TIMESPEC_H
# include <time.h>
+#ifndef _GL_INLINE_HEADER_BEGIN
+ #error "Please include config.h first."
+#endif
+_GL_INLINE_HEADER_BEGIN
+#ifndef _GL_TIMESPEC_INLINE
+# define _GL_TIMESPEC_INLINE _GL_INLINE
+#endif
+
+/* Resolution of timespec time stamps (in units per second), and log
+ base 10 of the resolution. */
+
+enum { TIMESPEC_RESOLUTION = 1000000000 };
+enum { LOG10_TIMESPEC_RESOLUTION = 9 };
+
+/* Return a timespec with seconds S and nanoseconds NS. */
+
+_GL_TIMESPEC_INLINE struct timespec
+make_timespec (time_t s, long int ns)
+{
+ struct timespec r;
+ r.tv_sec = s;
+ r.tv_nsec = ns;
+ return r;
+}
+
/* Return negative, zero, positive if A < B, A == B, A > B, respectively.
- Assume the nanosecond components are in range, or close to it. */
-static inline int
+
+ For each time stamp T, this code assumes that either:
+
+ * T.tv_nsec is in the range 0..999999999; or
+ * T.tv_sec corresponds to a valid leap second on a host that supports
+ leap seconds, and T.tv_nsec is in the range 1000000000..1999999999; or
+ * T.tv_sec is the minimum time_t value and T.tv_nsec is -1; or
+ T.tv_sec is the maximum time_t value and T.tv_nsec is 2000000000.
+ This allows for special struct timespec values that are less or
+ greater than all possible valid time stamps.
+
+ In all these cases, it is safe to subtract two tv_nsec values and
+ convert the result to integer without worrying about overflow on
+ any platform of interest to the GNU project, since all such
+ platforms have 32-bit int or wider.
+
+ Replacing "(int) (a.tv_nsec - b.tv_nsec)" with something like
+ "a.tv_nsec < b.tv_nsec ? -1 : a.tv_nsec > b.tv_nsec" would cause
+ this function to work in some cases where the above assumption is
+ violated, but not in all cases (e.g., a.tv_sec==1, a.tv_nsec==-2,
+ b.tv_sec==0, b.tv_nsec==999999999) and is arguably not worth the
+ extra instructions. Using a subtraction has the advantage of
+ detecting some invalid cases on platforms that detect integer
+ overflow.
+
+ The (int) cast avoids a gcc -Wconversion warning. */
+
+_GL_TIMESPEC_INLINE int _GL_ATTRIBUTE_PURE
timespec_cmp (struct timespec a, struct timespec b)
{
return (a.tv_sec < b.tv_sec ? -1
- : a.tv_sec > b.tv_sec ? 1
- : a.tv_nsec - b.tv_nsec);
+ : a.tv_sec > b.tv_sec ? 1
+ : (int) (a.tv_nsec - b.tv_nsec));
+}
+
+/* Return -1, 0, 1, depending on the sign of A. A.tv_nsec must be
+ nonnegative. */
+_GL_TIMESPEC_INLINE int _GL_ATTRIBUTE_PURE
+timespec_sign (struct timespec a)
+{
+ return a.tv_sec < 0 ? -1 : a.tv_sec || a.tv_nsec;
+}
+
+struct timespec timespec_add (struct timespec, struct timespec)
+ _GL_ATTRIBUTE_CONST;
+struct timespec timespec_sub (struct timespec, struct timespec)
+ _GL_ATTRIBUTE_CONST;
+struct timespec dtotimespec (double)
+ _GL_ATTRIBUTE_CONST;
+
+/* Return an approximation to A, of type 'double'. */
+_GL_TIMESPEC_INLINE double
+timespectod (struct timespec a)
+{
+ return a.tv_sec + a.tv_nsec / 1e9;
}
void gettime (struct timespec *);
int settime (struct timespec const *);
+_GL_INLINE_HEADER_END
+
#endif
diff --git a/lib/trim.c b/lib/trim.c
new file mode 100644
index 0000000..6f681a7
--- /dev/null
+++ b/lib/trim.c
@@ -0,0 +1,129 @@
+/* Removes leading and/or trailing whitespaces
+ Copyright (C) 2006-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Davide Angelocola <davide.angelocola@gmail.com> */
+
+#include <config.h>
+
+/* Specification. */
+#include "trim.h"
+
+#include <ctype.h>
+#include <string.h>
+#include <stddef.h>
+#include <stdlib.h>
+
+#include "mbchar.h"
+#include "mbiter.h"
+#include "xalloc.h"
+
+/* Use this to suppress gcc's "...may be used before initialized" warnings. */
+#ifdef lint
+# define IF_LINT(Code) Code
+#else
+# define IF_LINT(Code) /* empty */
+#endif
+
+char *
+trim2 (const char *s, int how)
+{
+ char *d;
+
+ d = strdup (s);
+
+ if (!d)
+ xalloc_die ();
+
+ if (MB_CUR_MAX > 1)
+ {
+ mbi_iterator_t i;
+
+ /* Trim leading whitespaces. */
+ if (how != TRIM_TRAILING)
+ {
+ mbi_init (i, d, strlen (d));
+
+ for (; mbi_avail (i) && mb_isspace (mbi_cur (i)); mbi_advance (i))
+ ;
+
+ memmove (d, mbi_cur_ptr (i), strlen (mbi_cur_ptr (i)) + 1);
+ }
+
+ /* Trim trailing whitespaces. */
+ if (how != TRIM_LEADING)
+ {
+ unsigned int state = 0;
+ char *r IF_LINT (= NULL); /* used only while state = 2 */
+
+ mbi_init (i, d, strlen (d));
+
+ for (; mbi_avail (i); mbi_advance (i))
+ {
+ if (state == 0 && mb_isspace (mbi_cur (i)))
+ continue;
+
+ if (state == 0 && !mb_isspace (mbi_cur (i)))
+ {
+ state = 1;
+ continue;
+ }
+
+ if (state == 1 && !mb_isspace (mbi_cur (i)))
+ continue;
+
+ if (state == 1 && mb_isspace (mbi_cur (i)))
+ {
+ state = 2;
+ r = (char *) mbi_cur_ptr (i);
+ }
+ else if (state == 2 && mb_isspace (mbi_cur (i)))
+ {
+ /* empty */
+ }
+ else
+ {
+ state = 1;
+ }
+ }
+
+ if (state == 2)
+ *r = '\0';
+ }
+ }
+ else
+ {
+ char *p;
+
+ /* Trim leading whitespaces. */
+ if (how != TRIM_TRAILING)
+ {
+ for (p = d; *p && isspace ((unsigned char) *p); p++)
+ ;
+
+ memmove (d, p, strlen (p) + 1);
+ }
+
+ /* Trim trailing whitespaces. */
+ if (how != TRIM_LEADING)
+ {
+ for (p = d + strlen (d) - 1;
+ p >= d && isspace ((unsigned char) *p); p--)
+ *p = '\0';
+ }
+ }
+
+ return d;
+}
diff --git a/lib/trim.h b/lib/trim.h
new file mode 100644
index 0000000..01c22f2
--- /dev/null
+++ b/lib/trim.h
@@ -0,0 +1,33 @@
+/* Removes leading and/or trailing whitespaces
+ Copyright (C) 2006, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Davide Angelocola <davide.angelocola@gmail.com> */
+
+/* Trim mode. */
+#define TRIM_TRAILING 0
+#define TRIM_LEADING 1
+#define TRIM_BOTH 2
+
+/* Removes trailing and leading whitespaces. */
+#define trim(s) trim2(s, TRIM_BOTH)
+
+/* Removes trailing whitespaces. */
+#define trim_trailing(s) trim2(s, TRIM_TRAILING)
+
+/* Removes leading whitespaces. */
+#define trim_leading(s) trim2(s, TRIM_LEADING)
+
+char *trim2 (const char *, int);
diff --git a/lib/u64.c b/lib/u64.c
new file mode 100644
index 0000000..1e3854d
--- /dev/null
+++ b/lib/u64.c
@@ -0,0 +1,4 @@
+#include <config.h>
+#define _GL_U64_INLINE _GL_EXTERN_INLINE
+#include "u64.h"
+typedef int dummy;
diff --git a/lib/u64.h b/lib/u64.h
index 1d581ec..1ece978 100644
--- a/lib/u64.h
+++ b/lib/u64.h
@@ -1,11 +1,11 @@
/* uint64_t-like operations that work even on hosts lacking uint64_t
- Copyright (C) 2006 Free Software Foundation, Inc.
+ Copyright (C) 2006, 2009-2016 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 2, or (at your option) any
- later version.
+ 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
@@ -13,14 +13,20 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
-#include <stddef.h>
#include <stdint.h>
+#ifndef _GL_INLINE_HEADER_BEGIN
+ #error "Please include config.h first."
+#endif
+_GL_INLINE_HEADER_BEGIN
+#ifndef _GL_U64_INLINE
+# define _GL_U64_INLINE _GL_INLINE
+#endif
+
/* Return X rotated left by N bits, where 0 < N < 64. */
#define u64rol(x, n) u64or (u64shl (x, n), u64shr (x, 64 - n))
@@ -32,6 +38,7 @@ typedef uint64_t u64;
# define u64hilo(hi, lo) ((u64) (((u64) (hi) << 32) + (lo)))
# define u64init(hi, lo) u64hilo (hi, lo)
# define u64lo(x) ((u64) (x))
+# define u64size(x) u64lo (x)
# define u64lt(x, y) ((x) < (y))
# define u64and(x, y) ((x) & (y))
# define u64or(x, y) ((x) | (y))
@@ -55,7 +62,7 @@ typedef struct { uint32_t lo, hi; } u64;
/* Given the high and low-order 32-bit quantities HI and LO, return a u64
value representing (HI << 32) + LO. */
-static inline u64
+_GL_U64_INLINE u64
u64hilo (uint32_t hi, uint32_t lo)
{
u64 r;
@@ -65,7 +72,7 @@ u64hilo (uint32_t hi, uint32_t lo)
}
/* Return a u64 value representing LO. */
-static inline u64
+_GL_U64_INLINE u64
u64lo (uint32_t lo)
{
u64 r;
@@ -74,15 +81,25 @@ u64lo (uint32_t lo)
return r;
}
+/* Return a u64 value representing SIZE. */
+_GL_U64_INLINE u64
+u64size (size_t size)
+{
+ u64 r;
+ r.hi = size >> 31 >> 1;
+ r.lo = size;
+ return r;
+}
+
/* Return X < Y. */
-static inline int
+_GL_U64_INLINE int
u64lt (u64 x, u64 y)
{
return x.hi < y.hi || (x.hi == y.hi && x.lo < y.lo);
}
/* Return X & Y. */
-static inline u64
+_GL_U64_INLINE u64
u64and (u64 x, u64 y)
{
u64 r;
@@ -92,7 +109,7 @@ u64and (u64 x, u64 y)
}
/* Return X | Y. */
-static inline u64
+_GL_U64_INLINE u64
u64or (u64 x, u64 y)
{
u64 r;
@@ -102,7 +119,7 @@ u64or (u64 x, u64 y)
}
/* Return X ^ Y. */
-static inline u64
+_GL_U64_INLINE u64
u64xor (u64 x, u64 y)
{
u64 r;
@@ -112,7 +129,7 @@ u64xor (u64 x, u64 y)
}
/* Return X + Y. */
-static inline u64
+_GL_U64_INLINE u64
u64plus (u64 x, u64 y)
{
u64 r;
@@ -122,7 +139,7 @@ u64plus (u64 x, u64 y)
}
/* Return X << N. */
-static inline u64
+_GL_U64_INLINE u64
u64shl (u64 x, int n)
{
u64 r;
@@ -140,7 +157,7 @@ u64shl (u64 x, int n)
}
/* Return X >> N. */
-static inline u64
+_GL_U64_INLINE u64
u64shr (u64 x, int n)
{
u64 r;
@@ -158,3 +175,5 @@ u64shr (u64 x, int n)
}
#endif
+
+_GL_INLINE_HEADER_END
diff --git a/lib/uinttostr.c b/lib/uinttostr.c
index 52d288e..48fd98f 100644
--- a/lib/uinttostr.c
+++ b/lib/uinttostr.c
@@ -1,3 +1,3 @@
-#define inttostr uinttostr
+#define anytostr uinttostr
#define inttype unsigned int
-#include "inttostr.c"
+#include "anytostr.c"
diff --git a/lib/umaxtostr.c b/lib/umaxtostr.c
index 4f49a7f..f95bfc3 100644
--- a/lib/umaxtostr.c
+++ b/lib/umaxtostr.c
@@ -1,3 +1,3 @@
-#define inttostr umaxtostr
+#define anytostr umaxtostr
#define inttype uintmax_t
-#include "inttostr.c"
+#include "anytostr.c"
diff --git a/lib/uname.c b/lib/uname.c
new file mode 100644
index 0000000..8fdb0fc
--- /dev/null
+++ b/lib/uname.c
@@ -0,0 +1,268 @@
+/* uname replacement.
+ Copyright (C) 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <sys/utsname.h>
+
+/* This file provides an implementation only for the native Windows API. */
+#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <windows.h>
+
+/* Mingw headers don't have all the platform codes. */
+#ifndef VER_PLATFORM_WIN32_CE
+# define VER_PLATFORM_WIN32_CE 3
+#endif
+
+/* Some headers don't have all the processor architecture codes. */
+#ifndef PROCESSOR_ARCHITECTURE_AMD64
+# define PROCESSOR_ARCHITECTURE_AMD64 9
+#endif
+#ifndef PROCESSOR_ARCHITECTURE_IA32_ON_WIN64
+# define PROCESSOR_ARCHITECTURE_IA32_ON_WIN64 10
+#endif
+
+/* Mingw headers don't have the latest processor codes. */
+#ifndef PROCESSOR_AMD_X8664
+# define PROCESSOR_AMD_X8664 8664
+#endif
+
+int
+uname (struct utsname *buf)
+{
+ OSVERSIONINFO version;
+ OSVERSIONINFOEX versionex;
+ BOOL have_versionex; /* indicates whether versionex is filled */
+ const char *super_version;
+
+ /* Preparation: Fill version and, if possible, also versionex.
+ But try to call GetVersionEx only once in the common case. */
+ versionex.dwOSVersionInfoSize = sizeof (OSVERSIONINFOEX);
+ have_versionex = GetVersionEx ((OSVERSIONINFO *) &versionex);
+ if (have_versionex)
+ {
+ /* We know that OSVERSIONINFO is a subset of OSVERSIONINFOEX. */
+ memcpy (&version, &versionex, sizeof (OSVERSIONINFO));
+ }
+ else
+ {
+ version.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
+ if (!GetVersionEx (&version))
+ abort ();
+ }
+
+ /* Fill in nodename. */
+ if (gethostname (buf->nodename, sizeof (buf->nodename)) < 0)
+ strcpy (buf->nodename, "localhost");
+
+ /* Determine major-major Windows version. */
+ if (version.dwPlatformId == VER_PLATFORM_WIN32_NT)
+ {
+ /* Windows NT or newer. */
+ super_version = "NT";
+ }
+ else if (version.dwPlatformId == VER_PLATFORM_WIN32_CE)
+ {
+ /* Windows CE or Embedded CE. */
+ super_version = "CE";
+ }
+ else if (version.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
+ {
+ /* Windows 95/98/ME. */
+ switch (version.dwMinorVersion)
+ {
+ case 0:
+ super_version = "95";
+ break;
+ case 10:
+ super_version = "98";
+ break;
+ case 90:
+ super_version = "ME";
+ break;
+ default:
+ super_version = "";
+ break;
+ }
+ }
+ else
+ super_version = "";
+
+ /* Fill in sysname. */
+#ifdef __MINGW32__
+ /* Returns a string compatible with the MSYS uname.exe program,
+ so that no further changes are needed to GNU config.guess.
+ For example,
+ $ ./uname.exe -s => MINGW32_NT-5.1
+ */
+ sprintf (buf->sysname, "MINGW32_%s-%u.%u", super_version,
+ (unsigned int) version.dwMajorVersion,
+ (unsigned int) version.dwMinorVersion);
+#else
+ sprintf (buf->sysname, "Windows%s", super_version);
+#endif
+
+ /* Fill in release, version. */
+ /* The MSYS uname.exe programs uses strings from a modified Cygwin runtime:
+ $ ./uname.exe -r => 1.0.11(0.46/3/2)
+ $ ./uname.exe -v => 2008-08-25 23:40
+ There is no point in imitating this behaviour. */
+ if (version.dwPlatformId == VER_PLATFORM_WIN32_NT)
+ {
+ /* Windows NT or newer. */
+ struct windows_version
+ {
+ int major;
+ int minor;
+ unsigned int server_offset;
+ const char *name;
+ };
+
+ /* Storing the workstation and server version names in a single
+ stream does not waste memory when they are the same. These
+ macros abstract the representation. VERSION1 is used if
+ version.wProductType does not matter, VERSION2 if it does. */
+ #define VERSION1(major, minor, name) \
+ { major, minor, 0, name }
+ #define VERSION2(major, minor, workstation, server) \
+ { major, minor, sizeof workstation, workstation "\0" server }
+ static const struct windows_version versions[] =
+ {
+ VERSION2 (3, -1, "Windows NT Workstation", "Windows NT Server"),
+ VERSION2 (4, -1, "Windows NT Workstation", "Windows NT Server"),
+ VERSION1 (5, 0, "Windows 2000"),
+ VERSION1 (5, 1, "Windows XP"),
+ VERSION1 (5, 2, "Windows Server 2003"),
+ VERSION2 (6, 0, "Windows Vista", "Windows Server 2008"),
+ VERSION2 (6, 1, "Windows 7", "Windows Server 2008 R2"),
+ VERSION2 (-1, -1, "Windows", "Windows Server")
+ };
+ const char *base;
+ const struct windows_version *v = versions;
+
+ /* Find a version that matches ours. The last element is a
+ wildcard that always ends the loop. */
+ while ((v->major != version.dwMajorVersion && v->major != -1)
+ || (v->minor != version.dwMinorVersion && v->minor != -1))
+ v++;
+
+ if (have_versionex && versionex.wProductType != VER_NT_WORKSTATION)
+ base = v->name + v->server_offset;
+ else
+ base = v->name;
+ if (v->major == -1 || v->minor == -1)
+ sprintf (buf->release, "%s %u.%u",
+ base,
+ (unsigned int) version.dwMajorVersion,
+ (unsigned int) version.dwMinorVersion);
+ else
+ strcpy (buf->release, base);
+ }
+ else if (version.dwPlatformId == VER_PLATFORM_WIN32_CE)
+ {
+ /* Windows CE or Embedded CE. */
+ sprintf (buf->release, "Windows CE %u.%u",
+ (unsigned int) version.dwMajorVersion,
+ (unsigned int) version.dwMinorVersion);
+ }
+ else
+ {
+ /* Windows 95/98/ME. */
+ sprintf (buf->release, "Windows %s", super_version);
+ }
+ strcpy (buf->version, version.szCSDVersion);
+
+ /* Fill in machine. */
+ {
+ SYSTEM_INFO info;
+
+ GetSystemInfo (&info);
+ /* Check for Windows NT or CE, since the info.wProcessorLevel is
+ garbage on Windows 95. */
+ if (version.dwPlatformId == VER_PLATFORM_WIN32_NT
+ || version.dwPlatformId == VER_PLATFORM_WIN32_CE)
+ {
+ /* Windows NT or newer, or Windows CE or Embedded CE. */
+ switch (info.wProcessorArchitecture)
+ {
+ case PROCESSOR_ARCHITECTURE_AMD64:
+ strcpy (buf->machine, "x86_64");
+ break;
+ case PROCESSOR_ARCHITECTURE_IA64:
+ strcpy (buf->machine, "ia64");
+ break;
+ case PROCESSOR_ARCHITECTURE_INTEL:
+ strcpy (buf->machine, "i386");
+ if (info.wProcessorLevel >= 3)
+ buf->machine[1] =
+ '0' + (info.wProcessorLevel <= 6 ? info.wProcessorLevel : 6);
+ break;
+ case PROCESSOR_ARCHITECTURE_IA32_ON_WIN64:
+ strcpy (buf->machine, "i686");
+ break;
+ case PROCESSOR_ARCHITECTURE_MIPS:
+ strcpy (buf->machine, "mips");
+ break;
+ case PROCESSOR_ARCHITECTURE_ALPHA:
+ case PROCESSOR_ARCHITECTURE_ALPHA64:
+ strcpy (buf->machine, "alpha");
+ break;
+ case PROCESSOR_ARCHITECTURE_PPC:
+ strcpy (buf->machine, "powerpc");
+ break;
+ case PROCESSOR_ARCHITECTURE_SHX:
+ strcpy (buf->machine, "sh");
+ break;
+ case PROCESSOR_ARCHITECTURE_ARM:
+ strcpy (buf->machine, "arm");
+ break;
+ default:
+ strcpy (buf->machine, "unknown");
+ break;
+ }
+ }
+ else
+ {
+ /* Windows 95/98/ME. */
+ switch (info.dwProcessorType)
+ {
+ case PROCESSOR_AMD_X8664:
+ strcpy (buf->machine, "x86_64");
+ break;
+ case PROCESSOR_INTEL_IA64:
+ strcpy (buf->machine, "ia64");
+ break;
+ default:
+ if (info.dwProcessorType % 100 == 86)
+ sprintf (buf->machine, "i%u",
+ (unsigned int) info.dwProcessorType);
+ else
+ strcpy (buf->machine, "unknown");
+ break;
+ }
+ }
+ }
+
+ return 0;
+}
+
+#endif
diff --git a/lib/unicodeio.c b/lib/unicodeio.c
index ceeff89..b2494ec 100644
--- a/lib/unicodeio.c
+++ b/lib/unicodeio.c
@@ -1,26 +1,22 @@
/* Unicode character output to streams with locale dependent encoding.
- Copyright (C) 2000-2003, 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2000-2003, 2006, 2008-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Bruno Haible <haible@clisp.cons.org>. */
-/* Note: This file requires the locale_charset() function. See in
- libiconv-1.8/libcharset/INTEGRATE for how to obtain it. */
-
#include <config.h>
/* Specification. */
@@ -40,17 +36,8 @@
#define _(msgid) gettext (msgid)
#define N_(msgid) msgid
-#ifndef __attribute__
-# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 8) || __STRICT_ANSI__
-# define __attribute__(x) /* empty */
-# endif
-#endif
-
-#ifndef ATTRIBUTE_UNUSED
-# define ATTRIBUTE_UNUSED __attribute__ ((__unused__))
-#endif
-
#include "localcharset.h"
+#include "unistr.h"
/* When we pass a Unicode character to iconv(), we must pass it in a
suitable encoding. The standardized Unicode encodings are
@@ -64,42 +51,6 @@
So we use UTF-8. It supports characters up to \U7FFFFFFF and is
unambiguously defined. */
-/* Stores the UTF-8 representation of the Unicode character wc in r[0..5].
- Returns the number of bytes stored, or -1 if wc is out of range. */
-static int
-utf8_wctomb (unsigned char *r, unsigned int wc)
-{
- int count;
-
- if (wc < 0x80)
- count = 1;
- else if (wc < 0x800)
- count = 2;
- else if (wc < 0x10000)
- count = 3;
- else if (wc < 0x200000)
- count = 4;
- else if (wc < 0x4000000)
- count = 5;
- else if (wc <= 0x7fffffff)
- count = 6;
- else
- return -1;
-
- switch (count)
- {
- /* Note: code falls through cases! */
- case 6: r[5] = 0x80 | (wc & 0x3f); wc = wc >> 6; wc |= 0x4000000;
- case 5: r[4] = 0x80 | (wc & 0x3f); wc = wc >> 6; wc |= 0x200000;
- case 4: r[3] = 0x80 | (wc & 0x3f); wc = wc >> 6; wc |= 0x10000;
- case 3: r[2] = 0x80 | (wc & 0x3f); wc = wc >> 6; wc |= 0x800;
- case 2: r[1] = 0x80 | (wc & 0x3f); wc = wc >> 6; wc |= 0xc0;
- case 1: r[0] = wc;
- }
-
- return count;
-}
-
/* Luckily, the encoding's name is platform independent. */
#define UTF8_NAME "UTF-8"
@@ -111,11 +62,11 @@ utf8_wctomb (unsigned char *r, unsigned int wc)
Assumes that the locale doesn't change between two calls. */
long
unicode_to_mb (unsigned int code,
- long (*success) (const char *buf, size_t buflen,
- void *callback_arg),
- long (*failure) (unsigned int code, const char *msg,
- void *callback_arg),
- void *callback_arg)
+ long (*success) (const char *buf, size_t buflen,
+ void *callback_arg),
+ long (*failure) (unsigned int code, const char *msg,
+ void *callback_arg),
+ void *callback_arg)
{
static int initialized;
static int is_utf8;
@@ -133,12 +84,12 @@ unicode_to_mb (unsigned int code,
is_utf8 = !strcmp (charset, UTF8_NAME);
#if HAVE_ICONV
if (!is_utf8)
- {
- utf8_to_local = iconv_open (charset, UTF8_NAME);
- if (utf8_to_local == (iconv_t)(-1))
- /* For an unknown encoding, assume ASCII. */
- utf8_to_local = iconv_open ("ASCII", UTF8_NAME);
- }
+ {
+ utf8_to_local = iconv_open (charset, UTF8_NAME);
+ if (utf8_to_local == (iconv_t)(-1))
+ /* For an unknown encoding, assume ASCII. */
+ utf8_to_local = iconv_open ("ASCII", UTF8_NAME);
+ }
#endif
initialized = 1;
}
@@ -148,14 +99,14 @@ unicode_to_mb (unsigned int code,
{
#if HAVE_ICONV
if (utf8_to_local == (iconv_t)(-1))
- return failure (code, N_("iconv function not usable"), callback_arg);
+ return failure (code, N_("iconv function not usable"), callback_arg);
#else
return failure (code, N_("iconv function not available"), callback_arg);
#endif
}
/* Convert the character to UTF-8. */
- count = utf8_wctomb ((unsigned char *) inbuf, code);
+ count = u8_uctomb ((unsigned char *) inbuf, code, sizeof (inbuf));
if (count < 0)
return failure (code, N_("character out of range"), callback_arg);
@@ -176,24 +127,26 @@ unicode_to_mb (unsigned int code,
/* Convert the character from UTF-8 to the locale's charset. */
res = iconv (utf8_to_local,
- (ICONV_CONST char **)&inptr, &inbytesleft,
- &outptr, &outbytesleft);
+ (ICONV_CONST char **)&inptr, &inbytesleft,
+ &outptr, &outbytesleft);
if (inbytesleft > 0 || res == (size_t)(-1)
- /* Irix iconv() inserts a NUL byte if it cannot convert. */
+ /* Irix iconv() inserts a NUL byte if it cannot convert. */
# if !defined _LIBICONV_VERSION && (defined sgi || defined __sgi)
- || (res > 0 && code != 0 && outptr - outbuf == 1 && *outbuf == '\0')
+ || (res > 0 && code != 0 && outptr - outbuf == 1 && *outbuf == '\0')
# endif
)
- return failure (code, NULL, callback_arg);
+ return failure (code, NULL, callback_arg);
/* Avoid glibc-2.1 bug and Solaris 7 bug. */
# if defined _LIBICONV_VERSION \
- || !((__GLIBC__ - 0 == 2 && __GLIBC_MINOR__ - 0 <= 1) || defined __sun)
+ || !(((__GLIBC__ - 0 == 2 && __GLIBC_MINOR__ - 0 <= 1) \
+ && !defined __UCLIBC__) \
+ || defined __sun)
/* Get back to the initial shift state. */
res = iconv (utf8_to_local, NULL, NULL, &outptr, &outbytesleft);
if (res == (size_t)(-1))
- return failure (code, NULL, callback_arg);
+ return failure (code, NULL, callback_arg);
# endif
return success (outbuf, outptr - outbuf, callback_arg);
@@ -211,6 +164,10 @@ fwrite_success_callback (const char *buf, size_t buflen, void *callback_arg)
{
FILE *stream = (FILE *) callback_arg;
+ /* The return value of fwrite can be ignored here, because under normal
+ conditions (STREAM is an open stream and not wide-character oriented)
+ when fwrite() returns a value != buflen it also sets STREAM's error
+ indicator. */
fwrite (buf, 1, buflen, stream);
return 0;
}
@@ -218,21 +175,22 @@ fwrite_success_callback (const char *buf, size_t buflen, void *callback_arg)
/* Simple failure callback that displays an error and exits. */
static long
exit_failure_callback (unsigned int code, const char *msg,
- void *callback_arg ATTRIBUTE_UNUSED)
+ void *callback_arg _GL_UNUSED)
{
if (msg == NULL)
error (1, 0, _("cannot convert U+%04X to local character set"), code);
else
error (1, 0, _("cannot convert U+%04X to local character set: %s"), code,
- gettext (msg));
+ gettext (msg));
return -1;
}
/* Simple failure callback that displays a fallback representation in plain
ASCII, using the same notation as ISO C99 strings. */
static long
-fallback_failure_callback (unsigned int code, const char *msg ATTRIBUTE_UNUSED
- , void *callback_arg)
+fallback_failure_callback (unsigned int code,
+ const char *msg _GL_UNUSED,
+ void *callback_arg)
{
FILE *stream = (FILE *) callback_arg;
@@ -250,8 +208,8 @@ void
print_unicode_char (FILE *stream, unsigned int code, int exit_on_error)
{
unicode_to_mb (code, fwrite_success_callback,
- exit_on_error
- ? exit_failure_callback
- : fallback_failure_callback,
- stream);
+ exit_on_error
+ ? exit_failure_callback
+ : fallback_failure_callback,
+ stream);
}
diff --git a/lib/unicodeio.h b/lib/unicodeio.h
index 9560f6e..64a3da2 100644
--- a/lib/unicodeio.h
+++ b/lib/unicodeio.h
@@ -1,20 +1,19 @@
/* Unicode character output to streams with locale dependent encoding.
- Copyright (C) 2000-2003, 2005 Free Software Foundation, Inc.
+ Copyright (C) 2000-2003, 2005, 2008-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifndef UNICODEIO_H
# define UNICODEIO_H
@@ -29,21 +28,21 @@
Returns whatever the callback returned.
Assumes that the locale doesn't change between two calls. */
extern long unicode_to_mb (unsigned int code,
- long (*success) (const char *buf, size_t buflen,
- void *callback_arg),
- long (*failure) (unsigned int code, const char *msg,
- void *callback_arg),
- void *callback_arg);
+ long (*success) (const char *buf, size_t buflen,
+ void *callback_arg),
+ long (*failure) (unsigned int code, const char *msg,
+ void *callback_arg),
+ void *callback_arg);
/* Outputs the Unicode character CODE to the output stream STREAM.
Upon failure, exit if exit_on_error is true, otherwise output a fallback
notation. */
extern void print_unicode_char (FILE *stream, unsigned int code,
- int exit_on_error);
+ int exit_on_error);
/* Simple success callback that outputs the converted string.
The STREAM is passed as callback_arg. */
extern long fwrite_success_callback (const char *buf, size_t buflen,
- void *callback_arg);
+ void *callback_arg);
#endif
diff --git a/lib/unistd--.h b/lib/unistd--.h
index 1fe6ce8..bd1d0fb 100644
--- a/lib/unistd--.h
+++ b/lib/unistd--.h
@@ -1,11 +1,11 @@
/* Like unistd.h, but redefine some names to avoid glitches.
- Copyright (C) 2005 Free Software Foundation, Inc.
+ Copyright (C) 2005, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
@@ -26,3 +25,8 @@
#undef pipe
#define pipe pipe_safer
+
+#if GNULIB_PIPE2_SAFER
+# undef pipe2
+# define pipe2 pipe2_safer
+#endif
diff --git a/lib/unistd-safer.h b/lib/unistd-safer.h
index f95999d..c8179ce 100644
--- a/lib/unistd-safer.h
+++ b/lib/unistd-safer.h
@@ -1,11 +1,11 @@
/* Invoke unistd-like functions, but avoid some glitches.
- Copyright (C) 2001, 2003, 2005 Free Software Foundation, Inc.
+ Copyright (C) 2001, 2003, 2005, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,11 +13,19 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
-/* Written by Paul Eggert. */
+/* Written by Paul Eggert and Eric Blake. */
int dup_safer (int);
int fd_safer (int);
int pipe_safer (int[2]);
+
+#if GNULIB_FD_SAFER_FLAG
+int dup_safer_flag (int, int);
+int fd_safer_flag (int, int);
+#endif
+
+#if GNULIB_PIPE2_SAFER
+int pipe2_safer (int[2], int);
+#endif
diff --git a/lib/unistd.c b/lib/unistd.c
new file mode 100644
index 0000000..72bad1c
--- /dev/null
+++ b/lib/unistd.c
@@ -0,0 +1,4 @@
+#include <config.h>
+#define _GL_UNISTD_INLINE _GL_EXTERN_INLINE
+#include "unistd.h"
+typedef int dummy;
diff --git a/lib/unistd.in.h b/lib/unistd.in.h
new file mode 100644
index 0000000..c3af07a
--- /dev/null
+++ b/lib/unistd.in.h
@@ -0,0 +1,1586 @@
+/* Substitute for and wrapper around <unistd.h>.
+ Copyright (C) 2003-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _@GUARD_PREFIX@_UNISTD_H
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+#ifdef _GL_INCLUDING_UNISTD_H
+/* Special invocation convention:
+ - On Mac OS X 10.3.9 we have a sequence of nested includes
+ <unistd.h> -> <signal.h> -> <pthread.h> -> <unistd.h>
+ In this situation, the functions are not yet declared, therefore we cannot
+ provide the C++ aliases. */
+
+#@INCLUDE_NEXT@ @NEXT_UNISTD_H@
+
+#else
+/* Normal invocation convention. */
+
+/* The include_next requires a split double-inclusion guard. */
+#if @HAVE_UNISTD_H@
+# define _GL_INCLUDING_UNISTD_H
+# @INCLUDE_NEXT@ @NEXT_UNISTD_H@
+# undef _GL_INCLUDING_UNISTD_H
+#endif
+
+/* Get all possible declarations of gethostname(). */
+#if @GNULIB_GETHOSTNAME@ && @UNISTD_H_HAVE_WINSOCK2_H@ \
+ && !defined _GL_INCLUDING_WINSOCK2_H
+# define _GL_INCLUDING_WINSOCK2_H
+# include <winsock2.h>
+# undef _GL_INCLUDING_WINSOCK2_H
+#endif
+
+#if !defined _@GUARD_PREFIX@_UNISTD_H && !defined _GL_INCLUDING_WINSOCK2_H
+#define _@GUARD_PREFIX@_UNISTD_H
+
+/* NetBSD 5.0 mis-defines NULL. Also get size_t. */
+#include <stddef.h>
+
+/* mingw doesn't define the SEEK_* or *_FILENO macros in <unistd.h>. */
+/* Cygwin 1.7.1 declares symlinkat in <stdio.h>, not in <unistd.h>. */
+/* But avoid namespace pollution on glibc systems. */
+#if (!(defined SEEK_CUR && defined SEEK_END && defined SEEK_SET) \
+ || ((@GNULIB_SYMLINKAT@ || defined GNULIB_POSIXCHECK) \
+ && defined __CYGWIN__)) \
+ && ! defined __GLIBC__
+# include <stdio.h>
+#endif
+
+/* Cygwin 1.7.1 declares unlinkat in <fcntl.h>, not in <unistd.h>. */
+/* But avoid namespace pollution on glibc systems. */
+#if (@GNULIB_UNLINKAT@ || defined GNULIB_POSIXCHECK) && defined __CYGWIN__ \
+ && ! defined __GLIBC__
+# include <fcntl.h>
+#endif
+
+/* mingw fails to declare _exit in <unistd.h>. */
+/* mingw, MSVC, BeOS, Haiku declare environ in <stdlib.h>, not in
+ <unistd.h>. */
+/* Solaris declares getcwd not only in <unistd.h> but also in <stdlib.h>. */
+/* OSF Tru64 Unix cannot see gnulib rpl_strtod when system <stdlib.h> is
+ included here. */
+/* But avoid namespace pollution on glibc systems. */
+#if !defined __GLIBC__ && !defined __osf__
+# define __need_system_stdlib_h
+# include <stdlib.h>
+# undef __need_system_stdlib_h
+#endif
+
+/* Native Windows platforms declare chdir, getcwd, rmdir in
+ <io.h> and/or <direct.h>, not in <unistd.h>.
+ They also declare access(), chmod(), close(), dup(), dup2(), isatty(),
+ lseek(), read(), unlink(), write() in <io.h>. */
+#if ((@GNULIB_CHDIR@ || @GNULIB_GETCWD@ || @GNULIB_RMDIR@ \
+ || defined GNULIB_POSIXCHECK) \
+ && ((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__))
+# include <io.h> /* mingw32, mingw64 */
+# include <direct.h> /* mingw64, MSVC 9 */
+#elif (@GNULIB_CLOSE@ || @GNULIB_DUP@ || @GNULIB_DUP2@ || @GNULIB_ISATTY@ \
+ || @GNULIB_LSEEK@ || @GNULIB_READ@ || @GNULIB_UNLINK@ || @GNULIB_WRITE@ \
+ || defined GNULIB_POSIXCHECK) \
+ && ((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__)
+# include <io.h>
+#endif
+
+/* AIX and OSF/1 5.1 declare getdomainname in <netdb.h>, not in <unistd.h>.
+ NonStop Kernel declares gethostname in <netdb.h>, not in <unistd.h>. */
+/* But avoid namespace pollution on glibc systems. */
+#if ((@GNULIB_GETDOMAINNAME@ && (defined _AIX || defined __osf__)) \
+ || (@GNULIB_GETHOSTNAME@ && defined __TANDEM)) \
+ && !defined __GLIBC__
+# include <netdb.h>
+#endif
+
+/* MSVC defines off_t in <sys/types.h>.
+ May also define off_t to a 64-bit type on native Windows. */
+#if !@HAVE_UNISTD_H@ || @WINDOWS_64_BIT_OFF_T@
+/* Get off_t. */
+# include <sys/types.h>
+#endif
+
+#if (@GNULIB_READ@ || @GNULIB_WRITE@ \
+ || @GNULIB_READLINK@ || @GNULIB_READLINKAT@ \
+ || @GNULIB_PREAD@ || @GNULIB_PWRITE@ || defined GNULIB_POSIXCHECK)
+/* Get ssize_t. */
+# include <sys/types.h>
+#endif
+
+/* Get getopt(), optarg, optind, opterr, optopt.
+ But avoid namespace pollution on glibc systems. */
+#if @GNULIB_UNISTD_H_GETOPT@ && !defined __GLIBC__ && !defined _GL_SYSTEM_GETOPT
+# define __need_getopt
+# include <getopt.h>
+#endif
+
+#ifndef _GL_INLINE_HEADER_BEGIN
+ #error "Please include config.h first."
+#endif
+_GL_INLINE_HEADER_BEGIN
+#ifndef _GL_UNISTD_INLINE
+# define _GL_UNISTD_INLINE _GL_INLINE
+#endif
+
+/* The definitions of _GL_FUNCDECL_RPL etc. are copied here. */
+
+/* The definition of _GL_ARG_NONNULL is copied here. */
+
+/* The definition of _GL_WARN_ON_USE is copied here. */
+
+
+/* Hide some function declarations from <winsock2.h>. */
+
+#if @GNULIB_GETHOSTNAME@ && @UNISTD_H_HAVE_WINSOCK2_H@
+# if !defined _@GUARD_PREFIX@_SYS_SOCKET_H
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef socket
+# define socket socket_used_without_including_sys_socket_h
+# undef connect
+# define connect connect_used_without_including_sys_socket_h
+# undef accept
+# define accept accept_used_without_including_sys_socket_h
+# undef bind
+# define bind bind_used_without_including_sys_socket_h
+# undef getpeername
+# define getpeername getpeername_used_without_including_sys_socket_h
+# undef getsockname
+# define getsockname getsockname_used_without_including_sys_socket_h
+# undef getsockopt
+# define getsockopt getsockopt_used_without_including_sys_socket_h
+# undef listen
+# define listen listen_used_without_including_sys_socket_h
+# undef recv
+# define recv recv_used_without_including_sys_socket_h
+# undef send
+# define send send_used_without_including_sys_socket_h
+# undef recvfrom
+# define recvfrom recvfrom_used_without_including_sys_socket_h
+# undef sendto
+# define sendto sendto_used_without_including_sys_socket_h
+# undef setsockopt
+# define setsockopt setsockopt_used_without_including_sys_socket_h
+# undef shutdown
+# define shutdown shutdown_used_without_including_sys_socket_h
+# else
+ _GL_WARN_ON_USE (socket,
+ "socket() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (connect,
+ "connect() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (accept,
+ "accept() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (bind,
+ "bind() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (getpeername,
+ "getpeername() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (getsockname,
+ "getsockname() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (getsockopt,
+ "getsockopt() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (listen,
+ "listen() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (recv,
+ "recv() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (send,
+ "send() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (recvfrom,
+ "recvfrom() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (sendto,
+ "sendto() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (setsockopt,
+ "setsockopt() used without including <sys/socket.h>");
+ _GL_WARN_ON_USE (shutdown,
+ "shutdown() used without including <sys/socket.h>");
+# endif
+# endif
+# if !defined _@GUARD_PREFIX@_SYS_SELECT_H
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef select
+# define select select_used_without_including_sys_select_h
+# else
+ _GL_WARN_ON_USE (select,
+ "select() used without including <sys/select.h>");
+# endif
+# endif
+#endif
+
+
+/* OS/2 EMX lacks these macros. */
+#ifndef STDIN_FILENO
+# define STDIN_FILENO 0
+#endif
+#ifndef STDOUT_FILENO
+# define STDOUT_FILENO 1
+#endif
+#ifndef STDERR_FILENO
+# define STDERR_FILENO 2
+#endif
+
+/* Ensure *_OK macros exist. */
+#ifndef F_OK
+# define F_OK 0
+# define X_OK 1
+# define W_OK 2
+# define R_OK 4
+#endif
+
+
+/* Declare overridden functions. */
+
+
+#if defined GNULIB_POSIXCHECK
+/* The access() function is a security risk. */
+_GL_WARN_ON_USE (access, "the access function is a security risk - "
+ "use the gnulib module faccessat instead");
+#endif
+
+
+#if @GNULIB_CHDIR@
+_GL_CXXALIAS_SYS (chdir, int, (const char *file) _GL_ARG_NONNULL ((1)));
+_GL_CXXALIASWARN (chdir);
+#elif defined GNULIB_POSIXCHECK
+# undef chdir
+# if HAVE_RAW_DECL_CHDIR
+_GL_WARN_ON_USE (chown, "chdir is not always in <unistd.h> - "
+ "use gnulib module chdir for portability");
+# endif
+#endif
+
+
+#if @GNULIB_CHOWN@
+/* Change the owner of FILE to UID (if UID is not -1) and the group of FILE
+ to GID (if GID is not -1). Follow symbolic links.
+ Return 0 if successful, otherwise -1 and errno set.
+ See the POSIX:2008 specification
+ <http://pubs.opengroup.org/onlinepubs/9699919799/functions/chown.html. */
+# if @REPLACE_CHOWN@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef chown
+# define chown rpl_chown
+# endif
+_GL_FUNCDECL_RPL (chown, int, (const char *file, uid_t uid, gid_t gid)
+ _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (chown, int, (const char *file, uid_t uid, gid_t gid));
+# else
+# if !@HAVE_CHOWN@
+_GL_FUNCDECL_SYS (chown, int, (const char *file, uid_t uid, gid_t gid)
+ _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (chown, int, (const char *file, uid_t uid, gid_t gid));
+# endif
+_GL_CXXALIASWARN (chown);
+#elif defined GNULIB_POSIXCHECK
+# undef chown
+# if HAVE_RAW_DECL_CHOWN
+_GL_WARN_ON_USE (chown, "chown fails to follow symlinks on some systems and "
+ "doesn't treat a uid or gid of -1 on some systems - "
+ "use gnulib module chown for portability");
+# endif
+#endif
+
+
+#if @GNULIB_CLOSE@
+# if @REPLACE_CLOSE@
+/* Automatically included by modules that need a replacement for close. */
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef close
+# define close rpl_close
+# endif
+_GL_FUNCDECL_RPL (close, int, (int fd));
+_GL_CXXALIAS_RPL (close, int, (int fd));
+# else
+_GL_CXXALIAS_SYS (close, int, (int fd));
+# endif
+_GL_CXXALIASWARN (close);
+#elif @UNISTD_H_HAVE_WINSOCK2_H_AND_USE_SOCKETS@
+# undef close
+# define close close_used_without_requesting_gnulib_module_close
+#elif defined GNULIB_POSIXCHECK
+# undef close
+/* Assume close is always declared. */
+_GL_WARN_ON_USE (close, "close does not portably work on sockets - "
+ "use gnulib module close for portability");
+#endif
+
+
+#if @GNULIB_DUP@
+# if @REPLACE_DUP@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define dup rpl_dup
+# endif
+_GL_FUNCDECL_RPL (dup, int, (int oldfd));
+_GL_CXXALIAS_RPL (dup, int, (int oldfd));
+# else
+_GL_CXXALIAS_SYS (dup, int, (int oldfd));
+# endif
+_GL_CXXALIASWARN (dup);
+#elif defined GNULIB_POSIXCHECK
+# undef dup
+# if HAVE_RAW_DECL_DUP
+_GL_WARN_ON_USE (dup, "dup is unportable - "
+ "use gnulib module dup for portability");
+# endif
+#endif
+
+
+#if @GNULIB_DUP2@
+/* Copy the file descriptor OLDFD into file descriptor NEWFD. Do nothing if
+ NEWFD = OLDFD, otherwise close NEWFD first if it is open.
+ Return newfd if successful, otherwise -1 and errno set.
+ See the POSIX:2008 specification
+ <http://pubs.opengroup.org/onlinepubs/9699919799/functions/dup2.html>. */
+# if @REPLACE_DUP2@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define dup2 rpl_dup2
+# endif
+_GL_FUNCDECL_RPL (dup2, int, (int oldfd, int newfd));
+_GL_CXXALIAS_RPL (dup2, int, (int oldfd, int newfd));
+# else
+# if !@HAVE_DUP2@
+_GL_FUNCDECL_SYS (dup2, int, (int oldfd, int newfd));
+# endif
+_GL_CXXALIAS_SYS (dup2, int, (int oldfd, int newfd));
+# endif
+_GL_CXXALIASWARN (dup2);
+#elif defined GNULIB_POSIXCHECK
+# undef dup2
+# if HAVE_RAW_DECL_DUP2
+_GL_WARN_ON_USE (dup2, "dup2 is unportable - "
+ "use gnulib module dup2 for portability");
+# endif
+#endif
+
+
+#if @GNULIB_DUP3@
+/* Copy the file descriptor OLDFD into file descriptor NEWFD, with the
+ specified flags.
+ The flags are a bitmask, possibly including O_CLOEXEC (defined in <fcntl.h>)
+ and O_TEXT, O_BINARY (defined in "binary-io.h").
+ Close NEWFD first if it is open.
+ Return newfd if successful, otherwise -1 and errno set.
+ See the Linux man page at
+ <http://www.kernel.org/doc/man-pages/online/pages/man2/dup3.2.html>. */
+# if @HAVE_DUP3@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define dup3 rpl_dup3
+# endif
+_GL_FUNCDECL_RPL (dup3, int, (int oldfd, int newfd, int flags));
+_GL_CXXALIAS_RPL (dup3, int, (int oldfd, int newfd, int flags));
+# else
+_GL_FUNCDECL_SYS (dup3, int, (int oldfd, int newfd, int flags));
+_GL_CXXALIAS_SYS (dup3, int, (int oldfd, int newfd, int flags));
+# endif
+_GL_CXXALIASWARN (dup3);
+#elif defined GNULIB_POSIXCHECK
+# undef dup3
+# if HAVE_RAW_DECL_DUP3
+_GL_WARN_ON_USE (dup3, "dup3 is unportable - "
+ "use gnulib module dup3 for portability");
+# endif
+#endif
+
+
+#if @GNULIB_ENVIRON@
+# if !@HAVE_DECL_ENVIRON@
+/* Set of environment variables and values. An array of strings of the form
+ "VARIABLE=VALUE", terminated with a NULL. */
+# if defined __APPLE__ && defined __MACH__
+# include <TargetConditionals.h>
+# if !TARGET_OS_IPHONE && !TARGET_IPHONE_SIMULATOR
+# define _GL_USE_CRT_EXTERNS
+# endif
+# endif
+# ifdef _GL_USE_CRT_EXTERNS
+# include <crt_externs.h>
+# define environ (*_NSGetEnviron ())
+# else
+# ifdef __cplusplus
+extern "C" {
+# endif
+extern char **environ;
+# ifdef __cplusplus
+}
+# endif
+# endif
+# endif
+#elif defined GNULIB_POSIXCHECK
+# if HAVE_RAW_DECL_ENVIRON
+_GL_UNISTD_INLINE char ***
+rpl_environ (void)
+{
+ return &environ;
+}
+_GL_WARN_ON_USE (rpl_environ, "environ is unportable - "
+ "use gnulib module environ for portability");
+# undef environ
+# define environ (*rpl_environ ())
+# endif
+#endif
+
+
+#if @GNULIB_EUIDACCESS@
+/* Like access(), except that it uses the effective user id and group id of
+ the current process. */
+# if !@HAVE_EUIDACCESS@
+_GL_FUNCDECL_SYS (euidaccess, int, (const char *filename, int mode)
+ _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (euidaccess, int, (const char *filename, int mode));
+_GL_CXXALIASWARN (euidaccess);
+# if defined GNULIB_POSIXCHECK
+/* Like access(), this function is a security risk. */
+_GL_WARN_ON_USE (euidaccess, "the euidaccess function is a security risk - "
+ "use the gnulib module faccessat instead");
+# endif
+#elif defined GNULIB_POSIXCHECK
+# undef euidaccess
+# if HAVE_RAW_DECL_EUIDACCESS
+_GL_WARN_ON_USE (euidaccess, "euidaccess is unportable - "
+ "use gnulib module euidaccess for portability");
+# endif
+#endif
+
+
+#if @GNULIB_FACCESSAT@
+# if !@HAVE_FACCESSAT@
+_GL_FUNCDECL_SYS (faccessat, int,
+ (int fd, char const *file, int mode, int flag)
+ _GL_ARG_NONNULL ((2)));
+# endif
+_GL_CXXALIAS_SYS (faccessat, int,
+ (int fd, char const *file, int mode, int flag));
+_GL_CXXALIASWARN (faccessat);
+#elif defined GNULIB_POSIXCHECK
+# undef faccessat
+# if HAVE_RAW_DECL_FACCESSAT
+_GL_WARN_ON_USE (faccessat, "faccessat is not portable - "
+ "use gnulib module faccessat for portability");
+# endif
+#endif
+
+
+#if @GNULIB_FCHDIR@
+/* Change the process' current working directory to the directory on which
+ the given file descriptor is open.
+ Return 0 if successful, otherwise -1 and errno set.
+ See the POSIX:2008 specification
+ <http://pubs.opengroup.org/onlinepubs/9699919799/functions/fchdir.html>. */
+# if ! @HAVE_FCHDIR@
+_GL_FUNCDECL_SYS (fchdir, int, (int /*fd*/));
+
+/* Gnulib internal hooks needed to maintain the fchdir metadata. */
+_GL_EXTERN_C int _gl_register_fd (int fd, const char *filename)
+ _GL_ARG_NONNULL ((2));
+_GL_EXTERN_C void _gl_unregister_fd (int fd);
+_GL_EXTERN_C int _gl_register_dup (int oldfd, int newfd);
+_GL_EXTERN_C const char *_gl_directory_name (int fd);
+
+# else
+# if !@HAVE_DECL_FCHDIR@
+_GL_FUNCDECL_SYS (fchdir, int, (int /*fd*/));
+# endif
+# endif
+_GL_CXXALIAS_SYS (fchdir, int, (int /*fd*/));
+_GL_CXXALIASWARN (fchdir);
+#elif defined GNULIB_POSIXCHECK
+# undef fchdir
+# if HAVE_RAW_DECL_FCHDIR
+_GL_WARN_ON_USE (fchdir, "fchdir is unportable - "
+ "use gnulib module fchdir for portability");
+# endif
+#endif
+
+
+#if @GNULIB_FCHOWNAT@
+# if @REPLACE_FCHOWNAT@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef fchownat
+# define fchownat rpl_fchownat
+# endif
+_GL_FUNCDECL_RPL (fchownat, int, (int fd, char const *file,
+ uid_t owner, gid_t group, int flag)
+ _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_RPL (fchownat, int, (int fd, char const *file,
+ uid_t owner, gid_t group, int flag));
+# else
+# if !@HAVE_FCHOWNAT@
+_GL_FUNCDECL_SYS (fchownat, int, (int fd, char const *file,
+ uid_t owner, gid_t group, int flag)
+ _GL_ARG_NONNULL ((2)));
+# endif
+_GL_CXXALIAS_SYS (fchownat, int, (int fd, char const *file,
+ uid_t owner, gid_t group, int flag));
+# endif
+_GL_CXXALIASWARN (fchownat);
+#elif defined GNULIB_POSIXCHECK
+# undef fchownat
+# if HAVE_RAW_DECL_FCHOWNAT
+_GL_WARN_ON_USE (fchownat, "fchownat is not portable - "
+ "use gnulib module openat for portability");
+# endif
+#endif
+
+
+#if @GNULIB_FDATASYNC@
+/* Synchronize changes to a file.
+ Return 0 if successful, otherwise -1 and errno set.
+ See POSIX:2008 specification
+ <http://pubs.opengroup.org/onlinepubs/9699919799/functions/fdatasync.html>. */
+# if !@HAVE_FDATASYNC@ || !@HAVE_DECL_FDATASYNC@
+_GL_FUNCDECL_SYS (fdatasync, int, (int fd));
+# endif
+_GL_CXXALIAS_SYS (fdatasync, int, (int fd));
+_GL_CXXALIASWARN (fdatasync);
+#elif defined GNULIB_POSIXCHECK
+# undef fdatasync
+# if HAVE_RAW_DECL_FDATASYNC
+_GL_WARN_ON_USE (fdatasync, "fdatasync is unportable - "
+ "use gnulib module fdatasync for portability");
+# endif
+#endif
+
+
+#if @GNULIB_FSYNC@
+/* Synchronize changes, including metadata, to a file.
+ Return 0 if successful, otherwise -1 and errno set.
+ See POSIX:2008 specification
+ <http://pubs.opengroup.org/onlinepubs/9699919799/functions/fsync.html>. */
+# if !@HAVE_FSYNC@
+_GL_FUNCDECL_SYS (fsync, int, (int fd));
+# endif
+_GL_CXXALIAS_SYS (fsync, int, (int fd));
+_GL_CXXALIASWARN (fsync);
+#elif defined GNULIB_POSIXCHECK
+# undef fsync
+# if HAVE_RAW_DECL_FSYNC
+_GL_WARN_ON_USE (fsync, "fsync is unportable - "
+ "use gnulib module fsync for portability");
+# endif
+#endif
+
+
+#if @GNULIB_FTRUNCATE@
+/* Change the size of the file to which FD is opened to become equal to LENGTH.
+ Return 0 if successful, otherwise -1 and errno set.
+ See the POSIX:2008 specification
+ <http://pubs.opengroup.org/onlinepubs/9699919799/functions/ftruncate.html>. */
+# if @REPLACE_FTRUNCATE@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef ftruncate
+# define ftruncate rpl_ftruncate
+# endif
+_GL_FUNCDECL_RPL (ftruncate, int, (int fd, off_t length));
+_GL_CXXALIAS_RPL (ftruncate, int, (int fd, off_t length));
+# else
+# if !@HAVE_FTRUNCATE@
+_GL_FUNCDECL_SYS (ftruncate, int, (int fd, off_t length));
+# endif
+_GL_CXXALIAS_SYS (ftruncate, int, (int fd, off_t length));
+# endif
+_GL_CXXALIASWARN (ftruncate);
+#elif defined GNULIB_POSIXCHECK
+# undef ftruncate
+# if HAVE_RAW_DECL_FTRUNCATE
+_GL_WARN_ON_USE (ftruncate, "ftruncate is unportable - "
+ "use gnulib module ftruncate for portability");
+# endif
+#endif
+
+
+#if @GNULIB_GETCWD@
+/* Get the name of the current working directory, and put it in SIZE bytes
+ of BUF.
+ Return BUF if successful, or NULL if the directory couldn't be determined
+ or SIZE was too small.
+ See the POSIX:2008 specification
+ <http://pubs.opengroup.org/onlinepubs/9699919799/functions/getcwd.html>.
+ Additionally, the gnulib module 'getcwd' guarantees the following GNU
+ extension: If BUF is NULL, an array is allocated with 'malloc'; the array
+ is SIZE bytes long, unless SIZE == 0, in which case it is as big as
+ necessary. */
+# if @REPLACE_GETCWD@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define getcwd rpl_getcwd
+# endif
+_GL_FUNCDECL_RPL (getcwd, char *, (char *buf, size_t size));
+_GL_CXXALIAS_RPL (getcwd, char *, (char *buf, size_t size));
+# else
+/* Need to cast, because on mingw, the second parameter is
+ int size. */
+_GL_CXXALIAS_SYS_CAST (getcwd, char *, (char *buf, size_t size));
+# endif
+_GL_CXXALIASWARN (getcwd);
+#elif defined GNULIB_POSIXCHECK
+# undef getcwd
+# if HAVE_RAW_DECL_GETCWD
+_GL_WARN_ON_USE (getcwd, "getcwd is unportable - "
+ "use gnulib module getcwd for portability");
+# endif
+#endif
+
+
+#if @GNULIB_GETDOMAINNAME@
+/* Return the NIS domain name of the machine.
+ WARNING! The NIS domain name is unrelated to the fully qualified host name
+ of the machine. It is also unrelated to email addresses.
+ WARNING! The NIS domain name is usually the empty string or "(none)" when
+ not using NIS.
+
+ Put up to LEN bytes of the NIS domain name into NAME.
+ Null terminate it if the name is shorter than LEN.
+ If the NIS domain name is longer than LEN, set errno = EINVAL and return -1.
+ Return 0 if successful, otherwise set errno and return -1. */
+# if @REPLACE_GETDOMAINNAME@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef getdomainname
+# define getdomainname rpl_getdomainname
+# endif
+_GL_FUNCDECL_RPL (getdomainname, int, (char *name, size_t len)
+ _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (getdomainname, int, (char *name, size_t len));
+# else
+# if !@HAVE_DECL_GETDOMAINNAME@
+_GL_FUNCDECL_SYS (getdomainname, int, (char *name, size_t len)
+ _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (getdomainname, int, (char *name, size_t len));
+# endif
+_GL_CXXALIASWARN (getdomainname);
+#elif defined GNULIB_POSIXCHECK
+# undef getdomainname
+# if HAVE_RAW_DECL_GETDOMAINNAME
+_GL_WARN_ON_USE (getdomainname, "getdomainname is unportable - "
+ "use gnulib module getdomainname for portability");
+# endif
+#endif
+
+
+#if @GNULIB_GETDTABLESIZE@
+/* Return the maximum number of file descriptors in the current process.
+ In POSIX, this is same as sysconf (_SC_OPEN_MAX). */
+# if @REPLACE_GETDTABLESIZE@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef getdtablesize
+# define getdtablesize rpl_getdtablesize
+# endif
+_GL_FUNCDECL_RPL (getdtablesize, int, (void));
+_GL_CXXALIAS_RPL (getdtablesize, int, (void));
+# else
+# if !@HAVE_GETDTABLESIZE@
+_GL_FUNCDECL_SYS (getdtablesize, int, (void));
+# endif
+_GL_CXXALIAS_SYS (getdtablesize, int, (void));
+# endif
+_GL_CXXALIASWARN (getdtablesize);
+#elif defined GNULIB_POSIXCHECK
+# undef getdtablesize
+# if HAVE_RAW_DECL_GETDTABLESIZE
+_GL_WARN_ON_USE (getdtablesize, "getdtablesize is unportable - "
+ "use gnulib module getdtablesize for portability");
+# endif
+#endif
+
+
+#if @GNULIB_GETGROUPS@
+/* Return the supplemental groups that the current process belongs to.
+ It is unspecified whether the effective group id is in the list.
+ If N is 0, return the group count; otherwise, N describes how many
+ entries are available in GROUPS. Return -1 and set errno if N is
+ not 0 and not large enough. Fails with ENOSYS on some systems. */
+# if @REPLACE_GETGROUPS@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef getgroups
+# define getgroups rpl_getgroups
+# endif
+_GL_FUNCDECL_RPL (getgroups, int, (int n, gid_t *groups));
+_GL_CXXALIAS_RPL (getgroups, int, (int n, gid_t *groups));
+# else
+# if !@HAVE_GETGROUPS@
+_GL_FUNCDECL_SYS (getgroups, int, (int n, gid_t *groups));
+# endif
+_GL_CXXALIAS_SYS (getgroups, int, (int n, gid_t *groups));
+# endif
+_GL_CXXALIASWARN (getgroups);
+#elif defined GNULIB_POSIXCHECK
+# undef getgroups
+# if HAVE_RAW_DECL_GETGROUPS
+_GL_WARN_ON_USE (getgroups, "getgroups is unportable - "
+ "use gnulib module getgroups for portability");
+# endif
+#endif
+
+
+#if @GNULIB_GETHOSTNAME@
+/* Return the standard host name of the machine.
+ WARNING! The host name may or may not be fully qualified.
+
+ Put up to LEN bytes of the host name into NAME.
+ Null terminate it if the name is shorter than LEN.
+ If the host name is longer than LEN, set errno = EINVAL and return -1.
+ Return 0 if successful, otherwise set errno and return -1. */
+# if @UNISTD_H_HAVE_WINSOCK2_H@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef gethostname
+# define gethostname rpl_gethostname
+# endif
+_GL_FUNCDECL_RPL (gethostname, int, (char *name, size_t len)
+ _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (gethostname, int, (char *name, size_t len));
+# else
+# if !@HAVE_GETHOSTNAME@
+_GL_FUNCDECL_SYS (gethostname, int, (char *name, size_t len)
+ _GL_ARG_NONNULL ((1)));
+# endif
+/* Need to cast, because on Solaris 10 and OSF/1 5.1 systems, the second
+ parameter is
+ int len. */
+_GL_CXXALIAS_SYS_CAST (gethostname, int, (char *name, size_t len));
+# endif
+_GL_CXXALIASWARN (gethostname);
+#elif @UNISTD_H_HAVE_WINSOCK2_H@
+# undef gethostname
+# define gethostname gethostname_used_without_requesting_gnulib_module_gethostname
+#elif defined GNULIB_POSIXCHECK
+# undef gethostname
+# if HAVE_RAW_DECL_GETHOSTNAME
+_GL_WARN_ON_USE (gethostname, "gethostname is unportable - "
+ "use gnulib module gethostname for portability");
+# endif
+#endif
+
+
+#if @GNULIB_GETLOGIN@
+/* Returns the user's login name, or NULL if it cannot be found. Upon error,
+ returns NULL with errno set.
+
+ See <http://www.opengroup.org/susv3xsh/getlogin.html>.
+
+ Most programs don't need to use this function, because the information is
+ available through environment variables:
+ ${LOGNAME-$USER} on Unix platforms,
+ $USERNAME on native Windows platforms.
+ */
+# if !@HAVE_GETLOGIN@
+_GL_FUNCDECL_SYS (getlogin, char *, (void));
+# endif
+_GL_CXXALIAS_SYS (getlogin, char *, (void));
+_GL_CXXALIASWARN (getlogin);
+#elif defined GNULIB_POSIXCHECK
+# undef getlogin
+# if HAVE_RAW_DECL_GETLOGIN
+_GL_WARN_ON_USE (getlogin, "getlogin is unportable - "
+ "use gnulib module getlogin for portability");
+# endif
+#endif
+
+
+#if @GNULIB_GETLOGIN_R@
+/* Copies the user's login name to NAME.
+ The array pointed to by NAME has room for SIZE bytes.
+
+ Returns 0 if successful. Upon error, an error number is returned, or -1 in
+ the case that the login name cannot be found but no specific error is
+ provided (this case is hopefully rare but is left open by the POSIX spec).
+
+ See <http://www.opengroup.org/susv3xsh/getlogin.html>.
+
+ Most programs don't need to use this function, because the information is
+ available through environment variables:
+ ${LOGNAME-$USER} on Unix platforms,
+ $USERNAME on native Windows platforms.
+ */
+# if @REPLACE_GETLOGIN_R@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define getlogin_r rpl_getlogin_r
+# endif
+_GL_FUNCDECL_RPL (getlogin_r, int, (char *name, size_t size)
+ _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (getlogin_r, int, (char *name, size_t size));
+# else
+# if !@HAVE_DECL_GETLOGIN_R@
+_GL_FUNCDECL_SYS (getlogin_r, int, (char *name, size_t size)
+ _GL_ARG_NONNULL ((1)));
+# endif
+/* Need to cast, because on Solaris 10 systems, the second argument is
+ int size. */
+_GL_CXXALIAS_SYS_CAST (getlogin_r, int, (char *name, size_t size));
+# endif
+_GL_CXXALIASWARN (getlogin_r);
+#elif defined GNULIB_POSIXCHECK
+# undef getlogin_r
+# if HAVE_RAW_DECL_GETLOGIN_R
+_GL_WARN_ON_USE (getlogin_r, "getlogin_r is unportable - "
+ "use gnulib module getlogin_r for portability");
+# endif
+#endif
+
+
+#if @GNULIB_GETPAGESIZE@
+# if @REPLACE_GETPAGESIZE@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define getpagesize rpl_getpagesize
+# endif
+_GL_FUNCDECL_RPL (getpagesize, int, (void));
+_GL_CXXALIAS_RPL (getpagesize, int, (void));
+# else
+# if !@HAVE_GETPAGESIZE@
+# if !defined getpagesize
+/* This is for POSIX systems. */
+# if !defined _gl_getpagesize && defined _SC_PAGESIZE
+# if ! (defined __VMS && __VMS_VER < 70000000)
+# define _gl_getpagesize() sysconf (_SC_PAGESIZE)
+# endif
+# endif
+/* This is for older VMS. */
+# if !defined _gl_getpagesize && defined __VMS
+# ifdef __ALPHA
+# define _gl_getpagesize() 8192
+# else
+# define _gl_getpagesize() 512
+# endif
+# endif
+/* This is for BeOS. */
+# if !defined _gl_getpagesize && @HAVE_OS_H@
+# include <OS.h>
+# if defined B_PAGE_SIZE
+# define _gl_getpagesize() B_PAGE_SIZE
+# endif
+# endif
+/* This is for AmigaOS4.0. */
+# if !defined _gl_getpagesize && defined __amigaos4__
+# define _gl_getpagesize() 2048
+# endif
+/* This is for older Unix systems. */
+# if !defined _gl_getpagesize && @HAVE_SYS_PARAM_H@
+# include <sys/param.h>
+# ifdef EXEC_PAGESIZE
+# define _gl_getpagesize() EXEC_PAGESIZE
+# else
+# ifdef NBPG
+# ifndef CLSIZE
+# define CLSIZE 1
+# endif
+# define _gl_getpagesize() (NBPG * CLSIZE)
+# else
+# ifdef NBPC
+# define _gl_getpagesize() NBPC
+# endif
+# endif
+# endif
+# endif
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define getpagesize() _gl_getpagesize ()
+# else
+# if !GNULIB_defined_getpagesize_function
+_GL_UNISTD_INLINE int
+getpagesize ()
+{
+ return _gl_getpagesize ();
+}
+# define GNULIB_defined_getpagesize_function 1
+# endif
+# endif
+# endif
+# endif
+/* Need to cast, because on Cygwin 1.5.x systems, the return type is size_t. */
+_GL_CXXALIAS_SYS_CAST (getpagesize, int, (void));
+# endif
+# if @HAVE_DECL_GETPAGESIZE@
+_GL_CXXALIASWARN (getpagesize);
+# endif
+#elif defined GNULIB_POSIXCHECK
+# undef getpagesize
+# if HAVE_RAW_DECL_GETPAGESIZE
+_GL_WARN_ON_USE (getpagesize, "getpagesize is unportable - "
+ "use gnulib module getpagesize for portability");
+# endif
+#endif
+
+
+#if @GNULIB_GETUSERSHELL@
+/* Return the next valid login shell on the system, or NULL when the end of
+ the list has been reached. */
+# if !@HAVE_DECL_GETUSERSHELL@
+_GL_FUNCDECL_SYS (getusershell, char *, (void));
+# endif
+_GL_CXXALIAS_SYS (getusershell, char *, (void));
+_GL_CXXALIASWARN (getusershell);
+#elif defined GNULIB_POSIXCHECK
+# undef getusershell
+# if HAVE_RAW_DECL_GETUSERSHELL
+_GL_WARN_ON_USE (getusershell, "getusershell is unportable - "
+ "use gnulib module getusershell for portability");
+# endif
+#endif
+
+#if @GNULIB_GETUSERSHELL@
+/* Rewind to pointer that is advanced at each getusershell() call. */
+# if !@HAVE_DECL_GETUSERSHELL@
+_GL_FUNCDECL_SYS (setusershell, void, (void));
+# endif
+_GL_CXXALIAS_SYS (setusershell, void, (void));
+_GL_CXXALIASWARN (setusershell);
+#elif defined GNULIB_POSIXCHECK
+# undef setusershell
+# if HAVE_RAW_DECL_SETUSERSHELL
+_GL_WARN_ON_USE (setusershell, "setusershell is unportable - "
+ "use gnulib module getusershell for portability");
+# endif
+#endif
+
+#if @GNULIB_GETUSERSHELL@
+/* Free the pointer that is advanced at each getusershell() call and
+ associated resources. */
+# if !@HAVE_DECL_GETUSERSHELL@
+_GL_FUNCDECL_SYS (endusershell, void, (void));
+# endif
+_GL_CXXALIAS_SYS (endusershell, void, (void));
+_GL_CXXALIASWARN (endusershell);
+#elif defined GNULIB_POSIXCHECK
+# undef endusershell
+# if HAVE_RAW_DECL_ENDUSERSHELL
+_GL_WARN_ON_USE (endusershell, "endusershell is unportable - "
+ "use gnulib module getusershell for portability");
+# endif
+#endif
+
+
+#if @GNULIB_GROUP_MEMBER@
+/* Determine whether group id is in calling user's group list. */
+# if !@HAVE_GROUP_MEMBER@
+_GL_FUNCDECL_SYS (group_member, int, (gid_t gid));
+# endif
+_GL_CXXALIAS_SYS (group_member, int, (gid_t gid));
+_GL_CXXALIASWARN (group_member);
+#elif defined GNULIB_POSIXCHECK
+# undef group_member
+# if HAVE_RAW_DECL_GROUP_MEMBER
+_GL_WARN_ON_USE (group_member, "group_member is unportable - "
+ "use gnulib module group-member for portability");
+# endif
+#endif
+
+
+#if @GNULIB_ISATTY@
+# if @REPLACE_ISATTY@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef isatty
+# define isatty rpl_isatty
+# endif
+_GL_FUNCDECL_RPL (isatty, int, (int fd));
+_GL_CXXALIAS_RPL (isatty, int, (int fd));
+# else
+_GL_CXXALIAS_SYS (isatty, int, (int fd));
+# endif
+_GL_CXXALIASWARN (isatty);
+#elif defined GNULIB_POSIXCHECK
+# undef isatty
+# if HAVE_RAW_DECL_ISATTY
+_GL_WARN_ON_USE (isatty, "isatty has portability problems on native Windows - "
+ "use gnulib module isatty for portability");
+# endif
+#endif
+
+
+#if @GNULIB_LCHOWN@
+/* Change the owner of FILE to UID (if UID is not -1) and the group of FILE
+ to GID (if GID is not -1). Do not follow symbolic links.
+ Return 0 if successful, otherwise -1 and errno set.
+ See the POSIX:2008 specification
+ <http://pubs.opengroup.org/onlinepubs/9699919799/functions/lchown.html>. */
+# if @REPLACE_LCHOWN@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef lchown
+# define lchown rpl_lchown
+# endif
+_GL_FUNCDECL_RPL (lchown, int, (char const *file, uid_t owner, gid_t group)
+ _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (lchown, int, (char const *file, uid_t owner, gid_t group));
+# else
+# if !@HAVE_LCHOWN@
+_GL_FUNCDECL_SYS (lchown, int, (char const *file, uid_t owner, gid_t group)
+ _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (lchown, int, (char const *file, uid_t owner, gid_t group));
+# endif
+_GL_CXXALIASWARN (lchown);
+#elif defined GNULIB_POSIXCHECK
+# undef lchown
+# if HAVE_RAW_DECL_LCHOWN
+_GL_WARN_ON_USE (lchown, "lchown is unportable to pre-POSIX.1-2001 systems - "
+ "use gnulib module lchown for portability");
+# endif
+#endif
+
+
+#if @GNULIB_LINK@
+/* Create a new hard link for an existing file.
+ Return 0 if successful, otherwise -1 and errno set.
+ See POSIX:2008 specification
+ <http://pubs.opengroup.org/onlinepubs/9699919799/functions/link.html>. */
+# if @REPLACE_LINK@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define link rpl_link
+# endif
+_GL_FUNCDECL_RPL (link, int, (const char *path1, const char *path2)
+ _GL_ARG_NONNULL ((1, 2)));
+_GL_CXXALIAS_RPL (link, int, (const char *path1, const char *path2));
+# else
+# if !@HAVE_LINK@
+_GL_FUNCDECL_SYS (link, int, (const char *path1, const char *path2)
+ _GL_ARG_NONNULL ((1, 2)));
+# endif
+_GL_CXXALIAS_SYS (link, int, (const char *path1, const char *path2));
+# endif
+_GL_CXXALIASWARN (link);
+#elif defined GNULIB_POSIXCHECK
+# undef link
+# if HAVE_RAW_DECL_LINK
+_GL_WARN_ON_USE (link, "link is unportable - "
+ "use gnulib module link for portability");
+# endif
+#endif
+
+
+#if @GNULIB_LINKAT@
+/* Create a new hard link for an existing file, relative to two
+ directories. FLAG controls whether symlinks are followed.
+ Return 0 if successful, otherwise -1 and errno set. */
+# if @REPLACE_LINKAT@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef linkat
+# define linkat rpl_linkat
+# endif
+_GL_FUNCDECL_RPL (linkat, int,
+ (int fd1, const char *path1, int fd2, const char *path2,
+ int flag)
+ _GL_ARG_NONNULL ((2, 4)));
+_GL_CXXALIAS_RPL (linkat, int,
+ (int fd1, const char *path1, int fd2, const char *path2,
+ int flag));
+# else
+# if !@HAVE_LINKAT@
+_GL_FUNCDECL_SYS (linkat, int,
+ (int fd1, const char *path1, int fd2, const char *path2,
+ int flag)
+ _GL_ARG_NONNULL ((2, 4)));
+# endif
+_GL_CXXALIAS_SYS (linkat, int,
+ (int fd1, const char *path1, int fd2, const char *path2,
+ int flag));
+# endif
+_GL_CXXALIASWARN (linkat);
+#elif defined GNULIB_POSIXCHECK
+# undef linkat
+# if HAVE_RAW_DECL_LINKAT
+_GL_WARN_ON_USE (linkat, "linkat is unportable - "
+ "use gnulib module linkat for portability");
+# endif
+#endif
+
+
+#if @GNULIB_LSEEK@
+/* Set the offset of FD relative to SEEK_SET, SEEK_CUR, or SEEK_END.
+ Return the new offset if successful, otherwise -1 and errno set.
+ See the POSIX:2008 specification
+ <http://pubs.opengroup.org/onlinepubs/9699919799/functions/lseek.html>. */
+# if @REPLACE_LSEEK@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define lseek rpl_lseek
+# endif
+_GL_FUNCDECL_RPL (lseek, off_t, (int fd, off_t offset, int whence));
+_GL_CXXALIAS_RPL (lseek, off_t, (int fd, off_t offset, int whence));
+# else
+_GL_CXXALIAS_SYS (lseek, off_t, (int fd, off_t offset, int whence));
+# endif
+_GL_CXXALIASWARN (lseek);
+#elif defined GNULIB_POSIXCHECK
+# undef lseek
+# if HAVE_RAW_DECL_LSEEK
+_GL_WARN_ON_USE (lseek, "lseek does not fail with ESPIPE on pipes on some "
+ "systems - use gnulib module lseek for portability");
+# endif
+#endif
+
+
+#if @GNULIB_PIPE@
+/* Create a pipe, defaulting to O_BINARY mode.
+ Store the read-end as fd[0] and the write-end as fd[1].
+ Return 0 upon success, or -1 with errno set upon failure. */
+# if !@HAVE_PIPE@
+_GL_FUNCDECL_SYS (pipe, int, (int fd[2]) _GL_ARG_NONNULL ((1)));
+# endif
+_GL_CXXALIAS_SYS (pipe, int, (int fd[2]));
+_GL_CXXALIASWARN (pipe);
+#elif defined GNULIB_POSIXCHECK
+# undef pipe
+# if HAVE_RAW_DECL_PIPE
+_GL_WARN_ON_USE (pipe, "pipe is unportable - "
+ "use gnulib module pipe-posix for portability");
+# endif
+#endif
+
+
+#if @GNULIB_PIPE2@
+/* Create a pipe, applying the given flags when opening the read-end of the
+ pipe and the write-end of the pipe.
+ The flags are a bitmask, possibly including O_CLOEXEC (defined in <fcntl.h>)
+ and O_TEXT, O_BINARY (defined in "binary-io.h").
+ Store the read-end as fd[0] and the write-end as fd[1].
+ Return 0 upon success, or -1 with errno set upon failure.
+ See also the Linux man page at
+ <http://www.kernel.org/doc/man-pages/online/pages/man2/pipe2.2.html>. */
+# if @HAVE_PIPE2@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define pipe2 rpl_pipe2
+# endif
+_GL_FUNCDECL_RPL (pipe2, int, (int fd[2], int flags) _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (pipe2, int, (int fd[2], int flags));
+# else
+_GL_FUNCDECL_SYS (pipe2, int, (int fd[2], int flags) _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_SYS (pipe2, int, (int fd[2], int flags));
+# endif
+_GL_CXXALIASWARN (pipe2);
+#elif defined GNULIB_POSIXCHECK
+# undef pipe2
+# if HAVE_RAW_DECL_PIPE2
+_GL_WARN_ON_USE (pipe2, "pipe2 is unportable - "
+ "use gnulib module pipe2 for portability");
+# endif
+#endif
+
+
+#if @GNULIB_PREAD@
+/* Read at most BUFSIZE bytes from FD into BUF, starting at OFFSET.
+ Return the number of bytes placed into BUF if successful, otherwise
+ set errno and return -1. 0 indicates EOF.
+ See the POSIX:2008 specification
+ <http://pubs.opengroup.org/onlinepubs/9699919799/functions/pread.html>. */
+# if @REPLACE_PREAD@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef pread
+# define pread rpl_pread
+# endif
+_GL_FUNCDECL_RPL (pread, ssize_t,
+ (int fd, void *buf, size_t bufsize, off_t offset)
+ _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_RPL (pread, ssize_t,
+ (int fd, void *buf, size_t bufsize, off_t offset));
+# else
+# if !@HAVE_PREAD@
+_GL_FUNCDECL_SYS (pread, ssize_t,
+ (int fd, void *buf, size_t bufsize, off_t offset)
+ _GL_ARG_NONNULL ((2)));
+# endif
+_GL_CXXALIAS_SYS (pread, ssize_t,
+ (int fd, void *buf, size_t bufsize, off_t offset));
+# endif
+_GL_CXXALIASWARN (pread);
+#elif defined GNULIB_POSIXCHECK
+# undef pread
+# if HAVE_RAW_DECL_PREAD
+_GL_WARN_ON_USE (pread, "pread is unportable - "
+ "use gnulib module pread for portability");
+# endif
+#endif
+
+
+#if @GNULIB_PWRITE@
+/* Write at most BUFSIZE bytes from BUF into FD, starting at OFFSET.
+ Return the number of bytes written if successful, otherwise
+ set errno and return -1. 0 indicates nothing written. See the
+ POSIX:2008 specification
+ <http://pubs.opengroup.org/onlinepubs/9699919799/functions/pwrite.html>. */
+# if @REPLACE_PWRITE@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef pwrite
+# define pwrite rpl_pwrite
+# endif
+_GL_FUNCDECL_RPL (pwrite, ssize_t,
+ (int fd, const void *buf, size_t bufsize, off_t offset)
+ _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_RPL (pwrite, ssize_t,
+ (int fd, const void *buf, size_t bufsize, off_t offset));
+# else
+# if !@HAVE_PWRITE@
+_GL_FUNCDECL_SYS (pwrite, ssize_t,
+ (int fd, const void *buf, size_t bufsize, off_t offset)
+ _GL_ARG_NONNULL ((2)));
+# endif
+_GL_CXXALIAS_SYS (pwrite, ssize_t,
+ (int fd, const void *buf, size_t bufsize, off_t offset));
+# endif
+_GL_CXXALIASWARN (pwrite);
+#elif defined GNULIB_POSIXCHECK
+# undef pwrite
+# if HAVE_RAW_DECL_PWRITE
+_GL_WARN_ON_USE (pwrite, "pwrite is unportable - "
+ "use gnulib module pwrite for portability");
+# endif
+#endif
+
+
+#if @GNULIB_READ@
+/* Read up to COUNT bytes from file descriptor FD into the buffer starting
+ at BUF. See the POSIX:2008 specification
+ <http://pubs.opengroup.org/onlinepubs/9699919799/functions/read.html>. */
+# if @REPLACE_READ@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef read
+# define read rpl_read
+# endif
+_GL_FUNCDECL_RPL (read, ssize_t, (int fd, void *buf, size_t count)
+ _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_RPL (read, ssize_t, (int fd, void *buf, size_t count));
+# else
+/* Need to cast, because on mingw, the third parameter is
+ unsigned int count
+ and the return type is 'int'. */
+_GL_CXXALIAS_SYS_CAST (read, ssize_t, (int fd, void *buf, size_t count));
+# endif
+_GL_CXXALIASWARN (read);
+#endif
+
+
+#if @GNULIB_READLINK@
+/* Read the contents of the symbolic link FILE and place the first BUFSIZE
+ bytes of it into BUF. Return the number of bytes placed into BUF if
+ successful, otherwise -1 and errno set.
+ See the POSIX:2008 specification
+ <http://pubs.opengroup.org/onlinepubs/9699919799/functions/readlink.html>. */
+# if @REPLACE_READLINK@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define readlink rpl_readlink
+# endif
+_GL_FUNCDECL_RPL (readlink, ssize_t,
+ (const char *file, char *buf, size_t bufsize)
+ _GL_ARG_NONNULL ((1, 2)));
+_GL_CXXALIAS_RPL (readlink, ssize_t,
+ (const char *file, char *buf, size_t bufsize));
+# else
+# if !@HAVE_READLINK@
+_GL_FUNCDECL_SYS (readlink, ssize_t,
+ (const char *file, char *buf, size_t bufsize)
+ _GL_ARG_NONNULL ((1, 2)));
+# endif
+_GL_CXXALIAS_SYS (readlink, ssize_t,
+ (const char *file, char *buf, size_t bufsize));
+# endif
+_GL_CXXALIASWARN (readlink);
+#elif defined GNULIB_POSIXCHECK
+# undef readlink
+# if HAVE_RAW_DECL_READLINK
+_GL_WARN_ON_USE (readlink, "readlink is unportable - "
+ "use gnulib module readlink for portability");
+# endif
+#endif
+
+
+#if @GNULIB_READLINKAT@
+# if @REPLACE_READLINKAT@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define readlinkat rpl_readlinkat
+# endif
+_GL_FUNCDECL_RPL (readlinkat, ssize_t,
+ (int fd, char const *file, char *buf, size_t len)
+ _GL_ARG_NONNULL ((2, 3)));
+_GL_CXXALIAS_RPL (readlinkat, ssize_t,
+ (int fd, char const *file, char *buf, size_t len));
+# else
+# if !@HAVE_READLINKAT@
+_GL_FUNCDECL_SYS (readlinkat, ssize_t,
+ (int fd, char const *file, char *buf, size_t len)
+ _GL_ARG_NONNULL ((2, 3)));
+# endif
+_GL_CXXALIAS_SYS (readlinkat, ssize_t,
+ (int fd, char const *file, char *buf, size_t len));
+# endif
+_GL_CXXALIASWARN (readlinkat);
+#elif defined GNULIB_POSIXCHECK
+# undef readlinkat
+# if HAVE_RAW_DECL_READLINKAT
+_GL_WARN_ON_USE (readlinkat, "readlinkat is not portable - "
+ "use gnulib module readlinkat for portability");
+# endif
+#endif
+
+
+#if @GNULIB_RMDIR@
+/* Remove the directory DIR. */
+# if @REPLACE_RMDIR@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define rmdir rpl_rmdir
+# endif
+_GL_FUNCDECL_RPL (rmdir, int, (char const *name) _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (rmdir, int, (char const *name));
+# else
+_GL_CXXALIAS_SYS (rmdir, int, (char const *name));
+# endif
+_GL_CXXALIASWARN (rmdir);
+#elif defined GNULIB_POSIXCHECK
+# undef rmdir
+# if HAVE_RAW_DECL_RMDIR
+_GL_WARN_ON_USE (rmdir, "rmdir is unportable - "
+ "use gnulib module rmdir for portability");
+# endif
+#endif
+
+
+#if @GNULIB_SETHOSTNAME@
+/* Set the host name of the machine.
+ The host name may or may not be fully qualified.
+
+ Put LEN bytes of NAME into the host name.
+ Return 0 if successful, otherwise, set errno and return -1.
+
+ Platforms with no ability to set the hostname return -1 and set
+ errno = ENOSYS. */
+# if !@HAVE_SETHOSTNAME@ || !@HAVE_DECL_SETHOSTNAME@
+_GL_FUNCDECL_SYS (sethostname, int, (const char *name, size_t len)
+ _GL_ARG_NONNULL ((1)));
+# endif
+/* Need to cast, because on Solaris 11 2011-10, Mac OS X 10.5, IRIX 6.5
+ and FreeBSD 6.4 the second parameter is int. On Solaris 11
+ 2011-10, the first parameter is not const. */
+_GL_CXXALIAS_SYS_CAST (sethostname, int, (const char *name, size_t len));
+_GL_CXXALIASWARN (sethostname);
+#elif defined GNULIB_POSIXCHECK
+# undef sethostname
+# if HAVE_RAW_DECL_SETHOSTNAME
+_GL_WARN_ON_USE (sethostname, "sethostname is unportable - "
+ "use gnulib module sethostname for portability");
+# endif
+#endif
+
+
+#if @GNULIB_SLEEP@
+/* Pause the execution of the current thread for N seconds.
+ Returns the number of seconds left to sleep.
+ See the POSIX:2008 specification
+ <http://pubs.opengroup.org/onlinepubs/9699919799/functions/sleep.html>. */
+# if @REPLACE_SLEEP@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef sleep
+# define sleep rpl_sleep
+# endif
+_GL_FUNCDECL_RPL (sleep, unsigned int, (unsigned int n));
+_GL_CXXALIAS_RPL (sleep, unsigned int, (unsigned int n));
+# else
+# if !@HAVE_SLEEP@
+_GL_FUNCDECL_SYS (sleep, unsigned int, (unsigned int n));
+# endif
+_GL_CXXALIAS_SYS (sleep, unsigned int, (unsigned int n));
+# endif
+_GL_CXXALIASWARN (sleep);
+#elif defined GNULIB_POSIXCHECK
+# undef sleep
+# if HAVE_RAW_DECL_SLEEP
+_GL_WARN_ON_USE (sleep, "sleep is unportable - "
+ "use gnulib module sleep for portability");
+# endif
+#endif
+
+
+#if @GNULIB_SYMLINK@
+# if @REPLACE_SYMLINK@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef symlink
+# define symlink rpl_symlink
+# endif
+_GL_FUNCDECL_RPL (symlink, int, (char const *contents, char const *file)
+ _GL_ARG_NONNULL ((1, 2)));
+_GL_CXXALIAS_RPL (symlink, int, (char const *contents, char const *file));
+# else
+# if !@HAVE_SYMLINK@
+_GL_FUNCDECL_SYS (symlink, int, (char const *contents, char const *file)
+ _GL_ARG_NONNULL ((1, 2)));
+# endif
+_GL_CXXALIAS_SYS (symlink, int, (char const *contents, char const *file));
+# endif
+_GL_CXXALIASWARN (symlink);
+#elif defined GNULIB_POSIXCHECK
+# undef symlink
+# if HAVE_RAW_DECL_SYMLINK
+_GL_WARN_ON_USE (symlink, "symlink is not portable - "
+ "use gnulib module symlink for portability");
+# endif
+#endif
+
+
+#if @GNULIB_SYMLINKAT@
+# if @REPLACE_SYMLINKAT@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef symlinkat
+# define symlinkat rpl_symlinkat
+# endif
+_GL_FUNCDECL_RPL (symlinkat, int,
+ (char const *contents, int fd, char const *file)
+ _GL_ARG_NONNULL ((1, 3)));
+_GL_CXXALIAS_RPL (symlinkat, int,
+ (char const *contents, int fd, char const *file));
+# else
+# if !@HAVE_SYMLINKAT@
+_GL_FUNCDECL_SYS (symlinkat, int,
+ (char const *contents, int fd, char const *file)
+ _GL_ARG_NONNULL ((1, 3)));
+# endif
+_GL_CXXALIAS_SYS (symlinkat, int,
+ (char const *contents, int fd, char const *file));
+# endif
+_GL_CXXALIASWARN (symlinkat);
+#elif defined GNULIB_POSIXCHECK
+# undef symlinkat
+# if HAVE_RAW_DECL_SYMLINKAT
+_GL_WARN_ON_USE (symlinkat, "symlinkat is not portable - "
+ "use gnulib module symlinkat for portability");
+# endif
+#endif
+
+
+#if @GNULIB_TTYNAME_R@
+/* Store at most BUFLEN characters of the pathname of the terminal FD is
+ open on in BUF. Return 0 on success, otherwise an error number. */
+# if @REPLACE_TTYNAME_R@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef ttyname_r
+# define ttyname_r rpl_ttyname_r
+# endif
+_GL_FUNCDECL_RPL (ttyname_r, int,
+ (int fd, char *buf, size_t buflen) _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_RPL (ttyname_r, int,
+ (int fd, char *buf, size_t buflen));
+# else
+# if !@HAVE_DECL_TTYNAME_R@
+_GL_FUNCDECL_SYS (ttyname_r, int,
+ (int fd, char *buf, size_t buflen) _GL_ARG_NONNULL ((2)));
+# endif
+_GL_CXXALIAS_SYS (ttyname_r, int,
+ (int fd, char *buf, size_t buflen));
+# endif
+_GL_CXXALIASWARN (ttyname_r);
+#elif defined GNULIB_POSIXCHECK
+# undef ttyname_r
+# if HAVE_RAW_DECL_TTYNAME_R
+_GL_WARN_ON_USE (ttyname_r, "ttyname_r is not portable - "
+ "use gnulib module ttyname_r for portability");
+# endif
+#endif
+
+
+#if @GNULIB_UNLINK@
+# if @REPLACE_UNLINK@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef unlink
+# define unlink rpl_unlink
+# endif
+_GL_FUNCDECL_RPL (unlink, int, (char const *file) _GL_ARG_NONNULL ((1)));
+_GL_CXXALIAS_RPL (unlink, int, (char const *file));
+# else
+_GL_CXXALIAS_SYS (unlink, int, (char const *file));
+# endif
+_GL_CXXALIASWARN (unlink);
+#elif defined GNULIB_POSIXCHECK
+# undef unlink
+# if HAVE_RAW_DECL_UNLINK
+_GL_WARN_ON_USE (unlink, "unlink is not portable - "
+ "use gnulib module unlink for portability");
+# endif
+#endif
+
+
+#if @GNULIB_UNLINKAT@
+# if @REPLACE_UNLINKAT@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef unlinkat
+# define unlinkat rpl_unlinkat
+# endif
+_GL_FUNCDECL_RPL (unlinkat, int, (int fd, char const *file, int flag)
+ _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_RPL (unlinkat, int, (int fd, char const *file, int flag));
+# else
+# if !@HAVE_UNLINKAT@
+_GL_FUNCDECL_SYS (unlinkat, int, (int fd, char const *file, int flag)
+ _GL_ARG_NONNULL ((2)));
+# endif
+_GL_CXXALIAS_SYS (unlinkat, int, (int fd, char const *file, int flag));
+# endif
+_GL_CXXALIASWARN (unlinkat);
+#elif defined GNULIB_POSIXCHECK
+# undef unlinkat
+# if HAVE_RAW_DECL_UNLINKAT
+_GL_WARN_ON_USE (unlinkat, "unlinkat is not portable - "
+ "use gnulib module openat for portability");
+# endif
+#endif
+
+
+#if @GNULIB_USLEEP@
+/* Pause the execution of the current thread for N microseconds.
+ Returns 0 on completion, or -1 on range error.
+ See the POSIX:2001 specification
+ <http://www.opengroup.org/susv3xsh/usleep.html>. */
+# if @REPLACE_USLEEP@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef usleep
+# define usleep rpl_usleep
+# endif
+_GL_FUNCDECL_RPL (usleep, int, (useconds_t n));
+_GL_CXXALIAS_RPL (usleep, int, (useconds_t n));
+# else
+# if !@HAVE_USLEEP@
+_GL_FUNCDECL_SYS (usleep, int, (useconds_t n));
+# endif
+_GL_CXXALIAS_SYS (usleep, int, (useconds_t n));
+# endif
+_GL_CXXALIASWARN (usleep);
+#elif defined GNULIB_POSIXCHECK
+# undef usleep
+# if HAVE_RAW_DECL_USLEEP
+_GL_WARN_ON_USE (usleep, "usleep is unportable - "
+ "use gnulib module usleep for portability");
+# endif
+#endif
+
+
+#if @GNULIB_WRITE@
+/* Write up to COUNT bytes starting at BUF to file descriptor FD.
+ See the POSIX:2008 specification
+ <http://pubs.opengroup.org/onlinepubs/9699919799/functions/write.html>. */
+# if @REPLACE_WRITE@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef write
+# define write rpl_write
+# endif
+_GL_FUNCDECL_RPL (write, ssize_t, (int fd, const void *buf, size_t count)
+ _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_RPL (write, ssize_t, (int fd, const void *buf, size_t count));
+# else
+/* Need to cast, because on mingw, the third parameter is
+ unsigned int count
+ and the return type is 'int'. */
+_GL_CXXALIAS_SYS_CAST (write, ssize_t, (int fd, const void *buf, size_t count));
+# endif
+_GL_CXXALIASWARN (write);
+#endif
+
+_GL_INLINE_HEADER_END
+
+#endif /* _@GUARD_PREFIX@_UNISTD_H */
+#endif /* _GL_INCLUDING_UNISTD_H */
+#endif /* _@GUARD_PREFIX@_UNISTD_H */
diff --git a/lib/unistd_.h b/lib/unistd_.h
deleted file mode 100644
index 77df861..0000000
--- a/lib/unistd_.h
+++ /dev/null
@@ -1,192 +0,0 @@
-/* Substitute for and wrapper around <unistd.h>.
- Copyright (C) 2004-2007 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-#ifndef _GL_UNISTD_H
-#define _GL_UNISTD_H
-
-#if @HAVE_UNISTD_H@
-# include @ABSOLUTE_UNISTD_H@
-#endif
-
-
-/* The definition of GL_LINK_WARNING is copied here. */
-
-
-/* Declare overridden functions. */
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-#if @GNULIB_CHOWN@
-# if @REPLACE_CHOWN@
-/* Change the owner of FILE to UID (if UID is not -1) and the group of FILE
- to GID (if GID is not -1).
- Return 0 if successful, otherwise -1 and errno set.
- See the POSIX:2001 specification
- <http://www.opengroup.org/susv3xsh/chown.html>. */
-# define chown rpl_chown
-extern int chown (const char *file, uid_t uid, gid_t gid);
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef chown
-# define chown(f,u,g) \
- (GL_LINK_WARNING ("chown fails to follow symlinks on some systems and " \
- "doesn't treat a uid or gid of -1 on some systems - " \
- "use gnulib module chown for portability"), \
- chown (f, u, g))
-#endif
-
-
-#if @GNULIB_DUP2@
-# if !@HAVE_DUP2@
-/* Copy the file descriptor OLDFD into file descriptor NEWFD. Do nothing if
- NEWFD = OLDFD, otherwise close NEWFD first if it is open.
- Return 0 if successful, otherwise -1 and errno set.
- See the POSIX:2001 specification
- <http://www.opengroup.org/susv3xsh/dup2.html>. */
-extern int dup2 (int oldfd, int newfd);
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef dup2
-# define dup2(o,n) \
- (GL_LINK_WARNING ("dup2 is unportable - " \
- "use gnulib module dup2 for portability"), \
- dup2 (o, n))
-#endif
-
-
-#if @GNULIB_FCHDIR@
-# if @REPLACE_FCHDIR@
-
-/* Change the process' current working directory to the directory on which
- the given file descriptor is open.
- Return 0 if successful, otherwise -1 and errno set.
- See the POSIX:2001 specification
- <http://www.opengroup.org/susv3xsh/fchdir.html>. */
-extern int fchdir (int /*fd*/);
-
-# define close rpl_close
-extern int close (int);
-# define dup rpl_dup
-extern int dup (int);
-# define dup2 rpl_dup2
-extern int dup2 (int, int);
-
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef fchdir
-# define fchdir(f) \
- (GL_LINK_WARNING ("fchdir is unportable - " \
- "use gnulib module fchdir for portability"), \
- fchdir (f))
-#endif
-
-
-#if @GNULIB_FTRUNCATE@
-# if !@HAVE_FTRUNCATE@
-/* Change the size of the file to which FD is opened to become equal to LENGTH.
- Return 0 if successful, otherwise -1 and errno set.
- See the POSIX:2001 specification
- <http://www.opengroup.org/susv3xsh/ftruncate.html>. */
-extern int ftruncate (int fd, off_t length);
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef ftruncate
-# define ftruncate(f,l) \
- (GL_LINK_WARNING ("ftruncate is unportable - " \
- "use gnulib module ftruncate for portability"), \
- ftruncate (f, l))
-#endif
-
-
-#if @GNULIB_GETCWD@
-/* Include the headers that might declare getcwd so that they will not
- cause confusion if included after this file. */
-# include <stdlib.h>
-# if @REPLACE_GETCWD@
-/* Get the name of the current working directory, and put it in SIZE bytes
- of BUF.
- Return BUF if successful, or NULL if the directory couldn't be determined
- or SIZE was too small.
- See the POSIX:2001 specification
- <http://www.opengroup.org/susv3xsh/getcwd.html>.
- Additionally, the gnulib module 'getcwd' guarantees the following GNU
- extension: If BUF is NULL, an array is allocated with 'malloc'; the array
- is SIZE bytes long, unless SIZE == 0, in which case it is as big as
- necessary. */
-# define getcwd rpl_getcwd
-extern char * getcwd (char *buf, size_t size);
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef getcwd
-# define getcwd(b,s) \
- (GL_LINK_WARNING ("getcwd is unportable - " \
- "use gnulib module getcwd for portability"), \
- getcwd (b, s))
-#endif
-
-
-#if @GNULIB_GETLOGIN_R@
-/* Copies the user's login name to NAME.
- The array pointed to by NAME has room for SIZE bytes.
-
- Returns 0 if successful. Upon error, an error number is returned, or -1 in
- the case that the login name cannot be found but no specific error is
- provided (this case is hopefully rare but is left open by the POSIX spec).
-
- See <http://www.opengroup.org/susv3xsh/getlogin.html>.
- */
-# if !@HAVE_DECL_GETLOGIN_R@
-# include <stddef.h>
-extern int getlogin_r (char *name, size_t size);
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef getlogin_r
-# define getlogin_r(n,s) \
- (GL_LINK_WARNING ("getlogin_r is unportable - " \
- "use gnulib module getlogin_r for portability"), \
- getlogin_r (n, s))
-#endif
-
-
-#if @GNULIB_READLINK@
-/* Read the contents of the symbolic link FILE and place the first BUFSIZE
- bytes of it into BUF. Return the number of bytes placed into BUF if
- successful, otherwise -1 and errno set.
- See the POSIX:2001 specification
- <http://www.opengroup.org/susv3xsh/readlink.html>. */
-# if !@HAVE_READLINK@
-# include <stddef.h>
-extern int readlink (const char *file, char *buf, size_t bufsize);
-# endif
-#elif defined GNULIB_POSIXCHECK
-# undef readlink
-# define readlink(f,b,s) \
- (GL_LINK_WARNING ("readlink is unportable - " \
- "use gnulib module readlink for portability"), \
- readlink (f, b, s))
-#endif
-
-
-#ifdef __cplusplus
-}
-#endif
-
-
-#endif /* _GL_UNISTD_H */
diff --git a/lib/unistr.in.h b/lib/unistr.in.h
new file mode 100644
index 0000000..70aa9cb
--- /dev/null
+++ b/lib/unistr.in.h
@@ -0,0 +1,750 @@
+/* Elementary Unicode string functions.
+ Copyright (C) 2001-2002, 2005-2016 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _UNISTR_H
+#define _UNISTR_H
+
+#include "unitypes.h"
+
+/* Get common macros for C. */
+#include "unused-parameter.h"
+
+/* Get bool. */
+#include <stdbool.h>
+
+/* Get size_t. */
+#include <stddef.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/* Conventions:
+
+ All functions prefixed with u8_ operate on UTF-8 encoded strings.
+ Their unit is an uint8_t (1 byte).
+
+ All functions prefixed with u16_ operate on UTF-16 encoded strings.
+ Their unit is an uint16_t (a 2-byte word).
+
+ All functions prefixed with u32_ operate on UCS-4 encoded strings.
+ Their unit is an uint32_t (a 4-byte word).
+
+ All argument pairs (s, n) denote a Unicode string s[0..n-1] with exactly
+ n units.
+
+ All arguments starting with "str" and the arguments of functions starting
+ with u8_str/u16_str/u32_str denote a NUL terminated string, i.e. a string
+ which terminates at the first NUL unit. This termination unit is
+ considered part of the string for all memory allocation purposes, but
+ is not considered part of the string for all other logical purposes.
+
+ Functions returning a string result take a (resultbuf, lengthp) argument
+ pair. If resultbuf is not NULL and the result fits into *lengthp units,
+ it is put in resultbuf, and resultbuf is returned. Otherwise, a freshly
+ allocated string is returned. In both cases, *lengthp is set to the
+ length (number of units) of the returned string. In case of error,
+ NULL is returned and errno is set. */
+
+
+/* Elementary string checks. */
+
+/* Check whether an UTF-8 string is well-formed.
+ Return NULL if valid, or a pointer to the first invalid unit otherwise. */
+extern const uint8_t *
+ u8_check (const uint8_t *s, size_t n)
+ _UC_ATTRIBUTE_PURE;
+
+/* Check whether an UTF-16 string is well-formed.
+ Return NULL if valid, or a pointer to the first invalid unit otherwise. */
+extern const uint16_t *
+ u16_check (const uint16_t *s, size_t n)
+ _UC_ATTRIBUTE_PURE;
+
+/* Check whether an UCS-4 string is well-formed.
+ Return NULL if valid, or a pointer to the first invalid unit otherwise. */
+extern const uint32_t *
+ u32_check (const uint32_t *s, size_t n)
+ _UC_ATTRIBUTE_PURE;
+
+
+/* Elementary string conversions. */
+
+/* Convert an UTF-8 string to an UTF-16 string. */
+extern uint16_t *
+ u8_to_u16 (const uint8_t *s, size_t n, uint16_t *resultbuf,
+ size_t *lengthp);
+
+/* Convert an UTF-8 string to an UCS-4 string. */
+extern uint32_t *
+ u8_to_u32 (const uint8_t *s, size_t n, uint32_t *resultbuf,
+ size_t *lengthp);
+
+/* Convert an UTF-16 string to an UTF-8 string. */
+extern uint8_t *
+ u16_to_u8 (const uint16_t *s, size_t n, uint8_t *resultbuf,
+ size_t *lengthp);
+
+/* Convert an UTF-16 string to an UCS-4 string. */
+extern uint32_t *
+ u16_to_u32 (const uint16_t *s, size_t n, uint32_t *resultbuf,
+ size_t *lengthp);
+
+/* Convert an UCS-4 string to an UTF-8 string. */
+extern uint8_t *
+ u32_to_u8 (const uint32_t *s, size_t n, uint8_t *resultbuf,
+ size_t *lengthp);
+
+/* Convert an UCS-4 string to an UTF-16 string. */
+extern uint16_t *
+ u32_to_u16 (const uint32_t *s, size_t n, uint16_t *resultbuf,
+ size_t *lengthp);
+
+
+/* Elementary string functions. */
+
+/* Return the length (number of units) of the first character in S, which is
+ no longer than N. Return 0 if it is the NUL character. Return -1 upon
+ failure. */
+/* Similar to mblen(), except that s must not be NULL. */
+extern int
+ u8_mblen (const uint8_t *s, size_t n)
+ _UC_ATTRIBUTE_PURE;
+extern int
+ u16_mblen (const uint16_t *s, size_t n)
+ _UC_ATTRIBUTE_PURE;
+extern int
+ u32_mblen (const uint32_t *s, size_t n)
+ _UC_ATTRIBUTE_PURE;
+
+/* Return the length (number of units) of the first character in S, putting
+ its 'ucs4_t' representation in *PUC. Upon failure, *PUC is set to 0xfffd,
+ and an appropriate number of units is returned.
+ The number of available units, N, must be > 0. */
+/* Similar to mbtowc(), except that puc and s must not be NULL, n must be > 0,
+ and the NUL character is not treated specially. */
+/* The variants with _safe suffix are safe, even if the library is compiled
+ without --enable-safety. */
+
+#if GNULIB_UNISTR_U8_MBTOUC_UNSAFE || HAVE_LIBUNISTRING
+# if !HAVE_INLINE
+extern int
+ u8_mbtouc_unsafe (ucs4_t *puc, const uint8_t *s, size_t n);
+# else
+extern int
+ u8_mbtouc_unsafe_aux (ucs4_t *puc, const uint8_t *s, size_t n);
+static inline int
+u8_mbtouc_unsafe (ucs4_t *puc, const uint8_t *s, size_t n)
+{
+ uint8_t c = *s;
+
+ if (c < 0x80)
+ {
+ *puc = c;
+ return 1;
+ }
+ else
+ return u8_mbtouc_unsafe_aux (puc, s, n);
+}
+# endif
+#endif
+
+#if GNULIB_UNISTR_U16_MBTOUC_UNSAFE || HAVE_LIBUNISTRING
+# if !HAVE_INLINE
+extern int
+ u16_mbtouc_unsafe (ucs4_t *puc, const uint16_t *s, size_t n);
+# else
+extern int
+ u16_mbtouc_unsafe_aux (ucs4_t *puc, const uint16_t *s, size_t n);
+static inline int
+u16_mbtouc_unsafe (ucs4_t *puc, const uint16_t *s, size_t n)
+{
+ uint16_t c = *s;
+
+ if (c < 0xd800 || c >= 0xe000)
+ {
+ *puc = c;
+ return 1;
+ }
+ else
+ return u16_mbtouc_unsafe_aux (puc, s, n);
+}
+# endif
+#endif
+
+#if GNULIB_UNISTR_U32_MBTOUC_UNSAFE || HAVE_LIBUNISTRING
+# if !HAVE_INLINE
+extern int
+ u32_mbtouc_unsafe (ucs4_t *puc, const uint32_t *s, size_t n);
+# else
+static inline int
+u32_mbtouc_unsafe (ucs4_t *puc,
+ const uint32_t *s, size_t n _GL_UNUSED_PARAMETER)
+{
+ uint32_t c = *s;
+
+# if CONFIG_UNICODE_SAFETY
+ if (c < 0xd800 || (c >= 0xe000 && c < 0x110000))
+# endif
+ *puc = c;
+# if CONFIG_UNICODE_SAFETY
+ else
+ /* invalid multibyte character */
+ *puc = 0xfffd;
+# endif
+ return 1;
+}
+# endif
+#endif
+
+#if GNULIB_UNISTR_U8_MBTOUC || HAVE_LIBUNISTRING
+# if !HAVE_INLINE
+extern int
+ u8_mbtouc (ucs4_t *puc, const uint8_t *s, size_t n);
+# else
+extern int
+ u8_mbtouc_aux (ucs4_t *puc, const uint8_t *s, size_t n);
+static inline int
+u8_mbtouc (ucs4_t *puc, const uint8_t *s, size_t n)
+{
+ uint8_t c = *s;
+
+ if (c < 0x80)
+ {
+ *puc = c;
+ return 1;
+ }
+ else
+ return u8_mbtouc_aux (puc, s, n);
+}
+# endif
+#endif
+
+#if GNULIB_UNISTR_U16_MBTOUC || HAVE_LIBUNISTRING
+# if !HAVE_INLINE
+extern int
+ u16_mbtouc (ucs4_t *puc, const uint16_t *s, size_t n);
+# else
+extern int
+ u16_mbtouc_aux (ucs4_t *puc, const uint16_t *s, size_t n);
+static inline int
+u16_mbtouc (ucs4_t *puc, const uint16_t *s, size_t n)
+{
+ uint16_t c = *s;
+
+ if (c < 0xd800 || c >= 0xe000)
+ {
+ *puc = c;
+ return 1;
+ }
+ else
+ return u16_mbtouc_aux (puc, s, n);
+}
+# endif
+#endif
+
+#if GNULIB_UNISTR_U32_MBTOUC || HAVE_LIBUNISTRING
+# if !HAVE_INLINE
+extern int
+ u32_mbtouc (ucs4_t *puc, const uint32_t *s, size_t n);
+# else
+static inline int
+u32_mbtouc (ucs4_t *puc, const uint32_t *s, size_t n _GL_UNUSED_PARAMETER)
+{
+ uint32_t c = *s;
+
+ if (c < 0xd800 || (c >= 0xe000 && c < 0x110000))
+ *puc = c;
+ else
+ /* invalid multibyte character */
+ *puc = 0xfffd;
+ return 1;
+}
+# endif
+#endif
+
+/* Return the length (number of units) of the first character in S, putting
+ its 'ucs4_t' representation in *PUC. Upon failure, *PUC is set to 0xfffd,
+ and -1 is returned for an invalid sequence of units, -2 is returned for an
+ incomplete sequence of units.
+ The number of available units, N, must be > 0. */
+/* Similar to u*_mbtouc(), except that the return value gives more details
+ about the failure, similar to mbrtowc(). */
+
+#if GNULIB_UNISTR_U8_MBTOUCR || HAVE_LIBUNISTRING
+extern int
+ u8_mbtoucr (ucs4_t *puc, const uint8_t *s, size_t n);
+#endif
+
+#if GNULIB_UNISTR_U16_MBTOUCR || HAVE_LIBUNISTRING
+extern int
+ u16_mbtoucr (ucs4_t *puc, const uint16_t *s, size_t n);
+#endif
+
+#if GNULIB_UNISTR_U32_MBTOUCR || HAVE_LIBUNISTRING
+extern int
+ u32_mbtoucr (ucs4_t *puc, const uint32_t *s, size_t n);
+#endif
+
+/* Put the multibyte character represented by UC in S, returning its
+ length. Return -1 upon failure, -2 if the number of available units, N,
+ is too small. The latter case cannot occur if N >= 6/2/1, respectively. */
+/* Similar to wctomb(), except that s must not be NULL, and the argument n
+ must be specified. */
+
+#if GNULIB_UNISTR_U8_UCTOMB || HAVE_LIBUNISTRING
+/* Auxiliary function, also used by u8_chr, u8_strchr, u8_strrchr. */
+extern int
+ u8_uctomb_aux (uint8_t *s, ucs4_t uc, int n);
+# if !HAVE_INLINE
+extern int
+ u8_uctomb (uint8_t *s, ucs4_t uc, int n);
+# else
+static inline int
+u8_uctomb (uint8_t *s, ucs4_t uc, int n)
+{
+ if (uc < 0x80 && n > 0)
+ {
+ s[0] = uc;
+ return 1;
+ }
+ else
+ return u8_uctomb_aux (s, uc, n);
+}
+# endif
+#endif
+
+#if GNULIB_UNISTR_U16_UCTOMB || HAVE_LIBUNISTRING
+/* Auxiliary function, also used by u16_chr, u16_strchr, u16_strrchr. */
+extern int
+ u16_uctomb_aux (uint16_t *s, ucs4_t uc, int n);
+# if !HAVE_INLINE
+extern int
+ u16_uctomb (uint16_t *s, ucs4_t uc, int n);
+# else
+static inline int
+u16_uctomb (uint16_t *s, ucs4_t uc, int n)
+{
+ if (uc < 0xd800 && n > 0)
+ {
+ s[0] = uc;
+ return 1;
+ }
+ else
+ return u16_uctomb_aux (s, uc, n);
+}
+# endif
+#endif
+
+#if GNULIB_UNISTR_U32_UCTOMB || HAVE_LIBUNISTRING
+# if !HAVE_INLINE
+extern int
+ u32_uctomb (uint32_t *s, ucs4_t uc, int n);
+# else
+static inline int
+u32_uctomb (uint32_t *s, ucs4_t uc, int n)
+{
+ if (uc < 0xd800 || (uc >= 0xe000 && uc < 0x110000))
+ {
+ if (n > 0)
+ {
+ *s = uc;
+ return 1;
+ }
+ else
+ return -2;
+ }
+ else
+ return -1;
+}
+# endif
+#endif
+
+/* Copy N units from SRC to DEST. */
+/* Similar to memcpy(). */
+extern uint8_t *
+ u8_cpy (uint8_t *dest, const uint8_t *src, size_t n);
+extern uint16_t *
+ u16_cpy (uint16_t *dest, const uint16_t *src, size_t n);
+extern uint32_t *
+ u32_cpy (uint32_t *dest, const uint32_t *src, size_t n);
+
+/* Copy N units from SRC to DEST, guaranteeing correct behavior for
+ overlapping memory areas. */
+/* Similar to memmove(). */
+extern uint8_t *
+ u8_move (uint8_t *dest, const uint8_t *src, size_t n);
+extern uint16_t *
+ u16_move (uint16_t *dest, const uint16_t *src, size_t n);
+extern uint32_t *
+ u32_move (uint32_t *dest, const uint32_t *src, size_t n);
+
+/* Set the first N characters of S to UC. UC should be a character that
+ occupies only 1 unit. */
+/* Similar to memset(). */
+extern uint8_t *
+ u8_set (uint8_t *s, ucs4_t uc, size_t n);
+extern uint16_t *
+ u16_set (uint16_t *s, ucs4_t uc, size_t n);
+extern uint32_t *
+ u32_set (uint32_t *s, ucs4_t uc, size_t n);
+
+/* Compare S1 and S2, each of length N. */
+/* Similar to memcmp(). */
+extern int
+ u8_cmp (const uint8_t *s1, const uint8_t *s2, size_t n)
+ _UC_ATTRIBUTE_PURE;
+extern int
+ u16_cmp (const uint16_t *s1, const uint16_t *s2, size_t n)
+ _UC_ATTRIBUTE_PURE;
+extern int
+ u32_cmp (const uint32_t *s1, const uint32_t *s2, size_t n)
+ _UC_ATTRIBUTE_PURE;
+
+/* Compare S1 and S2. */
+/* Similar to the gnulib function memcmp2(). */
+extern int
+ u8_cmp2 (const uint8_t *s1, size_t n1, const uint8_t *s2, size_t n2)
+ _UC_ATTRIBUTE_PURE;
+extern int
+ u16_cmp2 (const uint16_t *s1, size_t n1, const uint16_t *s2, size_t n2)
+ _UC_ATTRIBUTE_PURE;
+extern int
+ u32_cmp2 (const uint32_t *s1, size_t n1, const uint32_t *s2, size_t n2)
+ _UC_ATTRIBUTE_PURE;
+
+/* Search the string at S for UC. */
+/* Similar to memchr(). */
+extern uint8_t *
+ u8_chr (const uint8_t *s, size_t n, ucs4_t uc)
+ _UC_ATTRIBUTE_PURE;
+extern uint16_t *
+ u16_chr (const uint16_t *s, size_t n, ucs4_t uc)
+ _UC_ATTRIBUTE_PURE;
+extern uint32_t *
+ u32_chr (const uint32_t *s, size_t n, ucs4_t uc)
+ _UC_ATTRIBUTE_PURE;
+
+/* Count the number of Unicode characters in the N units from S. */
+/* Similar to mbsnlen(). */
+extern size_t
+ u8_mbsnlen (const uint8_t *s, size_t n)
+ _UC_ATTRIBUTE_PURE;
+extern size_t
+ u16_mbsnlen (const uint16_t *s, size_t n)
+ _UC_ATTRIBUTE_PURE;
+extern size_t
+ u32_mbsnlen (const uint32_t *s, size_t n)
+ _UC_ATTRIBUTE_PURE;
+
+/* Elementary string functions with memory allocation. */
+
+/* Make a freshly allocated copy of S, of length N. */
+extern uint8_t *
+ u8_cpy_alloc (const uint8_t *s, size_t n);
+extern uint16_t *
+ u16_cpy_alloc (const uint16_t *s, size_t n);
+extern uint32_t *
+ u32_cpy_alloc (const uint32_t *s, size_t n);
+
+/* Elementary string functions on NUL terminated strings. */
+
+/* Return the length (number of units) of the first character in S.
+ Return 0 if it is the NUL character. Return -1 upon failure. */
+extern int
+ u8_strmblen (const uint8_t *s)
+ _UC_ATTRIBUTE_PURE;
+extern int
+ u16_strmblen (const uint16_t *s)
+ _UC_ATTRIBUTE_PURE;
+extern int
+ u32_strmblen (const uint32_t *s)
+ _UC_ATTRIBUTE_PURE;
+
+/* Return the length (number of units) of the first character in S, putting
+ its 'ucs4_t' representation in *PUC. Return 0 if it is the NUL
+ character. Return -1 upon failure. */
+extern int
+ u8_strmbtouc (ucs4_t *puc, const uint8_t *s);
+extern int
+ u16_strmbtouc (ucs4_t *puc, const uint16_t *s);
+extern int
+ u32_strmbtouc (ucs4_t *puc, const uint32_t *s);
+
+/* Forward iteration step. Advances the pointer past the next character,
+ or returns NULL if the end of the string has been reached. Puts the
+ character's 'ucs4_t' representation in *PUC. */
+extern const uint8_t *
+ u8_next (ucs4_t *puc, const uint8_t *s);
+extern const uint16_t *
+ u16_next (ucs4_t *puc, const uint16_t *s);
+extern const uint32_t *
+ u32_next (ucs4_t *puc, const uint32_t *s);
+
+/* Backward iteration step. Advances the pointer to point to the previous
+ character, or returns NULL if the beginning of the string had been reached.
+ Puts the character's 'ucs4_t' representation in *PUC. */
+extern const uint8_t *
+ u8_prev (ucs4_t *puc, const uint8_t *s, const uint8_t *start);
+extern const uint16_t *
+ u16_prev (ucs4_t *puc, const uint16_t *s, const uint16_t *start);
+extern const uint32_t *
+ u32_prev (ucs4_t *puc, const uint32_t *s, const uint32_t *start);
+
+/* Return the number of units in S. */
+/* Similar to strlen(), wcslen(). */
+extern size_t
+ u8_strlen (const uint8_t *s)
+ _UC_ATTRIBUTE_PURE;
+extern size_t
+ u16_strlen (const uint16_t *s)
+ _UC_ATTRIBUTE_PURE;
+extern size_t
+ u32_strlen (const uint32_t *s)
+ _UC_ATTRIBUTE_PURE;
+
+/* Return the number of units in S, but at most MAXLEN. */
+/* Similar to strnlen(), wcsnlen(). */
+extern size_t
+ u8_strnlen (const uint8_t *s, size_t maxlen)
+ _UC_ATTRIBUTE_PURE;
+extern size_t
+ u16_strnlen (const uint16_t *s, size_t maxlen)
+ _UC_ATTRIBUTE_PURE;
+extern size_t
+ u32_strnlen (const uint32_t *s, size_t maxlen)
+ _UC_ATTRIBUTE_PURE;
+
+/* Copy SRC to DEST. */
+/* Similar to strcpy(), wcscpy(). */
+extern uint8_t *
+ u8_strcpy (uint8_t *dest, const uint8_t *src);
+extern uint16_t *
+ u16_strcpy (uint16_t *dest, const uint16_t *src);
+extern uint32_t *
+ u32_strcpy (uint32_t *dest, const uint32_t *src);
+
+/* Copy SRC to DEST, returning the address of the terminating NUL in DEST. */
+/* Similar to stpcpy(). */
+extern uint8_t *
+ u8_stpcpy (uint8_t *dest, const uint8_t *src);
+extern uint16_t *
+ u16_stpcpy (uint16_t *dest, const uint16_t *src);
+extern uint32_t *
+ u32_stpcpy (uint32_t *dest, const uint32_t *src);
+
+/* Copy no more than N units of SRC to DEST. */
+/* Similar to strncpy(), wcsncpy(). */
+extern uint8_t *
+ u8_strncpy (uint8_t *dest, const uint8_t *src, size_t n);
+extern uint16_t *
+ u16_strncpy (uint16_t *dest, const uint16_t *src, size_t n);
+extern uint32_t *
+ u32_strncpy (uint32_t *dest, const uint32_t *src, size_t n);
+
+/* Copy no more than N units of SRC to DEST. Return a pointer past the last
+ non-NUL unit written into DEST. */
+/* Similar to stpncpy(). */
+extern uint8_t *
+ u8_stpncpy (uint8_t *dest, const uint8_t *src, size_t n);
+extern uint16_t *
+ u16_stpncpy (uint16_t *dest, const uint16_t *src, size_t n);
+extern uint32_t *
+ u32_stpncpy (uint32_t *dest, const uint32_t *src, size_t n);
+
+/* Append SRC onto DEST. */
+/* Similar to strcat(), wcscat(). */
+extern uint8_t *
+ u8_strcat (uint8_t *dest, const uint8_t *src);
+extern uint16_t *
+ u16_strcat (uint16_t *dest, const uint16_t *src);
+extern uint32_t *
+ u32_strcat (uint32_t *dest, const uint32_t *src);
+
+/* Append no more than N units of SRC onto DEST. */
+/* Similar to strncat(), wcsncat(). */
+extern uint8_t *
+ u8_strncat (uint8_t *dest, const uint8_t *src, size_t n);
+extern uint16_t *
+ u16_strncat (uint16_t *dest, const uint16_t *src, size_t n);
+extern uint32_t *
+ u32_strncat (uint32_t *dest, const uint32_t *src, size_t n);
+
+/* Compare S1 and S2. */
+/* Similar to strcmp(), wcscmp(). */
+#ifdef __sun
+/* Avoid a collision with the u8_strcmp() function in Solaris 11 libc. */
+extern int
+ u8_strcmp_gnu (const uint8_t *s1, const uint8_t *s2)
+ _UC_ATTRIBUTE_PURE;
+# define u8_strcmp u8_strcmp_gnu
+#else
+extern int
+ u8_strcmp (const uint8_t *s1, const uint8_t *s2)
+ _UC_ATTRIBUTE_PURE;
+#endif
+extern int
+ u16_strcmp (const uint16_t *s1, const uint16_t *s2)
+ _UC_ATTRIBUTE_PURE;
+extern int
+ u32_strcmp (const uint32_t *s1, const uint32_t *s2)
+ _UC_ATTRIBUTE_PURE;
+
+/* Compare S1 and S2 using the collation rules of the current locale.
+ Return -1 if S1 < S2, 0 if S1 = S2, 1 if S1 > S2.
+ Upon failure, set errno and return any value. */
+/* Similar to strcoll(), wcscoll(). */
+extern int
+ u8_strcoll (const uint8_t *s1, const uint8_t *s2);
+extern int
+ u16_strcoll (const uint16_t *s1, const uint16_t *s2);
+extern int
+ u32_strcoll (const uint32_t *s1, const uint32_t *s2);
+
+/* Compare no more than N units of S1 and S2. */
+/* Similar to strncmp(), wcsncmp(). */
+extern int
+ u8_strncmp (const uint8_t *s1, const uint8_t *s2, size_t n)
+ _UC_ATTRIBUTE_PURE;
+extern int
+ u16_strncmp (const uint16_t *s1, const uint16_t *s2, size_t n)
+ _UC_ATTRIBUTE_PURE;
+extern int
+ u32_strncmp (const uint32_t *s1, const uint32_t *s2, size_t n)
+ _UC_ATTRIBUTE_PURE;
+
+/* Duplicate S, returning an identical malloc'd string. */
+/* Similar to strdup(), wcsdup(). */
+extern uint8_t *
+ u8_strdup (const uint8_t *s);
+extern uint16_t *
+ u16_strdup (const uint16_t *s);
+extern uint32_t *
+ u32_strdup (const uint32_t *s);
+
+/* Find the first occurrence of UC in STR. */
+/* Similar to strchr(), wcschr(). */
+extern uint8_t *
+ u8_strchr (const uint8_t *str, ucs4_t uc)
+ _UC_ATTRIBUTE_PURE;
+extern uint16_t *
+ u16_strchr (const uint16_t *str, ucs4_t uc)
+ _UC_ATTRIBUTE_PURE;
+extern uint32_t *
+ u32_strchr (const uint32_t *str, ucs4_t uc)
+ _UC_ATTRIBUTE_PURE;
+
+/* Find the last occurrence of UC in STR. */
+/* Similar to strrchr(), wcsrchr(). */
+extern uint8_t *
+ u8_strrchr (const uint8_t *str, ucs4_t uc)
+ _UC_ATTRIBUTE_PURE;
+extern uint16_t *
+ u16_strrchr (const uint16_t *str, ucs4_t uc)
+ _UC_ATTRIBUTE_PURE;
+extern uint32_t *
+ u32_strrchr (const uint32_t *str, ucs4_t uc)
+ _UC_ATTRIBUTE_PURE;
+
+/* Return the length of the initial segment of STR which consists entirely
+ of Unicode characters not in REJECT. */
+/* Similar to strcspn(), wcscspn(). */
+extern size_t
+ u8_strcspn (const uint8_t *str, const uint8_t *reject)
+ _UC_ATTRIBUTE_PURE;
+extern size_t
+ u16_strcspn (const uint16_t *str, const uint16_t *reject)
+ _UC_ATTRIBUTE_PURE;
+extern size_t
+ u32_strcspn (const uint32_t *str, const uint32_t *reject)
+ _UC_ATTRIBUTE_PURE;
+
+/* Return the length of the initial segment of STR which consists entirely
+ of Unicode characters in ACCEPT. */
+/* Similar to strspn(), wcsspn(). */
+extern size_t
+ u8_strspn (const uint8_t *str, const uint8_t *accept)
+ _UC_ATTRIBUTE_PURE;
+extern size_t
+ u16_strspn (const uint16_t *str, const uint16_t *accept)
+ _UC_ATTRIBUTE_PURE;
+extern size_t
+ u32_strspn (const uint32_t *str, const uint32_t *accept)
+ _UC_ATTRIBUTE_PURE;
+
+/* Find the first occurrence in STR of any character in ACCEPT. */
+/* Similar to strpbrk(), wcspbrk(). */
+extern uint8_t *
+ u8_strpbrk (const uint8_t *str, const uint8_t *accept)
+ _UC_ATTRIBUTE_PURE;
+extern uint16_t *
+ u16_strpbrk (const uint16_t *str, const uint16_t *accept)
+ _UC_ATTRIBUTE_PURE;
+extern uint32_t *
+ u32_strpbrk (const uint32_t *str, const uint32_t *accept)
+ _UC_ATTRIBUTE_PURE;
+
+/* Find the first occurrence of NEEDLE in HAYSTACK. */
+/* Similar to strstr(), wcsstr(). */
+extern uint8_t *
+ u8_strstr (const uint8_t *haystack, const uint8_t *needle)
+ _UC_ATTRIBUTE_PURE;
+extern uint16_t *
+ u16_strstr (const uint16_t *haystack, const uint16_t *needle)
+ _UC_ATTRIBUTE_PURE;
+extern uint32_t *
+ u32_strstr (const uint32_t *haystack, const uint32_t *needle)
+ _UC_ATTRIBUTE_PURE;
+
+/* Test whether STR starts with PREFIX. */
+extern bool
+ u8_startswith (const uint8_t *str, const uint8_t *prefix)
+ _UC_ATTRIBUTE_PURE;
+extern bool
+ u16_startswith (const uint16_t *str, const uint16_t *prefix)
+ _UC_ATTRIBUTE_PURE;
+extern bool
+ u32_startswith (const uint32_t *str, const uint32_t *prefix)
+ _UC_ATTRIBUTE_PURE;
+
+/* Test whether STR ends with SUFFIX. */
+extern bool
+ u8_endswith (const uint8_t *str, const uint8_t *suffix)
+ _UC_ATTRIBUTE_PURE;
+extern bool
+ u16_endswith (const uint16_t *str, const uint16_t *suffix)
+ _UC_ATTRIBUTE_PURE;
+extern bool
+ u32_endswith (const uint32_t *str, const uint32_t *suffix)
+ _UC_ATTRIBUTE_PURE;
+
+/* Divide STR into tokens separated by characters in DELIM.
+ This interface is actually more similar to wcstok than to strtok. */
+/* Similar to strtok_r(), wcstok(). */
+extern uint8_t *
+ u8_strtok (uint8_t *str, const uint8_t *delim, uint8_t **ptr);
+extern uint16_t *
+ u16_strtok (uint16_t *str, const uint16_t *delim, uint16_t **ptr);
+extern uint32_t *
+ u32_strtok (uint32_t *str, const uint32_t *delim, uint32_t **ptr);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _UNISTR_H */
diff --git a/lib/unistr/u8-mbtoucr.c b/lib/unistr/u8-mbtoucr.c
new file mode 100644
index 0000000..48f9ca3
--- /dev/null
+++ b/lib/unistr/u8-mbtoucr.c
@@ -0,0 +1,285 @@
+/* Look at first character in UTF-8 string, returning an error code.
+ Copyright (C) 1999-2002, 2006-2007, 2009-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2001.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include "unistr.h"
+
+int
+u8_mbtoucr (ucs4_t *puc, const uint8_t *s, size_t n)
+{
+ uint8_t c = *s;
+
+ if (c < 0x80)
+ {
+ *puc = c;
+ return 1;
+ }
+ else if (c >= 0xc2)
+ {
+ if (c < 0xe0)
+ {
+ if (n >= 2)
+ {
+ if ((s[1] ^ 0x80) < 0x40)
+ {
+ *puc = ((unsigned int) (c & 0x1f) << 6)
+ | (unsigned int) (s[1] ^ 0x80);
+ return 2;
+ }
+ /* invalid multibyte character */
+ }
+ else
+ {
+ /* incomplete multibyte character */
+ *puc = 0xfffd;
+ return -2;
+ }
+ }
+ else if (c < 0xf0)
+ {
+ if (n >= 2)
+ {
+ if ((s[1] ^ 0x80) < 0x40
+ && (c >= 0xe1 || s[1] >= 0xa0)
+ && (c != 0xed || s[1] < 0xa0))
+ {
+ if (n >= 3)
+ {
+ if ((s[2] ^ 0x80) < 0x40)
+ {
+ *puc = ((unsigned int) (c & 0x0f) << 12)
+ | ((unsigned int) (s[1] ^ 0x80) << 6)
+ | (unsigned int) (s[2] ^ 0x80);
+ return 3;
+ }
+ /* invalid multibyte character */
+ }
+ else
+ {
+ /* incomplete multibyte character */
+ *puc = 0xfffd;
+ return -2;
+ }
+ }
+ /* invalid multibyte character */
+ }
+ else
+ {
+ /* incomplete multibyte character */
+ *puc = 0xfffd;
+ return -2;
+ }
+ }
+ else if (c < 0xf8)
+ {
+ if (n >= 2)
+ {
+ if ((s[1] ^ 0x80) < 0x40
+ && (c >= 0xf1 || s[1] >= 0x90)
+#if 1
+ && (c < 0xf4 || (c == 0xf4 && s[1] < 0x90))
+#endif
+ )
+ {
+ if (n >= 3)
+ {
+ if ((s[2] ^ 0x80) < 0x40)
+ {
+ if (n >= 4)
+ {
+ if ((s[3] ^ 0x80) < 0x40)
+ {
+ *puc = ((unsigned int) (c & 0x07) << 18)
+ | ((unsigned int) (s[1] ^ 0x80) << 12)
+ | ((unsigned int) (s[2] ^ 0x80) << 6)
+ | (unsigned int) (s[3] ^ 0x80);
+ return 4;
+ }
+ /* invalid multibyte character */
+ }
+ else
+ {
+ /* incomplete multibyte character */
+ *puc = 0xfffd;
+ return -2;
+ }
+ }
+ /* invalid multibyte character */
+ }
+ else
+ {
+ /* incomplete multibyte character */
+ *puc = 0xfffd;
+ return -2;
+ }
+ }
+ /* invalid multibyte character */
+ }
+ else
+ {
+ /* incomplete multibyte character */
+ *puc = 0xfffd;
+ return -2;
+ }
+ }
+#if 0
+ else if (c < 0xfc)
+ {
+ if (n >= 2)
+ {
+ if ((s[1] ^ 0x80) < 0x40
+ && (c >= 0xf9 || s[1] >= 0x88))
+ {
+ if (n >= 3)
+ {
+ if ((s[2] ^ 0x80) < 0x40)
+ {
+ if (n >= 4)
+ {
+ if ((s[3] ^ 0x80) < 0x40)
+ {
+ if (n >= 5)
+ {
+ if ((s[4] ^ 0x80) < 0x40)
+ {
+ *puc = ((unsigned int) (c & 0x03) << 24)
+ | ((unsigned int) (s[1] ^ 0x80) << 18)
+ | ((unsigned int) (s[2] ^ 0x80) << 12)
+ | ((unsigned int) (s[3] ^ 0x80) << 6)
+ | (unsigned int) (s[4] ^ 0x80);
+ return 5;
+ }
+ /* invalid multibyte character */
+ }
+ else
+ {
+ /* incomplete multibyte character */
+ *puc = 0xfffd;
+ return -2;
+ }
+ }
+ /* invalid multibyte character */
+ }
+ else
+ {
+ /* incomplete multibyte character */
+ *puc = 0xfffd;
+ return -2;
+ }
+ }
+ /* invalid multibyte character */
+ }
+ else
+ {
+ /* incomplete multibyte character */
+ *puc = 0xfffd;
+ return -2;
+ }
+ }
+ /* invalid multibyte character */
+ }
+ else
+ {
+ /* incomplete multibyte character */
+ *puc = 0xfffd;
+ return -2;
+ }
+ }
+ else if (c < 0xfe)
+ {
+ if (n >= 2)
+ {
+ if ((s[1] ^ 0x80) < 0x40
+ && (c >= 0xfd || s[1] >= 0x84))
+ {
+ if (n >= 3)
+ {
+ if ((s[2] ^ 0x80) < 0x40)
+ {
+ if (n >= 4)
+ {
+ if ((s[3] ^ 0x80) < 0x40)
+ {
+ if (n >= 5)
+ {
+ if ((s[4] ^ 0x80) < 0x40)
+ {
+ if (n >= 6)
+ {
+ if ((s[5] ^ 0x80) < 0x40)
+ {
+ *puc = ((unsigned int) (c & 0x01) << 30)
+ | ((unsigned int) (s[1] ^ 0x80) << 24)
+ | ((unsigned int) (s[2] ^ 0x80) << 18)
+ | ((unsigned int) (s[3] ^ 0x80) << 12)
+ | ((unsigned int) (s[4] ^ 0x80) << 6)
+ | (unsigned int) (s[5] ^ 0x80);
+ return 6;
+ }
+ /* invalid multibyte character */
+ }
+ else
+ {
+ /* incomplete multibyte character */
+ *puc = 0xfffd;
+ return -2;
+ }
+ }
+ /* invalid multibyte character */
+ }
+ else
+ {
+ /* incomplete multibyte character */
+ *puc = 0xfffd;
+ return -2;
+ }
+ }
+ /* invalid multibyte character */
+ }
+ else
+ {
+ /* incomplete multibyte character */
+ *puc = 0xfffd;
+ return -2;
+ }
+ }
+ /* invalid multibyte character */
+ }
+ else
+ {
+ /* incomplete multibyte character */
+ *puc = 0xfffd;
+ return -2;
+ }
+ }
+ /* invalid multibyte character */
+ }
+ else
+ {
+ /* incomplete multibyte character */
+ *puc = 0xfffd;
+ return -2;
+ }
+ }
+#endif
+ }
+ /* invalid multibyte character */
+ *puc = 0xfffd;
+ return -1;
+}
diff --git a/lib/unistr/u8-uctomb-aux.c b/lib/unistr/u8-uctomb-aux.c
new file mode 100644
index 0000000..d5ff1d6
--- /dev/null
+++ b/lib/unistr/u8-uctomb-aux.c
@@ -0,0 +1,69 @@
+/* Conversion UCS-4 to UTF-8.
+ Copyright (C) 2002, 2006-2007, 2009-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2002.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include "unistr.h"
+
+int
+u8_uctomb_aux (uint8_t *s, ucs4_t uc, int n)
+{
+ int count;
+
+ if (uc < 0x80)
+ /* The case n >= 1 is already handled by the caller. */
+ return -2;
+ else if (uc < 0x800)
+ count = 2;
+ else if (uc < 0x10000)
+ {
+ if (uc < 0xd800 || uc >= 0xe000)
+ count = 3;
+ else
+ return -1;
+ }
+#if 0
+ else if (uc < 0x200000)
+ count = 4;
+ else if (uc < 0x4000000)
+ count = 5;
+ else if (uc <= 0x7fffffff)
+ count = 6;
+#else
+ else if (uc < 0x110000)
+ count = 4;
+#endif
+ else
+ return -1;
+
+ if (n < count)
+ return -2;
+
+ switch (count) /* note: code falls through cases! */
+ {
+#if 0
+ case 6: s[5] = 0x80 | (uc & 0x3f); uc = uc >> 6; uc |= 0x4000000;
+ case 5: s[4] = 0x80 | (uc & 0x3f); uc = uc >> 6; uc |= 0x200000;
+#endif
+ case 4: s[3] = 0x80 | (uc & 0x3f); uc = uc >> 6; uc |= 0x10000;
+ case 3: s[2] = 0x80 | (uc & 0x3f); uc = uc >> 6; uc |= 0x800;
+ case 2: s[1] = 0x80 | (uc & 0x3f); uc = uc >> 6; uc |= 0xc0;
+ /*case 1:*/ s[0] = uc;
+ }
+ return count;
+}
diff --git a/lib/unistr/u8-uctomb.c b/lib/unistr/u8-uctomb.c
new file mode 100644
index 0000000..419a6b4
--- /dev/null
+++ b/lib/unistr/u8-uctomb.c
@@ -0,0 +1,88 @@
+/* Store a character in UTF-8 string.
+ Copyright (C) 2002, 2005-2006, 2009-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2002.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+#if defined IN_LIBUNISTRING
+/* Tell unistr.h to declare u8_uctomb as 'extern', not 'static inline'. */
+# include "unistring-notinline.h"
+#endif
+
+/* Specification. */
+#include "unistr.h"
+
+#if !HAVE_INLINE
+
+int
+u8_uctomb (uint8_t *s, ucs4_t uc, int n)
+{
+ if (uc < 0x80)
+ {
+ if (n > 0)
+ {
+ s[0] = uc;
+ return 1;
+ }
+ /* else return -2, below. */
+ }
+ else
+ {
+ int count;
+
+ if (uc < 0x800)
+ count = 2;
+ else if (uc < 0x10000)
+ {
+ if (uc < 0xd800 || uc >= 0xe000)
+ count = 3;
+ else
+ return -1;
+ }
+#if 0
+ else if (uc < 0x200000)
+ count = 4;
+ else if (uc < 0x4000000)
+ count = 5;
+ else if (uc <= 0x7fffffff)
+ count = 6;
+#else
+ else if (uc < 0x110000)
+ count = 4;
+#endif
+ else
+ return -1;
+
+ if (n >= count)
+ {
+ switch (count) /* note: code falls through cases! */
+ {
+#if 0
+ case 6: s[5] = 0x80 | (uc & 0x3f); uc = uc >> 6; uc |= 0x4000000;
+ case 5: s[4] = 0x80 | (uc & 0x3f); uc = uc >> 6; uc |= 0x200000;
+#endif
+ case 4: s[3] = 0x80 | (uc & 0x3f); uc = uc >> 6; uc |= 0x10000;
+ case 3: s[2] = 0x80 | (uc & 0x3f); uc = uc >> 6; uc |= 0x800;
+ case 2: s[1] = 0x80 | (uc & 0x3f); uc = uc >> 6; uc |= 0xc0;
+ /*case 1:*/ s[0] = uc;
+ }
+ return count;
+ }
+ }
+ return -2;
+}
+
+#endif
diff --git a/lib/unitypes.in.h b/lib/unitypes.in.h
new file mode 100644
index 0000000..c6ca0ba
--- /dev/null
+++ b/lib/unitypes.in.h
@@ -0,0 +1,46 @@
+/* Elementary types and macros for the GNU UniString library.
+ Copyright (C) 2002, 2005-2006, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _UNITYPES_H
+#define _UNITYPES_H
+
+/* Get uint8_t, uint16_t, uint32_t. */
+#include <stdint.h>
+
+/* Type representing a Unicode character. */
+typedef uint32_t ucs4_t;
+
+/* Attribute of a function whose result depends only on the arguments
+ (not pointers!) and which has no side effects. */
+#ifndef _UC_ATTRIBUTE_CONST
+# if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 95)
+# define _UC_ATTRIBUTE_CONST __attribute__ ((__const__))
+# else
+# define _UC_ATTRIBUTE_CONST
+# endif
+#endif
+
+/* Attribute of a function whose result depends only on the arguments
+ (possibly pointers) and global memory, and which has no side effects. */
+#ifndef _UC_ATTRIBUTE_PURE
+# if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96)
+# define _UC_ATTRIBUTE_PURE __attribute__ ((__pure__))
+# else
+# define _UC_ATTRIBUTE_PURE
+# endif
+#endif
+
+#endif /* _UNITYPES_H */
diff --git a/lib/uniwidth.in.h b/lib/uniwidth.in.h
new file mode 100644
index 0000000..0ab6d25
--- /dev/null
+++ b/lib/uniwidth.in.h
@@ -0,0 +1,72 @@
+/* Display width functions.
+ Copyright (C) 2001-2002, 2005, 2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _UNIWIDTH_H
+#define _UNIWIDTH_H
+
+#include "unitypes.h"
+
+/* Get size_t. */
+#include <stddef.h>
+
+/* Get locale_charset() declaration. */
+#include "localcharset.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/* Display width. */
+
+/* These functions are locale dependent. The encoding argument identifies
+ the encoding (e.g. "ISO-8859-2" for Polish). */
+
+/* Determine number of column positions required for UC. */
+extern int
+ uc_width (ucs4_t uc, const char *encoding)
+ _UC_ATTRIBUTE_PURE;
+
+/* Determine number of column positions required for first N units
+ (or fewer if S ends before this) in S. */
+extern int
+ u8_width (const uint8_t *s, size_t n, const char *encoding)
+ _UC_ATTRIBUTE_PURE;
+extern int
+ u16_width (const uint16_t *s, size_t n, const char *encoding)
+ _UC_ATTRIBUTE_PURE;
+extern int
+ u32_width (const uint32_t *s, size_t n, const char *encoding)
+ _UC_ATTRIBUTE_PURE;
+
+/* Determine number of column positions required for S. */
+extern int
+ u8_strwidth (const uint8_t *s, const char *encoding)
+ _UC_ATTRIBUTE_PURE;
+extern int
+ u16_strwidth (const uint16_t *s, const char *encoding)
+ _UC_ATTRIBUTE_PURE;
+extern int
+ u32_strwidth (const uint32_t *s, const char *encoding)
+ _UC_ATTRIBUTE_PURE;
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _UNIWIDTH_H */
diff --git a/lib/uniwidth/cjk.h b/lib/uniwidth/cjk.h
new file mode 100644
index 0000000..0eac6fe
--- /dev/null
+++ b/lib/uniwidth/cjk.h
@@ -0,0 +1,37 @@
+/* Test for CJK encoding.
+ Copyright (C) 2001-2002, 2005-2007, 2009-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2002.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+#include "streq.h"
+
+static int
+is_cjk_encoding (const char *encoding)
+{
+ if (0
+ /* Legacy Japanese encodings */
+ || STREQ_OPT (encoding, "EUC-JP", 'E', 'U', 'C', '-', 'J', 'P', 0, 0, 0)
+ /* Legacy Chinese encodings */
+ || STREQ_OPT (encoding, "GB2312", 'G', 'B', '2', '3', '1', '2', 0, 0, 0)
+ || STREQ_OPT (encoding, "GBK", 'G', 'B', 'K', 0, 0, 0, 0, 0, 0)
+ || STREQ_OPT (encoding, "EUC-TW", 'E', 'U', 'C', '-', 'T', 'W', 0, 0, 0)
+ || STREQ_OPT (encoding, "BIG5", 'B', 'I', 'G', '5', 0, 0, 0, 0, 0)
+ /* Legacy Korean encodings */
+ || STREQ_OPT (encoding, "EUC-KR", 'E', 'U', 'C', '-', 'K', 'R', 0, 0, 0)
+ || STREQ_OPT (encoding, "CP949", 'C', 'P', '9', '4', '9', 0, 0, 0, 0)
+ || STREQ_OPT (encoding, "JOHAB", 'J', 'O', 'H', 'A', 'B', 0, 0, 0, 0))
+ return 1;
+ return 0;
+}
diff --git a/lib/uniwidth/width.c b/lib/uniwidth/width.c
new file mode 100644
index 0000000..bd3b3fc
--- /dev/null
+++ b/lib/uniwidth/width.c
@@ -0,0 +1,450 @@
+/* Determine display width of Unicode character.
+ Copyright (C) 2001-2002, 2006-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2002.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include "uniwidth.h"
+
+#include "cjk.h"
+
+/*
+ * Non-spacing attribute table.
+ * Consists of:
+ * - Non-spacing characters; generated from PropList.txt or
+ * "grep '^[^;]*;[^;]*;[^;]*;[^;]*;NSM;' UnicodeData.txt"
+ * - Format control characters; generated from
+ * "grep '^[^;]*;[^;]*;Cf;' UnicodeData.txt"
+ * - Zero width characters; generated from
+ * "grep '^[^;]*;ZERO WIDTH ' UnicodeData.txt"
+ */
+static const unsigned char nonspacing_table_data[36*64] = {
+ /* 0x0000-0x01ff */
+ 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, /* 0x0000-0x003f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, /* 0x0040-0x007f */
+ 0xff, 0xff, 0xff, 0xff, 0x00, 0x20, 0x00, 0x00, /* 0x0080-0x00bf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00c0-0x00ff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x0100-0x013f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x0140-0x017f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x0180-0x01bf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x01c0-0x01ff */
+ /* 0x0200-0x03ff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x0200-0x023f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x0240-0x027f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x0280-0x02bf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x02c0-0x02ff */
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x0300-0x033f */
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, /* 0x0340-0x037f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x0380-0x03bf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x03c0-0x03ff */
+ /* 0x0400-0x05ff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x0400-0x043f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x0440-0x047f */
+ 0xf8, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x0480-0x04bf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x04c0-0x04ff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x0500-0x053f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x0540-0x057f */
+ 0x00, 0x00, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xbf, /* 0x0580-0x05bf */
+ 0xb6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x05c0-0x05ff */
+ /* 0x0600-0x07ff */
+ 0x3f, 0x00, 0xff, 0x17, 0x00, 0x00, 0x00, 0x00, /* 0x0600-0x063f */
+ 0x00, 0xf8, 0xff, 0xff, 0x00, 0x00, 0x01, 0x00, /* 0x0640-0x067f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x0680-0x06bf */
+ 0x00, 0x00, 0xc0, 0xbf, 0x9f, 0x3d, 0x00, 0x00, /* 0x06c0-0x06ff */
+ 0x00, 0x80, 0x02, 0x00, 0x00, 0x00, 0xff, 0xff, /* 0x0700-0x073f */
+ 0xff, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x0740-0x077f */
+ 0x00, 0x00, 0x00, 0x00, 0xc0, 0xff, 0x01, 0x00, /* 0x0780-0x07bf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x0f, 0x00, /* 0x07c0-0x07ff */
+ /* 0x0800-0x09ff */
+ 0x00, 0x00, 0xc0, 0xfb, 0xef, 0x3e, 0x00, 0x00, /* 0x0800-0x083f */
+ 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x00, /* 0x0840-0x087f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x0880-0x08bf */
+ 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0xff, 0xff, /* 0x08c0-0x08ff */
+ 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, /* 0x0900-0x093f */
+ 0xfe, 0x21, 0xfe, 0x00, 0x0c, 0x00, 0x00, 0x00, /* 0x0940-0x097f */
+ 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, /* 0x0980-0x09bf */
+ 0x1e, 0x20, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, /* 0x09c0-0x09ff */
+ /* 0x0a00-0x0bff */
+ 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, /* 0x0a00-0x0a3f */
+ 0x86, 0x39, 0x02, 0x00, 0x00, 0x00, 0x23, 0x00, /* 0x0a40-0x0a7f */
+ 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, /* 0x0a80-0x0abf */
+ 0xbe, 0x21, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, /* 0x0ac0-0x0aff */
+ 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x90, /* 0x0b00-0x0b3f */
+ 0x1e, 0x20, 0x40, 0x00, 0x0c, 0x00, 0x00, 0x00, /* 0x0b40-0x0b7f */
+ 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x0b80-0x0bbf */
+ 0x01, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x0bc0-0x0bff */
+ /* 0x0c00-0x0dff */
+ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, /* 0x0c00-0x0c3f */
+ 0xc1, 0x3d, 0x60, 0x00, 0x0c, 0x00, 0x00, 0x00, /* 0x0c40-0x0c7f */
+ 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, /* 0x0c80-0x0cbf */
+ 0x00, 0x30, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, /* 0x0cc0-0x0cff */
+ 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x0d00-0x0d3f */
+ 0x1e, 0x20, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, /* 0x0d40-0x0d7f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x0d80-0x0dbf */
+ 0x00, 0x04, 0x5c, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x0dc0-0x0dff */
+ /* 0x0e00-0x0fff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf2, 0x07, /* 0x0e00-0x0e3f */
+ 0x80, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x0e40-0x0e7f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf2, 0x1b, /* 0x0e80-0x0ebf */
+ 0x00, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x0ec0-0x0eff */
+ 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0xa0, 0x02, /* 0x0f00-0x0f3f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x7f, /* 0x0f40-0x0f7f */
+ 0xdf, 0xe0, 0xff, 0xfe, 0xff, 0xff, 0xff, 0x1f, /* 0x0f80-0x0fbf */
+ 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x0fc0-0x0fff */
+ /* 0x1000-0x11ff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xfd, 0x66, /* 0x1000-0x103f */
+ 0x00, 0x00, 0x00, 0xc3, 0x01, 0x00, 0x1e, 0x00, /* 0x1040-0x107f */
+ 0x64, 0x20, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, /* 0x1080-0x10bf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10c0-0x10ff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1100-0x113f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1140-0x117f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1180-0x11bf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x11c0-0x11ff */
+ /* 0x1200-0x13ff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1200-0x123f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1240-0x127f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1280-0x12bf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x12c0-0x12ff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1300-0x133f */
+ 0x00, 0x00, 0x00, 0xe0, 0x00, 0x00, 0x00, 0x00, /* 0x1340-0x137f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1380-0x13bf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x13c0-0x13ff */
+ /* 0x1600-0x17ff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1600-0x163f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1640-0x167f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1680-0x16bf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x16c0-0x16ff */
+ 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x1c, 0x00, /* 0x1700-0x173f */
+ 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x0c, 0x00, /* 0x1740-0x177f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xb0, 0x3f, /* 0x1780-0x17bf */
+ 0x40, 0xfe, 0x0f, 0x20, 0x00, 0x00, 0x00, 0x00, /* 0x17c0-0x17ff */
+ /* 0x1800-0x19ff */
+ 0x00, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1800-0x183f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1840-0x187f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, /* 0x1880-0x18bf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18c0-0x18ff */
+ 0x00, 0x00, 0x00, 0x00, 0x87, 0x01, 0x04, 0x0e, /* 0x1900-0x193f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1940-0x197f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1980-0x19bf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x19c0-0x19ff */
+ /* 0x1a00-0x1bff */
+ 0x00, 0x00, 0x80, 0x09, 0x00, 0x00, 0x00, 0x00, /* 0x1a00-0x1a3f */
+ 0x00, 0x00, 0x40, 0x7f, 0xe5, 0x1f, 0xf8, 0x9f, /* 0x1a40-0x1a7f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x7f, /* 0x1a80-0x1abf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1ac0-0x1aff */
+ 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd0, 0x17, /* 0x1b00-0x1b3f */
+ 0x04, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x0f, 0x00, /* 0x1b40-0x1b7f */
+ 0x03, 0x00, 0x00, 0x00, 0x3c, 0x3b, 0x00, 0x00, /* 0x1b80-0x1bbf */
+ 0x00, 0x00, 0x00, 0x00, 0x40, 0xa3, 0x03, 0x00, /* 0x1bc0-0x1bff */
+ /* 0x1c00-0x1dff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xcf, 0x00, /* 0x1c00-0x1c3f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1c40-0x1c7f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1c80-0x1cbf */
+ 0x00, 0x00, 0xf7, 0xff, 0xfd, 0x21, 0x10, 0x03, /* 0x1cc0-0x1cff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1d00-0x1d3f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1d40-0x1d7f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1d80-0x1dbf */
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3f, 0xf0, /* 0x1dc0-0x1dff */
+ /* 0x2000-0x21ff */
+ 0x00, 0xf8, 0x00, 0x00, 0x00, 0x7c, 0x00, 0x00, /* 0x2000-0x203f */
+ 0x00, 0x00, 0x00, 0x00, 0xdf, 0xff, 0x00, 0x00, /* 0x2040-0x207f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x2080-0x20bf */
+ 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, /* 0x20c0-0x20ff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x2100-0x213f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x2140-0x217f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x2180-0x21bf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x21c0-0x21ff */
+ /* 0x2c00-0x2dff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x2c00-0x2c3f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x2c40-0x2c7f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x2c80-0x2cbf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x03, 0x00, /* 0x2cc0-0x2cff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x2d00-0x2d3f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, /* 0x2d40-0x2d7f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x2d80-0x2dbf */
+ 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, /* 0x2dc0-0x2dff */
+ /* 0x3000-0x31ff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00, /* 0x3000-0x303f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x3040-0x307f */
+ 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, /* 0x3080-0x30bf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30c0-0x30ff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x3100-0x313f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x3140-0x317f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x3180-0x31bf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x31c0-0x31ff */
+ /* 0xa600-0xa7ff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa600-0xa63f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xf7, 0x3f, /* 0xa640-0xa67f */
+ 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, /* 0xa680-0xa6bf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, /* 0xa6c0-0xa6ff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa700-0xa73f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa740-0xa77f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa780-0xa7bf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa7c0-0xa7ff */
+ /* 0xa800-0xa9ff */
+ 0x44, 0x08, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00, /* 0xa800-0xa83f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa840-0xa87f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa880-0xa8bf */
+ 0x10, 0x00, 0x00, 0x00, 0xff, 0xff, 0x03, 0x00, /* 0xa8c0-0xa8ff */
+ 0x00, 0x00, 0x00, 0x00, 0xc0, 0x3f, 0x00, 0x00, /* 0xa900-0xa93f */
+ 0x80, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa940-0xa97f */
+ 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc8, 0x13, /* 0xa980-0xa9bf */
+ 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, /* 0xa9c0-0xa9ff */
+ /* 0xaa00-0xabff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x7e, 0x66, 0x00, /* 0xaa00-0xaa3f */
+ 0x08, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, /* 0xaa40-0xaa7f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x9d, 0xc1, /* 0xaa80-0xaabf */
+ 0x02, 0x00, 0x00, 0x00, 0x00, 0x30, 0x40, 0x00, /* 0xaac0-0xaaff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xab00-0xab3f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xab40-0xab7f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xab80-0xabbf */
+ 0x00, 0x00, 0x00, 0x00, 0x20, 0x21, 0x00, 0x00, /* 0xabc0-0xabff */
+ /* 0xfa00-0xfbff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xfa00-0xfa3f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xfa40-0xfa7f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xfa80-0xfabf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xfac0-0xfaff */
+ 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, /* 0xfb00-0xfb3f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xfb40-0xfb7f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xfb80-0xfbbf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xfbc0-0xfbff */
+ /* 0xfe00-0xffff */
+ 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, /* 0xfe00-0xfe3f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xfe40-0xfe7f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xfe80-0xfebf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, /* 0xfec0-0xfeff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xff00-0xff3f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xff40-0xff7f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xff80-0xffbf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, /* 0xffc0-0xffff */
+ /* 0x10000-0x101ff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10000-0x1003f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10040-0x1007f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10080-0x100bf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x100c0-0x100ff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10100-0x1013f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10140-0x1017f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10180-0x101bf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, /* 0x101c0-0x101ff */
+ /* 0x10200-0x103ff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10200-0x1023f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10240-0x1027f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10280-0x102bf */
+ 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, /* 0x102c0-0x102ff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10300-0x1033f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x07, /* 0x10340-0x1037f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10380-0x103bf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x103c0-0x103ff */
+ /* 0x10a00-0x10bff */
+ 0x6e, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x87, /* 0x10a00-0x10a3f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10a40-0x10a7f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10a80-0x10abf */
+ 0x00, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00, /* 0x10ac0-0x10aff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10b00-0x10b3f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10b40-0x10b7f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10b80-0x10bbf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10bc0-0x10bff */
+ /* 0x11000-0x111ff */
+ 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, /* 0x11000-0x1103f */
+ 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, /* 0x11040-0x1107f */
+ 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x26, /* 0x11080-0x110bf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x110c0-0x110ff */
+ 0x07, 0x00, 0x00, 0x00, 0x80, 0xef, 0x1f, 0x00, /* 0x11100-0x1113f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, /* 0x11140-0x1117f */
+ 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x7f, /* 0x11180-0x111bf */
+ 0x00, 0x1c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x111c0-0x111ff */
+ /* 0x11200-0x113ff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xd3, 0x00, /* 0x11200-0x1123f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x11240-0x1127f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x11280-0x112bf */
+ 0x00, 0x00, 0x00, 0x80, 0xf8, 0x07, 0x00, 0x00, /* 0x112c0-0x112ff */
+ 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, /* 0x11300-0x1133f */
+ 0x01, 0x00, 0x00, 0x00, 0xc0, 0x1f, 0x1f, 0x00, /* 0x11340-0x1137f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x11380-0x113bf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x113c0-0x113ff */
+ /* 0x11400-0x115ff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x11400-0x1143f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x11440-0x1147f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x85, /* 0x11480-0x114bf */
+ 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x114c0-0x114ff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x11500-0x1153f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x11540-0x1157f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0xb0, /* 0x11580-0x115bf */
+ 0x01, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00, /* 0x115c0-0x115ff */
+ /* 0x11600-0x117ff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xa7, /* 0x11600-0x1163f */
+ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x11640-0x1167f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x28, 0xbf, 0x00, /* 0x11680-0x116bf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x116c0-0x116ff */
+ 0x00, 0x00, 0x00, 0xe0, 0xbc, 0x0f, 0x00, 0x00, /* 0x11700-0x1173f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x11740-0x1177f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x11780-0x117bf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x117c0-0x117ff */
+ /* 0x16a00-0x16bff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x16a00-0x16a3f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x16a40-0x16a7f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x16a80-0x16abf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x00, /* 0x16ac0-0x16aff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7f, 0x00, /* 0x16b00-0x16b3f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x16b40-0x16b7f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x16b80-0x16bbf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x16bc0-0x16bff */
+ /* 0x16e00-0x16fff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x16e00-0x16e3f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x16e40-0x16e7f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x16e80-0x16ebf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x16ec0-0x16eff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x16f00-0x16f3f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x16f40-0x16f7f */
+ 0x00, 0x80, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x16f80-0x16fbf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x16fc0-0x16fff */
+ /* 0x1bc00-0x1bdff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1bc00-0x1bc3f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1bc40-0x1bc7f */
+ 0x00, 0x00, 0x00, 0x60, 0x0f, 0x00, 0x00, 0x00, /* 0x1bc80-0x1bcbf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1bcc0-0x1bcff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1bd00-0x1bd3f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1bd40-0x1bd7f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1bd80-0x1bdbf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1bdc0-0x1bdff */
+ /* 0x1d000-0x1d1ff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1d000-0x1d03f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1d040-0x1d07f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1d080-0x1d0bf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1d0c0-0x1d0ff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1d100-0x1d13f */
+ 0x00, 0x00, 0x00, 0x00, 0x80, 0x03, 0xf8, 0xff, /* 0x1d140-0x1d17f */
+ 0xe7, 0x0f, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00, /* 0x1d180-0x1d1bf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1d1c0-0x1d1ff */
+ /* 0x1d200-0x1d3ff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1d200-0x1d23f */
+ 0x1c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1d240-0x1d27f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1d280-0x1d2bf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1d2c0-0x1d2ff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1d300-0x1d33f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1d340-0x1d37f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1d380-0x1d3bf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1d3c0-0x1d3ff */
+ /* 0x1da00-0x1dbff */
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0xf8, /* 0x1da00-0x1da3f */
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x20, 0x00, /* 0x1da40-0x1da7f */
+ 0x10, 0x00, 0x00, 0xf8, 0xfe, 0xff, 0x00, 0x00, /* 0x1da80-0x1dabf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1dac0-0x1daff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1db00-0x1db3f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1db40-0x1db7f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1db80-0x1dbbf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1dbc0-0x1dbff */
+ /* 0x1e800-0x1e9ff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1e800-0x1e83f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1e840-0x1e87f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1e880-0x1e8bf */
+ 0x00, 0x00, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1e8c0-0x1e8ff */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1e900-0x1e93f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1e940-0x1e97f */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x1e980-0x1e9bf */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 /* 0x1e9c0-0x1e9ff */
+};
+static const signed char nonspacing_table_ind[248] = {
+ 0, 1, 2, 3, 4, 5, 6, 7, /* 0x0000-0x0fff */
+ 8, 9, -1, 10, 11, 12, 13, -1, /* 0x1000-0x1fff */
+ 14, -1, -1, -1, -1, -1, 15, -1, /* 0x2000-0x2fff */
+ 16, -1, -1, -1, -1, -1, -1, -1, /* 0x3000-0x3fff */
+ -1, -1, -1, -1, -1, -1, -1, -1, /* 0x4000-0x4fff */
+ -1, -1, -1, -1, -1, -1, -1, -1, /* 0x5000-0x5fff */
+ -1, -1, -1, -1, -1, -1, -1, -1, /* 0x6000-0x6fff */
+ -1, -1, -1, -1, -1, -1, -1, -1, /* 0x7000-0x7fff */
+ -1, -1, -1, -1, -1, -1, -1, -1, /* 0x8000-0x8fff */
+ -1, -1, -1, -1, -1, -1, -1, -1, /* 0x9000-0x9fff */
+ -1, -1, -1, 17, 18, 19, -1, -1, /* 0xa000-0xafff */
+ -1, -1, -1, -1, -1, -1, -1, -1, /* 0xb000-0xbfff */
+ -1, -1, -1, -1, -1, -1, -1, -1, /* 0xc000-0xcfff */
+ -1, -1, -1, -1, -1, -1, -1, -1, /* 0xd000-0xdfff */
+ -1, -1, -1, -1, -1, -1, -1, -1, /* 0xe000-0xefff */
+ -1, -1, -1, -1, -1, 20, -1, 21, /* 0xf000-0xffff */
+ 22, 23, -1, -1, -1, 24, -1, -1, /* 0x10000-0x10fff */
+ 25, 26, 27, 28, -1, -1, -1, -1, /* 0x11000-0x11fff */
+ -1, -1, -1, -1, -1, -1, -1, -1, /* 0x12000-0x12fff */
+ -1, -1, -1, -1, -1, -1, -1, -1, /* 0x13000-0x13fff */
+ -1, -1, -1, -1, -1, -1, -1, -1, /* 0x14000-0x14fff */
+ -1, -1, -1, -1, -1, -1, -1, -1, /* 0x15000-0x15fff */
+ -1, -1, -1, -1, -1, 29, -1, 30, /* 0x16000-0x16fff */
+ -1, -1, -1, -1, -1, -1, -1, -1, /* 0x17000-0x17fff */
+ -1, -1, -1, -1, -1, -1, -1, -1, /* 0x18000-0x18fff */
+ -1, -1, -1, -1, -1, -1, -1, -1, /* 0x19000-0x19fff */
+ -1, -1, -1, -1, -1, -1, -1, -1, /* 0x1a000-0x1afff */
+ -1, -1, -1, -1, -1, -1, 31, -1, /* 0x1b000-0x1bfff */
+ -1, -1, -1, -1, -1, -1, -1, -1, /* 0x1c000-0x1cfff */
+ 32, 33, -1, -1, -1, 34, -1, -1, /* 0x1d000-0x1dfff */
+ -1, -1, -1, -1, 35, -1, -1, -1 /* 0x1e000-0x1efff */
+};
+
+/* Determine number of column positions required for UC. */
+int
+uc_width (ucs4_t uc, const char *encoding)
+{
+ /* Test for non-spacing or control character. */
+ if ((uc >> 9) < 248)
+ {
+ int ind = nonspacing_table_ind[uc >> 9];
+ if (ind >= 0)
+ if ((nonspacing_table_data[64*ind + ((uc >> 3) & 63)] >> (uc & 7)) & 1)
+ {
+ if (uc > 0 && uc < 0xa0)
+ return -1;
+ else
+ return 0;
+ }
+ }
+ else if ((uc >> 9) == (0xe0000 >> 9))
+ {
+ if (uc >= 0xe0100)
+ {
+ if (uc <= 0xe01ef)
+ return 0;
+ }
+ else
+ {
+ if (uc >= 0xe0020 ? uc <= 0xe007f : uc == 0xe0001)
+ return 0;
+ }
+ }
+ /* Test for double-width character.
+ * Generated from "grep '^[^;]\{4,5\};[WF]' EastAsianWidth.txt"
+ * and "grep '^[^;]\{4,5\};[^WF]' EastAsianWidth.txt"
+ */
+ if (uc >= 0x1100
+ && ((uc < 0x1160) /* Hangul Jamo */
+ || (uc >= 0x2329 && uc < 0x232b) /* Angle Brackets */
+ || (uc >= 0x2e80 && uc < 0xa4d0 /* CJK ... Yi */
+ && !(uc == 0x303f) && !(uc >= 0x4dc0 && uc < 0x4e00))
+ || (uc >= 0xac00 && uc < 0xd7a4) /* Hangul Syllables */
+ || (uc >= 0xf900 && uc < 0xfb00) /* CJK Compatibility Ideographs */
+ || (uc >= 0xfe10 && uc < 0xfe20) /* Presentation Forms for Vertical */
+ || (uc >= 0xfe30 && uc < 0xfe70) /* CJK Compatibility Forms */
+ || (uc >= 0xff00 && uc < 0xff61) /* Fullwidth Forms */
+ || (uc >= 0xffe0 && uc < 0xffe7) /* Fullwidth Signs */
+ || (uc >= 0x20000 && uc <= 0x2ffff) /* Supplementary Ideographic Plane */
+ || (uc >= 0x30000 && uc <= 0x3ffff) /* Tertiary Ideographic Plane */
+ ) )
+ return 2;
+ /* In ancient CJK encodings, Cyrillic and most other characters are
+ double-width as well. */
+ if (uc >= 0x00A1 && uc < 0xFF61 && uc != 0x20A9
+ && is_cjk_encoding (encoding))
+ return 2;
+ return 1;
+}
diff --git a/lib/unlink.c b/lib/unlink.c
new file mode 100644
index 0000000..10c0498
--- /dev/null
+++ b/lib/unlink.c
@@ -0,0 +1,97 @@
+/* Work around unlink bugs.
+
+ Copyright (C) 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+#include <unistd.h>
+
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+
+#include "dosname.h"
+
+#undef unlink
+
+/* Remove file NAME.
+ Return 0 if successful, -1 if not. */
+
+int
+rpl_unlink (char const *name)
+{
+ /* Work around Solaris 9 bug where unlink("file/") succeeds. */
+ size_t len = strlen (name);
+ int result = 0;
+ if (len && ISSLASH (name[len - 1]))
+ {
+ /* We can't unlink(2) something if it doesn't exist. If it does
+ exist, then it resolved to a directory, due to the trailing
+ slash, and POSIX requires that the unlink attempt to remove
+ that directory (which would leave the symlink dangling).
+ Unfortunately, Solaris 9 is one of the platforms where the
+ root user can unlink directories, and we don't want to
+ cripple this behavior on real directories, even if it is
+ seldom needed (at any rate, it's nicer to let coreutils'
+ unlink(1) give the correct errno for non-root users). But we
+ don't know whether name was an actual directory, or a symlink
+ to a directory; and due to the bug of ignoring trailing
+ slash, Solaris 9 would end up successfully unlinking the
+ symlink instead of the directory. Technically, we could use
+ realpath to find the canonical directory name to attempt
+ deletion on. But that is a lot of work for a corner case; so
+ we instead just use an lstat on the shortened name, and
+ reject symlinks with trailing slashes. The root user of
+ unlink(1) will just have to live with the rule that they
+ can't delete a directory via a symlink. */
+ struct stat st;
+ result = lstat (name, &st);
+ if (result == 0)
+ {
+ /* Trailing NUL will overwrite the trailing slash. */
+ char *short_name = malloc (len);
+ if (!short_name)
+ {
+ errno = EPERM;
+ return -1;
+ }
+ memcpy (short_name, name, len);
+ while (len && ISSLASH (short_name[len - 1]))
+ short_name[--len] = '\0';
+ if (len && (lstat (short_name, &st) || S_ISLNK (st.st_mode)))
+ {
+ free (short_name);
+ errno = EPERM;
+ return -1;
+ }
+ free (short_name);
+ }
+ }
+ if (!result)
+ {
+#if UNLINK_PARENT_BUG
+ if (len >= 2 && name[len - 1] == '.' && name[len - 2] == '.'
+ && (len == 2 || ISSLASH (name[len - 3])))
+ {
+ errno = EISDIR; /* could also use EPERM */
+ return -1;
+ }
+#endif
+ result = unlink (name);
+ }
+ return result;
+}
diff --git a/lib/unlinkat.c b/lib/unlinkat.c
new file mode 100644
index 0000000..c89bc9c
--- /dev/null
+++ b/lib/unlinkat.c
@@ -0,0 +1,122 @@
+/* Work around unlinkat bugs on Solaris 9 and Hurd.
+
+ Copyright (C) 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Eric Blake. */
+
+#include <config.h>
+
+#include <unistd.h>
+
+#include <errno.h>
+#include <fcntl.h>
+#include <string.h>
+#include <sys/stat.h>
+
+#include <stdlib.h>
+
+#include "dosname.h"
+#include "openat.h"
+
+#if HAVE_UNLINKAT
+
+# undef unlinkat
+
+/* unlinkat without AT_REMOVEDIR does not honor trailing / on Solaris 9.
+ Hurd has the same issue.
+
+ unlinkat without AT_REMOVEDIR erroneously ignores ".." on Darwin 14.
+
+ Solve these in a similar manner to unlink. */
+
+int
+rpl_unlinkat (int fd, char const *name, int flag)
+{
+ size_t len;
+ int result = 0;
+ /* rmdir behavior has no problems with trailing slash. */
+ if (flag & AT_REMOVEDIR)
+ return unlinkat (fd, name, flag);
+
+ len = strlen (name);
+ if (len && ISSLASH (name[len - 1]))
+ {
+ /* See the lengthy comment in unlink.c why we disobey the POSIX
+ rule of letting unlink("link-to-dir/") attempt to unlink a
+ directory. */
+ struct stat st;
+ result = lstatat (fd, name, &st);
+ if (result == 0)
+ {
+ /* Trailing NUL will overwrite the trailing slash. */
+ char *short_name = malloc (len);
+ if (!short_name)
+ {
+ errno = EPERM;
+ return -1;
+ }
+ memcpy (short_name, name, len);
+ while (len && ISSLASH (short_name[len - 1]))
+ short_name[--len] = '\0';
+ if (len && (lstatat (fd, short_name, &st) || S_ISLNK (st.st_mode)))
+ {
+ free (short_name);
+ errno = EPERM;
+ return -1;
+ }
+ free (short_name);
+ }
+ }
+ if (!result)
+ {
+# if UNLINK_PARENT_BUG
+ if (len >= 2 && name[len - 1] == '.' && name[len - 2] == '.'
+ && (len == 2 || ISSLASH (name[len - 3])))
+ {
+ errno = EISDIR; /* could also use EPERM */
+ return -1;
+ }
+# endif
+ result = unlinkat (fd, name, flag);
+ }
+ return result;
+}
+
+#else /* !HAVE_UNLINKAT */
+
+/* Replacement for Solaris' function by the same name.
+ <http://www.google.com/search?q=unlinkat+site:docs.sun.com>
+ First, try to simulate it via (unlink|rmdir) ("/proc/self/fd/FD/FILE").
+ Failing that, simulate it via save_cwd/fchdir/(unlink|rmdir)/restore_cwd.
+ If either the save_cwd or the restore_cwd fails (relatively unlikely),
+ then give a diagnostic and exit nonzero.
+ Otherwise, this function works just like Solaris' unlinkat. */
+
+# define AT_FUNC_NAME unlinkat
+# define AT_FUNC_F1 rmdir
+# define AT_FUNC_F2 unlink
+# define AT_FUNC_USE_F1_COND AT_REMOVEDIR
+# define AT_FUNC_POST_FILE_PARAM_DECLS , int flag
+# define AT_FUNC_POST_FILE_ARGS /* empty */
+# include "at-func.c"
+# undef AT_FUNC_NAME
+# undef AT_FUNC_F1
+# undef AT_FUNC_F2
+# undef AT_FUNC_USE_F1_COND
+# undef AT_FUNC_POST_FILE_PARAM_DECLS
+# undef AT_FUNC_POST_FILE_ARGS
+
+#endif /* !HAVE_UNLINKAT */
diff --git a/lib/unlinkdir.c b/lib/unlinkdir.c
deleted file mode 100644
index 07620db..0000000
--- a/lib/unlinkdir.c
+++ /dev/null
@@ -1,68 +0,0 @@
-/* unlinkdir.c - determine (and maybe change) whether we can unlink directories
-
- Copyright (C) 2005, 2006 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-/* Written by Paul Eggert and Jim Meyering. */
-
-#include <config.h>
-
-#include "unlinkdir.h"
-
-#if HAVE_PRIV_H
-# include <priv.h>
-#endif
-#include <unistd.h>
-
-#if ! UNLINK_CANNOT_UNLINK_DIR
-
-/* Return true if we cannot unlink directories, false if we might be
- able to unlink directories. If possible, tell the kernel we don't
- want to be able to unlink directories, so that we can return true. */
-
-bool
-cannot_unlink_dir (void)
-{
- static bool initialized;
- static bool cannot;
-
- if (! initialized)
- {
-# if defined PRIV_EFFECTIVE && defined PRIV_SYS_LINKDIR
- /* We might be able to unlink directories if we cannot
- determine our privileges, or if we have the
- PRIV_SYS_LINKDIR privilege and cannot delete it. */
- priv_set_t *pset = priv_allocset ();
- if (pset)
- {
- cannot =
- (getppriv (PRIV_EFFECTIVE, pset) == 0
- && (! priv_ismember (pset, PRIV_SYS_LINKDIR)
- || (priv_delset (pset, PRIV_SYS_LINKDIR) == 0
- && setppriv (PRIV_SET, PRIV_EFFECTIVE, pset) == 0)));
- priv_freeset (pset);
- }
-# else
- /* In traditional Unix, only root can unlink directories. */
- cannot = (geteuid () != 0);
-# endif
- initialized = true;
- }
-
- return cannot;
-}
-
-#endif
diff --git a/lib/unlinkdir.h b/lib/unlinkdir.h
deleted file mode 100644
index 6582418..0000000
--- a/lib/unlinkdir.h
+++ /dev/null
@@ -1,27 +0,0 @@
-/* unlinkdir.h - determine (and maybe change) whether we can unlink directories
-
- Copyright (C) 2005 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-/* Written by Paul Eggert and Jim Meyering. */
-
-#include <stdbool.h>
-
-#if UNLINK_CANNOT_UNLINK_DIR
-# define cannot_unlink_dir() true
-#else
-bool cannot_unlink_dir (void);
-#endif
diff --git a/lib/unlocked-io.h b/lib/unlocked-io.h
index d009303..c0ece50 100644
--- a/lib/unlocked-io.h
+++ b/lib/unlocked-io.h
@@ -1,20 +1,19 @@
/* Prefer faster, non-thread-safe stdio functions if available.
- Copyright (C) 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
+ Copyright (C) 2001-2004, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Jim Meyering. */
diff --git a/lib/unsetenv.c b/lib/unsetenv.c
index 0f83744..8368744 100644
--- a/lib/unsetenv.c
+++ b/lib/unsetenv.c
@@ -1,44 +1,46 @@
-/* Copyright (C) 1992,1995-1999,2000-2002,2005-2006 Free Software Foundation, Inc.
+/* Copyright (C) 1992, 1995-2002, 2005-2016 Free Software Foundation, Inc.
This file is part of the GNU C Library.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
+
+/* Don't use __attribute__ __nonnull__ in this compilation unit. Otherwise gcc
+ optimizes away the name == NULL test below. */
+#define _GL_ARG_NONNULL(params)
#include <config.h>
+/* Specification. */
+#include <stdlib.h>
+
#include <errno.h>
#if !_LIBC
# define __set_errno(ev) ((errno) = (ev))
#endif
-#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#if !_LIBC
-# define __environ environ
-# ifndef HAVE_ENVIRON_DECL
-extern char **environ;
-# endif
+# define __environ environ
#endif
#if _LIBC
-/* This lock protects against simultaneous modifications of `environ'. */
+/* This lock protects against simultaneous modifications of 'environ'. */
# include <bits/libc-lock.h>
__libc_lock_define_initialized (static, envlock)
-# define LOCK __libc_lock_lock (envlock)
-# define UNLOCK __libc_lock_unlock (envlock)
+# define LOCK __libc_lock_lock (envlock)
+# define UNLOCK __libc_lock_unlock (envlock)
#else
# define LOCK
# define UNLOCK
@@ -49,6 +51,7 @@ __libc_lock_define_initialized (static, envlock)
# define unsetenv __unsetenv
#endif
+#if _LIBC || !HAVE_UNSETENV
int
unsetenv (const char *name)
@@ -70,13 +73,13 @@ unsetenv (const char *name)
while (*ep != NULL)
if (!strncmp (*ep, name, len) && (*ep)[len] == '=')
{
- /* Found it. Remove this pointer by moving later ones back. */
- char **dp = ep;
+ /* Found it. Remove this pointer by moving later ones back. */
+ char **dp = ep;
- do
- dp[0] = dp[1];
- while (*dp++);
- /* Continue the loop in case NAME appears again. */
+ do
+ dp[0] = dp[1];
+ while (*dp++);
+ /* Continue the loop in case NAME appears again. */
}
else
++ep;
@@ -90,3 +93,35 @@ unsetenv (const char *name)
# undef unsetenv
weak_alias (__unsetenv, unsetenv)
#endif
+
+#else /* HAVE_UNSETENV */
+
+# undef unsetenv
+# if !HAVE_DECL_UNSETENV
+# if VOID_UNSETENV
+extern void unsetenv (const char *);
+# else
+extern int unsetenv (const char *);
+# endif
+# endif
+
+/* Call the underlying unsetenv, in case there is hidden bookkeeping
+ that needs updating beyond just modifying environ. */
+int
+rpl_unsetenv (const char *name)
+{
+ int result = 0;
+ if (!name || !*name || strchr (name, '='))
+ {
+ errno = EINVAL;
+ return -1;
+ }
+ while (getenv (name))
+# if !VOID_UNSETENV
+ result =
+# endif
+ unsetenv (name);
+ return result;
+}
+
+#endif /* HAVE_UNSETENV */
diff --git a/lib/userspec.c b/lib/userspec.c
index c1f580a..62cdc0f 100644
--- a/lib/userspec.c
+++ b/lib/userspec.c
@@ -1,11 +1,11 @@
/* userspec.c -- Parse a user and group string.
- Copyright (C) 1989-1992, 1997-1998, 2000, 2002-2007 Free Software
+ Copyright (C) 1989-1992, 1997-1998, 2000, 2002-2016 Free Software
Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by David MacKenzie <djm@gnu.ai.mit.edu>. */
@@ -72,16 +71,16 @@
# define MAXGID GID_T_MAX
#endif
+#ifdef __DJGPP__
+
/* ISDIGIT differs from isdigit, as follows:
- Its arg may be any int or unsigned int; it need not be an unsigned char
or EOF.
- It's typically faster.
POSIX says that only '0' through '9' are digits. Prefer ISDIGIT to
isdigit unless it's important to use the locale's definition
- of `digit' even when the host does not conform to POSIX. */
-#define ISDIGIT(c) ((unsigned int) (c) - '0' <= 9)
-
-#ifdef __DJGPP__
+ of "digit" even when the host does not conform to POSIX. */
+# define ISDIGIT(c) ((unsigned int) (c) - '0' <= 9)
/* Return true if STR represents an unsigned decimal integer. */
@@ -91,7 +90,7 @@ is_number (const char *str)
do
{
if (!ISDIGIT (*str))
- return false;
+ return false;
}
while (*++str);
@@ -101,8 +100,8 @@ is_number (const char *str)
static char const *
parse_with_separator (char const *spec, char const *separator,
- uid_t *uid, gid_t *gid,
- char **username, char **groupname)
+ uid_t *uid, gid_t *gid,
+ char **username, char **groupname)
{
static const char *E_invalid_user = N_("invalid user");
static const char *E_invalid_group = N_("invalid group");
@@ -115,10 +114,13 @@ parse_with_separator (char const *spec, char const *separator,
char const *g;
char *gname = NULL;
uid_t unum = *uid;
- gid_t gnum = *gid;
+ gid_t gnum = gid ? *gid : -1;
error_msg = NULL;
- *username = *groupname = NULL;
+ if (username)
+ *username = NULL;
+ if (groupname)
+ *groupname = NULL;
/* Set U and G to nonzero length strings corresponding to user and
group specifiers or to NULL. If U is not NULL, it is a newly
@@ -128,16 +130,16 @@ parse_with_separator (char const *spec, char const *separator,
if (separator == NULL)
{
if (*spec)
- u = xstrdup (spec);
+ u = xstrdup (spec);
}
else
{
size_t ulen = separator - spec;
if (ulen != 0)
- {
- u = xmemdup (spec, ulen + 1);
- u[ulen] = '\0';
- }
+ {
+ u = xmemdup (spec, ulen + 1);
+ u[ulen] = '\0';
+ }
}
g = (separator == NULL || *(separator + 1) == '\0'
@@ -146,7 +148,7 @@ parse_with_separator (char const *spec, char const *separator,
#ifdef __DJGPP__
/* Pretend that we are the user U whose group is G. This makes
- pwd and grp functions ``know'' about the UID and GID of these. */
+ pwd and grp functions "know" about the UID and GID of these. */
if (u && !is_number (u))
setenv ("USER", u, 1);
if (g && !is_number (g))
@@ -158,38 +160,38 @@ parse_with_separator (char const *spec, char const *separator,
/* If it starts with "+", skip the look-up. */
pwd = (*u == '+' ? NULL : getpwnam (u));
if (pwd == NULL)
- {
- bool use_login_group = (separator != NULL && g == NULL);
- if (use_login_group)
- {
- /* If there is no group,
- then there may not be a trailing ":", either. */
- error_msg = E_bad_spec;
- }
- else
- {
- unsigned long int tmp;
- if (xstrtoul (u, NULL, 10, &tmp, "") == LONGINT_OK
- && tmp <= MAXUID)
- unum = tmp;
- else
- error_msg = E_invalid_user;
- }
- }
+ {
+ bool use_login_group = (separator != NULL && g == NULL);
+ if (use_login_group)
+ {
+ /* If there is no group,
+ then there may not be a trailing ":", either. */
+ error_msg = E_bad_spec;
+ }
+ else
+ {
+ unsigned long int tmp;
+ if (xstrtoul (u, NULL, 10, &tmp, "") == LONGINT_OK
+ && tmp <= MAXUID && (uid_t) tmp != (uid_t) -1)
+ unum = tmp;
+ else
+ error_msg = E_invalid_user;
+ }
+ }
else
- {
- unum = pwd->pw_uid;
- if (g == NULL && separator != NULL)
- {
- /* A separator was given, but a group was not specified,
- so get the login group. */
- char buf[INT_BUFSIZE_BOUND (uintmax_t)];
- gnum = pwd->pw_gid;
- grp = getgrgid (gnum);
- gname = xstrdup (grp ? grp->gr_name : umaxtostr (gnum, buf));
- endgrent ();
- }
- }
+ {
+ unum = pwd->pw_uid;
+ if (g == NULL && separator != NULL)
+ {
+ /* A separator was given, but a group was not specified,
+ so get the login group. */
+ char buf[INT_BUFSIZE_BOUND (uintmax_t)];
+ gnum = pwd->pw_gid;
+ grp = getgrgid (gnum);
+ gname = xstrdup (grp ? grp->gr_name : umaxtostr (gnum, buf));
+ endgrent ();
+ }
+ }
endpwent ();
}
@@ -199,43 +201,53 @@ parse_with_separator (char const *spec, char const *separator,
/* If it starts with "+", skip the look-up. */
grp = (*g == '+' ? NULL : getgrnam (g));
if (grp == NULL)
- {
- unsigned long int tmp;
- if (xstrtoul (g, NULL, 10, &tmp, "") == LONGINT_OK && tmp <= MAXGID)
- gnum = tmp;
- else
- error_msg = E_invalid_group;
- }
+ {
+ unsigned long int tmp;
+ if (xstrtoul (g, NULL, 10, &tmp, "") == LONGINT_OK
+ && tmp <= MAXGID && (gid_t) tmp != (gid_t) -1)
+ gnum = tmp;
+ else
+ error_msg = E_invalid_group;
+ }
else
- gnum = grp->gr_gid;
- endgrent (); /* Save a file descriptor. */
+ gnum = grp->gr_gid;
+ endgrent (); /* Save a file descriptor. */
gname = xstrdup (g);
}
if (error_msg == NULL)
{
*uid = unum;
- *gid = gnum;
- *username = u;
- *groupname = gname;
- u = NULL;
+ if (gid)
+ *gid = gnum;
+ if (username)
+ {
+ *username = u;
+ u = NULL;
+ }
+ if (groupname)
+ {
+ *groupname = gname;
+ gname = NULL;
+ }
}
- else
- free (gname);
free (u);
- return _(error_msg);
+ free (gname);
+ return error_msg ? _(error_msg) : NULL;
}
/* Extract from SPEC, which has the form "[user][:.][group]",
a USERNAME, UID U, GROUPNAME, and GID G.
+ If the GID parameter is NULL the entire SPEC is treated as a user.
+ If the USERNAME and GROUPNAME parameters are NULL they're ignored.
Either user or group, or both, must be present.
If the group is omitted but the separator is given,
use the given user's login group.
- If SPEC contains a `:', then use that as the separator, ignoring
- any `.'s. If there is no `:', but there is a `.', then first look
+ If SPEC contains a ':', then use that as the separator, ignoring
+ any '.'s. If there is no ':', but there is a '.', then first look
up the entire SPEC as a login name. If that look-up fails, then
- try again interpreting the `.' as a separator.
+ try again interpreting the '.' as a separator.
USERNAME and GROUPNAME will be in newly malloc'd memory.
Either one might be NULL instead, indicating that it was not
@@ -245,24 +257,24 @@ parse_with_separator (char const *spec, char const *separator,
char const *
parse_user_spec (char const *spec, uid_t *uid, gid_t *gid,
- char **username, char **groupname)
+ char **username, char **groupname)
{
- char const *colon = strchr (spec, ':');
+ char const *colon = gid ? strchr (spec, ':') : NULL;
char const *error_msg =
parse_with_separator (spec, colon, uid, gid, username, groupname);
- if (!colon && error_msg)
+ if (gid && !colon && error_msg)
{
/* If there's no colon but there is a dot, and if looking up the
- whole spec failed (i.e., the spec is not a owner name that
- includes a dot), then try again, but interpret the dot as a
- separator. This is a compatible extension to POSIX, since
- the POSIX-required behavior is always tried first. */
+ whole spec failed (i.e., the spec is not an owner name that
+ includes a dot), then try again, but interpret the dot as a
+ separator. This is a compatible extension to POSIX, since
+ the POSIX-required behavior is always tried first. */
char const *dot = strchr (spec, '.');
if (dot
- && ! parse_with_separator (spec, dot, uid, gid, username, groupname))
- error_msg = NULL;
+ && ! parse_with_separator (spec, dot, uid, gid, username, groupname))
+ error_msg = NULL;
}
return error_msg;
@@ -289,15 +301,21 @@ main (int argc, char **argv)
e = parse_user_spec (tmp, &uid, &gid, &username, &groupname);
free (tmp);
printf ("%s: %lu %lu %s %s %s\n",
- argv[i],
- (unsigned long int) uid,
- (unsigned long int) gid,
- NULL_CHECK (username),
- NULL_CHECK (groupname),
- NULL_CHECK (e));
+ argv[i],
+ (unsigned long int) uid,
+ (unsigned long int) gid,
+ NULL_CHECK (username),
+ NULL_CHECK (groupname),
+ NULL_CHECK (e));
}
exit (0);
}
#endif
+
+/*
+Local Variables:
+indent-tabs-mode: nil
+End:
+*/
diff --git a/lib/userspec.h b/lib/userspec.h
index 8a09eae..67af845 100644
--- a/lib/userspec.h
+++ b/lib/userspec.h
@@ -5,6 +5,6 @@
const char *
parse_user_spec (const char *spec_arg, uid_t *uid, gid_t *gid,
- char **username_arg, char **groupname_arg);
+ char **username_arg, char **groupname_arg);
#endif
diff --git a/lib/utime.c b/lib/utime.c
deleted file mode 100644
index 273a5fb..0000000
--- a/lib/utime.c
+++ /dev/null
@@ -1,109 +0,0 @@
-/* Copyright (C) 1998, 2001, 2002, 2003, 2004, 2006 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-/* derived from a function in touch.c */
-
-#include <config.h>
-#undef utime
-
-#include <sys/types.h>
-
-#ifdef HAVE_UTIME_H
-# include <utime.h>
-#endif
-
-#if !HAVE_UTIMES_NULL
-# include <sys/stat.h>
-# include <fcntl.h>
-#endif
-
-#include <unistd.h>
-#include <errno.h>
-
-#include "full-write.h"
-#include "safe-read.h"
-
-/* Some systems (even some that do have <utime.h>) don't declare this
- structure anywhere. */
-#ifndef HAVE_STRUCT_UTIMBUF
-struct utimbuf
-{
- long actime;
- long modtime;
-};
-#endif
-
-/* The results of open() in this file are not used with fchdir,
- therefore save some unnecessary work in fchdir.c. */
-#undef open
-#undef close
-
-/* Emulate utime (file, NULL) for systems (like 4.3BSD) that do not
- interpret it to set the access and modification times of FILE to
- the current time. Return 0 if successful, -1 if not. */
-
-static int
-utime_null (const char *file)
-{
-#if HAVE_UTIMES_NULL
- return utimes (file, 0);
-#else
- int fd;
- char c;
- int status = 0;
- struct stat st;
- int saved_errno = 0;
-
- fd = open (file, O_RDWR);
- if (fd < 0
- || fstat (fd, &st) < 0
- || safe_read (fd, &c, sizeof c) == SAFE_READ_ERROR
- || lseek (fd, (off_t) 0, SEEK_SET) < 0
- || full_write (fd, &c, sizeof c) != sizeof c
- /* Maybe do this -- it's necessary on SunOS 4.1.3 with some combination
- of patches, but that system doesn't use this code: it has utimes.
- || fsync (fd) < 0
- */
- || (st.st_size == 0 && ftruncate (fd, st.st_size) < 0))
- {
- saved_errno = errno;
- status = -1;
- }
-
- if (0 <= fd)
- {
- if (close (fd) < 0)
- status = -1;
-
- /* If there was a prior failure, use the saved errno value.
- But if the only failure was in the close, don't change errno. */
- if (saved_errno)
- errno = saved_errno;
- }
-
- return status;
-#endif
-}
-
-int
-rpl_utime (const char *file, const struct utimbuf *times)
-{
- if (times)
- return utime (file, times);
-
- return utime_null (file);
-}
diff --git a/lib/utimecmp.c b/lib/utimecmp.c
index 051d03a..908fc1a 100644
--- a/lib/utimecmp.c
+++ b/lib/utimecmp.c
@@ -1,11 +1,11 @@
/* utimecmp.c -- compare file time stamps
- Copyright (C) 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
+ Copyright (C) 2004-2007, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
@@ -27,28 +26,31 @@
#include <stdint.h>
#include <stdlib.h>
#include <time.h>
+#include <unistd.h>
+
#include "hash.h"
#include "intprops.h"
#include "stat-time.h"
#include "utimens.h"
#include "verify.h"
-#include "xalloc.h"
#ifndef MAX
# define MAX(a, b) ((a) > (b) ? (a) : (b))
#endif
-enum { BILLION = 1000 * 1000 * 1000 };
+#define BILLION (1000 * 1000 * 1000)
/* Best possible resolution that utimens can set and stat can return,
due to system-call limitations. It must be a power of 10 that is
no greater than 1 billion. */
-#if (HAVE_WORKING_UTIMES \
- && (defined HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC \
- || defined HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC \
- || defined HAVE_STRUCT_STAT_ST_ATIMENSEC \
- || defined HAVE_STRUCT_STAT_ST_ATIM_ST__TIM_TV_NSEC \
- || defined HAVE_STRUCT_STAT_ST_SPARE1))
+#if HAVE_UTIMENSAT
+enum { SYSCALL_RESOLUTION = 1 };
+#elif ((HAVE_FUTIMESAT || HAVE_WORKING_UTIMES) \
+ && (defined HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC \
+ || defined HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC \
+ || defined HAVE_STRUCT_STAT_ST_ATIMENSEC \
+ || defined HAVE_STRUCT_STAT_ST_ATIM_ST__TIM_TV_NSEC \
+ || defined HAVE_STRUCT_STAT_ST_SPARE1))
enum { SYSCALL_RESOLUTION = 1000 };
#else
enum { SYSCALL_RESOLUTION = BILLION };
@@ -101,6 +103,8 @@ dev_info_compare (void const *x, void const *y)
DST_NAME and status DST_STAT) is older than SRC_STAT, the same age
as SRC_STAT, or newer than SRC_STAT, respectively.
+ DST_NAME may be NULL if OPTIONS is 0.
+
If OPTIONS & UTIMECMP_TRUNCATE_SOURCE, do the comparison after SRC is
converted to the destination's timestamp resolution as filtered through
utimens. In this case, return -2 if the exact answer cannot be
@@ -110,14 +114,16 @@ dev_info_compare (void const *x, void const *y)
int
utimecmp (char const *dst_name,
- struct stat const *dst_stat,
- struct stat const *src_stat,
- int options)
+ struct stat const *dst_stat,
+ struct stat const *src_stat,
+ int options)
{
/* Things to watch out for:
The code uses a static hash table internally and is not safe in the
- presence of signals, multiple threads, etc.
+ presence of signals, multiple threads, etc. However, memory pressure
+ that prevents use of the hash table is not fatal - we just fall back
+ to redoing the computations on every call in that case.
int and long int might be 32 bits. Many of the calculations store
numbers up to 2 billion, and multiply by 10; they have to avoid
@@ -138,179 +144,228 @@ utimecmp (char const *dst_name,
{
/* Look up the time stamp resolution for the destination device. */
- /* Hash table for devices. */
+ /* Hash table for caching information learned about devices. */
static Hash_table *ht;
/* Information about the destination file system. */
static struct fs_res *new_dst_res;
- struct fs_res *dst_res;
+ struct fs_res *dst_res = NULL;
+ struct fs_res tmp_dst_res;
/* Time stamp resolution in nanoseconds. */
int res;
+ /* Quick exit, if possible. Since the worst resolution is 2
+ seconds, anything that differs by more than that does not
+ needs source truncation. */
+ if (dst_s == src_s && dst_ns == src_ns)
+ return 0;
+ if (dst_s <= src_s - 2)
+ return -1;
+ if (src_s <= dst_s - 2)
+ return 1;
+
+ /* Try to do a hash lookup, but fall back to stack variables and
+ recomputation on low memory situations. */
if (! ht)
- ht = hash_initialize (16, NULL, dev_info_hash, dev_info_compare, free);
- if (! new_dst_res)
- {
- new_dst_res = xmalloc (sizeof *new_dst_res);
- new_dst_res->resolution = 2 * BILLION;
- new_dst_res->exact = false;
- }
- new_dst_res->dev = dst_stat->st_dev;
- dst_res = hash_insert (ht, new_dst_res);
- if (! dst_res)
- xalloc_die ();
-
- if (dst_res == new_dst_res)
- {
- /* NEW_DST_RES is now in use in the hash table, so allocate a
- new entry next time. */
- new_dst_res = NULL;
- }
+ ht = hash_initialize (16, NULL, dev_info_hash, dev_info_compare, free);
+ if (ht)
+ {
+ if (! new_dst_res)
+ {
+ new_dst_res = malloc (sizeof *new_dst_res);
+ if (!new_dst_res)
+ goto low_memory;
+ new_dst_res->resolution = 2 * BILLION;
+ new_dst_res->exact = false;
+ }
+ new_dst_res->dev = dst_stat->st_dev;
+ dst_res = hash_insert (ht, new_dst_res);
+ if (! dst_res)
+ goto low_memory;
+
+ if (dst_res == new_dst_res)
+ {
+ /* NEW_DST_RES is now in use in the hash table, so allocate a
+ new entry next time. */
+ new_dst_res = NULL;
+ }
+ }
+ else
+ {
+ low_memory:
+ if (ht)
+ {
+ tmp_dst_res.dev = dst_stat->st_dev;
+ dst_res = hash_lookup (ht, &tmp_dst_res);
+ }
+ if (!dst_res)
+ {
+ dst_res = &tmp_dst_res;
+ dst_res->resolution = 2 * BILLION;
+ dst_res->exact = false;
+ }
+ }
res = dst_res->resolution;
+#ifdef _PC_TIMESTAMP_RESOLUTION
+ /* If the system will tell us the resolution, we're set! */
+ if (! dst_res->exact)
+ {
+ res = pathconf (dst_name, _PC_TIMESTAMP_RESOLUTION);
+ if (0 < res)
+ {
+ dst_res->resolution = res;
+ dst_res->exact = true;
+ }
+ }
+#endif
+
if (! dst_res->exact)
- {
- /* This file system's resolution is not known exactly.
- Deduce it, and store the result in the hash table. */
-
- time_t dst_a_s = dst_stat->st_atime;
- time_t dst_c_s = dst_stat->st_ctime;
- time_t dst_m_s = dst_s;
- int dst_a_ns = get_stat_atime_ns (dst_stat);
- int dst_c_ns = get_stat_ctime_ns (dst_stat);
- int dst_m_ns = dst_ns;
-
- /* Set RES to an upper bound on the file system resolution
- (after truncation due to SYSCALL_RESOLUTION) by inspecting
- the atime, ctime and mtime of the existing destination.
- We don't know of any file system that stores atime or
- ctime with a higher precision than mtime, so it's valid to
- look at them too. */
- {
- bool odd_second = (dst_a_s | dst_c_s | dst_m_s) & 1;
-
- if (SYSCALL_RESOLUTION == BILLION)
- {
- if (odd_second | dst_a_ns | dst_c_ns | dst_m_ns)
- res = BILLION;
- }
- else
- {
- int a = dst_a_ns;
- int c = dst_c_ns;
- int m = dst_m_ns;
-
- /* Write it this way to avoid mistaken GCC warning
- about integer overflow in constant expression. */
- int SR10 = SYSCALL_RESOLUTION; SR10 *= 10;
-
- if ((a % SR10 | c % SR10 | m % SR10) != 0)
- res = SYSCALL_RESOLUTION;
- else
- for (res = SR10, a /= SR10, c /= SR10, m /= SR10;
- (res < dst_res->resolution
- && (a % 10 | c % 10 | m % 10) == 0);
- res *= 10, a /= 10, c /= 10, m /= 10)
- if (res == BILLION)
- {
- if (! odd_second)
- res *= 2;
- break;
- }
- }
-
- dst_res->resolution = res;
- }
-
- if (SYSCALL_RESOLUTION < res)
- {
- struct timespec timespec[2];
- struct stat dst_status;
-
- /* Ignore source time stamp information that must necessarily
- be lost when filtered through utimens. */
- src_ns -= src_ns % SYSCALL_RESOLUTION;
-
- /* If the time stamps disagree widely enough, there's no need
- to interrogate the file system to deduce the exact time
- stamp resolution; return the answer directly. */
- {
- time_t s = src_s & ~ (res == 2 * BILLION);
- if (src_s < dst_s || (src_s == dst_s && src_ns <= dst_ns))
- return 1;
- if (dst_s < s
- || (dst_s == s && dst_ns < src_ns - src_ns % res))
- return -1;
- }
-
- /* Determine the actual time stamp resolution for the
- destination file system (after truncation due to
- SYSCALL_RESOLUTION) by setting the access time stamp of the
- destination to the existing access time, except with
- trailing nonzero digits. */
-
- timespec[0].tv_sec = dst_a_s;
- timespec[0].tv_nsec = dst_a_ns;
- timespec[1].tv_sec = dst_m_s | (res == 2 * BILLION);
- timespec[1].tv_nsec = dst_m_ns + res / 9;
-
- /* Set the modification time. But don't try to set the
- modification time of symbolic links; on many hosts this sets
- the time of the pointed-to file. */
- if (S_ISLNK (dst_stat->st_mode)
- || utimens (dst_name, timespec) != 0)
- return -2;
-
- /* Read the modification time that was set. It's safe to call
- 'stat' here instead of worrying about 'lstat'; either the
- caller used 'stat', or the caller used 'lstat' and found
- something other than a symbolic link. */
- {
- int stat_result = stat (dst_name, &dst_status);
-
- if (stat_result
- | (dst_status.st_mtime ^ dst_m_s)
- | (get_stat_mtime_ns (&dst_status) ^ dst_m_ns))
- {
- /* The modification time changed, or we can't tell whether
- it changed. Change it back as best we can. */
- timespec[1].tv_sec = dst_m_s;
- timespec[1].tv_nsec = dst_m_ns;
- utimens (dst_name, timespec);
- }
-
- if (stat_result != 0)
- return -2;
- }
-
- /* Determine the exact resolution from the modification time
- that was read back. */
- {
- int old_res = res;
- int a = (BILLION * (dst_status.st_mtime & 1)
- + get_stat_mtime_ns (&dst_status));
-
- res = SYSCALL_RESOLUTION;
-
- for (a /= res; a % 10 != 0; a /= 10)
- {
- if (res == BILLION)
- {
- res *= 2;
- break;
- }
- res *= 10;
- if (res == old_res)
- break;
- }
- }
- }
-
- dst_res->resolution = res;
- dst_res->exact = true;
- }
+ {
+ /* This file system's resolution is not known exactly.
+ Deduce it, and store the result in the hash table. */
+
+ time_t dst_a_s = dst_stat->st_atime;
+ time_t dst_c_s = dst_stat->st_ctime;
+ time_t dst_m_s = dst_s;
+ int dst_a_ns = get_stat_atime_ns (dst_stat);
+ int dst_c_ns = get_stat_ctime_ns (dst_stat);
+ int dst_m_ns = dst_ns;
+
+ /* Set RES to an upper bound on the file system resolution
+ (after truncation due to SYSCALL_RESOLUTION) by inspecting
+ the atime, ctime and mtime of the existing destination.
+ We don't know of any file system that stores atime or
+ ctime with a higher precision than mtime, so it's valid to
+ look at them too. */
+ {
+ bool odd_second = (dst_a_s | dst_c_s | dst_m_s) & 1;
+
+ if (SYSCALL_RESOLUTION == BILLION)
+ {
+ if (odd_second | dst_a_ns | dst_c_ns | dst_m_ns)
+ res = BILLION;
+ }
+ else
+ {
+ int a = dst_a_ns;
+ int c = dst_c_ns;
+ int m = dst_m_ns;
+
+ /* Write it this way to avoid mistaken GCC warning
+ about integer overflow in constant expression. */
+ int SR10 = SYSCALL_RESOLUTION; SR10 *= 10;
+
+ if ((a % SR10 | c % SR10 | m % SR10) != 0)
+ res = SYSCALL_RESOLUTION;
+ else
+ for (res = SR10, a /= SR10, c /= SR10, m /= SR10;
+ (res < dst_res->resolution
+ && (a % 10 | c % 10 | m % 10) == 0);
+ res *= 10, a /= 10, c /= 10, m /= 10)
+ if (res == BILLION)
+ {
+ if (! odd_second)
+ res *= 2;
+ break;
+ }
+ }
+
+ dst_res->resolution = res;
+ }
+
+ if (SYSCALL_RESOLUTION < res)
+ {
+ struct timespec timespec[2];
+ struct stat dst_status;
+
+ /* Ignore source time stamp information that must necessarily
+ be lost when filtered through utimens. */
+ src_ns -= src_ns % SYSCALL_RESOLUTION;
+
+ /* If the time stamps disagree widely enough, there's no need
+ to interrogate the file system to deduce the exact time
+ stamp resolution; return the answer directly. */
+ {
+ time_t s = src_s & ~ (res == 2 * BILLION);
+ if (src_s < dst_s || (src_s == dst_s && src_ns <= dst_ns))
+ return 1;
+ if (dst_s < s
+ || (dst_s == s && dst_ns < src_ns - src_ns % res))
+ return -1;
+ }
+
+ /* Determine the actual time stamp resolution for the
+ destination file system (after truncation due to
+ SYSCALL_RESOLUTION) by setting the access time stamp of the
+ destination to the existing access time, except with
+ trailing nonzero digits. */
+
+ timespec[0].tv_sec = dst_a_s;
+ timespec[0].tv_nsec = dst_a_ns;
+ timespec[1].tv_sec = dst_m_s | (res == 2 * BILLION);
+ timespec[1].tv_nsec = dst_m_ns + res / 9;
+
+ /* Set the modification time. But don't try to set the
+ modification time of symbolic links; on many hosts this sets
+ the time of the pointed-to file. */
+ if ((S_ISLNK (dst_stat->st_mode)
+ ? lutimens (dst_name, timespec)
+ : utimens (dst_name, timespec)) != 0)
+ return -2;
+
+ /* Read the modification time that was set. */
+ {
+ int stat_result = (S_ISLNK (dst_stat->st_mode)
+ ? lstat (dst_name, &dst_status)
+ : stat (dst_name, &dst_status));
+
+ if (stat_result
+ | (dst_status.st_mtime ^ dst_m_s)
+ | (get_stat_mtime_ns (&dst_status) ^ dst_m_ns))
+ {
+ /* The modification time changed, or we can't tell whether
+ it changed. Change it back as best we can. */
+ timespec[1].tv_sec = dst_m_s;
+ timespec[1].tv_nsec = dst_m_ns;
+ if (S_ISLNK (dst_stat->st_mode))
+ lutimens (dst_name, timespec);
+ else
+ utimens (dst_name, timespec);
+ }
+
+ if (stat_result != 0)
+ return -2;
+ }
+
+ /* Determine the exact resolution from the modification time
+ that was read back. */
+ {
+ int old_res = res;
+ int a = (BILLION * (dst_status.st_mtime & 1)
+ + get_stat_mtime_ns (&dst_status));
+
+ res = SYSCALL_RESOLUTION;
+
+ for (a /= res; a % 10 == 0; a /= 10)
+ {
+ if (res == BILLION)
+ {
+ res *= 2;
+ break;
+ }
+ res *= 10;
+ if (res == old_res)
+ break;
+ }
+ }
+ }
+
+ dst_res->resolution = res;
+ dst_res->exact = true;
+ }
/* Truncate the source's time stamp according to the resolution. */
src_s &= ~ (res == 2 * BILLION);
@@ -319,7 +374,7 @@ utimecmp (char const *dst_name,
/* Compare the time stamps and return -1, 0, 1 accordingly. */
return (dst_s < src_s ? -1
- : dst_s > src_s ? 1
- : dst_ns < src_ns ? -1
- : dst_ns > src_ns);
+ : dst_s > src_s ? 1
+ : dst_ns < src_ns ? -1
+ : dst_ns > src_ns);
}
diff --git a/lib/utimecmp.h b/lib/utimecmp.h
index e82d15b..1df608f 100644
--- a/lib/utimecmp.h
+++ b/lib/utimecmp.h
@@ -1,11 +1,11 @@
/* utimecmp.h -- compare file time stamps
- Copyright (C) 2004 Free Software Foundation, Inc.
+ Copyright (C) 2004, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
diff --git a/lib/utimens.c b/lib/utimens.c
index 71bc510..ece9b07 100644
--- a/lib/utimens.c
+++ b/lib/utimens.c
@@ -1,11 +1,10 @@
/* Set file access and modification times.
- Copyright (C) 2003, 2004, 2005, 2006, 2007 Free Software
- Foundation, Inc.
+ Copyright (C) 2003-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify it
+ 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 2, or (at your option) any
+ Free Software Foundation; either version 3 of the License, or any
later version.
This program is distributed in the hope that it will be useful,
@@ -14,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
@@ -23,13 +21,19 @@
#include <config.h>
+#define _GL_UTIMENS_INLINE _GL_EXTERN_INLINE
#include "utimens.h"
#include <errno.h>
#include <fcntl.h>
+#include <stdbool.h>
+#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
+#include "stat-time.h"
+#include "timespec.h"
+
#if HAVE_UTIME_H
# include <utime.h>
#endif
@@ -44,25 +48,111 @@ struct utimbuf
};
#endif
-/* Some systems don't have ENOSYS. */
-#ifndef ENOSYS
-# ifdef ENOTSUP
-# define ENOSYS ENOTSUP
-# else
-/* Some systems don't have ENOTSUP either. */
-# define ENOSYS EINVAL
-# endif
-#endif
+/* Avoid recursion with rpl_futimens or rpl_utimensat. */
+#undef futimens
+#undef utimensat
-#ifndef __attribute__
-# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 8) || __STRICT_ANSI__
-# define __attribute__(x)
-# endif
+/* Solaris 9 mistakenly succeeds when given a non-directory with a
+ trailing slash. Force the use of rpl_stat for a fix. */
+#ifndef REPLACE_FUNC_STAT_FILE
+# define REPLACE_FUNC_STAT_FILE 0
#endif
-#ifndef ATTRIBUTE_UNUSED
-# define ATTRIBUTE_UNUSED __attribute__ ((__unused__))
-#endif
+#if HAVE_UTIMENSAT || HAVE_FUTIMENS
+/* Cache variables for whether the utimensat syscall works; used to
+ avoid calling the syscall if we know it will just fail with ENOSYS,
+ and to avoid unnecessary work in massaging timestamps if the
+ syscall will work. Multiple variables are needed, to distinguish
+ between the following scenarios on Linux:
+ utimensat doesn't exist, or is in glibc but kernel 2.6.18 fails with ENOSYS
+ kernel 2.6.22 and earlier rejects AT_SYMLINK_NOFOLLOW
+ kernel 2.6.25 and earlier reject UTIME_NOW/UTIME_OMIT with non-zero tv_sec
+ kernel 2.6.32 used with xfs or ntfs-3g fail to honor UTIME_OMIT
+ utimensat completely works
+ For each cache variable: 0 = unknown, 1 = yes, -1 = no. */
+static int utimensat_works_really;
+static int lutimensat_works_really;
+#endif /* HAVE_UTIMENSAT || HAVE_FUTIMENS */
+
+/* Validate the requested timestamps. Return 0 if the resulting
+ timespec can be used for utimensat (after possibly modifying it to
+ work around bugs in utimensat). Return a positive value if the
+ timespec needs further adjustment based on stat results: 1 if any
+ adjustment is needed for utimes, and 2 if any adjustment is needed
+ for Linux utimensat. Return -1, with errno set to EINVAL, if
+ timespec is out of range. */
+static int
+validate_timespec (struct timespec timespec[2])
+{
+ int result = 0;
+ int utime_omit_count = 0;
+ if ((timespec[0].tv_nsec != UTIME_NOW
+ && timespec[0].tv_nsec != UTIME_OMIT
+ && ! (0 <= timespec[0].tv_nsec
+ && timespec[0].tv_nsec < TIMESPEC_RESOLUTION))
+ || (timespec[1].tv_nsec != UTIME_NOW
+ && timespec[1].tv_nsec != UTIME_OMIT
+ && ! (0 <= timespec[1].tv_nsec
+ && timespec[1].tv_nsec < TIMESPEC_RESOLUTION)))
+ {
+ errno = EINVAL;
+ return -1;
+ }
+ /* Work around Linux kernel 2.6.25 bug, where utimensat fails with
+ EINVAL if tv_sec is not 0 when using the flag values of tv_nsec.
+ Flag a Linux kernel 2.6.32 bug, where an mtime of UTIME_OMIT
+ fails to bump ctime. */
+ if (timespec[0].tv_nsec == UTIME_NOW
+ || timespec[0].tv_nsec == UTIME_OMIT)
+ {
+ timespec[0].tv_sec = 0;
+ result = 1;
+ if (timespec[0].tv_nsec == UTIME_OMIT)
+ utime_omit_count++;
+ }
+ if (timespec[1].tv_nsec == UTIME_NOW
+ || timespec[1].tv_nsec == UTIME_OMIT)
+ {
+ timespec[1].tv_sec = 0;
+ result = 1;
+ if (timespec[1].tv_nsec == UTIME_OMIT)
+ utime_omit_count++;
+ }
+ return result + (utime_omit_count == 1);
+}
+
+/* Normalize any UTIME_NOW or UTIME_OMIT values in *TS, using stat
+ buffer STATBUF to obtain the current timestamps of the file. If
+ both times are UTIME_NOW, set *TS to NULL (as this can avoid some
+ permissions issues). If both times are UTIME_OMIT, return true
+ (nothing further beyond the prior collection of STATBUF is
+ necessary); otherwise return false. */
+static bool
+update_timespec (struct stat const *statbuf, struct timespec *ts[2])
+{
+ struct timespec *timespec = *ts;
+ if (timespec[0].tv_nsec == UTIME_OMIT
+ && timespec[1].tv_nsec == UTIME_OMIT)
+ return true;
+ if (timespec[0].tv_nsec == UTIME_NOW
+ && timespec[1].tv_nsec == UTIME_NOW)
+ {
+ *ts = NULL;
+ return false;
+ }
+
+ if (timespec[0].tv_nsec == UTIME_OMIT)
+ timespec[0] = get_stat_atime (statbuf);
+ else if (timespec[0].tv_nsec == UTIME_NOW)
+ gettime (&timespec[0]);
+
+ if (timespec[1].tv_nsec == UTIME_OMIT)
+ timespec[1] = get_stat_mtime (statbuf);
+ else if (timespec[1].tv_nsec == UTIME_NOW)
+ gettime (&timespec[1]);
+
+ return false;
+}
/* Set the access and modification time stamps of FD (a.k.a. FILE) to be
TIMESPEC[0] and TIMESPEC[1], respectively.
@@ -75,9 +165,31 @@ struct utimbuf
Return 0 on success, -1 (setting errno) on failure. */
int
-futimens (int fd ATTRIBUTE_UNUSED,
- char const *file, struct timespec const timespec[2])
+fdutimens (int fd, char const *file, struct timespec const timespec[2])
{
+ struct timespec adjusted_timespec[2];
+ struct timespec *ts = timespec ? adjusted_timespec : NULL;
+ int adjustment_needed = 0;
+ struct stat st;
+
+ if (ts)
+ {
+ adjusted_timespec[0] = timespec[0];
+ adjusted_timespec[1] = timespec[1];
+ adjustment_needed = validate_timespec (ts);
+ }
+ if (adjustment_needed < 0)
+ return -1;
+
+ /* Require that at least one of FD or FILE are potentially valid, to avoid
+ a Linux bug where futimens (AT_FDCWD, NULL) changes "." rather
+ than failing. */
+ if (fd < 0 && !file)
+ {
+ errno = EBADF;
+ return -1;
+ }
+
/* Some Linux-based NFS clients are buggy, and mishandle time stamps
of files in NFS file systems in some cases. We have no
configure-time test for this, but please see
@@ -95,95 +207,336 @@ futimens (int fd ATTRIBUTE_UNUSED,
fsync (fd);
#endif
- /* There's currently no interface to set file timestamps with
+ /* POSIX 2008 added two interfaces to set file timestamps with
+ nanosecond resolution; newer Linux implements both functions via
+ a single syscall. We provide a fallback for ENOSYS (for example,
+ compiling against Linux 2.6.25 kernel headers and glibc 2.7, but
+ running on Linux 2.6.18 kernel). */
+#if HAVE_UTIMENSAT || HAVE_FUTIMENS
+ if (0 <= utimensat_works_really)
+ {
+ int result;
+# if __linux__ || __sun
+ /* As recently as Linux kernel 2.6.32 (Dec 2009), several file
+ systems (xfs, ntfs-3g) have bugs with a single UTIME_OMIT,
+ but work if both times are either explicitly specified or
+ UTIME_NOW. Work around it with a preparatory [f]stat prior
+ to calling futimens/utimensat; fortunately, there is not much
+ timing impact due to the extra syscall even on file systems
+ where UTIME_OMIT would have worked.
+
+ The same bug occurs in Solaris 11.1 (Apr 2013).
+
+ FIXME: Simplify this for Linux in 2016 and for Solaris in
+ 2024, when file system bugs are no longer common. */
+ if (adjustment_needed == 2)
+ {
+ if (fd < 0 ? stat (file, &st) : fstat (fd, &st))
+ return -1;
+ if (ts[0].tv_nsec == UTIME_OMIT)
+ ts[0] = get_stat_atime (&st);
+ else if (ts[1].tv_nsec == UTIME_OMIT)
+ ts[1] = get_stat_mtime (&st);
+ /* Note that st is good, in case utimensat gives ENOSYS. */
+ adjustment_needed++;
+ }
+# endif
+# if HAVE_UTIMENSAT
+ if (fd < 0)
+ {
+ result = utimensat (AT_FDCWD, file, ts, 0);
+# ifdef __linux__
+ /* Work around a kernel bug:
+ http://bugzilla.redhat.com/442352
+ http://bugzilla.redhat.com/449910
+ It appears that utimensat can mistakenly return 280 rather
+ than -1 upon ENOSYS failure.
+ FIXME: remove in 2010 or whenever the offending kernels
+ are no longer in common use. */
+ if (0 < result)
+ errno = ENOSYS;
+# endif /* __linux__ */
+ if (result == 0 || errno != ENOSYS)
+ {
+ utimensat_works_really = 1;
+ return result;
+ }
+ }
+# endif /* HAVE_UTIMENSAT */
+# if HAVE_FUTIMENS
+ if (0 <= fd)
+ {
+ result = futimens (fd, ts);
+# ifdef __linux__
+ /* Work around the same bug as above. */
+ if (0 < result)
+ errno = ENOSYS;
+# endif /* __linux__ */
+ if (result == 0 || errno != ENOSYS)
+ {
+ utimensat_works_really = 1;
+ return result;
+ }
+ }
+# endif /* HAVE_FUTIMENS */
+ }
+ utimensat_works_really = -1;
+ lutimensat_works_really = -1;
+#endif /* HAVE_UTIMENSAT || HAVE_FUTIMENS */
+
+ /* The platform lacks an interface to set file timestamps with
nanosecond resolution, so do the best we can, discarding any
fractional part of the timestamp. */
-#if HAVE_FUTIMESAT || HAVE_WORKING_UTIMES
- struct timeval timeval[2];
- struct timeval const *t;
- if (timespec)
+
+ if (adjustment_needed || (REPLACE_FUNC_STAT_FILE && fd < 0))
{
- timeval[0].tv_sec = timespec[0].tv_sec;
- timeval[0].tv_usec = timespec[0].tv_nsec / 1000;
- timeval[1].tv_sec = timespec[1].tv_sec;
- timeval[1].tv_usec = timespec[1].tv_nsec / 1000;
- t = timeval;
+ if (adjustment_needed != 3
+ && (fd < 0 ? stat (file, &st) : fstat (fd, &st)))
+ return -1;
+ if (ts && update_timespec (&st, &ts))
+ return 0;
}
- else
- t = NULL;
+ {
+#if HAVE_FUTIMESAT || HAVE_WORKING_UTIMES
+ struct timeval timeval[2];
+ struct timeval *t;
+ if (ts)
+ {
+ timeval[0].tv_sec = ts[0].tv_sec;
+ timeval[0].tv_usec = ts[0].tv_nsec / 1000;
+ timeval[1].tv_sec = ts[1].tv_sec;
+ timeval[1].tv_usec = ts[1].tv_nsec / 1000;
+ t = timeval;
+ }
+ else
+ t = NULL;
- if (fd < 0)
- {
+ if (fd < 0)
+ {
# if HAVE_FUTIMESAT
- return futimesat (AT_FDCWD, file, t);
+ return futimesat (AT_FDCWD, file, t);
# endif
+ }
+ else
+ {
+ /* If futimesat or futimes fails here, don't try to speed things
+ up by returning right away. glibc can incorrectly fail with
+ errno == ENOENT if /proc isn't mounted. Also, Mandrake 10.0
+ in high security mode doesn't allow ordinary users to read
+ /proc/self, so glibc incorrectly fails with errno == EACCES.
+ If errno == EIO, EPERM, or EROFS, it's probably safe to fail
+ right away, but these cases are rare enough that they're not
+ worth optimizing, and who knows what other messed-up systems
+ are out there? So play it safe and fall back on the code
+ below. */
+
+# if (HAVE_FUTIMESAT && !FUTIMESAT_NULL_BUG) || HAVE_FUTIMES
+# if HAVE_FUTIMESAT && !FUTIMESAT_NULL_BUG
+# undef futimes
+# define futimes(fd, t) futimesat (fd, NULL, t)
+# endif
+ if (futimes (fd, t) == 0)
+ {
+# if __linux__ && __GLIBC__
+ /* Work around a longstanding glibc bug, still present as
+ of 2010-12-27. On older Linux kernels that lack both
+ utimensat and utimes, glibc's futimes rounds instead of
+ truncating when falling back on utime. The same bug
+ occurs in futimesat with a null 2nd arg. */
+ if (t)
+ {
+ bool abig = 500000 <= t[0].tv_usec;
+ bool mbig = 500000 <= t[1].tv_usec;
+ if ((abig | mbig) && fstat (fd, &st) == 0)
+ {
+ /* If these two subtractions overflow, they'll
+ track the overflows inside the buggy glibc. */
+ time_t adiff = st.st_atime - t[0].tv_sec;
+ time_t mdiff = st.st_mtime - t[1].tv_sec;
+
+ struct timeval *tt = NULL;
+ struct timeval truncated_timeval[2];
+ truncated_timeval[0] = t[0];
+ truncated_timeval[1] = t[1];
+ if (abig && adiff == 1 && get_stat_atime_ns (&st) == 0)
+ {
+ tt = truncated_timeval;
+ tt[0].tv_usec = 0;
+ }
+ if (mbig && mdiff == 1 && get_stat_mtime_ns (&st) == 0)
+ {
+ tt = truncated_timeval;
+ tt[1].tv_usec = 0;
+ }
+ if (tt)
+ futimes (fd, tt);
+ }
+ }
+# endif
+
+ return 0;
+ }
+# endif
+ }
+#endif /* HAVE_FUTIMESAT || HAVE_WORKING_UTIMES */
+
+ if (!file)
+ {
+#if ! ((HAVE_FUTIMESAT && !FUTIMESAT_NULL_BUG) \
+ || (HAVE_WORKING_UTIMES && HAVE_FUTIMES))
+ errno = ENOSYS;
+#endif
+ return -1;
+ }
+
+#if HAVE_WORKING_UTIMES
+ return utimes (file, t);
+#else
+ {
+ struct utimbuf utimbuf;
+ struct utimbuf *ut;
+ if (ts)
+ {
+ utimbuf.actime = ts[0].tv_sec;
+ utimbuf.modtime = ts[1].tv_sec;
+ ut = &utimbuf;
+ }
+ else
+ ut = NULL;
+
+ return utime (file, ut);
}
- else
+#endif /* !HAVE_WORKING_UTIMES */
+ }
+}
+
+/* Set the access and modification time stamps of FILE to be
+ TIMESPEC[0] and TIMESPEC[1], respectively. */
+int
+utimens (char const *file, struct timespec const timespec[2])
+{
+ return fdutimens (-1, file, timespec);
+}
+
+/* Set the access and modification time stamps of FILE to be
+ TIMESPEC[0] and TIMESPEC[1], respectively, without dereferencing
+ symlinks. Fail with ENOSYS if the platform does not support
+ changing symlink timestamps, but FILE was a symlink. */
+int
+lutimens (char const *file, struct timespec const timespec[2])
+{
+ struct timespec adjusted_timespec[2];
+ struct timespec *ts = timespec ? adjusted_timespec : NULL;
+ int adjustment_needed = 0;
+ struct stat st;
+
+ if (ts)
{
- /* If futimesat or futimes fails here, don't try to speed things
- up by returning right away. glibc can incorrectly fail with
- errno == ENOENT if /proc isn't mounted. Also, Mandrake 10.0
- in high security mode doesn't allow ordinary users to read
- /proc/self, so glibc incorrectly fails with errno == EACCES.
- If errno == EIO, EPERM, or EROFS, it's probably safe to fail
- right away, but these cases are rare enough that they're not
- worth optimizing, and who knows what other messed-up systems
- are out there? So play it safe and fall back on the code
- below. */
-# if HAVE_FUTIMESAT
- if (futimesat (fd, NULL, t) == 0)
- return 0;
-# elif HAVE_FUTIMES
- if (futimes (fd, t) == 0)
- return 0;
-# endif
+ adjusted_timespec[0] = timespec[0];
+ adjusted_timespec[1] = timespec[1];
+ adjustment_needed = validate_timespec (ts);
}
-#endif
+ if (adjustment_needed < 0)
+ return -1;
+
+ /* The Linux kernel did not support symlink timestamps until
+ utimensat, in version 2.6.22, so we don't need to mimic
+ fdutimens' worry about buggy NFS clients. But we do have to
+ worry about bogus return values. */
- if (!file)
+#if HAVE_UTIMENSAT
+ if (0 <= lutimensat_works_really)
{
-#if ! (HAVE_FUTIMESAT || (HAVE_WORKING_UTIMES && HAVE_FUTIMES))
- errno = ENOSYS;
-#endif
+ int result;
+# if __linux__ || __sun
+ /* As recently as Linux kernel 2.6.32 (Dec 2009), several file
+ systems (xfs, ntfs-3g) have bugs with a single UTIME_OMIT,
+ but work if both times are either explicitly specified or
+ UTIME_NOW. Work around it with a preparatory lstat prior to
+ calling utimensat; fortunately, there is not much timing
+ impact due to the extra syscall even on file systems where
+ UTIME_OMIT would have worked.
- /* Prefer EBADF to ENOSYS if both error numbers apply. */
- if (errno == ENOSYS)
- {
- int fd2 = dup (fd);
- int dup_errno = errno;
- if (0 <= fd2)
- close (fd2);
- errno = (fd2 < 0 && dup_errno == EBADF ? EBADF : ENOSYS);
- }
+ The same bug occurs in Solaris 11.1 (Apr 2013).
- return -1;
+ FIXME: Simplify this for Linux in 2016 and for Solaris in
+ 2024, when file system bugs are no longer common. */
+ if (adjustment_needed == 2)
+ {
+ if (lstat (file, &st))
+ return -1;
+ if (ts[0].tv_nsec == UTIME_OMIT)
+ ts[0] = get_stat_atime (&st);
+ else if (ts[1].tv_nsec == UTIME_OMIT)
+ ts[1] = get_stat_mtime (&st);
+ /* Note that st is good, in case utimensat gives ENOSYS. */
+ adjustment_needed++;
+ }
+# endif
+ result = utimensat (AT_FDCWD, file, ts, AT_SYMLINK_NOFOLLOW);
+# ifdef __linux__
+ /* Work around a kernel bug:
+ http://bugzilla.redhat.com/442352
+ http://bugzilla.redhat.com/449910
+ It appears that utimensat can mistakenly return 280 rather
+ than -1 upon ENOSYS failure.
+ FIXME: remove in 2010 or whenever the offending kernels
+ are no longer in common use. */
+ if (0 < result)
+ errno = ENOSYS;
+# endif
+ if (result == 0 || errno != ENOSYS)
+ {
+ utimensat_works_really = 1;
+ lutimensat_works_really = 1;
+ return result;
+ }
}
+ lutimensat_works_really = -1;
+#endif /* HAVE_UTIMENSAT */
-#if HAVE_WORKING_UTIMES
- return utimes (file, t);
-#else
+ /* The platform lacks an interface to set file timestamps with
+ nanosecond resolution, so do the best we can, discarding any
+ fractional part of the timestamp. */
+
+ if (adjustment_needed || REPLACE_FUNC_STAT_FILE)
+ {
+ if (adjustment_needed != 3 && lstat (file, &st))
+ return -1;
+ if (ts && update_timespec (&st, &ts))
+ return 0;
+ }
+
+ /* On Linux, lutimes is a thin wrapper around utimensat, so there is
+ no point trying lutimes if utimensat failed with ENOSYS. */
+#if HAVE_LUTIMES && !HAVE_UTIMENSAT
{
- struct utimbuf utimbuf;
- struct utimbuf const *ut;
- if (timespec)
+ struct timeval timeval[2];
+ struct timeval *t;
+ int result;
+ if (ts)
{
- utimbuf.actime = timespec[0].tv_sec;
- utimbuf.modtime = timespec[1].tv_sec;
- ut = &utimbuf;
+ timeval[0].tv_sec = ts[0].tv_sec;
+ timeval[0].tv_usec = ts[0].tv_nsec / 1000;
+ timeval[1].tv_sec = ts[1].tv_sec;
+ timeval[1].tv_usec = ts[1].tv_nsec / 1000;
+ t = timeval;
}
else
- ut = NULL;
+ t = NULL;
- return utime (file, ut);
+ result = lutimes (file, t);
+ if (result == 0 || errno != ENOSYS)
+ return result;
}
-#endif
-}
+#endif /* HAVE_LUTIMES && !HAVE_UTIMENSAT */
-/* Set the access and modification time stamps of FILE to be
- TIMESPEC[0] and TIMESPEC[1], respectively. */
-int
-utimens (char const *file, struct timespec const timespec[2])
-{
- return futimens (-1, file, timespec);
+ /* Out of luck for symlinks, but we still handle regular files. */
+ if (!(adjustment_needed || REPLACE_FUNC_STAT_FILE) && lstat (file, &st))
+ return -1;
+ if (!S_ISLNK (st.st_mode))
+ return fdutimens (-1, file, ts);
+ errno = ENOSYS;
+ return -1;
}
diff --git a/lib/utimens.h b/lib/utimens.h
index 0097aaa..a92cad4 100644
--- a/lib/utimens.h
+++ b/lib/utimens.h
@@ -1,3 +1,49 @@
+/* Set file access and modification times.
+
+ Copyright 2012-2016 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 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Paul Eggert. */
+
#include <time.h>
-int futimens (int, char const *, struct timespec const [2]);
+int fdutimens (int, char const *, struct timespec const [2]);
int utimens (char const *, struct timespec const [2]);
+int lutimens (char const *, struct timespec const [2]);
+
+#if GNULIB_FDUTIMENSAT
+# include <fcntl.h>
+# include <sys/stat.h>
+
+#ifndef _GL_INLINE_HEADER_BEGIN
+ #error "Please include config.h first."
+#endif
+_GL_INLINE_HEADER_BEGIN
+#ifndef _GL_UTIMENS_INLINE
+# define _GL_UTIMENS_INLINE _GL_INLINE
+#endif
+
+int fdutimensat (int fd, int dir, char const *name, struct timespec const [2],
+ int atflag);
+
+/* Using this function makes application code slightly more readable. */
+_GL_UTIMENS_INLINE int
+lutimensat (int dir, char const *file, struct timespec const times[2])
+{
+ return utimensat (dir, file, times, AT_SYMLINK_NOFOLLOW);
+}
+
+_GL_INLINE_HEADER_END
+
+#endif
diff --git a/lib/utimensat.c b/lib/utimensat.c
new file mode 100644
index 0000000..ae4da8f
--- /dev/null
+++ b/lib/utimensat.c
@@ -0,0 +1,158 @@
+/* Set the access and modification time of a file relative to directory fd.
+ Copyright (C) 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* written by Eric Blake */
+
+#include <config.h>
+
+#include <sys/stat.h>
+
+#include <errno.h>
+#include <fcntl.h>
+
+#include "stat-time.h"
+#include "timespec.h"
+#include "utimens.h"
+
+#if HAVE_UTIMENSAT
+
+# undef utimensat
+
+/* If we have a native utimensat, but are compiling this file, then
+ utimensat was defined to rpl_utimensat by our replacement
+ sys/stat.h. We assume the native version might fail with ENOSYS,
+ or succeed without properly affecting ctime (as is the case when
+ using newer glibc but older Linux kernel). In this scenario,
+ rpl_utimensat checks whether the native version is usable, and
+ local_utimensat provides the fallback manipulation. */
+
+static int local_utimensat (int, char const *, struct timespec const[2], int);
+# define AT_FUNC_NAME local_utimensat
+
+/* Like utimensat, but work around native bugs. */
+
+int
+rpl_utimensat (int fd, char const *file, struct timespec const times[2],
+ int flag)
+{
+# if defined __linux__ || defined __sun
+ struct timespec ts[2];
+# endif
+
+ /* See comments in utimens.c for details. */
+ static int utimensat_works_really; /* 0 = unknown, 1 = yes, -1 = no. */
+ if (0 <= utimensat_works_really)
+ {
+ int result;
+# if defined __linux__ || defined __sun
+ struct stat st;
+ /* As recently as Linux kernel 2.6.32 (Dec 2009), several file
+ systems (xfs, ntfs-3g) have bugs with a single UTIME_OMIT,
+ but work if both times are either explicitly specified or
+ UTIME_NOW. Work around it with a preparatory [l]stat prior
+ to calling utimensat; fortunately, there is not much timing
+ impact due to the extra syscall even on file systems where
+ UTIME_OMIT would have worked.
+
+ The same bug occurs in Solaris 11.1 (Apr 2013).
+
+ FIXME: Simplify this for Linux in 2016 and for Solaris in
+ 2024, when file system bugs are no longer common. */
+ if (times && (times[0].tv_nsec == UTIME_OMIT
+ || times[1].tv_nsec == UTIME_OMIT))
+ {
+ if (fstatat (fd, file, &st, flag))
+ return -1;
+ if (times[0].tv_nsec == UTIME_OMIT && times[1].tv_nsec == UTIME_OMIT)
+ return 0;
+ if (times[0].tv_nsec == UTIME_OMIT)
+ ts[0] = get_stat_atime (&st);
+ else
+ ts[0] = times[0];
+ if (times[1].tv_nsec == UTIME_OMIT)
+ ts[1] = get_stat_mtime (&st);
+ else
+ ts[1] = times[1];
+ times = ts;
+ }
+# ifdef __hppa__
+ /* Linux kernel 2.6.22.19 on hppa does not reject invalid tv_nsec
+ values. */
+ else if (times
+ && ((times[0].tv_nsec != UTIME_NOW
+ && ! (0 <= times[0].tv_nsec
+ && times[0].tv_nsec < TIMESPEC_RESOLUTION))
+ || (times[1].tv_nsec != UTIME_NOW
+ && ! (0 <= times[1].tv_nsec
+ && times[1].tv_nsec < TIMESPEC_RESOLUTION))))
+ {
+ errno = EINVAL;
+ return -1;
+ }
+# endif
+# endif
+ result = utimensat (fd, file, times, flag);
+ /* Linux kernel 2.6.25 has a bug where it returns EINVAL for
+ UTIME_NOW or UTIME_OMIT with non-zero tv_sec, which
+ local_utimensat works around. Meanwhile, EINVAL for a bad
+ flag is indeterminate whether the native utimensat works, but
+ local_utimensat will also reject it. */
+ if (result == -1 && errno == EINVAL && (flag & ~AT_SYMLINK_NOFOLLOW))
+ return result;
+ if (result == 0 || (errno != ENOSYS && errno != EINVAL))
+ {
+ utimensat_works_really = 1;
+ return result;
+ }
+ }
+ /* No point in trying openat/futimens, since on Linux, futimens is
+ implemented with the same syscall as utimensat. Only avoid the
+ native utimensat due to an ENOSYS failure; an EINVAL error was
+ data-dependent, and the next caller may pass valid data. */
+ if (0 <= utimensat_works_really && errno == ENOSYS)
+ utimensat_works_really = -1;
+ return local_utimensat (fd, file, times, flag);
+}
+
+#else /* !HAVE_UTIMENSAT */
+
+# define AT_FUNC_NAME utimensat
+
+#endif /* !HAVE_UTIMENSAT */
+
+/* Set the access and modification time stamps of FILE to be
+ TIMESPEC[0] and TIMESPEC[1], respectively; relative to directory
+ FD. If flag is AT_SYMLINK_NOFOLLOW, change the times of a symlink,
+ or fail with ENOSYS if not possible. If TIMESPEC is null, set the
+ time stamps to the current time. If possible, do it without
+ changing the working directory. Otherwise, resort to using
+ save_cwd/fchdir, then utimens/restore_cwd. If either the save_cwd
+ or the restore_cwd fails, then give a diagnostic and exit nonzero.
+ Return 0 on success, -1 (setting errno) on failure. */
+
+/* AT_FUNC_NAME is now utimensat or local_utimensat. */
+#define AT_FUNC_F1 lutimens
+#define AT_FUNC_F2 utimens
+#define AT_FUNC_USE_F1_COND AT_SYMLINK_NOFOLLOW
+#define AT_FUNC_POST_FILE_PARAM_DECLS , struct timespec const ts[2], int flag
+#define AT_FUNC_POST_FILE_ARGS , ts
+#include "at-func.c"
+#undef AT_FUNC_NAME
+#undef AT_FUNC_F1
+#undef AT_FUNC_F2
+#undef AT_FUNC_USE_F1_COND
+#undef AT_FUNC_POST_FILE_PARAM_DECLS
+#undef AT_FUNC_POST_FILE_ARGS
diff --git a/lib/vasnprintf.c b/lib/vasnprintf.c
index 8a9ec9e..72bf3bc 100644
--- a/lib/vasnprintf.c
+++ b/lib/vasnprintf.c
@@ -1,12 +1,9 @@
/* vsprintf with automatic memory allocation.
- This file is intended to provide exactly the same functionality
- as the version in gnulib, but without the need for the xsize module.
-
- Copyright (C) 1999, 2002-2007 Free Software Foundation, Inc.
+ Copyright (C) 1999, 2002-2016 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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -15,8 +12,36 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ with this program; if not, see <http://www.gnu.org/licenses/>. */
+
+/* This file can be parametrized with the following macros:
+ VASNPRINTF The name of the function being defined.
+ FCHAR_T The element type of the format string.
+ DCHAR_T The element type of the destination (result) string.
+ FCHAR_T_ONLY_ASCII Set to 1 to enable verification that all characters
+ in the format string are ASCII. MUST be set if
+ FCHAR_T and DCHAR_T are not the same type.
+ DIRECTIVE Structure denoting a format directive.
+ Depends on FCHAR_T.
+ DIRECTIVES Structure denoting the set of format directives of a
+ format string. Depends on FCHAR_T.
+ PRINTF_PARSE Function that parses a format string.
+ Depends on FCHAR_T.
+ DCHAR_CPY memcpy like function for DCHAR_T[] arrays.
+ DCHAR_SET memset like function for DCHAR_T[] arrays.
+ DCHAR_MBSNLEN mbsnlen like function for DCHAR_T[] arrays.
+ SNPRINTF The system's snprintf (or similar) function.
+ This may be either snprintf or swprintf.
+ TCHAR_T The element type of the argument and result string
+ of the said SNPRINTF function. This may be either
+ char or wchar_t. The code exploits that
+ sizeof (TCHAR_T) | sizeof (DCHAR_T) and
+ alignof (TCHAR_T) <= alignof (DCHAR_T).
+ DCHAR_IS_TCHAR Set to 1 if DCHAR_T and TCHAR_T are the same type.
+ DCHAR_CONV_FROM_ENCODING A function to convert from char[] to DCHAR[].
+ DCHAR_IS_UINT8_T Set to 1 if DCHAR_T is uint8_t.
+ DCHAR_IS_UINT16_T Set to 1 if DCHAR_T is uint16_t.
+ DCHAR_IS_UINT32_T Set to 1 if DCHAR_T is uint32_t. */
/* Tell glibc's <stdio.h> to provide a prototype for snprintf().
This must come before <config.h> because <config.h> may include
@@ -25,32 +50,181 @@
# define _GNU_SOURCE 1
#endif
-#include <config.h>
+#ifndef VASNPRINTF
+# include <config.h>
+#endif
#ifndef IN_LIBINTL
# include <alloca.h>
#endif
/* Specification. */
+#ifndef VASNPRINTF
+# if WIDE_CHAR_VERSION
+# include "vasnwprintf.h"
+# else
+# include "vasnprintf.h"
+# endif
+#endif
+
+#include <locale.h> /* localeconv() */
+#include <stdio.h> /* snprintf(), sprintf() */
+#include <stdlib.h> /* abort(), malloc(), realloc(), free() */
+#include <string.h> /* memcpy(), strlen() */
+#include <errno.h> /* errno */
+#include <limits.h> /* CHAR_BIT */
+#include <float.h> /* DBL_MAX_EXP, LDBL_MAX_EXP */
+#if HAVE_NL_LANGINFO
+# include <langinfo.h>
+#endif
+#ifndef VASNPRINTF
+# if WIDE_CHAR_VERSION
+# include "wprintf-parse.h"
+# else
+# include "printf-parse.h"
+# endif
+#endif
+
+/* Checked size_t computations. */
+#include "xsize.h"
+
+#include "verify.h"
+
+#if (NEED_PRINTF_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
+# include <math.h>
+# include "float+.h"
+#endif
+
+#if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
+# include <math.h>
+# include "isnand-nolibm.h"
+#endif
+
+#if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE) && !defined IN_LIBINTL
+# include <math.h>
+# include "isnanl-nolibm.h"
+# include "fpucw.h"
+#endif
+
+#if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
+# include <math.h>
+# include "isnand-nolibm.h"
+# include "printf-frexp.h"
+#endif
+
+#if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
+# include <math.h>
+# include "isnanl-nolibm.h"
+# include "printf-frexpl.h"
+# include "fpucw.h"
+#endif
+
+/* Default parameters. */
+#ifndef VASNPRINTF
+# if WIDE_CHAR_VERSION
+# define VASNPRINTF vasnwprintf
+# define FCHAR_T wchar_t
+# define DCHAR_T wchar_t
+# define TCHAR_T wchar_t
+# define DCHAR_IS_TCHAR 1
+# define DIRECTIVE wchar_t_directive
+# define DIRECTIVES wchar_t_directives
+# define PRINTF_PARSE wprintf_parse
+# define DCHAR_CPY wmemcpy
+# define DCHAR_SET wmemset
+# else
+# define VASNPRINTF vasnprintf
+# define FCHAR_T char
+# define DCHAR_T char
+# define TCHAR_T char
+# define DCHAR_IS_TCHAR 1
+# define DIRECTIVE char_directive
+# define DIRECTIVES char_directives
+# define PRINTF_PARSE printf_parse
+# define DCHAR_CPY memcpy
+# define DCHAR_SET memset
+# endif
+#endif
#if WIDE_CHAR_VERSION
-# include "vasnwprintf.h"
+ /* TCHAR_T is wchar_t. */
+# define USE_SNPRINTF 1
+# if HAVE_DECL__SNWPRINTF
+ /* On Windows, the function swprintf() has a different signature than
+ on Unix; we use the function _snwprintf() or - on mingw - snwprintf()
+ instead. The mingw function snwprintf() has fewer bugs than the
+ MSVCRT function _snwprintf(), so prefer that. */
+# if defined __MINGW32__
+# define SNPRINTF snwprintf
+# else
+# define SNPRINTF _snwprintf
+# endif
+# else
+ /* Unix. */
+# define SNPRINTF swprintf
+# endif
#else
-# include "vasnprintf.h"
+ /* TCHAR_T is char. */
+ /* Use snprintf if it exists under the name 'snprintf' or '_snprintf'.
+ But don't use it on BeOS, since BeOS snprintf produces no output if the
+ size argument is >= 0x3000000.
+ Also don't use it on Linux libc5, since there snprintf with size = 1
+ writes any output without bounds, like sprintf. */
+# if (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF) && !defined __BEOS__ && !(__GNU_LIBRARY__ == 1)
+# define USE_SNPRINTF 1
+# else
+# define USE_SNPRINTF 0
+# endif
+# if HAVE_DECL__SNPRINTF
+ /* Windows. The mingw function snprintf() has fewer bugs than the MSVCRT
+ function _snprintf(), so prefer that. */
+# if defined __MINGW32__
+# define SNPRINTF snprintf
+ /* Here we need to call the native snprintf, not rpl_snprintf. */
+# undef snprintf
+# else
+# define SNPRINTF _snprintf
+# endif
+# else
+ /* Unix. */
+# define SNPRINTF snprintf
+ /* Here we need to call the native snprintf, not rpl_snprintf. */
+# undef snprintf
+# endif
#endif
+/* Here we need to call the native sprintf, not rpl_sprintf. */
+#undef sprintf
-#include <stdio.h> /* snprintf(), sprintf() */
-#include <stdlib.h> /* abort(), malloc(), realloc(), free() */
-#include <stdint.h> /* SIZE_MAX */
-#include <string.h> /* memcpy(), strlen() */
-#include <errno.h> /* errno */
-#include <limits.h> /* CHAR_BIT, INT_MAX */
-#include <float.h> /* DBL_MAX_EXP, LDBL_MAX_EXP */
-#if WIDE_CHAR_VERSION
-# include "wprintf-parse.h"
+/* GCC >= 4.0 with -Wall emits unjustified "... may be used uninitialized"
+ warnings in this file. Use -Dlint to suppress them. */
+#ifdef lint
+# define IF_LINT(Code) Code
#else
-# include "printf-parse.h"
+# define IF_LINT(Code) /* empty */
#endif
-#if HAVE_WCHAR_T
+/* Avoid some warnings from "gcc -Wshadow".
+ This file doesn't use the exp() and remainder() functions. */
+#undef exp
+#define exp expo
+#undef remainder
+#define remainder rem
+
+#if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99) && !WIDE_CHAR_VERSION
+# if (HAVE_STRNLEN && !defined _AIX)
+# define local_strnlen strnlen
+# else
+# ifndef local_strnlen_defined
+# define local_strnlen_defined 1
+static size_t
+local_strnlen (const char *string, size_t maxlen)
+{
+ const char *end = memchr (string, '\0', maxlen);
+ return end ? (size_t) (end - string) : maxlen;
+}
+# endif
+# endif
+#endif
+
+#if (((!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99) && WIDE_CHAR_VERSION) || ((!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || (NEED_PRINTF_DIRECTIVE_LS && !defined IN_LIBINTL)) && !WIDE_CHAR_VERSION && DCHAR_IS_TCHAR)) && HAVE_WCHAR_T
# if HAVE_WCSLEN
# define local_wcslen wcslen
# else
@@ -73,55 +247,1546 @@ local_wcslen (const wchar_t *s)
# endif
#endif
-#if WIDE_CHAR_VERSION
-# define VASNPRINTF vasnwprintf
-# define CHAR_T wchar_t
-# define DIRECTIVE wchar_t_directive
-# define DIRECTIVES wchar_t_directives
-# define PRINTF_PARSE wprintf_parse
-# define USE_SNPRINTF 1
-# if HAVE_DECL__SNWPRINTF
- /* On Windows, the function swprintf() has a different signature than
- on Unix; we use the _snwprintf() function instead. */
-# define SNPRINTF _snwprintf
+#if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99) && HAVE_WCHAR_T && WIDE_CHAR_VERSION
+# if HAVE_WCSNLEN
+# define local_wcsnlen wcsnlen
# else
- /* Unix. */
-# define SNPRINTF swprintf
+# ifndef local_wcsnlen_defined
+# define local_wcsnlen_defined 1
+static size_t
+local_wcsnlen (const wchar_t *s, size_t maxlen)
+{
+ const wchar_t *ptr;
+
+ for (ptr = s; maxlen > 0 && *ptr != (wchar_t) 0; ptr++, maxlen--)
+ ;
+ return ptr - s;
+}
+# endif
# endif
-#else
-# define VASNPRINTF vasnprintf
-# define CHAR_T char
-# define DIRECTIVE char_directive
-# define DIRECTIVES char_directives
-# define PRINTF_PARSE printf_parse
-# define USE_SNPRINTF (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF)
-# if HAVE_DECL__SNPRINTF
- /* Windows. */
-# define SNPRINTF _snprintf
+#endif
+
+#if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
+/* Determine the decimal-point character according to the current locale. */
+# ifndef decimal_point_char_defined
+# define decimal_point_char_defined 1
+static char
+decimal_point_char (void)
+{
+ const char *point;
+ /* Determine it in a multithread-safe way. We know nl_langinfo is
+ multithread-safe on glibc systems and Mac OS X systems, but is not required
+ to be multithread-safe by POSIX. sprintf(), however, is multithread-safe.
+ localeconv() is rarely multithread-safe. */
+# if HAVE_NL_LANGINFO && (__GLIBC__ || defined __UCLIBC__ || (defined __APPLE__ && defined __MACH__))
+ point = nl_langinfo (RADIXCHAR);
+# elif 1
+ char pointbuf[5];
+ sprintf (pointbuf, "%#.0f", 1.0);
+ point = &pointbuf[1];
+# else
+ point = localeconv () -> decimal_point;
+# endif
+ /* The decimal point is always a single byte: either '.' or ','. */
+ return (point[0] != '\0' ? point[0] : '.');
+}
+# endif
+#endif
+
+#if NEED_PRINTF_INFINITE_DOUBLE && !NEED_PRINTF_DOUBLE && !defined IN_LIBINTL
+
+/* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
+static int
+is_infinite_or_zero (double x)
+{
+ return isnand (x) || x + x == x;
+}
+
+#endif
+
+#if NEED_PRINTF_INFINITE_LONG_DOUBLE && !NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
+
+/* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
+static int
+is_infinite_or_zerol (long double x)
+{
+ return isnanl (x) || x + x == x;
+}
+
+#endif
+
+#if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
+
+/* Converting 'long double' to decimal without rare rounding bugs requires
+ real bignums. We use the naming conventions of GNU gmp, but vastly simpler
+ (and slower) algorithms. */
+
+typedef unsigned int mp_limb_t;
+# define GMP_LIMB_BITS 32
+verify (sizeof (mp_limb_t) * CHAR_BIT == GMP_LIMB_BITS);
+
+typedef unsigned long long mp_twolimb_t;
+# define GMP_TWOLIMB_BITS 64
+verify (sizeof (mp_twolimb_t) * CHAR_BIT == GMP_TWOLIMB_BITS);
+
+/* Representation of a bignum >= 0. */
+typedef struct
+{
+ size_t nlimbs;
+ mp_limb_t *limbs; /* Bits in little-endian order, allocated with malloc(). */
+} mpn_t;
+
+/* Compute the product of two bignums >= 0.
+ Return the allocated memory in case of success, NULL in case of memory
+ allocation failure. */
+static void *
+multiply (mpn_t src1, mpn_t src2, mpn_t *dest)
+{
+ const mp_limb_t *p1;
+ const mp_limb_t *p2;
+ size_t len1;
+ size_t len2;
+
+ if (src1.nlimbs <= src2.nlimbs)
+ {
+ len1 = src1.nlimbs;
+ p1 = src1.limbs;
+ len2 = src2.nlimbs;
+ p2 = src2.limbs;
+ }
+ else
+ {
+ len1 = src2.nlimbs;
+ p1 = src2.limbs;
+ len2 = src1.nlimbs;
+ p2 = src1.limbs;
+ }
+ /* Now 0 <= len1 <= len2. */
+ if (len1 == 0)
+ {
+ /* src1 or src2 is zero. */
+ dest->nlimbs = 0;
+ dest->limbs = (mp_limb_t *) malloc (1);
+ }
+ else
+ {
+ /* Here 1 <= len1 <= len2. */
+ size_t dlen;
+ mp_limb_t *dp;
+ size_t k, i, j;
+
+ dlen = len1 + len2;
+ dp = (mp_limb_t *) malloc (dlen * sizeof (mp_limb_t));
+ if (dp == NULL)
+ return NULL;
+ for (k = len2; k > 0; )
+ dp[--k] = 0;
+ for (i = 0; i < len1; i++)
+ {
+ mp_limb_t digit1 = p1[i];
+ mp_twolimb_t carry = 0;
+ for (j = 0; j < len2; j++)
+ {
+ mp_limb_t digit2 = p2[j];
+ carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
+ carry += dp[i + j];
+ dp[i + j] = (mp_limb_t) carry;
+ carry = carry >> GMP_LIMB_BITS;
+ }
+ dp[i + len2] = (mp_limb_t) carry;
+ }
+ /* Normalise. */
+ while (dlen > 0 && dp[dlen - 1] == 0)
+ dlen--;
+ dest->nlimbs = dlen;
+ dest->limbs = dp;
+ }
+ return dest->limbs;
+}
+
+/* Compute the quotient of a bignum a >= 0 and a bignum b > 0.
+ a is written as a = q * b + r with 0 <= r < b. q is the quotient, r
+ the remainder.
+ Finally, round-to-even is performed: If r > b/2 or if r = b/2 and q is odd,
+ q is incremented.
+ Return the allocated memory in case of success, NULL in case of memory
+ allocation failure. */
+static void *
+divide (mpn_t a, mpn_t b, mpn_t *q)
+{
+ /* Algorithm:
+ First normalise a and b: a=[a[m-1],...,a[0]], b=[b[n-1],...,b[0]]
+ with m>=0 and n>0 (in base beta = 2^GMP_LIMB_BITS).
+ If m<n, then q:=0 and r:=a.
+ If m>=n=1, perform a single-precision division:
+ r:=0, j:=m,
+ while j>0 do
+ {Here (q[m-1]*beta^(m-1)+...+q[j]*beta^j) * b[0] + r*beta^j =
+ = a[m-1]*beta^(m-1)+...+a[j]*beta^j und 0<=r<b[0]<beta}
+ j:=j-1, r:=r*beta+a[j], q[j]:=floor(r/b[0]), r:=r-b[0]*q[j].
+ Normalise [q[m-1],...,q[0]], yields q.
+ If m>=n>1, perform a multiple-precision division:
+ We have a/b < beta^(m-n+1).
+ s:=intDsize-1-(highest bit in b[n-1]), 0<=s<intDsize.
+ Shift a and b left by s bits, copying them. r:=a.
+ r=[r[m],...,r[0]], b=[b[n-1],...,b[0]] with b[n-1]>=beta/2.
+ For j=m-n,...,0: {Here 0 <= r < b*beta^(j+1).}
+ Compute q* :
+ q* := floor((r[j+n]*beta+r[j+n-1])/b[n-1]).
+ In case of overflow (q* >= beta) set q* := beta-1.
+ Compute c2 := ((r[j+n]*beta+r[j+n-1]) - q* * b[n-1])*beta + r[j+n-2]
+ and c3 := b[n-2] * q*.
+ {We have 0 <= c2 < 2*beta^2, even 0 <= c2 < beta^2 if no overflow
+ occurred. Furthermore 0 <= c3 < beta^2.
+ If there was overflow and
+ r[j+n]*beta+r[j+n-1] - q* * b[n-1] >= beta, i.e. c2 >= beta^2,
+ the next test can be skipped.}
+ While c3 > c2, {Here 0 <= c2 < c3 < beta^2}
+ Put q* := q* - 1, c2 := c2 + b[n-1]*beta, c3 := c3 - b[n-2].
+ If q* > 0:
+ Put r := r - b * q* * beta^j. In detail:
+ [r[n+j],...,r[j]] := [r[n+j],...,r[j]] - q* * [b[n-1],...,b[0]].
+ hence: u:=0, for i:=0 to n-1 do
+ u := u + q* * b[i],
+ r[j+i]:=r[j+i]-(u mod beta) (+ beta, if carry),
+ u:=u div beta (+ 1, if carry in subtraction)
+ r[n+j]:=r[n+j]-u.
+ {Since always u = (q* * [b[i-1],...,b[0]] div beta^i) + 1
+ < q* + 1 <= beta,
+ the carry u does not overflow.}
+ If a negative carry occurs, put q* := q* - 1
+ and [r[n+j],...,r[j]] := [r[n+j],...,r[j]] + [0,b[n-1],...,b[0]].
+ Set q[j] := q*.
+ Normalise [q[m-n],..,q[0]]; this yields the quotient q.
+ Shift [r[n-1],...,r[0]] right by s bits and normalise; this yields the
+ rest r.
+ The room for q[j] can be allocated at the memory location of r[n+j].
+ Finally, round-to-even:
+ Shift r left by 1 bit.
+ If r > b or if r = b and q[0] is odd, q := q+1.
+ */
+ const mp_limb_t *a_ptr = a.limbs;
+ size_t a_len = a.nlimbs;
+ const mp_limb_t *b_ptr = b.limbs;
+ size_t b_len = b.nlimbs;
+ mp_limb_t *roomptr;
+ mp_limb_t *tmp_roomptr = NULL;
+ mp_limb_t *q_ptr;
+ size_t q_len;
+ mp_limb_t *r_ptr;
+ size_t r_len;
+
+ /* Allocate room for a_len+2 digits.
+ (Need a_len+1 digits for the real division and 1 more digit for the
+ final rounding of q.) */
+ roomptr = (mp_limb_t *) malloc ((a_len + 2) * sizeof (mp_limb_t));
+ if (roomptr == NULL)
+ return NULL;
+
+ /* Normalise a. */
+ while (a_len > 0 && a_ptr[a_len - 1] == 0)
+ a_len--;
+
+ /* Normalise b. */
+ for (;;)
+ {
+ if (b_len == 0)
+ /* Division by zero. */
+ abort ();
+ if (b_ptr[b_len - 1] == 0)
+ b_len--;
+ else
+ break;
+ }
+
+ /* Here m = a_len >= 0 and n = b_len > 0. */
+
+ if (a_len < b_len)
+ {
+ /* m<n: trivial case. q=0, r := copy of a. */
+ r_ptr = roomptr;
+ r_len = a_len;
+ memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
+ q_ptr = roomptr + a_len;
+ q_len = 0;
+ }
+ else if (b_len == 1)
+ {
+ /* n=1: single precision division.
+ beta^(m-1) <= a < beta^m ==> beta^(m-2) <= a/b < beta^m */
+ r_ptr = roomptr;
+ q_ptr = roomptr + 1;
+ {
+ mp_limb_t den = b_ptr[0];
+ mp_limb_t remainder = 0;
+ const mp_limb_t *sourceptr = a_ptr + a_len;
+ mp_limb_t *destptr = q_ptr + a_len;
+ size_t count;
+ for (count = a_len; count > 0; count--)
+ {
+ mp_twolimb_t num =
+ ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--sourceptr;
+ *--destptr = num / den;
+ remainder = num % den;
+ }
+ /* Normalise and store r. */
+ if (remainder > 0)
+ {
+ r_ptr[0] = remainder;
+ r_len = 1;
+ }
+ else
+ r_len = 0;
+ /* Normalise q. */
+ q_len = a_len;
+ if (q_ptr[q_len - 1] == 0)
+ q_len--;
+ }
+ }
+ else
+ {
+ /* n>1: multiple precision division.
+ beta^(m-1) <= a < beta^m, beta^(n-1) <= b < beta^n ==>
+ beta^(m-n-1) <= a/b < beta^(m-n+1). */
+ /* Determine s. */
+ size_t s;
+ {
+ mp_limb_t msd = b_ptr[b_len - 1]; /* = b[n-1], > 0 */
+ /* Determine s = GMP_LIMB_BITS - integer_length (msd).
+ Code copied from gnulib's integer_length.c. */
+# if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
+ s = __builtin_clz (msd);
# else
- /* Unix. */
-# define SNPRINTF snprintf
+# if defined DBL_EXPBIT0_WORD && defined DBL_EXPBIT0_BIT
+ if (GMP_LIMB_BITS <= DBL_MANT_BIT)
+ {
+ /* Use 'double' operations.
+ Assumes an IEEE 754 'double' implementation. */
+# define DBL_EXP_MASK ((DBL_MAX_EXP - DBL_MIN_EXP) | 7)
+# define DBL_EXP_BIAS (DBL_EXP_MASK / 2 - 1)
+# define NWORDS \
+ ((sizeof (double) + sizeof (unsigned int) - 1) / sizeof (unsigned int))
+ union { double value; unsigned int word[NWORDS]; } m;
+
+ /* Use a single integer to floating-point conversion. */
+ m.value = msd;
+
+ s = GMP_LIMB_BITS
+ - (((m.word[DBL_EXPBIT0_WORD] >> DBL_EXPBIT0_BIT) & DBL_EXP_MASK)
+ - DBL_EXP_BIAS);
+ }
+ else
+# undef NWORDS
+# endif
+ {
+ s = 31;
+ if (msd >= 0x10000)
+ {
+ msd = msd >> 16;
+ s -= 16;
+ }
+ if (msd >= 0x100)
+ {
+ msd = msd >> 8;
+ s -= 8;
+ }
+ if (msd >= 0x10)
+ {
+ msd = msd >> 4;
+ s -= 4;
+ }
+ if (msd >= 0x4)
+ {
+ msd = msd >> 2;
+ s -= 2;
+ }
+ if (msd >= 0x2)
+ {
+ msd = msd >> 1;
+ s -= 1;
+ }
+ }
+# endif
+ }
+ /* 0 <= s < GMP_LIMB_BITS.
+ Copy b, shifting it left by s bits. */
+ if (s > 0)
+ {
+ tmp_roomptr = (mp_limb_t *) malloc (b_len * sizeof (mp_limb_t));
+ if (tmp_roomptr == NULL)
+ {
+ free (roomptr);
+ return NULL;
+ }
+ {
+ const mp_limb_t *sourceptr = b_ptr;
+ mp_limb_t *destptr = tmp_roomptr;
+ mp_twolimb_t accu = 0;
+ size_t count;
+ for (count = b_len; count > 0; count--)
+ {
+ accu += (mp_twolimb_t) *sourceptr++ << s;
+ *destptr++ = (mp_limb_t) accu;
+ accu = accu >> GMP_LIMB_BITS;
+ }
+ /* accu must be zero, since that was how s was determined. */
+ if (accu != 0)
+ abort ();
+ }
+ b_ptr = tmp_roomptr;
+ }
+ /* Copy a, shifting it left by s bits, yields r.
+ Memory layout:
+ At the beginning: r = roomptr[0..a_len],
+ at the end: r = roomptr[0..b_len-1], q = roomptr[b_len..a_len] */
+ r_ptr = roomptr;
+ if (s == 0)
+ {
+ memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
+ r_ptr[a_len] = 0;
+ }
+ else
+ {
+ const mp_limb_t *sourceptr = a_ptr;
+ mp_limb_t *destptr = r_ptr;
+ mp_twolimb_t accu = 0;
+ size_t count;
+ for (count = a_len; count > 0; count--)
+ {
+ accu += (mp_twolimb_t) *sourceptr++ << s;
+ *destptr++ = (mp_limb_t) accu;
+ accu = accu >> GMP_LIMB_BITS;
+ }
+ *destptr++ = (mp_limb_t) accu;
+ }
+ q_ptr = roomptr + b_len;
+ q_len = a_len - b_len + 1; /* q will have m-n+1 limbs */
+ {
+ size_t j = a_len - b_len; /* m-n */
+ mp_limb_t b_msd = b_ptr[b_len - 1]; /* b[n-1] */
+ mp_limb_t b_2msd = b_ptr[b_len - 2]; /* b[n-2] */
+ mp_twolimb_t b_msdd = /* b[n-1]*beta+b[n-2] */
+ ((mp_twolimb_t) b_msd << GMP_LIMB_BITS) | b_2msd;
+ /* Division loop, traversed m-n+1 times.
+ j counts down, b is unchanged, beta/2 <= b[n-1] < beta. */
+ for (;;)
+ {
+ mp_limb_t q_star;
+ mp_limb_t c1;
+ if (r_ptr[j + b_len] < b_msd) /* r[j+n] < b[n-1] ? */
+ {
+ /* Divide r[j+n]*beta+r[j+n-1] by b[n-1], no overflow. */
+ mp_twolimb_t num =
+ ((mp_twolimb_t) r_ptr[j + b_len] << GMP_LIMB_BITS)
+ | r_ptr[j + b_len - 1];
+ q_star = num / b_msd;
+ c1 = num % b_msd;
+ }
+ else
+ {
+ /* Overflow, hence r[j+n]*beta+r[j+n-1] >= beta*b[n-1]. */
+ q_star = (mp_limb_t)~(mp_limb_t)0; /* q* = beta-1 */
+ /* Test whether r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] >= beta
+ <==> r[j+n]*beta+r[j+n-1] + b[n-1] >= beta*b[n-1]+beta
+ <==> b[n-1] < floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta)
+ {<= beta !}.
+ If yes, jump directly to the subtraction loop.
+ (Otherwise, r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] < beta
+ <==> floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta) = b[n-1] ) */
+ if (r_ptr[j + b_len] > b_msd
+ || (c1 = r_ptr[j + b_len - 1] + b_msd) < b_msd)
+ /* r[j+n] >= b[n-1]+1 or
+ r[j+n] = b[n-1] and the addition r[j+n-1]+b[n-1] gives a
+ carry. */
+ goto subtract;
+ }
+ /* q_star = q*,
+ c1 = (r[j+n]*beta+r[j+n-1]) - q* * b[n-1] (>=0, <beta). */
+ {
+ mp_twolimb_t c2 = /* c1*beta+r[j+n-2] */
+ ((mp_twolimb_t) c1 << GMP_LIMB_BITS) | r_ptr[j + b_len - 2];
+ mp_twolimb_t c3 = /* b[n-2] * q* */
+ (mp_twolimb_t) b_2msd * (mp_twolimb_t) q_star;
+ /* While c2 < c3, increase c2 and decrease c3.
+ Consider c3-c2. While it is > 0, decrease it by
+ b[n-1]*beta+b[n-2]. Because of b[n-1]*beta+b[n-2] >= beta^2/2
+ this can happen only twice. */
+ if (c3 > c2)
+ {
+ q_star = q_star - 1; /* q* := q* - 1 */
+ if (c3 - c2 > b_msdd)
+ q_star = q_star - 1; /* q* := q* - 1 */
+ }
+ }
+ if (q_star > 0)
+ subtract:
+ {
+ /* Subtract r := r - b * q* * beta^j. */
+ mp_limb_t cr;
+ {
+ const mp_limb_t *sourceptr = b_ptr;
+ mp_limb_t *destptr = r_ptr + j;
+ mp_twolimb_t carry = 0;
+ size_t count;
+ for (count = b_len; count > 0; count--)
+ {
+ /* Here 0 <= carry <= q*. */
+ carry =
+ carry
+ + (mp_twolimb_t) q_star * (mp_twolimb_t) *sourceptr++
+ + (mp_limb_t) ~(*destptr);
+ /* Here 0 <= carry <= beta*q* + beta-1. */
+ *destptr++ = ~(mp_limb_t) carry;
+ carry = carry >> GMP_LIMB_BITS; /* <= q* */
+ }
+ cr = (mp_limb_t) carry;
+ }
+ /* Subtract cr from r_ptr[j + b_len], then forget about
+ r_ptr[j + b_len]. */
+ if (cr > r_ptr[j + b_len])
+ {
+ /* Subtraction gave a carry. */
+ q_star = q_star - 1; /* q* := q* - 1 */
+ /* Add b back. */
+ {
+ const mp_limb_t *sourceptr = b_ptr;
+ mp_limb_t *destptr = r_ptr + j;
+ mp_limb_t carry = 0;
+ size_t count;
+ for (count = b_len; count > 0; count--)
+ {
+ mp_limb_t source1 = *sourceptr++;
+ mp_limb_t source2 = *destptr;
+ *destptr++ = source1 + source2 + carry;
+ carry =
+ (carry
+ ? source1 >= (mp_limb_t) ~source2
+ : source1 > (mp_limb_t) ~source2);
+ }
+ }
+ /* Forget about the carry and about r[j+n]. */
+ }
+ }
+ /* q* is determined. Store it as q[j]. */
+ q_ptr[j] = q_star;
+ if (j == 0)
+ break;
+ j--;
+ }
+ }
+ r_len = b_len;
+ /* Normalise q. */
+ if (q_ptr[q_len - 1] == 0)
+ q_len--;
+# if 0 /* Not needed here, since we need r only to compare it with b/2, and
+ b is shifted left by s bits. */
+ /* Shift r right by s bits. */
+ if (s > 0)
+ {
+ mp_limb_t ptr = r_ptr + r_len;
+ mp_twolimb_t accu = 0;
+ size_t count;
+ for (count = r_len; count > 0; count--)
+ {
+ accu = (mp_twolimb_t) (mp_limb_t) accu << GMP_LIMB_BITS;
+ accu += (mp_twolimb_t) *--ptr << (GMP_LIMB_BITS - s);
+ *ptr = (mp_limb_t) (accu >> GMP_LIMB_BITS);
+ }
+ }
# endif
+ /* Normalise r. */
+ while (r_len > 0 && r_ptr[r_len - 1] == 0)
+ r_len--;
+ }
+ /* Compare r << 1 with b. */
+ if (r_len > b_len)
+ goto increment_q;
+ {
+ size_t i;
+ for (i = b_len;;)
+ {
+ mp_limb_t r_i =
+ (i <= r_len && i > 0 ? r_ptr[i - 1] >> (GMP_LIMB_BITS - 1) : 0)
+ | (i < r_len ? r_ptr[i] << 1 : 0);
+ mp_limb_t b_i = (i < b_len ? b_ptr[i] : 0);
+ if (r_i > b_i)
+ goto increment_q;
+ if (r_i < b_i)
+ goto keep_q;
+ if (i == 0)
+ break;
+ i--;
+ }
+ }
+ if (q_len > 0 && ((q_ptr[0] & 1) != 0))
+ /* q is odd. */
+ increment_q:
+ {
+ size_t i;
+ for (i = 0; i < q_len; i++)
+ if (++(q_ptr[i]) != 0)
+ goto keep_q;
+ q_ptr[q_len++] = 1;
+ }
+ keep_q:
+ if (tmp_roomptr != NULL)
+ free (tmp_roomptr);
+ q->limbs = q_ptr;
+ q->nlimbs = q_len;
+ return roomptr;
+}
+
+/* Convert a bignum a >= 0, multiplied with 10^extra_zeroes, to decimal
+ representation.
+ Destroys the contents of a.
+ Return the allocated memory - containing the decimal digits in low-to-high
+ order, terminated with a NUL character - in case of success, NULL in case
+ of memory allocation failure. */
+static char *
+convert_to_decimal (mpn_t a, size_t extra_zeroes)
+{
+ mp_limb_t *a_ptr = a.limbs;
+ size_t a_len = a.nlimbs;
+ /* 0.03345 is slightly larger than log(2)/(9*log(10)). */
+ size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1);
+ char *c_ptr = (char *) malloc (xsum (c_len, extra_zeroes));
+ if (c_ptr != NULL)
+ {
+ char *d_ptr = c_ptr;
+ for (; extra_zeroes > 0; extra_zeroes--)
+ *d_ptr++ = '0';
+ while (a_len > 0)
+ {
+ /* Divide a by 10^9, in-place. */
+ mp_limb_t remainder = 0;
+ mp_limb_t *ptr = a_ptr + a_len;
+ size_t count;
+ for (count = a_len; count > 0; count--)
+ {
+ mp_twolimb_t num =
+ ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr;
+ *ptr = num / 1000000000;
+ remainder = num % 1000000000;
+ }
+ /* Store the remainder as 9 decimal digits. */
+ for (count = 9; count > 0; count--)
+ {
+ *d_ptr++ = '0' + (remainder % 10);
+ remainder = remainder / 10;
+ }
+ /* Normalize a. */
+ if (a_ptr[a_len - 1] == 0)
+ a_len--;
+ }
+ /* Remove leading zeroes. */
+ while (d_ptr > c_ptr && d_ptr[-1] == '0')
+ d_ptr--;
+ /* But keep at least one zero. */
+ if (d_ptr == c_ptr)
+ *d_ptr++ = '0';
+ /* Terminate the string. */
+ *d_ptr = '\0';
+ }
+ return c_ptr;
+}
+
+# if NEED_PRINTF_LONG_DOUBLE
+
+/* Assuming x is finite and >= 0:
+ write x as x = 2^e * m, where m is a bignum.
+ Return the allocated memory in case of success, NULL in case of memory
+ allocation failure. */
+static void *
+decode_long_double (long double x, int *ep, mpn_t *mp)
+{
+ mpn_t m;
+ int exp;
+ long double y;
+ size_t i;
+
+ /* Allocate memory for result. */
+ m.nlimbs = (LDBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
+ m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
+ if (m.limbs == NULL)
+ return NULL;
+ /* Split into exponential part and mantissa. */
+ y = frexpl (x, &exp);
+ if (!(y >= 0.0L && y < 1.0L))
+ abort ();
+ /* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * 2^LDBL_MANT_BIT), and the
+ latter is an integer. */
+ /* Convert the mantissa (y * 2^LDBL_MANT_BIT) to a sequence of limbs.
+ I'm not sure whether it's safe to cast a 'long double' value between
+ 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
+ 'long double' values between 0 and 2^16 (to 'unsigned int' or 'int',
+ doesn't matter). */
+# if (LDBL_MANT_BIT % GMP_LIMB_BITS) != 0
+# if (LDBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
+ {
+ mp_limb_t hi, lo;
+ y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % (GMP_LIMB_BITS / 2));
+ hi = (int) y;
+ y -= hi;
+ if (!(y >= 0.0L && y < 1.0L))
+ abort ();
+ y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
+ lo = (int) y;
+ y -= lo;
+ if (!(y >= 0.0L && y < 1.0L))
+ abort ();
+ m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
+ }
+# else
+ {
+ mp_limb_t d;
+ y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % GMP_LIMB_BITS);
+ d = (int) y;
+ y -= d;
+ if (!(y >= 0.0L && y < 1.0L))
+ abort ();
+ m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = d;
+ }
+# endif
+# endif
+ for (i = LDBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
+ {
+ mp_limb_t hi, lo;
+ y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
+ hi = (int) y;
+ y -= hi;
+ if (!(y >= 0.0L && y < 1.0L))
+ abort ();
+ y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
+ lo = (int) y;
+ y -= lo;
+ if (!(y >= 0.0L && y < 1.0L))
+ abort ();
+ m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
+ }
+# if 0 /* On FreeBSD 6.1/x86, 'long double' numbers sometimes have excess
+ precision. */
+ if (!(y == 0.0L))
+ abort ();
+# endif
+ /* Normalise. */
+ while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
+ m.nlimbs--;
+ *mp = m;
+ *ep = exp - LDBL_MANT_BIT;
+ return m.limbs;
+}
+
+# endif
+
+# if NEED_PRINTF_DOUBLE
+
+/* Assuming x is finite and >= 0:
+ write x as x = 2^e * m, where m is a bignum.
+ Return the allocated memory in case of success, NULL in case of memory
+ allocation failure. */
+static void *
+decode_double (double x, int *ep, mpn_t *mp)
+{
+ mpn_t m;
+ int exp;
+ double y;
+ size_t i;
+
+ /* Allocate memory for result. */
+ m.nlimbs = (DBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
+ m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
+ if (m.limbs == NULL)
+ return NULL;
+ /* Split into exponential part and mantissa. */
+ y = frexp (x, &exp);
+ if (!(y >= 0.0 && y < 1.0))
+ abort ();
+ /* x = 2^exp * y = 2^(exp - DBL_MANT_BIT) * (y * 2^DBL_MANT_BIT), and the
+ latter is an integer. */
+ /* Convert the mantissa (y * 2^DBL_MANT_BIT) to a sequence of limbs.
+ I'm not sure whether it's safe to cast a 'double' value between
+ 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
+ 'double' values between 0 and 2^16 (to 'unsigned int' or 'int',
+ doesn't matter). */
+# if (DBL_MANT_BIT % GMP_LIMB_BITS) != 0
+# if (DBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
+ {
+ mp_limb_t hi, lo;
+ y *= (mp_limb_t) 1 << (DBL_MANT_BIT % (GMP_LIMB_BITS / 2));
+ hi = (int) y;
+ y -= hi;
+ if (!(y >= 0.0 && y < 1.0))
+ abort ();
+ y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
+ lo = (int) y;
+ y -= lo;
+ if (!(y >= 0.0 && y < 1.0))
+ abort ();
+ m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
+ }
+# else
+ {
+ mp_limb_t d;
+ y *= (mp_limb_t) 1 << (DBL_MANT_BIT % GMP_LIMB_BITS);
+ d = (int) y;
+ y -= d;
+ if (!(y >= 0.0 && y < 1.0))
+ abort ();
+ m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = d;
+ }
+# endif
+# endif
+ for (i = DBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
+ {
+ mp_limb_t hi, lo;
+ y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
+ hi = (int) y;
+ y -= hi;
+ if (!(y >= 0.0 && y < 1.0))
+ abort ();
+ y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
+ lo = (int) y;
+ y -= lo;
+ if (!(y >= 0.0 && y < 1.0))
+ abort ();
+ m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
+ }
+ if (!(y == 0.0))
+ abort ();
+ /* Normalise. */
+ while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
+ m.nlimbs--;
+ *mp = m;
+ *ep = exp - DBL_MANT_BIT;
+ return m.limbs;
+}
+
+# endif
+
+/* Assuming x = 2^e * m is finite and >= 0, and n is an integer:
+ Returns the decimal representation of round (x * 10^n).
+ Return the allocated memory - containing the decimal digits in low-to-high
+ order, terminated with a NUL character - in case of success, NULL in case
+ of memory allocation failure. */
+static char *
+scale10_round_decimal_decoded (int e, mpn_t m, void *memory, int n)
+{
+ int s;
+ size_t extra_zeroes;
+ unsigned int abs_n;
+ unsigned int abs_s;
+ mp_limb_t *pow5_ptr;
+ size_t pow5_len;
+ unsigned int s_limbs;
+ unsigned int s_bits;
+ mpn_t pow5;
+ mpn_t z;
+ void *z_memory;
+ char *digits;
+
+ if (memory == NULL)
+ return NULL;
+ /* x = 2^e * m, hence
+ y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
+ = round (2^s * 5^n * m). */
+ s = e + n;
+ extra_zeroes = 0;
+ /* Factor out a common power of 10 if possible. */
+ if (s > 0 && n > 0)
+ {
+ extra_zeroes = (s < n ? s : n);
+ s -= extra_zeroes;
+ n -= extra_zeroes;
+ }
+ /* Here y = round (2^s * 5^n * m) * 10^extra_zeroes.
+ Before converting to decimal, we need to compute
+ z = round (2^s * 5^n * m). */
+ /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
+ sign. 2.322 is slightly larger than log(5)/log(2). */
+ abs_n = (n >= 0 ? n : -n);
+ abs_s = (s >= 0 ? s : -s);
+ pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
+ + abs_s / GMP_LIMB_BITS + 1)
+ * sizeof (mp_limb_t));
+ if (pow5_ptr == NULL)
+ {
+ free (memory);
+ return NULL;
+ }
+ /* Initialize with 1. */
+ pow5_ptr[0] = 1;
+ pow5_len = 1;
+ /* Multiply with 5^|n|. */
+ if (abs_n > 0)
+ {
+ static mp_limb_t const small_pow5[13 + 1] =
+ {
+ 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
+ 48828125, 244140625, 1220703125
+ };
+ unsigned int n13;
+ for (n13 = 0; n13 <= abs_n; n13 += 13)
+ {
+ mp_limb_t digit1 = small_pow5[n13 + 13 <= abs_n ? 13 : abs_n - n13];
+ size_t j;
+ mp_twolimb_t carry = 0;
+ for (j = 0; j < pow5_len; j++)
+ {
+ mp_limb_t digit2 = pow5_ptr[j];
+ carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
+ pow5_ptr[j] = (mp_limb_t) carry;
+ carry = carry >> GMP_LIMB_BITS;
+ }
+ if (carry > 0)
+ pow5_ptr[pow5_len++] = (mp_limb_t) carry;
+ }
+ }
+ s_limbs = abs_s / GMP_LIMB_BITS;
+ s_bits = abs_s % GMP_LIMB_BITS;
+ if (n >= 0 ? s >= 0 : s <= 0)
+ {
+ /* Multiply with 2^|s|. */
+ if (s_bits > 0)
+ {
+ mp_limb_t *ptr = pow5_ptr;
+ mp_twolimb_t accu = 0;
+ size_t count;
+ for (count = pow5_len; count > 0; count--)
+ {
+ accu += (mp_twolimb_t) *ptr << s_bits;
+ *ptr++ = (mp_limb_t) accu;
+ accu = accu >> GMP_LIMB_BITS;
+ }
+ if (accu > 0)
+ {
+ *ptr = (mp_limb_t) accu;
+ pow5_len++;
+ }
+ }
+ if (s_limbs > 0)
+ {
+ size_t count;
+ for (count = pow5_len; count > 0;)
+ {
+ count--;
+ pow5_ptr[s_limbs + count] = pow5_ptr[count];
+ }
+ for (count = s_limbs; count > 0;)
+ {
+ count--;
+ pow5_ptr[count] = 0;
+ }
+ pow5_len += s_limbs;
+ }
+ pow5.limbs = pow5_ptr;
+ pow5.nlimbs = pow5_len;
+ if (n >= 0)
+ {
+ /* Multiply m with pow5. No division needed. */
+ z_memory = multiply (m, pow5, &z);
+ }
+ else
+ {
+ /* Divide m by pow5 and round. */
+ z_memory = divide (m, pow5, &z);
+ }
+ }
+ else
+ {
+ pow5.limbs = pow5_ptr;
+ pow5.nlimbs = pow5_len;
+ if (n >= 0)
+ {
+ /* n >= 0, s < 0.
+ Multiply m with pow5, then divide by 2^|s|. */
+ mpn_t numerator;
+ mpn_t denominator;
+ void *tmp_memory;
+ tmp_memory = multiply (m, pow5, &numerator);
+ if (tmp_memory == NULL)
+ {
+ free (pow5_ptr);
+ free (memory);
+ return NULL;
+ }
+ /* Construct 2^|s|. */
+ {
+ mp_limb_t *ptr = pow5_ptr + pow5_len;
+ size_t i;
+ for (i = 0; i < s_limbs; i++)
+ ptr[i] = 0;
+ ptr[s_limbs] = (mp_limb_t) 1 << s_bits;
+ denominator.limbs = ptr;
+ denominator.nlimbs = s_limbs + 1;
+ }
+ z_memory = divide (numerator, denominator, &z);
+ free (tmp_memory);
+ }
+ else
+ {
+ /* n < 0, s > 0.
+ Multiply m with 2^s, then divide by pow5. */
+ mpn_t numerator;
+ mp_limb_t *num_ptr;
+ num_ptr = (mp_limb_t *) malloc ((m.nlimbs + s_limbs + 1)
+ * sizeof (mp_limb_t));
+ if (num_ptr == NULL)
+ {
+ free (pow5_ptr);
+ free (memory);
+ return NULL;
+ }
+ {
+ mp_limb_t *destptr = num_ptr;
+ {
+ size_t i;
+ for (i = 0; i < s_limbs; i++)
+ *destptr++ = 0;
+ }
+ if (s_bits > 0)
+ {
+ const mp_limb_t *sourceptr = m.limbs;
+ mp_twolimb_t accu = 0;
+ size_t count;
+ for (count = m.nlimbs; count > 0; count--)
+ {
+ accu += (mp_twolimb_t) *sourceptr++ << s_bits;
+ *destptr++ = (mp_limb_t) accu;
+ accu = accu >> GMP_LIMB_BITS;
+ }
+ if (accu > 0)
+ *destptr++ = (mp_limb_t) accu;
+ }
+ else
+ {
+ const mp_limb_t *sourceptr = m.limbs;
+ size_t count;
+ for (count = m.nlimbs; count > 0; count--)
+ *destptr++ = *sourceptr++;
+ }
+ numerator.limbs = num_ptr;
+ numerator.nlimbs = destptr - num_ptr;
+ }
+ z_memory = divide (numerator, pow5, &z);
+ free (num_ptr);
+ }
+ }
+ free (pow5_ptr);
+ free (memory);
+
+ /* Here y = round (x * 10^n) = z * 10^extra_zeroes. */
+
+ if (z_memory == NULL)
+ return NULL;
+ digits = convert_to_decimal (z, extra_zeroes);
+ free (z_memory);
+ return digits;
+}
+
+# if NEED_PRINTF_LONG_DOUBLE
+
+/* Assuming x is finite and >= 0, and n is an integer:
+ Returns the decimal representation of round (x * 10^n).
+ Return the allocated memory - containing the decimal digits in low-to-high
+ order, terminated with a NUL character - in case of success, NULL in case
+ of memory allocation failure. */
+static char *
+scale10_round_decimal_long_double (long double x, int n)
+{
+ int e IF_LINT(= 0);
+ mpn_t m;
+ void *memory = decode_long_double (x, &e, &m);
+ return scale10_round_decimal_decoded (e, m, memory, n);
+}
+
+# endif
+
+# if NEED_PRINTF_DOUBLE
+
+/* Assuming x is finite and >= 0, and n is an integer:
+ Returns the decimal representation of round (x * 10^n).
+ Return the allocated memory - containing the decimal digits in low-to-high
+ order, terminated with a NUL character - in case of success, NULL in case
+ of memory allocation failure. */
+static char *
+scale10_round_decimal_double (double x, int n)
+{
+ int e IF_LINT(= 0);
+ mpn_t m;
+ void *memory = decode_double (x, &e, &m);
+ return scale10_round_decimal_decoded (e, m, memory, n);
+}
+
+# endif
+
+# if NEED_PRINTF_LONG_DOUBLE
+
+/* Assuming x is finite and > 0:
+ Return an approximation for n with 10^n <= x < 10^(n+1).
+ The approximation is usually the right n, but may be off by 1 sometimes. */
+static int
+floorlog10l (long double x)
+{
+ int exp;
+ long double y;
+ double z;
+ double l;
+
+ /* Split into exponential part and mantissa. */
+ y = frexpl (x, &exp);
+ if (!(y >= 0.0L && y < 1.0L))
+ abort ();
+ if (y == 0.0L)
+ return INT_MIN;
+ if (y < 0.5L)
+ {
+ while (y < (1.0L / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
+ {
+ y *= 1.0L * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
+ exp -= GMP_LIMB_BITS;
+ }
+ if (y < (1.0L / (1 << 16)))
+ {
+ y *= 1.0L * (1 << 16);
+ exp -= 16;
+ }
+ if (y < (1.0L / (1 << 8)))
+ {
+ y *= 1.0L * (1 << 8);
+ exp -= 8;
+ }
+ if (y < (1.0L / (1 << 4)))
+ {
+ y *= 1.0L * (1 << 4);
+ exp -= 4;
+ }
+ if (y < (1.0L / (1 << 2)))
+ {
+ y *= 1.0L * (1 << 2);
+ exp -= 2;
+ }
+ if (y < (1.0L / (1 << 1)))
+ {
+ y *= 1.0L * (1 << 1);
+ exp -= 1;
+ }
+ }
+ if (!(y >= 0.5L && y < 1.0L))
+ abort ();
+ /* Compute an approximation for l = log2(x) = exp + log2(y). */
+ l = exp;
+ z = y;
+ if (z < 0.70710678118654752444)
+ {
+ z *= 1.4142135623730950488;
+ l -= 0.5;
+ }
+ if (z < 0.8408964152537145431)
+ {
+ z *= 1.1892071150027210667;
+ l -= 0.25;
+ }
+ if (z < 0.91700404320467123175)
+ {
+ z *= 1.0905077326652576592;
+ l -= 0.125;
+ }
+ if (z < 0.9576032806985736469)
+ {
+ z *= 1.0442737824274138403;
+ l -= 0.0625;
+ }
+ /* Now 0.95 <= z <= 1.01. */
+ z = 1 - z;
+ /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
+ Four terms are enough to get an approximation with error < 10^-7. */
+ l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
+ /* Finally multiply with log(2)/log(10), yields an approximation for
+ log10(x). */
+ l *= 0.30102999566398119523;
+ /* Round down to the next integer. */
+ return (int) l + (l < 0 ? -1 : 0);
+}
+
+# endif
+
+# if NEED_PRINTF_DOUBLE
+
+/* Assuming x is finite and > 0:
+ Return an approximation for n with 10^n <= x < 10^(n+1).
+ The approximation is usually the right n, but may be off by 1 sometimes. */
+static int
+floorlog10 (double x)
+{
+ int exp;
+ double y;
+ double z;
+ double l;
+
+ /* Split into exponential part and mantissa. */
+ y = frexp (x, &exp);
+ if (!(y >= 0.0 && y < 1.0))
+ abort ();
+ if (y == 0.0)
+ return INT_MIN;
+ if (y < 0.5)
+ {
+ while (y < (1.0 / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
+ {
+ y *= 1.0 * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
+ exp -= GMP_LIMB_BITS;
+ }
+ if (y < (1.0 / (1 << 16)))
+ {
+ y *= 1.0 * (1 << 16);
+ exp -= 16;
+ }
+ if (y < (1.0 / (1 << 8)))
+ {
+ y *= 1.0 * (1 << 8);
+ exp -= 8;
+ }
+ if (y < (1.0 / (1 << 4)))
+ {
+ y *= 1.0 * (1 << 4);
+ exp -= 4;
+ }
+ if (y < (1.0 / (1 << 2)))
+ {
+ y *= 1.0 * (1 << 2);
+ exp -= 2;
+ }
+ if (y < (1.0 / (1 << 1)))
+ {
+ y *= 1.0 * (1 << 1);
+ exp -= 1;
+ }
+ }
+ if (!(y >= 0.5 && y < 1.0))
+ abort ();
+ /* Compute an approximation for l = log2(x) = exp + log2(y). */
+ l = exp;
+ z = y;
+ if (z < 0.70710678118654752444)
+ {
+ z *= 1.4142135623730950488;
+ l -= 0.5;
+ }
+ if (z < 0.8408964152537145431)
+ {
+ z *= 1.1892071150027210667;
+ l -= 0.25;
+ }
+ if (z < 0.91700404320467123175)
+ {
+ z *= 1.0905077326652576592;
+ l -= 0.125;
+ }
+ if (z < 0.9576032806985736469)
+ {
+ z *= 1.0442737824274138403;
+ l -= 0.0625;
+ }
+ /* Now 0.95 <= z <= 1.01. */
+ z = 1 - z;
+ /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
+ Four terms are enough to get an approximation with error < 10^-7. */
+ l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
+ /* Finally multiply with log(2)/log(10), yields an approximation for
+ log10(x). */
+ l *= 0.30102999566398119523;
+ /* Round down to the next integer. */
+ return (int) l + (l < 0 ? -1 : 0);
+}
+
+# endif
+
+/* Tests whether a string of digits consists of exactly PRECISION zeroes and
+ a single '1' digit. */
+static int
+is_borderline (const char *digits, size_t precision)
+{
+ for (; precision > 0; precision--, digits++)
+ if (*digits != '0')
+ return 0;
+ if (*digits != '1')
+ return 0;
+ digits++;
+ return *digits == '\0';
+}
+
#endif
-CHAR_T *
-VASNPRINTF (CHAR_T *resultbuf, size_t *lengthp, const CHAR_T *format, va_list args)
+#if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99
+
+/* Use a different function name, to make it possible that the 'wchar_t'
+ parametrization and the 'char' parametrization get compiled in the same
+ translation unit. */
+# if WIDE_CHAR_VERSION
+# define MAX_ROOM_NEEDED wmax_room_needed
+# else
+# define MAX_ROOM_NEEDED max_room_needed
+# endif
+
+/* Returns the number of TCHAR_T units needed as temporary space for the result
+ of sprintf or SNPRINTF of a single conversion directive. */
+static size_t
+MAX_ROOM_NEEDED (const arguments *ap, size_t arg_index, FCHAR_T conversion,
+ arg_type type, int flags, size_t width, int has_precision,
+ size_t precision, int pad_ourselves)
+{
+ size_t tmp_length;
+
+ switch (conversion)
+ {
+ case 'd': case 'i': case 'u':
+# if HAVE_LONG_LONG_INT
+ if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
+ tmp_length =
+ (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
+ * 0.30103 /* binary -> decimal */
+ )
+ + 1; /* turn floor into ceil */
+ else
+# endif
+ if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
+ tmp_length =
+ (unsigned int) (sizeof (unsigned long) * CHAR_BIT
+ * 0.30103 /* binary -> decimal */
+ )
+ + 1; /* turn floor into ceil */
+ else
+ tmp_length =
+ (unsigned int) (sizeof (unsigned int) * CHAR_BIT
+ * 0.30103 /* binary -> decimal */
+ )
+ + 1; /* turn floor into ceil */
+ if (tmp_length < precision)
+ tmp_length = precision;
+ /* Multiply by 2, as an estimate for FLAG_GROUP. */
+ tmp_length = xsum (tmp_length, tmp_length);
+ /* Add 1, to account for a leading sign. */
+ tmp_length = xsum (tmp_length, 1);
+ break;
+
+ case 'o':
+# if HAVE_LONG_LONG_INT
+ if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
+ tmp_length =
+ (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
+ * 0.333334 /* binary -> octal */
+ )
+ + 1; /* turn floor into ceil */
+ else
+# endif
+ if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
+ tmp_length =
+ (unsigned int) (sizeof (unsigned long) * CHAR_BIT
+ * 0.333334 /* binary -> octal */
+ )
+ + 1; /* turn floor into ceil */
+ else
+ tmp_length =
+ (unsigned int) (sizeof (unsigned int) * CHAR_BIT
+ * 0.333334 /* binary -> octal */
+ )
+ + 1; /* turn floor into ceil */
+ if (tmp_length < precision)
+ tmp_length = precision;
+ /* Add 1, to account for a leading sign. */
+ tmp_length = xsum (tmp_length, 1);
+ break;
+
+ case 'x': case 'X':
+# if HAVE_LONG_LONG_INT
+ if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
+ tmp_length =
+ (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
+ * 0.25 /* binary -> hexadecimal */
+ )
+ + 1; /* turn floor into ceil */
+ else
+# endif
+ if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
+ tmp_length =
+ (unsigned int) (sizeof (unsigned long) * CHAR_BIT
+ * 0.25 /* binary -> hexadecimal */
+ )
+ + 1; /* turn floor into ceil */
+ else
+ tmp_length =
+ (unsigned int) (sizeof (unsigned int) * CHAR_BIT
+ * 0.25 /* binary -> hexadecimal */
+ )
+ + 1; /* turn floor into ceil */
+ if (tmp_length < precision)
+ tmp_length = precision;
+ /* Add 2, to account for a leading sign or alternate form. */
+ tmp_length = xsum (tmp_length, 2);
+ break;
+
+ case 'f': case 'F':
+ if (type == TYPE_LONGDOUBLE)
+ tmp_length =
+ (unsigned int) (LDBL_MAX_EXP
+ * 0.30103 /* binary -> decimal */
+ * 2 /* estimate for FLAG_GROUP */
+ )
+ + 1 /* turn floor into ceil */
+ + 10; /* sign, decimal point etc. */
+ else
+ tmp_length =
+ (unsigned int) (DBL_MAX_EXP
+ * 0.30103 /* binary -> decimal */
+ * 2 /* estimate for FLAG_GROUP */
+ )
+ + 1 /* turn floor into ceil */
+ + 10; /* sign, decimal point etc. */
+ tmp_length = xsum (tmp_length, precision);
+ break;
+
+ case 'e': case 'E': case 'g': case 'G':
+ tmp_length =
+ 12; /* sign, decimal point, exponent etc. */
+ tmp_length = xsum (tmp_length, precision);
+ break;
+
+ case 'a': case 'A':
+ if (type == TYPE_LONGDOUBLE)
+ tmp_length =
+ (unsigned int) (LDBL_DIG
+ * 0.831 /* decimal -> hexadecimal */
+ )
+ + 1; /* turn floor into ceil */
+ else
+ tmp_length =
+ (unsigned int) (DBL_DIG
+ * 0.831 /* decimal -> hexadecimal */
+ )
+ + 1; /* turn floor into ceil */
+ if (tmp_length < precision)
+ tmp_length = precision;
+ /* Account for sign, decimal point etc. */
+ tmp_length = xsum (tmp_length, 12);
+ break;
+
+ case 'c':
+# if HAVE_WINT_T && !WIDE_CHAR_VERSION
+ if (type == TYPE_WIDE_CHAR)
+ tmp_length = MB_CUR_MAX;
+ else
+# endif
+ tmp_length = 1;
+ break;
+
+ case 's':
+# if HAVE_WCHAR_T
+ if (type == TYPE_WIDE_STRING)
+ {
+# if WIDE_CHAR_VERSION
+ /* ISO C says about %ls in fwprintf:
+ "If the precision is not specified or is greater than the size
+ of the array, the array shall contain a null wide character."
+ So if there is a precision, we must not use wcslen. */
+ const wchar_t *arg = ap->arg[arg_index].a.a_wide_string;
+
+ if (has_precision)
+ tmp_length = local_wcsnlen (arg, precision);
+ else
+ tmp_length = local_wcslen (arg);
+# else
+ /* ISO C says about %ls in fprintf:
+ "If a precision is specified, no more than that many bytes are
+ written (including shift sequences, if any), and the array
+ shall contain a null wide character if, to equal the multibyte
+ character sequence length given by the precision, the function
+ would need to access a wide character one past the end of the
+ array."
+ So if there is a precision, we must not use wcslen. */
+ /* This case has already been handled separately in VASNPRINTF. */
+ abort ();
+# endif
+ }
+ else
+# endif
+ {
+# if WIDE_CHAR_VERSION
+ /* ISO C says about %s in fwprintf:
+ "If the precision is not specified or is greater than the size
+ of the converted array, the converted array shall contain a
+ null wide character."
+ So if there is a precision, we must not use strlen. */
+ /* This case has already been handled separately in VASNPRINTF. */
+ abort ();
+# else
+ /* ISO C says about %s in fprintf:
+ "If the precision is not specified or greater than the size of
+ the array, the array shall contain a null character."
+ So if there is a precision, we must not use strlen. */
+ const char *arg = ap->arg[arg_index].a.a_string;
+
+ if (has_precision)
+ tmp_length = local_strnlen (arg, precision);
+ else
+ tmp_length = strlen (arg);
+# endif
+ }
+ break;
+
+ case 'p':
+ tmp_length =
+ (unsigned int) (sizeof (void *) * CHAR_BIT
+ * 0.25 /* binary -> hexadecimal */
+ )
+ + 1 /* turn floor into ceil */
+ + 2; /* account for leading 0x */
+ break;
+
+ default:
+ abort ();
+ }
+
+ if (!pad_ourselves)
+ {
+# if ENABLE_UNISTDIO
+ /* Padding considers the number of characters, therefore the number of
+ elements after padding may be
+ > max (tmp_length, width)
+ but is certainly
+ <= tmp_length + width. */
+ tmp_length = xsum (tmp_length, width);
+# else
+ /* Padding considers the number of elements, says POSIX. */
+ if (tmp_length < width)
+ tmp_length = width;
+# endif
+ }
+
+ tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
+
+ return tmp_length;
+}
+
+#endif
+
+DCHAR_T *
+VASNPRINTF (DCHAR_T *resultbuf, size_t *lengthp,
+ const FCHAR_T *format, va_list args)
{
DIRECTIVES d;
arguments a;
if (PRINTF_PARSE (format, &d, &a) < 0)
- {
- errno = EINVAL;
- return NULL;
- }
+ /* errno is already set. */
+ return NULL;
#define CLEANUP() \
- free (d.dir); \
- if (a.arg) \
+ if (d.dir != d.direct_alloc_dir) \
+ free (d.dir); \
+ if (a.arg != a.direct_alloc_arg) \
free (a.arg);
- if (printf_fetchargs (args, &a) < 0)
+ if (PRINTF_FETCHARGS (args, &a) < 0)
{
CLEANUP ();
errno = EINVAL;
@@ -130,789 +1795,3780 @@ VASNPRINTF (CHAR_T *resultbuf, size_t *lengthp, const CHAR_T *format, va_list ar
{
size_t buf_neededlength;
- CHAR_T *buf;
- CHAR_T *buf_malloced;
- const CHAR_T *cp;
+ TCHAR_T *buf;
+ TCHAR_T *buf_malloced;
+ const FCHAR_T *cp;
size_t i;
DIRECTIVE *dp;
/* Output string accumulator. */
- CHAR_T *result;
+ DCHAR_T *result;
size_t allocated;
size_t length;
/* Allocate a small buffer that will hold a directive passed to
sprintf or snprintf. */
- buf_neededlength = 7 + d.max_width_length + d.max_precision_length + 6;
+ buf_neededlength =
+ xsum4 (7, d.max_width_length, d.max_precision_length, 6);
#if HAVE_ALLOCA
- if (buf_neededlength < 4000 / sizeof (CHAR_T))
+ if (buf_neededlength < 4000 / sizeof (TCHAR_T))
{
- buf = alloca (buf_neededlength * sizeof (CHAR_T));
- buf_malloced = NULL;
+ buf = (TCHAR_T *) alloca (buf_neededlength * sizeof (TCHAR_T));
+ buf_malloced = NULL;
}
else
#endif
{
- if (SIZE_MAX / sizeof (CHAR_T) < buf_neededlength)
- goto out_of_memory_1;
- buf = (CHAR_T *) malloc (buf_neededlength * sizeof (CHAR_T));
- if (buf == NULL)
- goto out_of_memory_1;
- buf_malloced = buf;
+ size_t buf_memsize = xtimes (buf_neededlength, sizeof (TCHAR_T));
+ if (size_overflow_p (buf_memsize))
+ goto out_of_memory_1;
+ buf = (TCHAR_T *) malloc (buf_memsize);
+ if (buf == NULL)
+ goto out_of_memory_1;
+ buf_malloced = buf;
}
if (resultbuf != NULL)
{
- result = resultbuf;
- allocated = *lengthp;
+ result = resultbuf;
+ allocated = *lengthp;
}
else
{
- result = NULL;
- allocated = 0;
+ result = NULL;
+ allocated = 0;
}
length = 0;
/* Invariants:
result is either == resultbuf or == NULL or malloc-allocated.
If length > 0, then result != NULL. */
- /* Ensures that allocated >= length + extra. Aborts through a jump to
- out_of_memory if size is too big. */
-#define ENSURE_ALLOCATION(extra) \
- { \
- size_t needed = length + (extra); \
- if (needed < length) \
- goto out_of_memory; \
- if (needed > allocated) \
- { \
- size_t memory_size; \
- CHAR_T *memory; \
- \
- allocated = (allocated > 0 ? 2 * allocated : 12); \
- if (needed > allocated) \
- allocated = needed; \
- if (SIZE_MAX / sizeof (CHAR_T) < allocated) \
- goto out_of_memory; \
- memory_size = allocated * sizeof (CHAR_T); \
- if (result == resultbuf || result == NULL) \
- memory = (CHAR_T *) malloc (memory_size); \
- else \
- memory = (CHAR_T *) realloc (result, memory_size); \
- if (memory == NULL) \
- goto out_of_memory; \
- if (result == resultbuf && length > 0) \
- memcpy (memory, result, length * sizeof (CHAR_T)); \
- result = memory; \
- } \
- }
+ /* Ensures that allocated >= needed. Aborts through a jump to
+ out_of_memory if needed is SIZE_MAX or otherwise too big. */
+#define ENSURE_ALLOCATION(needed) \
+ if ((needed) > allocated) \
+ { \
+ size_t memory_size; \
+ DCHAR_T *memory; \
+ \
+ allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \
+ if ((needed) > allocated) \
+ allocated = (needed); \
+ memory_size = xtimes (allocated, sizeof (DCHAR_T)); \
+ if (size_overflow_p (memory_size)) \
+ goto out_of_memory; \
+ if (result == resultbuf || result == NULL) \
+ memory = (DCHAR_T *) malloc (memory_size); \
+ else \
+ memory = (DCHAR_T *) realloc (result, memory_size); \
+ if (memory == NULL) \
+ goto out_of_memory; \
+ if (result == resultbuf && length > 0) \
+ DCHAR_CPY (memory, result, length); \
+ result = memory; \
+ }
for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
{
- if (cp != dp->dir_start)
- {
- size_t n = dp->dir_start - cp;
-
- ENSURE_ALLOCATION (n);
- memcpy (result + length, cp, n * sizeof (CHAR_T));
- length += n;
- }
- if (i == d.count)
- break;
-
- /* Execute a single directive. */
- if (dp->conversion == '%')
- {
- if (!(dp->arg_index == ARG_NONE))
- abort ();
- ENSURE_ALLOCATION (1);
- result[length] = '%';
- length += 1;
- }
- else
- {
- if (!(dp->arg_index != ARG_NONE))
- abort ();
-
- if (dp->conversion == 'n')
- {
- switch (a.arg[dp->arg_index].type)
- {
- case TYPE_COUNT_SCHAR_POINTER:
- *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
- break;
- case TYPE_COUNT_SHORT_POINTER:
- *a.arg[dp->arg_index].a.a_count_short_pointer = length;
- break;
- case TYPE_COUNT_INT_POINTER:
- *a.arg[dp->arg_index].a.a_count_int_pointer = length;
- break;
- case TYPE_COUNT_LONGINT_POINTER:
- *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
- break;
+ if (cp != dp->dir_start)
+ {
+ size_t n = dp->dir_start - cp;
+ size_t augmented_length = xsum (length, n);
+
+ ENSURE_ALLOCATION (augmented_length);
+ /* This copies a piece of FCHAR_T[] into a DCHAR_T[]. Here we
+ need that the format string contains only ASCII characters
+ if FCHAR_T and DCHAR_T are not the same type. */
+ if (sizeof (FCHAR_T) == sizeof (DCHAR_T))
+ {
+ DCHAR_CPY (result + length, (const DCHAR_T *) cp, n);
+ length = augmented_length;
+ }
+ else
+ {
+ do
+ result[length++] = *cp++;
+ while (--n > 0);
+ }
+ }
+ if (i == d.count)
+ break;
+
+ /* Execute a single directive. */
+ if (dp->conversion == '%')
+ {
+ size_t augmented_length;
+
+ if (!(dp->arg_index == ARG_NONE))
+ abort ();
+ augmented_length = xsum (length, 1);
+ ENSURE_ALLOCATION (augmented_length);
+ result[length] = '%';
+ length = augmented_length;
+ }
+ else
+ {
+ if (!(dp->arg_index != ARG_NONE))
+ abort ();
+
+ if (dp->conversion == 'n')
+ {
+ switch (a.arg[dp->arg_index].type)
+ {
+ case TYPE_COUNT_SCHAR_POINTER:
+ *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
+ break;
+ case TYPE_COUNT_SHORT_POINTER:
+ *a.arg[dp->arg_index].a.a_count_short_pointer = length;
+ break;
+ case TYPE_COUNT_INT_POINTER:
+ *a.arg[dp->arg_index].a.a_count_int_pointer = length;
+ break;
+ case TYPE_COUNT_LONGINT_POINTER:
+ *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
+ break;
#if HAVE_LONG_LONG_INT
- case TYPE_COUNT_LONGLONGINT_POINTER:
- *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
- break;
-#endif
- default:
- abort ();
- }
- }
- else
- {
- arg_type type = a.arg[dp->arg_index].type;
- CHAR_T *p;
- unsigned int prefix_count;
- int prefixes[2];
+ case TYPE_COUNT_LONGLONGINT_POINTER:
+ *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
+ break;
+#endif
+ default:
+ abort ();
+ }
+ }
+#if ENABLE_UNISTDIO
+ /* The unistdio extensions. */
+ else if (dp->conversion == 'U')
+ {
+ arg_type type = a.arg[dp->arg_index].type;
+ int flags = dp->flags;
+ int has_width;
+ size_t width;
+ int has_precision;
+ size_t precision;
+
+ has_width = 0;
+ width = 0;
+ if (dp->width_start != dp->width_end)
+ {
+ if (dp->width_arg_index != ARG_NONE)
+ {
+ int arg;
+
+ if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
+ abort ();
+ arg = a.arg[dp->width_arg_index].a.a_int;
+ width = arg;
+ if (arg < 0)
+ {
+ /* "A negative field width is taken as a '-' flag
+ followed by a positive field width." */
+ flags |= FLAG_LEFT;
+ width = -width;
+ }
+ }
+ else
+ {
+ const FCHAR_T *digitp = dp->width_start;
+
+ do
+ width = xsum (xtimes (width, 10), *digitp++ - '0');
+ while (digitp != dp->width_end);
+ }
+ has_width = 1;
+ }
+
+ has_precision = 0;
+ precision = 0;
+ if (dp->precision_start != dp->precision_end)
+ {
+ if (dp->precision_arg_index != ARG_NONE)
+ {
+ int arg;
+
+ if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
+ abort ();
+ arg = a.arg[dp->precision_arg_index].a.a_int;
+ /* "A negative precision is taken as if the precision
+ were omitted." */
+ if (arg >= 0)
+ {
+ precision = arg;
+ has_precision = 1;
+ }
+ }
+ else
+ {
+ const FCHAR_T *digitp = dp->precision_start + 1;
+
+ precision = 0;
+ while (digitp != dp->precision_end)
+ precision = xsum (xtimes (precision, 10), *digitp++ - '0');
+ has_precision = 1;
+ }
+ }
+
+ switch (type)
+ {
+ case TYPE_U8_STRING:
+ {
+ const uint8_t *arg = a.arg[dp->arg_index].a.a_u8_string;
+ const uint8_t *arg_end;
+ size_t characters;
+
+ if (has_precision)
+ {
+ /* Use only PRECISION characters, from the left. */
+ arg_end = arg;
+ characters = 0;
+ for (; precision > 0; precision--)
+ {
+ int count = u8_strmblen (arg_end);
+ if (count == 0)
+ break;
+ if (count < 0)
+ {
+ if (!(result == resultbuf || result == NULL))
+ free (result);
+ if (buf_malloced != NULL)
+ free (buf_malloced);
+ CLEANUP ();
+ errno = EILSEQ;
+ return NULL;
+ }
+ arg_end += count;
+ characters++;
+ }
+ }
+ else if (has_width)
+ {
+ /* Use the entire string, and count the number of
+ characters. */
+ arg_end = arg;
+ characters = 0;
+ for (;;)
+ {
+ int count = u8_strmblen (arg_end);
+ if (count == 0)
+ break;
+ if (count < 0)
+ {
+ if (!(result == resultbuf || result == NULL))
+ free (result);
+ if (buf_malloced != NULL)
+ free (buf_malloced);
+ CLEANUP ();
+ errno = EILSEQ;
+ return NULL;
+ }
+ arg_end += count;
+ characters++;
+ }
+ }
+ else
+ {
+ /* Use the entire string. */
+ arg_end = arg + u8_strlen (arg);
+ /* The number of characters doesn't matter. */
+ characters = 0;
+ }
+
+ if (characters < width && !(dp->flags & FLAG_LEFT))
+ {
+ size_t n = width - characters;
+ ENSURE_ALLOCATION (xsum (length, n));
+ DCHAR_SET (result + length, ' ', n);
+ length += n;
+ }
+
+# if DCHAR_IS_UINT8_T
+ {
+ size_t n = arg_end - arg;
+ ENSURE_ALLOCATION (xsum (length, n));
+ DCHAR_CPY (result + length, arg, n);
+ length += n;
+ }
+# else
+ { /* Convert. */
+ DCHAR_T *converted = result + length;
+ size_t converted_len = allocated - length;
+# if DCHAR_IS_TCHAR
+ /* Convert from UTF-8 to locale encoding. */
+ converted =
+ u8_conv_to_encoding (locale_charset (),
+ iconveh_question_mark,
+ arg, arg_end - arg, NULL,
+ converted, &converted_len);
+# else
+ /* Convert from UTF-8 to UTF-16/UTF-32. */
+ converted =
+ U8_TO_DCHAR (arg, arg_end - arg,
+ converted, &converted_len);
+# endif
+ if (converted == NULL)
+ {
+ int saved_errno = errno;
+ if (!(result == resultbuf || result == NULL))
+ free (result);
+ if (buf_malloced != NULL)
+ free (buf_malloced);
+ CLEANUP ();
+ errno = saved_errno;
+ return NULL;
+ }
+ if (converted != result + length)
+ {
+ ENSURE_ALLOCATION (xsum (length, converted_len));
+ DCHAR_CPY (result + length, converted, converted_len);
+ free (converted);
+ }
+ length += converted_len;
+ }
+# endif
+
+ if (characters < width && (dp->flags & FLAG_LEFT))
+ {
+ size_t n = width - characters;
+ ENSURE_ALLOCATION (xsum (length, n));
+ DCHAR_SET (result + length, ' ', n);
+ length += n;
+ }
+ }
+ break;
+
+ case TYPE_U16_STRING:
+ {
+ const uint16_t *arg = a.arg[dp->arg_index].a.a_u16_string;
+ const uint16_t *arg_end;
+ size_t characters;
+
+ if (has_precision)
+ {
+ /* Use only PRECISION characters, from the left. */
+ arg_end = arg;
+ characters = 0;
+ for (; precision > 0; precision--)
+ {
+ int count = u16_strmblen (arg_end);
+ if (count == 0)
+ break;
+ if (count < 0)
+ {
+ if (!(result == resultbuf || result == NULL))
+ free (result);
+ if (buf_malloced != NULL)
+ free (buf_malloced);
+ CLEANUP ();
+ errno = EILSEQ;
+ return NULL;
+ }
+ arg_end += count;
+ characters++;
+ }
+ }
+ else if (has_width)
+ {
+ /* Use the entire string, and count the number of
+ characters. */
+ arg_end = arg;
+ characters = 0;
+ for (;;)
+ {
+ int count = u16_strmblen (arg_end);
+ if (count == 0)
+ break;
+ if (count < 0)
+ {
+ if (!(result == resultbuf || result == NULL))
+ free (result);
+ if (buf_malloced != NULL)
+ free (buf_malloced);
+ CLEANUP ();
+ errno = EILSEQ;
+ return NULL;
+ }
+ arg_end += count;
+ characters++;
+ }
+ }
+ else
+ {
+ /* Use the entire string. */
+ arg_end = arg + u16_strlen (arg);
+ /* The number of characters doesn't matter. */
+ characters = 0;
+ }
+
+ if (characters < width && !(dp->flags & FLAG_LEFT))
+ {
+ size_t n = width - characters;
+ ENSURE_ALLOCATION (xsum (length, n));
+ DCHAR_SET (result + length, ' ', n);
+ length += n;
+ }
+
+# if DCHAR_IS_UINT16_T
+ {
+ size_t n = arg_end - arg;
+ ENSURE_ALLOCATION (xsum (length, n));
+ DCHAR_CPY (result + length, arg, n);
+ length += n;
+ }
+# else
+ { /* Convert. */
+ DCHAR_T *converted = result + length;
+ size_t converted_len = allocated - length;
+# if DCHAR_IS_TCHAR
+ /* Convert from UTF-16 to locale encoding. */
+ converted =
+ u16_conv_to_encoding (locale_charset (),
+ iconveh_question_mark,
+ arg, arg_end - arg, NULL,
+ converted, &converted_len);
+# else
+ /* Convert from UTF-16 to UTF-8/UTF-32. */
+ converted =
+ U16_TO_DCHAR (arg, arg_end - arg,
+ converted, &converted_len);
+# endif
+ if (converted == NULL)
+ {
+ int saved_errno = errno;
+ if (!(result == resultbuf || result == NULL))
+ free (result);
+ if (buf_malloced != NULL)
+ free (buf_malloced);
+ CLEANUP ();
+ errno = saved_errno;
+ return NULL;
+ }
+ if (converted != result + length)
+ {
+ ENSURE_ALLOCATION (xsum (length, converted_len));
+ DCHAR_CPY (result + length, converted, converted_len);
+ free (converted);
+ }
+ length += converted_len;
+ }
+# endif
+
+ if (characters < width && (dp->flags & FLAG_LEFT))
+ {
+ size_t n = width - characters;
+ ENSURE_ALLOCATION (xsum (length, n));
+ DCHAR_SET (result + length, ' ', n);
+ length += n;
+ }
+ }
+ break;
+
+ case TYPE_U32_STRING:
+ {
+ const uint32_t *arg = a.arg[dp->arg_index].a.a_u32_string;
+ const uint32_t *arg_end;
+ size_t characters;
+
+ if (has_precision)
+ {
+ /* Use only PRECISION characters, from the left. */
+ arg_end = arg;
+ characters = 0;
+ for (; precision > 0; precision--)
+ {
+ int count = u32_strmblen (arg_end);
+ if (count == 0)
+ break;
+ if (count < 0)
+ {
+ if (!(result == resultbuf || result == NULL))
+ free (result);
+ if (buf_malloced != NULL)
+ free (buf_malloced);
+ CLEANUP ();
+ errno = EILSEQ;
+ return NULL;
+ }
+ arg_end += count;
+ characters++;
+ }
+ }
+ else if (has_width)
+ {
+ /* Use the entire string, and count the number of
+ characters. */
+ arg_end = arg;
+ characters = 0;
+ for (;;)
+ {
+ int count = u32_strmblen (arg_end);
+ if (count == 0)
+ break;
+ if (count < 0)
+ {
+ if (!(result == resultbuf || result == NULL))
+ free (result);
+ if (buf_malloced != NULL)
+ free (buf_malloced);
+ CLEANUP ();
+ errno = EILSEQ;
+ return NULL;
+ }
+ arg_end += count;
+ characters++;
+ }
+ }
+ else
+ {
+ /* Use the entire string. */
+ arg_end = arg + u32_strlen (arg);
+ /* The number of characters doesn't matter. */
+ characters = 0;
+ }
+
+ if (characters < width && !(dp->flags & FLAG_LEFT))
+ {
+ size_t n = width - characters;
+ ENSURE_ALLOCATION (xsum (length, n));
+ DCHAR_SET (result + length, ' ', n);
+ length += n;
+ }
+
+# if DCHAR_IS_UINT32_T
+ {
+ size_t n = arg_end - arg;
+ ENSURE_ALLOCATION (xsum (length, n));
+ DCHAR_CPY (result + length, arg, n);
+ length += n;
+ }
+# else
+ { /* Convert. */
+ DCHAR_T *converted = result + length;
+ size_t converted_len = allocated - length;
+# if DCHAR_IS_TCHAR
+ /* Convert from UTF-32 to locale encoding. */
+ converted =
+ u32_conv_to_encoding (locale_charset (),
+ iconveh_question_mark,
+ arg, arg_end - arg, NULL,
+ converted, &converted_len);
+# else
+ /* Convert from UTF-32 to UTF-8/UTF-16. */
+ converted =
+ U32_TO_DCHAR (arg, arg_end - arg,
+ converted, &converted_len);
+# endif
+ if (converted == NULL)
+ {
+ int saved_errno = errno;
+ if (!(result == resultbuf || result == NULL))
+ free (result);
+ if (buf_malloced != NULL)
+ free (buf_malloced);
+ CLEANUP ();
+ errno = saved_errno;
+ return NULL;
+ }
+ if (converted != result + length)
+ {
+ ENSURE_ALLOCATION (xsum (length, converted_len));
+ DCHAR_CPY (result + length, converted, converted_len);
+ free (converted);
+ }
+ length += converted_len;
+ }
+# endif
+
+ if (characters < width && (dp->flags & FLAG_LEFT))
+ {
+ size_t n = width - characters;
+ ENSURE_ALLOCATION (xsum (length, n));
+ DCHAR_SET (result + length, ' ', n);
+ length += n;
+ }
+ }
+ break;
+
+ default:
+ abort ();
+ }
+ }
+#endif
+#if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || (NEED_PRINTF_DIRECTIVE_LS && !defined IN_LIBINTL)) && HAVE_WCHAR_T
+ else if (dp->conversion == 's'
+# if WIDE_CHAR_VERSION
+ && a.arg[dp->arg_index].type != TYPE_WIDE_STRING
+# else
+ && a.arg[dp->arg_index].type == TYPE_WIDE_STRING
+# endif
+ )
+ {
+ /* The normal handling of the 's' directive below requires
+ allocating a temporary buffer. The determination of its
+ length (tmp_length), in the case when a precision is
+ specified, below requires a conversion between a char[]
+ string and a wchar_t[] wide string. It could be done, but
+ we have no guarantee that the implementation of sprintf will
+ use the exactly same algorithm. Without this guarantee, it
+ is possible to have buffer overrun bugs. In order to avoid
+ such bugs, we implement the entire processing of the 's'
+ directive ourselves. */
+ int flags = dp->flags;
+ int has_width;
+ size_t width;
+ int has_precision;
+ size_t precision;
+
+ has_width = 0;
+ width = 0;
+ if (dp->width_start != dp->width_end)
+ {
+ if (dp->width_arg_index != ARG_NONE)
+ {
+ int arg;
+
+ if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
+ abort ();
+ arg = a.arg[dp->width_arg_index].a.a_int;
+ width = arg;
+ if (arg < 0)
+ {
+ /* "A negative field width is taken as a '-' flag
+ followed by a positive field width." */
+ flags |= FLAG_LEFT;
+ width = -width;
+ }
+ }
+ else
+ {
+ const FCHAR_T *digitp = dp->width_start;
+
+ do
+ width = xsum (xtimes (width, 10), *digitp++ - '0');
+ while (digitp != dp->width_end);
+ }
+ has_width = 1;
+ }
+
+ has_precision = 0;
+ precision = 6;
+ if (dp->precision_start != dp->precision_end)
+ {
+ if (dp->precision_arg_index != ARG_NONE)
+ {
+ int arg;
+
+ if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
+ abort ();
+ arg = a.arg[dp->precision_arg_index].a.a_int;
+ /* "A negative precision is taken as if the precision
+ were omitted." */
+ if (arg >= 0)
+ {
+ precision = arg;
+ has_precision = 1;
+ }
+ }
+ else
+ {
+ const FCHAR_T *digitp = dp->precision_start + 1;
+
+ precision = 0;
+ while (digitp != dp->precision_end)
+ precision = xsum (xtimes (precision, 10), *digitp++ - '0');
+ has_precision = 1;
+ }
+ }
+
+# if WIDE_CHAR_VERSION
+ /* %s in vasnwprintf. See the specification of fwprintf. */
+ {
+ const char *arg = a.arg[dp->arg_index].a.a_string;
+ const char *arg_end;
+ size_t characters;
+
+ if (has_precision)
+ {
+ /* Use only as many bytes as needed to produce PRECISION
+ wide characters, from the left. */
+# if HAVE_MBRTOWC
+ mbstate_t state;
+ memset (&state, '\0', sizeof (mbstate_t));
+# endif
+ arg_end = arg;
+ characters = 0;
+ for (; precision > 0; precision--)
+ {
+ int count;
+# if HAVE_MBRTOWC
+ count = mbrlen (arg_end, MB_CUR_MAX, &state);
+# else
+ count = mblen (arg_end, MB_CUR_MAX);
+# endif
+ if (count == 0)
+ /* Found the terminating NUL. */
+ break;
+ if (count < 0)
+ {
+ /* Invalid or incomplete multibyte character. */
+ if (!(result == resultbuf || result == NULL))
+ free (result);
+ if (buf_malloced != NULL)
+ free (buf_malloced);
+ CLEANUP ();
+ errno = EILSEQ;
+ return NULL;
+ }
+ arg_end += count;
+ characters++;
+ }
+ }
+ else if (has_width)
+ {
+ /* Use the entire string, and count the number of wide
+ characters. */
+# if HAVE_MBRTOWC
+ mbstate_t state;
+ memset (&state, '\0', sizeof (mbstate_t));
+# endif
+ arg_end = arg;
+ characters = 0;
+ for (;;)
+ {
+ int count;
+# if HAVE_MBRTOWC
+ count = mbrlen (arg_end, MB_CUR_MAX, &state);
+# else
+ count = mblen (arg_end, MB_CUR_MAX);
+# endif
+ if (count == 0)
+ /* Found the terminating NUL. */
+ break;
+ if (count < 0)
+ {
+ /* Invalid or incomplete multibyte character. */
+ if (!(result == resultbuf || result == NULL))
+ free (result);
+ if (buf_malloced != NULL)
+ free (buf_malloced);
+ CLEANUP ();
+ errno = EILSEQ;
+ return NULL;
+ }
+ arg_end += count;
+ characters++;
+ }
+ }
+ else
+ {
+ /* Use the entire string. */
+ arg_end = arg + strlen (arg);
+ /* The number of characters doesn't matter. */
+ characters = 0;
+ }
+
+ if (characters < width && !(dp->flags & FLAG_LEFT))
+ {
+ size_t n = width - characters;
+ ENSURE_ALLOCATION (xsum (length, n));
+ DCHAR_SET (result + length, ' ', n);
+ length += n;
+ }
+
+ if (has_precision || has_width)
+ {
+ /* We know the number of wide characters in advance. */
+ size_t remaining;
+# if HAVE_MBRTOWC
+ mbstate_t state;
+ memset (&state, '\0', sizeof (mbstate_t));
+# endif
+ ENSURE_ALLOCATION (xsum (length, characters));
+ for (remaining = characters; remaining > 0; remaining--)
+ {
+ wchar_t wc;
+ int count;
+# if HAVE_MBRTOWC
+ count = mbrtowc (&wc, arg, arg_end - arg, &state);
+# else
+ count = mbtowc (&wc, arg, arg_end - arg);
+# endif
+ if (count <= 0)
+ /* mbrtowc not consistent with mbrlen, or mbtowc
+ not consistent with mblen. */
+ abort ();
+ result[length++] = wc;
+ arg += count;
+ }
+ if (!(arg == arg_end))
+ abort ();
+ }
+ else
+ {
+# if HAVE_MBRTOWC
+ mbstate_t state;
+ memset (&state, '\0', sizeof (mbstate_t));
+# endif
+ while (arg < arg_end)
+ {
+ wchar_t wc;
+ int count;
+# if HAVE_MBRTOWC
+ count = mbrtowc (&wc, arg, arg_end - arg, &state);
+# else
+ count = mbtowc (&wc, arg, arg_end - arg);
+# endif
+ if (count <= 0)
+ /* mbrtowc not consistent with mbrlen, or mbtowc
+ not consistent with mblen. */
+ abort ();
+ ENSURE_ALLOCATION (xsum (length, 1));
+ result[length++] = wc;
+ arg += count;
+ }
+ }
+
+ if (characters < width && (dp->flags & FLAG_LEFT))
+ {
+ size_t n = width - characters;
+ ENSURE_ALLOCATION (xsum (length, n));
+ DCHAR_SET (result + length, ' ', n);
+ length += n;
+ }
+ }
+# else
+ /* %ls in vasnprintf. See the specification of fprintf. */
+ {
+ const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
+ const wchar_t *arg_end;
+ size_t characters;
+# if !DCHAR_IS_TCHAR
+ /* This code assumes that TCHAR_T is 'char'. */
+ verify (sizeof (TCHAR_T) == 1);
+ TCHAR_T *tmpsrc;
+ DCHAR_T *tmpdst;
+ size_t tmpdst_len;
+# endif
+ size_t w;
+
+ if (has_precision)
+ {
+ /* Use only as many wide characters as needed to produce
+ at most PRECISION bytes, from the left. */
+# if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
+ mbstate_t state;
+ memset (&state, '\0', sizeof (mbstate_t));
+# endif
+ arg_end = arg;
+ characters = 0;
+ while (precision > 0)
+ {
+ char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
+ int count;
+
+ if (*arg_end == 0)
+ /* Found the terminating null wide character. */
+ break;
+# if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
+ count = wcrtomb (cbuf, *arg_end, &state);
+# else
+ count = wctomb (cbuf, *arg_end);
+# endif
+ if (count < 0)
+ {
+ /* Cannot convert. */
+ if (!(result == resultbuf || result == NULL))
+ free (result);
+ if (buf_malloced != NULL)
+ free (buf_malloced);
+ CLEANUP ();
+ errno = EILSEQ;
+ return NULL;
+ }
+ if (precision < count)
+ break;
+ arg_end++;
+ characters += count;
+ precision -= count;
+ }
+ }
+# if DCHAR_IS_TCHAR
+ else if (has_width)
+# else
+ else
+# endif
+ {
+ /* Use the entire string, and count the number of
+ bytes. */
+# if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
+ mbstate_t state;
+ memset (&state, '\0', sizeof (mbstate_t));
+# endif
+ arg_end = arg;
+ characters = 0;
+ for (;;)
+ {
+ char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
+ int count;
+
+ if (*arg_end == 0)
+ /* Found the terminating null wide character. */
+ break;
+# if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
+ count = wcrtomb (cbuf, *arg_end, &state);
+# else
+ count = wctomb (cbuf, *arg_end);
+# endif
+ if (count < 0)
+ {
+ /* Cannot convert. */
+ if (!(result == resultbuf || result == NULL))
+ free (result);
+ if (buf_malloced != NULL)
+ free (buf_malloced);
+ CLEANUP ();
+ errno = EILSEQ;
+ return NULL;
+ }
+ arg_end++;
+ characters += count;
+ }
+ }
+# if DCHAR_IS_TCHAR
+ else
+ {
+ /* Use the entire string. */
+ arg_end = arg + local_wcslen (arg);
+ /* The number of bytes doesn't matter. */
+ characters = 0;
+ }
+# endif
+
+# if !DCHAR_IS_TCHAR
+ /* Convert the string into a piece of temporary memory. */
+ tmpsrc = (TCHAR_T *) malloc (characters * sizeof (TCHAR_T));
+ if (tmpsrc == NULL)
+ goto out_of_memory;
+ {
+ TCHAR_T *tmpptr = tmpsrc;
+ size_t remaining;
+# if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
+ mbstate_t state;
+ memset (&state, '\0', sizeof (mbstate_t));
+# endif
+ for (remaining = characters; remaining > 0; )
+ {
+ char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
+ int count;
+
+ if (*arg == 0)
+ abort ();
+# if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
+ count = wcrtomb (cbuf, *arg, &state);
+# else
+ count = wctomb (cbuf, *arg);
+# endif
+ if (count <= 0)
+ /* Inconsistency. */
+ abort ();
+ memcpy (tmpptr, cbuf, count);
+ tmpptr += count;
+ arg++;
+ remaining -= count;
+ }
+ if (!(arg == arg_end))
+ abort ();
+ }
+
+ /* Convert from TCHAR_T[] to DCHAR_T[]. */
+ tmpdst =
+ DCHAR_CONV_FROM_ENCODING (locale_charset (),
+ iconveh_question_mark,
+ tmpsrc, characters,
+ NULL,
+ NULL, &tmpdst_len);
+ if (tmpdst == NULL)
+ {
+ int saved_errno = errno;
+ free (tmpsrc);
+ if (!(result == resultbuf || result == NULL))
+ free (result);
+ if (buf_malloced != NULL)
+ free (buf_malloced);
+ CLEANUP ();
+ errno = saved_errno;
+ return NULL;
+ }
+ free (tmpsrc);
+# endif
+
+ if (has_width)
+ {
+# if ENABLE_UNISTDIO
+ /* Outside POSIX, it's preferable to compare the width
+ against the number of _characters_ of the converted
+ value. */
+ w = DCHAR_MBSNLEN (result + length, characters);
+# else
+ /* The width is compared against the number of _bytes_
+ of the converted value, says POSIX. */
+ w = characters;
+# endif
+ }
+ else
+ /* w doesn't matter. */
+ w = 0;
+
+ if (w < width && !(dp->flags & FLAG_LEFT))
+ {
+ size_t n = width - w;
+ ENSURE_ALLOCATION (xsum (length, n));
+ DCHAR_SET (result + length, ' ', n);
+ length += n;
+ }
+
+# if DCHAR_IS_TCHAR
+ if (has_precision || has_width)
+ {
+ /* We know the number of bytes in advance. */
+ size_t remaining;
+# if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
+ mbstate_t state;
+ memset (&state, '\0', sizeof (mbstate_t));
+# endif
+ ENSURE_ALLOCATION (xsum (length, characters));
+ for (remaining = characters; remaining > 0; )
+ {
+ char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
+ int count;
+
+ if (*arg == 0)
+ abort ();
+# if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
+ count = wcrtomb (cbuf, *arg, &state);
+# else
+ count = wctomb (cbuf, *arg);
+# endif
+ if (count <= 0)
+ /* Inconsistency. */
+ abort ();
+ memcpy (result + length, cbuf, count);
+ length += count;
+ arg++;
+ remaining -= count;
+ }
+ if (!(arg == arg_end))
+ abort ();
+ }
+ else
+ {
+# if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
+ mbstate_t state;
+ memset (&state, '\0', sizeof (mbstate_t));
+# endif
+ while (arg < arg_end)
+ {
+ char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
+ int count;
+
+ if (*arg == 0)
+ abort ();
+# if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
+ count = wcrtomb (cbuf, *arg, &state);
+# else
+ count = wctomb (cbuf, *arg);
+# endif
+ if (count <= 0)
+ {
+ /* Cannot convert. */
+ if (!(result == resultbuf || result == NULL))
+ free (result);
+ if (buf_malloced != NULL)
+ free (buf_malloced);
+ CLEANUP ();
+ errno = EILSEQ;
+ return NULL;
+ }
+ ENSURE_ALLOCATION (xsum (length, count));
+ memcpy (result + length, cbuf, count);
+ length += count;
+ arg++;
+ }
+ }
+# else
+ ENSURE_ALLOCATION (xsum (length, tmpdst_len));
+ DCHAR_CPY (result + length, tmpdst, tmpdst_len);
+ free (tmpdst);
+ length += tmpdst_len;
+# endif
+
+ if (w < width && (dp->flags & FLAG_LEFT))
+ {
+ size_t n = width - w;
+ ENSURE_ALLOCATION (xsum (length, n));
+ DCHAR_SET (result + length, ' ', n);
+ length += n;
+ }
+ }
+# endif
+ }
+#endif
+#if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
+ else if ((dp->conversion == 'a' || dp->conversion == 'A')
+# if !(NEED_PRINTF_DIRECTIVE_A || (NEED_PRINTF_LONG_DOUBLE && NEED_PRINTF_DOUBLE))
+ && (0
+# if NEED_PRINTF_DOUBLE
+ || a.arg[dp->arg_index].type == TYPE_DOUBLE
+# endif
+# if NEED_PRINTF_LONG_DOUBLE
+ || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
+# endif
+ )
+# endif
+ )
+ {
+ arg_type type = a.arg[dp->arg_index].type;
+ int flags = dp->flags;
+ size_t width;
+ int has_precision;
+ size_t precision;
+ size_t tmp_length;
+ size_t count;
+ DCHAR_T tmpbuf[700];
+ DCHAR_T *tmp;
+ DCHAR_T *pad_ptr;
+ DCHAR_T *p;
+
+ width = 0;
+ if (dp->width_start != dp->width_end)
+ {
+ if (dp->width_arg_index != ARG_NONE)
+ {
+ int arg;
+
+ if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
+ abort ();
+ arg = a.arg[dp->width_arg_index].a.a_int;
+ width = arg;
+ if (arg < 0)
+ {
+ /* "A negative field width is taken as a '-' flag
+ followed by a positive field width." */
+ flags |= FLAG_LEFT;
+ width = -width;
+ }
+ }
+ else
+ {
+ const FCHAR_T *digitp = dp->width_start;
+
+ do
+ width = xsum (xtimes (width, 10), *digitp++ - '0');
+ while (digitp != dp->width_end);
+ }
+ }
+
+ has_precision = 0;
+ precision = 0;
+ if (dp->precision_start != dp->precision_end)
+ {
+ if (dp->precision_arg_index != ARG_NONE)
+ {
+ int arg;
+
+ if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
+ abort ();
+ arg = a.arg[dp->precision_arg_index].a.a_int;
+ /* "A negative precision is taken as if the precision
+ were omitted." */
+ if (arg >= 0)
+ {
+ precision = arg;
+ has_precision = 1;
+ }
+ }
+ else
+ {
+ const FCHAR_T *digitp = dp->precision_start + 1;
+
+ precision = 0;
+ while (digitp != dp->precision_end)
+ precision = xsum (xtimes (precision, 10), *digitp++ - '0');
+ has_precision = 1;
+ }
+ }
+
+ /* Allocate a temporary buffer of sufficient size. */
+ if (type == TYPE_LONGDOUBLE)
+ tmp_length =
+ (unsigned int) ((LDBL_DIG + 1)
+ * 0.831 /* decimal -> hexadecimal */
+ )
+ + 1; /* turn floor into ceil */
+ else
+ tmp_length =
+ (unsigned int) ((DBL_DIG + 1)
+ * 0.831 /* decimal -> hexadecimal */
+ )
+ + 1; /* turn floor into ceil */
+ if (tmp_length < precision)
+ tmp_length = precision;
+ /* Account for sign, decimal point etc. */
+ tmp_length = xsum (tmp_length, 12);
+
+ if (tmp_length < width)
+ tmp_length = width;
+
+ tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
+
+ if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
+ tmp = tmpbuf;
+ else
+ {
+ size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
+
+ if (size_overflow_p (tmp_memsize))
+ /* Overflow, would lead to out of memory. */
+ goto out_of_memory;
+ tmp = (DCHAR_T *) malloc (tmp_memsize);
+ if (tmp == NULL)
+ /* Out of memory. */
+ goto out_of_memory;
+ }
+
+ pad_ptr = NULL;
+ p = tmp;
+ if (type == TYPE_LONGDOUBLE)
+ {
+# if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE
+ long double arg = a.arg[dp->arg_index].a.a_longdouble;
+
+ if (isnanl (arg))
+ {
+ if (dp->conversion == 'A')
+ {
+ *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
+ }
+ else
+ {
+ *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
+ }
+ }
+ else
+ {
+ int sign = 0;
+ DECL_LONG_DOUBLE_ROUNDING
+
+ BEGIN_LONG_DOUBLE_ROUNDING ();
+
+ if (signbit (arg)) /* arg < 0.0L or negative zero */
+ {
+ sign = -1;
+ arg = -arg;
+ }
+
+ if (sign < 0)
+ *p++ = '-';
+ else if (flags & FLAG_SHOWSIGN)
+ *p++ = '+';
+ else if (flags & FLAG_SPACE)
+ *p++ = ' ';
+
+ if (arg > 0.0L && arg + arg == arg)
+ {
+ if (dp->conversion == 'A')
+ {
+ *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
+ }
+ else
+ {
+ *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
+ }
+ }
+ else
+ {
+ int exponent;
+ long double mantissa;
+
+ if (arg > 0.0L)
+ mantissa = printf_frexpl (arg, &exponent);
+ else
+ {
+ exponent = 0;
+ mantissa = 0.0L;
+ }
+
+ if (has_precision
+ && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
+ {
+ /* Round the mantissa. */
+ long double tail = mantissa;
+ size_t q;
+
+ for (q = precision; ; q--)
+ {
+ int digit = (int) tail;
+ tail -= digit;
+ if (q == 0)
+ {
+ if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
+ tail = 1 - tail;
+ else
+ tail = - tail;
+ break;
+ }
+ tail *= 16.0L;
+ }
+ if (tail != 0.0L)
+ for (q = precision; q > 0; q--)
+ tail *= 0.0625L;
+ mantissa += tail;
+ }
+
+ *p++ = '0';
+ *p++ = dp->conversion - 'A' + 'X';
+ pad_ptr = p;
+ {
+ int digit;
+
+ digit = (int) mantissa;
+ mantissa -= digit;
+ *p++ = '0' + digit;
+ if ((flags & FLAG_ALT)
+ || mantissa > 0.0L || precision > 0)
+ {
+ *p++ = decimal_point_char ();
+ /* This loop terminates because we assume
+ that FLT_RADIX is a power of 2. */
+ while (mantissa > 0.0L)
+ {
+ mantissa *= 16.0L;
+ digit = (int) mantissa;
+ mantissa -= digit;
+ *p++ = digit
+ + (digit < 10
+ ? '0'
+ : dp->conversion - 10);
+ if (precision > 0)
+ precision--;
+ }
+ while (precision > 0)
+ {
+ *p++ = '0';
+ precision--;
+ }
+ }
+ }
+ *p++ = dp->conversion - 'A' + 'P';
+# if WIDE_CHAR_VERSION
+ {
+ static const wchar_t decimal_format[] =
+ { '%', '+', 'd', '\0' };
+ SNPRINTF (p, 6 + 1, decimal_format, exponent);
+ }
+ while (*p != '\0')
+ p++;
+# else
+ if (sizeof (DCHAR_T) == 1)
+ {
+ sprintf ((char *) p, "%+d", exponent);
+ while (*p != '\0')
+ p++;
+ }
+ else
+ {
+ char expbuf[6 + 1];
+ const char *ep;
+ sprintf (expbuf, "%+d", exponent);
+ for (ep = expbuf; (*p = *ep) != '\0'; ep++)
+ p++;
+ }
+# endif
+ }
+
+ END_LONG_DOUBLE_ROUNDING ();
+ }
+# else
+ abort ();
+# endif
+ }
+ else
+ {
+# if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE
+ double arg = a.arg[dp->arg_index].a.a_double;
+
+ if (isnand (arg))
+ {
+ if (dp->conversion == 'A')
+ {
+ *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
+ }
+ else
+ {
+ *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
+ }
+ }
+ else
+ {
+ int sign = 0;
+
+ if (signbit (arg)) /* arg < 0.0 or negative zero */
+ {
+ sign = -1;
+ arg = -arg;
+ }
+
+ if (sign < 0)
+ *p++ = '-';
+ else if (flags & FLAG_SHOWSIGN)
+ *p++ = '+';
+ else if (flags & FLAG_SPACE)
+ *p++ = ' ';
+
+ if (arg > 0.0 && arg + arg == arg)
+ {
+ if (dp->conversion == 'A')
+ {
+ *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
+ }
+ else
+ {
+ *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
+ }
+ }
+ else
+ {
+ int exponent;
+ double mantissa;
+
+ if (arg > 0.0)
+ mantissa = printf_frexp (arg, &exponent);
+ else
+ {
+ exponent = 0;
+ mantissa = 0.0;
+ }
+
+ if (has_precision
+ && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
+ {
+ /* Round the mantissa. */
+ double tail = mantissa;
+ size_t q;
+
+ for (q = precision; ; q--)
+ {
+ int digit = (int) tail;
+ tail -= digit;
+ if (q == 0)
+ {
+ if (digit & 1 ? tail >= 0.5 : tail > 0.5)
+ tail = 1 - tail;
+ else
+ tail = - tail;
+ break;
+ }
+ tail *= 16.0;
+ }
+ if (tail != 0.0)
+ for (q = precision; q > 0; q--)
+ tail *= 0.0625;
+ mantissa += tail;
+ }
+
+ *p++ = '0';
+ *p++ = dp->conversion - 'A' + 'X';
+ pad_ptr = p;
+ {
+ int digit;
+
+ digit = (int) mantissa;
+ mantissa -= digit;
+ *p++ = '0' + digit;
+ if ((flags & FLAG_ALT)
+ || mantissa > 0.0 || precision > 0)
+ {
+ *p++ = decimal_point_char ();
+ /* This loop terminates because we assume
+ that FLT_RADIX is a power of 2. */
+ while (mantissa > 0.0)
+ {
+ mantissa *= 16.0;
+ digit = (int) mantissa;
+ mantissa -= digit;
+ *p++ = digit
+ + (digit < 10
+ ? '0'
+ : dp->conversion - 10);
+ if (precision > 0)
+ precision--;
+ }
+ while (precision > 0)
+ {
+ *p++ = '0';
+ precision--;
+ }
+ }
+ }
+ *p++ = dp->conversion - 'A' + 'P';
+# if WIDE_CHAR_VERSION
+ {
+ static const wchar_t decimal_format[] =
+ { '%', '+', 'd', '\0' };
+ SNPRINTF (p, 6 + 1, decimal_format, exponent);
+ }
+ while (*p != '\0')
+ p++;
+# else
+ if (sizeof (DCHAR_T) == 1)
+ {
+ sprintf ((char *) p, "%+d", exponent);
+ while (*p != '\0')
+ p++;
+ }
+ else
+ {
+ char expbuf[6 + 1];
+ const char *ep;
+ sprintf (expbuf, "%+d", exponent);
+ for (ep = expbuf; (*p = *ep) != '\0'; ep++)
+ p++;
+ }
+# endif
+ }
+ }
+# else
+ abort ();
+# endif
+ }
+
+ /* The generated string now extends from tmp to p, with the
+ zero padding insertion point being at pad_ptr. */
+ count = p - tmp;
+
+ if (count < width)
+ {
+ size_t pad = width - count;
+ DCHAR_T *end = p + pad;
+
+ if (flags & FLAG_LEFT)
+ {
+ /* Pad with spaces on the right. */
+ for (; pad > 0; pad--)
+ *p++ = ' ';
+ }
+ else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
+ {
+ /* Pad with zeroes. */
+ DCHAR_T *q = end;
+
+ while (p > pad_ptr)
+ *--q = *--p;
+ for (; pad > 0; pad--)
+ *p++ = '0';
+ }
+ else
+ {
+ /* Pad with spaces on the left. */
+ DCHAR_T *q = end;
+
+ while (p > tmp)
+ *--q = *--p;
+ for (; pad > 0; pad--)
+ *p++ = ' ';
+ }
+
+ p = end;
+ }
+
+ count = p - tmp;
+
+ if (count >= tmp_length)
+ /* tmp_length was incorrectly calculated - fix the
+ code above! */
+ abort ();
+
+ /* Make room for the result. */
+ if (count >= allocated - length)
+ {
+ size_t n = xsum (length, count);
+
+ ENSURE_ALLOCATION (n);
+ }
+
+ /* Append the result. */
+ memcpy (result + length, tmp, count * sizeof (DCHAR_T));
+ if (tmp != tmpbuf)
+ free (tmp);
+ length += count;
+ }
+#endif
+#if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
+ else if ((dp->conversion == 'f' || dp->conversion == 'F'
+ || dp->conversion == 'e' || dp->conversion == 'E'
+ || dp->conversion == 'g' || dp->conversion == 'G'
+ || dp->conversion == 'a' || dp->conversion == 'A')
+ && (0
+# if NEED_PRINTF_DOUBLE
+ || a.arg[dp->arg_index].type == TYPE_DOUBLE
+# elif NEED_PRINTF_INFINITE_DOUBLE
+ || (a.arg[dp->arg_index].type == TYPE_DOUBLE
+ /* The systems (mingw) which produce wrong output
+ for Inf, -Inf, and NaN also do so for -0.0.
+ Therefore we treat this case here as well. */
+ && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
+# endif
+# if NEED_PRINTF_LONG_DOUBLE
+ || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
+# elif NEED_PRINTF_INFINITE_LONG_DOUBLE
+ || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
+ /* Some systems produce wrong output for Inf,
+ -Inf, and NaN. Some systems in this category
+ (IRIX 5.3) also do so for -0.0. Therefore we
+ treat this case here as well. */
+ && is_infinite_or_zerol (a.arg[dp->arg_index].a.a_longdouble))
+# endif
+ ))
+ {
+# if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
+ arg_type type = a.arg[dp->arg_index].type;
+# endif
+ int flags = dp->flags;
+ size_t width;
+ size_t count;
+ int has_precision;
+ size_t precision;
+ size_t tmp_length;
+ DCHAR_T tmpbuf[700];
+ DCHAR_T *tmp;
+ DCHAR_T *pad_ptr;
+ DCHAR_T *p;
+
+ width = 0;
+ if (dp->width_start != dp->width_end)
+ {
+ if (dp->width_arg_index != ARG_NONE)
+ {
+ int arg;
+
+ if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
+ abort ();
+ arg = a.arg[dp->width_arg_index].a.a_int;
+ width = arg;
+ if (arg < 0)
+ {
+ /* "A negative field width is taken as a '-' flag
+ followed by a positive field width." */
+ flags |= FLAG_LEFT;
+ width = -width;
+ }
+ }
+ else
+ {
+ const FCHAR_T *digitp = dp->width_start;
+
+ do
+ width = xsum (xtimes (width, 10), *digitp++ - '0');
+ while (digitp != dp->width_end);
+ }
+ }
+
+ has_precision = 0;
+ precision = 0;
+ if (dp->precision_start != dp->precision_end)
+ {
+ if (dp->precision_arg_index != ARG_NONE)
+ {
+ int arg;
+
+ if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
+ abort ();
+ arg = a.arg[dp->precision_arg_index].a.a_int;
+ /* "A negative precision is taken as if the precision
+ were omitted." */
+ if (arg >= 0)
+ {
+ precision = arg;
+ has_precision = 1;
+ }
+ }
+ else
+ {
+ const FCHAR_T *digitp = dp->precision_start + 1;
+
+ precision = 0;
+ while (digitp != dp->precision_end)
+ precision = xsum (xtimes (precision, 10), *digitp++ - '0');
+ has_precision = 1;
+ }
+ }
+
+ /* POSIX specifies the default precision to be 6 for %f, %F,
+ %e, %E, but not for %g, %G. Implementations appear to use
+ the same default precision also for %g, %G. But for %a, %A,
+ the default precision is 0. */
+ if (!has_precision)
+ if (!(dp->conversion == 'a' || dp->conversion == 'A'))
+ precision = 6;
+
+ /* Allocate a temporary buffer of sufficient size. */
+# if NEED_PRINTF_DOUBLE && NEED_PRINTF_LONG_DOUBLE
+ tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : DBL_DIG + 1);
+# elif NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
+ tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
+# elif NEED_PRINTF_LONG_DOUBLE
+ tmp_length = LDBL_DIG + 1;
+# elif NEED_PRINTF_DOUBLE
+ tmp_length = DBL_DIG + 1;
+# else
+ tmp_length = 0;
+# endif
+ if (tmp_length < precision)
+ tmp_length = precision;
+# if NEED_PRINTF_LONG_DOUBLE
+# if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
+ if (type == TYPE_LONGDOUBLE)
+# endif
+ if (dp->conversion == 'f' || dp->conversion == 'F')
+ {
+ long double arg = a.arg[dp->arg_index].a.a_longdouble;
+ if (!(isnanl (arg) || arg + arg == arg))
+ {
+ /* arg is finite and nonzero. */
+ int exponent = floorlog10l (arg < 0 ? -arg : arg);
+ if (exponent >= 0 && tmp_length < exponent + precision)
+ tmp_length = exponent + precision;
+ }
+ }
+# endif
+# if NEED_PRINTF_DOUBLE
+# if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
+ if (type == TYPE_DOUBLE)
+# endif
+ if (dp->conversion == 'f' || dp->conversion == 'F')
+ {
+ double arg = a.arg[dp->arg_index].a.a_double;
+ if (!(isnand (arg) || arg + arg == arg))
+ {
+ /* arg is finite and nonzero. */
+ int exponent = floorlog10 (arg < 0 ? -arg : arg);
+ if (exponent >= 0 && tmp_length < exponent + precision)
+ tmp_length = exponent + precision;
+ }
+ }
+# endif
+ /* Account for sign, decimal point etc. */
+ tmp_length = xsum (tmp_length, 12);
+
+ if (tmp_length < width)
+ tmp_length = width;
+
+ tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
+
+ if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
+ tmp = tmpbuf;
+ else
+ {
+ size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
+
+ if (size_overflow_p (tmp_memsize))
+ /* Overflow, would lead to out of memory. */
+ goto out_of_memory;
+ tmp = (DCHAR_T *) malloc (tmp_memsize);
+ if (tmp == NULL)
+ /* Out of memory. */
+ goto out_of_memory;
+ }
+
+ pad_ptr = NULL;
+ p = tmp;
+
+# if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
+# if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
+ if (type == TYPE_LONGDOUBLE)
+# endif
+ {
+ long double arg = a.arg[dp->arg_index].a.a_longdouble;
+
+ if (isnanl (arg))
+ {
+ if (dp->conversion >= 'A' && dp->conversion <= 'Z')
+ {
+ *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
+ }
+ else
+ {
+ *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
+ }
+ }
+ else
+ {
+ int sign = 0;
+ DECL_LONG_DOUBLE_ROUNDING
+
+ BEGIN_LONG_DOUBLE_ROUNDING ();
+
+ if (signbit (arg)) /* arg < 0.0L or negative zero */
+ {
+ sign = -1;
+ arg = -arg;
+ }
+
+ if (sign < 0)
+ *p++ = '-';
+ else if (flags & FLAG_SHOWSIGN)
+ *p++ = '+';
+ else if (flags & FLAG_SPACE)
+ *p++ = ' ';
+
+ if (arg > 0.0L && arg + arg == arg)
+ {
+ if (dp->conversion >= 'A' && dp->conversion <= 'Z')
+ {
+ *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
+ }
+ else
+ {
+ *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
+ }
+ }
+ else
+ {
+# if NEED_PRINTF_LONG_DOUBLE
+ pad_ptr = p;
+
+ if (dp->conversion == 'f' || dp->conversion == 'F')
+ {
+ char *digits;
+ size_t ndigits;
+
+ digits =
+ scale10_round_decimal_long_double (arg, precision);
+ if (digits == NULL)
+ {
+ END_LONG_DOUBLE_ROUNDING ();
+ goto out_of_memory;
+ }
+ ndigits = strlen (digits);
+
+ if (ndigits > precision)
+ do
+ {
+ --ndigits;
+ *p++ = digits[ndigits];
+ }
+ while (ndigits > precision);
+ else
+ *p++ = '0';
+ /* Here ndigits <= precision. */
+ if ((flags & FLAG_ALT) || precision > 0)
+ {
+ *p++ = decimal_point_char ();
+ for (; precision > ndigits; precision--)
+ *p++ = '0';
+ while (ndigits > 0)
+ {
+ --ndigits;
+ *p++ = digits[ndigits];
+ }
+ }
+
+ free (digits);
+ }
+ else if (dp->conversion == 'e' || dp->conversion == 'E')
+ {
+ int exponent;
+
+ if (arg == 0.0L)
+ {
+ exponent = 0;
+ *p++ = '0';
+ if ((flags & FLAG_ALT) || precision > 0)
+ {
+ *p++ = decimal_point_char ();
+ for (; precision > 0; precision--)
+ *p++ = '0';
+ }
+ }
+ else
+ {
+ /* arg > 0.0L. */
+ int adjusted;
+ char *digits;
+ size_t ndigits;
+
+ exponent = floorlog10l (arg);
+ adjusted = 0;
+ for (;;)
+ {
+ digits =
+ scale10_round_decimal_long_double (arg,
+ (int)precision - exponent);
+ if (digits == NULL)
+ {
+ END_LONG_DOUBLE_ROUNDING ();
+ goto out_of_memory;
+ }
+ ndigits = strlen (digits);
+
+ if (ndigits == precision + 1)
+ break;
+ if (ndigits < precision
+ || ndigits > precision + 2)
+ /* The exponent was not guessed
+ precisely enough. */
+ abort ();
+ if (adjusted)
+ /* None of two values of exponent is
+ the right one. Prevent an endless
+ loop. */
+ abort ();
+ free (digits);
+ if (ndigits == precision)
+ exponent -= 1;
+ else
+ exponent += 1;
+ adjusted = 1;
+ }
+ /* Here ndigits = precision+1. */
+ if (is_borderline (digits, precision))
+ {
+ /* Maybe the exponent guess was too high
+ and a smaller exponent can be reached
+ by turning a 10...0 into 9...9x. */
+ char *digits2 =
+ scale10_round_decimal_long_double (arg,
+ (int)precision - exponent + 1);
+ if (digits2 == NULL)
+ {
+ free (digits);
+ END_LONG_DOUBLE_ROUNDING ();
+ goto out_of_memory;
+ }
+ if (strlen (digits2) == precision + 1)
+ {
+ free (digits);
+ digits = digits2;
+ exponent -= 1;
+ }
+ else
+ free (digits2);
+ }
+ /* Here ndigits = precision+1. */
+
+ *p++ = digits[--ndigits];
+ if ((flags & FLAG_ALT) || precision > 0)
+ {
+ *p++ = decimal_point_char ();
+ while (ndigits > 0)
+ {
+ --ndigits;
+ *p++ = digits[ndigits];
+ }
+ }
+
+ free (digits);
+ }
+
+ *p++ = dp->conversion; /* 'e' or 'E' */
+# if WIDE_CHAR_VERSION
+ {
+ static const wchar_t decimal_format[] =
+ { '%', '+', '.', '2', 'd', '\0' };
+ SNPRINTF (p, 6 + 1, decimal_format, exponent);
+ }
+ while (*p != '\0')
+ p++;
+# else
+ if (sizeof (DCHAR_T) == 1)
+ {
+ sprintf ((char *) p, "%+.2d", exponent);
+ while (*p != '\0')
+ p++;
+ }
+ else
+ {
+ char expbuf[6 + 1];
+ const char *ep;
+ sprintf (expbuf, "%+.2d", exponent);
+ for (ep = expbuf; (*p = *ep) != '\0'; ep++)
+ p++;
+ }
+# endif
+ }
+ else if (dp->conversion == 'g' || dp->conversion == 'G')
+ {
+ if (precision == 0)
+ precision = 1;
+ /* precision >= 1. */
+
+ if (arg == 0.0L)
+ /* The exponent is 0, >= -4, < precision.
+ Use fixed-point notation. */
+ {
+ size_t ndigits = precision;
+ /* Number of trailing zeroes that have to be
+ dropped. */
+ size_t nzeroes =
+ (flags & FLAG_ALT ? 0 : precision - 1);
+
+ --ndigits;
+ *p++ = '0';
+ if ((flags & FLAG_ALT) || ndigits > nzeroes)
+ {
+ *p++ = decimal_point_char ();
+ while (ndigits > nzeroes)
+ {
+ --ndigits;
+ *p++ = '0';
+ }
+ }
+ }
+ else
+ {
+ /* arg > 0.0L. */
+ int exponent;
+ int adjusted;
+ char *digits;
+ size_t ndigits;
+ size_t nzeroes;
+
+ exponent = floorlog10l (arg);
+ adjusted = 0;
+ for (;;)
+ {
+ digits =
+ scale10_round_decimal_long_double (arg,
+ (int)(precision - 1) - exponent);
+ if (digits == NULL)
+ {
+ END_LONG_DOUBLE_ROUNDING ();
+ goto out_of_memory;
+ }
+ ndigits = strlen (digits);
+
+ if (ndigits == precision)
+ break;
+ if (ndigits < precision - 1
+ || ndigits > precision + 1)
+ /* The exponent was not guessed
+ precisely enough. */
+ abort ();
+ if (adjusted)
+ /* None of two values of exponent is
+ the right one. Prevent an endless
+ loop. */
+ abort ();
+ free (digits);
+ if (ndigits < precision)
+ exponent -= 1;
+ else
+ exponent += 1;
+ adjusted = 1;
+ }
+ /* Here ndigits = precision. */
+ if (is_borderline (digits, precision - 1))
+ {
+ /* Maybe the exponent guess was too high
+ and a smaller exponent can be reached
+ by turning a 10...0 into 9...9x. */
+ char *digits2 =
+ scale10_round_decimal_long_double (arg,
+ (int)(precision - 1) - exponent + 1);
+ if (digits2 == NULL)
+ {
+ free (digits);
+ END_LONG_DOUBLE_ROUNDING ();
+ goto out_of_memory;
+ }
+ if (strlen (digits2) == precision)
+ {
+ free (digits);
+ digits = digits2;
+ exponent -= 1;
+ }
+ else
+ free (digits2);
+ }
+ /* Here ndigits = precision. */
+
+ /* Determine the number of trailing zeroes
+ that have to be dropped. */
+ nzeroes = 0;
+ if ((flags & FLAG_ALT) == 0)
+ while (nzeroes < ndigits
+ && digits[nzeroes] == '0')
+ nzeroes++;
+
+ /* The exponent is now determined. */
+ if (exponent >= -4
+ && exponent < (long)precision)
+ {
+ /* Fixed-point notation:
+ max(exponent,0)+1 digits, then the
+ decimal point, then the remaining
+ digits without trailing zeroes. */
+ if (exponent >= 0)
+ {
+ size_t ecount = exponent + 1;
+ /* Note: count <= precision = ndigits. */
+ for (; ecount > 0; ecount--)
+ *p++ = digits[--ndigits];
+ if ((flags & FLAG_ALT) || ndigits > nzeroes)
+ {
+ *p++ = decimal_point_char ();
+ while (ndigits > nzeroes)
+ {
+ --ndigits;
+ *p++ = digits[ndigits];
+ }
+ }
+ }
+ else
+ {
+ size_t ecount = -exponent - 1;
+ *p++ = '0';
+ *p++ = decimal_point_char ();
+ for (; ecount > 0; ecount--)
+ *p++ = '0';
+ while (ndigits > nzeroes)
+ {
+ --ndigits;
+ *p++ = digits[ndigits];
+ }
+ }
+ }
+ else
+ {
+ /* Exponential notation. */
+ *p++ = digits[--ndigits];
+ if ((flags & FLAG_ALT) || ndigits > nzeroes)
+ {
+ *p++ = decimal_point_char ();
+ while (ndigits > nzeroes)
+ {
+ --ndigits;
+ *p++ = digits[ndigits];
+ }
+ }
+ *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
+# if WIDE_CHAR_VERSION
+ {
+ static const wchar_t decimal_format[] =
+ { '%', '+', '.', '2', 'd', '\0' };
+ SNPRINTF (p, 6 + 1, decimal_format, exponent);
+ }
+ while (*p != '\0')
+ p++;
+# else
+ if (sizeof (DCHAR_T) == 1)
+ {
+ sprintf ((char *) p, "%+.2d", exponent);
+ while (*p != '\0')
+ p++;
+ }
+ else
+ {
+ char expbuf[6 + 1];
+ const char *ep;
+ sprintf (expbuf, "%+.2d", exponent);
+ for (ep = expbuf; (*p = *ep) != '\0'; ep++)
+ p++;
+ }
+# endif
+ }
+
+ free (digits);
+ }
+ }
+ else
+ abort ();
+# else
+ /* arg is finite. */
+ if (!(arg == 0.0L))
+ abort ();
+
+ pad_ptr = p;
+
+ if (dp->conversion == 'f' || dp->conversion == 'F')
+ {
+ *p++ = '0';
+ if ((flags & FLAG_ALT) || precision > 0)
+ {
+ *p++ = decimal_point_char ();
+ for (; precision > 0; precision--)
+ *p++ = '0';
+ }
+ }
+ else if (dp->conversion == 'e' || dp->conversion == 'E')
+ {
+ *p++ = '0';
+ if ((flags & FLAG_ALT) || precision > 0)
+ {
+ *p++ = decimal_point_char ();
+ for (; precision > 0; precision--)
+ *p++ = '0';
+ }
+ *p++ = dp->conversion; /* 'e' or 'E' */
+ *p++ = '+';
+ *p++ = '0';
+ *p++ = '0';
+ }
+ else if (dp->conversion == 'g' || dp->conversion == 'G')
+ {
+ *p++ = '0';
+ if (flags & FLAG_ALT)
+ {
+ size_t ndigits =
+ (precision > 0 ? precision - 1 : 0);
+ *p++ = decimal_point_char ();
+ for (; ndigits > 0; --ndigits)
+ *p++ = '0';
+ }
+ }
+ else if (dp->conversion == 'a' || dp->conversion == 'A')
+ {
+ *p++ = '0';
+ *p++ = dp->conversion - 'A' + 'X';
+ pad_ptr = p;
+ *p++ = '0';
+ if ((flags & FLAG_ALT) || precision > 0)
+ {
+ *p++ = decimal_point_char ();
+ for (; precision > 0; precision--)
+ *p++ = '0';
+ }
+ *p++ = dp->conversion - 'A' + 'P';
+ *p++ = '+';
+ *p++ = '0';
+ }
+ else
+ abort ();
+# endif
+ }
+
+ END_LONG_DOUBLE_ROUNDING ();
+ }
+ }
+# if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
+ else
+# endif
+# endif
+# if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
+ {
+ double arg = a.arg[dp->arg_index].a.a_double;
+
+ if (isnand (arg))
+ {
+ if (dp->conversion >= 'A' && dp->conversion <= 'Z')
+ {
+ *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
+ }
+ else
+ {
+ *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
+ }
+ }
+ else
+ {
+ int sign = 0;
+
+ if (signbit (arg)) /* arg < 0.0 or negative zero */
+ {
+ sign = -1;
+ arg = -arg;
+ }
+
+ if (sign < 0)
+ *p++ = '-';
+ else if (flags & FLAG_SHOWSIGN)
+ *p++ = '+';
+ else if (flags & FLAG_SPACE)
+ *p++ = ' ';
+
+ if (arg > 0.0 && arg + arg == arg)
+ {
+ if (dp->conversion >= 'A' && dp->conversion <= 'Z')
+ {
+ *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
+ }
+ else
+ {
+ *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
+ }
+ }
+ else
+ {
+# if NEED_PRINTF_DOUBLE
+ pad_ptr = p;
+
+ if (dp->conversion == 'f' || dp->conversion == 'F')
+ {
+ char *digits;
+ size_t ndigits;
+
+ digits =
+ scale10_round_decimal_double (arg, precision);
+ if (digits == NULL)
+ goto out_of_memory;
+ ndigits = strlen (digits);
+
+ if (ndigits > precision)
+ do
+ {
+ --ndigits;
+ *p++ = digits[ndigits];
+ }
+ while (ndigits > precision);
+ else
+ *p++ = '0';
+ /* Here ndigits <= precision. */
+ if ((flags & FLAG_ALT) || precision > 0)
+ {
+ *p++ = decimal_point_char ();
+ for (; precision > ndigits; precision--)
+ *p++ = '0';
+ while (ndigits > 0)
+ {
+ --ndigits;
+ *p++ = digits[ndigits];
+ }
+ }
+
+ free (digits);
+ }
+ else if (dp->conversion == 'e' || dp->conversion == 'E')
+ {
+ int exponent;
+
+ if (arg == 0.0)
+ {
+ exponent = 0;
+ *p++ = '0';
+ if ((flags & FLAG_ALT) || precision > 0)
+ {
+ *p++ = decimal_point_char ();
+ for (; precision > 0; precision--)
+ *p++ = '0';
+ }
+ }
+ else
+ {
+ /* arg > 0.0. */
+ int adjusted;
+ char *digits;
+ size_t ndigits;
+
+ exponent = floorlog10 (arg);
+ adjusted = 0;
+ for (;;)
+ {
+ digits =
+ scale10_round_decimal_double (arg,
+ (int)precision - exponent);
+ if (digits == NULL)
+ goto out_of_memory;
+ ndigits = strlen (digits);
+
+ if (ndigits == precision + 1)
+ break;
+ if (ndigits < precision
+ || ndigits > precision + 2)
+ /* The exponent was not guessed
+ precisely enough. */
+ abort ();
+ if (adjusted)
+ /* None of two values of exponent is
+ the right one. Prevent an endless
+ loop. */
+ abort ();
+ free (digits);
+ if (ndigits == precision)
+ exponent -= 1;
+ else
+ exponent += 1;
+ adjusted = 1;
+ }
+ /* Here ndigits = precision+1. */
+ if (is_borderline (digits, precision))
+ {
+ /* Maybe the exponent guess was too high
+ and a smaller exponent can be reached
+ by turning a 10...0 into 9...9x. */
+ char *digits2 =
+ scale10_round_decimal_double (arg,
+ (int)precision - exponent + 1);
+ if (digits2 == NULL)
+ {
+ free (digits);
+ goto out_of_memory;
+ }
+ if (strlen (digits2) == precision + 1)
+ {
+ free (digits);
+ digits = digits2;
+ exponent -= 1;
+ }
+ else
+ free (digits2);
+ }
+ /* Here ndigits = precision+1. */
+
+ *p++ = digits[--ndigits];
+ if ((flags & FLAG_ALT) || precision > 0)
+ {
+ *p++ = decimal_point_char ();
+ while (ndigits > 0)
+ {
+ --ndigits;
+ *p++ = digits[ndigits];
+ }
+ }
+
+ free (digits);
+ }
+
+ *p++ = dp->conversion; /* 'e' or 'E' */
+# if WIDE_CHAR_VERSION
+ {
+ static const wchar_t decimal_format[] =
+ /* Produce the same number of exponent digits
+ as the native printf implementation. */
+# if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+ { '%', '+', '.', '3', 'd', '\0' };
+# else
+ { '%', '+', '.', '2', 'd', '\0' };
+# endif
+ SNPRINTF (p, 6 + 1, decimal_format, exponent);
+ }
+ while (*p != '\0')
+ p++;
+# else
+ {
+ static const char decimal_format[] =
+ /* Produce the same number of exponent digits
+ as the native printf implementation. */
+# if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+ "%+.3d";
+# else
+ "%+.2d";
+# endif
+ if (sizeof (DCHAR_T) == 1)
+ {
+ sprintf ((char *) p, decimal_format, exponent);
+ while (*p != '\0')
+ p++;
+ }
+ else
+ {
+ char expbuf[6 + 1];
+ const char *ep;
+ sprintf (expbuf, decimal_format, exponent);
+ for (ep = expbuf; (*p = *ep) != '\0'; ep++)
+ p++;
+ }
+ }
+# endif
+ }
+ else if (dp->conversion == 'g' || dp->conversion == 'G')
+ {
+ if (precision == 0)
+ precision = 1;
+ /* precision >= 1. */
+
+ if (arg == 0.0)
+ /* The exponent is 0, >= -4, < precision.
+ Use fixed-point notation. */
+ {
+ size_t ndigits = precision;
+ /* Number of trailing zeroes that have to be
+ dropped. */
+ size_t nzeroes =
+ (flags & FLAG_ALT ? 0 : precision - 1);
+
+ --ndigits;
+ *p++ = '0';
+ if ((flags & FLAG_ALT) || ndigits > nzeroes)
+ {
+ *p++ = decimal_point_char ();
+ while (ndigits > nzeroes)
+ {
+ --ndigits;
+ *p++ = '0';
+ }
+ }
+ }
+ else
+ {
+ /* arg > 0.0. */
+ int exponent;
+ int adjusted;
+ char *digits;
+ size_t ndigits;
+ size_t nzeroes;
+
+ exponent = floorlog10 (arg);
+ adjusted = 0;
+ for (;;)
+ {
+ digits =
+ scale10_round_decimal_double (arg,
+ (int)(precision - 1) - exponent);
+ if (digits == NULL)
+ goto out_of_memory;
+ ndigits = strlen (digits);
+
+ if (ndigits == precision)
+ break;
+ if (ndigits < precision - 1
+ || ndigits > precision + 1)
+ /* The exponent was not guessed
+ precisely enough. */
+ abort ();
+ if (adjusted)
+ /* None of two values of exponent is
+ the right one. Prevent an endless
+ loop. */
+ abort ();
+ free (digits);
+ if (ndigits < precision)
+ exponent -= 1;
+ else
+ exponent += 1;
+ adjusted = 1;
+ }
+ /* Here ndigits = precision. */
+ if (is_borderline (digits, precision - 1))
+ {
+ /* Maybe the exponent guess was too high
+ and a smaller exponent can be reached
+ by turning a 10...0 into 9...9x. */
+ char *digits2 =
+ scale10_round_decimal_double (arg,
+ (int)(precision - 1) - exponent + 1);
+ if (digits2 == NULL)
+ {
+ free (digits);
+ goto out_of_memory;
+ }
+ if (strlen (digits2) == precision)
+ {
+ free (digits);
+ digits = digits2;
+ exponent -= 1;
+ }
+ else
+ free (digits2);
+ }
+ /* Here ndigits = precision. */
+
+ /* Determine the number of trailing zeroes
+ that have to be dropped. */
+ nzeroes = 0;
+ if ((flags & FLAG_ALT) == 0)
+ while (nzeroes < ndigits
+ && digits[nzeroes] == '0')
+ nzeroes++;
+
+ /* The exponent is now determined. */
+ if (exponent >= -4
+ && exponent < (long)precision)
+ {
+ /* Fixed-point notation:
+ max(exponent,0)+1 digits, then the
+ decimal point, then the remaining
+ digits without trailing zeroes. */
+ if (exponent >= 0)
+ {
+ size_t ecount = exponent + 1;
+ /* Note: ecount <= precision = ndigits. */
+ for (; ecount > 0; ecount--)
+ *p++ = digits[--ndigits];
+ if ((flags & FLAG_ALT) || ndigits > nzeroes)
+ {
+ *p++ = decimal_point_char ();
+ while (ndigits > nzeroes)
+ {
+ --ndigits;
+ *p++ = digits[ndigits];
+ }
+ }
+ }
+ else
+ {
+ size_t ecount = -exponent - 1;
+ *p++ = '0';
+ *p++ = decimal_point_char ();
+ for (; ecount > 0; ecount--)
+ *p++ = '0';
+ while (ndigits > nzeroes)
+ {
+ --ndigits;
+ *p++ = digits[ndigits];
+ }
+ }
+ }
+ else
+ {
+ /* Exponential notation. */
+ *p++ = digits[--ndigits];
+ if ((flags & FLAG_ALT) || ndigits > nzeroes)
+ {
+ *p++ = decimal_point_char ();
+ while (ndigits > nzeroes)
+ {
+ --ndigits;
+ *p++ = digits[ndigits];
+ }
+ }
+ *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
+# if WIDE_CHAR_VERSION
+ {
+ static const wchar_t decimal_format[] =
+ /* Produce the same number of exponent digits
+ as the native printf implementation. */
+# if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+ { '%', '+', '.', '3', 'd', '\0' };
+# else
+ { '%', '+', '.', '2', 'd', '\0' };
+# endif
+ SNPRINTF (p, 6 + 1, decimal_format, exponent);
+ }
+ while (*p != '\0')
+ p++;
+# else
+ {
+ static const char decimal_format[] =
+ /* Produce the same number of exponent digits
+ as the native printf implementation. */
+# if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+ "%+.3d";
+# else
+ "%+.2d";
+# endif
+ if (sizeof (DCHAR_T) == 1)
+ {
+ sprintf ((char *) p, decimal_format, exponent);
+ while (*p != '\0')
+ p++;
+ }
+ else
+ {
+ char expbuf[6 + 1];
+ const char *ep;
+ sprintf (expbuf, decimal_format, exponent);
+ for (ep = expbuf; (*p = *ep) != '\0'; ep++)
+ p++;
+ }
+ }
+# endif
+ }
+
+ free (digits);
+ }
+ }
+ else
+ abort ();
+# else
+ /* arg is finite. */
+ if (!(arg == 0.0))
+ abort ();
+
+ pad_ptr = p;
+
+ if (dp->conversion == 'f' || dp->conversion == 'F')
+ {
+ *p++ = '0';
+ if ((flags & FLAG_ALT) || precision > 0)
+ {
+ *p++ = decimal_point_char ();
+ for (; precision > 0; precision--)
+ *p++ = '0';
+ }
+ }
+ else if (dp->conversion == 'e' || dp->conversion == 'E')
+ {
+ *p++ = '0';
+ if ((flags & FLAG_ALT) || precision > 0)
+ {
+ *p++ = decimal_point_char ();
+ for (; precision > 0; precision--)
+ *p++ = '0';
+ }
+ *p++ = dp->conversion; /* 'e' or 'E' */
+ *p++ = '+';
+ /* Produce the same number of exponent digits as
+ the native printf implementation. */
+# if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+ *p++ = '0';
+# endif
+ *p++ = '0';
+ *p++ = '0';
+ }
+ else if (dp->conversion == 'g' || dp->conversion == 'G')
+ {
+ *p++ = '0';
+ if (flags & FLAG_ALT)
+ {
+ size_t ndigits =
+ (precision > 0 ? precision - 1 : 0);
+ *p++ = decimal_point_char ();
+ for (; ndigits > 0; --ndigits)
+ *p++ = '0';
+ }
+ }
+ else
+ abort ();
+# endif
+ }
+ }
+ }
+# endif
+
+ /* The generated string now extends from tmp to p, with the
+ zero padding insertion point being at pad_ptr. */
+ count = p - tmp;
+
+ if (count < width)
+ {
+ size_t pad = width - count;
+ DCHAR_T *end = p + pad;
+
+ if (flags & FLAG_LEFT)
+ {
+ /* Pad with spaces on the right. */
+ for (; pad > 0; pad--)
+ *p++ = ' ';
+ }
+ else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
+ {
+ /* Pad with zeroes. */
+ DCHAR_T *q = end;
+
+ while (p > pad_ptr)
+ *--q = *--p;
+ for (; pad > 0; pad--)
+ *p++ = '0';
+ }
+ else
+ {
+ /* Pad with spaces on the left. */
+ DCHAR_T *q = end;
+
+ while (p > tmp)
+ *--q = *--p;
+ for (; pad > 0; pad--)
+ *p++ = ' ';
+ }
+
+ p = end;
+ }
+
+ count = p - tmp;
+
+ if (count >= tmp_length)
+ /* tmp_length was incorrectly calculated - fix the
+ code above! */
+ abort ();
+
+ /* Make room for the result. */
+ if (count >= allocated - length)
+ {
+ size_t n = xsum (length, count);
+
+ ENSURE_ALLOCATION (n);
+ }
+
+ /* Append the result. */
+ memcpy (result + length, tmp, count * sizeof (DCHAR_T));
+ if (tmp != tmpbuf)
+ free (tmp);
+ length += count;
+ }
+#endif
+ else
+ {
+ arg_type type = a.arg[dp->arg_index].type;
+ int flags = dp->flags;
+#if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
+ int has_width;
+#endif
+#if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
+ size_t width;
+#endif
+#if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || NEED_PRINTF_UNBOUNDED_PRECISION
+ int has_precision;
+ size_t precision;
+#endif
+#if NEED_PRINTF_UNBOUNDED_PRECISION
+ int prec_ourselves;
+#else
+# define prec_ourselves 0
+#endif
+#if NEED_PRINTF_FLAG_LEFTADJUST
+# define pad_ourselves 1
+#elif !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
+ int pad_ourselves;
+#else
+# define pad_ourselves 0
+#endif
+ TCHAR_T *fbp;
+ unsigned int prefix_count;
+ int prefixes[2] IF_LINT (= { 0 });
+ int orig_errno;
#if !USE_SNPRINTF
- size_t tmp_length;
- CHAR_T tmpbuf[700];
- CHAR_T *tmp;
-
- /* Allocate a temporary buffer of sufficient size for calling
- sprintf. */
- {
- size_t width;
- size_t precision;
-
- width = 0;
- if (dp->width_start != dp->width_end)
- {
- if (dp->width_arg_index != ARG_NONE)
- {
- int arg;
-
- if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
- abort ();
- arg = a.arg[dp->width_arg_index].a.a_int;
- width = (arg < 0 ? (unsigned int) (-arg) : arg);
- }
- else
- {
- const CHAR_T *digitp = dp->width_start;
-
- do
- {
- size_t w_tmp = width * 10 + (*digitp++ - '0');
- if (SIZE_MAX / 10 < width || w_tmp < width)
- goto out_of_memory;
- width = w_tmp;
- }
- while (digitp != dp->width_end);
- }
- }
-
- precision = 6;
- if (dp->precision_start != dp->precision_end)
- {
- if (dp->precision_arg_index != ARG_NONE)
- {
- int arg;
-
- if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
- abort ();
- arg = a.arg[dp->precision_arg_index].a.a_int;
- precision = (arg < 0 ? 0 : arg);
- }
- else
- {
- const CHAR_T *digitp = dp->precision_start + 1;
-
- precision = 0;
- while (digitp != dp->precision_end)
- {
- size_t p1 = 10 * precision + (*digitp++ - '0');
- precision = ((SIZE_MAX / 10 < precision
- || p1 < precision)
- ? SIZE_MAX : p1);
- }
- }
- }
-
- switch (dp->conversion)
- {
-
- case 'd': case 'i': case 'u':
-# if HAVE_LONG_LONG_INT
- if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
- tmp_length =
- (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
- * 0.30103 /* binary -> decimal */
- )
- + 1; /* turn floor into ceil */
- else
-# endif
- if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
- tmp_length =
- (unsigned int) (sizeof (unsigned long) * CHAR_BIT
- * 0.30103 /* binary -> decimal */
- )
- + 1; /* turn floor into ceil */
- else
- tmp_length =
- (unsigned int) (sizeof (unsigned int) * CHAR_BIT
- * 0.30103 /* binary -> decimal */
- )
- + 1; /* turn floor into ceil */
- if (tmp_length < precision)
- tmp_length = precision;
- /* Multiply by 2, as an estimate for FLAG_GROUP. */
- /* Add 1, to account for a leading sign. */
- tmp_length = (tmp_length < SIZE_MAX / 2
- ? 2 * tmp_length + 1
- : SIZE_MAX);
- break;
-
- case 'o':
-# if HAVE_LONG_LONG_INT
- if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
- tmp_length =
- (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
- * 0.333334 /* binary -> octal */
- )
- + 1; /* turn floor into ceil */
- else
-# endif
- if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
- tmp_length =
- (unsigned int) (sizeof (unsigned long) * CHAR_BIT
- * 0.333334 /* binary -> octal */
- )
- + 1; /* turn floor into ceil */
- else
- tmp_length =
- (unsigned int) (sizeof (unsigned int) * CHAR_BIT
- * 0.333334 /* binary -> octal */
- )
- + 1; /* turn floor into ceil */
- if (tmp_length < precision)
- tmp_length = precision;
- /* Add 1, to account for a leading sign. */
- tmp_length += (tmp_length < SIZE_MAX);
- break;
-
- case 'x': case 'X':
-# if HAVE_LONG_LONG_INT
- if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
- tmp_length =
- (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
- * 0.25 /* binary -> hexadecimal */
- )
- + 1; /* turn floor into ceil */
- else
-# endif
- if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
- tmp_length =
- (unsigned int) (sizeof (unsigned long) * CHAR_BIT
- * 0.25 /* binary -> hexadecimal */
- )
- + 1; /* turn floor into ceil */
- else
- tmp_length =
- (unsigned int) (sizeof (unsigned int) * CHAR_BIT
- * 0.25 /* binary -> hexadecimal */
- )
- + 1; /* turn floor into ceil */
- if (tmp_length < precision)
- tmp_length = precision;
- /* Add 2, to account for a leading sign or alternate form. */
- tmp_length += 2;
- if (tmp_length < 2)
- goto out_of_memory;
- break;
-
- case 'f': case 'F':
-# if HAVE_LONG_DOUBLE
- if (type == TYPE_LONGDOUBLE)
- tmp_length =
- (unsigned int) (LDBL_MAX_EXP
- * 0.30103 /* binary -> decimal */
- * 2 /* estimate for FLAG_GROUP */
- )
- + 1 /* turn floor into ceil */
- + 10; /* sign, decimal point etc. */
- else
-# endif
- tmp_length =
- (unsigned int) (DBL_MAX_EXP
- * 0.30103 /* binary -> decimal */
- * 2 /* estimate for FLAG_GROUP */
- )
- + 1 /* turn floor into ceil */
- + 10; /* sign, decimal point etc. */
- tmp_length += precision;
- if (tmp_length < precision)
- goto out_of_memory;
- break;
-
- case 'e': case 'E': case 'g': case 'G':
- tmp_length =
- 12; /* sign, decimal point, exponent etc. */
- tmp_length += precision;
- if (tmp_length < precision)
- goto out_of_memory;
- break;
-
- case 'a': case 'A':
-# if HAVE_LONG_DOUBLE
- if (type == TYPE_LONGDOUBLE)
- tmp_length =
- (unsigned int) (LDBL_DIG
- * 0.831 /* decimal -> hexadecimal */
- )
- + 1; /* turn floor into ceil */
- else
-# endif
- tmp_length =
- (unsigned int) (DBL_DIG
- * 0.831 /* decimal -> hexadecimal */
- )
- + 1; /* turn floor into ceil */
- if (tmp_length < precision)
- tmp_length = precision;
- /* Account for sign, decimal point etc. */
- tmp_length += 12;
- if (tmp_length < 12)
- goto out_of_memory;
- break;
-
- case 'c':
-# if HAVE_WINT_T && !WIDE_CHAR_VERSION
- if (type == TYPE_WIDE_CHAR)
- tmp_length = MB_CUR_MAX;
- else
+ size_t tmp_length;
+ TCHAR_T tmpbuf[700];
+ TCHAR_T *tmp;
+#endif
+
+#if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
+ has_width = 0;
+#endif
+#if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
+ width = 0;
+ if (dp->width_start != dp->width_end)
+ {
+ if (dp->width_arg_index != ARG_NONE)
+ {
+ int arg;
+
+ if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
+ abort ();
+ arg = a.arg[dp->width_arg_index].a.a_int;
+ width = arg;
+ if (arg < 0)
+ {
+ /* "A negative field width is taken as a '-' flag
+ followed by a positive field width." */
+ flags |= FLAG_LEFT;
+ width = -width;
+ }
+ }
+ else
+ {
+ const FCHAR_T *digitp = dp->width_start;
+
+ do
+ width = xsum (xtimes (width, 10), *digitp++ - '0');
+ while (digitp != dp->width_end);
+ }
+#if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
+ has_width = 1;
+#endif
+ }
+#endif
+
+#if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || NEED_PRINTF_UNBOUNDED_PRECISION
+ has_precision = 0;
+ precision = 6;
+ if (dp->precision_start != dp->precision_end)
+ {
+ if (dp->precision_arg_index != ARG_NONE)
+ {
+ int arg;
+
+ if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
+ abort ();
+ arg = a.arg[dp->precision_arg_index].a.a_int;
+ /* "A negative precision is taken as if the precision
+ were omitted." */
+ if (arg >= 0)
+ {
+ precision = arg;
+ has_precision = 1;
+ }
+ }
+ else
+ {
+ const FCHAR_T *digitp = dp->precision_start + 1;
+
+ precision = 0;
+ while (digitp != dp->precision_end)
+ precision = xsum (xtimes (precision, 10), *digitp++ - '0');
+ has_precision = 1;
+ }
+ }
+#endif
+
+ /* Decide whether to handle the precision ourselves. */
+#if NEED_PRINTF_UNBOUNDED_PRECISION
+ switch (dp->conversion)
+ {
+ case 'd': case 'i': case 'u':
+ case 'o':
+ case 'x': case 'X': case 'p':
+ prec_ourselves = has_precision && (precision > 0);
+ break;
+ default:
+ prec_ourselves = 0;
+ break;
+ }
+#endif
+
+ /* Decide whether to perform the padding ourselves. */
+#if !NEED_PRINTF_FLAG_LEFTADJUST && (!DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION)
+ switch (dp->conversion)
+ {
+# if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
+ /* If we need conversion from TCHAR_T[] to DCHAR_T[], we need
+ to perform the padding after this conversion. Functions
+ with unistdio extensions perform the padding based on
+ character count rather than element count. */
+ case 'c': case 's':
+# endif
+# if NEED_PRINTF_FLAG_ZERO
+ case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
+ case 'a': case 'A':
# endif
- tmp_length = 1;
- break;
+ pad_ourselves = 1;
+ break;
+ default:
+ pad_ourselves = prec_ourselves;
+ break;
+ }
+#endif
- case 's':
-# if HAVE_WCHAR_T
- if (type == TYPE_WIDE_STRING)
- {
- tmp_length =
- local_wcslen (a.arg[dp->arg_index].a.a_wide_string);
-
-# if !WIDE_CHAR_VERSION
- if (SIZE_MAX / MB_CUR_MAX < tmp_length)
- goto out_of_memory;
- tmp_length *= MB_CUR_MAX;
-# endif
- }
- else
-# endif
- tmp_length = strlen (a.arg[dp->arg_index].a.a_string);
- break;
-
- case 'p':
- tmp_length =
- (unsigned int) (sizeof (void *) * CHAR_BIT
- * 0.25 /* binary -> hexadecimal */
- )
- + 1 /* turn floor into ceil */
- + 2; /* account for leading 0x */
- break;
-
- default:
- abort ();
- }
-
- if (tmp_length < width)
- tmp_length = width;
-
- tmp_length++; /* account for trailing NUL */
- if (!tmp_length)
- goto out_of_memory;
- }
-
- if (tmp_length <= sizeof (tmpbuf) / sizeof (CHAR_T))
- tmp = tmpbuf;
- else
- {
- if (SIZE_MAX / sizeof (CHAR_T) < tmp_length)
- /* Overflow, would lead to out of memory. */
- goto out_of_memory;
- tmp = (CHAR_T *) malloc (tmp_length * sizeof (CHAR_T));
- if (tmp == NULL)
- /* Out of memory. */
- goto out_of_memory;
- }
-#endif
-
- /* Construct the format string for calling snprintf or
- sprintf. */
- p = buf;
- *p++ = '%';
- if (dp->flags & FLAG_GROUP)
- *p++ = '\'';
- if (dp->flags & FLAG_LEFT)
- *p++ = '-';
- if (dp->flags & FLAG_SHOWSIGN)
- *p++ = '+';
- if (dp->flags & FLAG_SPACE)
- *p++ = ' ';
- if (dp->flags & FLAG_ALT)
- *p++ = '#';
- if (dp->flags & FLAG_ZERO)
- *p++ = '0';
- if (dp->width_start != dp->width_end)
- {
- size_t n = dp->width_end - dp->width_start;
- memcpy (p, dp->width_start, n * sizeof (CHAR_T));
- p += n;
- }
- if (dp->precision_start != dp->precision_end)
- {
- size_t n = dp->precision_end - dp->precision_start;
- memcpy (p, dp->precision_start, n * sizeof (CHAR_T));
- p += n;
- }
-
- switch (type)
- {
+#if !USE_SNPRINTF
+ /* Allocate a temporary buffer of sufficient size for calling
+ sprintf. */
+ tmp_length =
+ MAX_ROOM_NEEDED (&a, dp->arg_index, dp->conversion, type,
+ flags, width, has_precision, precision,
+ pad_ourselves);
+
+ if (tmp_length <= sizeof (tmpbuf) / sizeof (TCHAR_T))
+ tmp = tmpbuf;
+ else
+ {
+ size_t tmp_memsize = xtimes (tmp_length, sizeof (TCHAR_T));
+
+ if (size_overflow_p (tmp_memsize))
+ /* Overflow, would lead to out of memory. */
+ goto out_of_memory;
+ tmp = (TCHAR_T *) malloc (tmp_memsize);
+ if (tmp == NULL)
+ /* Out of memory. */
+ goto out_of_memory;
+ }
+#endif
+
+ /* Construct the format string for calling snprintf or
+ sprintf. */
+ fbp = buf;
+ *fbp++ = '%';
+#if NEED_PRINTF_FLAG_GROUPING
+ /* The underlying implementation doesn't support the ' flag.
+ Produce no grouping characters in this case; this is
+ acceptable because the grouping is locale dependent. */
+#else
+ if (flags & FLAG_GROUP)
+ *fbp++ = '\'';
+#endif
+ if (flags & FLAG_LEFT)
+ *fbp++ = '-';
+ if (flags & FLAG_SHOWSIGN)
+ *fbp++ = '+';
+ if (flags & FLAG_SPACE)
+ *fbp++ = ' ';
+ if (flags & FLAG_ALT)
+ *fbp++ = '#';
+#if __GLIBC__ >= 2 && !defined __UCLIBC__
+ if (flags & FLAG_LOCALIZED)
+ *fbp++ = 'I';
+#endif
+ if (!pad_ourselves)
+ {
+ if (flags & FLAG_ZERO)
+ *fbp++ = '0';
+ if (dp->width_start != dp->width_end)
+ {
+ size_t n = dp->width_end - dp->width_start;
+ /* The width specification is known to consist only
+ of standard ASCII characters. */
+ if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
+ {
+ memcpy (fbp, dp->width_start, n * sizeof (TCHAR_T));
+ fbp += n;
+ }
+ else
+ {
+ const FCHAR_T *mp = dp->width_start;
+ do
+ *fbp++ = *mp++;
+ while (--n > 0);
+ }
+ }
+ }
+ if (!prec_ourselves)
+ {
+ if (dp->precision_start != dp->precision_end)
+ {
+ size_t n = dp->precision_end - dp->precision_start;
+ /* The precision specification is known to consist only
+ of standard ASCII characters. */
+ if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
+ {
+ memcpy (fbp, dp->precision_start, n * sizeof (TCHAR_T));
+ fbp += n;
+ }
+ else
+ {
+ const FCHAR_T *mp = dp->precision_start;
+ do
+ *fbp++ = *mp++;
+ while (--n > 0);
+ }
+ }
+ }
+
+ switch (type)
+ {
#if HAVE_LONG_LONG_INT
- case TYPE_LONGLONGINT:
- case TYPE_ULONGLONGINT:
- *p++ = 'l';
- /*FALLTHROUGH*/
+ case TYPE_LONGLONGINT:
+ case TYPE_ULONGLONGINT:
+# if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+ *fbp++ = 'I';
+ *fbp++ = '6';
+ *fbp++ = '4';
+ break;
+# else
+ *fbp++ = 'l';
+ /*FALLTHROUGH*/
+# endif
#endif
- case TYPE_LONGINT:
- case TYPE_ULONGINT:
+ case TYPE_LONGINT:
+ case TYPE_ULONGINT:
#if HAVE_WINT_T
- case TYPE_WIDE_CHAR:
+ case TYPE_WIDE_CHAR:
#endif
#if HAVE_WCHAR_T
- case TYPE_WIDE_STRING:
-#endif
- *p++ = 'l';
- break;
-#if HAVE_LONG_DOUBLE
- case TYPE_LONGDOUBLE:
- *p++ = 'L';
- break;
-#endif
- default:
- break;
- }
- *p = dp->conversion;
+ case TYPE_WIDE_STRING:
+#endif
+ *fbp++ = 'l';
+ break;
+ case TYPE_LONGDOUBLE:
+ *fbp++ = 'L';
+ break;
+ default:
+ break;
+ }
+#if NEED_PRINTF_DIRECTIVE_F
+ if (dp->conversion == 'F')
+ *fbp = 'f';
+ else
+#endif
+ *fbp = dp->conversion;
#if USE_SNPRINTF
- p[1] = '%';
- p[2] = 'n';
- p[3] = '\0';
+# if !(((__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) && !defined __UCLIBC__) || ((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__))
+ fbp[1] = '%';
+ fbp[2] = 'n';
+ fbp[3] = '\0';
+# else
+ /* On glibc2 systems from glibc >= 2.3 - probably also older
+ ones - we know that snprintf's return value conforms to
+ ISO C 99: the tests gl_SNPRINTF_RETVAL_C99 and
+ gl_SNPRINTF_TRUNCATION_C99 pass.
+ Therefore we can avoid using %n in this situation.
+ On glibc2 systems from 2004-10-18 or newer, the use of %n
+ in format strings in writable memory may crash the program
+ (if compiled with _FORTIFY_SOURCE=2), so we should avoid it
+ in this situation. */
+ /* On native Windows systems (such as mingw), we can avoid using
+ %n because:
+ - Although the gl_SNPRINTF_TRUNCATION_C99 test fails,
+ snprintf does not write more than the specified number
+ of bytes. (snprintf (buf, 3, "%d %d", 4567, 89) writes
+ '4', '5', '6' into buf, not '4', '5', '\0'.)
+ - Although the gl_SNPRINTF_RETVAL_C99 test fails, snprintf
+ allows us to recognize the case of an insufficient
+ buffer size: it returns -1 in this case.
+ On native Windows systems (such as mingw) where the OS is
+ Windows Vista, the use of %n in format strings by default
+ crashes the program. See
+ <http://gcc.gnu.org/ml/gcc/2007-06/msg00122.html> and
+ <http://msdn2.microsoft.com/en-us/library/ms175782(VS.80).aspx>
+ So we should avoid %n in this situation. */
+ fbp[1] = '\0';
+# endif
#else
- p[1] = '\0';
-#endif
-
- /* Construct the arguments for calling snprintf or sprintf. */
- prefix_count = 0;
- if (dp->width_arg_index != ARG_NONE)
- {
- if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
- abort ();
- prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
- }
- if (dp->precision_arg_index != ARG_NONE)
- {
- if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
- abort ();
- prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
- }
+ fbp[1] = '\0';
+#endif
+
+ /* Construct the arguments for calling snprintf or sprintf. */
+ prefix_count = 0;
+ if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
+ {
+ if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
+ abort ();
+ prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
+ }
+ if (!prec_ourselves && dp->precision_arg_index != ARG_NONE)
+ {
+ if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
+ abort ();
+ prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
+ }
#if USE_SNPRINTF
- /* Prepare checking whether snprintf returns the count
- via %n. */
- ENSURE_ALLOCATION (1);
- result[length] = '\0';
+ /* The SNPRINTF result is appended after result[0..length].
+ The latter is an array of DCHAR_T; SNPRINTF appends an
+ array of TCHAR_T to it. This is possible because
+ sizeof (TCHAR_T) divides sizeof (DCHAR_T) and
+ alignof (TCHAR_T) <= alignof (DCHAR_T). */
+# define TCHARS_PER_DCHAR (sizeof (DCHAR_T) / sizeof (TCHAR_T))
+ /* Ensure that maxlen below will be >= 2. Needed on BeOS,
+ where an snprintf() with maxlen==1 acts like sprintf(). */
+ ENSURE_ALLOCATION (xsum (length,
+ (2 + TCHARS_PER_DCHAR - 1)
+ / TCHARS_PER_DCHAR));
+ /* Prepare checking whether snprintf returns the count
+ via %n. */
+ *(TCHAR_T *) (result + length) = '\0';
#endif
- for (;;)
- {
- size_t maxlen;
- int count;
- int retcount;
+ orig_errno = errno;
- maxlen = allocated - length;
- count = -1;
- retcount = 0;
+ for (;;)
+ {
+ int count = -1;
#if USE_SNPRINTF
+ int retcount = 0;
+ size_t maxlen = allocated - length;
+ /* SNPRINTF can fail if its second argument is
+ > INT_MAX. */
+ if (maxlen > INT_MAX / TCHARS_PER_DCHAR)
+ maxlen = INT_MAX / TCHARS_PER_DCHAR;
+ maxlen = maxlen * TCHARS_PER_DCHAR;
# define SNPRINTF_BUF(arg) \
- switch (prefix_count) \
- { \
- case 0: \
- retcount = SNPRINTF (result + length, maxlen, buf, \
- arg, &count); \
- break; \
- case 1: \
- retcount = SNPRINTF (result + length, maxlen, buf, \
- prefixes[0], arg, &count); \
- break; \
- case 2: \
- retcount = SNPRINTF (result + length, maxlen, buf, \
- prefixes[0], prefixes[1], arg, \
- &count); \
- break; \
- default: \
- abort (); \
- }
+ switch (prefix_count) \
+ { \
+ case 0: \
+ retcount = SNPRINTF ((TCHAR_T *) (result + length), \
+ maxlen, buf, \
+ arg, &count); \
+ break; \
+ case 1: \
+ retcount = SNPRINTF ((TCHAR_T *) (result + length), \
+ maxlen, buf, \
+ prefixes[0], arg, &count); \
+ break; \
+ case 2: \
+ retcount = SNPRINTF ((TCHAR_T *) (result + length), \
+ maxlen, buf, \
+ prefixes[0], prefixes[1], arg, \
+ &count); \
+ break; \
+ default: \
+ abort (); \
+ }
#else
# define SNPRINTF_BUF(arg) \
- switch (prefix_count) \
- { \
- case 0: \
- count = sprintf (tmp, buf, arg); \
- break; \
- case 1: \
- count = sprintf (tmp, buf, prefixes[0], arg); \
- break; \
- case 2: \
- count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
- arg); \
- break; \
- default: \
- abort (); \
- }
-#endif
-
- switch (type)
- {
- case TYPE_SCHAR:
- {
- int arg = a.arg[dp->arg_index].a.a_schar;
- SNPRINTF_BUF (arg);
- }
- break;
- case TYPE_UCHAR:
- {
- unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
- SNPRINTF_BUF (arg);
- }
- break;
- case TYPE_SHORT:
- {
- int arg = a.arg[dp->arg_index].a.a_short;
- SNPRINTF_BUF (arg);
- }
- break;
- case TYPE_USHORT:
- {
- unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
- SNPRINTF_BUF (arg);
- }
- break;
- case TYPE_INT:
- {
- int arg = a.arg[dp->arg_index].a.a_int;
- SNPRINTF_BUF (arg);
- }
- break;
- case TYPE_UINT:
- {
- unsigned int arg = a.arg[dp->arg_index].a.a_uint;
- SNPRINTF_BUF (arg);
- }
- break;
- case TYPE_LONGINT:
- {
- long int arg = a.arg[dp->arg_index].a.a_longint;
- SNPRINTF_BUF (arg);
- }
- break;
- case TYPE_ULONGINT:
- {
- unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
- SNPRINTF_BUF (arg);
- }
- break;
+ switch (prefix_count) \
+ { \
+ case 0: \
+ count = sprintf (tmp, buf, arg); \
+ break; \
+ case 1: \
+ count = sprintf (tmp, buf, prefixes[0], arg); \
+ break; \
+ case 2: \
+ count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
+ arg); \
+ break; \
+ default: \
+ abort (); \
+ }
+#endif
+
+ errno = 0;
+ switch (type)
+ {
+ case TYPE_SCHAR:
+ {
+ int arg = a.arg[dp->arg_index].a.a_schar;
+ SNPRINTF_BUF (arg);
+ }
+ break;
+ case TYPE_UCHAR:
+ {
+ unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
+ SNPRINTF_BUF (arg);
+ }
+ break;
+ case TYPE_SHORT:
+ {
+ int arg = a.arg[dp->arg_index].a.a_short;
+ SNPRINTF_BUF (arg);
+ }
+ break;
+ case TYPE_USHORT:
+ {
+ unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
+ SNPRINTF_BUF (arg);
+ }
+ break;
+ case TYPE_INT:
+ {
+ int arg = a.arg[dp->arg_index].a.a_int;
+ SNPRINTF_BUF (arg);
+ }
+ break;
+ case TYPE_UINT:
+ {
+ unsigned int arg = a.arg[dp->arg_index].a.a_uint;
+ SNPRINTF_BUF (arg);
+ }
+ break;
+ case TYPE_LONGINT:
+ {
+ long int arg = a.arg[dp->arg_index].a.a_longint;
+ SNPRINTF_BUF (arg);
+ }
+ break;
+ case TYPE_ULONGINT:
+ {
+ unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
+ SNPRINTF_BUF (arg);
+ }
+ break;
#if HAVE_LONG_LONG_INT
- case TYPE_LONGLONGINT:
- {
- long long int arg = a.arg[dp->arg_index].a.a_longlongint;
- SNPRINTF_BUF (arg);
- }
- break;
- case TYPE_ULONGLONGINT:
- {
- unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
- SNPRINTF_BUF (arg);
- }
- break;
-#endif
- case TYPE_DOUBLE:
- {
- double arg = a.arg[dp->arg_index].a.a_double;
- SNPRINTF_BUF (arg);
- }
- break;
-#if HAVE_LONG_DOUBLE
- case TYPE_LONGDOUBLE:
- {
- long double arg = a.arg[dp->arg_index].a.a_longdouble;
- SNPRINTF_BUF (arg);
- }
- break;
-#endif
- case TYPE_CHAR:
- {
- int arg = a.arg[dp->arg_index].a.a_char;
- SNPRINTF_BUF (arg);
- }
- break;
+ case TYPE_LONGLONGINT:
+ {
+ long long int arg = a.arg[dp->arg_index].a.a_longlongint;
+ SNPRINTF_BUF (arg);
+ }
+ break;
+ case TYPE_ULONGLONGINT:
+ {
+ unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
+ SNPRINTF_BUF (arg);
+ }
+ break;
+#endif
+ case TYPE_DOUBLE:
+ {
+ double arg = a.arg[dp->arg_index].a.a_double;
+ SNPRINTF_BUF (arg);
+ }
+ break;
+ case TYPE_LONGDOUBLE:
+ {
+ long double arg = a.arg[dp->arg_index].a.a_longdouble;
+ SNPRINTF_BUF (arg);
+ }
+ break;
+ case TYPE_CHAR:
+ {
+ int arg = a.arg[dp->arg_index].a.a_char;
+ SNPRINTF_BUF (arg);
+ }
+ break;
#if HAVE_WINT_T
- case TYPE_WIDE_CHAR:
- {
- wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
- SNPRINTF_BUF (arg);
- }
- break;
-#endif
- case TYPE_STRING:
- {
- const char *arg = a.arg[dp->arg_index].a.a_string;
- SNPRINTF_BUF (arg);
- }
- break;
+ case TYPE_WIDE_CHAR:
+ {
+ wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
+ SNPRINTF_BUF (arg);
+ }
+ break;
+#endif
+ case TYPE_STRING:
+ {
+ const char *arg = a.arg[dp->arg_index].a.a_string;
+ SNPRINTF_BUF (arg);
+ }
+ break;
#if HAVE_WCHAR_T
- case TYPE_WIDE_STRING:
- {
- const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
- SNPRINTF_BUF (arg);
- }
- break;
-#endif
- case TYPE_POINTER:
- {
- void *arg = a.arg[dp->arg_index].a.a_pointer;
- SNPRINTF_BUF (arg);
- }
- break;
- default:
- abort ();
- }
+ case TYPE_WIDE_STRING:
+ {
+ const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
+ SNPRINTF_BUF (arg);
+ }
+ break;
+#endif
+ case TYPE_POINTER:
+ {
+ void *arg = a.arg[dp->arg_index].a.a_pointer;
+ SNPRINTF_BUF (arg);
+ }
+ break;
+ default:
+ abort ();
+ }
#if USE_SNPRINTF
- /* Portability: Not all implementations of snprintf()
- are ISO C 99 compliant. Determine the number of
- bytes that snprintf() has produced or would have
- produced. */
- if (count >= 0)
- {
- /* Verify that snprintf() has NUL-terminated its
- result. */
- if (count < maxlen && result[length + count] != '\0')
- abort ();
- /* Portability hack. */
- if (retcount > count)
- count = retcount;
- }
- else
- {
- /* snprintf() doesn't understand the '%n'
- directive. */
- if (p[1] != '\0')
- {
- /* Don't use the '%n' directive; instead, look
- at the snprintf() return value. */
- p[1] = '\0';
- continue;
- }
- else
- {
- /* Look at the snprintf() return value. */
- if (retcount < 0)
- {
- /* HP-UX 10.20 snprintf() is doubly deficient:
- It doesn't understand the '%n' directive,
- *and* it returns -1 (rather than the length
- that would have been required) when the
- buffer is too small. */
- size_t bigger_need =
- (allocated > 12 ? allocated : 12);
- ENSURE_ALLOCATION (bigger_need);
- continue;
- }
- else
- count = retcount;
- }
- }
-#endif
-
- /* Attempt to handle failure. */
- if (count < 0)
- {
- if (!(result == resultbuf || result == NULL))
- free (result);
- if (buf_malloced != NULL)
- free (buf_malloced);
- CLEANUP ();
- errno = EINVAL;
- return NULL;
- }
+ /* Portability: Not all implementations of snprintf()
+ are ISO C 99 compliant. Determine the number of
+ bytes that snprintf() has produced or would have
+ produced. */
+ if (count >= 0)
+ {
+ /* Verify that snprintf() has NUL-terminated its
+ result. */
+ if (count < maxlen
+ && ((TCHAR_T *) (result + length)) [count] != '\0')
+ abort ();
+ /* Portability hack. */
+ if (retcount > count)
+ count = retcount;
+ }
+ else
+ {
+ /* snprintf() doesn't understand the '%n'
+ directive. */
+ if (fbp[1] != '\0')
+ {
+ /* Don't use the '%n' directive; instead, look
+ at the snprintf() return value. */
+ fbp[1] = '\0';
+ continue;
+ }
+ else
+ {
+ /* Look at the snprintf() return value. */
+ if (retcount < 0)
+ {
+# if !HAVE_SNPRINTF_RETVAL_C99
+ /* HP-UX 10.20 snprintf() is doubly deficient:
+ It doesn't understand the '%n' directive,
+ *and* it returns -1 (rather than the length
+ that would have been required) when the
+ buffer is too small.
+ But a failure at this point can also come
+ from other reasons than a too small buffer,
+ such as an invalid wide string argument to
+ the %ls directive, or possibly an invalid
+ floating-point argument. */
+ size_t tmp_length =
+ MAX_ROOM_NEEDED (&a, dp->arg_index,
+ dp->conversion, type, flags,
+ width,
+ has_precision,
+ precision, pad_ourselves);
-#if !USE_SNPRINTF
- if (count >= tmp_length)
- /* tmp_length was incorrectly calculated - fix the
- code above! */
- abort ();
-#endif
-
- /* Make room for the result. */
- if (count >= maxlen)
- {
- /* Need at least count bytes. But allocate
- proportionally, to avoid looping eternally if
- snprintf() reports a too small count. */
- ENSURE_ALLOCATION (count < allocated
- ? allocated : count);
-#if USE_SNPRINTF
- continue;
+ if (maxlen < tmp_length)
+ {
+ /* Make more room. But try to do through
+ this reallocation only once. */
+ size_t bigger_need =
+ xsum (length,
+ xsum (tmp_length,
+ TCHARS_PER_DCHAR - 1)
+ / TCHARS_PER_DCHAR);
+ /* And always grow proportionally.
+ (There may be several arguments, each
+ needing a little more room than the
+ previous one.) */
+ size_t bigger_need2 =
+ xsum (xtimes (allocated, 2), 12);
+ if (bigger_need < bigger_need2)
+ bigger_need = bigger_need2;
+ ENSURE_ALLOCATION (bigger_need);
+ continue;
+ }
+# endif
+ }
+ else
+ count = retcount;
+ }
+ }
#endif
- }
+
+ /* Attempt to handle failure. */
+ if (count < 0)
+ {
+ /* SNPRINTF or sprintf failed. Save and use the errno
+ that it has set, if any. */
+ int saved_errno = errno;
+ if (saved_errno == 0)
+ {
+ if (dp->conversion == 'c' || dp->conversion == 's')
+ saved_errno = EILSEQ;
+ else
+ saved_errno = EINVAL;
+ }
+
+ if (!(result == resultbuf || result == NULL))
+ free (result);
+ if (buf_malloced != NULL)
+ free (buf_malloced);
+ CLEANUP ();
+
+ errno = saved_errno;
+ return NULL;
+ }
#if USE_SNPRINTF
- /* The snprintf() result did fit. */
+ /* Handle overflow of the allocated buffer.
+ If such an overflow occurs, a C99 compliant snprintf()
+ returns a count >= maxlen. However, a non-compliant
+ snprintf() function returns only count = maxlen - 1. To
+ cover both cases, test whether count >= maxlen - 1. */
+ if ((unsigned int) count + 1 >= maxlen)
+ {
+ /* If maxlen already has attained its allowed maximum,
+ allocating more memory will not increase maxlen.
+ Instead of looping, bail out. */
+ if (maxlen == INT_MAX / TCHARS_PER_DCHAR)
+ goto overflow;
+ else
+ {
+ /* Need at least (count + 1) * sizeof (TCHAR_T)
+ bytes. (The +1 is for the trailing NUL.)
+ But ask for (count + 2) * sizeof (TCHAR_T)
+ bytes, so that in the next round, we likely get
+ maxlen > (unsigned int) count + 1
+ and so we don't get here again.
+ And allocate proportionally, to avoid looping
+ eternally if snprintf() reports a too small
+ count. */
+ size_t n =
+ xmax (xsum (length,
+ ((unsigned int) count + 2
+ + TCHARS_PER_DCHAR - 1)
+ / TCHARS_PER_DCHAR),
+ xtimes (allocated, 2));
+
+ ENSURE_ALLOCATION (n);
+ continue;
+ }
+ }
+#endif
+
+#if NEED_PRINTF_UNBOUNDED_PRECISION
+ if (prec_ourselves)
+ {
+ /* Handle the precision. */
+ TCHAR_T *prec_ptr =
+# if USE_SNPRINTF
+ (TCHAR_T *) (result + length);
+# else
+ tmp;
+# endif
+ size_t prefix_count;
+ size_t move;
+
+ prefix_count = 0;
+ /* Put the additional zeroes after the sign. */
+ if (count >= 1
+ && (*prec_ptr == '-' || *prec_ptr == '+'
+ || *prec_ptr == ' '))
+ prefix_count = 1;
+ /* Put the additional zeroes after the 0x prefix if
+ (flags & FLAG_ALT) || (dp->conversion == 'p'). */
+ else if (count >= 2
+ && prec_ptr[0] == '0'
+ && (prec_ptr[1] == 'x' || prec_ptr[1] == 'X'))
+ prefix_count = 2;
+
+ move = count - prefix_count;
+ if (precision > move)
+ {
+ /* Insert zeroes. */
+ size_t insert = precision - move;
+ TCHAR_T *prec_end;
+
+# if USE_SNPRINTF
+ size_t n =
+ xsum (length,
+ (count + insert + TCHARS_PER_DCHAR - 1)
+ / TCHARS_PER_DCHAR);
+ length += (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
+ ENSURE_ALLOCATION (n);
+ length -= (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
+ prec_ptr = (TCHAR_T *) (result + length);
+# endif
+
+ prec_end = prec_ptr + count;
+ prec_ptr += prefix_count;
+
+ while (prec_end > prec_ptr)
+ {
+ prec_end--;
+ prec_end[insert] = prec_end[0];
+ }
+
+ prec_end += insert;
+ do
+ *--prec_end = '0';
+ while (prec_end > prec_ptr);
+
+ count += insert;
+ }
+ }
+#endif
+
+#if !USE_SNPRINTF
+ if (count >= tmp_length)
+ /* tmp_length was incorrectly calculated - fix the
+ code above! */
+ abort ();
+#endif
+
+#if !DCHAR_IS_TCHAR
+ /* Convert from TCHAR_T[] to DCHAR_T[]. */
+ if (dp->conversion == 'c' || dp->conversion == 's')
+ {
+ /* type = TYPE_CHAR or TYPE_WIDE_CHAR or TYPE_STRING
+ TYPE_WIDE_STRING.
+ The result string is not certainly ASCII. */
+ const TCHAR_T *tmpsrc;
+ DCHAR_T *tmpdst;
+ size_t tmpdst_len;
+ /* This code assumes that TCHAR_T is 'char'. */
+ verify (sizeof (TCHAR_T) == 1);
+# if USE_SNPRINTF
+ tmpsrc = (TCHAR_T *) (result + length);
+# else
+ tmpsrc = tmp;
+# endif
+ tmpdst =
+ DCHAR_CONV_FROM_ENCODING (locale_charset (),
+ iconveh_question_mark,
+ tmpsrc, count,
+ NULL,
+ NULL, &tmpdst_len);
+ if (tmpdst == NULL)
+ {
+ int saved_errno = errno;
+ if (!(result == resultbuf || result == NULL))
+ free (result);
+ if (buf_malloced != NULL)
+ free (buf_malloced);
+ CLEANUP ();
+ errno = saved_errno;
+ return NULL;
+ }
+ ENSURE_ALLOCATION (xsum (length, tmpdst_len));
+ DCHAR_CPY (result + length, tmpdst, tmpdst_len);
+ free (tmpdst);
+ count = tmpdst_len;
+ }
+ else
+ {
+ /* The result string is ASCII.
+ Simple 1:1 conversion. */
+# if USE_SNPRINTF
+ /* If sizeof (DCHAR_T) == sizeof (TCHAR_T), it's a
+ no-op conversion, in-place on the array starting
+ at (result + length). */
+ if (sizeof (DCHAR_T) != sizeof (TCHAR_T))
+# endif
+ {
+ const TCHAR_T *tmpsrc;
+ DCHAR_T *tmpdst;
+ size_t n;
+
+# if USE_SNPRINTF
+ if (result == resultbuf)
+ {
+ tmpsrc = (TCHAR_T *) (result + length);
+ /* ENSURE_ALLOCATION will not move tmpsrc
+ (because it's part of resultbuf). */
+ ENSURE_ALLOCATION (xsum (length, count));
+ }
+ else
+ {
+ /* ENSURE_ALLOCATION will move the array
+ (because it uses realloc(). */
+ ENSURE_ALLOCATION (xsum (length, count));
+ tmpsrc = (TCHAR_T *) (result + length);
+ }
+# else
+ tmpsrc = tmp;
+ ENSURE_ALLOCATION (xsum (length, count));
+# endif
+ tmpdst = result + length;
+ /* Copy backwards, because of overlapping. */
+ tmpsrc += count;
+ tmpdst += count;
+ for (n = count; n > 0; n--)
+ *--tmpdst = *--tmpsrc;
+ }
+ }
+#endif
+
+#if DCHAR_IS_TCHAR && !USE_SNPRINTF
+ /* Make room for the result. */
+ if (count > allocated - length)
+ {
+ /* Need at least count elements. But allocate
+ proportionally. */
+ size_t n =
+ xmax (xsum (length, count), xtimes (allocated, 2));
+
+ ENSURE_ALLOCATION (n);
+ }
+#endif
+
+ /* Here count <= allocated - length. */
+
+ /* Perform padding. */
+#if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
+ if (pad_ourselves && has_width)
+ {
+ size_t w;
+# if ENABLE_UNISTDIO
+ /* Outside POSIX, it's preferable to compare the width
+ against the number of _characters_ of the converted
+ value. */
+ w = DCHAR_MBSNLEN (result + length, count);
+# else
+ /* The width is compared against the number of _bytes_
+ of the converted value, says POSIX. */
+ w = count;
+# endif
+ if (w < width)
+ {
+ size_t pad = width - w;
+
+ /* Make room for the result. */
+ if (xsum (count, pad) > allocated - length)
+ {
+ /* Need at least count + pad elements. But
+ allocate proportionally. */
+ size_t n =
+ xmax (xsum3 (length, count, pad),
+ xtimes (allocated, 2));
+
+# if USE_SNPRINTF
+ length += count;
+ ENSURE_ALLOCATION (n);
+ length -= count;
+# else
+ ENSURE_ALLOCATION (n);
+# endif
+ }
+ /* Here count + pad <= allocated - length. */
+
+ {
+# if !DCHAR_IS_TCHAR || USE_SNPRINTF
+ DCHAR_T * const rp = result + length;
+# else
+ DCHAR_T * const rp = tmp;
+# endif
+ DCHAR_T *p = rp + count;
+ DCHAR_T *end = p + pad;
+ DCHAR_T *pad_ptr;
+# if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
+ if (dp->conversion == 'c'
+ || dp->conversion == 's')
+ /* No zero-padding for string directives. */
+ pad_ptr = NULL;
+ else
+# endif
+ {
+ pad_ptr = (*rp == '-' ? rp + 1 : rp);
+ /* No zero-padding of "inf" and "nan". */
+ if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
+ || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
+ pad_ptr = NULL;
+ }
+ /* The generated string now extends from rp to p,
+ with the zero padding insertion point being at
+ pad_ptr. */
+
+ count = count + pad; /* = end - rp */
+
+ if (flags & FLAG_LEFT)
+ {
+ /* Pad with spaces on the right. */
+ for (; pad > 0; pad--)
+ *p++ = ' ';
+ }
+ else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
+ {
+ /* Pad with zeroes. */
+ DCHAR_T *q = end;
+
+ while (p > pad_ptr)
+ *--q = *--p;
+ for (; pad > 0; pad--)
+ *p++ = '0';
+ }
+ else
+ {
+ /* Pad with spaces on the left. */
+ DCHAR_T *q = end;
+
+ while (p > rp)
+ *--q = *--p;
+ for (; pad > 0; pad--)
+ *p++ = ' ';
+ }
+ }
+ }
+ }
+#endif
+
+ /* Here still count <= allocated - length. */
+
+#if !DCHAR_IS_TCHAR || USE_SNPRINTF
+ /* The snprintf() result did fit. */
#else
- /* Append the sprintf() result. */
- memcpy (result + length, tmp, count * sizeof (CHAR_T));
- if (tmp != tmpbuf)
- free (tmp);
+ /* Append the sprintf() result. */
+ memcpy (result + length, tmp, count * sizeof (DCHAR_T));
+#endif
+#if !USE_SNPRINTF
+ if (tmp != tmpbuf)
+ free (tmp);
+#endif
+
+#if NEED_PRINTF_DIRECTIVE_F
+ if (dp->conversion == 'F')
+ {
+ /* Convert the %f result to upper case for %F. */
+ DCHAR_T *rp = result + length;
+ size_t rc;
+ for (rc = count; rc > 0; rc--, rp++)
+ if (*rp >= 'a' && *rp <= 'z')
+ *rp = *rp - 'a' + 'A';
+ }
#endif
- length += count;
- break;
- }
- }
- }
+ length += count;
+ break;
+ }
+ errno = orig_errno;
+#undef pad_ourselves
+#undef prec_ourselves
+ }
+ }
}
/* Add the final NUL. */
- ENSURE_ALLOCATION (1);
+ ENSURE_ALLOCATION (xsum (length, 1));
result[length] = '\0';
if (result != resultbuf && length + 1 < allocated)
{
- /* Shrink the allocated memory if possible. */
- CHAR_T *memory;
+ /* Shrink the allocated memory if possible. */
+ DCHAR_T *memory;
- memory = (CHAR_T *) realloc (result, (length + 1) * sizeof (CHAR_T));
- if (memory != NULL)
- result = memory;
+ memory = (DCHAR_T *) realloc (result, (length + 1) * sizeof (DCHAR_T));
+ if (memory != NULL)
+ result = memory;
}
if (buf_malloced != NULL)
free (buf_malloced);
CLEANUP ();
*lengthp = length;
- if (length > INT_MAX)
- goto length_overflow;
+ /* Note that we can produce a big string of a length > INT_MAX. POSIX
+ says that snprintf() fails with errno = EOVERFLOW in this case, but
+ that's only because snprintf() returns an 'int'. This function does
+ not have this limitation. */
return result;
- length_overflow:
- /* We could produce such a big string, but its length doesn't fit into
- an 'int'. POSIX says that snprintf() fails with errno = EOVERFLOW in
- this case. */
- if (result != resultbuf)
+#if USE_SNPRINTF
+ overflow:
+ if (!(result == resultbuf || result == NULL))
free (result);
+ if (buf_malloced != NULL)
+ free (buf_malloced);
+ CLEANUP ();
errno = EOVERFLOW;
return NULL;
+#endif
out_of_memory:
if (!(result == resultbuf || result == NULL))
@@ -926,10 +5582,17 @@ VASNPRINTF (CHAR_T *resultbuf, size_t *lengthp, const CHAR_T *format, va_list ar
}
}
+#undef MAX_ROOM_NEEDED
+#undef TCHARS_PER_DCHAR
#undef SNPRINTF
#undef USE_SNPRINTF
+#undef DCHAR_SET
+#undef DCHAR_CPY
#undef PRINTF_PARSE
#undef DIRECTIVES
#undef DIRECTIVE
-#undef CHAR_T
+#undef DCHAR_IS_TCHAR
+#undef TCHAR_T
+#undef DCHAR_T
+#undef FCHAR_T
#undef VASNPRINTF
diff --git a/lib/vasnprintf.h b/lib/vasnprintf.h
index 7a0c01f..8e9d84f 100644
--- a/lib/vasnprintf.h
+++ b/lib/vasnprintf.h
@@ -1,9 +1,9 @@
/* vsprintf with automatic memory allocation.
- Copyright (C) 2002-2004, 2007 Free Software Foundation, Inc.
+ Copyright (C) 2002-2004, 2007-2016 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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -12,8 +12,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ with this program; if not, see <http://www.gnu.org/licenses/>. */
#ifndef _VASNPRINTF_H
#define _VASNPRINTF_H
@@ -24,17 +23,16 @@
/* Get size_t. */
#include <stddef.h>
-#ifndef __attribute__
-/* This feature is available in gcc versions 2.5 and later. */
-# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 5) || __STRICT_ANSI__
-# define __attribute__(Spec) /* empty */
-# endif
-/* The __-protected variants of `format' and `printf' attributes
- are accepted by gcc versions 2.6.4 (effectively 2.7) and later. */
-# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 7)
-# define __format__ format
-# define __printf__ printf
-# endif
+/* The __attribute__ feature is available in gcc versions 2.5 and later.
+ The __-protected variants of the attributes 'format' and 'printf' are
+ accepted by gcc versions 2.6.4 (effectively 2.7) and later.
+ We enable _GL_ATTRIBUTE_FORMAT only if these are supported too, because
+ gnulib and libintl do '#define printf __printf__' when they override
+ the 'printf' function. */
+#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 7)
+# define _GL_ATTRIBUTE_FORMAT(spec) __attribute__ ((__format__ spec))
+#else
+# define _GL_ATTRIBUTE_FORMAT(spec) /* empty */
#endif
#ifdef __cplusplus
@@ -70,9 +68,9 @@ extern "C" {
# define vasnprintf rpl_vasnprintf
#endif
extern char * asnprintf (char *resultbuf, size_t *lengthp, const char *format, ...)
- __attribute__ ((__format__ (__printf__, 3, 4)));
+ _GL_ATTRIBUTE_FORMAT ((__printf__, 3, 4));
extern char * vasnprintf (char *resultbuf, size_t *lengthp, const char *format, va_list args)
- __attribute__ ((__format__ (__printf__, 3, 0)));
+ _GL_ATTRIBUTE_FORMAT ((__printf__, 3, 0));
#ifdef __cplusplus
}
diff --git a/lib/vasprintf.c b/lib/vasprintf.c
index 8247073..a5dc1be 100644
--- a/lib/vasprintf.c
+++ b/lib/vasprintf.c
@@ -1,9 +1,9 @@
/* Formatted output to strings.
- Copyright (C) 1999, 2002, 2006 Free Software Foundation, Inc.
+ Copyright (C) 1999, 2002, 2006-2016 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 2, or (at your option)
+ the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
@@ -12,13 +12,16 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ with this program; if not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
/* Specification. */
-#include "vasprintf.h"
+#ifdef IN_LIBASPRINTF
+# include "vasprintf.h"
+#else
+# include <stdio.h>
+#endif
#include <errno.h>
#include <limits.h>
@@ -26,11 +29,6 @@
#include "vasnprintf.h"
-/* Some systems, like OSF/1 4.0 and Woe32, don't have EOVERFLOW. */
-#ifndef EOVERFLOW
-# define EOVERFLOW E2BIG
-#endif
-
int
vasprintf (char **resultp, const char *format, va_list args)
{
diff --git a/lib/vasprintf.h b/lib/vasprintf.h
deleted file mode 100644
index 65f0531..0000000
--- a/lib/vasprintf.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/* vsprintf with automatic memory allocation.
- Copyright (C) 2002-2003, 2007 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-#ifndef _VASPRINTF_H
-#define _VASPRINTF_H
-
-#if HAVE_VASPRINTF
-
-/* Get asprintf(), vasprintf() declarations. */
-#include <stdio.h>
-
-#endif
-
-#if !HAVE_VASPRINTF || REPLACE_VASPRINTF
-
-/* Get va_list. */
-#include <stdarg.h>
-
-#ifndef __attribute__
-/* This feature is available in gcc versions 2.5 and later. */
-# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 5) || __STRICT_ANSI__
-# define __attribute__(Spec) /* empty */
-# endif
-/* The __-protected variants of `format' and `printf' attributes
- are accepted by gcc versions 2.6.4 (effectively 2.7) and later. */
-# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 7)
-# define __format__ format
-# define __printf__ printf
-# endif
-#endif
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Write formatted output to a string dynamically allocated with malloc().
- If the memory allocation succeeds, store the address of the string in
- *RESULT and return the number of resulting bytes, excluding the trailing
- NUL. Upon memory allocation error, or some other error, return -1. */
-#if REPLACE_VASPRINTF
-# define asprintf rpl_asprintf
-# define vasprintf rpl_vasprintf
-#endif
-extern int asprintf (char **result, const char *format, ...)
- __attribute__ ((__format__ (__printf__, 2, 3)));
-extern int vasprintf (char **result, const char *format, va_list args)
- __attribute__ ((__format__ (__printf__, 2, 0)));
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
-
-#endif /* _VASPRINTF_H */
diff --git a/lib/verify.h b/lib/verify.h
index d603b17..2f43837 100644
--- a/lib/verify.h
+++ b/lib/verify.h
@@ -1,11 +1,11 @@
/* Compile-time assert-like macros.
- Copyright (C) 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2005-2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,26 +13,53 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert, Bruno Haible, and Jim Meyering. */
-#ifndef VERIFY_H
-# define VERIFY_H 1
+#ifndef _GL_VERIFY_H
+#define _GL_VERIFY_H
+
+
+/* Define _GL_HAVE__STATIC_ASSERT to 1 if _Static_assert works as per C11.
+ This is supported by GCC 4.6.0 and later, in C mode, and its use
+ here generates easier-to-read diagnostics when verify (R) fails.
+
+ Define _GL_HAVE_STATIC_ASSERT to 1 if static_assert works as per C++11.
+ This will likely be supported by future GCC versions, in C++ mode.
+
+ Use this only with GCC. If we were willing to slow 'configure'
+ down we could also use it with other compilers, but since this
+ affects only the quality of diagnostics, why bother? */
+#if (4 < __GNUC__ + (6 <= __GNUC_MINOR__) \
+ && (201112L <= __STDC_VERSION__ || !defined __STRICT_ANSI__) \
+ && !defined __cplusplus)
+# define _GL_HAVE__STATIC_ASSERT 1
+#endif
+/* The condition (99 < __GNUC__) is temporary, until we know about the
+ first G++ release that supports static_assert. */
+#if (99 < __GNUC__) && defined __cplusplus
+# define _GL_HAVE_STATIC_ASSERT 1
+#endif
+
+/* FreeBSD 9.1 <sys/cdefs.h>, included by <stddef.h> and lots of other
+ system headers, defines a conflicting _Static_assert that is no
+ better than ours; override it. */
+#ifndef _GL_HAVE_STATIC_ASSERT
+# include <stddef.h>
+# undef _Static_assert
+#endif
/* Each of these macros verifies that its argument R is nonzero. To
be portable, R should be an integer constant expression. Unlike
assert (R), there is no run-time overhead.
- There are two macros, since no single macro can be used in all
- contexts in C. verify_true (R) is for scalar contexts, including
- integer constant expression contexts. verify (R) is for declaration
- contexts, e.g., the top level.
-
- Symbols ending in "__" are private to this header.
+ If _Static_assert works, verify (R) uses it directly. Similarly,
+ _GL_VERIFY_TRUE works by packaging a _Static_assert inside a struct
+ that is an operand of sizeof.
- The code below uses several ideas.
+ The code below uses several ideas for C++ compilers, and for C
+ compilers that do not support _Static_assert:
* The first step is ((R) ? 1 : -1). Given an expression R, of
integral or boolean or floating-point type, this yields an
@@ -40,7 +67,9 @@
constant and nonnegative.
* Next this expression W is wrapped in a type
- struct verify_type__ { unsigned int verify_error_if_negative_size__: W; }.
+ struct _gl_verify_type {
+ unsigned int _gl_verify_error_if_negative: W;
+ }.
If W is negative, this yields a compile-time error. No compiler can
deal with a bit-field of negative size.
@@ -54,7 +83,7 @@
void function (int n) { verify (n < 0); }
- * For the verify macro, the struct verify_type__ will need to
+ * For the verify macro, the struct _gl_verify_type will need to
somehow be embedded into a declaration. To be portable, this
declaration must declare an object, a constant, a function, or a
typedef name. If the declared entity uses the type directly,
@@ -70,13 +99,14 @@
if the entity names are not disambiguated. A workaround is to
attach the current line number to the entity name:
- #define GL_CONCAT0(x, y) x##y
- #define GL_CONCAT(x, y) GL_CONCAT0 (x, y)
- extern struct {...} * GL_CONCAT(dummy,__LINE__);
+ #define _GL_CONCAT0(x, y) x##y
+ #define _GL_CONCAT(x, y) _GL_CONCAT0 (x, y)
+ extern struct {...} * _GL_CONCAT (dummy, __LINE__);
But this has the problem that two invocations of verify from
within the same macro would collide, since the __LINE__ value
- would be the same for both invocations.
+ would be the same for both invocations. (The GCC __COUNTER__
+ macro solves this problem, but is not portable.)
A solution is to use the sizeof operator. It yields a number,
getting rid of the identity of the type. Declarations like
@@ -91,11 +121,11 @@
Which of the following alternatives can be used?
extern int dummy [sizeof (struct {...})];
- extern int dummy [sizeof (struct verify_type__ {...})];
+ extern int dummy [sizeof (struct _gl_verify_type {...})];
extern void dummy (int [sizeof (struct {...})]);
- extern void dummy (int [sizeof (struct verify_type__ {...})]);
+ extern void dummy (int [sizeof (struct _gl_verify_type {...})]);
extern int (*dummy (void)) [sizeof (struct {...})];
- extern int (*dummy (void)) [sizeof (struct verify_type__ {...})];
+ extern int (*dummy (void)) [sizeof (struct _gl_verify_type {...})];
In the second and sixth case, the struct type is exported to the
outer scope; two such declarations therefore collide. GCC warns
@@ -104,38 +134,146 @@
extern int (*dummy (void)) [sizeof (struct {...})];
- * This implementation exploits the fact that GCC does not warn about
- the last declaration mentioned above. If a future version of GCC
- introduces a warning for this, the problem could be worked around
- by using code specialized to GCC, e.g.,:
+ * GCC warns about duplicate declarations of the dummy function if
+ -Wredundant-decls is used. GCC 4.3 and later have a builtin
+ __COUNTER__ macro that can let us generate unique identifiers for
+ each dummy function, to suppress this warning.
- #if 4 <= __GNUC__
- # define verify(R) \
- extern int (* verify_function__ (void)) \
- [__builtin_constant_p (R) && (R) ? 1 : -1]
- #endif
+ * This implementation exploits the fact that older versions of GCC,
+ which do not support _Static_assert, also do not warn about the
+ last declaration mentioned above.
+
+ * GCC warns if -Wnested-externs is enabled and verify() is used
+ within a function body; but inside a function, you can always
+ arrange to use verify_expr() instead.
* In C++, any struct definition inside sizeof is invalid.
Use a template type to work around the problem. */
+/* Concatenate two preprocessor tokens. */
+#define _GL_CONCAT(x, y) _GL_CONCAT0 (x, y)
+#define _GL_CONCAT0(x, y) x##y
+
+/* _GL_COUNTER is an integer, preferably one that changes each time we
+ use it. Use __COUNTER__ if it works, falling back on __LINE__
+ otherwise. __LINE__ isn't perfect, but it's better than a
+ constant. */
+#if defined __COUNTER__ && __COUNTER__ != __COUNTER__
+# define _GL_COUNTER __COUNTER__
+#else
+# define _GL_COUNTER __LINE__
+#endif
-/* Verify requirement R at compile-time, as an integer constant expression.
- Return 1. */
+/* Generate a symbol with the given prefix, making it unique if
+ possible. */
+#define _GL_GENSYM(prefix) _GL_CONCAT (prefix, _GL_COUNTER)
-# ifdef __cplusplus
+/* Verify requirement R at compile-time, as an integer constant expression
+ that returns 1. If R is false, fail at compile-time, preferably
+ with a diagnostic that includes the string-literal DIAGNOSTIC. */
+
+#define _GL_VERIFY_TRUE(R, DIAGNOSTIC) \
+ (!!sizeof (_GL_VERIFY_TYPE (R, DIAGNOSTIC)))
+
+#ifdef __cplusplus
+# if !GNULIB_defined_struct__gl_verify_type
template <int w>
- struct verify_type__ { unsigned int verify_error_if_negative_size__: w; };
-# define verify_true(R) \
- (!!sizeof (verify_type__<(R) ? 1 : -1>))
-# else
-# define verify_true(R) \
- (!!sizeof \
- (struct { unsigned int verify_error_if_negative_size__: (R) ? 1 : -1; }))
+ struct _gl_verify_type {
+ unsigned int _gl_verify_error_if_negative: w;
+ };
+# define GNULIB_defined_struct__gl_verify_type 1
# endif
+# define _GL_VERIFY_TYPE(R, DIAGNOSTIC) \
+ _gl_verify_type<(R) ? 1 : -1>
+#elif defined _GL_HAVE__STATIC_ASSERT
+# define _GL_VERIFY_TYPE(R, DIAGNOSTIC) \
+ struct { \
+ _Static_assert (R, DIAGNOSTIC); \
+ int _gl_dummy; \
+ }
+#else
+# define _GL_VERIFY_TYPE(R, DIAGNOSTIC) \
+ struct { unsigned int _gl_verify_error_if_negative: (R) ? 1 : -1; }
+#endif
+
+/* Verify requirement R at compile-time, as a declaration without a
+ trailing ';'. If R is false, fail at compile-time, preferably
+ with a diagnostic that includes the string-literal DIAGNOSTIC.
+
+ Unfortunately, unlike C11, this implementation must appear as an
+ ordinary declaration, and cannot appear inside struct { ... }. */
+
+#ifdef _GL_HAVE__STATIC_ASSERT
+# define _GL_VERIFY _Static_assert
+#else
+# define _GL_VERIFY(R, DIAGNOSTIC) \
+ extern int (*_GL_GENSYM (_gl_verify_function) (void)) \
+ [_GL_VERIFY_TRUE (R, DIAGNOSTIC)]
+#endif
+
+/* _GL_STATIC_ASSERT_H is defined if this code is copied into assert.h. */
+#ifdef _GL_STATIC_ASSERT_H
+# if !defined _GL_HAVE__STATIC_ASSERT && !defined _Static_assert
+# define _Static_assert(R, DIAGNOSTIC) _GL_VERIFY (R, DIAGNOSTIC)
+# endif
+# if !defined _GL_HAVE_STATIC_ASSERT && !defined static_assert
+# define static_assert _Static_assert /* C11 requires this #define. */
+# endif
+#endif
+
+/* @assert.h omit start@ */
+
+/* Each of these macros verifies that its argument R is nonzero. To
+ be portable, R should be an integer constant expression. Unlike
+ assert (R), there is no run-time overhead.
+
+ There are two macros, since no single macro can be used in all
+ contexts in C. verify_true (R) is for scalar contexts, including
+ integer constant expression contexts. verify (R) is for declaration
+ contexts, e.g., the top level. */
+
+/* Verify requirement R at compile-time, as an integer constant expression.
+ Return 1. This is equivalent to verify_expr (R, 1).
+
+ verify_true is obsolescent; please use verify_expr instead. */
+
+#define verify_true(R) _GL_VERIFY_TRUE (R, "verify_true (" #R ")")
+
+/* Verify requirement R at compile-time. Return the value of the
+ expression E. */
+
+#define verify_expr(R, E) \
+ (_GL_VERIFY_TRUE (R, "verify_expr (" #R ", " #E ")") ? (E) : (E))
/* Verify requirement R at compile-time, as a declaration without a
trailing ';'. */
-# define verify(R) extern int (* verify_function__ (void)) [verify_true (R)]
+#define verify(R) _GL_VERIFY (R, "verify (" #R ")")
+
+#ifndef __has_builtin
+# define __has_builtin(x) 0
+#endif
+
+/* Assume that R always holds. This lets the compiler optimize
+ accordingly. R should not have side-effects; it may or may not be
+ evaluated. Behavior is undefined if R is false. */
+
+#if (__has_builtin (__builtin_unreachable) \
+ || 4 < __GNUC__ + (5 <= __GNUC_MINOR__))
+# define assume(R) ((R) ? (void) 0 : __builtin_unreachable ())
+#elif 1200 <= _MSC_VER
+# define assume(R) __assume (R)
+#elif (defined lint \
+ && (__has_builtin (__builtin_trap) \
+ || 3 < __GNUC__ + (3 < __GNUC_MINOR__ + (4 <= __GNUC_PATCHLEVEL__))))
+ /* Doing it this way helps various packages when configured with
+ --enable-gcc-warnings, which compiles with -Dlint. It's nicer
+ when 'assume' silences warnings even with older GCCs. */
+# define assume(R) ((R) ? (void) 0 : __builtin_trap ())
+#else
+# define assume(R) ((void) (0 && (R)))
+#endif
+
+/* @assert.h omit end@ */
#endif
diff --git a/lib/verror.c b/lib/verror.c
new file mode 100644
index 0000000..1abf3fe
--- /dev/null
+++ b/lib/verror.c
@@ -0,0 +1,77 @@
+/* va_list error handler for noninteractive utilities
+ Copyright (C) 2006-2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Eric Blake. */
+
+#include <config.h>
+
+#include "verror.h"
+#include "xvasprintf.h"
+
+#include <errno.h>
+#include <stdarg.h>
+#include <stdlib.h>
+
+#if ENABLE_NLS
+# include "gettext.h"
+# define _(msgid) gettext (msgid)
+#endif
+
+#ifndef _
+# define _(String) String
+#endif
+
+/* Print a message with 'vfprintf (stderr, FORMAT, ARGS)';
+ if ERRNUM is nonzero, follow it with ": " and strerror (ERRNUM).
+ If STATUS is nonzero, terminate the program with 'exit (STATUS)'.
+ Use the globals error_print_progname and error_message_count similarly
+ to error(). */
+void
+verror (int status, int errnum, const char *format, va_list args)
+{
+ verror_at_line (status, errnum, NULL, 0, format, args);
+}
+
+/* Print a message with 'vfprintf (stderr, FORMAT, ARGS)';
+ if ERRNUM is nonzero, follow it with ": " and strerror (ERRNUM).
+ If STATUS is nonzero, terminate the program with 'exit (STATUS)'.
+ If FNAME is not NULL, prepend the message with "FNAME:LINENO:".
+ Use the globals error_print_progname, error_message_count, and
+ error_one_per_line similarly to error_at_line(). */
+void
+verror_at_line (int status, int errnum, const char *file,
+ unsigned int line_number, const char *format, va_list args)
+{
+ char *message = xvasprintf (format, args);
+ if (message)
+ {
+ /* Until http://sourceware.org/bugzilla/show_bug.cgi?id=2997 is fixed,
+ glibc violates GNU Coding Standards when the file argument to
+ error_at_line is NULL. */
+ if (file)
+ error_at_line (status, errnum, file, line_number, "%s", message);
+ else
+ error (status, errnum, "%s", message);
+ }
+ else
+ {
+ /* EOVERFLOW, EINVAL, and EILSEQ from xvasprintf are signs of
+ serious programmer errors. */
+ error (0, errno, _("unable to display error message"));
+ abort ();
+ }
+ free (message);
+}
diff --git a/lib/verror.h b/lib/verror.h
new file mode 100644
index 0000000..6d5123a
--- /dev/null
+++ b/lib/verror.h
@@ -0,0 +1,54 @@
+/* Declaration for va_list error-reporting function
+ Copyright (C) 2006-2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _VERROR_H
+#define _VERROR_H 1
+
+#include <stdarg.h>
+
+#include "error.h" /* for _GL_ATTRIBUTE_FORMAT */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Print a message with 'vfprintf (stderr, FORMAT, ARGS)';
+ if ERRNUM is nonzero, follow it with ": " and strerror (ERRNUM).
+ If STATUS is nonzero, terminate the program with 'exit (STATUS)'.
+ Use the globals error_print_progname and error_message_count similarly
+ to error(). */
+
+extern void verror (int __status, int __errnum, const char *__format,
+ va_list __args)
+ _GL_ATTRIBUTE_FORMAT ((__printf__, 3, 0));
+
+/* Print a message with 'vfprintf (stderr, FORMAT, ARGS)';
+ if ERRNUM is nonzero, follow it with ": " and strerror (ERRNUM).
+ If STATUS is nonzero, terminate the program with 'exit (STATUS)'.
+ If FNAME is not NULL, prepend the message with "FNAME:LINENO:".
+ Use the globals error_print_progname, error_message_count, and
+ error_one_per_line similarly to error_at_line(). */
+
+extern void verror_at_line (int __status, int __errnum, const char *__fname,
+ unsigned int __lineno, const char *__format,
+ va_list __args)
+ _GL_ATTRIBUTE_FORMAT ((__printf__, 5, 0));
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* verror.h */
diff --git a/lib/version-etc-fsf.c b/lib/version-etc-fsf.c
index f25eb65..baaebb6 100644
--- a/lib/version-etc-fsf.c
+++ b/lib/version-etc-fsf.c
@@ -1,10 +1,10 @@
/* Variable with FSF copyright information, for version-etc.
- Copyright (C) 1999-2006 Free Software Foundation, Inc.
+ Copyright (C) 1999-2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -12,8 +12,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Jim Meyering. */
diff --git a/lib/version-etc.c b/lib/version-etc.c
index 65997d9..a9a0fdb 100644
--- a/lib/version-etc.c
+++ b/lib/version-etc.c
@@ -1,10 +1,10 @@
-/* Utility to help print --version output in a consistent format.
- Copyright (C) 1999-2007 Free Software Foundation, Inc.
+/* Print --version and bug-reporting information in a consistent format.
+ Copyright (C) 1999-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -12,8 +12,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Jim Meyering. */
@@ -33,33 +32,52 @@
#include "gettext.h"
#define _(msgid) gettext (msgid)
-enum { COPYRIGHT_YEAR = 2007 };
+/* If you use AM_INIT_AUTOMAKE's no-define option,
+ PACKAGE is not defined. Use PACKAGE_TARNAME instead. */
+#if ! defined PACKAGE && defined PACKAGE_TARNAME
+# define PACKAGE PACKAGE_TARNAME
+#endif
-/* Like version_etc, below, but with the NULL-terminated author list
- provided via a variable of type va_list. */
-void
-version_etc_va (FILE *stream,
- const char *command_name, const char *package,
- const char *version, va_list authors)
-{
- size_t n_authors;
+enum { COPYRIGHT_YEAR = 2016 };
- /* Count the number of authors. */
- {
- va_list tmp_authors;
+/* The three functions below display the --version information the
+ standard way.
- va_copy (tmp_authors, authors);
+ If COMMAND_NAME is NULL, the PACKAGE is assumed to be the name of
+ the program. The formats are therefore:
- n_authors = 0;
- while (va_arg (tmp_authors, const char *) != NULL)
- ++n_authors;
- }
+ PACKAGE VERSION
+
+ or
+
+ COMMAND_NAME (PACKAGE) VERSION.
+ The functions differ in the way they are passed author names. */
+
+/* Display the --version information the standard way.
+
+ Author names are given in the array AUTHORS. N_AUTHORS is the
+ number of elements in the array. */
+void
+version_etc_arn (FILE *stream,
+ const char *command_name, const char *package,
+ const char *version,
+ const char * const * authors, size_t n_authors)
+{
if (command_name)
fprintf (stream, "%s (%s) %s\n", command_name, package, version);
else
fprintf (stream, "%s %s\n", package, version);
+#ifdef PACKAGE_PACKAGER
+# ifdef PACKAGE_PACKAGER_VERSION
+ fprintf (stream, _("Packaged by %s (%s)\n"), PACKAGE_PACKAGER,
+ PACKAGE_PACKAGER_VERSION);
+# else
+ fprintf (stream, _("Packaged by %s\n"), PACKAGE_PACKAGER);
+# endif
+#endif
+
/* TRANSLATORS: Translate "(C)" to the copyright symbol
(C-in-a-circle), if this symbol is available in the user's
locale. Otherwise, do not translate "(C)"; leave it as-is. */
@@ -67,12 +85,12 @@ version_etc_va (FILE *stream,
fputs (_("\
\n\
-This is free software. You may redistribute copies of it under the terms of\n\
-the GNU General Public License <http://www.gnu.org/licenses/gpl.html>.\n\
+License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\n\
+This is free software: you are free to change and redistribute it.\n\
There is NO WARRANTY, to the extent permitted by law.\n\
\n\
"),
- stream);
+ stream);
switch (n_authors)
{
@@ -81,76 +99,120 @@ There is NO WARRANTY, to the extent permitted by law.\n\
abort ();
case 1:
/* TRANSLATORS: %s denotes an author name. */
- vfprintf (stream, _("Written by %s.\n"), authors);
+ fprintf (stream, _("Written by %s.\n"), authors[0]);
break;
case 2:
/* TRANSLATORS: Each %s denotes an author name. */
- vfprintf (stream, _("Written by %s and %s.\n"), authors);
+ fprintf (stream, _("Written by %s and %s.\n"), authors[0], authors[1]);
break;
case 3:
/* TRANSLATORS: Each %s denotes an author name. */
- vfprintf (stream, _("Written by %s, %s, and %s.\n"), authors);
+ fprintf (stream, _("Written by %s, %s, and %s.\n"),
+ authors[0], authors[1], authors[2]);
break;
case 4:
/* TRANSLATORS: Each %s denotes an author name.
- You can use line breaks, estimating that each author name occupies
- ca. 16 screen columns and that a screen line has ca. 80 columns. */
- vfprintf (stream, _("Written by %s, %s, %s,\nand %s.\n"), authors);
+ You can use line breaks, estimating that each author name occupies
+ ca. 16 screen columns and that a screen line has ca. 80 columns. */
+ fprintf (stream, _("Written by %s, %s, %s,\nand %s.\n"),
+ authors[0], authors[1], authors[2], authors[3]);
break;
case 5:
/* TRANSLATORS: Each %s denotes an author name.
- You can use line breaks, estimating that each author name occupies
- ca. 16 screen columns and that a screen line has ca. 80 columns. */
- vfprintf (stream, _("Written by %s, %s, %s,\n%s, and %s.\n"), authors);
+ You can use line breaks, estimating that each author name occupies
+ ca. 16 screen columns and that a screen line has ca. 80 columns. */
+ fprintf (stream, _("Written by %s, %s, %s,\n%s, and %s.\n"),
+ authors[0], authors[1], authors[2], authors[3], authors[4]);
break;
case 6:
/* TRANSLATORS: Each %s denotes an author name.
- You can use line breaks, estimating that each author name occupies
- ca. 16 screen columns and that a screen line has ca. 80 columns. */
- vfprintf (stream, _("Written by %s, %s, %s,\n%s, %s, and %s.\n"),
- authors);
+ You can use line breaks, estimating that each author name occupies
+ ca. 16 screen columns and that a screen line has ca. 80 columns. */
+ fprintf (stream, _("Written by %s, %s, %s,\n%s, %s, and %s.\n"),
+ authors[0], authors[1], authors[2], authors[3], authors[4],
+ authors[5]);
break;
case 7:
/* TRANSLATORS: Each %s denotes an author name.
- You can use line breaks, estimating that each author name occupies
- ca. 16 screen columns and that a screen line has ca. 80 columns. */
- vfprintf (stream, _("Written by %s, %s, %s,\n%s, %s, %s, and %s.\n"),
- authors);
+ You can use line breaks, estimating that each author name occupies
+ ca. 16 screen columns and that a screen line has ca. 80 columns. */
+ fprintf (stream, _("Written by %s, %s, %s,\n%s, %s, %s, and %s.\n"),
+ authors[0], authors[1], authors[2], authors[3], authors[4],
+ authors[5], authors[6]);
break;
case 8:
/* TRANSLATORS: Each %s denotes an author name.
- You can use line breaks, estimating that each author name occupies
- ca. 16 screen columns and that a screen line has ca. 80 columns. */
- vfprintf (stream, _("\
+ You can use line breaks, estimating that each author name occupies
+ ca. 16 screen columns and that a screen line has ca. 80 columns. */
+ fprintf (stream, _("\
Written by %s, %s, %s,\n%s, %s, %s, %s,\nand %s.\n"),
- authors);
+ authors[0], authors[1], authors[2], authors[3], authors[4],
+ authors[5], authors[6], authors[7]);
break;
case 9:
/* TRANSLATORS: Each %s denotes an author name.
- You can use line breaks, estimating that each author name occupies
- ca. 16 screen columns and that a screen line has ca. 80 columns. */
- vfprintf (stream, _("\
+ You can use line breaks, estimating that each author name occupies
+ ca. 16 screen columns and that a screen line has ca. 80 columns. */
+ fprintf (stream, _("\
Written by %s, %s, %s,\n%s, %s, %s, %s,\n%s, and %s.\n"),
- authors);
+ authors[0], authors[1], authors[2], authors[3], authors[4],
+ authors[5], authors[6], authors[7], authors[8]);
break;
default:
/* 10 or more authors. Use an abbreviation, since the human reader
- will probably not want to read the entire list anyway. */
+ will probably not want to read the entire list anyway. */
/* TRANSLATORS: Each %s denotes an author name.
- You can use line breaks, estimating that each author name occupies
- ca. 16 screen columns and that a screen line has ca. 80 columns. */
- vfprintf (stream, _("\
+ You can use line breaks, estimating that each author name occupies
+ ca. 16 screen columns and that a screen line has ca. 80 columns. */
+ fprintf (stream, _("\
Written by %s, %s, %s,\n%s, %s, %s, %s,\n%s, %s, and others.\n"),
- authors);
+ authors[0], authors[1], authors[2], authors[3], authors[4],
+ authors[5], authors[6], authors[7], authors[8]);
break;
}
- va_end (authors);
+}
+
+/* Display the --version information the standard way. See the initial
+ comment to this module, for more information.
+
+ Author names are given in the NULL-terminated array AUTHORS. */
+void
+version_etc_ar (FILE *stream,
+ const char *command_name, const char *package,
+ const char *version, const char * const * authors)
+{
+ size_t n_authors;
+
+ for (n_authors = 0; authors[n_authors]; n_authors++)
+ ;
+ version_etc_arn (stream, command_name, package, version, authors, n_authors);
+}
+
+/* Display the --version information the standard way. See the initial
+ comment to this module, for more information.
+
+ Author names are given in the NULL-terminated va_list AUTHORS. */
+void
+version_etc_va (FILE *stream,
+ const char *command_name, const char *package,
+ const char *version, va_list authors)
+{
+ size_t n_authors;
+ const char *authtab[10];
+
+ for (n_authors = 0;
+ n_authors < 10
+ && (authtab[n_authors] = va_arg (authors, const char *)) != NULL;
+ n_authors++)
+ ;
+ version_etc_arn (stream, command_name, package, version,
+ authtab, n_authors);
}
/* Display the --version information the standard way.
- If COMMAND_NAME is NULL, the PACKAGE is asumed to be the name of
+ If COMMAND_NAME is NULL, the PACKAGE is assumed to be the name of
the program. The formats are therefore:
PACKAGE VERSION
@@ -159,15 +221,38 @@ Written by %s, %s, %s,\n%s, %s, %s, %s,\n%s, %s, and others.\n"),
COMMAND_NAME (PACKAGE) VERSION.
- The author names are passed as separate arguments, with an additional
+ The authors names are passed as separate arguments, with an additional
NULL argument at the end. */
void
version_etc (FILE *stream,
- const char *command_name, const char *package,
- const char *version, /* const char *author1, ...*/ ...)
+ const char *command_name, const char *package,
+ const char *version, /* const char *author1, ...*/ ...)
{
va_list authors;
va_start (authors, version);
version_etc_va (stream, command_name, package, version, authors);
+ va_end (authors);
+}
+
+void
+emit_bug_reporting_address (void)
+{
+ /* TRANSLATORS: The placeholder indicates the bug-reporting address
+ for this package. Please add _another line_ saying
+ "Report translation bugs to <...>\n" with the address for translation
+ bugs (typically your translation team's web or email address). */
+ printf (_("\nReport bugs to: %s\n"), PACKAGE_BUGREPORT);
+#ifdef PACKAGE_PACKAGER_BUG_REPORTS
+ printf (_("Report %s bugs to: %s\n"), PACKAGE_PACKAGER,
+ PACKAGE_PACKAGER_BUG_REPORTS);
+#endif
+#ifdef PACKAGE_URL
+ printf (_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
+#else
+ printf (_("%s home page: <http://www.gnu.org/software/%s/>\n"),
+ PACKAGE_NAME, PACKAGE);
+#endif
+ fputs (_("General help using GNU software: <http://www.gnu.org/gethelp/>\n"),
+ stdout);
}
diff --git a/lib/version-etc.h b/lib/version-etc.h
index 84da535..1a5f603 100644
--- a/lib/version-etc.h
+++ b/lib/version-etc.h
@@ -1,10 +1,10 @@
-/* Utility to help print --version output in a consistent format.
- Copyright (C) 1999, 2003, 2005 Free Software Foundation, Inc.
+/* Print --version and bug-reporting information in a consistent format.
+ Copyright (C) 1999, 2003, 2005, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -12,8 +12,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Jim Meyering. */
@@ -23,15 +22,57 @@
# include <stdarg.h>
# include <stdio.h>
+/* The 'sentinel' attribute was added in gcc 4.0. */
+#ifndef _GL_ATTRIBUTE_SENTINEL
+# if 4 <= __GNUC__
+# define _GL_ATTRIBUTE_SENTINEL __attribute__ ((__sentinel__))
+# else
+# define _GL_ATTRIBUTE_SENTINEL /* empty */
+# endif
+#endif
+
extern const char version_etc_copyright[];
+/* The three functions below display the --version information in the
+ standard way: command and package names, package version, followed
+ by a short GPLv3+ notice and a list of up to 10 author names.
+
+ If COMMAND_NAME is NULL, the PACKAGE is assumed to be the name of
+ the program. The formats are therefore:
+
+ PACKAGE VERSION
+
+ or
+
+ COMMAND_NAME (PACKAGE) VERSION.
+
+ The functions differ in the way they are passed author names: */
+
+/* N_AUTHORS names are supplied in array AUTHORS. */
+extern void version_etc_arn (FILE *stream,
+ const char *command_name, const char *package,
+ const char *version,
+ const char * const * authors, size_t n_authors);
+
+/* Names are passed in the NULL-terminated array AUTHORS. */
+extern void version_etc_ar (FILE *stream,
+ const char *command_name, const char *package,
+ const char *version, const char * const * authors);
+
+/* Names are passed in the NULL-terminated va_list. */
extern void version_etc_va (FILE *stream,
- const char *command_name, const char *package,
- const char *version, va_list authors);
+ const char *command_name, const char *package,
+ const char *version, va_list authors);
+/* Names are passed as separate arguments, with an additional
+ NULL argument at the end. */
extern void version_etc (FILE *stream,
- const char *command_name, const char *package,
- const char *version,
- /* const char *author1, ...*/ ...);
+ const char *command_name, const char *package,
+ const char *version,
+ /* const char *author1, ..., NULL */ ...)
+ _GL_ATTRIBUTE_SENTINEL;
+
+/* Display the usual "Report bugs to" stanza. */
+extern void emit_bug_reporting_address (void);
#endif /* VERSION_ETC_H */
diff --git a/lib/vfprintf.c b/lib/vfprintf.c
new file mode 100644
index 0000000..7701542
--- /dev/null
+++ b/lib/vfprintf.c
@@ -0,0 +1,74 @@
+/* Formatted output to a stream.
+ Copyright (C) 2004, 2006-2016 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 <http://www.gnu.org/licenses/>. */
+
+#if 1
+# include <config.h>
+#endif
+
+/* Specification. */
+#include <stdio.h>
+
+#include <errno.h>
+#include <limits.h>
+#include <stdarg.h>
+#include <stdlib.h>
+
+#include "fseterr.h"
+#include "vasnprintf.h"
+
+/* Print formatted output to the stream FP.
+ Return string length of formatted string. On error, return a negative
+ value. */
+int
+vfprintf (FILE *fp, const char *format, va_list args)
+{
+ char buf[2000];
+ char *output;
+ size_t len;
+ size_t lenbuf = sizeof (buf);
+
+ output = vasnprintf (buf, &lenbuf, format, args);
+ len = lenbuf;
+
+ if (!output)
+ {
+ fseterr (fp);
+ return -1;
+ }
+
+ if (fwrite (output, 1, len, fp) < len)
+ {
+ if (output != buf)
+ {
+ int saved_errno = errno;
+ free (output);
+ errno = saved_errno;
+ }
+ return -1;
+ }
+
+ if (output != buf)
+ free (output);
+
+ if (len > INT_MAX)
+ {
+ errno = EOVERFLOW;
+ fseterr (fp);
+ return -1;
+ }
+
+ return len;
+}
diff --git a/lib/vprintf.c b/lib/vprintf.c
new file mode 100644
index 0000000..ce96ef2
--- /dev/null
+++ b/lib/vprintf.c
@@ -0,0 +1,33 @@
+/* Formatted output to a stream.
+ Copyright (C) 2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+#if 1
+# include <config.h>
+#endif
+
+/* Specification. */
+#include <stdio.h>
+
+#include <stdarg.h>
+
+/* Print formatted output to standard output.
+ Return string length of formatted string. On error, return a negative
+ value. */
+int
+vprintf (const char *format, va_list args)
+{
+ return vfprintf (stdout, format, args);
+}
diff --git a/lib/w32sock.h b/lib/w32sock.h
new file mode 100644
index 0000000..c78b4bb
--- /dev/null
+++ b/lib/w32sock.h
@@ -0,0 +1,136 @@
+/* w32sock.h --- internal auxiliary functions for Windows socket functions
+
+ Copyright (C) 2008-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Paolo Bonzini */
+
+#include <errno.h>
+
+/* Get O_RDWR and O_BINARY. */
+#include <fcntl.h>
+
+/* Get _open_osfhandle(). */
+#include <io.h>
+
+/* Get _get_osfhandle(). */
+#include "msvc-nothrow.h"
+
+#define FD_TO_SOCKET(fd) ((SOCKET) _get_osfhandle ((fd)))
+#define SOCKET_TO_FD(fh) (_open_osfhandle ((intptr_t) (fh), O_RDWR | O_BINARY))
+
+static inline void
+set_winsock_errno (void)
+{
+ int err = WSAGetLastError ();
+
+ /* Map some WSAE* errors to the runtime library's error codes. */
+ switch (err)
+ {
+ case WSA_INVALID_HANDLE:
+ errno = EBADF;
+ break;
+ case WSA_NOT_ENOUGH_MEMORY:
+ errno = ENOMEM;
+ break;
+ case WSA_INVALID_PARAMETER:
+ errno = EINVAL;
+ break;
+ case WSAENAMETOOLONG:
+ errno = ENAMETOOLONG;
+ break;
+ case WSAENOTEMPTY:
+ errno = ENOTEMPTY;
+ break;
+ case WSAEWOULDBLOCK:
+ errno = EWOULDBLOCK;
+ break;
+ case WSAEINPROGRESS:
+ errno = EINPROGRESS;
+ break;
+ case WSAEALREADY:
+ errno = EALREADY;
+ break;
+ case WSAENOTSOCK:
+ errno = ENOTSOCK;
+ break;
+ case WSAEDESTADDRREQ:
+ errno = EDESTADDRREQ;
+ break;
+ case WSAEMSGSIZE:
+ errno = EMSGSIZE;
+ break;
+ case WSAEPROTOTYPE:
+ errno = EPROTOTYPE;
+ break;
+ case WSAENOPROTOOPT:
+ errno = ENOPROTOOPT;
+ break;
+ case WSAEPROTONOSUPPORT:
+ errno = EPROTONOSUPPORT;
+ break;
+ case WSAEOPNOTSUPP:
+ errno = EOPNOTSUPP;
+ break;
+ case WSAEAFNOSUPPORT:
+ errno = EAFNOSUPPORT;
+ break;
+ case WSAEADDRINUSE:
+ errno = EADDRINUSE;
+ break;
+ case WSAEADDRNOTAVAIL:
+ errno = EADDRNOTAVAIL;
+ break;
+ case WSAENETDOWN:
+ errno = ENETDOWN;
+ break;
+ case WSAENETUNREACH:
+ errno = ENETUNREACH;
+ break;
+ case WSAENETRESET:
+ errno = ENETRESET;
+ break;
+ case WSAECONNABORTED:
+ errno = ECONNABORTED;
+ break;
+ case WSAECONNRESET:
+ errno = ECONNRESET;
+ break;
+ case WSAENOBUFS:
+ errno = ENOBUFS;
+ break;
+ case WSAEISCONN:
+ errno = EISCONN;
+ break;
+ case WSAENOTCONN:
+ errno = ENOTCONN;
+ break;
+ case WSAETIMEDOUT:
+ errno = ETIMEDOUT;
+ break;
+ case WSAECONNREFUSED:
+ errno = ECONNREFUSED;
+ break;
+ case WSAELOOP:
+ errno = ELOOP;
+ break;
+ case WSAEHOSTUNREACH:
+ errno = EHOSTUNREACH;
+ break;
+ default:
+ errno = (err > 10000 && err < 10025) ? err - 10000 : err;
+ break;
+ }
+}
diff --git a/lib/wchar.in.h b/lib/wchar.in.h
new file mode 100644
index 0000000..755600f
--- /dev/null
+++ b/lib/wchar.in.h
@@ -0,0 +1,1038 @@
+/* A substitute for ISO C99 <wchar.h>, for platforms that have issues.
+
+ Copyright (C) 2007-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Eric Blake. */
+
+/*
+ * ISO C 99 <wchar.h> for platforms that have issues.
+ * <http://www.opengroup.org/susv3xbd/wchar.h.html>
+ *
+ * For now, this just ensures proper prerequisite inclusion order and
+ * the declaration of wcwidth().
+ */
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+#if (((defined __need_mbstate_t || defined __need_wint_t) \
+ && !defined __MINGW32__ && !defined __KLIBC__) \
+ || (defined __hpux \
+ && ((defined _INTTYPES_INCLUDED && !defined strtoimax) \
+ || defined _GL_JUST_INCLUDE_SYSTEM_WCHAR_H)) \
+ || defined _GL_ALREADY_INCLUDING_WCHAR_H)
+/* Special invocation convention:
+ - Inside glibc and uClibc header files, but not MinGW.
+ - On HP-UX 11.00 we have a sequence of nested includes
+ <wchar.h> -> <stdlib.h> -> <stdint.h>, and the latter includes <wchar.h>,
+ once indirectly <stdint.h> -> <sys/types.h> -> <inttypes.h> -> <wchar.h>
+ and once directly. In both situations 'wint_t' is not yet defined,
+ therefore we cannot provide the function overrides; instead include only
+ the system's <wchar.h>.
+ - On IRIX 6.5, similarly, we have an include <wchar.h> -> <wctype.h>, and
+ the latter includes <wchar.h>. But here, we have no way to detect whether
+ <wctype.h> is completely included or is still being included. */
+
+#@INCLUDE_NEXT@ @NEXT_WCHAR_H@
+
+#else
+/* Normal invocation convention. */
+
+#ifndef _@GUARD_PREFIX@_WCHAR_H
+
+#define _GL_ALREADY_INCLUDING_WCHAR_H
+
+#if @HAVE_FEATURES_H@
+# include <features.h> /* for __GLIBC__ */
+#endif
+
+/* Tru64 with Desktop Toolkit C has a bug: <stdio.h> must be included before
+ <wchar.h>.
+ BSD/OS 4.0.1 has a bug: <stddef.h>, <stdio.h> and <time.h> must be
+ included before <wchar.h>.
+ In some builds of uClibc, <wchar.h> is nonexistent and wchar_t is defined
+ by <stddef.h>.
+ But avoid namespace pollution on glibc systems. */
+#if !(defined __GLIBC__ && !defined __UCLIBC__)
+# include <stddef.h>
+#endif
+#ifndef __GLIBC__
+# include <stdio.h>
+# include <time.h>
+#endif
+
+/* Include the original <wchar.h> if it exists.
+ Some builds of uClibc lack it. */
+/* The include_next requires a split double-inclusion guard. */
+#if @HAVE_WCHAR_H@
+# @INCLUDE_NEXT@ @NEXT_WCHAR_H@
+#endif
+
+#undef _GL_ALREADY_INCLUDING_WCHAR_H
+
+#ifndef _@GUARD_PREFIX@_WCHAR_H
+#define _@GUARD_PREFIX@_WCHAR_H
+
+/* The __attribute__ feature is available in gcc versions 2.5 and later.
+ The attribute __pure__ was added in gcc 2.96. */
+#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96)
+# define _GL_ATTRIBUTE_PURE __attribute__ ((__pure__))
+#else
+# define _GL_ATTRIBUTE_PURE /* empty */
+#endif
+
+/* The definitions of _GL_FUNCDECL_RPL etc. are copied here. */
+
+/* The definition of _GL_ARG_NONNULL is copied here. */
+
+/* The definition of _GL_WARN_ON_USE is copied here. */
+
+
+/* Define wint_t and WEOF. (Also done in wctype.in.h.) */
+#if !@HAVE_WINT_T@ && !defined wint_t
+# define wint_t int
+# ifndef WEOF
+# define WEOF -1
+# endif
+#else
+/* MSVC defines wint_t as 'unsigned short' in <crtdefs.h>.
+ This is too small: ISO C 99 section 7.24.1.(2) says that wint_t must be
+ "unchanged by default argument promotions". Override it. */
+# if defined _MSC_VER
+# if !GNULIB_defined_wint_t
+# include <crtdefs.h>
+typedef unsigned int rpl_wint_t;
+# undef wint_t
+# define wint_t rpl_wint_t
+# define GNULIB_defined_wint_t 1
+# endif
+# endif
+# ifndef WEOF
+# define WEOF ((wint_t) -1)
+# endif
+#endif
+
+
+/* Override mbstate_t if it is too small.
+ On IRIX 6.5, sizeof (mbstate_t) == 1, which is not sufficient for
+ implementing mbrtowc for encodings like UTF-8. */
+#if !(@HAVE_MBSINIT@ && @HAVE_MBRTOWC@) || @REPLACE_MBSTATE_T@
+# if !GNULIB_defined_mbstate_t
+typedef int rpl_mbstate_t;
+# undef mbstate_t
+# define mbstate_t rpl_mbstate_t
+# define GNULIB_defined_mbstate_t 1
+# endif
+#endif
+
+
+/* Convert a single-byte character to a wide character. */
+#if @GNULIB_BTOWC@
+# if @REPLACE_BTOWC@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef btowc
+# define btowc rpl_btowc
+# endif
+_GL_FUNCDECL_RPL (btowc, wint_t, (int c) _GL_ATTRIBUTE_PURE);
+_GL_CXXALIAS_RPL (btowc, wint_t, (int c));
+# else
+# if !@HAVE_BTOWC@
+_GL_FUNCDECL_SYS (btowc, wint_t, (int c) _GL_ATTRIBUTE_PURE);
+# endif
+_GL_CXXALIAS_SYS (btowc, wint_t, (int c));
+# endif
+_GL_CXXALIASWARN (btowc);
+#elif defined GNULIB_POSIXCHECK
+# undef btowc
+# if HAVE_RAW_DECL_BTOWC
+_GL_WARN_ON_USE (btowc, "btowc is unportable - "
+ "use gnulib module btowc for portability");
+# endif
+#endif
+
+
+/* Convert a wide character to a single-byte character. */
+#if @GNULIB_WCTOB@
+# if @REPLACE_WCTOB@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef wctob
+# define wctob rpl_wctob
+# endif
+_GL_FUNCDECL_RPL (wctob, int, (wint_t wc) _GL_ATTRIBUTE_PURE);
+_GL_CXXALIAS_RPL (wctob, int, (wint_t wc));
+# else
+# if !defined wctob && !@HAVE_DECL_WCTOB@
+/* wctob is provided by gnulib, or wctob exists but is not declared. */
+_GL_FUNCDECL_SYS (wctob, int, (wint_t wc) _GL_ATTRIBUTE_PURE);
+# endif
+_GL_CXXALIAS_SYS (wctob, int, (wint_t wc));
+# endif
+_GL_CXXALIASWARN (wctob);
+#elif defined GNULIB_POSIXCHECK
+# undef wctob
+# if HAVE_RAW_DECL_WCTOB
+_GL_WARN_ON_USE (wctob, "wctob is unportable - "
+ "use gnulib module wctob for portability");
+# endif
+#endif
+
+
+/* Test whether *PS is in the initial state. */
+#if @GNULIB_MBSINIT@
+# if @REPLACE_MBSINIT@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef mbsinit
+# define mbsinit rpl_mbsinit
+# endif
+_GL_FUNCDECL_RPL (mbsinit, int, (const mbstate_t *ps));
+_GL_CXXALIAS_RPL (mbsinit, int, (const mbstate_t *ps));
+# else
+# if !@HAVE_MBSINIT@
+_GL_FUNCDECL_SYS (mbsinit, int, (const mbstate_t *ps));
+# endif
+_GL_CXXALIAS_SYS (mbsinit, int, (const mbstate_t *ps));
+# endif
+_GL_CXXALIASWARN (mbsinit);
+#elif defined GNULIB_POSIXCHECK
+# undef mbsinit
+# if HAVE_RAW_DECL_MBSINIT
+_GL_WARN_ON_USE (mbsinit, "mbsinit is unportable - "
+ "use gnulib module mbsinit for portability");
+# endif
+#endif
+
+
+/* Convert a multibyte character to a wide character. */
+#if @GNULIB_MBRTOWC@
+# if @REPLACE_MBRTOWC@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef mbrtowc
+# define mbrtowc rpl_mbrtowc
+# endif
+_GL_FUNCDECL_RPL (mbrtowc, size_t,
+ (wchar_t *pwc, const char *s, size_t n, mbstate_t *ps));
+_GL_CXXALIAS_RPL (mbrtowc, size_t,
+ (wchar_t *pwc, const char *s, size_t n, mbstate_t *ps));
+# else
+# if !@HAVE_MBRTOWC@
+_GL_FUNCDECL_SYS (mbrtowc, size_t,
+ (wchar_t *pwc, const char *s, size_t n, mbstate_t *ps));
+# endif
+_GL_CXXALIAS_SYS (mbrtowc, size_t,
+ (wchar_t *pwc, const char *s, size_t n, mbstate_t *ps));
+# endif
+_GL_CXXALIASWARN (mbrtowc);
+#elif defined GNULIB_POSIXCHECK
+# undef mbrtowc
+# if HAVE_RAW_DECL_MBRTOWC
+_GL_WARN_ON_USE (mbrtowc, "mbrtowc is unportable - "
+ "use gnulib module mbrtowc for portability");
+# endif
+#endif
+
+
+/* Recognize a multibyte character. */
+#if @GNULIB_MBRLEN@
+# if @REPLACE_MBRLEN@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef mbrlen
+# define mbrlen rpl_mbrlen
+# endif
+_GL_FUNCDECL_RPL (mbrlen, size_t, (const char *s, size_t n, mbstate_t *ps));
+_GL_CXXALIAS_RPL (mbrlen, size_t, (const char *s, size_t n, mbstate_t *ps));
+# else
+# if !@HAVE_MBRLEN@
+_GL_FUNCDECL_SYS (mbrlen, size_t, (const char *s, size_t n, mbstate_t *ps));
+# endif
+_GL_CXXALIAS_SYS (mbrlen, size_t, (const char *s, size_t n, mbstate_t *ps));
+# endif
+_GL_CXXALIASWARN (mbrlen);
+#elif defined GNULIB_POSIXCHECK
+# undef mbrlen
+# if HAVE_RAW_DECL_MBRLEN
+_GL_WARN_ON_USE (mbrlen, "mbrlen is unportable - "
+ "use gnulib module mbrlen for portability");
+# endif
+#endif
+
+
+/* Convert a string to a wide string. */
+#if @GNULIB_MBSRTOWCS@
+# if @REPLACE_MBSRTOWCS@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef mbsrtowcs
+# define mbsrtowcs rpl_mbsrtowcs
+# endif
+_GL_FUNCDECL_RPL (mbsrtowcs, size_t,
+ (wchar_t *dest, const char **srcp, size_t len, mbstate_t *ps)
+ _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_RPL (mbsrtowcs, size_t,
+ (wchar_t *dest, const char **srcp, size_t len,
+ mbstate_t *ps));
+# else
+# if !@HAVE_MBSRTOWCS@
+_GL_FUNCDECL_SYS (mbsrtowcs, size_t,
+ (wchar_t *dest, const char **srcp, size_t len, mbstate_t *ps)
+ _GL_ARG_NONNULL ((2)));
+# endif
+_GL_CXXALIAS_SYS (mbsrtowcs, size_t,
+ (wchar_t *dest, const char **srcp, size_t len,
+ mbstate_t *ps));
+# endif
+_GL_CXXALIASWARN (mbsrtowcs);
+#elif defined GNULIB_POSIXCHECK
+# undef mbsrtowcs
+# if HAVE_RAW_DECL_MBSRTOWCS
+_GL_WARN_ON_USE (mbsrtowcs, "mbsrtowcs is unportable - "
+ "use gnulib module mbsrtowcs for portability");
+# endif
+#endif
+
+
+/* Convert a string to a wide string. */
+#if @GNULIB_MBSNRTOWCS@
+# if @REPLACE_MBSNRTOWCS@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef mbsnrtowcs
+# define mbsnrtowcs rpl_mbsnrtowcs
+# endif
+_GL_FUNCDECL_RPL (mbsnrtowcs, size_t,
+ (wchar_t *dest, const char **srcp, size_t srclen, size_t len,
+ mbstate_t *ps)
+ _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_RPL (mbsnrtowcs, size_t,
+ (wchar_t *dest, const char **srcp, size_t srclen, size_t len,
+ mbstate_t *ps));
+# else
+# if !@HAVE_MBSNRTOWCS@
+_GL_FUNCDECL_SYS (mbsnrtowcs, size_t,
+ (wchar_t *dest, const char **srcp, size_t srclen, size_t len,
+ mbstate_t *ps)
+ _GL_ARG_NONNULL ((2)));
+# endif
+_GL_CXXALIAS_SYS (mbsnrtowcs, size_t,
+ (wchar_t *dest, const char **srcp, size_t srclen, size_t len,
+ mbstate_t *ps));
+# endif
+_GL_CXXALIASWARN (mbsnrtowcs);
+#elif defined GNULIB_POSIXCHECK
+# undef mbsnrtowcs
+# if HAVE_RAW_DECL_MBSNRTOWCS
+_GL_WARN_ON_USE (mbsnrtowcs, "mbsnrtowcs is unportable - "
+ "use gnulib module mbsnrtowcs for portability");
+# endif
+#endif
+
+
+/* Convert a wide character to a multibyte character. */
+#if @GNULIB_WCRTOMB@
+# if @REPLACE_WCRTOMB@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef wcrtomb
+# define wcrtomb rpl_wcrtomb
+# endif
+_GL_FUNCDECL_RPL (wcrtomb, size_t, (char *s, wchar_t wc, mbstate_t *ps));
+_GL_CXXALIAS_RPL (wcrtomb, size_t, (char *s, wchar_t wc, mbstate_t *ps));
+# else
+# if !@HAVE_WCRTOMB@
+_GL_FUNCDECL_SYS (wcrtomb, size_t, (char *s, wchar_t wc, mbstate_t *ps));
+# endif
+_GL_CXXALIAS_SYS (wcrtomb, size_t, (char *s, wchar_t wc, mbstate_t *ps));
+# endif
+_GL_CXXALIASWARN (wcrtomb);
+#elif defined GNULIB_POSIXCHECK
+# undef wcrtomb
+# if HAVE_RAW_DECL_WCRTOMB
+_GL_WARN_ON_USE (wcrtomb, "wcrtomb is unportable - "
+ "use gnulib module wcrtomb for portability");
+# endif
+#endif
+
+
+/* Convert a wide string to a string. */
+#if @GNULIB_WCSRTOMBS@
+# if @REPLACE_WCSRTOMBS@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef wcsrtombs
+# define wcsrtombs rpl_wcsrtombs
+# endif
+_GL_FUNCDECL_RPL (wcsrtombs, size_t,
+ (char *dest, const wchar_t **srcp, size_t len, mbstate_t *ps)
+ _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_RPL (wcsrtombs, size_t,
+ (char *dest, const wchar_t **srcp, size_t len,
+ mbstate_t *ps));
+# else
+# if !@HAVE_WCSRTOMBS@
+_GL_FUNCDECL_SYS (wcsrtombs, size_t,
+ (char *dest, const wchar_t **srcp, size_t len, mbstate_t *ps)
+ _GL_ARG_NONNULL ((2)));
+# endif
+_GL_CXXALIAS_SYS (wcsrtombs, size_t,
+ (char *dest, const wchar_t **srcp, size_t len,
+ mbstate_t *ps));
+# endif
+_GL_CXXALIASWARN (wcsrtombs);
+#elif defined GNULIB_POSIXCHECK
+# undef wcsrtombs
+# if HAVE_RAW_DECL_WCSRTOMBS
+_GL_WARN_ON_USE (wcsrtombs, "wcsrtombs is unportable - "
+ "use gnulib module wcsrtombs for portability");
+# endif
+#endif
+
+
+/* Convert a wide string to a string. */
+#if @GNULIB_WCSNRTOMBS@
+# if @REPLACE_WCSNRTOMBS@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef wcsnrtombs
+# define wcsnrtombs rpl_wcsnrtombs
+# endif
+_GL_FUNCDECL_RPL (wcsnrtombs, size_t,
+ (char *dest, const wchar_t **srcp, size_t srclen, size_t len,
+ mbstate_t *ps)
+ _GL_ARG_NONNULL ((2)));
+_GL_CXXALIAS_RPL (wcsnrtombs, size_t,
+ (char *dest, const wchar_t **srcp, size_t srclen, size_t len,
+ mbstate_t *ps));
+# else
+# if !@HAVE_WCSNRTOMBS@
+_GL_FUNCDECL_SYS (wcsnrtombs, size_t,
+ (char *dest, const wchar_t **srcp, size_t srclen, size_t len,
+ mbstate_t *ps)
+ _GL_ARG_NONNULL ((2)));
+# endif
+_GL_CXXALIAS_SYS (wcsnrtombs, size_t,
+ (char *dest, const wchar_t **srcp, size_t srclen, size_t len,
+ mbstate_t *ps));
+# endif
+_GL_CXXALIASWARN (wcsnrtombs);
+#elif defined GNULIB_POSIXCHECK
+# undef wcsnrtombs
+# if HAVE_RAW_DECL_WCSNRTOMBS
+_GL_WARN_ON_USE (wcsnrtombs, "wcsnrtombs is unportable - "
+ "use gnulib module wcsnrtombs for portability");
+# endif
+#endif
+
+
+/* Return the number of screen columns needed for WC. */
+#if @GNULIB_WCWIDTH@
+# if @REPLACE_WCWIDTH@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef wcwidth
+# define wcwidth rpl_wcwidth
+# endif
+_GL_FUNCDECL_RPL (wcwidth, int, (wchar_t) _GL_ATTRIBUTE_PURE);
+_GL_CXXALIAS_RPL (wcwidth, int, (wchar_t));
+# else
+# if !@HAVE_DECL_WCWIDTH@
+/* wcwidth exists but is not declared. */
+_GL_FUNCDECL_SYS (wcwidth, int, (wchar_t) _GL_ATTRIBUTE_PURE);
+# elif defined __KLIBC__
+/* On OS/2 kLIBC, wcwidth is a macro that expands to the name of a
+ static inline function. The implementation of wcwidth in wcwidth.c
+ causes a "conflicting types" error. */
+# undef wcwidth
+# endif
+_GL_CXXALIAS_SYS (wcwidth, int, (wchar_t));
+# endif
+_GL_CXXALIASWARN (wcwidth);
+#elif defined GNULIB_POSIXCHECK
+# undef wcwidth
+# if HAVE_RAW_DECL_WCWIDTH
+_GL_WARN_ON_USE (wcwidth, "wcwidth is unportable - "
+ "use gnulib module wcwidth for portability");
+# endif
+#endif
+
+
+/* Search N wide characters of S for C. */
+#if @GNULIB_WMEMCHR@
+# if !@HAVE_WMEMCHR@
+_GL_FUNCDECL_SYS (wmemchr, wchar_t *, (const wchar_t *s, wchar_t c, size_t n)
+ _GL_ATTRIBUTE_PURE);
+# endif
+ /* On some systems, this function is defined as an overloaded function:
+ extern "C++" {
+ const wchar_t * std::wmemchr (const wchar_t *, wchar_t, size_t);
+ wchar_t * std::wmemchr (wchar_t *, wchar_t, size_t);
+ } */
+_GL_CXXALIAS_SYS_CAST2 (wmemchr,
+ wchar_t *, (const wchar_t *, wchar_t, size_t),
+ const wchar_t *, (const wchar_t *, wchar_t, size_t));
+# if ((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 10) && !defined __UCLIBC__) \
+ && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4))
+_GL_CXXALIASWARN1 (wmemchr, wchar_t *, (wchar_t *s, wchar_t c, size_t n));
+_GL_CXXALIASWARN1 (wmemchr, const wchar_t *,
+ (const wchar_t *s, wchar_t c, size_t n));
+# else
+_GL_CXXALIASWARN (wmemchr);
+# endif
+#elif defined GNULIB_POSIXCHECK
+# undef wmemchr
+# if HAVE_RAW_DECL_WMEMCHR
+_GL_WARN_ON_USE (wmemchr, "wmemchr is unportable - "
+ "use gnulib module wmemchr for portability");
+# endif
+#endif
+
+
+/* Compare N wide characters of S1 and S2. */
+#if @GNULIB_WMEMCMP@
+# if !@HAVE_WMEMCMP@
+_GL_FUNCDECL_SYS (wmemcmp, int,
+ (const wchar_t *s1, const wchar_t *s2, size_t n)
+ _GL_ATTRIBUTE_PURE);
+# endif
+_GL_CXXALIAS_SYS (wmemcmp, int,
+ (const wchar_t *s1, const wchar_t *s2, size_t n));
+_GL_CXXALIASWARN (wmemcmp);
+#elif defined GNULIB_POSIXCHECK
+# undef wmemcmp
+# if HAVE_RAW_DECL_WMEMCMP
+_GL_WARN_ON_USE (wmemcmp, "wmemcmp is unportable - "
+ "use gnulib module wmemcmp for portability");
+# endif
+#endif
+
+
+/* Copy N wide characters of SRC to DEST. */
+#if @GNULIB_WMEMCPY@
+# if !@HAVE_WMEMCPY@
+_GL_FUNCDECL_SYS (wmemcpy, wchar_t *,
+ (wchar_t *dest, const wchar_t *src, size_t n));
+# endif
+_GL_CXXALIAS_SYS (wmemcpy, wchar_t *,
+ (wchar_t *dest, const wchar_t *src, size_t n));
+_GL_CXXALIASWARN (wmemcpy);
+#elif defined GNULIB_POSIXCHECK
+# undef wmemcpy
+# if HAVE_RAW_DECL_WMEMCPY
+_GL_WARN_ON_USE (wmemcpy, "wmemcpy is unportable - "
+ "use gnulib module wmemcpy for portability");
+# endif
+#endif
+
+
+/* Copy N wide characters of SRC to DEST, guaranteeing correct behavior for
+ overlapping memory areas. */
+#if @GNULIB_WMEMMOVE@
+# if !@HAVE_WMEMMOVE@
+_GL_FUNCDECL_SYS (wmemmove, wchar_t *,
+ (wchar_t *dest, const wchar_t *src, size_t n));
+# endif
+_GL_CXXALIAS_SYS (wmemmove, wchar_t *,
+ (wchar_t *dest, const wchar_t *src, size_t n));
+_GL_CXXALIASWARN (wmemmove);
+#elif defined GNULIB_POSIXCHECK
+# undef wmemmove
+# if HAVE_RAW_DECL_WMEMMOVE
+_GL_WARN_ON_USE (wmemmove, "wmemmove is unportable - "
+ "use gnulib module wmemmove for portability");
+# endif
+#endif
+
+
+/* Set N wide characters of S to C. */
+#if @GNULIB_WMEMSET@
+# if !@HAVE_WMEMSET@
+_GL_FUNCDECL_SYS (wmemset, wchar_t *, (wchar_t *s, wchar_t c, size_t n));
+# endif
+_GL_CXXALIAS_SYS (wmemset, wchar_t *, (wchar_t *s, wchar_t c, size_t n));
+_GL_CXXALIASWARN (wmemset);
+#elif defined GNULIB_POSIXCHECK
+# undef wmemset
+# if HAVE_RAW_DECL_WMEMSET
+_GL_WARN_ON_USE (wmemset, "wmemset is unportable - "
+ "use gnulib module wmemset for portability");
+# endif
+#endif
+
+
+/* Return the number of wide characters in S. */
+#if @GNULIB_WCSLEN@
+# if !@HAVE_WCSLEN@
+_GL_FUNCDECL_SYS (wcslen, size_t, (const wchar_t *s) _GL_ATTRIBUTE_PURE);
+# endif
+_GL_CXXALIAS_SYS (wcslen, size_t, (const wchar_t *s));
+_GL_CXXALIASWARN (wcslen);
+#elif defined GNULIB_POSIXCHECK
+# undef wcslen
+# if HAVE_RAW_DECL_WCSLEN
+_GL_WARN_ON_USE (wcslen, "wcslen is unportable - "
+ "use gnulib module wcslen for portability");
+# endif
+#endif
+
+
+/* Return the number of wide characters in S, but at most MAXLEN. */
+#if @GNULIB_WCSNLEN@
+# if !@HAVE_WCSNLEN@
+_GL_FUNCDECL_SYS (wcsnlen, size_t, (const wchar_t *s, size_t maxlen)
+ _GL_ATTRIBUTE_PURE);
+# endif
+_GL_CXXALIAS_SYS (wcsnlen, size_t, (const wchar_t *s, size_t maxlen));
+_GL_CXXALIASWARN (wcsnlen);
+#elif defined GNULIB_POSIXCHECK
+# undef wcsnlen
+# if HAVE_RAW_DECL_WCSNLEN
+_GL_WARN_ON_USE (wcsnlen, "wcsnlen is unportable - "
+ "use gnulib module wcsnlen for portability");
+# endif
+#endif
+
+
+/* Copy SRC to DEST. */
+#if @GNULIB_WCSCPY@
+# if !@HAVE_WCSCPY@
+_GL_FUNCDECL_SYS (wcscpy, wchar_t *, (wchar_t *dest, const wchar_t *src));
+# endif
+_GL_CXXALIAS_SYS (wcscpy, wchar_t *, (wchar_t *dest, const wchar_t *src));
+_GL_CXXALIASWARN (wcscpy);
+#elif defined GNULIB_POSIXCHECK
+# undef wcscpy
+# if HAVE_RAW_DECL_WCSCPY
+_GL_WARN_ON_USE (wcscpy, "wcscpy is unportable - "
+ "use gnulib module wcscpy for portability");
+# endif
+#endif
+
+
+/* Copy SRC to DEST, returning the address of the terminating L'\0' in DEST. */
+#if @GNULIB_WCPCPY@
+# if !@HAVE_WCPCPY@
+_GL_FUNCDECL_SYS (wcpcpy, wchar_t *, (wchar_t *dest, const wchar_t *src));
+# endif
+_GL_CXXALIAS_SYS (wcpcpy, wchar_t *, (wchar_t *dest, const wchar_t *src));
+_GL_CXXALIASWARN (wcpcpy);
+#elif defined GNULIB_POSIXCHECK
+# undef wcpcpy
+# if HAVE_RAW_DECL_WCPCPY
+_GL_WARN_ON_USE (wcpcpy, "wcpcpy is unportable - "
+ "use gnulib module wcpcpy for portability");
+# endif
+#endif
+
+
+/* Copy no more than N wide characters of SRC to DEST. */
+#if @GNULIB_WCSNCPY@
+# if !@HAVE_WCSNCPY@
+_GL_FUNCDECL_SYS (wcsncpy, wchar_t *,
+ (wchar_t *dest, const wchar_t *src, size_t n));
+# endif
+_GL_CXXALIAS_SYS (wcsncpy, wchar_t *,
+ (wchar_t *dest, const wchar_t *src, size_t n));
+_GL_CXXALIASWARN (wcsncpy);
+#elif defined GNULIB_POSIXCHECK
+# undef wcsncpy
+# if HAVE_RAW_DECL_WCSNCPY
+_GL_WARN_ON_USE (wcsncpy, "wcsncpy is unportable - "
+ "use gnulib module wcsncpy for portability");
+# endif
+#endif
+
+
+/* Copy no more than N characters of SRC to DEST, returning the address of
+ the last character written into DEST. */
+#if @GNULIB_WCPNCPY@
+# if !@HAVE_WCPNCPY@
+_GL_FUNCDECL_SYS (wcpncpy, wchar_t *,
+ (wchar_t *dest, const wchar_t *src, size_t n));
+# endif
+_GL_CXXALIAS_SYS (wcpncpy, wchar_t *,
+ (wchar_t *dest, const wchar_t *src, size_t n));
+_GL_CXXALIASWARN (wcpncpy);
+#elif defined GNULIB_POSIXCHECK
+# undef wcpncpy
+# if HAVE_RAW_DECL_WCPNCPY
+_GL_WARN_ON_USE (wcpncpy, "wcpncpy is unportable - "
+ "use gnulib module wcpncpy for portability");
+# endif
+#endif
+
+
+/* Append SRC onto DEST. */
+#if @GNULIB_WCSCAT@
+# if !@HAVE_WCSCAT@
+_GL_FUNCDECL_SYS (wcscat, wchar_t *, (wchar_t *dest, const wchar_t *src));
+# endif
+_GL_CXXALIAS_SYS (wcscat, wchar_t *, (wchar_t *dest, const wchar_t *src));
+_GL_CXXALIASWARN (wcscat);
+#elif defined GNULIB_POSIXCHECK
+# undef wcscat
+# if HAVE_RAW_DECL_WCSCAT
+_GL_WARN_ON_USE (wcscat, "wcscat is unportable - "
+ "use gnulib module wcscat for portability");
+# endif
+#endif
+
+
+/* Append no more than N wide characters of SRC onto DEST. */
+#if @GNULIB_WCSNCAT@
+# if !@HAVE_WCSNCAT@
+_GL_FUNCDECL_SYS (wcsncat, wchar_t *,
+ (wchar_t *dest, const wchar_t *src, size_t n));
+# endif
+_GL_CXXALIAS_SYS (wcsncat, wchar_t *,
+ (wchar_t *dest, const wchar_t *src, size_t n));
+_GL_CXXALIASWARN (wcsncat);
+#elif defined GNULIB_POSIXCHECK
+# undef wcsncat
+# if HAVE_RAW_DECL_WCSNCAT
+_GL_WARN_ON_USE (wcsncat, "wcsncat is unportable - "
+ "use gnulib module wcsncat for portability");
+# endif
+#endif
+
+
+/* Compare S1 and S2. */
+#if @GNULIB_WCSCMP@
+# if !@HAVE_WCSCMP@
+_GL_FUNCDECL_SYS (wcscmp, int, (const wchar_t *s1, const wchar_t *s2)
+ _GL_ATTRIBUTE_PURE);
+# endif
+_GL_CXXALIAS_SYS (wcscmp, int, (const wchar_t *s1, const wchar_t *s2));
+_GL_CXXALIASWARN (wcscmp);
+#elif defined GNULIB_POSIXCHECK
+# undef wcscmp
+# if HAVE_RAW_DECL_WCSCMP
+_GL_WARN_ON_USE (wcscmp, "wcscmp is unportable - "
+ "use gnulib module wcscmp for portability");
+# endif
+#endif
+
+
+/* Compare no more than N wide characters of S1 and S2. */
+#if @GNULIB_WCSNCMP@
+# if !@HAVE_WCSNCMP@
+_GL_FUNCDECL_SYS (wcsncmp, int,
+ (const wchar_t *s1, const wchar_t *s2, size_t n)
+ _GL_ATTRIBUTE_PURE);
+# endif
+_GL_CXXALIAS_SYS (wcsncmp, int,
+ (const wchar_t *s1, const wchar_t *s2, size_t n));
+_GL_CXXALIASWARN (wcsncmp);
+#elif defined GNULIB_POSIXCHECK
+# undef wcsncmp
+# if HAVE_RAW_DECL_WCSNCMP
+_GL_WARN_ON_USE (wcsncmp, "wcsncmp is unportable - "
+ "use gnulib module wcsncmp for portability");
+# endif
+#endif
+
+
+/* Compare S1 and S2, ignoring case. */
+#if @GNULIB_WCSCASECMP@
+# if !@HAVE_WCSCASECMP@
+_GL_FUNCDECL_SYS (wcscasecmp, int, (const wchar_t *s1, const wchar_t *s2)
+ _GL_ATTRIBUTE_PURE);
+# endif
+_GL_CXXALIAS_SYS (wcscasecmp, int, (const wchar_t *s1, const wchar_t *s2));
+_GL_CXXALIASWARN (wcscasecmp);
+#elif defined GNULIB_POSIXCHECK
+# undef wcscasecmp
+# if HAVE_RAW_DECL_WCSCASECMP
+_GL_WARN_ON_USE (wcscasecmp, "wcscasecmp is unportable - "
+ "use gnulib module wcscasecmp for portability");
+# endif
+#endif
+
+
+/* Compare no more than N chars of S1 and S2, ignoring case. */
+#if @GNULIB_WCSNCASECMP@
+# if !@HAVE_WCSNCASECMP@
+_GL_FUNCDECL_SYS (wcsncasecmp, int,
+ (const wchar_t *s1, const wchar_t *s2, size_t n)
+ _GL_ATTRIBUTE_PURE);
+# endif
+_GL_CXXALIAS_SYS (wcsncasecmp, int,
+ (const wchar_t *s1, const wchar_t *s2, size_t n));
+_GL_CXXALIASWARN (wcsncasecmp);
+#elif defined GNULIB_POSIXCHECK
+# undef wcsncasecmp
+# if HAVE_RAW_DECL_WCSNCASECMP
+_GL_WARN_ON_USE (wcsncasecmp, "wcsncasecmp is unportable - "
+ "use gnulib module wcsncasecmp for portability");
+# endif
+#endif
+
+
+/* Compare S1 and S2, both interpreted as appropriate to the LC_COLLATE
+ category of the current locale. */
+#if @GNULIB_WCSCOLL@
+# if !@HAVE_WCSCOLL@
+_GL_FUNCDECL_SYS (wcscoll, int, (const wchar_t *s1, const wchar_t *s2));
+# endif
+_GL_CXXALIAS_SYS (wcscoll, int, (const wchar_t *s1, const wchar_t *s2));
+_GL_CXXALIASWARN (wcscoll);
+#elif defined GNULIB_POSIXCHECK
+# undef wcscoll
+# if HAVE_RAW_DECL_WCSCOLL
+_GL_WARN_ON_USE (wcscoll, "wcscoll is unportable - "
+ "use gnulib module wcscoll for portability");
+# endif
+#endif
+
+
+/* Transform S2 into array pointed to by S1 such that if wcscmp is applied
+ to two transformed strings the result is the as applying 'wcscoll' to the
+ original strings. */
+#if @GNULIB_WCSXFRM@
+# if !@HAVE_WCSXFRM@
+_GL_FUNCDECL_SYS (wcsxfrm, size_t, (wchar_t *s1, const wchar_t *s2, size_t n));
+# endif
+_GL_CXXALIAS_SYS (wcsxfrm, size_t, (wchar_t *s1, const wchar_t *s2, size_t n));
+_GL_CXXALIASWARN (wcsxfrm);
+#elif defined GNULIB_POSIXCHECK
+# undef wcsxfrm
+# if HAVE_RAW_DECL_WCSXFRM
+_GL_WARN_ON_USE (wcsxfrm, "wcsxfrm is unportable - "
+ "use gnulib module wcsxfrm for portability");
+# endif
+#endif
+
+
+/* Duplicate S, returning an identical malloc'd string. */
+#if @GNULIB_WCSDUP@
+# if !@HAVE_WCSDUP@
+_GL_FUNCDECL_SYS (wcsdup, wchar_t *, (const wchar_t *s));
+# endif
+_GL_CXXALIAS_SYS (wcsdup, wchar_t *, (const wchar_t *s));
+_GL_CXXALIASWARN (wcsdup);
+#elif defined GNULIB_POSIXCHECK
+# undef wcsdup
+# if HAVE_RAW_DECL_WCSDUP
+_GL_WARN_ON_USE (wcsdup, "wcsdup is unportable - "
+ "use gnulib module wcsdup for portability");
+# endif
+#endif
+
+
+/* Find the first occurrence of WC in WCS. */
+#if @GNULIB_WCSCHR@
+# if !@HAVE_WCSCHR@
+_GL_FUNCDECL_SYS (wcschr, wchar_t *, (const wchar_t *wcs, wchar_t wc)
+ _GL_ATTRIBUTE_PURE);
+# endif
+ /* On some systems, this function is defined as an overloaded function:
+ extern "C++" {
+ const wchar_t * std::wcschr (const wchar_t *, wchar_t);
+ wchar_t * std::wcschr (wchar_t *, wchar_t);
+ } */
+_GL_CXXALIAS_SYS_CAST2 (wcschr,
+ wchar_t *, (const wchar_t *, wchar_t),
+ const wchar_t *, (const wchar_t *, wchar_t));
+# if ((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 10) && !defined __UCLIBC__) \
+ && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4))
+_GL_CXXALIASWARN1 (wcschr, wchar_t *, (wchar_t *wcs, wchar_t wc));
+_GL_CXXALIASWARN1 (wcschr, const wchar_t *, (const wchar_t *wcs, wchar_t wc));
+# else
+_GL_CXXALIASWARN (wcschr);
+# endif
+#elif defined GNULIB_POSIXCHECK
+# undef wcschr
+# if HAVE_RAW_DECL_WCSCHR
+_GL_WARN_ON_USE (wcschr, "wcschr is unportable - "
+ "use gnulib module wcschr for portability");
+# endif
+#endif
+
+
+/* Find the last occurrence of WC in WCS. */
+#if @GNULIB_WCSRCHR@
+# if !@HAVE_WCSRCHR@
+_GL_FUNCDECL_SYS (wcsrchr, wchar_t *, (const wchar_t *wcs, wchar_t wc)
+ _GL_ATTRIBUTE_PURE);
+# endif
+ /* On some systems, this function is defined as an overloaded function:
+ extern "C++" {
+ const wchar_t * std::wcsrchr (const wchar_t *, wchar_t);
+ wchar_t * std::wcsrchr (wchar_t *, wchar_t);
+ } */
+_GL_CXXALIAS_SYS_CAST2 (wcsrchr,
+ wchar_t *, (const wchar_t *, wchar_t),
+ const wchar_t *, (const wchar_t *, wchar_t));
+# if ((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 10) && !defined __UCLIBC__) \
+ && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4))
+_GL_CXXALIASWARN1 (wcsrchr, wchar_t *, (wchar_t *wcs, wchar_t wc));
+_GL_CXXALIASWARN1 (wcsrchr, const wchar_t *, (const wchar_t *wcs, wchar_t wc));
+# else
+_GL_CXXALIASWARN (wcsrchr);
+# endif
+#elif defined GNULIB_POSIXCHECK
+# undef wcsrchr
+# if HAVE_RAW_DECL_WCSRCHR
+_GL_WARN_ON_USE (wcsrchr, "wcsrchr is unportable - "
+ "use gnulib module wcsrchr for portability");
+# endif
+#endif
+
+
+/* Return the length of the initial segmet of WCS which consists entirely
+ of wide characters not in REJECT. */
+#if @GNULIB_WCSCSPN@
+# if !@HAVE_WCSCSPN@
+_GL_FUNCDECL_SYS (wcscspn, size_t, (const wchar_t *wcs, const wchar_t *reject)
+ _GL_ATTRIBUTE_PURE);
+# endif
+_GL_CXXALIAS_SYS (wcscspn, size_t, (const wchar_t *wcs, const wchar_t *reject));
+_GL_CXXALIASWARN (wcscspn);
+#elif defined GNULIB_POSIXCHECK
+# undef wcscspn
+# if HAVE_RAW_DECL_WCSCSPN
+_GL_WARN_ON_USE (wcscspn, "wcscspn is unportable - "
+ "use gnulib module wcscspn for portability");
+# endif
+#endif
+
+
+/* Return the length of the initial segmet of WCS which consists entirely
+ of wide characters in ACCEPT. */
+#if @GNULIB_WCSSPN@
+# if !@HAVE_WCSSPN@
+_GL_FUNCDECL_SYS (wcsspn, size_t, (const wchar_t *wcs, const wchar_t *accept)
+ _GL_ATTRIBUTE_PURE);
+# endif
+_GL_CXXALIAS_SYS (wcsspn, size_t, (const wchar_t *wcs, const wchar_t *accept));
+_GL_CXXALIASWARN (wcsspn);
+#elif defined GNULIB_POSIXCHECK
+# undef wcsspn
+# if HAVE_RAW_DECL_WCSSPN
+_GL_WARN_ON_USE (wcsspn, "wcsspn is unportable - "
+ "use gnulib module wcsspn for portability");
+# endif
+#endif
+
+
+/* Find the first occurrence in WCS of any character in ACCEPT. */
+#if @GNULIB_WCSPBRK@
+# if !@HAVE_WCSPBRK@
+_GL_FUNCDECL_SYS (wcspbrk, wchar_t *,
+ (const wchar_t *wcs, const wchar_t *accept)
+ _GL_ATTRIBUTE_PURE);
+# endif
+ /* On some systems, this function is defined as an overloaded function:
+ extern "C++" {
+ const wchar_t * std::wcspbrk (const wchar_t *, const wchar_t *);
+ wchar_t * std::wcspbrk (wchar_t *, const wchar_t *);
+ } */
+_GL_CXXALIAS_SYS_CAST2 (wcspbrk,
+ wchar_t *, (const wchar_t *, const wchar_t *),
+ const wchar_t *, (const wchar_t *, const wchar_t *));
+# if ((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 10) && !defined __UCLIBC__) \
+ && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4))
+_GL_CXXALIASWARN1 (wcspbrk, wchar_t *,
+ (wchar_t *wcs, const wchar_t *accept));
+_GL_CXXALIASWARN1 (wcspbrk, const wchar_t *,
+ (const wchar_t *wcs, const wchar_t *accept));
+# else
+_GL_CXXALIASWARN (wcspbrk);
+# endif
+#elif defined GNULIB_POSIXCHECK
+# undef wcspbrk
+# if HAVE_RAW_DECL_WCSPBRK
+_GL_WARN_ON_USE (wcspbrk, "wcspbrk is unportable - "
+ "use gnulib module wcspbrk for portability");
+# endif
+#endif
+
+
+/* Find the first occurrence of NEEDLE in HAYSTACK. */
+#if @GNULIB_WCSSTR@
+# if !@HAVE_WCSSTR@
+_GL_FUNCDECL_SYS (wcsstr, wchar_t *,
+ (const wchar_t *haystack, const wchar_t *needle)
+ _GL_ATTRIBUTE_PURE);
+# endif
+ /* On some systems, this function is defined as an overloaded function:
+ extern "C++" {
+ const wchar_t * std::wcsstr (const wchar_t *, const wchar_t *);
+ wchar_t * std::wcsstr (wchar_t *, const wchar_t *);
+ } */
+_GL_CXXALIAS_SYS_CAST2 (wcsstr,
+ wchar_t *, (const wchar_t *, const wchar_t *),
+ const wchar_t *, (const wchar_t *, const wchar_t *));
+# if ((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 10) && !defined __UCLIBC__) \
+ && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4))
+_GL_CXXALIASWARN1 (wcsstr, wchar_t *,
+ (wchar_t *haystack, const wchar_t *needle));
+_GL_CXXALIASWARN1 (wcsstr, const wchar_t *,
+ (const wchar_t *haystack, const wchar_t *needle));
+# else
+_GL_CXXALIASWARN (wcsstr);
+# endif
+#elif defined GNULIB_POSIXCHECK
+# undef wcsstr
+# if HAVE_RAW_DECL_WCSSTR
+_GL_WARN_ON_USE (wcsstr, "wcsstr is unportable - "
+ "use gnulib module wcsstr for portability");
+# endif
+#endif
+
+
+/* Divide WCS into tokens separated by characters in DELIM. */
+#if @GNULIB_WCSTOK@
+# if !@HAVE_WCSTOK@
+_GL_FUNCDECL_SYS (wcstok, wchar_t *,
+ (wchar_t *wcs, const wchar_t *delim, wchar_t **ptr));
+# endif
+_GL_CXXALIAS_SYS (wcstok, wchar_t *,
+ (wchar_t *wcs, const wchar_t *delim, wchar_t **ptr));
+_GL_CXXALIASWARN (wcstok);
+#elif defined GNULIB_POSIXCHECK
+# undef wcstok
+# if HAVE_RAW_DECL_WCSTOK
+_GL_WARN_ON_USE (wcstok, "wcstok is unportable - "
+ "use gnulib module wcstok for portability");
+# endif
+#endif
+
+
+/* Determine number of column positions required for first N wide
+ characters (or fewer if S ends before this) in S. */
+#if @GNULIB_WCSWIDTH@
+# if @REPLACE_WCSWIDTH@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# undef wcswidth
+# define wcswidth rpl_wcswidth
+# endif
+_GL_FUNCDECL_RPL (wcswidth, int, (const wchar_t *s, size_t n)
+ _GL_ATTRIBUTE_PURE);
+_GL_CXXALIAS_RPL (wcswidth, int, (const wchar_t *s, size_t n));
+# else
+# if !@HAVE_WCSWIDTH@
+_GL_FUNCDECL_SYS (wcswidth, int, (const wchar_t *s, size_t n)
+ _GL_ATTRIBUTE_PURE);
+# endif
+_GL_CXXALIAS_SYS (wcswidth, int, (const wchar_t *s, size_t n));
+# endif
+_GL_CXXALIASWARN (wcswidth);
+#elif defined GNULIB_POSIXCHECK
+# undef wcswidth
+# if HAVE_RAW_DECL_WCSWIDTH
+_GL_WARN_ON_USE (wcswidth, "wcswidth is unportable - "
+ "use gnulib module wcswidth for portability");
+# endif
+#endif
+
+
+#endif /* _@GUARD_PREFIX@_WCHAR_H */
+#endif /* _@GUARD_PREFIX@_WCHAR_H */
+#endif
diff --git a/lib/wchar_.h b/lib/wchar_.h
deleted file mode 100644
index 6813a21..0000000
--- a/lib/wchar_.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/* A substitute for ISO C99 <wchar.h>, for platforms that have issues.
-
- Copyright (C) 2007 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-/* Written by Eric Blake. */
-
-/*
- * ISO C 99 <wchar.h> for platforms that have issues.
- * <http://www.opengroup.org/susv3xbd/wchar.h.html>
- *
- * For now, this just ensures proper prerequisite inclusion order.
- */
-
-#ifndef _GL_WCHAR_H
-#define _GL_WCHAR_H
-
-/* Tru64 with Desktop Toolkit C has a bug: <stdio.h> must be included before
- <wchar.h>.
- BSD/OS 4.0.1 has a bug: <stddef.h>, <stdio.h> and <time.h> must be
- included before <wchar.h>. */
-#include <stddef.h>
-#include <stdio.h>
-#include <time.h>
-
-/* Include the original <wchar.h>. */
-#include @ABSOLUTE_WCHAR_H@
-
-#endif /* _GL_WCHAR_H */
diff --git a/lib/wcrtomb.c b/lib/wcrtomb.c
new file mode 100644
index 0000000..b931ee9
--- /dev/null
+++ b/lib/wcrtomb.c
@@ -0,0 +1,53 @@
+/* Convert wide character to multibyte character.
+ Copyright (C) 2008-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2008.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <wchar.h>
+
+#include <errno.h>
+#include <stdlib.h>
+
+
+size_t
+wcrtomb (char *s, wchar_t wc, mbstate_t *ps)
+{
+ /* This implementation of wcrtomb on top of wctomb() supports only
+ stateless encodings. ps must be in the initial state. */
+ if (ps != NULL && !mbsinit (ps))
+ {
+ errno = EINVAL;
+ return (size_t)(-1);
+ }
+
+ if (s == NULL)
+ /* We know the NUL wide character corresponds to the NUL character. */
+ return 1;
+ else
+ {
+ int ret = wctomb (s, wc);
+
+ if (ret >= 0)
+ return ret;
+ else
+ {
+ errno = EILSEQ;
+ return (size_t)(-1);
+ }
+ }
+}
diff --git a/lib/wcswidth-impl.h b/lib/wcswidth-impl.h
new file mode 100644
index 0000000..e023f24
--- /dev/null
+++ b/lib/wcswidth-impl.h
@@ -0,0 +1,43 @@
+/* Determine number of screen columns needed for a size-bounded wide string.
+ Copyright (C) 1999, 2011-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 1999.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+int
+wcswidth (const wchar_t *s, size_t n)
+{
+ int count = 0;
+ for (; n > 0; s++, n--)
+ {
+ wchar_t c = *s;
+ if (c == (wchar_t)'\0')
+ break;
+ {
+ int width = wcwidth (c);
+ if (width < 0)
+ goto found_nonprinting;
+ if (width > INT_MAX - count)
+ goto overflow;
+ count += width;
+ }
+ }
+ return count;
+
+ found_nonprinting:
+ return -1;
+
+ overflow:
+ return INT_MAX;
+}
diff --git a/lib/wcswidth.c b/lib/wcswidth.c
new file mode 100644
index 0000000..c3d2550
--- /dev/null
+++ b/lib/wcswidth.c
@@ -0,0 +1,25 @@
+/* Determine number of screen columns needed for a size-bounded wide string.
+ Copyright (C) 2011-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2011.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <wchar.h>
+
+#include <limits.h>
+
+#include "wcswidth-impl.h"
diff --git a/lib/wctype-h.c b/lib/wctype-h.c
new file mode 100644
index 0000000..bb5f847
--- /dev/null
+++ b/lib/wctype-h.c
@@ -0,0 +1,4 @@
+/* Normally this would be wctype.c, but that name's already taken. */
+#include <config.h>
+#define _GL_WCTYPE_INLINE _GL_EXTERN_INLINE
+#include "wctype.h"
diff --git a/lib/wctype.in.h b/lib/wctype.in.h
new file mode 100644
index 0000000..3431854
--- /dev/null
+++ b/lib/wctype.in.h
@@ -0,0 +1,514 @@
+/* A substitute for ISO C99 <wctype.h>, for platforms that lack it.
+
+ Copyright (C) 2006-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Bruno Haible and Paul Eggert. */
+
+/*
+ * ISO C 99 <wctype.h> for platforms that lack it.
+ * <http://www.opengroup.org/susv3xbd/wctype.h.html>
+ *
+ * iswctype, towctrans, towlower, towupper, wctrans, wctype,
+ * wctrans_t, and wctype_t are not yet implemented.
+ */
+
+#ifndef _@GUARD_PREFIX@_WCTYPE_H
+
+#if __GNUC__ >= 3
+@PRAGMA_SYSTEM_HEADER@
+#endif
+@PRAGMA_COLUMNS@
+
+#if @HAVE_WINT_T@
+/* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>.
+ Tru64 with Desktop Toolkit C has a bug: <stdio.h> must be included before
+ <wchar.h>.
+ BSD/OS 4.0.1 has a bug: <stddef.h>, <stdio.h> and <time.h> must be
+ included before <wchar.h>. */
+# include <stddef.h>
+# include <stdio.h>
+# include <time.h>
+# include <wchar.h>
+#endif
+
+/* mingw has declarations of towupper and towlower in <ctype.h> as
+ well <wctype.h>. Include <ctype.h> in advance to avoid rpl_ prefix
+ being added to the declarations. */
+#ifdef __MINGW32__
+# include <ctype.h>
+#endif
+
+/* Include the original <wctype.h> if it exists.
+ BeOS 5 has the functions but no <wctype.h>. */
+/* The include_next requires a split double-inclusion guard. */
+#if @HAVE_WCTYPE_H@
+# @INCLUDE_NEXT@ @NEXT_WCTYPE_H@
+#endif
+
+#ifndef _@GUARD_PREFIX@_WCTYPE_H
+#define _@GUARD_PREFIX@_WCTYPE_H
+
+#ifndef _GL_INLINE_HEADER_BEGIN
+ #error "Please include config.h first."
+#endif
+_GL_INLINE_HEADER_BEGIN
+#ifndef _GL_WCTYPE_INLINE
+# define _GL_WCTYPE_INLINE _GL_INLINE
+#endif
+
+/* The definitions of _GL_FUNCDECL_RPL etc. are copied here. */
+
+/* The definition of _GL_WARN_ON_USE is copied here. */
+
+/* Solaris 2.6 <wctype.h> includes <widec.h> which includes <euc.h> which
+ #defines a number of identifiers in the application namespace. Revert
+ these #defines. */
+#ifdef __sun
+# undef multibyte
+# undef eucw1
+# undef eucw2
+# undef eucw3
+# undef scrw1
+# undef scrw2
+# undef scrw3
+#endif
+
+/* Define wint_t and WEOF. (Also done in wchar.in.h.) */
+#if !@HAVE_WINT_T@ && !defined wint_t
+# define wint_t int
+# ifndef WEOF
+# define WEOF -1
+# endif
+#else
+/* MSVC defines wint_t as 'unsigned short' in <crtdefs.h>.
+ This is too small: ISO C 99 section 7.24.1.(2) says that wint_t must be
+ "unchanged by default argument promotions". Override it. */
+# if defined _MSC_VER
+# if !GNULIB_defined_wint_t
+# include <crtdefs.h>
+typedef unsigned int rpl_wint_t;
+# undef wint_t
+# define wint_t rpl_wint_t
+# define GNULIB_defined_wint_t 1
+# endif
+# endif
+# ifndef WEOF
+# define WEOF ((wint_t) -1)
+# endif
+#endif
+
+
+#if !GNULIB_defined_wctype_functions
+
+/* FreeBSD 4.4 to 4.11 has <wctype.h> but lacks the functions.
+ Linux libc5 has <wctype.h> and the functions but they are broken.
+ Assume all 11 functions (all isw* except iswblank) are implemented the
+ same way, or not at all. */
+# if ! @HAVE_ISWCNTRL@ || @REPLACE_ISWCNTRL@
+
+/* IRIX 5.3 has macros but no functions, its isw* macros refer to an
+ undefined variable _ctmp_ and to <ctype.h> macros like _P, and they
+ refer to system functions like _iswctype that are not in the
+ standard C library. Rather than try to get ancient buggy
+ implementations like this to work, just disable them. */
+# undef iswalnum
+# undef iswalpha
+# undef iswblank
+# undef iswcntrl
+# undef iswdigit
+# undef iswgraph
+# undef iswlower
+# undef iswprint
+# undef iswpunct
+# undef iswspace
+# undef iswupper
+# undef iswxdigit
+# undef towlower
+# undef towupper
+
+/* Linux libc5 has <wctype.h> and the functions but they are broken. */
+# if @REPLACE_ISWCNTRL@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define iswalnum rpl_iswalnum
+# define iswalpha rpl_iswalpha
+# define iswblank rpl_iswblank
+# define iswcntrl rpl_iswcntrl
+# define iswdigit rpl_iswdigit
+# define iswgraph rpl_iswgraph
+# define iswlower rpl_iswlower
+# define iswprint rpl_iswprint
+# define iswpunct rpl_iswpunct
+# define iswspace rpl_iswspace
+# define iswupper rpl_iswupper
+# define iswxdigit rpl_iswxdigit
+# endif
+# endif
+# if @REPLACE_TOWLOWER@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define towlower rpl_towlower
+# define towupper rpl_towupper
+# endif
+# endif
+
+_GL_WCTYPE_INLINE int
+# if @REPLACE_ISWCNTRL@
+rpl_iswalnum
+# else
+iswalnum
+# endif
+ (wint_t wc)
+{
+ return ((wc >= '0' && wc <= '9')
+ || ((wc & ~0x20) >= 'A' && (wc & ~0x20) <= 'Z'));
+}
+
+_GL_WCTYPE_INLINE int
+# if @REPLACE_ISWCNTRL@
+rpl_iswalpha
+# else
+iswalpha
+# endif
+ (wint_t wc)
+{
+ return (wc & ~0x20) >= 'A' && (wc & ~0x20) <= 'Z';
+}
+
+_GL_WCTYPE_INLINE int
+# if @REPLACE_ISWCNTRL@
+rpl_iswblank
+# else
+iswblank
+# endif
+ (wint_t wc)
+{
+ return wc == ' ' || wc == '\t';
+}
+
+_GL_WCTYPE_INLINE int
+# if @REPLACE_ISWCNTRL@
+rpl_iswcntrl
+# else
+iswcntrl
+# endif
+ (wint_t wc)
+{
+ return (wc & ~0x1f) == 0 || wc == 0x7f;
+}
+
+_GL_WCTYPE_INLINE int
+# if @REPLACE_ISWCNTRL@
+rpl_iswdigit
+# else
+iswdigit
+# endif
+ (wint_t wc)
+{
+ return wc >= '0' && wc <= '9';
+}
+
+_GL_WCTYPE_INLINE int
+# if @REPLACE_ISWCNTRL@
+rpl_iswgraph
+# else
+iswgraph
+# endif
+ (wint_t wc)
+{
+ return wc >= '!' && wc <= '~';
+}
+
+_GL_WCTYPE_INLINE int
+# if @REPLACE_ISWCNTRL@
+rpl_iswlower
+# else
+iswlower
+# endif
+ (wint_t wc)
+{
+ return wc >= 'a' && wc <= 'z';
+}
+
+_GL_WCTYPE_INLINE int
+# if @REPLACE_ISWCNTRL@
+rpl_iswprint
+# else
+iswprint
+# endif
+ (wint_t wc)
+{
+ return wc >= ' ' && wc <= '~';
+}
+
+_GL_WCTYPE_INLINE int
+# if @REPLACE_ISWCNTRL@
+rpl_iswpunct
+# else
+iswpunct
+# endif
+ (wint_t wc)
+{
+ return (wc >= '!' && wc <= '~'
+ && !((wc >= '0' && wc <= '9')
+ || ((wc & ~0x20) >= 'A' && (wc & ~0x20) <= 'Z')));
+}
+
+_GL_WCTYPE_INLINE int
+# if @REPLACE_ISWCNTRL@
+rpl_iswspace
+# else
+iswspace
+# endif
+ (wint_t wc)
+{
+ return (wc == ' ' || wc == '\t'
+ || wc == '\n' || wc == '\v' || wc == '\f' || wc == '\r');
+}
+
+_GL_WCTYPE_INLINE int
+# if @REPLACE_ISWCNTRL@
+rpl_iswupper
+# else
+iswupper
+# endif
+ (wint_t wc)
+{
+ return wc >= 'A' && wc <= 'Z';
+}
+
+_GL_WCTYPE_INLINE int
+# if @REPLACE_ISWCNTRL@
+rpl_iswxdigit
+# else
+iswxdigit
+# endif
+ (wint_t wc)
+{
+ return ((wc >= '0' && wc <= '9')
+ || ((wc & ~0x20) >= 'A' && (wc & ~0x20) <= 'F'));
+}
+
+_GL_WCTYPE_INLINE wint_t
+# if @REPLACE_TOWLOWER@
+rpl_towlower
+# else
+towlower
+# endif
+ (wint_t wc)
+{
+ return (wc >= 'A' && wc <= 'Z' ? wc - 'A' + 'a' : wc);
+}
+
+_GL_WCTYPE_INLINE wint_t
+# if @REPLACE_TOWLOWER@
+rpl_towupper
+# else
+towupper
+# endif
+ (wint_t wc)
+{
+ return (wc >= 'a' && wc <= 'z' ? wc - 'a' + 'A' : wc);
+}
+
+# elif @GNULIB_ISWBLANK@ && (! @HAVE_ISWBLANK@ || @REPLACE_ISWBLANK@)
+/* Only the iswblank function is missing. */
+
+# if @REPLACE_ISWBLANK@
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define iswblank rpl_iswblank
+# endif
+_GL_FUNCDECL_RPL (iswblank, int, (wint_t wc));
+# else
+_GL_FUNCDECL_SYS (iswblank, int, (wint_t wc));
+# endif
+
+# endif
+
+# if defined __MINGW32__
+
+/* On native Windows, wchar_t is uint16_t, and wint_t is uint32_t.
+ The functions towlower and towupper are implemented in the MSVCRT library
+ to take a wchar_t argument and return a wchar_t result. mingw declares
+ these functions to take a wint_t argument and return a wint_t result.
+ This means that:
+ 1. When the user passes an argument outside the range 0x0000..0xFFFF, the
+ function will look only at the lower 16 bits. This is allowed according
+ to POSIX.
+ 2. The return value is returned in the lower 16 bits of the result register.
+ The upper 16 bits are random: whatever happened to be in that part of the
+ result register. We need to fix this by adding a zero-extend from
+ wchar_t to wint_t after the call. */
+
+_GL_WCTYPE_INLINE wint_t
+rpl_towlower (wint_t wc)
+{
+ return (wint_t) (wchar_t) towlower (wc);
+}
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define towlower rpl_towlower
+# endif
+
+_GL_WCTYPE_INLINE wint_t
+rpl_towupper (wint_t wc)
+{
+ return (wint_t) (wchar_t) towupper (wc);
+}
+# if !(defined __cplusplus && defined GNULIB_NAMESPACE)
+# define towupper rpl_towupper
+# endif
+
+# endif /* __MINGW32__ */
+
+# define GNULIB_defined_wctype_functions 1
+#endif
+
+#if @REPLACE_ISWCNTRL@
+_GL_CXXALIAS_RPL (iswalnum, int, (wint_t wc));
+_GL_CXXALIAS_RPL (iswalpha, int, (wint_t wc));
+_GL_CXXALIAS_RPL (iswcntrl, int, (wint_t wc));
+_GL_CXXALIAS_RPL (iswdigit, int, (wint_t wc));
+_GL_CXXALIAS_RPL (iswgraph, int, (wint_t wc));
+_GL_CXXALIAS_RPL (iswlower, int, (wint_t wc));
+_GL_CXXALIAS_RPL (iswprint, int, (wint_t wc));
+_GL_CXXALIAS_RPL (iswpunct, int, (wint_t wc));
+_GL_CXXALIAS_RPL (iswspace, int, (wint_t wc));
+_GL_CXXALIAS_RPL (iswupper, int, (wint_t wc));
+_GL_CXXALIAS_RPL (iswxdigit, int, (wint_t wc));
+#else
+_GL_CXXALIAS_SYS (iswalnum, int, (wint_t wc));
+_GL_CXXALIAS_SYS (iswalpha, int, (wint_t wc));
+_GL_CXXALIAS_SYS (iswcntrl, int, (wint_t wc));
+_GL_CXXALIAS_SYS (iswdigit, int, (wint_t wc));
+_GL_CXXALIAS_SYS (iswgraph, int, (wint_t wc));
+_GL_CXXALIAS_SYS (iswlower, int, (wint_t wc));
+_GL_CXXALIAS_SYS (iswprint, int, (wint_t wc));
+_GL_CXXALIAS_SYS (iswpunct, int, (wint_t wc));
+_GL_CXXALIAS_SYS (iswspace, int, (wint_t wc));
+_GL_CXXALIAS_SYS (iswupper, int, (wint_t wc));
+_GL_CXXALIAS_SYS (iswxdigit, int, (wint_t wc));
+#endif
+_GL_CXXALIASWARN (iswalnum);
+_GL_CXXALIASWARN (iswalpha);
+_GL_CXXALIASWARN (iswcntrl);
+_GL_CXXALIASWARN (iswdigit);
+_GL_CXXALIASWARN (iswgraph);
+_GL_CXXALIASWARN (iswlower);
+_GL_CXXALIASWARN (iswprint);
+_GL_CXXALIASWARN (iswpunct);
+_GL_CXXALIASWARN (iswspace);
+_GL_CXXALIASWARN (iswupper);
+_GL_CXXALIASWARN (iswxdigit);
+
+#if @GNULIB_ISWBLANK@
+# if @REPLACE_ISWCNTRL@ || @REPLACE_ISWBLANK@
+_GL_CXXALIAS_RPL (iswblank, int, (wint_t wc));
+# else
+_GL_CXXALIAS_SYS (iswblank, int, (wint_t wc));
+# endif
+_GL_CXXALIASWARN (iswblank);
+#endif
+
+#if !@HAVE_WCTYPE_T@
+# if !GNULIB_defined_wctype_t
+typedef void * wctype_t;
+# define GNULIB_defined_wctype_t 1
+# endif
+#endif
+
+/* Get a descriptor for a wide character property. */
+#if @GNULIB_WCTYPE@
+# if !@HAVE_WCTYPE_T@
+_GL_FUNCDECL_SYS (wctype, wctype_t, (const char *name));
+# endif
+_GL_CXXALIAS_SYS (wctype, wctype_t, (const char *name));
+_GL_CXXALIASWARN (wctype);
+#elif defined GNULIB_POSIXCHECK
+# undef wctype
+# if HAVE_RAW_DECL_WCTYPE
+_GL_WARN_ON_USE (wctype, "wctype is unportable - "
+ "use gnulib module wctype for portability");
+# endif
+#endif
+
+/* Test whether a wide character has a given property.
+ The argument WC must be either a wchar_t value or WEOF.
+ The argument DESC must have been returned by the wctype() function. */
+#if @GNULIB_ISWCTYPE@
+# if !@HAVE_WCTYPE_T@
+_GL_FUNCDECL_SYS (iswctype, int, (wint_t wc, wctype_t desc));
+# endif
+_GL_CXXALIAS_SYS (iswctype, int, (wint_t wc, wctype_t desc));
+_GL_CXXALIASWARN (iswctype);
+#elif defined GNULIB_POSIXCHECK
+# undef iswctype
+# if HAVE_RAW_DECL_ISWCTYPE
+_GL_WARN_ON_USE (iswctype, "iswctype is unportable - "
+ "use gnulib module iswctype for portability");
+# endif
+#endif
+
+#if @REPLACE_TOWLOWER@ || defined __MINGW32__
+_GL_CXXALIAS_RPL (towlower, wint_t, (wint_t wc));
+_GL_CXXALIAS_RPL (towupper, wint_t, (wint_t wc));
+#else
+_GL_CXXALIAS_SYS (towlower, wint_t, (wint_t wc));
+_GL_CXXALIAS_SYS (towupper, wint_t, (wint_t wc));
+#endif
+_GL_CXXALIASWARN (towlower);
+_GL_CXXALIASWARN (towupper);
+
+#if !@HAVE_WCTRANS_T@
+# if !GNULIB_defined_wctrans_t
+typedef void * wctrans_t;
+# define GNULIB_defined_wctrans_t 1
+# endif
+#endif
+
+/* Get a descriptor for a wide character case conversion. */
+#if @GNULIB_WCTRANS@
+# if !@HAVE_WCTRANS_T@
+_GL_FUNCDECL_SYS (wctrans, wctrans_t, (const char *name));
+# endif
+_GL_CXXALIAS_SYS (wctrans, wctrans_t, (const char *name));
+_GL_CXXALIASWARN (wctrans);
+#elif defined GNULIB_POSIXCHECK
+# undef wctrans
+# if HAVE_RAW_DECL_WCTRANS
+_GL_WARN_ON_USE (wctrans, "wctrans is unportable - "
+ "use gnulib module wctrans for portability");
+# endif
+#endif
+
+/* Perform a given case conversion on a wide character.
+ The argument WC must be either a wchar_t value or WEOF.
+ The argument DESC must have been returned by the wctrans() function. */
+#if @GNULIB_TOWCTRANS@
+# if !@HAVE_WCTRANS_T@
+_GL_FUNCDECL_SYS (towctrans, wint_t, (wint_t wc, wctrans_t desc));
+# endif
+_GL_CXXALIAS_SYS (towctrans, wint_t, (wint_t wc, wctrans_t desc));
+_GL_CXXALIASWARN (towctrans);
+#elif defined GNULIB_POSIXCHECK
+# undef towctrans
+# if HAVE_RAW_DECL_TOWCTRANS
+_GL_WARN_ON_USE (towctrans, "towctrans is unportable - "
+ "use gnulib module towctrans for portability");
+# endif
+#endif
+
+_GL_INLINE_HEADER_END
+
+#endif /* _@GUARD_PREFIX@_WCTYPE_H */
+#endif /* _@GUARD_PREFIX@_WCTYPE_H */
diff --git a/lib/wctype_.h b/lib/wctype_.h
deleted file mode 100644
index 1297c61..0000000
--- a/lib/wctype_.h
+++ /dev/null
@@ -1,154 +0,0 @@
-/* A substitute for ISO C99 <wctype.h>, for platforms that lack it.
-
- Copyright (C) 2006, 2007 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-/* Written by Bruno Haible and Paul Eggert. */
-
-/*
- * ISO C 99 <wctype.h> for platforms that lack it.
- * <http://www.opengroup.org/susv3xbd/wctype.h.html>
- *
- * iswctype, towctrans, towlower, towupper, wctrans, wctype,
- * wctrans_t, and wctype_t are not yet implemented.
- */
-
-#ifndef _GL_WCTYPE_H
-#define _GL_WCTYPE_H
-
-#if @HAVE_WINT_T@
-/* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>.
- Tru64 with Desktop Toolkit C has a bug: <stdio.h> must be included before
- <wchar.h>.
- BSD/OS 4.0.1 has a bug: <stddef.h>, <stdio.h> and <time.h> must be
- included before <wchar.h>. */
-# include <stddef.h>
-# include <stdio.h>
-# include <time.h>
-# include <wchar.h>
-typedef wint_t __wctype_wint_t;
-#else
-typedef int __wctype_wint_t;
-#endif
-
-/* Include the original <wctype.h> if it exists.
- BeOS 5 has the functions but no <wctype.h>. */
-#if @HAVE_WCTYPE_H@
-# include @ABSOLUTE_WCTYPE_H@
-#endif
-
-/* FreeBSD 4.4 to 4.11 has <wctype.h> but lacks the functions.
- Assume all 12 functions are implemented the same way, or not at all. */
-#if ! HAVE_ISWCNTRL
-
-/* IRIX 5.3 has macros but no functions, its isw* macros refer to an
- undefined variable _ctmp_ and to <ctype.h> macros like _P, and they
- refer to system functions like _iswctype that are not in the
- standard C library. Rather than try to get ancient buggy
- implementations like this to work, just disable them. */
-# undef iswalnum
-# undef iswalpha
-# undef iswblank
-# undef iswcntrl
-# undef iswdigit
-# undef iswgraph
-# undef iswlower
-# undef iswprint
-# undef iswpunct
-# undef iswspace
-# undef iswupper
-# undef iswxdigit
-
-static inline int
-iswalnum (__wctype_wint_t wc)
-{
- return ((wc >= '0' && wc <= '9')
- || ((wc & ~0x20) >= 'A' && (wc & ~0x20) <= 'Z'));
-}
-
-static inline int
-iswalpha (__wctype_wint_t wc)
-{
- return (wc & ~0x20) >= 'A' && (wc & ~0x20) <= 'Z';
-}
-
-static inline int
-iswblank (__wctype_wint_t wc)
-{
- return wc == ' ' || wc == '\t';
-}
-
-static inline int
-iswcntrl (__wctype_wint_t wc)
-{
- return (wc & ~0x1f) == 0 || wc == 0x7f;
-}
-
-static inline int
-iswdigit (__wctype_wint_t wc)
-{
- return wc >= '0' && wc <= '9';
-}
-
-static inline int
-iswgraph (__wctype_wint_t wc)
-{
- return wc >= '!' && wc <= '~';
-}
-
-static inline int
-iswlower (__wctype_wint_t wc)
-{
- return wc >= 'a' && wc <= 'z';
-}
-
-static inline int
-iswprint (__wctype_wint_t wc)
-{
- return wc >= ' ' && wc <= '~';
-}
-
-static inline int
-iswpunct (__wctype_wint_t wc)
-{
- return (wc >= '!' && wc <= '~'
- && !((wc >= '0' && wc <= '9')
- || ((wc & ~0x20) >= 'A' && (wc & ~0x20) <= 'Z')));
-}
-
-static inline int
-iswspace (__wctype_wint_t wc)
-{
- return (wc == ' ' || wc == '\t'
- || wc == '\n' || wc == '\v' || wc == '\f' || wc == '\r');
-}
-
-static inline int
-iswupper (__wctype_wint_t wc)
-{
- return wc >= 'A' && wc <= 'Z';
-}
-
-static inline int
-iswxdigit (__wctype_wint_t wc)
-{
- return ((wc >= '0' && wc <= '9')
- || ((wc & ~0x20) >= 'A' && (wc & ~0x20) <= 'F'));
-}
-
-# endif /* ! HAVE_ISWCNTRL */
-
-#endif /* _GL_WCTYPE_H */
diff --git a/lib/wcwidth.c b/lib/wcwidth.c
new file mode 100644
index 0000000..b94fad0
--- /dev/null
+++ b/lib/wcwidth.c
@@ -0,0 +1,50 @@
+/* Determine the number of screen columns needed for a character.
+ Copyright (C) 2006-2007, 2010-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <wchar.h>
+
+/* Get iswprint. */
+#include <wctype.h>
+
+#include "localcharset.h"
+#include "streq.h"
+#include "uniwidth.h"
+
+int
+wcwidth (wchar_t wc)
+#undef wcwidth
+{
+ /* In UTF-8 locales, use a Unicode aware width function. */
+ const char *encoding = locale_charset ();
+ if (STREQ_OPT (encoding, "UTF-8", 'U', 'T', 'F', '-', '8', 0, 0, 0 ,0))
+ {
+ /* We assume that in a UTF-8 locale, a wide character is the same as a
+ Unicode character. */
+ return uc_width (wc, encoding);
+ }
+ else
+ {
+ /* Otherwise, fall back to the system's wcwidth function. */
+#if HAVE_WCWIDTH
+ return wcwidth (wc);
+#else
+ return wc == 0 ? 0 : iswprint (wc) ? 1 : -1;
+#endif
+ }
+}
diff --git a/lib/wcwidth.h b/lib/wcwidth.h
deleted file mode 100644
index 8ed5ff8..0000000
--- a/lib/wcwidth.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/* Determine the number of screen columns needed for a character.
- Copyright (C) 2006, 2007 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-#ifndef _gl_WCWIDTH_H
-#define _gl_WCWIDTH_H
-
-#if HAVE_WCHAR_T
-
-/* Get wcwidth if available, along with wchar_t. */
-# include <wchar.h>
-
-/* Get iswprint. */
-# include <wctype.h>
-
-# ifndef HAVE_DECL_WCWIDTH
-"this configure-time declaration test was not run"
-# endif
-# ifndef wcwidth
-# if !HAVE_WCWIDTH
-
-/* wcwidth doesn't exist, so assume all printable characters have
- width 1. */
-static inline int
-wcwidth (wchar_t wc)
-{
- return wc == 0 ? 0 : iswprint (wc) ? 1 : -1;
-}
-
-# elif !HAVE_DECL_WCWIDTH
-
-/* wcwidth exists but is not declared. */
-extern
-# ifdef __cplusplus
-"C"
-# endif
-int wcwidth (int /* actually wchar_t */);
-
-# endif
-# endif
-
-#endif /* HAVE_WCHAR_T */
-
-#endif /* _gl_WCWIDTH_H */
diff --git a/lib/write-any-file.c b/lib/write-any-file.c
new file mode 100644
index 0000000..73a435c
--- /dev/null
+++ b/lib/write-any-file.c
@@ -0,0 +1,51 @@
+/* Determine whether we can write any file.
+
+ Copyright (C) 2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Written by Paul Eggert. */
+
+#include <config.h>
+
+#include "write-any-file.h"
+#include "priv-set.h"
+#include "root-uid.h"
+
+#include <unistd.h>
+
+/* Return true if we know that we can write any file, including
+ writing directories. */
+
+bool
+can_write_any_file (void)
+{
+ static bool initialized;
+ static bool can_write;
+
+ if (! initialized)
+ {
+ bool can = false;
+#if defined PRIV_FILE_DAC_WRITE
+ can = (priv_set_ismember (PRIV_FILE_DAC_WRITE) == 1);
+#else
+ /* In traditional Unix, only root can unlink directories. */
+ can = (geteuid () == ROOT_UID);
+#endif
+ can_write = can;
+ initialized = true;
+ }
+
+ return can_write;
+}
diff --git a/lib/write-any-file.h b/lib/write-any-file.h
new file mode 100644
index 0000000..3930d4d
--- /dev/null
+++ b/lib/write-any-file.h
@@ -0,0 +1,2 @@
+#include <stdbool.h>
+bool can_write_any_file (void);
diff --git a/lib/write.c b/lib/write.c
new file mode 100644
index 0000000..8c048e7
--- /dev/null
+++ b/lib/write.c
@@ -0,0 +1,145 @@
+/* POSIX compatible write() function.
+ Copyright (C) 2008-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible <bruno@clisp.org>, 2008.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include <unistd.h>
+
+/* On native Windows platforms, SIGPIPE does not exist. When write() is
+ called on a pipe with no readers, WriteFile() fails with error
+ GetLastError() = ERROR_NO_DATA, and write() in consequence fails with
+ error EINVAL. */
+
+#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+
+# include <errno.h>
+# include <signal.h>
+# include <io.h>
+
+# define WIN32_LEAN_AND_MEAN /* avoid including junk */
+# include <windows.h>
+
+# include "msvc-inval.h"
+# include "msvc-nothrow.h"
+
+# undef write
+
+# if HAVE_MSVC_INVALID_PARAMETER_HANDLER
+static ssize_t
+write_nothrow (int fd, const void *buf, size_t count)
+{
+ ssize_t result;
+
+ TRY_MSVC_INVAL
+ {
+ result = write (fd, buf, count);
+ }
+ CATCH_MSVC_INVAL
+ {
+ result = -1;
+ errno = EBADF;
+ }
+ DONE_MSVC_INVAL;
+
+ return result;
+}
+# else
+# define write_nothrow write
+# endif
+
+ssize_t
+rpl_write (int fd, const void *buf, size_t count)
+{
+ for (;;)
+ {
+ ssize_t ret = write_nothrow (fd, buf, count);
+
+ if (ret < 0)
+ {
+# if GNULIB_NONBLOCKING
+ if (errno == ENOSPC)
+ {
+ HANDLE h = (HANDLE) _get_osfhandle (fd);
+ if (GetFileType (h) == FILE_TYPE_PIPE)
+ {
+ /* h is a pipe or socket. */
+ DWORD state;
+ if (GetNamedPipeHandleState (h, &state, NULL, NULL, NULL,
+ NULL, 0)
+ && (state & PIPE_NOWAIT) != 0)
+ {
+ /* h is a pipe in non-blocking mode.
+ We can get here in four situations:
+ 1. When the pipe buffer is full.
+ 2. When count <= pipe_buf_size and the number of
+ free bytes in the pipe buffer is < count.
+ 3. When count > pipe_buf_size and the number of free
+ bytes in the pipe buffer is > 0, < pipe_buf_size.
+ 4. When count > pipe_buf_size and the pipe buffer is
+ entirely empty.
+ The cases 1 and 2 are POSIX compliant. In cases 3 and
+ 4 POSIX specifies that write() must split the request
+ and succeed with a partial write. We fix case 4.
+ We don't fix case 3 because it is not essential for
+ programs. */
+ DWORD out_size; /* size of the buffer for outgoing data */
+ DWORD in_size; /* size of the buffer for incoming data */
+ if (GetNamedPipeInfo (h, NULL, &out_size, &in_size, NULL))
+ {
+ size_t reduced_count = count;
+ /* In theory we need only one of out_size, in_size.
+ But I don't know which of the two. The description
+ is ambiguous. */
+ if (out_size != 0 && out_size < reduced_count)
+ reduced_count = out_size;
+ if (in_size != 0 && in_size < reduced_count)
+ reduced_count = in_size;
+ if (reduced_count < count)
+ {
+ /* Attempt to write only the first part. */
+ count = reduced_count;
+ continue;
+ }
+ }
+ /* Change errno from ENOSPC to EAGAIN. */
+ errno = EAGAIN;
+ }
+ }
+ }
+ else
+# endif
+ {
+# if GNULIB_SIGPIPE
+ if (GetLastError () == ERROR_NO_DATA
+ && GetFileType ((HANDLE) _get_osfhandle (fd))
+ == FILE_TYPE_PIPE)
+ {
+ /* Try to raise signal SIGPIPE. */
+ raise (SIGPIPE);
+ /* If it is currently blocked or ignored, change errno from
+ EINVAL to EPIPE. */
+ errno = EPIPE;
+ }
+# endif
+ }
+ }
+ return ret;
+ }
+}
+
+#endif
diff --git a/lib/xalloc-die.c b/lib/xalloc-die.c
index 090f060..4c7994b 100644
--- a/lib/xalloc-die.c
+++ b/lib/xalloc-die.c
@@ -1,12 +1,12 @@
/* Report a memory allocation failure and exit.
- Copyright (C) 1997, 1998, 1999, 2000, 2002, 2003, 2004, 2006 Free
- Software Foundation, Inc.
+ Copyright (C) 1997-2000, 2002-2004, 2006, 2009-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
@@ -34,7 +33,7 @@ xalloc_die (void)
{
error (exit_failure, 0, "%s", _("memory exhausted"));
- /* The `noreturn' cannot be given to error, since it may return if
+ /* _Noreturn cannot be given to error, since it may return if
its first argument is 0. To help compilers understand the
xalloc_die does not return, call abort. Also, the abort is a
safety feature if exit_failure is 0 (which shouldn't happen). */
diff --git a/lib/xalloc-oversized.h b/lib/xalloc-oversized.h
new file mode 100644
index 0000000..d81a847
--- /dev/null
+++ b/lib/xalloc-oversized.h
@@ -0,0 +1,47 @@
+/* xalloc-oversized.h -- memory allocation size checking
+
+ Copyright (C) 1990-2000, 2003-2004, 2006-2016 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef XALLOC_OVERSIZED_H_
+#define XALLOC_OVERSIZED_H_
+
+#include <stddef.h>
+
+#ifndef __has_builtin
+# define __has_builtin(x) 0
+#endif
+
+/* Return 1 if an array of N objects, each of size S, cannot exist due
+ to size arithmetic overflow. S must be positive and N must be
+ nonnegative. This is a macro, not a function, so that it
+ works correctly even when SIZE_MAX < N.
+
+ By gnulib convention, SIZE_MAX represents overflow in size
+ calculations, so the conservative dividend to use here is
+ SIZE_MAX - 1, since SIZE_MAX might represent an overflowed value.
+ However, malloc (SIZE_MAX) fails on all known hosts where
+ sizeof (ptrdiff_t) <= sizeof (size_t), so do not bother to test for
+ exactly-SIZE_MAX allocations on such hosts; this avoids a test and
+ branch when S is known to be 1. */
+#if 5 <= __GNUC__ || __has_builtin (__builtin_mul_overflow)
+# define xalloc_oversized(n, s) \
+ ({ size_t __xalloc_size; __builtin_mul_overflow (n, s, &__xalloc_size); })
+#else
+# define xalloc_oversized(n, s) \
+ ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n))
+#endif
+
+#endif /* !XALLOC_OVERSIZED_H_ */
diff --git a/lib/xalloc.h b/lib/xalloc.h
index 0c6d8dc..a4fddbf 100644
--- a/lib/xalloc.h
+++ b/lib/xalloc.h
@@ -1,12 +1,11 @@
/* xalloc.h -- malloc with out-of-memory checking
- Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
- 1999, 2000, 2003, 2004, 2006, 2007 Free Software Foundation, Inc.
+ Copyright (C) 1990-2000, 2003-2004, 2006-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,60 +13,61 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifndef XALLOC_H_
-# define XALLOC_H_
+#define XALLOC_H_
-# include <stddef.h>
+#include <stddef.h>
+#include "xalloc-oversized.h"
-# ifdef __cplusplus
+#ifndef _GL_INLINE_HEADER_BEGIN
+ #error "Please include config.h first."
+#endif
+_GL_INLINE_HEADER_BEGIN
+#ifndef XALLOC_INLINE
+# define XALLOC_INLINE _GL_INLINE
+#endif
+
+#ifdef __cplusplus
extern "C" {
-# endif
+#endif
-# ifndef __attribute__
-# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 8) || __STRICT_ANSI__
-# define __attribute__(x)
-# endif
-# endif
+#if __GNUC__ >= 3
+# define _GL_ATTRIBUTE_MALLOC __attribute__ ((__malloc__))
+#else
+# define _GL_ATTRIBUTE_MALLOC
+#endif
-# ifndef ATTRIBUTE_NORETURN
-# define ATTRIBUTE_NORETURN __attribute__ ((__noreturn__))
-# endif
+#if ! defined __clang__ && \
+ (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
+# define _GL_ATTRIBUTE_ALLOC_SIZE(args) __attribute__ ((__alloc_size__ args))
+#else
+# define _GL_ATTRIBUTE_ALLOC_SIZE(args)
+#endif
/* This function is always triggered when memory is exhausted.
It must be defined by the application, either explicitly
or by using gnulib's xalloc-die module. This is the
function to call when one wants the program to die because of a
memory allocation failure. */
-extern void xalloc_die (void) ATTRIBUTE_NORETURN;
-
-void *xmalloc (size_t s);
-void *xzalloc (size_t s);
-void *xcalloc (size_t n, size_t s);
-void *xrealloc (void *p, size_t s);
+extern _Noreturn void xalloc_die (void);
+
+void *xmalloc (size_t s)
+ _GL_ATTRIBUTE_MALLOC _GL_ATTRIBUTE_ALLOC_SIZE ((1));
+void *xzalloc (size_t s)
+ _GL_ATTRIBUTE_MALLOC _GL_ATTRIBUTE_ALLOC_SIZE ((1));
+void *xcalloc (size_t n, size_t s)
+ _GL_ATTRIBUTE_MALLOC _GL_ATTRIBUTE_ALLOC_SIZE ((1, 2));
+void *xrealloc (void *p, size_t s)
+ _GL_ATTRIBUTE_ALLOC_SIZE ((2));
void *x2realloc (void *p, size_t *pn);
-void *xmemdup (void const *p, size_t s);
-char *xstrdup (char const *str);
-
-/* Return 1 if an array of N objects, each of size S, cannot exist due
- to size arithmetic overflow. S must be positive and N must be
- nonnegative. This is a macro, not an inline function, so that it
- works correctly even when SIZE_MAX < N.
-
- By gnulib convention, SIZE_MAX represents overflow in size
- calculations, so the conservative dividend to use here is
- SIZE_MAX - 1, since SIZE_MAX might represent an overflowed value.
- However, malloc (SIZE_MAX) fails on all known hosts where
- sizeof (ptrdiff_t) <= sizeof (size_t), so do not bother to test for
- exactly-SIZE_MAX allocations on such hosts; this avoids a test and
- branch when S is known to be 1. */
-# define xalloc_oversized(n, s) \
- ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n))
-
+void *xmemdup (void const *p, size_t s)
+ _GL_ATTRIBUTE_ALLOC_SIZE ((2));
+char *xstrdup (char const *str)
+ _GL_ATTRIBUTE_MALLOC;
/* In the following macros, T must be an elementary or structure/union or
typedef'ed type, or a pointer to such a type. To apply one of the
@@ -76,40 +76,31 @@ char *xstrdup (char const *str);
/* Allocate an object of type T dynamically, with error checking. */
/* extern t *XMALLOC (typename t); */
-# define XMALLOC(t) ((t *) xmalloc (sizeof (t)))
+#define XMALLOC(t) ((t *) xmalloc (sizeof (t)))
/* Allocate memory for N elements of type T, with error checking. */
/* extern t *XNMALLOC (size_t n, typename t); */
-# define XNMALLOC(n, t) \
- ((t *) (sizeof (t) == 1 ? xmalloc (n) : xnmalloc (n, sizeof (t))))
+#define XNMALLOC(n, t) \
+ ((t *) (sizeof (t) == 1 ? xmalloc (n) : xnmalloc (n, sizeof (t))))
/* Allocate an object of type T dynamically, with error checking,
and zero it. */
/* extern t *XZALLOC (typename t); */
-# define XZALLOC(t) ((t *) xzalloc (sizeof (t)))
+#define XZALLOC(t) ((t *) xzalloc (sizeof (t)))
/* Allocate memory for N elements of type T, with error checking,
and zero it. */
/* extern t *XCALLOC (size_t n, typename t); */
-# define XCALLOC(n, t) \
- ((t *) (sizeof (t) == 1 ? xzalloc (n) : xcalloc (n, sizeof (t))))
-
+#define XCALLOC(n, t) \
+ ((t *) (sizeof (t) == 1 ? xzalloc (n) : xcalloc (n, sizeof (t))))
-# if HAVE_INLINE
-# define static_inline static inline
-# else
- void *xnmalloc (size_t n, size_t s);
- void *xnrealloc (void *p, size_t n, size_t s);
- void *x2nrealloc (void *p, size_t *pn, size_t s);
- char *xcharalloc (size_t n);
-# endif
-
-# ifdef static_inline
/* Allocate an array of N objects, each with S bytes of memory,
dynamically, with error checking. S must be nonzero. */
-static_inline void *
+XALLOC_INLINE void *xnmalloc (size_t n, size_t s)
+ _GL_ATTRIBUTE_MALLOC _GL_ATTRIBUTE_ALLOC_SIZE ((1, 2));
+XALLOC_INLINE void *
xnmalloc (size_t n, size_t s)
{
if (xalloc_oversized (n, s))
@@ -120,7 +111,9 @@ xnmalloc (size_t n, size_t s)
/* Change the size of an allocated block of memory P to an array of N
objects each of S bytes, with error checking. S must be nonzero. */
-static_inline void *
+XALLOC_INLINE void *xnrealloc (void *p, size_t n, size_t s)
+ _GL_ATTRIBUTE_ALLOC_SIZE ((2, 3));
+XALLOC_INLINE void *
xnrealloc (void *p, size_t n, size_t s)
{
if (xalloc_oversized (n, s))
@@ -130,10 +123,9 @@ xnrealloc (void *p, size_t n, size_t s)
/* If P is null, allocate a block of at least *PN such objects;
otherwise, reallocate P so that it contains more than *PN objects
- each of S bytes. *PN must be nonzero unless P is null, and S must
- be nonzero. Set *PN to the new number of objects, and return the
- pointer to the new block. *PN is never set to zero, and the
- returned pointer is never null.
+ each of S bytes. S must be nonzero. Set *PN to the new number of
+ objects, and return the pointer to the new block. *PN is never set
+ to zero, and the returned pointer is never null.
Repeated reallocations are guaranteed to make progress, either by
allocating an initial block with a nonzero size, or by allocating a
@@ -153,9 +145,9 @@ xnrealloc (void *p, size_t n, size_t s)
void
append_int (int value)
{
- if (used == allocated)
- p = x2nrealloc (p, &allocated, sizeof *p);
- p[used++] = value;
+ if (used == allocated)
+ p = x2nrealloc (p, &allocated, sizeof *p);
+ p[used++] = value;
}
This causes x2nrealloc to allocate a block of some nonzero size the
@@ -173,17 +165,17 @@ xnrealloc (void *p, size_t n, size_t s)
void
append_int (int value)
{
- if (used == allocated)
- {
- p = x2nrealloc (p, &allocated1, sizeof *p);
- allocated = allocated1;
- }
- p[used++] = value;
+ if (used == allocated)
+ {
+ p = x2nrealloc (p, &allocated1, sizeof *p);
+ allocated = allocated1;
+ }
+ p[used++] = value;
}
*/
-static_inline void *
+XALLOC_INLINE void *
x2nrealloc (void *p, size_t *pn, size_t s)
{
size_t n = *pn;
@@ -191,26 +183,26 @@ x2nrealloc (void *p, size_t *pn, size_t s)
if (! p)
{
if (! n)
- {
- /* The approximate size to use for initial small allocation
- requests, when the invoking code specifies an old size of
- zero. 64 bytes is the largest "small" request for the
- GNU C library malloc. */
- enum { DEFAULT_MXFAST = 64 };
-
- n = DEFAULT_MXFAST / s;
- n += !n;
- }
+ {
+ /* The approximate size to use for initial small allocation
+ requests, when the invoking code specifies an old size of
+ zero. This is the largest "small" request for the GNU C
+ library malloc. */
+ enum { DEFAULT_MXFAST = 64 * sizeof (size_t) / 4 };
+
+ n = DEFAULT_MXFAST / s;
+ n += !n;
+ }
}
else
{
- /* Set N = ceil (1.5 * N) so that progress is made if N == 1.
- Check for overflow, so that N * S stays in size_t range.
- The check is slightly conservative, but an exact check isn't
- worth the trouble. */
+ /* Set N = floor (1.5 * N) + 1 so that progress is made even if N == 0.
+ Check for overflow, so that N * S stays in size_t range.
+ The check may be slightly conservative, but an exact check isn't
+ worth the trouble. */
if ((size_t) -1 / 3 * 2 / s <= n)
- xalloc_die ();
- n += (n + 1) / 2;
+ xalloc_die ();
+ n += n / 2 + 1;
}
*pn = n;
@@ -220,15 +212,15 @@ x2nrealloc (void *p, size_t *pn, size_t s)
/* Return a pointer to a new buffer of N bytes. This is like xmalloc,
except it returns char *. */
-static_inline char *
+XALLOC_INLINE char *xcharalloc (size_t n)
+ _GL_ATTRIBUTE_MALLOC _GL_ATTRIBUTE_ALLOC_SIZE ((1));
+XALLOC_INLINE char *
xcharalloc (size_t n)
{
return XNMALLOC (n, char);
}
-# endif
-
-# ifdef __cplusplus
+#ifdef __cplusplus
}
/* C++ does not allow conversions from void * to other pointer types
@@ -265,7 +257,8 @@ xmemdup (T const *p, size_t s)
return (T *) xmemdup ((void const *) p, s);
}
-# endif
+#endif
+_GL_INLINE_HEADER_END
#endif /* !XALLOC_H_ */
diff --git a/lib/xasprintf.c b/lib/xasprintf.c
new file mode 100644
index 0000000..e9e83ef
--- /dev/null
+++ b/lib/xasprintf.c
@@ -0,0 +1,34 @@
+/* vasprintf and asprintf with out-of-memory checking.
+ Copyright (C) 1999, 2002-2004, 2006, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include "xvasprintf.h"
+
+char *
+xasprintf (const char *format, ...)
+{
+ va_list args;
+ char *result;
+
+ va_start (args, format);
+ result = xvasprintf (format, args);
+ va_end (args);
+
+ return result;
+}
diff --git a/lib/xdectoimax.c b/lib/xdectoimax.c
new file mode 100644
index 0000000..d4bb18f
--- /dev/null
+++ b/lib/xdectoimax.c
@@ -0,0 +1,6 @@
+#define __xdectoint xdectoimax
+#define __xnumtoint xnumtoimax
+#define __xdectoint_t intmax_t
+#define __xstrtol xstrtoimax
+#define __xdectoint_signed 1
+#include "xdectoint.c"
diff --git a/lib/xdectoint.c b/lib/xdectoint.c
new file mode 100644
index 0000000..db41348
--- /dev/null
+++ b/lib/xdectoint.c
@@ -0,0 +1,86 @@
+/* Convert decimal strings with bounds checking and exit on error.
+
+ Copyright (C) 2014-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+#include "xdectoint.h"
+
+#include <errno.h>
+#include <inttypes.h>
+#include <stdlib.h>
+
+#include "error.h"
+#include "quote.h"
+#include "xstrtol.h"
+
+/* Parse numeric string N_STR of base BASE, and return the value.
+ Exit on parse error or if MIN or MAX are exceeded.
+ Strings can have multiplicative SUFFIXES if specified.
+ ERR is printed along with N_STR on error. */
+
+__xdectoint_t
+__xnumtoint (const char *n_str, int base, __xdectoint_t min, __xdectoint_t max,
+ const char *suffixes, const char *err, int err_exit)
+{
+ strtol_error s_err;
+
+ __xdectoint_t tnum;
+ s_err = __xstrtol (n_str, NULL, base, &tnum, suffixes);
+
+ if (s_err == LONGINT_OK)
+ {
+ if (tnum < min || max < tnum)
+ {
+ s_err = LONGINT_OVERFLOW;
+ /* Use have the INT range as a heuristic to distinguish
+ type overflow rather than other min/max limits. */
+ if (tnum > INT_MAX/2)
+ errno = EOVERFLOW;
+#if __xdectoint_signed
+ else if (tnum < INT_MIN/2)
+ errno = EOVERFLOW;
+#endif
+ else
+ errno = ERANGE;
+ }
+ }
+ else if (s_err == LONGINT_OVERFLOW)
+ errno = EOVERFLOW;
+ else if (s_err == LONGINT_INVALID_SUFFIX_CHAR_WITH_OVERFLOW)
+ errno = 0; /* Don't show ERANGE errors for invalid numbers. */
+
+ if (s_err != LONGINT_OK)
+ {
+ /* EINVAL error message is redundant in this context. */
+ error (err_exit ? err_exit : EXIT_FAILURE, errno == EINVAL ? 0 : errno,
+ "%s: %s", err, quote (n_str));
+ }
+
+ return tnum;
+}
+
+/* Parse decimal string N_STR, and return the value.
+ Exit on parse error or if MIN or MAX are exceeded.
+ Strings can have multiplicative SUFFIXES if specified.
+ ERR is printed along with N_STR on error. */
+
+__xdectoint_t
+__xdectoint (const char *n_str, __xdectoint_t min, __xdectoint_t max,
+ const char *suffixes, const char *err, int err_exit)
+{
+ return __xnumtoint (n_str, 10, min, max, suffixes, err, err_exit);
+}
diff --git a/lib/xdectoint.h b/lib/xdectoint.h
new file mode 100644
index 0000000..47cc1af
--- /dev/null
+++ b/lib/xdectoint.h
@@ -0,0 +1,36 @@
+/* Convert decimal strings with bounds checking and exit on error.
+
+ Copyright (C) 2014-2016 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef XDECTOINT_H_
+# define XDECTOINT_H_ 1
+
+# include <inttypes.h>
+
+# define _DECLARE_XDECTOINT(name, type) \
+ type name (const char *n_str, type min, type max, \
+ const char *suffixes, const char *err, int err_exit);
+# define _DECLARE_XNUMTOINT(name, type) \
+ type name (const char *n_str, int base, type min, type max, \
+ const char *suffixes, const char *err, int err_exit);
+
+_DECLARE_XDECTOINT (xdectoimax, intmax_t)
+_DECLARE_XDECTOINT (xdectoumax, uintmax_t)
+
+_DECLARE_XNUMTOINT (xnumtoimax, intmax_t)
+_DECLARE_XNUMTOINT (xnumtoumax, uintmax_t)
+
+#endif /* not XDECTOINT_H_ */
diff --git a/lib/xdectoumax.c b/lib/xdectoumax.c
new file mode 100644
index 0000000..412ddf9
--- /dev/null
+++ b/lib/xdectoumax.c
@@ -0,0 +1,6 @@
+#define __xdectoint xdectoumax
+#define __xnumtoint xnumtoumax
+#define __xdectoint_t uintmax_t
+#define __xstrtol xstrtoumax
+#define __xdectoint_signed 0
+#include "xdectoint.c"
diff --git a/lib/xfreopen.c b/lib/xfreopen.c
new file mode 100644
index 0000000..c02843a
--- /dev/null
+++ b/lib/xfreopen.c
@@ -0,0 +1,42 @@
+/* a wrapper for freopen
+ Copyright (C) 2008-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+#include "xfreopen.h"
+
+#include <errno.h>
+#include "error.h"
+#include "exitfail.h"
+#include "quote.h"
+#include "stdio--.h"
+
+#include "gettext.h"
+#define _(msgid) gettext (msgid)
+
+void
+xfreopen (char const *filename, char const *mode, FILE *fp)
+{
+ if (!freopen (filename, mode, fp))
+ {
+ char const *f = (filename ? filename
+ : (fp == stdin ? _("stdin")
+ : (fp == stdout ? _("stdout")
+ : (fp == stderr ? _("stderr")
+ : _("unknown stream")))));
+ error (exit_failure, errno, _("failed to reopen %s with mode %s"),
+ quote_n (0, f), quote_n (1, mode));
+ }
+}
diff --git a/lib/xfreopen.h b/lib/xfreopen.h
new file mode 100644
index 0000000..2ce49b5
--- /dev/null
+++ b/lib/xfreopen.h
@@ -0,0 +1,2 @@
+#include <stdio.h>
+void xfreopen (char const *filename, char const *mode, FILE *fp);
diff --git a/lib/xfts.c b/lib/xfts.c
index 1402e95..13525d9 100644
--- a/lib/xfts.c
+++ b/lib/xfts.c
@@ -1,11 +1,11 @@
/* xfts.c -- a wrapper for fts_open
- Copyright (C) 2003, 2005-2007 Free Software Foundation, Inc.
+ Copyright (C) 2003-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Jim Meyering. */
@@ -22,13 +21,9 @@
#include <stdbool.h>
#include <stdlib.h>
+#include <errno.h>
+#include <assert.h>
-#include "error.h"
-
-#include "gettext.h"
-#define _(msgid) gettext (msgid)
-
-#include "quote.h"
#include "xalloc.h"
#include "xfts.h"
@@ -36,29 +31,35 @@
FTS *
xfts_open (char * const *argv, int options,
- int (*compar) (const FTSENT **, const FTSENT **))
+ int (*compar) (const FTSENT **, const FTSENT **))
{
FTS *fts = fts_open (argv, options | FTS_CWDFD, compar);
if (fts == NULL)
{
- /* This can fail in three ways: out of memory, invalid bit_flags,
- and one or more of the FILES is an empty string. We could try
- to decipher that errno==EINVAL means invalid bit_flags and
- errno==ENOENT means there's an empty string, but that seems wrong.
- Ideally, fts_open would return a proper error indicator. For now,
- we'll presume that the bit_flags are valid and just check for
- empty strings. */
- bool invalid_arg = false;
- for (; *argv; ++argv)
- {
- if (**argv == '\0')
- invalid_arg = true;
- }
- if (invalid_arg)
- error (EXIT_FAILURE, 0, _("invalid argument: %s"), quote (""));
- else
- xalloc_die ();
+ /* This can fail in two ways: out of memory or with errno==EINVAL,
+ which indicates it was called with invalid bit_flags. */
+ assert (errno != EINVAL);
+ xalloc_die ();
}
return fts;
}
+
+/* When fts_read returns FTS_DC to indicate a directory cycle,
+ it may or may not indicate a real problem. When a program like
+ chgrp performs a recursive traversal that requires traversing
+ symbolic links, it is *not* a problem. However, when invoked
+ with "-P -R", it deserves a warning. The fts_options member
+ records the options that control this aspect of fts's behavior,
+ so test that. */
+bool
+cycle_warning_required (FTS const *fts, FTSENT const *ent)
+{
+#define ISSET(Fts,Opt) ((Fts)->fts_options & (Opt))
+ /* When dereferencing no symlinks, or when dereferencing only
+ those listed on the command line and we're not processing
+ a command-line argument, then a cycle is a serious problem. */
+ return ((ISSET (fts, FTS_PHYSICAL) && !ISSET (fts, FTS_COMFOLLOW))
+ || (ISSET (fts, FTS_PHYSICAL) && ISSET (fts, FTS_COMFOLLOW)
+ && ent->fts_level != FTS_ROOTLEVEL));
+}
diff --git a/lib/xfts.h b/lib/xfts.h
index 4790613..f903f48 100644
--- a/lib/xfts.h
+++ b/lib/xfts.h
@@ -1,5 +1,10 @@
+#include <stdbool.h>
#include "fts_.h"
FTS *
xfts_open (char * const *, int options,
- int (*) (const FTSENT **, const FTSENT **));
+ int (*) (const FTSENT **, const FTSENT **));
+
+bool
+cycle_warning_required (FTS const *fts, FTSENT const *ent)
+ _GL_ATTRIBUTE_PURE;
diff --git a/lib/xgetcwd.c b/lib/xgetcwd.c
index 26ea5da..8f2d84e 100644
--- a/lib/xgetcwd.c
+++ b/lib/xgetcwd.c
@@ -1,11 +1,12 @@
/* xgetcwd.c -- return current directory with unlimited length
- Copyright (C) 2001, 2003, 2004, 2006, 2007 Free Software Foundation, Inc.
+ Copyright (C) 2001, 2003-2004, 2006-2007, 2009-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Jim Meyering. */
diff --git a/lib/xgetcwd.h b/lib/xgetcwd.h
index 70afe35..184c7a8 100644
--- a/lib/xgetcwd.h
+++ b/lib/xgetcwd.h
@@ -1,10 +1,10 @@
/* prototype for xgetcwd
- Copyright (C) 1995, 2001, 2003 Free Software Foundation, Inc.
+ Copyright (C) 1995, 2001, 2003, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -12,7 +12,6 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
extern char *xgetcwd (void);
diff --git a/lib/xgetgroups.c b/lib/xgetgroups.c
new file mode 100644
index 0000000..771dad5
--- /dev/null
+++ b/lib/xgetgroups.c
@@ -0,0 +1,37 @@
+/* xgetgroups.c -- return a list of the groups a user or current process is in
+
+ Copyright (C) 2007-2016 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 <http://www.gnu.org/licenses/>. */
+
+/* Extracted from coreutils' src/id.c. */
+
+#include <config.h>
+
+#include "mgetgroups.h"
+
+#include <errno.h>
+
+#include "xalloc.h"
+
+/* Like mgetgroups, but call xalloc_die on allocation failure. */
+
+int
+xgetgroups (char const *username, gid_t gid, gid_t **groups)
+{
+ int result = mgetgroups (username, gid, groups);
+ if (result == -1 && errno == ENOMEM)
+ xalloc_die ();
+ return result;
+}
diff --git a/lib/xgethostname.c b/lib/xgethostname.c
index b4c8dcc..91c760d 100644
--- a/lib/xgethostname.c
+++ b/lib/xgethostname.c
@@ -1,12 +1,12 @@
/* xgethostname.c -- return current hostname with unlimited length
- Copyright (C) 1992, 1996, 2000, 2001, 2003, 2004, 2005, 2006 Free
- Software Foundation, Inc.
+ Copyright (C) 1992, 1996, 2000-2001, 2003-2006, 2009-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* written by Jim Meyering */
@@ -30,10 +29,6 @@
#include "xalloc.h"
-#ifndef ENAMETOOLONG
-# define ENAMETOOLONG 0
-#endif
-
#ifndef INITIAL_HOSTNAME_LENGTH
# define INITIAL_HOSTNAME_LENGTH 34
#endif
@@ -50,8 +45,8 @@ xgethostname (void)
while (1)
{
/* Use SIZE_1 here rather than SIZE to work around the bug in
- SunOS 5.5's gethostname whereby it NUL-terminates HOSTNAME
- even when the name is as long as the supplied buffer. */
+ SunOS 5.5's gethostname whereby it NUL-terminates HOSTNAME
+ even when the name is as long as the supplied buffer. */
size_t size_1;
hostname = x2realloc (hostname, &size);
@@ -60,19 +55,19 @@ xgethostname (void)
errno = 0;
if (gethostname (hostname, size_1) == 0)
- {
- if (! hostname[size_1 - 1])
- break;
- }
+ {
+ if (! hostname[size_1 - 1])
+ break;
+ }
else if (errno != 0 && errno != ENAMETOOLONG && errno != EINVAL
- /* OSX/Darwin does this when the buffer is not large enough */
- && errno != ENOMEM)
- {
- int saved_errno = errno;
- free (hostname);
- errno = saved_errno;
- return NULL;
- }
+ /* OSX/Darwin does this when the buffer is not large enough */
+ && errno != ENOMEM)
+ {
+ int saved_errno = errno;
+ free (hostname);
+ errno = saved_errno;
+ return NULL;
+ }
}
return hostname;
diff --git a/lib/xmalloc.c b/lib/xmalloc.c
index 318e0dd..429b50d 100644
--- a/lib/xmalloc.c
+++ b/lib/xmalloc.c
@@ -1,13 +1,11 @@
/* xmalloc.c -- malloc with out of memory checking
- Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
- 1999, 2000, 2002, 2003, 2004, 2005, 2006 Free Software Foundation,
- Inc.
+ Copyright (C) 1990-2000, 2002-2006, 2008-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -15,28 +13,21 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
-#if ! HAVE_INLINE
-# define static_inline
-#endif
+#define XALLOC_INLINE _GL_EXTERN_INLINE
+
#include "xalloc.h"
-#undef static_inline
#include <stdlib.h>
#include <string.h>
-#ifndef SIZE_MAX
-# define SIZE_MAX ((size_t) -1)
-#endif
-
/* 1 if calloc is known to be compatible with GNU calloc. This
matters if we are not also using the calloc module, which defines
- HAVE_CALLOC and supports the GNU API even on non-GNU platforms. */
-#if defined HAVE_CALLOC || defined __GLIBC__
+ HAVE_CALLOC_GNU and supports the GNU API even on non-GNU platforms. */
+#if defined HAVE_CALLOC_GNU || (defined __GLIBC__ && !defined __UCLIBC__)
enum { HAVE_GNU_CALLOC = 1 };
#else
enum { HAVE_GNU_CALLOC = 0 };
@@ -59,8 +50,16 @@ xmalloc (size_t n)
void *
xrealloc (void *p, size_t n)
{
+ if (!n && p)
+ {
+ /* The GNU and C99 realloc behaviors disagree here. Act like
+ GNU, even if the underlying realloc is C99. */
+ free (p);
+ return NULL;
+ }
+
p = realloc (p, n);
- if (!p && n != 0)
+ if (!p && n)
xalloc_die ();
return p;
}
diff --git a/lib/xmemcoll.c b/lib/xmemcoll.c
index de00c84..4a0c9bd 100644
--- a/lib/xmemcoll.c
+++ b/lib/xmemcoll.c
@@ -1,11 +1,11 @@
/* Locale-specific memory comparison.
- Copyright (C) 2002, 2003, 2004, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2002-2004, 2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Contributed by Paul Eggert <eggert@twinsun.com>. */
@@ -32,6 +31,19 @@
#include "quotearg.h"
#include "xmemcoll.h"
+static void
+collate_error (int collation_errno,
+ char const *s1, size_t s1len,
+ char const *s2, size_t s2len)
+{
+ error (0, collation_errno, _("string comparison failed"));
+ error (0, 0, _("Set LC_ALL='C' to work around the problem."));
+ error (exit_failure, 0,
+ _("The strings compared were %s and %s."),
+ quotearg_n_style_mem (0, locale_quoting_style, s1, s1len),
+ quotearg_n_style_mem (1, locale_quoting_style, s2, s2len));
+}
+
/* Compare S1 (with length S1LEN) and S2 (with length S2LEN) according
to the LC_COLLATE locale. S1 and S2 do not overlap, and are not
adjacent. Temporarily modify the bytes after S1 and S2, but
@@ -43,16 +55,22 @@ xmemcoll (char *s1, size_t s1len, char *s2, size_t s2len)
{
int diff = memcoll (s1, s1len, s2, s2len);
int collation_errno = errno;
-
if (collation_errno)
- {
- error (0, collation_errno, _("string comparison failed"));
- error (0, 0, _("Set LC_ALL='C' to work around the problem."));
- error (exit_failure, 0,
- _("The strings compared were %s and %s."),
- quotearg_n_style_mem (0, locale_quoting_style, s1, s1len),
- quotearg_n_style_mem (1, locale_quoting_style, s2, s2len));
- }
+ collate_error (collation_errno, s1, s1len, s2, s2len);
+ return diff;
+}
+/* Compare S1 (a memory block of size S1SIZE, with a NUL as last byte)
+ and S2 (a memory block of size S2SIZE, with a NUL as last byte)
+ according to the LC_COLLATE locale. S1SIZE and S2SIZE must be > 0.
+ Report an error and exit if there is an error. */
+
+int
+xmemcoll0 (char const *s1, size_t s1size, char const *s2, size_t s2size)
+{
+ int diff = memcoll0 (s1, s1size, s2, s2size);
+ int collation_errno = errno;
+ if (collation_errno)
+ collate_error (collation_errno, s1, s1size - 1, s2, s2size - 1);
return diff;
}
diff --git a/lib/xmemcoll.h b/lib/xmemcoll.h
index 2f422e8..4170b9b 100644
--- a/lib/xmemcoll.h
+++ b/lib/xmemcoll.h
@@ -1,2 +1,3 @@
#include <stddef.h>
int xmemcoll (char *, size_t, char *, size_t);
+int xmemcoll0 (char const *, size_t, char const *, size_t);
diff --git a/lib/xmemxfrm.c b/lib/xmemxfrm.c
deleted file mode 100644
index 8150334..0000000
--- a/lib/xmemxfrm.c
+++ /dev/null
@@ -1,63 +0,0 @@
-/* Locale-specific memory transformation
-
- Copyright (C) 2006 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 2, 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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
-
-/* Written by Paul Eggert <eggert@cs.ucla.edu>. */
-
-#include <config.h>
-
-#include "xmemxfrm.h"
-
-#include <errno.h>
-#include <stdlib.h>
-
-#include "gettext.h"
-#define _(msgid) gettext (msgid)
-
-#include "error.h"
-#include "exitfail.h"
-#include "memxfrm.h"
-#include "quotearg.h"
-
-/* Store into DEST (of size DESTSIZE) the text in SRC (of size
- SRCSIZE) transformed so that the result of memcmp on two
- transformed texts (with ties going to the longer text) is the same
- as the result of memcoll on the two texts before their
- transformation. Perhaps temporarily modify the byte after SRC, but
- restore its original contents before returning.
-
- Return the size of the resulting text. DEST contains an
- indeterminate value if the resulting size is greater than DESTSIZE.
- Report an error and exit if there is an error. */
-
-size_t
-xmemxfrm (char *restrict dest, size_t destsize,
- char *restrict src, size_t srcsize)
-{
- size_t translated_size = memxfrm (dest, destsize, src, srcsize);
-
- if (errno)
- {
- error (0, errno, _("string transformation failed"));
- error (0, 0, _("Set LC_ALL='C' to work around the problem."));
- error (exit_failure, 0,
- _("The untransformed string was %s."),
- quotearg_n_style_mem (0, locale_quoting_style, src, srcsize));
- }
-
- return translated_size;
-}
diff --git a/lib/xmemxfrm.h b/lib/xmemxfrm.h
deleted file mode 100644
index 7c4b8ad..0000000
--- a/lib/xmemxfrm.h
+++ /dev/null
@@ -1,2 +0,0 @@
-#include <stddef.h>
-size_t xmemxfrm (char *restrict, size_t, char *restrict, size_t);
diff --git a/lib/xnanosleep.c b/lib/xnanosleep.c
index ebbd7ee..fc04ddc 100644
--- a/lib/xnanosleep.c
+++ b/lib/xnanosleep.c
@@ -1,12 +1,11 @@
/* xnanosleep.c -- a more convenient interface to nanosleep
- Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007 Free Software
- Foundation, Inc.
+ Copyright (C) 2002-2007, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Mostly written (for sleep.c) by Paul Eggert.
Factored out (creating this file) by Jim Meyering. */
@@ -24,83 +22,36 @@
#include "xnanosleep.h"
-#include <limits.h>
-#include <stdbool.h>
-#include <stdio.h>
-#include <assert.h>
+#include <timespec.h>
+
#include <errno.h>
-#include <sys/types.h>
#include <time.h>
-#include "intprops.h"
-
-#ifndef TIME_T_MAX
-# define TIME_T_MAX TYPE_MAXIMUM (time_t)
-#endif
-
/* Sleep until the time (call it WAKE_UP_TIME) specified as
SECONDS seconds after the time this function is called.
SECONDS must be non-negative. If SECONDS is so large that
- it is not representable as a `struct timespec', then use
+ it is not representable as a 'struct timespec', then use
the maximum value for that interval. Return -1 on failure
(setting errno), 0 on success. */
int
xnanosleep (double seconds)
{
- enum { BILLION = 1000000000 };
-
- bool overflow = false;
- double ns;
- struct timespec ts_sleep;
-
- assert (0 <= seconds);
-
- /* Separate whole seconds from nanoseconds.
- Be careful to detect any overflow. */
- ts_sleep.tv_sec = seconds;
- ns = BILLION * (seconds - ts_sleep.tv_sec);
- overflow |= ! (ts_sleep.tv_sec <= seconds && 0 <= ns && ns <= BILLION);
- ts_sleep.tv_nsec = ns;
-
- /* Round up to the next whole number, if necessary, so that we
- always sleep for at least the requested amount of time. Assuming
- the default rounding mode, we don't have to worry about the
- rounding error when computing 'ns' above, since the error won't
- cause 'ns' to drop below an integer boundary. */
- ts_sleep.tv_nsec += (ts_sleep.tv_nsec < ns);
-
- /* Normalize the interval length. nanosleep requires this. */
- if (BILLION <= ts_sleep.tv_nsec)
- {
- time_t t = ts_sleep.tv_sec + 1;
-
- /* Detect integer overflow. */
- overflow |= (t < ts_sleep.tv_sec);
-
- ts_sleep.tv_sec = t;
- ts_sleep.tv_nsec -= BILLION;
- }
+ struct timespec ts_sleep = dtotimespec (seconds);
for (;;)
{
- if (overflow)
- {
- ts_sleep.tv_sec = TIME_T_MAX;
- ts_sleep.tv_nsec = BILLION - 1;
- }
-
/* Linux-2.6.8.1's nanosleep returns -1, but doesn't set errno
- when resumed after being suspended. Earlier versions would
- set errno to EINTR. nanosleep from linux-2.6.10, as well as
- implementations by (all?) other vendors, doesn't return -1
- in that case; either it continues sleeping (if time remains)
- or it returns zero (if the wake-up time has passed). */
+ when resumed after being suspended. Earlier versions would
+ set errno to EINTR. nanosleep from linux-2.6.10, as well as
+ implementations by (all?) other vendors, doesn't return -1
+ in that case; either it continues sleeping (if time remains)
+ or it returns zero (if the wake-up time has passed). */
errno = 0;
if (nanosleep (&ts_sleep, NULL) == 0)
- break;
+ break;
if (errno != EINTR && errno != 0)
- return -1;
+ return -1;
}
return 0;
diff --git a/lib/xprintf.c b/lib/xprintf.c
new file mode 100644
index 0000000..eed2269
--- /dev/null
+++ b/lib/xprintf.c
@@ -0,0 +1,79 @@
+/* printf wrappers that fail immediately for non-file-related errors
+ Copyright (C) 2007, 2009-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+#include "xprintf.h"
+
+#include <errno.h>
+
+#include "error.h"
+#include "exitfail.h"
+#include "gettext.h"
+
+/* written by Jim Meyering */
+
+/* Just like printf, but call error if it fails without setting the
+ stream's error indicator. */
+int
+xprintf (char const *restrict format, ...)
+{
+ va_list args;
+ int retval;
+ va_start (args, format);
+ retval = xvprintf (format, args);
+ va_end (args);
+
+ return retval;
+}
+
+/* Just like vprintf, but call error if it fails without setting the
+ stream's error indicator. */
+int
+xvprintf (char const *restrict format, va_list args)
+{
+ int retval = vprintf (format, args);
+ if (retval < 0 && ! ferror (stdout))
+ error (exit_failure, errno, gettext ("cannot perform formatted output"));
+
+ return retval;
+}
+
+/* Just like fprintf, but call error if it fails without setting the
+ stream's error indicator. */
+int
+xfprintf (FILE *restrict stream, char const *restrict format, ...)
+{
+ va_list args;
+ int retval;
+ va_start (args, format);
+ retval = xvfprintf (stream, format, args);
+ va_end (args);
+
+ return retval;
+}
+
+/* Just like vfprintf, but call error if it fails without setting the
+ stream's error indicator. */
+int
+xvfprintf (FILE *restrict stream, char const *restrict format, va_list args)
+{
+ int retval = vfprintf (stream, format, args);
+ if (retval < 0 && ! ferror (stream))
+ error (exit_failure, errno, gettext ("cannot perform formatted output"));
+
+ return retval;
+}
diff --git a/lib/xprintf.h b/lib/xprintf.h
new file mode 100644
index 0000000..31ae6f9
--- /dev/null
+++ b/lib/xprintf.h
@@ -0,0 +1,45 @@
+/* printf wrappers that fail immediately for non-file-related errors
+ Copyright (C) 2007-2016 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _XPRINTF_H
+#define _XPRINTF_H
+
+#include <stdarg.h>
+#include <stdio.h>
+
+/* The __attribute__ feature is available in gcc versions 2.5 and later.
+ The __-protected variants of the attributes 'format' and 'printf' are
+ accepted by gcc versions 2.6.4 (effectively 2.7) and later.
+ We enable _GL_ATTRIBUTE_FORMAT only if these are supported too, because
+ gnulib and libintl do '#define printf __printf__' when they override
+ the 'printf' function. */
+#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 7)
+# define _GL_ATTRIBUTE_FORMAT(spec) __attribute__ ((__format__ spec))
+#else
+# define _GL_ATTRIBUTE_FORMAT(spec) /* empty */
+#endif
+
+extern int xprintf (char const *restrict format, ...)
+ _GL_ATTRIBUTE_FORMAT ((__printf__, 1, 2));
+extern int xvprintf (char const *restrict format, va_list args)
+ _GL_ATTRIBUTE_FORMAT ((__printf__, 1, 0));
+extern int xfprintf (FILE *restrict stream, char const *restrict format, ...)
+ _GL_ATTRIBUTE_FORMAT ((__printf__, 2, 3));
+extern int xvfprintf (FILE *restrict stream, char const *restrict format,
+ va_list args)
+ _GL_ATTRIBUTE_FORMAT ((__printf__, 2, 0));
+
+#endif
diff --git a/lib/xreadlink.c b/lib/xreadlink.c
index 2aba265..901f946 100644
--- a/lib/xreadlink.c
+++ b/lib/xreadlink.c
@@ -1,11 +1,11 @@
/* xreadlink.c -- readlink wrapper to return the link name in malloc'd storage
- Copyright (C) 2001, 2003-2007 Free Software Foundation, Inc.
+ Copyright (C) 2001, 2003-2007, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,9 +13,7 @@
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with this program; see the file COPYING.
- If not, write to the Free Software Foundation,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Jim Meyering <jim@meyering.net>
and Bruno Haible <bruno@clisp.org>. */
@@ -25,107 +23,22 @@
/* Specification. */
#include "xreadlink.h"
-#include <stdio.h>
-#include <string.h>
#include <errno.h>
-#include <limits.h>
-#include <sys/types.h>
-#include <stdlib.h>
-#include <unistd.h>
-#ifndef SIZE_MAX
-# define SIZE_MAX ((size_t) -1)
-#endif
-#ifndef SSIZE_MAX
-# define SSIZE_MAX ((ssize_t) (SIZE_MAX / 2))
-#endif
-
-#ifdef NO_XMALLOC
-# define xmalloc malloc
-#else
-# include "xalloc.h"
-#endif
+#include "areadlink.h"
+#include "xalloc.h"
/* Call readlink to get the symbolic link value of FILENAME.
Return a pointer to that NUL-terminated string in malloc'd storage.
- If readlink fails, return NULL (caller may use errno to diagnose).
+ If readlink fails, return NULL and set errno.
If realloc fails, or if the link value is longer than SIZE_MAX :-),
give a diagnostic and exit. */
char *
xreadlink (char const *filename)
{
- /* The initial buffer size for the link value. A power of 2
- detects arithmetic overflow earlier, but is not required. */
-#define INITIAL_BUF_SIZE 1024
-
- /* Allocate the initial buffer on the stack. This way, in the common
- case of a symlink of small size, we get away with a single small malloc()
- instead of a big malloc() followed by a shrinking realloc(). */
- char initial_buf[INITIAL_BUF_SIZE];
-
- char *buffer = initial_buf;
- size_t buf_size = sizeof (initial_buf);
-
- while (1)
- {
- /* Attempt to read the link into the current buffer. */
- ssize_t link_length = readlink (filename, buffer, buf_size);
-
- /* On AIX 5L v5.3 and HP-UX 11i v2 04/09, readlink returns -1
- with errno == ERANGE if the buffer is too small. */
- if (link_length < 0 && errno != ERANGE)
- {
- if (buffer != initial_buf)
- {
- int saved_errno = errno;
- free (buffer);
- errno = saved_errno;
- }
- return NULL;
- }
-
- if ((size_t) link_length < buf_size)
- {
- buffer[link_length++] = '\0';
-
- /* Return it in a chunk of memory as small as possible. */
- if (buffer == initial_buf)
- {
- buffer = (char *) xmalloc (link_length);
-#ifdef NO_XMALLOC
- if (buffer == NULL)
- return NULL;
-#endif
- memcpy (buffer, initial_buf, link_length);
- }
- else
- {
- /* Shrink buffer before returning it. */
- if ((size_t) link_length < buf_size)
- {
- char *smaller_buffer = (char *) realloc (buffer, link_length);
-
- if (smaller_buffer != NULL)
- buffer = smaller_buffer;
- }
- }
- return buffer;
- }
-
- if (buffer != initial_buf)
- free (buffer);
- buf_size *= 2;
- if (SSIZE_MAX < buf_size || (SIZE_MAX / 2 < SSIZE_MAX && buf_size == 0))
-#ifdef NO_XMALLOC
- return NULL;
-#else
- xalloc_die ();
-#endif
- buffer = (char *) xmalloc (buf_size);
-#ifdef NO_XMALLOC
- if (buffer == NULL)
- return NULL;
-#endif
- }
+ char *result = areadlink (filename);
+ if (result == NULL && errno == ENOMEM)
+ xalloc_die ();
+ return result;
}
diff --git a/lib/xreadlink.h b/lib/xreadlink.h
index 6d93fe6..555c27d 100644
--- a/lib/xreadlink.h
+++ b/lib/xreadlink.h
@@ -1,11 +1,12 @@
/* Reading symbolic links without size limitation.
- Copyright (C) 2001, 2003, 2004, 2007 Free Software Foundation, Inc.
+ Copyright (C) 2001, 2003-2004, 2007, 2009-2016 Free Software Foundation,
+ Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,22 +14,12 @@
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with this program; see the file COPYING.
- If not, write to the Free Software Foundation,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Jim Meyering <jim@meyering.net> */
-#include <stddef.h>
-
-/* Call readlink to get the symbolic link value of FILENAME.
- Return a pointer to that NUL-terminated string in malloc'd storage.
- If readlink fails, return NULL and set errno. */
extern char *xreadlink (char const *filename);
-/* Call readlink to get the symbolic link value of FILENAME.
- SIZE_HINT is a hint as to how long the link is expected to be;
- typically it is taken from st_size. It need not be correct.
- Return a pointer to that NUL-terminated string in malloc'd storage.
- If readlink fails, return NULL and set errno. */
-extern char *xreadlink_with_size (char const *filename, size_t size_hint);
+#if GNULIB_XREADLINKAT
+extern char *xreadlinkat (int fd, char const *filename);
+#endif
diff --git a/lib/xsize.c b/lib/xsize.c
new file mode 100644
index 0000000..4b4914c
--- /dev/null
+++ b/lib/xsize.c
@@ -0,0 +1,3 @@
+#include <config.h>
+#define XSIZE_INLINE _GL_EXTERN_INLINE
+#include "xsize.h"
diff --git a/lib/xsize.h b/lib/xsize.h
new file mode 100644
index 0000000..202a87e
--- /dev/null
+++ b/lib/xsize.h
@@ -0,0 +1,117 @@
+/* xsize.h -- Checked size_t computations.
+
+ Copyright (C) 2003, 2008-2016 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, 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _XSIZE_H
+#define _XSIZE_H
+
+/* Get size_t. */
+#include <stddef.h>
+
+/* Get SIZE_MAX. */
+#include <limits.h>
+#if HAVE_STDINT_H
+# include <stdint.h>
+#endif
+
+#ifndef _GL_INLINE_HEADER_BEGIN
+ #error "Please include config.h first."
+#endif
+_GL_INLINE_HEADER_BEGIN
+#ifndef XSIZE_INLINE
+# define XSIZE_INLINE _GL_INLINE
+#endif
+
+/* The size of memory objects is often computed through expressions of
+ type size_t. Example:
+ void* p = malloc (header_size + n * element_size).
+ These computations can lead to overflow. When this happens, malloc()
+ returns a piece of memory that is way too small, and the program then
+ crashes while attempting to fill the memory.
+ To avoid this, the functions and macros in this file check for overflow.
+ The convention is that SIZE_MAX represents overflow.
+ malloc (SIZE_MAX) is not guaranteed to fail -- think of a malloc
+ implementation that uses mmap --, it's recommended to use size_overflow_p()
+ or size_in_bounds_p() before invoking malloc().
+ The example thus becomes:
+ size_t size = xsum (header_size, xtimes (n, element_size));
+ void *p = (size_in_bounds_p (size) ? malloc (size) : NULL);
+*/
+
+/* Convert an arbitrary value >= 0 to type size_t. */
+#define xcast_size_t(N) \
+ ((N) <= SIZE_MAX ? (size_t) (N) : SIZE_MAX)
+
+/* Sum of two sizes, with overflow check. */
+XSIZE_INLINE size_t
+#if __GNUC__ >= 3
+__attribute__ ((__pure__))
+#endif
+xsum (size_t size1, size_t size2)
+{
+ size_t sum = size1 + size2;
+ return (sum >= size1 ? sum : SIZE_MAX);
+}
+
+/* Sum of three sizes, with overflow check. */
+XSIZE_INLINE size_t
+#if __GNUC__ >= 3
+__attribute__ ((__pure__))
+#endif
+xsum3 (size_t size1, size_t size2, size_t size3)
+{
+ return xsum (xsum (size1, size2), size3);
+}
+
+/* Sum of four sizes, with overflow check. */
+XSIZE_INLINE size_t
+#if __GNUC__ >= 3
+__attribute__ ((__pure__))
+#endif
+xsum4 (size_t size1, size_t size2, size_t size3, size_t size4)
+{
+ return xsum (xsum (xsum (size1, size2), size3), size4);
+}
+
+/* Maximum of two sizes, with overflow check. */
+XSIZE_INLINE size_t
+#if __GNUC__ >= 3
+__attribute__ ((__pure__))
+#endif
+xmax (size_t size1, size_t size2)
+{
+ /* No explicit check is needed here, because for any n:
+ max (SIZE_MAX, n) == SIZE_MAX and max (n, SIZE_MAX) == SIZE_MAX. */
+ return (size1 >= size2 ? size1 : size2);
+}
+
+/* Multiplication of a count with an element size, with overflow check.
+ The count must be >= 0 and the element size must be > 0.
+ This is a macro, not a function, so that it works correctly even
+ when N is of a wider type and N > SIZE_MAX. */
+#define xtimes(N, ELSIZE) \
+ ((N) <= SIZE_MAX / (ELSIZE) ? (size_t) (N) * (ELSIZE) : SIZE_MAX)
+
+/* Check for overflow. */
+#define size_overflow_p(SIZE) \
+ ((SIZE) == SIZE_MAX)
+/* Check against overflow. */
+#define size_in_bounds_p(SIZE) \
+ ((SIZE) != SIZE_MAX)
+
+_GL_INLINE_HEADER_END
+
+#endif /* _XSIZE_H */
diff --git a/lib/xstriconv.c b/lib/xstriconv.c
new file mode 100644
index 0000000..2dbee18
--- /dev/null
+++ b/lib/xstriconv.c
@@ -0,0 +1,62 @@
+/* Charset conversion with out-of-memory checking.
+ Copyright (C) 2001-2004, 2006, 2009-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include "xstriconv.h"
+
+#include <errno.h>
+
+#include "striconv.h"
+#include "xalloc.h"
+
+
+#if HAVE_ICONV
+
+int
+xmem_cd_iconv (const char *src, size_t srclen, iconv_t cd,
+ char **resultp, size_t *lengthp)
+{
+ int retval = mem_cd_iconv (src, srclen, cd, resultp, lengthp);
+
+ if (retval < 0 && errno == ENOMEM)
+ xalloc_die ();
+ return retval;
+}
+
+char *
+xstr_cd_iconv (const char *src, iconv_t cd)
+{
+ char *result = str_cd_iconv (src, cd);
+
+ if (result == NULL && errno == ENOMEM)
+ xalloc_die ();
+ return result;
+}
+
+#endif
+
+char *
+xstr_iconv (const char *src, const char *from_codeset, const char *to_codeset)
+{
+ char *result = str_iconv (src, from_codeset, to_codeset);
+
+ if (result == NULL && errno == ENOMEM)
+ xalloc_die ();
+ return result;
+}
diff --git a/lib/xstriconv.h b/lib/xstriconv.h
new file mode 100644
index 0000000..61e7c75
--- /dev/null
+++ b/lib/xstriconv.h
@@ -0,0 +1,78 @@
+/* Charset conversion with out-of-memory checking.
+ Copyright (C) 2001-2004, 2006-2007, 2009-2016 Free Software Foundation, Inc.
+ Written by Bruno Haible and Simon Josefsson.
+
+ 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _XSTRICONV_H
+#define _XSTRICONV_H
+
+#include <stddef.h>
+#if HAVE_ICONV
+#include <iconv.h>
+#endif
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+#if HAVE_ICONV
+
+/* Convert an entire string from one encoding to another, using iconv.
+ The original string is at [SRC,...,SRC+SRCLEN-1].
+ The conversion descriptor is passed as CD.
+ *RESULTP and *LENGTH should initially be a scratch buffer and its size,
+ or *RESULTP can initially be NULL.
+ May erase the contents of the memory at *RESULTP.
+ Upon memory allocation failure, report the error and exit.
+ Return value: 0 if successful, otherwise -1 and errno set.
+ If successful: The resulting string is stored in *RESULTP and its length
+ in *LENGTHP. *RESULTP is set to a freshly allocated memory block, or is
+ unchanged if no dynamic memory allocation was necessary. */
+extern int xmem_cd_iconv (const char *src, size_t srclen, iconv_t cd,
+ char **resultp, size_t *lengthp);
+
+/* Convert an entire string from one encoding to another, using iconv.
+ The original string is the NUL-terminated string starting at SRC.
+ The conversion descriptor is passed as CD. Both the "from" and the "to"
+ encoding must use a single NUL byte at the end of the string (i.e. not
+ UCS-2, UCS-4, UTF-16, UTF-32).
+ Allocate a malloced memory block for the result.
+ Upon memory allocation failure, report the error and exit.
+ Return value: the freshly allocated resulting NUL-terminated string if
+ successful, otherwise NULL and errno set. */
+extern char * xstr_cd_iconv (const char *src, iconv_t cd);
+
+#endif
+
+/* Convert an entire string from one encoding to another, using iconv.
+ The original string is the NUL-terminated string starting at SRC.
+ Both the "from" and the "to" encoding must use a single NUL byte at the
+ end of the string (i.e. not UCS-2, UCS-4, UTF-16, UTF-32).
+ Allocate a malloced memory block for the result.
+ Upon memory allocation failure, report the error and exit.
+ Return value: the freshly allocated resulting NUL-terminated string if
+ successful, otherwise NULL and errno set. */
+extern char * xstr_iconv (const char *src,
+ const char *from_codeset, const char *to_codeset);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif /* _XSTRICONV_H */
diff --git a/lib/xstrndup.c b/lib/xstrndup.c
index 7ccefd7..3d605ef 100644
--- a/lib/xstrndup.c
+++ b/lib/xstrndup.c
@@ -1,11 +1,11 @@
/* Duplicate a bounded initial segment of a string, with out-of-memory
checking.
- Copyright (C) 2003, 2006, 2007 Free Software Foundation, Inc.
+ Copyright (C) 2003, 2006-2007, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
diff --git a/lib/xstrndup.h b/lib/xstrndup.h
index 88354cf..0d3021c 100644
--- a/lib/xstrndup.h
+++ b/lib/xstrndup.h
@@ -1,11 +1,11 @@
/* Duplicate a bounded initial segment of a string, with out-of-memory
checking.
- Copyright (C) 2003 Free Software Foundation, Inc.
+ Copyright (C) 2003, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <stddef.h>
diff --git a/lib/xstrtod.c b/lib/xstrtod.c
index 86e124f..2ce0451 100644
--- a/lib/xstrtod.c
+++ b/lib/xstrtod.c
@@ -1,12 +1,12 @@
/* error-checking interface to strtod-like functions
- Copyright (C) 1996, 1999, 2000, 2003, 2004, 2005, 2006 Free
- Software Foundation, Inc.
+ Copyright (C) 1996, 1999-2000, 2003-2006, 2009-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Jim Meyering. */
@@ -44,7 +43,7 @@
bool
XSTRTOD (char const *str, char const **ptr, DOUBLE *result,
- DOUBLE (*convert) (char const *, char **))
+ DOUBLE (*convert) (char const *, char **))
{
DOUBLE val;
char *terminator;
@@ -59,9 +58,9 @@ XSTRTOD (char const *str, char const **ptr, DOUBLE *result,
else
{
/* Allow underflow (in which case CONVERT returns zero),
- but flag overflow as an error. */
+ but flag overflow as an error. */
if (val != 0 && errno == ERANGE)
- ok = false;
+ ok = false;
}
if (ptr != NULL)
diff --git a/lib/xstrtod.h b/lib/xstrtod.h
index 1e5ad94..7126cd6 100644
--- a/lib/xstrtod.h
+++ b/lib/xstrtod.h
@@ -1,11 +1,12 @@
/* Error-checking interface to strtod-like functions.
- Copyright (C) 1996, 1998, 2003, 2004, 2006 Free Software Foundation, Inc.
+ Copyright (C) 1996, 1998, 2003-2004, 2006, 2009-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Jim Meyering. */
@@ -24,8 +24,8 @@
# include <stdbool.h>
bool xstrtod (const char *str, const char **ptr, double *result,
- double (*convert) (char const *, char **));
+ double (*convert) (char const *, char **));
bool xstrtold (const char *str, const char **ptr, long double *result,
- long double (*convert) (char const *, char **));
+ long double (*convert) (char const *, char **));
#endif /* not XSTRTOD_H */
diff --git a/lib/xstrtol-error.c b/lib/xstrtol-error.c
new file mode 100644
index 0000000..30b51cb
--- /dev/null
+++ b/lib/xstrtol-error.c
@@ -0,0 +1,98 @@
+/* A more useful interface to strtol.
+
+ Copyright (C) 1995-1996, 1998-1999, 2001-2004, 2006-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+#include "xstrtol.h"
+
+#include <stdlib.h>
+
+#include "error.h"
+#include "exitfail.h"
+#include "gettext.h"
+
+#define N_(msgid) msgid
+
+/* Report an error for an invalid integer in an option argument.
+
+ ERR is the error code returned by one of the xstrto* functions.
+
+ Use OPT_IDX to decide whether to print the short option string "C"
+ or "-C" or a long option string derived from LONG_OPTION. OPT_IDX
+ is -2 if the short option "C" was used, without any leading "-"; it
+ is -1 if the short option "-C" was used; otherwise it is an index
+ into LONG_OPTIONS, which should have a name preceded by two '-'
+ characters.
+
+ ARG is the option-argument containing the integer.
+
+ After reporting an error, exit with status EXIT_STATUS if it is
+ nonzero. */
+
+static void
+xstrtol_error (enum strtol_error err,
+ int opt_idx, char c, struct option const *long_options,
+ char const *arg,
+ int exit_status)
+{
+ char const *hyphens = "--";
+ char const *msgid;
+ char const *option;
+ char option_buffer[2];
+
+ switch (err)
+ {
+ default:
+ abort ();
+
+ case LONGINT_INVALID:
+ msgid = N_("invalid %s%s argument '%s'");
+ break;
+
+ case LONGINT_INVALID_SUFFIX_CHAR:
+ case LONGINT_INVALID_SUFFIX_CHAR_WITH_OVERFLOW:
+ msgid = N_("invalid suffix in %s%s argument '%s'");
+ break;
+
+ case LONGINT_OVERFLOW:
+ msgid = N_("%s%s argument '%s' too large");
+ break;
+ }
+
+ if (opt_idx < 0)
+ {
+ hyphens -= opt_idx;
+ option_buffer[0] = c;
+ option_buffer[1] = '\0';
+ option = option_buffer;
+ }
+ else
+ option = long_options[opt_idx].name;
+
+ error (exit_status, 0, gettext (msgid), hyphens, option, arg);
+}
+
+/* Like xstrtol_error, except exit with a failure status. */
+
+void
+xstrtol_fatal (enum strtol_error err,
+ int opt_idx, char c, struct option const *long_options,
+ char const *arg)
+{
+ xstrtol_error (err, opt_idx, c, long_options, arg, exit_failure);
+ abort ();
+}
diff --git a/lib/xstrtol.c b/lib/xstrtol.c
index c4557a0..5a3afb5 100644
--- a/lib/xstrtol.c
+++ b/lib/xstrtol.c
@@ -1,12 +1,12 @@
/* A more useful interface to strtol.
- Copyright (C) 1995, 1996, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006
- Free Software Foundation, Inc.
+ Copyright (C) 1995-1996, 1998-2001, 2003-2007, 2009-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +14,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Jim Meyering. */
@@ -35,15 +34,28 @@
need stderr defined if assertion checking is enabled. */
#include <stdio.h>
-#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
+#include "assure.h"
#include "intprops.h"
+/* xstrtoll.c and xstrtoull.c, which include this file, require that
+ ULLONG_MAX, LLONG_MAX, LLONG_MIN are defined, but <limits.h> does not
+ define them on all platforms. */
+#ifndef ULLONG_MAX
+# define ULLONG_MAX TYPE_MAXIMUM (unsigned long long)
+#endif
+#ifndef LLONG_MAX
+# define LLONG_MAX TYPE_MAXIMUM (long long int)
+#endif
+#ifndef LLONG_MIN
+# define LLONG_MIN TYPE_MINIMUM (long long int)
+#endif
+
static strtol_error
bkm_scale (__strtol_t *x, int scale_factor)
{
@@ -74,49 +86,50 @@ bkm_scale_by_power (__strtol_t *x, int base, int power)
strtol_error
__xstrtol (const char *s, char **ptr, int strtol_base,
- __strtol_t *val, const char *valid_suffixes)
+ __strtol_t *val, const char *valid_suffixes)
{
char *t_ptr;
char **p;
__strtol_t tmp;
strtol_error err = LONGINT_OK;
- assert (0 <= strtol_base && strtol_base <= 36);
+ assure (0 <= strtol_base && strtol_base <= 36);
p = (ptr ? ptr : &t_ptr);
+ errno = 0;
+
if (! TYPE_SIGNED (__strtol_t))
{
const char *q = s;
unsigned char ch = *q;
while (isspace (ch))
- ch = *++q;
+ ch = *++q;
if (ch == '-')
- return LONGINT_INVALID;
+ return LONGINT_INVALID;
}
- errno = 0;
tmp = __strtol (s, p, strtol_base);
if (*p == s)
{
/* If there is no number but there is a valid suffix, assume the
- number is 1. The string is invalid otherwise. */
+ number is 1. The string is invalid otherwise. */
if (valid_suffixes && **p && strchr (valid_suffixes, **p))
- tmp = 1;
+ tmp = 1;
else
- return LONGINT_INVALID;
+ return LONGINT_INVALID;
}
else if (errno != 0)
{
if (errno != ERANGE)
- return LONGINT_INVALID;
+ return LONGINT_INVALID;
err = LONGINT_OVERFLOW;
}
- /* Let valid_suffixes == NULL mean `allow any suffix'. */
+ /* Let valid_suffixes == NULL mean "allow any suffix". */
/* FIXME: update all callers except the ones that allow suffixes
- after the number, changing last parameter NULL to `""'. */
+ after the number, changing last parameter NULL to "". */
if (!valid_suffixes)
{
*val = tmp;
@@ -130,134 +143,100 @@ __xstrtol (const char *s, char **ptr, int strtol_base,
strtol_error overflow;
if (!strchr (valid_suffixes, **p))
- {
- *val = tmp;
- return err | LONGINT_INVALID_SUFFIX_CHAR;
- }
+ {
+ *val = tmp;
+ return err | LONGINT_INVALID_SUFFIX_CHAR;
+ }
if (strchr (valid_suffixes, '0'))
- {
- /* The ``valid suffix'' '0' is a special flag meaning that
- an optional second suffix is allowed, which can change
- the base. A suffix "B" (e.g. "100MB") stands for a power
- of 1000, whereas a suffix "iB" (e.g. "100MiB") stands for
- a power of 1024. If no suffix (e.g. "100M"), assume
- power-of-1024. */
-
- switch (p[0][1])
- {
- case 'i':
- if (p[0][2] == 'B')
- suffixes += 2;
- break;
-
- case 'B':
- case 'D': /* 'D' is obsolescent */
- base = 1000;
- suffixes++;
- break;
- }
- }
+ {
+ /* The "valid suffix" '0' is a special flag meaning that
+ an optional second suffix is allowed, which can change
+ the base. A suffix "B" (e.g. "100MB") stands for a power
+ of 1000, whereas a suffix "iB" (e.g. "100MiB") stands for
+ a power of 1024. If no suffix (e.g. "100M"), assume
+ power-of-1024. */
+
+ switch (p[0][1])
+ {
+ case 'i':
+ if (p[0][2] == 'B')
+ suffixes += 2;
+ break;
+
+ case 'B':
+ case 'D': /* 'D' is obsolescent */
+ base = 1000;
+ suffixes++;
+ break;
+ }
+ }
switch (**p)
- {
- case 'b':
- overflow = bkm_scale (&tmp, 512);
- break;
-
- case 'B':
- overflow = bkm_scale (&tmp, 1024);
- break;
-
- case 'c':
- overflow = 0;
- break;
-
- case 'E': /* exa or exbi */
- overflow = bkm_scale_by_power (&tmp, base, 6);
- break;
-
- case 'G': /* giga or gibi */
- case 'g': /* 'g' is undocumented; for compatibility only */
- overflow = bkm_scale_by_power (&tmp, base, 3);
- break;
-
- case 'k': /* kilo */
- case 'K': /* kibi */
- overflow = bkm_scale_by_power (&tmp, base, 1);
- break;
-
- case 'M': /* mega or mebi */
- case 'm': /* 'm' is undocumented; for compatibility only */
- overflow = bkm_scale_by_power (&tmp, base, 2);
- break;
-
- case 'P': /* peta or pebi */
- overflow = bkm_scale_by_power (&tmp, base, 5);
- break;
-
- case 'T': /* tera or tebi */
- case 't': /* 't' is undocumented; for compatibility only */
- overflow = bkm_scale_by_power (&tmp, base, 4);
- break;
-
- case 'w':
- overflow = bkm_scale (&tmp, 2);
- break;
-
- case 'Y': /* yotta or 2**80 */
- overflow = bkm_scale_by_power (&tmp, base, 8);
- break;
-
- case 'Z': /* zetta or 2**70 */
- overflow = bkm_scale_by_power (&tmp, base, 7);
- break;
-
- default:
- *val = tmp;
- return err | LONGINT_INVALID_SUFFIX_CHAR;
- }
+ {
+ case 'b':
+ overflow = bkm_scale (&tmp, 512);
+ break;
+
+ case 'B':
+ overflow = bkm_scale (&tmp, 1024);
+ break;
+
+ case 'c':
+ overflow = LONGINT_OK;
+ break;
+
+ case 'E': /* exa or exbi */
+ overflow = bkm_scale_by_power (&tmp, base, 6);
+ break;
+
+ case 'G': /* giga or gibi */
+ case 'g': /* 'g' is undocumented; for compatibility only */
+ overflow = bkm_scale_by_power (&tmp, base, 3);
+ break;
+
+ case 'k': /* kilo */
+ case 'K': /* kibi */
+ overflow = bkm_scale_by_power (&tmp, base, 1);
+ break;
+
+ case 'M': /* mega or mebi */
+ case 'm': /* 'm' is undocumented; for compatibility only */
+ overflow = bkm_scale_by_power (&tmp, base, 2);
+ break;
+
+ case 'P': /* peta or pebi */
+ overflow = bkm_scale_by_power (&tmp, base, 5);
+ break;
+
+ case 'T': /* tera or tebi */
+ case 't': /* 't' is undocumented; for compatibility only */
+ overflow = bkm_scale_by_power (&tmp, base, 4);
+ break;
+
+ case 'w':
+ overflow = bkm_scale (&tmp, 2);
+ break;
+
+ case 'Y': /* yotta or 2**80 */
+ overflow = bkm_scale_by_power (&tmp, base, 8);
+ break;
+
+ case 'Z': /* zetta or 2**70 */
+ overflow = bkm_scale_by_power (&tmp, base, 7);
+ break;
+
+ default:
+ *val = tmp;
+ return err | LONGINT_INVALID_SUFFIX_CHAR;
+ }
err |= overflow;
*p += suffixes;
if (**p)
- err |= LONGINT_INVALID_SUFFIX_CHAR;
+ err |= LONGINT_INVALID_SUFFIX_CHAR;
}
*val = tmp;
return err;
}
-
-#ifdef TESTING_XSTRTO
-
-# include <stdio.h>
-# include "error.h"
-
-char *program_name;
-
-int
-main (int argc, char **argv)
-{
- strtol_error s_err;
- int i;
-
- program_name = argv[0];
- for (i=1; i<argc; i++)
- {
- char *p;
- __strtol_t val;
-
- s_err = __xstrtol (argv[i], &p, 0, &val, "bckmw");
- if (s_err == LONGINT_OK)
- {
- printf ("%s->%lu (%s)\n", argv[i], val, p);
- }
- else
- {
- STRTOL_FATAL_ERROR (argv[i], "arg", s_err);
- }
- }
- exit (0);
-}
-
-#endif /* TESTING_XSTRTO */
diff --git a/lib/xstrtol.h b/lib/xstrtol.h
index 475728a..6f51d6e 100644
--- a/lib/xstrtol.h
+++ b/lib/xstrtol.h
@@ -1,12 +1,12 @@
/* A more useful interface to strtol.
- Copyright (C) 1995, 1996, 1998, 1999, 2001, 2002, 2003, 2004, 2006
- Free Software Foundation, Inc.
+ Copyright (C) 1995-1996, 1998-1999, 2001-2004, 2006-2016 Free Software
+ Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,18 +14,14 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifndef XSTRTOL_H_
# define XSTRTOL_H_ 1
-# include "exitfail.h"
-
+# include <getopt.h>
# include <inttypes.h>
-# include "gettext.h"
-
# ifndef _STRTOL_ERROR
enum strtol_error
{
@@ -37,7 +33,7 @@ enum strtol_error
LONGINT_INVALID_SUFFIX_CHAR = 2,
LONGINT_INVALID_SUFFIX_CHAR_WITH_OVERFLOW = (LONGINT_INVALID_SUFFIX_CHAR
- | LONGINT_OVERFLOW),
+ | LONGINT_OVERFLOW),
LONGINT_INVALID = 4
};
typedef enum strtol_error strtol_error;
@@ -50,38 +46,28 @@ _DECLARE_XSTRTOL (xstrtoul, unsigned long int)
_DECLARE_XSTRTOL (xstrtoimax, intmax_t)
_DECLARE_XSTRTOL (xstrtoumax, uintmax_t)
-# define _STRTOL_ERROR(Exit_code, Str, Argument_type_string, Err) \
- do \
- { \
- switch ((Err)) \
- { \
- default: \
- abort (); \
- \
- case LONGINT_INVALID: \
- error ((Exit_code), 0, gettext ("invalid %s `%s'"), \
- (Argument_type_string), (Str)); \
- break; \
- \
- case LONGINT_INVALID_SUFFIX_CHAR: \
- case LONGINT_INVALID_SUFFIX_CHAR | LONGINT_OVERFLOW: \
- error ((Exit_code), 0, \
- gettext ("invalid character following %s in `%s'"), \
- (Argument_type_string), (Str)); \
- break; \
- \
- case LONGINT_OVERFLOW: \
- error ((Exit_code), 0, gettext ("%s `%s' too large"), \
- (Argument_type_string), (Str)); \
- break; \
- } \
- } \
- while (0)
-
-# define STRTOL_FATAL_ERROR(Str, Argument_type_string, Err) \
- _STRTOL_ERROR (exit_failure, Str, Argument_type_string, Err)
-
-# define STRTOL_FAIL_WARN(Str, Argument_type_string, Err) \
- _STRTOL_ERROR (0, Str, Argument_type_string, Err)
+#if HAVE_LONG_LONG_INT
+_DECLARE_XSTRTOL (xstrtoll, long long int)
+_DECLARE_XSTRTOL (xstrtoull, unsigned long long int)
+#endif
+
+/* Report an error for an invalid integer in an option argument.
+
+ ERR is the error code returned by one of the xstrto* functions.
+
+ Use OPT_IDX to decide whether to print the short option string "C"
+ or "-C" or a long option string derived from LONG_OPTION. OPT_IDX
+ is -2 if the short option "C" was used, without any leading "-"; it
+ is -1 if the short option "-C" was used; otherwise it is an index
+ into LONG_OPTIONS, which should have a name preceded by two '-'
+ characters.
+
+ ARG is the option-argument containing the integer.
+
+ After reporting an error, exit with a failure status. */
+
+_Noreturn void xstrtol_fatal (enum strtol_error,
+ int, char, struct option const *,
+ char const *);
#endif /* not XSTRTOL_H_ */
diff --git a/lib/xtime.c b/lib/xtime.c
new file mode 100644
index 0000000..e608f69
--- /dev/null
+++ b/lib/xtime.c
@@ -0,0 +1,3 @@
+#include <config.h>
+#define XTIME_INLINE _GL_EXTERN_INLINE
+#include "xtime.h"
diff --git a/lib/xtime.h b/lib/xtime.h
index d268d2d..084a32c 100644
--- a/lib/xtime.h
+++ b/lib/xtime.h
@@ -1,11 +1,11 @@
/* xtime -- extended-resolution integer time stamps
- Copyright (C) 2005, 2006 Free Software Foundation, Inc.
+ Copyright (C) 2005-2006, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -13,34 +13,45 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Paul Eggert. */
#ifndef XTIME_H_
-# define XTIME_H_ 1
+#define XTIME_H_ 1
+
+#ifndef _GL_INLINE_HEADER_BEGIN
+ #error "Please include config.h first."
+#endif
+_GL_INLINE_HEADER_BEGIN
+#ifndef XTIME_INLINE
+# define XTIME_INLINE _GL_INLINE
+#endif
/* xtime_t is a signed type used for time stamps. It is an integer
type that is a count of nanoseconds -- except for obsolescent hosts
without sufficiently-wide integers, where it is a count of
seconds. */
-# if HAVE_LONG_LONG_INT
+#if HAVE_LONG_LONG_INT
typedef long long int xtime_t;
-# define XTIME_PRECISION 1000000000
-# else
-# include <limits.h>
+# define XTIME_PRECISION 1000000000
+#else
+# include <limits.h>
typedef long int xtime_t;
-# if LONG_MAX >> 31 >> 31 == 0
-# define XTIME_PRECISION 1
-# else
-# define XTIME_PRECISION 1000000000
-# endif
+# if LONG_MAX >> 31 >> 31 == 0
+# define XTIME_PRECISION 1
+# else
+# define XTIME_PRECISION 1000000000
# endif
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
/* Return an extended time value that contains S seconds and NS
nanoseconds, without any overflow checking. */
-static inline xtime_t
+XTIME_INLINE xtime_t
xtime_make (xtime_t s, long int ns)
{
if (XTIME_PRECISION == 1)
@@ -50,32 +61,32 @@ xtime_make (xtime_t s, long int ns)
}
/* Return the number of seconds in T, which must be nonnegative. */
-static inline xtime_t
+XTIME_INLINE xtime_t
xtime_nonnegative_sec (xtime_t t)
{
return t / XTIME_PRECISION;
}
/* Return the number of seconds in T. */
-static inline xtime_t
+XTIME_INLINE xtime_t
xtime_sec (xtime_t t)
{
return (XTIME_PRECISION == 1
- ? t
- : t < 0
- ? (t + XTIME_PRECISION - 1) / XTIME_PRECISION - 1
- : xtime_nonnegative_sec (t));
+ ? t
+ : t < 0
+ ? (t + XTIME_PRECISION - 1) / XTIME_PRECISION - 1
+ : xtime_nonnegative_sec (t));
}
/* Return the number of nanoseconds in T, which must be nonnegative. */
-static inline long int
+XTIME_INLINE long int
xtime_nonnegative_nsec (xtime_t t)
{
return t % XTIME_PRECISION;
}
/* Return the number of nanoseconds in T. */
-static inline long int
+XTIME_INLINE long int
xtime_nsec (xtime_t t)
{
long int ns = t % XTIME_PRECISION;
@@ -84,4 +95,8 @@ xtime_nsec (xtime_t t)
return ns;
}
+#ifdef __cplusplus
+}
+#endif
+
#endif
diff --git a/lib/xvasprintf.c b/lib/xvasprintf.c
new file mode 100644
index 0000000..9deaad0
--- /dev/null
+++ b/lib/xvasprintf.c
@@ -0,0 +1,110 @@
+/* vasprintf and asprintf with out-of-memory checking.
+ Copyright (C) 1999, 2002-2004, 2006-2016 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 <http://www.gnu.org/licenses/>. */
+
+#include <config.h>
+
+/* Specification. */
+#include "xvasprintf.h"
+
+#include <errno.h>
+#include <limits.h>
+#include <string.h>
+#include <stdio.h>
+
+#include "xalloc.h"
+
+/* Checked size_t computations. */
+#include "xsize.h"
+
+static char *
+xstrcat (size_t argcount, va_list args)
+{
+ char *result;
+ va_list ap;
+ size_t totalsize;
+ size_t i;
+ char *p;
+
+ /* Determine the total size. */
+ totalsize = 0;
+ va_copy (ap, args);
+ for (i = argcount; i > 0; i--)
+ {
+ const char *next = va_arg (ap, const char *);
+ totalsize = xsum (totalsize, strlen (next));
+ }
+ va_end (ap);
+
+ /* Test for overflow in the summing pass above or in (totalsize + 1) below.
+ Also, don't return a string longer than INT_MAX, for consistency with
+ vasprintf(). */
+ if (totalsize == SIZE_MAX || totalsize > INT_MAX)
+ {
+ errno = EOVERFLOW;
+ return NULL;
+ }
+
+ /* Allocate and fill the result string. */
+ result = XNMALLOC (totalsize + 1, char);
+ p = result;
+ for (i = argcount; i > 0; i--)
+ {
+ const char *next = va_arg (args, const char *);
+ size_t len = strlen (next);
+ memcpy (p, next, len);
+ p += len;
+ }
+ *p = '\0';
+
+ return result;
+}
+
+char *
+xvasprintf (const char *format, va_list args)
+{
+ char *result;
+
+ /* Recognize the special case format = "%s...%s". It is a frequently used
+ idiom for string concatenation and needs to be fast. We don't want to
+ have a separate function xstrcat() for this purpose. */
+ {
+ size_t argcount = 0;
+ const char *f;
+
+ for (f = format;;)
+ {
+ if (*f == '\0')
+ /* Recognized the special case of string concatenation. */
+ return xstrcat (argcount, args);
+ if (*f != '%')
+ break;
+ f++;
+ if (*f != 's')
+ break;
+ f++;
+ argcount++;
+ }
+ }
+
+ if (vasprintf (&result, format, args) < 0)
+ {
+ if (errno == ENOMEM)
+ xalloc_die ();
+ return NULL;
+ }
+
+ return result;
+}
diff --git a/lib/xvasprintf.h b/lib/xvasprintf.h
new file mode 100644
index 0000000..d62d7b7
--- /dev/null
+++ b/lib/xvasprintf.h
@@ -0,0 +1,55 @@
+/* vasprintf and asprintf with out-of-memory checking.
+ Copyright (C) 2002-2004, 2006-2016 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 <http://www.gnu.org/licenses/>. */
+
+#ifndef _XVASPRINTF_H
+#define _XVASPRINTF_H
+
+/* Get va_list. */
+#include <stdarg.h>
+
+/* The __attribute__ feature is available in gcc versions 2.5 and later.
+ The __-protected variants of the attributes 'format' and 'printf' are
+ accepted by gcc versions 2.6.4 (effectively 2.7) and later.
+ We enable _GL_ATTRIBUTE_FORMAT only if these are supported too, because
+ gnulib and libintl do '#define printf __printf__' when they override
+ the 'printf' function. */
+#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 7)
+# define _GL_ATTRIBUTE_FORMAT(spec) __attribute__ ((__format__ spec))
+#else
+# define _GL_ATTRIBUTE_FORMAT(spec) /* empty */
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Write formatted output to a string dynamically allocated with malloc(),
+ and return it. Upon [ENOMEM] memory allocation error, call xalloc_die.
+ On some other error
+ - [EOVERFLOW] resulting string length is > INT_MAX,
+ - [EINVAL] invalid format string,
+ - [EILSEQ] error during conversion between wide and multibyte characters,
+ return NULL. */
+extern char *xasprintf (const char *format, ...)
+ _GL_ATTRIBUTE_FORMAT ((__printf__, 1, 2));
+extern char *xvasprintf (const char *format, va_list args)
+ _GL_ATTRIBUTE_FORMAT ((__printf__, 1, 0));
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _XVASPRINTF_H */
diff --git a/lib/yesno.c b/lib/yesno.c
index 2400628..81f77d1 100644
--- a/lib/yesno.c
+++ b/lib/yesno.c
@@ -1,12 +1,11 @@
/* yesno.c -- read a yes/no response from stdin
- Copyright (C) 1990, 1998, 2001, 2003, 2004, 2005, 2006 Free
- Software Foundation, Inc.
+ Copyright (C) 1990, 1998, 2001, 2003-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -14,8 +13,7 @@
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, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
@@ -24,13 +22,11 @@
#include <stdlib.h>
#include <stdio.h>
-#if ENABLE_NLS
-# include "getline.h"
-#endif
-
-/* Return true if we read an affirmative line from standard input. */
+/* Return true if we read an affirmative line from standard input.
-extern int rpmatch (char const *response);
+ Since this function uses stdin, it is suggested that the caller not
+ use STDIN_FILENO directly, and also that the line
+ atexit(close_stdin) be added to main(). */
bool
yesno (void)
@@ -46,7 +42,10 @@ yesno (void)
yes = false;
else
{
- response[response_len - 1] = '\0';
+ /* Remove EOL if present as that's not part of the matched response,
+ and not matched by $ for example. */
+ if (response[response_len - 1] == '\n')
+ response[response_len - 1] = '\0';
yes = (0 < rpmatch (response));
}
diff --git a/lib/yesno.h b/lib/yesno.h
index dfa70bc..e6fe6e7 100644
--- a/lib/yesno.h
+++ b/lib/yesno.h
@@ -1,10 +1,10 @@
/* declare yesno
- Copyright (C) 2004 Free Software Foundation, Inc.
+ Copyright (C) 2004, 2009-2016 Free Software Foundation, Inc.
- This program is free software; you can redistribute it and/or modify
+ 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 2, or (at your option)
- any later version.
+ 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
@@ -12,9 +12,7 @@
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with this program; see the file COPYING.
- If not, write to the Free Software Foundation,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifndef YESNO_H_
# define YESNO_H_