Changeset 1953 for coreutils/trunk/lib


Ignore:
Timestamp:
Jan 27, 2017, 4:40:38 PM (8 years ago)
Author:
Silvan Scherrer
Message:

coreutils: update trunk to version 8.26

Location:
coreutils/trunk
Files:
71 edited
4 copied

Legend:

Unmodified
Added
Removed
  • coreutils/trunk

  • TabularUnified coreutils/trunk/lib/alloca.in.h

    r1648 r1953  
    5252#  pragma intrinsic (_alloca)
    5353#  define alloca _alloca
     54# elif defined __MVS__
     55#  include <stdlib.h>
    5456# else
    5557#  include <stddef.h>
  • TabularUnified coreutils/trunk/lib/argmatch.c

    r1648 r1953  
    3636#include "quotearg.h"
    3737#include "quote.h"
     38#include "getprogname.h"
    3839
    3940#if USE_UNLOCKED_IO
     
    211212 * Based on "getversion.c" by David MacKenzie <djm@gnu.ai.mit.edu>
    212213 */
    213 char *program_name;
    214214
    215215/* When to make backup files.  */
     
    255255  enum backup_type backup_type = no_backups;
    256256
    257   program_name = (char *) argv[0];
    258 
    259257  if (argc > 2)
    260258    {
    261       fprintf (stderr, "Usage: %s [VERSION_CONTROL]\n", program_name);
     259      fprintf (stderr, "Usage: %s [VERSION_CONTROL]\n", getprogname ());
    262260      exit (1);
    263261    }
     
    268266
    269267  if (argc == 2)
    270     backup_type = XARGMATCH (program_name, argv[1],
     268    backup_type = XARGMATCH (getprogname (), argv[1],
    271269                             backup_args, backup_vals);
    272270
  • TabularUnified coreutils/trunk/lib/backupfile.c

    r1652 r1953  
    8181/* The extension added to file names to produce a simple (as opposed
    8282   to numbered) backup file name. */
    83 char const *simple_backup_suffix = "~";
     83char const *simple_backup_suffix = NULL;
    8484
    8585
     
    269269  bool simple = true;
    270270
     271  /* Initialize the default simple backup suffix.  */
     272  if (! simple_backup_suffix)
     273    {
     274      char const *env_suffix = getenv ("SIMPLE_BACKUP_SUFFIX");
     275      if (env_suffix && *env_suffix)
     276        simple_backup_suffix = env_suffix;
     277      else
     278        simple_backup_suffix = "~";
     279    }
     280
    271281  /* Allow room for simple or ".~N~" backups.  The guess must be at
    272282     least sizeof ".~1~", but otherwise will be adjusted as needed.  */
  • TabularUnified coreutils/trunk/lib/chdir-long.c

    r1648 r1953  
    213213# include "error.h"
    214214
    215 char *program_name;
    216 
    217215int
    218216main (int argc, char *argv[])
     
    222220  int len;
    223221
    224   program_name = argv[0];
    225222  atexit (close_stdout);
    226223
  • TabularUnified coreutils/trunk/lib/error.c

    r1648 r1953  
    4343# define _GL_ATTRIBUTE_FORMAT_PRINTF(a, b)
    4444# define _GL_ARG_NONNULL(a)
     45#else
     46# include "getprogname.h"
    4547#endif
    4648
     
    114116# endif
    115117
    116 /* The calling program should define program_name and set it to the
    117    name of the executing program.  */
    118 extern char *program_name;
     118#define program_name getprogname ()
    119119
    120120# if HAVE_STRERROR_R || defined strerror_r
  • TabularUnified coreutils/trunk/lib/euidaccess.c

    r1648 r1953  
    199199# include <stdlib.h>
    200200
    201 char *program_name;
    202 
    203201int
    204202main (int argc, char **argv)
     
    208206  int err;
    209207
    210   program_name = argv[0];
    211208  if (argc < 3)
    212209    abort ();
  • TabularUnified coreutils/trunk/lib/fnmatch.c

    r1648 r1953  
    2323#endif
    2424
    25 #if ! defined __builtin_expect && __GNUC__ < 3
     25#if ! defined __builtin_expect && (!defined __GNUC__ || __GNUC__ < 3)
    2626# define __builtin_expect(expr, expected) (expr)
    2727#endif
     
    6767# define SIZE_MAX ((size_t) -1)
    6868#endif
     69
     70#include "flexmember.h"
    6971
    7072/* We often have to test for FNM_FILE_NAME and FNM_PERIOD being both set.  */
  • TabularUnified coreutils/trunk/lib/fnmatch_loop.c

    r1648 r1953  
    10321032  {
    10331033    struct patternlist *next;
    1034     CHAR str[1];
     1034    CHAR str[FLEXIBLE_ARRAY_MEMBER];
    10351035  } *list = NULL;
    10361036  struct patternlist **lastp = &list;
     
    10841084                    : p - startp + 1UL);                                      \
    10851085            plensize = plen * sizeof (CHAR);                                  \
    1086             newpsize = offsetof (struct patternlist, str) + plensize;         \
     1086            newpsize = FLEXSIZEOF (struct patternlist, str, plensize);        \
    10871087            if ((size_t) -1 / sizeof (CHAR) < plen                            \
    10881088                || newpsize < offsetof (struct patternlist, str)              \
  • TabularUnified coreutils/trunk/lib/freopen.c

    r1648 r1953  
    2020   the system's <stdio.h> here, so that orig_freopen doesn't recurse to
    2121   rpl_freopen.  */
    22 #define __need_FILE
     22#define _GL_ALREADY_INCLUDING_STDIO_H
    2323#include <config.h>
    2424
    2525/* Get the original definition of freopen.  It might be defined as a macro.  */
    2626#include <stdio.h>
    27 #undef __need_FILE
     27#undef _GL_ALREADY_INCLUDING_STDIO_H
    2828
    2929#include <errno.h>
     
    4040#include "stdio.h"
    4141
     42#include <fcntl.h>
    4243#include <string.h>
     44#include <unistd.h>
    4345
    4446FILE *
     
    4648{
    4749  FILE *result;
    48 
    4950#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
    50   if (filename != NULL && strcmp (filename, "/dev/null") == 0)
    51     filename = "NUL";
     51  char const *null_device = "NUL";
     52  if (filename && strcmp (filename, "/dev/null") == 0)
     53    filename = null_device;
     54#else
     55  char const *null_device = "/dev/null";
    5256#endif
    5357
    54   /* Clear errno to check the success of freopen() with it */
     58#ifdef __KLIBC__
    5559  errno = 0;
     60#endif
    5661
    5762  result = orig_freopen (filename, mode, stream);
    5863
     64  if (!result)
     65    {
    5966#ifdef __KLIBC__
    60   /* On OS/2 kLIBC, freopen() returns NULL even if it is successful
    61      if filename is NULL. */
    62   if (!filename && !result && !errno)
    63     result = stream;
     67      /* On OS/2 kLIBC, freopen returns NULL even if it is successful
     68         if filename is NULL. */
     69      if (!filename && !errno)
     70        result = stream;
    6471#endif
     72    }
     73  else if (filename)
     74    {
     75      int fd = fileno (result);
     76      if (dup2 (fd, fd) < 0 && errno == EBADF)
     77        {
     78          int nullfd = open (null_device, O_RDONLY | O_CLOEXEC);
     79          int err = 0;
     80          if (nullfd != fd)
     81            {
     82              if (dup2 (nullfd, fd) < 0)
     83                err = 1;
     84              close (nullfd);
     85            }
     86          if (!err)
     87            result = orig_freopen (filename, mode, result);
     88        }
     89    }
    6590
    6691  return result;
  • TabularUnified coreutils/trunk/lib/ftoastr.h

    r1648 r1953  
    8989#  define _GL_FLOAT_DIG_BITS_BOUND 4
    9090# else /* no machine is this bad, but let's be complete */
    91 #  define _GL_FLOAT_DIG_BITS_BOUND (CHAR_BIT * (int) sizeof (int) - 1)
     91#  define _GL_FLOAT_DIG_BITS_BOUND ((int) TYPE_WIDTH (int) - 1)
    9292# endif
    9393
  • TabularUnified coreutils/trunk/lib/fts.c

    r1652 r1953  
    4747#include <config.h>
    4848
    49 #if defined(LIBC_SCCS) && !defined(lint)
     49#if defined LIBC_SCCS && !defined GCC_LINT && !defined lint
    5050static char sccsid[] = "@(#)fts.c       8.6 (Berkeley) 8/14/94";
    51 #endif /* LIBC_SCCS and not lint */
     51#endif
    5252
    5353#include "fts_.h"
     
    7777   supported.  */
    7878# include "cloexec.h"
     79# include "flexmember.h"
    7980# include "openat.h"
    8081# include "same-inode.h"
     
    14621463                bool is_dir;
    14631464                size_t d_namelen;
     1465                __set_errno (0);
    14641466                struct dirent *dp = readdir(cur->fts_dirp);
    1465                 if (dp == NULL)
     1467                if (dp == NULL) {
     1468                        if (errno) {
     1469                                cur->fts_errno = errno;
     1470                                /* If we've not read any items yet, treat
     1471                                   the error as if we can't access the dir.  */
     1472                                cur->fts_info = (continue_readdir || nitems)
     1473                                                ? FTS_ERR : FTS_DNR;
     1474                        }
    14661475                        break;
     1476                }
    14671477                if (!ISSET(FTS_SEEDOT) && ISDOT(dp->d_name))
    14681478                        continue;
     
    16231633        /* If didn't find anything, return NULL. */
    16241634        if (!nitems) {
    1625                 if (type == BREAD)
     1635                if (type == BREAD
     1636                    && cur->fts_info != FTS_DNR && cur->fts_info != FTS_ERR)
    16261637                        cur->fts_info = FTS_DP;
    16271638                fts_lfree(head);
     
    19161927         * structure and the file name in one chunk.
    19171928         */
    1918         len = offsetof(FTSENT, fts_name) + namelen + 1;
    1919         /* Align the allocation size so that it works for FTSENT,
    1920            so that trailing padding may be referenced by direct access
    1921            to the flexible array members, without triggering undefined behavior
    1922            by accessing bytes beyond the heap allocation.  This implicit access
    1923            was seen for example with ISDOT() and GCC 5.1.1 at -O2.
    1924            Do not use alignof (FTSENT) here, since C11 prohibits
    1925            taking the alignment of a structure containing a flexible
    1926            array member.  */
    1927         len += alignof (max_align_t) - 1;
    1928         len &= ~ (alignof (max_align_t) - 1);
     1929        len = FLEXSIZEOF(FTSENT, fts_name, namelen + 1);
    19291930        if ((p = malloc(len)) == NULL)
    19301931                return (NULL);
  • TabularUnified coreutils/trunk/lib/get-permissions.c

    r1648 r1953  
    103103       pathconf (name, _PC_ACL_ENABLED)
    104104       fpathconf (desc, _PC_ACL_ENABLED)
    105      that allows to determine which of the two kinds of ACLs is supported
     105     that allows us to determine which of the two kinds of ACLs is supported
    106106     for the given file.  But some file systems may implement this call
    107107     incorrectly, so better not use it.
  • TabularUnified coreutils/trunk/lib/getdelim.c

    r1648 r1953  
    4848#endif
    4949
     50static void
     51alloc_failed (void)
     52{
     53#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
     54  /* Avoid errno problem without using the realloc module; see:
     55     http://lists.gnu.org/archive/html/bug-gnulib/2016-08/msg00025.html  */
     56  errno = ENOMEM;
     57#endif
     58}
     59
    5060/* Read up to (and including) a DELIMITER from FP into *LINEPTR (and
    5161   NUL-terminate it).  *LINEPTR is a pointer returned from malloc (or
     
    7585      if (new_lineptr == NULL)
    7686        {
     87          alloc_failed ();
    7788          result = -1;
    7889          goto unlock_return;
     
    112123          if (new_lineptr == NULL)
    113124            {
     125              alloc_failed ();
    114126              result = -1;
    115127              goto unlock_return;
  • TabularUnified coreutils/trunk/lib/getndelim2.c

    r1648 r1953  
    5353
    5454/* Use this to suppress gcc's "...may be used before initialized" warnings. */
    55 #ifdef lint
     55#if defined GCC_LINT || defined lint
    5656# define IF_LINT(Code) Code
    5757#else
  • TabularUnified coreutils/trunk/lib/gettext.h

    r1648 r1953  
    226226#endif
    227227    {
     228      int found_translation;
    228229      memcpy (msg_ctxt_id, msgctxt, msgctxt_len - 1);
    229230      msg_ctxt_id[msgctxt_len - 1] = '\004';
    230231      memcpy (msg_ctxt_id + msgctxt_len, msgid, msgid_len);
    231232      translation = dcgettext (domain, msg_ctxt_id, category);
     233      found_translation = (translation != msg_ctxt_id);
    232234#if !_LIBGETTEXT_HAVE_VARIABLE_SIZE_ARRAYS
    233235      if (msg_ctxt_id != buf)
    234236        free (msg_ctxt_id);
    235237#endif
    236       if (translation != msg_ctxt_id)
     238      if (found_translation)
    237239        return translation;
    238240    }
     
    272274#endif
    273275    {
     276      int found_translation;
    274277      memcpy (msg_ctxt_id, msgctxt, msgctxt_len - 1);
    275278      msg_ctxt_id[msgctxt_len - 1] = '\004';
    276279      memcpy (msg_ctxt_id + msgctxt_len, msgid, msgid_len);
    277280      translation = dcngettext (domain, msg_ctxt_id, msgid_plural, n, category);
     281      found_translation = !(translation == msg_ctxt_id || translation == msgid_plural);
    278282#if !_LIBGETTEXT_HAVE_VARIABLE_SIZE_ARRAYS
    279283      if (msg_ctxt_id != buf)
    280284        free (msg_ctxt_id);
    281285#endif
    282       if (!(translation == msg_ctxt_id || translation == msgid_plural))
     286      if (found_translation)
    283287        return translation;
    284288    }
  • TabularUnified coreutils/trunk/lib/gnulib.mk

    r1650 r1953  
    2222#
    2323# Generated by gnulib-tool.
    24 # 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
     24# 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 flexmember 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
    2525
    2626
     
    962962## end   gnulib module filevercmp
    963963
     964## begin gnulib module flexmember
     965
     966
     967EXTRA_DIST += lib/flexmember.h
     968
     969## end   gnulib module flexmember
     970
    964971## begin gnulib module float
    965972
     
    14271434
    14281435## end   gnulib module getpass-gnu
     1436
     1437## begin gnulib module getprogname
     1438
     1439lib_libcoreutils_a_SOURCES += lib/getprogname.h lib/getprogname.c
     1440
     1441## end   gnulib module getprogname
    14291442
    14301443## begin gnulib module gettext-h
     
    18641877
    18651878## end   gnulib module ldtoastr
     1879
     1880## begin gnulib module limits-h
     1881
     1882BUILT_SOURCES += $(LIMITS_H)
     1883
     1884# We need the following in order to create <limits.h> when the system
     1885# doesn't have one that is compatible with GNU.
     1886if GL_GENERATE_LIMITS_H
     1887lib/limits.h: lib/limits.in.h $(top_builddir)/config.status
     1888        $(AM_V_GEN)rm -f $@-t $@ && \
     1889        { echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */' && \
     1890          sed -e 's|@''GUARD_PREFIX''@|GL|g' \
     1891              -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
     1892              -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
     1893              -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
     1894              -e 's|@''NEXT_LIMITS_H''@|$(NEXT_LIMITS_H)|g' \
     1895              < $(top_srcdir)/lib/limits.in.h; \
     1896        } > $@-t && \
     1897        mv $@-t $@
     1898else
     1899lib/limits.h: $(top_builddir)/config.status
     1900        rm -f $@
     1901endif
     1902MOSTLYCLEANFILES += lib/limits.h lib/limits.h-t
     1903
     1904EXTRA_DIST += lib/limits.in.h
     1905
     1906## end   gnulib module limits-h
    18661907
    18671908## begin gnulib module linebuffer
     
    32183259          sed -e 's|@''GUARD_PREFIX''@|GL|g' \
    32193260              -e 's|@''HAVE_SCHED_H''@|$(HAVE_SCHED_H)|g' \
     3261              -e 's|@''HAVE_SYS_CDEFS_H''@|$(HAVE_SYS_CDEFS_H)|g' \
    32203262              -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
    32213263              -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
     
    36953737              -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
    36963738              -e 's|@''NEXT_STDINT_H''@|$(NEXT_STDINT_H)|g' \
     3739              -e 's/@''HAVE_C99_STDINT_H''@/$(HAVE_C99_STDINT_H)/g' \
    36973740              -e 's/@''HAVE_SYS_TYPES_H''@/$(HAVE_SYS_TYPES_H)/g' \
    36983741              -e 's/@''HAVE_INTTYPES_H''@/$(HAVE_INTTYPES_H)/g' \
     
    39203963              -e 's|@''HAVE_PTSNAME''@|$(HAVE_PTSNAME)|g' \
    39213964              -e 's|@''HAVE_PTSNAME_R''@|$(HAVE_PTSNAME_R)|g' \
     3965              -e 's|@''HAVE_QSORT_R''@|$(HAVE_QSORT_R)|g' \
    39223966              -e 's|@''HAVE_RANDOM''@|$(HAVE_RANDOM)|g' \
    39233967              -e 's|@''HAVE_RANDOM_H''@|$(HAVE_RANDOM_H)|g' \
  • TabularUnified coreutils/trunk/lib/group-member.c

    r1648 r1953  
    9898#ifdef TEST
    9999
    100 char *program_name;
    101 
    102100int
    103101main (int argc, char **argv)
    104102{
    105103  int i;
    106 
    107   program_name = argv[0];
    108104
    109105  for (i = 1; i < argc; i++)
  • TabularUnified coreutils/trunk/lib/idcache.c

    r1648 r1953  
    2828#include <unistd.h>
    2929
     30#include "flexmember.h"
    3031#include "xalloc.h"
    3132
     
    4748/* FIXME: provide a function to free any malloc'd storage and reset lists,
    4849   so that an application can use code like this just before exiting:
    49    #ifdef lint
     50   #if defined GCC_LINT || defined lint
    5051     idcache_clear ();
    5152   #endif
     
    8485      struct passwd *pwent = getpwuid (uid);
    8586      char const *name = pwent ? pwent->pw_name : "";
    86       match = xmalloc (offsetof (struct userid, name) + strlen (name) + 1);
     87      match = xmalloc (FLEXSIZEOF (struct userid, name, strlen (name) + 1));
    8788      match->id.u = uid;
    8889      strcpy (match->name, name);
     
    128129#endif
    129130
    130   tail = xmalloc (offsetof (struct userid, name) + strlen (user) + 1);
     131  tail = xmalloc (FLEXSIZEOF (struct userid, name, strlen (user) + 1));
    131132  strcpy (tail->name, user);
    132133
     
    166167      struct group *grent = getgrgid (gid);
    167168      char const *name = grent ? grent->gr_name : "";
    168       match = xmalloc (offsetof (struct userid, name) + strlen (name) + 1);
     169      match = xmalloc (FLEXSIZEOF (struct userid, name, strlen (name) + 1));
    169170      match->id.g = gid;
    170171      strcpy (match->name, name);
     
    210211#endif
    211212
    212   tail = xmalloc (offsetof (struct userid, name) + strlen (group) + 1);
     213  tail = xmalloc (FLEXSIZEOF (struct userid, name, strlen (group) + 1));
    213214  strcpy (tail->name, group);
    214215
  • TabularUnified coreutils/trunk/lib/inet_ntop.c

    r1648 r1953  
    4141   Beware: The Code argument must not contain commas.  */
    4242#ifndef IF_LINT
    43 # ifdef lint
     43# if defined GCC_LINT || defined lint
    4444#  define IF_LINT(Code) Code
    4545# else
  • TabularUnified coreutils/trunk/lib/intprops.h

    r1648 r1953  
    11/* intprops.h -- properties of integer types
    22
    3    Copyright (C) 2001-2005, 2009-2016 Free Software Foundation, Inc.
    4 
    5    This program is free software: you can redistribute it and/or modify
    6    it under the terms of the GNU General Public License as published by
    7    the Free Software Foundation; either version 3 of the License, or
     3   Copyright (C) 2001-2016 Free Software Foundation, Inc.
     4
     5   This program is free software: you can redistribute it and/or modify it
     6   under the terms of the GNU General Public License as published
     7   by the Free Software Foundation; either version 3 of the License, or
    88   (at your option) any later version.
    99
     
    2222
    2323#include <limits.h>
     24#include <verify.h>
     25
     26#ifndef __has_builtin
     27# define __has_builtin(x) 0
     28#endif
    2429
    2530/* Return a value with the common real type of E and V and the value of V.  */
     
    3742#define TYPE_IS_INTEGER(t) ((t) 1.5 == 1)
    3843
    39 /* True if negative values of the signed integer type T use two's
    40    complement, ones' complement, or signed magnitude representation,
    41    respectively.  Much GNU code assumes two's complement, but some
    42    people like to be portable to all possible C hosts.  */
    43 #define TYPE_TWOS_COMPLEMENT(t) ((t) ~ (t) 0 == (t) -1)
    44 #define TYPE_ONES_COMPLEMENT(t) ((t) ~ (t) 0 == 0)
    45 #define TYPE_SIGNED_MAGNITUDE(t) ((t) ~ (t) 0 < (t) -1)
    46 
    47 /* True if the signed integer expression E uses two's complement.  */
    48 #define _GL_INT_TWOS_COMPLEMENT(e) (~ _GL_INT_CONVERT (e, 0) == -1)
    49 
    5044/* True if the real type T is signed.  */
    5145#define TYPE_SIGNED(t) (! ((t) 0 < (t) -1))
     
    5650
    5751
    58 /* Minimum and maximum values for integer types and expressions.  These
    59    macros have undefined behavior if T is signed and has padding bits.
    60    If this is a problem for you, please let us know how to fix it for
    61    your host.  */
     52/* Minimum and maximum values for integer types and expressions.  */
     53
     54/* The width in bits of the integer type or expression T.
     55   Padding bits are not supported; this is checked at compile-time below.  */
     56#define TYPE_WIDTH(t) (sizeof (t) * CHAR_BIT)
    6257
    6358/* The maximum and minimum values for the integer type T.  */
    64 #define TYPE_MINIMUM(t)                                                 \
    65   ((t) (! TYPE_SIGNED (t)                                               \
    66         ? (t) 0                                                         \
    67         : TYPE_SIGNED_MAGNITUDE (t)                                     \
    68         ? ~ (t) 0                                                       \
    69         : ~ TYPE_MAXIMUM (t)))
     59#define TYPE_MINIMUM(t) ((t) ~ TYPE_MAXIMUM (t))
    7060#define TYPE_MAXIMUM(t)                                                 \
    7161  ((t) (! TYPE_SIGNED (t)                                               \
    7262        ? (t) -1                                                        \
    73         : ((((t) 1 << (sizeof (t) * CHAR_BIT - 2)) - 1) * 2 + 1)))
     63        : ((((t) 1 << (TYPE_WIDTH (t) - 2)) - 1) * 2 + 1)))
    7464
    7565/* The maximum and minimum values for the type of the expression E,
     
    7767#define _GL_INT_MINIMUM(e)                                              \
    7868  (EXPR_SIGNED (e)                                                      \
    79    ? - _GL_INT_TWOS_COMPLEMENT (e) - _GL_SIGNED_INT_MAXIMUM (e)         \
     69   ? ~ _GL_SIGNED_INT_MAXIMUM (e)                                       \
    8070   : _GL_INT_CONVERT (e, 0))
    8171#define _GL_INT_MAXIMUM(e)                                              \
     
    8474   : _GL_INT_NEGATE_CONVERT (e, 1))
    8575#define _GL_SIGNED_INT_MAXIMUM(e)                                       \
    86   (((_GL_INT_CONVERT (e, 1) << (sizeof ((e) + 0) * CHAR_BIT - 2)) - 1) * 2 + 1)
    87 
    88 
    89 /* Return 1 if the __typeof__ keyword works.  This could be done by
     76  (((_GL_INT_CONVERT (e, 1) << (TYPE_WIDTH ((e) + 0) - 2)) - 1) * 2 + 1)
     77
     78/* Work around OpenVMS incompatibility with C99.  */
     79#if !defined LLONG_MAX && defined __INT64_MAX
     80# define LLONG_MAX __INT64_MAX
     81# define LLONG_MIN __INT64_MIN
     82#endif
     83
     84/* This include file assumes that signed types are two's complement without
     85   padding bits; the above macros have undefined behavior otherwise.
     86   If this is a problem for you, please let us know how to fix it for your host.
     87   As a sanity check, test the assumption for some signed types that
     88   <limits.h> bounds.  */
     89verify (TYPE_MINIMUM (signed char) == SCHAR_MIN);
     90verify (TYPE_MAXIMUM (signed char) == SCHAR_MAX);
     91verify (TYPE_MINIMUM (short int) == SHRT_MIN);
     92verify (TYPE_MAXIMUM (short int) == SHRT_MAX);
     93verify (TYPE_MINIMUM (int) == INT_MIN);
     94verify (TYPE_MAXIMUM (int) == INT_MAX);
     95verify (TYPE_MINIMUM (long int) == LONG_MIN);
     96verify (TYPE_MAXIMUM (long int) == LONG_MAX);
     97#ifdef LLONG_MAX
     98verify (TYPE_MINIMUM (long long int) == LLONG_MIN);
     99verify (TYPE_MAXIMUM (long long int) == LLONG_MAX);
     100#endif
     101/* Similarly, sanity-check one ISO/IEC TS 18661-1:2014 macro if defined.  */
     102#ifdef UINT_WIDTH
     103verify (TYPE_WIDTH (unsigned int) == UINT_WIDTH);
     104#endif
     105
     106/* Does the __typeof__ keyword work?  This could be done by
    90107   'configure', but for now it's easier to do it by hand.  */
    91 #if (2 <= __GNUC__ || defined __IBM__TYPEOF__ \
     108#if (2 <= __GNUC__ \
     109     || (1210 <= __IBMC__ && defined __IBM__TYPEOF__) \
    92110     || (0x5110 <= __SUNPRO_C && !__STDC__))
    93111# define _GL_HAVE___TYPEOF__ 1
     
    118136   applied to unsigned types of size 2, 4, 16, ... bytes.  */
    119137#define INT_STRLEN_BOUND(t)                                     \
    120   (INT_BITS_STRLEN_BOUND (sizeof (t) * CHAR_BIT                 \
    121                           - _GL_SIGNED_TYPE_OR_EXPR (t))        \
     138  (INT_BITS_STRLEN_BOUND (TYPE_WIDTH (t) - _GL_SIGNED_TYPE_OR_EXPR (t)) \
    122139   + _GL_SIGNED_TYPE_OR_EXPR (t))
    123140
     
    224241   : (max) >> (b) < (a))
    225242
     243/* True if __builtin_add_overflow (A, B, P) works when P is non-null.  */
     244#define _GL_HAS_BUILTIN_OVERFLOW \
     245  (5 <= __GNUC__ || __has_builtin (__builtin_add_overflow))
     246
     247/* True if __builtin_add_overflow_p (A, B, C) works.  */
     248#define _GL_HAS_BUILTIN_OVERFLOW_P \
     249  (7 <= __GNUC__ || __has_builtin (__builtin_add_overflow_p))
    226250
    227251/* The _GL*_OVERFLOW macros have the same restrictions as the
     
    229253   (e.g., A and B) have the same type as MIN and MAX.  Instead, they assume
    230254   that the result (e.g., A + B) has that type.  */
    231 #define _GL_ADD_OVERFLOW(a, b, min, max)                                \
    232   ((min) < 0 ? INT_ADD_RANGE_OVERFLOW (a, b, min, max)                  \
    233    : (a) < 0 ? (b) <= (a) + (b)                                         \
    234    : (b) < 0 ? (a) <= (a) + (b)                                         \
    235    : (a) + (b) < (b))
    236 #define _GL_SUBTRACT_OVERFLOW(a, b, min, max)                           \
    237   ((min) < 0 ? INT_SUBTRACT_RANGE_OVERFLOW (a, b, min, max)             \
    238    : (a) < 0 ? 1                                                        \
    239    : (b) < 0 ? (a) - (b) <= (a)                                         \
    240    : (a) < (b))
    241 #define _GL_MULTIPLY_OVERFLOW(a, b, min, max)                           \
    242   (((min) == 0 && (((a) < 0 && 0 < (b)) || ((b) < 0 && 0 < (a))))       \
    243    || INT_MULTIPLY_RANGE_OVERFLOW (a, b, min, max))
     255#if _GL_HAS_BUILTIN_OVERFLOW_P
     256# define _GL_ADD_OVERFLOW(a, b, min, max)                               \
     257   __builtin_add_overflow_p (a, b, (__typeof__ ((a) + (b))) 0)
     258# define _GL_SUBTRACT_OVERFLOW(a, b, min, max)                          \
     259   __builtin_sub_overflow_p (a, b, (__typeof__ ((a) - (b))) 0)
     260# define _GL_MULTIPLY_OVERFLOW(a, b, min, max)                          \
     261   __builtin_mul_overflow_p (a, b, (__typeof__ ((a) * (b))) 0)
     262#else
     263# define _GL_ADD_OVERFLOW(a, b, min, max)                                \
     264   ((min) < 0 ? INT_ADD_RANGE_OVERFLOW (a, b, min, max)                  \
     265    : (a) < 0 ? (b) <= (a) + (b)                                         \
     266    : (b) < 0 ? (a) <= (a) + (b)                                         \
     267    : (a) + (b) < (b))
     268# define _GL_SUBTRACT_OVERFLOW(a, b, min, max)                           \
     269   ((min) < 0 ? INT_SUBTRACT_RANGE_OVERFLOW (a, b, min, max)             \
     270    : (a) < 0 ? 1                                                        \
     271    : (b) < 0 ? (a) - (b) <= (a)                                         \
     272    : (a) < (b))
     273# define _GL_MULTIPLY_OVERFLOW(a, b, min, max)                           \
     274   (((min) == 0 && (((a) < 0 && 0 < (b)) || ((b) < 0 && 0 < (a))))       \
     275    || INT_MULTIPLY_RANGE_OVERFLOW (a, b, min, max))
     276#endif
    244277#define _GL_DIVIDE_OVERFLOW(a, b, min, max)                             \
    245278  ((min) < 0 ? (b) == _GL_INT_NEGATE_CONVERT (min, 1) && (a) < - (max)  \
     
    306339#define INT_SUBTRACT_OVERFLOW(a, b) \
    307340  _GL_BINARY_OP_OVERFLOW (a, b, _GL_SUBTRACT_OVERFLOW)
    308 #define INT_NEGATE_OVERFLOW(a) \
    309   INT_NEGATE_RANGE_OVERFLOW (a, _GL_INT_MINIMUM (a), _GL_INT_MAXIMUM (a))
     341#if _GL_HAS_BUILTIN_OVERFLOW_P
     342# define INT_NEGATE_OVERFLOW(a) INT_SUBTRACT_OVERFLOW (0, a)
     343#else
     344# define INT_NEGATE_OVERFLOW(a) \
     345   INT_NEGATE_RANGE_OVERFLOW (a, _GL_INT_MINIMUM (a), _GL_INT_MAXIMUM (a))
     346#endif
    310347#define INT_MULTIPLY_OVERFLOW(a, b) \
    311348  _GL_BINARY_OP_OVERFLOW (a, b, _GL_MULTIPLY_OVERFLOW)
     
    327364                      _GL_INT_MAXIMUM (0 * (b) + (a)))
    328365
    329 /* Compute A + B, A - B, A * B, respectively, storing the result into *R.
     366/* Store the low-order bits of A + B, A - B, A * B, respectively, into *R.
    330367   Return 1 if the result overflows.  See above for restrictions.  */
    331368#define INT_ADD_WRAPV(a, b, r) \
     
    335372#define INT_MULTIPLY_WRAPV(a, b, r) \
    336373  _GL_INT_OP_WRAPV (a, b, r, *, __builtin_mul_overflow, INT_MULTIPLY_OVERFLOW)
    337 
    338 #ifndef __has_builtin
    339 # define __has_builtin(x) 0
    340 #endif
    341374
    342375/* Nonzero if this compiler has GCC bug 68193 or Clang bug 25390.  See:
     
    352385#endif
    353386
    354 /* Store A <op> B into *R, where OP specifies the operation.
    355    BUILTIN is the builtin operation, and OVERFLOW the overflow predicate.
    356    See above for restrictions.  */
    357 #if 5 <= __GNUC__ || __has_builtin (__builtin_add_overflow)
     387/* Store the low-order bits of A <op> B into *R, where OP specifies
     388   the operation.  BUILTIN is the builtin operation, and OVERFLOW the
     389   overflow predicate.  Return 1 if the result overflows.  See above
     390   for restrictions.  */
     391#if _GL_HAS_BUILTIN_OVERFLOW
    358392# define _GL_INT_OP_WRAPV(a, b, r, op, builtin, overflow) builtin (a, b, r)
    359393#elif 201112 <= __STDC_VERSION__ && !_GL__GENERIC_BOGUS
     
    398432#  define _GL_INT_OP_WRAPV_LONGISH(a, b, r, op, overflow) \
    399433    _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned long int, \
    400                      long int, LONG_MIN, LONG_MAX))
     434                     long int, LONG_MIN, LONG_MAX)
    401435# endif
    402436#endif
     
    405439   is given by OP.  Use the unsigned type UT for calculation to avoid
    406440   overflow problems.  *R's type is T, with extremal values TMIN and
    407    TMAX.  T must be a signed integer type.  */
     441   TMAX.  T must be a signed integer type.  Return 1 if the result
     442   overflows.  */
    408443#define _GL_INT_OP_CALC(a, b, r, op, overflow, ut, t, tmin, tmax) \
    409444  (sizeof ((a) op (b)) < sizeof (t) \
  • TabularUnified coreutils/trunk/lib/long-options.c

    r1648 r1953  
    6565        case 'h':
    6666          (*usage_func) (EXIT_SUCCESS);
     67          break;
    6768
    6869        case 'v':
  • TabularUnified coreutils/trunk/lib/math.in.h

    r1648 r1953  
    6464}
    6565# define _GL_MATH_CXX_REAL_FLOATING_DECL_2(func) \
     66_GL_BEGIN_NAMESPACE                                                 \
    6667inline int                                                          \
    6768func (float f)                                                      \
     
    7879{                                                                   \
    7980  return _gl_cxx_ ## func ## l (l);                                 \
    80 }
     81}                                                                   \
     82_GL_END_NAMESPACE
    8183#endif
    8284
     
    407409# if @REPLACE_CEIL@
    408410#  if !(defined __cplusplus && defined GNULIB_NAMESPACE)
     411#   undef ceil
    409412#   define ceil rpl_ceil
    410413#  endif
     
    754757# if @REPLACE_FLOOR@
    755758#  if !(defined __cplusplus && defined GNULIB_NAMESPACE)
     759#   undef floor
    756760#   define floor rpl_floor
    757761#  endif
     
    974978# if @REPLACE_FREXP@
    975979#  if !(defined __cplusplus && defined GNULIB_NAMESPACE)
     980#   undef frexp
    976981#   define frexp rpl_frexp
    977982#  endif
     
    981986_GL_CXXALIAS_SYS (frexp, double, (double x, int *expptr));
    982987# endif
    983 _GL_CXXALIASWARN (frexp);
     988_GL_CXXALIASWARN1 (frexp, double, (double x, int *expptr));
    984989#elif defined GNULIB_POSIXCHECK
    985990# undef frexp
     
    19591964# if @REPLACE_TRUNCF@
    19601965#  if !(defined __cplusplus && defined GNULIB_NAMESPACE)
     1966#   undef truncf
    19611967#   define truncf rpl_truncf
    19621968#  endif
     
    19811987# if @REPLACE_TRUNC@
    19821988#  if !(defined __cplusplus && defined GNULIB_NAMESPACE)
     1989#   undef trunc
    19831990#   define trunc rpl_trunc
    19841991#  endif
     
    20402047# endif
    20412048# ifdef __cplusplus
    2042 #  ifdef isfinite
     2049#  if defined isfinite || defined GNULIB_NAMESPACE
    20432050_GL_MATH_CXX_REAL_FLOATING_DECL_1 (isfinite)
    20442051#   undef isfinite
     
    20672074# endif
    20682075# ifdef __cplusplus
    2069 #  ifdef isinf
     2076#  if defined isinf || defined GNULIB_NAMESPACE
    20702077_GL_MATH_CXX_REAL_FLOATING_DECL_1 (isinf)
    20712078#   undef isinf
     
    21852192# endif
    21862193# ifdef __cplusplus
    2187 #  ifdef isnan
     2194#  if defined isnan || defined GNULIB_NAMESPACE
    21882195_GL_MATH_CXX_REAL_FLOATING_DECL_1 (isnan)
    21892196#   undef isnan
     
    22062213
    22072214#if @GNULIB_SIGNBIT@
    2208 # if @REPLACE_SIGNBIT_USING_GCC@
     2215# if (@REPLACE_SIGNBIT_USING_GCC@ \
     2216      && (!defined __cplusplus || __cplusplus < 201103))
    22092217#  undef signbit
    22102218   /* GCC 4.0 and newer provides three built-ins for signbit.  */
     
    22592267# endif
    22602268# ifdef __cplusplus
    2261 #  ifdef signbit
     2269#  if defined signbit || defined GNULIB_NAMESPACE
    22622270_GL_MATH_CXX_REAL_FLOATING_DECL_1 (signbit)
    22632271#   undef signbit
  • TabularUnified coreutils/trunk/lib/mbrtowc.c

    r1648 r1953  
    2020/* Specification.  */
    2121#include <wchar.h>
     22
     23#if C_LOCALE_MAYBE_EILSEQ
     24# include "hard-locale.h"
     25# include <locale.h>
     26#endif
    2227
    2328#if GNULIB_defined_mbstate_t
     
    329334rpl_mbrtowc (wchar_t *pwc, const char *s, size_t n, mbstate_t *ps)
    330335{
     336  size_t ret;
     337  wchar_t wc;
     338
    331339# if MBRTOWC_NULL_ARG2_BUG || MBRTOWC_RETVAL_BUG || MBRTOWC_EMPTY_INPUT_BUG
    332340  if (s == NULL)
     
    343351# endif
    344352
     353  if (! pwc)
     354    pwc = &wc;
     355
    345356# if MBRTOWC_RETVAL_BUG
    346357  {
     
    358369        for (; n > 0; s++, n--)
    359370          {
    360             wchar_t wc;
    361             size_t ret = mbrtowc (&wc, s, 1, ps);
     371            ret = mbrtowc (&wc, s, 1, ps);
    362372
    363373            if (ret == (size_t)(-1))
     
    367377              {
    368378                /* The multibyte character has been completed.  */
    369                 if (pwc != NULL)
    370                   *pwc = wc;
     379                *pwc = wc;
    371380                return (wc == 0 ? 0 : count);
    372381              }
     
    377386# endif
    378387
     388  ret = mbrtowc (pwc, s, n, ps);
     389
    379390# if MBRTOWC_NUL_RETVAL_BUG
    380   {
    381     wchar_t wc;
    382     size_t ret = mbrtowc (&wc, s, n, ps);
    383 
    384     if (ret != (size_t)(-1) && ret != (size_t)(-2))
    385       {
    386         if (pwc != NULL)
    387           *pwc = wc;
    388         if (wc == 0)
    389           ret = 0;
    390       }
    391     return ret;
    392   }
    393 # else
    394   {
    395 #   if MBRTOWC_NULL_ARG1_BUG
    396     wchar_t dummy;
    397 
    398     if (pwc == NULL)
    399       pwc = &dummy;
    400 #   endif
    401 
    402     return mbrtowc (pwc, s, n, ps);
    403   }
    404 # endif
     391  if (ret < (size_t) -2 && !*pwc)
     392    return 0;
     393# endif
     394
     395# if C_LOCALE_MAYBE_EILSEQ
     396  if ((size_t) -2 <= ret && n != 0 && ! hard_locale (LC_CTYPE))
     397    {
     398      unsigned char uc = *s;
     399      *pwc = uc;
     400      return 1;
     401    }
     402# endif
     403
     404  return ret;
    405405}
    406406
  • TabularUnified coreutils/trunk/lib/mktime-internal.h

    r194 r1953  
     1/* mktime variant that also uses an offset guess
     2
     3   Copyright 2016 Free Software Foundation, Inc.
     4
     5   This program is free software; you can redistribute it and/or
     6   modify it under the terms of the GNU General Public
     7   License as published by the Free Software Foundation; either
     8   version 3 of the License, or (at your option) any later version.
     9
     10   This program is distributed in the hope that it will be useful,
     11   but WITHOUT ANY WARRANTY; without even the implied warranty of
     12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     13   General Public License for more details.
     14
     15   You should have received a copy of the GNU General Public
     16   License along with this program; if not, see
     17   <http://www.gnu.org/licenses/>.  */
     18
    119#include <time.h>
     20
     21/* mktime_offset_t is a signed type wide enough to hold a UTC offset
     22   in seconds, and used as part of the type of the offset-guess
     23   argument to mktime_internal.  Use time_t on platforms where time_t
     24   is signed, to be compatible with platforms like BeOS that export
     25   this implementation detail of mktime.  On platforms where time_t is
     26   unsigned, GNU and POSIX code can assume 'int' is at least 32 bits
     27   which is wide enough for a UTC offset.  */
     28
     29#if TIME_T_IS_SIGNED
     30typedef time_t mktime_offset_t;
     31#else
     32typedef int mktime_offset_t;
     33#endif
     34
    235time_t mktime_internal (struct tm *,
    336                        struct tm * (*) (time_t const *, struct tm *),
    4                         time_t *);
     37                        mktime_offset_t *);
  • TabularUnified coreutils/trunk/lib/mktime.c

    r1648 r1953  
    1818   <http://www.gnu.org/licenses/>.  */
    1919
    20 /* Define this to have a standalone program to test this implementation of
     20/* Define this to 1 to have a standalone program to test this implementation of
    2121   mktime.  */
    22 /* #define DEBUG_MKTIME 1 */
    23 
    24 #ifndef _LIBC
     22#ifndef DEBUG_MKTIME
     23# define DEBUG_MKTIME 0
     24#endif
     25
     26#if !defined _LIBC && !DEBUG_MKTIME
    2527# include <config.h>
    2628#endif
     
    3638
    3739#include <limits.h>
    38 
    39 #include <string.h>             /* For the real memcpy prototype.  */
    40 
    41 #if defined DEBUG_MKTIME && DEBUG_MKTIME
     40#include <stdbool.h>
     41
     42#include <intprops.h>
     43#include <verify.h>
     44
     45#if DEBUG_MKTIME
    4246# include <stdio.h>
    4347# include <stdlib.h>
     48# include <string.h>
    4449/* Make it work even if the system's libc has its own mktime routine.  */
    4550# undef mktime
    4651# define mktime my_mktime
    47 #endif /* DEBUG_MKTIME */
    48 
    49 /* Some of the code in this file assumes that signed integer overflow
    50    silently wraps around.  This assumption can't easily be programmed
    51    around, nor can it be checked for portably at compile-time or
    52    easily eliminated at run-time.
    53 
    54    Define WRAPV to 1 if the assumption is valid and if
    55      #pragma GCC optimize ("wrapv")
    56    does not trigger GCC bug 51793
    57    <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=51793>.
    58    Otherwise, define it to 0; this forces the use of slower code that,
    59    while not guaranteed by the C Standard, works on all production
    60    platforms that we know about.  */
    61 #ifndef WRAPV
    62 # if (((__GNUC__ == 4 && 4 <= __GNUC_MINOR__) || 4 < __GNUC__) \
    63       && defined __GLIBC__)
    64 #  pragma GCC optimize ("wrapv")
    65 #  define WRAPV 1
    66 # else
    67 #  define WRAPV 0
    68 # endif
    69 #endif
    70 
    71 /* Verify a requirement at compile-time (unlike assert, which is runtime).  */
    72 #define verify(name, assertion) struct name { char a[(assertion) ? 1 : -1]; }
    73 
    74 /* A signed type that is at least one bit wider than int.  */
    75 #if INT_MAX <= LONG_MAX / 2
     52#endif
     53
     54/* A signed type that can represent an integer number of years
     55   multiplied by three times the number of seconds in a year.  It is
     56   needed when converting a tm_year value times the number of seconds
     57   in a year.  The factor of three comes because these products need
     58   to be subtracted from each other, and sometimes with an offset
     59   added to them, without worrying about overflow.
     60
     61   Much of the code uses long_int to represent time_t values, to
     62   lessen the hassle of dealing with platforms where time_t is
     63   unsigned, and because long_int should suffice to represent all
     64   time_t values that mktime can generate even on platforms where
     65   time_t is excessively wide.  */
     66
     67#if INT_MAX <= LONG_MAX / 3 / 366 / 24 / 60 / 60
    7668typedef long int long_int;
    7769#else
    7870typedef long long int long_int;
    7971#endif
    80 verify (long_int_is_wide_enough, INT_MAX == INT_MAX * (long_int) 2 / 2);
     72verify (INT_MAX <= TYPE_MAXIMUM (long_int) / 3 / 366 / 24 / 60 / 60);
    8173
    8274/* Shift A right by B bits portably, by dividing A by 2**B and
    83    truncating towards minus infinity.  A and B should be free of side
    84    effects, and B should be in the range 0 <= B <= INT_BITS - 2, where
    85    INT_BITS is the number of useful bits in an int.  GNU code can
    86    assume that INT_BITS is at least 32.
     75   truncating towards minus infinity.  B should be in the range 0 <= B
     76   <= LONG_INT_BITS - 2, where LONG_INT_BITS is the number of useful
     77   bits in a long_int.  LONG_INT_BITS is at least 32.
    8778
    8879   ISO C99 says that A >> B is implementation-defined if A < 0.  Some
     
    9081   right in the usual way when A < 0, so SHR falls back on division if
    9182   ordinary A >> B doesn't seem to be the usual signed shift.  */
    92 #define SHR(a, b)                                               \
    93   ((-1 >> 1 == -1                                               \
    94     && (long_int) -1 >> 1 == -1                                 \
    95     && ((time_t) -1 >> 1 == -1 || ! TYPE_SIGNED (time_t)))      \
    96    ? (a) >> (b)                                                 \
    97    : (a) / (1 << (b)) - ((a) % (1 << (b)) < 0))
    98 
    99 /* The extra casts in the following macros work around compiler bugs,
    100    e.g., in Cray C 5.0.3.0.  */
    101 
    102 /* True if the arithmetic type T is an integer type.  bool counts as
    103    an integer.  */
    104 #define TYPE_IS_INTEGER(t) ((t) 1.5 == 1)
    105 
    106 /* True if negative values of the signed integer type T use two's
    107    complement, or if T is an unsigned integer type.  */
    108 #define TYPE_TWOS_COMPLEMENT(t) ((t) ~ (t) 0 == (t) -1)
    109 
    110 /* True if the arithmetic type T is signed.  */
    111 #define TYPE_SIGNED(t) (! ((t) 0 < (t) -1))
    112 
    113 /* The maximum and minimum values for the integer type T.  These
    114    macros have undefined behavior if T is signed and has padding bits.
    115    If this is a problem for you, please let us know how to fix it for
    116    your host.  */
    117 #define TYPE_MINIMUM(t) \
    118   ((t) (! TYPE_SIGNED (t) \
    119         ? (t) 0 \
    120         : ~ TYPE_MAXIMUM (t)))
    121 #define TYPE_MAXIMUM(t) \
    122   ((t) (! TYPE_SIGNED (t) \
    123         ? (t) -1 \
    124         : ((((t) 1 << (sizeof (t) * CHAR_BIT - 2)) - 1) * 2 + 1)))
    125 
    126 #ifndef TIME_T_MIN
    127 # define TIME_T_MIN TYPE_MINIMUM (time_t)
    128 #endif
    129 #ifndef TIME_T_MAX
    130 # define TIME_T_MAX TYPE_MAXIMUM (time_t)
    131 #endif
    132 #define TIME_T_MIDPOINT (SHR (TIME_T_MIN + TIME_T_MAX, 1) + 1)
    133 
    134 verify (time_t_is_integer, TYPE_IS_INTEGER (time_t));
    135 verify (twos_complement_arithmetic,
    136         (TYPE_TWOS_COMPLEMENT (int)
    137          && TYPE_TWOS_COMPLEMENT (long_int)
    138          && TYPE_TWOS_COMPLEMENT (time_t)));
     83
     84static long_int
     85shr (long_int a, int b)
     86{
     87  long_int one = 1;
     88  return (-one >> 1 == -1
     89          ? a >> b
     90          : a / (one << b) - (a % (one << b) < 0));
     91}
     92
     93/* Bounds for the intersection of time_t and long_int.  */
     94
     95static long_int const mktime_min
     96  = ((TYPE_SIGNED (time_t) && TYPE_MINIMUM (time_t) < TYPE_MINIMUM (long_int))
     97     ? TYPE_MINIMUM (long_int) : TYPE_MINIMUM (time_t));
     98static long_int const mktime_max
     99  = (TYPE_MAXIMUM (long_int) < TYPE_MAXIMUM (time_t)
     100     ? TYPE_MAXIMUM (long_int) : TYPE_MAXIMUM (time_t));
     101
     102verify (TYPE_IS_INTEGER (time_t));
    139103
    140104#define EPOCH_YEAR 1970
    141105#define TM_YEAR_BASE 1900
    142 verify (base_year_is_a_multiple_of_100, TM_YEAR_BASE % 100 == 0);
    143 
    144 /* Return 1 if YEAR + TM_YEAR_BASE is a leap year.  */
    145 static int
     106verify (TM_YEAR_BASE % 100 == 0);
     107
     108/* Is YEAR + TM_YEAR_BASE a leap year?  */
     109static bool
    146110leapyear (long_int year)
    147111{
     
    167131
    168132
    169 #ifndef _LIBC
     133#ifdef _LIBC
     134typedef time_t mktime_offset_t;
     135#else
    170136/* Portable standalone applications should supply a <time.h> that
    171137   declares a POSIX-compliant localtime_r, for the benefit of older
     
    178144#endif
    179145
    180 /* Return 1 if the values A and B differ according to the rules for
    181    tm_isdst: A and B differ if one is zero and the other positive.  */
    182 static int
     146/* Do the values A and B differ according to the rules for tm_isdst?
     147   A and B differ if one is zero and the other positive.  */
     148static bool
    183149isdst_differ (int a, int b)
    184150{
     
    191157
    192158   The YEAR values uses the same numbering as TP->tm_year.  Values
    193    need not be in the usual range.  However, YEAR1 must not be less
    194    than 2 * INT_MIN or greater than 2 * INT_MAX.
    195 
    196    The result may overflow.  It is the caller's responsibility to
    197    detect overflow.  */
    198 
    199 static time_t
     159   need not be in the usual range.  However, YEAR1 must not overflow
     160   when multiplied by three times the number of seconds in a year, and
     161   likewise for YDAY1 and three times the number of seconds in a day.  */
     162
     163static long_int
    200164ydhms_diff (long_int year1, long_int yday1, int hour1, int min1, int sec1,
    201165            int year0, int yday0, int hour0, int min0, int sec0)
    202166{
    203   verify (C99_integer_division, -1 / 2 == 0);
     167  verify (-1 / 2 == 0);
    204168
    205169  /* Compute intervening leap days correctly even if year is negative.
    206170     Take care to avoid integer overflow here.  */
    207   int a4 = SHR (year1, 2) + SHR (TM_YEAR_BASE, 2) - ! (year1 & 3);
    208   int b4 = SHR (year0, 2) + SHR (TM_YEAR_BASE, 2) - ! (year0 & 3);
     171  int a4 = shr (year1, 2) + shr (TM_YEAR_BASE, 2) - ! (year1 & 3);
     172  int b4 = shr (year0, 2) + shr (TM_YEAR_BASE, 2) - ! (year0 & 3);
    209173  int a100 = a4 / 25 - (a4 % 25 < 0);
    210174  int b100 = b4 / 25 - (b4 % 25 < 0);
    211   int a400 = SHR (a100, 2);
    212   int b400 = SHR (b100, 2);
     175  int a400 = shr (a100, 2);
     176  int b400 = shr (b100, 2);
    213177  int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
    214178
    215   /* Compute the desired time in time_t precision.  Overflow might
    216      occur here.  */
    217   time_t tyear1 = year1;
    218   time_t years = tyear1 - year0;
    219   time_t days = 365 * years + yday1 - yday0 + intervening_leap_days;
    220   time_t hours = 24 * days + hour1 - hour0;
    221   time_t minutes = 60 * hours + min1 - min0;
    222   time_t seconds = 60 * minutes + sec1 - sec0;
     179  /* Compute the desired time without overflowing.  */
     180  long_int years = year1 - year0;
     181  long_int days = 365 * years + yday1 - yday0 + intervening_leap_days;
     182  long_int hours = 24 * days + hour1 - hour0;
     183  long_int minutes = 60 * hours + min1 - min0;
     184  long_int seconds = 60 * minutes + sec1 - sec0;
    223185  return seconds;
    224186}
    225187
    226 /* Return the average of A and B, even if A + B would overflow.  */
    227 static time_t
    228 time_t_avg (time_t a, time_t b)
    229 {
    230   return SHR (a, 1) + SHR (b, 1) + (a & b & 1);
    231 }
    232 
    233 /* Return 1 if A + B does not overflow.  If time_t is unsigned and if
    234    B's top bit is set, assume that the sum represents A - -B, and
    235    return 1 if the subtraction does not wrap around.  */
    236 static int
    237 time_t_add_ok (time_t a, time_t b)
    238 {
    239   if (! TYPE_SIGNED (time_t))
    240     {
    241       time_t sum = a + b;
    242       return (sum < a) == (TIME_T_MIDPOINT <= b);
    243     }
    244   else if (WRAPV)
    245     {
    246       time_t sum = a + b;
    247       return (sum < a) == (b < 0);
    248     }
    249   else
    250     {
    251       time_t avg = time_t_avg (a, b);
    252       return TIME_T_MIN / 2 <= avg && avg <= TIME_T_MAX / 2;
    253     }
    254 }
    255 
    256 /* Return 1 if A + B does not overflow.  */
    257 static int
    258 time_t_int_add_ok (time_t a, int b)
    259 {
    260   verify (int_no_wider_than_time_t, INT_MAX <= TIME_T_MAX);
    261   if (WRAPV)
    262     {
    263       time_t sum = a + b;
    264       return (sum < a) == (b < 0);
    265     }
    266   else
    267     {
    268       int a_odd = a & 1;
    269       time_t avg = SHR (a, 1) + (SHR (b, 1) + (a_odd & b));
    270       return TIME_T_MIN / 2 <= avg && avg <= TIME_T_MAX / 2;
    271     }
     188/* Return the average of A and B, even if A + B would overflow.
     189   Round toward positive infinity.  */
     190static long_int
     191long_int_avg (long_int a, long_int b)
     192{
     193  return shr (a, 1) + shr (b, 1) + ((a | b) & 1);
    272194}
    273195
    274196/* Return a time_t value corresponding to (YEAR-YDAY HOUR:MIN:SEC),
    275    assuming that *T corresponds to *TP and that no clock adjustments
     197   assuming that T corresponds to *TP and that no clock adjustments
    276198   occurred between *TP and the desired time.
    277    If TP is null, return a value not equal to *T; this avoids false matches.
    278    If overflow occurs, yield the minimal or maximal value, except do not
    279    yield a value equal to *T.  */
    280 static time_t
     199   Although T and the returned value are of type long_int,
     200   they represent time_t values and must be in time_t range.
     201   If TP is null, return a value not equal to T; this avoids false matches.
     202   YEAR and YDAY must not be so large that multiplying them by three times the
     203   number of seconds in a year (or day, respectively) would overflow long_int.
     204   If the returned value would be out of range, yield the minimal or
     205   maximal in-range value, except do not yield a value equal to T.  */
     206static long_int
    281207guess_time_tm (long_int year, long_int yday, int hour, int min, int sec,
    282                const time_t *t, const struct tm *tp)
     208               long_int t, const struct tm *tp)
    283209{
    284210  if (tp)
    285211    {
    286       time_t d = ydhms_diff (year, yday, hour, min, sec,
    287                              tp->tm_year, tp->tm_yday,
    288                              tp->tm_hour, tp->tm_min, tp->tm_sec);
    289       if (time_t_add_ok (*t, d))
    290         return *t + d;
     212      long_int result;
     213      long_int d = ydhms_diff (year, yday, hour, min, sec,
     214                               tp->tm_year, tp->tm_yday,
     215                               tp->tm_hour, tp->tm_min, tp->tm_sec);
     216      if (! INT_ADD_WRAPV (t, d, &result))
     217        return result;
    291218    }
    292219
     
    296223     match; and don't oscillate between two values, as that would
    297224     confuse the spring-forward gap detector.  */
    298   return (*t < TIME_T_MIDPOINT
    299           ? (*t <= TIME_T_MIN + 1 ? *t + 1 : TIME_T_MIN)
    300           : (TIME_T_MAX - 1 <= *t ? *t - 1 : TIME_T_MAX));
     225  return (t < long_int_avg (mktime_min, mktime_max)
     226          ? (t <= mktime_min + 1 ? t + 1 : mktime_min)
     227          : (mktime_max - 1 <= t ? t - 1 : mktime_max));
     228}
     229
     230/* Use CONVERT to convert T to a struct tm value in *TM.  T must be in
     231   range for time_t.  Return TM if successful, NULL if T is out of
     232   range for CONVERT.  */
     233static struct tm *
     234convert_time (struct tm *(*convert) (const time_t *, struct tm *),
     235              long_int t, struct tm *tm)
     236{
     237  time_t x = t;
     238  return convert (&x, tm);
    301239}
    302240
    303241/* Use CONVERT to convert *T to a broken down time in *TP.
    304242   If *T is out of range for conversion, adjust it so that
    305    it is the nearest in-range value and then convert that.  */
     243   it is the nearest in-range value and then convert that.
     244   A value is in range if it fits in both time_t and long_int.  */
    306245static struct tm *
    307246ranged_convert (struct tm *(*convert) (const time_t *, struct tm *),
    308                 time_t *t, struct tm *tp)
    309 {
    310   struct tm *r = convert (t, tp);
     247                long_int *t, struct tm *tp)
     248{
     249  struct tm *r;
     250  if (*t < mktime_min)
     251    *t = mktime_min;
     252  else if (mktime_max < *t)
     253    *t = mktime_max;
     254  r = convert_time (convert, *t, tp);
    311255
    312256  if (!r && *t)
    313257    {
    314       time_t bad = *t;
    315       time_t ok = 0;
    316 
    317       /* BAD is a known unconvertible time_t, and OK is a known good one.
     258      long_int bad = *t;
     259      long_int ok = 0;
     260
     261      /* BAD is a known unconvertible value, and OK is a known good one.
    318262         Use binary search to narrow the range between BAD and OK until
    319263         they differ by 1.  */
    320       while (bad != ok + (bad < 0 ? -1 : 1))
     264      while (true)
    321265        {
    322           time_t mid = *t = time_t_avg (ok, bad);
    323           r = convert (t, tp);
     266          long_int mid = long_int_avg (ok, bad);
     267          if (mid != ok && mid != bad)
     268            break;
     269          r = convert_time (convert, mid, tp);
    324270          if (r)
    325271            ok = mid;
     
    332278          /* The last conversion attempt failed;
    333279             revert to the most recent successful attempt.  */
    334           *t = ok;
    335           r = convert (t, tp);
     280          r = convert_time (convert, ok, tp);
    336281        }
    337282    }
     
    339284  return r;
    340285}
    341 
    342286
    343287/* Convert *TP to a time_t value, inverting
     
    350294__mktime_internal (struct tm *tp,
    351295                   struct tm *(*convert) (const time_t *, struct tm *),
    352                    time_t *offset)
    353 {
    354   time_t t, gt, t0, t1, t2;
     296                   mktime_offset_t *offset)
     297{
     298  long_int t, gt, t0, t1, t2, dt;
    355299  struct tm tm;
    356300
     
    382326
    383327  /* The other values need not be in range:
    384      the remaining code handles minor overflows correctly,
    385      assuming int and time_t arithmetic wraps around.
    386      Major overflows are caught at the end.  */
     328     the remaining code handles overflows correctly.  */
    387329
    388330  /* Calculate day of year from year, month, and day of month.
     
    394336  long_int yday = mon_yday + lmday;
    395337
    396   time_t guessed_offset = *offset;
     338  int negative_offset_guess;
    397339
    398340  int sec_requested = sec;
     
    411353     time.  */
    412354
     355  INT_SUBTRACT_WRAPV (0, *offset, &negative_offset_guess);
    413356  t0 = ydhms_diff (year, yday, hour, min, sec,
    414                    EPOCH_YEAR - TM_YEAR_BASE, 0, 0, 0, - guessed_offset);
    415 
    416   if (TIME_T_MAX / INT_MAX / 366 / 24 / 60 / 60 < 3)
    417     {
    418       /* time_t isn't large enough to rule out overflows, so check
    419          for major overflows.  A gross check suffices, since if t0
    420          has overflowed, it is off by a multiple of TIME_T_MAX -
    421          TIME_T_MIN + 1.  So ignore any component of the difference
    422          that is bounded by a small value.  */
    423 
    424       /* Approximate log base 2 of the number of time units per
    425          biennium.  A biennium is 2 years; use this unit instead of
    426          years to avoid integer overflow.  For example, 2 average
    427          Gregorian years are 2 * 365.2425 * 24 * 60 * 60 seconds,
    428          which is 63113904 seconds, and rint (log2 (63113904)) is
    429          26.  */
    430       int ALOG2_SECONDS_PER_BIENNIUM = 26;
    431       int ALOG2_MINUTES_PER_BIENNIUM = 20;
    432       int ALOG2_HOURS_PER_BIENNIUM = 14;
    433       int ALOG2_DAYS_PER_BIENNIUM = 10;
    434       int LOG2_YEARS_PER_BIENNIUM = 1;
    435 
    436       int approx_requested_biennia =
    437         (SHR (year_requested, LOG2_YEARS_PER_BIENNIUM)
    438          - SHR (EPOCH_YEAR - TM_YEAR_BASE, LOG2_YEARS_PER_BIENNIUM)
    439          + SHR (mday, ALOG2_DAYS_PER_BIENNIUM)
    440          + SHR (hour, ALOG2_HOURS_PER_BIENNIUM)
    441          + SHR (min, ALOG2_MINUTES_PER_BIENNIUM)
    442          + (LEAP_SECONDS_POSSIBLE
    443             ? 0
    444             : SHR (sec, ALOG2_SECONDS_PER_BIENNIUM)));
    445 
    446       int approx_biennia = SHR (t0, ALOG2_SECONDS_PER_BIENNIUM);
    447       int diff = approx_biennia - approx_requested_biennia;
    448       int approx_abs_diff = diff < 0 ? -1 - diff : diff;
    449 
    450       /* IRIX 4.0.5 cc miscalculates TIME_T_MIN / 3: it erroneously
    451          gives a positive value of 715827882.  Setting a variable
    452          first then doing math on it seems to work.
    453          (ghazi@caip.rutgers.edu) */
    454       time_t time_t_max = TIME_T_MAX;
    455       time_t time_t_min = TIME_T_MIN;
    456       time_t overflow_threshold =
    457         (time_t_max / 3 - time_t_min / 3) >> ALOG2_SECONDS_PER_BIENNIUM;
    458 
    459       if (overflow_threshold < approx_abs_diff)
    460         {
    461           /* Overflow occurred.  Try repairing it; this might work if
    462              the time zone offset is enough to undo the overflow.  */
    463           time_t repaired_t0 = -1 - t0;
    464           approx_biennia = SHR (repaired_t0, ALOG2_SECONDS_PER_BIENNIUM);
    465           diff = approx_biennia - approx_requested_biennia;
    466           approx_abs_diff = diff < 0 ? -1 - diff : diff;
    467           if (overflow_threshold < approx_abs_diff)
    468             return -1;
    469           guessed_offset += repaired_t0 - t0;
    470           t0 = repaired_t0;
    471         }
    472     }
     357                   EPOCH_YEAR - TM_YEAR_BASE, 0, 0, 0, negative_offset_guess);
    473358
    474359  /* Repeatedly use the error to improve the guess.  */
    475360
    476361  for (t = t1 = t2 = t0, dst2 = 0;
    477        (gt = guess_time_tm (year, yday, hour, min, sec, &t,
     362       (gt = guess_time_tm (year, yday, hour, min, sec, t,
    478363                            ranged_convert (convert, &t, &tm)),
    479364        t != gt);
     
    532417      for (delta = stride; delta < delta_bound; delta += stride)
    533418        for (direction = -1; direction <= 1; direction += 2)
    534           if (time_t_int_add_ok (t, delta * direction))
    535             {
    536               time_t ot = t + delta * direction;
    537               struct tm otm;
    538               ranged_convert (convert, &ot, &otm);
    539               if (! isdst_differ (isdst, otm.tm_isdst))
    540                 {
    541                   /* We found the desired tm_isdst.
    542                      Extrapolate back to the desired time.  */
    543                   t = guess_time_tm (year, yday, hour, min, sec, &ot, &otm);
    544                   ranged_convert (convert, &t, &tm);
    545                   goto offset_found;
    546                 }
    547             }
     419          {
     420            long_int ot;
     421            if (! INT_ADD_WRAPV (t, delta * direction, &ot))
     422              {
     423                struct tm otm;
     424                ranged_convert (convert, &ot, &otm);
     425                if (! isdst_differ (isdst, otm.tm_isdst))
     426                  {
     427                    /* We found the desired tm_isdst.
     428                       Extrapolate back to the desired time.  */
     429                    t = guess_time_tm (year, yday, hour, min, sec, ot, &otm);
     430                    ranged_convert (convert, &t, &tm);
     431                    goto offset_found;
     432                  }
     433              }
     434          }
    548435    }
    549436
    550437 offset_found:
    551   *offset = guessed_offset + t - t0;
     438  /* Set *OFFSET to the low-order bits of T - T0 - NEGATIVE_OFFSET_GUESS.
     439     This is just a heuristic to speed up the next mktime call, and
     440     correctness is unaffected if integer overflow occurs here.  */
     441  INT_SUBTRACT_WRAPV (t, t0, &dt);
     442  INT_SUBTRACT_WRAPV (dt, negative_offset_guess, offset);
    552443
    553444  if (LEAP_SECONDS_POSSIBLE && sec_requested != tm.tm_sec)
     
    555446      /* Adjust time to reflect the tm_sec requested, not the normalized value.
    556447         Also, repair any damage from a false match due to a leap second.  */
    557       int sec_adjustment = (sec == 0 && tm.tm_sec == 60) - sec;
    558       if (! time_t_int_add_ok (t, sec_requested))
     448      long_int sec_adjustment = sec == 0 && tm.tm_sec == 60;
     449      sec_adjustment -= sec;
     450      sec_adjustment += sec_requested;
     451      if (INT_ADD_WRAPV (t, sec_adjustment, &t)
     452          || ! (mktime_min <= t && t <= mktime_max)
     453          || ! convert_time (convert, t, &tm))
    559454        return -1;
    560       t1 = t + sec_requested;
    561       if (! time_t_int_add_ok (t1, sec_adjustment))
    562         return -1;
    563       t2 = t1 + sec_adjustment;
    564       if (! convert (&t2, &tm))
    565         return -1;
    566       t = t2;
    567455    }
    568456
     
    572460
    573461
    574 /* FIXME: This should use a signed type wide enough to hold any UTC
    575    offset in seconds.  'int' should be good enough for GNU code.  We
    576    can't fix this unilaterally though, as other modules invoke
    577    __mktime_internal.  */
    578 static time_t localtime_offset;
     462static mktime_offset_t localtime_offset;
    579463
    580464/* Convert *TP to a time_t value.  */
     
    587471     be set as if the tzset() function had been called.  */
    588472  __tzset ();
     473#elif HAVE_TZSET
     474  tzset ();
    589475#endif
    590476
     
    602488
    603489
    604 #if defined DEBUG_MKTIME && DEBUG_MKTIME
     490#if DEBUG_MKTIME
    605491
    606492static int
     
    654540  char trailer;
    655541
     542  /* Sanity check, plus call tzset.  */
     543  tl = 0;
     544  if (! localtime (&tl))
     545    {
     546      printf ("localtime (0) fails\n");
     547      status = 1;
     548    }
     549
    656550  if ((argc == 3 || argc == 4)
    657551      && (sscanf (argv[1], "%d-%d-%d%c",
     
    667561      tmk = tm;
    668562      tl = mktime (&tmk);
    669       lt = localtime (&tl);
    670       if (lt)
    671         {
    672           tml = *lt;
    673           lt = &tml;
    674         }
     563      lt = localtime_r (&tl, &tml);
    675564      printf ("mktime returns %ld == ", (long int) tl);
    676565      print_tm (&tmk);
     
    687576        for (tl = from; by < 0 ? to <= tl : tl <= to; tl = tl1)
    688577          {
    689             lt = localtime (&tl);
     578            lt = localtime_r (&tl, &tml);
    690579            if (lt)
    691580              {
    692                 tmk = tml = *lt;
     581                tmk = tml;
    693582                tk = mktime (&tmk);
    694583                status |= check_result (tk, tmk, tl, &tml);
     
    696585            else
    697586              {
    698                 printf ("localtime (%ld) yields 0\n", (long int) tl);
     587                printf ("localtime_r (%ld) yields 0\n", (long int) tl);
    699588                status = 1;
    700589              }
     
    707596          {
    708597            /* Null benchmark.  */
    709             lt = localtime (&tl);
     598            lt = localtime_r (&tl, &tml);
    710599            if (lt)
    711600              {
    712                 tmk = tml = *lt;
     601                tmk = tml;
    713602                tk = tl;
    714603                status |= check_result (tk, tmk, tl, &tml);
     
    716605            else
    717606              {
    718                 printf ("localtime (%ld) yields 0\n", (long int) tl);
     607                printf ("localtime_r (%ld) yields 0\n", (long int) tl);
    719608                status = 1;
    720609              }
  • TabularUnified coreutils/trunk/lib/mountlist.c

    r1648 r1953  
    3636#if HAVE_SYS_PARAM_H
    3737# include <sys/param.h>
     38#endif
     39
     40#if MAJOR_IN_MKDEV
     41# include <sys/mkdev.h>
     42#elif MAJOR_IN_SYSMACROS
     43# include <sys/sysmacros.h>
    3844#endif
    3945
     
    218224#ifndef ME_REMOTE
    219225/* A file system is "remote" if its Fs_name contains a ':'
    220    or if (it is of type (smbfs or cifs) and its Fs_name starts with '//').  */
     226   or if (it is of type (smbfs or cifs) and its Fs_name starts with '//')
     227   or Fs_name is equal to "-hosts" (used by autofs to mount remote fs).  */
    221228# define ME_REMOTE(Fs_name, Fs_type)            \
    222229    (strchr (Fs_name, ':') != NULL              \
     
    224231         && (Fs_name)[1] == '/'                 \
    225232         && (strcmp (Fs_type, "smbfs") == 0     \
    226              || strcmp (Fs_type, "cifs") == 0)))
     233             || strcmp (Fs_type, "cifs") == 0)) \
     234     || (strcmp("-hosts", Fs_name) == 0))
    227235#endif
    228236
     
    10691077        struct dirent *result;
    10701078
     1079        /* FIXME: readdir_r is planned to be withdrawn from POSIX and
     1080           marked obsolescent in glibc.  Use readdir instead.  */
    10711081        if (readdir_r (dirp, &entry, &result) || result == NULL)
    10721082          break;
  • TabularUnified coreutils/trunk/lib/nl_langinfo.c

    r1648 r1953  
    3535{
    3636  static char buf[2 + 10 + 1];
    37   size_t buflen = 0;
    3837  char const *locale = setlocale (LC_CTYPE, NULL);
    3938  char *codeset = buf;
     
    10099# if GNULIB_defined_T_FMT_AMPM
    101100    case T_FMT_AMPM:
    102       return "%I:%M:%S %p";
     101      return (char *) "%I:%M:%S %p";
    103102# endif
    104103# if GNULIB_defined_ERA
     
    107106         of the form "direction:offset:start_date:end_date:era_name:era_format"
    108107         with an empty string at the end.  */
    109       return "";
     108      return (char *) "";
    110109    case ERA_D_FMT:
    111110      /* The %Ex conversion in strftime behaves like %x if the locale does not
     
    126125      /* The format is not standardized.  In glibc it is a sequence of 10
    127126         strings, appended in memory.  */
    128       return "\0\0\0\0\0\0\0\0\0\0";
     127      return (char *) "\0\0\0\0\0\0\0\0\0\0";
    129128# endif
    130129# if GNULIB_defined_YESEXPR || !FUNC_NL_LANGINFO_YESEXPR_WORKS
    131130    case YESEXPR:
    132       return "^[yY]";
     131      return (char *) "^[yY]";
    133132    case NOEXPR:
    134       return "^[nN]";
     133      return (char *) "^[nN]";
    135134# endif
    136135    default:
     
    164163      }
    165164# ifdef __BEOS__
    166       return "UTF-8";
     165      return (char *) "UTF-8";
    167166# else
    168       return "ISO-8859-1";
     167      return (char *) "ISO-8859-1";
    169168# endif
    170169    /* nl_langinfo items of the LC_NUMERIC category */
     
    179178    case D_T_FMT:
    180179    case ERA_D_T_FMT:
    181       return "%a %b %e %H:%M:%S %Y";
     180      return (char *) "%a %b %e %H:%M:%S %Y";
    182181    case D_FMT:
    183182    case ERA_D_FMT:
    184       return "%m/%d/%y";
     183      return (char *) "%m/%d/%y";
    185184    case T_FMT:
    186185    case ERA_T_FMT:
    187       return "%H:%M:%S";
     186      return (char *) "%H:%M:%S";
    188187    case T_FMT_AMPM:
    189       return "%I:%M:%S %p";
     188      return (char *) "%I:%M:%S %p";
    190189    case AM_STR:
    191190      if (!strftime (nlbuf, sizeof nlbuf, "%p", &tmm))
    192         return "AM";
     191        return (char *) "AM";
    193192      return nlbuf;
    194193    case PM_STR:
    195194      tmm.tm_hour = 12;
    196195      if (!strftime (nlbuf, sizeof nlbuf, "%p", &tmm))
    197         return "PM";
     196        return (char *) "PM";
    198197      return nlbuf;
    199198    case DAY_1:
     
    275274      }
    276275    case ERA:
    277       return "";
     276      return (char *) "";
    278277    case ALT_DIGITS:
    279       return "\0\0\0\0\0\0\0\0\0\0";
     278      return (char *) "\0\0\0\0\0\0\0\0\0\0";
    280279    /* nl_langinfo items of the LC_MONETARY category.  */
    281280    case CRNCYSTR:
     
    312311       TODO: Really use the locale. */
    313312    case YESEXPR:
    314       return "^[yY]";
     313      return (char *) "^[yY]";
    315314    case NOEXPR:
    316       return "^[nN]";
     315      return (char *) "^[nN]";
    317316    default:
    318       return "";
     317      return (char *) "";
    319318    }
    320319}
  • TabularUnified coreutils/trunk/lib/obstack.c

    r1648 r1953  
    349349   variable by default points to the internal function
    350350   'print_and_abort'.  */
    351 void (*obstack_alloc_failed_handler) (void) = print_and_abort;
     351__attribute_noreturn__ void (*obstack_alloc_failed_handler) (void)
     352  = print_and_abort;
    352353# endif /* !_OBSTACK_NO_ERROR_HANDLER */
    353354#endif /* !_OBSTACK_ELIDE_CODE */
  • TabularUnified coreutils/trunk/lib/obstack.h

    r1648 r1953  
    112112#include <string.h>             /* For __GNU_LIBRARY__, and memcpy.  */
    113113
     114#if __STDC_VERSION__ < 199901L
     115# define __FLEXIBLE_ARRAY_MEMBER 1
     116#else
     117# define __FLEXIBLE_ARRAY_MEMBER
     118#endif
     119
    114120#if _OBSTACK_INTERFACE_VERSION == 1
    115121/* For binary compatibility with obstack version 1, which used "int"
     
    146152#endif
    147153
     154/* Not the same as _Noreturn, since it also works with function pointers.  */
     155#ifndef __attribute_noreturn__
     156# if 2 < __GNUC__ + (8 <= __GNUC_MINOR__) || 0x5110 <= __SUNPRO_C
     157#  define __attribute_noreturn__ __attribute__ ((__noreturn__))
     158# else
     159#  define __attribute_noreturn__
     160# endif
     161#endif
     162
    148163#ifdef __cplusplus
    149164extern "C" {
     
    154169  char *limit;                  /* 1 past end of this chunk */
    155170  struct _obstack_chunk *prev;  /* address of prior chunk or NULL */
    156   char contents[4];            /* objects begin here */
     171  char contents[__FLEXIBLE_ARRAY_MEMBER]; /* objects begin here */
    157172};
    158173
     
    213228   should either abort gracefully or use longjump - but shouldn't
    214229   return.  The default action is to print a message and abort.  */
    215 extern void (*obstack_alloc_failed_handler) (void);
     230extern __attribute_noreturn__ void (*obstack_alloc_failed_handler) (void);
    216231
    217232/* Exit value used when 'print_and_abort' is used.  */
  • TabularUnified coreutils/trunk/lib/parse-datetime.c

    r1648 r1953  
    103103#include "timespec.h"
    104104#include "verify.h"
     105#include "strftime.h"
    105106
    106107/* There's no need to extend the stack, so there's no need to involve
     
    125126#endif
    126127
     128#include <inttypes.h>
    127129#include <c-ctype.h>
    128130#include <limits.h>
     
    131133#include <string.h>
    132134
     135#include "gettext.h"
    133136#include "xalloc.h"
     137
     138#define _(str) gettext (str)
    134139
    135140/* Bison's skeleton tests _STDLIB_H, while some stdlib.h headers
     
    171176#define HOUR(x) ((x) * 60)
    172177
     178#define STREQ(a, b) (strcmp (a, b) == 0)
     179
    173180/* long_time_t is a signed integer type that contains all time_t values.  */
    174181verify (TYPE_IS_INTEGER (time_t));
     
    183190   errors that the cast doesn't.  */
    184191static unsigned char to_uchar (char ch) { return ch; }
     192
     193static void
     194dbg_printf (const char *msg,...)
     195{
     196  va_list args;
     197  /* TODO: use gnulib's 'program_name' instead? */
     198  fputs ("date: ", stderr);
     199
     200  va_start (args, msg);
     201  vfprintf (stderr, msg, args);
     202  va_end (args);
     203}
     204
     205
    185206
    186207/* Lots of this code assumes time_t and time_t-like values fit into
     
    274295  size_t times_seen;
    275296  size_t zones_seen;
     297
     298  /* if true, print debugging output to stderr */
     299  bool parse_datetime_debug;
     300
     301  /* which of the 'seen' parts has been printed when debugging */
     302  size_t debug_dates_seen;
     303  size_t debug_days_seen;
     304  size_t debug_local_zones_seen;
     305  size_t debug_dsts_seen;
     306  size_t debug_times_seen;
     307  size_t debug_zones_seen;
     308
     309  /* true if the user specified explicit ordinal day value, */
     310  bool debug_ordinal_day_seen;
     311
     312  /* the default input timezone, set by TZ value */
     313  long int debug_default_input_timezone;
    276314
    277315  /* Table of local time zone abbreviations, terminated by a null entry.  */
     
    348386}
    349387
    350 
    351 #line 352 "parse-datetime.c" /* yacc.c:339  */
     388/* returns a textual representation of the day ordinal/number values
     389   in the parser_control struct (e.g. 'last wed', 'this tues', 'thu') */
     390static const char*
     391str_days (parser_control *pc, char* /*output*/ buffer, size_t n)
     392{
     393  /* TODO: use the  relative_time_table[] for reverse lookup */
     394  static const char* ordinal_values[] = {
     395     "last",
     396     "this",
     397     "next/first",
     398     "(SECOND)", /* SECOND is commented out in relative_time_table[] */
     399     "third",
     400     "fourth",
     401     "fifth",
     402     "sixth",
     403     "seventh",
     404     "eight",
     405     "ninth",
     406     "tenth",
     407     "eleventh",
     408     "twelfth"};
     409
     410  static const char* days_values[] = {
     411     "Sun",
     412     "Mon",
     413     "Tue",
     414     "Wed",
     415     "Thu",
     416     "Fri",
     417     "Sat"
     418    };
     419
     420  /* don't add an ordinal prefix if the user didn't specify it
     421     (e.g., "this wed" vs "wed") */
     422  if (pc->debug_ordinal_day_seen)
     423    {
     424      /* use word description of possible (e.g. -1 = last, 3 = third) */
     425      if (pc->day_ordinal>=-1 && pc->day_ordinal <=12)
     426        {
     427          strncpy (buffer, ordinal_values[ pc->day_ordinal+1 ], n);
     428          buffer[n-1]='\0';
     429        }
     430      else
     431        {
     432          snprintf (buffer,n,"%ld",pc->day_ordinal);
     433        }
     434    }
     435  else
     436    {
     437      buffer[0] = '\0';
     438    }
     439
     440  /* Add the day name */
     441  if (pc->day_number>=0 && pc->day_number<=6)
     442    {
     443      size_t l = strlen (buffer);
     444      if (l>0)
     445        {
     446          strncat (buffer," ",n-l);
     447          ++l;
     448        }
     449      strncat (buffer,days_values[pc->day_number],n-l);
     450    }
     451  else
     452    {
     453      /* invalid day_number value - should never happen */
     454    }
     455  return buffer;
     456}
     457
     458/* debugging: print the current time in the parser_control structure.
     459   The parser will increment "*_seen" members for those which were parsed.
     460   This function will print only newly seen parts. */
     461static void
     462debug_print_current_time (const char* item, parser_control *pc)
     463{
     464  char tmp[100] = {0};
     465  int space = 0; /* if true, add space delimiter */
     466
     467  if (!pc->parse_datetime_debug)
     468    return;
     469
     470  /* no newline, more items printed below */
     471  dbg_printf (_("parsed %s part: "), item);
     472
     473  if (pc->dates_seen != pc->debug_dates_seen)
     474    {
     475      /*TODO: use pc->year.negative? */
     476      fprintf (stderr,"(Y-M-D) %04ld-%02ld-%02ld",
     477              pc->year.value, pc->month, pc->day);
     478      pc->debug_dates_seen = pc->dates_seen;
     479      space = 1;
     480    }
     481
     482  if (pc->times_seen != pc->debug_times_seen)
     483    {
     484      if (space)
     485        fputc (' ',stderr);
     486      fprintf (stderr,"%02ld:%02ld:%02ld",
     487              pc->hour, pc->minutes, pc->seconds.tv_sec);
     488      if (pc->seconds.tv_nsec!=0)
     489        fprintf (stderr,"%09ld", pc->seconds.tv_nsec);
     490      if (pc->meridian==MERpm)
     491        fputs ("pm",stderr);
     492
     493      pc->debug_times_seen = pc->times_seen;
     494      space = 1;
     495    }
     496
     497  if (pc->days_seen != pc->debug_days_seen)
     498    {
     499      if (space)
     500        fputc (' ',stderr);
     501      fprintf (stderr,_("%s (day ordinal=%ld number=%d)"),
     502              str_days (pc,tmp,sizeof (tmp)),
     503              pc->day_ordinal, pc->day_number);
     504      pc->debug_days_seen = pc->days_seen ;
     505      space = 1;
     506    }
     507
     508  if (pc->dsts_seen != pc->debug_dsts_seen)
     509    {
     510      if (space)
     511        fputc (' ',stderr);
     512      fprintf (stderr,_("is-dst=%d"), pc->local_isdst);
     513      pc->dsts_seen = pc->debug_dsts_seen;
     514      space = 1;
     515    }
     516
     517  /* TODO: fix incorrect display of EST=2:08h? */
     518  if (pc->zones_seen != pc->debug_zones_seen)
     519    {
     520      if (space)
     521        fputc (' ',stderr);
     522      fprintf (stderr,_("TZ=%+03d:%02d"), (int)(pc->time_zone/60),
     523              abs ((int)pc->time_zone%60));
     524      pc->debug_zones_seen = pc->zones_seen;
     525      space = 1;
     526    }
     527
     528  if (pc->local_zones_seen != pc->debug_local_zones_seen)
     529    {
     530      if (space)
     531        fputc (' ',stderr);
     532      fprintf (stderr,_("Local-TZ=%+03d:%02d"), (int)(pc->time_zone/60),
     533              abs ((int)pc->time_zone%60));
     534      pc->debug_local_zones_seen = pc->local_zones_seen;
     535      space = 1;
     536    }
     537
     538  if (pc->timespec_seen)
     539    {
     540      if (space)
     541        fputc (' ',stderr);
     542      fprintf (stderr,_("number of seconds: %ld"), pc->seconds.tv_sec);
     543    }
     544
     545  fputc ('\n', stderr);
     546}
     547
     548/* debugging: print the current relative values. */
     549static void
     550debug_print_relative_time (const char* item, const parser_control *pc)
     551{
     552  int space = 0; /* if true, add space delimiter */
     553
     554  if (!pc->parse_datetime_debug)
     555    return;
     556
     557  /* no newline, more items printed below */
     558  dbg_printf (_("parsed %s part: "), item);
     559
     560  if (pc->rel.year==0 && pc->rel.month==0 && pc->rel.day==0
     561      && pc->rel.hour==0 && pc->rel.minutes==00 && pc->rel.seconds == 0
     562      && pc->rel.ns==0)
     563    {
     564      /* Special case: relative time of this/today/now */
     565      fputs (_("today/this/now\n"),stderr);
     566      return ;
     567    }
     568
     569#define PRINT_REL_PART(x,name)                          \
     570  do {                                                  \
     571    if ( (pc->rel.x) != 0 )                             \
     572      {                                                 \
     573        if (space)                                      \
     574          fputc (' ',stderr);                           \
     575        fprintf (stderr,"%+ld %s", pc->rel.x, name);    \
     576        space = 1;                                      \
     577      }                                                 \
     578  } while (0)
     579
     580  PRINT_REL_PART (year,"year(s)");
     581  PRINT_REL_PART (month,"month(s)");
     582  PRINT_REL_PART (day,"day(s)");
     583  PRINT_REL_PART (hour,"hour(s)");
     584  PRINT_REL_PART (minutes,"minutes");
     585  PRINT_REL_PART (seconds,"seconds");
     586  PRINT_REL_PART (ns,"nanoseconds");
     587
     588  fputc ('\n',stderr);
     589}
     590
     591
     592
     593
     594#line 595 "parse-datetime.c" /* yacc.c:339  */
    352595
    353596# ifndef YY_NULLPTR
     
    430673union YYSTYPE
    431674{
    432 #line 297 "./lib/parse-datetime.y" /* yacc.c:355  */
     675#line 540 "./lib/parse-datetime.y" /* yacc.c:355  */
    433676
    434677  long int intval;
     
    437680  relative_time rel;
    438681
    439 #line 440 "parse-datetime.c" /* yacc.c:355  */
     682#line 683 "parse-datetime.c" /* yacc.c:355  */
    440683};
    441684
     
    453696/* Copy the second part of user declarations.  */
    454697
    455 #line 456 "parse-datetime.c" /* yacc.c:358  */
     698#line 699 "parse-datetime.c" /* yacc.c:358  */
    456699
    457700#ifdef short
     
    752995static const yytype_uint16 yyrline[] =
    753996{
    754        0,   324,   324,   325,   329,   336,   338,   342,   344,   346,
    755      348,   350,   352,   354,   355,   356,   360,   364,   368,   373,
    756      378,   383,   387,   392,   397,   404,   406,   410,   418,   423,
    757      433,   435,   437,   440,   443,   445,   447,   452,   457,   462,
    758      467,   475,   480,   500,   508,   516,   521,   527,   532,   538,
    759      542,   552,   554,   556,   561,   563,   565,   567,   569,   571,
    760      573,   575,   577,   579,   581,   583,   585,   587,   589,   591,
    761      593,   595,   597,   599,   601,   605,   607,   609,   611,   613,
    762      615,   620,   624,   624,   627,   628,   633,   634,   639,   644,
    763      655,   656
     997       0,   567,   567,   568,   572,   580,   582,   586,   591,   596,
     998     601,   606,   611,   616,   620,   624,   631,   635,   639,   644,
     999     649,   654,   658,   663,   668,   675,   677,   681,   689,   694,
     1000     704,   706,   708,   711,   714,   716,   718,   723,   728,   733,
     1001     739,   748,   753,   781,   789,   797,   802,   808,   813,   819,
     1002     823,   833,   835,   837,   842,   844,   846,   848,   850,   852,
     1003     854,   856,   858,   860,   862,   864,   866,   868,   870,   872,
     1004     874,   876,   878,   880,   882,   886,   888,   890,   892,   894,
     1005     896,   901,   905,   905,   908,   909,   914,   915,   920,   925,
     1006     936,   937
    7641007};
    7651008#endif
     
    16201863    {
    16211864        case 4:
    1622 #line 330 "./lib/parse-datetime.y" /* yacc.c:1646  */
     1865#line 573 "./lib/parse-datetime.y" /* yacc.c:1646  */
    16231866    {
    16241867        pc->seconds = (yyvsp[0].timespec);
    16251868        pc->timespec_seen = true;
     1869        debug_print_current_time (_("number of seconds"), pc);
    16261870      }
    1627 #line 1628 "parse-datetime.c" /* yacc.c:1646  */
     1871#line 1872 "parse-datetime.c" /* yacc.c:1646  */
    16281872    break;
    16291873
    16301874  case 7:
    1631 #line 343 "./lib/parse-datetime.y" /* yacc.c:1646  */
    1632     { pc->times_seen++; pc->dates_seen++; }
    1633 #line 1634 "parse-datetime.c" /* yacc.c:1646  */
     1875#line 587 "./lib/parse-datetime.y" /* yacc.c:1646  */
     1876    {
     1877        pc->times_seen++; pc->dates_seen++;
     1878        debug_print_current_time (_("datetime"), pc);
     1879      }
     1880#line 1881 "parse-datetime.c" /* yacc.c:1646  */
    16341881    break;
    16351882
    16361883  case 8:
    1637 #line 345 "./lib/parse-datetime.y" /* yacc.c:1646  */
    1638     { pc->times_seen++; }
    1639 #line 1640 "parse-datetime.c" /* yacc.c:1646  */
     1884#line 592 "./lib/parse-datetime.y" /* yacc.c:1646  */
     1885    {
     1886        pc->times_seen++;
     1887        debug_print_current_time (_("time"), pc);
     1888      }
     1889#line 1890 "parse-datetime.c" /* yacc.c:1646  */
    16401890    break;
    16411891
    16421892  case 9:
    1643 #line 347 "./lib/parse-datetime.y" /* yacc.c:1646  */
    1644     { pc->local_zones_seen++; }
    1645 #line 1646 "parse-datetime.c" /* yacc.c:1646  */
     1893#line 597 "./lib/parse-datetime.y" /* yacc.c:1646  */
     1894    {
     1895        pc->local_zones_seen++;
     1896        debug_print_current_time (_("local_zone"), pc);
     1897      }
     1898#line 1899 "parse-datetime.c" /* yacc.c:1646  */
    16461899    break;
    16471900
    16481901  case 10:
    1649 #line 349 "./lib/parse-datetime.y" /* yacc.c:1646  */
    1650     { pc->zones_seen++; }
    1651 #line 1652 "parse-datetime.c" /* yacc.c:1646  */
     1902#line 602 "./lib/parse-datetime.y" /* yacc.c:1646  */
     1903    {
     1904        pc->zones_seen++;
     1905        debug_print_current_time (_("zone"), pc);
     1906      }
     1907#line 1908 "parse-datetime.c" /* yacc.c:1646  */
    16521908    break;
    16531909
    16541910  case 11:
    1655 #line 351 "./lib/parse-datetime.y" /* yacc.c:1646  */
    1656     { pc->dates_seen++; }
    1657 #line 1658 "parse-datetime.c" /* yacc.c:1646  */
     1911#line 607 "./lib/parse-datetime.y" /* yacc.c:1646  */
     1912    {
     1913        pc->dates_seen++;
     1914        debug_print_current_time (_("date"), pc);
     1915      }
     1916#line 1917 "parse-datetime.c" /* yacc.c:1646  */
    16581917    break;
    16591918
    16601919  case 12:
    1661 #line 353 "./lib/parse-datetime.y" /* yacc.c:1646  */
    1662     { pc->days_seen++; }
    1663 #line 1664 "parse-datetime.c" /* yacc.c:1646  */
     1920#line 612 "./lib/parse-datetime.y" /* yacc.c:1646  */
     1921    {
     1922        pc->days_seen++;
     1923        debug_print_current_time (_("day"), pc);
     1924      }
     1925#line 1926 "parse-datetime.c" /* yacc.c:1646  */
     1926    break;
     1927
     1928  case 13:
     1929#line 617 "./lib/parse-datetime.y" /* yacc.c:1646  */
     1930    {
     1931        debug_print_relative_time (_("relative"), pc);
     1932      }
     1933#line 1934 "parse-datetime.c" /* yacc.c:1646  */
     1934    break;
     1935
     1936  case 14:
     1937#line 621 "./lib/parse-datetime.y" /* yacc.c:1646  */
     1938    {
     1939        debug_print_relative_time (_("number"), pc);
     1940      }
     1941#line 1942 "parse-datetime.c" /* yacc.c:1646  */
     1942    break;
     1943
     1944  case 15:
     1945#line 625 "./lib/parse-datetime.y" /* yacc.c:1646  */
     1946    {
     1947        debug_print_relative_time (_("hybrid"), pc);
     1948      }
     1949#line 1950 "parse-datetime.c" /* yacc.c:1646  */
    16641950    break;
    16651951
    16661952  case 18:
    1667 #line 369 "./lib/parse-datetime.y" /* yacc.c:1646  */
     1953#line 640 "./lib/parse-datetime.y" /* yacc.c:1646  */
    16681954    {
    16691955        set_hhmmss (pc, (yyvsp[-1].textintval).value, 0, 0, 0);
    16701956        pc->meridian = (yyvsp[0].intval);
    16711957      }
    1672 #line 1673 "parse-datetime.c" /* yacc.c:1646  */
     1958#line 1959 "parse-datetime.c" /* yacc.c:1646  */
    16731959    break;
    16741960
    16751961  case 19:
    1676 #line 374 "./lib/parse-datetime.y" /* yacc.c:1646  */
     1962#line 645 "./lib/parse-datetime.y" /* yacc.c:1646  */
    16771963    {
    16781964        set_hhmmss (pc, (yyvsp[-3].textintval).value, (yyvsp[-1].textintval).value, 0, 0);
    16791965        pc->meridian = (yyvsp[0].intval);
    16801966      }
    1681 #line 1682 "parse-datetime.c" /* yacc.c:1646  */
     1967#line 1968 "parse-datetime.c" /* yacc.c:1646  */
    16821968    break;
    16831969
    16841970  case 20:
    1685 #line 379 "./lib/parse-datetime.y" /* yacc.c:1646  */
     1971#line 650 "./lib/parse-datetime.y" /* yacc.c:1646  */
    16861972    {
    16871973        set_hhmmss (pc, (yyvsp[-5].textintval).value, (yyvsp[-3].textintval).value, (yyvsp[-1].timespec).tv_sec, (yyvsp[-1].timespec).tv_nsec);
    16881974        pc->meridian = (yyvsp[0].intval);
    16891975      }
    1690 #line 1691 "parse-datetime.c" /* yacc.c:1646  */
     1976#line 1977 "parse-datetime.c" /* yacc.c:1646  */
    16911977    break;
    16921978
    16931979  case 22:
    1694 #line 388 "./lib/parse-datetime.y" /* yacc.c:1646  */
     1980#line 659 "./lib/parse-datetime.y" /* yacc.c:1646  */
    16951981    {
    16961982        set_hhmmss (pc, (yyvsp[-1].textintval).value, 0, 0, 0);
    16971983        pc->meridian = MER24;
    16981984      }
    1699 #line 1700 "parse-datetime.c" /* yacc.c:1646  */
     1985#line 1986 "parse-datetime.c" /* yacc.c:1646  */
    17001986    break;
    17011987
    17021988  case 23:
    1703 #line 393 "./lib/parse-datetime.y" /* yacc.c:1646  */
     1989#line 664 "./lib/parse-datetime.y" /* yacc.c:1646  */
    17041990    {
    17051991        set_hhmmss (pc, (yyvsp[-3].textintval).value, (yyvsp[-1].textintval).value, 0, 0);
    17061992        pc->meridian = MER24;
    17071993      }
    1708 #line 1709 "parse-datetime.c" /* yacc.c:1646  */
     1994#line 1995 "parse-datetime.c" /* yacc.c:1646  */
    17091995    break;
    17101996
    17111997  case 24:
    1712 #line 398 "./lib/parse-datetime.y" /* yacc.c:1646  */
     1998#line 669 "./lib/parse-datetime.y" /* yacc.c:1646  */
    17131999    {
    17142000        set_hhmmss (pc, (yyvsp[-5].textintval).value, (yyvsp[-3].textintval).value, (yyvsp[-1].timespec).tv_sec, (yyvsp[-1].timespec).tv_nsec);
    17152001        pc->meridian = MER24;
    17162002      }
    1717 #line 1718 "parse-datetime.c" /* yacc.c:1646  */
     2003#line 2004 "parse-datetime.c" /* yacc.c:1646  */
    17182004    break;
    17192005
    17202006  case 27:
    1721 #line 411 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2007#line 682 "./lib/parse-datetime.y" /* yacc.c:1646  */
    17222008    {
    17232009        pc->zones_seen++;
    17242010        pc->time_zone = time_zone_hhmm (pc, (yyvsp[-1].textintval), (yyvsp[0].intval));
    17252011      }
    1726 #line 1727 "parse-datetime.c" /* yacc.c:1646  */
     2012#line 2013 "parse-datetime.c" /* yacc.c:1646  */
    17272013    break;
    17282014
    17292015  case 28:
    1730 #line 419 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2016#line 690 "./lib/parse-datetime.y" /* yacc.c:1646  */
    17312017    {
    17322018        pc->local_isdst = (yyvsp[0].intval);
    17332019        pc->dsts_seen += (0 < (yyvsp[0].intval));
    17342020      }
    1735 #line 1736 "parse-datetime.c" /* yacc.c:1646  */
     2021#line 2022 "parse-datetime.c" /* yacc.c:1646  */
    17362022    break;
    17372023
    17382024  case 29:
    1739 #line 424 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2025#line 695 "./lib/parse-datetime.y" /* yacc.c:1646  */
    17402026    {
    17412027        pc->local_isdst = 1;
    17422028        pc->dsts_seen += (0 < (yyvsp[-1].intval)) + 1;
    17432029      }
    1744 #line 1745 "parse-datetime.c" /* yacc.c:1646  */
     2030#line 2031 "parse-datetime.c" /* yacc.c:1646  */
    17452031    break;
    17462032
    17472033  case 30:
    1748 #line 434 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2034#line 705 "./lib/parse-datetime.y" /* yacc.c:1646  */
    17492035    { pc->time_zone = (yyvsp[0].intval); }
    1750 #line 1751 "parse-datetime.c" /* yacc.c:1646  */
     2036#line 2037 "parse-datetime.c" /* yacc.c:1646  */
    17512037    break;
    17522038
    17532039  case 31:
    1754 #line 436 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2040#line 707 "./lib/parse-datetime.y" /* yacc.c:1646  */
    17552041    { pc->time_zone = HOUR(7); }
    1756 #line 1757 "parse-datetime.c" /* yacc.c:1646  */
     2042#line 2043 "parse-datetime.c" /* yacc.c:1646  */
    17572043    break;
    17582044
    17592045  case 32:
    1760 #line 438 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2046#line 709 "./lib/parse-datetime.y" /* yacc.c:1646  */
    17612047    { pc->time_zone = (yyvsp[-1].intval);
    17622048        apply_relative_time (pc, (yyvsp[0].rel), 1); }
    1763 #line 1764 "parse-datetime.c" /* yacc.c:1646  */
     2049#line 2050 "parse-datetime.c" /* yacc.c:1646  */
    17642050    break;
    17652051
    17662052  case 33:
    1767 #line 441 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2053#line 712 "./lib/parse-datetime.y" /* yacc.c:1646  */
    17682054    { pc->time_zone = HOUR(7);
    17692055        apply_relative_time (pc, (yyvsp[0].rel), 1); }
    1770 #line 1771 "parse-datetime.c" /* yacc.c:1646  */
     2056#line 2057 "parse-datetime.c" /* yacc.c:1646  */
    17712057    break;
    17722058
    17732059  case 34:
    1774 #line 444 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2060#line 715 "./lib/parse-datetime.y" /* yacc.c:1646  */
    17752061    { pc->time_zone = (yyvsp[-2].intval) + time_zone_hhmm (pc, (yyvsp[-1].textintval), (yyvsp[0].intval)); }
    1776 #line 1777 "parse-datetime.c" /* yacc.c:1646  */
     2062#line 2063 "parse-datetime.c" /* yacc.c:1646  */
    17772063    break;
    17782064
    17792065  case 35:
    1780 #line 446 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2066#line 717 "./lib/parse-datetime.y" /* yacc.c:1646  */
    17812067    { pc->time_zone = (yyvsp[0].intval) + 60; }
    1782 #line 1783 "parse-datetime.c" /* yacc.c:1646  */
     2068#line 2069 "parse-datetime.c" /* yacc.c:1646  */
    17832069    break;
    17842070
    17852071  case 36:
    1786 #line 448 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2072#line 719 "./lib/parse-datetime.y" /* yacc.c:1646  */
    17872073    { pc->time_zone = (yyvsp[-1].intval) + 60; }
    1788 #line 1789 "parse-datetime.c" /* yacc.c:1646  */
     2074#line 2075 "parse-datetime.c" /* yacc.c:1646  */
    17892075    break;
    17902076
    17912077  case 37:
    1792 #line 453 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2078#line 724 "./lib/parse-datetime.y" /* yacc.c:1646  */
    17932079    {
    17942080        pc->day_ordinal = 0;
    17952081        pc->day_number = (yyvsp[0].intval);
    17962082      }
    1797 #line 1798 "parse-datetime.c" /* yacc.c:1646  */
     2083#line 2084 "parse-datetime.c" /* yacc.c:1646  */
    17982084    break;
    17992085
    18002086  case 38:
    1801 #line 458 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2087#line 729 "./lib/parse-datetime.y" /* yacc.c:1646  */
    18022088    {
    18032089        pc->day_ordinal = 0;
    18042090        pc->day_number = (yyvsp[-1].intval);
    18052091      }
    1806 #line 1807 "parse-datetime.c" /* yacc.c:1646  */
     2092#line 2093 "parse-datetime.c" /* yacc.c:1646  */
    18072093    break;
    18082094
    18092095  case 39:
    1810 #line 463 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2096#line 734 "./lib/parse-datetime.y" /* yacc.c:1646  */
    18112097    {
    18122098        pc->day_ordinal = (yyvsp[-1].intval);
    18132099        pc->day_number = (yyvsp[0].intval);
     2100        pc->debug_ordinal_day_seen = true;
    18142101      }
    1815 #line 1816 "parse-datetime.c" /* yacc.c:1646  */
     2102#line 2103 "parse-datetime.c" /* yacc.c:1646  */
    18162103    break;
    18172104
    18182105  case 40:
    1819 #line 468 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2106#line 740 "./lib/parse-datetime.y" /* yacc.c:1646  */
    18202107    {
    18212108        pc->day_ordinal = (yyvsp[-1].textintval).value;
    18222109        pc->day_number = (yyvsp[0].intval);
     2110        pc->debug_ordinal_day_seen = true;
    18232111      }
    1824 #line 1825 "parse-datetime.c" /* yacc.c:1646  */
     2112#line 2113 "parse-datetime.c" /* yacc.c:1646  */
    18252113    break;
    18262114
    18272115  case 41:
    1828 #line 476 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2116#line 749 "./lib/parse-datetime.y" /* yacc.c:1646  */
    18292117    {
    18302118        pc->month = (yyvsp[-2].textintval).value;
    18312119        pc->day = (yyvsp[0].textintval).value;
    18322120      }
    1833 #line 1834 "parse-datetime.c" /* yacc.c:1646  */
     2121#line 2122 "parse-datetime.c" /* yacc.c:1646  */
    18342122    break;
    18352123
    18362124  case 42:
    1837 #line 481 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2125#line 754 "./lib/parse-datetime.y" /* yacc.c:1646  */
    18382126    {
    18392127        /* Interpret as YYYY/MM/DD if the first value has 4 or more digits,
     
    18442132        if (4 <= (yyvsp[-4].textintval).digits)
    18452133          {
     2134            if (pc->parse_datetime_debug)
     2135              dbg_printf (_("warning: value %ld has %"PRIuMAX" digits. " \
     2136                            "Assuming YYYY/MM/DD\n"), (yyvsp[-4].textintval).value, (yyvsp[-4].textintval).digits);
     2137
    18462138            pc->year = (yyvsp[-4].textintval);
    18472139            pc->month = (yyvsp[-2].textintval).value;
     
    18502142        else
    18512143          {
     2144            if (pc->parse_datetime_debug)
     2145              dbg_printf (_("warning: value %ld has less than 4 digits. "    \
     2146                            "Assuming MM/DD/YY[YY]\n"), (yyvsp[-4].textintval).value);
     2147
    18522148            pc->month = (yyvsp[-4].textintval).value;
    18532149            pc->day = (yyvsp[-2].textintval).value;
     
    18552151          }
    18562152      }
    1857 #line 1858 "parse-datetime.c" /* yacc.c:1646  */
     2153#line 2154 "parse-datetime.c" /* yacc.c:1646  */
    18582154    break;
    18592155
    18602156  case 43:
    1861 #line 501 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2157#line 782 "./lib/parse-datetime.y" /* yacc.c:1646  */
    18622158    {
    18632159        /* e.g. 17-JUN-1992.  */
     
    18672163        pc->year.digits = (yyvsp[0].textintval).digits;
    18682164      }
    1869 #line 1870 "parse-datetime.c" /* yacc.c:1646  */
     2165#line 2166 "parse-datetime.c" /* yacc.c:1646  */
    18702166    break;
    18712167
    18722168  case 44:
    1873 #line 509 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2169#line 790 "./lib/parse-datetime.y" /* yacc.c:1646  */
    18742170    {
    18752171        /* e.g. JUN-17-1992.  */
     
    18792175        pc->year.digits = (yyvsp[0].textintval).digits;
    18802176      }
    1881 #line 1882 "parse-datetime.c" /* yacc.c:1646  */
     2177#line 2178 "parse-datetime.c" /* yacc.c:1646  */
    18822178    break;
    18832179
    18842180  case 45:
    1885 #line 517 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2181#line 798 "./lib/parse-datetime.y" /* yacc.c:1646  */
    18862182    {
    18872183        pc->month = (yyvsp[-1].intval);
    18882184        pc->day = (yyvsp[0].textintval).value;
    18892185      }
    1890 #line 1891 "parse-datetime.c" /* yacc.c:1646  */
     2186#line 2187 "parse-datetime.c" /* yacc.c:1646  */
    18912187    break;
    18922188
    18932189  case 46:
    1894 #line 522 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2190#line 803 "./lib/parse-datetime.y" /* yacc.c:1646  */
    18952191    {
    18962192        pc->month = (yyvsp[-3].intval);
     
    18982194        pc->year = (yyvsp[0].textintval);
    18992195      }
    1900 #line 1901 "parse-datetime.c" /* yacc.c:1646  */
     2196#line 2197 "parse-datetime.c" /* yacc.c:1646  */
    19012197    break;
    19022198
    19032199  case 47:
    1904 #line 528 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2200#line 809 "./lib/parse-datetime.y" /* yacc.c:1646  */
    19052201    {
    19062202        pc->day = (yyvsp[-1].textintval).value;
    19072203        pc->month = (yyvsp[0].intval);
    19082204      }
    1909 #line 1910 "parse-datetime.c" /* yacc.c:1646  */
     2205#line 2206 "parse-datetime.c" /* yacc.c:1646  */
    19102206    break;
    19112207
    19122208  case 48:
    1913 #line 533 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2209#line 814 "./lib/parse-datetime.y" /* yacc.c:1646  */
    19142210    {
    19152211        pc->day = (yyvsp[-2].textintval).value;
     
    19172213        pc->year = (yyvsp[0].textintval);
    19182214      }
    1919 #line 1920 "parse-datetime.c" /* yacc.c:1646  */
     2215#line 2216 "parse-datetime.c" /* yacc.c:1646  */
    19202216    break;
    19212217
    19222218  case 50:
    1923 #line 543 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2219#line 824 "./lib/parse-datetime.y" /* yacc.c:1646  */
    19242220    {
    19252221        /* ISO 8601 format.  YYYY-MM-DD.  */
     
    19282224        pc->day = -(yyvsp[0].textintval).value;
    19292225      }
    1930 #line 1931 "parse-datetime.c" /* yacc.c:1646  */
     2226#line 2227 "parse-datetime.c" /* yacc.c:1646  */
    19312227    break;
    19322228
    19332229  case 51:
    1934 #line 553 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2230#line 834 "./lib/parse-datetime.y" /* yacc.c:1646  */
    19352231    { apply_relative_time (pc, (yyvsp[-1].rel), (yyvsp[0].intval)); }
    1936 #line 1937 "parse-datetime.c" /* yacc.c:1646  */
     2232#line 2233 "parse-datetime.c" /* yacc.c:1646  */
    19372233    break;
    19382234
    19392235  case 52:
    1940 #line 555 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2236#line 836 "./lib/parse-datetime.y" /* yacc.c:1646  */
    19412237    { apply_relative_time (pc, (yyvsp[0].rel), 1); }
    1942 #line 1943 "parse-datetime.c" /* yacc.c:1646  */
     2238#line 2239 "parse-datetime.c" /* yacc.c:1646  */
    19432239    break;
    19442240
    19452241  case 53:
    1946 #line 557 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2242#line 838 "./lib/parse-datetime.y" /* yacc.c:1646  */
    19472243    { apply_relative_time (pc, (yyvsp[0].rel), 1); }
    1948 #line 1949 "parse-datetime.c" /* yacc.c:1646  */
     2244#line 2245 "parse-datetime.c" /* yacc.c:1646  */
    19492245    break;
    19502246
    19512247  case 54:
    1952 #line 562 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2248#line 843 "./lib/parse-datetime.y" /* yacc.c:1646  */
    19532249    { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).year = (yyvsp[-1].intval); }
    1954 #line 1955 "parse-datetime.c" /* yacc.c:1646  */
     2250#line 2251 "parse-datetime.c" /* yacc.c:1646  */
    19552251    break;
    19562252
    19572253  case 55:
    1958 #line 564 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2254#line 845 "./lib/parse-datetime.y" /* yacc.c:1646  */
    19592255    { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).year = (yyvsp[-1].textintval).value; }
    1960 #line 1961 "parse-datetime.c" /* yacc.c:1646  */
     2256#line 2257 "parse-datetime.c" /* yacc.c:1646  */
    19612257    break;
    19622258
    19632259  case 56:
    1964 #line 566 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2260#line 847 "./lib/parse-datetime.y" /* yacc.c:1646  */
    19652261    { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).year = 1; }
    1966 #line 1967 "parse-datetime.c" /* yacc.c:1646  */
     2262#line 2263 "parse-datetime.c" /* yacc.c:1646  */
    19672263    break;
    19682264
    19692265  case 57:
    1970 #line 568 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2266#line 849 "./lib/parse-datetime.y" /* yacc.c:1646  */
    19712267    { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).month = (yyvsp[-1].intval); }
    1972 #line 1973 "parse-datetime.c" /* yacc.c:1646  */
     2268#line 2269 "parse-datetime.c" /* yacc.c:1646  */
    19732269    break;
    19742270
    19752271  case 58:
    1976 #line 570 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2272#line 851 "./lib/parse-datetime.y" /* yacc.c:1646  */
    19772273    { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).month = (yyvsp[-1].textintval).value; }
    1978 #line 1979 "parse-datetime.c" /* yacc.c:1646  */
     2274#line 2275 "parse-datetime.c" /* yacc.c:1646  */
    19792275    break;
    19802276
    19812277  case 59:
    1982 #line 572 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2278#line 853 "./lib/parse-datetime.y" /* yacc.c:1646  */
    19832279    { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).month = 1; }
    1984 #line 1985 "parse-datetime.c" /* yacc.c:1646  */
     2280#line 2281 "parse-datetime.c" /* yacc.c:1646  */
    19852281    break;
    19862282
    19872283  case 60:
    1988 #line 574 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2284#line 855 "./lib/parse-datetime.y" /* yacc.c:1646  */
    19892285    { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).day = (yyvsp[-1].intval) * (yyvsp[0].intval); }
    1990 #line 1991 "parse-datetime.c" /* yacc.c:1646  */
     2286#line 2287 "parse-datetime.c" /* yacc.c:1646  */
    19912287    break;
    19922288
    19932289  case 61:
    1994 #line 576 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2290#line 857 "./lib/parse-datetime.y" /* yacc.c:1646  */
    19952291    { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).day = (yyvsp[-1].textintval).value * (yyvsp[0].intval); }
    1996 #line 1997 "parse-datetime.c" /* yacc.c:1646  */
     2292#line 2293 "parse-datetime.c" /* yacc.c:1646  */
    19972293    break;
    19982294
    19992295  case 62:
    2000 #line 578 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2296#line 859 "./lib/parse-datetime.y" /* yacc.c:1646  */
    20012297    { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).day = (yyvsp[0].intval); }
    2002 #line 2003 "parse-datetime.c" /* yacc.c:1646  */
     2298#line 2299 "parse-datetime.c" /* yacc.c:1646  */
    20032299    break;
    20042300
    20052301  case 63:
    2006 #line 580 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2302#line 861 "./lib/parse-datetime.y" /* yacc.c:1646  */
    20072303    { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).hour = (yyvsp[-1].intval); }
    2008 #line 2009 "parse-datetime.c" /* yacc.c:1646  */
     2304#line 2305 "parse-datetime.c" /* yacc.c:1646  */
    20092305    break;
    20102306
    20112307  case 64:
    2012 #line 582 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2308#line 863 "./lib/parse-datetime.y" /* yacc.c:1646  */
    20132309    { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).hour = (yyvsp[-1].textintval).value; }
    2014 #line 2015 "parse-datetime.c" /* yacc.c:1646  */
     2310#line 2311 "parse-datetime.c" /* yacc.c:1646  */
    20152311    break;
    20162312
    20172313  case 65:
    2018 #line 584 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2314#line 865 "./lib/parse-datetime.y" /* yacc.c:1646  */
    20192315    { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).hour = 1; }
    2020 #line 2021 "parse-datetime.c" /* yacc.c:1646  */
     2316#line 2317 "parse-datetime.c" /* yacc.c:1646  */
    20212317    break;
    20222318
    20232319  case 66:
    2024 #line 586 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2320#line 867 "./lib/parse-datetime.y" /* yacc.c:1646  */
    20252321    { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).minutes = (yyvsp[-1].intval); }
    2026 #line 2027 "parse-datetime.c" /* yacc.c:1646  */
     2322#line 2323 "parse-datetime.c" /* yacc.c:1646  */
    20272323    break;
    20282324
    20292325  case 67:
    2030 #line 588 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2326#line 869 "./lib/parse-datetime.y" /* yacc.c:1646  */
    20312327    { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).minutes = (yyvsp[-1].textintval).value; }
    2032 #line 2033 "parse-datetime.c" /* yacc.c:1646  */
     2328#line 2329 "parse-datetime.c" /* yacc.c:1646  */
    20332329    break;
    20342330
    20352331  case 68:
    2036 #line 590 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2332#line 871 "./lib/parse-datetime.y" /* yacc.c:1646  */
    20372333    { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).minutes = 1; }
    2038 #line 2039 "parse-datetime.c" /* yacc.c:1646  */
     2334#line 2335 "parse-datetime.c" /* yacc.c:1646  */
    20392335    break;
    20402336
    20412337  case 69:
    2042 #line 592 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2338#line 873 "./lib/parse-datetime.y" /* yacc.c:1646  */
    20432339    { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).seconds = (yyvsp[-1].intval); }
    2044 #line 2045 "parse-datetime.c" /* yacc.c:1646  */
     2340#line 2341 "parse-datetime.c" /* yacc.c:1646  */
    20452341    break;
    20462342
    20472343  case 70:
    2048 #line 594 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2344#line 875 "./lib/parse-datetime.y" /* yacc.c:1646  */
    20492345    { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).seconds = (yyvsp[-1].textintval).value; }
    2050 #line 2051 "parse-datetime.c" /* yacc.c:1646  */
     2346#line 2347 "parse-datetime.c" /* yacc.c:1646  */
    20512347    break;
    20522348
    20532349  case 71:
    2054 #line 596 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2350#line 877 "./lib/parse-datetime.y" /* yacc.c:1646  */
    20552351    { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).seconds = (yyvsp[-1].timespec).tv_sec; (yyval.rel).ns = (yyvsp[-1].timespec).tv_nsec; }
    2056 #line 2057 "parse-datetime.c" /* yacc.c:1646  */
     2352#line 2353 "parse-datetime.c" /* yacc.c:1646  */
    20572353    break;
    20582354
    20592355  case 72:
    2060 #line 598 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2356#line 879 "./lib/parse-datetime.y" /* yacc.c:1646  */
    20612357    { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).seconds = (yyvsp[-1].timespec).tv_sec; (yyval.rel).ns = (yyvsp[-1].timespec).tv_nsec; }
    2062 #line 2063 "parse-datetime.c" /* yacc.c:1646  */
     2358#line 2359 "parse-datetime.c" /* yacc.c:1646  */
    20632359    break;
    20642360
    20652361  case 73:
    2066 #line 600 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2362#line 881 "./lib/parse-datetime.y" /* yacc.c:1646  */
    20672363    { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).seconds = 1; }
    2068 #line 2069 "parse-datetime.c" /* yacc.c:1646  */
     2364#line 2365 "parse-datetime.c" /* yacc.c:1646  */
    20692365    break;
    20702366
    20712367  case 75:
    2072 #line 606 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2368#line 887 "./lib/parse-datetime.y" /* yacc.c:1646  */
    20732369    { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).year = (yyvsp[-1].textintval).value; }
    2074 #line 2075 "parse-datetime.c" /* yacc.c:1646  */
     2370#line 2371 "parse-datetime.c" /* yacc.c:1646  */
    20752371    break;
    20762372
    20772373  case 76:
    2078 #line 608 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2374#line 889 "./lib/parse-datetime.y" /* yacc.c:1646  */
    20792375    { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).month = (yyvsp[-1].textintval).value; }
    2080 #line 2081 "parse-datetime.c" /* yacc.c:1646  */
     2376#line 2377 "parse-datetime.c" /* yacc.c:1646  */
    20812377    break;
    20822378
    20832379  case 77:
    2084 #line 610 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2380#line 891 "./lib/parse-datetime.y" /* yacc.c:1646  */
    20852381    { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).day = (yyvsp[-1].textintval).value * (yyvsp[0].intval); }
    2086 #line 2087 "parse-datetime.c" /* yacc.c:1646  */
     2382#line 2383 "parse-datetime.c" /* yacc.c:1646  */
    20872383    break;
    20882384
    20892385  case 78:
    2090 #line 612 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2386#line 893 "./lib/parse-datetime.y" /* yacc.c:1646  */
    20912387    { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).hour = (yyvsp[-1].textintval).value; }
    2092 #line 2093 "parse-datetime.c" /* yacc.c:1646  */
     2388#line 2389 "parse-datetime.c" /* yacc.c:1646  */
    20932389    break;
    20942390
    20952391  case 79:
    2096 #line 614 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2392#line 895 "./lib/parse-datetime.y" /* yacc.c:1646  */
    20972393    { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).minutes = (yyvsp[-1].textintval).value; }
    2098 #line 2099 "parse-datetime.c" /* yacc.c:1646  */
     2394#line 2395 "parse-datetime.c" /* yacc.c:1646  */
    20992395    break;
    21002396
    21012397  case 80:
    2102 #line 616 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2398#line 897 "./lib/parse-datetime.y" /* yacc.c:1646  */
    21032399    { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).seconds = (yyvsp[-1].textintval).value; }
    2104 #line 2105 "parse-datetime.c" /* yacc.c:1646  */
     2400#line 2401 "parse-datetime.c" /* yacc.c:1646  */
    21052401    break;
    21062402
    21072403  case 81:
    2108 #line 621 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2404#line 902 "./lib/parse-datetime.y" /* yacc.c:1646  */
    21092405    { (yyval.rel) = RELATIVE_TIME_0; (yyval.rel).day = (yyvsp[0].intval); }
    2110 #line 2111 "parse-datetime.c" /* yacc.c:1646  */
     2406#line 2407 "parse-datetime.c" /* yacc.c:1646  */
    21112407    break;
    21122408
    21132409  case 85:
    2114 #line 629 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2410#line 910 "./lib/parse-datetime.y" /* yacc.c:1646  */
    21152411    { (yyval.timespec).tv_sec = (yyvsp[0].textintval).value; (yyval.timespec).tv_nsec = 0; }
    2116 #line 2117 "parse-datetime.c" /* yacc.c:1646  */
     2412#line 2413 "parse-datetime.c" /* yacc.c:1646  */
    21172413    break;
    21182414
    21192415  case 87:
    2120 #line 635 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2416#line 916 "./lib/parse-datetime.y" /* yacc.c:1646  */
    21212417    { (yyval.timespec).tv_sec = (yyvsp[0].textintval).value; (yyval.timespec).tv_nsec = 0; }
    2122 #line 2123 "parse-datetime.c" /* yacc.c:1646  */
     2418#line 2419 "parse-datetime.c" /* yacc.c:1646  */
    21232419    break;
    21242420
    21252421  case 88:
    2126 #line 640 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2422#line 921 "./lib/parse-datetime.y" /* yacc.c:1646  */
    21272423    { digits_to_date_time (pc, (yyvsp[0].textintval)); }
    2128 #line 2129 "parse-datetime.c" /* yacc.c:1646  */
     2424#line 2425 "parse-datetime.c" /* yacc.c:1646  */
    21292425    break;
    21302426
    21312427  case 89:
    2132 #line 645 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2428#line 926 "./lib/parse-datetime.y" /* yacc.c:1646  */
    21332429    {
    21342430        /* Hybrid all-digit and relative offset, so that we accept e.g.,
     
    21372433        apply_relative_time (pc, (yyvsp[0].rel), 1);
    21382434      }
    2139 #line 2140 "parse-datetime.c" /* yacc.c:1646  */
     2435#line 2436 "parse-datetime.c" /* yacc.c:1646  */
    21402436    break;
    21412437
    21422438  case 90:
    2143 #line 655 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2439#line 936 "./lib/parse-datetime.y" /* yacc.c:1646  */
    21442440    { (yyval.intval) = -1; }
    2145 #line 2146 "parse-datetime.c" /* yacc.c:1646  */
     2441#line 2442 "parse-datetime.c" /* yacc.c:1646  */
    21462442    break;
    21472443
    21482444  case 91:
    2149 #line 657 "./lib/parse-datetime.y" /* yacc.c:1646  */
     2445#line 938 "./lib/parse-datetime.y" /* yacc.c:1646  */
    21502446    { (yyval.intval) = (yyvsp[0].textintval).value; }
    2151 #line 2152 "parse-datetime.c" /* yacc.c:1646  */
    2152     break;
    2153 
    2154 
    2155 #line 2156 "parse-datetime.c" /* yacc.c:1646  */
     2447#line 2448 "parse-datetime.c" /* yacc.c:1646  */
     2448    break;
     2449
     2450
     2451#line 2452 "parse-datetime.c" /* yacc.c:1646  */
    21562452      default: break;
    21572453    }
     
    23812677  return yyresult;
    23822678}
    2383 #line 660 "./lib/parse-datetime.y" /* yacc.c:1906  */
     2679#line 941 "./lib/parse-datetime.y" /* yacc.c:1906  */
    23842680
    23852681
     
    26212917
    26222918static long int
    2623 to_year (textint textyear)
     2919to_year (textint textyear, bool debug)
    26242920{
    26252921  long int year = textyear.value;
     
    26312927     years 69-99 map to 1969-1999.  */
    26322928  else if (textyear.digits == 2)
    2633     year += year < 69 ? 2000 : 1900;
     2929    {
     2930      year += year < 69 ? 2000 : 1900;
     2931      if (debug)
     2932        dbg_printf (_("warning: adjusting year value %ld to %ld\n"),
     2933                    textyear.value, year);
     2934    }
    26342935
    26352936  return year;
     
    28963197          tp = lookup_word (pc, buff);
    28973198          if (! tp)
    2898             return '?';
     3199            {
     3200              if (pc->parse_datetime_debug)
     3201                dbg_printf (_("error: unknown word '%s'\n"), buff);
     3202              return '?';
     3203            }
    28993204          lvalp->intval = tp->value;
    29003205          return tp->type;
     
    29563261enum { TZBUFSIZE = 100 };
    29573262
     3263/* A reasonable upper bound for the buffer used in debug print outs.
     3264   see days_to_name(), debug_strftime() and debug_mktime_not_ok() */
     3265enum { DBGBUFSIZE = 100 };
     3266
    29583267/* Return a copy of TZ, stored in TZBUF if it fits, and heap-allocated
    29593268   otherwise.  */
     
    29703279    }
    29713280  return tz;
     3281}
     3282
     3283/* debugging: format a 'struct tm' into a buffer, taking the parser's
     3284   timezone information into account (if pc!=NULL). */
     3285static const char*
     3286debug_strfdatetime (const struct tm *tm, const parser_control *pc,
     3287                    char* /*output*/ buf, size_t n)
     3288{
     3289  /* TODO:
     3290     1. find an optimal way to print date string in a clear and unambiguous
     3291        format. Currently, always add '(Y-M-D)' prefix.
     3292        Consider '2016y01m10d'  or 'year(2016) month(01) day(10)'.
     3293
     3294        If the user needs debug printing, it means he/she already having
     3295        issues with the parsing - better to avoid formats that could
     3296        be mis-interpreted (e.g. just YYYY-MM-DD).
     3297
     3298     2. Can strftime be used instead?
     3299        depends if it is portable and can print invalid dates on all systems.
     3300
     3301     3. Print timezone information ?
     3302
     3303     4. Print DST information ?
     3304
     3305     5. Print nanosecond information ?
     3306
     3307     NOTE:
     3308     Printed date/time values might not be valid, e.g. '2016-02-31'
     3309     or '2016-19-2016' .  These are the values as parsed from the user
     3310     string, before validation.
     3311  */
     3312  int m = nstrftime (buf, n, "(Y-M-D) %Y-%m-%d %H:%M:%S", tm, 0, 0);
     3313
     3314  /* if parser_control information was provided (for timezone),
     3315     and there's enough space in the buffer - add timezone info */
     3316  if (pc != NULL && ((n-m)>0))
     3317    {
     3318      const long int tz = (pc->zones_seen || pc->local_zones_seen)
     3319                          ? pc->time_zone
     3320                          : pc->debug_default_input_timezone;
     3321      snprintf (&buf[m],n-m," TZ=%+03d:%02d", (int)(tz/60), abs ((int)tz)%60);
     3322    }
     3323  return buf;
     3324}
     3325
     3326static const char*
     3327debug_strfdate (const struct tm *tm, char* /*output*/ buf, size_t n)
     3328{
     3329  snprintf (buf,n,"(Y-M-D) %04d-%02d-%02d",
     3330            tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday);
     3331  return buf;
     3332}
     3333
     3334static const char*
     3335debug_strftime (const struct tm *tm, char* /*output*/ buf, size_t n)
     3336{
     3337  snprintf (buf,n,"%02d:%02d:%02d", tm->tm_hour, tm->tm_min, tm->tm_sec);
     3338  return buf;
     3339}
     3340
     3341/* If 'mktime_ok()' failed, display the failed time values,
     3342   and provide possible hints. Example output:
     3343
     3344    date: error: invalid date/time value:
     3345    date:     user provided time: '(Y-M-D) 2006-04-02 02:45:00'
     3346    date:        normalized time: '(Y-M-D) 2006-04-02 03:45:00'
     3347    date:                                             __
     3348    date:      possible reasons:
     3349    date:        non-existing due to daylight-saving time;
     3350    date:        numeric values overflow;
     3351    date:        missing timezone;
     3352 */
     3353static void
     3354debug_mktime_not_ok (struct tm const *tm0, struct tm const *tm1,
     3355                     const parser_control *pc,  bool time_zone_seen)
     3356{
     3357  /* TODO: handle t==-1 (as in 'mktime_ok') */
     3358  char tmp[DBGBUFSIZE];
     3359  int i;
     3360  const bool eq_sec   = (tm0->tm_sec  == tm1->tm_sec);
     3361  const bool eq_min   = (tm0->tm_min  == tm1->tm_min);
     3362  const bool eq_hour  = (tm0->tm_hour == tm1->tm_hour);
     3363  const bool eq_mday  = (tm0->tm_mday == tm1->tm_mday);
     3364  const bool eq_month = (tm0->tm_mon  == tm1->tm_mon);
     3365  const bool eq_year  = (tm0->tm_year == tm1->tm_year);
     3366
     3367  const bool dst_shift = eq_sec && eq_min && !eq_hour
     3368                         && eq_mday && eq_month && eq_year;
     3369
     3370  if (!pc->parse_datetime_debug)
     3371    return;
     3372
     3373  dbg_printf (_("error: invalid date/time value:\n"));
     3374  dbg_printf (_("    user provided time: '%s'\n"),
     3375              debug_strfdatetime (tm0, pc, tmp, sizeof (tmp)));
     3376  dbg_printf (_("       normalized time: '%s'\n"),
     3377              debug_strfdatetime (tm1, pc, tmp, sizeof (tmp)));
     3378  /* NOTEs: the format must be aligned with debug_strfdatetime() and the two
     3379            DEBUG statements above. this string is not translated. */
     3380  i = snprintf (tmp, sizeof(tmp),
     3381                "                                 %4s %2s %2s %2s %2s %2s",
     3382                eq_year?"":"----", eq_month?"":"--", eq_mday?"":"--",
     3383                eq_hour?"":"--", eq_min?"":"--", eq_sec?"":"--");
     3384  /* Trim trailing whitespace */
     3385  if ((i>0) && (i<sizeof(tmp)))
     3386    {
     3387      while ((i>0) && (tmp[i-1]==' '))
     3388        --i;
     3389      tmp[i] = '\0';
     3390    }
     3391  dbg_printf ("%s\n", tmp);
     3392
     3393  dbg_printf (_("     possible reasons:\n"));
     3394  if (dst_shift)
     3395    dbg_printf (_("       non-existing due to daylight-saving time;\n"));
     3396  if (!eq_mday && !eq_month)
     3397    dbg_printf (_("       invalid day/month combination;\n"));
     3398  dbg_printf (_("       numeric values overflow;\n"));
     3399  dbg_printf ("       %s\n",time_zone_seen?_("incorrect timezone")
     3400                                          :_("missing timezone"));
     3401}
     3402
     3403
     3404/* Returns the effective local timezone, in minutes. */
     3405static long int
     3406get_effective_timezone (void)
     3407{
     3408  /* TODO: check for failures */
     3409  const time_t z = 0;
     3410  time_t lz ;
     3411  struct tm *ltm;
     3412  ltm = localtime (&z);
     3413  lz = timegm (ltm)/60;
     3414  return (long int)lz;
     3415}
     3416
     3417/* The original interface: run with debug=false */
     3418bool
     3419parse_datetime (struct timespec *result, char const *p,
     3420                struct timespec const *now)
     3421{
     3422  return parse_datetime2 (result, p, now, 0);
    29723423}
    29733424
     
    29773428   *NOW as the basis for the returned time.  */
    29783429bool
    2979 parse_datetime (struct timespec *result, char const *p,
    2980                 struct timespec const *now)
     3430parse_datetime2 (struct timespec *result, char const *p,
     3431                 struct timespec const *now, unsigned int flags)
    29813432{
    29823433  time_t Start;
     
    29923443  char tz0buf[TZBUFSIZE];
    29933444  bool ok = true;
     3445  char dbg_ord[DBGBUFSIZE];
     3446  char dbg_tm[DBGBUFSIZE];
     3447  char const *input_sentinel = p + strlen (p);
    29943448
    29953449  if (! now)
     
    30773531  pc.dsts_seen = 0;
    30783532  pc.zones_seen = 0;
     3533  pc.parse_datetime_debug = (flags & PARSE_DATETIME_DEBUG)!=0;
     3534  pc.debug_dates_seen = 0;
     3535  pc.debug_days_seen = 0;
     3536  pc.debug_times_seen = 0;
     3537  pc.debug_local_zones_seen = 0;
     3538  pc.debug_dsts_seen = 0;
     3539  pc.debug_zones_seen = 0;
     3540  pc.debug_ordinal_day_seen = false;
     3541  pc.debug_default_input_timezone = 0;
    30793542
    30803543#if HAVE_STRUCT_TM_TM_ZONE
     
    31363599    }
    31373600
     3601  pc.debug_default_input_timezone = get_effective_timezone ();
     3602
    31383603  if (yyparse (&pc) != 0)
    3139     goto fail;
     3604    {
     3605      if (pc.parse_datetime_debug)
     3606        {
     3607          if (input_sentinel <= pc.input)
     3608            dbg_printf (_("error: parsing failed\n"), pc.input);
     3609          else
     3610            {
     3611              dbg_printf (_("error: parsing failed, stopped at '%s'\n"),
     3612                          pc.input);
     3613            }
     3614         }
     3615      goto fail;
     3616    }
     3617
     3618  /* determine effective timezone source */
     3619  if (pc.parse_datetime_debug)
     3620    {
     3621      long int tz = pc.debug_default_input_timezone;
     3622      const char* tz_env;
     3623      const char* tz_src;
     3624
     3625      if (pc.timespec_seen)
     3626        {
     3627          tz = 0 ;
     3628          tz_src = _("'@timespec' - always UTC0");
     3629        }
     3630      else if (pc.local_zones_seen || pc.zones_seen)
     3631        {
     3632          tz = pc.time_zone;
     3633          tz_src = _("parsed date/time string");
     3634        }
     3635      else if ((tz_env = getenv("TZ")))
     3636        {
     3637          if (tz_was_altered)
     3638            {
     3639              snprintf (dbg_tm, sizeof(dbg_tm), _("TZ=\"%s\" in date string"),
     3640                        tz_env);
     3641              tz_src = dbg_tm;
     3642            }
     3643          else if (STREQ(tz_env,"UTC0"))
     3644            {
     3645              /* Special case: using 'date -u' simply set TZ=UTC0 */
     3646              tz_src = _("TZ=UTC0 environment value or -u");
     3647            }
     3648          else
     3649            {
     3650              snprintf (dbg_tm, sizeof(dbg_tm),
     3651                        _("TZ=\"%s\" environment value"), tz_env);
     3652              tz_src = dbg_tm;
     3653            }
     3654        }
     3655      else
     3656        {
     3657          tz_src = _("system default");
     3658        }
     3659
     3660      if (pc.parse_datetime_debug)
     3661        dbg_printf (_("input timezone: %+03d:%02d (set from %s)\n"),
     3662                    (int)(tz/60), abs ((int)tz)%60, tz_src);
     3663
     3664    }
    31403665
    31413666  if (pc.timespec_seen)
     
    31453670      if (1 < (pc.times_seen | pc.dates_seen | pc.days_seen | pc.dsts_seen
    31463671               | (pc.local_zones_seen + pc.zones_seen)))
    3147         goto fail;
    3148 
    3149       tm.tm_year = to_year (pc.year) - TM_YEAR_BASE;
     3672        {
     3673          if (pc.parse_datetime_debug)
     3674            {
     3675              if (pc.times_seen > 1)
     3676                dbg_printf ("error: seen multiple time parts\n");
     3677              if (pc.dates_seen > 1)
     3678                dbg_printf ("error: seen multiple date parts\n");
     3679              if (pc.days_seen > 1)
     3680                dbg_printf ("error: seen multiple days parts\n");
     3681              if (pc.dsts_seen > 1)
     3682                dbg_printf ("error: seen multiple daylight-saving parts\n");
     3683              if ( (pc.local_zones_seen + pc.zones_seen) > 1)
     3684                dbg_printf ("error: seen multiple time-zone parts\n");
     3685            }
     3686          goto fail;
     3687        }
     3688
     3689      tm.tm_year = to_year (pc.year, pc.parse_datetime_debug) - TM_YEAR_BASE;
    31503690      tm.tm_mon = pc.month - 1;
    31513691      tm.tm_mday = pc.day;
     
    31543694          tm.tm_hour = to_hour (pc.hour, pc.meridian);
    31553695          if (tm.tm_hour < 0)
    3156             goto fail;
     3696            {
     3697              const char* mrd = (pc.meridian==MERam)?"am":
     3698                                  (pc.meridian==MERpm)?"pm":"";
     3699              if (pc.parse_datetime_debug)
     3700                dbg_printf (_("error: invalid hour %ld%s\n"), pc.hour, mrd);
     3701
     3702              goto fail;
     3703            }
    31573704          tm.tm_min = pc.minutes;
    31583705          tm.tm_sec = pc.seconds.tv_sec;
     3706          if (pc.parse_datetime_debug)
     3707            dbg_printf (_("using %s time as starting value: '%s'\n"),
     3708                        (pc.times_seen)?_("specified"):_("current"),
     3709                        debug_strftime (&tm,dbg_tm,sizeof (dbg_tm)));
    31593710        }
    31603711      else
     
    31623713          tm.tm_hour = tm.tm_min = tm.tm_sec = 0;
    31633714          pc.seconds.tv_nsec = 0;
     3715          if (pc.parse_datetime_debug)
     3716            dbg_printf ("warning: using midnight as starting time: 00:00:00\n");
    31643717        }
    31653718
     
    31803733        {
    31813734          if (! pc.zones_seen)
    3182             goto fail;
     3735            {
     3736              debug_mktime_not_ok (&tm0, &tm, &pc, pc.zones_seen);
     3737
     3738              goto fail;
     3739            }
    31833740          else
    31843741            {
     
    31973754              long int abs_time_zone_hour = abs_time_zone / 60;
    31983755              int abs_time_zone_min = abs_time_zone % 60;
    3199               char tz1buf[sizeof "XXX+0:00"
    3200                           + sizeof pc.time_zone * CHAR_BIT / 3];
     3756              char tz1buf[sizeof "XXX+0:00" + TYPE_WIDTH (pc.time_zone) / 3];
    32013757              if (!tz_was_altered)
    32023758                tz0 = get_tz (tz0buf);
     
    32043760                       abs_time_zone_hour, abs_time_zone_min);
    32053761              if (setenv ("TZ", tz1buf, 1) != 0)
    3206                 goto fail;
     3762                {
     3763                  /* TODO: was warn () + print errno? */
     3764                  if (pc.parse_datetime_debug)
     3765                    dbg_printf (_("error: setenv('TZ','%s') failed\n"), tz1buf);
     3766
     3767                  goto fail;
     3768                }
    32073769              tz_was_altered = true;
    32083770              tm = tm0;
    32093771              Start = mktime (&tm);
    32103772              if (! mktime_ok (&tm0, &tm, Start))
    3211                 goto fail;
     3773                {
     3774                  debug_mktime_not_ok (&tm0, &tm, &pc, pc.zones_seen);
     3775
     3776                  goto fail;
     3777                }
    32123778            }
    32133779        }
     
    32223788          Start = mktime (&tm);
    32233789          if (Start == (time_t) -1)
    3224             goto fail;
     3790            {
     3791              if (pc.parse_datetime_debug)
     3792                dbg_printf (_("error: day '%s' (day ordinal=%ld number=%d) "   \
     3793                              "resulted in an invalid date: '%s'\n"),
     3794                            str_days (&pc,dbg_ord,sizeof (dbg_ord)),
     3795                            pc.day_ordinal,pc.day_number,
     3796                            debug_strfdatetime (&tm, &pc, dbg_tm,
     3797                                                sizeof (dbg_tm)));
     3798
     3799              goto fail;
     3800            }
     3801
     3802          if (pc.parse_datetime_debug)
     3803            dbg_printf (_("new start date: '%s' is '%s'\n"),
     3804                        str_days (&pc,dbg_ord,sizeof (dbg_ord)),
     3805                        debug_strfdatetime (&tm, &pc, dbg_tm,sizeof (dbg_tm)));
     3806
     3807        }
     3808
     3809      if (pc.parse_datetime_debug)
     3810        {
     3811          if (!pc.dates_seen && !pc.days_seen)
     3812            dbg_printf (_("using current date as starting value: '%s'\n"),
     3813                        debug_strfdate (&tm,dbg_tm,sizeof (dbg_tm)));
     3814
     3815          if (pc.days_seen && pc.dates_seen)
     3816            dbg_printf (_("warning: day (%s) ignored when explicit dates " \
     3817                          "are given\n"),
     3818                        str_days (&pc,dbg_ord,sizeof (dbg_ord)));
     3819
     3820          dbg_printf (_("starting date/time: '%s'\n"),
     3821                      debug_strfdatetime (&tm, &pc, dbg_tm,sizeof (dbg_tm)));
    32253822        }
    32263823
     
    32283825      if (pc.rel.year | pc.rel.month | pc.rel.day)
    32293826        {
     3827          if (pc.parse_datetime_debug)
     3828            {
     3829              if ((pc.rel.year != 0 || pc.rel.month !=0) && tm.tm_mday==1)
     3830                dbg_printf (_("warning: when adding relative months/years, " \
     3831                              "it is recommended to specify the 15th of the " \
     3832                              "months\n"));
     3833
     3834              if (pc.rel.day != 0 && tm.tm_hour==0)
     3835                dbg_printf (_("warning: when adding relative days, "    \
     3836                              "it is recommended to specify 12:00pm\n"));
     3837            }
     3838
    32303839          int year = tm.tm_year + pc.rel.year;
    32313840          int month = tm.tm_mon + pc.rel.month;
     
    32343843              | ((month < tm.tm_mon) ^ (pc.rel.month < 0))
    32353844              | ((day < tm.tm_mday) ^ (pc.rel.day < 0)))
    3236             goto fail;
     3845            {
     3846              /* TODO: what is the actual error? int-value wrap-around? */
     3847              if (pc.parse_datetime_debug)
     3848                dbg_printf (_("error: %s:%d\n"), __FILE__,__LINE__);
     3849
     3850              goto fail;
     3851            }
    32373852          tm.tm_year = year;
    32383853          tm.tm_mon = month;
     
    32443859          Start = mktime (&tm);
    32453860          if (Start == (time_t) -1)
    3246             goto fail;
     3861            {
     3862              if (pc.parse_datetime_debug)
     3863                dbg_printf(_("error: adding relative date resulted " \
     3864                             "in an invalid date: '%s'\n"),
     3865                           debug_strfdatetime (&tm, &pc, dbg_tm,
     3866                                               sizeof (dbg_tm)));
     3867
     3868              goto fail;
     3869            }
     3870
     3871          if (pc.parse_datetime_debug)
     3872            {
     3873              dbg_printf (_("after date adjustment "                    \
     3874                            "(%+ld years, %+ld months, %+ld days),\n"),
     3875                          pc.rel.year, pc.rel.month, pc.rel.day);
     3876              dbg_printf (_("    new date/time = '%s'\n"),
     3877                          debug_strfdatetime (&tm, &pc, dbg_tm,
     3878                                              sizeof (dbg_tm)));
     3879            }
     3880
    32473881        }
    32483882
     
    32593893          struct tm const *gmt = gmtime (&t);
    32603894          if (! gmt)
    3261             goto fail;
     3895            {
     3896              /* TODO: use 'warn(3)' + print errno ? */
     3897              if (pc.parse_datetime_debug)
     3898                dbg_printf (_("error: gmtime failed for t=%ld\n"),t);
     3899
     3900              goto fail;
     3901            }
    32623902          delta -= tm_diff (&tm, gmt);
    32633903#endif
    32643904          t1 = Start - delta;
    32653905          if ((Start < t1) != (delta < 0))
    3266             goto fail;  /* time_t overflow */
     3906            {
     3907              if (pc.parse_datetime_debug)
     3908                dbg_printf (_("error: timezone %ld caused time_t overflow\n"),
     3909                            pc.time_zone);
     3910
     3911              goto fail;  /* time_t overflow */
     3912            }
    32673913          Start = t1;
    32683914        }
     3915
     3916      if (pc.parse_datetime_debug)
     3917        dbg_printf (_("'%s' = %ld epoch-seconds\n"),
     3918                    debug_strfdatetime (&tm, &pc, dbg_tm, sizeof (dbg_tm)),
     3919                    Start);
    32693920
    32703921      /* Add relative hours, minutes, and seconds.  On hosts that support
     
    32963947            | ((t4 < t3) ^ (d4 < 0))
    32973948            | (t5 != t4))
    3298           goto fail;
     3949            {
     3950              if (pc.parse_datetime_debug)
     3951                dbg_printf (_("error: adding relative time caused an " \
     3952                              "overflow\n"));
     3953
     3954              goto fail;
     3955            }
     3956
     3957          if (pc.parse_datetime_debug
     3958              && (pc.rel.hour | pc.rel.minutes | pc.rel.seconds | pc.rel.ns))
     3959            {
     3960              dbg_printf (_("after time adjustment (%+ld hours, " \
     3961                            "%+ld minutes, %+ld seconds, %+ld ns),\n"),
     3962                          pc.rel.hour,pc.rel.minutes,pc.rel.seconds,pc.rel.ns);
     3963              dbg_printf (_("    new time = %ld epoch-seconds\n"),t5);
     3964            }
    32993965
    33003966        result->tv_sec = t5;
     
    33123978  if (tz0 != tz0buf)
    33133979    free (tz0);
     3980
     3981  if (ok && pc.parse_datetime_debug)
     3982    {
     3983      /* print local timezone AFTER restoring TZ (if tz_was_altered)*/
     3984      const long int otz = get_effective_timezone ();
     3985      const char* tz_src;
     3986      const char* tz_env;
     3987
     3988      if ((tz_env = getenv("TZ")))
     3989        {
     3990          /* Special case: using 'date -u' simply set TZ=UTC0 */
     3991          if (STREQ(tz_env,"UTC0"))
     3992            {
     3993              tz_src = _("TZ=UTC0 environment value or -u");
     3994            }
     3995          else
     3996            {
     3997              snprintf (dbg_tm, sizeof(dbg_tm),
     3998                        _("TZ=\"%s\" environment value"), tz_env);
     3999              tz_src = dbg_tm;
     4000            }
     4001        }
     4002      else
     4003        {
     4004          tz_src = _("system default");
     4005        }
     4006
     4007      if (pc.parse_datetime_debug)
     4008        {
     4009          dbg_printf (_("output timezone: %+03d:%02d (set from %s)\n"),
     4010                      (int)(otz/60), abs ((int)otz)%60, tz_src);
     4011
     4012
     4013          dbg_printf (_("final: %ld.%09ld (epoch-seconds)\n"),
     4014                      result->tv_sec,result->tv_nsec);
     4015
     4016          struct tm const *gmt = gmtime (&result->tv_sec);
     4017          dbg_printf (_("final: %s (UTC0)\n"),
     4018                      debug_strfdatetime (gmt, NULL, dbg_tm, sizeof (dbg_tm)));
     4019          struct tm const *lmt = localtime (&result->tv_sec);
     4020          dbg_printf (_("final: %s (output timezone TZ=%+03d:%02d)\n"),
     4021                      debug_strfdatetime (lmt, NULL, dbg_tm, sizeof (dbg_tm)),
     4022                      (int)(otz/60), abs ((int)otz)%60);
     4023        }
     4024    }
     4025
    33144026  return ok;
    33154027}
  • TabularUnified coreutils/trunk/lib/parse-datetime.h

    r1648 r1953  
    2121
    2222bool parse_datetime (struct timespec *, char const *, struct timespec const *);
     23
     24/* parse_datetime2 flag: if set, print debug/progress information to STDERR */
     25#define PARSE_DATETIME_DEBUG 1
     26
     27/* same as above, supporting additional flags */
     28bool parse_datetime2 (struct timespec *, char const *, struct timespec const *,
     29                      unsigned int flags);
  • TabularUnified coreutils/trunk/lib/parse-datetime.y

    r1648 r1953  
    3838#include "timespec.h"
    3939#include "verify.h"
     40#include "strftime.h"
    4041
    4142/* There's no need to extend the stack, so there's no need to involve
     
    6061#endif
    6162
     63#include <inttypes.h>
    6264#include <c-ctype.h>
    6365#include <limits.h>
     
    6668#include <string.h>
    6769
     70#include "gettext.h"
    6871#include "xalloc.h"
     72
     73#define _(str) gettext (str)
    6974
    7075/* Bison's skeleton tests _STDLIB_H, while some stdlib.h headers
     
    106111#define HOUR(x) ((x) * 60)
    107112
     113#define STREQ(a, b) (strcmp (a, b) == 0)
     114
    108115/* long_time_t is a signed integer type that contains all time_t values.  */
    109116verify (TYPE_IS_INTEGER (time_t));
     
    118125   errors that the cast doesn't.  */
    119126static unsigned char to_uchar (char ch) { return ch; }
     127
     128static void
     129dbg_printf (const char *msg,...)
     130{
     131  va_list args;
     132  /* TODO: use gnulib's 'program_name' instead? */
     133  fputs ("date: ", stderr);
     134
     135  va_start (args, msg);
     136  vfprintf (stderr, msg, args);
     137  va_end (args);
     138}
     139
     140
    120141
    121142/* Lots of this code assumes time_t and time_t-like values fit into
     
    210231  size_t zones_seen;
    211232
     233  /* if true, print debugging output to stderr */
     234  bool parse_datetime_debug;
     235
     236  /* which of the 'seen' parts has been printed when debugging */
     237  size_t debug_dates_seen;
     238  size_t debug_days_seen;
     239  size_t debug_local_zones_seen;
     240  size_t debug_dsts_seen;
     241  size_t debug_times_seen;
     242  size_t debug_zones_seen;
     243
     244  /* true if the user specified explicit ordinal day value, */
     245  bool debug_ordinal_day_seen;
     246
     247  /* the default input timezone, set by TZ value */
     248  long int debug_default_input_timezone;
     249
    212250  /* Table of local time zone abbreviations, terminated by a null entry.  */
    213251  table local_time_zone_table[3];
     
    283321}
    284322
     323/* returns a textual representation of the day ordinal/number values
     324   in the parser_control struct (e.g. 'last wed', 'this tues', 'thu') */
     325static const char*
     326str_days (parser_control *pc, char* /*output*/ buffer, size_t n)
     327{
     328  /* TODO: use the  relative_time_table[] for reverse lookup */
     329  static const char* ordinal_values[] = {
     330     "last",
     331     "this",
     332     "next/first",
     333     "(SECOND)", /* SECOND is commented out in relative_time_table[] */
     334     "third",
     335     "fourth",
     336     "fifth",
     337     "sixth",
     338     "seventh",
     339     "eight",
     340     "ninth",
     341     "tenth",
     342     "eleventh",
     343     "twelfth"};
     344
     345  static const char* days_values[] = {
     346     "Sun",
     347     "Mon",
     348     "Tue",
     349     "Wed",
     350     "Thu",
     351     "Fri",
     352     "Sat"
     353    };
     354
     355  /* don't add an ordinal prefix if the user didn't specify it
     356     (e.g., "this wed" vs "wed") */
     357  if (pc->debug_ordinal_day_seen)
     358    {
     359      /* use word description of possible (e.g. -1 = last, 3 = third) */
     360      if (pc->day_ordinal>=-1 && pc->day_ordinal <=12)
     361        {
     362          strncpy (buffer, ordinal_values[ pc->day_ordinal+1 ], n);
     363          buffer[n-1]='\0';
     364        }
     365      else
     366        {
     367          snprintf (buffer,n,"%ld",pc->day_ordinal);
     368        }
     369    }
     370  else
     371    {
     372      buffer[0] = '\0';
     373    }
     374
     375  /* Add the day name */
     376  if (pc->day_number>=0 && pc->day_number<=6)
     377    {
     378      size_t l = strlen (buffer);
     379      if (l>0)
     380        {
     381          strncat (buffer," ",n-l);
     382          ++l;
     383        }
     384      strncat (buffer,days_values[pc->day_number],n-l);
     385    }
     386  else
     387    {
     388      /* invalid day_number value - should never happen */
     389    }
     390  return buffer;
     391}
     392
     393/* debugging: print the current time in the parser_control structure.
     394   The parser will increment "*_seen" members for those which were parsed.
     395   This function will print only newly seen parts. */
     396static void
     397debug_print_current_time (const char* item, parser_control *pc)
     398{
     399  char tmp[100] = {0};
     400  int space = 0; /* if true, add space delimiter */
     401
     402  if (!pc->parse_datetime_debug)
     403    return;
     404
     405  /* no newline, more items printed below */
     406  dbg_printf (_("parsed %s part: "), item);
     407
     408  if (pc->dates_seen != pc->debug_dates_seen)
     409    {
     410      /*TODO: use pc->year.negative? */
     411      fprintf (stderr,"(Y-M-D) %04ld-%02ld-%02ld",
     412              pc->year.value, pc->month, pc->day);
     413      pc->debug_dates_seen = pc->dates_seen;
     414      space = 1;
     415    }
     416
     417  if (pc->times_seen != pc->debug_times_seen)
     418    {
     419      if (space)
     420        fputc (' ',stderr);
     421      fprintf (stderr,"%02ld:%02ld:%02ld",
     422              pc->hour, pc->minutes, pc->seconds.tv_sec);
     423      if (pc->seconds.tv_nsec!=0)
     424        fprintf (stderr,"%09ld", pc->seconds.tv_nsec);
     425      if (pc->meridian==MERpm)
     426        fputs ("pm",stderr);
     427
     428      pc->debug_times_seen = pc->times_seen;
     429      space = 1;
     430    }
     431
     432  if (pc->days_seen != pc->debug_days_seen)
     433    {
     434      if (space)
     435        fputc (' ',stderr);
     436      fprintf (stderr,_("%s (day ordinal=%ld number=%d)"),
     437              str_days (pc,tmp,sizeof (tmp)),
     438              pc->day_ordinal, pc->day_number);
     439      pc->debug_days_seen = pc->days_seen ;
     440      space = 1;
     441    }
     442
     443  if (pc->dsts_seen != pc->debug_dsts_seen)
     444    {
     445      if (space)
     446        fputc (' ',stderr);
     447      fprintf (stderr,_("is-dst=%d"), pc->local_isdst);
     448      pc->dsts_seen = pc->debug_dsts_seen;
     449      space = 1;
     450    }
     451
     452  /* TODO: fix incorrect display of EST=2:08h? */
     453  if (pc->zones_seen != pc->debug_zones_seen)
     454    {
     455      if (space)
     456        fputc (' ',stderr);
     457      fprintf (stderr,_("TZ=%+03d:%02d"), (int)(pc->time_zone/60),
     458              abs ((int)pc->time_zone%60));
     459      pc->debug_zones_seen = pc->zones_seen;
     460      space = 1;
     461    }
     462
     463  if (pc->local_zones_seen != pc->debug_local_zones_seen)
     464    {
     465      if (space)
     466        fputc (' ',stderr);
     467      fprintf (stderr,_("Local-TZ=%+03d:%02d"), (int)(pc->time_zone/60),
     468              abs ((int)pc->time_zone%60));
     469      pc->debug_local_zones_seen = pc->local_zones_seen;
     470      space = 1;
     471    }
     472
     473  if (pc->timespec_seen)
     474    {
     475      if (space)
     476        fputc (' ',stderr);
     477      fprintf (stderr,_("number of seconds: %ld"), pc->seconds.tv_sec);
     478    }
     479
     480  fputc ('\n', stderr);
     481}
     482
     483/* debugging: print the current relative values. */
     484static void
     485debug_print_relative_time (const char* item, const parser_control *pc)
     486{
     487  int space = 0; /* if true, add space delimiter */
     488
     489  if (!pc->parse_datetime_debug)
     490    return;
     491
     492  /* no newline, more items printed below */
     493  dbg_printf (_("parsed %s part: "), item);
     494
     495  if (pc->rel.year==0 && pc->rel.month==0 && pc->rel.day==0
     496      && pc->rel.hour==0 && pc->rel.minutes==00 && pc->rel.seconds == 0
     497      && pc->rel.ns==0)
     498    {
     499      /* Special case: relative time of this/today/now */
     500      fputs (_("today/this/now\n"),stderr);
     501      return ;
     502    }
     503
     504#define PRINT_REL_PART(x,name)                          \
     505  do {                                                  \
     506    if ( (pc->rel.x) != 0 )                             \
     507      {                                                 \
     508        if (space)                                      \
     509          fputc (' ',stderr);                           \
     510        fprintf (stderr,"%+ld %s", pc->rel.x, name);    \
     511        space = 1;                                      \
     512      }                                                 \
     513  } while (0)
     514
     515  PRINT_REL_PART (year,"year(s)");
     516  PRINT_REL_PART (month,"month(s)");
     517  PRINT_REL_PART (day,"day(s)");
     518  PRINT_REL_PART (hour,"hour(s)");
     519  PRINT_REL_PART (minutes,"minutes");
     520  PRINT_REL_PART (seconds,"seconds");
     521  PRINT_REL_PART (ns,"nanoseconds");
     522
     523  fputc ('\n',stderr);
     524}
     525
     526
     527
    285528%}
    286529
     
    331574        pc->seconds = $2;
    332575        pc->timespec_seen = true;
     576        debug_print_current_time (_("number of seconds"), pc);
    333577      }
    334578  ;
     
    341585item:
    342586    datetime
    343       { pc->times_seen++; pc->dates_seen++; }
     587      {
     588        pc->times_seen++; pc->dates_seen++;
     589        debug_print_current_time (_("datetime"), pc);
     590      }
    344591  | time
    345       { pc->times_seen++; }
     592      {
     593        pc->times_seen++;
     594        debug_print_current_time (_("time"), pc);
     595      }
    346596  | local_zone
    347       { pc->local_zones_seen++; }
     597      {
     598        pc->local_zones_seen++;
     599        debug_print_current_time (_("local_zone"), pc);
     600      }
    348601  | zone
    349       { pc->zones_seen++; }
     602      {
     603        pc->zones_seen++;
     604        debug_print_current_time (_("zone"), pc);
     605      }
    350606  | date
    351       { pc->dates_seen++; }
     607      {
     608        pc->dates_seen++;
     609        debug_print_current_time (_("date"), pc);
     610      }
    352611  | day
    353       { pc->days_seen++; }
     612      {
     613        pc->days_seen++;
     614        debug_print_current_time (_("day"), pc);
     615      }
    354616  | rel
     617      {
     618        debug_print_relative_time (_("relative"), pc);
     619      }
    355620  | number
     621      {
     622        debug_print_relative_time (_("number"), pc);
     623      }
    356624  | hybrid
     625      {
     626        debug_print_relative_time (_("hybrid"), pc);
     627      }
    357628  ;
    358629
     
    464735        pc->day_ordinal = $1;
    465736        pc->day_number = $2;
     737        pc->debug_ordinal_day_seen = true;
    466738      }
    467739  | tUNUMBER tDAY
     
    469741        pc->day_ordinal = $1.value;
    470742        pc->day_number = $2;
     743        pc->debug_ordinal_day_seen = true;
    471744      }
    472745  ;
     
    487760        if (4 <= $1.digits)
    488761          {
     762            if (pc->parse_datetime_debug)
     763              dbg_printf (_("warning: value %ld has %"PRIuMAX" digits. " \
     764                            "Assuming YYYY/MM/DD\n"), $1.value, $1.digits);
     765
    489766            pc->year = $1;
    490767            pc->month = $3.value;
     
    493770        else
    494771          {
     772            if (pc->parse_datetime_debug)
     773              dbg_printf (_("warning: value %ld has less than 4 digits. "    \
     774                            "Assuming MM/DD/YY[YY]\n"), $1.value);
     775
    495776            pc->month = $1.value;
    496777            pc->day = $3.value;
     
    8971178
    8981179static long int
    899 to_year (textint textyear)
     1180to_year (textint textyear, bool debug)
    9001181{
    9011182  long int year = textyear.value;
     
    9071188     years 69-99 map to 1969-1999.  */
    9081189  else if (textyear.digits == 2)
    909     year += year < 69 ? 2000 : 1900;
     1190    {
     1191      year += year < 69 ? 2000 : 1900;
     1192      if (debug)
     1193        dbg_printf (_("warning: adjusting year value %ld to %ld\n"),
     1194                    textyear.value, year);
     1195    }
    9101196
    9111197  return year;
     
    11721458          tp = lookup_word (pc, buff);
    11731459          if (! tp)
    1174             return '?';
     1460            {
     1461              if (pc->parse_datetime_debug)
     1462                dbg_printf (_("error: unknown word '%s'\n"), buff);
     1463              return '?';
     1464            }
    11751465          lvalp->intval = tp->value;
    11761466          return tp->type;
     
    12321522enum { TZBUFSIZE = 100 };
    12331523
     1524/* A reasonable upper bound for the buffer used in debug print outs.
     1525   see days_to_name(), debug_strftime() and debug_mktime_not_ok() */
     1526enum { DBGBUFSIZE = 100 };
     1527
    12341528/* Return a copy of TZ, stored in TZBUF if it fits, and heap-allocated
    12351529   otherwise.  */
     
    12461540    }
    12471541  return tz;
     1542}
     1543
     1544/* debugging: format a 'struct tm' into a buffer, taking the parser's
     1545   timezone information into account (if pc!=NULL). */
     1546static const char*
     1547debug_strfdatetime (const struct tm *tm, const parser_control *pc,
     1548                    char* /*output*/ buf, size_t n)
     1549{
     1550  /* TODO:
     1551     1. find an optimal way to print date string in a clear and unambiguous
     1552        format. Currently, always add '(Y-M-D)' prefix.
     1553        Consider '2016y01m10d'  or 'year(2016) month(01) day(10)'.
     1554
     1555        If the user needs debug printing, it means he/she already having
     1556        issues with the parsing - better to avoid formats that could
     1557        be mis-interpreted (e.g. just YYYY-MM-DD).
     1558
     1559     2. Can strftime be used instead?
     1560        depends if it is portable and can print invalid dates on all systems.
     1561
     1562     3. Print timezone information ?
     1563
     1564     4. Print DST information ?
     1565
     1566     5. Print nanosecond information ?
     1567
     1568     NOTE:
     1569     Printed date/time values might not be valid, e.g. '2016-02-31'
     1570     or '2016-19-2016' .  These are the values as parsed from the user
     1571     string, before validation.
     1572  */
     1573  int m = nstrftime (buf, n, "(Y-M-D) %Y-%m-%d %H:%M:%S", tm, 0, 0);
     1574
     1575  /* if parser_control information was provided (for timezone),
     1576     and there's enough space in the buffer - add timezone info */
     1577  if (pc != NULL && ((n-m)>0))
     1578    {
     1579      const long int tz = (pc->zones_seen || pc->local_zones_seen)
     1580                          ? pc->time_zone
     1581                          : pc->debug_default_input_timezone;
     1582      snprintf (&buf[m],n-m," TZ=%+03d:%02d", (int)(tz/60), abs ((int)tz)%60);
     1583    }
     1584  return buf;
     1585}
     1586
     1587static const char*
     1588debug_strfdate (const struct tm *tm, char* /*output*/ buf, size_t n)
     1589{
     1590  snprintf (buf,n,"(Y-M-D) %04d-%02d-%02d",
     1591            tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday);
     1592  return buf;
     1593}
     1594
     1595static const char*
     1596debug_strftime (const struct tm *tm, char* /*output*/ buf, size_t n)
     1597{
     1598  snprintf (buf,n,"%02d:%02d:%02d", tm->tm_hour, tm->tm_min, tm->tm_sec);
     1599  return buf;
     1600}
     1601
     1602/* If 'mktime_ok()' failed, display the failed time values,
     1603   and provide possible hints. Example output:
     1604
     1605    date: error: invalid date/time value:
     1606    date:     user provided time: '(Y-M-D) 2006-04-02 02:45:00'
     1607    date:        normalized time: '(Y-M-D) 2006-04-02 03:45:00'
     1608    date:                                             __
     1609    date:      possible reasons:
     1610    date:        non-existing due to daylight-saving time;
     1611    date:        numeric values overflow;
     1612    date:        missing timezone;
     1613 */
     1614static void
     1615debug_mktime_not_ok (struct tm const *tm0, struct tm const *tm1,
     1616                     const parser_control *pc,  bool time_zone_seen)
     1617{
     1618  /* TODO: handle t==-1 (as in 'mktime_ok') */
     1619  char tmp[DBGBUFSIZE];
     1620  int i;
     1621  const bool eq_sec   = (tm0->tm_sec  == tm1->tm_sec);
     1622  const bool eq_min   = (tm0->tm_min  == tm1->tm_min);
     1623  const bool eq_hour  = (tm0->tm_hour == tm1->tm_hour);
     1624  const bool eq_mday  = (tm0->tm_mday == tm1->tm_mday);
     1625  const bool eq_month = (tm0->tm_mon  == tm1->tm_mon);
     1626  const bool eq_year  = (tm0->tm_year == tm1->tm_year);
     1627
     1628  const bool dst_shift = eq_sec && eq_min && !eq_hour
     1629                         && eq_mday && eq_month && eq_year;
     1630
     1631  if (!pc->parse_datetime_debug)
     1632    return;
     1633
     1634  dbg_printf (_("error: invalid date/time value:\n"));
     1635  dbg_printf (_("    user provided time: '%s'\n"),
     1636              debug_strfdatetime (tm0, pc, tmp, sizeof (tmp)));
     1637  dbg_printf (_("       normalized time: '%s'\n"),
     1638              debug_strfdatetime (tm1, pc, tmp, sizeof (tmp)));
     1639  /* NOTEs: the format must be aligned with debug_strfdatetime() and the two
     1640            DEBUG statements above. this string is not translated. */
     1641  i = snprintf (tmp, sizeof(tmp),
     1642                "                                 %4s %2s %2s %2s %2s %2s",
     1643                eq_year?"":"----", eq_month?"":"--", eq_mday?"":"--",
     1644                eq_hour?"":"--", eq_min?"":"--", eq_sec?"":"--");
     1645  /* Trim trailing whitespace */
     1646  if ((i>0) && (i<sizeof(tmp)))
     1647    {
     1648      while ((i>0) && (tmp[i-1]==' '))
     1649        --i;
     1650      tmp[i] = '\0';
     1651    }
     1652  dbg_printf ("%s\n", tmp);
     1653
     1654  dbg_printf (_("     possible reasons:\n"));
     1655  if (dst_shift)
     1656    dbg_printf (_("       non-existing due to daylight-saving time;\n"));
     1657  if (!eq_mday && !eq_month)
     1658    dbg_printf (_("       invalid day/month combination;\n"));
     1659  dbg_printf (_("       numeric values overflow;\n"));
     1660  dbg_printf ("       %s\n",time_zone_seen?_("incorrect timezone")
     1661                                          :_("missing timezone"));
     1662}
     1663
     1664
     1665/* Returns the effective local timezone, in minutes. */
     1666static long int
     1667get_effective_timezone (void)
     1668{
     1669  /* TODO: check for failures */
     1670  const time_t z = 0;
     1671  time_t lz ;
     1672  struct tm *ltm;
     1673  ltm = localtime (&z);
     1674  lz = timegm (ltm)/60;
     1675  return (long int)lz;
     1676}
     1677
     1678/* The original interface: run with debug=false */
     1679bool
     1680parse_datetime (struct timespec *result, char const *p,
     1681                struct timespec const *now)
     1682{
     1683  return parse_datetime2 (result, p, now, 0);
    12481684}
    12491685
     
    12531689   *NOW as the basis for the returned time.  */
    12541690bool
    1255 parse_datetime (struct timespec *result, char const *p,
    1256                 struct timespec const *now)
     1691parse_datetime2 (struct timespec *result, char const *p,
     1692                 struct timespec const *now, unsigned int flags)
    12571693{
    12581694  time_t Start;
     
    12681704  char tz0buf[TZBUFSIZE];
    12691705  bool ok = true;
     1706  char dbg_ord[DBGBUFSIZE];
     1707  char dbg_tm[DBGBUFSIZE];
     1708  char const *input_sentinel = p + strlen (p);
    12701709
    12711710  if (! now)
     
    13531792  pc.dsts_seen = 0;
    13541793  pc.zones_seen = 0;
     1794  pc.parse_datetime_debug = (flags & PARSE_DATETIME_DEBUG)!=0;
     1795  pc.debug_dates_seen = 0;
     1796  pc.debug_days_seen = 0;
     1797  pc.debug_times_seen = 0;
     1798  pc.debug_local_zones_seen = 0;
     1799  pc.debug_dsts_seen = 0;
     1800  pc.debug_zones_seen = 0;
     1801  pc.debug_ordinal_day_seen = false;
     1802  pc.debug_default_input_timezone = 0;
    13551803
    13561804#if HAVE_STRUCT_TM_TM_ZONE
     
    14121860    }
    14131861
     1862  pc.debug_default_input_timezone = get_effective_timezone ();
     1863
    14141864  if (yyparse (&pc) != 0)
    1415     goto fail;
     1865    {
     1866      if (pc.parse_datetime_debug)
     1867        {
     1868          if (input_sentinel <= pc.input)
     1869            dbg_printf (_("error: parsing failed\n"), pc.input);
     1870          else
     1871            {
     1872              dbg_printf (_("error: parsing failed, stopped at '%s'\n"),
     1873                          pc.input);
     1874            }
     1875         }
     1876      goto fail;
     1877    }
     1878
     1879  /* determine effective timezone source */
     1880  if (pc.parse_datetime_debug)
     1881    {
     1882      long int tz = pc.debug_default_input_timezone;
     1883      const char* tz_env;
     1884      const char* tz_src;
     1885
     1886      if (pc.timespec_seen)
     1887        {
     1888          tz = 0 ;
     1889          tz_src = _("'@timespec' - always UTC0");
     1890        }
     1891      else if (pc.local_zones_seen || pc.zones_seen)
     1892        {
     1893          tz = pc.time_zone;
     1894          tz_src = _("parsed date/time string");
     1895        }
     1896      else if ((tz_env = getenv("TZ")))
     1897        {
     1898          if (tz_was_altered)
     1899            {
     1900              snprintf (dbg_tm, sizeof(dbg_tm), _("TZ=\"%s\" in date string"),
     1901                        tz_env);
     1902              tz_src = dbg_tm;
     1903            }
     1904          else if (STREQ(tz_env,"UTC0"))
     1905            {
     1906              /* Special case: using 'date -u' simply set TZ=UTC0 */
     1907              tz_src = _("TZ=UTC0 environment value or -u");
     1908            }
     1909          else
     1910            {
     1911              snprintf (dbg_tm, sizeof(dbg_tm),
     1912                        _("TZ=\"%s\" environment value"), tz_env);
     1913              tz_src = dbg_tm;
     1914            }
     1915        }
     1916      else
     1917        {
     1918          tz_src = _("system default");
     1919        }
     1920
     1921      if (pc.parse_datetime_debug)
     1922        dbg_printf (_("input timezone: %+03d:%02d (set from %s)\n"),
     1923                    (int)(tz/60), abs ((int)tz)%60, tz_src);
     1924
     1925    }
    14161926
    14171927  if (pc.timespec_seen)
     
    14211931      if (1 < (pc.times_seen | pc.dates_seen | pc.days_seen | pc.dsts_seen
    14221932               | (pc.local_zones_seen + pc.zones_seen)))
    1423         goto fail;
    1424 
    1425       tm.tm_year = to_year (pc.year) - TM_YEAR_BASE;
     1933        {
     1934          if (pc.parse_datetime_debug)
     1935            {
     1936              if (pc.times_seen > 1)
     1937                dbg_printf ("error: seen multiple time parts\n");
     1938              if (pc.dates_seen > 1)
     1939                dbg_printf ("error: seen multiple date parts\n");
     1940              if (pc.days_seen > 1)
     1941                dbg_printf ("error: seen multiple days parts\n");
     1942              if (pc.dsts_seen > 1)
     1943                dbg_printf ("error: seen multiple daylight-saving parts\n");
     1944              if ( (pc.local_zones_seen + pc.zones_seen) > 1)
     1945                dbg_printf ("error: seen multiple time-zone parts\n");
     1946            }
     1947          goto fail;
     1948        }
     1949
     1950      tm.tm_year = to_year (pc.year, pc.parse_datetime_debug) - TM_YEAR_BASE;
    14261951      tm.tm_mon = pc.month - 1;
    14271952      tm.tm_mday = pc.day;
     
    14301955          tm.tm_hour = to_hour (pc.hour, pc.meridian);
    14311956          if (tm.tm_hour < 0)
    1432             goto fail;
     1957            {
     1958              const char* mrd = (pc.meridian==MERam)?"am":
     1959                                  (pc.meridian==MERpm)?"pm":"";
     1960              if (pc.parse_datetime_debug)
     1961                dbg_printf (_("error: invalid hour %ld%s\n"), pc.hour, mrd);
     1962
     1963              goto fail;
     1964            }
    14331965          tm.tm_min = pc.minutes;
    14341966          tm.tm_sec = pc.seconds.tv_sec;
     1967          if (pc.parse_datetime_debug)
     1968            dbg_printf (_("using %s time as starting value: '%s'\n"),
     1969                        (pc.times_seen)?_("specified"):_("current"),
     1970                        debug_strftime (&tm,dbg_tm,sizeof (dbg_tm)));
    14351971        }
    14361972      else
     
    14381974          tm.tm_hour = tm.tm_min = tm.tm_sec = 0;
    14391975          pc.seconds.tv_nsec = 0;
     1976          if (pc.parse_datetime_debug)
     1977            dbg_printf ("warning: using midnight as starting time: 00:00:00\n");
    14401978        }
    14411979
     
    14561994        {
    14571995          if (! pc.zones_seen)
    1458             goto fail;
     1996            {
     1997              debug_mktime_not_ok (&tm0, &tm, &pc, pc.zones_seen);
     1998
     1999              goto fail;
     2000            }
    14592001          else
    14602002            {
     
    14732015              long int abs_time_zone_hour = abs_time_zone / 60;
    14742016              int abs_time_zone_min = abs_time_zone % 60;
    1475               char tz1buf[sizeof "XXX+0:00"
    1476                           + sizeof pc.time_zone * CHAR_BIT / 3];
     2017              char tz1buf[sizeof "XXX+0:00" + TYPE_WIDTH (pc.time_zone) / 3];
    14772018              if (!tz_was_altered)
    14782019                tz0 = get_tz (tz0buf);
     
    14802021                       abs_time_zone_hour, abs_time_zone_min);
    14812022              if (setenv ("TZ", tz1buf, 1) != 0)
    1482                 goto fail;
     2023                {
     2024                  /* TODO: was warn () + print errno? */
     2025                  if (pc.parse_datetime_debug)
     2026                    dbg_printf (_("error: setenv('TZ','%s') failed\n"), tz1buf);
     2027
     2028                  goto fail;
     2029                }
    14832030              tz_was_altered = true;
    14842031              tm = tm0;
    14852032              Start = mktime (&tm);
    14862033              if (! mktime_ok (&tm0, &tm, Start))
    1487                 goto fail;
     2034                {
     2035                  debug_mktime_not_ok (&tm0, &tm, &pc, pc.zones_seen);
     2036
     2037                  goto fail;
     2038                }
    14882039            }
    14892040        }
     
    14982049          Start = mktime (&tm);
    14992050          if (Start == (time_t) -1)
    1500             goto fail;
     2051            {
     2052              if (pc.parse_datetime_debug)
     2053                dbg_printf (_("error: day '%s' (day ordinal=%ld number=%d) "   \
     2054                              "resulted in an invalid date: '%s'\n"),
     2055                            str_days (&pc,dbg_ord,sizeof (dbg_ord)),
     2056                            pc.day_ordinal,pc.day_number,
     2057                            debug_strfdatetime (&tm, &pc, dbg_tm,
     2058                                                sizeof (dbg_tm)));
     2059
     2060              goto fail;
     2061            }
     2062
     2063          if (pc.parse_datetime_debug)
     2064            dbg_printf (_("new start date: '%s' is '%s'\n"),
     2065                        str_days (&pc,dbg_ord,sizeof (dbg_ord)),
     2066                        debug_strfdatetime (&tm, &pc, dbg_tm,sizeof (dbg_tm)));
     2067
     2068        }
     2069
     2070      if (pc.parse_datetime_debug)
     2071        {
     2072          if (!pc.dates_seen && !pc.days_seen)
     2073            dbg_printf (_("using current date as starting value: '%s'\n"),
     2074                        debug_strfdate (&tm,dbg_tm,sizeof (dbg_tm)));
     2075
     2076          if (pc.days_seen && pc.dates_seen)
     2077            dbg_printf (_("warning: day (%s) ignored when explicit dates " \
     2078                          "are given\n"),
     2079                        str_days (&pc,dbg_ord,sizeof (dbg_ord)));
     2080
     2081          dbg_printf (_("starting date/time: '%s'\n"),
     2082                      debug_strfdatetime (&tm, &pc, dbg_tm,sizeof (dbg_tm)));
    15012083        }
    15022084
     
    15042086      if (pc.rel.year | pc.rel.month | pc.rel.day)
    15052087        {
     2088          if (pc.parse_datetime_debug)
     2089            {
     2090              if ((pc.rel.year != 0 || pc.rel.month !=0) && tm.tm_mday==1)
     2091                dbg_printf (_("warning: when adding relative months/years, " \
     2092                              "it is recommended to specify the 15th of the " \
     2093                              "months\n"));
     2094
     2095              if (pc.rel.day != 0 && tm.tm_hour==0)
     2096                dbg_printf (_("warning: when adding relative days, "    \
     2097                              "it is recommended to specify 12:00pm\n"));
     2098            }
     2099
    15062100          int year = tm.tm_year + pc.rel.year;
    15072101          int month = tm.tm_mon + pc.rel.month;
     
    15102104              | ((month < tm.tm_mon) ^ (pc.rel.month < 0))
    15112105              | ((day < tm.tm_mday) ^ (pc.rel.day < 0)))
    1512             goto fail;
     2106            {
     2107              /* TODO: what is the actual error? int-value wrap-around? */
     2108              if (pc.parse_datetime_debug)
     2109                dbg_printf (_("error: %s:%d\n"), __FILE__,__LINE__);
     2110
     2111              goto fail;
     2112            }
    15132113          tm.tm_year = year;
    15142114          tm.tm_mon = month;
     
    15202120          Start = mktime (&tm);
    15212121          if (Start == (time_t) -1)
    1522             goto fail;
     2122            {
     2123              if (pc.parse_datetime_debug)
     2124                dbg_printf(_("error: adding relative date resulted " \
     2125                             "in an invalid date: '%s'\n"),
     2126                           debug_strfdatetime (&tm, &pc, dbg_tm,
     2127                                               sizeof (dbg_tm)));
     2128
     2129              goto fail;
     2130            }
     2131
     2132          if (pc.parse_datetime_debug)
     2133            {
     2134              dbg_printf (_("after date adjustment "                    \
     2135                            "(%+ld years, %+ld months, %+ld days),\n"),
     2136                          pc.rel.year, pc.rel.month, pc.rel.day);
     2137              dbg_printf (_("    new date/time = '%s'\n"),
     2138                          debug_strfdatetime (&tm, &pc, dbg_tm,
     2139                                              sizeof (dbg_tm)));
     2140            }
     2141
    15232142        }
    15242143
     
    15352154          struct tm const *gmt = gmtime (&t);
    15362155          if (! gmt)
    1537             goto fail;
     2156            {
     2157              /* TODO: use 'warn(3)' + print errno ? */
     2158              if (pc.parse_datetime_debug)
     2159                dbg_printf (_("error: gmtime failed for t=%ld\n"),t);
     2160
     2161              goto fail;
     2162            }
    15382163          delta -= tm_diff (&tm, gmt);
    15392164#endif
    15402165          t1 = Start - delta;
    15412166          if ((Start < t1) != (delta < 0))
    1542             goto fail;  /* time_t overflow */
     2167            {
     2168              if (pc.parse_datetime_debug)
     2169                dbg_printf (_("error: timezone %ld caused time_t overflow\n"),
     2170                            pc.time_zone);
     2171
     2172              goto fail;  /* time_t overflow */
     2173            }
    15432174          Start = t1;
    15442175        }
     2176
     2177      if (pc.parse_datetime_debug)
     2178        dbg_printf (_("'%s' = %ld epoch-seconds\n"),
     2179                    debug_strfdatetime (&tm, &pc, dbg_tm, sizeof (dbg_tm)),
     2180                    Start);
    15452181
    15462182      /* Add relative hours, minutes, and seconds.  On hosts that support
     
    15722208            | ((t4 < t3) ^ (d4 < 0))
    15732209            | (t5 != t4))
    1574           goto fail;
     2210            {
     2211              if (pc.parse_datetime_debug)
     2212                dbg_printf (_("error: adding relative time caused an " \
     2213                              "overflow\n"));
     2214
     2215              goto fail;
     2216            }
     2217
     2218          if (pc.parse_datetime_debug
     2219              && (pc.rel.hour | pc.rel.minutes | pc.rel.seconds | pc.rel.ns))
     2220            {
     2221              dbg_printf (_("after time adjustment (%+ld hours, " \
     2222                            "%+ld minutes, %+ld seconds, %+ld ns),\n"),
     2223                          pc.rel.hour,pc.rel.minutes,pc.rel.seconds,pc.rel.ns);
     2224              dbg_printf (_("    new time = %ld epoch-seconds\n"),t5);
     2225            }
    15752226
    15762227        result->tv_sec = t5;
     
    15882239  if (tz0 != tz0buf)
    15892240    free (tz0);
     2241
     2242  if (ok && pc.parse_datetime_debug)
     2243    {
     2244      /* print local timezone AFTER restoring TZ (if tz_was_altered)*/
     2245      const long int otz = get_effective_timezone ();
     2246      const char* tz_src;
     2247      const char* tz_env;
     2248
     2249      if ((tz_env = getenv("TZ")))
     2250        {
     2251          /* Special case: using 'date -u' simply set TZ=UTC0 */
     2252          if (STREQ(tz_env,"UTC0"))
     2253            {
     2254              tz_src = _("TZ=UTC0 environment value or -u");
     2255            }
     2256          else
     2257            {
     2258              snprintf (dbg_tm, sizeof(dbg_tm),
     2259                        _("TZ=\"%s\" environment value"), tz_env);
     2260              tz_src = dbg_tm;
     2261            }
     2262        }
     2263      else
     2264        {
     2265          tz_src = _("system default");
     2266        }
     2267
     2268      if (pc.parse_datetime_debug)
     2269        {
     2270          dbg_printf (_("output timezone: %+03d:%02d (set from %s)\n"),
     2271                      (int)(otz/60), abs ((int)otz)%60, tz_src);
     2272
     2273
     2274          dbg_printf (_("final: %ld.%09ld (epoch-seconds)\n"),
     2275                      result->tv_sec,result->tv_nsec);
     2276
     2277          struct tm const *gmt = gmtime (&result->tv_sec);
     2278          dbg_printf (_("final: %s (UTC0)\n"),
     2279                      debug_strfdatetime (gmt, NULL, dbg_tm, sizeof (dbg_tm)));
     2280          struct tm const *lmt = localtime (&result->tv_sec);
     2281          dbg_printf (_("final: %s (output timezone TZ=%+03d:%02d)\n"),
     2282                      debug_strfdatetime (lmt, NULL, dbg_tm, sizeof (dbg_tm)),
     2283                      (int)(otz/60), abs ((int)otz)%60);
     2284        }
     2285    }
     2286
    15902287  return ok;
    15912288}
  • TabularUnified coreutils/trunk/lib/quotearg.c

    r1648 r1953  
    253253  size_t i;
    254254  size_t len = 0;
     255  size_t orig_buffersize = 0;
    255256  char const *quote_string = 0;
    256257  size_t quote_string_len = 0;
     
    259260  bool elide_outer_quotes = (flags & QA_ELIDE_OUTER_QUOTES) != 0;
    260261  bool pending_shell_escape_end = false;
     262  bool encountered_single_quote = false;
     263  bool all_c_and_shell_quote_compat = true;
    261264
    262265#define STORE(c) \
     
    299302    while (0)
    300303
     304 process_input:
     305
    301306  switch (quoting_style)
    302307    {
     
    389394      bool is_right_quote = false;
    390395      bool escaping = false;
     396      bool c_and_shell_quote_compat = false;
    391397
    392398      if (backslash_escapes
     
    516522          /* Fall through.  */
    517523        case ' ':
     524          c_and_shell_quote_compat = true;
     525          /* Fall through.  */
    518526        case '!': /* special in bash */
    519527        case '"': case '$': case '&':
     
    534542
    535543        case '\'':
     544          encountered_single_quote = true;
     545          c_and_shell_quote_compat = true;
    536546          if (quoting_style == shell_always_quoting_style)
    537547            {
    538548              if (elide_outer_quotes)
    539549                goto force_outer_quoting_style;
     550
     551              if (buffersize && ! orig_buffersize)
     552                {
     553                  /* Just scan string to see if supports a more concise
     554                     representation, rather than writing a longer string
     555                     but returning the length of the more concise form.  */
     556                  orig_buffersize = buffersize;
     557                  buffersize = 0;
     558                }
     559
    540560              STORE ('\'');
    541561              STORE ('\\');
     
    567587             trouble if it appeared in quote_these_too, but that's also
    568588             documented as not accepting them.  */
     589          c_and_shell_quote_compat = true;
    569590          break;
    570591
     
    645666              }
    646667
     668            c_and_shell_quote_compat = printable;
     669
    647670            if (1 < m || (backslash_escapes && ! printable))
    648671              {
     
    690713      END_ESC ();
    691714      STORE (c);
     715
     716      if (! c_and_shell_quote_compat)
     717        all_c_and_shell_quote_compat = false;
    692718    }
    693719
     
    695721      && elide_outer_quotes)
    696722    goto force_outer_quoting_style;
     723
     724  /* Single shell quotes (') are commonly enough used as an apostrophe,
     725     that we attempt to minimize the quoting in this case.  Note itÊŒs
     726     better to use the apostrophe modifier "\u02BC" if possible, as that
     727     renders better and works with the word match regex \W+ etc.  */
     728  if (quoting_style == shell_always_quoting_style && ! elide_outer_quotes
     729      && encountered_single_quote)
     730    {
     731      if (all_c_and_shell_quote_compat)
     732        return quotearg_buffer_restyled (buffer, orig_buffersize, arg, argsize,
     733                                         c_quoting_style,
     734                                         flags, quote_these_too,
     735                                         left_quote, right_quote);
     736      else if (! buffersize && orig_buffersize)
     737        {
     738          /* Disable read-only scan, and reprocess to write quoted string.  */
     739          buffersize = orig_buffersize;
     740          len = 0;
     741          goto process_input;
     742        }
     743    }
    697744
    698745  if (quote_string && !elide_outer_quotes)
  • TabularUnified coreutils/trunk/lib/rand-isaac.c

    r1648 r1953  
    4141   then don't have -fsanitize=undefined warn about it.  */
    4242#undef ATTRIBUTE_NO_WARN_SANITIZE_UNDEFINED
    43 #if !_STRING_ARCH_unaligned \
     43#if !(_STRING_ARCH_unaligned || _STRING_INLINE_unaligned) \
    4444    || __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 9)
    4545# define ATTRIBUTE_NO_WARN_SANITIZE_UNDEFINED /* empty */
  • TabularUnified coreutils/trunk/lib/randread.c

    r1648 r1953  
    6161#endif
    6262
    63 #if _STRING_ARCH_unaligned
     63#if _STRING_ARCH_unaligned || _STRING_INLINE_unaligned
    6464# define ALIGNED_POINTER(ptr, type) true
    6565#else
  • TabularUnified coreutils/trunk/lib/regcomp.c

    r1648 r1953  
    155155    "\0"
    156156#define REG_EBRACK_IDX  (REG_ESUBREG_IDX + sizeof "Invalid back reference")
    157     gettext_noop ("Unmatched [ or [^")  /* REG_EBRACK */
     157    gettext_noop ("Unmatched [, [^, [:, [., or [=")     /* REG_EBRACK */
    158158    "\0"
    159 #define REG_EPAREN_IDX  (REG_EBRACK_IDX + sizeof "Unmatched [ or [^")
     159#define REG_EPAREN_IDX  (REG_EBRACK_IDX + sizeof "Unmatched [, [^, [:, [., or [=")
    160160    gettext_noop ("Unmatched ( or \\(") /* REG_EPAREN */
    161161    "\0"
     
    216216   are set in BUFP on entry.  */
    217217
    218 #ifdef _LIBC
    219 const char *
    220 re_compile_pattern (pattern, length, bufp)
    221     const char *pattern;
    222     size_t length;
    223     struct re_pattern_buffer *bufp;
    224 #else /* size_t might promote */
    225218const char *
    226219re_compile_pattern (const char *pattern, size_t length,
    227220                    struct re_pattern_buffer *bufp)
    228 #endif
    229221{
    230222  reg_errcode_t ret;
     
    264256
    265257reg_syntax_t
    266 re_set_syntax (syntax)
    267     reg_syntax_t syntax;
     258re_set_syntax (reg_syntax_t syntax)
    268259{
    269260  reg_syntax_t ret = re_syntax_options;
     
    277268
    278269int
    279 re_compile_fastmap (bufp)
    280     struct re_pattern_buffer *bufp;
     270re_compile_fastmap (struct re_pattern_buffer *bufp)
    281271{
    282272  re_dfa_t *dfa = bufp->buffer;
     
    478468
    479469int
    480 regcomp (preg, pattern, cflags)
    481     regex_t *_Restrict_ preg;
    482     const char *_Restrict_ pattern;
    483     int cflags;
     470regcomp (regex_t *_Restrict_ preg, const char *_Restrict_ pattern, int cflags)
    484471{
    485472  reg_errcode_t ret;
     
    539526   from either regcomp or regexec.   We don't use PREG here.  */
    540527
    541 #ifdef _LIBC
    542528size_t
    543 regerror (errcode, preg, errbuf, errbuf_size)
    544     int errcode;
    545     const regex_t *_Restrict_ preg;
    546     char *_Restrict_ errbuf;
    547     size_t errbuf_size;
    548 #else /* size_t might promote */
    549 size_t
    550 regerror (int errcode, const regex_t *_Restrict_ preg _UNUSED_PARAMETER_,
    551           char *_Restrict_ errbuf, size_t errbuf_size)
    552 #endif
     529regerror (int errcode, const regex_t *_Restrict_ preg, char *_Restrict_ errbuf,
     530          size_t errbuf_size)
    553531{
    554532  const char *msg;
     
    666644
    667645void
    668 regfree (preg)
    669     regex_t *preg;
     646regfree (regex_t *preg)
    670647{
    671648  re_dfa_t *dfa = preg->buffer;
     
    704681weak_function
    705682# endif
    706 re_comp (s)
    707      const char *s;
     683re_comp (const char *s)
    708684{
    709685  reg_errcode_t ret;
     
    14291405      node->first = node;
    14301406      node->node_idx = re_dfa_add_node (dfa, node->token);
    1431       if (BE (node->node_idx == REG_MISSING, 0))
     1407      if (BE (node->node_idx == -1, 0))
    14321408        return REG_ESPACE;
    14331409      if (node->token.type == ANCHOR)
     
    14391415/* Pass 2: compute NEXT on the tree.  Preorder visit.  */
    14401416static reg_errcode_t
    1441 calc_next (void *extra _UNUSED_PARAMETER_, bin_tree_t *node)
     1417calc_next (void *extra, bin_tree_t *node)
    14421418{
    14431419  switch (node->token.type)
     
    14901466        else
    14911467          right = node->next->node_idx;
    1492         assert (REG_VALID_INDEX (left));
    1493         assert (REG_VALID_INDEX (right));
     1468        assert (left > -1);
     1469        assert (right > -1);
    14941470        err = re_node_set_init_2 (dfa->edests + idx, left, right);
    14951471      }
     
    15411517          re_node_set_empty (dfa->edests + clone_node);
    15421518          clone_dest = duplicate_node (dfa, org_dest, constraint);
    1543           if (BE (clone_dest == REG_MISSING, 0))
     1519          if (BE (clone_dest == -1, 0))
    15441520            return REG_ESPACE;
    15451521          dfa->nexts[clone_node] = dfa->nexts[org_node];
     
    15741550          constraint |= dfa->nodes[org_node].constraint;
    15751551          clone_dest = duplicate_node (dfa, org_dest, constraint);
    1576           if (BE (clone_dest == REG_MISSING, 0))
     1552          if (BE (clone_dest == -1, 0))
    15771553            return REG_ESPACE;
    15781554          ok = re_node_set_insert (dfa->edests + clone_node, clone_dest);
     
    15881564          /* Search for a duplicated node which satisfies the constraint.  */
    15891565          clone_dest = search_duplicated_node (dfa, org_dest, constraint);
    1590           if (clone_dest == REG_MISSING)
     1566          if (clone_dest == -1)
    15911567            {
    15921568              /* There is no such duplicated node, create a new one.  */
    15931569              reg_errcode_t err;
    15941570              clone_dest = duplicate_node (dfa, org_dest, constraint);
    1595               if (BE (clone_dest == REG_MISSING, 0))
     1571              if (BE (clone_dest == -1, 0))
    15961572                return REG_ESPACE;
    15971573              ok = re_node_set_insert (dfa->edests + clone_node, clone_dest);
     
    16141590          org_dest = dfa->edests[org_node].elems[1];
    16151591          clone_dest = duplicate_node (dfa, org_dest, constraint);
    1616           if (BE (clone_dest == REG_MISSING, 0))
     1592          if (BE (clone_dest == -1, 0))
    16171593            return REG_ESPACE;
    16181594          ok = re_node_set_insert (dfa->edests + clone_node, clone_dest);
     
    16401616        return idx; /* Found.  */
    16411617    }
    1642   return REG_MISSING; /* Not found.  */
     1618  return -1; /* Not found.  */
    16431619}
    16441620
    16451621/* Duplicate the node whose index is ORG_IDX and set the constraint CONSTRAINT.
    1646    Return the index of the new node, or REG_MISSING if insufficient storage is
     1622   Return the index of the new node, or -1 if insufficient storage is
    16471623   available.  */
    16481624
     
    16511627{
    16521628  Idx dup_idx = re_dfa_add_node (dfa, dfa->nodes[org_idx]);
    1653   if (BE (dup_idx != REG_MISSING, 1))
     1629  if (BE (dup_idx != -1, 1))
    16541630    {
    16551631      dfa->nodes[dup_idx].constraint = constraint;
     
    17101686
    17111687#ifdef DEBUG
    1712       assert (dfa->eclosures[node_idx].nelem != REG_MISSING);
     1688      assert (dfa->eclosures[node_idx].nelem != -1);
    17131689#endif
    17141690
     
    17461722  /* This indicates that we are calculating this node now.
    17471723     We reference this value to avoid infinite loop.  */
    1748   dfa->eclosures[node].nelem = REG_MISSING;
     1724  dfa->eclosures[node].nelem = -1;
    17491725
    17501726  /* If the current node has constraints, duplicate all nodes
     
    17681744        /* If calculating the epsilon closure of 'edest' is in progress,
    17691745           return intermediate result.  */
    1770         if (dfa->eclosures[edest].nelem == REG_MISSING)
     1746        if (dfa->eclosures[edest].nelem == -1)
    17711747          {
    17721748            incomplete = true;
     
    25672543      end = 0;
    25682544      start = fetch_number (regexp, token, syntax);
    2569       if (start == REG_MISSING)
     2545      if (start == -1)
    25702546        {
    25712547          if (token->type == CHARACTER && token->opr.c == ',')
     
    25772553            }
    25782554        }
    2579       if (BE (start != REG_ERROR, 1))
     2555      if (BE (start != -2, 1))
    25802556        {
    25812557          /* We treat "{n}" as "{n,n}".  */
    25822558          end = ((token->type == OP_CLOSE_DUP_NUM) ? start
    25832559                 : ((token->type == CHARACTER && token->opr.c == ',')
    2584                     ? fetch_number (regexp, token, syntax) : REG_ERROR));
    2585         }
    2586       if (BE (start == REG_ERROR || end == REG_ERROR, 0))
     2560                    ? fetch_number (regexp, token, syntax) : -2));
     2561        }
     2562      if (BE (start == -2 || end == -2, 0))
    25872563        {
    25882564          /* Invalid sequence.  */
     
    26062582        }
    26072583
    2608       if (BE ((end != REG_MISSING && start > end)
     2584      if (BE ((end != -1 && start > end)
    26092585              || token->type != OP_CLOSE_DUP_NUM, 0))
    26102586        {
     
    26142590        }
    26152591
    2616       if (BE (RE_DUP_MAX < (end == REG_MISSING ? start : end), 0))
     2592      if (BE (RE_DUP_MAX < (end == -1 ? start : end), 0))
    26172593        {
    26182594          *err = REG_ESIZE;
     
    26232599    {
    26242600      start = (token->type == OP_DUP_PLUS) ? 1 : 0;
    2625       end = (token->type == OP_DUP_QUESTION) ? 1 : REG_MISSING;
     2601      end = (token->type == OP_DUP_QUESTION) ? 1 : -1;
    26262602    }
    26272603
     
    26672643
    26682644  tree = create_tree (dfa, elem, NULL,
    2669                       (end == REG_MISSING ? OP_DUP_ASTERISK : OP_ALT));
     2645                      (end == -1 ? OP_DUP_ASTERISK : OP_ALT));
    26702646  if (BE (tree == NULL, 0))
    26712647    goto parse_dup_op_espace;
     
    26752651#define TYPE_SIGNED(t) (! ((t) 0 < (t) -1))
    26762652
    2677   /* This loop is actually executed only when end != REG_MISSING,
     2653  /* This loop is actually executed only when end != -1,
    26782654     to rewrite <re>{0,n} as (<re>(<re>...<re>?)?)?...  We have
    26792655     already created the start+1-th copy.  */
    2680   if (TYPE_SIGNED (Idx) || end != REG_MISSING)
     2656  if (TYPE_SIGNED (Idx) || end != -1)
    26812657    for (i = start + 2; i <= end; ++i)
    26822658      {
     
    27062682
    27072683#ifndef _LIBC
     2684
     2685# ifdef RE_ENABLE_I18N
     2686/* Convert the byte B to the corresponding wide character.  In a
     2687   unibyte locale, treat B as itself if it is an encoding error.
     2688   In a multibyte locale, return WEOF if B is an encoding error.  */
     2689static wint_t
     2690parse_byte (unsigned char b, re_charset_t *mbcset)
     2691{
     2692  wint_t wc = __btowc (b);
     2693  return wc == WEOF && !mbcset ? b : wc;
     2694}
     2695#endif
     2696
    27082697  /* Local function for parse_bracket_exp only used in case of NOT _LIBC.
    27092698     Build the range expression which starts from START_ELEM, and ends
     
    27572746                 : 0));
    27582747    start_wc = ((start_elem->type == SB_CHAR || start_elem->type == COLL_SYM)
    2759                 ? __btowc (start_ch) : start_elem->opr.wch);
     2748                ? parse_byte (start_ch, mbcset) : start_elem->opr.wch);
    27602749    end_wc = ((end_elem->type == SB_CHAR || end_elem->type == COLL_SYM)
    2761               ? __btowc (end_ch) : end_elem->opr.wch);
     2750              ? parse_byte (end_ch, mbcset) : end_elem->opr.wch);
    27622751    if (start_wc == WEOF || end_wc == WEOF)
    27632752      return REG_ECOLLATE;
     
    27892778
    27902779            if (BE (new_array_start == NULL || new_array_end == NULL, 0))
    2791               return REG_ESPACE;
     2780              {
     2781                re_free (new_array_start);
     2782                re_free (new_array_end);
     2783                return REG_ESPACE;
     2784              }
    27922785
    27932786            mbcset->range_starts = new_array_start;
     
    28382831internal_function
    28392832# ifdef RE_ENABLE_I18N
    2840 build_collating_symbol (bitset_t sbcset,
    2841                         re_charset_t *mbcset _UNUSED_PARAMETER_,
    2842                         Idx *coll_sym_alloc _UNUSED_PARAMETER_,
    2843                         const unsigned char *name)
     2833build_collating_symbol (bitset_t sbcset, re_charset_t *mbcset,
     2834                        Idx *coll_sym_alloc, const unsigned char *name)
    28442835# else /* not RE_ENABLE_I18N */
    28452836build_collating_symbol (bitset_t sbcset, const unsigned char *name)
     
    34113402static reg_errcode_t
    34123403parse_bracket_element (bracket_elem_t *elem, re_string_t *regexp,
    3413                        re_token_t *token, int token_len,
    3414                        re_dfa_t *dfa _UNUSED_PARAMETER_,
     3404                       re_token_t *token, int token_len, re_dfa_t *dfa,
    34153405                       reg_syntax_t syntax, bool accept_hyphen)
    34163406{
     
    34993489static reg_errcode_t
    35003490#ifdef RE_ENABLE_I18N
    3501 build_equiv_class (bitset_t sbcset,
    3502                    re_charset_t *mbcset _UNUSED_PARAMETER_,
    3503                    Idx *equiv_class_alloc _UNUSED_PARAMETER_,
    3504                    const unsigned char *name)
     3491build_equiv_class (bitset_t sbcset, re_charset_t *mbcset,
     3492                   Idx *equiv_class_alloc, const unsigned char *name)
    35053493#else /* not RE_ENABLE_I18N */
    35063494build_equiv_class (bitset_t sbcset, const unsigned char *name)
     
    36913679
    36923680  sbcset = (re_bitset_ptr_t) calloc (sizeof (bitset_t), 1);
    3693 #ifdef RE_ENABLE_I18N
    3694   mbcset = (re_charset_t *) calloc (sizeof (re_charset_t), 1);
    3695 #endif /* RE_ENABLE_I18N */
    3696 
    3697 #ifdef RE_ENABLE_I18N
    3698   if (BE (sbcset == NULL || mbcset == NULL, 0))
    3699 #else /* not RE_ENABLE_I18N */
    37003681  if (BE (sbcset == NULL, 0))
    3701 #endif /* not RE_ENABLE_I18N */
    37023682    {
    37033683      *err = REG_ESPACE;
    37043684      return NULL;
    37053685    }
    3706 
    3707   if (non_match)
    3708     {
    3709 #ifdef RE_ENABLE_I18N
    3710       mbcset->non_match = 1;
    3711 #endif /* not RE_ENABLE_I18N */
    3712     }
     3686#ifdef RE_ENABLE_I18N
     3687  mbcset = (re_charset_t *) calloc (sizeof (re_charset_t), 1);
     3688  if (BE (mbcset == NULL, 0))
     3689    {
     3690      re_free (sbcset);
     3691      *err = REG_ESPACE;
     3692      return NULL;
     3693    }
     3694  mbcset->non_match = non_match;
     3695#endif /* RE_ENABLE_I18N */
    37133696
    37143697  /* We don't care the syntax in this case.  */
     
    37433726
    37443727  /* Build a tree for simple bracket.  */
     3728#if defined GCC_LINT || defined lint
     3729  memset (&br_token, 0, sizeof br_token);
     3730#endif
    37453731  br_token.type = SIMPLE_BRACKET;
    37463732  br_token.opr.sbcset = sbcset;
     
    37853771/* This is intended for the expressions like "a{1,3}".
    37863772   Fetch a number from 'input', and return the number.
    3787    Return REG_MISSING if the number field is empty like "{,1}".
     3773   Return -1 if the number field is empty like "{,1}".
    37883774   Return RE_DUP_MAX + 1 if the number field is too large.
    3789    Return REG_ERROR if an error occurred.  */
     3775   Return -2 if an error occurred.  */
    37903776
    37913777static Idx
    37923778fetch_number (re_string_t *input, re_token_t *token, reg_syntax_t syntax)
    37933779{
    3794   Idx num = REG_MISSING;
     3780  Idx num = -1;
    37953781  unsigned char c;
    37963782  while (1)
     
    37993785      c = token->opr.c;
    38003786      if (BE (token->type == END_OF_RE, 0))
    3801         return REG_ERROR;
     3787        return -2;
    38023788      if (token->type == OP_CLOSE_DUP_NUM || c == ',')
    38033789        break;
    3804       num = ((token->type != CHARACTER || c < '0' || '9' < c
    3805               || num == REG_ERROR)
    3806              ? REG_ERROR
    3807              : num == REG_MISSING
     3790      num = ((token->type != CHARACTER || c < '0' || '9' < c || num == -2)
     3791             ? -2
     3792             : num == -1
    38083793             ? c - '0'
    38093794             : MIN (RE_DUP_MAX + 1, num * 10 + c - '0'));
     
    38393824{
    38403825  re_token_t t;
     3826#if defined GCC_LINT || defined lint
     3827  memset (&t, 0, sizeof t);
     3828#endif
    38413829  t.type = type;
    38423830  return create_token_tree (dfa, left, right, &t);
     
    38683856  tree->first = NULL;
    38693857  tree->next = NULL;
    3870   tree->node_idx = REG_MISSING;
     3858  tree->node_idx = -1;
    38713859
    38723860  if (left != NULL)
     
    39083896
    39093897static reg_errcode_t
    3910 free_tree (void *extra _UNUSED_PARAMETER_, bin_tree_t *node)
     3898free_tree (void *extra, bin_tree_t *node)
    39113899{
    39123900  free_token (&node->token);
  • TabularUnified coreutils/trunk/lib/regex.h

    r1648 r1953  
    4343   _REGEX_LARGE_OFFSETS.  */
    4444
    45 /* The type of nonnegative object indexes.  Traditionally, GNU regex
    46    uses 'int' for these.  Code that uses __re_idx_t should work
    47    regardless of whether the type is signed.  */
    48 typedef size_t __re_idx_t;
    49 
    5045/* The type of object sizes.  */
    5146typedef size_t __re_size_t;
     
    5954/* The traditional GNU regex implementation mishandles strings longer
    6055   than INT_MAX.  */
    61 typedef int __re_idx_t;
    6256typedef unsigned int __re_size_t;
    6357typedef unsigned long int __re_long_size_t;
     
    492486/* POSIX 1003.1-2008 requires that regoff_t be at least as wide as
    493487   ptrdiff_t and ssize_t.  We don't know of any hosts where ptrdiff_t
    494    is wider than ssize_t, so ssize_t is safe.  */
     488   is wider than ssize_t, so ssize_t is safe.  ptrdiff_t is not
     489   visible here, so use ssize_t.  */
    495490typedef ssize_t regoff_t;
    496491#else
     
    543538
    544539   To free the allocated storage, you must call 'regfree' on BUFFER.
    545    Note that the translate table must either have been initialised by
     540   Note that the translate table must either have been initialized by
    546541   'regcomp', with a malloc'ed value, or set to NULL before calling
    547542   'regfree'.  */
     
    562557   information in REGS (if REGS and BUFFER->no_sub are nonzero).  */
    563558extern regoff_t re_search (struct re_pattern_buffer *__buffer,
    564                            const char *__string, __re_idx_t __length,
    565                            __re_idx_t __start, regoff_t __range,
     559                           const char *__String, regoff_t __length,
     560                           regoff_t __start, regoff_t __range,
    566561                           struct re_registers *__regs);
    567562
     
    570565   STRING2.  Also, stop searching at index START + STOP.  */
    571566extern regoff_t re_search_2 (struct re_pattern_buffer *__buffer,
    572                              const char *__string1, __re_idx_t __length1,
    573                              const char *__string2, __re_idx_t __length2,
    574                              __re_idx_t __start, regoff_t __range,
     567                             const char *__string1, regoff_t __length1,
     568                             const char *__string2, regoff_t __length2,
     569                             regoff_t __start, regoff_t __range,
    575570                             struct re_registers *__regs,
    576                              __re_idx_t __stop);
     571                             regoff_t __stop);
    577572
    578573
     
    580575   in BUFFER matched, starting at position START.  */
    581576extern regoff_t re_match (struct re_pattern_buffer *__buffer,
    582                           const char *__string, __re_idx_t __length,
    583                           __re_idx_t __start, struct re_registers *__regs);
     577                          const char *__String, regoff_t __length,
     578                          regoff_t __start, struct re_registers *__regs);
    584579
    585580
    586581/* Relates to 're_match' as 're_search_2' relates to 're_search'.  */
    587582extern regoff_t re_match_2 (struct re_pattern_buffer *__buffer,
    588                             const char *__string1, __re_idx_t __length1,
    589                             const char *__string2, __re_idx_t __length2,
    590                             __re_idx_t __start, struct re_registers *__regs,
    591                             __re_idx_t __stop);
     583                            const char *__string1, regoff_t __length1,
     584                            const char *__string2, regoff_t __length2,
     585                            regoff_t __start, struct re_registers *__regs,
     586                            regoff_t __stop);
    592587
    593588
     
    652647
    653648extern int regexec (const regex_t *_Restrict_ __preg,
    654                     const char *_Restrict_ __string, size_t __nmatch,
     649                    const char *_Restrict_ __String, size_t __nmatch,
    655650                    regmatch_t __pmatch[_Restrict_arr_],
    656651                    int __eflags);
  • TabularUnified coreutils/trunk/lib/regex_internal.c

    r1648 r1953  
    1818   <http://www.gnu.org/licenses/>.  */
    1919
    20 #include "verify.h"
    21 #include "intprops.h"
    2220static void re_string_construct_common (const char *str, Idx len,
    2321                                        re_string_t *pstr,
     
    926924{
    927925  int c;
    928   if (BE (! REG_VALID_INDEX (idx), 0))
     926  if (BE (idx < 0, 0))
    929927    /* In this case, we use the value stored in input->tip_context,
    930928       since we can't know the character in input->mbs[-1] here.  */
     
    942940#if defined DEBUG && DEBUG
    943941          /* It must not happen.  */
    944           assert (REG_VALID_INDEX (wc_idx));
     942          assert (wc_idx >= 0);
    945943#endif
    946944          --wc_idx;
    947           if (! REG_VALID_INDEX (wc_idx))
     945          if (wc_idx < 0)
    948946            return input->tip_context;
    949947        }
     
    10821080        {
    10831081          /* Try to find the item in DEST.  Maybe we could binary search?  */
    1084           while (REG_VALID_INDEX (id) && dest->elems[id] > src1->elems[i1])
     1082          while (id >= 0 && dest->elems[id] > src1->elems[i1])
    10851083            --id;
    10861084
    1087           if (! REG_VALID_INDEX (id) || dest->elems[id] != src1->elems[i1])
     1085          if (id < 0 || dest->elems[id] != src1->elems[i1])
    10881086            dest->elems[--sbase] = src1->elems[i1];
    10891087
    1090           if (! REG_VALID_INDEX (--i1) || ! REG_VALID_INDEX (--i2))
     1088          if (--i1 < 0 || --i2 < 0)
    10911089            break;
    10921090        }
     
    10951093      else if (src1->elems[i1] < src2->elems[i2])
    10961094        {
    1097           if (! REG_VALID_INDEX (--i2))
     1095          if (--i2 < 0)
    10981096            break;
    10991097        }
    11001098      else
    11011099        {
    1102           if (! REG_VALID_INDEX (--i1))
     1100          if (--i1 < 0)
    11031101            break;
    11041102        }
     
    11131111     less the same loop that is in re_node_set_merge.  */
    11141112  dest->nelem += delta;
    1115   if (delta > 0 && REG_VALID_INDEX (id))
     1113  if (delta > 0 && id >= 0)
    11161114    for (;;)
    11171115      {
     
    11271125            /* Slide from the bottom.  */
    11281126            dest->elems[id + delta] = dest->elems[id];
    1129             if (! REG_VALID_INDEX (--id))
     1127            if (--id < 0)
    11301128              break;
    11311129          }
     
    12211219     found in DEST.  Maybe we could binary search in DEST?  */
    12221220  for (sbase = dest->nelem + 2 * src->nelem,
    1223        is = src->nelem - 1, id = dest->nelem - 1;
    1224        REG_VALID_INDEX (is) && REG_VALID_INDEX (id); )
     1221       is = src->nelem - 1, id = dest->nelem - 1; is >= 0 && id >= 0; )
    12251222    {
    12261223      if (dest->elems[id] == src->elems[is])
     
    12321229    }
    12331230
    1234   if (REG_VALID_INDEX (is))
     1231  if (is >= 0)
    12351232    {
    12361233      /* If DEST is exhausted, the remaining items of SRC must be unique.  */
     
    12611258          /* Slide from the bottom.  */
    12621259          dest->elems[id + delta] = dest->elems[id];
    1263           if (! REG_VALID_INDEX (--id))
     1260          if (--id < 0)
    12641261            {
    12651262              /* Copy remaining SRC elements.  */
     
    13601357  if (set1 == NULL || set2 == NULL || set1->nelem != set2->nelem)
    13611358    return false;
    1362   for (i = set1->nelem ; REG_VALID_INDEX (--i) ; )
     1359  for (i = set1->nelem ; --i >= 0 ; )
    13631360    if (set1->elems[i] != set2->elems[i])
    13641361      return false;
     
    13731370{
    13741371  __re_size_t idx, right, mid;
    1375   if (! REG_VALID_NONZERO_INDEX (set->nelem))
     1372  if (set->nelem <= 0)
    13761373    return 0;
    13771374
     
    13941391re_node_set_remove_at (re_node_set *set, Idx idx)
    13951392{
    1396   verify (! TYPE_SIGNED (Idx));
    1397   /* if (idx < 0)
    1398      return; */
    1399   if (idx >= set->nelem)
     1393  if (idx < 0 || idx >= set->nelem)
    14001394    return;
    14011395  --set->nelem;
     
    14071401
    14081402/* Add the token TOKEN to dfa->nodes, and return the index of the token.
    1409    Or return REG_MISSING if an error occurred.  */
     1403   Or return -1 if an error occurred.  */
    14101404
    14111405static Idx
     
    14251419                                               sizeof (Idx)));
    14261420      if (BE (MIN (IDX_MAX, SIZE_MAX / max_object_size) < new_nodes_alloc, 0))
    1427         return REG_MISSING;
     1421        return -1;
    14281422
    14291423      new_nodes = re_realloc (dfa->nodes, re_token_t, new_nodes_alloc);
    14301424      if (BE (new_nodes == NULL, 0))
    1431         return REG_MISSING;
     1425        return -1;
    14321426      dfa->nodes = new_nodes;
    14331427      new_nexts = re_realloc (dfa->nexts, Idx, new_nodes_alloc);
     
    14371431      if (BE (new_nexts == NULL || new_indices == NULL
    14381432              || new_edests == NULL || new_eclosures == NULL, 0))
    1439         return REG_MISSING;
     1433        {
     1434           re_free (new_nexts);
     1435           re_free (new_indices);
     1436           re_free (new_edests);
     1437           re_free (new_eclosures);
     1438           return -1;
     1439        }
    14401440      dfa->nexts = new_nexts;
    14411441      dfa->org_indices = new_indices;
     
    14511451     || token.type == COMPLEX_BRACKET);
    14521452#endif
    1453   dfa->nexts[dfa->nodes_len] = REG_MISSING;
     1453  dfa->nexts[dfa->nodes_len] = -1;
    14541454  re_node_set_init_empty (dfa->edests + dfa->nodes_len);
    14551455  re_node_set_init_empty (dfa->eclosures + dfa->nodes_len);
     
    14861486  struct re_state_table_entry *spot;
    14871487  Idx i;
    1488 #ifdef lint
     1488#if defined GCC_LINT || defined lint
    14891489  /* Suppress bogus uninitialized-variable warnings.  */
    14901490  *err = REG_NOERROR;
     
    15341534  struct re_state_table_entry *spot;
    15351535  Idx i;
    1536 #ifdef lint
     1536#if defined GCC_LINT || defined lint
    15371537  /* Suppress bogus uninitialized-variable warnings.  */
    15381538  *err = REG_NOERROR;
  • TabularUnified coreutils/trunk/lib/regex_internal.h

    r1648 r1953  
    152152#endif
    153153
    154 typedef __re_idx_t Idx;
     154#ifndef SSIZE_MAX
     155# define SSIZE_MAX ((ssize_t) (SIZE_MAX / 2))
     156#endif
     157
     158/* The type of indexes into strings.  This is signed, not size_t,
     159   since the API requires indexes to fit in regoff_t anyway, and using
     160   signed integers makes the code a bit smaller and presumably faster.
     161   The traditional GNU regex implementation uses int for indexes.
     162   The POSIX-compatible implementation uses a possibly-wider type.
     163   The name 'Idx' is three letters to minimize the hassle of
     164   reindenting a lot of regex code that formerly used 'int'.  */
     165typedef regoff_t Idx;
    155166#ifdef _REGEX_LARGE_OFFSETS
    156 # define IDX_MAX (SIZE_MAX - 2)
     167# define IDX_MAX SSIZE_MAX
    157168#else
    158169# define IDX_MAX INT_MAX
    159 #endif
    160 
    161 /* Special return value for failure to match.  */
    162 #define REG_MISSING ((Idx) -1)
    163 
    164 /* Special return value for internal error.  */
    165 #define REG_ERROR ((Idx) -2)
    166 
    167 /* Test whether N is a valid index, and is not one of the above.  */
    168 #ifdef _REGEX_LARGE_OFFSETS
    169 # define REG_VALID_INDEX(n) ((Idx) (n) < REG_ERROR)
    170 #else
    171 # define REG_VALID_INDEX(n) (0 <= (n))
    172 #endif
    173 
    174 /* Test whether N is a valid nonzero index.  */
    175 #ifdef _REGEX_LARGE_OFFSETS
    176 # define REG_VALID_NONZERO_INDEX(n) ((Idx) ((n) - 1) < (Idx) (REG_ERROR - 1))
    177 #else
    178 # define REG_VALID_NONZERO_INDEX(n) (0 < (n))
    179170#endif
    180171
     
    870861static int
    871862internal_function __attribute__ ((pure, unused))
    872 re_string_elem_size_at (const re_string_t *pstr _UNUSED_PARAMETER_,
    873                         Idx idx _UNUSED_PARAMETER_)
     863re_string_elem_size_at (const re_string_t *pstr, Idx idx)
    874864{
    875865# ifdef _LIBC
  • TabularUnified coreutils/trunk/lib/regexec.c

    r1648 r1953  
    1818   <http://www.gnu.org/licenses/>.  */
    1919
    20 #include "verify.h"
    21 #include "intprops.h"
    2220static reg_errcode_t match_ctx_init (re_match_context_t *cache, int eflags,
    2321                                     Idx n) internal_function;
     
    223221
    224222int
    225 regexec (preg, string, nmatch, pmatch, eflags)
    226     const regex_t *_Restrict_ preg;
    227     const char *_Restrict_ string;
    228     size_t nmatch;
    229     regmatch_t pmatch[_Restrict_arr_];
    230     int eflags;
     223regexec (const regex_t *_Restrict_ preg, const char *_Restrict_ string,
     224         size_t nmatch, regmatch_t pmatch[], int eflags)
    231225{
    232226  reg_errcode_t err;
     
    309303
    310304regoff_t
    311 re_match (bufp, string, length, start, regs)
    312     struct re_pattern_buffer *bufp;
    313     const char *string;
    314     Idx length, start;
    315     struct re_registers *regs;
     305re_match (struct re_pattern_buffer *bufp, const char *string, Idx length,
     306          Idx start, struct re_registers *regs)
    316307{
    317308  return re_search_stub (bufp, string, length, start, 0, length, regs, true);
     
    322313
    323314regoff_t
    324 re_search (bufp, string, length, start, range, regs)
    325     struct re_pattern_buffer *bufp;
    326     const char *string;
    327     Idx length, start;
    328     regoff_t range;
    329     struct re_registers *regs;
     315re_search (struct re_pattern_buffer *bufp, const char *string, Idx length,
     316           Idx start, regoff_t range, struct re_registers *regs)
    330317{
    331318  return re_search_stub (bufp, string, length, start, range, length, regs,
     
    337324
    338325regoff_t
    339 re_match_2 (bufp, string1, length1, string2, length2, start, regs, stop)
    340     struct re_pattern_buffer *bufp;
    341     const char *string1, *string2;
    342     Idx length1, length2, start, stop;
    343     struct re_registers *regs;
     326re_match_2 (struct re_pattern_buffer *bufp, const char *string1, Idx length1,
     327            const char *string2, Idx length2, Idx start,
     328            struct re_registers *regs, Idx stop)
    344329{
    345330  return re_search_2_stub (bufp, string1, length1, string2, length2,
     
    351336
    352337regoff_t
    353 re_search_2 (bufp, string1, length1, string2, length2, start, range, regs, stop)
    354     struct re_pattern_buffer *bufp;
    355     const char *string1, *string2;
    356     Idx length1, length2, start, stop;
    357     regoff_t range;
    358     struct re_registers *regs;
     338re_search_2 (struct re_pattern_buffer *bufp, const char *string1, Idx length1,
     339             const char *string2, Idx length2, Idx start, regoff_t range,
     340             struct re_registers *regs, Idx stop)
    359341{
    360342  return re_search_2_stub (bufp, string1, length1, string2, length2,
     
    366348
    367349static regoff_t
    368 re_search_2_stub (struct re_pattern_buffer *bufp,
    369                   const char *string1, Idx length1,
    370                   const char *string2, Idx length2,
    371                   Idx start, regoff_t range, struct re_registers *regs,
     350internal_function
     351re_search_2_stub (struct re_pattern_buffer *bufp, const char *string1,
     352                  Idx length1, const char *string2, Idx length2, Idx start,
     353                  regoff_t range, struct re_registers *regs,
    372354                  Idx stop, bool ret_len)
    373355{
     
    377359  char *s = NULL;
    378360
    379   verify (! TYPE_SIGNED (Idx));
    380   if (BE (len < length1, 0))
    381      return -2;
    382   /* if (BE (length1 < 0 || length2 < 0 || stop < 0, 0))
    383      return -2; */
     361  if (BE (length1 < 0 || length2 < 0 || stop < 0 || len < length1, 0))
     362    return -2;
    384363
    385364  /* Concatenate the strings.  */
     
    416395
    417396static regoff_t
    418 re_search_stub (struct re_pattern_buffer *bufp,
    419                 const char *string, Idx length,
     397internal_function
     398re_search_stub (struct re_pattern_buffer *bufp, const char *string, Idx length,
    420399                Idx start, regoff_t range, Idx stop, struct re_registers *regs,
    421400                bool ret_len)
     
    430409
    431410  /* Check for out-of-range.  */
    432   verify (! TYPE_SIGNED (Idx));
    433   /* if (BE (start < 0, 0))
    434      return -1; */
    435   if (BE (start > length, 0))
    436      return -1;
     411  if (BE (start < 0 || start > length, 0))
     412    return -1;
    437413  if (BE (length < last_start || (0 <= range && last_start < start), 0))
    438414    last_start = length;
    439   else if (BE (/* last_start < 0 || */ (range < 0 && start <= last_start), 0))
     415  else if (BE (last_start < 0 || (range < 0 && start <= last_start), 0))
    440416    last_start = 0;
    441417
     
    509485
    510486static unsigned
     487internal_function
    511488re_copy_regs (struct re_registers *regs, regmatch_t *pmatch, Idx nregs,
    512489              int regs_allocated)
     
    587564
    588565void
    589 re_set_registers (bufp, regs, num_regs, starts, ends)
    590     struct re_pattern_buffer *bufp;
    591     struct re_registers *regs;
    592     __re_size_t num_regs;
    593     regoff_t *starts, *ends;
     566re_set_registers (struct re_pattern_buffer *bufp, struct re_registers *regs,
     567                  __re_size_t num_regs, regoff_t *starts, regoff_t *ends)
    594568{
    595569  if (num_regs)
     
    620594weak_function
    621595# endif
    622 re_exec (s)
    623      const char *s;
     596re_exec (const char *s)
    624597{
    625598  return 0 == regexec (&re_comp_buf, s, 0, NULL, 0);
     
    640613
    641614static reg_errcode_t
    642 __attribute_warn_unused_result__
    643 re_search_internal (const regex_t *preg,
    644                     const char *string, Idx length,
    645                     Idx start, Idx last_start, Idx stop,
    646                     size_t nmatch, regmatch_t pmatch[],
    647                     int eflags)
     615__attribute_warn_unused_result__ internal_function
     616re_search_internal (const regex_t *preg, const char *string, Idx length,
     617                    Idx start, Idx last_start, Idx stop, size_t nmatch,
     618                    regmatch_t pmatch[], int eflags)
    648619{
    649620  reg_errcode_t err;
     
    654625  int match_kind;
    655626  Idx match_first;
    656   Idx match_last = REG_MISSING;
     627  Idx match_last = -1;
    657628  Idx extra_nmatch;
    658629  bool sb;
     
    863834      match_last = check_matching (&mctx, fl_longest_match,
    864835                                   start <= last_start ? &match_first : NULL);
    865       if (match_last != REG_MISSING)
    866         {
    867           if (BE (match_last == REG_ERROR, 0))
     836      if (match_last != -1)
     837        {
     838          if (BE (match_last == -2, 0))
    868839            {
    869840              err = REG_ESPACE;
     
    887858                  if (BE (err != REG_NOMATCH, 0))
    888859                    goto free_return;
    889                   match_last = REG_MISSING;
     860                  match_last = -1;
    890861                }
    891862              else
     
    898869
    899870#ifdef DEBUG
    900   assert (match_last != REG_MISSING);
     871  assert (match_last != -1);
    901872  assert (err == REG_NOERROR);
    902873#endif
     
    976947
    977948static reg_errcode_t
    978 __attribute_warn_unused_result__
     949internal_function __attribute_warn_unused_result__
    979950prune_impossible_nodes (re_match_context_t *mctx)
    980951{
     
    1024995            {
    1025996              --match_last;
    1026               if (! REG_VALID_INDEX (match_last))
     997              if (match_last < 0)
    1027998                {
    1028999                  ret = REG_NOMATCH;
     
    11051076
    11061077/* Check whether the regular expression match input string INPUT or not,
    1107    and return the index where the matching end.  Return REG_MISSING if
    1108    there is no match, and return REG_ERROR in case of an error.
     1078   and return the index where the matching end.  Return -1 if
     1079   there is no match, and return -2 in case of an error.
    11091080   FL_LONGEST_MATCH means we want the POSIX longest matching.
    11101081   If P_MATCH_FIRST is not NULL, and the match fails, it is set to the
     
    11211092  reg_errcode_t err;
    11221093  Idx match = 0;
    1123   Idx match_last = REG_MISSING;
     1094  Idx match_last = -1;
    11241095  Idx cur_str_idx = re_string_cur_idx (&mctx->input);
    11251096  re_dfastate_t *cur_state;
     
    11331104    {
    11341105      assert (err == REG_ESPACE);
    1135       return REG_ERROR;
     1106      return -2;
    11361107    }
    11371108
     
    11881159            {
    11891160              assert (err == REG_ESPACE);
    1190               return REG_ERROR;
     1161              return -2;
    11911162            }
    11921163        }
     
    12021173             already found a valid (even if not the longest) match.  */
    12031174          if (BE (err != REG_NOERROR, 0))
    1204             return REG_ERROR;
     1175            return -2;
    12051176
    12061177          if (mctx->state_log == NULL
     
    12851256   corresponding to the DFA).
    12861257   Return the destination node, and update EPS_VIA_NODES;
    1287    return REG_MISSING in case of errors.  */
     1258   return -1 in case of errors.  */
    12881259
    12891260static Idx
     
    13031274      ok = re_node_set_insert (eps_via_nodes, node);
    13041275      if (BE (! ok, 0))
    1305         return REG_ERROR;
    1306       /* Pick up a valid destination, or return REG_MISSING if none
     1276        return -2;
     1277      /* Pick up a valid destination, or return -1 if none
    13071278         is found.  */
    1308       for (dest_node = REG_MISSING, i = 0; i < edests->nelem; ++i)
     1279      for (dest_node = -1, i = 0; i < edests->nelem; ++i)
    13091280        {
    13101281          Idx candidate = edests->elems[i];
    13111282          if (!re_node_set_contains (cur_nodes, candidate))
    13121283            continue;
    1313           if (dest_node == REG_MISSING)
     1284          if (dest_node == -1)
    13141285            dest_node = candidate;
    13151286
     
    13251296                       && push_fail_stack (fs, *pidx, candidate, nregs, regs,
    13261297                                           eps_via_nodes))
    1327                 return REG_ERROR;
     1298                return -2;
    13281299
    13291300              /* We know we are going to exit.  */
     
    13501321            {
    13511322              if (regs[subexp_idx].rm_so == -1 || regs[subexp_idx].rm_eo == -1)
    1352                 return REG_MISSING;
     1323                return -1;
    13531324              else if (naccepted)
    13541325                {
     
    13561327                  if (memcmp (buf + regs[subexp_idx].rm_so, buf + *pidx,
    13571328                              naccepted) != 0)
    1358                     return REG_MISSING;
     1329                    return -1;
    13591330                }
    13601331            }
     
    13651336              ok = re_node_set_insert (eps_via_nodes, node);
    13661337              if (BE (! ok, 0))
    1367                 return REG_ERROR;
     1338                return -2;
    13681339              dest_node = dfa->edests[node].elems[0];
    13691340              if (re_node_set_contains (&mctx->state_log[*pidx]->nodes,
     
    13811352                     || !re_node_set_contains (&mctx->state_log[*pidx]->nodes,
    13821353                                               dest_node)))
    1383             return REG_MISSING;
     1354            return -1;
    13841355          re_node_set_empty (eps_via_nodes);
    13851356          return dest_node;
    13861357        }
    13871358    }
    1388   return REG_MISSING;
     1359  return -1;
    13891360}
    13901361
     
    14221393{
    14231394  Idx num = --fs->num;
    1424   assert (REG_VALID_INDEX (num));
     1395  assert (num >= 0);
    14251396  *pidx = fs->stack[num].idx;
    14261397  memcpy (regs, fs->stack[num].regs, sizeof (regmatch_t) * nregs);
     
    15151486                                    &eps_via_nodes, fs);
    15161487
    1517       if (BE (! REG_VALID_INDEX (cur_node), 0))
    1518         {
    1519           if (BE (cur_node == REG_ERROR, 0))
     1488      if (BE (cur_node < 0, 0))
     1489        {
     1490          if (BE (cur_node == -2, 0))
    15201491            {
    15211492              re_node_set_free (&eps_via_nodes);
     
    19011872            Idx edst1 = dfa->edests[cur_node].elems[0];
    19021873            Idx edst2 = ((dfa->edests[cur_node].nelem > 1)
    1903                          ? dfa->edests[cur_node].elems[1] : REG_MISSING);
     1874                         ? dfa->edests[cur_node].elems[1] : -1);
    19041875            if ((!re_node_set_contains (inv_eclosure, edst1)
    19051876                 && re_node_set_contains (dest_nodes, edst1))
    1906                 || (REG_VALID_NONZERO_INDEX (edst2)
     1877                || (edst2 > 0
    19071878                    && !re_node_set_contains (inv_eclosure, edst2)
    19081879                    && re_node_set_contains (dest_nodes, edst2)))
     
    19841955        {
    19851956        case OP_BACK_REF:
    1986           if (bkref_idx != REG_MISSING)
     1957          if (bkref_idx != -1)
    19871958            {
    19881959              struct re_backref_cache_entry *ent = mctx->bkref_ents + bkref_idx;
     
    21002071      if (ent->subexp_to == str_idx)
    21012072        {
    2102           Idx ops_node = REG_MISSING;
    2103           Idx cls_node = REG_MISSING;
     2073          Idx ops_node = -1;
     2074          Idx cls_node = -1;
    21042075          for (node_idx = 0; node_idx < dest_nodes->nelem; ++node_idx)
    21052076            {
     
    21162087          /* Check the limitation of the open subexpression.  */
    21172088          /* Note that (ent->subexp_to = str_idx != ent->subexp_from).  */
    2118           if (REG_VALID_INDEX (ops_node))
     2089          if (ops_node >= 0)
    21192090            {
    21202091              err = sub_epsilon_src_nodes (dfa, ops_node, dest_nodes,
     
    21252096
    21262097          /* Check the limitation of the close subexpression.  */
    2127           if (REG_VALID_INDEX (cls_node))
     2098          if (cls_node >= 0)
    21282099            for (node_idx = 0; node_idx < dest_nodes->nelem; ++node_idx)
    21292100              {
     
    21782149  Idx first_idx = search_cur_bkref_entry (mctx, str_idx);
    21792150
    2180   if (first_idx == REG_MISSING)
     2151  if (first_idx == -1)
    21812152    return REG_NOERROR;
    21822153
     
    25832554        return err;
    25842555#ifdef DEBUG
    2585       assert (dfa->nexts[cur_node_idx] != REG_MISSING);
     2556      assert (dfa->nexts[cur_node_idx] != -1);
    25862557#endif
    25872558      new_nodes = dfa->eclosures + dfa->nexts[cur_node_idx];
     
    26492620         the backreference to appropriate state_log.  */
    26502621#ifdef DEBUG
    2651       assert (dfa->nexts[node_idx] != REG_MISSING);
     2622      assert (dfa->nexts[node_idx] != -1);
    26522623#endif
    26532624      for (; bkc_idx < mctx->nbkref_ents; ++bkc_idx)
     
    27332704  /* Return if we have already checked BKREF_NODE at BKREF_STR_IDX.  */
    27342705  Idx cache_idx = search_cur_bkref_entry (mctx, bkref_str_idx);
    2735   if (cache_idx != REG_MISSING)
     2706  if (cache_idx != -1)
    27362707    {
    27372708      const struct re_backref_cache_entry *entry
     
    28382809          cls_node = find_subexp_node (dfa, nodes, subexp_num,
    28392810                                       OP_CLOSE_SUBEXP);
    2840           if (cls_node == REG_MISSING)
     2811          if (cls_node == -1)
    28412812            continue; /* No.  */
    28422813          if (sub_top->path == NULL)
     
    29172888        return cls_node;
    29182889    }
    2919   return REG_MISSING;
     2890  return -1;
    29202891}
    29212892
     
    31933164      const re_node_set *eclosure = dfa->eclosures + cur_node;
    31943165      outside_node = find_subexp_node (dfa, eclosure, ex_subexp, type);
    3195       if (outside_node == REG_MISSING)
     3166      if (outside_node == -1)
    31963167        {
    31973168          /* There are no problematic nodes, just merge them.  */
     
    32793250  struct re_backref_cache_entry *ent;
    32803251
    3281   if (cache_idx_start == REG_MISSING)
     3252  if (cache_idx_start == -1)
    32823253    return REG_NOERROR;
    32833254
     
    34043375     destinations.  */
    34053376  ndests = group_nodes_into_DFAstates (dfa, state, dests_node, dests_ch);
    3406   if (BE (! REG_VALID_NONZERO_INDEX (ndests), 0))
     3377  if (BE (ndests <= 0, 0))
    34073378    {
    34083379      if (dests_node_malloced)
     
    34663437        {
    34673438          next_node = dfa->nexts[dests_node[i].elems[j]];
    3468           if (next_node != REG_MISSING)
     3439          if (next_node != -1)
    34693440            {
    34703441              err = re_node_set_merge (&follows, dfa->eclosures + next_node);
     
    37773748  for (j = 0; j < ndests; ++j)
    37783749    re_node_set_free (dests_node + j);
    3779   return REG_MISSING;
     3750  return -1;
    37803751}
    37813752
     
    42094180{
    42104181  mctx->eflags = eflags;
    4211   mctx->match_last = REG_MISSING;
     4182  mctx->match_last = -1;
    42124183  if (n > 0)
    42134184    {
     
    43304301}
    43314302
    4332 /* Return the first entry with the same str_idx, or REG_MISSING if none is
     4303/* Return the first entry with the same str_idx, or -1 if none is
    43334304   found.  Note that MCTX->BKREF_ENTS is already sorted by MCTX->STR_IDX.  */
    43344305
     
    43504321    return left;
    43514322  else
    4352     return REG_MISSING;
     4323    return -1;
    43534324}
    43544325
  • TabularUnified coreutils/trunk/lib/sched.in.h

    r1648 r1953  
    1 /* Replacement <sched.h> for platforms that lack it.
     1/* A GNU-like <sched.h>.
    22   Copyright (C) 2008-2016 Free Software Foundation, Inc.
    33
     
    2424/* The include_next requires a split double-inclusion guard.  */
    2525#if @HAVE_SCHED_H@
     26# if @HAVE_SYS_CDEFS_H@
     27#  include <sys/cdefs.h>
     28# endif
    2629# @INCLUDE_NEXT@ @NEXT_SCHED_H@
    2730#endif
  • TabularUnified coreutils/trunk/lib/secure_getenv.c

    r1648 r1953  
    1 /* Look up an environment variable more securely.
     1/* Look up an environment variable, returning NULL in insecure situations.
    22
    33   Copyright 2013-2016 Free Software Foundation, Inc.
     
    2121
    2222#if !HAVE___SECURE_GETENV
    23 # if HAVE_ISSETUGID
     23# if HAVE_ISSETUGID || (HAVE_GETUID && HAVE_GETEUID && HAVE_GETGID && HAVE_GETEGID)
    2424#  include <unistd.h>
    25 # else
    26 #  undef issetugid
    27 #  define issetugid() 1
    2825# endif
    2926#endif
     
    3229secure_getenv (char const *name)
    3330{
    34 #if HAVE___SECURE_GETENV
     31#if HAVE___SECURE_GETENV /* glibc */
    3532  return __secure_getenv (name);
     33#elif HAVE_ISSETUGID /* OS X, FreeBSD, NetBSD, OpenBSD */
     34  if (issetugid ())
     35    return NULL;
     36  return getenv (name);
     37#elif HAVE_GETUID && HAVE_GETEUID && HAVE_GETGID && HAVE_GETEGID /* other Unix */
     38  if (geteuid () != getuid () || getegid () != getgid ())
     39    return NULL;
     40  return getenv (name);
     41#elif (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__ /* native Windows */
     42  /* On native Windows, there is no such concept as setuid or setgid binaries.
     43     - Programs launched as system services have high privileges, but they don't
     44       inherit environment variables from a user.
     45     - Programs launched by a user with "Run as Administrator" have high
     46       privileges and use the environment variables, but the user has been asked
     47       whether he agrees.
     48     - Programs launched by a user without "Run as Administrator" cannot gain
     49       high privileges, therefore there is no risk. */
     50  return getenv (name);
    3651#else
    37   if (issetugid ())
    38     return 0;
    39   return getenv (name);
     52  return NULL;
    4053#endif
    4154}
  • TabularUnified coreutils/trunk/lib/set-permissions.c

    r1648 r1953  
    270270        return -1;
    271271      }
     272    return 0;
    272273  }
    273274}
  • TabularUnified coreutils/trunk/lib/stdalign.in.h

    r1648 r1953  
    104104         ? 4 < __GNUC__ + (1 <= __GNUC_MINOR__)                 \
    105105         : __GNUC__)                                            \
    106         || __HP_cc || __HP_aCC || __IBMC__ || __IBMCPP__        \
    107         || __ICC || 0x590 <= __SUNPRO_C)
     106        || 061200 <= __HP_cc || 061200 <= __HP_aCC                \
     107        || __ICC || 0x590 <= __SUNPRO_C || 0x0600 <= __xlC__)
    108108#  define _Alignas(a) __attribute__ ((__aligned__ (a)))
    109109# elif 1300 <= _MSC_VER
     
    112112#endif
    113113#if ((defined _Alignas && ! (defined __cplusplus && 201103 <= __cplusplus)) \
    114      || (defined __STDC_VERSION && 201112 <= __STDC_VERSION__))
     114     || (defined __STDC_VERSION__ && 201112 <= __STDC_VERSION__))
    115115# define alignas _Alignas
    116116#endif
  • TabularUnified coreutils/trunk/lib/stddef.in.h

    r1648 r1953  
    8282#endif
    8383
    84 /* Some platforms lack max_align_t.  */
    85 #if !@HAVE_MAX_ALIGN_T@
     84/* Some platforms lack max_align_t.  The check for _GCC_MAX_ALIGN_T is
     85   a hack in case the configure-time test was done with g++ even though
     86   we are currently compiling with gcc.  */
     87#if ! (@HAVE_MAX_ALIGN_T@ || defined _GCC_MAX_ALIGN_T)
    8688/* On the x86, the maximum storage alignment of double, long, etc. is 4,
    8789   but GCC's C11 ABI for x86 says that max_align_t has an alignment of 8,
  • TabularUnified coreutils/trunk/lib/stdint.in.h

    r1648 r1953  
    8080#define _@GUARD_PREFIX@_STDINT_H
    8181
     82/* Get SCHAR_MIN, SCHAR_MAX, UCHAR_MAX, INT_MIN, INT_MAX,
     83   LONG_MIN, LONG_MAX, ULONG_MAX, _GL_INTEGER_WIDTH.  */
     84#include <limits.h>
     85
     86#if ! @HAVE_C99_STDINT_H@
     87
    8288/* <sys/types.h> defines some of the stdint.h types as well, on glibc,
    8389   IRIX 6.5, and OpenBSD 3.8 (via <machine/types.h>).
     
    8692   relies on the system <stdint.h> definitions, so include
    8793   <sys/types.h> after @NEXT_STDINT_H@.  */
    88 #if @HAVE_SYS_TYPES_H@ && ! defined _AIX
    89 # include <sys/types.h>
    90 #endif
    91 
    92 /* Get SCHAR_MIN, SCHAR_MAX, UCHAR_MAX, INT_MIN, INT_MAX,
    93    LONG_MIN, LONG_MAX, ULONG_MAX.  */
    94 #include <limits.h>
    95 
    96 #if @HAVE_INTTYPES_H@
     94# if @HAVE_SYS_TYPES_H@ && ! defined _AIX
     95#  include <sys/types.h>
     96# endif
     97
     98# if @HAVE_INTTYPES_H@
    9799  /* In OpenBSD 3.8, <inttypes.h> includes <machine/types.h>, which defines
    98100     int{8,16,32,64}_t, uint{8,16,32,64}_t and __BIT_TYPES_DEFINED__.
    99101     <inttypes.h> also defines intptr_t and uintptr_t.  */
    100 # include <inttypes.h>
    101 #elif @HAVE_SYS_INTTYPES_H@
     102#  include <inttypes.h>
     103# elif @HAVE_SYS_INTTYPES_H@
    102104  /* Solaris 7 <sys/inttypes.h> has the types except the *_fast*_t types, and
    103105     the macros except for *_FAST*_*, INTPTR_MIN, PTRDIFF_MIN, PTRDIFF_MAX.  */
    104 # include <sys/inttypes.h>
    105 #endif
    106 
    107 #if @HAVE_SYS_BITYPES_H@ && ! defined __BIT_TYPES_DEFINED__
     106#  include <sys/inttypes.h>
     107# endif
     108
     109# if @HAVE_SYS_BITYPES_H@ && ! defined __BIT_TYPES_DEFINED__
    108110  /* Linux libc4 >= 4.6.7 and libc5 have a <sys/bitypes.h> that defines
    109111     int{8,16,32,64}_t and __BIT_TYPES_DEFINED__.  In libc5 >= 5.2.2 it is
    110112     included by <sys/types.h>.  */
    111 # include <sys/bitypes.h>
    112 #endif
    113 
    114 #undef _GL_JUST_INCLUDE_SYSTEM_INTTYPES_H
     113#  include <sys/bitypes.h>
     114# endif
     115
     116# undef _GL_JUST_INCLUDE_SYSTEM_INTTYPES_H
    115117
    116118/* Minimum and maximum values for an integer type under the usual assumption.
     
    118120   picky compilers.  */
    119121
    120 #define _STDINT_MIN(signed, bits, zero) \
    121   ((signed) ? (- ((zero) + 1) << ((bits) ? (bits) - 1 : 0)) : (zero))
    122 
    123 #define _STDINT_MAX(signed, bits, zero) \
    124   ((signed) \
    125    ? ~ _STDINT_MIN (signed, bits, zero) \
    126    : /* The expression for the unsigned case.  The subtraction of (signed) \
    127         is a nop in the unsigned case and avoids "signed integer overflow" \
    128         warnings in the signed case.  */ \
    129      ((((zero) + 1) << ((bits) ? (bits) - 1 - (signed) : 0)) - 1) * 2 + 1)
     122# define _STDINT_MIN(signed, bits, zero) \
     123    ((signed) ? ~ _STDINT_MAX (signed, bits, zero) : (zero))
     124
     125# define _STDINT_MAX(signed, bits, zero) \
     126    (((((zero) + 1) << ((bits) ? (bits) - 1 - (signed) : 0)) - 1) * 2 + 1)
    130127
    131128#if !GNULIB_defined_stdint_types
     
    136133   types have 8, 16, 32, optionally 64 bits.  */
    137134
    138 #undef int8_t
    139 #undef uint8_t
     135# undef int8_t
     136# undef uint8_t
    140137typedef signed char gl_int8_t;
    141138typedef unsigned char gl_uint8_t;
    142 #define int8_t gl_int8_t
    143 #define uint8_t gl_uint8_t
    144 
    145 #undef int16_t
    146 #undef uint16_t
     139# define int8_t gl_int8_t
     140# define uint8_t gl_uint8_t
     141
     142# undef int16_t
     143# undef uint16_t
    147144typedef short int gl_int16_t;
    148145typedef unsigned short int gl_uint16_t;
    149 #define int16_t gl_int16_t
    150 #define uint16_t gl_uint16_t
    151 
    152 #undef int32_t
    153 #undef uint32_t
     146# define int16_t gl_int16_t
     147# define uint16_t gl_uint16_t
     148
     149# undef int32_t
     150# undef uint32_t
    154151typedef int gl_int32_t;
    155152typedef unsigned int gl_uint32_t;
    156 #define int32_t gl_int32_t
    157 #define uint32_t gl_uint32_t
     153# define int32_t gl_int32_t
     154# define uint32_t gl_uint32_t
    158155
    159156/* If the system defines INT64_MAX, assume int64_t works.  That way,
     
    163160   rather than #if, to avoid an error with HP-UX 10.20 cc.  */
    164161
    165 #ifdef INT64_MAX
    166 # define GL_INT64_T
    167 #else
     162# ifdef INT64_MAX
     163#  define GL_INT64_T
     164# else
    168165/* Do not undefine int64_t if gnulib is not being used with 64-bit
    169166   types, since otherwise it breaks platforms like Tandem/NSK.  */
    170 # if LONG_MAX >> 31 >> 31 == 1
    171 undef int64_t
     167#  if LONG_MAX >> 31 >> 31 == 1
     168 undef int64_t
    172169typedef long int gl_int64_t;
    173 define int64_t gl_int64_t
    174 define GL_INT64_T
    175 # elif defined _MSC_VER
    176 undef int64_t
     170 define int64_t gl_int64_t
     171 define GL_INT64_T
     172#  elif defined _MSC_VER
     173 undef int64_t
    177174typedef __int64 gl_int64_t;
    178 define int64_t gl_int64_t
    179 define GL_INT64_T
    180 # elif @HAVE_LONG_LONG_INT@
    181 undef int64_t
     175 define int64_t gl_int64_t
     176 define GL_INT64_T
     177#  elif @HAVE_LONG_LONG_INT@
     178 undef int64_t
    182179typedef long long int gl_int64_t;
    183 define int64_t gl_int64_t
    184 define GL_INT64_T
    185 # endif
    186 #endif
    187 
    188 #ifdef UINT64_MAX
    189 # define GL_UINT64_T
    190 #else
    191 # if ULONG_MAX >> 31 >> 31 >> 1 == 1
    192 undef uint64_t
     180 define int64_t gl_int64_t
     181 define GL_INT64_T
     182#  endif
     183# endif
     184
     185# ifdef UINT64_MAX
     186#  define GL_UINT64_T
     187# else
     188#  if ULONG_MAX >> 31 >> 31 >> 1 == 1
     189 undef uint64_t
    193190typedef unsigned long int gl_uint64_t;
    194 define uint64_t gl_uint64_t
    195 define GL_UINT64_T
    196 # elif defined _MSC_VER
    197 undef uint64_t
     191 define uint64_t gl_uint64_t
     192 define GL_UINT64_T
     193#  elif defined _MSC_VER
     194 undef uint64_t
    198195typedef unsigned __int64 gl_uint64_t;
    199 define uint64_t gl_uint64_t
    200 define GL_UINT64_T
    201 # elif @HAVE_UNSIGNED_LONG_LONG_INT@
    202 undef uint64_t
     196 define uint64_t gl_uint64_t
     197 define GL_UINT64_T
     198#  elif @HAVE_UNSIGNED_LONG_LONG_INT@
     199 undef uint64_t
    203200typedef unsigned long long int gl_uint64_t;
    204 define uint64_t gl_uint64_t
    205 define GL_UINT64_T
    206 # endif
    207 #endif
     201 define uint64_t gl_uint64_t
     202 define GL_UINT64_T
     203#  endif
     204# endif
    208205
    209206/* Avoid collision with Solaris 2.5.1 <pthread.h> etc.  */
    210 #define _UINT8_T
    211 #define _UINT32_T
    212 #define _UINT64_T
     207# define _UINT8_T
     208# define _UINT32_T
     209# define _UINT64_T
    213210
    214211
     
    219216   are the same as the corresponding N_t types.  */
    220217
    221 #undef int_least8_t
    222 #undef uint_least8_t
    223 #undef int_least16_t
    224 #undef uint_least16_t
    225 #undef int_least32_t
    226 #undef uint_least32_t
    227 #undef int_least64_t
    228 #undef uint_least64_t
    229 #define int_least8_t int8_t
    230 #define uint_least8_t uint8_t
    231 #define int_least16_t int16_t
    232 #define uint_least16_t uint16_t
    233 #define int_least32_t int32_t
    234 #define uint_least32_t uint32_t
    235 #ifdef GL_INT64_T
    236 # define int_least64_t int64_t
    237 #endif
    238 #ifdef GL_UINT64_T
    239 # define uint_least64_t uint64_t
    240 #endif
     218# undef int_least8_t
     219# undef uint_least8_t
     220# undef int_least16_t
     221# undef uint_least16_t
     222# undef int_least32_t
     223# undef uint_least32_t
     224# undef int_least64_t
     225# undef uint_least64_t
     226# define int_least8_t int8_t
     227# define uint_least8_t uint8_t
     228# define int_least16_t int16_t
     229# define uint_least16_t uint16_t
     230# define int_least32_t int32_t
     231# define uint_least32_t uint32_t
     232# ifdef GL_INT64_T
     233#  define int_least64_t int64_t
     234# endif
     235# ifdef GL_UINT64_T
     236#  define uint_least64_t uint64_t
     237# endif
    241238
    242239/* 7.18.1.3. Fastest minimum-width integer types */
     
    251248   incompatibility with older GNU hosts.  */
    252249
    253 #undef int_fast8_t
    254 #undef uint_fast8_t
    255 #undef int_fast16_t
    256 #undef uint_fast16_t
    257 #undef int_fast32_t
    258 #undef uint_fast32_t
    259 #undef int_fast64_t
    260 #undef uint_fast64_t
     250# undef int_fast8_t
     251# undef uint_fast8_t
     252# undef int_fast16_t
     253# undef uint_fast16_t
     254# undef int_fast32_t
     255# undef uint_fast32_t
     256# undef int_fast64_t
     257# undef uint_fast64_t
    261258typedef signed char gl_int_fast8_t;
    262259typedef unsigned char gl_uint_fast8_t;
    263260
    264 #ifdef __sun
     261# ifdef __sun
    265262/* Define types compatible with SunOS 5.10, so that code compiled under
    266263   earlier SunOS versions works with code compiled under SunOS 5.10.  */
    267264typedef int gl_int_fast32_t;
    268265typedef unsigned int gl_uint_fast32_t;
    269 #else
     266# else
    270267typedef long int gl_int_fast32_t;
    271268typedef unsigned long int gl_uint_fast32_t;
    272 #endif
     269# endif
    273270typedef gl_int_fast32_t gl_int_fast16_t;
    274271typedef gl_uint_fast32_t gl_uint_fast16_t;
    275272
    276 #define int_fast8_t gl_int_fast8_t
    277 #define uint_fast8_t gl_uint_fast8_t
    278 #define int_fast16_t gl_int_fast16_t
    279 #define uint_fast16_t gl_uint_fast16_t
    280 #define int_fast32_t gl_int_fast32_t
    281 #define uint_fast32_t gl_uint_fast32_t
    282 #ifdef GL_INT64_T
    283 # define int_fast64_t int64_t
    284 #endif
    285 #ifdef GL_UINT64_T
    286 # define uint_fast64_t uint64_t
    287 #endif
     273# define int_fast8_t gl_int_fast8_t
     274# define uint_fast8_t gl_uint_fast8_t
     275# define int_fast16_t gl_int_fast16_t
     276# define uint_fast16_t gl_uint_fast16_t
     277# define int_fast32_t gl_int_fast32_t
     278# define uint_fast32_t gl_uint_fast32_t
     279# ifdef GL_INT64_T
     280#  define int_fast64_t int64_t
     281# endif
     282# ifdef GL_UINT64_T
     283#  define uint_fast64_t uint64_t
     284# endif
    288285
    289286/* 7.18.1.4. Integer types capable of holding object pointers */
     
    292289   definitions of intptr_t and uintptr_t (which use int and unsigned)
    293290   to avoid clashes with declarations of system functions like sbrk.  */
    294 #ifndef _INTPTR_T_DECLARED
    295 #undef intptr_t
    296 #undef uintptr_t
     291# ifndef _INTPTR_T_DECLARED
     292# undef intptr_t
     293# undef uintptr_t
    297294typedef long int gl_intptr_t;
    298295typedef unsigned long int gl_uintptr_t;
    299 #define intptr_t gl_intptr_t
    300 #define uintptr_t gl_uintptr_t
    301 #endif
     296# define intptr_t gl_intptr_t
     297# define uintptr_t gl_uintptr_t
     298# endif
    302299
    303300/* 7.18.1.5. Greatest-width integer types */
     
    310307   assuming one type where another is used by the system.  */
    311308
    312 #ifndef INTMAX_MAX
    313 # undef INTMAX_C
    314 # undef intmax_t
    315 # if @HAVE_LONG_LONG_INT@ && LONG_MAX >> 30 == 1
     309# ifndef INTMAX_MAX
     310#  undef INTMAX_C
     311#  undef intmax_t
     312#  if @HAVE_LONG_LONG_INT@ && LONG_MAX >> 30 == 1
    316313typedef long long int gl_intmax_t;
    317 define intmax_t gl_intmax_t
    318 # elif defined GL_INT64_T
    319 define intmax_t int64_t
    320 # else
     314 define intmax_t gl_intmax_t
     315#  elif defined GL_INT64_T
     316 define intmax_t int64_t
     317#  else
    321318typedef long int gl_intmax_t;
    322 define intmax_t gl_intmax_t
    323 # endif
    324 #endif
    325 
    326 #ifndef UINTMAX_MAX
    327 # undef UINTMAX_C
    328 # undef uintmax_t
    329 # if @HAVE_UNSIGNED_LONG_LONG_INT@ && ULONG_MAX >> 31 == 1
     319 define intmax_t gl_intmax_t
     320#  endif
     321# endif
     322
     323# ifndef UINTMAX_MAX
     324#  undef UINTMAX_C
     325#  undef uintmax_t
     326#  if @HAVE_UNSIGNED_LONG_LONG_INT@ && ULONG_MAX >> 31 == 1
    330327typedef unsigned long long int gl_uintmax_t;
    331 define uintmax_t gl_uintmax_t
    332 # elif defined GL_UINT64_T
    333 define uintmax_t uint64_t
    334 # else
     328 define uintmax_t gl_uintmax_t
     329#  elif defined GL_UINT64_T
     330 define uintmax_t uint64_t
     331#  else
    335332typedef unsigned long int gl_uintmax_t;
    336 define uintmax_t gl_uintmax_t
    337 # endif
    338 #endif
     333 define uintmax_t gl_uintmax_t
     334#  endif
     335# endif
    339336
    340337/* Verify that intmax_t and uintmax_t have the same size.  Too much code
     
    344341                                ? 1 : -1];
    345342
    346 #define GNULIB_defined_stdint_types 1
    347 #endif /* !GNULIB_defined_stdint_types */
     343# define GNULIB_defined_stdint_types 1
     344# endif /* !GNULIB_defined_stdint_types */
    348345
    349346/* 7.18.2. Limits of specified-width integer types */
     
    354351   types have 8, 16, 32, optionally 64 bits.  */
    355352
    356 #undef INT8_MIN
    357 #undef INT8_MAX
    358 #undef UINT8_MAX
    359 #define INT8_MIN  (~ INT8_MAX)
    360 #define INT8_MAX  127
    361 #define UINT8_MAX  255
    362 
    363 #undef INT16_MIN
    364 #undef INT16_MAX
    365 #undef UINT16_MAX
    366 #define INT16_MIN  (~ INT16_MAX)
    367 #define INT16_MAX  32767
    368 #define UINT16_MAX  65535
    369 
    370 #undef INT32_MIN
    371 #undef INT32_MAX
    372 #undef UINT32_MAX
    373 #define INT32_MIN  (~ INT32_MAX)
    374 #define INT32_MAX  2147483647
    375 #define UINT32_MAX  4294967295U
    376 
    377 #if defined GL_INT64_T && ! defined INT64_MAX
     353# undef INT8_MIN
     354# undef INT8_MAX
     355# undef UINT8_MAX
     356# define INT8_MIN  (~ INT8_MAX)
     357# define INT8_MAX  127
     358# define UINT8_MAX  255
     359
     360# undef INT16_MIN
     361# undef INT16_MAX
     362# undef UINT16_MAX
     363# define INT16_MIN  (~ INT16_MAX)
     364# define INT16_MAX  32767
     365# define UINT16_MAX  65535
     366
     367# undef INT32_MIN
     368# undef INT32_MAX
     369# undef UINT32_MAX
     370# define INT32_MIN  (~ INT32_MAX)
     371# define INT32_MAX  2147483647
     372# define UINT32_MAX  4294967295U
     373
     374# if defined GL_INT64_T && ! defined INT64_MAX
    378375/* Prefer (- INTMAX_C (1) << 63) over (~ INT64_MAX) because SunPRO C 5.0
    379376   evaluates the latter incorrectly in preprocessor expressions.  */
    380 # define INT64_MIN  (- INTMAX_C (1) << 63)
    381 # define INT64_MAX  INTMAX_C (9223372036854775807)
    382 #endif
    383 
    384 #if defined GL_UINT64_T && ! defined UINT64_MAX
    385 # define UINT64_MAX  UINTMAX_C (18446744073709551615)
    386 #endif
     377#  define INT64_MIN  (- INTMAX_C (1) << 63)
     378#  define INT64_MAX  INTMAX_C (9223372036854775807)
     379# endif
     380
     381# if defined GL_UINT64_T && ! defined UINT64_MAX
     382#  define UINT64_MAX  UINTMAX_C (18446744073709551615)
     383# endif
    387384
    388385/* 7.18.2.2. Limits of minimum-width integer types */
     
    392389   are the same as the corresponding N_t types.  */
    393390
    394 #undef INT_LEAST8_MIN
    395 #undef INT_LEAST8_MAX
    396 #undef UINT_LEAST8_MAX
    397 #define INT_LEAST8_MIN  INT8_MIN
    398 #define INT_LEAST8_MAX  INT8_MAX
    399 #define UINT_LEAST8_MAX  UINT8_MAX
    400 
    401 #undef INT_LEAST16_MIN
    402 #undef INT_LEAST16_MAX
    403 #undef UINT_LEAST16_MAX
    404 #define INT_LEAST16_MIN  INT16_MIN
    405 #define INT_LEAST16_MAX  INT16_MAX
    406 #define UINT_LEAST16_MAX  UINT16_MAX
    407 
    408 #undef INT_LEAST32_MIN
    409 #undef INT_LEAST32_MAX
    410 #undef UINT_LEAST32_MAX
    411 #define INT_LEAST32_MIN  INT32_MIN
    412 #define INT_LEAST32_MAX  INT32_MAX
    413 #define UINT_LEAST32_MAX  UINT32_MAX
    414 
    415 #undef INT_LEAST64_MIN
    416 #undef INT_LEAST64_MAX
    417 #ifdef GL_INT64_T
    418 # define INT_LEAST64_MIN  INT64_MIN
    419 # define INT_LEAST64_MAX  INT64_MAX
    420 #endif
    421 
    422 #undef UINT_LEAST64_MAX
    423 #ifdef GL_UINT64_T
    424 # define UINT_LEAST64_MAX  UINT64_MAX
    425 #endif
     391# undef INT_LEAST8_MIN
     392# undef INT_LEAST8_MAX
     393# undef UINT_LEAST8_MAX
     394# define INT_LEAST8_MIN  INT8_MIN
     395# define INT_LEAST8_MAX  INT8_MAX
     396# define UINT_LEAST8_MAX  UINT8_MAX
     397
     398# undef INT_LEAST16_MIN
     399# undef INT_LEAST16_MAX
     400# undef UINT_LEAST16_MAX
     401# define INT_LEAST16_MIN  INT16_MIN
     402# define INT_LEAST16_MAX  INT16_MAX
     403# define UINT_LEAST16_MAX  UINT16_MAX
     404
     405# undef INT_LEAST32_MIN
     406# undef INT_LEAST32_MAX
     407# undef UINT_LEAST32_MAX
     408# define INT_LEAST32_MIN  INT32_MIN
     409# define INT_LEAST32_MAX  INT32_MAX
     410# define UINT_LEAST32_MAX  UINT32_MAX
     411
     412# undef INT_LEAST64_MIN
     413# undef INT_LEAST64_MAX
     414# ifdef GL_INT64_T
     415#  define INT_LEAST64_MIN  INT64_MIN
     416#  define INT_LEAST64_MAX  INT64_MAX
     417# endif
     418
     419# undef UINT_LEAST64_MAX
     420# ifdef GL_UINT64_T
     421#  define UINT_LEAST64_MAX  UINT64_MAX
     422# endif
    426423
    427424/* 7.18.2.3. Limits of fastest minimum-width integer types */
     
    431428   are taken from the same list of types.  */
    432429
    433 #undef INT_FAST8_MIN
    434 #undef INT_FAST8_MAX
    435 #undef UINT_FAST8_MAX
    436 #define INT_FAST8_MIN  SCHAR_MIN
    437 #define INT_FAST8_MAX  SCHAR_MAX
    438 #define UINT_FAST8_MAX  UCHAR_MAX
    439 
    440 #undef INT_FAST16_MIN
    441 #undef INT_FAST16_MAX
    442 #undef UINT_FAST16_MAX
    443 #define INT_FAST16_MIN  INT_FAST32_MIN
    444 #define INT_FAST16_MAX  INT_FAST32_MAX
    445 #define UINT_FAST16_MAX  UINT_FAST32_MAX
    446 
    447 #undef INT_FAST32_MIN
    448 #undef INT_FAST32_MAX
    449 #undef UINT_FAST32_MAX
    450 #ifdef __sun
    451 # define INT_FAST32_MIN  INT_MIN
    452 # define INT_FAST32_MAX  INT_MAX
    453 # define UINT_FAST32_MAX  UINT_MAX
    454 #else
    455 # define INT_FAST32_MIN  LONG_MIN
    456 # define INT_FAST32_MAX  LONG_MAX
    457 # define UINT_FAST32_MAX  ULONG_MAX
    458 #endif
    459 
    460 #undef INT_FAST64_MIN
    461 #undef INT_FAST64_MAX
    462 #ifdef GL_INT64_T
    463 # define INT_FAST64_MIN  INT64_MIN
    464 # define INT_FAST64_MAX  INT64_MAX
    465 #endif
    466 
    467 #undef UINT_FAST64_MAX
    468 #ifdef GL_UINT64_T
    469 # define UINT_FAST64_MAX  UINT64_MAX
    470 #endif
     430# undef INT_FAST8_MIN
     431# undef INT_FAST8_MAX
     432# undef UINT_FAST8_MAX
     433# define INT_FAST8_MIN  SCHAR_MIN
     434# define INT_FAST8_MAX  SCHAR_MAX
     435# define UINT_FAST8_MAX  UCHAR_MAX
     436
     437# undef INT_FAST16_MIN
     438# undef INT_FAST16_MAX
     439# undef UINT_FAST16_MAX
     440# define INT_FAST16_MIN  INT_FAST32_MIN
     441# define INT_FAST16_MAX  INT_FAST32_MAX
     442# define UINT_FAST16_MAX  UINT_FAST32_MAX
     443
     444# undef INT_FAST32_MIN
     445# undef INT_FAST32_MAX
     446# undef UINT_FAST32_MAX
     447# ifdef __sun
     448#  define INT_FAST32_MIN  INT_MIN
     449#  define INT_FAST32_MAX  INT_MAX
     450#  define UINT_FAST32_MAX  UINT_MAX
     451# else
     452#  define INT_FAST32_MIN  LONG_MIN
     453#  define INT_FAST32_MAX  LONG_MAX
     454#  define UINT_FAST32_MAX  ULONG_MAX
     455# endif
     456
     457# undef INT_FAST64_MIN
     458# undef INT_FAST64_MAX
     459# ifdef GL_INT64_T
     460#  define INT_FAST64_MIN  INT64_MIN
     461#  define INT_FAST64_MAX  INT64_MAX
     462# endif
     463
     464# undef UINT_FAST64_MAX
     465# ifdef GL_UINT64_T
     466#  define UINT_FAST64_MAX  UINT64_MAX
     467# endif
    471468
    472469/* 7.18.2.4. Limits of integer types capable of holding object pointers */
    473470
    474 #undef INTPTR_MIN
    475 #undef INTPTR_MAX
    476 #undef UINTPTR_MAX
    477 #define INTPTR_MIN  LONG_MIN
    478 #define INTPTR_MAX  LONG_MAX
    479 #define UINTPTR_MAX  ULONG_MAX
     471# undef INTPTR_MIN
     472# undef INTPTR_MAX
     473# undef UINTPTR_MAX
     474# define INTPTR_MIN  LONG_MIN
     475# define INTPTR_MAX  LONG_MAX
     476# define UINTPTR_MAX  ULONG_MAX
    480477
    481478/* 7.18.2.5. Limits of greatest-width integer types */
    482479
    483 #ifndef INTMAX_MAX
    484 # undef INTMAX_MIN
    485 # ifdef INT64_MAX
    486 #  define INTMAX_MIN  INT64_MIN
    487 #  define INTMAX_MAX  INT64_MAX
     480# ifndef INTMAX_MAX
     481#  undef INTMAX_MIN
     482#  ifdef INT64_MAX
     483#   define INTMAX_MIN  INT64_MIN
     484#   define INTMAX_MAX  INT64_MAX
     485#  else
     486#   define INTMAX_MIN  INT32_MIN
     487#   define INTMAX_MAX  INT32_MAX
     488#  endif
     489# endif
     490
     491# ifndef UINTMAX_MAX
     492#  ifdef UINT64_MAX
     493#   define UINTMAX_MAX  UINT64_MAX
     494#  else
     495#   define UINTMAX_MAX  UINT32_MAX
     496#  endif
     497# endif
     498
     499/* 7.18.3. Limits of other integer types */
     500
     501/* ptrdiff_t limits */
     502# undef PTRDIFF_MIN
     503# undef PTRDIFF_MAX
     504# if @APPLE_UNIVERSAL_BUILD@
     505#  ifdef _LP64
     506#   define PTRDIFF_MIN  _STDINT_MIN (1, 64, 0l)
     507#   define PTRDIFF_MAX  _STDINT_MAX (1, 64, 0l)
     508#  else
     509#   define PTRDIFF_MIN  _STDINT_MIN (1, 32, 0)
     510#   define PTRDIFF_MAX  _STDINT_MAX (1, 32, 0)
     511#  endif
    488512# else
    489 #  define INTMAX_MIN  INT32_MIN
    490 #  define INTMAX_MAX  INT32_MAX
    491 # endif
    492 #endif
    493 
    494 #ifndef UINTMAX_MAX
    495 # ifdef UINT64_MAX
    496 #  define UINTMAX_MAX  UINT64_MAX
    497 # else
    498 #  define UINTMAX_MAX  UINT32_MAX
    499 # endif
    500 #endif
    501 
    502 /* 7.18.3. Limits of other integer types */
    503 
    504 /* ptrdiff_t limits */
    505 #undef PTRDIFF_MIN
    506 #undef PTRDIFF_MAX
    507 #if @APPLE_UNIVERSAL_BUILD@
    508 # ifdef _LP64
    509 #  define PTRDIFF_MIN  _STDINT_MIN (1, 64, 0l)
    510 #  define PTRDIFF_MAX  _STDINT_MAX (1, 64, 0l)
    511 # else
    512 #  define PTRDIFF_MIN  _STDINT_MIN (1, 32, 0)
    513 #  define PTRDIFF_MAX  _STDINT_MAX (1, 32, 0)
    514 # endif
    515 #else
    516 # define PTRDIFF_MIN  \
     513#  define PTRDIFF_MIN  \
    517514    _STDINT_MIN (1, @BITSIZEOF_PTRDIFF_T@, 0@PTRDIFF_T_SUFFIX@)
    518 # define PTRDIFF_MAX  \
     515#  define PTRDIFF_MAX  \
    519516    _STDINT_MAX (1, @BITSIZEOF_PTRDIFF_T@, 0@PTRDIFF_T_SUFFIX@)
    520 #endif
     517# endif
    521518
    522519/* sig_atomic_t limits */
    523 #undef SIG_ATOMIC_MIN
    524 #undef SIG_ATOMIC_MAX
    525 #define SIG_ATOMIC_MIN  \
     520# undef SIG_ATOMIC_MIN
     521# undef SIG_ATOMIC_MAX
     522# define SIG_ATOMIC_MIN  \
    526523   _STDINT_MIN (@HAVE_SIGNED_SIG_ATOMIC_T@, @BITSIZEOF_SIG_ATOMIC_T@, \
    527524                0@SIG_ATOMIC_T_SUFFIX@)
    528 #define SIG_ATOMIC_MAX  \
     525# define SIG_ATOMIC_MAX  \
    529526   _STDINT_MAX (@HAVE_SIGNED_SIG_ATOMIC_T@, @BITSIZEOF_SIG_ATOMIC_T@, \
    530527                0@SIG_ATOMIC_T_SUFFIX@)
     
    532529
    533530/* size_t limit */
    534 #undef SIZE_MAX
    535 #if @APPLE_UNIVERSAL_BUILD@
    536 # ifdef _LP64
    537 #  define SIZE_MAX  _STDINT_MAX (0, 64, 0ul)
     531# undef SIZE_MAX
     532# if @APPLE_UNIVERSAL_BUILD@
     533#  ifdef _LP64
     534#   define SIZE_MAX  _STDINT_MAX (0, 64, 0ul)
     535#  else
     536#   define SIZE_MAX  _STDINT_MAX (0, 32, 0ul)
     537#  endif
    538538# else
    539 #  define SIZE_MAX  _STDINT_MAX (0, 32, 0ul)
    540 # endif
    541 #else
    542 # define SIZE_MAX  _STDINT_MAX (0, @BITSIZEOF_SIZE_T@, 0@SIZE_T_SUFFIX@)
    543 #endif
     539#  define SIZE_MAX  _STDINT_MAX (0, @BITSIZEOF_SIZE_T@, 0@SIZE_T_SUFFIX@)
     540# endif
    544541
    545542/* wchar_t limits */
     
    549546   <wchar.h> -> <stdio.h> -> <getopt.h> -> <stdlib.h>, and the latter includes
    550547   <stdint.h> and assumes its types are already defined.  */
    551 #if @HAVE_WCHAR_H@ && ! (defined WCHAR_MIN && defined WCHAR_MAX)
     548# if @HAVE_WCHAR_H@ && ! (defined WCHAR_MIN && defined WCHAR_MAX)
    552549  /* BSD/OS 4.0.1 has a bug: <stddef.h>, <stdio.h> and <time.h> must be
    553550     included before <wchar.h>.  */
    554 # include <stddef.h>
    555 # include <stdio.h>
    556 # include <time.h>
    557 # define _GL_JUST_INCLUDE_SYSTEM_WCHAR_H
    558 # include <wchar.h>
    559 # undef _GL_JUST_INCLUDE_SYSTEM_WCHAR_H
    560 #endif
    561 #undef WCHAR_MIN
    562 #undef WCHAR_MAX
    563 #define WCHAR_MIN  \
     551#  include <stddef.h>
     552#  include <stdio.h>
     553#  include <time.h>
     554#  define _GL_JUST_INCLUDE_SYSTEM_WCHAR_H
     555#  include <wchar.h>
     556#  undef _GL_JUST_INCLUDE_SYSTEM_WCHAR_H
     557# endif
     558# undef WCHAR_MIN
     559# undef WCHAR_MAX
     560# define WCHAR_MIN  \
    564561   _STDINT_MIN (@HAVE_SIGNED_WCHAR_T@, @BITSIZEOF_WCHAR_T@, 0@WCHAR_T_SUFFIX@)
    565 #define WCHAR_MAX  \
     562# define WCHAR_MAX  \
    566563   _STDINT_MAX (@HAVE_SIGNED_WCHAR_T@, @BITSIZEOF_WCHAR_T@, 0@WCHAR_T_SUFFIX@)
    567564
    568565/* wint_t limits */
    569 #undef WINT_MIN
    570 #undef WINT_MAX
    571 #define WINT_MIN  \
     566# undef WINT_MIN
     567# undef WINT_MAX
     568# define WINT_MIN  \
    572569   _STDINT_MIN (@HAVE_SIGNED_WINT_T@, @BITSIZEOF_WINT_T@, 0@WINT_T_SUFFIX@)
    573 #define WINT_MAX  \
     570# define WINT_MAX  \
    574571   _STDINT_MAX (@HAVE_SIGNED_WINT_T@, @BITSIZEOF_WINT_T@, 0@WINT_T_SUFFIX@)
    575572
     
    582579   types have 8, 16, 32, optionally 64 bits, and int is 32 bits.  */
    583580
    584 #undef INT8_C
    585 #undef UINT8_C
    586 #define INT8_C(x) x
    587 #define UINT8_C(x) x
    588 
    589 #undef INT16_C
    590 #undef UINT16_C
    591 #define INT16_C(x) x
    592 #define UINT16_C(x) x
    593 
    594 #undef INT32_C
    595 #undef UINT32_C
    596 #define INT32_C(x) x
    597 #define UINT32_C(x) x ## U
    598 
    599 #undef INT64_C
    600 #undef UINT64_C
    601 #if LONG_MAX >> 31 >> 31 == 1
    602 # define INT64_C(x) x##L
    603 #elif defined _MSC_VER
    604 # define INT64_C(x) x##i64
    605 #elif @HAVE_LONG_LONG_INT@
    606 # define INT64_C(x) x##LL
    607 #endif
    608 #if ULONG_MAX >> 31 >> 31 >> 1 == 1
    609 # define UINT64_C(x) x##UL
    610 #elif defined _MSC_VER
    611 # define UINT64_C(x) x##ui64
    612 #elif @HAVE_UNSIGNED_LONG_LONG_INT@
    613 # define UINT64_C(x) x##ULL
    614 #endif
     581# undef INT8_C
     582# undef UINT8_C
     583# define INT8_C(x) x
     584# define UINT8_C(x) x
     585
     586# undef INT16_C
     587# undef UINT16_C
     588# define INT16_C(x) x
     589# define UINT16_C(x) x
     590
     591# undef INT32_C
     592# undef UINT32_C
     593# define INT32_C(x) x
     594# define UINT32_C(x) x ## U
     595
     596# undef INT64_C
     597# undef UINT64_C
     598# if LONG_MAX >> 31 >> 31 == 1
     599#  define INT64_C(x) x##L
     600# elif defined _MSC_VER
     601#  define INT64_C(x) x##i64
     602# elif @HAVE_LONG_LONG_INT@
     603#  define INT64_C(x) x##LL
     604# endif
     605# if ULONG_MAX >> 31 >> 31 >> 1 == 1
     606#  define UINT64_C(x) x##UL
     607# elif defined _MSC_VER
     608#  define UINT64_C(x) x##ui64
     609# elif @HAVE_UNSIGNED_LONG_LONG_INT@
     610#  define UINT64_C(x) x##ULL
     611# endif
    615612
    616613/* 7.18.4.2. Macros for greatest-width integer constants */
    617614
    618 #ifndef INTMAX_C
    619 # if @HAVE_LONG_LONG_INT@ && LONG_MAX >> 30 == 1
    620 #  define INTMAX_C(x)   x##LL
    621 # elif defined GL_INT64_T
    622 #  define INTMAX_C(x)   INT64_C(x)
    623 # else
    624 #  define INTMAX_C(x)   x##L
    625 # endif
    626 #endif
    627 
    628 #ifndef UINTMAX_C
    629 # if @HAVE_UNSIGNED_LONG_LONG_INT@ && ULONG_MAX >> 31 == 1
    630 #  define UINTMAX_C(x)  x##ULL
    631 # elif defined GL_UINT64_T
    632 #  define UINTMAX_C(x)  UINT64_C(x)
    633 # else
    634 #  define UINTMAX_C(x)  x##UL
    635 # endif
    636 #endif
     615# ifndef INTMAX_C
     616#  if @HAVE_LONG_LONG_INT@ && LONG_MAX >> 30 == 1
     617#   define INTMAX_C(x)   x##LL
     618#  elif defined GL_INT64_T
     619#   define INTMAX_C(x)   INT64_C(x)
     620#  else
     621#   define INTMAX_C(x)   x##L
     622#  endif
     623# endif
     624
     625# ifndef UINTMAX_C
     626#  if @HAVE_UNSIGNED_LONG_LONG_INT@ && ULONG_MAX >> 31 == 1
     627#   define UINTMAX_C(x)  x##ULL
     628#  elif defined GL_UINT64_T
     629#   define UINTMAX_C(x)  UINT64_C(x)
     630#  else
     631#   define UINTMAX_C(x)  x##UL
     632#  endif
     633# endif
     634
     635#endif /* !@HAVE_C99_STDINT_H@ */
     636
     637/* Macros specified by ISO/IEC TS 18661-1:2014.  */
     638
     639#if (!defined UINTMAX_WIDTH \
     640     && (defined _GNU_SOURCE || defined __STDC_WANT_IEC_60559_BFP_EXT__))
     641# ifdef INT8_MAX
     642#  define INT8_WIDTH _GL_INTEGER_WIDTH (INT8_MIN, INT8_MAX)
     643# endif
     644# ifdef UINT8_MAX
     645#  define UINT8_WIDTH _GL_INTEGER_WIDTH (0, UINT8_MAX)
     646# endif
     647# ifdef INT16_MAX
     648#  define INT16_WIDTH _GL_INTEGER_WIDTH (INT16_MIN, INT16_MAX)
     649# endif
     650# ifdef UINT16_MAX
     651#  define UINT16_WIDTH _GL_INTEGER_WIDTH (0, UINT16_MAX)
     652# endif
     653# ifdef INT32_MAX
     654#  define INT32_WIDTH _GL_INTEGER_WIDTH (INT32_MIN, INT32_MAX)
     655# endif
     656# ifdef UINT32_MAX
     657#  define UINT32_WIDTH _GL_INTEGER_WIDTH (0, UINT32_MAX)
     658# endif
     659# ifdef INT64_MAX
     660#  define INT64_WIDTH _GL_INTEGER_WIDTH (INT64_MIN, INT64_MAX)
     661# endif
     662# ifdef UINT64_MAX
     663#  define UINT64_WIDTH _GL_INTEGER_WIDTH (0, UINT64_MAX)
     664# endif
     665# define INT_LEAST8_WIDTH _GL_INTEGER_WIDTH (INT_LEAST8_MIN, INT_LEAST8_MAX)
     666# define UINT_LEAST8_WIDTH _GL_INTEGER_WIDTH (0, UINT_LEAST8_MAX)
     667# define INT_LEAST16_WIDTH _GL_INTEGER_WIDTH (INT_LEAST16_MIN, INT_LEAST16_MAX)
     668# define UINT_LEAST16_WIDTH _GL_INTEGER_WIDTH (0, UINT_LEAST16_MAX)
     669# define INT_LEAST32_WIDTH _GL_INTEGER_WIDTH (INT_LEAST32_MIN, INT_LEAST32_MAX)
     670# define UINT_LEAST32_WIDTH _GL_INTEGER_WIDTH (0, UINT_LEAST32_MAX)
     671# define INT_LEAST64_WIDTH _GL_INTEGER_WIDTH (INT_LEAST64_MIN, INT_LEAST64_MAX)
     672# define UINT_LEAST64_WIDTH _GL_INTEGER_WIDTH (0, UINT_LEAST64_MAX)
     673# define INT_FAST8_WIDTH _GL_INTEGER_WIDTH (INT_FAST8_MIN, INT_FAST8_MAX)
     674# define UINT_FAST8_WIDTH _GL_INTEGER_WIDTH (0, UINT_FAST8_MAX)
     675# define INT_FAST16_WIDTH _GL_INTEGER_WIDTH (INT_FAST16_MIN, INT_FAST16_MAX)
     676# define UINT_FAST16_WIDTH _GL_INTEGER_WIDTH (0, UINT_FAST16_MAX)
     677# define INT_FAST32_WIDTH _GL_INTEGER_WIDTH (INT_FAST32_MIN, INT_FAST32_MAX)
     678# define UINT_FAST32_WIDTH _GL_INTEGER_WIDTH (0, UINT_FAST32_MAX)
     679# define INT_FAST64_WIDTH _GL_INTEGER_WIDTH (INT_FAST64_MIN, INT_FAST64_MAX)
     680# define UINT_FAST64_WIDTH _GL_INTEGER_WIDTH (0, UINT_FAST64_MAX)
     681# define INTPTR_WIDTH _GL_INTEGER_WIDTH (INTPTR_MIN, INTPTR_MAX)
     682# define UINTPTR_WIDTH _GL_INTEGER_WIDTH (0, UINTPTR_MAX)
     683# define INTMAX_WIDTH _GL_INTEGER_WIDTH (INTMAX_MIN, INTMAX_MAX)
     684# define UINTMAX_WIDTH _GL_INTEGER_WIDTH (0, UINTMAX_MAX)
     685# define PTRDIFF_WIDTH _GL_INTEGER_WIDTH (PTRDIFF_MIN, PTRDIFF_MAX)
     686# define SIZE_WIDTH _GL_INTEGER_WIDTH (0, SIZE_MAX)
     687# define WCHAR_WIDTH _GL_INTEGER_WIDTH (WCHAR_MIN, WCHAR_MAX)
     688# ifdef WINT_MAX
     689#  define WINT_WIDTH _GL_INTEGER_WIDTH (WINT_MIN, WINT_MAX)
     690# endif
     691# ifdef SIG_ATOMIC_MAX
     692#  define SIG_ATOMIC_WIDTH _GL_INTEGER_WIDTH (SIG_ATOMIC_MIN, SIG_ATOMIC_MAX)
     693# endif
     694#endif /* !WINT_WIDTH && (_GNU_SOURCE || __STDC_WANT_IEC_60559_BFP_EXT__) */
    637695
    638696#endif /* _@GUARD_PREFIX@_STDINT_H */
  • TabularUnified coreutils/trunk/lib/stdlib.in.h

    r1648 r1953  
    522522
    523523#if @GNULIB_QSORT_R@
     524/* Sort an array of NMEMB elements, starting at address BASE, each element
     525   occupying SIZE bytes, in ascending order according to the comparison
     526   function COMPARE.  */
    524527# if @REPLACE_QSORT_R@
    525528#  if !(defined __cplusplus && defined GNULIB_NAMESPACE)
     
    536539                                  void *arg));
    537540# else
     541#  if !@HAVE_QSORT_R@
     542_GL_FUNCDECL_SYS (qsort_r, void, (void *base, size_t nmemb, size_t size,
     543                                  int (*compare) (void const *, void const *,
     544                                                  void *),
     545                                  void *arg) _GL_ARG_NONNULL ((1, 4)));
     546#  endif
    538547_GL_CXXALIAS_SYS (qsort_r, void, (void *base, size_t nmemb, size_t size,
    539548                                  int (*compare) (void const *, void const *,
     
    542551# endif
    543552_GL_CXXALIASWARN (qsort_r);
     553#elif defined GNULIB_POSIXCHECK
     554# undef qsort_r
     555# if HAVE_RAW_DECL_QSORT_R
     556_GL_WARN_ON_USE (qsort_r, "qsort_r is not portable - "
     557                 "use gnulib module qsort_r for portability");
     558# endif
    544559#endif
    545560
  • TabularUnified coreutils/trunk/lib/strerror.c

    r1648 r1953  
    6767    abort ();
    6868
    69   return memcpy (buf, msg, len + 1);
     69  memcpy (buf, msg, len + 1);
     70  return buf;
    7071}
  • TabularUnified coreutils/trunk/lib/strftime.c

    r1648 r1953  
    1 /* Copyright (C) 1991-2001, 2003-2007, 2009-2016 Free Software Foundation, Inc.
    2 
    3    NOTE: The canonical source of this file is maintained with the GNU C Library.
    4    Bugs can be reported to bug-glibc@prep.ai.mit.edu.
    5 
    6    This program is free software: you can redistribute it and/or modify
    7    it under the terms of the GNU General Public License as published by
    8    the Free Software Foundation; either version 3 of the License, or
    9    (at your option) any later version.
    10 
    11    This program is distributed in the hope that it will be useful,
     1/* Copyright (C) 1991-2016 Free Software Foundation, Inc.
     2   This file is part of the GNU C Library.
     3
     4   The GNU C Library is free software; you can redistribute it and/or
     5   modify it under the terms of the GNU General Public
     6   License as published by the Free Software Foundation; either
     7   version 3 of the License, or (at your option) any later version.
     8
     9   The GNU C Library is distributed in the hope that it will be useful,
    1210   but WITHOUT ANY WARRANTY; without even the implied warranty of
    13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    14    GNU General Public License for more details.
    15 
    16    You should have received a copy of the GNU General Public License
    17    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
     11   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     12   General Public License for more details.
     13
     14   You should have received a copy of the GNU General Public
     15   License along with the GNU C Library; if not, see
     16   <http://www.gnu.org/licenses/>.  */
    1817
    1918#ifdef _LIBC
     19# define USE_IN_EXTENDED_LOCALE_MODEL 1
    2020# define HAVE_STRUCT_ERA_ENTRY 1
    2121# define HAVE_TM_GMTOFF 1
     
    6464
    6565#include <limits.h>
    66 #include <stdbool.h>
    6766#include <stddef.h>
    6867#include <stdlib.h>
    6968#include <string.h>
     69#include <stdbool.h>
    7070
    7171#ifdef COMPILE_WIDE
     
    248248# define _NL_CURRENT(category, item) \
    249249  (current->values[_NL_ITEM_INDEX (item)].string)
     250# define LOCALE_PARAM , __locale_t loc
    250251# define LOCALE_ARG , loc
    251 # define LOCALE_PARAM_PROTO , __locale_t loc
    252252# define HELPER_LOCALE_ARG  , current
    253253#else
    254 # define LOCALE_PARAM_PROTO
     254# define LOCALE_PARAM
    255255# define LOCALE_ARG
    256256# ifdef _LIBC
     
    305305}
    306306#else
     307static CHAR_T *memcpy_lowcase (CHAR_T *dest, const CHAR_T *src,
     308                               size_t len LOCALE_PARAM);
     309
    307310static CHAR_T *
    308 memcpy_lowcase (CHAR_T *dest, const CHAR_T *src,
    309                 size_t len LOCALE_PARAM_PROTO)
     311memcpy_lowcase (CHAR_T *dest, const CHAR_T *src, size_t len LOCALE_PARAM)
    310312{
    311313  while (len-- > 0)
     
    314316}
    315317
     318static CHAR_T *memcpy_uppcase (CHAR_T *dest, const CHAR_T *src,
     319                               size_t len LOCALE_PARAM);
     320
    316321static CHAR_T *
    317 memcpy_uppcase (CHAR_T *dest, const CHAR_T *src,
    318                 size_t len LOCALE_PARAM_PROTO)
     322memcpy_uppcase (CHAR_T *dest, const CHAR_T *src, size_t len LOCALE_PARAM)
    319323{
    320324  while (len-- > 0)
     
    329333   measured in seconds, ignoring leap seconds.  */
    330334# define tm_diff ftime_tm_diff
     335static int tm_diff (const struct tm *, const struct tm *);
    331336static int
    332337tm_diff (const struct tm *a, const struct tm *b)
     
    360365#define ISO_WEEK1_WDAY 4 /* Thursday */
    361366#define YDAY_MINIMUM (-366)
     367static int iso_week_days (int, int);
    362368#ifdef __GNUC__
    363369__inline__
     
    402408#endif
    403409
    404 
    405 /* Just like my_strftime, below, but with one more parameter, UPCASE,
    406    to indicate that the result should be converted to upper case.  */
     410static size_t __strftime_internal (STREAM_OR_CHAR_T *, STRFTIME_ARG (size_t)
     411                                   const CHAR_T *, const struct tm *,
     412                                   bool, bool *
     413                                   extra_args_spec LOCALE_PARAM);
     414
     415/* Write information from TP into S according to the format
     416   string FORMAT, writing no more that MAXSIZE characters
     417   (including the terminating '\0') and returning number of
     418   characters written.  If S is NULL, nothing will be written
     419   anywhere, so to determine how many characters would be
     420   written, use NULL for S and (size_t) -1 for MAXSIZE.  */
     421size_t
     422my_strftime (STREAM_OR_CHAR_T *s, STRFTIME_ARG (size_t maxsize)
     423             const CHAR_T *format,
     424             const struct tm *tp extra_args_spec LOCALE_PARAM)
     425{
     426  bool tzset_called = false;
     427  return __strftime_internal (s, STRFTIME_ARG (maxsize) format, tp,
     428                              false, &tzset_called extra_args LOCALE_ARG);
     429}
     430#if defined _LIBC && ! FPRINTFTIME
     431libc_hidden_def (my_strftime)
     432#endif
     433
     434/* Just like my_strftime, above, but with two more parameters.
     435   UPCASE indicate that the result should be converted to upper case,
     436   and *TZSET_CALLED indicates whether tzset has been called here.  */
    407437static size_t
    408 strftime_case_ (bool upcase, STREAM_OR_CHAR_T *s,
    409                 STRFTIME_ARG (size_t maxsize)
    410                 const CHAR_T *format,
    411                 const struct tm *tp extra_args_spec LOCALE_PARAM_PROTO)
     438__strftime_internal (STREAM_OR_CHAR_T *s, STRFTIME_ARG (size_t maxsize)
     439                     const CHAR_T *format,
     440                     const struct tm *tp, bool upcase, bool *tzset_called
     441                     extra_args_spec LOCALE_PARAM)
    412442{
    413443#if defined _LIBC && defined USE_IN_EXTENDED_LOCALE_MODEL
    414   struct locale_data *const current = loc->__locales[LC_TIME];
     444  struct __locale_data *const current = loc->__locales[LC_TIME];
    415445#endif
    416446#if FPRINTFTIME
     
    427457     requires this.  Then it is ok to fail if the pointers are invalid.  */
    428458# define a_wkday \
    429   ((const CHAR_T *) _NL_CURRENT (LC_TIME, NLW(ABDAY_1) + tp->tm_wday))
     459  ((const CHAR_T *) (tp->tm_wday < 0 || tp->tm_wday > 6                      \
     460                     ? "?" : _NL_CURRENT (LC_TIME, NLW(ABDAY_1) + tp->tm_wday)))
    430461# define f_wkday \
    431   ((const CHAR_T *) _NL_CURRENT (LC_TIME, NLW(DAY_1) + tp->tm_wday))
     462  ((const CHAR_T *) (tp->tm_wday < 0 || tp->tm_wday > 6                      \
     463                     ? "?" : _NL_CURRENT (LC_TIME, NLW(DAY_1) + tp->tm_wday)))
    432464# define a_month \
    433   ((const CHAR_T *) _NL_CURRENT (LC_TIME, NLW(ABMON_1) + tp->tm_mon))
     465  ((const CHAR_T *) (tp->tm_mon < 0 || tp->tm_mon > 11                       \
     466                     ? "?" : _NL_CURRENT (LC_TIME, NLW(ABMON_1) + tp->tm_mon)))
    434467# define f_month \
    435   ((const CHAR_T *) _NL_CURRENT (LC_TIME, NLW(MON_1) + tp->tm_mon))
     468  ((const CHAR_T *) (tp->tm_mon < 0 || tp->tm_mon > 11                       \
     469                     ? "?" : _NL_CURRENT (LC_TIME, NLW(MON_1) + tp->tm_mon)))
    436470# define ampm \
    437471  ((const CHAR_T *) _NL_CURRENT (LC_TIME, tp->tm_hour > 11                    \
     
    484518      tzname_vec = tz->tzname_copy;
    485519# endif
     520    }
     521  /* The tzset() call might have changed the value.  */
     522  if (!(zone && *zone) && tp->tm_isdst >= 0)
     523    {
    486524      /* POSIX.1 requires that local time zone information be used as
    487525         though strftime called tzset.  */
    488526# if HAVE_TZSET
    489       tzset ();
     527      if (!*tzset_called)
     528        {
     529          tzset ();
     530          *tzset_called = true;
     531        }
    490532# endif
     533      zone = tzname_vec[tp->tm_isdst != 0];
    491534    }
    492   /* The tzset() call might have changed the value.  */
    493   if (!(zone && *zone) && tp->tm_isdst >= 0)
    494     zone = tzname_vec[tp->tm_isdst != 0];
    495535#endif
    496536  if (! zone)
     
    642682        }
    643683
    644       /* As a GNU extension we allow to specify the field width.  */
     684      /* As a GNU extension we allow the field width to be specified.  */
    645685      if (ISDIGIT (*f))
    646686        {
     
    802842        subformat:
    803843          {
    804             size_t len = strftime_case_ (to_uppcase,
    805                                          NULL, STRFTIME_ARG ((size_t) -1)
    806                                          subfmt,
    807                                          tp extra_args LOCALE_ARG);
    808             add (len, strftime_case_ (to_uppcase, p,
    809                                       STRFTIME_ARG (maxsize - i)
    810                                       subfmt,
    811                                       tp extra_args LOCALE_ARG));
     844            size_t len = __strftime_internal (NULL, STRFTIME_ARG ((size_t) -1)
     845                                              subfmt,
     846                                              tp, to_uppcase, tzset_called
     847                                              extra_args LOCALE_ARG);
     848            add (len, __strftime_internal (p,
     849                                           STRFTIME_ARG (maxsize - i)
     850                                           subfmt,
     851                                           tp, to_uppcase, tzset_called
     852                                           extra_args LOCALE_ARG));
    812853          }
    813854          break;
     
    846887
    847888        case L_('C'):
    848           if (modifier == L_('O'))
    849             goto bad_format;
    850889          if (modifier == L_('E'))
    851890            {
     
    11151154          goto underlying_strftime;
    11161155#endif
     1156
     1157        case L_('q'):           /* GNU extension.  */
     1158          DO_SIGNED_NUMBER (1, false, ((tp->tm_mon * 11) >> 5) + 1);
     1159          break;
    11171160
    11181161        case L_('R'):
     
    13651408                time_t lt;
    13661409
     1410                /* POSIX.1 requires that local time zone information be used as
     1411                   though strftime called tzset.  */
     1412# if HAVE_TZSET
     1413                if (!*tzset_called)
     1414                  {
     1415                    tzset ();
     1416                    *tzset_called = true;
     1417                  }
     1418# endif
     1419
    13671420                ltm = *tp;
    13681421                lt = mktime_z (tz, &ltm);
     
    14451498  return i;
    14461499}
    1447 
    1448 /* Write information from TP into S according to the format
    1449    string FORMAT, writing no more that MAXSIZE characters
    1450    (including the terminating '\0') and returning number of
    1451    characters written.  If S is NULL, nothing will be written
    1452    anywhere, so to determine how many characters would be
    1453    written, use NULL for S and (size_t) -1 for MAXSIZE.  */
    1454 size_t
    1455 my_strftime (STREAM_OR_CHAR_T *s, STRFTIME_ARG (size_t maxsize)
    1456              const CHAR_T *format,
    1457              const struct tm *tp extra_args_spec LOCALE_PARAM_PROTO)
    1458 {
    1459   return strftime_case_ (false, s, STRFTIME_ARG (maxsize)
    1460                          format, tp extra_args LOCALE_ARG);
    1461 }
    1462 
    1463 #if defined _LIBC && ! FPRINTFTIME
    1464 libc_hidden_def (my_strftime)
    1465 #endif
  • TabularUnified coreutils/trunk/lib/string.in.h

    r1648 r1953  
    417417#   define strndup rpl_strndup
    418418#  endif
    419 _GL_FUNCDECL_RPL (strndup, char *, (char const *__string, size_t __n)
     419_GL_FUNCDECL_RPL (strndup, char *, (char const *__s, size_t __n)
    420420                                   _GL_ARG_NONNULL ((1)));
    421 _GL_CXXALIAS_RPL (strndup, char *, (char const *__string, size_t __n));
     421_GL_CXXALIAS_RPL (strndup, char *, (char const *__s, size_t __n));
    422422# else
    423423#  if ! @HAVE_DECL_STRNDUP@
    424 _GL_FUNCDECL_SYS (strndup, char *, (char const *__string, size_t __n)
     424_GL_FUNCDECL_SYS (strndup, char *, (char const *__s, size_t __n)
    425425                                   _GL_ARG_NONNULL ((1)));
    426426#  endif
    427 _GL_CXXALIAS_SYS (strndup, char *, (char const *__string, size_t __n));
     427_GL_CXXALIAS_SYS (strndup, char *, (char const *__s, size_t __n));
    428428# endif
    429429_GL_CXXALIASWARN (strndup);
     
    445445#   define strnlen rpl_strnlen
    446446#  endif
    447 _GL_FUNCDECL_RPL (strnlen, size_t, (char const *__string, size_t __maxlen)
     447_GL_FUNCDECL_RPL (strnlen, size_t, (char const *__s, size_t __maxlen)
    448448                                   _GL_ATTRIBUTE_PURE
    449449                                   _GL_ARG_NONNULL ((1)));
    450 _GL_CXXALIAS_RPL (strnlen, size_t, (char const *__string, size_t __maxlen));
     450_GL_CXXALIAS_RPL (strnlen, size_t, (char const *__s, size_t __maxlen));
    451451# else
    452452#  if ! @HAVE_DECL_STRNLEN@
    453 _GL_FUNCDECL_SYS (strnlen, size_t, (char const *__string, size_t __maxlen)
     453_GL_FUNCDECL_SYS (strnlen, size_t, (char const *__s, size_t __maxlen)
    454454                                   _GL_ATTRIBUTE_PURE
    455455                                   _GL_ARG_NONNULL ((1)));
    456456#  endif
    457 _GL_CXXALIAS_SYS (strnlen, size_t, (char const *__string, size_t __maxlen));
     457_GL_CXXALIAS_SYS (strnlen, size_t, (char const *__s, size_t __maxlen));
    458458# endif
    459459_GL_CXXALIASWARN (strnlen);
  • TabularUnified coreutils/trunk/lib/strtod.c

    r1648 r1953  
    216216  const char *end;
    217217  char *endbuf;
    218   int saved_errno;
     218  int saved_errno = errno;
    219219
    220220  /* Eat whitespace.  */
     
    227227    ++s;
    228228
    229   saved_errno = errno;
    230229  num = underlying_strtod (s, &endbuf);
    231230  end = endbuf;
     
    240239        {
    241240          if (! c_isxdigit (s[2 + (s[2] == '.')]))
    242             end = s + 1;
     241            {
     242              end = s + 1;
     243
     244              /* strtod() on z/OS returns ERANGE for "0x".  */
     245              errno = saved_errno;
     246            }
    243247          else if (end <= s + 2)
    244248            {
     
    322326         nice implementation populates the bits of the NaN according
    323327         to interpreting n-char-sequence as a hexadecimal number.  */
    324       if (s != end)
     328      if (s != end || num == num)
    325329        num = NAN;
    326330      errno = saved_errno;
  • TabularUnified coreutils/trunk/lib/strtol.c

    r1648 r1953  
    122122   e.g., in Cray C 5.0.3.0.  */
    123123
    124 /* True if negative values of the signed integer type T use two's
    125    complement, ones' complement, or signed magnitude representation,
    126    respectively.  Much GNU code assumes two's complement, but some
    127    people like to be portable to all possible C hosts.  */
    128 # define TYPE_TWOS_COMPLEMENT(t) ((t) ~ (t) 0 == (t) -1)
    129 # define TYPE_ONES_COMPLEMENT(t) ((t) ~ (t) 0 == 0)
    130 # define TYPE_SIGNED_MAGNITUDE(t) ((t) ~ (t) 0 < (t) -1)
    131 
    132124/* True if the arithmetic type T is signed.  */
    133125# define TYPE_SIGNED(t) (! ((t) 0 < (t) -1))
    134126
    135 /* The maximum and minimum values for the integer type T.  These
    136    macros have undefined behavior if T is signed and has padding bits.
    137    If this is a problem for you, please let us know how to fix it for
    138    your host.  */
    139 # define TYPE_MINIMUM(t) \
    140    ((t) (! TYPE_SIGNED (t) \
    141          ? (t) 0 \
    142          : TYPE_SIGNED_MAGNITUDE (t) \
    143          ? ~ (t) 0 \
    144          : ~ TYPE_MAXIMUM (t)))
    145 # define TYPE_MAXIMUM(t) \
    146    ((t) (! TYPE_SIGNED (t) \
    147          ? (t) -1 \
     127/* Minimum and maximum values for integer types.
     128   These macros have undefined behavior for signed types that either
     129   have padding bits or do not use two's complement.  If this is a
     130   problem for you, please let us know how to fix it for your host.  */
     131
     132/* The maximum and minimum values for the integer type T.  */
     133# define TYPE_MINIMUM(t) ((t) ~ TYPE_MAXIMUM (t))
     134# define TYPE_MAXIMUM(t)                                                 \
     135   ((t) (! TYPE_SIGNED (t)                                               \
     136         ? (t) -1                                                        \
    148137         : ((((t) 1 << (sizeof (t) * CHAR_BIT - 2)) - 1) * 2 + 1)))
    149138
  • TabularUnified coreutils/trunk/lib/sys_select.in.h

    r1648 r1953  
    8282   Also, Mac OS X, AIX, HP-UX, IRIX, Solaris, Interix declare select()
    8383   in <sys/time.h>.
    84    But avoid namespace pollution on glibc systems.  */
    85 # ifndef __GLIBC__
     84   But avoid namespace pollution on glibc systems and "unknown type
     85   name" problems on Cygwin.  */
     86# if !(defined __GLIBC__ || defined __CYGWIN__)
    8687#  include <sys/time.h>
    8788# endif
     
    101102
    102103/* Get definition of 'sigset_t'.
    103    But avoid namespace pollution on glibc systems.
     104   But avoid namespace pollution on glibc systems and "unknown type
     105   name" problems on Cygwin.
    104106   Do this after the include_next (for the sake of OpenBSD 5.0) but before
    105107   the split double-inclusion guard (for the sake of Solaris).  */
    106 #if !(defined __GLIBC__ && !defined __UCLIBC__)
     108#if !((defined __GLIBC__ || defined __CYGWIN__) && !defined __UCLIBC__)
    107109# include <signal.h>
    108110#endif
     
    290292#  endif
    291293_GL_FUNCDECL_RPL (select, int,
    292                   (int, fd_set *, fd_set *, fd_set *, struct timeval *));
     294                  (int, fd_set *restrict, fd_set *restrict, fd_set *restrict,
     295                   struct timeval *restrict));
    293296_GL_CXXALIAS_RPL (select, int,
    294                   (int, fd_set *, fd_set *, fd_set *, struct timeval *));
     297                  (int, fd_set *restrict, fd_set *restrict, fd_set *restrict,
     298                   struct timeval *restrict));
    295299# else
    296300_GL_CXXALIAS_SYS (select, int,
    297                   (int, fd_set *, fd_set *, fd_set *, struct timeval *));
     301                  (int, fd_set *restrict, fd_set *restrict, fd_set *restrict,
     302                   struct timeval *restrict));
    298303# endif
    299304_GL_CXXALIASWARN (select);
  • TabularUnified coreutils/trunk/lib/sys_time.in.h

    r1648 r1953  
    110110# endif
    111111_GL_CXXALIASWARN (gettimeofday);
     112# if defined __cplusplus && defined GNULIB_NAMESPACE
     113namespace GNULIB_NAMESPACE {
     114  typedef ::timeval
     115#undef timeval
     116    timeval;
     117}
     118# endif
    112119#elif defined GNULIB_POSIXCHECK
    113120# undef gettimeofday
  • TabularUnified coreutils/trunk/lib/time_rz.c

    r1648 r1953  
    3333#include <string.h>
    3434
     35#include "flexmember.h"
    3536#include "time-internal.h"
    3637
     
    4748   used.  */
    4849enum { ABBR_SIZE_MIN = DEFAULT_MXFAST - offsetof (struct tm_zone, abbrs) };
    49 
    50 static char const TZ[] = "TZ";
    5150
    5251/* Magic cookie timezone_t value, for local time.  It differs from
     
    9796  size_t name_size = name ? strlen (name) + 1 : 0;
    9897  size_t abbr_size = name_size < ABBR_SIZE_MIN ? ABBR_SIZE_MIN : name_size + 1;
    99   timezone_t tz = malloc (offsetof (struct tm_zone, abbrs) + abbr_size);
     98  timezone_t tz = malloc (FLEXSIZEOF (struct tm_zone, abbrs, abbr_size));
    10099  if (tz)
    101100    {
     
    206205getenv_TZ (void)
    207206{
    208   return getenv (TZ);
     207  return getenv ("TZ");
    209208}
    210209#endif
     
    214213setenv_TZ (char const *tz)
    215214{
    216   return tz ? setenv (TZ, tz, 1) : unsetenv (TZ);
     215  return tz ? setenv ("TZ", tz, 1) : unsetenv ("TZ");
    217216}
    218217#endif
  • TabularUnified coreutils/trunk/lib/timegm.c

    r1648 r1953  
    2323#include <time.h>
    2424
    25 #ifndef _LIBC
     25#ifdef _LIBC
     26typedef time_t mktime_offset_t;
     27#else
    2628# undef __gmtime_r
    2729# define __gmtime_r gmtime_r
     
    3335timegm (struct tm *tmp)
    3436{
    35   static time_t gmtime_offset;
     37  static mktime_offset_t gmtime_offset;
    3638  tmp->tm_isdst = 0;
    3739  return __mktime_internal (tmp, __gmtime_r, &gmtime_offset);
  • TabularUnified coreutils/trunk/lib/trim.c

    r1648 r1953  
    3232
    3333/* Use this to suppress gcc's "...may be used before initialized" warnings. */
    34 #ifdef lint
     34#if defined GCC_LINT || defined lint
    3535# define IF_LINT(Code) Code
    3636#else
  • TabularUnified coreutils/trunk/lib/unistr.in.h

    r1648 r1953  
    198198  uint32_t c = *s;
    199199
    200 #  if CONFIG_UNICODE_SAFETY
    201200  if (c < 0xd800 || (c >= 0xe000 && c < 0x110000))
    202 #  endif
    203201    *puc = c;
    204 #  if CONFIG_UNICODE_SAFETY
    205202  else
    206203    /* invalid multibyte character */
    207204    *puc = 0xfffd;
    208 #  endif
    209205  return 1;
    210206}
  • TabularUnified coreutils/trunk/lib/unistr/u8-mbtoucr.c

    r1648 r1953  
    9393              if ((s[1] ^ 0x80) < 0x40
    9494                  && (c >= 0xf1 || s[1] >= 0x90)
    95 #if 1
    96                   && (c < 0xf4 || (c == 0xf4 && s[1] < 0x90))
    97 #endif
    98                  )
     95                  && (c < 0xf4 || (c == 0xf4 && s[1] < 0x90)))
    9996                {
    10097                  if (n >= 3)
     
    139136            }
    140137        }
    141 #if 0
    142       else if (c < 0xfc)
    143         {
    144           if (n >= 2)
    145             {
    146               if ((s[1] ^ 0x80) < 0x40
    147                   && (c >= 0xf9 || s[1] >= 0x88))
    148                 {
    149                   if (n >= 3)
    150                     {
    151                       if ((s[2] ^ 0x80) < 0x40)
    152                         {
    153                           if (n >= 4)
    154                             {
    155                               if ((s[3] ^ 0x80) < 0x40)
    156                                 {
    157                                   if (n >= 5)
    158                                     {
    159                                       if ((s[4] ^ 0x80) < 0x40)
    160                                         {
    161                                           *puc = ((unsigned int) (c & 0x03) << 24)
    162                                                  | ((unsigned int) (s[1] ^ 0x80) << 18)
    163                                                  | ((unsigned int) (s[2] ^ 0x80) << 12)
    164                                                  | ((unsigned int) (s[3] ^ 0x80) << 6)
    165                                                  | (unsigned int) (s[4] ^ 0x80);
    166                                           return 5;
    167                                         }
    168                                       /* invalid multibyte character */
    169                                     }
    170                                   else
    171                                     {
    172                                       /* incomplete multibyte character */
    173                                       *puc = 0xfffd;
    174                                       return -2;
    175                                     }
    176                                 }
    177                               /* invalid multibyte character */
    178                             }
    179                           else
    180                             {
    181                               /* incomplete multibyte character */
    182                               *puc = 0xfffd;
    183                               return -2;
    184                             }
    185                         }
    186                       /* invalid multibyte character */
    187                     }
    188                   else
    189                     {
    190                       /* incomplete multibyte character */
    191                       *puc = 0xfffd;
    192                       return -2;
    193                     }
    194                 }
    195               /* invalid multibyte character */
    196             }
    197           else
    198             {
    199               /* incomplete multibyte character */
    200               *puc = 0xfffd;
    201               return -2;
    202             }
    203         }
    204       else if (c < 0xfe)
    205         {
    206           if (n >= 2)
    207             {
    208               if ((s[1] ^ 0x80) < 0x40
    209                   && (c >= 0xfd || s[1] >= 0x84))
    210                 {
    211                   if (n >= 3)
    212                     {
    213                       if ((s[2] ^ 0x80) < 0x40)
    214                         {
    215                           if (n >= 4)
    216                             {
    217                               if ((s[3] ^ 0x80) < 0x40)
    218                                 {
    219                                   if (n >= 5)
    220                                     {
    221                                       if ((s[4] ^ 0x80) < 0x40)
    222                                         {
    223                                           if (n >= 6)
    224                                             {
    225                                               if ((s[5] ^ 0x80) < 0x40)
    226                                                 {
    227                                                   *puc = ((unsigned int) (c & 0x01) << 30)
    228                                                          | ((unsigned int) (s[1] ^ 0x80) << 24)
    229                                                          | ((unsigned int) (s[2] ^ 0x80) << 18)
    230                                                          | ((unsigned int) (s[3] ^ 0x80) << 12)
    231                                                          | ((unsigned int) (s[4] ^ 0x80) << 6)
    232                                                          | (unsigned int) (s[5] ^ 0x80);
    233                                                   return 6;
    234                                                 }
    235                                               /* invalid multibyte character */
    236                                             }
    237                                           else
    238                                             {
    239                                               /* incomplete multibyte character */
    240                                               *puc = 0xfffd;
    241                                               return -2;
    242                                             }
    243                                         }
    244                                       /* invalid multibyte character */
    245                                     }
    246                                   else
    247                                     {
    248                                       /* incomplete multibyte character */
    249                                       *puc = 0xfffd;
    250                                       return -2;
    251                                     }
    252                                 }
    253                               /* invalid multibyte character */
    254                             }
    255                           else
    256                             {
    257                               /* incomplete multibyte character */
    258                               *puc = 0xfffd;
    259                               return -2;
    260                             }
    261                         }
    262                       /* invalid multibyte character */
    263                     }
    264                   else
    265                     {
    266                       /* incomplete multibyte character */
    267                       *puc = 0xfffd;
    268                       return -2;
    269                     }
    270                 }
    271               /* invalid multibyte character */
    272             }
    273           else
    274             {
    275               /* incomplete multibyte character */
    276               *puc = 0xfffd;
    277               return -2;
    278             }
    279         }
    280 #endif
    281138    }
    282139  /* invalid multibyte character */
  • TabularUnified coreutils/trunk/lib/unistr/u8-uctomb-aux.c

    r1648 r1953  
    3838        return -1;
    3939    }
    40 #if 0
    41   else if (uc < 0x200000)
    42     count = 4;
    43   else if (uc < 0x4000000)
    44     count = 5;
    45   else if (uc <= 0x7fffffff)
    46     count = 6;
    47 #else
    4840  else if (uc < 0x110000)
    4941    count = 4;
    50 #endif
    5142  else
    5243    return -1;
     
    5748  switch (count) /* note: code falls through cases! */
    5849    {
    59 #if 0
    60     case 6: s[5] = 0x80 | (uc & 0x3f); uc = uc >> 6; uc |= 0x4000000;
    61     case 5: s[4] = 0x80 | (uc & 0x3f); uc = uc >> 6; uc |= 0x200000;
    62 #endif
    6350    case 4: s[3] = 0x80 | (uc & 0x3f); uc = uc >> 6; uc |= 0x10000;
     51      /* fallthrough */
    6452    case 3: s[2] = 0x80 | (uc & 0x3f); uc = uc >> 6; uc |= 0x800;
     53      /* fallthrough */
    6554    case 2: s[1] = 0x80 | (uc & 0x3f); uc = uc >> 6; uc |= 0xc0;
    6655  /*case 1:*/ s[0] = uc;
  • TabularUnified coreutils/trunk/lib/unistr/u8-uctomb.c

    r1648 r1953  
    5353            return -1;
    5454        }
    55 #if 0
    56       else if (uc < 0x200000)
    57         count = 4;
    58       else if (uc < 0x4000000)
    59         count = 5;
    60       else if (uc <= 0x7fffffff)
    61         count = 6;
    62 #else
    6355      else if (uc < 0x110000)
    6456        count = 4;
    65 #endif
    6657      else
    6758        return -1;
     
    7162          switch (count) /* note: code falls through cases! */
    7263            {
    73 #if 0
    74             case 6: s[5] = 0x80 | (uc & 0x3f); uc = uc >> 6; uc |= 0x4000000;
    75             case 5: s[4] = 0x80 | (uc & 0x3f); uc = uc >> 6; uc |= 0x200000;
    76 #endif
    7764            case 4: s[3] = 0x80 | (uc & 0x3f); uc = uc >> 6; uc |= 0x10000;
    7865            case 3: s[2] = 0x80 | (uc & 0x3f); uc = uc >> 6; uc |= 0x800;
  • TabularUnified coreutils/trunk/lib/utimecmp.c

    r1648 r1953  
    133133
    134134  verify (TYPE_IS_INTEGER (time_t));
    135   verify (TYPE_TWOS_COMPLEMENT (int));
    136135
    137136  /* Destination and source time stamps.  */
     
    290289                 stamp resolution; return the answer directly.  */
    291290              {
    292                 time_t s = src_s & ~ (res == 2 * BILLION);
     291                time_t s = src_s & ~ (res == 2 * BILLION ? 1 : 0);
    293292                if (src_s < dst_s || (src_s == dst_s && src_ns <= dst_ns))
    294293                  return 1;
     
    369368
    370369      /* Truncate the source's time stamp according to the resolution.  */
    371       src_s &= ~ (res == 2 * BILLION);
     370      src_s &= ~ (res == 2 * BILLION ? 1 : 0);
    372371      src_ns -= src_ns % res;
    373372    }
  • TabularUnified coreutils/trunk/lib/utimensat.c

    r1648 r1953  
    7070         The same bug occurs in Solaris 11.1 (Apr 2013).
    7171
    72          FIXME: Simplify this for Linux in 2016 and for Solaris in
    73          2024, when file system bugs are no longer common.  */
     72         FIXME: Simplify this in 2024, when these file system bugs are
     73         no longer common on Gnulib target platforms.  */
    7474      if (times && (times[0].tv_nsec == UTIME_OMIT
    7575                    || times[1].tv_nsec == UTIME_OMIT))
  • TabularUnified coreutils/trunk/lib/vasnprintf.c

    r1648 r1953  
    196196/* GCC >= 4.0 with -Wall emits unjustified "... may be used uninitialized"
    197197   warnings in this file.  Use -Dlint to suppress them.  */
    198 #ifdef lint
     198#if defined GCC_LINT || defined lint
    199199# define IF_LINT(Code) Code
    200200#else
     
    48334833# else
    48344834                    *fbp++ = 'l';
     4835# endif
     4836#endif
    48354837                    /*FALLTHROUGH*/
    4836 # endif
    4837 #endif
    48384838                  case TYPE_LONGINT:
    48394839                  case TYPE_ULONGINT:
  • TabularUnified coreutils/trunk/lib/verify.h

    r1648 r1953  
    264264#elif 1200 <= _MSC_VER
    265265# define assume(R) __assume (R)
    266 #elif (defined lint \
     266#elif ((defined GCC_LINT || defined lint) \
    267267       && (__has_builtin (__builtin_trap) \
    268268           || 3 < __GNUC__ + (3 < __GNUC_MINOR__ + (4 <= __GNUC_PATCHLEVEL__))))
  • TabularUnified coreutils/trunk/lib/wchar.in.h

    r1648 r1953  
    3636         && ((defined _INTTYPES_INCLUDED && !defined strtoimax)         \
    3737             || defined _GL_JUST_INCLUDE_SYSTEM_WCHAR_H))               \
     38     || (defined __MINGW32__ && defined __STRING_H_SOURCED__)           \
    3839     || defined _GL_ALREADY_INCLUDING_WCHAR_H)
    3940/* Special invocation convention:
     
    4546     therefore we cannot provide the function overrides; instead include only
    4647     the system's <wchar.h>.
     48   - With MinGW 3.22, when <string.h> includes <wchar.h>, only some part of
     49     <wchar.h> is actually processed, and that doesn't include 'mbstate_t'.
    4750   - On IRIX 6.5, similarly, we have an include <wchar.h> -> <wctype.h>, and
    4851     the latter includes <wchar.h>.  But here, we have no way to detect whether
  • TabularUnified coreutils/trunk/lib/wctype.in.h

    r1648 r1953  
    2626 */
    2727
    28 #ifndef _@GUARD_PREFIX@_WCTYPE_H
    29 
    3028#if __GNUC__ >= 3
    3129@PRAGMA_SYSTEM_HEADER@
    3230#endif
    3331@PRAGMA_COLUMNS@
     32
     33#if (defined __MINGW32__ && defined __CTYPE_H_SOURCED__)
     34
     35/* Special invocation convention:
     36   - With MinGW 3.22, when <ctype.h> includes <wctype.h>, only some part of
     37     <wctype.h> is being processed, which doesn't include the idempotency
     38     guard.   */
     39
     40#@INCLUDE_NEXT@ @NEXT_WCTYPE_H@
     41
     42#else
     43/* Normal invocation convention.  */
     44
     45#ifndef _@GUARD_PREFIX@_WCTYPE_H
    3446
    3547#if @HAVE_WINT_T@
     
    513525#endif /* _@GUARD_PREFIX@_WCTYPE_H */
    514526#endif /* _@GUARD_PREFIX@_WCTYPE_H */
     527#endif
  • TabularUnified coreutils/trunk/lib/xalloc-oversized.h

    r1648 r1953  
    2121#include <stddef.h>
    2222
     23/* Default for (non-Clang) compilers that lack __has_builtin.  */
    2324#ifndef __has_builtin
    2425# define __has_builtin(x) 0
    2526#endif
    2627
    27 /* Return 1 if an array of N objects, each of size S, cannot exist due
    28    to size arithmetic overflow.  S must be positive and N must be
    29    nonnegative.  This is a macro, not a function, so that it
    30    works correctly even when SIZE_MAX < N.
    31 
     28/* True if N * S would overflow in a size calculation.
     29   This expands to a constant expression if N and S are both constants.
    3230   By gnulib convention, SIZE_MAX represents overflow in size
    3331   calculations, so the conservative dividend to use here is
     
    3735   exactly-SIZE_MAX allocations on such hosts; this avoids a test and
    3836   branch when S is known to be 1.  */
    39 #if 5 <= __GNUC__ || __has_builtin (__builtin_mul_overflow)
     37#define __xalloc_oversized(n, s) \
     38    ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n))
     39
     40
     41/* Return 1 if an array of N objects, each of size S, cannot exist due
     42   to size arithmetic overflow.  S must be positive and N must be
     43   nonnegative.  This is a macro, not a function, so that it
     44   works correctly even when SIZE_MAX < N.  */
     45
     46#if 7 <= __GNUC__ || __has_builtin (__builtin_add_overflow_p)
     47# define xalloc_oversized(n, s) __builtin_mul_overflow_p (n, s, (size_t) 1)
     48#elif ((5 <= __GNUC__ \
     49        || (__has_builtin (__builtin_mul_overflow) \
     50            && __has_builtin (__builtin_constant_p))) \
     51       && !__STRICT_ANSI__)
    4052# define xalloc_oversized(n, s) \
    41     ({ size_t __xalloc_size; __builtin_mul_overflow (n, s, &__xalloc_size); })
     53   (__builtin_constant_p (n) && __builtin_constant_p (s) \
     54    ? __xalloc_oversized (n, s) \
     55    : ({ size_t __xalloc_size; __builtin_mul_overflow (n, s, &__xalloc_size); }))
     56
     57/* Other compilers use integer division; this may be slower but is
     58   more portable.  */
    4259#else
    43 # define xalloc_oversized(n, s) \
    44     ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n))
     60# define xalloc_oversized(n, s) __xalloc_oversized (n, s)
    4561#endif
    4662
  • TabularUnified coreutils/trunk/lib/xstrtod.c

    r1648 r1953  
    3737/* An interface to a string-to-floating-point conversion function that
    3838   encapsulates all the error checking one should usually perform.
    39    Like strtod/strtold, but upon successful
    40    conversion put the result in *RESULT and return true.  Return
    41    false and don't modify *RESULT upon any failure.  CONVERT
    42    specifies the conversion function, e.g., strtod itself.  */
     39   Like strtod/strtold, but stores the conversion in *RESULT,
     40   and returns true upon successful conversion.
     41   CONVERT specifies the conversion function, e.g., strtod itself.  */
    4342
    4443bool
     
    5958    {
    6059      /* Allow underflow (in which case CONVERT returns zero),
    61          but flag overflow as an error. */
     60         but flag overflow as an error.  The user can decide
     61         to use the limits in RESULT upon ERANGE.  */
    6262      if (val != 0 && errno == ERANGE)
    6363        ok = false;
  • TabularUnified coreutils/trunk/lib/xstrtol.c

    r1648 r1953  
    149149        }
    150150
    151       if (strchr (valid_suffixes, '0'))
     151      switch (**p)
    152152        {
     153        case 'E': case 'G': case 'g': case 'k': case 'K': case 'M': case 'm':
     154        case 'P': case 'T': case 't': case 'Y': case 'Z':
     155
    153156          /* The "valid suffix" '0' is a special flag meaning that
    154157             an optional second suffix is allowed, which can change
     
    158161             power-of-1024.  */
    159162
    160           switch (p[0][1])
    161             {
    162             case 'i':
    163               if (p[0][2] == 'B')
    164                 suffixes += 2;
    165               break;
    166 
    167             case 'B':
    168             case 'D': /* 'D' is obsolescent */
    169               base = 1000;
    170               suffixes++;
    171               break;
    172             }
     163          if (strchr (valid_suffixes, '0'))
     164            switch (p[0][1])
     165              {
     166              case 'i':
     167                if (p[0][2] == 'B')
     168                  suffixes += 2;
     169                break;
     170
     171              case 'B':
     172              case 'D': /* 'D' is obsolescent */
     173                base = 1000;
     174                suffixes++;
     175                break;
     176              }
    173177        }
    174178
     
    180184
    181185        case 'B':
     186          /* This obsolescent first suffix is distinct from the 'B'
     187             second suffix above.  E.g., 'tar -L 1000B' means change
     188             the tape after writing 1000 KiB of data.  */
    182189          overflow = bkm_scale (&tmp, 1024);
    183190          break;
Note: See TracChangeset for help on using the changeset viewer.